more data

This commit is contained in:
2026-11-27 13:30:59 +01:00
parent a2fe1de359
commit 321342762c
2573 changed files with 1659852 additions and 1104 deletions
+103 -55
View File
@@ -41,10 +41,8 @@ DATA_DIR = Path("data")
PART_DIR = DATA_DIR / ".partial"
CHECKPOINT_EVERY = 25 # pages
APPIDS = list(range(3760000, 4000001)) # 3600000 through 3601000 inclusive (1001 ids)
stop = threading.Event()
APPIDS = list(range(3000000, 4000001, 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."""
@@ -185,6 +183,8 @@ class Progress:
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):
@@ -224,8 +224,8 @@ class Progress:
self.finished[appid] = n
# -- rendering
def _snapshot_lines(self):
cols = shutil.get_terminal_size((100, 20)).columns
def _snapshot_lines(self, cols, rows):
now = time.time()
with self.lock:
total = sum(self.totals.values())
@@ -233,48 +233,59 @@ class Progress:
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
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 = len(self.failed)
probed = self.n_probed
kept = len(self.totals)
fails, probed, kept = len(self.failed), self.n_probed, len(self.totals)
w = max(10, min(30, cols - 75))
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:,} reviews"
f" probed {probed}/{self.n_candidates} kept {kept} done {apps_done}"
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" | limit {limiter.rate:.1f} req/s reqs {limiter.requests:,}"
f" throttled {limiter.throttled}",
f"{rate:,.0f} rev/s elapsed {fmt_time(elapsed)} ETA {fmt_time(eta)} | "
f"{limiter.rate:.0f} req/s throttled {limiter.throttled}",
]
for appid, a in active:
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, w)}] {fr * 100:5.1f}% "
f"{a['done']:>9,}/{a['total']:<9,} {r:5.0f}/s ETA {fmt_time(e)}")
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):
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)
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
@@ -296,26 +307,49 @@ class Progress:
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)
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 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)
@@ -422,13 +456,27 @@ def download(appid, prog):
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=8, help="apps in parallel (default 8)")
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)")