remove bloat
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
"""
|
||||
Download classification, price and genres for every game in data/.
|
||||
Fast version: bulk price lookups + parallel workers behind a shared rate limiter.
|
||||
|
||||
- Game ids come from the file names in data/ (e.g. data/730.csv -> app id 730).
|
||||
- A row is complete when it has price AND genres. Incomplete or missing rows are (re)fetched,
|
||||
so the script can be stopped and re-run, and old files without a genres column are upgraded.
|
||||
- Writes game_tags.csv: sheet, group, name, categories, price, currency, genres
|
||||
group = sp / mp / both / unknown (from Steam store "categories")
|
||||
price = base price before discount, 0 if free, "NA" if no price listed
|
||||
genres = Steam store genres joined by ";" ("none" if the store lists none)
|
||||
|
||||
Install: pip install requests
|
||||
"""
|
||||
import csv
|
||||
import glob
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import requests
|
||||
|
||||
DATA_GLOB = "data/*.csv"
|
||||
OUT = "game_tags.csv"
|
||||
API = "https://store.steampowered.com/api/appdetails"
|
||||
CC = "us"
|
||||
MIN_INTERVAL = 1.3 # global seconds between requests, shared by all workers
|
||||
WORKERS = 4
|
||||
BULK_SIZE = 100 # max ids per price_overview request
|
||||
SAVE_EVERY = 25
|
||||
FIELDS = ["sheet", "group", "name", "categories", "price", "currency", "genres"]
|
||||
|
||||
MP_CATS = {"multi-player", "co-op", "online co-op", "pvp", "online pvp", "mmo",
|
||||
"cross-platform multiplayer"}
|
||||
SP_CATS = {"single-player"}
|
||||
|
||||
session = requests.Session()
|
||||
_lock = threading.Lock()
|
||||
_next_slot = 0.0 # earliest time the next request may start
|
||||
|
||||
|
||||
def wait_slot(extra_pause=0.0):
|
||||
"""Reserve the next global request slot (thread safe) and sleep until it."""
|
||||
global _next_slot
|
||||
with _lock:
|
||||
now = time.monotonic()
|
||||
if extra_pause:
|
||||
_next_slot = max(_next_slot, now + extra_pause)
|
||||
start = max(now, _next_slot)
|
||||
_next_slot = start + MIN_INTERVAL
|
||||
time.sleep(max(0, start - now))
|
||||
|
||||
|
||||
def get_json(params):
|
||||
for attempt in range(5):
|
||||
wait_slot()
|
||||
try:
|
||||
r = session.get(API, params={**params, "l": "english", "cc": CC}, timeout=20)
|
||||
if r.status_code == 429:
|
||||
wait_slot(extra_pause=60 * (attempt + 1)) # pauses every worker
|
||||
continue
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except (requests.RequestException, ValueError):
|
||||
time.sleep(3 * (attempt + 1))
|
||||
return None
|
||||
|
||||
|
||||
def ids_from_files():
|
||||
ids = []
|
||||
for path in sorted(glob.glob(DATA_GLOB)):
|
||||
stem = os.path.splitext(os.path.basename(path))[0]
|
||||
if stem.isdigit():
|
||||
ids.append(stem)
|
||||
else:
|
||||
print(f"skipping {path}: file name is not a numeric app id")
|
||||
return ids
|
||||
|
||||
|
||||
def load_rows():
|
||||
"""Existing rows keyed by sheet; columns missing in an old file load as blanks."""
|
||||
if not os.path.exists(OUT):
|
||||
return {}
|
||||
with open(OUT, newline="", encoding="utf-8") as f:
|
||||
return {row["sheet"]: {k: row.get(k) or "" for k in FIELDS} for row in csv.DictReader(f)}
|
||||
|
||||
|
||||
def save_rows(rows):
|
||||
tmp = OUT + ".tmp"
|
||||
with open(tmp, "w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=FIELDS)
|
||||
writer.writeheader()
|
||||
writer.writerows(rows.values())
|
||||
os.replace(tmp, OUT)
|
||||
|
||||
|
||||
def classify(categories):
|
||||
cats = {c.lower() for c in categories}
|
||||
mp, sp = bool(cats & MP_CATS), bool(cats & SP_CATS)
|
||||
if mp and sp:
|
||||
return "both"
|
||||
if mp:
|
||||
return "mp"
|
||||
if sp:
|
||||
return "sp"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def get_price(data):
|
||||
if data.get("is_free"):
|
||||
return 0, ""
|
||||
po = data.get("price_overview")
|
||||
if po:
|
||||
return round(po["initial"] / 100, 2), po.get("currency", "")
|
||||
return "NA", ""
|
||||
|
||||
|
||||
def needs_fetch(rows, appid):
|
||||
r = rows.get(appid)
|
||||
return r is None or r["price"] == "" or r["genres"] == ""
|
||||
|
||||
|
||||
def bulk_prices(ids):
|
||||
"""{appid: (price, currency)} for ids that have a price_overview. 100 ids per request."""
|
||||
out = {}
|
||||
for i in range(0, len(ids), BULK_SIZE):
|
||||
chunk = ids[i:i + BULK_SIZE]
|
||||
js = get_json({"appids": ",".join(chunk), "filters": "price_overview"})
|
||||
if js is None:
|
||||
print(f"bulk price batch {i // BULK_SIZE + 1} failed, those ids fall back to single requests")
|
||||
continue
|
||||
for appid, entry in js.items():
|
||||
data = entry.get("data") if entry.get("success") else None
|
||||
if isinstance(data, dict) and data.get("price_overview"):
|
||||
po = data["price_overview"]
|
||||
out[appid] = (round(po["initial"] / 100, 2), po.get("currency", ""))
|
||||
print(f"bulk prices: {min(i + BULK_SIZE, len(ids))}/{len(ids)}")
|
||||
return out
|
||||
|
||||
|
||||
def fetch_full(appid):
|
||||
"""(appid, data dict), data = {} if Steam has no store entry, None on a temporary failure."""
|
||||
js = get_json({"appids": appid})
|
||||
if js is None:
|
||||
return appid, None
|
||||
try:
|
||||
entry = js[appid]
|
||||
return appid, (entry["data"] if entry.get("success") else {})
|
||||
except (KeyError, TypeError):
|
||||
return appid, None
|
||||
|
||||
|
||||
def main():
|
||||
ids = ids_from_files()
|
||||
rows = load_rows()
|
||||
need = [i for i in ids if needs_fetch(rows, i)]
|
||||
print(f"{len(ids)} games in data/, {len(ids) - len(need)} complete, {len(need)} to fetch")
|
||||
|
||||
# Step 1: rows that already have genres but miss only the price -> bulk lookup.
|
||||
# (Genres need the full request, so rows missing genres skip this step.)
|
||||
price_only = [i for i in need if i in rows and rows[i]["genres"] != ""]
|
||||
prices = bulk_prices(price_only) if price_only else {}
|
||||
for appid, (price, cur) in prices.items():
|
||||
rows[appid]["price"], rows[appid]["currency"] = price, cur
|
||||
if prices:
|
||||
save_rows(rows)
|
||||
|
||||
# Step 2: everything else (new ids, missing genres, free/unlisted games) -> full request
|
||||
todo = [i for i in need if i not in prices]
|
||||
print(f"{len(todo)} need a full request "
|
||||
f"(about {len(todo) * MIN_INTERVAL / 60:.0f} min at the shared rate limit)")
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(WORKERS) as pool:
|
||||
futures = [pool.submit(fetch_full, i) for i in todo]
|
||||
for n, fut in enumerate(as_completed(futures), 1):
|
||||
appid, data = fut.result()
|
||||
if data is None:
|
||||
print(f"[{n}/{len(todo)}] {appid}: request failed, will retry on next run")
|
||||
continue
|
||||
cats = [c["description"] for c in data.get("categories", [])]
|
||||
genres = [g["description"] for g in data.get("genres", [])]
|
||||
price, currency = get_price(data)
|
||||
rows[appid] = {"sheet": appid, "group": classify(cats), "name": data.get("name", ""),
|
||||
"categories": ";".join(cats), "price": price, "currency": currency,
|
||||
"genres": ";".join(genres) or "none"}
|
||||
print(f"[{n}/{len(todo)}] {appid} {data.get('name', '?')}: {rows[appid]['group']}, "
|
||||
f"{price} {currency}, {rows[appid]['genres']}")
|
||||
if n % SAVE_EVERY == 0:
|
||||
save_rows(rows)
|
||||
finally:
|
||||
save_rows(rows)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user