feat: localize tags and genres; improve search, duration and sorting
CI / test (push) Successful in 27s
CI / test (push) Successful in 27s
This commit is contained in:
1 parent
ea3074e0a9
commit
be4fbf6864
31 files changed
+1126
-145
No files matched your search
+181
-11
@@ -10,6 +10,7 @@ import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
@@ -24,7 +25,9 @@ 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"
|
||||
TAG_URL = "https://store.steampowered.com/tagdata/populartags/{language}"
|
||||
APP_URL = "https://store.steampowered.com/app/{appid}/?l={language}"
|
||||
TAG_MODAL_MARKER = "InitAppTagModal"
|
||||
|
||||
|
||||
def iso_from_unix(ts):
|
||||
@@ -33,13 +36,144 @@ def iso_from_unix(ts):
|
||||
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"})
|
||||
def fetch_tag_names(language="english"):
|
||||
url = TAG_URL.format(language=language)
|
||||
req = urllib.request.Request(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 parse_app_tag_modal(html):
|
||||
"""Return {tag_id: name} from the InitAppTagModal(...) call on a Store page.
|
||||
|
||||
The popular-tags endpoint exposes 429 browsable tags. A game page still lists
|
||||
every tag it uses in the ``InitAppTagModal`` JSON, so this fills gaps for
|
||||
tag ids outside the popular list.
|
||||
"""
|
||||
index = html.find(TAG_MODAL_MARKER)
|
||||
if index == -1:
|
||||
return {}
|
||||
start = html.find("[", index)
|
||||
if start == -1:
|
||||
return {}
|
||||
try:
|
||||
payload, _ = json.JSONDecoder().raw_decode(html[start:])
|
||||
except ValueError:
|
||||
return {}
|
||||
if not isinstance(payload, list):
|
||||
return {}
|
||||
names = {}
|
||||
for item in payload:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
tag_id = int(item.get("tagid"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
name = item.get("name")
|
||||
if tag_id and isinstance(name, str) and name.strip():
|
||||
names[tag_id] = name.strip()
|
||||
return names
|
||||
|
||||
|
||||
def fetch_app_tag_names(appid, language="english", timeout=20):
|
||||
url = APP_URL.format(appid=appid, language=language)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return parse_app_tag_modal(resp.read().decode("utf-8", "replace"))
|
||||
|
||||
|
||||
def missing_tag_ids(con):
|
||||
rows = con.execute(
|
||||
"""SELECT DISTINCT gt.tag_id FROM game_tags gt
|
||||
LEFT JOIN tag_names tn ON tn.tag_id = gt.tag_id
|
||||
WHERE tn.tag_id IS NULL OR tn.name IS NULL""")
|
||||
return {r["tag_id"] for r in rows}
|
||||
|
||||
|
||||
def untranslated_tag_ids(con):
|
||||
rows = con.execute(
|
||||
"""SELECT tn.tag_id FROM tag_names tn
|
||||
WHERE (tn.name_ru IS NULL OR tn.name_ru = '')
|
||||
AND EXISTS (SELECT 1 FROM game_tags gt WHERE gt.tag_id = tn.tag_id)""")
|
||||
return {r["tag_id"] for r in rows}
|
||||
|
||||
|
||||
def resolve_missing_tag_names(con, max_pages=50, delay=0.4, log=print):
|
||||
"""Name and translate tag ids outside the popular list using Store pages."""
|
||||
missing_names = missing_tag_ids(con)
|
||||
missing_ru = untranslated_tag_ids(con)
|
||||
if not (missing_names or missing_ru):
|
||||
return 0, 0
|
||||
|
||||
wanted_ids = missing_names | missing_ru
|
||||
holders = {}
|
||||
placeholders = ",".join("?" for _ in wanted_ids)
|
||||
for row in con.execute(
|
||||
f"SELECT appid, tag_id FROM game_tags WHERE tag_id IN ({placeholders}) ORDER BY appid",
|
||||
sorted(wanted_ids)):
|
||||
holders.setdefault(row["tag_id"], []).append(row["appid"])
|
||||
|
||||
pages = {}
|
||||
for tag_id, appids in holders.items():
|
||||
for appid in appids[:3]:
|
||||
pages.setdefault(appid, set()).add(tag_id)
|
||||
ordered = sorted(pages, key=lambda appid: (-len(pages[appid]), appid))[:max_pages]
|
||||
|
||||
resolved_names = resolved_ru = 0
|
||||
for appid in ordered:
|
||||
wanted = pages[appid] & (missing_names | missing_ru)
|
||||
if not wanted:
|
||||
continue
|
||||
names_en = {}
|
||||
names_ru = {}
|
||||
if wanted & missing_names:
|
||||
try:
|
||||
names_en = fetch_app_tag_names(appid, "english")
|
||||
except Exception as exc:
|
||||
log(f" tag names from app {appid} skipped: {exc}")
|
||||
time.sleep(delay)
|
||||
try:
|
||||
names_ru = fetch_app_tag_names(appid, "russian")
|
||||
except Exception as exc:
|
||||
log(f" tag translations from app {appid} skipped: {exc}")
|
||||
time.sleep(delay)
|
||||
|
||||
rows = []
|
||||
for tag_id in wanted:
|
||||
name = names_en.get(tag_id)
|
||||
if name:
|
||||
rows.append((tag_id, name, names_ru.get(tag_id)))
|
||||
if rows:
|
||||
con.executemany(
|
||||
"""INSERT INTO tag_names (tag_id, name, name_ru) VALUES (?, ?, ?)
|
||||
ON CONFLICT(tag_id) DO UPDATE SET
|
||||
name = COALESCE(excluded.name, tag_names.name),
|
||||
name_ru = COALESCE(excluded.name_ru, tag_names.name_ru)""",
|
||||
rows)
|
||||
con.commit()
|
||||
|
||||
ru_only = [(names_ru[tag_id], tag_id) for tag_id in wanted
|
||||
if tag_id not in missing_names and names_ru.get(tag_id)]
|
||||
if ru_only:
|
||||
con.executemany("UPDATE tag_names SET name_ru = ? WHERE tag_id = ?", ru_only)
|
||||
con.commit()
|
||||
|
||||
if rows or ru_only:
|
||||
log(f" tags from app {appid}: {len(rows)} names, {len(ru_only)} translations")
|
||||
|
||||
before_names, before_ru = len(missing_names), len(missing_ru)
|
||||
missing_names = missing_tag_ids(con)
|
||||
missing_ru = untranslated_tag_ids(con)
|
||||
resolved_names += before_names - len(missing_names)
|
||||
resolved_ru += before_ru - len(missing_ru)
|
||||
if not (missing_names or missing_ru):
|
||||
break
|
||||
|
||||
return resolved_names, resolved_ru
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Import the local Steam library into SQLite")
|
||||
ap.add_argument("--steam-root")
|
||||
@@ -49,6 +183,10 @@ def main():
|
||||
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")
|
||||
ap.add_argument("--max-tag-pages", type=int, default=50,
|
||||
help="max Store pages fetched to resolve tag names (default: 50)")
|
||||
ap.add_argument("--tag-delay", type=float, default=0.4,
|
||||
help="delay between Store requests in seconds (default: 0.4)")
|
||||
ap.add_argument("--refresh-parents", action="store_true",
|
||||
help="update games.parent_appid from appinfo and exit")
|
||||
args = ap.parse_args()
|
||||
@@ -98,13 +236,23 @@ def main():
|
||||
return
|
||||
|
||||
existing_tags = {r["tag_id"]: r["name"] for r in con.execute("SELECT tag_id, name FROM tag_names")}
|
||||
existing_ru = {r["tag_id"] for r in con.execute(
|
||||
"SELECT tag_id FROM tag_names WHERE name_ru IS NOT NULL AND name_ru <> ''")}
|
||||
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)
|
||||
new_tags_ru = {}
|
||||
if not args.no_network:
|
||||
if 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)
|
||||
if args.refresh_tags or len(existing_tags) < 50 or len(existing_ru) < len(existing_tags):
|
||||
try:
|
||||
new_tags_ru = fetch_tag_names("russian")
|
||||
print(f"Tag translations downloaded: {len(new_tags_ru)}")
|
||||
except Exception as exc:
|
||||
print(f"Tag translation download skipped: {exc}", file=sys.stderr)
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
@@ -153,8 +301,14 @@ def main():
|
||||
report_every = max(1, total_apps // 20)
|
||||
with con:
|
||||
if new_tags:
|
||||
con.executemany("INSERT OR REPLACE INTO tag_names (tag_id, name) VALUES (?, ?)",
|
||||
new_tags.items())
|
||||
con.executemany(
|
||||
"""INSERT INTO tag_names (tag_id, name) VALUES (?, ?)
|
||||
ON CONFLICT(tag_id) DO UPDATE SET name = excluded.name""",
|
||||
new_tags.items())
|
||||
if new_tags_ru:
|
||||
con.executemany(
|
||||
"UPDATE tag_names SET name_ru = ? WHERE tag_id = ?",
|
||||
[(name, tag_id) for tag_id, name in new_tags_ru.items()])
|
||||
|
||||
for index, appid in enumerate(lib_ids, 1):
|
||||
pt = playtime.get(appid)
|
||||
@@ -210,16 +364,32 @@ def main():
|
||||
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,))
|
||||
|
||||
unnamed = missing_tag_ids(con)
|
||||
untranslated = untranslated_tag_ids(con)
|
||||
if (unnamed or untranslated) and not args.no_network:
|
||||
print(f"Tags without names/translations: {len(unnamed)}/{len(untranslated)}; "
|
||||
f"resolving from Store pages...")
|
||||
added_names, added_ru = resolve_missing_tag_names(
|
||||
con, max_pages=args.max_tag_pages, delay=args.tag_delay)
|
||||
unnamed = missing_tag_ids(con)
|
||||
untranslated = untranslated_tag_ids(con)
|
||||
print(f"Tag names resolved: +{added_names}, translations: +{added_ru} "
|
||||
f"(unnamed now: {len(unnamed)}, untranslated now: {len(untranslated)})")
|
||||
|
||||
db.refresh_search_index(con)
|
||||
db.refresh_duration_estimates(con)
|
||||
db.backfill_release_dates(con)
|
||||
|
||||
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")}
|
||||
named = con.execute("SELECT COUNT(*) FROM tag_names").fetchone()[0]
|
||||
translated = con.execute(
|
||||
"SELECT COUNT(*) FROM tag_names WHERE name_ru IS NOT NULL AND name_ru <> ''").fetchone()[0]
|
||||
con.close()
|
||||
|
||||
print(f"Processed: {new_count + updated_count} apps (new: {new_count}, existing: {updated_count}) -> {args.db}")
|
||||
print(f"By type: {counts}")
|
||||
print(f"Tags: {named} named ({translated} ru), {len(unnamed)} unnamed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user