File size: 3,244 Bytes
ec6a6cd 62e368e 33d949e 62e368e 0c1723c e799ee4 0c1723c d3c31b7 33d949e e799ee4 33d949e d3c31b7 e799ee4 0c1723c 62e368e 0c1723c 62e368e 0c1723c 38cb927 9d1c4bb d3c31b7 38cb927 9d1c4bb 39b6876 38cb927 62e368e 38cb927 e799ee4 0c1723c 62e368e b6473ab 62e368e 9d1c4bb 62e368e 0c1723c 62e368e 0c1723c 62e368e 0c1723c | 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 | import logging, os
from datasets import (
GeneratorBasedBuilder,
DatasetInfo,
SplitGenerator,
Split,
DownloadManager,
Features,
Value,
Array2D,
Version,
BuilderConfig
)
from datasets.data_files import sanitize_patterns, DataFilesDict
from adversarial_gym.chess_env import ChessEnv
class ChessPGNConfig(BuilderConfig):
def __init__(self, *, data_files: dict, **kwargs):
super().__init__(**kwargs)
# data_files is just {"train":"train/*.pgn", "test":"test/*.pgn"}
self.data_files = data_files
class ChessPGNDataset(GeneratorBasedBuilder):
VERSION = "0.0.1"
BUILDER_CONFIGS = [
ChessPGNConfig(
name="default",
version=Version("0.0.3"), # bump this each time you update the script
description="PGN shards of chess games",
data_files={
"train": "train/*.pgn",
"test": "test/*.pgn",
},
),
]
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 _split_generators(self, dl_manager: DownloadManager):
from pathlib import Path, os
if self.config.data_files:
train_files = self.config.data_files["train"]
test_files = self.config.data_files["test"]
elif self.config.data_dir or self.config.data_files is None:
repo_root = Path(self.config.data_dir)
train_files = [repo_root / 'train' / f for f in os.listdir(repo_root / 'train')]
test_files = [repo_root / 'test' / f for f in os.listdir(repo_root / 'test')]
train_paths = dl_manager.download(train_files)
test_paths = dl_manager.download(test_files)
return [
SplitGenerator(
name=Split.TRAIN,
gen_kwargs={"shards": train_paths},
),
SplitGenerator(
name=Split.TEST,
gen_kwargs={"shards": test_paths},
),
]
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)
|