#!/usr/bin/env python3 """Fetches real cover art for the sample library's titles. Searches a public Libby catalogue (no sign-in) for each sample title, takes the cover of the closest match by title, author and format, and saves it as crates/libbui/src/sample/covers/.jpg. Titles with no confident match (made-up magazines, for instance) keep their drawn cover. scripts/sample-covers.py [library-key] # default: lapl Cover art belongs to its publishers; it is bundled only to show each book as Libby would. """ import json, re, sys, time, unicodedata, urllib.parse, urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parent.parent SAMPLE = ROOT / "crates/libbui/src/sample" OUT = SAMPLE / "covers" LIBRARY = sys.argv[1] if len(sys.argv) > 1 else "lapl" AGENT = "libbui-sample-covers" def norm(text): text = unicodedata.normalize("NFKC", text or "").casefold() return re.sub(r"[^\w]+", " ", text).strip() def titles(): found = {} def walk(node): if isinstance(node, dict): if "title" in node and "covers" in node and "id" in node: creator = node.get("firstCreatorName") or next( (c.get("name") for c in node.get("creators", []) if c.get("name")), "") kind = node.get("type", {}).get("id") if isinstance(node.get("type"), dict) else node.get("type") found.setdefault(str(node["id"]), (node["title"], creator, kind)) for value in node.values(): walk(value) elif isinstance(node, list): for value in node: walk(value) for name in ["sync.json", "search.json", "search-page-2.json", "catalog.json"]: walk(json.loads((SAMPLE / name).read_text())) return found def get(url): request = urllib.request.Request(url, headers={"User-Agent": AGENT}) with urllib.request.urlopen(request, timeout=30) as response: return response.read() def best(title, creator, kind): query = urllib.parse.quote(title.split(":")[0] if len(title) > 60 else title.split(";")[0]) page = json.loads(get(f"https://thunder.api.overdrive.com/v2/libraries/{LIBRARY}/media?query={query}&perPage=24")) # "Frankenstein; or, The Modern Prometheus" may be listed without its subtitle. wants = {norm(title), norm(title.split(";")[0])} # A long title may be listed by its main title alone, but only a long one: # "Dune" must not stand in for "Dune: The Graphic Novel". head = norm(title.split(":")[0]) scored = [] for item in page.get("items", []): have = norm(item.get("title")) if have not in wants and not (len(head) >= 20 and have == head): continue score = 0 if creator and norm(item.get("firstCreatorName")) == norm(creator): score += 2 if item.get("type", {}).get("id") == kind: score += 1 cover = item.get("covers", {}).get("cover150Wide") if cover: scored.append((score, cover["href"], item.get("title"), item.get("firstCreatorName"))) return max(scored, default=None, key=lambda s: s[0]) def main(): OUT.mkdir(exist_ok=True) for sample_id, (title, creator, kind) in sorted(titles().items()): target = OUT / f"{sample_id}.jpg" match = best(title, creator, kind) if match is None: print(f"- {sample_id} {title}: no confident match; keeps a drawn cover") target.unlink(missing_ok=True) else: target.write_bytes(get(match[1])) print(f"ok {sample_id} {title} <- {match[2]} / {match[3]} ({target.stat().st_size // 1024} KB)") time.sleep(0.5) if __name__ == "__main__": main()