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.
This commit is contained in:
1 parent
02af4bde09
commit
54a7b36aae
12 files changed
+105
-4
No files matched your search
@@ -134,6 +134,8 @@
|
||||
скрытия серии/тега остаётся доступным, пока не использован или не закрыт.
|
||||
- Сравнение пресетов в интерфейсе: `GET /api/compare`, ссылка «сравнить пресеты»
|
||||
с общими/уникальными играми, Jaccard и переходом в карточку.
|
||||
- Профили вкуса `solo`/`coop`: фильтрация кандидатов и веса тегов по контексту
|
||||
(соло или с друзьями); селектор в UI, `--taste` в CLI, `taste_profile` в API.
|
||||
- Сортировка таблицы по жанру и избранному; опции в селекторе сортировки.
|
||||
- Демо-скриншоты текущего UI в README.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
+1
-1
@@ -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`).
|
||||
@@ -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`.
|
||||
|
||||
+3
-1
@@ -158,7 +158,9 @@ python web/server.py --port 9000
|
||||
новые добавляются, существующие обновляются, встроенные имена пропускаются;
|
||||
- фильтры: только неигранное, учитывать `tribute`, учитывать `nostalgia`,
|
||||
минимальный процент отзывов, доступное время (30 минут / вечер / выходные),
|
||||
время суток (утро/день/вечер/ночь);
|
||||
время суток (утро/день/вечер/ночь), профиль вкуса (весь / соло / с друзьями);
|
||||
- профиль вкуса фильтрует игры по контексту (`Singleplayer` без коопа или
|
||||
кооп/мультиплеер) и считает веса тегов только по этому контексту;
|
||||
- результаты: оценка совпадения, обложка, совпавшие теги, описание и 2–3 причины
|
||||
(«Теги: …», «Жанры: …», «Ещё не запускали», «Похоже на игры, отмеченные „в точку“»);
|
||||
- выдача перемешивается с штрафом за игры одной серии и сильно пересекающиеся теги;
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
+40
-2
@@ -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))
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -295,6 +295,13 @@ try {
|
||||
<option value="night">ночь</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="range">вкус
|
||||
<select id="optTaste" aria-label="Профиль вкуса">
|
||||
<option value="">весь</option>
|
||||
<option value="solo">соло</option>
|
||||
<option value="coop">с друзьями</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<button id="recommendBtn" class="primary">Подобрать</button>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user