Falguni commited on
Commit
63103fa
·
1 Parent(s): fa83ca0

Add PGN util

Browse files
Files changed (1) hide show
  1. src/util/pgn_util.py +39 -0
src/util/pgn_util.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import chess.pgn
2
+ import tempfile
3
+
4
+
5
+ # Load game
6
+ def read_pgn(pgn_filepath):
7
+ with open(pgn_filepath) as f:
8
+ game = chess.pgn.read_game(f)
9
+ return game
10
+
11
+
12
+ def export_pgn(game):
13
+ # Create a temp file with .pgn extension that won't be auto-deleted
14
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pgn", mode="w") as tmp:
15
+ exporter = chess.pgn.FileExporter(tmp)
16
+ game.accept(exporter)
17
+ return tmp.name # Return the file path so Gradio can serve it
18
+
19
+
20
+ def format_pv(pv_moves, board):
21
+ temp_board = board.copy()
22
+ san_moves = []
23
+ for move in pv_moves:
24
+ san_moves.append(temp_board.san(move))
25
+ temp_board.push(move)
26
+ return " ".join(san_moves)
27
+
28
+
29
+ def add_variation(node, variation):
30
+ board = node.board()
31
+ current = node
32
+
33
+ for move in variation:
34
+ # Ensure move is legal in current position
35
+ if move in board.legal_moves:
36
+ current = current.add_variation(move)
37
+ board.push(move)
38
+ else:
39
+ break # Stop if PV deviates from legal moves