init
This commit is contained in:
@@ -0,0 +1,511 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fetch public datasets from 17Lands.com.
|
||||
|
||||
17Lands publishes its bulk data as gzipped CSV files on S3. The list of
|
||||
available files is not served by a plain API; it lives in a Prismic CMS
|
||||
document of type ``public-data``. This script reads that catalog, lets you
|
||||
filter it, and downloads the matching files (optionally gunzipping them).
|
||||
|
||||
Requires only the Python standard library (3.8+).
|
||||
|
||||
Examples
|
||||
--------
|
||||
# Show every dataset in the catalog.
|
||||
python scripts/fetch_17lands.py list
|
||||
|
||||
# Show only SOS datasets.
|
||||
python scripts/fetch_17lands.py list --set SOS
|
||||
|
||||
# Download the game data for SOS Premier Draft.
|
||||
python scripts/fetch_17lands.py fetch --set SOS --format PremierDraft --type game
|
||||
|
||||
# Download draft + game data for the 3 most recent expansions, unzipped.
|
||||
python scripts/fetch_17lands.py fetch --latest 3 --type draft,game --decompress
|
||||
|
||||
# Download the shared helper files and card lists.
|
||||
python scripts/fetch_17lands.py helpers
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
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.parse import urlencode, urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
PRISMIC_API = "https://17lands.cdn.prismic.io/api/v2"
|
||||
PRISMIC_SEARCH = PRISMIC_API + "/documents/search"
|
||||
USER_AGENT = "mtga-17lands-fetcher/1.0 (+https://17lands.com)"
|
||||
DEFAULT_OUT = Path(__file__).resolve().parent.parent / "data" / "17lands"
|
||||
CACHE_TTL_HOURS = 24
|
||||
DATA_TYPES = ("draft", "game", "replay")
|
||||
CHUNK = 1 << 20 # 1 MiB
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Catalog access
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _http_json(url: str, timeout: float) -> dict:
|
||||
req = Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
|
||||
def _rich_text(node) -> str:
|
||||
"""Flatten a Prismic rich-text field into plain text."""
|
||||
if isinstance(node, list):
|
||||
return "".join(_rich_text(item) for item in node)
|
||||
if isinstance(node, dict):
|
||||
if "text" in node:
|
||||
return str(node.get("text") or "")
|
||||
return "".join(_rich_text(v) for v in node.values())
|
||||
return ""
|
||||
|
||||
|
||||
def _first_hyperlink(node) -> str | None:
|
||||
"""Return the first hyperlink URL found anywhere in a rich-text field."""
|
||||
if isinstance(node, list):
|
||||
for item in node:
|
||||
found = _first_hyperlink(item)
|
||||
if found:
|
||||
return found
|
||||
elif isinstance(node, dict):
|
||||
if node.get("type") == "hyperlink":
|
||||
return (node.get("data") or {}).get("url")
|
||||
for value in node.values():
|
||||
found = _first_hyperlink(value)
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
|
||||
def _basename(url: str) -> str:
|
||||
return Path(urlparse(url).path).name
|
||||
|
||||
|
||||
def fetch_catalog(refresh: bool, out_dir: Path, timeout: float) -> dict:
|
||||
"""Return the parsed catalog, using an on-disk cache when possible."""
|
||||
cache_file = out_dir / ".cache" / "catalog.json"
|
||||
if cache_file.exists() and not refresh:
|
||||
age = time.time() - cache_file.stat().st_mtime
|
||||
if age < CACHE_TTL_HOURS * 3600:
|
||||
try:
|
||||
with cache_file.open(encoding="utf-8") as fh:
|
||||
return json.load(fh)
|
||||
except (OSError, json.JSONDecodeError):
|
||||
pass # fall through to a network fetch
|
||||
|
||||
api = _http_json(PRISMIC_API, timeout)
|
||||
ref = next((r["ref"] for r in api.get("refs", []) if r.get("isMasterRef")), None)
|
||||
ref = ref or next((r["ref"] for r in api.get("refs", [])), None)
|
||||
if not ref:
|
||||
raise RuntimeError("Prismic did not return a document ref")
|
||||
|
||||
query = urlencode(
|
||||
{
|
||||
"ref": ref,
|
||||
"q": '[[at(document.type,"public-data")]]',
|
||||
"pageSize": 100,
|
||||
}
|
||||
)
|
||||
payload = _http_json(f"{PRISMIC_SEARCH}?{query}", timeout)
|
||||
results = payload.get("results", [])
|
||||
if not results:
|
||||
raise RuntimeError("No public-data document found in the 17Lands catalog")
|
||||
|
||||
catalog = _parse_document(results[0])
|
||||
catalog["fetched_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
cache_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = cache_file.with_suffix(".tmp")
|
||||
with tmp.open("w", encoding="utf-8") as fh:
|
||||
json.dump(catalog, fh, ensure_ascii=False, indent=1)
|
||||
tmp.replace(cache_file)
|
||||
return catalog
|
||||
|
||||
|
||||
def _parse_document(doc: dict) -> dict:
|
||||
data = doc.get("data", {})
|
||||
datasets = []
|
||||
for entry in data.get("datasets", []):
|
||||
urls = {}
|
||||
for kind in DATA_TYPES:
|
||||
url = _first_hyperlink(entry.get(kind + "_data"))
|
||||
if url:
|
||||
urls[kind] = url
|
||||
datasets.append(
|
||||
{
|
||||
"expansion": _rich_text(entry.get("expansion")).strip(),
|
||||
"format": _rich_text(entry.get("format")).strip(),
|
||||
"last_updated": _rich_text(entry.get("last_updated")).strip(),
|
||||
"urls": urls,
|
||||
}
|
||||
)
|
||||
|
||||
helpers = []
|
||||
for entry in data.get("helper_files", []):
|
||||
url = _first_hyperlink(entry.get("file"))
|
||||
if url:
|
||||
helpers.append(
|
||||
{
|
||||
"name": _basename(url),
|
||||
"description": _rich_text(entry.get("description")).strip(),
|
||||
"last_updated": _rich_text(entry.get("last_updated")).strip(),
|
||||
"url": url,
|
||||
}
|
||||
)
|
||||
for entry in data.get("card_lists", []):
|
||||
url = _first_hyperlink(entry.get("dataset"))
|
||||
if url:
|
||||
helpers.append(
|
||||
{
|
||||
"name": _basename(url),
|
||||
"description": "",
|
||||
"last_updated": _rich_text(entry.get("last_updated")).strip(),
|
||||
"url": url,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"source": "https://www.17lands.com/public_datasets",
|
||||
"datasets": datasets,
|
||||
"helpers": helpers,
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Filtering / listing
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _split(value: str | None) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
return [part.strip() for part in value.split(",") if part.strip()]
|
||||
|
||||
|
||||
def select_datasets(catalog: dict, args) -> list[dict]:
|
||||
records = catalog["datasets"]
|
||||
if not records:
|
||||
return []
|
||||
|
||||
sets = {s.upper() for s in _split(args.set)}
|
||||
formats = {f.lower() for f in _split(args.format)}
|
||||
types = [t.lower() for t in _split(args.type)] or ["game"]
|
||||
for t in types:
|
||||
if t not in DATA_TYPES:
|
||||
raise SystemExit(f"unknown --type {t!r}; choose from {', '.join(DATA_TYPES)}")
|
||||
|
||||
if args.latest:
|
||||
ordered = sorted(
|
||||
{r["expansion"] for r in records},
|
||||
key=lambda e: max(r["last_updated"] for r in records if r["expansion"] == e),
|
||||
reverse=True,
|
||||
)
|
||||
keep = set(ordered[: args.latest])
|
||||
records = [r for r in records if r["expansion"] in keep]
|
||||
|
||||
if sets:
|
||||
records = [r for r in records if r["expansion"].upper() in sets]
|
||||
if formats:
|
||||
records = [r for r in records if r["format"].lower() in formats]
|
||||
|
||||
selected = []
|
||||
for rec in records:
|
||||
for kind in types:
|
||||
url = rec["urls"].get(kind)
|
||||
if url:
|
||||
selected.append(
|
||||
{
|
||||
"expansion": rec["expansion"],
|
||||
"format": rec["format"],
|
||||
"last_updated": rec["last_updated"],
|
||||
"type": kind,
|
||||
"url": url,
|
||||
}
|
||||
)
|
||||
return selected
|
||||
|
||||
|
||||
def cmd_list(catalog: dict, args) -> int:
|
||||
records = catalog["datasets"]
|
||||
sets = {s.upper() for s in _split(args.set)}
|
||||
formats = {f.lower() for f in _split(args.format)}
|
||||
if sets:
|
||||
records = [r for r in records if r["expansion"].upper() in sets]
|
||||
if formats:
|
||||
records = [r for r in records if r["format"].lower() in formats]
|
||||
|
||||
if not records:
|
||||
print("No datasets matched the given filters.")
|
||||
return 1
|
||||
|
||||
header = f"{'SET':<6} {'FORMAT':<14} {'UPDATED':<12} {'AVAILABLE':<22} URL HINT"
|
||||
print(header)
|
||||
print("-" * len(header))
|
||||
for rec in sorted(records, key=lambda r: (r["last_updated"], r["expansion"], r["format"])):
|
||||
available = ",".join(k for k in DATA_TYPES if k in rec["urls"]) or "-"
|
||||
print(
|
||||
f"{rec['expansion']:<6} {rec['format']:<14} {rec['last_updated']:<12} "
|
||||
f"{available:<22} {_url_hint(rec['urls'])}"
|
||||
)
|
||||
print(f"\n{len(records)} dataset(s). Catalog cached from {catalog.get('fetched_at', '?')}.")
|
||||
print("Download with: fetch --set <SET> --format <FORMAT> --type game,draft,replay")
|
||||
return 0
|
||||
|
||||
|
||||
def _url_hint(urls: dict) -> str:
|
||||
if not urls:
|
||||
return "-"
|
||||
first = next(iter(urls.values()))
|
||||
return _basename(first)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Downloading
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _remote_size(url: str, timeout: float) -> int:
|
||||
req = Request(url, method="HEAD", headers={"User-Agent": USER_AGENT})
|
||||
try:
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
return int(resp.headers.get("Content-Length") or 0)
|
||||
except (HTTPError, URLError, OSError):
|
||||
return 0
|
||||
|
||||
|
||||
def _human(num: float) -> str:
|
||||
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
|
||||
if abs(num) < 1024 or unit == "TiB":
|
||||
return f"{num:,.0f} {unit}" if unit == "B" else f"{num:,.1f} {unit}"
|
||||
num /= 1024
|
||||
return f"{num:.1f} TiB"
|
||||
|
||||
|
||||
def download(url: str, dest: Path, *, overwrite: bool = False, quiet: bool = False,
|
||||
timeout: float = 60, retries: int = 3) -> tuple[str, Path, int]:
|
||||
"""Download ``url`` to ``dest`` atomically, resuming partial files."""
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
expected = _remote_size(url, timeout)
|
||||
if not overwrite and dest.exists() and expected and dest.stat().st_size == expected:
|
||||
return ("skip", dest, expected)
|
||||
|
||||
tmp = dest.with_name(dest.name + ".part")
|
||||
last_error = None
|
||||
for attempt in range(1, retries + 1):
|
||||
pos = tmp.stat().st_size if tmp.exists() and not overwrite else 0
|
||||
headers = {"User-Agent": USER_AGENT}
|
||||
if pos:
|
||||
headers["Range"] = f"bytes={pos}-"
|
||||
req = Request(url, headers=headers)
|
||||
try:
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
# S3 ignores Range and returns 200 if resuming isn't supported.
|
||||
if pos and getattr(resp, "status", 200) == 200:
|
||||
pos = 0
|
||||
total = pos + int(resp.headers.get("Content-Length") or 0)
|
||||
mode = "ab" if pos else "wb"
|
||||
done = pos
|
||||
with tmp.open(mode) as out:
|
||||
while True:
|
||||
chunk = resp.read(CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
out.write(chunk)
|
||||
done += len(chunk)
|
||||
if not quiet:
|
||||
_progress(dest.name, done, total)
|
||||
if not quiet:
|
||||
sys.stderr.write("\r" + " " * 79 + "\r")
|
||||
tmp.replace(dest)
|
||||
return ("download", dest, dest.stat().st_size)
|
||||
except (HTTPError, URLError, OSError, TimeoutError) as exc:
|
||||
last_error = exc
|
||||
if attempt < retries:
|
||||
time.sleep(min(2 ** attempt, 10))
|
||||
raise RuntimeError(f"failed to download {url}: {last_error}")
|
||||
|
||||
|
||||
def _progress(name: str, done: int, total: int) -> None:
|
||||
if total:
|
||||
pct = done * 100 / total
|
||||
msg = f" {name[:40]:<40} {pct:5.1f}% {_human(done)} / {_human(total)}"
|
||||
else:
|
||||
msg = f" {name[:40]:<40} {_human(done)}"
|
||||
sys.stderr.write("\r" + msg[:79])
|
||||
sys.stderr.flush()
|
||||
|
||||
|
||||
def gunzip_file(path: Path, keep: bool) -> Path:
|
||||
target = path.with_suffix("") # strip .gz
|
||||
with gzip.open(path, "rb") as src, target.open("wb") as dst:
|
||||
shutil.copyfileobj(src, dst, CHUNK)
|
||||
if not keep:
|
||||
path.unlink()
|
||||
return target
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Commands
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _download_jobs(jobs: list[dict], out_dir: Path, args) -> int:
|
||||
if args.dry_run:
|
||||
for job in jobs:
|
||||
print(f"[dry-run] {job['url']}\n -> {out_dir / job['filename']}")
|
||||
return 0
|
||||
|
||||
failures = 0
|
||||
quiet = args.quiet or args.jobs > 1
|
||||
|
||||
def run(job: dict) -> tuple[str, Path, int]:
|
||||
dest = out_dir / job["filename"]
|
||||
final = dest.with_suffix("") if args.decompress and dest.suffix == ".gz" else dest
|
||||
if not args.overwrite and final.exists():
|
||||
return ("skip", final, final.stat().st_size)
|
||||
status, path, size = download(
|
||||
job["url"], dest, overwrite=args.overwrite, quiet=quiet, timeout=args.timeout
|
||||
)
|
||||
if status == "download" and args.decompress and path.suffix == ".gz":
|
||||
path = gunzip_file(path, keep=args.keep_gz)
|
||||
return status, path, size
|
||||
|
||||
if args.jobs > 1:
|
||||
with ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
||||
futures = {pool.submit(run, job): job for job in jobs}
|
||||
for future in as_completed(futures):
|
||||
job = futures[future]
|
||||
try:
|
||||
status, path, size = future.result()
|
||||
print(f"[{status}] {path} ({_human(size)})")
|
||||
except Exception as exc: # noqa: BLE001 - report and keep going
|
||||
failures += 1
|
||||
print(f"[failed] {job['filename']}: {exc}", file=sys.stderr)
|
||||
else:
|
||||
for job in jobs:
|
||||
try:
|
||||
status, path, size = run(job)
|
||||
print(f"[{status}] {path} ({_human(size)})")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failures += 1
|
||||
print(f"[failed] {job['filename']}: {exc}", file=sys.stderr)
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
def _dataset_jobs(selected: list[dict]) -> list[dict]:
|
||||
jobs = []
|
||||
for rec in selected:
|
||||
url = rec["url"]
|
||||
filename = _basename(url) or f"{rec['type']}.csv.gz"
|
||||
jobs.append({"url": url, **rec, "filename": filename})
|
||||
return jobs
|
||||
|
||||
|
||||
def cmd_fetch(catalog: dict, args) -> int:
|
||||
selected = select_datasets(catalog, args)
|
||||
if not selected:
|
||||
print("No datasets matched. Run `list` to see what is available.", file=sys.stderr)
|
||||
return 1
|
||||
if not args.all and not _split(args.set) and not args.format and not args.latest:
|
||||
print(
|
||||
f"Refusing to download all {len(selected)} files. "
|
||||
"Narrow with --set/--format/--latest, or pass --all to confirm.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
return _download_jobs(_dataset_jobs(selected), Path(args.out), args)
|
||||
|
||||
|
||||
def cmd_helpers(catalog: dict, args) -> int:
|
||||
jobs = [
|
||||
{
|
||||
"url": item["url"],
|
||||
"filename": item["name"],
|
||||
"expansion": "-",
|
||||
"format": "-",
|
||||
"type": "helper",
|
||||
}
|
||||
for item in catalog.get("helpers", [])
|
||||
]
|
||||
if not jobs:
|
||||
print("No helper files found in the catalog.", file=sys.stderr)
|
||||
return 1
|
||||
return _download_jobs(jobs, Path(args.out), args)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# CLI
|
||||
# --------------------------------------------------------------------------- #
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Browse and download 17Lands public datasets.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__,
|
||||
)
|
||||
parser.add_argument("--out", default=str(DEFAULT_OUT), help="output directory (default: %(default)s)")
|
||||
parser.add_argument("--refresh", action="store_true", help="ignore the cached catalog and refetch")
|
||||
parser.add_argument("--timeout", type=float, default=60, help="per-request timeout in seconds")
|
||||
parser.add_argument("-q", "--quiet", action="store_true", help="suppress progress output")
|
||||
sub = parser.add_subparsers(dest="command")
|
||||
|
||||
def add_filter_args(p):
|
||||
p.add_argument("-s", "--set", help="comma-separated expansion codes, e.g. SOS,BLB")
|
||||
p.add_argument("-f", "--format", help="comma-separated formats, e.g. PremierDraft,TradDraft")
|
||||
p.add_argument("-t", "--type", default="game",
|
||||
help="comma-separated data types: draft,game,replay (default: game)")
|
||||
|
||||
p_list = sub.add_parser("list", help="list datasets in the catalog")
|
||||
add_filter_args(p_list)
|
||||
|
||||
p_fetch = sub.add_parser("fetch", help="download datasets")
|
||||
add_filter_args(p_fetch)
|
||||
p_fetch.add_argument("--latest", type=int, metavar="N", help="only the N most recently updated expansions")
|
||||
p_fetch.add_argument("--all", action="store_true", help="download everything the filters match")
|
||||
p_fetch.add_argument("-o", "--overwrite", action="store_true", help="redownload files that already exist")
|
||||
p_fetch.add_argument("-d", "--decompress", action="store_true", help="gunzip files after download")
|
||||
p_fetch.add_argument("--keep-gz", action="store_true", help="keep the .gz alongside the decompressed file")
|
||||
p_fetch.add_argument("-j", "--jobs", type=int, default=1, help="parallel downloads (default: 1)")
|
||||
p_fetch.add_argument("-n", "--dry-run", action="store_true", help="show what would be downloaded")
|
||||
|
||||
p_helpers = sub.add_parser("helpers", help="download shared helper files and card lists")
|
||||
p_helpers.add_argument("-o", "--overwrite", action="store_true")
|
||||
p_helpers.add_argument("-d", "--decompress", action="store_true")
|
||||
p_helpers.add_argument("--keep-gz", action="store_true")
|
||||
p_helpers.add_argument("-j", "--jobs", type=int, default=1)
|
||||
p_helpers.add_argument("-n", "--dry-run", action="store_true")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
out_dir = Path(args.out)
|
||||
try:
|
||||
catalog = fetch_catalog(args.refresh, out_dir, args.timeout)
|
||||
except (HTTPError, URLError, OSError, RuntimeError, json.JSONDecodeError) as exc:
|
||||
print(f"Could not load the 17Lands catalog: {exc}", file=sys.stderr)
|
||||
return 3
|
||||
|
||||
command = args.command or "list"
|
||||
if command == "list":
|
||||
return cmd_list(catalog, args)
|
||||
if command == "fetch":
|
||||
return cmd_fetch(catalog, args)
|
||||
if command == "helpers":
|
||||
return cmd_helpers(catalog, args)
|
||||
parser.error(f"unknown command {command!r}")
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except KeyboardInterrupt:
|
||||
print("\nInterrupted.", file=sys.stderr)
|
||||
raise SystemExit(130)
|
||||
@@ -0,0 +1,350 @@
|
||||
#!/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)
|
||||
Reference in New Issue
Block a user