File size: 2,029 Bytes
56f9d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b17bca5
56f9d69
 
 
 
 
b17bca5
56f9d69
 
 
b17bca5
56f9d69
 
 
 
d153237
56f9d69
d153237
56f9d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from datasets import (
    GeneratorBasedBuilder, DatasetInfo, SplitGenerator, Split,
    Features, Value, Array2D
)
from adversarial_gym.chess_env import ChessEnv

class ChessPGNDataset(GeneratorBasedBuilder):
    VERSION = "0.0.1"

    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):
        import glob
        # data_dir is the root of your dataset repo
        data_dir = self.config.data_dir
        return [
          SplitGenerator(
            name=Split.TRAIN,
            gen_kwargs={"shards": glob.glob(os.path.join(data_dir,"train","*.pgn"))}
          ),
          SplitGenerator(
            name=Split.TEST,
            gen_kwargs={"shards": glob.glob(os.path.join(data_dir,"test","*.pgn"))}
          ),
        ]

    def _generate_examples(self, shards):
        import chess.pgn
        uid = 0

        for path in sorted(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)