Fu01978 commited on
Commit
a7419c4
·
verified ·
1 Parent(s): ee0cc4d

Delete analyzer.py

Browse files
Files changed (1) hide show
  1. analyzer.py +0 -548
analyzer.py DELETED
@@ -1,548 +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 _is_hanging(board: chess.Board, square: int, our_color: chess.Color) -> bool:
94
- """
95
- Returns True if the piece on `square` is en prise for the opponent —
96
- i.e. the opponent comes out ahead if they capture it (SEE > 0).
97
- """
98
- piece = board.piece_at(square)
99
- if piece is None or piece.color != our_color:
100
- return False
101
- piece_val = PIECE_VALUES.get(piece.piece_type, 0)
102
- if piece_val < 3:
103
- return False # Ignore pawns and kings
104
- opponent = not our_color
105
- return _see(board, square, opponent, piece_val) > 0
106
-
107
-
108
- def check_sacrifice(board: chess.Board, move: chess.Move) -> bool:
109
- """
110
- Returns True if this move involves a genuine piece sacrifice — either:
111
- (a) The moved piece itself lands en prise (SEE favours the opponent), OR
112
- (b) A friendly piece is newly left hanging after the move — e.g. a queen
113
- that was shielded by the moving piece (pin scenario) is now exposed.
114
-
115
- A knight defended by a pawn attacked by a bishop is NOT a sacrifice:
116
- Bxn, pxB = even trade → SEE = 0 → not flagged.
117
- """
118
- our_color = board.turn
119
- piece = board.piece_at(move.from_square)
120
- if piece is None:
121
- return False
122
-
123
- piece_val = PIECE_VALUES.get(piece.piece_type, 0)
124
-
125
- # ── (a) Moved-piece sacrifice ──────────────────────────────────────────
126
- if piece_val >= 3:
127
- # Skip if we're taking a piece of equal or greater value
128
- if board.is_capture(move):
129
- target = board.piece_at(move.to_square)
130
- if target and PIECE_VALUES.get(target.piece_type, 0) >= piece_val:
131
- pass # Fall through — could still be a sacrifice on the landing sq
132
- else:
133
- pass # Check below
134
-
135
- board_after = board.copy()
136
- board_after.push(move)
137
- opponent = board_after.turn
138
-
139
- gain_for_opponent = _see(board_after, move.to_square, opponent, piece_val)
140
- if gain_for_opponent > 0:
141
- return True
142
-
143
- # ── (b) Piece-left-behind sacrifice (e.g. walking out of a pin) ───────
144
- # Collect which friendly pieces were already hanging BEFORE the move,
145
- # so we only flag pieces that are *newly* exposed.
146
- hanging_before: set[int] = set()
147
- for sq in board.pieces(chess.QUEEN, our_color) | \
148
- board.pieces(chess.ROOK, our_color) | \
149
- board.pieces(chess.BISHOP, our_color) | \
150
- board.pieces(chess.KNIGHT, our_color):
151
- if sq == move.from_square:
152
- continue # This is the piece we're moving — skip
153
- if _is_hanging(board, sq, our_color):
154
- hanging_before.add(sq)
155
-
156
- board_after = board.copy()
157
- board_after.push(move)
158
-
159
- for sq in board_after.pieces(chess.QUEEN, our_color) | \
160
- board_after.pieces(chess.ROOK, our_color) | \
161
- board_after.pieces(chess.BISHOP, our_color) | \
162
- board_after.pieces(chess.KNIGHT, our_color):
163
- if sq == move.to_square:
164
- continue # Already handled in (a)
165
- if sq not in hanging_before and _is_hanging(board_after, sq, our_color):
166
- return True # This piece is newly hanging — it's the real sacrifice
167
-
168
- return False
169
-
170
- # ── Move classification ────────────────────────────────────────────────────────
171
-
172
- COMMENTS = {
173
- "Brilliant": [
174
- "A stunning sacrifice that seizes a lasting advantage.",
175
- "Extraordinary piece sacrifice — the position rewards bold play.",
176
- "An unexpected sacrifice with deep positional compensation.",
177
- ],
178
- "Great": [
179
- "A critical move that shifts the balance of the game.",
180
- "Finding this move takes real precision — it dramatically improves the position.",
181
- "The only move that keeps things in hand. Well found.",
182
- ],
183
- "Miss": [
184
- "A missed opportunity — the opponent's error went unpunished.",
185
- "After the opponent's mistake, this fails to press the advantage.",
186
- "The position offered a winning shot, but it slipped away here.",
187
- ],
188
- "Best": [
189
- "The engine's top choice. Precise and principled.",
190
- "Perfect play — the ideal move in this position.",
191
- "Exactly what the position demanded.",
192
- ],
193
- "Excellent": [
194
- "A very strong move that keeps the position under control.",
195
- "Nearly best — a fine practical choice.",
196
- "A sharp, high-quality response.",
197
- ],
198
- "Good": [
199
- "A solid move that maintains the balance.",
200
- "Reasonable play — the position stays roughly equal.",
201
- "A sensible continuation with no serious drawbacks.",
202
- ],
203
- "Inaccuracy": [
204
- "A slight imprecision — a better option was available.",
205
- "Not a serious error, but leaves something on the table.",
206
- "The position allowed for more here.",
207
- ],
208
- "Mistake": [
209
- "An error that hands the opponent a meaningful advantage.",
210
- "This weakens the position more than it needed to.",
211
- "A significant misstep — the opponent can now press hard.",
212
- ],
213
- "Blunder": [
214
- "A serious blunder that could cost the game.",
215
- "A major error — this dramatically changes the evaluation.",
216
- "Devastating. The position collapses after this move.",
217
- ],
218
- }
219
-
220
- def get_comment(classification: str) -> str:
221
- return random.choice(COMMENTS.get(classification, ["—"]))
222
-
223
- def classify_move(
224
- player_ep_before: float,
225
- player_ep_after: float,
226
- player_ep_second_best: float | None,
227
- is_best: bool,
228
- move_rank: int | None,
229
- is_sacrifice: bool,
230
- opponent_blunder_swing: float | None,
231
- ep_before_opponent_blunder: float | None,
232
- ) -> str:
233
- ep_loss = player_ep_before - player_ep_after
234
-
235
- # ── Brilliant ──────────────────────────────────────────────────────────────
236
- # Best move + piece sacrifice + lands in a good position.
237
- # Two paths to Brilliant:
238
- # 1. Normal: wasn't already near-completely-winning (< 0.97).
239
- # 2. Was already winning but the sacrifice dramatically improves the position
240
- # (ep jump >= 0.15) -- e.g. forcing bishop sac into a mating attack.
241
- if is_best and is_sacrifice:
242
- ep_jump = player_ep_after - player_ep_before
243
- already_winning = player_ep_before >= 0.97
244
- lands_well = player_ep_after > 0.50
245
- if lands_well and (not already_winning or ep_jump >= 0.15):
246
- return "Brilliant"
247
-
248
- # ── Great ──────────────────────────────────────────────────────────────────
249
- if is_best:
250
- was_losing = player_ep_before < 0.45
251
- is_equal = 0.44 <= player_ep_after <= 0.62
252
- is_winning = player_ep_after > 0.55
253
- major_swing = was_losing and (is_equal or is_winning)
254
-
255
- only_good = (
256
- player_ep_second_best is not None
257
- and player_ep_before - player_ep_second_best > 0.15
258
- )
259
-
260
- if major_swing or only_good:
261
- return "Great"
262
-
263
- # ── Miss ───────────────────────────────────────────────────────────────────
264
- if (
265
- opponent_blunder_swing is not None
266
- and opponent_blunder_swing > 0.10
267
- and ep_before_opponent_blunder is not None
268
- and player_ep_after <= ep_before_opponent_blunder + 0.02
269
- ):
270
- return "Miss"
271
-
272
- # ── EP table ───────────────────────────────────────────────────────────────
273
- ep_loss = max(0.0, ep_loss) # cap negatives (position improved beyond eval)
274
-
275
- # is_best is checked first — float rounding can produce a tiny non-zero
276
- # ep_loss even for the engine's top move, so we must not let the threshold
277
- # bands override a confirmed best-move result.
278
- if is_best:
279
- return "Best"
280
- if ep_loss <= 0.02:
281
- return "Excellent"
282
- if ep_loss <= 0.05:
283
- return "Good"
284
- if ep_loss <= 0.10:
285
- return "Inaccuracy"
286
- if ep_loss <= 0.20:
287
- return "Mistake"
288
- return "Blunder"
289
-
290
- # ── Continuation formatting ────────────────────────────────────────────────────
291
-
292
- def format_continuation(moves_san: list[str], move_number: int, player_color: str) -> str:
293
- """Format a list of SAN continuation moves with proper move numbers.
294
-
295
- After white plays move N → continuation starts with black at N, then white at N+1
296
- After black plays move N → continuation starts with white at N+1
297
- """
298
- if not moves_san:
299
- return ""
300
-
301
- parts: list[str] = []
302
-
303
- if player_color == "white":
304
- # Next is black's response at the same move number
305
- next_is_white = False
306
- num = move_number
307
- else:
308
- # Next is white's move, which is move_number + 1
309
- next_is_white = True
310
- num = move_number + 1
311
-
312
- for i, san in enumerate(moves_san):
313
- if next_is_white:
314
- parts.append(f"{num}.")
315
- parts.append(san)
316
- next_is_white = False
317
- else:
318
- if i == 0:
319
- # First black continuation move: needs the "N..." prefix
320
- parts.append(f"{num}...")
321
- parts.append(san)
322
- next_is_white = True
323
- num += 1 # After black plays, white's next turn is N+1
324
-
325
- return " ".join(parts)
326
-
327
- # ── Main analysis entry point ──────────────────────────────────────────────────
328
-
329
- def analyze_game(pgn_text: str, depth: int, progress_cb):
330
- """
331
- Analyze a full PGN game. Calls progress_cb({type, message, progress, [data]}).
332
- """
333
- pgn_io = io.StringIO(pgn_text)
334
- game = chess.pgn.read_game(pgn_io)
335
-
336
- if game is None:
337
- progress_cb({"type": "error", "message": "Could not parse PGN. Please check the notation."})
338
- return
339
-
340
- white = game.headers.get("White", "White")
341
- black = game.headers.get("Black", "Black")
342
-
343
- moves_list = list(game.mainline_moves())
344
- total = len(moves_list)
345
-
346
- if total == 0:
347
- progress_cb({"type": "error", "message": "The PGN contains no moves."})
348
- return
349
-
350
- progress_cb({"type": "progress", "message": "Initializing Stockfish engine…", "progress": 0.0})
351
-
352
- sf_path = _find_stockfish()
353
- try:
354
- engine = chess.engine.SimpleEngine.popen_uci(sf_path)
355
- except FileNotFoundError:
356
- progress_cb({"type": "error",
357
- "message": f"Stockfish not found (tried '{sf_path}'). Install Stockfish and ensure it is on your PATH."})
358
- return
359
-
360
- try:
361
- # Build board snapshots: boards[i] is the state BEFORE move i
362
- boards: list[chess.Board] = []
363
- b = game.board()
364
- for mv in moves_list:
365
- boards.append(b.copy())
366
- b.push(mv)
367
- boards.append(b.copy()) # final position after all moves
368
-
369
- # Analyse every position with MultiPV=5
370
- multipv: list[list[dict]] = []
371
- ep_white: list[float] = []
372
-
373
- for i, board_snap in enumerate(boards):
374
- if i < total:
375
- msg = f"Analyzing move {i + 1} of {total}…"
376
- prog = i / total * 0.90
377
- else:
378
- msg = "Finalizing analysis…"
379
- prog = 0.93
380
-
381
- progress_cb({"type": "progress", "message": msg, "progress": prog})
382
-
383
- infos = engine.analyse(board_snap, chess.engine.Limit(depth=depth), multipv=5)
384
- multipv.append(infos)
385
- ep_white.append(get_ep_white(infos[0]))
386
-
387
- # Classify each move
388
- progress_cb({"type": "progress", "message": "Classifying moves…", "progress": 0.96})
389
-
390
- results = []
391
-
392
- for i, move in enumerate(moves_list):
393
- board_snap = boards[i]
394
- turn = board_snap.turn
395
- color = "white" if turn == chess.WHITE else "black"
396
-
397
- move_san = board_snap.san(move)
398
- move_uci = move.uci()
399
- fen_before = board_snap.fen()
400
- fen_after = boards[i + 1].fen()
401
-
402
- ep_w_before = ep_white[i]
403
- ep_w_after = ep_white[i + 1]
404
-
405
- if turn == chess.WHITE:
406
- player_ep_before = ep_w_before
407
- player_ep_after = ep_w_after
408
- else:
409
- player_ep_before = 1.0 - ep_w_before
410
- player_ep_after = 1.0 - ep_w_after
411
-
412
- # Best move
413
- best_move_obj = multipv[i][0]["pv"][0]
414
- best_move_san = board_snap.san(best_move_obj)
415
- best_move_uci = best_move_obj.uci()
416
- is_best = (move.uci() == best_move_uci)
417
-
418
- # Second-best EP (for "only good move" detection)
419
- player_ep_second_best: float | None = None
420
- if len(multipv[i]) > 1:
421
- ep_sb_w = get_ep_white(multipv[i][1])
422
- player_ep_second_best = ep_sb_w if turn == chess.WHITE else 1.0 - ep_sb_w
423
-
424
- # Rank among top-5
425
- move_rank: int | None = None
426
- for rank, info in enumerate(multipv[i], 1):
427
- if info["pv"][0].uci() == move.uci():
428
- move_rank = rank
429
- break
430
-
431
- # Sacrifice?
432
- is_sacrifice = check_sacrifice(board_snap, move)
433
-
434
- # Miss detection
435
- opponent_blunder_swing: float | None = None
436
- ep_before_opponent_blunder: float | None = None
437
-
438
- if i >= 1:
439
- ep_w_prev = ep_white[i - 1]
440
- if turn == chess.WHITE:
441
- swing = ep_w_before - ep_w_prev
442
- pre_blunder = ep_w_prev
443
- else:
444
- swing = (1.0 - ep_w_before) - (1.0 - ep_w_prev)
445
- pre_blunder = 1.0 - ep_w_prev
446
-
447
- if swing > 0.10:
448
- opponent_blunder_swing = swing
449
- ep_before_opponent_blunder = pre_blunder
450
-
451
- classification = classify_move(
452
- player_ep_before=player_ep_before,
453
- player_ep_after=player_ep_after,
454
- player_ep_second_best=player_ep_second_best,
455
- is_best=is_best,
456
- move_rank=move_rank,
457
- is_sacrifice=is_sacrifice,
458
- opponent_blunder_swing=opponent_blunder_swing,
459
- ep_before_opponent_blunder=ep_before_opponent_blunder,
460
- )
461
-
462
- # Continuation: engine's best line from the position after this move
463
- continuation_san: list[str] = []
464
- if multipv[i + 1] and "pv" in multipv[i + 1][0]:
465
- temp = boards[i + 1].copy()
466
- for cont_mv in multipv[i + 1][0]["pv"][:6]:
467
- try:
468
- continuation_san.append(temp.san(cont_mv))
469
- temp.push(cont_mv)
470
- except Exception:
471
- break
472
-
473
- ep_loss = max(0.0, player_ep_before - player_ep_after)
474
-
475
- results.append({
476
- "move_number": (i // 2) + 1,
477
- "ply": i,
478
- "color": color,
479
- "san": move_san,
480
- "uci": move_uci,
481
- "from_square": chess.square_name(move.from_square),
482
- "to_square": chess.square_name(move.to_square),
483
- "classification": classification,
484
- "ep_loss": round(ep_loss, 4),
485
- "ep_before": round(player_ep_before, 4),
486
- "ep_after": round(player_ep_after, 4),
487
- "best_move_san": best_move_san if not is_best else None,
488
- "best_move_uci": best_move_uci if not is_best else None,
489
- "continuation": continuation_san,
490
- "continuation_fmt": format_continuation(continuation_san,
491
- (i // 2) + 1, color),
492
- "fen_before": fen_before,
493
- "fen_after": fen_after,
494
- "is_best": is_best,
495
- "comment": get_comment(classification),
496
- })
497
-
498
- progress_cb({
499
- "type": "complete",
500
- "message": "Analysis complete!",
501
- "progress": 1.0,
502
- "data": {
503
- "white": white,
504
- "black": black,
505
- "initial_fen": game.board().fen(),
506
- "moves": results,
507
- "summary": _compute_summary(results),
508
- }
509
- })
510
-
511
- finally:
512
- engine.quit()
513
-
514
-
515
- # ── Summary stats ──────────────────────────────────────────────────────────────
516
-
517
- ALL_CLASSIFICATIONS = [
518
- "Brilliant", "Great", "Best", "Excellent", "Good",
519
- "Inaccuracy", "Mistake", "Blunder", "Miss",
520
- ]
521
-
522
- def _compute_summary(moves: list[dict]) -> dict:
523
- """Return per-player classification counts and accuracy."""
524
- stats = {}
525
- for color in ("white", "black"):
526
- player_moves = [m for m in moves if m["color"] == color]
527
-
528
- counts = {cls: 0 for cls in ALL_CLASSIFICATIONS}
529
- for m in player_moves:
530
- cls = m["classification"]
531
- if cls in counts:
532
- counts[cls] += 1
533
-
534
- # Accuracy: average fraction of winning chances preserved each move.
535
- # For each move: score = ep_after / max(ep_before, 0.01), clamped 0-1.
536
- # Gives 100% for Best/Brilliant, degrades proportionally with EP loss.
537
- if player_moves:
538
- scores = [
539
- max(0.0, min(1.0, m["ep_after"] / max(m["ep_before"], 0.01)))
540
- for m in player_moves
541
- ]
542
- accuracy = round(sum(scores) / len(scores) * 100, 1)
543
- else:
544
- accuracy = 0.0
545
-
546
- stats[color] = {"accuracy": accuracy, "counts": counts}
547
-
548
- return stats