This commit is contained in:
2026-11-27 00:13:33 +01:00
parent efce8a1b58
commit 58efbeaea8
152 changed files with 29942 additions and 91 deletions
+68 -42
View File
@@ -41,8 +41,7 @@ DATA_DIR = Path("data")
PART_DIR = DATA_DIR / ".partial"
CHECKPOINT_EVERY = 25 # pages
APPIDS = []
APPIDS = list(range(3640000, 3700001)) # 3600000 through 3601000 inclusive (1001 ids)
stop = threading.Event()
@@ -103,7 +102,6 @@ class Stopped(Exception):
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():
@@ -119,6 +117,8 @@ def get_json(params, max_tries=8):
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))
@@ -137,29 +137,19 @@ def get_json(params, max_tries=8):
raise RuntimeError("Steam kept returning bad responses")
def query(appid, cursor="*", per_page=100):
def query(appid, cursor="*", per_page=100, max_tries=8):
return get_json({"input_json": json.dumps({
"appid": appid,
"filter": 1, # 1 = Recent
"filter": 1,
"languages": ["all"],
"review_type": 0, # all reviews
"purchase_type": 1, # all purchase types (incl. key activations)
"filter_offtopic_activity": False, # keep review-bomb days
"review_type": 0,
"purchase_type": 1,
"filter_offtopic_activity": False,
"num_per_page": per_page,
"cursor": cursor,
})})
})}, max_tries=max_tries)
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):
@@ -180,10 +170,12 @@ def bar(frac, width):
class Progress:
"""Thread-safe state + a redraw thread. Live dashboard on a TTY, periodic log lines otherwise."""
def __init__(self, totals, n_apps):
def __init__(self, n_candidates):
self.lock = threading.Lock()
self.totals = totals # appid -> total reviews (for apps still to do)
self.n_apps = n_apps
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 = {}
@@ -195,6 +187,20 @@ class Progress:
self._thread = threading.Thread(target=self._loop, daemon=True)
# -- 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),
@@ -210,10 +216,12 @@ class Progress:
def finish(self, appid, n, ok=True, err=None):
with self.lock:
self.active.pop(appid, None)
if ok:
self.finished[appid] = n
else:
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):
@@ -229,12 +237,15 @@ class Progress:
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)
probed = self.n_probed
kept = len(self.totals)
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" 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" | limit {limiter.rate:.1f} req/s reqs {limiter.requests:,}"
f" throttled {limiter.throttled}",
@@ -296,6 +307,25 @@ class Progress:
else:
print(msg, file=sys.stderr)
def probe_total(appid):
"""Total review count, or None if the probe failed."""
try:
resp = query(appid, per_page=1, max_tries=3).get("response", {})
return int((resp.get("query_summary") or {}).get("total_reviews") or 0)
except Stopped:
raise
except Exception:
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):
@@ -340,7 +370,7 @@ def download(appid, prog):
summary = resp["query_summary"]
if summary.get("total_reviews"):
total = int(summary["total_reviews"])
prog.active[appid]["total"] = total
prog.set_total(appid, total)
if not reviews:
break
@@ -398,8 +428,10 @@ 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)")
ap.add_argument("--workers", type=int, default=8, help="apps in parallel (default 8)")
ap.add_argument("--rate", type=float, default=10, 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)
@@ -414,23 +446,16 @@ def main():
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 = Progress(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}
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())
prog.finish(a, fut.result()) # None => skipped
except Stopped:
prog.finish(a, 0, ok=False, err="stopped")
except Exception as e:
@@ -444,14 +469,15 @@ def main():
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("\nNot finished (re-run to resume from checkpoints):", file=sys.stderr)
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()
main()