Files
buryan-infra/ops/hub-core/content_graph.py
buryan-agent 3ea974ce95 Метаданные через VPS + граф контента: франшизы, экранизации, серии
Главное: медиатека не могла пополняться. Radarr ходит за метаданными на
api.radarr.video, а с домашнего IP этот адрес отдаёт 403 Cloudflare; с VPS —
200. На VPS уже был tinyproxy, разрешающий Tailscale-сеть. Поднят проброс
socat на узле (192.168.1.10:8888 → 100.64.0.2:8888), Radarr и Sonarr
переключены на него. После этого добавлены 5 фильмов с коллекциями.

Второе: граф контента. content_graph.py строит карточки и связи: фильм →
коллекция, книга → автор, книга → серия, книга ↔ фильм (экранизация),
коллекция ↔ книжная серия (общая вселенная). На реальных данных: 21
карточка, 19 связей, включая Matrix-трилогию, Dune-дилогию, экранизацию
Dune и связь коллекции Dune с книжной серией.

Добавлен GET /links в ядро (сводка по типам и список), блок «Связи
контента» в Медиа Хабе, расписание 04:45.

Ловушки: PUT /api/v3/config/host требует allowedHosts (и не принимает «*»);
прокси на Tailscale-адрес из контейнера не работает — нужен проброс; успех
сохранения отдаёт 202.
2026-10-20 10:12:54 +03:00

181 lines
6.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Граф контента: связи между фильмами, книгами, коллекциями и авторами.
Строит карточки и связи в ядре:
фильм → коллекция «входит в»
книга → серия «входит в серию»
книга → автор «написал»
книга ↔ фильм «экранизация»
коллекция ↔ серия книг «общая вселенная»
"""
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())