#!/usr/bin/env python3 """ book_finder.py (v3) — поиск книг, которых нет в библиотеке. ИСПРАВЛЕНИЯ ПРОТИВ v2: * ЛитРес: точный шаблон карточки (id, обложка, ссылка, название) — теперь цены и ссылки на товар настоящие; * ФантЛаб: отбрасываю служебные ссылки и результаты, не связанные с запросом (сверяю слова названия); * Open Library: проверяю совпадение по фамилии автора или словам названия, иначе результат считается чужим. Ничего не скачивает. """ import json import os import re import sys import time import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor from datetime import datetime TIMEOUT = 25 UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/155.0 Safari/537.36" STOP = {"the", "a", "an", "of", "and", "or", "in", "on", "to", "book", "part", "vol", "книга", "часть", "том", "и", "в", "на", "для", "по", "с"} def fetch(url, as_json=False): req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "ru,en;q=0.8"}) try: with urllib.request.urlopen(req, timeout=TIMEOUT) as r: data = r.read().decode("utf-8", "replace") if as_json: try: return json.loads(data) except Exception: return None return data except Exception: return None def tokens(text): return { w for w in re.findall(r"[\wа-яёА-ЯЁ]{3,}", (text or "").lower()) if w not in STOP } def relevant(query_title, query_author, cand_title, cand_authors=""): """Похоже ли найденное на искомое.""" qt, ct = tokens(query_title), tokens(cand_title) if qt and ct and len(qt & ct) >= max(1, min(2, len(qt))): return True qa = tokens(query_author) ca = tokens(cand_authors) if qa and ca and (qa & ca): return True return False def lit_res(title, author=None): """ЛитРес: карточки вида id → обложка → ссылка → название.""" q = urllib.parse.quote(f"{author} {title}" if author else title) html = fetch(f"https://www.litres.ru/search/?q={q}") if not html: return [] # ЛитРес отдаёт данные с экранированными кавычками (\"id\":...) — # без этого разбор не находит ни одной карточки. html = html.replace('\\"', '"') out, seen = [], set() pattern = re.compile( r'"id":\d+,"uuid":"[^"]*","cover_url":"[^"]*","url":"(/book/[^"]+)","title":"((?:[^"\\]|\\.){1,200})"' ) for m in pattern.finditer(html): url = "https://www.litres.ru" + m.group(1) name = m.group(2).replace('\\"', '"').strip() if url in seen or not name: continue seen.add(url) tail = html[m.end(): m.end() + 900] price = re.search(r'"final_price":(\d+)', tail) out.append( { "title": name, "url": url, "price": int(price.group(1)) if price else None, "source": "ЛитРес", } ) if len(out) >= 4: break return out def open_library(title, author=None): for params in ({"title": title, "limit": 5}, {"q": title, "limit": 5}): url = "https://openlibrary.org/search.json?" + urllib.parse.urlencode(params) d = fetch(url, as_json=True) if not d or not d.get("docs"): time.sleep(1) continue out = [] for doc in d["docs"]: cand_authors = ", ".join((doc.get("author_name") or [])[:2]) if not relevant(title, author, doc.get("title") or "", cand_authors): continue out.append( { "title": doc.get("title"), "authors": cand_authors, "year": doc.get("first_publish_year"), "lang": ", ".join((doc.get("language") or [])[:2]), "isbn": (doc.get("isbn") or [None])[0], "url": "https://openlibrary.org" + (doc.get("key") or ""), "source": "Open Library", } ) if len(out) >= 3: break if out: return out return [] def fantlab(title, author=None): q = urllib.parse.quote(f"{author} {title}" if author else title) html = fetch(f"https://fantlab.ru/searchmain?searchstr={q}") if not html: return [] out, seen = [], set() for m in re.finditer(r']+href="(/work\d+)"[^>]*>([^<]{2,150})', html): url, name = "https://fantlab.ru" + m.group(1), m.group(2).strip() if url in seen: continue if not relevant(title, author, name, ""): continue seen.add(url) out.append({"title": name, "url": url, "source": "ФантЛаб"}) if len(out) >= 3: break return out def google_books(title, author=None): url = "https://www.googleapis.com/books/v1/volumes?" + urllib.parse.urlencode( {"q": f"intitle:{title}", "maxResults": 5} ) d = fetch(url, as_json=True) if not d or "error" in d or not d.get("items"): return [] out = [] for item in d["items"]: v = item.get("volumeInfo", {}) cand_authors = ", ".join(v.get("authors") or []) if not relevant(title, author, v.get("title") or "", cand_authors): continue out.append( { "title": v.get("title"), "authors": cand_authors, "year": v.get("publishedDate"), "lang": v.get("language"), "isbn": next((i["identifier"] for i in v.get("industryIdentifiers", [])), None), "url": v.get("infoLink"), "source": "Google Books", } ) if len(out) >= 3: break return out def wanted(catalog): out = [] for s in catalog.get("series") or []: nxt = s.get("next") or {} if not nxt.get("title"): continue if (nxt.get("availability") or "").lower() in ("scheduled", "announced_no_date"): continue out.append( { "series": s.get("name"), "authors": s.get("authors") or [], "read_count": s.get("read_count"), "personal_status": s.get("personal_status"), "title": nxt.get("title"), "availability": nxt.get("availability"), "ru_status": nxt.get("ru_status"), "note": nxt.get("note"), } ) return out def search_one(w): author = (w["authors"] or [None])[0] if w["authors"] else None res = {} with ThreadPoolExecutor(max_workers=4) as ex: futs = { "litres": ex.submit(lit_res, w["title"], author), "openlibrary": ex.submit(open_library, w["title"], author), "fantlab": ex.submit(fantlab, w["title"], author), "google": ex.submit(google_books, w["title"], author), } for k, f in futs.items(): try: res[k] = f.result(timeout=40) or [] except Exception: res[k] = [] return res def links(title, author): q = urllib.parse.quote(f"{author} {title}" if author else title) return { "ЛитРес": f"https://www.litres.ru/search/?q={q}", "Bookmate": f"https://bookmate.com/search?q={q}", "ФантЛаб": f"https://fantlab.ru/searchmain?searchstr={q}", "Гутенберг": f"https://www.gutenberg.org/ebooks/search/?query={urllib.parse.quote(title)}", "Анна": f"https://annas-archive.org/search?q={q}", "Флибуста": f"https://flibusta.is/booksearch?ask={q}", } def main(): if len(sys.argv) < 3: print("нужно: book_finder.py <каталог.json> <отчёт.md>") sys.exit(1) src, dst = sys.argv[1], sys.argv[2] with open(src, encoding="utf-8") as f: catalog = json.load(f) want = wanted(catalog) print(f"книг к поиску: {len(want)}") results = [] for i, w in enumerate(want, 1): author = (w["authors"] or [None])[0] if w["authors"] else None w["found"] = search_one(w) w["links"] = links(w["title"], author) n = sum(len(v) for v in w["found"].values()) print(f" [{i}/{len(want)}] {w['title']}: {n} совпадений") results.append(w) os.makedirs(os.path.dirname(dst) or ".", exist_ok=True) found_any = sum(1 for w in results if any(w["found"].values())) lines = [ "# Поиск книг, которых нет в библиотеке", "", f"Обновлено: {datetime.now():%Y-%m-%d %H:%M}. Книг к поиску: **{len(results)}**, " f"с совпадениями: **{found_any}**.", "", "Проверены: ЛитРес (магазин), Open Library (мировой каталог), " "ФантЛаб (фантастика), Google Books.", "", ] for w in results: lines.append(f"## {w['title']}") meta = [] if w["series"]: meta.append(f"серия «{w['series']}»") if w["authors"]: meta.append("автор: " + ", ".join(w["authors"])) if w["read_count"]: meta.append(f"прочитано в серии: {w['read_count']}") if w["availability"]: meta.append(f"доступность: {w['availability']}") if w["note"]: meta.append(f"примечание: {w['note']}") lines += ["", "* " + "; ".join(meta), ""] rows = [] for k in ("litres", "openlibrary", "fantlab", "google"): rows += w["found"].get(k, []) if rows: lines.append("| Найдено | Автор | Год | Цена | Источник | Ссылка |") lines.append("|---|---|---|---|---|---|") for f in rows[:6]: t = (f.get("title") or "—").replace("|", "/")[:45] a = (f.get("authors") or "—").replace("|", "/")[:25] y = f.get("year") or "—" p = f"{f['price']} ₽" if f.get("price") else "—" lines.append( f"| {t} | {a} | {y} | {p} | {f['source']} | [открыть]({f.get('url') or '#'}) |" ) lines.append("") else: lines.append("_Точных совпадений нет — только поисковые ссылки ниже._") lines.append("") lines.append("Искать также: " + " · ".join(f"[{k}]({v})" for k, v in w["links"].items())) lines.append("") with open(dst, "w", encoding="utf-8") as f: f.write("\n".join(lines)) with open(dst.replace(".md", ".json"), "w", encoding="utf-8") as f: json.dump(results, f, ensure_ascii=False, indent=2) print(f"готово: {dst}, совпадений: {found_any}/{len(results)}") if __name__ == "__main__": main()