File size: 7,682 Bytes
5842de6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

import chess.pgn
import chess
import numpy as np
from tqdm.notebook import tqdm


def extract_moves_from_pgn(pgn_path:str, max_games=None) -> np.ndarray:
    all_moves = []

    def is_improper_piece(piece_type):
        return piece_type in {chess.PAWN, chess.ROOK, chess.KING}

    def make_starting_position_move(board):
        setup = ['X', '->']
        parts = []

        for square in chess.SQUARES:
            piece = board.piece_at(square)
            if piece:
                color = 'w' if piece.color == chess.WHITE else 'b'
                symbol = piece.symbol().upper()
                square_name = chess.square_name(square)
                if is_improper_piece(piece.piece_type):
                    piece_id = f"{symbol.lower()}{color}"
                else:
                    piece_id = f"{symbol}{color}"
                parts.extend([piece_id, square_name])

        for i in range(0, len(parts), 2):
            if i > 0:
                setup.append('&')
            setup.extend(parts[i:i+2])

        return setup

    def get_piece_id(piece, color, square, moved_from):
        symbol = piece.symbol().upper()
        if square not in moved_from and is_improper_piece(piece.piece_type):
            return f"{symbol.lower()}{color}"
        return f"{symbol}{color}"

    with open(pgn_path) as pgn:
        progress   = tqdm(desc="Processing Games", unit="games", dynamic_ncols=True, leave=True)
        game_count = 0
        while True:
            game = chess.pgn.read_game(pgn)
            if game is None or (max_games is not None and game_count >= max_games):
                    break
            game_count += 1

            fen = game.headers.get("FEN", chess.STARTING_FEN)
            board = chess.Board(fen)

            moved_from = set()
            game_moves = []

            game_moves.append(['<S>'])
            game_moves.append(make_starting_position_move(board))

            for move in game.mainline_moves():
                from_sq = move.from_square
                to_sq = move.to_square
                from_sq_name = chess.square_name(from_sq)
                to_sq_name = chess.square_name(to_sq)

                moving_piece = board.piece_at(from_sq)
                color = 'w' if moving_piece.color == chess.WHITE else 'b'
                piece_id_before = get_piece_id(moving_piece, color, from_sq_name, moved_from)

                # fallback castling detection if castling_rook_square() is not available
                if board.is_castling(move):
                    king_move = [piece_id_before, from_sq_name, '->', piece_id_before, to_sq_name]

                    fen_before = board.fen()
                    board_before = chess.Board(fen_before)
                    rooks_before = set(sq for sq in board_before.pieces(chess.ROOK, moving_piece.color))

                    board.push(move)

                    rooks_after = set(sq for sq in board.pieces(chess.ROOK, moving_piece.color))

                    rook_from_sq = list(rooks_before - rooks_after)
                    rook_to_sq = list(rooks_after - rooks_before)

                    if not rook_from_sq and not rook_to_sq:
                        # ✅ Rook didn't move (legal in Chess960), no second action needed
                        moved_from.add(from_sq_name)
                        game_moves.append(king_move)
                        continue

                    if len(rook_from_sq) == 1 and len(rook_to_sq) == 1:
                        rook_from = chess.square_name(rook_from_sq[0])
                        rook_to = chess.square_name(rook_to_sq[0])
                        rook_piece = board.piece_at(rook_to_sq[0])
                        rook_id = get_piece_id(rook_piece, color, rook_from, moved_from)

                        rook_move = [rook_id, rook_from, '->', rook_id, rook_to]
                        action = king_move + ['&'] + rook_move
                        moved_from.update([from_sq_name, rook_from])
                        game_moves.append(action)
                        continue

                    # Still couldn't determine rook move
                    print(f"\n⚠️  Warning: Could not determine rook move during castling at {from_sq_name}->{to_sq_name}")
                    print("→ PGN headers:")
                    for key, val in game.headers.items():
                        print(f"[{key} \"{val}\"]")
                    print("→ Current FEN before move:")
                    print(fen_before)
                    print("→ Move UCI:", move.uci())
                    print("→ Rooks before:", [chess.square_name(sq) for sq in rooks_before])
                    print("→ Rooks after:", [chess.square_name(sq) for sq in rooks_after])
                    print("→ Difference:")
                    print("    Disappeared:", [chess.square_name(sq) for sq in rooks_before - rooks_after])
                    print("    Appeared:", [chess.square_name(sq) for sq in rooks_after - rooks_before])
                    print()

                    game_moves.append(king_move)
                    continue

                captured_piece = board.piece_at(to_sq)
                board.push(move)

                new_piece = board.piece_at(to_sq)
                piece_id_after = f"{new_piece.symbol().upper()}{color}"

                action = [piece_id_before, from_sq_name, '->', piece_id_after, to_sq_name]
                moved_from.add(from_sq_name)

                if board.is_en_passant(move):
                    capture_sq = chess.square_name(to_sq + (8 if color == 'b' else -8))
                    action += ['&', f"P{'w' if color == 'b' else 'b'}", capture_sq, '->', 'X']

                elif captured_piece:
                    captured_id = f"{captured_piece.symbol().upper()}{'w' if captured_piece.color == chess.WHITE else 'b'}"
                    action += ['&', captured_id, to_sq_name, '->', 'X']

                game_moves.append(action)

            result = game.headers.get("Result", "*")
            game_moves.append([result])
            game_moves.append(['<E>'])

            all_moves.extend(game_moves)
            progress.update(1)
            
            
        progress.close()


    # 🔽 Final flattening step to yield List[str]
    flattened = []
    for move in all_moves:
        flattened.extend(move)
        flattened.append(',')  # comma delimiter

    if flattened:
        flattened.pop()  # Remove last comma


    # Step 2: Token dictionary
    NORMALIZE_MAP = {
    '½-½': '1/2-1/2',
    '1-0': '1-0',
    '0-1': '0-1',
    # Just in case someone uses space around dashes
    '1 - 0': '1-0',
    '0 - 1': '0-1',
    '1/2 - 1/2': '1/2-1/2',
    '½ - ½': '1/2-1/2',
    }
    tokens   = ['<S>', '<E>', '->', '&', ',', 'X']
    files    = 'abcdefgh'
    ranks    = '12345678'
    squares  = [f + r for r in ranks for f in files]
    tokens  += squares
    pieces   = ['P', 'p', 'R', 'r', 'N', 'B', 'Q', 'K', 'k']
    colors   = ['w', 'b']
    tokens  += [p + c for p in pieces for c in colors]
    annotations = ['!!', '!', '!?', '?!', '?', '??', '+', '#', '+−', '−+']
    results     = ['1-0', '0-1', '1/2-1/2']
    tokens     += annotations + results
    str_2_int = {token: idx for idx, token in enumerate(tokens)}

    # Step 3: Convert to integer list
    int_tokens = []
    for token in flattened:
        token = NORMALIZE_MAP.get(token, token)  # normalize if needed
        if token in str_2_int:
            int_tokens.append(str_2_int[token])
        else:
            raise ValueError(f"Unknown token: {token}")

    # Step 4: Convert to numpy array
    arr = np.array(int_tokens, dtype=np.int8)

    return arr