Files
SteamBase/tools/fetch_hltb.py
T
2026-11-07 00:27:41 +03:00

211 lines
7.5 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 difflib
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())
ROMAN = {"ii": "2", "iii": "3", "iv": "4", "v": "5", "vi": "6",
"vii": "7", "viii": "8", "ix": "9", "x": "10"}
EDITION_WORDS = re.compile(
r"\b(goty|game of the year|hd|gold pack|gold edition|definitive edition|"
r"remastered|anniversary edition|complete edition|deluxe edition|"
r"ultimate edition|classic edition|classic|edition|rhcp|pcr|cis|row)\b", re.I)
def match_key(name):
"""Normalize titles for matching: editions, years, roman numerals."""
value = normalize(name)
value = re.sub(r"\b(?:19|20)\d{2}\b", " ", value)
value = EDITION_WORDS.sub(" ", value)
words = [ROMAN.get(word, word) for word in value.split()]
return " ".join(words)
def search_variants(name, year=None):
base = normalize(name)
stripped = match_key(name)
variants = [base, name.strip(), stripped]
if year:
variants.extend([f"{base} {year}", f"{stripped} {year}"])
out = []
for value in variants:
if value and value not in out:
out.append(value)
return out
def find_match(entries, name, year=None):
key = match_key(name)
best, best_score = None, 0.0
for entry in entries:
candidate = match_key(entry.game_name)
score = 1.0 if candidate == key else difflib.SequenceMatcher(None, key, candidate).ratio()
if year and getattr(entry, "release_world", None) == year:
score += 0.05
if score >= 0.92 and score > best_score:
best, best_score = entry, score
return best
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_match = 0 AND hltb_checked_at IS NOT NULL")
else:
where.append("hltb_checked_at IS NULL")
sql = (f"SELECT appid, name, release_date 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):
release = str(row["release_date"] or "")
year = int(release[:4]) if len(release) >= 4 and release[:4].isdigit() else None
entry = None
last_error = None
for query in search_variants(row["name"], year):
try:
entries = searcher.search(query)
except Exception as exc:
last_error = exc
break
entry = find_match(entries, row["name"], year)
if entry:
break
time.sleep(args.delay)
if last_error is not None:
errors += 1
print(f" {row['name']}: {last_error}")
time.sleep(args.delay)
continue
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 len(rows) <= 20:
print(f" {row['name']}: не найдено")
if index % 10 == 0 or index == len(rows) or len(rows) <= 20:
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)
if len(rows) <= 20:
print(f" {row['name']}: нет времени")
if len(rows) <= 20:
print(f" {index}/{len(rows)} matched={matched} missing={missing} errors={errors}")
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 len(rows) <= 20:
print(f" {row['name']}: {best} ч")
if index % 10 == 0 or index == len(rows) or len(rows) <= 20:
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())