Fu01978 commited on
Commit
85e38c1
·
verified ·
1 Parent(s): cf90432

Delete analyzer.py

Browse files
Files changed (1) hide show
  1. analyzer.py +0 -432
analyzer.py DELETED
@@ -1,432 +0,0 @@
1
- """
2
- Chess game analyzer using Stockfish + Expected Points model.
3
-
4
- Classification hierarchy (highest priority first):
5
- Brilliant → Great → Miss → Best → Excellent → Good → Inaccuracy → Mistake → Blunder
6
- """
7
-
8
- import chess
9
- import chess.pgn
10
- import chess.engine
11
- import io
12
- import math
13
- import random
14
- import shutil
15
- import os
16
-
17
- def _find_stockfish() -> str:
18
- """Locate stockfish binary on common paths."""
19
- # Try PATH first
20
- found = shutil.which("stockfish")
21
- if found:
22
- return found
23
- for path in [
24
- "/usr/games/stockfish",
25
- "/usr/bin/stockfish",
26
- "/usr/local/bin/stockfish",
27
- "/opt/homebrew/bin/stockfish",
28
- "/opt/homebrew/games/stockfish",
29
- ]:
30
- if os.path.isfile(path) and os.access(path, os.X_OK):
31
- return path
32
- return "stockfish" # Let it fail with a clear error
33
-
34
- # ── Expected Points ────────────────────────────────────────────────────────────
35
-
36
- def cp_to_ep(cp: float, k: float = 0.4) -> float:
37
- """Convert centipawn score to Expected Points from White's perspective."""
38
- return 1.0 / (1.0 + math.exp(-k * (cp / 100.0)))
39
-
40
- def score_to_ep_white(score: chess.engine.Score) -> float:
41
- """Convert a PovScore (already in White's POV) to EP."""
42
- if score.is_mate():
43
- m = score.mate()
44
- return 1.0 if (m is not None and m > 0) else 0.0
45
- cp = score.score()
46
- return cp_to_ep(cp if cp is not None else 0)
47
-
48
- def get_ep_white(info: dict) -> float:
49
- return score_to_ep_white(info["score"].white())
50
-
51
- # ── Sacrifice detection ────────────────────────────────────────────────────────
52
-
53
- PIECE_VALUES = {
54
- chess.PAWN: 1, chess.KNIGHT: 3, chess.BISHOP: 3,
55
- chess.ROOK: 5, chess.QUEEN: 9, chess.KING: 99
56
- }
57
-
58
- def check_sacrifice(board: chess.Board, move: chess.Move) -> bool:
59
- """
60
- Returns True if this move leaves a piece (worth ≥ 3pts) on a square
61
- where the opponent can capture it with a less-or-equally-valued piece.
62
- Also flags exchange sacrifices (Rook for minor piece).
63
- """
64
- piece = board.piece_at(move.from_square)
65
- if piece is None:
66
- return False
67
-
68
- piece_val = PIECE_VALUES.get(piece.piece_type, 0)
69
- if piece_val < 3:
70
- return False # Pawn sacs handled separately; king never sacrificed
71
-
72
- # If it's a capture, is it a losing exchange?
73
- if board.is_capture(move):
74
- target = board.piece_at(move.to_square)
75
- if target:
76
- target_val = PIECE_VALUES.get(target.piece_type, 0)
77
- if target_val >= piece_val:
78
- return False # Fair trade or winning capture — not a sac
79
-
80
- board_after = board.copy()
81
- board_after.push(move)
82
- to_sq = move.to_square
83
- opponent = board_after.turn # Opponent's turn after we moved
84
-
85
- attackers = board_after.attackers(opponent, to_sq)
86
- if not attackers:
87
- return False # Piece is safe
88
-
89
- min_attacker_val = min(
90
- PIECE_VALUES.get(board_after.piece_at(sq).piece_type, 0)
91
- for sq in attackers
92
- if board_after.piece_at(sq)
93
- )
94
-
95
- return min_attacker_val <= piece_val
96
-
97
- # ── Move classification ────────────────────────────────────────────────────────
98
-
99
- COMMENTS = {
100
- "Brilliant": [
101
- "A stunning sacrifice that seizes a lasting advantage.",
102
- "Extraordinary piece sacrifice — the position rewards bold play.",
103
- "An unexpected sacrifice with deep positional compensation.",
104
- ],
105
- "Great": [
106
- "A critical move that shifts the balance of the game.",
107
- "Finding this move takes real precision — it dramatically improves the position.",
108
- "The only move that keeps things in hand. Well found.",
109
- ],
110
- "Miss": [
111
- "A missed opportunity — the opponent's error went unpunished.",
112
- "After the opponent's mistake, this fails to press the advantage.",
113
- "The position offered a winning shot, but it slipped away here.",
114
- ],
115
- "Best": [
116
- "The engine's top choice. Precise and principled.",
117
- "Perfect play — the ideal move in this position.",
118
- "Exactly what the position demanded.",
119
- ],
120
- "Excellent": [
121
- "A very strong move that keeps the position under control.",
122
- "Nearly best — a fine practical choice.",
123
- "A sharp, high-quality response.",
124
- ],
125
- "Good": [
126
- "A solid move that maintains the balance.",
127
- "Reasonable play — the position stays roughly equal.",
128
- "A sensible continuation with no serious drawbacks.",
129
- ],
130
- "Inaccuracy": [
131
- "A slight imprecision — a better option was available.",
132
- "Not a serious error, but leaves something on the table.",
133
- "The position allowed for more here.",
134
- ],
135
- "Mistake": [
136
- "An error that hands the opponent a meaningful advantage.",
137
- "This weakens the position more than it needed to.",
138
- "A significant misstep — the opponent can now press hard.",
139
- ],
140
- "Blunder": [
141
- "A serious blunder that could cost the game.",
142
- "A major error — this dramatically changes the evaluation.",
143
- "Devastating. The position collapses after this move.",
144
- ],
145
- }
146
-
147
- def get_comment(classification: str) -> str:
148
- return random.choice(COMMENTS.get(classification, ["—"]))
149
-
150
- def classify_move(
151
- player_ep_before: float,
152
- player_ep_after: float,
153
- player_ep_second_best: float | None,
154
- is_best: bool,
155
- move_rank: int | None,
156
- is_sacrifice: bool,
157
- opponent_blunder_swing: float | None,
158
- ep_before_opponent_blunder: float | None,
159
- ) -> str:
160
- ep_loss = player_ep_before - player_ep_after
161
-
162
- # ── Brilliant ──────────────────────────────────────────────────────────────
163
- # Best move + piece sacrifice + wasn't already winning + not left in bad shape
164
- if is_best and is_sacrifice:
165
- if player_ep_before < 0.90 and player_ep_after > 0.50:
166
- return "Brilliant"
167
-
168
- # ── Great ──────────────────────────────────────────────────────────────────
169
- if is_best:
170
- was_losing = player_ep_before < 0.45
171
- is_equal = 0.44 <= player_ep_after <= 0.62
172
- is_winning = player_ep_after > 0.55
173
- major_swing = was_losing and (is_equal or is_winning)
174
-
175
- only_good = (
176
- player_ep_second_best is not None
177
- and player_ep_before - player_ep_second_best > 0.15
178
- )
179
-
180
- if major_swing or only_good:
181
- return "Great"
182
-
183
- # ── Miss ───────────────────────────────────────────────────────────────────
184
- if (
185
- opponent_blunder_swing is not None
186
- and opponent_blunder_swing > 0.10
187
- and ep_before_opponent_blunder is not None
188
- and player_ep_after <= ep_before_opponent_blunder + 0.02
189
- ):
190
- return "Miss"
191
-
192
- # ── EP table ───────────────────────────────────────────────────────────────
193
- ep_loss = max(0.0, ep_loss) # cap negatives (position improved beyond eval)
194
-
195
- if ep_loss == 0.0:
196
- if is_best:
197
- return "Best"
198
- if move_rank is not None and move_rank <= 3:
199
- return "Excellent"
200
- return "Good"
201
- if ep_loss <= 0.02:
202
- return "Excellent"
203
- if ep_loss <= 0.05:
204
- return "Good"
205
- if ep_loss <= 0.10:
206
- return "Inaccuracy"
207
- if ep_loss <= 0.20:
208
- return "Mistake"
209
- return "Blunder"
210
-
211
- # ── Continuation formatting ────────────────────────────────────────────────────
212
-
213
- def format_continuation(moves_san: list[str], move_number: int, player_color: str) -> str:
214
- """Format a list of SAN continuation moves with proper move numbers.
215
-
216
- After white plays move N → continuation starts with black at N, then white at N+1
217
- After black plays move N → continuation starts with white at N+1
218
- """
219
- if not moves_san:
220
- return ""
221
-
222
- parts: list[str] = []
223
-
224
- if player_color == "white":
225
- # Next is black's response at the same move number
226
- next_is_white = False
227
- num = move_number
228
- else:
229
- # Next is white's move, which is move_number + 1
230
- next_is_white = True
231
- num = move_number + 1
232
-
233
- for i, san in enumerate(moves_san):
234
- if next_is_white:
235
- parts.append(f"{num}.")
236
- parts.append(san)
237
- next_is_white = False
238
- else:
239
- if i == 0:
240
- # First black continuation move: needs the "N..." prefix
241
- parts.append(f"{num}...")
242
- parts.append(san)
243
- next_is_white = True
244
- num += 1 # After black plays, white's next turn is N+1
245
-
246
- return " ".join(parts)
247
-
248
- # ── Main analysis entry point ──────────────────────────────────────────────────
249
-
250
- def analyze_game(pgn_text: str, depth: int, progress_cb):
251
- """
252
- Analyze a full PGN game. Calls progress_cb({type, message, progress, [data]}).
253
- """
254
- pgn_io = io.StringIO(pgn_text)
255
- game = chess.pgn.read_game(pgn_io)
256
-
257
- if game is None:
258
- progress_cb({"type": "error", "message": "Could not parse PGN. Please check the notation."})
259
- return
260
-
261
- white = game.headers.get("White", "White")
262
- black = game.headers.get("Black", "Black")
263
-
264
- moves_list = list(game.mainline_moves())
265
- total = len(moves_list)
266
-
267
- if total == 0:
268
- progress_cb({"type": "error", "message": "The PGN contains no moves."})
269
- return
270
-
271
- progress_cb({"type": "progress", "message": "Initializing Stockfish engine…", "progress": 0.0})
272
-
273
- sf_path = _find_stockfish()
274
- try:
275
- engine = chess.engine.SimpleEngine.popen_uci(sf_path)
276
- except FileNotFoundError:
277
- progress_cb({"type": "error",
278
- "message": f"Stockfish not found (tried '{sf_path}'). Install Stockfish and ensure it is on your PATH."})
279
- return
280
-
281
- try:
282
- # Build board snapshots: boards[i] is the state BEFORE move i
283
- boards: list[chess.Board] = []
284
- b = game.board()
285
- for mv in moves_list:
286
- boards.append(b.copy())
287
- b.push(mv)
288
- boards.append(b.copy()) # final position after all moves
289
-
290
- # Analyse every position with MultiPV=5
291
- multipv: list[list[dict]] = []
292
- ep_white: list[float] = []
293
-
294
- for i, board_snap in enumerate(boards):
295
- if i < total:
296
- msg = f"Analyzing move {i + 1} of {total}…"
297
- prog = i / total * 0.90
298
- else:
299
- msg = "Finalizing analysis…"
300
- prog = 0.93
301
-
302
- progress_cb({"type": "progress", "message": msg, "progress": prog})
303
-
304
- infos = engine.analyse(board_snap, chess.engine.Limit(depth=depth), multipv=5)
305
- multipv.append(infos)
306
- ep_white.append(get_ep_white(infos[0]))
307
-
308
- # Classify each move
309
- progress_cb({"type": "progress", "message": "Classifying moves…", "progress": 0.96})
310
-
311
- results = []
312
-
313
- for i, move in enumerate(moves_list):
314
- board_snap = boards[i]
315
- turn = board_snap.turn
316
- color = "white" if turn == chess.WHITE else "black"
317
-
318
- move_san = board_snap.san(move)
319
- move_uci = move.uci()
320
- fen_before = board_snap.fen()
321
- fen_after = boards[i + 1].fen()
322
-
323
- ep_w_before = ep_white[i]
324
- ep_w_after = ep_white[i + 1]
325
-
326
- if turn == chess.WHITE:
327
- player_ep_before = ep_w_before
328
- player_ep_after = ep_w_after
329
- else:
330
- player_ep_before = 1.0 - ep_w_before
331
- player_ep_after = 1.0 - ep_w_after
332
-
333
- # Best move
334
- best_move_obj = multipv[i][0]["pv"][0]
335
- best_move_san = board_snap.san(best_move_obj)
336
- best_move_uci = best_move_obj.uci()
337
- is_best = (move.uci() == best_move_uci)
338
-
339
- # Second-best EP (for "only good move" detection)
340
- player_ep_second_best: float | None = None
341
- if len(multipv[i]) > 1:
342
- ep_sb_w = get_ep_white(multipv[i][1])
343
- player_ep_second_best = ep_sb_w if turn == chess.WHITE else 1.0 - ep_sb_w
344
-
345
- # Rank among top-5
346
- move_rank: int | None = None
347
- for rank, info in enumerate(multipv[i], 1):
348
- if info["pv"][0].uci() == move.uci():
349
- move_rank = rank
350
- break
351
-
352
- # Sacrifice?
353
- is_sacrifice = check_sacrifice(board_snap, move)
354
-
355
- # Miss detection
356
- opponent_blunder_swing: float | None = None
357
- ep_before_opponent_blunder: float | None = None
358
-
359
- if i >= 1:
360
- ep_w_prev = ep_white[i - 1]
361
- if turn == chess.WHITE:
362
- swing = ep_w_before - ep_w_prev
363
- pre_blunder = ep_w_prev
364
- else:
365
- swing = (1.0 - ep_w_before) - (1.0 - ep_w_prev)
366
- pre_blunder = 1.0 - ep_w_prev
367
-
368
- if swing > 0.10:
369
- opponent_blunder_swing = swing
370
- ep_before_opponent_blunder = pre_blunder
371
-
372
- classification = classify_move(
373
- player_ep_before=player_ep_before,
374
- player_ep_after=player_ep_after,
375
- player_ep_second_best=player_ep_second_best,
376
- is_best=is_best,
377
- move_rank=move_rank,
378
- is_sacrifice=is_sacrifice,
379
- opponent_blunder_swing=opponent_blunder_swing,
380
- ep_before_opponent_blunder=ep_before_opponent_blunder,
381
- )
382
-
383
- # Continuation: engine's best line from the position after this move
384
- continuation_san: list[str] = []
385
- if multipv[i + 1] and "pv" in multipv[i + 1][0]:
386
- temp = boards[i + 1].copy()
387
- for cont_mv in multipv[i + 1][0]["pv"][:6]:
388
- try:
389
- continuation_san.append(temp.san(cont_mv))
390
- temp.push(cont_mv)
391
- except Exception:
392
- break
393
-
394
- ep_loss = max(0.0, player_ep_before - player_ep_after)
395
-
396
- results.append({
397
- "move_number": (i // 2) + 1,
398
- "ply": i,
399
- "color": color,
400
- "san": move_san,
401
- "uci": move_uci,
402
- "from_square": chess.square_name(move.from_square),
403
- "to_square": chess.square_name(move.to_square),
404
- "classification": classification,
405
- "ep_loss": round(ep_loss, 4),
406
- "ep_before": round(player_ep_before, 4),
407
- "ep_after": round(player_ep_after, 4),
408
- "best_move_san": best_move_san if not is_best else None,
409
- "best_move_uci": best_move_uci if not is_best else None,
410
- "continuation": continuation_san,
411
- "continuation_fmt": format_continuation(continuation_san,
412
- (i // 2) + 1, color),
413
- "fen_before": fen_before,
414
- "fen_after": fen_after,
415
- "is_best": is_best,
416
- "comment": get_comment(classification),
417
- })
418
-
419
- progress_cb({
420
- "type": "complete",
421
- "message": "Analysis complete!",
422
- "progress": 1.0,
423
- "data": {
424
- "white": white,
425
- "black": black,
426
- "initial_fen": game.board().fen(),
427
- "moves": results,
428
- }
429
- })
430
-
431
- finally:
432
- engine.quit()