first
This commit is contained in:
+188
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Scan Steam app IDs, fetch review metadata, and save the IDs whose positive-review
|
||||
percentage is near a target (default 20 / 40 / 70) with at least N reviews (default 500).
|
||||
|
||||
Usage examples:
|
||||
python steam_scan.py --start 10 --end 3000000 --step 10
|
||||
python steam_scan.py --ids-file my_ids.txt # one appid per line instead of incrementing
|
||||
python steam_scan.py --targets 20 40 70 --tolerance 2 --min-reviews 1000
|
||||
|
||||
Output (in --out, default ./steam_out):
|
||||
interesting.csv matching games (appended as found)
|
||||
state.json checkpoint, so re-running resumes where it stopped
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
URL = "https://store.steampowered.com/appreviews/{appid}"
|
||||
FIELDS = ["appid", "bucket", "pct_positive", "positive", "negative",
|
||||
"total", "review_score_desc", "store_url"]
|
||||
|
||||
|
||||
def fetch_summary(session, appid, retries=6):
|
||||
"""Return the query_summary dict, or None if the app doesn't exist / has no data."""
|
||||
wait = 5
|
||||
for _ in range(retries):
|
||||
try:
|
||||
r = session.get(
|
||||
URL.format(appid=appid),
|
||||
params={"json": 1, "language": "all", "purchase_type": "all",
|
||||
"num_per_page": 0, "filter": "all"},
|
||||
timeout=20,
|
||||
)
|
||||
except requests.RequestException:
|
||||
time.sleep(wait)
|
||||
wait = min(wait * 2, 300)
|
||||
continue
|
||||
if r.status_code == 429: # rate limited -> back off
|
||||
print(f" rate limited, sleeping {wait}s", file=sys.stderr)
|
||||
time.sleep(wait)
|
||||
wait = min(wait * 2, 300)
|
||||
continue
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
return None
|
||||
if data.get("success") != 1:
|
||||
return None
|
||||
return data.get("query_summary")
|
||||
raise RuntimeError(f"Giving up on appid {appid} after {retries} retries")
|
||||
|
||||
|
||||
def pick_bucket(pct, targets, tol):
|
||||
best = min(targets, key=lambda t: abs(pct - t))
|
||||
return best if abs(pct - best) <= tol else None
|
||||
|
||||
|
||||
def load_state(path):
|
||||
if os.path.exists(path):
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
return {"last_id": None}
|
||||
|
||||
|
||||
def save_state(path, last_id):
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump({"last_id": last_id}, f)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def id_stream(args, last_id):
|
||||
if args.ids_file:
|
||||
with open(args.ids_file) as f:
|
||||
ids = [int(line.strip()) for line in f if line.strip().isdigit()]
|
||||
if last_id is not None:
|
||||
ids = [i for i in ids if i > last_id]
|
||||
yield from ids
|
||||
else:
|
||||
start = args.start if last_id is None else max(args.start, last_id + args.step)
|
||||
yield from range(start, args.end, args.step)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--start", type=int, default=10)
|
||||
p.add_argument("--end", type=int, default=3_000_000)
|
||||
p.add_argument("--step", type=int, default=10, help="Steam app IDs are almost all multiples of 10")
|
||||
p.add_argument("--ids-file", help="read app IDs from a file instead of incrementing")
|
||||
p.add_argument("--targets", type=float, nargs="+", default=[20, 40, 70])
|
||||
p.add_argument("--tolerance", type=float, default=3.0, help="+/- percentage points")
|
||||
p.add_argument("--min-reviews", type=int, default=500)
|
||||
p.add_argument("--delay", type=float, default=1.0, help="seconds between requests")
|
||||
p.add_argument("--out", default="steam_out")
|
||||
args = p.parse_args()
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
csv_path = os.path.join(args.out, "interesting.csv")
|
||||
state_path = os.path.join(args.out, "state.json")
|
||||
|
||||
state = load_state(state_path)
|
||||
last_id = state["last_id"]
|
||||
if last_id is not None:
|
||||
print(f"Resuming after appid {last_id}")
|
||||
|
||||
new_file = not os.path.exists(csv_path)
|
||||
session = requests.Session()
|
||||
session.headers["User-Agent"] = "steam-review-scan/1.0"
|
||||
|
||||
found = scanned = 0
|
||||
current = last_id
|
||||
|
||||
# per-bucket match counters (seeded from the CSV so they survive a resume)
|
||||
bucket_counts = {t: 0 for t in args.targets}
|
||||
if not new_file:
|
||||
with open(csv_path, newline="") as rf:
|
||||
for row in csv.DictReader(rf):
|
||||
try:
|
||||
b = float(row["bucket"])
|
||||
except (KeyError, ValueError):
|
||||
continue
|
||||
if b in bucket_counts:
|
||||
bucket_counts[b] += 1
|
||||
|
||||
def counter_line(appid):
|
||||
per_bucket = " ".join(f"{t:g}%:{n}" for t, n in bucket_counts.items())
|
||||
return f"scanned {scanned} | appid {appid} | matches {found} this run | saved [{per_bucket}]"
|
||||
with open(csv_path, "a", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=FIELDS)
|
||||
if new_file:
|
||||
writer.writeheader()
|
||||
try:
|
||||
for appid in id_stream(args, last_id):
|
||||
current = appid
|
||||
summary = fetch_summary(session, appid)
|
||||
scanned += 1
|
||||
|
||||
if summary:
|
||||
pos = summary.get("total_positive", 0)
|
||||
neg = summary.get("total_negative", 0)
|
||||
total = pos + neg
|
||||
if total >= args.min_reviews:
|
||||
pct = 100 * pos / total
|
||||
bucket = pick_bucket(pct, args.targets, args.tolerance)
|
||||
if bucket is not None:
|
||||
writer.writerow({
|
||||
"appid": appid, "bucket": bucket,
|
||||
"pct_positive": round(pct, 1),
|
||||
"positive": pos, "negative": neg, "total": total,
|
||||
"review_score_desc": summary.get("review_score_desc", ""),
|
||||
"store_url": f"https://store.steampowered.com/app/{appid}/",
|
||||
})
|
||||
f.flush()
|
||||
found += 1
|
||||
bucket_counts[bucket] += 1
|
||||
sys.stdout.write("\r" + " " * 100 + "\r") # clear live counter line
|
||||
print(f"[MATCH] {appid}: {pct:.1f}% of {total} reviews (target {bucket:g}%)")
|
||||
|
||||
if scanned % 50 == 0:
|
||||
save_state(state_path, appid)
|
||||
sys.stdout.write("\r" + counter_line(appid)) # live counter
|
||||
sys.stdout.flush()
|
||||
time.sleep(args.delay)
|
||||
except KeyboardInterrupt:
|
||||
print("\nInterrupted.")
|
||||
except RuntimeError as e:
|
||||
print(e, file=sys.stderr)
|
||||
finally:
|
||||
if current is not None:
|
||||
# resume from the last fully processed id
|
||||
save_state(state_path, current)
|
||||
|
||||
print()
|
||||
print(f"Done. Scanned {scanned}, saved {found} new matches to {csv_path}")
|
||||
for t, n in bucket_counts.items():
|
||||
print(f" {t:g}% bucket: {n} total saved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user