load data

This commit is contained in:
2026-10-07 23:25:09 +08:00
parent 8cae22f955
commit 31812ec75d
8 changed files with 741 additions and 1598 deletions
+443 -7
View File
@@ -29,6 +29,7 @@ from __future__ import annotations
import argparse
import json
import os
import sys
import threading
import time
@@ -36,12 +37,13 @@ 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
from urllib.parse import quote
from urllib.request import Request, build_opener, ProxyHandler, 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"
DEFAULT_OUT = Path(__file__).resolve().parent.parent / "data" / "17lands"
# --------------------------------------------------------------------------- #
@@ -127,9 +129,175 @@ def collect_index(expansion: str, fmt: str, limiter: RateLimiter,
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}")
class ProxyPool:
"""Round-robin-ish proxy pool: stick to the current proxy until it fails
(HTTP 403 / connect error), then rotate to the next one."""
def __init__(self, proxies: list[str]):
self.proxies = proxies
self.lock = threading.Lock()
self.idx = 0
self.dead: set[str] = set()
@property
def has_proxies(self) -> bool:
return bool(self.proxies)
def acquire(self) -> str | None:
with self.lock:
if not self.proxies:
return None
n = len(self.proxies)
if len(self.dead) >= n:
self.dead.clear()
while self.proxies[self.idx % n] in self.dead:
self.idx += 1
return self.proxies[self.idx % n]
def mark_dead(self, proxy: str | None) -> None:
if proxy is None:
return
with self.lock:
self.dead.add(proxy)
self.idx += 1
def load_proxies(args) -> ProxyPool:
items: list[str] = list(getattr(args, "proxy", None) or [])
if getattr(args, "proxy_file", None):
for line in Path(args.proxy_file).read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#"):
items.append(line)
for env in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"):
value = os.environ.get(env)
if value:
items.append(value)
normalized = [p if "://" in p else "http://" + p for p in items]
return ProxyPool(normalized)
COOKIE = "" # Cookie header value, populated by load_cookies()
def _headers(accept: str = "application/json") -> dict:
headers = {"User-Agent": USER_AGENT, "Accept": accept}
if COOKIE:
headers["Cookie"] = COOKIE
return headers
def load_cookies(args) -> str:
"""Load a Cookie header from --cookie (string) or --cookie-file
(a raw Cookie header line, or a Netscape cookies.txt export)."""
global COOKIE
raw = None
if getattr(args, "cookie", None):
raw = args.cookie
elif getattr(args, "cookie_file", None):
raw = Path(args.cookie_file).read_text(encoding="utf-8")
if not raw:
return COOKIE
raw = raw.strip()
if "\t" in raw: # Netscape cookies.txt
parts = []
for line in raw.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
cols = line.split("\t")
if len(cols) >= 7:
parts.append(f"{cols[5]}={cols[6]}")
COOKIE = "; ".join(parts)
else:
if raw.lower().startswith("cookie:"):
raw = raw.split(":", 1)[1]
COOKIE = " ".join(raw.split())
return COOKIE
def _open(url: str, headers: dict, timeout: float, proxy: str | None):
opener = build_opener(ProxyHandler({"http": proxy, "https": proxy})) if proxy else build_opener()
return opener.open(Request(url, headers=headers), timeout=timeout)
def fetch_json_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
proxies: ProxyPool | None = None, retries: int = 12,
timeout: float = 60) -> dict:
"""GET a URL as JSON with shared rate-limiting, 403 cooldown and proxy rotation."""
headers = _headers()
proxies = proxies or ProxyPool([])
soft = 0 # non-403 errors count against ``retries``
rl = 0 # 403s are IP-level; the router rotates, so retry freely
while soft < retries and rl < 5000:
if not proxies.has_proxies:
cooldown.wait()
limiter.wait()
proxy = proxies.acquire()
try:
with _open(url, headers, timeout, proxy) as resp:
return json.loads(resp.read().decode("utf-8"))
except HTTPError as exc:
if exc.code == 403:
rl += 1
proxies.mark_dead(proxy)
if not proxies.has_proxies:
cooldown.hit()
continue
soft += 1
if soft >= retries:
raise
time.sleep(min(2 ** soft, 8))
except (URLError, TimeoutError, OSError, json.JSONDecodeError):
soft += 1
proxies.mark_dead(proxy)
if soft >= retries:
raise
time.sleep(min(2 ** soft, 5))
raise RuntimeError("exhausted retries")
def fetch_bytes_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
proxies: ProxyPool | None = None, retries: int = 12,
timeout: float = 120) -> bytes:
"""GET a URL as raw bytes (e.g. a gzipped replay) with the same resilience."""
headers = _headers(accept="application/octet-stream")
proxies = proxies or ProxyPool([])
soft = 0
rl = 0
while soft < retries and rl < 5000:
if not proxies.has_proxies:
cooldown.wait()
limiter.wait()
proxy = proxies.acquire()
try:
with _open(url, headers, timeout, proxy) as resp:
return resp.read()
except HTTPError as exc:
if exc.code == 403:
rl += 1
proxies.mark_dead(proxy)
if not proxies.has_proxies:
cooldown.hit()
continue
soft += 1
if soft >= retries:
raise
time.sleep(min(2 ** soft, 8))
except (URLError, TimeoutError, OSError):
soft += 1
proxies.mark_dead(proxy)
if soft >= retries:
raise
time.sleep(min(2 ** soft, 5))
raise RuntimeError("exhausted retries")
def fetch_deck(aggregate_id: str, deck_index: int, limiter: RateLimiter,
cooldown: "Cooldown", proxies: ProxyPool | None = None,
retries: int = 12, timeout: float = 60) -> tuple[list[int], list[int]]:
url = f"{BASE}/api/deck/draft/?draft_id={aggregate_id}&deck_index={deck_index}"
data = fetch_json_rl(url, limiter, cooldown, proxies, retries, timeout)
maindeck: list[int] = []
sideboard: list[int] = []
for group in data.get("data", {}).get("groups", []):
@@ -140,6 +308,28 @@ def fetch_deck(aggregate_id: str, deck_index: int, limiter: RateLimiter) -> tupl
return maindeck, sideboard
class Cooldown:
"""Global pause shared by all workers when the server rate-limits us (HTTP 403)."""
def __init__(self, seconds: float):
self.seconds = seconds
self.until = 0.0
self.lock = threading.Lock()
def hit(self) -> None:
with self.lock:
self.until = max(self.until, time.monotonic() + self.seconds)
def wait(self) -> None:
while True:
with self.lock:
remaining = self.until - time.monotonic()
if remaining <= 0:
return
print(f" [cooldown] rate-limited; waiting {remaining:.0f}s", file=sys.stderr)
time.sleep(min(remaining, 10))
# --------------------------------------------------------------------------- #
# Files
# --------------------------------------------------------------------------- #
@@ -190,6 +380,10 @@ def cmd_trophies(args) -> int:
out_dir.mkdir(parents=True, exist_ok=True)
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
if proxies.has_proxies:
print(f"[proxies] {len(proxies.proxies)} proxies loaded (rotate on 403)", file=sys.stderr)
t0 = time.time()
# ---- index ----
@@ -232,7 +426,8 @@ def cmd_trophies(args) -> int:
def worker(entry: dict) -> dict | None:
try:
maindeck, sideboard = fetch_deck(entry["aggregate_id"], entry["deck_index"], limiter)
maindeck, sideboard = fetch_deck(entry["aggregate_id"], entry["deck_index"],
limiter, cooldown, proxies)
valid = len(maindeck) == 40
if not valid:
with lock:
@@ -290,6 +485,206 @@ def cmd_trophies(args) -> int:
return 0
def cmd_replays(args) -> int:
"""Download the turn-by-turn GRE replay (gzip) for every game.
``history_path`` is derived from ``game_results[].history_s3_path``
(``s3://17lands-game-histories/<rel>.json.gz`` -> ``<rel>``), so no extra
request to /data/history_info/ is needed.
"""
if not COOKIE:
print("[replays] WARNING: no cookie given; /data/history requires login.", file=sys.stderr)
out_dir = Path(args.out) if args.out else (
DEFAULT_OUT / f"{args.set.upper()}{datetime.now():%Y%m%d}" / "replays")
out_dir.mkdir(parents=True, exist_ok=True)
index_path = out_dir / "replay_index.jsonl"
games: list[dict] = []
seen: set[str] = set()
with Path(args.events).open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
rec = json.loads(line)
did = rec["draft_id"]
for mi, match in enumerate(rec.get("details", {}).get("match_results") or []):
for gi, game in enumerate(match.get("game_results") or []):
hp = game.get("history_s3_path")
if not hp:
continue
rel = hp.split("17lands-game-histories/", 1)[-1]
if rel.endswith(".json.gz"):
rel = rel[: -len(".json.gz")]
if rel in seen:
continue
seen.add(rel)
games.append({
"history_path": rel, "draft_id": did,
"match_index": mi, "game_index": gi,
"won": game.get("won"), "on_play": game.get("on_play"),
"opponent_colors": game.get("opponent_colors"),
"total_turns": game.get("total_turns"),
"game_number": game.get("game_number"),
})
with index_path.open("w", encoding="utf-8") as fh:
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")}
pending = [g for g in games if g["history_path"] not in done]
if args.max_replays:
pending = pending[: args.max_replays]
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
print(f"[replays] {len(games)} games, {len(done)} done, {len(pending)} pending", file=sys.stderr)
lock = threading.Lock()
stats = {"ok": 0, "failed": 0}
t0 = time.time()
def worker(g: dict) -> None:
rel = g["history_path"]
dest = out_dir / (rel + ".json.gz")
dest.parent.mkdir(parents=True, exist_ok=True)
try:
data = fetch_bytes_rl(
f"{BASE}/data/history?history_path={quote(rel, safe='')}",
limiter, cooldown, proxies)
tmp = dest.with_suffix(".part")
tmp.write_bytes(data)
tmp.replace(dest)
with lock:
stats["ok"] += 1
except Exception as exc: # noqa: BLE001
with lock:
stats["failed"] += 1
print(f" [failed] {rel}: {exc}", file=sys.stderr)
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, g) for g in pending]
for i, fut in enumerate(as_completed(futures), 1):
fut.result()
if not args.quiet and (i % 25 == 0 or i == len(futures)):
el = time.time() - t0
print(f" {i}/{len(futures)} ok={stats['ok']} failed={stats['failed']} "
f"{i / el if el else 0:.1f}/s", file=sys.stderr)
print("\n===== replays summary =====")
print(f"games : {len(games)}")
print(f"new replays : {stats['ok']}")
print(f"failed : {stats['failed']}")
print(f"stored : {len(done) + stats['ok']} -> {out_dir}")
print(f"elapsed : {time.time() - t0:.1f}s")
return 0
def read_jsonl_ids(path: Path, key: str) -> set:
ids: set = set()
if not path.exists():
return ids
with path.open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
ids.add(json.loads(line)[key])
except (json.JSONDecodeError, KeyError):
continue
return ids
def cmd_drafts(args) -> int:
"""Per trophy draft: /api/draft_picks + /data/event_details (game results)."""
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}" / "drafts"
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)
picks_path = out_dir / "draft_picks.jsonl"
events_path = out_dir / "event_details.jsonl"
have_picks = read_jsonl_ids(picks_path, "draft_id")
have_events = read_jsonl_ids(events_path, "draft_id")
total = len(ids)
pending = [d for d in ids if d not in have_picks or d not in have_events]
if args.max_drafts:
pending = pending[: args.max_drafts]
ids = pending
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
if proxies.has_proxies:
print(f"[proxies] {len(proxies.proxies)} proxies loaded", file=sys.stderr)
print(f"[drafts] {total} total, {len(ids)} pending "
f"(picks done={len(have_picks)} events done={len(have_events)})", file=sys.stderr)
lock = threading.Lock()
stats = {"picks": 0, "events": 0, "failed": 0, "done": 0}
t0 = time.time()
with picks_path.open("a", encoding="utf-8") as pf, \
events_path.open("a", encoding="utf-8") as ef:
def worker(did: str) -> None:
got: dict[str, dict] = {}
try:
if did not in have_picks:
got["picks"] = fetch_json_rl(
f"{BASE}/api/draft_picks?draft_id={did}", limiter, cooldown, proxies)
if did not in have_events:
got["events"] = fetch_json_rl(
f"{BASE}/data/event_details?draft_id={did}", limiter, cooldown, proxies)
except Exception as exc: # noqa: BLE001
with lock:
stats["failed"] += 1
print(f" [failed] {did}: {exc}", file=sys.stderr)
return
with lock:
if "picks" in got:
pf.write(json.dumps({"draft_id": did, **got["picks"]}, ensure_ascii=False) + "\n")
pf.flush()
stats["picks"] += 1
if "events" in got:
ef.write(json.dumps({"draft_id": did, **got["events"]}, ensure_ascii=False) + "\n")
ef.flush()
stats["events"] += 1
stats["done"] += 1
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, did) for did in ids]
for i, fut in enumerate(as_completed(futures), 1):
fut.result()
if not args.quiet and (i % 50 == 0 or i == len(futures)):
elapsed = time.time() - t0
rate = i / elapsed if elapsed else 0
print(f" {i}/{len(futures)} picks={stats['picks']} events={stats['events']} "
f"failed={stats['failed']} {rate:.1f}/s", file=sys.stderr)
print("\n===== drafts summary =====")
print(f"drafts : {len(ids)}")
print(f"picks new : {stats['picks']} (total {len(read_jsonl_ids(picks_path, 'draft_id'))})")
print(f"events new : {stats['events']} (total {len(read_jsonl_ids(events_path, 'draft_id'))})")
print(f"failed : {stats['failed']}")
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)
@@ -322,14 +717,54 @@ def build_parser() -> argparse.ArgumentParser:
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)")
help="output directory (default: data/17lands/<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("--cooldown", type=float, default=120.0,
help="global pause in seconds after an HTTP 403 when no proxies are set (default: 120)")
p.add_argument("--proxy", action="append", default=[], metavar="URL",
help="proxy URL, repeatable (e.g. http://user:pass@host:port)")
p.add_argument("--proxy-file", metavar="FILE",
help="file with one proxy per line; rotate to the next on HTTP 403")
p.add_argument("--cookie", help="Cookie header value (or use --cookie-file)")
p.add_argument("--cookie-file", help="file with a Cookie header or Netscape cookies.txt")
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)
pd = sub.add_parser("drafts", help="fetch draft picks + event/game details per trophy draft")
pd.add_argument("--set", required=True)
pd.add_argument("--format", default="PremierDraft")
pd.add_argument("--index", required=True, help="trophies_index.jsonl from the trophies command")
pd.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/drafts)")
pd.add_argument("-w", "--workers", type=int, default=8)
pd.add_argument("-r", "--rate", type=float, default=10.0)
pd.add_argument("--cooldown", type=float, default=2.0)
pd.add_argument("--proxy", action="append", default=[])
pd.add_argument("--proxy-file")
pd.add_argument("--cookie")
pd.add_argument("--cookie-file")
pd.add_argument("--max-drafts", type=int)
pd.add_argument("-q", "--quiet", action="store_true")
pd.set_defaults(func=cmd_drafts)
pr = sub.add_parser("replays", help="download turn-by-turn GRE replays (login required)")
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("--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)
pr.add_argument("--cooldown", type=float, default=2.0)
pr.add_argument("--proxy", action="append", default=[])
pr.add_argument("--proxy-file")
pr.add_argument("--cookie")
pr.add_argument("--cookie-file")
pr.add_argument("--max-replays", type=int)
pr.add_argument("-q", "--quiet", action="store_true")
pr.set_defaults(func=cmd_replays)
return parser
@@ -339,6 +774,7 @@ def main(argv: list[str] | None = None) -> int:
if not getattr(args, "func", None):
parser.print_help()
return 2
load_cookies(args)
return args.func(args)