|
| 1 | +""" |
| 2 | +End-to-end pipeline: tournament URL → per-opponent dossiers. |
| 3 | +
|
| 4 | +Usage: |
| 5 | + python -m pipeline.runner Challenge34 |
| 6 | + python -m pipeline.runner Challenge34 --site kingregistration --output-dir ./dossiers |
| 7 | + python -m pipeline.runner "https://chessaction.com/tournaments/advance_entry_list.php?tid=nKGioA==" |
| 8 | + python -m pipeline.runner Challenge34 --max-games 30 --format json |
| 9 | +
|
| 10 | +Output (default): |
| 11 | + <output-dir>/ |
| 12 | + smith_john.md ← one file per opponent |
| 13 | + combined.md ← all dossiers concatenated (print-friendly) |
| 14 | +""" |
| 15 | + |
| 16 | +import re |
| 17 | +import sys |
| 18 | +import argparse |
| 19 | +from pathlib import Path |
| 20 | + |
| 21 | +from scraper import scrape_entry_list |
| 22 | +from dossier.report import build_dossier, render_markdown, render_json |
| 23 | +from pipeline.resolver import resolve_lichess, resolve_chesscom |
| 24 | + |
| 25 | + |
| 26 | +def _slug(name: str) -> str: |
| 27 | + """'Smith, John' → 'smith_john'""" |
| 28 | + return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_") |
| 29 | + |
| 30 | + |
| 31 | +def _fetch_lichess_games(username: str, max_games: int) -> tuple[list[str], dict | None]: |
| 32 | + try: |
| 33 | + from lookup.lichess import get_profile, games_as_pgn |
| 34 | + import io, chess.pgn, time |
| 35 | + profile = get_profile(username) |
| 36 | + time.sleep(1.0) |
| 37 | + pgn_text = games_as_pgn(username, max=max_games) |
| 38 | + pgns = [] |
| 39 | + buf = io.StringIO(pgn_text) |
| 40 | + while True: |
| 41 | + game = chess.pgn.read_game(buf) |
| 42 | + if game is None: |
| 43 | + break |
| 44 | + import io as _io |
| 45 | + out = _io.StringIO() |
| 46 | + game.accept(chess.pgn.FileExporter(out)) |
| 47 | + pgns.append(out.getvalue().strip()) |
| 48 | + return pgns, profile |
| 49 | + except Exception as exc: |
| 50 | + print(f" Lichess fetch failed ({username}): {exc}", file=sys.stderr) |
| 51 | + return [], None |
| 52 | + |
| 53 | + |
| 54 | +def _fetch_chesscom_games(username: str, months: int) -> tuple[list[str], dict | None]: |
| 55 | + try: |
| 56 | + from lookup.chesscom import get_profile, games_as_pgn |
| 57 | + import re as _re |
| 58 | + profile = get_profile(username) |
| 59 | + pgn_text = games_as_pgn(username, months=months) |
| 60 | + pgns = [g for g in _re.split(r"\n(?=\[)", pgn_text.strip()) if g.strip()] |
| 61 | + return pgns, profile |
| 62 | + except Exception as exc: |
| 63 | + print(f" chess.com fetch failed ({username}): {exc}", file=sys.stderr) |
| 64 | + return [], None |
| 65 | + |
| 66 | + |
| 67 | +def run_pipeline( |
| 68 | + tournament: str, |
| 69 | + site: str = "kingregistration", |
| 70 | + output_dir: str = "dossiers", |
| 71 | + max_games: int = 50, |
| 72 | + chesscom_months: int = 3, |
| 73 | + depth: int = 6, |
| 74 | + top: int = 8, |
| 75 | + fmt: str = "markdown", |
| 76 | +) -> list[Path]: |
| 77 | + """ |
| 78 | + Run the full pipeline for a tournament. Returns list of written file paths. |
| 79 | + """ |
| 80 | + out = Path(output_dir) |
| 81 | + out.mkdir(parents=True, exist_ok=True) |
| 82 | + |
| 83 | + print(f"Scraping entry list: {tournament}", file=sys.stderr) |
| 84 | + players = scrape_entry_list(tournament, site=site) |
| 85 | + if not players: |
| 86 | + print("No players found — check the tournament URL.", file=sys.stderr) |
| 87 | + return [] |
| 88 | + print(f"Found {len(players)} player(s).", file=sys.stderr) |
| 89 | + |
| 90 | + written: list[Path] = [] |
| 91 | + combined_parts: list[str] = [] |
| 92 | + |
| 93 | + for i, player in enumerate(players, 1): |
| 94 | + name = player.get("name", "").strip() |
| 95 | + if not name: |
| 96 | + continue |
| 97 | + |
| 98 | + print(f"\n[{i}/{len(players)}] {name}", file=sys.stderr) |
| 99 | + |
| 100 | + pgn_strings: list[str] = [] |
| 101 | + profiles: list[dict] = [] |
| 102 | + |
| 103 | + # --- Lichess --- |
| 104 | + lichess_user, lc_conf = resolve_lichess(name) |
| 105 | + if lichess_user: |
| 106 | + print(f" Lichess: {lichess_user} ({lc_conf} confidence)", file=sys.stderr) |
| 107 | + pgns, profile = _fetch_lichess_games(lichess_user, max_games) |
| 108 | + print(f" Lichess games: {len(pgns)}", file=sys.stderr) |
| 109 | + pgn_strings += pgns |
| 110 | + if profile: |
| 111 | + profiles.append({**profile, "confidence": lc_conf}) |
| 112 | + else: |
| 113 | + print(" Lichess: no match found", file=sys.stderr) |
| 114 | + |
| 115 | + # --- chess.com --- |
| 116 | + cc_user, cc_conf = resolve_chesscom(name) |
| 117 | + if cc_user: |
| 118 | + print(f" chess.com: {cc_user} ({cc_conf} confidence)", file=sys.stderr) |
| 119 | + pgns, profile = _fetch_chesscom_games(cc_user, chesscom_months) |
| 120 | + print(f" chess.com games: {len(pgns)}", file=sys.stderr) |
| 121 | + pgn_strings += pgns |
| 122 | + if profile: |
| 123 | + profiles.append({**profile, "confidence": cc_conf}) |
| 124 | + else: |
| 125 | + print(" chess.com: no match found", file=sys.stderr) |
| 126 | + |
| 127 | + if not pgn_strings: |
| 128 | + print(" No games found — generating skeleton dossier.", file=sys.stderr) |
| 129 | + |
| 130 | + dossier = build_dossier(name, pgn_strings, profiles=profiles, |
| 131 | + depth=depth, top=top) |
| 132 | + |
| 133 | + if fmt == "json": |
| 134 | + content = render_json(dossier) |
| 135 | + ext = "json" |
| 136 | + else: |
| 137 | + content = render_markdown(dossier) |
| 138 | + ext = "md" |
| 139 | + |
| 140 | + path = out / f"{_slug(name)}.{ext}" |
| 141 | + path.write_text(content, encoding="utf-8") |
| 142 | + written.append(path) |
| 143 | + combined_parts.append(content) |
| 144 | + print(f" Saved → {path}", file=sys.stderr) |
| 145 | + |
| 146 | + # --- Combined output --- |
| 147 | + if combined_parts and fmt == "markdown": |
| 148 | + sep = "\n\n---\n\n" |
| 149 | + combined = out / "combined.md" |
| 150 | + combined.write_text(sep.join(combined_parts), encoding="utf-8") |
| 151 | + written.append(combined) |
| 152 | + print(f"\nCombined → {combined}", file=sys.stderr) |
| 153 | + |
| 154 | + print(f"\nDone. {len(players)} dossier(s) written to {out}/", file=sys.stderr) |
| 155 | + return written |
| 156 | + |
| 157 | + |
| 158 | +def main() -> None: |
| 159 | + parser = argparse.ArgumentParser( |
| 160 | + description="Generate dossiers for all opponents in a tournament." |
| 161 | + ) |
| 162 | + parser.add_argument("tournament", help="Tournament ID or full URL") |
| 163 | + parser.add_argument("--site", choices=["kingregistration", "chessaction"], |
| 164 | + default="kingregistration") |
| 165 | + parser.add_argument("--output-dir", default="dossiers", |
| 166 | + help="Directory to write dossier files (default: dossiers/)") |
| 167 | + parser.add_argument("--max-games", type=int, default=50, |
| 168 | + help="Max games to fetch per player from Lichess (default: 50)") |
| 169 | + parser.add_argument("--chesscom-months", type=int, default=3, |
| 170 | + help="Months of chess.com history to fetch (default: 3)") |
| 171 | + parser.add_argument("--depth", type=int, default=6, |
| 172 | + help="Opening depth in half-moves (default: 6)") |
| 173 | + parser.add_argument("--top", type=int, default=8, |
| 174 | + help="Top N opening lines per colour (default: 8)") |
| 175 | + parser.add_argument("--format", dest="fmt", choices=["markdown", "json"], |
| 176 | + default="markdown") |
| 177 | + args = parser.parse_args() |
| 178 | + |
| 179 | + run_pipeline( |
| 180 | + args.tournament, |
| 181 | + site=args.site, |
| 182 | + output_dir=args.output_dir, |
| 183 | + max_games=args.max_games, |
| 184 | + chesscom_months=args.chesscom_months, |
| 185 | + depth=args.depth, |
| 186 | + top=args.top, |
| 187 | + fmt=args.fmt, |
| 188 | + ) |
| 189 | + |
| 190 | + |
| 191 | +if __name__ == "__main__": |
| 192 | + main() |
0 commit comments