351 lines
14 KiB
Python
351 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Fetch 17Lands *web API* data (as opposed to the bulk public datasets).
|
|
|
|
Currently implements the trophy-deck pipeline, which is the only way to get
|
|
actual 40-card decklists. Reverse-engineered facts (all verified):
|
|
|
|
* ``GET /api/trophies/?format=<FMT>&expansion=<SET>`` -> up to 500 recent
|
|
trophy decks; ``format`` required; pagination/time params are ignored.
|
|
* ``POST /api/trophies/`` body
|
|
``{expansion, event_type, card_names[], ranks[], deck_colors[]}`` -> up to
|
|
100 recent decks. Only ``deck_colors`` actually filters (10 WUBRG pairs,
|
|
100 unique each, no overlap). ``card_names`` / ``ranks`` are no-ops.
|
|
* ``GET /api/deck/draft/?draft_id=<id>&deck_index=<n>`` -> full decklist as
|
|
``data.groups[]{name: Maindeck|Sideboard, cards:[mtga_id, ...]}``.
|
|
|
|
The union of GET + the 10 color pairs is ~1100 unique decks per poll for a busy
|
|
set; because the window rolls, run this periodically and it accumulates.
|
|
|
|
Examples
|
|
--------
|
|
# Collect the index only and report counts.
|
|
python scripts/fetch_17lands_api.py trophies --set FRA --format PremierDraft --index-only
|
|
|
|
# Collect index + fetch every 40-card decklist, 6 req/s, 4 workers.
|
|
python scripts/fetch_17lands_api.py trophies --set FRA --format PremierDraft -w 4 -r 6
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
import threading
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import Request, urlopen
|
|
|
|
BASE = "https://www.17lands.com"
|
|
USER_AGENT = "mtga-17lands-fetcher/1.0"
|
|
COLOR_PAIRS = ["WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"]
|
|
DEFAULT_OUT = Path(__file__).resolve().parent.parent / "value"
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# HTTP
|
|
# --------------------------------------------------------------------------- #
|
|
def http_json(url: str, method: str = "GET", body: dict | None = None,
|
|
timeout: float = 60, retries: int = 3) -> dict:
|
|
payload = json.dumps(body).encode("utf-8") if body is not None else None
|
|
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
if payload is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
last = None
|
|
for attempt in range(1, retries + 1):
|
|
try:
|
|
req = Request(url, data=payload, headers=headers, method=method)
|
|
with urlopen(req, timeout=timeout) as resp:
|
|
return json.loads(resp.read().decode("utf-8"))
|
|
except (HTTPError, URLError, TimeoutError, OSError, json.JSONDecodeError) as exc:
|
|
last = exc
|
|
if attempt < retries:
|
|
time.sleep(min(2 ** attempt, 8))
|
|
raise RuntimeError(f"request failed: {url}: {last}")
|
|
|
|
|
|
class RateLimiter:
|
|
"""Thread-safe token spacing: at most ``rate`` requests per second."""
|
|
|
|
def __init__(self, rate: float):
|
|
self.interval = 1.0 / rate if rate > 0 else 0.0
|
|
self.lock = threading.Lock()
|
|
self.next_t = 0.0
|
|
|
|
def wait(self) -> None:
|
|
if not self.interval:
|
|
return
|
|
with self.lock:
|
|
now = time.monotonic()
|
|
delay = max(0.0, self.next_t - now)
|
|
self.next_t = max(now, self.next_t) + self.interval
|
|
if delay:
|
|
time.sleep(delay)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Trophy index
|
|
# --------------------------------------------------------------------------- #
|
|
def _key(entry: dict) -> str:
|
|
return f"{entry['aggregate_id']}:{entry['deck_index']}"
|
|
|
|
|
|
def collect_index(expansion: str, fmt: str, limiter: RateLimiter,
|
|
quiet: bool = False) -> dict[str, dict]:
|
|
"""Union of the 500-item GET and the 10 color-pair POSTs, deduped."""
|
|
entries: dict[str, dict] = {}
|
|
|
|
def add(rows, source):
|
|
for row in rows:
|
|
k = _key(row)
|
|
if k not in entries:
|
|
entries[k] = {**row, "source": source}
|
|
|
|
limiter.wait()
|
|
data = http_json(f"{BASE}/api/trophies/?format={fmt}&expansion={expansion}")
|
|
add(data.get("data", []), "get")
|
|
if not quiet:
|
|
print(f" GET -> {len(entries):4} unique", file=sys.stderr)
|
|
|
|
for color in COLOR_PAIRS:
|
|
limiter.wait()
|
|
body = {
|
|
"expansion": expansion,
|
|
"event_type": fmt,
|
|
"card_names": [],
|
|
"ranks": [],
|
|
"deck_colors": [color],
|
|
}
|
|
data = http_json(f"{BASE}/api/trophies/", method="POST", body=body)
|
|
before = len(entries)
|
|
add(data.get("data", []), f"post:{color}")
|
|
if not quiet:
|
|
print(f" POST {color:<2} -> {len(entries):4} unique (+{len(entries) - before})",
|
|
file=sys.stderr)
|
|
return entries
|
|
|
|
|
|
def fetch_deck(aggregate_id: str, deck_index: int, limiter: RateLimiter) -> tuple[list[int], list[int]]:
|
|
limiter.wait()
|
|
data = http_json(f"{BASE}/api/deck/draft/?draft_id={aggregate_id}&deck_index={deck_index}")
|
|
maindeck: list[int] = []
|
|
sideboard: list[int] = []
|
|
for group in data.get("data", {}).get("groups", []):
|
|
if group.get("name") == "Maindeck":
|
|
maindeck = group.get("cards", [])
|
|
elif group.get("name") == "Sideboard":
|
|
sideboard = group.get("cards", [])
|
|
return maindeck, sideboard
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Files
|
|
# --------------------------------------------------------------------------- #
|
|
def read_done_keys(path: Path) -> set[str]:
|
|
done: set[str] = set()
|
|
if not path.exists():
|
|
return done
|
|
with path.open(encoding="utf-8") as fh:
|
|
for line in fh:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
try:
|
|
row = json.loads(line)
|
|
done.add(f"{row['aggregate_id']}:{row['deck_index']}")
|
|
except (json.JSONDecodeError, KeyError):
|
|
continue
|
|
return done
|
|
|
|
|
|
def write_jsonl(path: Path, rows: list[dict]) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with path.open("w", encoding="utf-8") as fh:
|
|
for row in rows:
|
|
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
|
|
|
|
def load_card_names(expansion: str, fmt: str, limiter: RateLimiter) -> dict[int, str]:
|
|
limiter.wait()
|
|
data = http_json(
|
|
f"{BASE}/api/card_data?expansion={expansion}&event_type={fmt}&time_period=ALL_TIME"
|
|
)
|
|
return {c["mtga_id"]: c["name"] for c in data.get("data", []) if "mtga_id" in c}
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Command: trophies
|
|
# --------------------------------------------------------------------------- #
|
|
def cmd_trophies(args) -> int:
|
|
if args.out:
|
|
out_dir = Path(args.out)
|
|
else:
|
|
stamp = datetime.now().strftime("%Y%m%d")
|
|
out_dir = DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "trophies"
|
|
index_path = out_dir / "trophies_index.jsonl"
|
|
decks_path = out_dir / "trophies_decks.jsonl"
|
|
cards_path = out_dir / "cards.json"
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
limiter = RateLimiter(args.rate)
|
|
t0 = time.time()
|
|
|
|
# ---- index ----
|
|
if args.reuse_index and index_path.exists():
|
|
entries = {}
|
|
with index_path.open(encoding="utf-8") as fh:
|
|
for line in fh:
|
|
row = json.loads(line)
|
|
entries[_key(row)] = row
|
|
print(f"[index] reused {len(entries)} entries from {index_path}", file=sys.stderr)
|
|
else:
|
|
print(f"[index] collecting trophy index for {args.set} {args.format} ...", file=sys.stderr)
|
|
entries = collect_index(args.set.upper(), args.format, limiter, quiet=args.quiet)
|
|
write_jsonl(index_path, list(entries.values()))
|
|
print(f"[index] {len(entries)} unique entries -> {index_path}", file=sys.stderr)
|
|
|
|
if args.index_only:
|
|
_summary_index(entries)
|
|
return 0
|
|
|
|
# ---- card names ----
|
|
names: dict[int, str] = {}
|
|
if cards_path.exists():
|
|
names = {int(k): v for k, v in json.loads(cards_path.read_text(encoding="utf-8")).items()}
|
|
else:
|
|
names = load_card_names(args.set.upper(), args.format, limiter)
|
|
cards_path.write_text(json.dumps(names, ensure_ascii=False, indent=0), encoding="utf-8")
|
|
print(f"[cards] {len(names)} card names", file=sys.stderr)
|
|
|
|
# ---- decklists ----
|
|
done = read_done_keys(decks_path)
|
|
todo = [e for k, e in entries.items() if k not in done]
|
|
if args.max_decks:
|
|
todo = todo[: args.max_decks]
|
|
print(f"[decks] {len(done)} already done, {len(todo)} to fetch", file=sys.stderr)
|
|
|
|
lock = threading.Lock()
|
|
stats = {"fetched": 0, "valid": 0, "invalid": 0, "failed": 0}
|
|
started = time.time()
|
|
|
|
def worker(entry: dict) -> dict | None:
|
|
try:
|
|
maindeck, sideboard = fetch_deck(entry["aggregate_id"], entry["deck_index"], limiter)
|
|
valid = len(maindeck) == 40
|
|
if not valid:
|
|
with lock:
|
|
stats["invalid"] += 1
|
|
return None
|
|
row = {
|
|
"aggregate_id": entry["aggregate_id"],
|
|
"deck_index": entry["deck_index"],
|
|
"colors": entry.get("colors"),
|
|
"wins": entry.get("wins"),
|
|
"losses": entry.get("losses"),
|
|
"start_rank": entry.get("start_rank"),
|
|
"end_rank": entry.get("end_rank"),
|
|
"time": entry.get("time"),
|
|
"source": entry.get("source"),
|
|
"maindeck": _counts(maindeck, names),
|
|
"sideboard": _counts(sideboard, names),
|
|
"fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
}
|
|
return row
|
|
except Exception as exc: # noqa: BLE001
|
|
with lock:
|
|
stats["failed"] += 1
|
|
print(f" [failed] {_key(entry)}: {exc}", file=sys.stderr)
|
|
return None
|
|
|
|
mode = "a" if decks_path.exists() else "w"
|
|
with decks_path.open(mode, encoding="utf-8") as fh, \
|
|
ThreadPoolExecutor(max_workers=args.workers) as pool:
|
|
futures = [pool.submit(worker, e) for e in todo]
|
|
for i, fut in enumerate(as_completed(futures), 1):
|
|
row = fut.result()
|
|
if row is not None:
|
|
with lock:
|
|
stats["valid"] += 1
|
|
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
fh.flush()
|
|
with lock:
|
|
stats["fetched"] += 1
|
|
if not args.quiet and (i % 25 == 0 or i == len(futures)):
|
|
elapsed = time.time() - started
|
|
rate = i / elapsed if elapsed else 0
|
|
print(f" {i}/{len(futures)} valid={stats['valid']} invalid={stats['invalid']} "
|
|
f"failed={stats['failed']} {rate:.1f}/s", file=sys.stderr)
|
|
|
|
total_valid = len(read_done_keys(decks_path))
|
|
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" invalid : {stats['invalid']}")
|
|
print(f" failed : {stats['failed']}")
|
|
print(f"total valid stored : {total_valid} -> {decks_path}")
|
|
print(f"elapsed : {time.time() - t0:.1f}s")
|
|
return 0
|
|
|
|
|
|
def _counts(cards: list[int], names: dict[int, str]) -> list[dict]:
|
|
from collections import Counter
|
|
counter = Counter(cards)
|
|
return [
|
|
{"mtga_id": cid, "name": names.get(cid, str(cid)), "count": n}
|
|
for cid, n in sorted(counter.items(), key=lambda kv: (-kv[1], kv[0]))
|
|
]
|
|
|
|
|
|
def _summary_index(entries: dict[str, dict]) -> None:
|
|
from collections import Counter
|
|
print("\n===== index summary =====")
|
|
print(f"unique decks : {len(entries)}")
|
|
print("by source :", dict(Counter(e["source"] for e in entries.values()).most_common()))
|
|
print("by colors :", Counter(e.get("colors") for e in entries.values()).most_common(12))
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# CLI
|
|
# --------------------------------------------------------------------------- #
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser(
|
|
description="Fetch 17Lands web-API data (trophy decks).",
|
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog=__doc__,
|
|
)
|
|
sub = parser.add_subparsers(dest="command")
|
|
|
|
p = sub.add_parser("trophies", help="collect trophy-deck index + full decklists")
|
|
p.add_argument("--set", required=True, help="expansion code, e.g. FRA")
|
|
p.add_argument("--format", default="PremierDraft", help="event type / format (default: PremierDraft)")
|
|
p.add_argument("--out", default=None,
|
|
help="output directory (default: value/<SET><YYYYMMDD>/trophies)")
|
|
p.add_argument("-w", "--workers", type=int, default=4, help="parallel deck fetches (default: 4)")
|
|
p.add_argument("-r", "--rate", type=float, default=5.0, help="max requests/sec (default: 5)")
|
|
p.add_argument("--index-only", action="store_true", help="only collect the index, no decklists")
|
|
p.add_argument("--reuse-index", action="store_true", help="reuse existing trophies_index.jsonl")
|
|
p.add_argument("--max-decks", type=int, help="limit decklists fetched (for testing)")
|
|
p.add_argument("-q", "--quiet", action="store_true")
|
|
p.set_defaults(func=cmd_trophies)
|
|
return parser
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = build_parser()
|
|
args = parser.parse_args(argv)
|
|
if not getattr(args, "func", None):
|
|
parser.print_help()
|
|
return 2
|
|
return args.func(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
raise SystemExit(main())
|
|
except KeyboardInterrupt:
|
|
print("\nInterrupted.", file=sys.stderr)
|
|
raise SystemExit(130)
|