chessai.core.gameparser
1import enum 2import gzip 3import logging 4import os 5import random 6import re 7import typing 8 9import edq.util.serial 10 11import chessai.core.action 12import chessai.core.board 13import chessai.core.castling 14import chessai.core.coordinate 15import chessai.core.gameannotation 16import chessai.core.gamestate 17import chessai.core.piece 18import chessai.core.types 19 20THIS_DIR: str = os.path.join(os.path.dirname(os.path.realpath(__file__))) 21GAMES_DIR: str = os.path.join(THIS_DIR, '..', 'resources', 'games') 22 23PGN_FILE_EXTENSION: str = '.pgn' 24GZIP_FILE_EXTENSION: str = '.gz' 25 26DEFAULT_ENCODING: str = 'utf-8' 27 28# File parsing patterns. 29SEPARATOR_PATTERN: re.Pattern = re.compile(r'^\s*-{3,}\s*$') 30 31# PGN parsing patterns. 32TAG_PATTERN: re.Pattern= re.compile(r"^\[([A-Za-z0-9][A-Za-z0-9_+#=:-]*)\s+\"([^\r]*)\"\]\s*$") 33TAG_NAME_PATTERN: re.Pattern = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_+#=:-]*\Z") 34MOVETEXT_PATTERN: re.Pattern = re.compile(r""" 35 ( 36 [NBKRQ]?[a-h]?[1-8]?[\-x]?[a-h][1-8](?:=?[nbrqkNBRQK])? 37 |[PNBRQK]?@[a-h][1-8] 38 |-- 39 |Z0 40 |0000 41 |@@@@ 42 |O-O(?:-O)? 43 |0-0(?:-0)? 44 ) 45 |(\{.*?}) 46 |(\{.*) 47 |(;.*) 48 |(\$[0-9]+) 49 |(\() 50 |(\)) 51 |(\*|1-0|0-1|1/2-1/2) 52 |([\?!]{1,2}) 53 """, re.DOTALL | re.VERBOSE) 54 55SKIP_MOVETEXT_PATTERN: re.Pattern = re.compile(r""";|\{|\}""") 56 57FEN_HEADER_KEY: str = 'FEN' 58SET_UP_HEADER_KEY: str = 'SetUp' 59 60MAX_PGN_LINE_LENGTH: int = 80 61 62PGN_HEADERS: list[str] = [ 63 "event", 64 "site", 65 "date", 66 "round", 67 "white", 68 "black", 69 "result", 70] 71 72class StandardHeaders(edq.util.serial.DictConverter): 73 """ 74 These seven standard tags will always be present in the headers: 75 - Event: the name of the tournament or match event 76 - Site: the location of the event 77 - Date: the starting date of the game 78 - Round: the playing round ordinal of the game 79 - White: the player of the white pieces 80 - Black: the player of the black pieces 81 - Result: the result of the game 82 83 To see the full description of the possible headers and their format, 84 see https://www.saremba.de/chessgml/standards/pgn/pgn-complete.htm#c8.1 . 85 """ 86 87 def __init__(self, 88 event: str = "?", 89 site: str = "?", 90 date: str = "????.??.??", 91 game_round: str = "?", 92 white: str = "?", 93 black: str = "?", 94 result: str = "*", 95 ) -> None: 96 self.event: str = event 97 """ The name of the tournament or match event. """ 98 99 self.site: str = site 100 """ The location of the event. """ 101 102 self.date: str = date 103 """ The starting date of the game. """ 104 105 self.round: str = game_round 106 """ The playing round ordinal of the game. """ 107 108 self.white: str = white 109 """ The player of the white pieces. """ 110 111 self.black: str = black 112 """ The player of the black pieces. """ 113 114 self.result: str = result 115 """ The result of the game. """ 116 117 def _set(self, attribute: str, value: str) -> None: 118 """ Update the header attribute to the given value. """ 119 120 match attribute.lower(): 121 case "event": 122 self.event = value 123 case "site": 124 self.site = value 125 case "date": 126 self.date = value 127 case "round": 128 self.round = value 129 case "white": 130 self.white = value 131 case "black": 132 self.black = value 133 case "result": 134 self.result = value 135 case _: 136 return 137 138 def to_pgn(self) -> list[str]: 139 """ Convert the headers to a list of PGN tags. """ 140 141 tags: list[str] = [] 142 143 tags.append(_to_tag("Event", self.event)) 144 tags.append(_to_tag("Site", self.site)) 145 tags.append(_to_tag("Date", self.date)) 146 tags.append(_to_tag("Round", self.round)) 147 tags.append(_to_tag("White", self.white)) 148 tags.append(_to_tag("Black", self.black)) 149 tags.append(_to_tag("Result", self.result)) 150 151 return tags 152 153 def __eq__(self, other: object) -> bool: 154 if (not isinstance(other, StandardHeaders)): 155 return False 156 157 return (self.event == other.event 158 and self.site == other.site 159 and self.date == other.date 160 and self.round == other.round 161 and self.white == other.white 162 and self.black == other.black 163 and self.result == other.result) 164 165class PGNResult(str, enum.Enum): 166 """ The possible game endings denoted in a PGN. """ 167 168 WHITE_WIN = '1-0' 169 """ White won the game. """ 170 171 BLACK_WIN = '0-1' 172 """ Black won the game. """ 173 174 TIE = '1/2-1/2' 175 """ The game was a tie. """ 176 177 IN_PROGRESS = '*' 178 """ The game is still in progress. """ 179 180 UNKNOWN = 'Unknown' 181 """ The ending of the game is unknown. """ 182 183class ParsedPGN(edq.util.serial.DictConverter): 184 """ 185 The parsed result of a single PGN game. 186 """ 187 188 def __init__(self, 189 headers: StandardHeaders | None = None, 190 optional_headers: dict[str, typing.Any] | None = None, 191 starting_fen: str | None = None, 192 initial_actions: list[chessai.core.action.Action] | None = None, 193 comments: list[str] | None = None, 194 result: PGNResult = PGNResult.UNKNOWN) -> None: 195 196 if (headers is None): 197 headers = StandardHeaders() 198 199 self.headers: StandardHeaders = headers 200 """ The standard headers from a single PGN game. """ 201 202 if (optional_headers is None): 203 optional_headers = {} 204 205 self.optional_headers: dict[str, typing.Any] = optional_headers 206 """ Any additional headers parsed from the PGN. """ 207 208 self.starting_fen: str | None = starting_fen 209 """ The starting FEN for the game, which is often omitted to denote the default FEN. """ 210 211 if (initial_actions is None): 212 initial_actions = [] 213 214 self.initial_actions: list[chessai.core.action.Action] = initial_actions 215 """ The mainline moves in the game. """ 216 217 if (comments is None): 218 comments = [] 219 220 self.comments: list[str] = comments 221 """ The comments found in the game. """ 222 223 self.result: PGNResult = result 224 """ The result of the PGN or if the game is still in progress. """ 225 226 def get_starting_fen(self) -> str | None: 227 """ Get the optional FEN header from the PGN. """ 228 229 return self.optional_headers.get(FEN_HEADER_KEY, None) 230 231 def get_game_rating_annotation(self) -> chessai.core.gameannotation.GameRatingAnnotation | None: 232 """ Get the optional typed engine-rating annotation stored in this PGN. """ 233 234 value = self.optional_headers.get(chessai.core.gameannotation.GAME_RATING_ANNOTATION_HEADER, None) 235 if (value is None): 236 return None 237 238 if (not isinstance(value, str)): 239 raise ValueError('The game rating annotation header must be a string.') 240 241 return chessai.core.gameannotation.GameRatingAnnotation.from_header_value(value) 242 243def parse_pgn(pgn: str, state_class: typing.Type[chessai.core.gamestate.GameState]) -> ParsedPGN | None: 244 """ 245 Parse a single PGN string into a ParsedPGN. 246 247 Raises ValueError if the PGN is malformed. 248 See https://en.wikipedia.org/wiki/Portable_Game_Notation . 249 """ 250 251 lines = pgn.splitlines() 252 253 # If it is only one line, try loading it from a file. 254 if (len(lines) == 1): 255 pgn = load_pgn_from_file(pgn) 256 lines = pgn.splitlines() 257 258 index = 0 259 260 headers: StandardHeaders = StandardHeaders() 261 262 optional_headers: dict[str, typing.Any] = {} 263 264 # Parse the header fields. 265 for i, line in enumerate(lines): 266 # Track where we are in the lines. 267 index = i 268 269 clean_line = line.strip() 270 271 # Skip empty lines. 272 if (len(line) == 0): 273 continue 274 275 # Skip comments. 276 if (_is_pgn_comment_line(clean_line)): 277 continue 278 279 # Headers must begin with an open bracket. 280 if (not clean_line.startswith("[")): 281 break 282 283 tag_match = TAG_PATTERN.match(clean_line) 284 285 # Ignore malformed tags. 286 if (not tag_match): 287 continue 288 289 tag_header_key = tag_match.group(1) 290 tag_header_value = _unescape_tag_value(tag_match.group(2)) 291 292 # Determine if this is a standard header key or not. 293 if (tag_header_key.lower() in PGN_HEADERS): 294 headers._set(tag_header_key, tag_header_value) 295 else: 296 optional_headers[tag_header_key] = tag_header_value 297 298 # No game found. 299 if (headers == StandardHeaders()): 300 return None 301 302 # Start scanning for moves from the end of the headers. 303 lines = lines[index:] 304 305 # Set up a gamestate to follow along and parse SANs. 306 fen = optional_headers.get(FEN_HEADER_KEY, None) 307 state = state_class.from_fen(fen = fen) 308 rng = random.Random(1) 309 310 initial_actions: list[chessai.core.action.Action] = [] 311 comments: list[str] = [] 312 result: PGNResult = PGNResult.UNKNOWN 313 314 in_comment = False 315 comment_buffer: list[str] = [] 316 317 skip_variation_depth = 0 318 319 for line in lines: 320 line = line.strip() 321 322 if (not line): 323 break 324 325 # Skip whole-line comments. 326 if _is_pgn_comment_line(line): 327 continue 328 329 i = 0 330 while (i < len(line)): 331 if in_comment: 332 end_index = line.find("}", i) 333 334 # The rest of the line is part of the comment. 335 if (end_index == -1): 336 comment_buffer.append(line[i:]) 337 break 338 339 # Add the remainder of the comment and continue processing the current line. 340 comment_buffer.append(line[i:end_index]) 341 comments.append("\n".join(comment_buffer).strip()) 342 343 comment_buffer = [] 344 in_comment = False 345 346 i = end_index + 1 347 348 continue 349 350 match = MOVETEXT_PATTERN.match(line, i) 351 352 if (not match): 353 i += 1 354 continue 355 356 token = match.group(0) 357 i = match.end() 358 359 # Handle block comments {...}. 360 if token.startswith("{"): 361 content = token[1:] 362 363 end_index = content.find("}") 364 365 if (end_index == -1): 366 # Track part of a multi-line comment. 367 in_comment = True 368 comment_buffer.append(content) 369 else: 370 # Add the in-line comment and continue processing this line. 371 comments.append(content[:end_index].strip()) 372 373 continue 374 375 # Skip variations (...) entirely. 376 if (token == "("): 377 skip_variation_depth += 1 378 continue 379 380 if (token == ")"): 381 if (skip_variation_depth > 0): 382 skip_variation_depth -= 1 383 384 continue 385 386 if (skip_variation_depth > 0): 387 continue 388 389 # Skip line comments. 390 if token.startswith(";"): 391 break 392 393 # Skip move numbers like "1." or "23.". 394 if token.endswith("."): 395 continue 396 397 # Skip results. 398 if (token in ["1-0", "0-1", "1/2-1/2", "*"]): 399 result = PGNResult(token) 400 break 401 402 # Skip NAGs / annotations. 403 if (token.startswith("$") or (token in ["!", "?", "!!", "??", "!?", "?!"])): 404 continue 405 406 # Otherwise, this must be a SAN move. 407 action = state.get_action_from_san(token) 408 if (action == chessai.core.action.NoneAction()): 409 raise ValueError(f"Unable to find a legal action for the SAN: '{token}'.") 410 411 state.process_turn_full(action, rng) 412 initial_actions.append(action) 413 414 # Check if the gamestate agrees with the expected result. 415 if ((result in [PGNResult.WHITE_WIN, PGNResult.BLACK_WIN]) and (not state.is_game_over())): 416 # The game is not over when the PGN believes it should be, so add a forfeit action. 417 initial_actions.append(chessai.core.action.ForfeitAction()) 418 419 if ((result == PGNResult.TIE) and (not state.is_game_over())): 420 # The game must be a proposed draw, so add the draw handshake. 421 initial_actions.append(chessai.core.action.ProposeDrawAction()) 422 initial_actions.append(chessai.core.action.AcceptDrawAction()) 423 424 return ParsedPGN( 425 headers = headers, 426 optional_headers = optional_headers, 427 initial_actions = initial_actions, 428 comments = comments, 429 result = result, 430 ) 431 432def load_pgn_from_file(path: str) -> str: 433 """ 434 Load the PGN string from a file. 435 436 If the given path does not exist, 437 try to prefix the path with the standard game directory and suffix with the standard extension. 438 """ 439 440 raw_path = path 441 442 # If the path does not exist, try the boards directory. 443 if (not os.path.exists(path)): 444 path = os.path.join(GAMES_DIR, path) 445 446 # If this path does not have a good extension, add one. 447 if ((os.path.splitext(path)[-1] != PGN_FILE_EXTENSION) and (os.path.splitext(path)[-1] != GZIP_FILE_EXTENSION)): 448 path = path + PGN_FILE_EXTENSION 449 450 # If the path still does not exist, try adding the GZip extension. 451 if (not os.path.exists(path)): 452 if (os.path.splitext(path)[-1] != GZIP_FILE_EXTENSION): 453 path = path + GZIP_FILE_EXTENSION 454 455 if (not os.path.exists(path)): 456 raise ValueError(f"Could not find PGN file, path does not exist: '{raw_path}'.") 457 458 if (os.path.splitext(path)[-1] == GZIP_FILE_EXTENSION): 459 return load_pgn_from_gzip(path) 460 461 contents = edq.util.dirent.read_file(path, strip = False) 462 return contents 463 464def load_pgn_from_gzip(path: str) -> str: 465 """ 466 Load the PGN string from a file. 467 468 If the given path does not exist, 469 try to prefix the path with the standard game directory and suffix with the standard extension. 470 """ 471 472 raw_path = path 473 474 # If the path does not exist, try the boards directory. 475 if (not os.path.exists(path)): 476 path = os.path.join(GAMES_DIR, path) 477 478 # If this path does not have a good extension, add one. 479 if (os.path.splitext(path)[-1] != GZIP_FILE_EXTENSION): 480 path = path + GZIP_FILE_EXTENSION 481 482 if (not os.path.exists(path)): 483 raise ValueError(f"Could not find PGN file, path does not exist: '{raw_path}'.") 484 485 with gzip.open(path, 'rb') as file: 486 uncompressed_contents = file.read() 487 decompressed_contents = uncompressed_contents.decode(DEFAULT_ENCODING) 488 489 return decompressed_contents 490 491def to_pgn(headers: StandardHeaders, optional_headers: dict[str, typing.Any], 492 state_class: typing.Type[chessai.core.gamestate.GameState], start_fen: str, 493 actions: list[chessai.core.action.Action]) -> str: 494 """ 495 Convert a game into a PGN. 496 497 Raises an error if any of the seven required headers are missing. 498 If a move cannot be generated from an action and gamestate pair, an error is raised. 499 """ 500 501 lines: list[str] = headers.to_pgn() 502 503 # Non-default starting FENs require additional PGN information. 504 if (start_fen != chessai.core.gamestate.DEFAULT_FEN): 505 lines.append(_to_tag(SET_UP_HEADER_KEY, '1')) 506 lines.append(_to_tag(FEN_HEADER_KEY, start_fen)) 507 508 # Add optional headers. 509 for (key, value) in optional_headers.items(): 510 try: 511 str_value = str(value) 512 except Exception: 513 logging.warning("Could not convert optional header value for key '%s' to a string.", key) 514 continue 515 516 lines.append(_to_tag(str(key), str_value)) 517 518 # Add an extra blank line after the header section. 519 lines.append('') 520 521 # Build the move SAN tokens while replaying the game. 522 state = state_class.from_fen(fen = start_fen) 523 pgn_tokens: list[str] = [] 524 current_fullmove_number = 0 525 526 for action in actions: 527 # Ignore meta actions as they do not have a valid SAN representation. 528 if (not isinstance(action, chessai.core.action.MoveAction)): 529 continue 530 531 if (state.fullmove_number != current_fullmove_number): 532 pgn_tokens.append(f"{state.fullmove_number}.") 533 current_fullmove_number = state.fullmove_number 534 535 san = _action_to_san(action, state) 536 pgn_tokens.append(san) 537 538 state.push(action) 539 540 # Add the result token. 541 pgn_tokens.append(headers.result) 542 543 movetext_lines: list[str] = [] 544 current_line = '' 545 546 for token in pgn_tokens: 547 if (len(current_line) == 0): 548 candidate_line = token 549 else: 550 candidate_line = f"{current_line} {token}" 551 552 # Keep building a line until it surpasses the max line length. 553 if (len(candidate_line) <= MAX_PGN_LINE_LENGTH): 554 current_line = candidate_line 555 else: 556 movetext_lines.append(current_line) 557 current_line = token 558 559 if (len(current_line) > 0): 560 movetext_lines.append(current_line) 561 562 lines.extend(movetext_lines) 563 564 # Add a trailing newline after the movetext. 565 lines.append('') 566 567 return '\n'.join(lines) 568 569def _escape_tag_value(value: str) -> str: 570 """ Escape the tag value to avoid parsing errors. """ 571 572 escaped = value.replace('\\', '\\\\').replace('"', '\\"') 573 return escaped 574 575def _unescape_tag_value(value: str) -> str: 576 """ Unescape a PGN tag value parsed from its surrounding quotes. """ 577 578 unescaped = '' 579 escaped = False 580 for character in value: 581 if (escaped): 582 unescaped += character 583 escaped = False 584 elif (character == '\\'): 585 escaped = True 586 else: 587 unescaped += character 588 589 if (escaped): 590 unescaped += '\\' 591 592 return unescaped 593 594def _to_tag(header: str, value: str) -> str: 595 """ Write a header and its value to a PGN tag. """ 596 597 escaped_value = _escape_tag_value(value) 598 return f'[{header} "{escaped_value}"]' 599 600def _action_to_san(action: chessai.core.action.MoveAction, state: chessai.core.gamestate.GameState) -> str: 601 """ 602 Convert an action to a SAN using the state before the action is applied evaluate SAN move ambiguity. 603 604 This method does not understand meta actions (i.e., forfeits or draw actions). 605 """ 606 607 piece = state.get(action.start_coordinate) 608 if (piece is None): 609 raise ValueError(f"The start coordinate for action '{action.uci()}' does not have a piece.") 610 611 piece_symbol_upper = piece.symbol().upper() 612 613 move_san: str | None = None 614 615 # Detect castling by checking for a king moving two squares horizontally. 616 if (piece_symbol_upper == 'K'): 617 file_delta = action.end_coordinate.file - action.start_coordinate.file 618 619 if (file_delta == 2): 620 # Kingside castle. 621 move_san = 'O-O' 622 elif (file_delta == -2): 623 # Queenside castle. 624 move_san = 'O-O-O' 625 626 is_pawn = (piece_symbol_upper == 'P') 627 628 if (move_san is None): 629 is_capture = state.is_capture(action) 630 631 # Detect en-passant captures. 632 if (is_pawn and (action.end_coordinate == state.en_passant_coordinate)): 633 is_capture = True 634 635 # Check if the move is ambiguous. 636 ambiguous_actions: list[chessai.core.action.MoveAction] = [] 637 for alternate_action in state.get_legal_actions(): 638 if (not isinstance(alternate_action, chessai.core.action.MoveAction)): 639 continue 640 641 # An ambiguous move must have the same action type. 642 if (type(alternate_action) != type(action)): 643 continue 644 645 # An ambiguous move must end at the same coordinate. 646 if (alternate_action.end_coordinate != action.end_coordinate): 647 continue 648 649 # An ambiguous move cannot start at the same coordinate because that would be the same piece moving. 650 if (alternate_action.start_coordinate == action.start_coordinate): 651 continue 652 653 # An ambiguous action must have the same promotion. 654 if (isinstance(action, chessai.core.action.PromotionAction) 655 and isinstance(alternate_action, chessai.core.action.PromotionAction) 656 and (alternate_action.promotion != action.promotion)): 657 continue 658 659 # An ambiguous action must have a different piece type. 660 alternate_action_piece = state.get(alternate_action.start_coordinate) 661 if (alternate_action_piece is None): 662 continue 663 664 if (alternate_action_piece.symbol().upper() != piece_symbol_upper): 665 continue 666 667 ambiguous_actions.append(alternate_action) 668 669 disambiguation_str = '' 670 671 # Pawn actions cannot be ambiguous. 672 if ((len(ambiguous_actions) > 0) and (not is_pawn)): 673 # Check if there is an ambiguous action on the same file. 674 same_file = False 675 for ambiguous_action in ambiguous_actions: 676 if (ambiguous_action.start_coordinate.file != action.start_coordinate.file): 677 continue 678 679 same_file = True 680 681 # Check if there is an ambiguous action on the same rank. 682 same_rank = False 683 for ambiguous_action in ambiguous_actions: 684 if (ambiguous_action.start_coordinate.rank != action.start_coordinate.rank): 685 continue 686 687 same_rank = True 688 689 if (not same_file): 690 disambiguation_str = action.start_coordinate.uci(only_file = True) 691 elif (not same_rank): 692 disambiguation_str = action.start_coordinate.uci(only_rank = True) 693 else: 694 # Fallback to the entire coordinate. 695 disambiguation_str = action.start_coordinate.uci() 696 697 # Build the final SAN with the above information. 698 destination_str = action.end_coordinate.uci() 699 700 if (is_pawn): 701 if is_capture: 702 # Pawn captures require the starting file to disambiguate. 703 start_file = action.start_coordinate.uci(only_file = True) 704 move_san = f"{start_file}x{destination_str}" 705 else: 706 move_san = destination_str 707 else: 708 if is_capture: 709 capture_str = 'x' 710 else: 711 capture_str = '' 712 713 move_san = f"{piece_symbol_upper}{disambiguation_str}{capture_str}{destination_str}" 714 715 # Add the piece promotion suffix. 716 if isinstance(action, chessai.core.action.PromotionAction): 717 move_san += f"={action.promotion.symbol().upper()}" 718 719 # Apply the action and check for check and checkmate. 720 successor = state.generate_successor(action) 721 722 if (successor.is_checkmate()): 723 move_san += '#' 724 elif (successor.is_check(successor.turn)): 725 move_san += '+' 726 727 return move_san 728 729def _is_pgn_comment_line(line: str) -> bool: 730 """ 731 Returns if the line is a comment. 732 733 A line is a comment in a PGN if it starts with a '%' or ';'. 734 """ 735 736 line = line.strip() 737 if (len(line) == 0): 738 return True 739 740 if (line[0] == '%'): 741 return True 742 743 if (line[0] == ';'): 744 return True 745 746 return False
73class StandardHeaders(edq.util.serial.DictConverter): 74 """ 75 These seven standard tags will always be present in the headers: 76 - Event: the name of the tournament or match event 77 - Site: the location of the event 78 - Date: the starting date of the game 79 - Round: the playing round ordinal of the game 80 - White: the player of the white pieces 81 - Black: the player of the black pieces 82 - Result: the result of the game 83 84 To see the full description of the possible headers and their format, 85 see https://www.saremba.de/chessgml/standards/pgn/pgn-complete.htm#c8.1 . 86 """ 87 88 def __init__(self, 89 event: str = "?", 90 site: str = "?", 91 date: str = "????.??.??", 92 game_round: str = "?", 93 white: str = "?", 94 black: str = "?", 95 result: str = "*", 96 ) -> None: 97 self.event: str = event 98 """ The name of the tournament or match event. """ 99 100 self.site: str = site 101 """ The location of the event. """ 102 103 self.date: str = date 104 """ The starting date of the game. """ 105 106 self.round: str = game_round 107 """ The playing round ordinal of the game. """ 108 109 self.white: str = white 110 """ The player of the white pieces. """ 111 112 self.black: str = black 113 """ The player of the black pieces. """ 114 115 self.result: str = result 116 """ The result of the game. """ 117 118 def _set(self, attribute: str, value: str) -> None: 119 """ Update the header attribute to the given value. """ 120 121 match attribute.lower(): 122 case "event": 123 self.event = value 124 case "site": 125 self.site = value 126 case "date": 127 self.date = value 128 case "round": 129 self.round = value 130 case "white": 131 self.white = value 132 case "black": 133 self.black = value 134 case "result": 135 self.result = value 136 case _: 137 return 138 139 def to_pgn(self) -> list[str]: 140 """ Convert the headers to a list of PGN tags. """ 141 142 tags: list[str] = [] 143 144 tags.append(_to_tag("Event", self.event)) 145 tags.append(_to_tag("Site", self.site)) 146 tags.append(_to_tag("Date", self.date)) 147 tags.append(_to_tag("Round", self.round)) 148 tags.append(_to_tag("White", self.white)) 149 tags.append(_to_tag("Black", self.black)) 150 tags.append(_to_tag("Result", self.result)) 151 152 return tags 153 154 def __eq__(self, other: object) -> bool: 155 if (not isinstance(other, StandardHeaders)): 156 return False 157 158 return (self.event == other.event 159 and self.site == other.site 160 and self.date == other.date 161 and self.round == other.round 162 and self.white == other.white 163 and self.black == other.black 164 and self.result == other.result)
These seven standard tags will always be present in the headers:
- Event: the name of the tournament or match event
- Site: the location of the event
- Date: the starting date of the game
- Round: the playing round ordinal of the game
- White: the player of the white pieces
- Black: the player of the black pieces
- Result: the result of the game
To see the full description of the possible headers and their format, see https://www.saremba.de/chessgml/standards/pgn/pgn-complete.htm#c8.1 .
88 def __init__(self, 89 event: str = "?", 90 site: str = "?", 91 date: str = "????.??.??", 92 game_round: str = "?", 93 white: str = "?", 94 black: str = "?", 95 result: str = "*", 96 ) -> None: 97 self.event: str = event 98 """ The name of the tournament or match event. """ 99 100 self.site: str = site 101 """ The location of the event. """ 102 103 self.date: str = date 104 """ The starting date of the game. """ 105 106 self.round: str = game_round 107 """ The playing round ordinal of the game. """ 108 109 self.white: str = white 110 """ The player of the white pieces. """ 111 112 self.black: str = black 113 """ The player of the black pieces. """ 114 115 self.result: str = result 116 """ The result of the game. """
139 def to_pgn(self) -> list[str]: 140 """ Convert the headers to a list of PGN tags. """ 141 142 tags: list[str] = [] 143 144 tags.append(_to_tag("Event", self.event)) 145 tags.append(_to_tag("Site", self.site)) 146 tags.append(_to_tag("Date", self.date)) 147 tags.append(_to_tag("Round", self.round)) 148 tags.append(_to_tag("White", self.white)) 149 tags.append(_to_tag("Black", self.black)) 150 tags.append(_to_tag("Result", self.result)) 151 152 return tags
Convert the headers to a list of PGN tags.
Inherited Members
166class PGNResult(str, enum.Enum): 167 """ The possible game endings denoted in a PGN. """ 168 169 WHITE_WIN = '1-0' 170 """ White won the game. """ 171 172 BLACK_WIN = '0-1' 173 """ Black won the game. """ 174 175 TIE = '1/2-1/2' 176 """ The game was a tie. """ 177 178 IN_PROGRESS = '*' 179 """ The game is still in progress. """ 180 181 UNKNOWN = 'Unknown' 182 """ The ending of the game is unknown. """
The possible game endings denoted in a PGN.
184class ParsedPGN(edq.util.serial.DictConverter): 185 """ 186 The parsed result of a single PGN game. 187 """ 188 189 def __init__(self, 190 headers: StandardHeaders | None = None, 191 optional_headers: dict[str, typing.Any] | None = None, 192 starting_fen: str | None = None, 193 initial_actions: list[chessai.core.action.Action] | None = None, 194 comments: list[str] | None = None, 195 result: PGNResult = PGNResult.UNKNOWN) -> None: 196 197 if (headers is None): 198 headers = StandardHeaders() 199 200 self.headers: StandardHeaders = headers 201 """ The standard headers from a single PGN game. """ 202 203 if (optional_headers is None): 204 optional_headers = {} 205 206 self.optional_headers: dict[str, typing.Any] = optional_headers 207 """ Any additional headers parsed from the PGN. """ 208 209 self.starting_fen: str | None = starting_fen 210 """ The starting FEN for the game, which is often omitted to denote the default FEN. """ 211 212 if (initial_actions is None): 213 initial_actions = [] 214 215 self.initial_actions: list[chessai.core.action.Action] = initial_actions 216 """ The mainline moves in the game. """ 217 218 if (comments is None): 219 comments = [] 220 221 self.comments: list[str] = comments 222 """ The comments found in the game. """ 223 224 self.result: PGNResult = result 225 """ The result of the PGN or if the game is still in progress. """ 226 227 def get_starting_fen(self) -> str | None: 228 """ Get the optional FEN header from the PGN. """ 229 230 return self.optional_headers.get(FEN_HEADER_KEY, None) 231 232 def get_game_rating_annotation(self) -> chessai.core.gameannotation.GameRatingAnnotation | None: 233 """ Get the optional typed engine-rating annotation stored in this PGN. """ 234 235 value = self.optional_headers.get(chessai.core.gameannotation.GAME_RATING_ANNOTATION_HEADER, None) 236 if (value is None): 237 return None 238 239 if (not isinstance(value, str)): 240 raise ValueError('The game rating annotation header must be a string.') 241 242 return chessai.core.gameannotation.GameRatingAnnotation.from_header_value(value)
The parsed result of a single PGN game.
189 def __init__(self, 190 headers: StandardHeaders | None = None, 191 optional_headers: dict[str, typing.Any] | None = None, 192 starting_fen: str | None = None, 193 initial_actions: list[chessai.core.action.Action] | None = None, 194 comments: list[str] | None = None, 195 result: PGNResult = PGNResult.UNKNOWN) -> None: 196 197 if (headers is None): 198 headers = StandardHeaders() 199 200 self.headers: StandardHeaders = headers 201 """ The standard headers from a single PGN game. """ 202 203 if (optional_headers is None): 204 optional_headers = {} 205 206 self.optional_headers: dict[str, typing.Any] = optional_headers 207 """ Any additional headers parsed from the PGN. """ 208 209 self.starting_fen: str | None = starting_fen 210 """ The starting FEN for the game, which is often omitted to denote the default FEN. """ 211 212 if (initial_actions is None): 213 initial_actions = [] 214 215 self.initial_actions: list[chessai.core.action.Action] = initial_actions 216 """ The mainline moves in the game. """ 217 218 if (comments is None): 219 comments = [] 220 221 self.comments: list[str] = comments 222 """ The comments found in the game. """ 223 224 self.result: PGNResult = result 225 """ The result of the PGN or if the game is still in progress. """
The starting FEN for the game, which is often omitted to denote the default FEN.
227 def get_starting_fen(self) -> str | None: 228 """ Get the optional FEN header from the PGN. """ 229 230 return self.optional_headers.get(FEN_HEADER_KEY, None)
Get the optional FEN header from the PGN.
232 def get_game_rating_annotation(self) -> chessai.core.gameannotation.GameRatingAnnotation | None: 233 """ Get the optional typed engine-rating annotation stored in this PGN. """ 234 235 value = self.optional_headers.get(chessai.core.gameannotation.GAME_RATING_ANNOTATION_HEADER, None) 236 if (value is None): 237 return None 238 239 if (not isinstance(value, str)): 240 raise ValueError('The game rating annotation header must be a string.') 241 242 return chessai.core.gameannotation.GameRatingAnnotation.from_header_value(value)
Get the optional typed engine-rating annotation stored in this PGN.
Inherited Members
244def parse_pgn(pgn: str, state_class: typing.Type[chessai.core.gamestate.GameState]) -> ParsedPGN | None: 245 """ 246 Parse a single PGN string into a ParsedPGN. 247 248 Raises ValueError if the PGN is malformed. 249 See https://en.wikipedia.org/wiki/Portable_Game_Notation . 250 """ 251 252 lines = pgn.splitlines() 253 254 # If it is only one line, try loading it from a file. 255 if (len(lines) == 1): 256 pgn = load_pgn_from_file(pgn) 257 lines = pgn.splitlines() 258 259 index = 0 260 261 headers: StandardHeaders = StandardHeaders() 262 263 optional_headers: dict[str, typing.Any] = {} 264 265 # Parse the header fields. 266 for i, line in enumerate(lines): 267 # Track where we are in the lines. 268 index = i 269 270 clean_line = line.strip() 271 272 # Skip empty lines. 273 if (len(line) == 0): 274 continue 275 276 # Skip comments. 277 if (_is_pgn_comment_line(clean_line)): 278 continue 279 280 # Headers must begin with an open bracket. 281 if (not clean_line.startswith("[")): 282 break 283 284 tag_match = TAG_PATTERN.match(clean_line) 285 286 # Ignore malformed tags. 287 if (not tag_match): 288 continue 289 290 tag_header_key = tag_match.group(1) 291 tag_header_value = _unescape_tag_value(tag_match.group(2)) 292 293 # Determine if this is a standard header key or not. 294 if (tag_header_key.lower() in PGN_HEADERS): 295 headers._set(tag_header_key, tag_header_value) 296 else: 297 optional_headers[tag_header_key] = tag_header_value 298 299 # No game found. 300 if (headers == StandardHeaders()): 301 return None 302 303 # Start scanning for moves from the end of the headers. 304 lines = lines[index:] 305 306 # Set up a gamestate to follow along and parse SANs. 307 fen = optional_headers.get(FEN_HEADER_KEY, None) 308 state = state_class.from_fen(fen = fen) 309 rng = random.Random(1) 310 311 initial_actions: list[chessai.core.action.Action] = [] 312 comments: list[str] = [] 313 result: PGNResult = PGNResult.UNKNOWN 314 315 in_comment = False 316 comment_buffer: list[str] = [] 317 318 skip_variation_depth = 0 319 320 for line in lines: 321 line = line.strip() 322 323 if (not line): 324 break 325 326 # Skip whole-line comments. 327 if _is_pgn_comment_line(line): 328 continue 329 330 i = 0 331 while (i < len(line)): 332 if in_comment: 333 end_index = line.find("}", i) 334 335 # The rest of the line is part of the comment. 336 if (end_index == -1): 337 comment_buffer.append(line[i:]) 338 break 339 340 # Add the remainder of the comment and continue processing the current line. 341 comment_buffer.append(line[i:end_index]) 342 comments.append("\n".join(comment_buffer).strip()) 343 344 comment_buffer = [] 345 in_comment = False 346 347 i = end_index + 1 348 349 continue 350 351 match = MOVETEXT_PATTERN.match(line, i) 352 353 if (not match): 354 i += 1 355 continue 356 357 token = match.group(0) 358 i = match.end() 359 360 # Handle block comments {...}. 361 if token.startswith("{"): 362 content = token[1:] 363 364 end_index = content.find("}") 365 366 if (end_index == -1): 367 # Track part of a multi-line comment. 368 in_comment = True 369 comment_buffer.append(content) 370 else: 371 # Add the in-line comment and continue processing this line. 372 comments.append(content[:end_index].strip()) 373 374 continue 375 376 # Skip variations (...) entirely. 377 if (token == "("): 378 skip_variation_depth += 1 379 continue 380 381 if (token == ")"): 382 if (skip_variation_depth > 0): 383 skip_variation_depth -= 1 384 385 continue 386 387 if (skip_variation_depth > 0): 388 continue 389 390 # Skip line comments. 391 if token.startswith(";"): 392 break 393 394 # Skip move numbers like "1." or "23.". 395 if token.endswith("."): 396 continue 397 398 # Skip results. 399 if (token in ["1-0", "0-1", "1/2-1/2", "*"]): 400 result = PGNResult(token) 401 break 402 403 # Skip NAGs / annotations. 404 if (token.startswith("$") or (token in ["!", "?", "!!", "??", "!?", "?!"])): 405 continue 406 407 # Otherwise, this must be a SAN move. 408 action = state.get_action_from_san(token) 409 if (action == chessai.core.action.NoneAction()): 410 raise ValueError(f"Unable to find a legal action for the SAN: '{token}'.") 411 412 state.process_turn_full(action, rng) 413 initial_actions.append(action) 414 415 # Check if the gamestate agrees with the expected result. 416 if ((result in [PGNResult.WHITE_WIN, PGNResult.BLACK_WIN]) and (not state.is_game_over())): 417 # The game is not over when the PGN believes it should be, so add a forfeit action. 418 initial_actions.append(chessai.core.action.ForfeitAction()) 419 420 if ((result == PGNResult.TIE) and (not state.is_game_over())): 421 # The game must be a proposed draw, so add the draw handshake. 422 initial_actions.append(chessai.core.action.ProposeDrawAction()) 423 initial_actions.append(chessai.core.action.AcceptDrawAction()) 424 425 return ParsedPGN( 426 headers = headers, 427 optional_headers = optional_headers, 428 initial_actions = initial_actions, 429 comments = comments, 430 result = result, 431 )
Parse a single PGN string into a ParsedPGN.
Raises ValueError if the PGN is malformed. See https://en.wikipedia.org/wiki/Portable_Game_Notation .
433def load_pgn_from_file(path: str) -> str: 434 """ 435 Load the PGN string from a file. 436 437 If the given path does not exist, 438 try to prefix the path with the standard game directory and suffix with the standard extension. 439 """ 440 441 raw_path = path 442 443 # If the path does not exist, try the boards directory. 444 if (not os.path.exists(path)): 445 path = os.path.join(GAMES_DIR, path) 446 447 # If this path does not have a good extension, add one. 448 if ((os.path.splitext(path)[-1] != PGN_FILE_EXTENSION) and (os.path.splitext(path)[-1] != GZIP_FILE_EXTENSION)): 449 path = path + PGN_FILE_EXTENSION 450 451 # If the path still does not exist, try adding the GZip extension. 452 if (not os.path.exists(path)): 453 if (os.path.splitext(path)[-1] != GZIP_FILE_EXTENSION): 454 path = path + GZIP_FILE_EXTENSION 455 456 if (not os.path.exists(path)): 457 raise ValueError(f"Could not find PGN file, path does not exist: '{raw_path}'.") 458 459 if (os.path.splitext(path)[-1] == GZIP_FILE_EXTENSION): 460 return load_pgn_from_gzip(path) 461 462 contents = edq.util.dirent.read_file(path, strip = False) 463 return contents
Load the PGN string from a file.
If the given path does not exist, try to prefix the path with the standard game directory and suffix with the standard extension.
465def load_pgn_from_gzip(path: str) -> str: 466 """ 467 Load the PGN string from a file. 468 469 If the given path does not exist, 470 try to prefix the path with the standard game directory and suffix with the standard extension. 471 """ 472 473 raw_path = path 474 475 # If the path does not exist, try the boards directory. 476 if (not os.path.exists(path)): 477 path = os.path.join(GAMES_DIR, path) 478 479 # If this path does not have a good extension, add one. 480 if (os.path.splitext(path)[-1] != GZIP_FILE_EXTENSION): 481 path = path + GZIP_FILE_EXTENSION 482 483 if (not os.path.exists(path)): 484 raise ValueError(f"Could not find PGN file, path does not exist: '{raw_path}'.") 485 486 with gzip.open(path, 'rb') as file: 487 uncompressed_contents = file.read() 488 decompressed_contents = uncompressed_contents.decode(DEFAULT_ENCODING) 489 490 return decompressed_contents
Load the PGN string from a file.
If the given path does not exist, try to prefix the path with the standard game directory and suffix with the standard extension.
492def to_pgn(headers: StandardHeaders, optional_headers: dict[str, typing.Any], 493 state_class: typing.Type[chessai.core.gamestate.GameState], start_fen: str, 494 actions: list[chessai.core.action.Action]) -> str: 495 """ 496 Convert a game into a PGN. 497 498 Raises an error if any of the seven required headers are missing. 499 If a move cannot be generated from an action and gamestate pair, an error is raised. 500 """ 501 502 lines: list[str] = headers.to_pgn() 503 504 # Non-default starting FENs require additional PGN information. 505 if (start_fen != chessai.core.gamestate.DEFAULT_FEN): 506 lines.append(_to_tag(SET_UP_HEADER_KEY, '1')) 507 lines.append(_to_tag(FEN_HEADER_KEY, start_fen)) 508 509 # Add optional headers. 510 for (key, value) in optional_headers.items(): 511 try: 512 str_value = str(value) 513 except Exception: 514 logging.warning("Could not convert optional header value for key '%s' to a string.", key) 515 continue 516 517 lines.append(_to_tag(str(key), str_value)) 518 519 # Add an extra blank line after the header section. 520 lines.append('') 521 522 # Build the move SAN tokens while replaying the game. 523 state = state_class.from_fen(fen = start_fen) 524 pgn_tokens: list[str] = [] 525 current_fullmove_number = 0 526 527 for action in actions: 528 # Ignore meta actions as they do not have a valid SAN representation. 529 if (not isinstance(action, chessai.core.action.MoveAction)): 530 continue 531 532 if (state.fullmove_number != current_fullmove_number): 533 pgn_tokens.append(f"{state.fullmove_number}.") 534 current_fullmove_number = state.fullmove_number 535 536 san = _action_to_san(action, state) 537 pgn_tokens.append(san) 538 539 state.push(action) 540 541 # Add the result token. 542 pgn_tokens.append(headers.result) 543 544 movetext_lines: list[str] = [] 545 current_line = '' 546 547 for token in pgn_tokens: 548 if (len(current_line) == 0): 549 candidate_line = token 550 else: 551 candidate_line = f"{current_line} {token}" 552 553 # Keep building a line until it surpasses the max line length. 554 if (len(candidate_line) <= MAX_PGN_LINE_LENGTH): 555 current_line = candidate_line 556 else: 557 movetext_lines.append(current_line) 558 current_line = token 559 560 if (len(current_line) > 0): 561 movetext_lines.append(current_line) 562 563 lines.extend(movetext_lines) 564 565 # Add a trailing newline after the movetext. 566 lines.append('') 567 568 return '\n'.join(lines)
Convert a game into a PGN.
Raises an error if any of the seven required headers are missing. If a move cannot be generated from an action and gamestate pair, an error is raised.