feat: initial SteamBase 1.0.0
This commit is contained in:
commit
d1aee28115
37 files changed
+6518
No files matched your search
@@ -0,0 +1,108 @@
|
||||
"""Warm the local cover cache.
|
||||
|
||||
The web server already caches covers on first request. This script can prefetch
|
||||
them in advance for games that have no art in the Steam client cache.
|
||||
|
||||
python tools/cache_covers.py --all
|
||||
python tools/cache_covers.py --limit 200
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
import steam_source
|
||||
|
||||
CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps"
|
||||
NAMES = ("library_600x900.jpg", "header.jpg")
|
||||
|
||||
|
||||
def has_any(paths):
|
||||
for directory, names in paths:
|
||||
if not directory:
|
||||
continue
|
||||
for name in names:
|
||||
if os.path.isfile(os.path.join(directory, name)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Prefetch game covers")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--limit", type=int)
|
||||
ap.add_argument("--all", action="store_true")
|
||||
ap.add_argument("--delay", type=float, default=0.1)
|
||||
args = ap.parse_args()
|
||||
|
||||
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
cache_dir = os.path.join(base, "cache", "covers")
|
||||
try:
|
||||
steam_root = steam_source.find_steam_root()
|
||||
lib_cache = os.path.join(steam_root, "appcache", "librarycache")
|
||||
except SystemExit:
|
||||
lib_cache = None
|
||||
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
rows = con.execute("""SELECT appid, name FROM games
|
||||
WHERE LOWER(type)='game' ORDER BY review_pct DESC""").fetchall()
|
||||
if not args.all and args.limit:
|
||||
rows = rows[: args.limit]
|
||||
print(f"Games: {len(rows)}")
|
||||
|
||||
downloaded = skipped = failed = 0
|
||||
for row in rows:
|
||||
appid = row["appid"]
|
||||
cached = os.path.join(cache_dir, str(appid))
|
||||
steam_art = os.path.join(lib_cache, str(appid)) if lib_cache else None
|
||||
if has_any([(cached, NAMES), (steam_art, steam_source_names())]):
|
||||
skipped += 1
|
||||
continue
|
||||
got = False
|
||||
for name in NAMES:
|
||||
url = f"{CDN}/{appid}/{name}"
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||
data = resp.read()
|
||||
if not data:
|
||||
continue
|
||||
os.makedirs(cached, exist_ok=True)
|
||||
path = os.path.join(cached, name)
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(data)
|
||||
os.replace(tmp, path)
|
||||
got = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
finally:
|
||||
time.sleep(args.delay)
|
||||
if got:
|
||||
downloaded += 1
|
||||
else:
|
||||
failed += 1
|
||||
|
||||
print(f"downloaded={downloaded} skipped={skipped} failed={failed}")
|
||||
print(f"cache: {cache_dir}")
|
||||
|
||||
|
||||
def steam_source_names():
|
||||
return ("library_600x900.jpg", "header.jpg", "library_hero.jpg", "logo.png")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DEFAULT_DB = os.path.join(BASE_DIR, "steam.db")
|
||||
SCHEMA_PATH = os.path.join(BASE_DIR, "tools", "schema.sql")
|
||||
|
||||
MOOD_PRESETS = {
|
||||
"adventure-rpg-party": {
|
||||
"description": "Приключение + RPG, прокачка героя/группы, исследование, подземелья",
|
||||
"genres": ["RPG", "Adventure"],
|
||||
"tags": {
|
||||
"RPG": 1.0,
|
||||
"Adventure": 1.0,
|
||||
"Party-Based RPG": 1.3,
|
||||
"Character Customization": 1.0,
|
||||
"Dungeon Crawler": 1.2,
|
||||
"Exploration": 1.0,
|
||||
"Story Rich": 0.8,
|
||||
"Turn-Based Combat": 0.7,
|
||||
"CRPG": 0.9,
|
||||
"Loot": 0.7,
|
||||
"Choices Matter": 0.6,
|
||||
"Fantasy": 0.5,
|
||||
"Open World": 0.4,
|
||||
},
|
||||
},
|
||||
"dungeon-crawler": {
|
||||
"description": "Подземелья, пошаговые бои, лут, рогалик",
|
||||
"genres": ["RPG", "Adventure"],
|
||||
"tags": {
|
||||
"Dungeon Crawler": 1.5,
|
||||
"Roguelike": 1.0,
|
||||
"Turn-Based Combat": 1.2,
|
||||
"Loot": 1.1,
|
||||
"CRPG": 0.8,
|
||||
"RPG": 1.0,
|
||||
"Party-Based RPG": 0.8,
|
||||
"Exploration": 0.7,
|
||||
},
|
||||
},
|
||||
"colony-management": {
|
||||
"description": "Колонии, базы, менеджмент, строительство",
|
||||
"genres": ["Simulation", "Strategy"],
|
||||
"tags": {
|
||||
"Colony Sim": 1.5,
|
||||
"Base Building": 1.2,
|
||||
"Management": 1.2,
|
||||
"Building": 1.0,
|
||||
"City Builder": 1.0,
|
||||
"Resource Management": 1.0,
|
||||
"Sandbox": 0.6,
|
||||
"Strategy": 0.7,
|
||||
"Simulation": 0.7,
|
||||
},
|
||||
},
|
||||
"survival-craft": {
|
||||
"description": "Выживание, крафт, открытый мир, кооп",
|
||||
"genres": ["Action", "Adventure", "Simulation"],
|
||||
"tags": {
|
||||
"Survival": 1.5,
|
||||
"Open World Survival Craft": 1.5,
|
||||
"Crafting": 1.2,
|
||||
"Base Building": 1.0,
|
||||
"Exploration": 0.8,
|
||||
"Open World": 0.7,
|
||||
"Co-op": 0.7,
|
||||
"Survival Horror": 0.4,
|
||||
},
|
||||
},
|
||||
"story-heavy": {
|
||||
"description": "Сюжет, выборы, атмосфера",
|
||||
"genres": ["Adventure", "RPG"],
|
||||
"tags": {
|
||||
"Story Rich": 1.5,
|
||||
"Narrative": 1.2,
|
||||
"Choices Matter": 1.1,
|
||||
"Adventure": 0.9,
|
||||
"Atmospheric": 0.8,
|
||||
"Exploration": 0.6,
|
||||
"RPG": 0.6,
|
||||
},
|
||||
},
|
||||
"dark-fantasy": {
|
||||
"description": "Тёмное фэнтези, сложность, атмосфера",
|
||||
"genres": ["RPG", "Adventure", "Action"],
|
||||
"tags": {
|
||||
"Dark Fantasy": 1.5,
|
||||
"Souls-like": 1.2,
|
||||
"Atmospheric": 1.0,
|
||||
"Lore-Rich": 0.9,
|
||||
"Difficult": 0.8,
|
||||
"Action RPG": 0.8,
|
||||
"RPG": 0.9,
|
||||
"Story Rich": 0.5,
|
||||
"Medieval": 0.5,
|
||||
},
|
||||
},
|
||||
"relaxing-evening": {
|
||||
"description": "Спокойный вечер: уютно и без спешки",
|
||||
"genres": ["Casual", "Simulation", "Adventure"],
|
||||
"tags": {
|
||||
"Relaxing": 1.5,
|
||||
"Cozy": 1.3,
|
||||
"Farming Sim": 1.2,
|
||||
"Life Sim": 0.9,
|
||||
"Casual": 1.0,
|
||||
"Atmospheric": 0.6,
|
||||
"Building": 0.5,
|
||||
"Cute": 0.5,
|
||||
},
|
||||
},
|
||||
"coop-friends": {
|
||||
"description": "Кооп с друзьями",
|
||||
"genres": ["Action", "Adventure", "RPG"],
|
||||
"tags": {
|
||||
"Co-op": 1.5,
|
||||
"Online Co-Op": 1.3,
|
||||
"Multiplayer": 1.0,
|
||||
"Co-op Campaign": 1.0,
|
||||
"PvE": 0.8,
|
||||
"Survival": 0.7,
|
||||
"Open World": 0.6,
|
||||
"Local Co-Op": 0.7,
|
||||
},
|
||||
},
|
||||
"sci-fi-exploration": {
|
||||
"description": "Космос, научная фантастика, исследование",
|
||||
"genres": ["Adventure", "Simulation", "Action"],
|
||||
"tags": {
|
||||
"Sci-fi": 1.4,
|
||||
"Space": 1.3,
|
||||
"Exploration": 1.2,
|
||||
"Open World": 0.8,
|
||||
"Survival": 0.7,
|
||||
"Atmospheric": 0.7,
|
||||
"Cyberpunk": 0.6,
|
||||
},
|
||||
},
|
||||
"tactical-turn-based": {
|
||||
"description": "Тактика, пошаговые бои, продуманные решения",
|
||||
"genres": ["Strategy", "RPG"],
|
||||
"tags": {
|
||||
"Turn-Based Tactics": 1.4,
|
||||
"Turn-Based Combat": 1.2,
|
||||
"Tactical": 1.2,
|
||||
"Turn-Based Strategy": 1.0,
|
||||
"Strategy": 0.9,
|
||||
"RPG": 0.6,
|
||||
"CRPG": 0.6,
|
||||
},
|
||||
},
|
||||
"horror-night": {
|
||||
"description": "Хоррор на ночь",
|
||||
"genres": ["Adventure", "Action"],
|
||||
"tags": {
|
||||
"Horror": 1.5,
|
||||
"Survival Horror": 1.3,
|
||||
"Psychological Horror": 0.9,
|
||||
"Atmospheric": 1.0,
|
||||
"Dark": 0.8,
|
||||
"Story Rich": 0.5,
|
||||
},
|
||||
},
|
||||
"city-builder": {
|
||||
"description": "Город, поселение, экономика, строительство",
|
||||
"genres": ["Simulation", "Strategy"],
|
||||
"tags": {
|
||||
"City Builder": 1.5,
|
||||
"Building": 1.2,
|
||||
"Management": 1.1,
|
||||
"Economy": 1.0,
|
||||
"Resource Management": 0.9,
|
||||
"Sandbox": 0.5,
|
||||
"Colony Sim": 0.6,
|
||||
},
|
||||
},
|
||||
"roguelike-run": {
|
||||
"description": "Рогалик на один забег",
|
||||
"genres": ["RPG", "Action", "Indie"],
|
||||
"tags": {
|
||||
"Roguelike": 1.4,
|
||||
"Roguelite": 1.3,
|
||||
"Action Roguelike": 0.9,
|
||||
"Replay Value": 0.9,
|
||||
"Dungeon Crawler": 0.7,
|
||||
"Loot": 0.6,
|
||||
},
|
||||
},
|
||||
"short-session": {
|
||||
"description": "Короткие сессии на вечер",
|
||||
"genres": ["Indie", "Casual", "Adventure"],
|
||||
"tags": {
|
||||
"Short": 1.5,
|
||||
"Casual": 1.2,
|
||||
"Relaxing": 0.8,
|
||||
"Puzzle": 0.8,
|
||||
"Atmospheric": 0.5,
|
||||
"Story Rich": 0.5,
|
||||
"Minimalist": 0.3,
|
||||
},
|
||||
},
|
||||
"mystery-detective": {
|
||||
"description": "Детектив, загадка, расследование",
|
||||
"genres": ["Adventure", "RPG"],
|
||||
"tags": {
|
||||
"Mystery": 1.5,
|
||||
"Detective": 1.4,
|
||||
"Story Rich": 1.0,
|
||||
"Point & Click": 0.8,
|
||||
"Visual Novel": 0.7,
|
||||
"Atmospheric": 0.6,
|
||||
"Puzzle": 0.5,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def connect(path=None):
|
||||
path = path or DEFAULT_DB
|
||||
con = sqlite3.connect(path, timeout=10)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA foreign_keys = ON")
|
||||
con.execute("PRAGMA busy_timeout = 8000")
|
||||
return con
|
||||
|
||||
|
||||
def _ensure_column(con, table, column, declaration):
|
||||
columns = {row[1] for row in con.execute(f"PRAGMA table_info({table})")}
|
||||
if column not in columns:
|
||||
con.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}")
|
||||
|
||||
|
||||
def init(con):
|
||||
with open(SCHEMA_PATH, encoding="utf-8") as f:
|
||||
con.executescript(f.read())
|
||||
_ensure_column(con, "game_details", "source_appid", "INTEGER")
|
||||
con.commit()
|
||||
|
||||
|
||||
def seed_moods(con):
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
for name, preset in MOOD_PRESETS.items():
|
||||
con.execute(
|
||||
"""INSERT INTO moods (name, description, genres, tags, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(name) DO UPDATE SET
|
||||
description = excluded.description,
|
||||
genres = excluded.genres,
|
||||
tags = excluded.tags,
|
||||
updated_at = excluded.updated_at""",
|
||||
(name, preset["description"], json.dumps(preset["genres"]),
|
||||
json.dumps(preset["tags"]), now),
|
||||
)
|
||||
con.commit()
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Cache short descriptions and metadata from the Steam Store API.
|
||||
|
||||
One request per app (the public endpoint does not accept batches), so the
|
||||
script is resumable and rate-limited.
|
||||
|
||||
Examples:
|
||||
python tools/fetch_details.py --limit 200
|
||||
python tools/fetch_details.py --all --delay 1.6
|
||||
python tools/fetch_details.py --stats
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
|
||||
API = "https://store.steampowered.com/api/appdetails"
|
||||
|
||||
|
||||
def _fetch_once(appid, lang, cc, timeout=30):
|
||||
params = urllib.parse.urlencode({"appids": appid, "l": lang, "cc": cc})
|
||||
req = urllib.request.Request(f"{API}?{params}", headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
payload = json.load(resp)
|
||||
entry = payload.get(str(appid)) or {}
|
||||
if not entry.get("success"):
|
||||
return None
|
||||
data = entry.get("data") or {}
|
||||
return {
|
||||
"short_description": data.get("short_description"),
|
||||
"about": data.get("about_the_game"),
|
||||
"header_image": data.get("header_image"),
|
||||
"developers": ", ".join(data.get("developers") or []),
|
||||
"publishers": ", ".join(data.get("publishers") or []),
|
||||
"release_date": (data.get("release_date") or {}).get("date"),
|
||||
"lang": lang,
|
||||
}
|
||||
|
||||
|
||||
def fetch_app_details_region(appid, lang, cc, timeout=30):
|
||||
"""Single attempt in one store region (used by the recovery tool)."""
|
||||
return _fetch_once(appid, lang, cc, timeout=timeout)
|
||||
|
||||
|
||||
def fetch_app_details(appid, lang="russian", timeout=30):
|
||||
"""Fetch store details, preferring the requested language.
|
||||
|
||||
Some games are region/age-gated in the Russian store and answer
|
||||
``success: false``; for those we retry in English before giving up.
|
||||
"""
|
||||
attempts = [(lang, "ru")]
|
||||
if lang != "english":
|
||||
attempts.append(("english", "us"))
|
||||
for attempt_lang, cc in attempts:
|
||||
details = _fetch_once(appid, attempt_lang, cc, timeout=timeout)
|
||||
if details and (details["short_description"] or details["about"]):
|
||||
return details
|
||||
return None
|
||||
|
||||
|
||||
def save_details(con, appid, details, status="ok", source_appid=None):
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
if details is not None:
|
||||
if details.get("short_description"):
|
||||
details["short_description"] = details["short_description"].replace("\ufeff", "").strip()
|
||||
if details.get("about"):
|
||||
details["about"] = details["about"].replace("\ufeff", "").strip()
|
||||
if details is None:
|
||||
con.execute(
|
||||
"""INSERT INTO game_details (appid, lang, fetched_at, status)
|
||||
VALUES (?, ?, ?, 'missing')
|
||||
ON CONFLICT(appid) DO UPDATE SET lang=excluded.lang,
|
||||
fetched_at=excluded.fetched_at, status='missing'""",
|
||||
(appid, "russian", now),
|
||||
)
|
||||
con.commit()
|
||||
return
|
||||
con.execute(
|
||||
"""INSERT INTO game_details
|
||||
(appid, short_description, about, header_image, developers, publishers,
|
||||
release_date, lang, fetched_at, status, source_appid)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(appid) DO UPDATE SET
|
||||
short_description=excluded.short_description,
|
||||
about=excluded.about,
|
||||
header_image=excluded.header_image,
|
||||
developers=excluded.developers,
|
||||
publishers=excluded.publishers,
|
||||
release_date=excluded.release_date,
|
||||
lang=excluded.lang,
|
||||
fetched_at=excluded.fetched_at,
|
||||
status=excluded.status,
|
||||
source_appid=excluded.source_appid""",
|
||||
(appid, details["short_description"], details["about"], details["header_image"],
|
||||
details["developers"], details["publishers"], details["release_date"],
|
||||
details["lang"], now, status, source_appid),
|
||||
)
|
||||
con.commit()
|
||||
|
||||
|
||||
def missing_appids(con, limit=None, unplayed_only=False, min_review=None):
|
||||
sql = """SELECT g.appid
|
||||
FROM games g
|
||||
LEFT JOIN game_details d ON d.appid = g.appid
|
||||
LEFT JOIN game_playtime p ON p.appid = g.appid
|
||||
WHERE LOWER(g.type) = 'game'
|
||||
AND (d.appid IS NULL OR d.status IS NULL)
|
||||
ORDER BY (COALESCE(p.minutes, 0) = 0) DESC,
|
||||
COALESCE(g.review_pct, 0) DESC,
|
||||
g.name"""
|
||||
rows = [r["appid"] for r in con.execute(sql)]
|
||||
if unplayed_only:
|
||||
rows = [a for a in rows if con.execute(
|
||||
"SELECT COALESCE(minutes, 0) FROM game_playtime WHERE appid = ?", (a,)).fetchone()[0] == 0]
|
||||
if min_review is not None:
|
||||
rows = [a for a in rows if (lambda r: r is None or r >= min_review)(
|
||||
con.execute("SELECT review_pct FROM games WHERE appid = ?", (a,)).fetchone()[0])]
|
||||
return rows[:limit] if limit else rows
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Cache Steam Store details")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--limit", type=int)
|
||||
ap.add_argument("--all", action="store_true")
|
||||
ap.add_argument("--stats", action="store_true")
|
||||
ap.add_argument("--retry-missing", action="store_true", help="retry games marked missing")
|
||||
ap.add_argument("--unplayed-only", action="store_true")
|
||||
ap.add_argument("--min-review", type=int)
|
||||
ap.add_argument("--delay", type=float, default=1.4, help="seconds between requests")
|
||||
ap.add_argument("--lang", default="russian")
|
||||
args = ap.parse_args()
|
||||
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
|
||||
if args.stats:
|
||||
total = con.execute("SELECT COUNT(*) FROM games WHERE LOWER(type)='game'").fetchone()[0]
|
||||
done = con.execute("""SELECT COUNT(*) FROM game_details d JOIN games g ON g.appid=d.appid
|
||||
WHERE LOWER(g.type)='game' AND d.status='ok'""").fetchone()[0]
|
||||
missing = con.execute("""SELECT COUNT(*) FROM game_details d JOIN games g ON g.appid=d.appid
|
||||
WHERE LOWER(g.type)='game' AND d.status='missing'""").fetchone()[0]
|
||||
print(f"games: {total} | cached: {done} | missing: {missing} | left: {total - done - missing}")
|
||||
return
|
||||
|
||||
if args.retry_missing:
|
||||
con.execute("DELETE FROM game_details WHERE status = 'missing'")
|
||||
con.commit()
|
||||
|
||||
limit = None if args.all else (args.limit or 100)
|
||||
ids = missing_appids(con, limit, args.unplayed_only, args.min_review)
|
||||
print(f"To fetch: {len(ids)}")
|
||||
ok = miss = err = 0
|
||||
consecutive_errors = 0
|
||||
for i, appid in enumerate(ids, 1):
|
||||
try:
|
||||
details = fetch_app_details(appid, lang=args.lang)
|
||||
save_details(con, appid, details)
|
||||
if details is None:
|
||||
miss += 1
|
||||
else:
|
||||
ok += 1
|
||||
consecutive_errors = 0
|
||||
except urllib.error.HTTPError as exc:
|
||||
err += 1
|
||||
consecutive_errors += 1
|
||||
if exc.code == 429:
|
||||
print(" rate limited, sleeping 60s")
|
||||
time.sleep(60)
|
||||
elif consecutive_errors >= 5:
|
||||
print(f" stopping after {consecutive_errors} consecutive HTTP errors ({exc.code})")
|
||||
break
|
||||
except Exception as exc:
|
||||
err += 1
|
||||
print(f" {appid}: {exc}")
|
||||
if i % 10 == 0 or i == len(ids):
|
||||
print(f" {i}/{len(ids)} ok={ok} missing={miss} errors={err}")
|
||||
time.sleep(args.delay)
|
||||
|
||||
print("Done.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Build/refresh steam.db from the local Steam client cache.
|
||||
|
||||
Usage:
|
||||
python tools/import_steam.py
|
||||
python tools/import_steam.py --refresh-tags
|
||||
python tools/import_steam.py --steam-root "D:\\Steam" --steamid 76561198000000000
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
import steam_source
|
||||
|
||||
TAG_URL = "https://store.steampowered.com/tagdata/populartags/english"
|
||||
|
||||
|
||||
def iso_from_unix(ts):
|
||||
if not ts:
|
||||
return None
|
||||
return datetime.fromtimestamp(int(ts), tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def fetch_tag_names():
|
||||
req = urllib.request.Request(TAG_URL, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = json.load(resp)
|
||||
return {int(t["tagid"]): t["name"] for t in data}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Import the local Steam library into SQLite")
|
||||
ap.add_argument("--steam-root")
|
||||
ap.add_argument("--steamid", help="17-digit SteamID64 (default: most recent login)")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--refresh-tags", action="store_true", help="re-download Steam tag names")
|
||||
ap.add_argument("--incremental", action="store_true",
|
||||
help="only add new apps; update install/playtime for existing")
|
||||
ap.add_argument("--no-network", action="store_true", help="never download tag names")
|
||||
args = ap.parse_args()
|
||||
|
||||
root = args.steam_root or steam_source.find_steam_root()
|
||||
users = steam_source.read_users(root)
|
||||
if args.steamid:
|
||||
steamid = args.steamid
|
||||
else:
|
||||
recent = [u for u in users if u["most_recent"]] or users
|
||||
if not recent:
|
||||
raise SystemExit("No Steam users found; pass --steamid")
|
||||
steamid = recent[0]["steamid"]
|
||||
|
||||
roots = steam_source.library_roots(root)
|
||||
lib_ids = steam_source.library_appids(root)
|
||||
if not lib_ids:
|
||||
raise SystemExit(f"Empty library cache under {root}\\appcache\\librarycache")
|
||||
|
||||
print(f"Steam: {root}")
|
||||
print(f"User: {steamid}")
|
||||
print(f"Libraries: {', '.join(roots)}")
|
||||
print(f"Apps in library cache: {len(lib_ids)}")
|
||||
|
||||
appinfo = steam_source.read_appinfo(root)
|
||||
playtime = steam_source.read_playtime(root, steamid)
|
||||
installed = steam_source.installed_apps(roots)
|
||||
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
db.seed_moods(con)
|
||||
|
||||
existing_tags = {r["tag_id"]: r["name"] for r in con.execute("SELECT tag_id, name FROM tag_names")}
|
||||
new_tags = {}
|
||||
if not args.no_network and (args.refresh_tags or len(existing_tags) < 50):
|
||||
try:
|
||||
new_tags = fetch_tag_names()
|
||||
print(f"Tag names downloaded: {len(new_tags)}")
|
||||
except Exception as exc:
|
||||
print(f"Tag download skipped: {exc}", file=sys.stderr)
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
def upsert_game(row):
|
||||
con.execute(
|
||||
"""INSERT INTO games (appid, name, type, release_date, metacritic, review_pct, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(appid) DO UPDATE SET
|
||||
name = excluded.name, type = excluded.type,
|
||||
release_date = excluded.release_date,
|
||||
metacritic = excluded.metacritic, review_pct = excluded.review_pct,
|
||||
updated_at = excluded.updated_at""",
|
||||
row,
|
||||
)
|
||||
|
||||
def write_playtime(appid, pt):
|
||||
if pt:
|
||||
con.execute(
|
||||
"""INSERT INTO game_playtime (appid, minutes, last_played) VALUES (?, ?, ?)
|
||||
ON CONFLICT(appid) DO UPDATE SET
|
||||
minutes = excluded.minutes, last_played = excluded.last_played""",
|
||||
(appid, pt["minutes"], iso_from_unix(pt["last_played"])),
|
||||
)
|
||||
else:
|
||||
con.execute("INSERT OR IGNORE INTO game_playtime (appid, minutes) VALUES (?, 0)", (appid,))
|
||||
|
||||
def write_install(appid, inst):
|
||||
if inst:
|
||||
con.execute(
|
||||
"""INSERT INTO game_install (appid, installed, size_bytes, library_path)
|
||||
VALUES (?, 1, ?, ?)
|
||||
ON CONFLICT(appid) DO UPDATE SET
|
||||
installed = 1, size_bytes = excluded.size_bytes,
|
||||
library_path = excluded.library_path""",
|
||||
(appid, inst["size_bytes"], inst["library_path"]),
|
||||
)
|
||||
else:
|
||||
con.execute("INSERT OR IGNORE INTO game_install (appid, installed) VALUES (?, 0)", (appid,))
|
||||
con.execute("UPDATE game_install SET installed = 0 WHERE appid = ?", (appid,))
|
||||
|
||||
existing_ids = {r["appid"] for r in con.execute("SELECT appid FROM games")}
|
||||
imported = new_count = updated_count = 0
|
||||
with con:
|
||||
if new_tags:
|
||||
con.executemany("INSERT OR REPLACE INTO tag_names (tag_id, name) VALUES (?, ?)",
|
||||
new_tags.items())
|
||||
|
||||
for appid in lib_ids:
|
||||
pt = playtime.get(appid)
|
||||
inst = installed.get(appid)
|
||||
is_new = appid not in existing_ids
|
||||
|
||||
if args.incremental and not is_new:
|
||||
write_playtime(appid, pt)
|
||||
write_install(appid, inst)
|
||||
updated_count += 1
|
||||
continue
|
||||
|
||||
info = appinfo.get(appid, {})
|
||||
name = info.get("name") or installed.get(appid, {}).get("name") or f"App {appid}"
|
||||
upsert_game((appid, name, info.get("type"), iso_from_unix(info.get("release")),
|
||||
info.get("metacritic"), info.get("review_pct"), now))
|
||||
|
||||
genre_ids = info.get("genres") or {}
|
||||
con.execute("DELETE FROM game_genres WHERE appid = ?", (appid,))
|
||||
con.executemany(
|
||||
"INSERT OR IGNORE INTO game_genres (appid, genre) VALUES (?, ?)",
|
||||
[(appid, steam_source.GENRES.get(v, f"Genre {v}")) for v in genre_ids.values()
|
||||
if isinstance(v, int) and v not in steam_source.SKIP_GENRE_IDS],
|
||||
)
|
||||
|
||||
tag_ids = info.get("tags") or {}
|
||||
con.execute("DELETE FROM game_tags WHERE appid = ?", (appid,))
|
||||
con.executemany(
|
||||
"INSERT OR IGNORE INTO game_tags (appid, tag_id) VALUES (?, ?)",
|
||||
[(appid, v) for v in tag_ids.values() if isinstance(v, int)],
|
||||
)
|
||||
|
||||
write_playtime(appid, pt)
|
||||
write_install(appid, inst)
|
||||
|
||||
default_status = "played" if pt and pt["minutes"] > 0 else "backlog"
|
||||
con.execute("INSERT OR IGNORE INTO personal (appid, status, updated_at) VALUES (?, ?, ?)",
|
||||
(appid, default_status, now))
|
||||
imported += 1
|
||||
if is_new:
|
||||
new_count += 1
|
||||
else:
|
||||
updated_count += 1
|
||||
|
||||
con.execute("""UPDATE personal SET status = 'played'
|
||||
WHERE status = 'backlog'
|
||||
AND appid IN (SELECT appid FROM game_playtime WHERE minutes > 0)""")
|
||||
|
||||
con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('imported_at', ?)", (now,))
|
||||
con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('steam_root', ?)", (root,))
|
||||
con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('steamid', ?)", (steamid,))
|
||||
|
||||
counts = {r["type"]: r["n"] for r in con.execute(
|
||||
"SELECT COALESCE(LOWER(type), 'unknown') AS type, COUNT(*) AS n FROM games GROUP BY 1")}
|
||||
con.close()
|
||||
|
||||
print(f"Processed: {new_count + updated_count} apps (new: {new_count}, existing: {updated_count}) -> {args.db}")
|
||||
print(f"By type: {counts}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Manual per-game data: status, rating, notes, arbitrary attributes.
|
||||
|
||||
Examples:
|
||||
python tools/personal.py set "Fallout: New Vegas" --status tribute --note "прошёл вне Steam, купил в знак уважения"
|
||||
python tools/personal.py set "Might & Magic VI" --status nostalgia --note "не запускать, чтобы не портить воспоминания"
|
||||
python tools/personal.py set 1086940 --status playing --rating 10 --favorite
|
||||
python tools/personal.py attr "Kenshi" mood_tags "sandbox,survival"
|
||||
python tools/personal.py list --status nostalgia
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
|
||||
STATUSES = ("backlog", "playing", "played", "tribute", "nostalgia", "ignore")
|
||||
|
||||
|
||||
def resolve(con, needle):
|
||||
if needle.isdigit():
|
||||
row = con.execute("SELECT appid, name FROM games WHERE appid = ?", (int(needle),)).fetchone()
|
||||
if row:
|
||||
return row
|
||||
row = con.execute("SELECT appid, name FROM games WHERE name = ? COLLATE NOCASE", (needle,)).fetchone()
|
||||
if row:
|
||||
return row
|
||||
rows = con.execute("SELECT appid, name FROM games WHERE name LIKE ? COLLATE NOCASE ORDER BY name",
|
||||
(f"%{needle}%",)).fetchall()
|
||||
if len(rows) == 1:
|
||||
return rows[0]
|
||||
if not rows:
|
||||
raise SystemExit(f"Game not found: {needle}")
|
||||
print("Ambiguous; use appid:")
|
||||
for r in rows[:20]:
|
||||
print(f" {r['appid']:>8} {r['name']}")
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Per-game personal data")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
p_set = sub.add_parser("set")
|
||||
p_set.add_argument("game")
|
||||
p_set.add_argument("--status", choices=STATUSES)
|
||||
p_set.add_argument("--rating", type=int, choices=range(1, 11))
|
||||
p_set.add_argument("--favorite", action="store_true")
|
||||
p_set.add_argument("--no-favorite", action="store_true")
|
||||
p_set.add_argument("--note")
|
||||
|
||||
p_list = sub.add_parser("list")
|
||||
p_list.add_argument("--status", choices=STATUSES)
|
||||
p_list.add_argument("--limit", type=int, default=200)
|
||||
|
||||
p_attr = sub.add_parser("attr")
|
||||
p_attr.add_argument("game")
|
||||
p_attr.add_argument("key")
|
||||
p_attr.add_argument("value")
|
||||
|
||||
p_attrs = sub.add_parser("attrs")
|
||||
p_attrs.add_argument("game")
|
||||
|
||||
p_unattr = sub.add_parser("unattr")
|
||||
p_unattr.add_argument("game")
|
||||
p_unattr.add_argument("key")
|
||||
|
||||
args = ap.parse_args()
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
if args.cmd == "set":
|
||||
g = resolve(con, args.game)
|
||||
con.execute("INSERT OR IGNORE INTO personal (appid, status, updated_at) VALUES (?, 'backlog', ?)",
|
||||
(g["appid"], now))
|
||||
shifts, vals = [], []
|
||||
if args.status:
|
||||
shifts.append("status = ?"); vals.append(args.status)
|
||||
if args.rating is not None:
|
||||
shifts.append("rating = ?"); vals.append(args.rating)
|
||||
if args.favorite:
|
||||
shifts.append("favorite = ?"); vals.append(1)
|
||||
if args.no_favorite:
|
||||
shifts.append("favorite = ?"); vals.append(0)
|
||||
if args.note is not None:
|
||||
shifts.append("notes = ?"); vals.append(args.note)
|
||||
if not shifts:
|
||||
raise SystemExit("Nothing to change")
|
||||
shifts.append("updated_at = ?"); vals.append(now)
|
||||
con.execute(f"UPDATE personal SET {', '.join(shifts)} WHERE appid = ?", (*vals, g["appid"]))
|
||||
con.commit()
|
||||
row = con.execute("SELECT * FROM personal WHERE appid = ?", (g["appid"],)).fetchone()
|
||||
print(f"{g['appid']} {g['name']}: status={row['status']} rating={row['rating']} "
|
||||
f"favorite={row['favorite']} notes={row['notes'] or ''}")
|
||||
|
||||
elif args.cmd == "list":
|
||||
sql = """SELECT g.appid, g.name, pe.status, pe.rating, pe.favorite, pe.notes
|
||||
FROM personal pe JOIN games g ON g.appid = pe.appid WHERE 1=1"""
|
||||
vals = []
|
||||
if args.status:
|
||||
sql += " AND pe.status = ?"; vals.append(args.status)
|
||||
sql += " ORDER BY g.name LIMIT ?"; vals.append(args.limit)
|
||||
for r in con.execute(sql, vals):
|
||||
flags = []
|
||||
if r["rating"]:
|
||||
flags.append(f"{r['rating']}/10")
|
||||
if r["favorite"]:
|
||||
flags.append("fav")
|
||||
print(f"{r['status']:10} {r['appid']:>8} {r['name']}"
|
||||
+ (f" [{', '.join(flags)}]" if flags else "")
|
||||
+ (f" -- {r['notes']}" if r["notes"] else ""))
|
||||
|
||||
elif args.cmd == "attr":
|
||||
g = resolve(con, args.game)
|
||||
con.execute("INSERT OR REPLACE INTO attributes (appid, key, value) VALUES (?, ?, ?)",
|
||||
(g["appid"], args.key, args.value))
|
||||
con.commit()
|
||||
print(f"{g['name']}: {args.key} = {args.value}")
|
||||
|
||||
elif args.cmd == "attrs":
|
||||
g = resolve(con, args.game)
|
||||
rows = con.execute("SELECT key, value FROM attributes WHERE appid = ? ORDER BY key", (g["appid"],))
|
||||
for r in rows:
|
||||
print(f"{r['key']} = {r['value']}")
|
||||
|
||||
elif args.cmd == "unattr":
|
||||
g = resolve(con, args.game)
|
||||
con.execute("DELETE FROM attributes WHERE appid = ? AND key = ?", (g["appid"], args.key))
|
||||
con.commit()
|
||||
print(f"deleted {args.key} for {g['name']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+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
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Mood-based recommendations from steam.db.
|
||||
|
||||
Examples:
|
||||
python tools/recommend.py --mood "рпг приключение прокачка группы исследование подземелья"
|
||||
python tools/recommend.py --preset adventure-rpg-party --unplayed-only
|
||||
python tools/recommend.py --list-presets
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
import reco
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Recommend games for a mood")
|
||||
ap.add_argument("--mood", help="free text, Russian or English")
|
||||
ap.add_argument("--preset", help="mood preset name")
|
||||
ap.add_argument("--list-presets", action="store_true")
|
||||
ap.add_argument("--limit", type=int, default=20)
|
||||
ap.add_argument("--min-review", type=int, default=65,
|
||||
help="skip games below this Steam review percentage (default 65)")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--unplayed-only", action="store_true", help="only games with 0 minutes")
|
||||
ap.add_argument("--include-tribute", action="store_true",
|
||||
help="include games you played outside Steam (status=tribute)")
|
||||
ap.add_argument("--include-nostalgia", action="store_true",
|
||||
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("--json", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
db.seed_moods(con)
|
||||
|
||||
if args.list_presets:
|
||||
for row in con.execute("SELECT name, description FROM moods ORDER BY name"):
|
||||
print(f"{row['name']:22} {row['description']}")
|
||||
return
|
||||
|
||||
try:
|
||||
mood = reco.load_mood(con, args.preset, args.mood)
|
||||
except KeyError as exc:
|
||||
raise SystemExit(f"Unknown preset: {exc.args[0]}")
|
||||
except ValueError:
|
||||
raise SystemExit('Pass --mood "..." or --preset NAME (see --list-presets)')
|
||||
|
||||
if not mood["tags"] and not mood["genres"]:
|
||||
raise SystemExit("Could not understand the mood; try different words")
|
||||
|
||||
allowed = {"backlog", "playing", "played"}
|
||||
if args.include_tribute:
|
||||
allowed.add("tribute")
|
||||
if args.include_nostalgia:
|
||||
allowed.add("nostalgia")
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps({"mood": mood, "results": results}, ensure_ascii=False, indent=2))
|
||||
return
|
||||
|
||||
print(f"Настроение: {mood['description']}")
|
||||
print(f"Теги: {', '.join(mood['tags'])}")
|
||||
if mood["genres"]:
|
||||
print(f"Жанры: {', '.join(sorted(mood['genres']))}")
|
||||
print()
|
||||
for i, g in enumerate(results, 1):
|
||||
flags = ["установлена" if g["installed"] else None,
|
||||
f"{g['hours']:g} ч" if g["hours"] else "не запускалась",
|
||||
g["status"] if g["status"] != "backlog" else None]
|
||||
flags = [f for f in flags if f]
|
||||
q = []
|
||||
if g["review"] is not None:
|
||||
q.append(f"{g['review']}%")
|
||||
if g["metacritic"] is not None:
|
||||
q.append(f"MC {g['metacritic']}")
|
||||
print(f"{i:2}. {g['name']} [{g['score']}]")
|
||||
print(f" совпало: {', '.join(g['matched']) or '-'}")
|
||||
print(f" {' · '.join(flags)}" + (f" · {', '.join(q)}" if q else ""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Recover descriptions for delisted / region-locked games.
|
||||
|
||||
Fallbacks, in order:
|
||||
1. explicit base-edition map (Dishonored RHCP -> Dishonored, ...)
|
||||
2. exact normalized title match inside the library (regional -> base edition)
|
||||
3. exact normalized title match in the Steam store search
|
||||
4. the same appid requested from a different store region (CN/JP/KR)
|
||||
|
||||
Only exact title matches are accepted, so a similar-but-different game is
|
||||
never used as the source.
|
||||
|
||||
python tools/recover_missing.py
|
||||
python tools/recover_missing.py --dry-run --limit 20
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import difflib
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
from fetch_details import fetch_app_details, fetch_app_details_region, save_details
|
||||
|
||||
STORE_SEARCH = "https://store.steampowered.com/api/storesearch/"
|
||||
|
||||
# Known regional / retail variants whose base edition has a store page.
|
||||
BASE_MAP = {
|
||||
217980: 205100, # Dishonored RHCP -> Dishonored
|
||||
22490: 22380, # Fallout: New Vegas PCR -> Fallout: New Vegas
|
||||
}
|
||||
|
||||
REGIONS = [
|
||||
("schinese", "cn"),
|
||||
("japanese", "jp"),
|
||||
("koreana", "kr"),
|
||||
]
|
||||
|
||||
|
||||
def safe_fetch(appid, lang=None, cc=None, delay=0.4):
|
||||
try:
|
||||
if lang:
|
||||
return fetch_app_details_region(appid, lang, cc)
|
||||
return fetch_app_details(appid)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 429:
|
||||
print(" rate limited, sleeping 60s")
|
||||
time.sleep(60)
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
time.sleep(delay)
|
||||
|
||||
SUFFIXES = re.compile(r"\b(PCR|RHCP|RU|CIS|ROW|Retail|PTS|Beta|Demo)\b", re.I)
|
||||
|
||||
|
||||
def normalize(name):
|
||||
name = (name or "").replace("™", "").replace("®", "").replace("(R)", "").replace("(TM)", "")
|
||||
name = SUFFIXES.sub(" ", name)
|
||||
name = re.sub(r"[^0-9a-zа-яё]+", " ", name.lower())
|
||||
return " ".join(name.split())
|
||||
|
||||
|
||||
def store_search(term, delay=0.4):
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
url = STORE_SEARCH + urllib.parse.urlencode({"term": term, "l": "russian", "cc": "RU"})
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = json.load(resp)
|
||||
time.sleep(delay)
|
||||
return data.get("items", [])
|
||||
|
||||
|
||||
def copy_details(row):
|
||||
return {
|
||||
"short_description": row["short_description"],
|
||||
"about": row["about"],
|
||||
"header_image": row["header_image"],
|
||||
"developers": row["developers"],
|
||||
"publishers": row["publishers"],
|
||||
"release_date": row["release_date"],
|
||||
"lang": row["lang"] or "unknown",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Recover descriptions for delisted games")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--limit", type=int)
|
||||
ap.add_argument("--delay", type=float, default=0.4)
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
|
||||
missing = con.execute("""
|
||||
SELECT g.appid, g.name FROM games g
|
||||
JOIN game_details d ON d.appid = g.appid
|
||||
WHERE d.status = 'missing' AND LOWER(g.type) = 'game'
|
||||
ORDER BY COALESCE(g.review_pct, 0) DESC, g.name
|
||||
""").fetchall()
|
||||
if args.limit:
|
||||
missing = missing[: args.limit]
|
||||
print(f"Missing: {len(missing)}")
|
||||
|
||||
ok_rows = con.execute("""
|
||||
SELECT g.appid, g.name, d.short_description, d.about, d.header_image,
|
||||
d.developers, d.publishers, d.release_date, d.lang
|
||||
FROM games g JOIN game_details d ON d.appid = g.appid
|
||||
WHERE d.status = 'ok' AND LOWER(g.type) = 'game'
|
||||
""").fetchall()
|
||||
by_norm = {}
|
||||
for row in ok_rows:
|
||||
by_norm.setdefault(normalize(row["name"]), []).append(row)
|
||||
by_appid = {row["appid"]: row for row in ok_rows}
|
||||
|
||||
recovered = skipped = 0
|
||||
for target in missing:
|
||||
appid, name = target["appid"], target["name"]
|
||||
norm = normalize(name)
|
||||
source = None
|
||||
details = None
|
||||
|
||||
if appid in BASE_MAP:
|
||||
base = BASE_MAP[appid]
|
||||
details = safe_fetch(base, delay=args.delay)
|
||||
if details:
|
||||
source = base
|
||||
|
||||
if details is None and norm in by_norm:
|
||||
row = by_norm[norm][0]
|
||||
if row["appid"] != appid:
|
||||
details = copy_details(row)
|
||||
source = row["appid"]
|
||||
|
||||
if details is None and norm:
|
||||
try:
|
||||
for item in store_search(name, args.delay):
|
||||
cand = item.get("id")
|
||||
if not cand or cand == appid:
|
||||
continue
|
||||
if normalize(item.get("name")) != norm:
|
||||
continue
|
||||
found = safe_fetch(cand, delay=args.delay)
|
||||
if found and (found["short_description"] or found["about"]):
|
||||
details = found
|
||||
source = cand
|
||||
break
|
||||
except Exception as exc:
|
||||
print(f" search failed for {appid}: {exc}")
|
||||
|
||||
if details is None:
|
||||
for lang, cc in REGIONS:
|
||||
details = safe_fetch(appid, lang, cc, delay=args.delay)
|
||||
if details and (details["short_description"] or details["about"]):
|
||||
source = appid
|
||||
break
|
||||
details = None
|
||||
|
||||
if details is None:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
recovered += 1
|
||||
src = "base" if source != appid else "same"
|
||||
print(f" {appid} {name} <- {src} {source} [{details.get('lang')}] "
|
||||
f"{('(dry run)' if args.dry_run else '')}")
|
||||
if not args.dry_run:
|
||||
save_details(con, appid, details, source_appid=source)
|
||||
time.sleep(args.delay)
|
||||
|
||||
print(f"Recovered: {recovered}, still missing: {len(missing) - recovered} (skipped {skipped})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,120 @@
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA foreign_keys = ON;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS schema_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS games (
|
||||
appid INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT,
|
||||
release_date TEXT,
|
||||
metacritic INTEGER,
|
||||
review_pct INTEGER,
|
||||
updated_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS game_genres (
|
||||
appid INTEGER NOT NULL REFERENCES games(appid) ON DELETE CASCADE,
|
||||
genre TEXT NOT NULL,
|
||||
PRIMARY KEY (appid, genre)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_game_genres_genre ON game_genres(genre);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tag_names (
|
||||
tag_id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS game_tags (
|
||||
appid INTEGER NOT NULL REFERENCES games(appid) ON DELETE CASCADE,
|
||||
tag_id INTEGER NOT NULL,
|
||||
PRIMARY KEY (appid, tag_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_game_tags_tag ON game_tags(tag_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS game_playtime (
|
||||
appid INTEGER PRIMARY KEY REFERENCES games(appid) ON DELETE CASCADE,
|
||||
minutes INTEGER NOT NULL DEFAULT 0,
|
||||
last_played TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS game_install (
|
||||
appid INTEGER PRIMARY KEY REFERENCES games(appid) ON DELETE CASCADE,
|
||||
installed INTEGER NOT NULL DEFAULT 0,
|
||||
size_bytes INTEGER,
|
||||
library_path TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS personal (
|
||||
appid INTEGER PRIMARY KEY REFERENCES games(appid) ON DELETE CASCADE,
|
||||
status TEXT NOT NULL DEFAULT 'backlog'
|
||||
CHECK (status IN ('backlog','playing','played','tribute','nostalgia','ignore')),
|
||||
rating INTEGER CHECK (rating BETWEEN 1 AND 10),
|
||||
favorite INTEGER NOT NULL DEFAULT 0,
|
||||
notes TEXT,
|
||||
updated_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS attributes (
|
||||
appid INTEGER NOT NULL REFERENCES games(appid) ON DELETE CASCADE,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT,
|
||||
PRIMARY KEY (appid, key)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS game_details (
|
||||
appid INTEGER PRIMARY KEY REFERENCES games(appid) ON DELETE CASCADE,
|
||||
short_description TEXT,
|
||||
about TEXT,
|
||||
header_image TEXT,
|
||||
developers TEXT,
|
||||
publishers TEXT,
|
||||
release_date TEXT,
|
||||
lang TEXT,
|
||||
fetched_at TEXT,
|
||||
status TEXT,
|
||||
source_appid INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS game_translations (
|
||||
appid INTEGER PRIMARY KEY REFERENCES games(appid) ON DELETE CASCADE,
|
||||
lang TEXT NOT NULL DEFAULT 'ru',
|
||||
short_description TEXT,
|
||||
about TEXT,
|
||||
provider TEXT,
|
||||
translated_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS moods (
|
||||
name TEXT PRIMARY KEY,
|
||||
description TEXT,
|
||||
genres TEXT NOT NULL DEFAULT '[]',
|
||||
tags TEXT NOT NULL DEFAULT '{}',
|
||||
updated_at TEXT
|
||||
);
|
||||
|
||||
CREATE VIEW IF NOT EXISTS v_library AS
|
||||
SELECT
|
||||
g.appid,
|
||||
g.name,
|
||||
g.type,
|
||||
g.release_date,
|
||||
g.metacritic,
|
||||
g.review_pct,
|
||||
COALESCE(p.minutes, 0) AS minutes,
|
||||
p.last_played,
|
||||
COALESCE(i.installed, 0) AS installed,
|
||||
i.size_bytes,
|
||||
COALESCE(pe.status, 'backlog') AS status,
|
||||
pe.rating,
|
||||
COALESCE(pe.favorite, 0) AS favorite,
|
||||
pe.notes,
|
||||
(SELECT GROUP_CONCAT(gg.genre, '/')
|
||||
FROM game_genres gg WHERE gg.appid = g.appid) AS genres
|
||||
FROM games g
|
||||
LEFT 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;
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Passive reader for the local Steam installation.
|
||||
|
||||
Reads only files the Steam client has already written:
|
||||
appcache/librarycache/* -- every app in the client's library
|
||||
appcache/appinfo.vdf -- names, genres, tags, scores (binary VDF v29)
|
||||
appcache/../config/libraryfolders.vdf
|
||||
steamapps/appmanifest_*.acf -- installed apps
|
||||
userdata/<id>/config/localconfig.vdf -- playtime
|
||||
No Steam session, credentials or network access are required.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
|
||||
GENRES = {
|
||||
1: "Action",
|
||||
2: "Strategy",
|
||||
3: "RPG",
|
||||
4: "Casual",
|
||||
5: "Sports",
|
||||
6: "Racing",
|
||||
7: "Simulation",
|
||||
8: "Accounting",
|
||||
9: "Racing",
|
||||
18: "Sports",
|
||||
23: "Indie",
|
||||
25: "Adventure",
|
||||
28: "Simulation",
|
||||
29: "Massively Multiplayer",
|
||||
37: "Free To Play",
|
||||
70: "Early Access",
|
||||
71: "Animation & Modeling",
|
||||
72: "Design & Illustration",
|
||||
73: "Violent",
|
||||
74: "Gore",
|
||||
}
|
||||
|
||||
SKIP_GENRE_IDS = {30, 73, 74}
|
||||
|
||||
DEFAULT_ROOTS = (
|
||||
r"C:\Program Files (x86)\Steam",
|
||||
r"C:\Program Files\Steam",
|
||||
)
|
||||
|
||||
|
||||
def find_steam_root():
|
||||
try:
|
||||
import winreg
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam") as k:
|
||||
path = winreg.QueryValueEx(k, "SteamPath")[0]
|
||||
if path and os.path.isdir(path):
|
||||
return os.path.normpath(path)
|
||||
except Exception:
|
||||
pass
|
||||
for path in DEFAULT_ROOTS:
|
||||
if os.path.isdir(path):
|
||||
return path
|
||||
raise SystemExit("Steam not found; pass --steam-root explicitly")
|
||||
|
||||
|
||||
def _read_text(path):
|
||||
with open(path, encoding="utf-8-sig", errors="replace") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def read_users(root):
|
||||
path = os.path.join(root, "config", "loginusers.vdf")
|
||||
if not os.path.isfile(path):
|
||||
return []
|
||||
text = _read_text(path)
|
||||
users = []
|
||||
for m in re.finditer(r'"(?P<id>\d{17})"\s*\{(?P<body>[^}]*)\}', text):
|
||||
body = m.group("body")
|
||||
users.append({
|
||||
"steamid": m.group("id"),
|
||||
"account": (re.search(r'"AccountName"\s*"([^"]*)"', body) or [None, None])[1],
|
||||
"persona": (re.search(r'"PersonaName"\s*"([^"]*)"', body) or [None, None])[1],
|
||||
"most_recent": (re.search(r'"MostRecent"\s*"(\d)"', body) or [None, "0"])[1] == "1",
|
||||
})
|
||||
return users
|
||||
|
||||
|
||||
def account_id(steamid64):
|
||||
return int(steamid64) - 76561197960265728
|
||||
|
||||
|
||||
def library_roots(root):
|
||||
roots = [root]
|
||||
seen = {os.path.normcase(root)}
|
||||
for vdf in (os.path.join(root, "config", "libraryfolders.vdf"),
|
||||
os.path.join(root, "steamapps", "libraryfolders.vdf")):
|
||||
if not os.path.isfile(vdf):
|
||||
continue
|
||||
for m in re.finditer(r'"path"\s*"((?:[^"\\]|\\.)*)"', _read_text(vdf)):
|
||||
path = m.group(1).replace("\\\\", "\\")
|
||||
key = os.path.normcase(path)
|
||||
if os.path.isdir(path) and key not in seen:
|
||||
seen.add(key)
|
||||
roots.append(path)
|
||||
return roots
|
||||
|
||||
|
||||
def installed_apps(roots):
|
||||
out = {}
|
||||
for root in roots:
|
||||
apps_dir = os.path.join(root, "steamapps")
|
||||
if not os.path.isdir(apps_dir):
|
||||
continue
|
||||
for fn in os.listdir(apps_dir):
|
||||
m = re.match(r"appmanifest_(\d+)\.acf$", fn)
|
||||
if not m:
|
||||
continue
|
||||
text = _read_text(os.path.join(apps_dir, fn))
|
||||
appid = int(m.group(1))
|
||||
out[appid] = {
|
||||
"name": (re.search(r'"name"\s*"((?:[^"\\]|\\.)*)"', text) or [None, None])[1],
|
||||
"size_bytes": int((re.search(r'"SizeOnDisk"\s*"(\d+)"', text) or [None, 0])[1]),
|
||||
"last_played": (re.search(r'"LastPlayed"\s*"(\d+)"', text) or [None, "0"])[1],
|
||||
"library_path": root,
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def library_appids(root):
|
||||
cache = os.path.join(root, "appcache", "librarycache")
|
||||
if not os.path.isdir(cache):
|
||||
return []
|
||||
return sorted(int(n) for n in os.listdir(cache) if n.isdigit())
|
||||
|
||||
|
||||
def _appinfo_strings(data, offset):
|
||||
count = struct.unpack_from("<I", data, offset)[0]
|
||||
pos = offset + 4
|
||||
strings = []
|
||||
for _ in range(count):
|
||||
end = data.index(b"\x00", pos)
|
||||
strings.append(data[pos:end].decode("utf-8", "replace"))
|
||||
pos = end + 1
|
||||
return strings
|
||||
|
||||
|
||||
def _appinfo_kv(data, off, strings):
|
||||
out = {}
|
||||
while True:
|
||||
kind = data[off]
|
||||
off += 1
|
||||
if kind == 0x08:
|
||||
return out, off
|
||||
idx = struct.unpack_from("<I", data, off)[0]
|
||||
off += 4
|
||||
key = strings[idx] if idx < len(strings) else None
|
||||
if kind == 0x00:
|
||||
value, off = _appinfo_kv(data, off, strings)
|
||||
elif kind == 0x01:
|
||||
end = data.index(b"\x00", off)
|
||||
value = data[off:end].decode("utf-8", "replace")
|
||||
off = end + 1
|
||||
elif kind == 0x02:
|
||||
value = struct.unpack_from("<i", data, off)[0]; off += 4
|
||||
elif kind == 0x03:
|
||||
value = struct.unpack_from("<f", data, off)[0]; off += 4
|
||||
elif kind == 0x04:
|
||||
value = struct.unpack_from("<I", data, off)[0]; off += 4
|
||||
elif kind == 0x05:
|
||||
value = struct.unpack_from("<I", data, off)[0]; off += 4
|
||||
elif kind == 0x06:
|
||||
value = struct.unpack_from("<I", data, off)[0]; off += 4
|
||||
elif kind == 0x07:
|
||||
value = struct.unpack_from("<Q", data, off)[0]; off += 8
|
||||
elif kind == 0x0A:
|
||||
value = struct.unpack_from("<q", data, off)[0]; off += 8
|
||||
else:
|
||||
raise ValueError(f"unknown binary VDF type {kind:#x}")
|
||||
out[key] = value
|
||||
|
||||
|
||||
def read_appinfo(root):
|
||||
"""Return {appid: {name, type, genres, tags, metacritic, review_pct, release}}."""
|
||||
path = os.path.join(root, "appcache", "appinfo.vdf")
|
||||
if not os.path.isfile(path):
|
||||
return {}
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
magic = struct.unpack_from("<I", data, 0)[0]
|
||||
if magic != 0x07564429:
|
||||
raise SystemExit(f"Unsupported appinfo.vdf version: {magic:#x} (only v29 is implemented)")
|
||||
|
||||
table_offset = struct.unpack_from("<Q", data, 8)[0]
|
||||
strings = _appinfo_strings(data, table_offset)
|
||||
|
||||
apps = {}
|
||||
off = 16
|
||||
while True:
|
||||
if off + 8 > len(data):
|
||||
break
|
||||
appid = struct.unpack_from("<I", data, off)[0]
|
||||
if appid == 0:
|
||||
break
|
||||
size = struct.unpack_from("<I", data, off + 4)[0]
|
||||
kv_offset = off + 68
|
||||
try:
|
||||
kv, _ = _appinfo_kv(data, kv_offset, strings)
|
||||
info = kv.get("appinfo", {})
|
||||
common = info.get("common", {})
|
||||
apps[appid] = {
|
||||
"name": common.get("name") or info.get("name"),
|
||||
"type": common.get("type"),
|
||||
"genres": common.get("genres") or {},
|
||||
"tags": common.get("store_tags") or {},
|
||||
"metacritic": common.get("metacritic_score"),
|
||||
"review_pct": common.get("review_percentage"),
|
||||
"release": common.get("steam_release_date"),
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
off += 8 + size
|
||||
return apps
|
||||
|
||||
|
||||
def read_playtime(root, steamid):
|
||||
"""Return {appid: {minutes, last_played}} from localconfig.vdf."""
|
||||
path = os.path.join(root, "userdata", str(account_id(steamid)), "config", "localconfig.vdf")
|
||||
if not os.path.isfile(path):
|
||||
return {}
|
||||
text = _read_text(path)
|
||||
start = text.find('"apps"')
|
||||
if start < 0:
|
||||
return {}
|
||||
text = text[start:]
|
||||
|
||||
out = {}
|
||||
for m in re.finditer(r'"(\d+)"\s*\n\s*\{', text):
|
||||
appid = int(m.group(1))
|
||||
depth = 0
|
||||
end = m.end() - 1
|
||||
while end < len(text):
|
||||
if text[end] == "{":
|
||||
depth += 1
|
||||
elif text[end] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
end += 1
|
||||
body = text[m.end():end]
|
||||
last = re.search(r'"LastPlayed"\s*"(\d+)"', body)
|
||||
play = re.search(r'"Playtime"\s*"(\d+)"', body)
|
||||
if last or play:
|
||||
out[appid] = {
|
||||
"minutes": int(play.group(1)) if play else 0,
|
||||
"last_played": int(last.group(1)) if last else 0,
|
||||
}
|
||||
return out
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Translate cached English descriptions into Russian.
|
||||
|
||||
Uses the public Google Translate endpoint (no key). Translations are stored in
|
||||
``game_translations`` and preferred by the web UI over the original text.
|
||||
|
||||
python tools/translate_details.py --stats
|
||||
python tools/translate_details.py --limit 200
|
||||
python tools/translate_details.py --all --about
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
|
||||
ENDPOINT = "https://translate.googleapis.com/translate_a/single"
|
||||
MAX_CHUNK = 3800
|
||||
|
||||
|
||||
def clean_html(text):
|
||||
if not text:
|
||||
return ""
|
||||
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
|
||||
text = re.sub(r"</p>", "\n", text, flags=re.I)
|
||||
text = re.sub(r"<[^>]+>", " ", text)
|
||||
text = html.unescape(text)
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def looks_english(text):
|
||||
if not text:
|
||||
return False
|
||||
letters = [c for c in text if c.isalpha()]
|
||||
if len(letters) < 8:
|
||||
return False
|
||||
latin = sum(1 for c in letters if "a" <= c.lower() <= "z")
|
||||
cyrillic = sum(1 for c in letters if "а" <= c.lower() <= "я" or c.lower() == "ё")
|
||||
return latin / len(letters) > 0.6 and cyrillic / len(letters) < 0.1
|
||||
|
||||
|
||||
def split_chunks(text, size=MAX_CHUNK):
|
||||
chunks, current = [], ""
|
||||
for part in re.split(r"(?<=[.!?])\s+|\n+", text):
|
||||
if not part:
|
||||
continue
|
||||
if len(current) + len(part) + 1 > size and current:
|
||||
chunks.append(current.strip())
|
||||
current = part
|
||||
else:
|
||||
current = f"{current} {part}".strip()
|
||||
if current:
|
||||
chunks.append(current.strip())
|
||||
return chunks or [text[:size]]
|
||||
|
||||
|
||||
def translate_chunk(text, delay=0.25, retries=3):
|
||||
params = urllib.parse.urlencode({
|
||||
"client": "gtx", "sl": "auto", "tl": "ru", "dt": "t", "q": text,
|
||||
})
|
||||
req = urllib.request.Request(f"{ENDPOINT}?{params}",
|
||||
headers={"User-Agent": "Mozilla/5.0"})
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=40) as resp:
|
||||
data = json.load(resp)
|
||||
time.sleep(delay)
|
||||
return "".join(part[0] for part in data[0] if part and part[0])
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code in (429, 403):
|
||||
time.sleep(30 * (attempt + 1))
|
||||
continue
|
||||
time.sleep(2)
|
||||
except Exception:
|
||||
time.sleep(2)
|
||||
return None
|
||||
|
||||
|
||||
def translate_text(text, delay=0.25):
|
||||
if not text:
|
||||
return None
|
||||
parts = []
|
||||
for chunk in split_chunks(text):
|
||||
translated = translate_chunk(chunk, delay=delay)
|
||||
if translated is None:
|
||||
return None
|
||||
parts.append(translated)
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def pending_rows(con, limit=None, about=False):
|
||||
if about:
|
||||
sql = """
|
||||
SELECT d.appid, d.short_description, d.about,
|
||||
t.short_description AS short_existing
|
||||
FROM game_details d
|
||||
JOIN games g ON g.appid = d.appid
|
||||
LEFT JOIN game_translations t ON t.appid = d.appid
|
||||
WHERE d.status = 'ok' AND LOWER(g.type) = 'game'
|
||||
AND COALESCE(d.about, '') <> ''
|
||||
AND t.about IS NULL
|
||||
ORDER BY COALESCE(g.review_pct, 0) DESC, g.name
|
||||
"""
|
||||
rows = [r for r in con.execute(sql) if looks_english(r["about"])]
|
||||
else:
|
||||
sql = """
|
||||
SELECT d.appid, d.short_description, d.about
|
||||
FROM game_details d
|
||||
JOIN games g ON g.appid = d.appid
|
||||
LEFT JOIN game_translations t ON t.appid = d.appid
|
||||
WHERE d.status = 'ok' AND LOWER(g.type) = 'game'
|
||||
AND t.appid IS NULL
|
||||
AND (COALESCE(d.short_description, '') <> '' OR COALESCE(d.about, '') <> '')
|
||||
ORDER BY COALESCE(g.review_pct, 0) DESC, g.name
|
||||
"""
|
||||
rows = [r for r in con.execute(sql)
|
||||
if looks_english(r["short_description"])
|
||||
or (not r["short_description"] and looks_english(r["about"]))]
|
||||
return rows[:limit] if limit else rows
|
||||
|
||||
|
||||
def save_translation(con, appid, short_ru, about_ru):
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
con.execute(
|
||||
"""INSERT INTO game_translations
|
||||
(appid, lang, short_description, about, provider, translated_at)
|
||||
VALUES (?, 'ru', ?, ?, 'google', ?)
|
||||
ON CONFLICT(appid) DO UPDATE SET
|
||||
lang = 'ru',
|
||||
short_description = COALESCE(excluded.short_description,
|
||||
game_translations.short_description),
|
||||
about = COALESCE(excluded.about, game_translations.about),
|
||||
provider = excluded.provider,
|
||||
translated_at = excluded.translated_at""",
|
||||
(appid, short_ru, about_ru, now),
|
||||
)
|
||||
con.commit()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Translate descriptions to Russian")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--limit", type=int)
|
||||
ap.add_argument("--all", action="store_true")
|
||||
ap.add_argument("--about", action="store_true", help="translate full descriptions too")
|
||||
ap.add_argument("--delay", type=float, default=0.3)
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
ap.add_argument("--stats", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
|
||||
if args.stats:
|
||||
rows = con.execute("""SELECT d.short_description, d.about
|
||||
FROM game_details d JOIN games g ON g.appid=d.appid
|
||||
WHERE d.status='ok' AND LOWER(g.type)='game'""").fetchall()
|
||||
total = sum(1 for r in rows
|
||||
if looks_english(r["short_description"])
|
||||
or (not r["short_description"] and looks_english(r["about"])))
|
||||
done = con.execute("""SELECT COUNT(*) FROM game_translations t JOIN games g ON g.appid=t.appid
|
||||
WHERE LOWER(g.type)='game'""").fetchone()[0]
|
||||
print(f"english details: {total} | translated: {done} | pending: {len(pending_rows(con))}"
|
||||
f" | full pending: {len(pending_rows(con, about=True))}")
|
||||
return
|
||||
|
||||
limit = None if args.all else (args.limit or 100)
|
||||
rows = pending_rows(con, limit, about=args.about)
|
||||
print(f"To translate: {len(rows)}" + (" (with full descriptions)" if args.about else ""))
|
||||
ok = failed = 0
|
||||
for i, row in enumerate(rows, 1):
|
||||
existing_short = row["short_existing"] if args.about and "short_existing" in row.keys() else None
|
||||
short_ru = None
|
||||
if not existing_short and row["short_description"]:
|
||||
short_ru = translate_text(clean_html(row["short_description"]), args.delay)
|
||||
about_ru = None
|
||||
if args.about and row["about"]:
|
||||
about_ru = translate_text(clean_html(row["about"]), args.delay)
|
||||
if not short_ru and not about_ru and not existing_short:
|
||||
failed += 1
|
||||
continue
|
||||
ok += 1
|
||||
if not args.dry_run:
|
||||
save_translation(con, row["appid"], short_ru or existing_short, about_ru)
|
||||
if i % 10 == 0 or i == len(rows):
|
||||
print(f" {i}/{len(rows)} ok={ok} failed={failed}")
|
||||
|
||||
print(f"Done. translated={ok} failed={failed}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user