Fu01978 commited on
Commit
9b9e6e5
·
verified ·
1 Parent(s): 55c9015

Delete analyzer.py

Browse files
Files changed (1) hide show
  1. analyzer.py +0 -461
analyzer.py DELETED
@@ -1,461 +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 _see(board: chess.Board, square: int, attacker: chess.Color, target_val: int) -> int:
59
- """
60
- Recursive Static Exchange Evaluation.
61
- Returns the net material gain for `attacker` if they initiate a capture
62
- sequence on `square`, where `target_val` is the value of the piece there.
63
- Positive = attacker profits, 0 = even trade, negative = attacker loses.
64
- """
65
- attackers = board.attackers(attacker, square)
66
- if not attackers:
67
- return 0
68
-
69
- # Always capture with the least valuable piece first
70
- best_sq = min(
71
- (sq for sq in attackers if board.piece_at(sq)),
72
- key=lambda sq: PIECE_VALUES.get(board.piece_at(sq).piece_type, 99),
73
- default=None,
74
- )
75
- if best_sq is None:
76
- return 0
77
-
78
- capturing_piece = board.piece_at(best_sq)
79
- capturing_val = PIECE_VALUES.get(capturing_piece.piece_type, 0)
80
-
81
- # Simulate the capture by manually updating a board copy
82
- b2 = board.copy()
83
- b2.remove_piece_at(best_sq)
84
- b2.set_piece_at(square, chess.Piece(capturing_piece.piece_type, attacker))
85
-
86
- # The other side may now recapture — they'll only do so if it's profitable
87
- recapture_gain = _see(b2, square, not attacker, capturing_val)
88
-
89
- # Our gain: captured target_val, but may lose capturing_val if opponent recaptures
90
- return target_val - max(0, recapture_gain)
91
-
92
-
93
- def check_sacrifice(board: chess.Board, move: chess.Move) -> bool:
94
- """
95
- Returns True if this move is a genuine piece sacrifice — a piece of value ≥ 3
96
- is placed on a square where the full capture sequence (SEE) is net positive
97
- for the opponent, meaning the piece is genuinely en prise.
98
- A knight defended by a pawn attacked by a bishop is NOT a sacrifice:
99
- Bxn, pxB = even trade → SEE returns 0 for the opponent → not flagged.
100
- """
101
- piece = board.piece_at(move.from_square)
102
- if piece is None:
103
- return False
104
-
105
- piece_val = PIECE_VALUES.get(piece.piece_type, 0)
106
- if piece_val < 3:
107
- return False # Pawn sacs and king moves ignored
108
-
109
- # If it's a capture, skip the check when we're taking equal or higher value
110
- if board.is_capture(move):
111
- target = board.piece_at(move.to_square)
112
- if target:
113
- target_val = PIECE_VALUES.get(target.piece_type, 0)
114
- if target_val >= piece_val:
115
- return False # Winning or fair capture — not a sac
116
-
117
- board_after = board.copy()
118
- board_after.push(move)
119
- to_sq = move.to_square
120
- opponent = board_after.turn # Opponent moves next
121
-
122
- # SEE: does the opponent come out ahead if they capture our piece?
123
- # If gain_for_opponent <= 0, the exchange doesn't favour them → not a sacrifice.
124
- gain_for_opponent = _see(board_after, to_sq, opponent, piece_val)
125
- return gain_for_opponent > 0
126
-
127
- # ── Move classification ────────────────────────────────────────────────────────
128
-
129
- COMMENTS = {
130
- "Brilliant": [
131
- "A stunning sacrifice that seizes a lasting advantage.",
132
- "Extraordinary piece sacrifice — the position rewards bold play.",
133
- "An unexpected sacrifice with deep positional compensation.",
134
- ],
135
- "Great": [
136
- "A critical move that shifts the balance of the game.",
137
- "Finding this move takes real precision — it dramatically improves the position.",
138
- "The only move that keeps things in hand. Well found.",
139
- ],
140
- "Miss": [
141
- "A missed opportunity — the opponent's error went unpunished.",
142
- "After the opponent's mistake, this fails to press the advantage.",
143
- "The position offered a winning shot, but it slipped away here.",
144
- ],
145
- "Best": [
146
- "The engine's top choice. Precise and principled.",
147
- "Perfect play — the ideal move in this position.",
148
- "Exactly what the position demanded.",
149
- ],
150
- "Excellent": [
151
- "A very strong move that keeps the position under control.",
152
- "Nearly best — a fine practical choice.",
153
- "A sharp, high-quality response.",
154
- ],
155
- "Good": [
156
- "A solid move that maintains the balance.",
157
- "Reasonable play — the position stays roughly equal.",
158
- "A sensible continuation with no serious drawbacks.",
159
- ],
160
- "Inaccuracy": [
161
- "A slight imprecision — a better option was available.",
162
- "Not a serious error, but leaves something on the table.",
163
- "The position allowed for more here.",
164
- ],
165
- "Mistake": [
166
- "An error that hands the opponent a meaningful advantage.",
167
- "This weakens the position more than it needed to.",
168
- "A significant misstep — the opponent can now press hard.",
169
- ],
170
- "Blunder": [
171
- "A serious blunder that could cost the game.",
172
- "A major error — this dramatically changes the evaluation.",
173
- "Devastating. The position collapses after this move.",
174
- ],
175
- }
176
-
177
- def get_comment(classification: str) -> str:
178
- return random.choice(COMMENTS.get(classification, ["—"]))
179
-
180
- def classify_move(
181
- player_ep_before: float,
182
- player_ep_after: float,
183
- player_ep_second_best: float | None,
184
- is_best: bool,
185
- move_rank: int | None,
186
- is_sacrifice: bool,
187
- opponent_blunder_swing: float | None,
188
- ep_before_opponent_blunder: float | None,
189
- ) -> str:
190
- ep_loss = player_ep_before - player_ep_after
191
-
192
- # ── Brilliant ──────────────────────────────────────────────────────────────
193
- # Best move + piece sacrifice + wasn't already winning + not left in bad shape
194
- if is_best and is_sacrifice:
195
- if player_ep_before < 0.90 and player_ep_after > 0.50:
196
- return "Brilliant"
197
-
198
- # ── Great ──────────────────────────────────────────────────────────────────
199
- if is_best:
200
- was_losing = player_ep_before < 0.45
201
- is_equal = 0.44 <= player_ep_after <= 0.62
202
- is_winning = player_ep_after > 0.55
203
- major_swing = was_losing and (is_equal or is_winning)
204
-
205
- only_good = (
206
- player_ep_second_best is not None
207
- and player_ep_before - player_ep_second_best > 0.15
208
- )
209
-
210
- if major_swing or only_good:
211
- return "Great"
212
-
213
- # ── Miss ───────────────────────────────────────────────────────────────────
214
- if (
215
- opponent_blunder_swing is not None
216
- and opponent_blunder_swing > 0.10
217
- and ep_before_opponent_blunder is not None
218
- and player_ep_after <= ep_before_opponent_blunder + 0.02
219
- ):
220
- return "Miss"
221
-
222
- # ── EP table ───────────────────────────────────────────────────────────────
223
- ep_loss = max(0.0, ep_loss) # cap negatives (position improved beyond eval)
224
-
225
- # is_best is checked first — float rounding can produce a tiny non-zero
226
- # ep_loss even for the engine's top move, so we must not let the threshold
227
- # bands override a confirmed best-move result.
228
- if is_best:
229
- return "Best"
230
- if ep_loss <= 0.02:
231
- return "Excellent"
232
- if ep_loss <= 0.05:
233
- return "Good"
234
- if ep_loss <= 0.10:
235
- return "Inaccuracy"
236
- if ep_loss <= 0.20:
237
- return "Mistake"
238
- return "Blunder"
239
-
240
- # ── Continuation formatting ────────────────────────────────────────────────────
241
-
242
- def format_continuation(moves_san: list[str], move_number: int, player_color: str) -> str:
243
- """Format a list of SAN continuation moves with proper move numbers.
244
-
245
- After white plays move N → continuation starts with black at N, then white at N+1
246
- After black plays move N → continuation starts with white at N+1
247
- """
248
- if not moves_san:
249
- return ""
250
-
251
- parts: list[str] = []
252
-
253
- if player_color == "white":
254
- # Next is black's response at the same move number
255
- next_is_white = False
256
- num = move_number
257
- else:
258
- # Next is white's move, which is move_number + 1
259
- next_is_white = True
260
- num = move_number + 1
261
-
262
- for i, san in enumerate(moves_san):
263
- if next_is_white:
264
- parts.append(f"{num}.")
265
- parts.append(san)
266
- next_is_white = False
267
- else:
268
- if i == 0:
269
- # First black continuation move: needs the "N..." prefix
270
- parts.append(f"{num}...")
271
- parts.append(san)
272
- next_is_white = True
273
- num += 1 # After black plays, white's next turn is N+1
274
-
275
- return " ".join(parts)
276
-
277
- # ── Main analysis entry point ──────────────────────────────────────────────────
278
-
279
- def analyze_game(pgn_text: str, depth: int, progress_cb):
280
- """
281
- Analyze a full PGN game. Calls progress_cb({type, message, progress, [data]}).
282
- """
283
- pgn_io = io.StringIO(pgn_text)
284
- game = chess.pgn.read_game(pgn_io)
285
-
286
- if game is None:
287
- progress_cb({"type": "error", "message": "Could not parse PGN. Please check the notation."})
288
- return
289
-
290
- white = game.headers.get("White", "White")
291
- black = game.headers.get("Black", "Black")
292
-
293
- moves_list = list(game.mainline_moves())
294
- total = len(moves_list)
295
-
296
- if total == 0:
297
- progress_cb({"type": "error", "message": "The PGN contains no moves."})
298
- return
299
-
300
- progress_cb({"type": "progress", "message": "Initializing Stockfish engine…", "progress": 0.0})
301
-
302
- sf_path = _find_stockfish()
303
- try:
304
- engine = chess.engine.SimpleEngine.popen_uci(sf_path)
305
- except FileNotFoundError:
306
- progress_cb({"type": "error",
307
- "message": f"Stockfish not found (tried '{sf_path}'). Install Stockfish and ensure it is on your PATH."})
308
- return
309
-
310
- try:
311
- # Build board snapshots: boards[i] is the state BEFORE move i
312
- boards: list[chess.Board] = []
313
- b = game.board()
314
- for mv in moves_list:
315
- boards.append(b.copy())
316
- b.push(mv)
317
- boards.append(b.copy()) # final position after all moves
318
-
319
- # Analyse every position with MultiPV=5
320
- multipv: list[list[dict]] = []
321
- ep_white: list[float] = []
322
-
323
- for i, board_snap in enumerate(boards):
324
- if i < total:
325
- msg = f"Analyzing move {i + 1} of {total}…"
326
- prog = i / total * 0.90
327
- else:
328
- msg = "Finalizing analysis…"
329
- prog = 0.93
330
-
331
- progress_cb({"type": "progress", "message": msg, "progress": prog})
332
-
333
- infos = engine.analyse(board_snap, chess.engine.Limit(depth=depth), multipv=5)
334
- multipv.append(infos)
335
- ep_white.append(get_ep_white(infos[0]))
336
-
337
- # Classify each move
338
- progress_cb({"type": "progress", "message": "Classifying moves…", "progress": 0.96})
339
-
340
- results = []
341
-
342
- for i, move in enumerate(moves_list):
343
- board_snap = boards[i]
344
- turn = board_snap.turn
345
- color = "white" if turn == chess.WHITE else "black"
346
-
347
- move_san = board_snap.san(move)
348
- move_uci = move.uci()
349
- fen_before = board_snap.fen()
350
- fen_after = boards[i + 1].fen()
351
-
352
- ep_w_before = ep_white[i]
353
- ep_w_after = ep_white[i + 1]
354
-
355
- if turn == chess.WHITE:
356
- player_ep_before = ep_w_before
357
- player_ep_after = ep_w_after
358
- else:
359
- player_ep_before = 1.0 - ep_w_before
360
- player_ep_after = 1.0 - ep_w_after
361
-
362
- # Best move
363
- best_move_obj = multipv[i][0]["pv"][0]
364
- best_move_san = board_snap.san(best_move_obj)
365
- best_move_uci = best_move_obj.uci()
366
- is_best = (move.uci() == best_move_uci)
367
-
368
- # Second-best EP (for "only good move" detection)
369
- player_ep_second_best: float | None = None
370
- if len(multipv[i]) > 1:
371
- ep_sb_w = get_ep_white(multipv[i][1])
372
- player_ep_second_best = ep_sb_w if turn == chess.WHITE else 1.0 - ep_sb_w
373
-
374
- # Rank among top-5
375
- move_rank: int | None = None
376
- for rank, info in enumerate(multipv[i], 1):
377
- if info["pv"][0].uci() == move.uci():
378
- move_rank = rank
379
- break
380
-
381
- # Sacrifice?
382
- is_sacrifice = check_sacrifice(board_snap, move)
383
-
384
- # Miss detection
385
- opponent_blunder_swing: float | None = None
386
- ep_before_opponent_blunder: float | None = None
387
-
388
- if i >= 1:
389
- ep_w_prev = ep_white[i - 1]
390
- if turn == chess.WHITE:
391
- swing = ep_w_before - ep_w_prev
392
- pre_blunder = ep_w_prev
393
- else:
394
- swing = (1.0 - ep_w_before) - (1.0 - ep_w_prev)
395
- pre_blunder = 1.0 - ep_w_prev
396
-
397
- if swing > 0.10:
398
- opponent_blunder_swing = swing
399
- ep_before_opponent_blunder = pre_blunder
400
-
401
- classification = classify_move(
402
- player_ep_before=player_ep_before,
403
- player_ep_after=player_ep_after,
404
- player_ep_second_best=player_ep_second_best,
405
- is_best=is_best,
406
- move_rank=move_rank,
407
- is_sacrifice=is_sacrifice,
408
- opponent_blunder_swing=opponent_blunder_swing,
409
- ep_before_opponent_blunder=ep_before_opponent_blunder,
410
- )
411
-
412
- # Continuation: engine's best line from the position after this move
413
- continuation_san: list[str] = []
414
- if multipv[i + 1] and "pv" in multipv[i + 1][0]:
415
- temp = boards[i + 1].copy()
416
- for cont_mv in multipv[i + 1][0]["pv"][:6]:
417
- try:
418
- continuation_san.append(temp.san(cont_mv))
419
- temp.push(cont_mv)
420
- except Exception:
421
- break
422
-
423
- ep_loss = max(0.0, player_ep_before - player_ep_after)
424
-
425
- results.append({
426
- "move_number": (i // 2) + 1,
427
- "ply": i,
428
- "color": color,
429
- "san": move_san,
430
- "uci": move_uci,
431
- "from_square": chess.square_name(move.from_square),
432
- "to_square": chess.square_name(move.to_square),
433
- "classification": classification,
434
- "ep_loss": round(ep_loss, 4),
435
- "ep_before": round(player_ep_before, 4),
436
- "ep_after": round(player_ep_after, 4),
437
- "best_move_san": best_move_san if not is_best else None,
438
- "best_move_uci": best_move_uci if not is_best else None,
439
- "continuation": continuation_san,
440
- "continuation_fmt": format_continuation(continuation_san,
441
- (i // 2) + 1, color),
442
- "fen_before": fen_before,
443
- "fen_after": fen_after,
444
- "is_best": is_best,
445
- "comment": get_comment(classification),
446
- })
447
-
448
- progress_cb({
449
- "type": "complete",
450
- "message": "Analysis complete!",
451
- "progress": 1.0,
452
- "data": {
453
- "white": white,
454
- "black": black,
455
- "initial_fen": game.board().fen(),
456
- "moves": results,
457
- }
458
- })
459
-
460
- finally:
461
- engine.quit()