-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbookinfo.py
More file actions
224 lines (174 loc) · 5.99 KB
/
Copy pathbookinfo.py
File metadata and controls
224 lines (174 loc) · 5.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""
bookinfo.py — Fallback book metadata from Google Books and Open Library.
When Audible search fails entirely, these APIs can still provide:
- Cover image
- Description / synopsis
- Publisher, publish date
- ISBN, page count
- Genres / categories
No API keys needed. Both are free and public.
"""
import logging
import re
import requests
log = logging.getLogger(__name__)
_s = requests.Session()
_s.headers["User-Agent"] = "AudiobookshelfEnricher/1.0"
# ============================================================
# Google Books
# ============================================================
def search_google_books(title: str, author: str = "", max_results: int = 5) -> list[dict]:
"""
Search Google Books API. Returns list of normalized result dicts.
Free, no API key needed (rate limited to ~1000/day).
"""
query = title
if author:
query += f"+inauthor:{author}"
try:
r = _s.get(
"https://www.googleapis.com/books/v1/volumes",
params={"q": query, "maxResults": max_results, "printType": "books"},
timeout=15,
)
r.raise_for_status()
data = r.json()
except Exception as e:
log.warning(f" Google Books error: {e}")
return []
results = []
for item in data.get("items", []):
info = item.get("volumeInfo", {})
result = _parse_google_book(info)
if result.get("title"):
result["source"] = "google_books"
result["google_id"] = item.get("id", "")
results.append(result)
return results
def _parse_google_book(info: dict) -> dict:
"""Parse a Google Books volumeInfo into our standard format."""
r = {}
if info.get("title"):
r["title"] = info["title"]
if info.get("subtitle"):
r["title"] += f": {info['subtitle']}"
if info.get("authors"):
r["author"] = ", ".join(info["authors"])
if info.get("description"):
r["description"] = info["description"]
if info.get("publisher"):
r["publisher"] = info["publisher"]
if info.get("publishedDate"):
r["publishedDate"] = info["publishedDate"]
if info.get("categories"):
r["genres"] = info["categories"]
if info.get("language"):
r["language"] = info["language"]
# Cover image — prefer large, fall back to smaller
images = info.get("imageLinks", {})
for size in ["extraLarge", "large", "medium", "small", "thumbnail"]:
if images.get(size):
# Google Books returns http URLs, upgrade to https
# Also remove edge=curl parameter for cleaner image
cover = images[size].replace("http://", "https://")
cover = re.sub(r'&edge=curl', '', cover)
# Request larger zoom
cover = re.sub(r'zoom=\d', 'zoom=3', cover)
r["cover_url"] = cover
break
# ISBNs
for ident in info.get("industryIdentifiers", []):
if ident.get("type") == "ISBN_13":
r["isbn13"] = ident["identifier"]
elif ident.get("type") == "ISBN_10":
r["isbn10"] = ident["identifier"]
return r
# ============================================================
# Open Library
# ============================================================
def search_open_library(title: str, author: str = "", max_results: int = 5) -> list[dict]:
"""
Search Open Library API. Returns list of normalized result dicts.
Completely free, no limits.
"""
params = {"title": title, "limit": max_results}
if author:
params["author"] = author
try:
r = _s.get(
"https://openlibrary.org/search.json",
params=params,
timeout=15,
)
r.raise_for_status()
data = r.json()
except Exception as e:
log.warning(f" Open Library error: {e}")
return []
results = []
for doc in data.get("docs", [])[:max_results]:
result = _parse_open_library(doc)
if result.get("title"):
result["source"] = "open_library"
results.append(result)
return results
def _parse_open_library(doc: dict) -> dict:
"""Parse an Open Library search doc into our standard format."""
r = {}
if doc.get("title"):
r["title"] = doc["title"]
if doc.get("author_name"):
r["author"] = ", ".join(doc["author_name"])
if doc.get("publisher"):
r["publisher"] = doc["publisher"][0] if doc["publisher"] else ""
if doc.get("first_publish_year"):
r["publishedDate"] = str(doc["first_publish_year"])
if doc.get("subject"):
r["genres"] = doc["subject"][:5] # Cap at 5
if doc.get("language"):
r["language"] = doc["language"][0] if doc["language"] else ""
# Cover from Open Library covers API
cover_id = doc.get("cover_i")
if cover_id:
r["cover_url"] = f"https://covers.openlibrary.org/b/id/{cover_id}-L.jpg"
# ISBNs
if doc.get("isbn"):
for isbn in doc["isbn"]:
if len(isbn) == 13:
r.setdefault("isbn13", isbn)
elif len(isbn) == 10:
r.setdefault("isbn10", isbn)
# Open Library key for detail fetch
if doc.get("key"):
r["ol_key"] = doc["key"]
return r
def get_open_library_description(ol_key: str) -> str:
"""Fetch description from Open Library work/edition page."""
try:
r = _s.get(f"https://openlibrary.org{ol_key}.json", timeout=10)
r.raise_for_status()
data = r.json()
except Exception:
return ""
desc = data.get("description", "")
if isinstance(desc, dict):
desc = desc.get("value", "")
return desc
# ============================================================
# Combined Search
# ============================================================
def search_book_metadata(title: str, author: str = "") -> list[dict]:
"""
Search both Google Books and Open Library, return combined results.
Google Books results come first (usually better covers and descriptions).
"""
results = []
results.extend(search_google_books(title, author, max_results=3))
results.extend(search_open_library(title, author, max_results=3))
# Enrich Open Library results with descriptions if missing
for r in results:
if r.get("source") == "open_library" and not r.get("description") and r.get("ol_key"):
desc = get_open_library_description(r["ol_key"])
if desc:
r["description"] = desc
return results