|
import logging |
|
from datasets import ( |
|
GeneratorBasedBuilder, |
|
DatasetInfo, |
|
SplitGenerator, |
|
Split, |
|
DownloadManager, |
|
Features, |
|
Value, |
|
Array2D, |
|
Version, |
|
BuilderConfig |
|
) |
|
from adversarial_gym.chess_env import ChessEnv |
|
|
|
|
|
class ChessPGNConfig(BuilderConfig): |
|
def __init__(self, *, data_files, **kwargs): |
|
super().__init__(**kwargs) |
|
self.data_files = data_files |
|
|
|
|
|
class ChessPGNDataset(GeneratorBasedBuilder): |
|
BUILDER_CONFIGS = [ |
|
ChessPGNConfig( |
|
name="default", |
|
version=Version("0.0.2"), |
|
description="Chess positions + moves + results, streamed from PGN shards", |
|
data_files={ |
|
"train": "train/*.pgn", |
|
"test": "test/*.pgn", |
|
}, |
|
), |
|
] |
|
DEFAULT_CONFIG_NAME = "default" |
|
def _info(self): |
|
return DatasetInfo( |
|
description="Chess positions + moves + results, streamed from PGN shards", |
|
features=Features({ |
|
"state": Array2D((8,8), dtype="int8"), |
|
"action": Value("int16"), |
|
"result": Value("int8"), |
|
}) |
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _generate_examples(self, shards): |
|
import chess.pgn |
|
uid = 0 |
|
|
|
for path in shards: |
|
with open(path, "r") as f: |
|
while (game := chess.pgn.read_game(f)) is not None: |
|
board = game.board() |
|
base = {"1-0":1,"0-1":-1}.get(game.headers["Result"], 0) |
|
for move in game.mainline_moves(): |
|
state = ChessEnv.get_piece_configuration(board) |
|
state = state if board.turn else -state |
|
action = ChessEnv.move_to_action(move) |
|
result = base * (-1 if board.turn == 0 else 1) |
|
yield uid, { |
|
"state": state.astype("int8"), |
|
"action": int(action), |
|
"result": int(result), |
|
} |
|
uid += 1 |
|
board.push(move) |
|
|