Files
Valve_research/parr_download.py
T
2026-12-01 09:25:04 +01:00

532 lines
19 KiB
Python

#!/usr/bin/env python3
"""
Daily positive/negative Steam review counts for many apps, from first review until now.
Uses Valve's IUserReviewsService/GetAppReviews (the old store.steampowered.com/appreviews
JSON endpoint was switched off on 22 Oct 2026).
Speed-ups (all bounded by ONE global rate limiter, so more workers can't hammer Steam):
* different apps download in parallel (pages inside one app stay sequential: cursor chain)
* adaptive limiter: slows down on 429/5xx (honours Retry-After), creeps back up on success
* biggest apps start first (cheap 1-review probe per app gets total_reviews)
* checkpoints every N pages -> Ctrl-C or a crash resumes mid-app instead of from zero
Usage:
python steam_daily_reviews.py # use the built-in APPIDS list
python steam_daily_reviews.py 2139460 304930 # only these apps
python steam_daily_reviews.py --workers 4 --rate 3
"""
import argparse
import csv
import json
import os
import random
import shutil
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path
import requests
URL = "https://api.steampowered.com/IUserReviewsService/GetAppReviews/v1/"
HEADERS = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0 Safari/537.36",
}
DATA_DIR = Path("data")
PART_DIR = DATA_DIR / ".partial"
CHECKPOINT_EVERY = 25 # pages
APPIDS = list(range(2000000, 4000000, 10))
stop = threading.Event() # <- this line is probably missing now
# --------------------------------------------------------------------------- limiter
class RateLimiter:
"""Global limiter: at most ~`rate` requests/sec across all threads, self-adjusting."""
def __init__(self, rate):
self.base_interval = 1.0 / rate
self.interval = self.base_interval
self.lock = threading.Lock()
self.next_time = 0.0
self.requests = 0
self.throttled = 0
def wait(self):
with self.lock:
now = time.monotonic()
t = max(self.next_time, now)
self.next_time = t + self.interval
self.requests += 1
delay = t - now
if delay > 0:
time.sleep(delay)
def slow_down(self, factor=1.5, max_interval=5.0, pause=0.0):
with self.lock:
self.throttled += 1
self.interval = min(self.interval * factor, max_interval)
if pause: # push everyone back, not just this thread
self.next_time = max(self.next_time, time.monotonic() + pause)
def success(self):
"""Creep back toward the configured rate after good responses."""
with self.lock:
if self.interval > self.base_interval:
self.interval = max(self.base_interval, self.interval * 0.98)
@property
def rate(self):
return 1.0 / self.interval
limiter = None # set in main()
_local = threading.local()
def get_session():
if not hasattr(_local, "s"):
s = requests.Session()
s.headers.update(HEADERS)
_local.s = s
return _local.s
class Stopped(Exception):
pass
def get_json(params, max_tries=8):
delay = 2.0
for attempt in range(1, max_tries + 1):
if stop.is_set():
raise Stopped()
limiter.wait()
retry_after = 0.0
try:
r = get_session().get(URL, params=params, timeout=30)
if r.status_code == 200 and r.text.strip():
try:
data = r.json()
limiter.success()
return data
except ValueError:
pass
elif r.status_code in (400, 403, 404): # won't get better by retrying
raise RuntimeError(f"HTTP {r.status_code}")
if r.status_code in (429, 500, 502, 503, 504):
try:
retry_after = float(r.headers.get("Retry-After", 0))
except ValueError:
retry_after = 0.0
limiter.slow_down(pause=retry_after)
except requests.RequestException:
limiter.slow_down(factor=1.2)
sleep_for = max(delay, retry_after) + random.uniform(0, 1)
end = time.monotonic() + sleep_for
while time.monotonic() < end: # interruptible sleep
if stop.is_set():
raise Stopped()
time.sleep(0.25)
delay = min(delay * 2, 60)
raise RuntimeError("Steam kept returning bad responses")
def query(appid, cursor="*", per_page=100, max_tries=8):
return get_json({"input_json": json.dumps({
"appid": appid,
"filter": 1,
"languages": ["all"],
"review_type": 0,
"purchase_type": 1,
"filter_offtopic_activity": False,
"num_per_page": per_page,
"cursor": cursor,
})}, max_tries=max_tries)
# --------------------------------------------------------------------------- progress
def fmt_time(sec):
if sec is None or sec != sec or sec == float("inf"):
return "--"
sec = int(sec)
h, rem = divmod(sec, 3600)
m, s = divmod(rem, 60)
return f"{h}h{m:02d}m" if h else f"{m}m{s:02d}s"
def bar(frac, width):
frac = max(0.0, min(frac, 1.0))
filled = int(width * frac)
return "█" * filled + "░" * (width - filled)
class Progress:
"""Thread-safe state + a redraw thread. Live dashboard on a TTY, periodic log lines otherwise."""
def __init__(self, n_candidates):
self.lock = threading.Lock()
self.totals = {} # only apps that passed the filter
self.n_candidates = n_candidates
self.n_probed = 0
self.n_skipped = 0
self.active = {} # appid -> dict(done, total, start, base)
self.finished = {} # appid -> reviews
self.failed = {}
self.session_fetched = 0
self.start = time.time()
self.tty = sys.stderr.isatty()
self._drawn = 0
self._done_evt = threading.Event()
self._thread = threading.Thread(target=self._loop, daemon=True)
self.draw_lock = threading.Lock()
self._prev_lines = []
# -- updates from workers
def probed(self):
with self.lock:
self.n_probed += 1
def add_app(self, appid, total):
with self.lock:
self.totals[appid] = total
def set_total(self, appid, total):
with self.lock:
self.totals[appid] = total
if appid in self.active:
self.active[appid]["total"] = total
def begin(self, appid, done, total):
with self.lock:
self.active[appid] = {"done": done, "total": total or self.totals.get(appid, 0),
"start": time.time(), "base": done}
def tick(self, appid, done, fetched_now):
with self.lock:
a = self.active.get(appid)
if a:
a["done"] = done
self.session_fetched += fetched_now
def finish(self, appid, n, ok=True, err=None):
with self.lock:
self.active.pop(appid, None)
if not ok:
self.failed[appid] = err
elif n is None:
self.n_skipped += 1
else:
self.finished[appid] = n
# -- rendering
def _snapshot_lines(self, cols, rows):
now = time.time()
with self.lock:
total = sum(self.totals.values())
done = sum(self.finished.values()) + sum(a["done"] for a in self.active.values())
apps_done = len(self.finished)
elapsed = max(now - self.start, 1e-6)
rate = self.session_fetched / elapsed
eta = max(total - done, 0) / rate if rate > 0 and total else None
active = sorted(self.active.items(), key=lambda kv: -kv[1]["total"])
fails, probed, kept = len(self.failed), self.n_probed, len(self.totals)
w = max(10, min(30, cols - 60))
frac = done / total if total else 0
lines = [
f"Overall [{bar(frac, w)}] {frac*100:5.1f}% {done:,}/{total:,}",
f"probed {probed}/{self.n_candidates} kept {kept} done {apps_done}"
+ (f" failed {fails}" if fails else ""),
f"{rate:,.0f} rev/s elapsed {fmt_time(elapsed)} ETA {fmt_time(eta)} | "
f"{limiter.rate:.0f} req/s throttled {limiter.throttled}",
]
max_active = max(0, rows - len(lines) - 3) # leave room so it never exceeds the screen
for appid, a in active[:max_active]:
fr = a["done"] / a["total"] if a["total"] else 0
el = max(now - a["start"], 1e-6)
r = (a["done"] - a["base"]) / el
e = (a["total"] - a["done"]) / r if r > 0 and a["total"] else None
lines.append(f"{appid:>8} [{bar(fr, 12)}] {fr*100:4.0f}% "
f"{a['done']:,}/{a['total']:,} {r:.0f}/s {fmt_time(e)}")
if len(active) > max_active:
lines.append(f"... +{len(active) - max_active} more active")
return [ln[:cols - 1] for ln in lines]
def _erase(self):
"""Move to the top of the previous frame and clear everything below it."""
cols = shutil.get_terminal_size((100, 20)).columns
# rows the old frame occupies at the CURRENT width (handles resize/reflow)
rows = sum(max(1, -(-len(l) // cols)) for l in self._prev_lines)
if rows:
sys.stderr.write(f"\033[{rows}F")
sys.stderr.write("\033[J")
self._prev_lines = []
def _draw(self):
with self.draw_lock:
cols, rows = shutil.get_terminal_size((100, 20))
lines = self._snapshot_lines(cols, rows)
self._erase()
sys.stderr.write("\n".join(lines) + "\n")
sys.stderr.flush()
self._prev_lines = lines
def log(self, msg):
if self.tty:
with self.draw_lock:
self._erase()
sys.stderr.write(msg + "\n")
sys.stderr.flush()
self._draw()
else:
print(msg, file=sys.stderr)
def _loop(self):
last_log = 0
while not self._done_evt.wait(0.5):
if self.tty:
self._draw()
elif time.time() - last_log >= 30:
last_log = time.time()
print(" | ".join(self._snapshot_lines()[:2]), file=sys.stderr)
def start_display(self):
self._thread.start()
def stop_display(self):
self._done_evt.set()
self._thread.join()
if self.tty:
self._draw()
else:
print(" | ".join(self._snapshot_lines()[:2]), file=sys.stderr)
def probe_total(appid, max_tries=3):
"""Review count; 0 for non-apps / no reviews; None only on transient failure."""
params = {"input_json": json.dumps({
"appid": appid, "filter": 1, "languages": ["all"], "review_type": 0,
"purchase_type": 1, "num_per_page": 1, "cursor": "*"})}
empty_seen = False
for attempt in range(max_tries):
if stop.is_set():
raise Stopped()
limiter.wait()
try:
r = get_session().get(URL, params=params, timeout=10)
except requests.RequestException:
limiter.slow_down(factor=1.2)
time.sleep(1 + attempt)
continue
if r.status_code in (429, 500, 502, 503, 504): # transient: back off, retry
try:
ra = float(r.headers.get("Retry-After", 0))
except ValueError:
ra = 0.0
limiter.slow_down(pause=ra)
time.sleep(max(2.0, ra) + random.random())
continue
if r.status_code in (400, 403, 404): # definitive: not an app
return 0
if r.status_code == 200:
if not r.text.strip(): # empty body: retry once, then accept
if empty_seen:
return 0
empty_seen = True
continue
try:
resp = r.json().get("response", {})
except ValueError:
continue
limiter.success()
return int((resp.get("query_summary") or {}).get("total_reviews") or 0)
return None
def process(appid, prog, min_reviews):
total = probe_total(appid)
prog.probed()
if total is None:
raise RuntimeError("probe failed") # shows up in the re-run list
if total < min_reviews:
return None # skipped, too few reviews
prog.add_app(appid, total)
return download(appid, prog)
# --------------------------------------------------------------------------- checkpoints
def part_path(appid):
return PART_DIR / f"{appid}.json"
def save_checkpoint(appid, cursor, daily, n, total):
tmp = part_path(appid).with_suffix(".json.tmp")
payload = {"cursor": cursor, "n": n, "total": total,
"daily": {d.isoformat(): v for d, v in daily.items()}}
with open(tmp, "w") as f:
json.dump(payload, f)
os.replace(tmp, part_path(appid))
def load_checkpoint(appid):
try:
with open(part_path(appid)) as f:
p = json.load(f)
daily = {datetime.fromisoformat(d).date(): list(v) for d, v in p["daily"].items()}
return p["cursor"], daily, int(p["n"]), p.get("total")
except (OSError, ValueError, KeyError):
return "*", {}, 0, None
# --------------------------------------------------------------------------- download
def download(appid, prog):
cursor, daily_d, n, total = load_checkpoint(appid)
daily = {d: v for d, v in daily_d.items()}
seen_ids = set() # dedupe within this run (recent filter can shift pages)
seen_cursors = set()
prog.begin(appid, n, total)
pages = 0
summary = None
try:
while True:
data = query(appid, cursor)
resp = data.get("response", data)
reviews = resp.get("reviews") or []
if summary is None and resp.get("query_summary"):
summary = resp["query_summary"]
if summary.get("total_reviews"):
total = int(summary["total_reviews"])
prog.set_total(appid, total)
if not reviews:
break
fetched = 0
for rv in reviews:
rid = rv.get("recommendationid")
if rid is not None:
if rid in seen_ids:
continue
seen_ids.add(rid)
ts = rv.get("timestamp_created") or rv.get("created") or rv.get("time_created")
up = rv.get("voted_up", rv.get("recommended"))
day = datetime.fromtimestamp(int(ts), tz=timezone.utc).date()
daily.setdefault(day, [0, 0])[0 if up else 1] += 1
n += 1
fetched += 1
prog.tick(appid, n, fetched)
cursor = resp.get("cursor")
pages += 1
if not cursor or cursor in seen_cursors:
break
seen_cursors.add(cursor)
if pages % CHECKPOINT_EVERY == 0:
save_checkpoint(appid, cursor, daily, n, total)
except BaseException:
# Stopped, crash, anything: keep what we have so a re-run resumes here.
if cursor and cursor != "*":
save_checkpoint(appid, cursor, daily, n, total)
raise
path = DATA_DIR / f"{appid}.csv"
tmp = path.with_suffix(".csv.tmp")
with open(tmp, "w", newline="") as f:
w = csv.writer(f)
w.writerow(["date", "positive", "negative", "total"])
for day in sorted(daily):
p, ng = daily[day]
w.writerow([day.isoformat(), p, ng, p + ng])
tmp.replace(path) # the .csv only appears once complete
try:
part_path(appid).unlink()
except FileNotFoundError:
pass
note = ""
if summary:
note = f" (Steam reports +{summary.get('total_positive')} / -{summary.get('total_negative')})"
prog.log(f"done {appid}: {len(daily)} days / {n:,} reviews{note}")
return n
def fetch_app_ids(key, lo, hi):
ids, last = set(), 0
while True:
r = requests.get(
"https://api.steampowered.com/IStoreService/GetAppList/v1/",
params={"key": key, "include_games": "true", "include_dlc": "false",
"include_software": "false", "include_videos": "false",
"include_hardware": "false", "max_results": 50000,
"last_appid": last}, timeout=30).json()["response"]
apps = r.get("apps", [])
ids.update(a["appid"] for a in apps if lo <= a["appid"] <= hi)
if not r.get("have_more_results"):
return sorted(ids)
last = r["last_appid"]
# --------------------------------------------------------------------------- main
def main():
global limiter
ap = argparse.ArgumentParser()
ap.add_argument("appids", nargs="*", type=int, help="app ids (default: built-in list)")
ap.add_argument("--workers", type=int, default=32, help="apps in parallel (default 8)")
ap.add_argument("--rate", type=float, default=500, help="global requests/sec (default 10)")
ap.add_argument("--min-reviews", type=int, default=500,
help="only download apps with at least this many total reviews (default 500)")
args = ap.parse_args()
limiter = RateLimiter(args.rate)
DATA_DIR.mkdir(exist_ok=True)
PART_DIR.mkdir(exist_ok=True)
appids = args.appids or APPIDS
todo = [a for a in dict.fromkeys(appids) if not (DATA_DIR / f"{a}.csv").exists()]
if len(appids) - len(todo):
print(f"Skipping {len(appids) - len(todo)} already downloaded, {len(todo)} to go")
if not todo:
return
try:
prog = Progress(len(todo))
prog.start_display()
try:
with ThreadPoolExecutor(max_workers=args.workers) as ex:
futures = {ex.submit(process, a, prog, args.min_reviews): a for a in todo}
try:
for fut in as_completed(futures):
a = futures[fut]
try:
prog.finish(a, fut.result()) # None => skipped
except Stopped:
prog.finish(a, 0, ok=False, err="stopped")
except Exception as e:
prog.finish(a, 0, ok=False, err=str(e))
prog.log(f"app {a} failed: {e}")
except KeyboardInterrupt:
stop.set()
prog.log("Ctrl-C: saving checkpoints and stopping...")
for f in futures:
f.cancel()
finally:
prog.stop_display()
print(f"\nProbed {prog.n_probed}, downloaded {len(prog.finished)}, "
f"skipped {prog.n_skipped} (<{args.min_reviews} reviews)", file=sys.stderr)
if prog.failed:
print("Not finished (re-run to resume / retry):", file=sys.stderr)
for a, e in prog.failed.items():
print(f" {a}: {e}", file=sys.stderr)
except (KeyboardInterrupt, Stopped):
stop.set()
print("\nInterrupted.", file=sys.stderr)
if __name__ == "__main__":
main()