История роста графа и автодополнение в интерфейсе
Таблица graph_history с ежедневными снимками (карточки, связи, персоны). GET /snapshot делает снимок, GET /history отдаёт ряд и прирост. Cron 23:30. Панель показывает рост за период, бот в команде «граф» — тоже. Проверено на имитированном недельном снимке: было 250/380, стало 310/455, прирост 60 карточек и 75 связей. В /ask.html добавлено автодополнение через GET /suggest.
This commit is contained in:
1 parent
55108a6ba4
commit
3707a34e09
5 files changed
+125
-2
No files matched your search
@@ -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):
|
||||
|
||||
@@ -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})
|
||||
@@ -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.
|
||||
+65
-1
@@ -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"<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_growth = ""
|
||||
if growth:
|
||||
g_growth = (" · рост за период: карточек " + str(growth.get("cards")) +
|
||||
", связей " + str(growth.get("links")))
|
||||
g_cross_rows = "".join(cross_rows) or "<tr><td colspan=3>пока нет совпадений</td></tr>"
|
||||
|
||||
job_rows = "".join(
|
||||
@@ -1052,7 +1100,7 @@ th{{color:#7d8b99;font-weight:500}}
|
||||
<a href="graph.html">интерактивный граф</a> ·
|
||||
<a href="ask.html">спросить агента</a>
|
||||
</div>
|
||||
<div class="muted">карточек {g_cards} · связей {g_links}</div>
|
||||
<div class="muted">карточек {g_cards} · связей {g_links}{g_growth}</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>
|
||||
@@ -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 {}
|
||||
|
||||
@@ -36,7 +36,8 @@
|
||||
<h1>Агент по медиатеке</h1>
|
||||
<div class="sub">Понимает вопрос словами и отвечает по графу контента</div>
|
||||
<form id="f">
|
||||
<input id="q" type="text" placeholder="например: фильмы Нолана про космос с высоким рейтингом" autofocus>
|
||||
<input id="q" type="text" list="hints" placeholder="например: фильмы Нолана про космос с высоким рейтингом" autofocus>
|
||||
<datalist id="hints"></datalist>
|
||||
<button id="b">Спросить</button>
|
||||
</form>
|
||||
<div class="chips" id="chips"></div>
|
||||
@@ -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 =>
|
||||
"<option value='" + String(i.title).replace(/'/g, "’") + "'>").join("");
|
||||
} catch (err) {}
|
||||
}, 250);
|
||||
});
|
||||
|
||||
async function ask(){
|
||||
const q = document.getElementById("q").value.trim();
|
||||
if (!q) return;
|
||||
|
||||
Reference in new issue
Block a user