"""Граф контента: связи между фильмами, книгами, коллекциями и авторами. Строит карточки и связи в ядре: фильм → коллекция «входит в» книга → серия «входит в серию» книга → автор «написал» книга ↔ фильм «экранизация» коллекция ↔ серия книг «общая вселенная» """ import json import os import re import subprocess import sys import urllib.parse import urllib.request CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120") RADARR = os.environ.get("RADARR_URL", "http://192.168.1.118:7878") RADARR_KEY = os.environ.get("RADARR_KEY", "") def get(url, headers=None, timeout=20): try: req = urllib.request.Request(url, headers=headers or {}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read() or b"{}"), None except Exception as e: return None, str(e)[:100] def post(path, payload): req = urllib.request.Request(f"{CORE}{path}", data=json.dumps(payload, ensure_ascii=False).encode(), method="POST", headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=20) as r: return json.loads(r.read() or b"{}"), None except Exception as e: return None, str(e)[:100] def norm(s): s = (s or "").lower().replace("ё", "е") s = re.sub(r"[:!?.,'’\"()\[\]]", " ", s) s = re.sub(r"\b(part|chapter|часть|том|книга)\b", " ", s) return " ".join(s.split()) # ─────────── источники ─────────── def movies(): data, err = get(f"{RADARR}/api/v3/movie", {"X-Api-Key": RADARR_KEY}) if err: print(f" Radarr: ошибка {err}") return [] out = [] for m in data or []: col = m.get("collection") or {} out.append({ "title": m.get("title"), "year": m.get("year"), "tmdb": m.get("tmdbId"), "collection": col.get("title"), "collection_tmdb": col.get("tmdbId"), "genres": m.get("genres") or [], }) return out def books(): script = """ import json, sqlite3 c = sqlite3.connect('/opt/books/library/metadata.db') q = '''select b.id, b.title, b.series_index, s.name from books b left join books_series_link l on l.book = b.id left join series s on s.id = l.series''' rows = [] for bid, title, idx, series in c.execute(q): authors = [r[0] for r in c.execute( 'select a.name from authors a join books_authors_link l on l.author = a.id where l.book = ?', (bid,))] rows.append({"id": bid, "title": title, "series": series, "series_index": idx, "authors": authors}) print(json.dumps(rows, ensure_ascii=False)) """ path = "/tmp/books.json" open(path, "w", encoding="utf-8").write(script) subprocess.run(["pct", "push", "111", path, path, "--perms", "644"], capture_output=True, timeout=30) out = subprocess.run(["pct", "exec", "111", "--", "python3", path], capture_output=True, text=True, timeout=60) try: return json.loads(out.stdout or "[]") except Exception: print(" Calibre: не прочитал", (out.stderr or "")[:80]) return [] # ─────────── граф ─────────── def main(): mv = movies() bk = books() print(f"фильмов: {len(mv)}, книг: {len(bk)}") ids = {} made_cards = 0 made_links = 0 def card(kind, key, title, status=None): nonlocal made_cards res, err = post("/entity", {"kind": kind, "key": key, "title": title, "status": status}) if err or not res: return None made_cards += 1 ids[key] = res.get("id") return res.get("id") def link(a, b, relation): nonlocal made_links if not a or not b or a == b: return _, err = post("/link", {"from": a, "to": b, "relation": relation}) if not err: made_links += 1 # фильмы for m in mv: card("фильм", f"tmdb:{m['tmdb']}", f"{m['title']} ({m['year']})", "в медиатеке") # коллекции for m in mv: if m["collection"]: key = f"collection:{m['collection_tmdb'] or norm(m['collection'])}" card("коллекция", key, m["collection"], "франшиза") link(ids.get(f"tmdb:{m['tmdb']}"), ids.get(key), "входит в") # книги for b in bk: card("книга", f"calibre:{b['id']}", b["title"], "в библиотеке") for author in b.get("authors") or []: key = f"author:{norm(author)}" card("автор", key, author) link(ids.get(f"calibre:{b['id']}"), ids.get(key), "написал") if b.get("series"): key = f"series:{norm(b['series'])}" card("серия книг", key, b["series"], "книжная серия") link(ids.get(f"calibre:{b['id']}"), ids.get(key), "входит в серию") # экранизации: книга ↔ фильм по названию by_title = {} for m in mv: by_title.setdefault(norm(m["title"]), []).append(("фильм", m["tmdb"])) for b in bk: for kind, ident in by_title.get(norm(b["title"]), []): link(ids.get(f"calibre:{b['id']}"), ids.get(f"tmdb:{ident}"), "экранизация") # общая вселенная: коллекция фильмов ↔ книжная серия с тем же названием for m in mv: if not m["collection"]: continue col_key = f"collection:{m['collection_tmdb'] or norm(m['collection'])}" col_norm = norm(m["collection"]).replace("collection", "").strip() for b in bk: if b.get("series") and norm(b["series"]) == col_norm: link(ids.get(col_key), ids.get(f"series:{norm(b['series'])}"), "общая вселенная") print(f"карточек создано/обновлено: {made_cards}, связей: {made_links}") # сводка по типам связей from collections import Counter try: import urllib.request as u with u.urlopen(f"{CORE}/entity/{list(ids.values())[0]}", timeout=20) as r: pass except Exception: pass return 0 if __name__ == "__main__": sys.exit(main())