first
This commit is contained in:
@@ -0,0 +1,467 @@
|
||||
#!/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 = [
|
||||
3024130, 1118200, 477160, 363970, 527230, 387990, 2646460, 976730, 2116120,
|
||||
3024040, 2113850, 1282270, 2223980, 3065800, 1353300,960170, 5027520, 72850,
|
||||
203770, 2333000, 3552140, 2439510, 1683150, 2744880, 814380, 1799840, 2622000,
|
||||
2054970, 2479810, 1366540,3609080, 305620, 1604270, 214950, 4564320, 1328670,
|
||||
568220, 3595270, 1149460, 990080, 4128580, 2325290, 3590, 883710, 1659040, 4282500,
|
||||
499170, 3687090, 1057090, 3285880, 412220, 3432860, 5228920, 203160, 1167630, 750920,
|
||||
413410, 208650, 2835570, 3164330, 477160, 3478870, 418370, 5027520, 5189500, 2475460,
|
||||
3330, 2187220, 920210, 2129530, 2903690, 1435670, 1433420, 1802880, 496620, 839310, 2738380, 2494780,
|
||||
70620, 232430, 1924480, 3739730, 1100930, 720380, 1286340, 1104340, 242840, 525360, 629090,
|
||||
]
|
||||
|
||||
stop = threading.Event()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- 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):
|
||||
"""Rate-limited GET with backoff. Returns parsed JSON or raises."""
|
||||
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
|
||||
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):
|
||||
return get_json({"input_json": json.dumps({
|
||||
"appid": appid,
|
||||
"filter": 1, # 1 = Recent
|
||||
"languages": ["all"],
|
||||
"review_type": 0, # all reviews
|
||||
"purchase_type": 1, # all purchase types (incl. key activations)
|
||||
"filter_offtopic_activity": False, # keep review-bomb days
|
||||
"num_per_page": per_page,
|
||||
"cursor": cursor,
|
||||
})})
|
||||
|
||||
|
||||
def probe_total(appid):
|
||||
"""Cheap request to learn how many reviews an app has (0 if unknown)."""
|
||||
try:
|
||||
resp = query(appid, per_page=1).get("response", {})
|
||||
return int((resp.get("query_summary") or {}).get("total_reviews") or 0)
|
||||
except Stopped:
|
||||
raise
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- 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, totals, n_apps):
|
||||
self.lock = threading.Lock()
|
||||
self.totals = totals # appid -> total reviews (for apps still to do)
|
||||
self.n_apps = n_apps
|
||||
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)
|
||||
|
||||
# -- updates from workers
|
||||
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 ok:
|
||||
self.finished[appid] = n
|
||||
else:
|
||||
self.failed[appid] = err
|
||||
|
||||
# -- rendering
|
||||
def _snapshot_lines(self):
|
||||
cols = shutil.get_terminal_size((100, 20)).columns
|
||||
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
|
||||
remaining = max(total - done, 0)
|
||||
eta = remaining / rate if rate > 0 and total else None
|
||||
active = sorted(self.active.items(), key=lambda kv: -kv[1]["total"])
|
||||
fails = len(self.failed)
|
||||
|
||||
w = max(10, min(30, cols - 75))
|
||||
frac = done / total if total else 0
|
||||
lines = [
|
||||
f"Overall [{bar(frac, w)}] {frac * 100:5.1f}% {done:,}/{total:,} reviews"
|
||||
f" apps {apps_done}/{self.n_apps}" + (f" failed {fails}" if fails else ""),
|
||||
f" {rate:,.0f} rev/s elapsed {fmt_time(elapsed)} ETA {fmt_time(eta)}"
|
||||
f" | limit {limiter.rate:.1f} req/s reqs {limiter.requests:,}"
|
||||
f" throttled {limiter.throttled}",
|
||||
]
|
||||
for appid, a in 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, w)}] {fr * 100:5.1f}% "
|
||||
f"{a['done']:>9,}/{a['total']:<9,} {r:5.0f}/s ETA {fmt_time(e)}")
|
||||
return [ln[:cols - 1] for ln in lines]
|
||||
|
||||
def _draw(self):
|
||||
lines = self._snapshot_lines()
|
||||
out = []
|
||||
if self._drawn:
|
||||
out.append(f"\033[{self._drawn}A")
|
||||
for ln in lines:
|
||||
out.append("\033[2K" + ln + "\n")
|
||||
# clear leftover lines from a taller previous frame
|
||||
for _ in range(max(0, self._drawn - len(lines))):
|
||||
out.append("\033[2K\n")
|
||||
extra = max(0, self._drawn - len(lines))
|
||||
if extra:
|
||||
out.append(f"\033[{extra}A")
|
||||
sys.stderr.write("".join(out))
|
||||
sys.stderr.flush()
|
||||
self._drawn = len(lines)
|
||||
|
||||
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 log(self, msg):
|
||||
"""Print a message above the dashboard without garbling it."""
|
||||
if self.tty and self._drawn:
|
||||
sys.stderr.write(f"\033[{self._drawn}A\033[2K{msg}\n")
|
||||
sys.stderr.write("\n" * self._drawn) # push dashboard back down
|
||||
sys.stderr.write(f"\033[{self._drawn}A")
|
||||
sys.stderr.flush()
|
||||
self._draw()
|
||||
else:
|
||||
print(msg, file=sys.stderr)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- 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.active[appid]["total"] = 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
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- 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=8, help="apps in parallel (default 3)")
|
||||
ap.add_argument("--rate", type=float, default=10, help="global requests/sec (default 2.5)")
|
||||
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:
|
||||
# Probe totals so we can start the biggest apps first and show real percentages.
|
||||
print(f"Probing {len(todo)} apps for review totals...", file=sys.stderr)
|
||||
totals = {}
|
||||
for a in todo:
|
||||
totals[a] = probe_total(a)
|
||||
todo.sort(key=lambda a: -totals[a])
|
||||
|
||||
prog = Progress(totals, len(todo))
|
||||
prog.start_display()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as ex:
|
||||
futures = {ex.submit(download, a, prog): a for a in todo}
|
||||
try:
|
||||
for fut in as_completed(futures):
|
||||
a = futures[fut]
|
||||
try:
|
||||
prog.finish(a, fut.result())
|
||||
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()
|
||||
|
||||
if prog.failed:
|
||||
print("\nNot finished (re-run to resume from checkpoints):", 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()
|
||||
Reference in New Issue
Block a user