File size: 7,095 Bytes
e00315f
 
 
 
 
 
 
 
fee60bf
e00315f
 
 
 
 
 
 
 
 
fee60bf
e00315f
fee60bf
e00315f
fee60bf
 
e00315f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee60bf
 
 
 
 
 
 
 
 
e00315f
 
 
 
 
 
 
 
fee60bf
e00315f
 
 
 
 
 
 
 
 
 
fee60bf
e00315f
 
 
 
 
 
 
 
617960c
e00315f
 
 
 
617960c
e00315f
 
fee60bf
 
 
 
 
 
 
 
 
e00315f
 
 
 
fee60bf
 
e00315f
 
 
 
 
 
 
fee60bf
e00315f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee60bf
 
 
 
 
 
 
 
 
 
e00315f
 
cf2167d
e00315f
 
 
 
fee60bf
e00315f
 
 
 
 
 
 
 
 
 
 
 
 
 
fee60bf
 
e00315f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import chess
import chess.pgn
import chess.engine
import chess.svg
import asyncio
import io
import os
import sys
import re

# Dictionary to hold openings data
openings = {}

def load_openings_db():
    """Load openings database into dictionary (eco -> opening name)."""
    print("Loading openings database...")
    with open("data/openings/all.tsv", "r", encoding="utf-8") as file:
        for line in file.readlines():
            # Each line format: ECO_CODE \t Opening Name \t PGN \t UCI \t Opening Moves (FEN)
            parts = line.strip().split("\t")
            if len(parts) >= 5:
                eco_code = parts[0]
                openings[eco_code] = { "opening_name": parts[1], "pgn": parts[2], "fen": parts[4]}
        print(f"Loaded {len(openings)} openings from database.")

def load_pgn(pgn_text: str) -> chess.pgn.Game:
    """
    Load a PGN game from the provided text.
    """
    pgn = io.StringIO(pgn_text)
    game = chess.pgn.read_game(pgn)
    if game is None:
        raise ValueError("Invalid PGN format")
    return game

def get_moves(game: chess.pgn.Game) -> list:
    """
    Extract the list of FEN strings for each move in the game.
    """
    moves = []
    board = game.board()
    for move in game.mainline_moves():
        board.push(move)
        moves.append(board.fen())

    return moves

def is_valid_pgn(pgn_text: str) -> bool:
    """
    Check if the provided PGN text is valid.
    """
    try:
        game = load_pgn(pgn_text)
        return game is not None and len(game.errors) == 0
    except Exception:
        return False

def explain(delta):
    if delta <= -1.5:
        return "Serious blunder losing material or initiative"
    if delta <= -1:
        return "Positional disadvantage or pawn loss"
    return "Reasonable move"


async def analyze_pgn(pgn_string):
    # PGN → Moves (0.01s, nativ)
    game = chess.pgn.read_game(io.StringIO(pgn_string))
    board = game.board()
    
    engine_path = os.environ.get("CHESS_ENGINE_PATH", "stockfish")
    engine = chess.engine.SimpleEngine.popen_uci(engine_path)
    
    analysis = []
    critical = []
    
    # Get initial evaluation from White's perspective
    info = engine.analyse(board, chess.engine.Limit(time=0.1))
    last_wp_eval = info['score'].white().score(mate_score=10000)

    for i, move in enumerate(game.mainline_moves()):
        turn_before_move = board.turn
        
        board.push(move)
        
        time_limit = 0.1
        info = engine.analyse(board, chess.engine.Limit(time=time_limit))
        current_wp_eval = info['score'].white().score(mate_score=10000)

        is_blunder = False
        if last_wp_eval is not None and current_wp_eval is not None:
            # If white moved, the eval should not drop a lot
            if turn_before_move == chess.WHITE:
                # Drop of more than 1 pawn (100 centipawns)
                if (last_wp_eval - current_wp_eval) > 70:
                    is_blunder = True
            # If black moved, the eval should not rise a lot
            else:
                # Rise of more than 1 pawn (100 centipawns)
                if (current_wp_eval - last_wp_eval) > 70:
                    is_blunder = True
        
        if is_blunder == True:
            critical.append({
                "move": i+1,
                "played": str(move),
                "best": str(info['pv'][0]) if info.get('pv') else None,
                "eval_before": last_wp_eval/100,
                "eval_after": current_wp_eval/100
            })

        analysis.append({
            'nr': i+1,
            'move': str(move),
            'fen': board.fen(),
            'eval_before': last_wp_eval/100,
            'eval': current_wp_eval/100,
            'best_move': str(info['pv'][0]) if info.get('pv') else None,
            'is_blunder': is_blunder
        })
        
        last_wp_eval = current_wp_eval
    
    engine.quit()
    return analysis, critical


async def analyze_fen_position(fen_string: str, analysis_time: float = 3.0):
    """
    Analyzes a single chess position from a FEN string for a given time.
    """
    board = chess.Board(fen_string)
    
    engine_path = os.environ.get("CHESS_ENGINE_PATH", "stockfish")
    engine = chess.engine.SimpleEngine.popen_uci(engine_path)
    
    info = engine.analyse(board, chess.engine.Limit(time=analysis_time))
    
    engine.quit()
    
    return {
        'fen': board.fen(),
        'eval': info['score'].relative.score(mate_score=10000)/100,
        'best_move': str(info['pv'][0]) if info['pv'] else None,
        'variation': [str(move) for move in info['pv']] if info['pv'] else []
    }


def get_opening(pgn: str) -> str:
    """Return opening name for given ECO code inside PGN using the loaded openings dict."""
    pattern = re.compile(r'\[ECO\s+"([^"]+)"\]')

    matches = pattern.findall(pgn)
    if len(matches) > 0:
        eco_code = matches[0]
    else:
        return "Unkown Opening"
    return openings.get(eco_code, "Unknown Opening")

def render_board(fen: str, size: int = 350) -> str:
    """Render a chess position from FEN to SVG."""
    board = chess.Board(fen)
    return chess.svg.board(
        board,
        size=size,
    )

def analyze_game_handler(pgn):
    # parse PGN
    yield ui_helpers.set_value("♞ Parsing Game...")
    pgn_text = load_pgn(pgn)
    yield ui_helpers.set_value("Start analysis...")
    analysis_result = asyncio.run(analyze_pgn(pgn_text))
    yield ui_helpers.set_value("Analysis complete.")
    yield ui_helpers.set_value(analysis_result)
    # run LLM
    # yield results


load_openings_db()

if __name__ == "__main__":
    import os

    load_openings_db()

    # --- New code to set CHESS_ENGINE_PATH for testing purposes ---
    stockfish_path = os.path.join(sys.path[0], "stockfish", "windows", "stockfish-windows-x86-64-avx2.exe")
    if os.path.isfile(stockfish_path):
        os.environ["CHESS_ENGINE_PATH"] = stockfish_path
        print(f"Test: Set CHESS_ENGINE_PATH to: {stockfish_path}")
    else:
        print(f"Test: Warning: Stockfish binary not found at '{stockfish_path}'. Please ensure it's in the correct location or in system PATH.")
    # --- End of new code ---

    # Example usage
    example_pgn = """[Event "Example"]
[Event "Live Chess"]
[Site "Chess.com"]
[Date "2025.11.21"]
[Round "?"]
[White "pablitsky"]
[Black "travelhawk"]
[Result "0-1"]
[TimeControl "180+2"]
[WhiteElo "959"]
[BlackElo "919"]
[Termination "travelhawk gewinnt auf Zeit"]
[ECO "A21"]
[EndTime "22:18:21 GMT+0000"]
[Link "https://www.chess.com/game/live/145800054980?move=0"]

1. c4 e5 2. Nc3 Bb4 3. a3 Bxc3 4. dxc3 d6 5. e4 Bg4 6. f3 Be6 7. h4 Nf6 8. Be3
Nbd7 9. Qd2 Nh5 10. Bf2 O-O 11. O-O-O a6 12. g4 Nf4 13. Nh3 Nxh3 14. Rxh3 h5 15.
Rg3 Qxh4 16. Rh3 Qe7 17. Rxh5 b5 18. Bh4 Qe8 19. g5 g6 20. Rh6 Bxc4 21. Bf2 Nc5
22. Bxc5 dxc5 23. Qh2 f5 24. Rh8+ Kf7 25. Qh7+ Ke6 26. Rxf8 Qxf8 27. Qxg6+ Ke7
28. exf5 Bf7 29. f6+ Ke8 0-1
"""
    analysis_result = asyncio.run(analyze_pgn(example_pgn, fast_mode=True))
    for move_analysis in analysis_result:
        print(move_analysis)