Граф в браузере, подбор по настроению, недельный дайджест

Интерактивный граф: /graph.html — canvas с силовой укладкой без внешних
библиотек, подсветка соседей, клик по узлу, поиск, зум и перетаскивание.
Доступен через панель ядра (status.buryans.ru/hub/graph.html).

Подбор по настроению: /mood с словарём тем и жанров (мрачное, лёгкое,
умное, эпичное, страшное, детектив). Сначала искал только по темам и на
маленькой библиотеке давал пустоту — добавление жанров исправило.

Недельный дайджест media_digest.py: понедельник 09:00 в личный чат бота
Медиа — фильмы, книги, связи, книги-экранизации, кандидаты. Копия в ядре.

Ловушка: токены в bots.env, а актуальные комнаты — в dm.env. Комната из
bots.env даёт 403 Forbidden (старые комнаты).
This commit is contained in:
buryan-agent committed 2026-10-20 11:41:54 +03:00
1 parent 03d20b95db
commit 483617d38f
6 files changed
+485

No files matched your search

+24
View File
@@ -40,6 +40,29 @@ class MediaBot(Bot):
def _mood_cmd(self, arg):
word = (arg or "").strip()
if not word:
return ("Укажите настроение: !настроение мрачное, лёгкое, умное, "
"эпичное, страшное, доброе")
data, err = core_api.mood(word)
if err:
return "Ядро не ответило: " + str(err)
items = (data or {}).get("items") or []
if not items:
hints = (data or {}).get("hints") or []
return ("Под это настроение ничего не нашлось. Искал по темам: "
+ ", ".join(hints[:5]) if hints else "Не понял настроение.")
lines = ["**Настроение: " + word + "** — " + str(len(items)), ""]
for i in items:
parts = [str(i.get("title"))]
if i.get("rating"):
parts.append(str(i.get("rating")))
lines.append("• " + " — ".join(parts))
return chr(10).join(lines)
def _agent_cmd(self, arg):
"""Агент: понимает фразу и выполняет запрос по графу."""
from . import agent as graph_agent
@@ -329,6 +352,7 @@ class MediaBot(Bot):
self.cmd("персоны", "у кого больше фильмов: !персоны режиссёры")(lambda a: self._persons_cmd(a))
self.cmd("граф", "статистика графа: !граф")(lambda a: self._graph_cmd(a))
self.cmd("агент", "спросить агента словами: !агент найди фильмы Нолана")(lambda a: self._agent_cmd(a))
self.cmd("настроение", "подбор по настроению: !настроение мрачное")(lambda a: self._mood_cmd(a))
def _stats(self, jf):
c = jf.counts()
info, _ = jf.info()
+4
View File
@@ -139,3 +139,7 @@ def top_persons(kind="актёр"):
def graph_stats():
return _get("/graph")
def mood(word, limit=10):
return _get("/mood", {"mood": word, "limit": limit})
+60
View File
@@ -0,0 +1,60 @@
# Граф: страница в браузере, настроения, дайджест
## Интерактивный граф
`GET /graph.html` — страница с силовой укладкой на canvas, без внешних
библиотек (работает офлайн).
* узлы окрашены по виду карточки, размер — по числу связей;
* наведение и выбор подсвечивают соседей;
* клик показывает карточку и её связи;
* поиск по названию подсвечивает совпадения;
* перетаскивание — сдвиг, колесо — масштаб.
Доступно по `https://status.buryans.ru/hub/graph.html` (панель ядра
проксируется туда же). Данные берутся из `GET /graph?json` относительным
путём — иначе за прокси `/graph` уходит в корень домена.
## Подбор по настроению
`GET /mood?mood=мрачное` — темы и жанры из словаря:
| Настроение | На что смотрит |
|---|---|
| мрачное | dystopia, noir, dark, survival, horror, thriller, drama |
| лёгкое | comedy, family, adventure, romance |
| умное | artificial intelligence, based on novel, mystery, science fiction |
| эпичное | epic, space opera, adventure, science fiction, war |
| страшное | horror, monster, thriller, mystery |
| детектив | detective, mystery, crime, thriller |
Команда бота: `!настроение умное` → 8 фильмов с оценками.
Первая версия искала только по темам и на маленькой библиотеке давала
пустоту; добавление жанров в те же списки решило проблему.
## Недельный дайджест
`media_digest.py` — понедельник 09:00, отправка в личный чат бота Медиа:
```
🎬 Медиатека: неделя в графе
Фильмов: 12 · книг: 10 · связей: 382
Связи: рекомендует 72, снялся 60, тема 60, жанр 49, похож 22, снял 15
Книга ↔ фильм:
• Dune ↔ Dune (2021)
Посмотреть (кандидаты):
• Terminator Salvation …
```
Копия сохраняется в ядре (коллекция `media_digest`).
### Ловушка с отправкой
Токены лежат в `bots.env` (`MEDIA_TOKEN`), а **актуальные комнаты — в
`dm.env`** (`MEDIA=!x7_Vj4CVPXA…`). Если взять комнату из `bots.env`,
Matrix отвечает **403 Forbidden**, потому что там старые комнаты.
Правильно: токен из `bots.env`, комната из `dm.env`.
+75
View File
@@ -758,6 +758,59 @@ def do_graph_json(limit=150):
return {"nodes": nodes, "edges": edges}
MOODS = {
"мрачн": ["dystopia", "noir", "dark", "survival", "horror", "thriller", "drama"],
"мрач": ["dystopia", "noir", "dark", "survival", "horror", "thriller", "drama"],
"тяжёл": ["drama", "war", "thriller", "mystery"],
"лёгк": ["comedy", "family", "adventure", "romance"],
"легк": ["comedy", "family", "adventure", "romance"],
"добр": ["family", "friendship", "adventure", "comedy"],
"умн": ["artificial intelligence", "based on novel", "mystery", "science fiction"],
"эпичн": ["epic", "space opera", "adventure", "science fiction", "war"],
"страшн": ["horror", "monster", "thriller", "mystery"],
"смешн": ["comedy"],
"романтич": ["romance", "drama"],
"детектив": ["detective", "mystery", "crime", "thriller"],
}
def do_mood(mood, limit=10):
"""Подбор по настроению: темы и жанры из словаря MOODS."""
low = (mood or "").lower()
hints = []
for key, words in MOODS.items():
if key in low:
hints = words
break
if not hints:
return {"mood": mood, "count": 0, "items": [], "hints": []}
con = db()
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
like = ["%" + h.lower() + "%" for h in hints]
cur.execute("""
select e.id, e.title, count(distinct n.id) as score
from entities e
join entity_links l on l.from_id = e.id
join entities n on n.id = l.to_id
where e.kind = 'фильм' and n.search_text like any(%s)
and l.relation in ('тема', 'жанр')
group by e.id, e.title
order by score desc, e.title
limit %s
""", (like, limit))
items = [dict(r) for r in cur.fetchall()]
for it in items:
cur.execute("""select n.title from entity_links l join entities n on n.id = l.to_id
where l.from_id = %s and l.relation = 'оценка' limit 1""", (it["id"],))
row = cur.fetchone()
it["rating"] = row["title"] if row else None
con.close()
return {"mood": mood, "count": len(items), "items": items, "hints": hints}
def render_panel():
"""HTML-страница: состояние системы в одном месте."""
try:
@@ -1079,6 +1132,18 @@ class Handler(BaseHTTPRequestHandler):
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.html"):
try:
with open("/opt/hub-core/graph.html", encoding="utf-8") as f:
body = f.read().encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
except Exception as e:
return self._json(500, {"error": str(e)[:200]})
if self.path.startswith("/graph"):
try:
if "json" in self.path:
@@ -1086,6 +1151,16 @@ class Handler(BaseHTTPRequestHandler):
return self._json(200, do_graph_stats())
except Exception as e:
return self._json(500, {"error": str(e)[:200]})
if self.path.startswith("/mood"):
import urllib.parse as _um
qs = _um.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
m = (qs.get("mood") or [""])[0]
if not m:
return self._json(400, {"error": "нужен mood"})
try:
return self._json(200, do_mood(m))
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 {}
+211
View File
@@ -0,0 +1,211 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Граф контента — Buryans Hub</title>
<style>
:root { --bg:#0d1117; --fg:#c9d1d9; --dim:#8b949e; --line:#30363d; }
* { box-sizing: border-box; }
body { margin:0; background:var(--bg); color:var(--fg);
font:14px/1.5 -apple-system,"Segoe UI",Roboto,sans-serif; overflow:hidden; }
#top { position:fixed; top:0; left:0; right:0; height:52px; display:flex;
align-items:center; gap:14px; padding:0 16px;
background:rgba(13,17,23,.92); border-bottom:1px solid var(--line); z-index:5; }
#top h1 { font-size:15px; margin:0; font-weight:600; }
#top .stat { color:var(--dim); font-size:12px; }
#search { margin-left:auto; background:#161b22; border:1px solid var(--line);
color:var(--fg); border-radius:6px; padding:6px 10px; width:240px; outline:none; }
#legend { position:fixed; left:16px; bottom:16px; background:rgba(22,27,34,.92);
border:1px solid var(--line); border-radius:8px; padding:10px 12px;
font-size:12px; z-index:5; max-width:220px; }
#legend div { display:flex; align-items:center; gap:8px; margin:3px 0; }
.dot { width:10px; height:10px; border-radius:50%; flex:none; }
#info { position:fixed; right:16px; bottom:16px; width:280px; max-height:50vh;
overflow:auto; background:rgba(22,27,34,.95); border:1px solid var(--line);
border-radius:8px; padding:12px; font-size:12px; z-index:5; display:none; }
#info b { color:#fff; }
#info ul { margin:8px 0 0; padding-left:16px; }
canvas { display:block; }
</style>
</head>
<body>
<div id="top">
<h1>Граф контента</h1>
<span class="stat" id="stat">загрузка…</span>
<input id="search" placeholder="Найти карточку…">
</div>
<div id="legend"></div>
<div id="info"></div>
<canvas id="c"></canvas>
<script>
const COLORS = {
"фильм":"#58a6ff","книга":"#3fb950","жанр":"#d29922","тема":"#a371f7",
"актёр":"#f0883e","режиссёр":"#f85149","композитор":"#db61a2",
"студия":"#39c5cf","коллекция":"#e3b341","серия книг":"#7ee787",
"автор":"#ffa657","эпоха":"#8b949e","кандидат":"#484f58","оценка":"#bc8cff",
"язык":"#79c0ff","рейтинг":"#ff7b72"
};
const c = document.getElementById("c"), ctx = c.getContext("2d");
let W=0,H=0, nodes=[], edges=[], byId={}, hover=null, selected=null, query="";
let cam={x:0,y:0,k:1};
function resize(){
W = c.width = innerWidth * devicePixelRatio;
H = c.height = innerHeight * devicePixelRatio;
c.style.width = innerWidth+"px"; c.style.height = innerHeight+"px";
}
addEventListener("resize", resize); resize();
fetch("graph?json").then(r=>r.json()).then(d=>{
const raw = d.nodes || [];
byId = {};
nodes = raw.map((n,i)=>{
const a = i / raw.length * Math.PI * 2;
const r = 120 + Math.random()*260;
const o = {id:n.id,title:n.title,kind:n.kind,degree:n.degree||1,
x:Math.cos(a)*r, y:Math.sin(a)*r, vx:0, vy:0};
byId[n.id]=o; return o;
});
edges = (d.edges||[]).map(e=>({s:+e.source,t:+e.target,r:e.relation}))
.filter(e=>byId[e.s]&&byId[e.t]);
document.getElementById("stat").textContent =
nodes.length+" карточек · "+edges.length+" связей";
buildLegend();
requestAnimationFrame(tick);
});
function buildLegend(){
const kinds = [...new Set(nodes.map(n=>n.kind))]
.sort((a,b)=>nodes.filter(n=>n.kind===b).length-nodes.filter(n=>n.kind===a).length);
const el = document.getElementById("legend");
el.innerHTML = kinds.map(k=>{
const n = nodes.filter(x=>x.kind===k).length;
return `<div><span class="dot" style="background:${COLORS[k]||'#666'}"></span>
${k} <span style="color:#8b949e">${n}</span></div>`;
}).join("");
}
function tick(){
// силы
for (let i=0;i<nodes.length;i++){
const a = nodes[i];
for (let j=i+1;j<nodes.length;j++){
const b = nodes[j];
let dx = b.x-a.x, dy = b.y-a.y, d2 = dx*dx+dy*dy+0.01;
if (d2 > 90000) continue;
const f = 900 / d2;
const d = Math.sqrt(d2);
dx/=d; dy/=d;
a.vx -= dx*f; a.vy -= dy*f; b.vx += dx*f; b.vy += dy*f;
}
}
for (const e of edges){
const a = byId[e.s], b = byId[e.t];
let dx=b.x-a.x, dy=b.y-a.y, d=Math.hypot(dx,dy)||1;
const f = (d-110) * 0.0016;
dx/=d; dy/=d;
a.vx += dx*f*d*0.02; a.vy += dy*f*d*0.02;
b.vx -= dx*f*d*0.02; b.vy -= dy*f*d*0.02;
}
for (const n of nodes){
n.vx += -n.x*0.0008; n.vy += -n.y*0.0008;
n.vx *= 0.94; n.vy *= 0.94;
n.x += n.vx; n.y += n.vy;
}
draw();
requestAnimationFrame(tick);
}
function draw(){
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,W,H);
ctx.fillStyle="#0d1117"; ctx.fillRect(0,0,W,H);
const dp = devicePixelRatio;
ctx.setTransform(cam.k*dp,0,0,cam.k*dp, W/2+cam.x*dp, H/2+cam.y*dp);
const hi = selected || hover;
const near = new Set();
if (hi){
near.add(hi.id);
for (const e of edges){
if (e.s===hi.id) near.add(e.t);
if (e.t===hi.id) near.add(e.s);
}
}
for (const e of edges){
const a=byId[e.s], b=byId[e.t];
const on = !hi || (near.has(a.id)&&near.has(b.id));
ctx.strokeStyle = on ? "rgba(88,166,255,.45)" : "rgba(48,54,61,.35)";
ctx.lineWidth = on ? 1.2 : 0.6;
ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y); ctx.stroke();
}
for (const n of nodes){
const r = 3 + Math.min(9, Math.sqrt(n.degree));
const col = COLORS[n.kind] || "#8b949e";
const match = query && n.title.toLowerCase().includes(query);
ctx.beginPath();
ctx.arc(n.x, n.y, r, 0, Math.PI*2);
ctx.fillStyle = (!hi || near.has(n.id)) ? col : "#2a2f36";
ctx.globalAlpha = match ? 1 : (hi && !near.has(n.id) ? 0.35 : 0.95);
ctx.fill();
ctx.globalAlpha = 1;
if (match){
ctx.strokeStyle="#fff"; ctx.lineWidth=2; ctx.stroke();
}
const show = n.degree > 20 || (hi && near.has(n.id)) || match;
if (show && cam.k > 0.55){
ctx.fillStyle = match ? "#fff" : "#c9d1d9";
ctx.font = (r+8)+"px -apple-system,Segoe UI,sans-serif";
ctx.textAlign="center";
ctx.fillText(n.title.slice(0,28), n.x, n.y - r - 5);
}
}
}
function locate(e){
const dp = devicePixelRatio;
return {x:(e.clientX*dp - W/2 - cam.x*dp)/(cam.k*dp),
y:(e.clientY*dp - H/2 - cam.y*dp)/(cam.k*dp)};
}
c.addEventListener("mousemove", e=>{
const p = locate(e);
hover = nodes.find(n=>Math.hypot(n.x-p.x, n.y-p.y) < 10/cam.k*2) || null;
c.style.cursor = hover ? "pointer" : "default";
});
let drag=null;
c.addEventListener("mousedown", e=>{ drag={x:e.clientX,y:e.clientY,cx:cam.x,cy:cam.y}; });
addEventListener("mouseup", ()=>{ drag=null; });
addEventListener("mousemove", e=>{
if (!drag) return;
cam.x = drag.cx + (e.clientX - drag.x);
cam.y = drag.cy + (e.clientY - drag.y);
});
c.addEventListener("wheel", e=>{
e.preventDefault();
cam.k *= e.deltaY < 0 ? 1.1 : 0.9;
cam.k = Math.max(0.25, Math.min(2.5, cam.k));
}, {passive:false});
c.addEventListener("click", e=>{
const p = locate(e);
const n = nodes.find(n=>Math.hypot(n.x-p.x, n.y-p.y) < 12/cam.k*2);
selected = n || null;
const info = document.getElementById("info");
if (!n){ info.style.display="none"; return; }
const rels = edges.filter(x=>x.s===n.id||x.t===n.id).slice(0,20).map(x=>{
const other = byId[x.s===n.id ? x.t : x.s];
return `<li>${x.r}: <b>${other?other.title:""}</b></li>`;
}).join("");
info.innerHTML = `<b>${n.title}</b><br><span style="color:#8b949e">${n.kind} · связей ${n.degree}</span>
<ul>${rels}</ul>`;
info.style.display="block";
});
document.getElementById("search").addEventListener("input", e=>{
query = e.target.value.trim().toLowerCase();
});
</script>
</body>
</html>
+111
View File
@@ -0,0 +1,111 @@
"""Недельный дайджест медиатеки: что есть, что нового, что посмотреть."""
import json
import os
import sys
import urllib.parse
import urllib.request
from collections import Counter
from datetime import datetime
import psycopg2
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
DSN = os.environ.get(
"CORE_DSN",
"dbname=hub_core user=hub_core password=hub_core host=192.168.1.151 client_encoding=utf8")
MATRIX_HS = os.environ.get("MATRIX_HS", "https://matrix.buryans.ru")
TOKEN = os.environ.get("NOTIFY_TOKEN", "")
ROOM = os.environ.get("NOTIFY_ROOM", "")
def send(text):
if not (TOKEN and ROOM):
print("нет настроек Matrix")
return False
txn = int(datetime.now().timestamp() * 1000)
rid = urllib.parse.quote(ROOM, safe="")
body = json.dumps({"msgtype": "m.text", "body": text,
"format": "org.matrix.custom.html",
"formatted_body": text.replace("\n", "<br>")}).encode()
req = urllib.request.Request(
f"{MATRIX_HS}/_matrix/client/v3/rooms/{rid}/send/m.room.message/{txn}",
data=body, method="PUT",
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=15):
return True
except Exception as e:
print("не отправилось:", str(e)[:100])
return False
def get(path, params=None):
url = CORE + path
if params:
url += "?" + urllib.parse.urlencode(params)
try:
with urllib.request.urlopen(url, timeout=15) as r:
return json.loads(r.read() or b"{}"), None
except Exception as e:
return None, str(e)[:100]
def main():
con = psycopg2.connect(DSN, connect_timeout=10)
cur = con.cursor()
cur.execute("select count(*) from entities where kind = 'фильм'")
films = cur.fetchone()[0]
cur.execute("select count(*) from entities where kind = 'книга'")
books = cur.fetchone()[0]
cur.execute("select count(*) from entity_links")
links = cur.fetchone()[0]
cur.execute("""select relation, count(*) from entity_links
group by relation order by 2 desc limit 6""")
rels = cur.fetchall()
cur.execute("""select title from entities where kind = 'кандидат'
order by updated_at desc limit 5""")
candidates = [r[0] for r in cur.fetchall()]
cur.execute("""select b.title, f.title 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 = 'экранизация' limit 5""")
cross = cur.fetchall()
con.close()
lines = ["🎬 **Медиатека: неделя в графе**", ""]
lines.append(f"Фильмов: {films} · книг: {books} · связей: {links}")
lines.append("")
lines.append("Связи: " + ", ".join(f"{r} {n}" for r, n in rels))
lines.append("")
if cross:
lines.append("Книга ↔ фильм:")
for b, f in cross:
lines.append(f"• {b} ↔ {f}")
lines.append("")
if candidates:
lines.append("Посмотреть (кандидаты):")
for c in candidates[:5]:
lines.append(f"• {c}")
text = "\n".join(lines)
print(text)
send(text)
data = {"key": "digest", "payload": {"markdown": text}, "tags": ["медиа", "дайджест"]}
try:
req = urllib.request.Request(f"{CORE}/data/media_digest",
data=json.dumps(data, ensure_ascii=False).encode(),
method="POST",
headers={"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=15).read()
except Exception as e:
print("не сохранил:", str(e)[:80])
return 0
if __name__ == "__main__":
sys.exit(main())