From 54a7b36aae94d3e4c1a4b2f264e04742fb1679fb Mon Sep 17 00:00:00 2001 From: strsv Date: Sat, 7 Nov 2026 00:53:18 +0300 Subject: [PATCH] feat: add solo and co-op taste profiles Filter recommendation candidates and taste weights by play context, with taste_profile in the API, --taste in the CLI and a selector in the UI. --- CHANGELOG.md | 2 ++ docs/HANDOFF.md | 3 +++ docs/ROADMAP.md | 2 +- docs/api.md | 5 +++++ docs/manual.md | 4 +++- tests/test_api.py | 8 ++++++++ tests/test_reco.py | 27 +++++++++++++++++++++++++++ tools/reco.py | 42 ++++++++++++++++++++++++++++++++++++++++-- tools/recommend.py | 3 +++ web/server.py | 5 +++++ web/static/app.js | 1 + web/static/index.html | 7 +++++++ 12 files changed, 105 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f999f7f..ba6dcd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -134,6 +134,8 @@ скрытия серии/тега остаётся доступным, пока не использован или не закрыт. - Сравнение пресетов в интерфейсе: `GET /api/compare`, ссылка «сравнить пресеты» с общими/уникальными играми, Jaccard и переходом в карточку. +- Профили вкуса `solo`/`coop`: фильтрация кандидатов и веса тегов по контексту + (соло или с друзьями); селектор в UI, `--taste` в CLI, `taste_profile` в API. - Сортировка таблицы по жанру и избранному; опции в селекторе сортировки. - Демо-скриншоты текущего UI в README. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 8b386c3..0930643 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -60,6 +60,8 @@ (миграция v5; осталось 43 игры без даты в Store). - Экспорт отфильтрованной библиотеки: `GET /api/export?format=csv|json` и кнопка «экспорт». - Профиль вкуса: веса тегов из часов, избранного и оценок; причина «Похоже на ваш вкус». +- Профили вкуса `solo`/`coop`: фильтрация по контексту и веса только по нему; + селектор в UI, `--taste` в CLI, `taste_profile` в API. - Скрытие по серии/тегу: `POST /api/personal/hide-scope`, подтверждение и undo; панель «отменить скрытие» остаётся после закрытия уведомления. - Сравнение пресетов: `tools/compare_presets.py` (общие/уникальные игры, Jaccard, `--json`) @@ -292,6 +294,7 @@ Invoke-RestMethod http://127.0.0.1:8765/api/meta 49. Импорт/экспорт профилей настроений (JSON, API и UI). 50. Постоянная панель undo для скрытия серии/тега. 51. Сравнение пресетов в UI (`GET /api/compare`). +52. Профили вкуса `solo`/`coop` (UI, CLI, API). Дальше — ручной screen reader, Steam API, новые версии appinfo. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index dbe7aeb..34643ab 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -292,7 +292,7 @@ 4. Добавить импорт истории из других лаунчеров. 5. [x] Undo для скрытия серии/тега после закрытия уведомления (панель «отменить скрытие»). 6. [x] Сравнение пресетов в UI (`GET /api/compare`). -7. Добавить несколько профилей вкуса (соло/с друзьями). +7. [x] Несколько профилей вкуса (соло/с друзьями). 8. Добавить тепловую карту активности по времени. 9. [x] Импорт/экспорт профилей настроений (JSON, API и UI). 10. [x] Кэш HLTB-запросов (`hltb_cache`, TTL, `--clear-cache`). diff --git a/docs/api.md b/docs/api.md index 6fc677b..cd92f0c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -303,10 +303,15 @@ DELETE → `{"deleted": true}`. "allow_unknown": false, "session": null, "time_of_day": null, + "taste_profile": null, "limit": 36 } ``` +`taste_profile`: `solo` (игры с `Singleplayer` без кооп-тегов), `coop` (кооп/мультиплеер) +или `null`. Профиль фильтрует кандидатов и считает веса вкуса только по играм +соответствующего контекста; неизвестное значение → 400. + `session`: `short` (30 минут), `evening` (вечер), `weekend` (выходные) или `null`. Это эвристика по тегам (Short/Casual/Roguelike, Story Rich/Atmospheric, Open World/RPG), которая повышает вес подходящих игр и добавляет причину в `reasons`. diff --git a/docs/manual.md b/docs/manual.md index 8f3c53a..154c215 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -158,7 +158,9 @@ python web/server.py --port 9000 новые добавляются, существующие обновляются, встроенные имена пропускаются; - фильтры: только неигранное, учитывать `tribute`, учитывать `nostalgia`, минимальный процент отзывов, доступное время (30 минут / вечер / выходные), - время суток (утро/день/вечер/ночь); + время суток (утро/день/вечер/ночь), профиль вкуса (весь / соло / с друзьями); +- профиль вкуса фильтрует игры по контексту (`Singleplayer` без коопа или + кооп/мультиплеер) и считает веса тегов только по этому контексту; - результаты: оценка совпадения, обложка, совпавшие теги, описание и 2–3 причины («Теги: …», «Жанры: …», «Ещё не запускали», «Похоже на игры, отмеченные „в точку“»); - выдача перемешивается с штрафом за игры одной серии и сильно пересекающиеся теги; diff --git a/tests/test_api.py b/tests/test_api.py index f0785d6..f72d5e8 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -487,6 +487,14 @@ class ApiTests(unittest.TestCase): finally: con.close() + def test_recommend_taste_profile(self): + data = self.post("/api/recommend", { + "preset": "dark-fantasy", "limit": 5, "taste_profile": "solo"}) + self.assertIsInstance(data["results"], list) + self.assertEqual(self.post("/api/recommend", { + "preset": "dark-fantasy", "taste_profile": "nope"}, expect=400)["error"], + "unknown taste profile") + def test_compare_presets(self): data = self.get("/api/compare?a=dark-fantasy&b=story-heavy&limit=5") self.assertEqual(data["a"], "dark-fantasy") diff --git a/tests/test_reco.py b/tests/test_reco.py index 83b89be..02e116b 100644 --- a/tests/test_reco.py +++ b/tests/test_reco.py @@ -118,6 +118,33 @@ class MoodTests(RecoFixture): reco.load_mood(self.con) +class TasteProfileTests(RecoFixture): + def _add_context_tags(self): + self.con.executemany( + "INSERT INTO tag_names (tag_id, name) VALUES (?,?)", + [(10, "Singleplayer"), (11, "Co-op"), (12, "Online Co-Op")]) + self.con.executemany( + "INSERT INTO game_tags (appid, tag_id) VALUES (?,?)", + [(1, 10), (2, 10), (3, 11), (4, 12)]) + self.con.commit() + + def test_profile_appids(self): + self._add_context_tags() + self.assertEqual(reco.taste_profile_appids(self.con, "solo"), {1, 2}) + self.assertEqual(reco.taste_profile_appids(self.con, "coop"), {3, 4}) + + def test_profiles_filter_candidates(self): + self._add_context_tags() + _, solo = reco.recommend(self.con, self.mood(), taste_profile="solo", limit=10) + self.assertEqual(set(self.names(solo)), {"Alpha", "Beta"}) + _, coop = reco.recommend(self.con, self.mood(), taste_profile="coop", limit=10) + self.assertEqual(set(self.names(coop)), {"Gamma", "Delta"}) + + def test_unknown_profile(self): + with self.assertRaises(ValueError): + reco.recommend(self.con, self.mood(), taste_profile="party") + + class RecommendTests(RecoFixture): def test_default_excludes_unknown_ignored_and_non_games(self): _, results = reco.recommend(self.con, self.mood(), limit=10) diff --git a/tools/reco.py b/tools/reco.py index 9dad847..3ae9f81 100644 --- a/tools/reco.py +++ b/tools/reco.py @@ -73,6 +73,37 @@ TIME_TAGS = { "Atmospheric", "Relaxing"}, } +TASTE_PROFILES = { + "solo": { + "label": "соло", + "include": {"Singleplayer"}, + "exclude": {"Co-op", "Online Co-Op", "Local Co-Op", "Multiplayer", + "Local Multiplayer", "MMORPG", "Massively Multiplayer", "PvP"}, + }, + "coop": { + "label": "с друзьями", + "include": {"Co-op", "Online Co-Op", "Local Co-Op", "Multiplayer", + "Local Multiplayer", "MMORPG", "Massively Multiplayer"}, + "exclude": set(), + }, +} + + +def taste_profile_appids(con, profile): + """Appids matching a play-context taste profile (solo/co-op).""" + spec = TASTE_PROFILES[profile] + tags = {} + for row in con.execute(""" + SELECT gt.appid, tn.name + FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id + """): + tags.setdefault(row["appid"], set()).add(row["name"]) + return { + appid for appid, names in tags.items() + if spec["include"] & names and not (spec["exclude"] & names) + } + + TIME_REASONS = { "morning": "Хорошо для утра", "day": "Подходит для дня", @@ -194,10 +225,13 @@ def load_mood(con, preset=None, text=None): def recommend(con, mood, allowed_statuses=None, unplayed_only=False, min_review=65, allow_unknown=False, limit=20, feedback_key=None, - session=None, time_of_day=None): + session=None, time_of_day=None, taste_profile=None): allowed = set(allowed_statuses or {"backlog", "playing", "played"}) if not allowed: allowed = {"backlog", "playing", "played"} + if taste_profile and taste_profile not in TASTE_PROFILES: + raise ValueError(f"unknown taste profile: {taste_profile}") + context_appids = taste_profile_appids(con, taste_profile) if taste_profile else None tag_names = {r["tag_id"]: r["name"] for r in con.execute("SELECT tag_id, name FROM tag_names")} name_to_ids = {} @@ -223,6 +257,8 @@ def recommend(con, mood, allowed_statuses=None, unplayed_only=False, rows = [r for r in rows if r["review_pct"] is None or r["review_pct"] >= min_review] if not allow_unknown: rows = [r for r in rows if r["review_pct"] is not None or r["metacritic"] is not None] + if context_appids is not None: + rows = [r for r in rows if r["appid"] in context_appids] feedback = {} liked_ids = set() @@ -266,7 +302,7 @@ def recommend(con, mood, allowed_statuses=None, unplayed_only=False, taste_weights = {} for row in con.execute(""" - SELECT gt.tag_id, COALESCE(p.minutes, 0) AS minutes, + SELECT gt.appid AS appid, gt.tag_id, COALESCE(p.minutes, 0) AS minutes, COALESCE(pe.favorite, 0) AS favorite, COALESCE(pe.rating, 0) AS rating FROM game_tags gt JOIN games g ON g.appid = gt.appid @@ -274,6 +310,8 @@ def recommend(con, mood, allowed_statuses=None, unplayed_only=False, LEFT JOIN personal pe ON pe.appid = gt.appid WHERE LOWER(g.type) = 'game' """): + if context_appids is not None and row["appid"] not in context_appids: + continue weight = 0.0 if row["minutes"] > 0: weight += min(2.0, math.log1p(row["minutes"] / 60)) diff --git a/tools/recommend.py b/tools/recommend.py index 0ed8386..2ab62ee 100644 --- a/tools/recommend.py +++ b/tools/recommend.py @@ -39,6 +39,8 @@ def main(): help="include games kept unplayed on purpose (status=nostalgia)") ap.add_argument("--allow-unknown", action="store_true", help="also consider games without any review/metacritic score") + ap.add_argument("--taste", choices=sorted(reco.TASTE_PROFILES), + help="play-context taste profile (solo/coop)") ap.add_argument("--json", action="store_true") args = ap.parse_args() @@ -70,6 +72,7 @@ def main(): mood, results = reco.recommend( con, mood, allowed_statuses=allowed, unplayed_only=args.unplayed_only, min_review=args.min_review, allow_unknown=args.allow_unknown, limit=args.limit, + taste_profile=args.taste, ) if args.json: diff --git a/web/server.py b/web/server.py index 93e8d19..5f57bfa 100644 --- a/web/server.py +++ b/web/server.py @@ -1479,6 +1479,10 @@ class Handler(BaseHTTPRequestHandler): time_of_day = body.get("time_of_day") if time_of_day not in {"morning", "day", "evening", "night"}: time_of_day = None + taste_profile = body.get("taste_profile") or None + if taste_profile not in reco.TASTE_PROFILES and taste_profile is not None: + self._error(400, "unknown taste profile") + return mood, results = reco.recommend( con, mood, allowed_statuses=allowed, @@ -1489,6 +1493,7 @@ class Handler(BaseHTTPRequestHandler): feedback_key=key, session=session, time_of_day=time_of_day, + taste_profile=taste_profile, ) ids = [g["appid"] for g in results] details = details_map(con, ids) diff --git a/web/static/app.js b/web/static/app.js index 806ceff..6528ebc 100644 --- a/web/static/app.js +++ b/web/static/app.js @@ -1142,6 +1142,7 @@ async function runRecommend(scroll = true) { min_review: Number($("#optReview").value), session: $("#optSession").value || null, time_of_day: $("#optTimeOfDay").value || null, + taste_profile: $("#optTaste").value || null, limit: 36, }; state.recommendContext = { preset: state.preset, mood: state.preset ? null : text }; diff --git a/web/static/index.html b/web/static/index.html index 5664fc8..63e3b10 100644 --- a/web/static/index.html +++ b/web/static/index.html @@ -295,6 +295,13 @@ try { +