feat: add optional HLTB enrichment
CI / test (push) Successful in 7m10s

This commit is contained in:
strsv committed 2026-11-06 22:16:27 +03:00
1 parent b865a4a389
commit d07dec5e75
19 files changed
+258 -23

No files matched your search

+14 -1
View File
@@ -8,7 +8,7 @@ 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")
SCHEMA_VERSION = 5
SCHEMA_VERSION = 6
MOOD_PRESETS = {
"adventure-rpg-party": {
@@ -550,12 +550,25 @@ def _migration_5(con):
backfill_release_dates(con)
def _migration_6(con):
"""Add optional HowLongToBeat columns."""
for column, declaration in (
("hltb_main", "REAL"),
("hltb_extra", "REAL"),
("hltb_complete", "REAL"),
("hltb_id", "INTEGER"),
("hltb_updated_at", "TEXT"),
):
_ensure_column(con, "games", column, declaration)
MIGRATIONS = {
1: _migration_1,
2: _migration_2,
3: _migration_3,
4: _migration_4,
5: _migration_5,
6: _migration_6,
}
+135
View File
@@ -0,0 +1,135 @@
"""Optional HowLongToBeat enrichment.
Requires the optional wrapper:
pip install -r requirements-hltb.txt
python tools/fetch_hltb.py --limit 100
python tools/fetch_hltb.py --refresh --limit 50
python tools/fetch_hltb.py --all --delay 0.6
Only exact normalized title matches are accepted. Times are stored in
games.hltb_* and the main story time becomes games.estimated_hours.
"""
import argparse
import os
import re
import sys
import time
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
try:
from howlongtobeatpy import HowLongToBeat
except Exception:
HowLongToBeat = None
def normalize(name):
value = (name or "").lower()
value = value.replace("™", "").replace("®", "").replace("(r)", "").replace("(tm)", "")
value = re.sub(r"[^0-9a-zа-яё]+", " ", value)
return " ".join(value.split())
def find_match(entries, name):
key = normalize(name)
for entry in entries:
if normalize(entry.game_name) == key:
return entry
return None
def positive(value):
try:
value = float(value)
except (TypeError, ValueError):
return None
return value if value > 0 else None
def main():
ap = argparse.ArgumentParser(description="Enrich games with HowLongToBeat times")
ap.add_argument("--db", default=db.DEFAULT_DB)
ap.add_argument("--limit", type=int, default=100)
ap.add_argument("--all", action="store_true")
ap.add_argument("--refresh", action="store_true", help="refetch games already enriched")
ap.add_argument("--delay", type=float, default=0.5)
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
if HowLongToBeat is None:
print("howlongtobeatpy is not installed; run: pip install -r requirements-hltb.txt",
file=sys.stderr)
return 1
con = db.connect(args.db)
db.init(con)
where = ["LOWER(type) = 'game'"]
if not args.refresh:
where.append("hltb_updated_at IS NULL")
sql = (f"SELECT appid, name FROM games WHERE {' AND '.join(where)} "
"ORDER BY COALESCE(review_pct, 0) DESC, name")
rows = con.execute(sql).fetchall()
if not args.all:
rows = rows[:args.limit]
print(f"To fetch: {len(rows)}")
searcher = HowLongToBeat()
matched = missing = errors = 0
for index, row in enumerate(rows, 1):
try:
entries = searcher.search(row["name"])
except Exception as exc:
errors += 1
print(f" {row['name']}: {exc}")
time.sleep(args.delay)
continue
entry = find_match(entries, row["name"])
if not entry:
missing += 1
time.sleep(args.delay)
if index % 20 == 0 or index == len(rows):
print(f" {index}/{len(rows)} matched={matched} missing={missing} errors={errors}")
continue
main_hours = positive(getattr(entry, "main_story", None))
extra_hours = positive(getattr(entry, "main_extra", None))
complete_hours = positive(getattr(entry, "completionist", None))
best = main_hours or extra_hours or complete_hours
if not best:
missing += 1
time.sleep(args.delay)
continue
matched += 1
if not args.dry_run:
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
con.execute(
"""UPDATE games SET hltb_main = ?, hltb_extra = ?, hltb_complete = ?,
hltb_id = ?, hltb_updated_at = ?, estimated_hours = ?
WHERE appid = ?""",
(main_hours, extra_hours, complete_hours,
getattr(entry, "game_id", None), now, best, row["appid"]))
con.commit()
if index % 10 == 0 or index == len(rows):
print(f" {index}/{len(rows)} matched={matched} missing={missing} errors={errors}")
time.sleep(args.delay)
print(f"Done. matched={matched} missing={missing} errors={errors}")
if args.dry_run:
print("dry run: database was not changed")
con.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+5
View File
@@ -14,6 +14,11 @@ CREATE TABLE IF NOT EXISTS games (
metacritic INTEGER,
review_pct INTEGER,
estimated_hours REAL,
hltb_main REAL,
hltb_extra REAL,
hltb_complete REAL,
hltb_id INTEGER,
hltb_updated_at TEXT,
updated_at TEXT
);