From 3707a34e09bd631cfcaac3f60cabf55fc5776dea Mon Sep 17 00:00:00 2001 From: buryan-agent Date: Tue, 20 Oct 2026 12:00:33 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=81=D1=82=D0=BE=D1=80=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=80=D0=BE=D1=81=D1=82=D0=B0=20=D0=B3=D1=80=D0=B0=D1=84=D0=B0?= =?UTF-8?q?=20=D0=B8=20=D0=B0=D0=B2=D1=82=D0=BE=D0=B4=D0=BE=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D0=BD=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=20=D0=B8=D0=BD?= =?UTF-8?q?=D1=82=D0=B5=D1=80=D1=84=D0=B5=D0=B9=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Таблица graph_history с ежедневными снимками (карточки, связи, персоны). GET /snapshot делает снимок, GET /history отдаёт ряд и прирост. Cron 23:30. Панель показывает рост за период, бот в команде «граф» — тоже. Проверено на имитированном недельном снимке: было 250/380, стало 310/455, прирост 60 карточек и 75 связей. В /ask.html добавлено автодополнение через GET /suggest. --- ops/bots/hub/bots.py | 6 ++++ ops/bots/hub/core_api.py | 4 +++ ops/media/GRAPH-HISTORY.md | 32 ++++++++++++++++++ ops/media/core.py | 66 +++++++++++++++++++++++++++++++++++++- ops/media/graph/ask.html | 19 ++++++++++- 5 files changed, 125 insertions(+), 2 deletions(-) create mode 100644 ops/media/GRAPH-HISTORY.md diff --git a/ops/bots/hub/bots.py b/ops/bots/hub/bots.py index cf16373..6bf85d2 100644 --- a/ops/bots/hub/bots.py +++ b/ops/bots/hub/bots.py @@ -245,6 +245,12 @@ class MediaBot(Bot): lines.append("Связи:") for r in rels[:10]: lines.append("• " + str(r.get("relation")) + ": " + str(r.get("n"))) + hist, _ = core_api.history(30) + growth = (hist or {}).get("growth") + if growth: + lines.append("") + lines.append("_рост за период: карточек " + str(growth.get("cards")) + + ", связей " + str(growth.get("links")) + "_") return chr(10).join(lines) def _graph_lookup(self, term): diff --git a/ops/bots/hub/core_api.py b/ops/bots/hub/core_api.py index ee56637..5ca1c85 100644 --- a/ops/bots/hub/core_api.py +++ b/ops/bots/hub/core_api.py @@ -155,3 +155,7 @@ def coworkers(query, limit=12): def suggest(q, limit=8): return _get("/suggest", {"q": q, "limit": limit}) + + +def history(days=30): + return _get("/history", {"days": days}) diff --git a/ops/media/GRAPH-HISTORY.md b/ops/media/GRAPH-HISTORY.md new file mode 100644 index 0000000..f08832b --- /dev/null +++ b/ops/media/GRAPH-HISTORY.md @@ -0,0 +1,32 @@ +# История роста графа + +Ежедневный снимок размеров графа — чтобы видеть, растёт ли медиатека. + +## Как устроено + +* таблица `graph_history(day, cards, links, persons)` создаётся при первом + обращении; +* `GET /snapshot` — сделать снимок за сегодня (upsert); +* `GET /history?days=30` — ряд снимков и прирост между первым и последним; +* cron `30 23 * * *` — снимок каждый вечер. + +## Где видно + +* панель: строка «карточек N · связей M · рост за период: карточек +X, + связей +Y»; +* бот: команда `граф` добавляет «_рост за период: …_». + +### Проверка + +Имитировал снимок недельной давности (250 карточек, 380 связей) — текущий +310/455: + +``` +история: [{13.10: 250/380/60}, {20.10: 310/455/74}] +рост: карточек 60, связей 75 +``` + +## Дополнительно: автодополнение + +В `/ask.html` поле ввода подсказывает карточки (`GET /suggest`, задержка +250 мс). Работает и по русским окончаниям: «дюн» → оба Dune. diff --git a/ops/media/core.py b/ops/media/core.py index 1d2ef20..872ca94 100644 --- a/ops/media/core.py +++ b/ops/media/core.py @@ -884,6 +884,45 @@ def do_suggest(q, limit=8): return {"query": q, "items": items} + + +def snapshot_graph(day=None): + """Снимок размеров графа за день.""" + from datetime import date + day = day or date.today().isoformat() + con = db() + cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) + cur.execute("""create table if not exists graph_history ( + day date primary key, cards integer, links integer, persons integer)""") + cur.execute("select count(*) as n from entities") + cards = cur.fetchone()["n"] + cur.execute("select count(*) as n from entity_links") + links = cur.fetchone()["n"] + cur.execute("select count(*) as n from entities where kind in ('актёр','режиссёр','композитор')") + persons = cur.fetchone()["n"] + cur.execute("""insert into graph_history (day, cards, links, persons) values (%s, %s, %s, %s) + on conflict (day) do update set cards = %s, links = %s, persons = %s""", + (day, cards, links, persons, cards, links, persons)) + con.commit() + con.close() + return {"day": str(day), "cards": cards, "links": links, "persons": persons} + + +def do_history(days=30): + con = db() + cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) + cur.execute("""select day, cards, links, persons from graph_history + order by day desc limit %s""", (days,)) + rows = [dict(r) for r in cur.fetchall()] + con.close() + rows.reverse() + growth = None + if len(rows) >= 2: + growth = {"cards": rows[-1]["cards"] - rows[0]["cards"], + "links": rows[-1]["links"] - rows[0]["links"]} + return {"items": rows, "growth": growth} + + def render_panel(): """HTML-страница: состояние системы в одном месте.""" try: @@ -927,6 +966,11 @@ def render_panel(): gstats = do_graph_stats() except Exception: gstats = {"cards": [], "relations": [], "total_cards": 0, "total_links": 0} + try: + hist = do_history(30) + growth = hist.get("growth") + except Exception: + growth = None try: cross = do_cross(limit=10) except Exception: @@ -974,6 +1018,10 @@ def render_panel(): cross_rows.append(f"📖 {esc(b['book'])}↔🎬 {esc(b['film'])}") for a in (cross.get("authors_screened") or [])[:6]: cross_rows.append(f"✍️ {esc(a['author'])}→🎬 {esc(a['film'])}") + g_growth = "" + if growth: + g_growth = (" · рост за период: карточек " + str(growth.get("cards")) + + ", связей " + str(growth.get("links"))) g_cross_rows = "".join(cross_rows) or "пока нет совпадений" job_rows = "".join( @@ -1052,7 +1100,7 @@ th{{color:#7d8b99;font-weight:500}} интерактивный граф · спросить агента -
карточек {g_cards} · связей {g_links}
+
карточек {g_cards} · связей {g_links}{g_growth}
{g_rel_rows}
связьсколько

Книги и экранизации

{g_cross_rows}
@@ -1279,6 +1327,22 @@ class Handler(BaseHTTPRequestHandler): 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("/history"): + import urllib.parse as _uh + qs = _uh.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} + try: + days = int((qs.get("days") or ["30"])[0]) + except ValueError: + days = 30 + try: + return self._json(200, do_history(days)) + except Exception as e: + return self._json(500, {"error": str(e)[:200]}) + if self.path.startswith("/snapshot"): + try: + return self._json(200, snapshot_graph()) + except Exception as e: + return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/suggest"): import urllib.parse as _usg qs = _usg.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} diff --git a/ops/media/graph/ask.html b/ops/media/graph/ask.html index cb05d2b..d900b7a 100644 --- a/ops/media/graph/ask.html +++ b/ops/media/graph/ask.html @@ -36,7 +36,8 @@

Агент по медиатеке

Понимает вопрос словами и отвечает по графу контента
- + +
@@ -65,6 +66,22 @@ const out = document.getElementById("out"); const btn = document.getElementById("b"); document.getElementById("f").addEventListener("submit", e => { e.preventDefault(); ask(); }); +let hintTimer = null; +document.getElementById("q").addEventListener("input", e => { + const v = e.target.value.trim(); + clearTimeout(hintTimer); + if (v.length < 2) return; + hintTimer = setTimeout(async () => { + try { + const r = await fetch("suggest?q=" + encodeURIComponent(v)); + const d = await r.json(); + const dl = document.getElementById("hints"); + dl.innerHTML = (d.items || []).map(i => + "