Store search results in hltb_cache (schema v8) with a 7-day TTL, cache misses too, prune rows older than 90 days, and add --cache-ttl, --no-cache and --clear-cache.
313 lines
11 KiB
Python
313 lines
11 KiB
Python
"""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 json
|
||
import os
|
||
import re
|
||
import sys
|
||
import time
|
||
from datetime import datetime, timedelta, timezone
|
||
from types import SimpleNamespace
|
||
|
||
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
|
||
|
||
|
||
CACHE_TTL_DAYS = 7.0
|
||
CACHE_RETENTION_DAYS = 90
|
||
CACHE_FIELDS = ("game_name", "release_world", "game_id",
|
||
"main_story", "main_extra", "completionist")
|
||
|
||
|
||
def entry_to_dict(entry):
|
||
"""Keep only the fields needed for matching and storage."""
|
||
return {field: getattr(entry, field, None) for field in CACHE_FIELDS}
|
||
|
||
|
||
def entry_from_dict(data):
|
||
return SimpleNamespace(**{field: data.get(field) for field in CACHE_FIELDS})
|
||
|
||
|
||
def cache_get(con, query, ttl_days):
|
||
"""Return cached search entries, or None when missing or stale."""
|
||
if ttl_days <= 0:
|
||
return None
|
||
row = con.execute("SELECT fetched_at, results FROM hltb_cache WHERE query = ?",
|
||
(query,)).fetchone()
|
||
if not row:
|
||
return None
|
||
try:
|
||
fetched = datetime.fromisoformat(row["fetched_at"])
|
||
except (TypeError, ValueError):
|
||
return None
|
||
if fetched.tzinfo is None:
|
||
fetched = fetched.replace(tzinfo=timezone.utc)
|
||
age = (datetime.now(timezone.utc) - fetched).total_seconds()
|
||
if age > ttl_days * 86400:
|
||
return None
|
||
try:
|
||
data = json.loads(row["results"])
|
||
except (TypeError, ValueError):
|
||
return None
|
||
if not isinstance(data, list):
|
||
return None
|
||
return data
|
||
|
||
|
||
def cache_put(con, query, entries):
|
||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||
con.execute(
|
||
"""INSERT INTO hltb_cache (query, fetched_at, results) VALUES (?, ?, ?)
|
||
ON CONFLICT(query) DO UPDATE SET fetched_at = excluded.fetched_at,
|
||
results = excluded.results""",
|
||
(query, now, json.dumps(entries, ensure_ascii=False)))
|
||
con.commit()
|
||
|
||
|
||
def cache_clear(con):
|
||
deleted = con.execute("DELETE FROM hltb_cache").rowcount
|
||
con.commit()
|
||
return deleted
|
||
|
||
|
||
def cache_prune(con, days=CACHE_RETENTION_DAYS):
|
||
cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat(timespec="seconds")
|
||
deleted = con.execute("DELETE FROM hltb_cache WHERE fetched_at < ?",
|
||
(cutoff,)).rowcount
|
||
con.commit()
|
||
return deleted
|
||
|
||
|
||
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")
|
||
ap.add_argument("--cache-ttl", type=float, default=CACHE_TTL_DAYS,
|
||
help="days to reuse cached HLTB searches (0 disables)")
|
||
ap.add_argument("--no-cache", action="store_true",
|
||
help="do not read or write the HLTB query cache")
|
||
ap.add_argument("--clear-cache", action="store_true",
|
||
help="delete cached HLTB searches and exit")
|
||
args = ap.parse_args()
|
||
|
||
con = db.connect(args.db)
|
||
db.init(con)
|
||
if args.clear_cache:
|
||
print(f"Cleared {cache_clear(con)} cached searches.")
|
||
con.close()
|
||
return 0
|
||
|
||
cache_enabled = not args.no_cache
|
||
if cache_enabled and not args.dry_run:
|
||
pruned = cache_prune(con)
|
||
if pruned:
|
||
print(f"Pruned {pruned} stale cached searches.")
|
||
|
||
if HowLongToBeat is None:
|
||
print("howlongtobeatpy is not installed; run: pip install -r requirements-hltb.txt",
|
||
file=sys.stderr)
|
||
con.close()
|
||
return 1
|
||
|
||
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 = cached_hits = 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
|
||
network_used = False
|
||
for query in search_variants(row["name"], year):
|
||
entries = None
|
||
if cache_enabled:
|
||
cached = cache_get(con, query, args.cache_ttl)
|
||
if cached is not None:
|
||
entries = [entry_from_dict(item) for item in cached]
|
||
cached_hits += 1
|
||
if entries is None:
|
||
try:
|
||
raw = searcher.search(query)
|
||
except Exception as exc:
|
||
last_error = exc
|
||
break
|
||
network_used = True
|
||
entries = raw
|
||
if cache_enabled and not args.dry_run:
|
||
cache_put(con, query, [entry_to_dict(item) for item in raw])
|
||
time.sleep(args.delay)
|
||
entry = find_match(entries, row["name"], year)
|
||
if entry:
|
||
break
|
||
if last_error is not None:
|
||
errors += 1
|
||
print(f" {row['name']}: {last_error}")
|
||
if network_used:
|
||
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()
|
||
if network_used:
|
||
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()
|
||
if network_used:
|
||
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}")
|
||
if network_used:
|
||
time.sleep(args.delay)
|
||
|
||
print(f"Done. matched={matched} missing={missing} errors={errors} "
|
||
f"cached={cached_hits}")
|
||
if args.dry_run:
|
||
print("dry run: database was not changed")
|
||
con.close()
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|