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(['']) 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(['']) 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 = ['', '', '->', '&', ',', '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