opa-traint / scripts /build_puzzles.py
lukehola's picture
Deploy Opa Traint
75c683a verified
Raw History Blame Contribute Delete
3.96 kB
#!/usr/bin/env python3
"""Build content/puzzles.json from the Lichess puzzle database (run once, locally).
The Lichess puzzle DB is CC0: https://database.lichess.org/#puzzles
Download: https://database.lichess.org/lichess_db_puzzle.csv.zst
Lichess format note: the CSV's FEN is the position *before* the opponent's
setup move, and Moves[0] is that opponent move. This script applies Moves[0]
to the FEN so that our puzzles.json stores the position with the *solver* to
move and `moves` starting with the solver's move — the format the app expects.
Usage:
pip install zstandard python-chess
python scripts/build_puzzles.py lichess_db_puzzle.csv.zst \
--min-rating 1400 --max-rating 1800 --min-popularity 90 \
--max-plies 4 --count 2000
"""
from __future__ import annotations
import argparse
import csv
import io
import json
import random
import sys
from pathlib import Path
OUT_PATH = Path(__file__).resolve().parent.parent / "content" / "puzzles.json"
def open_csv(path: str):
if path.endswith(".zst"):
import zstandard # pip install zstandard
fh = open(path, "rb")
reader = zstandard.ZstdDecompressor().stream_reader(fh)
return io.TextIOWrapper(reader, encoding="utf-8")
return open(path, encoding="utf-8")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("csv_path", help="lichess_db_puzzle.csv[.zst]")
ap.add_argument("--min-rating", type=int, default=1400)
ap.add_argument("--max-rating", type=int, default=1800)
ap.add_argument("--min-popularity", type=int, default=90)
ap.add_argument("--max-plies", type=int, default=4,
help="max solution length in plies (solver+opponent moves)")
ap.add_argument("--count", type=int, default=2000)
ap.add_argument("--seed", type=int, default=42)
args = ap.parse_args()
try:
import chess # pip install python-chess
except ImportError:
print("Please: pip install python-chess zstandard", file=sys.stderr)
return 1
candidates = []
with open_csv(args.csv_path) as f:
for row in csv.DictReader(f):
try:
rating = int(row["Rating"])
popularity = int(row["Popularity"])
except (KeyError, ValueError):
continue
if not (args.min_rating <= rating <= args.max_rating):
continue
if popularity < args.min_popularity:
continue
moves = row["Moves"].split()
# moves[0] is the opponent's setup move; the rest is the solution.
if len(moves) - 1 > args.max_plies or len(moves) < 2:
continue
candidates.append((row["FEN"], moves, rating, row.get("Themes", "")))
print(f"{len(candidates)} candidate puzzles after filtering")
random.Random(args.seed).shuffle(candidates)
puzzles = []
for fen, moves, rating, themes in candidates:
if len(puzzles) >= args.count:
break
try:
board = chess.Board(fen)
board.push_uci(moves[0]) # apply opponent setup move
solver_fen = board.fen()
# Sanity check: full solution line must be legal.
for m in moves[1:]:
board.push_uci(m)
except Exception:
continue
puzzles.append({
"fen": solver_fen,
"moves": moves[1:],
"rating": rating,
"themes": themes.split(),
})
OUT_PATH.write_text(json.dumps({
"_comment": "Generated by scripts/build_puzzles.py from the Lichess CC0 puzzle DB. "
"FEN = solver to move; moves = solution line. Ratings are never shown in the app.",
"puzzles": puzzles,
}, indent=1), encoding="utf-8")
print(f"wrote {len(puzzles)} puzzles -> {OUT_PATH}")
return 0
if __name__ == "__main__":
raise SystemExit(main())