Datasets:
File size: 4,438 Bytes
ebf9926 | 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 | #!/usr/bin/env python3
"""Export games from the Parquet layout to common text formats.
Formats: jsonl | csv | txt | pgn
Notation: uci (e2e4, as stored) | san (Nf3, O-O) | lan (Ng1-f3, e4xd5)
python export.py data -o games.pgn --format pgn --months 2026-06 --limit 1000
python export.py data -o games.jsonl --format jsonl --notation san --min-elo 2400
python export.py data -o moves.txt --format txt --notation uci # one game per line
SAN/LAN/PGN need python-chess and replay every game (~20-40k games/s per
core); UCI export is a straight copy of the ``moves`` column.
"""
import argparse
import csv
import glob
import json
import os
import sys
import pyarrow.compute as pc
import pyarrow.parquet as pq
META = ["month", "row_idx", "white", "black", "white_elo", "black_elo", "white_title", "black_title",
"result", "termination", "time_control", "eco", "opening", "n_plies"]
def convert(moves_uci, notation):
if notation == "uci":
return moves_uci.split()
import chess
board, out = chess.Board(), []
for u in moves_uci.split():
mv = chess.Move.from_uci(u)
out.append(board.san(mv) if notation == "san" else board.lan(mv))
board.push(mv)
return out
def pgn_text(row):
import chess
board = chess.Board()
headers = {"Event": f"Lichess rated {row['time_control']}", "Site": "lichess.org",
"Date": row["month"].replace("-", ".") + ".??", "White": row["white"] or "?",
"Black": row["black"] or "?", "Result": row["result"], "WhiteElo": row["white_elo"],
"BlackElo": row["black_elo"], "TimeControl": row["time_control"], "ECO": row["eco"] or "?",
"Opening": row["opening"] or "?", "Termination": row["termination"] or "?",
"Annotator": f"chsm8-pre-training {row['month']}#{row['row_idx']}"}
parts = []
for i, u in enumerate(row["moves"].split()):
mv = chess.Move.from_uci(u)
if i % 2 == 0:
parts.append(f"{i // 2 + 1}.")
parts.append(board.san(mv))
board.push(mv)
# moves may stop before the recorded result (15-second clock cut), see README
head = "".join(f'[{k} "{v}"]\n' for k, v in headers.items())
return head + "\n" + " ".join(parts + [row["result"]]) + "\n\n"
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("indir", help="Parquet dataset root (<YYYY-MM>/part-*.parquet)")
ap.add_argument("-o", "--out", default="-")
ap.add_argument("--format", choices=["jsonl", "csv", "txt", "pgn"], default="jsonl")
ap.add_argument("--notation", choices=["uci", "san", "lan"], default="uci")
ap.add_argument("--months", nargs="*")
ap.add_argument("--min-elo", type=int, default=0)
ap.add_argument("--limit", type=int, default=0, help="stop after N games (0 = all)")
a = ap.parse_args()
months = sorted(a.months or [m for m in os.listdir(a.indir) if os.path.isdir(os.path.join(a.indir, m))])
out = sys.stdout if a.out == "-" else open(a.out, "w", newline="")
writer = csv.writer(out) if a.format == "csv" else None
if writer:
writer.writerow(META + ["moves"])
n = 0
for m in months:
for f in sorted(glob.glob(os.path.join(a.indir, m, "*.parquet"))):
t = pq.read_table(f)
if a.min_elo:
t = t.filter(pc.greater_equal(pc.min_element_wise(t["white_elo"], t["black_elo"]), a.min_elo))
for row in t.to_pylist():
if a.format == "pgn":
out.write(pgn_text(row))
else:
moves = convert(row["moves"], a.notation)
if a.format == "jsonl":
out.write(json.dumps({**{k: row[k] for k in META}, "moves": moves}) + "\n")
elif a.format == "csv":
writer.writerow([row[k] for k in META] + [" ".join(moves)])
else:
out.write(" ".join(moves) + "\n")
n += 1
if a.limit and n >= a.limit:
out.close() if out is not sys.stdout else None
print(f"wrote {n:,} games", file=sys.stderr)
return
if out is not sys.stdout:
out.close()
print(f"wrote {n:,} games", file=sys.stderr)
if __name__ == "__main__":
main()
|