analyse
This commit is contained in:
@@ -244,6 +244,8 @@ def fetch_json_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
|
||||
if not proxies.has_proxies:
|
||||
cooldown.hit()
|
||||
continue
|
||||
if exc.code == 404: # permanent: resource does not exist
|
||||
raise
|
||||
soft += 1
|
||||
if soft >= retries:
|
||||
raise
|
||||
@@ -280,6 +282,8 @@ def fetch_bytes_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
|
||||
if not proxies.has_proxies:
|
||||
cooldown.hit()
|
||||
continue
|
||||
if exc.code == 404: # permanent: resource does not exist
|
||||
raise
|
||||
soft += 1
|
||||
if soft >= retries:
|
||||
raise
|
||||
@@ -428,7 +432,7 @@ def cmd_trophies(args) -> int:
|
||||
try:
|
||||
maindeck, sideboard = fetch_deck(entry["aggregate_id"], entry["deck_index"],
|
||||
limiter, cooldown, proxies)
|
||||
valid = len(maindeck) == 40
|
||||
valid = len(maindeck) >= 40 # limited decks are 40+ cards (41, 42, ... are legal)
|
||||
if not valid:
|
||||
with lock:
|
||||
stats["invalid"] += 1
|
||||
@@ -477,7 +481,7 @@ def cmd_trophies(args) -> int:
|
||||
print("\n===== trophy fetch summary =====")
|
||||
print(f"index entries : {len(entries)}")
|
||||
print(f"new decks fetched : {stats['fetched']}")
|
||||
print(f" valid (40 cards) : {stats['valid']}")
|
||||
print(f" valid (>=40 cards): {stats['valid']}")
|
||||
print(f" invalid : {stats['invalid']}")
|
||||
print(f" failed : {stats['failed']}")
|
||||
print(f"total valid stored : {total_valid} -> {decks_path}")
|
||||
@@ -485,6 +489,76 @@ def cmd_trophies(args) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_draftdata(args) -> int:
|
||||
"""Fetch full per-pick draft replays (`/data/draft?draft_id=`) incl. pack contents."""
|
||||
stamp = datetime.now().strftime("%Y%m%d")
|
||||
out_dir = Path(args.out) if args.out else (DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "draftdata")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
ids: list[str] = []
|
||||
seen: set[str] = set()
|
||||
with Path(args.index).open(encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
did = json.loads(line)["aggregate_id"]
|
||||
if did not in seen:
|
||||
seen.add(did)
|
||||
ids.append(did)
|
||||
done = {p.stem for p in out_dir.glob("*.json")}
|
||||
pending = [d for d in ids if d not in done]
|
||||
if args.max_drafts:
|
||||
pending = pending[: args.max_drafts]
|
||||
|
||||
limiter = RateLimiter(args.rate)
|
||||
cooldown = Cooldown(args.cooldown)
|
||||
proxies = load_proxies(args)
|
||||
print(f"[draftdata] {len(ids)} ids, {len(done)} done, {len(pending)} pending", file=sys.stderr)
|
||||
|
||||
lock = threading.Lock()
|
||||
stats = {"ok": 0, "failed": 0, "missing": 0}
|
||||
missing: list[str] = []
|
||||
t0 = time.time()
|
||||
|
||||
def worker(did: str) -> None:
|
||||
try:
|
||||
data = fetch_json_rl(f"{BASE}/data/draft?draft_id={did}", limiter, cooldown, proxies)
|
||||
tmp = out_dir / f"{did}.json.part"
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
tmp.replace(out_dir / f"{did}.json")
|
||||
with lock:
|
||||
stats["ok"] += 1
|
||||
except HTTPError as exc:
|
||||
if exc.code == 404: # this draft has no pick replay
|
||||
with lock:
|
||||
missing.append(did)
|
||||
stats["missing"] += 1
|
||||
return
|
||||
with lock:
|
||||
stats["failed"] += 1
|
||||
print(f" [failed] {did}: {exc}", file=sys.stderr)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
with lock:
|
||||
stats["failed"] += 1
|
||||
print(f" [failed] {did}: {exc}", file=sys.stderr)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as pool:
|
||||
futures = [pool.submit(worker, d) for d in pending]
|
||||
for i, fut in enumerate(as_completed(futures), 1):
|
||||
fut.result()
|
||||
if not args.quiet and (i % 10 == 0 or i == len(futures)):
|
||||
el = time.time() - t0
|
||||
print(f" {i}/{len(futures)} ok={stats['ok']} missing={stats['missing']} "
|
||||
f"failed={stats['failed']} {i / el if el else 0:.1f}/s", file=sys.stderr)
|
||||
|
||||
if missing:
|
||||
(out_dir / "_missing.txt").write_text("\n".join(sorted(missing)) + "\n", encoding="utf-8")
|
||||
print(f"\n===== draftdata summary =====\nnew: {stats['ok']} missing(404): {stats['missing']} "
|
||||
f"failed: {stats['failed']} stored: {len(done) + stats['ok']}\n-> {out_dir}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_replays(args) -> int:
|
||||
"""Download the turn-by-turn GRE replay (gzip) for every game.
|
||||
|
||||
@@ -531,7 +605,14 @@ def cmd_replays(args) -> int:
|
||||
for g in games:
|
||||
fh.write(json.dumps(g, ensure_ascii=False) + "\n")
|
||||
|
||||
done = {p.name[: -len(".json.gz")] for p in out_dir.rglob("*.json.gz")}
|
||||
if args.selection_file:
|
||||
want = [ln.strip() for ln in Path(args.selection_file).read_text(encoding="utf-8").splitlines()
|
||||
if ln.strip()]
|
||||
order = {hp: i for i, hp in enumerate(want)}
|
||||
games = [g for g in games if g["history_path"] in order]
|
||||
games.sort(key=lambda g: order[g["history_path"]])
|
||||
|
||||
done = {p.relative_to(out_dir).as_posix()[: -len(".json.gz")] for p in out_dir.rglob("*.json.gz")}
|
||||
pending = [g for g in games if g["history_path"] not in done]
|
||||
if args.max_replays:
|
||||
pending = pending[: args.max_replays]
|
||||
@@ -580,6 +661,45 @@ def cmd_replays(args) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_stats(args) -> int:
|
||||
"""Fetch the aggregate/statistics endpoints (scenarios 1, 2, 6).
|
||||
|
||||
* /api/card_data -> card_data.json (per-card)
|
||||
* /api/card_data?colors=<pair> -> card_data.<pair>.json (archetype context)
|
||||
* /color_ratings/data -> color_ratings.json (color win rates)
|
||||
* /api/draft_metagame/ -> draft_metagame.json (pick order over time)
|
||||
"""
|
||||
stamp = datetime.now().strftime("%Y%m%d")
|
||||
out_dir = Path(args.out) if args.out else (DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "stats")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
limiter = RateLimiter(args.rate)
|
||||
cooldown = Cooldown(args.cooldown)
|
||||
proxies = load_proxies(args)
|
||||
|
||||
exp, fmt = args.set.upper(), args.format
|
||||
base = f"{BASE}/api/card_data?expansion={exp}&event_type={fmt}&time_period={args.time_period}"
|
||||
jobs = [("card_data.json", base)]
|
||||
for color in COLOR_PAIRS:
|
||||
jobs.append((f"card_data.{color}.json", f"{base}&colors={color}"))
|
||||
jobs.append(("color_ratings.json",
|
||||
f"{BASE}/color_ratings/data?expansion={exp}&event_type={fmt}"
|
||||
f"&time_period={args.time_period}&combine_splash=true"))
|
||||
jobs.append(("draft_metagame.json",
|
||||
f"{BASE}/api/draft_metagame/?expansion={exp}&format={fmt}"
|
||||
f"&time_period={args.time_period}"))
|
||||
|
||||
for name, url in jobs:
|
||||
try:
|
||||
data = fetch_json_rl(url, limiter, cooldown, proxies)
|
||||
(out_dir / name).write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
n = len(data.get("data", [])) if isinstance(data, dict) else len(data)
|
||||
print(f" [ok] {name:26} ({n} items)", file=sys.stderr)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" [failed] {name}: {exc}", file=sys.stderr)
|
||||
print(f"\nstored -> {out_dir}")
|
||||
return 0
|
||||
|
||||
|
||||
def read_jsonl_ids(path: Path, key: str) -> set:
|
||||
ids: set = set()
|
||||
if not path.exists():
|
||||
@@ -754,6 +874,8 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
pr.add_argument("--set", required=True)
|
||||
pr.add_argument("--format", default="PremierDraft")
|
||||
pr.add_argument("--events", required=True, help="event_details.jsonl from the drafts command")
|
||||
pr.add_argument("--selection-file", default=None,
|
||||
help="only fetch the history_paths listed in this file (one per line)")
|
||||
pr.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/replays)")
|
||||
pr.add_argument("-w", "--workers", type=int, default=8)
|
||||
pr.add_argument("-r", "--rate", type=float, default=10.0)
|
||||
@@ -765,6 +887,36 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
pr.add_argument("--max-replays", type=int)
|
||||
pr.add_argument("-q", "--quiet", action="store_true")
|
||||
pr.set_defaults(func=cmd_replays)
|
||||
|
||||
ps = sub.add_parser("stats", help="fetch aggregate stats: card_data, per-color, color_ratings, draft_metagame")
|
||||
ps.add_argument("--set", required=True)
|
||||
ps.add_argument("--format", default="PremierDraft")
|
||||
ps.add_argument("--time-period", default="ALL_TIME")
|
||||
ps.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/stats)")
|
||||
ps.add_argument("-r", "--rate", type=float, default=5.0)
|
||||
ps.add_argument("--cooldown", type=float, default=2.0)
|
||||
ps.add_argument("--proxy", action="append", default=[])
|
||||
ps.add_argument("--proxy-file")
|
||||
ps.add_argument("--cookie")
|
||||
ps.add_argument("--cookie-file")
|
||||
ps.set_defaults(func=cmd_stats)
|
||||
|
||||
pdd = sub.add_parser("draftdata", help="fetch full per-pick draft replays incl. pack contents")
|
||||
pdd.add_argument("--set", required=True)
|
||||
pdd.add_argument("--format", default="PremierDraft")
|
||||
pdd.add_argument("--index", required=True, help="trophies_index.jsonl (draft ids)")
|
||||
pdd.add_argument("--out", default=None,
|
||||
help="output dir (default: data/17lands/<SET><YYYYMMDD>/draftdata)")
|
||||
pdd.add_argument("-w", "--workers", type=int, default=48)
|
||||
pdd.add_argument("-r", "--rate", type=float, default=0.0, help="requests/sec (0 = no limit)")
|
||||
pdd.add_argument("--cooldown", type=float, default=0.0)
|
||||
pdd.add_argument("--proxy", action="append", default=[])
|
||||
pdd.add_argument("--proxy-file")
|
||||
pdd.add_argument("--cookie")
|
||||
pdd.add_argument("--cookie-file")
|
||||
pdd.add_argument("--max-drafts", type=int)
|
||||
pdd.add_argument("-q", "--quiet", action="store_true")
|
||||
pdd.set_defaults(func=cmd_draftdata)
|
||||
return parser
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user