Files
SteamBase/tools/fetch_hltb.py
T
2026-11-06 22:39:33 +03:00

155 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 all games")
ap.add_argument("--retry-missed", action="store_true",
help="retry games that were checked without a match")
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:
if args.retry_missed:
where.append("(hltb_checked_at IS NULL OR hltb_match = 0)")
else:
where.append("hltb_checked_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
if not args.dry_run:
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
con.execute(
"""UPDATE games SET hltb_checked_at = ?,
hltb_match = CASE WHEN hltb_id IS NOT NULL THEN 1 ELSE 0 END
WHERE appid = ?""", (now, row["appid"]))
con.commit()
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
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
if not best:
missing += 1
if not args.dry_run:
con.execute(
"""UPDATE games SET hltb_checked_at = ?,
hltb_match = CASE WHEN hltb_id IS NOT NULL THEN 1 ELSE 0 END
WHERE appid = ?""", (now, row["appid"]))
con.commit()
time.sleep(args.delay)
continue
matched += 1
if not args.dry_run:
con.execute(
"""UPDATE games SET hltb_main = ?, hltb_extra = ?, hltb_complete = ?,
hltb_id = ?, hltb_checked_at = ?, hltb_match = 1,
hltb_updated_at = ?, estimated_hours = ?
WHERE appid = ?""",
(main_hours, extra_hours, complete_hours,
getattr(entry, "game_id", None), now, 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())