feat: initial SteamBase 1.0.0
This commit is contained in:
commit
d1aee28115
37 files changed
+6518
No files matched your search
+300
@@ -0,0 +1,300 @@
|
||||
"""Mood parsing and scoring shared by the CLI and the web UI."""
|
||||
|
||||
import json
|
||||
import math
|
||||
|
||||
TAG_KEYWORDS = {
|
||||
"рпг": ["RPG"], "ролев": ["RPG"], "rpg": ["RPG"],
|
||||
"приключ": ["Adventure"], "adventure": ["Adventure"],
|
||||
"прокач": ["Character Customization", "RPG"], "character": ["Character Customization"],
|
||||
"групп": ["Party-Based RPG"], "парти": ["Party-Based RPG"], "отряд": ["Party-Based RPG"],
|
||||
"party": ["Party-Based RPG"],
|
||||
"исследов": ["Exploration"], "explor": ["Exploration"],
|
||||
"подземел": ["Dungeon Crawler"], "dungeon": ["Dungeon Crawler"],
|
||||
"сюжет": ["Story Rich"], "истор": ["Story Rich"], "story": ["Story Rich"], "narrative": ["Narrative"],
|
||||
"пошаг": ["Turn-Based Combat"], "turn": ["Turn-Based Combat"],
|
||||
"тактик": ["Tactical"], "tactical": ["Tactical"],
|
||||
"открыт": ["Open World"], "open world": ["Open World"],
|
||||
"крафт": ["Crafting"], "craft": ["Crafting"],
|
||||
"выжив": ["Survival"], "surviv": ["Survival"],
|
||||
"колони": ["Colony Sim"], "colony": ["Colony Sim"],
|
||||
"баз": ["Base Building"], "base": ["Base Building"],
|
||||
"менедж": ["Management"], "управл": ["Management"], "management": ["Management"],
|
||||
"строит": ["Building", "Base Building"], "building": ["Building"],
|
||||
"рогалик": ["Roguelike"], "rogue": ["Roguelike"],
|
||||
"лут": ["Loot"], "loot": ["Loot"],
|
||||
"фэнтези": ["Fantasy"], "фентези": ["Fantasy"], "fantasy": ["Fantasy"],
|
||||
"тёмн": ["Dark Fantasy", "Dark"], "dark": ["Dark Fantasy", "Dark"],
|
||||
"кооп": ["Co-op"], "coop": ["Co-op"], "co-op": ["Co-op"],
|
||||
"хоррор": ["Horror", "Survival Horror"], "horror": ["Horror"],
|
||||
"атмосфер": ["Atmospheric"], "atmospher": ["Atmospheric"],
|
||||
"пиксел": ["Pixel Graphics"], "pixel": ["Pixel Graphics"],
|
||||
"ммо": ["MMORPG", "Massively Multiplayer"],
|
||||
"город": ["City Builder"], "city": ["City Builder"],
|
||||
"песочниц": ["Sandbox"], "sandbox": ["Sandbox"],
|
||||
"стелс": ["Stealth"], "stealth": ["Stealth"],
|
||||
"логик": ["Puzzle"], "puzzle": ["Puzzle"],
|
||||
"гонк": ["Racing"], "racing": ["Racing"],
|
||||
"космос": ["Space"], "space": ["Space"],
|
||||
"фантаст": ["Sci-fi"], "sci-fi": ["Sci-fi"],
|
||||
"уют": ["Cozy", "Relaxing"], "cozy": ["Cozy"], "relax": ["Relaxing"],
|
||||
"коротк": ["Short"], "short": ["Short"],
|
||||
"детектив": ["Detective", "Mystery"], "mystery": ["Mystery"],
|
||||
"квест": ["Adventure"], "вестерн": ["Western"], "western": ["Western"],
|
||||
"спокойн": ["Relaxing"], "casual": ["Casual"],
|
||||
"ферм": ["Farming Sim"], "farming": ["Farming Sim"],
|
||||
}
|
||||
|
||||
GENRE_KEYWORDS = {
|
||||
"экшен": "Action", "action": "Action",
|
||||
"стратег": "Strategy", "strategy": "Strategy",
|
||||
"рпг": "RPG", "ролев": "RPG",
|
||||
"симулятор": "Simulation", "simulation": "Simulation",
|
||||
"приключ": "Adventure", "adventure": "Adventure",
|
||||
"инди": "Indie", "indie": "Indie",
|
||||
"казуал": "Casual", "casual": "Casual",
|
||||
"ммо": "Massively Multiplayer",
|
||||
}
|
||||
|
||||
|
||||
def mood_from_text(text):
|
||||
text = (text or "").lower()
|
||||
tags = {}
|
||||
for stem, names in TAG_KEYWORDS.items():
|
||||
if stem in text:
|
||||
for name in names:
|
||||
tags[name] = tags.get(name, 0.0) + 1.0
|
||||
for stem, genre in GENRE_KEYWORDS.items():
|
||||
if stem in text:
|
||||
tags.setdefault(genre, 1.0)
|
||||
genres = sorted({g for g in GENRE_KEYWORDS.values() if g in tags})
|
||||
if "RPG" in tags and "Adventure" not in genres:
|
||||
genres.append("Adventure")
|
||||
for name in list(tags):
|
||||
if name == "Party-Based RPG":
|
||||
tags[name] = max(tags[name], 1.3)
|
||||
if name == "Dungeon Crawler":
|
||||
tags[name] = max(tags[name], 1.2)
|
||||
return {"description": text.strip(), "genres": genres, "tags": tags}
|
||||
|
||||
|
||||
def load_mood(con, preset=None, text=None):
|
||||
if preset:
|
||||
row = con.execute("SELECT * FROM moods WHERE name = ?", (preset,)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(preset)
|
||||
return {
|
||||
"preset": preset,
|
||||
"description": row["description"],
|
||||
"genres": json.loads(row["genres"]),
|
||||
"tags": json.loads(row["tags"]),
|
||||
}
|
||||
if text:
|
||||
return mood_from_text(text)
|
||||
raise ValueError("empty mood")
|
||||
|
||||
|
||||
def recommend(con, mood, allowed_statuses=None, unplayed_only=False,
|
||||
min_review=65, allow_unknown=False, limit=20):
|
||||
allowed = set(allowed_statuses or {"backlog", "playing", "played"})
|
||||
if not allowed:
|
||||
allowed = {"backlog", "playing", "played"}
|
||||
|
||||
tag_names = {r["tag_id"]: r["name"] for r in con.execute("SELECT tag_id, name FROM tag_names")}
|
||||
name_to_ids = {}
|
||||
for tid, name in tag_names.items():
|
||||
name_to_ids.setdefault(name, []).append(tid)
|
||||
|
||||
rows = con.execute("""
|
||||
SELECT g.appid, g.name, g.metacritic, g.review_pct, g.release_date,
|
||||
COALESCE(p.minutes, 0) AS minutes, p.last_played,
|
||||
COALESCE(i.installed, 0) AS installed,
|
||||
COALESCE(pe.status, 'backlog') AS status, pe.rating, pe.favorite, pe.notes
|
||||
FROM games g
|
||||
JOIN game_playtime p ON p.appid = g.appid
|
||||
LEFT JOIN game_install i ON i.appid = g.appid
|
||||
LEFT JOIN personal pe ON pe.appid = g.appid
|
||||
WHERE LOWER(g.type) = 'game'
|
||||
""").fetchall()
|
||||
rows = [r for r in rows if r["status"] in allowed]
|
||||
if unplayed_only:
|
||||
rows = [r for r in rows if r["minutes"] == 0]
|
||||
if min_review:
|
||||
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]
|
||||
|
||||
ids = [r["appid"] for r in rows]
|
||||
if not ids:
|
||||
return mood, []
|
||||
|
||||
placeholders = ",".join("?" * len(ids))
|
||||
game_tags = {i: set() for i in ids}
|
||||
for r in con.execute(f"SELECT appid, tag_id FROM game_tags WHERE appid IN ({placeholders})", ids):
|
||||
game_tags[r["appid"]].add(r["tag_id"])
|
||||
game_genres = {i: set() for i in ids}
|
||||
for r in con.execute(f"SELECT appid, genre FROM game_genres WHERE appid IN ({placeholders})", ids):
|
||||
game_genres[r["appid"]].add(r["genre"])
|
||||
|
||||
total = len(ids)
|
||||
df = {}
|
||||
for tags in game_tags.values():
|
||||
for t in tags:
|
||||
df[t] = df.get(t, 0) + 1
|
||||
idf = {t: math.log(1 + total / c) for t, c in df.items()}
|
||||
|
||||
mood_tags = {k: float(v) for k, v in mood["tags"].items()}
|
||||
denom = 0.0
|
||||
for name, weight in mood_tags.items():
|
||||
vals = [idf.get(tid, 0.0) for tid in name_to_ids.get(name, [])]
|
||||
denom += weight * (max(vals) if vals else 0.0)
|
||||
mood_genres = set(mood["genres"])
|
||||
|
||||
def quality(r):
|
||||
rev = r["review_pct"] / 100 if r["review_pct"] is not None else 0.7
|
||||
mc = r["metacritic"] / 100 if r["metacritic"] is not None else 0.65
|
||||
return 0.8 * rev + 0.2 * mc
|
||||
|
||||
results = []
|
||||
for r in rows:
|
||||
tags = game_tags.get(r["appid"], set())
|
||||
matched, raw = [], 0.0
|
||||
for name, weight in mood_tags.items():
|
||||
hit = [tid for tid in name_to_ids.get(name, []) if tid in tags]
|
||||
if hit:
|
||||
raw += weight * max(idf.get(t, 0.0) for t in hit)
|
||||
matched.append(name)
|
||||
tag_norm = raw / denom if denom else 0.0
|
||||
hit_genres = mood_genres & game_genres.get(r["appid"], set())
|
||||
genre_norm = len(hit_genres) / len(mood_genres) if mood_genres else 0.0
|
||||
score = 100 * (0.55 * tag_norm + 0.25 * genre_norm + 0.20 * quality(r))
|
||||
score += 8 if r["minutes"] == 0 else -2 * math.log1p(r["minutes"] / 60)
|
||||
score += 2 if r["installed"] else 0
|
||||
score += 3 if r["status"] == "backlog" else 0
|
||||
score += 4 if r["status"] == "playing" else 0
|
||||
results.append({
|
||||
"appid": r["appid"],
|
||||
"name": r["name"],
|
||||
"score": round(score, 1),
|
||||
"matched": matched[:6],
|
||||
"genres": sorted(hit_genres) or sorted(game_genres.get(r["appid"], []))[:3],
|
||||
"review": r["review_pct"],
|
||||
"metacritic": r["metacritic"],
|
||||
"hours": round(r["minutes"] / 60, 1),
|
||||
"installed": bool(r["installed"]),
|
||||
"status": r["status"],
|
||||
"rating": r["rating"],
|
||||
"favorite": bool(r["favorite"]),
|
||||
"notes": r["notes"],
|
||||
"release": r["release_date"],
|
||||
})
|
||||
results.sort(key=lambda g: -g["score"])
|
||||
return mood, results[:limit]
|
||||
|
||||
|
||||
def similar_games(con, appid, limit=6):
|
||||
"""Games from the library with similar tags and genres."""
|
||||
base = con.execute("SELECT appid, name FROM games WHERE appid = ? AND LOWER(type) = 'game'",
|
||||
(appid,)).fetchone()
|
||||
if not base:
|
||||
return []
|
||||
|
||||
rows = con.execute("""
|
||||
SELECT g.appid, g.name, g.review_pct, g.metacritic, g.release_date,
|
||||
COALESCE(p.minutes, 0) AS minutes,
|
||||
COALESCE(i.installed, 0) AS installed,
|
||||
COALESCE(pe.status, 'backlog') AS status
|
||||
FROM games g
|
||||
JOIN game_playtime p ON p.appid = g.appid
|
||||
LEFT JOIN game_install i ON i.appid = g.appid
|
||||
LEFT JOIN personal pe ON pe.appid = g.appid
|
||||
WHERE LOWER(g.type) = 'game'
|
||||
""").fetchall()
|
||||
if not rows:
|
||||
return []
|
||||
by_id = {r["appid"]: r for r in rows}
|
||||
if appid not in by_id:
|
||||
return []
|
||||
ids = list(by_id)
|
||||
|
||||
ph = ",".join("?" * len(ids))
|
||||
tag_map = {i: set() for i in ids}
|
||||
for r in con.execute(f"SELECT appid, tag_id FROM game_tags WHERE appid IN ({ph})", ids):
|
||||
tag_map[r["appid"]].add(r["tag_id"])
|
||||
genre_map = {i: set() for i in ids}
|
||||
for r in con.execute(f"SELECT appid, genre FROM game_genres WHERE appid IN ({ph})", ids):
|
||||
genre_map[r["appid"]].add(r["genre"])
|
||||
|
||||
target_tags = tag_map.get(appid, set())
|
||||
if not target_tags:
|
||||
return []
|
||||
|
||||
df = {}
|
||||
for tags in tag_map.values():
|
||||
for t in tags:
|
||||
df[t] = df.get(t, 0) + 1
|
||||
total = len(ids)
|
||||
idf = {t: math.log(1 + total / c) for t, c in df.items()}
|
||||
|
||||
target_weight = sum(idf.get(t, 0.0) for t in target_tags)
|
||||
if not target_weight:
|
||||
return []
|
||||
target_genres = genre_map.get(appid, set())
|
||||
|
||||
def quality(r):
|
||||
rev = r["review_pct"] / 100 if r["review_pct"] is not None else 0.7
|
||||
mc = r["metacritic"] / 100 if r["metacritic"] is not None else 0.65
|
||||
return 0.8 * rev + 0.2 * mc
|
||||
|
||||
scored = []
|
||||
for other_id in ids:
|
||||
if other_id == appid or by_id[other_id]["status"] == "ignore":
|
||||
continue
|
||||
tags = tag_map.get(other_id, set())
|
||||
common = target_tags & tags
|
||||
if len(common) < 2:
|
||||
continue
|
||||
common_weight = sum(idf.get(t, 0.0) for t in common)
|
||||
other_weight = sum(idf.get(t, 0.0) for t in tags)
|
||||
if not other_weight:
|
||||
continue
|
||||
tag_sim = common_weight / math.sqrt(target_weight * other_weight)
|
||||
genres = genre_map.get(other_id, set())
|
||||
union = target_genres | genres
|
||||
genre_sim = len(target_genres & genres) / len(union) if union else 0.0
|
||||
score = 0.72 * tag_sim + 0.20 * genre_sim + 0.08 * quality(by_id[other_id])
|
||||
if score <= 0:
|
||||
continue
|
||||
r = by_id[other_id]
|
||||
release = r["release_date"] or ""
|
||||
year = int(release[:4]) if len(release) >= 4 and release[:4].isdigit() else None
|
||||
scored.append({
|
||||
"appid": other_id,
|
||||
"name": r["name"],
|
||||
"score": round(score, 3),
|
||||
"review": r["review_pct"],
|
||||
"metacritic": r["metacritic"],
|
||||
"release": r["release_date"],
|
||||
"year": year,
|
||||
"genres": sorted(genres)[:3],
|
||||
"matched": [],
|
||||
"hours": round((r["minutes"] or 0) / 60, 1),
|
||||
"installed": bool(r["installed"]),
|
||||
"status": r["status"],
|
||||
})
|
||||
|
||||
scored.sort(key=lambda g: -g["score"])
|
||||
# resolve tag names in one query for the finalists
|
||||
top = scored[:limit]
|
||||
if top:
|
||||
wanted = set()
|
||||
for g in top:
|
||||
wanted.update(target_tags & tag_map.get(g["appid"], set()))
|
||||
if wanted:
|
||||
ph2 = ",".join("?" * len(wanted))
|
||||
names = {r["tag_id"]: r["name"] for r in con.execute(
|
||||
f"SELECT tag_id, name FROM tag_names WHERE tag_id IN ({ph2})", list(wanted))}
|
||||
for g in top:
|
||||
common = target_tags & tag_map.get(g["appid"], set())
|
||||
g["matched"] = [names[t] for t in common if t in names][:5]
|
||||
return top
|
||||
Reference in new issue
Block a user