Files
mtga/scripts/merge_snapshots.py
T
fukunee 58446ec562 Add TRK set preview and refresh draft analysis
Track the TRK preview package and the newest value artifacts for FRA20261007, move the 17lands API notes under data, and ignore downloaded 17lands, card image and live directories.
2026-11-15 11:37:16 +08:00

155 lines
5.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""把多个 17lands 快照目录合并成一份(按主键去重)。
用途:17Lands 的奖杯窗口是滚动的,单次抓取只覆盖约 1~2 天;定期抓取后把各批
` data/17lands/<SET><DATE>/ ` 合并,得到更大的样本再重建 `value/`。
用法(可复现):
python scripts/merge_snapshots.py --out data/17lands/FRA20261011 \
data/17lands/FRA20261007 data/17lands/FRA20261011
规则:
* jsonl(index/decks/drafts):按各自主键去重,追加写出;已去重的输入会被跳过。
* draftdata/ :文件名 = draft_id,直接并集拷贝。
* replays/ :以 `replay_index.jsonl` 的 history_path 为准并集拷贝 *.json.gz。
* stats/ :默认保留第一个存在的(聚合数据不合并;可用 --stats-from 指定)。
* 不删除任何源文件;--out 与某个输入相同则原地合并(先写 .orig 备份)。
"""
from __future__ import annotations
import argparse
import json
import shutil
from pathlib import Path
# 每个 jsonl 的主键
KEYS = {
"trophies/trophies_index.jsonl": lambda r: r.get("aggregate_id"),
"trophies/trophies_decks.jsonl": lambda r: (r.get("aggregate_id"), r.get("deck_index")),
"drafts/draft_picks.jsonl": lambda r: r.get("draft_id"),
"drafts/event_details.jsonl": lambda r: r.get("draft_id"),
}
def load_jsonl(p: Path):
if not p.exists():
return []
out = []
for ln in p.read_text(encoding="utf-8").splitlines():
if ln.strip():
try:
out.append(json.loads(ln))
except json.JSONDecodeError:
pass
return out
def merge_jsonl(out_root: Path, sources: list[Path], rel: str, keyfn) -> tuple[int, int]:
seen, rows = set(), []
for s in sources:
for r in load_jsonl(s / rel):
k = keyfn(r)
if k is None or k in seen:
continue
seen.add(k)
rows.append(json.dumps(r, ensure_ascii=False))
if not rows:
return 0, 0
dest = out_root / rel
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists() and dest not in [None]:
shutil.copy2(dest, dest.with_suffix(dest.suffix + ".orig")) if not dest.with_suffix(
dest.suffix + ".orig").exists() else None
dest.write_text("\n".join(rows) + "\n", encoding="utf-8")
return len(seen), len(rows)
def merge_dir(out_root: Path, sources: list[Path], rel: str, suffix: str) -> int:
dest = out_root / rel
dest.mkdir(parents=True, exist_ok=True)
have = {p.name for p in dest.glob("*" + suffix)}
added = 0
for s in sources:
d = s / rel
if not d.exists():
continue
for f in d.glob("*" + suffix):
if f.name not in have:
shutil.copy2(f, dest / f.name)
have.add(f.name)
added += 1
return added
def merge_replays(out_root: Path, sources: list[Path]) -> tuple[int, int]:
"""以 replay_index.jsonl 的 history_path 并集拷贝 gz。"""
paths, seen = [], set()
for s in sources:
for r in load_jsonl(s / "replays/replay_index.jsonl"):
hp = r.get("history_path")
if hp and hp not in seen:
seen.add(hp)
paths.append(r)
# 源里可能只有 gz 没有 index:也扫一遍
for gz in (s / "replays").rglob("*.json.gz"):
hp = gz.relative_to(s / "replays").as_posix()[:-len(".json.gz")]
if hp not in seen:
seen.add(hp)
paths.append({"history_path": hp})
dest = out_root / "replays"
dest.mkdir(parents=True, exist_ok=True)
(dest / "replay_index.jsonl").write_text(
"\n".join(json.dumps(r, ensure_ascii=False) for r in paths) + "\n", encoding="utf-8")
have = {p.relative_to(dest).as_posix()[:-len(".json.gz")] for p in dest.rglob("*.json.gz")}
missing = [r["history_path"] for r in paths if r["history_path"] not in have]
added = 0
for hp in missing:
for s in sources:
src = s / "replays" / (hp + ".json.gz")
if src.exists():
d = dest / (hp + ".json.gz")
d.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, d)
added += 1
break
return len(paths), added
def main() -> int:
ap = argparse.ArgumentParser(description="合并多个 17lands 快照(去重)")
ap.add_argument("sources", nargs="+", help="源快照目录,按优先级从左到右")
ap.add_argument("--out", required=True, help="输出/原地合并目录")
ap.add_argument("--stats-from", default=None, help="stats/ 从哪个源取(默认第一个有 stats 的)")
ap.add_argument("--skip-replays", action="store_true")
a = ap.parse_args()
sources = [Path(s) for s in a.sources]
out_root = Path(a.out)
out_root.mkdir(parents=True, exist_ok=True)
for rel, keyfn in KEYS.items():
u, n = merge_jsonl(out_root, sources, rel, keyfn)
print(f" {rel:32s} -> {u} unique")
n = merge_dir(out_root, sources, "draftdata", ".json")
print(f" draftdata/ +{n} files -> "
f"{len(list((out_root / 'draftdata').glob('*.json')))}")
if not a.skip_replays:
total, added = merge_replays(out_root, sources)
print(f" replays/ index={total} +{added} gz -> "
f"{len(list((out_root / 'replays').rglob('*.json.gz')))}")
# stats:取一个源(聚合数据不合并)
if not (out_root / "stats/card_data.json").exists():
src = Path(a.stats_from) if a.stats_from else next(
(s for s in sources if (s / "stats/card_data.json").exists()), None)
if src:
shutil.copytree(src / "stats", out_root / "stats", dirs_exist_ok=True)
print(f" stats/ copied from {src}")
return 0
if __name__ == "__main__":
raise SystemExit(main())