File size: 3,958 Bytes
75c683a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/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())