Аналитика графа: шкала времени, кросс-формат, топ персон, блок на панели

Ядро: GET /graph (статистика и JSON узлов/рёбер), /timeline (тема по
десятилетиям), /cross (книги с экранизацией и авторы), /persons (топ персон).

Бот: команды «граф», «время <тема>», «кросс», «персоны режиссёры».
Проверено: science fiction по десятилетиям с фильмами, Dune ↔ Dune (2021),
Frank Herbert → Dune, Дени Вильнёв — 4 фильма.

Панель: раздел «Медиа: граф контента» с числом карточек и связей, таблицей
связей с диаграммами и списком книг-экранизаций. Панель выросла до 10.4 КБ.

Ловушки: /person перехватывал /persons (уточнён маршрут); «персоны режиссёры»
разбиралось как поиск человека по имени «режиссёры» — добавлено распознавание
запросов-списков.
This commit is contained in:
buryan-agent committed 2026-10-20 11:32:23 +03:00
1 parent ba5e011d7a
commit d9ec1d25a3
4 files changed
+341 -25

No files matched your search

+97 -24
View File
@@ -24,7 +24,7 @@ def _empty_hint():
class MediaBot(Bot):
ALIASES = dict(Bot.ALIASES, **{"связи": "связи", "тема": "тема",
ALIASES = dict(Bot.ALIASES, **{"связи": "связи", "тема": "тема", "граф": "граф",
"рекомендации": "рекомендации"})
name = "media"
title = "Медиа"
@@ -36,6 +36,93 @@ class MediaBot(Bot):
def _timeline_cmd(self, arg):
term = (arg or "").strip()
if not term:
return "Укажите тему или жанр: !время science fiction"
for kind in ("тема", "жанр"):
data, err = core_api.timeline(term, kind)
if err or not data:
continue
node = data.get("node") or {}
decades = data.get("decades") or []
lines = ["**" + str(node.get("title")) + " по десятилетиям**", ""]
for d in decades:
lines.append("• " + str(d.get("decade")) + " — " + str(d.get("n")) +
": " + str(d.get("items"))[:120])
if not decades:
lines.append("_по десятилетиям не разложилось_")
return chr(10).join(lines)
return "«" + term + "» в графе нет."
def _cross_cmd(self):
data, err = core_api.cross_format()
if err:
return "Ядро не ответило: " + str(err)
books = (data or {}).get("books_with_film") or []
authors = (data or {}).get("authors_screened") or []
lines = ["**Книги и их экранизации в медиатеке**", ""]
if books:
for b in books[:10]:
lines.append("• " + str(b.get("book")) + " ↔ " + str(b.get("film")))
else:
lines.append("_совпадений по названию нет_")
if authors:
lines.append("")
lines.append("**Авторы, чьи книги экранизированы**")
for a in authors[:10]:
lines.append("• " + str(a.get("author")) + " → " + str(a.get("film")))
return chr(10).join(lines)
def _persons_cmd(self, arg):
kind = "режиссёр" if "реж" in (arg or "").lower() else "актёр"
data, err = core_api.top_persons(kind)
if err:
return "Ядро не ответило: " + str(err)
items = (data or {}).get("items") or []
if not items:
return "Персон пока нет в графе."
lines = ["**" + kind.capitalize() + "ы: у кого больше фильмов**", ""]
for i in items[:12]:
lines.append("• " + str(i.get("title")) + " — " + str(i.get("films")))
return chr(10).join(lines)
def _graph_cmd(self, arg):
token = (arg or "").strip().lower()
if token and token not in ("граф", "stats", "статистика"):
return self._graph_lookup(token)
data, err = core_api.graph_stats()
if err:
return "Ядро не ответило: " + str(err)
cards = (data or {}).get("cards") or []
rels = (data or {}).get("relations") or []
lines = ["**Граф контента: " + str((data or {}).get("total_cards")) + " карточек, " +
str((data or {}).get("total_links")) + " связей**", ""]
lines.append("Карточки:")
for c in cards[:10]:
if c.get("kind") in ("монитор", "устройство", "тревога", "бэкап", "аудит", "проверка"):
continue
lines.append("• " + str(c.get("kind")) + ": " + str(c.get("n")))
lines.append("")
lines.append("Связи:")
for r in rels[:10]:
lines.append("• " + str(r.get("relation")) + ": " + str(r.get("n")))
return chr(10).join(lines)
def _graph_lookup(self, term):
card, err = core_api.find_entity(term)
if err or not card:
return "«" + term + "» в графе нет. Просто !граф — общая статистика."
data, _ = core_api.links_of(card["id"])
links = (data or {}).get("links") or []
lines = ["**" + str(card.get("title")) + "** (" + str(card.get("kind")) + "), связей: " +
str(len(links)), ""]
for l in links[:15]:
lines.append("• " + str(l.get("relation")) + ": " + str(l.get("title")))
return chr(10).join(lines)
def _pick_cmd(self, arg):
import re as _re
text = (arg or "").strip()
@@ -95,8 +182,12 @@ class MediaBot(Bot):
def _person_cmd(self, arg):
name = (arg or "").strip()
low = name.lower()
# «персоны режиссёры» — это запрос списка, а не имя
if any(w in low for w in ("режисс", "актёр", "актер", "композитор", "все ")):
return self._persons_cmd(name)
if not name:
return "Укажите имя: !персона Зендая или !персона Zendaya"
return "Укажите имя: !персона Zendaya, либо !персоны режиссёры"
data, err = core_api.person(name)
if err:
return "Ядро не ответило: " + str(err)
@@ -173,28 +264,6 @@ class MediaBot(Bot):
lines.append("_Это кандидаты: их нет в медиатеке, но они рекомендованы._")
return chr(10).join(lines)
def _graph_cmd(self, arg):
term = (arg or "").strip()
if not term:
return "Укажите название: !связи Дюна"
card, err = core_api.find_entity(term)
if err:
return "Ядро не ответило: " + str(err)
if not card:
return "«" + term + "» в графе нет."
data, _ = core_api.links_of(card["id"])
info = data or {}
links = info.get("links") or []
lines = ["**" + str(card.get("title")) + "** (" + str(card.get("kind")) + ")", ""]
by_rel = {}
for l in links:
by_rel.setdefault(l.get("relation") or "связь", []).append(str(l.get("title")))
for rel, titles in by_rel.items():
lines.append("• " + rel + ": " + ", ".join(titles[:8]))
if not links:
lines.append("_связей нет_")
return chr(10).join(lines)
def _media_hub_cmd(self):
"""Медиа Хаб: заявки, очередь, просмотр, нехватка, место."""
data, err = core_api.get_data("media", 1)
@@ -230,6 +299,10 @@ class MediaBot(Bot):
self.cmd("персона", "фильмы персоны: !персона Zendaya")(lambda a: self._person_cmd(a))
self.cmd("похоже", "похожие по темам: !похоже Дюна")(lambda a: self._similar_cmd(a))
self.cmd("посмотреть", "подбор из медиатеки: !посмотреть 80-е")(lambda a: self._pick_cmd(a))
self.cmd("время", "тема по десятилетиям: !время science fiction")(lambda a: self._timeline_cmd(a))
self.cmd("кросс", "книги и их экранизации в медиатеке")(lambda a: self._cross_cmd())
self.cmd("персоны", "у кого больше фильмов: !персоны режиссёры")(lambda a: self._persons_cmd(a))
self.cmd("граф", "статистика графа: !граф")(lambda a: self._graph_cmd(a))
def _stats(self, jf):
c = jf.counts()
info, _ = jf.info()
+16
View File
@@ -123,3 +123,19 @@ def pick(genre=None, theme=None, decade=None, limit=10):
if decade:
params["decade"] = decade
return _get("/pick", params)
def timeline(query, kind="тема"):
return _get("/timeline", {"q": query, "kind": kind})
def cross_format():
return _get("/cross")
def top_persons(kind="актёр"):
return _get("/persons", {"kind": kind})
def graph_stats():
return _get("/graph")
+40
View File
@@ -165,3 +165,43 @@ GET /pick?decade=1980-е → Blade Runner (1982)
Двузначный год нельзя превращать в `80-е` напрямую: получалось `800-е`.
Правило: 30–99 → 19xx, 00–29 → 20xx, дальше десятилетие.
---
## Аналитика графа
### Эндпоинты
| Эндпоинт | Что отдаёт |
|---|---|
| `GET /graph` | статистика: карточки по видам, связи по типам |
| `GET /graph?json` | узлы (с числом связей) и рёбра для визуализации |
| `GET /timeline?q=&kind=` | тема или жанр по десятилетиям |
| `GET /cross` | книги с экранизацией и авторы, чьи книги экранизированы |
| `GET /persons?kind=` | персоны с наибольшим числом фильмов |
### Команды бота
```
граф → 285 карточек, 382 связи; топ связей
время science fiction → по десятилетиям:
1970-е — Alien, 1980-е — Blade Runner,
1990-е — Fifth Element и Matrix, 2000-е — Matrix 2-3,
2010-е — Arrival, BR2049, Interstellar, Prometheus,
2020-е — оба Dune
кросс → Dune ↔ Dune (2021); Frank Herbert → Dune (2021)
персоны режиссёры → Denis Villeneuve 4, Wachowskis по 3, Ridley Scott 3
```
### Панель
Новый раздел **«Медиа: граф контента»**: число карточек и связей, таблица
связей с полосками-диаграммами, список книг и их экранизаций.
### Ловушки
* Маршрут `/person` (поиск персоны) перехватывал `/persons` (список).
Исправлено: `/person` срабатывает только на точный путь или с `?`.
* Слово «персоны» разбиралось как команда `персона`, поэтому
«персоны режиссёры» шло в поиск человека по имени «режиссёры».
Теперь `_person_cmd` распознаёт запросы-списки и передаёт их в `_persons_cmd`.
+188 -1
View File
@@ -561,6 +561,124 @@ def do_pick(genre=None, theme=None, decade=None, kind="фильм", limit=10):
return {"count": len(items), "items": items}
def do_timeline(node_query, kind="тема"):
"""Как тема или жанр распределены по десятилетиям."""
con = db()
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""select id, title from entities
where kind = %s and search_text like %s
order by length(title) limit 1""", (kind, f"%{node_query.lower()}%"))
node = cur.fetchone()
if not node:
con.close()
return None
cur.execute("""
with items as (
select case when l.from_id = %s then l.to_id else l.from_id end as item_id
from entity_links l
where (l.from_id = %s or l.to_id = %s) and l.relation = %s
)
select d.title as decade, count(*) as n,
string_agg(e.title, ', ' order by e.title) as items
from items i
join entity_links l on (l.from_id = i.item_id or l.to_id = i.item_id)
join entities d on d.id = case when l.from_id = i.item_id then l.to_id else l.from_id end
join entities e on e.id = i.item_id
where d.kind = 'эпоха' and l.relation = 'снят в'
group by d.title
order by d.title
""", (node["id"], node["id"], node["id"], kind if False else node.get("title") and kind or kind))
rows = [dict(r) for r in cur.fetchall()]
con.close()
return {"node": dict(node), "decades": rows}
def do_cross(limit=50):
"""Книги с экранизацией в медиатеке и наоборот."""
con = db()
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
select b.title as book, f.title as film
from entity_links l
join entities b on b.id = l.from_id and b.kind = 'книга'
join entities f on f.id = l.to_id and f.kind = 'фильм'
where l.relation = 'экранизация'
order by b.title limit %s
""", (limit,))
books_with_film = [dict(r) for r in cur.fetchall()]
cur.execute("""
select a.title as author, f.title as film
from entity_links l
join entities a on a.id = l.from_id and a.kind = 'автор'
join entities f on f.id = l.to_id and f.kind = 'фильм'
where l.relation = 'экранирован'
order by a.title limit %s
""", (limit,))
authors_screen = [dict(r) for r in cur.fetchall()]
con.close()
return {"books_with_film": books_with_film,
"authors_screened": authors_screen}
def do_top_persons(kind="актёр", limit=10):
"""Персоны с наибольшим числом фильмов."""
con = db()
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
select p.id, p.title, count(*) as films
from entity_links l
join entities p on p.id = case when l.from_id = p.id then p.id else l.to_id end
where p.kind = %s and l.relation in ('снялся','снял','музыка')
group by p.id, p.title
order by films desc, p.title
limit %s
""", (kind, limit))
items = [dict(r) for r in cur.fetchall()]
con.close()
return {"kind": kind, "items": items}
def do_graph_stats():
con = db()
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("select kind, count(*) as n from entities group by kind order by n desc")
cards = [dict(r) for r in cur.fetchall()]
cur.execute("select relation, count(*) as n from entity_links group by relation order by n desc")
relations = [dict(r) for r in cur.fetchall()]
con.close()
return {"cards": cards, "relations": relations,
"total_cards": sum(c["n"] for c in cards),
"total_links": sum(r["n"] for r in relations)}
def do_graph_json(limit=150):
"""Узлы и рёбра для визуализации."""
con = db()
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("""
select e.id, e.kind, e.title, count(l.id) as degree
from entities e left join entity_links l on l.from_id = e.id or l.to_id = e.id
group by e.id, e.kind, e.title
order by degree desc limit %s
""", (limit,))
nodes = [dict(r) for r in cur.fetchall()]
ids = [n["id"] for n in nodes]
edges = []
if ids:
cur.execute("""
select l.from_id as source, l.to_id as target, l.relation
from entity_links l
where l.from_id = any(%s) and l.to_id = any(%s)
limit 500
""", (ids, ids))
edges = [dict(r) for r in cur.fetchall()]
con.close()
return {"nodes": nodes, "edges": edges}
def render_panel():
"""HTML-страница: состояние системы в одном месте."""
try:
@@ -600,6 +718,18 @@ def render_panel():
except Exception:
identity = None
jobs = jobs_status()
try:
gstats = do_graph_stats()
except Exception:
gstats = {"cards": [], "relations": [], "total_cards": 0, "total_links": 0}
try:
cross = do_cross(limit=10)
except Exception:
cross = {"books_with_film": [], "authors_screened": []}
try:
top_genres = do_pick(limit=100) if False else []
except Exception:
top_genres = []
cur.execute("select count(*) from entity_links")
links = cur.fetchone()[0]
cur.execute("""select at, kind, target, detail, status from actions
@@ -611,6 +741,8 @@ def render_panel():
entities = events = events24 = open_problems = 0
problems, recent, by_source, actions, links, inventory, identity = [], [], [], [], 0, None, None
jobs = []
gstats = {"cards": [], "relations": [], "total_cards": 0, "total_links": 0}
cross = {"books_with_film": [], "authors_screened": []}
err = str(e)[:200]
def esc(x):
@@ -621,6 +753,24 @@ def render_panel():
f"<td>{esc(typ)}</td><td>{esc(title)}</td></tr>"
for at, src, typ, title in recent) or "<tr><td colspan=4>событий пока нет</td></tr>"
media_kinds = {"фильм", "книга", "жанр", "тема", "актёр", "режиссёр",
"композитор", "студия", "коллекция", "серия книг", "автор",
"эпоха", "кандидат", "оценка", "язык", "рейтинг"}
g_cards = sum(c["n"] for c in gstats.get("cards") or [] if c["kind"] in media_kinds)
g_links = gstats.get("total_links") or 0
max_rel = max([r["n"] for r in gstats.get("relations") or []] or [1])
g_rel_rows = "".join(
f"<tr><td>{esc(r['relation'])}</td><td>{r['n']}</td>"
f"<td><div style='background:#2d6cdf;height:8px;width:{int(180 * r['n'] / max_rel)}px;border-radius:4px'></div></td></tr>"
for r in (gstats.get("relations") or [])[:12]) or "<tr><td colspan=3>пусто</td></tr>"
cross_rows = []
for b in (cross.get("books_with_film") or [])[:6]:
cross_rows.append(f"<tr><td>📖 {esc(b['book'])}</td><td>↔</td><td>🎬 {esc(b['film'])}</td></tr>")
for a in (cross.get("authors_screened") or [])[:6]:
cross_rows.append(f"<tr><td>✍️ {esc(a['author'])}</td><td>→</td><td>🎬 {esc(a['film'])}</td></tr>")
g_cross_rows = "".join(cross_rows) or "<tr><td colspan=3>пока нет совпадений</td></tr>"
job_rows = "".join(
f"<tr><td>{esc(n)}</td><td>{(str(round(a, 1)) + ' ч') if a is not None else '—'}</td>"
f"<td>{lim} ч</td><td class=\"{'bad' if st != 'ок' else ''}\">{esc(st)}</td></tr>"
@@ -692,6 +842,11 @@ th{{color:#7d8b99;font-weight:500}}
<h2>Графики</h2>
<div>Дашборд: <a href="http://192.168.1.113:3000/d/buryan-hub">Grafana — Buryan Hub</a>
· <a href="/metrics">метрики Prometheus</a></div>
<h2>Медиа: граф контента</h2>
<div class="muted">карточек {g_cards} · связей {g_links}</div>
<table><tr><th>связь</th><th>сколько</th><th></th></tr>{g_rel_rows}</table>
<h3 style="font-size:14px;color:#8fb4d9;margin:18px 0 6px">Книги и экранизации</h3>
<table>{g_cross_rows}</table>
<h2>Доступы по сервисам</h2>
<div class="muted">аудит по понедельникам, команда !users у бота Инфраструктура</div>
<pre>{identity_text}</pre>
@@ -808,6 +963,38 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(body)
return
if self.path.startswith("/timeline"):
import urllib.parse as _u1
qs = _u1.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
q = (qs.get("q") or [""])[0]
k = (qs.get("kind") or ["тема"])[0]
if not q:
return self._json(400, {"error": "нужен q"})
try:
data = do_timeline(q, k)
except Exception as e:
return self._json(500, {"error": str(e)[:200]})
return self._json(200 if data else 404, data or {"error": "не найдено"})
if self.path.startswith("/cross"):
try:
return self._json(200, do_cross())
except Exception as e:
return self._json(500, {"error": str(e)[:200]})
if self.path.startswith("/persons"):
import urllib.parse as _u2
qs = _u2.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
k = (qs.get("kind") or ["актёр"])[0]
try:
return self._json(200, do_top_persons(k))
except Exception as e:
return self._json(500, {"error": str(e)[:200]})
if self.path.startswith("/graph"):
try:
if "json" in self.path:
return self._json(200, do_graph_json())
return self._json(200, do_graph_stats())
except Exception as e:
return self._json(500, {"error": str(e)[:200]})
if self.path.startswith("/pick"):
import urllib.parse as _upp
qs = _upp.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
@@ -839,7 +1026,7 @@ class Handler(BaseHTTPRequestHandler):
if not data:
return self._json(404, {"error": "карточка не найдена"})
return self._json(200, data)
if self.path.startswith("/person"):
if self.path == "/person" or self.path.startswith("/person?"):
import urllib.parse as _up3
qs = _up3.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
q = (qs.get("q") or [""])[0]