From 4878f3b0dbfe22e026f945bcbf4eccb5aa22531d Mon Sep 17 00:00:00 2001 From: buryan-agent Date: Tue, 20 Oct 2026 12:48:03 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D1=81=D0=BE=D0=BD=D0=B0?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=80=D0=B5=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B4=D0=B0=D1=86=D0=B8=D0=B8=20=C2=AB=D0=94=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=B2=D0=B0=D1=81=C2=BB=20=D0=BF=D0=BE=20=D1=81=D0=B2?= =?UTF-8?q?=D0=BE=D0=B8=D0=BC=20=D0=BE=D1=86=D0=B5=D0=BD=D0=BA=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /for-me: берёт фильмы с оценкой 8+, собирает их темы и жанры, находит неоценённые карточки с теми же темами, добивает кандидатами TMDB. Команда «для меня», блок «Личное» на панели (хочу посмотреть, мои оценки, для вас). Проверено: оценки Dune 9 и Matrix Reloaded 8 → Рекомендованы Matrix Revolutions, Terminator 2, Salvation, The Matrix, Dune: Part Two, Blade Runner, Interstellar, Dark. Оценённое исключается. --- ops/bots/hub/bots.py | 21 +++++++++ ops/bots/hub/core_api.py | 4 ++ ops/media/PERSONAL.md | 28 ++++++++++++ ops/media/core.py | 92 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 145 insertions(+) diff --git a/ops/bots/hub/bots.py b/ops/bots/hub/bots.py index ae13f17..ad6c3f9 100644 --- a/ops/bots/hub/bots.py +++ b/ops/bots/hub/bots.py @@ -49,6 +49,26 @@ class MediaBot(Bot): + + + + def _forme_cmd(self, arg): + data, err = core_api.for_me() + if err: + return "Ядро не ответило: " + str(err) + liked = (data or {}).get("liked") or [] + items = (data or {}).get("items") or [] + if not items: + return ("Недостаточно данных. Поставьте оценки: !оценка Дюна 9 — " + "и я подберу похожее.") + lines = ["**Для вас**", ""] + if liked: + lines.append("_по мотивам: " + ", ".join(str(l.get("title")) for l in liked[:4]) + "_") + lines.append("") + for i in items[:10]: + tail = "" if i.get("kind") != "кандидат" else " · нет в медиатеке" + lines.append("• " + str(i.get("title")) + tail) + return chr(10).join(lines) def _want_cmd(self, arg): title = (arg or "").strip() @@ -520,6 +540,7 @@ class MediaBot(Bot): self.cmd("сезоны", "сезоны сериала: !сезоны Foundation")(lambda a: self._seasons_cmd(a)) self.cmd("хочу", "список желаемого: !хочу Дюна")(lambda a: self._want_cmd(a)) self.cmd("оценка", "поставить оценку: !оценка Дюна 9")(lambda a: self._rate_cmd(a)) + self.cmd("для меня", "персональные рекомендации по вашим оценкам")(lambda a: self._forme_cmd(a)) def _stats(self, jf): c = jf.counts() info, _ = jf.info() diff --git a/ops/bots/hub/core_api.py b/ops/bots/hub/core_api.py index adcb724..94f6e08 100644 --- a/ops/bots/hub/core_api.py +++ b/ops/bots/hub/core_api.py @@ -178,3 +178,7 @@ def rate(title, score): def rated(): return _get("/rated") + + +def for_me(limit=10): + return _get("/for-me", {"limit": limit}) diff --git a/ops/media/PERSONAL.md b/ops/media/PERSONAL.md index 0a780c0..1e952f6 100644 --- a/ops/media/PERSONAL.md +++ b/ops/media/PERSONAL.md @@ -48,3 +48,31 @@ Маршрут `/rate` перехватывал `/rated` (префиксное совпадение), поэтому `!оценка` без аргументов отвечала `400`. Исправлено: `/rate` срабатывает только на точный путь или с `?`. + +--- + +## Рекомендации «Для вас» + +`GET /for-me` собирает подборку из ваших высоких оценок (8+): + +1. берёт темы и жанры любимых фильмов и сериалов; +2. находит карточки с теми же темами, которых вы ещё не оценивали; +3. если не хватает — добивает кандидатами из рекомендаций TMDB. + +Команда `!для меня`, блок «Личное» на панели. + +``` +!для меня + +_по мотивам: Dune (2021), The Matrix Reloaded (2003)_ + +• The Matrix Revolutions (2003) +• Terminator 2: Judgment Day (1991) +• Terminator Salvation (2009) +• The Matrix (1999) +• Dune: Part Two (2024) +• Blade Runner (1982) … +``` + +Оценённое исключается: то, что уже посмотрели и оценили, повторно не +советуется. diff --git a/ops/media/core.py b/ops/media/core.py index 059086b..9604fb6 100644 --- a/ops/media/core.py +++ b/ops/media/core.py @@ -1013,6 +1013,69 @@ def do_rated(limit=30): return {"count": len(items), "average": avg, "items": items} + + +def do_for_me(limit=10): + """Рекомендации на основе высоких личных оценок.""" + con = db() + cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) + + # что я оценил высоко + cur.execute("""select e.id, e.title, r.score + from user_ratings r join entities e on e.id = r.entity_id + where r.score >= 8 order by r.score desc limit 10""") + liked = cur.fetchall() + if not liked: + con.close() + return {"liked": [], "items": [], "reason": "нет высоких оценок"} + + liked_ids = [r["id"] for r in liked] + rated_ids = set() + cur.execute("select entity_id from user_ratings") + for r in cur.fetchall(): + rated_ids.add(r["entity_id"]) + + # темы и жанры любимых + cur.execute("""select distinct l.to_id as node + from entity_links l + where l.from_id = any(%s) and l.relation in ('тема','жанр')""", (liked_ids,)) + nodes = [r["node"] for r in cur.fetchall()] + + items = [] + if nodes: + cur.execute(""" + select e.id, e.title, e.kind, count(*) as score + from entity_links l + join entities e on e.id = l.from_id + where l.to_id = any(%s) and l.relation in ('тема','жанр') + and e.kind in ('фильм','сериал') + group by e.id, e.title, e.kind + order by score desc, e.title + limit %s + """, (nodes, limit * 3)) + for r in cur.fetchall(): + if r["id"] not in rated_ids and r["id"] not in liked_ids: + items.append(dict(r)) + + # добить кандидатами, которых нет в медиатеке + if len(items) < limit: + cur.execute("""select e.id, e.title, count(l.id) as votes + from entities e + left join entity_links l on l.to_id = e.id and l.relation = 'рекомендует' + where e.kind = 'кандидат' + group by e.id, e.title + order by votes desc limit %s""", (limit,)) + for r in cur.fetchall(): + cand = {"id": r["id"], "title": r["title"], "kind": "кандидат", + "score": r["votes"]} + if not any(i["id"] == cand["id"] for i in items): + items.append(cand) + + con.close() + return {"liked": [dict(r) for r in liked], "items": items[:limit], + "reason": "по темам и жанрам любимых"} + + def render_panel(): """HTML-страница: состояние системы в одном месте.""" try: @@ -1065,6 +1128,12 @@ def render_panel(): growth = hist.get("growth") except Exception: growth = None + try: + personal = {"watch": do_watchlist().get("items") or [], + "rated": do_rated(5).get("items") or [], + "forme": do_for_me(5).get("items") or []} + except Exception: + personal = {"watch": [], "rated": [], "forme": []} try: cross = do_cross(limit=10) except Exception: @@ -1112,6 +1181,15 @@ 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'])}") + rows = [] + for w in personal.get("watch") or []: + rows.append(f"🎯{esc(w['title'])}хочу посмотреть") + for r in personal.get("rated") or []: + rows.append(f"⭐{esc(r['title'])}{r['score']}/10") + for f in personal.get("forme") or []: + rows.append(f"💡{esc(f['title'])}{esc(str(f.get('kind') or ''))}") + g_personal = "".join(rows) or "пока пусто: !хочу и !оценка" + g_timeline = "
нет данных
" if tl and tl.get("decades"): mx = max(d["n"] for d in tl["decades"]) or 1 @@ -1212,6 +1290,9 @@ th{{color:#7d8b99;font-weight:500}} {g_timeline}

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

{g_cross_rows}
+

Личное

+
хочу посмотреть · мои оценки · для вас
+{g_personal}

Доступы по сервисам

аудит по понедельникам, команда !users у бота Инфраструктура
{identity_text}
@@ -1451,6 +1532,17 @@ class Handler(BaseHTTPRequestHandler): return self._json(200, snapshot_graph()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) + if self.path.startswith("/for-me"): + import urllib.parse as _ufm + qs = _ufm.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} + try: + lim = int((qs.get("limit") or ["10"])[0]) + except ValueError: + lim = 10 + try: + return self._json(200, do_for_me(lim)) + except Exception as e: + return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/watchlist"): import urllib.parse as _uw qs = _uw.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}