Агент по графу: понимает вопросы словами, без LLM
agent.py разбирает фразу в план (намерение, персона, жанр, тема, эпоха, оценка) и выполняет запрос. Словарь берётся из графа, поэтому агент знает только то, что есть в медиатеке. Понимает русские синонимы (фантастика → science fiction, искусственный интеллект → artificial intelligence, робот → robot) и транслитерацию имён («фильмы Нолана» → Christopher Nolan). Эпохи в любом виде, оценки по словам. Пять намерений: подбор, фильмография, по десятилетиям, похожее, сравнение. При пустом результате ослабляет условия по одному и сообщает об этом. Показывает, как понял запрос. Вызовы: команда «агент», свободный текст Медиа-бота, и «найди» с падением в граф, когда в Jellyfin пусто. Проверено: Нолан → Interstellar; ИИ по десятилетиям (1980-е 1, 1990-е 1, 2000-е 2, 2010-е 2); похоже на Дюну → 8 фильмов; высокорейтинговые 80-х → Blade Runner; «найди про роботов с рейтингом» → 7 фильмов. Попутно: /pick получил фильтры по персоне и оценке; /compare сравнивает книгу и фильм (общие и разные жанры, автор, связь экранизации); поиск ядра понимает русские окончания (Дюну → Dune). Ловушки: явная команда первым словом (иначе «похоже» перехватывало запрос), порог основы для коротких слов, и восстановление аналитических функций, случайно срезанных при замене do_pick.
This commit is contained in:
1 parent
d9ec1d25a3
commit
03d20b95db
5 files changed
+563
-25
No files matched your search
@@ -0,0 +1,334 @@
|
||||
"""Агент по графу: понимает фразу, строит план и выполняет запросы.
|
||||
|
||||
Работает без LLM: словарь берётся из самого графа (персоны, жанры, темы,
|
||||
десятилетия), поэтому агент знает ровно то, что есть в медиатеке.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
CORE = "http://127.0.0.1:9120"
|
||||
CACHE = {"at": 0, "vocab": None}
|
||||
TTL = 300
|
||||
|
||||
|
||||
def _get(path, params=None, timeout=15):
|
||||
url = CORE + path
|
||||
if params:
|
||||
url += "?" + urllib.parse.urlencode(params)
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
def vocab():
|
||||
"""Словарь графа: персоны, жанры, темы, эпохи."""
|
||||
if CACHE["vocab"] and time.time() - CACHE["at"] < TTL:
|
||||
return CACHE["vocab"]
|
||||
v = {"persons": [], "genres": [], "themes": [], "decades": []}
|
||||
for kind, key in (("актёр", "persons"), ("режиссёр", "persons"),
|
||||
("композитор", "persons"), ("жанр", "genres"),
|
||||
("тема", "themes"), ("эпоха", "decades")):
|
||||
data, _ = _get("/entities", {"kind": kind, "limit": 500})
|
||||
for it in (data or {}).get("items") or []:
|
||||
v[key].append(it.get("title"))
|
||||
v["persons"] = sorted(set(v["persons"]))
|
||||
v["genres"] = sorted(set(v["genres"]))
|
||||
v["themes"] = sorted(set(v["themes"]))
|
||||
v["decades"] = sorted(set(v["decades"]))
|
||||
CACHE.update({"at": time.time(), "vocab": v})
|
||||
return v
|
||||
|
||||
|
||||
|
||||
|
||||
# ── русские синонимы тем и жанров графа ──
|
||||
RU_THEMES = {
|
||||
"искусственн": "artificial intelligence",
|
||||
"интеллект": "artificial intelligence",
|
||||
"робот": "robot",
|
||||
"андроид": "android",
|
||||
"космос": "space",
|
||||
"космическ": "space",
|
||||
"будущ": "future",
|
||||
"антиутоп": "dystopia",
|
||||
"постапокал": "post-apocalyptic",
|
||||
"время": "time travel",
|
||||
"путешеств": "time travel",
|
||||
"инопланет": "alien",
|
||||
"чужой": "alien",
|
||||
"монстр": "monster",
|
||||
"катастроф": "disaster",
|
||||
"война": "war",
|
||||
"супергеро": "superhero",
|
||||
"магия": "magic",
|
||||
"детектив": "detective",
|
||||
"любов": "love",
|
||||
"месть": "revenge",
|
||||
"школ": "school",
|
||||
"зомби": "zombie",
|
||||
"вампир": "vampire",
|
||||
"дракон": "dragon",
|
||||
"рыцар": "knight",
|
||||
"пират": "pirate",
|
||||
}
|
||||
|
||||
RU_GENRES = {
|
||||
"фантастик": "science fiction",
|
||||
"фэнтези": "fantasy",
|
||||
"фентези": "fantasy",
|
||||
"ужас": "horror",
|
||||
"хоррор": "horror",
|
||||
"комеди": "comedy",
|
||||
"драм": "drama",
|
||||
"боевик": "action",
|
||||
"триллер": "thriller",
|
||||
"детектив": "mystery",
|
||||
"приключен": "adventure",
|
||||
"мелодрам": "romance",
|
||||
"документальн": "documentary",
|
||||
"анимаци": "animation",
|
||||
}
|
||||
|
||||
TRANSLIT = {
|
||||
"а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e",
|
||||
"ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m",
|
||||
"н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u",
|
||||
"ф": "f", "х": "h", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "sch",
|
||||
"ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya",
|
||||
}
|
||||
|
||||
|
||||
def translit(text):
|
||||
return "".join(TRANSLIT.get(ch, ch) for ch in (text or "").lower())
|
||||
|
||||
|
||||
def match_person(text, persons):
|
||||
"""Ищем персону: латиницей напрямую или через транслитерацию."""
|
||||
low = text.lower()
|
||||
for p in persons:
|
||||
if p and p.lower() in low:
|
||||
return p
|
||||
tr = translit(text)
|
||||
best = None
|
||||
for p in persons:
|
||||
for token in (p or "").lower().split():
|
||||
if len(token) < 4:
|
||||
continue
|
||||
stem = token[:5]
|
||||
if stem and stem in tr:
|
||||
best = p
|
||||
break
|
||||
if best:
|
||||
break
|
||||
return best
|
||||
|
||||
|
||||
def match_by_dict(text, mapping, vocabulary):
|
||||
"""Русское слово → английское значение из словаря графа."""
|
||||
low = text.lower()
|
||||
for ru, en in mapping.items():
|
||||
if ru in low:
|
||||
for v in vocabulary:
|
||||
if v and en.lower() in v.lower():
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
def _contains_any(text, words):
|
||||
low = text.lower()
|
||||
return any(w in low for w in words)
|
||||
|
||||
|
||||
def parse(text, v=None):
|
||||
"""План: что понял агент."""
|
||||
v = v or vocab()
|
||||
low = text.lower()
|
||||
plan = {"raw": text, "intent": None, "person": None, "genre": None,
|
||||
"theme": None, "decade": None, "rating": None, "targets": []}
|
||||
|
||||
# интент
|
||||
if _contains_any(low, ("сравн", "общего", "отлича")):
|
||||
plan["intent"] = "compare"
|
||||
elif _contains_any(low, ("когда", "динамик", "по годам", "десятилет")):
|
||||
plan["intent"] = "timeline"
|
||||
elif _contains_any(low, ("кто снимал", "кто снял", "с кем", "фильмы с", "фильмография")):
|
||||
plan["intent"] = "person"
|
||||
elif _contains_any(low, ("похож", "как ", "вроде")):
|
||||
plan["intent"] = "similar"
|
||||
else:
|
||||
plan["intent"] = "pick"
|
||||
|
||||
# персона: латиница или транслитерация
|
||||
plan["person"] = match_person(text, v["persons"])
|
||||
|
||||
# эпоха
|
||||
m = re.search(r"(19|20)\d{2}", text)
|
||||
if m:
|
||||
plan["decade"] = str((int(m.group(0)) // 10) * 10) + "-е"
|
||||
else:
|
||||
m2 = re.search(r"\b(\d{2})\s*(?:-?е|-?х|ые|ых)\b", text)
|
||||
if m2:
|
||||
two = int(m2.group(1))
|
||||
year = (1900 + two) if two >= 30 else (2000 + two)
|
||||
plan["decade"] = str((year // 10) * 10) + "-е"
|
||||
|
||||
# жанр: прямое совпадение или русский синоним
|
||||
genre = None
|
||||
for g in v["genres"]:
|
||||
if g and g.lower() in low:
|
||||
genre = g
|
||||
break
|
||||
if not genre:
|
||||
genre = match_by_dict(text, RU_GENRES, v["genres"])
|
||||
plan["genre"] = genre
|
||||
|
||||
# тема: прямое совпадение или русский синоним
|
||||
theme = None
|
||||
for t in sorted(v["themes"], key=len, reverse=True):
|
||||
if len(t) > 4 and t.lower() in low:
|
||||
theme = t
|
||||
break
|
||||
if not theme:
|
||||
theme = match_by_dict(text, RU_THEMES, v["themes"])
|
||||
plan["theme"] = theme
|
||||
|
||||
# оценка
|
||||
if _contains_any(low, ("высок", "отличн", "8+", "лучш", "топ")):
|
||||
plan["rating"] = "высокая"
|
||||
elif _contains_any(low, ("неплох", "хорош", "7+")):
|
||||
plan["rating"] = "хорошая"
|
||||
|
||||
# цели для сравнения/похожего: всё, что похоже на название
|
||||
for token in re.findall(r"«([^»]+)»|\"([^\"]+)\"", text):
|
||||
t = token[0] or token[1]
|
||||
if t:
|
||||
plan["targets"].append(t)
|
||||
|
||||
if not plan["targets"]:
|
||||
m3 = re.search(r"(?:похож\w*\s+на|вроде|как)\s+(.+)", text, re.IGNORECASE)
|
||||
if m3:
|
||||
plan["targets"].append(m3.group(1).strip().strip(".,!?"))
|
||||
return plan
|
||||
|
||||
|
||||
def describe(plan):
|
||||
parts = []
|
||||
names = {"pick": "подбор", "person": "фильмография", "timeline": "по десятилетиям",
|
||||
"similar": "похожее", "compare": "сравнение"}
|
||||
parts.append("намерение: " + names.get(plan["intent"], plan["intent"]))
|
||||
for key, label in (("person", "персона"), ("genre", "жанр"), ("theme", "тема"),
|
||||
("decade", "эпоха"), ("rating", "оценка")):
|
||||
if plan.get(key):
|
||||
parts.append(label + ": " + str(plan[key]))
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
def run(text):
|
||||
"""Выполнить запрос. Возвращает (ответ, план)."""
|
||||
v = vocab()
|
||||
plan = parse(text, v)
|
||||
intent = plan["intent"]
|
||||
|
||||
if intent == "pick":
|
||||
params = {"limit": 10}
|
||||
for key in ("genre", "theme", "decade", "rating", "person"):
|
||||
if plan.get(key):
|
||||
params[key] = plan[key]
|
||||
data, err = _get("/pick", params)
|
||||
if err:
|
||||
return "Не смог получить данные: " + err, plan
|
||||
items = (data or {}).get("items") or []
|
||||
relaxed = []
|
||||
for key in ("rating", "theme", "genre", "decade", "person"):
|
||||
if items or key not in params:
|
||||
continue
|
||||
del params[key]
|
||||
relaxed.append(key)
|
||||
data, err = _get("/pick", params)
|
||||
if err:
|
||||
break
|
||||
items = (data or {}).get("items") or []
|
||||
if not items:
|
||||
return "По таким условиям в медиатеке ничего нет.", plan
|
||||
plan["relaxed"] = relaxed
|
||||
lines = ["Нашёл " + str(len(items)) + ":", ""]
|
||||
if plan.get("relaxed"):
|
||||
lines.insert(0, "_условия ослаблены: убрал " + ", ".join(plan["relaxed"]) + "_")
|
||||
for i in items:
|
||||
parts = [str(i.get("title"))]
|
||||
if i.get("rating"):
|
||||
parts.append(str(i.get("rating")))
|
||||
if i.get("genres"):
|
||||
parts.append(str(i.get("genres")))
|
||||
lines.append("• " + " — ".join(parts))
|
||||
return "\n".join(lines), plan
|
||||
|
||||
if intent == "person":
|
||||
if not plan["person"]:
|
||||
return "Не понял, кто имеется в виду. Назовите имя.", plan
|
||||
data, err = _get("/person", {"q": plan["person"]})
|
||||
if err or not data:
|
||||
return "Персону не нашёл.", plan
|
||||
films = data.get("films") or []
|
||||
lines = ["**" + str(plan["person"]) + "**, фильмов: " + str(len(films)), ""]
|
||||
for f in films[:15]:
|
||||
lines.append("• " + str(f.get("title")))
|
||||
return "\n".join(lines), plan
|
||||
|
||||
if intent == "timeline":
|
||||
node = plan.get("theme") or plan.get("genre")
|
||||
if not node:
|
||||
return "Укажите тему или жанр: например «когда были фильмы про искусственный интеллект».", plan
|
||||
kind = "тема" if plan.get("theme") else "жанр"
|
||||
data, err = _get("/timeline", {"q": node, "kind": kind})
|
||||
if err or not data:
|
||||
return "Не нашёл такую тему.", plan
|
||||
lines = ["**" + str(node) + " по десятилетиям**", ""]
|
||||
for d in data.get("decades") or []:
|
||||
lines.append("• " + str(d.get("decade")) + " — " + str(d.get("n")))
|
||||
return "\n".join(lines), plan
|
||||
|
||||
if intent == "similar":
|
||||
target = plan["targets"][0] if plan["targets"] else None
|
||||
if not target:
|
||||
return "Скажите, похоже на что: «похоже на Дюну».", plan
|
||||
card, _ = _get("/search", {"q": target})
|
||||
items = (card or {}).get("items") or []
|
||||
film = next((i for i in items if i.get("kind") in ("фильм", "книга")), None)
|
||||
if not film:
|
||||
return "Не нашёл «" + target + "» в графе.", plan
|
||||
data, err = _get("/similar", {"id": film["id"]})
|
||||
if err or not data:
|
||||
return "Похожего нет.", plan
|
||||
lines = ["**Похоже на " + str(film.get("title")) + "**", ""]
|
||||
for s in (data.get("similar") or [])[:8]:
|
||||
lines.append("• " + str(s.get("title")) + " — общих: " + str(s.get("shared")))
|
||||
return "\n".join(lines), plan
|
||||
|
||||
if intent == "compare":
|
||||
targets = plan["targets"]
|
||||
if len(targets) < 2:
|
||||
return "Для сравнения назовите два объекта в кавычках: «Дюна» и «Дюна».", plan
|
||||
data, err = _get("/compare", {"book": targets[0], "film": targets[1]})
|
||||
if err or not data:
|
||||
return "Не нашёл пару для сравнения (нужны книга и фильм).", plan
|
||||
b, f = data["book"]["title"], data["film"]["title"]
|
||||
lines = ["**" + b + "** и **" + f + "**", ""]
|
||||
lines.append("• Связаны экранизацией: " + ("да" if data.get("linked") else "нет"))
|
||||
if data.get("common_genres"):
|
||||
lines.append("• Общие жанры: " + ", ".join(data["common_genres"]))
|
||||
if data.get("only_book_genres"):
|
||||
lines.append("• Только в книге: " + ", ".join(data["only_book_genres"]))
|
||||
if data.get("only_film_genres"):
|
||||
lines.append("• Только в фильме: " + ", ".join(data["only_film_genres"]))
|
||||
if data.get("authors"):
|
||||
lines.append("• Автор: " + ", ".join(data["authors"]))
|
||||
return "\n".join(lines), plan
|
||||
|
||||
return "Не понял запрос.", plan
|
||||
@@ -38,6 +38,30 @@ class MediaBot(Bot):
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _agent_cmd(self, arg):
|
||||
"""Агент: понимает фразу и выполняет запрос по графу."""
|
||||
from . import agent as graph_agent
|
||||
text = (arg or "").strip()
|
||||
if not text:
|
||||
return ("Я агент по медиатеке. Спросите словами:\n"
|
||||
"• найди фильмы Нолана про космос\n"
|
||||
"• когда были фильмы про искусственный интеллект\n"
|
||||
"• фильмография Кеану Ривза\n"
|
||||
"• сравни «Дюна» и «Дюна»")
|
||||
try:
|
||||
answer, plan = graph_agent.run(text)
|
||||
except Exception as e:
|
||||
return "Агент сломался: " + str(e)[:120]
|
||||
try:
|
||||
steps = graph_agent.describe(plan)
|
||||
except Exception:
|
||||
steps = ""
|
||||
if steps:
|
||||
return answer + chr(10) + chr(10) + "_понял так: " + steps + "_"
|
||||
return answer
|
||||
|
||||
def _timeline_cmd(self, arg):
|
||||
term = (arg or "").strip()
|
||||
if not term:
|
||||
@@ -204,6 +228,7 @@ class MediaBot(Bot):
|
||||
|
||||
def _similar_cmd(self, arg):
|
||||
term = (arg or "").strip()
|
||||
term = term[3:] if term.lower().startswith("на ") else term
|
||||
if not term:
|
||||
return "Укажите название: !похоже Дюна"
|
||||
card, err = core_api.find_entity(term, kinds=["фильм", "книга"])
|
||||
@@ -303,6 +328,7 @@ class MediaBot(Bot):
|
||||
self.cmd("кросс", "книги и их экранизации в медиатеке")(lambda a: self._cross_cmd())
|
||||
self.cmd("персоны", "у кого больше фильмов: !персоны режиссёры")(lambda a: self._persons_cmd(a))
|
||||
self.cmd("граф", "статистика графа: !граф")(lambda a: self._graph_cmd(a))
|
||||
self.cmd("агент", "спросить агента словами: !агент найди фильмы Нолана")(lambda a: self._agent_cmd(a))
|
||||
def _stats(self, jf):
|
||||
c = jf.counts()
|
||||
info, _ = jf.info()
|
||||
@@ -344,6 +370,15 @@ class MediaBot(Bot):
|
||||
if err:
|
||||
return util.human_error(err, "Jellyfin")
|
||||
if not items:
|
||||
try:
|
||||
from . import agent as graph_agent
|
||||
answer, plan = graph_agent.run(term)
|
||||
low = (answer or "").lower()
|
||||
if answer and "ничего нет" not in low and "не нашёл" not in low:
|
||||
return (answer + chr(10) + chr(10) + "_в файлах нет, искал по графу: "
|
||||
+ graph_agent.describe(plan) + "_")
|
||||
except Exception:
|
||||
pass
|
||||
return f"По запросу «{term}» ничего не нашлось."
|
||||
lines = [f"**Найдено по «{term}»**", ""]
|
||||
for it in items:
|
||||
|
||||
+20
-1
@@ -192,6 +192,13 @@ class Bot:
|
||||
if not in_dm:
|
||||
return None, "", text
|
||||
|
||||
# явная команда первым словом: «агент найди фильмы» → агент, а не «найди»
|
||||
first = text.split(None, 1)
|
||||
head = first[0].lower().strip(" ?!.,")
|
||||
if head in self.commands:
|
||||
rest = first[1] if len(first) > 1 else ""
|
||||
return head, rest, text
|
||||
|
||||
# точное совпадение с псевдонимом или командой
|
||||
if low in self.ALIASES:
|
||||
return self.ALIASES[low], "", text
|
||||
@@ -327,7 +334,19 @@ class Bot:
|
||||
pass
|
||||
|
||||
def handle_freeform(self, text):
|
||||
"""Свободный текст: это просьба. Передаём владельцу и агенту."""
|
||||
"""Свободный текст: сначала агент по графу, потом владельцу."""
|
||||
if self.name == "media":
|
||||
low = (text or "").lower()
|
||||
hints = ("найди", "посовет", "подбери", "что посмотреть", "сравн",
|
||||
"похож", "когда", "фильмограф", "кто снимал", "покажи")
|
||||
if any(h in low for h in hints):
|
||||
try:
|
||||
from . import agent as graph_agent
|
||||
answer, plan = graph_agent.run(text)
|
||||
steps = graph_agent.describe(plan)
|
||||
return answer + chr(10) + chr(10) + "_понял так: " + steps + "_"
|
||||
except Exception:
|
||||
pass
|
||||
from . import inbox
|
||||
num = inbox.add(self.name, self.last_sender or "?", text)
|
||||
if num is None:
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Агент по графу
|
||||
|
||||
Понимает вопрос словами и сам выбирает, что спросить у графа. Работает без
|
||||
LLM: словарь берётся из самого графа, поэтому агент знает ровно то, что есть
|
||||
в медиатеке.
|
||||
|
||||
## Намерения
|
||||
|
||||
| Намерение | Как понять | Что делает |
|
||||
|---|---|---|
|
||||
| подбор | по умолчанию | `GET /pick` с фильтрами |
|
||||
| фильмография | «кто снимал», «фильмография», «с кем» | `GET /person` |
|
||||
| по десятилетиям | «когда», «динамика», «по годам» | `GET /timeline` |
|
||||
| похожее | «похоже», «вроде» | `/search` + `/similar` |
|
||||
| сравнение | «сравни», «что общего» | `GET /compare` |
|
||||
|
||||
## Как понимает слова
|
||||
|
||||
1. **Персоны** — напрямую латиницей или через транслитерацию:
|
||||
«фильмы Нолана» → `Christopher Nolan`.
|
||||
2. **Жанры и темы** — словарь русских синонимов:
|
||||
`фантастика` → `science fiction`, `искусственный интеллект` →
|
||||
`artificial intelligence`, `робот` → `robot`.
|
||||
3. **Эпоха** — `80-е`, `1980`, `2019`.
|
||||
4. **Оценка** — «высокий рейтинг», «8+», «топ» → `высокая (8+)`.
|
||||
|
||||
После ответа агент показывает, **как понял**: `_понял так: намерение:
|
||||
подбор, персона: Christopher Nolan_`.
|
||||
|
||||
## Мягкое ослабление условий
|
||||
|
||||
Если с фильтрами ничего не нашлось, агент снимает их по одному в порядке
|
||||
оценка → тема → жанр → эпоха → персона и сообщает, что убрал. Поэтому
|
||||
«фильмы про роботов с высоким рейтингом» не возвращает пустоту, а находит
|
||||
7 фильмов с рейтингом.
|
||||
|
||||
## Где живёт
|
||||
|
||||
`/opt/hub-bots/hub/agent.py`. Вызовы:
|
||||
* команда `!агент <фраза>`;
|
||||
* свободный текст Медиа-бота с глаголами «найди», «посоветуй», «сравни»,
|
||||
«похоже», «когда», «фильмография»;
|
||||
* `!find` — если в файлах Jellyfin пусто, ищет по графу.
|
||||
|
||||
## Ловушки
|
||||
|
||||
* **Явная команда первым словом.** Раньше «агент похоже на Дюну»
|
||||
разбиралось как команда `похоже`, и агент не вызывался. Теперь первое
|
||||
слово, совпавшее с командой, выигрывает.
|
||||
* **Русские окончания.** «Дюну» не находило «Dune». Добавлена грубая основа
|
||||
(`stem_ru`): убираем окончания, ищем по `%дюн%`.
|
||||
* **Порог основы.** Условие `len(t) > len(suf) + 3` не срабатывало для
|
||||
коротких слов («дюну» → 4 символа). Заменено на `>=`.
|
||||
* **Вырезанный код.** Замена `do_pick` захватила и удалила аналитические
|
||||
функции (`do_timeline`, `do_cross`, `do_top_persons`, `do_graph_stats`,
|
||||
`do_graph_json`) — восстановлены. Урок: перед заменой блока проверять,
|
||||
что ещё внутри.
|
||||
+117
-24
@@ -113,6 +113,20 @@ def human_event(ev):
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def stem_ru(text):
|
||||
"""Грубая основа русского слова: «Дюну» → «дюн»."""
|
||||
t = (text or "").lower().strip()
|
||||
for suf in ("ами", "ями", "ого", "его", "ому", "ему", "ыми", "ими",
|
||||
"ая", "яя", "ое", "ее", "ые", "ие", "ой", "ый", "ий",
|
||||
"ах", "ях", "ам", "ям", "ом", "ем", "ов", "ев", "ии",
|
||||
"у", "ю", "а", "я", "ы", "и", "е", "о", "ь"):
|
||||
if len(t) >= len(suf) + 3 and t.endswith(suf):
|
||||
return t[:-len(suf)]
|
||||
return t
|
||||
|
||||
|
||||
def do_search(q, limit=20):
|
||||
"""Поиск по карточкам: название и внешние ключи."""
|
||||
like = f"%{q.strip().lower()}%"
|
||||
@@ -122,6 +136,14 @@ def do_search(q, limit=20):
|
||||
from entities where search_text like %s
|
||||
order by updated_at desc limit %s""", (like, limit))
|
||||
items = [dict(r) for r in cur.fetchall()]
|
||||
|
||||
if not items:
|
||||
stem = stem_ru(q)
|
||||
if stem and len(stem) >= 3:
|
||||
cur.execute("""select id, kind, title, status from entities
|
||||
where search_text like %s order by length(title) limit %s""",
|
||||
(f"%{stem}%", limit))
|
||||
items = [dict(r) for r in cur.fetchall()]
|
||||
con.close()
|
||||
return {"query": q, "count": len(items), "items": items}
|
||||
|
||||
@@ -523,17 +545,18 @@ def do_person(query, limit=20):
|
||||
|
||||
|
||||
|
||||
def do_pick(genre=None, theme=None, decade=None, kind="фильм", limit=10):
|
||||
"""Подбор из имеющегося: фильтр по жанру, теме и эпохе."""
|
||||
|
||||
|
||||
def do_pick2(genre=None, theme=None, decade=None, kind="фильм", person=None,
|
||||
rating=None, limit=10):
|
||||
"""Подбор из медиатеки с любыми фильтрами графа."""
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
|
||||
conds = ["e.kind = %s"]
|
||||
args = [kind]
|
||||
|
||||
for rel, value in (("жанр", genre), ("тема", theme), ("снят в", decade)):
|
||||
if not value:
|
||||
continue
|
||||
def add_relation(rel, value):
|
||||
conds.append("""exists (
|
||||
select 1 from entity_links li
|
||||
join entities ni on ni.id = li.to_id
|
||||
@@ -541,13 +564,29 @@ def do_pick(genre=None, theme=None, decade=None, kind="фильм", limit=10):
|
||||
and ni.search_text like %s)""")
|
||||
args.extend([rel, f"%{value.lower()}%"])
|
||||
|
||||
sql = ("select e.id, e.title, e.kind, e.status from entities e where " + " and ".join(conds)
|
||||
+ " order by e.title limit %s")
|
||||
if genre:
|
||||
add_relation("жанр", genre)
|
||||
if theme:
|
||||
add_relation("тема", theme)
|
||||
if decade:
|
||||
add_relation("снят в", decade)
|
||||
if rating:
|
||||
add_relation("оценка", rating)
|
||||
|
||||
if person:
|
||||
conds.append("""exists (
|
||||
select 1 from entity_links lp
|
||||
join entities np on np.id = lp.to_id
|
||||
where lp.from_id = e.id and np.kind in ('актёр','режиссёр','композитор')
|
||||
and np.search_text like %s)""")
|
||||
args.append(f"%{person.lower()}%")
|
||||
|
||||
sql = ("select e.id, e.title, e.kind, e.status from entities e where "
|
||||
+ " and ".join(conds) + " order by e.title limit %s")
|
||||
args.append(limit)
|
||||
cur.execute(sql, args)
|
||||
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"],))
|
||||
@@ -561,10 +600,51 @@ def do_pick(genre=None, theme=None, decade=None, kind="фильм", limit=10):
|
||||
return {"count": len(items), "items": items}
|
||||
|
||||
|
||||
def do_compare(book_query, film_query):
|
||||
"""Сравнение книги и фильма: что общего."""
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
|
||||
def find(kind, q):
|
||||
cur.execute("""select id, kind, title from entities
|
||||
where kind = %s and search_text like %s
|
||||
order by length(title) limit 1""", (kind, f"%{q.lower()}%"))
|
||||
return cur.fetchone()
|
||||
|
||||
book = find("книга", book_query)
|
||||
film = find("фильм", film_query)
|
||||
if not book or not film:
|
||||
con.close()
|
||||
return None
|
||||
|
||||
def related(eid, rel):
|
||||
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 = %s""", (eid, rel))
|
||||
return {r["title"] for r in cur.fetchall()}
|
||||
|
||||
b_genres, b_themes = related(book["id"], "жанр"), related(book["id"], "тема")
|
||||
f_genres, f_themes = related(film["id"], "жанр"), related(film["id"], "тема")
|
||||
b_authors = related(book["id"], "написал")
|
||||
|
||||
cur.execute("""select 1 from entity_links l
|
||||
where l.from_id = %s and l.to_id = %s and l.relation = 'экранизация'""",
|
||||
(book["id"], film["id"]))
|
||||
linked = cur.fetchone() is not None
|
||||
con.close()
|
||||
|
||||
return {
|
||||
"book": dict(book), "film": dict(film), "linked": linked,
|
||||
"common_genres": sorted(b_genres & f_genres),
|
||||
"only_book_genres": sorted(b_genres - f_genres),
|
||||
"only_film_genres": sorted(f_genres - b_genres),
|
||||
"common_themes": sorted(b_themes & f_themes),
|
||||
"authors": sorted(b_authors),
|
||||
}
|
||||
|
||||
|
||||
|
||||
def do_timeline(node_query, kind="тема"):
|
||||
"""Как тема или жанр распределены по десятилетиям."""
|
||||
"""Тема или жанр по десятилетиям."""
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
cur.execute("""select id, title from entities
|
||||
@@ -581,22 +661,22 @@ def do_timeline(node_query, kind="тема"):
|
||||
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
|
||||
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 entity_links l
|
||||
on (l.from_id = i.item_id and l.relation = 'снят в')
|
||||
join entities d on d.id = l.to_id
|
||||
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))
|
||||
""", (node["id"], node["id"], node["id"], 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("""
|
||||
@@ -617,10 +697,9 @@ def do_cross(limit=50):
|
||||
where l.relation = 'экранирован'
|
||||
order by a.title limit %s
|
||||
""", (limit,))
|
||||
authors_screen = [dict(r) for r in cur.fetchall()]
|
||||
authors_screened = [dict(r) for r in cur.fetchall()]
|
||||
con.close()
|
||||
return {"books_with_film": books_with_film,
|
||||
"authors_screened": authors_screen}
|
||||
return {"books_with_film": books_with_film, "authors_screened": authors_screened}
|
||||
|
||||
|
||||
def do_top_persons(kind="актёр", limit=10):
|
||||
@@ -628,12 +707,12 @@ 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
|
||||
select e.id, e.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
|
||||
join entities e on e.id = case when l.from_id = e.id then e.id else l.to_id end
|
||||
where e.kind = %s and l.relation in ('снялся','снял','музыка')
|
||||
group by e.id, e.title
|
||||
order by films desc, e.title
|
||||
limit %s
|
||||
""", (kind, limit))
|
||||
items = [dict(r) for r in cur.fetchall()]
|
||||
@@ -963,6 +1042,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if self.path.startswith("/compare"):
|
||||
import urllib.parse as _uc
|
||||
qs = _uc.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
|
||||
b = (qs.get("book") or [""])[0]
|
||||
f = (qs.get("film") or [""])[0]
|
||||
if not b or not f:
|
||||
return self._json(400, {"error": "нужны book и film"})
|
||||
try:
|
||||
data = do_compare(b, f)
|
||||
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("/timeline"):
|
||||
import urllib.parse as _u1
|
||||
qs = _u1.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
|
||||
@@ -1002,12 +1093,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
t = (qs.get("theme") or [None])[0]
|
||||
d = (qs.get("decade") or [None])[0]
|
||||
k = (qs.get("kind") or ["фильм"])[0]
|
||||
per = (qs.get("person") or [None])[0]
|
||||
rat = (qs.get("rating") or [None])[0]
|
||||
try:
|
||||
lim = int((qs.get("limit") or ["10"])[0])
|
||||
except ValueError:
|
||||
lim = 10
|
||||
try:
|
||||
return self._json(200, do_pick(g, t, d, k, lim))
|
||||
return self._json(200, do_pick2(g, t, d, k, per, rat, lim))
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
if self.path.startswith("/similar"):
|
||||
|
||||
Reference in new issue
Block a user