Fu01978 commited on
Commit
293bfaf
·
verified ·
1 Parent(s): 98ec1ae

Upload analyzer (9).py

Browse files
Files changed (1) hide show
  1. analyzer (9).py +635 -0
analyzer (9).py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chess game analyzer using Stockfish + Expected Points model.
3
+
4
+ Classification hierarchy (highest priority first):
5
+ Book → 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 json
14
+ import random
15
+ import shutil
16
+ import os
17
+
18
+ def _find_stockfish() -> str:
19
+ """Locate stockfish binary on common paths."""
20
+ # Try PATH first
21
+ found = shutil.which("stockfish")
22
+ if found:
23
+ return found
24
+ for path in [
25
+ "/usr/games/stockfish",
26
+ "/usr/bin/stockfish",
27
+ "/usr/local/bin/stockfish",
28
+ "/opt/homebrew/bin/stockfish",
29
+ "/opt/homebrew/games/stockfish",
30
+ ]:
31
+ if os.path.isfile(path) and os.access(path, os.X_OK):
32
+ return path
33
+ return "stockfish" # Let it fail with a clear error
34
+
35
+
36
+ # ── ECO opening book ───────────────────────────────────────────────────────────
37
+
38
+ def _load_eco_db() -> dict:
39
+ """
40
+ Load ECO JSON files (ecoA-D.json) from an eco/ folder next to this file.
41
+ Keys are FEN strings; values contain name, eco code, and moves.
42
+ Returns an empty dict gracefully if the folder or files are missing.
43
+ """
44
+ db: dict = {}
45
+ eco_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "eco")
46
+ if not os.path.isdir(eco_dir):
47
+ return db
48
+ for letter in "ABCD":
49
+ path = os.path.join(eco_dir, f"eco{letter}.json")
50
+ if not os.path.isfile(path):
51
+ continue
52
+ try:
53
+ with open(path, encoding="utf-8") as f:
54
+ data = json.load(f)
55
+ db.update(data)
56
+ except Exception:
57
+ pass
58
+ return db
59
+
60
+ ECO_DB: dict = _load_eco_db()
61
+
62
+ def lookup_book(fen_after: str) -> dict | None:
63
+ """Return opening entry if position is in ECO db, else None."""
64
+ return ECO_DB.get(fen_after)
65
+
66
+ # ── Expected Points ────────────────────────────────────────────────────────────
67
+
68
+ def cp_to_ep(cp: float, k: float = 0.4) -> float:
69
+ """Convert centipawn score to Expected Points from White's perspective."""
70
+ return 1.0 / (1.0 + math.exp(-k * (cp / 100.0)))
71
+
72
+ def score_to_ep_white(score: chess.engine.Score) -> float:
73
+ """Convert a PovScore (already in White's POV) to EP."""
74
+ if score.is_mate():
75
+ m = score.mate()
76
+ return 1.0 if (m is not None and m > 0) else 0.0
77
+ cp = score.score()
78
+ return cp_to_ep(cp if cp is not None else 0)
79
+
80
+ def get_ep_white(info: dict) -> float:
81
+ return score_to_ep_white(info["score"].white())
82
+
83
+ # ── Sacrifice detection ────────────────────────────────────────────────────────
84
+
85
+ PIECE_VALUES = {
86
+ chess.PAWN: 1, chess.KNIGHT: 3, chess.BISHOP: 3,
87
+ chess.ROOK: 5, chess.QUEEN: 9, chess.KING: 99
88
+ }
89
+
90
+ def _see(board: chess.Board, square: int, attacker: chess.Color, target_val: int) -> int:
91
+ """
92
+ Recursive Static Exchange Evaluation.
93
+ Returns the net material gain for `attacker` if they initiate a capture
94
+ sequence on `square`, where `target_val` is the value of the piece there.
95
+ Positive = attacker profits, 0 = even trade, negative = attacker loses.
96
+ """
97
+ attackers = board.attackers(attacker, square)
98
+ if not attackers:
99
+ return 0
100
+
101
+ # Always capture with the least valuable piece first
102
+ best_sq = min(
103
+ (sq for sq in attackers if board.piece_at(sq)),
104
+ key=lambda sq: PIECE_VALUES.get(board.piece_at(sq).piece_type, 99),
105
+ default=None,
106
+ )
107
+ if best_sq is None:
108
+ return 0
109
+
110
+ capturing_piece = board.piece_at(best_sq)
111
+ capturing_val = PIECE_VALUES.get(capturing_piece.piece_type, 0)
112
+
113
+ # Simulate the capture by manually updating a board copy
114
+ b2 = board.copy()
115
+ b2.remove_piece_at(best_sq)
116
+ b2.set_piece_at(square, chess.Piece(capturing_piece.piece_type, attacker))
117
+
118
+ # The other side may now recapture — they'll only do so if it's profitable
119
+ recapture_gain = _see(b2, square, not attacker, capturing_val)
120
+
121
+ # Our gain: captured target_val, but may lose capturing_val if opponent recaptures
122
+ return target_val - max(0, recapture_gain)
123
+
124
+
125
+ def _is_hanging(board: chess.Board, square: int, our_color: chess.Color) -> bool:
126
+ """
127
+ Returns True if the piece on `square` is en prise for the opponent —
128
+ i.e. the opponent comes out ahead if they capture it (SEE > 0).
129
+ """
130
+ piece = board.piece_at(square)
131
+ if piece is None or piece.color != our_color:
132
+ return False
133
+ piece_val = PIECE_VALUES.get(piece.piece_type, 0)
134
+ if piece_val < 3:
135
+ return False # Ignore pawns and kings
136
+ opponent = not our_color
137
+ return _see(board, square, opponent, piece_val) > 0
138
+
139
+
140
+ def check_sacrifice(board: chess.Board, move: chess.Move) -> bool:
141
+ """
142
+ Returns True if this move involves a genuine piece sacrifice — either:
143
+ (a) The moved piece itself lands en prise (SEE favours the opponent), OR
144
+ (b) A friendly piece is newly left hanging after the move — e.g. a queen
145
+ that was shielded by the moving piece (pin scenario) is now exposed.
146
+
147
+ A knight defended by a pawn attacked by a bishop is NOT a sacrifice:
148
+ Bxn, pxB = even trade → SEE = 0 → not flagged.
149
+ """
150
+ our_color = board.turn
151
+ piece = board.piece_at(move.from_square)
152
+ if piece is None:
153
+ return False
154
+
155
+ piece_val = PIECE_VALUES.get(piece.piece_type, 0)
156
+
157
+ # ── (a) Moved-piece sacrifice ──────────────────────────────────────────
158
+ if piece_val >= 3:
159
+ # Skip if we're taking a piece of equal or greater value
160
+ if board.is_capture(move):
161
+ target = board.piece_at(move.to_square)
162
+ if target and PIECE_VALUES.get(target.piece_type, 0) >= piece_val:
163
+ pass # Fall through — could still be a sacrifice on the landing sq
164
+ else:
165
+ pass # Check below
166
+
167
+ board_after = board.copy()
168
+ board_after.push(move)
169
+ opponent = board_after.turn
170
+
171
+ gain_for_opponent = _see(board_after, move.to_square, opponent, piece_val)
172
+ if gain_for_opponent > 0:
173
+ return True
174
+
175
+ # ── (b) Piece-left-behind sacrifice (e.g. walking out of a pin) ───────
176
+ # Collect which friendly pieces were already hanging BEFORE the move,
177
+ # so we only flag pieces that are *newly* exposed.
178
+ hanging_before: set[int] = set()
179
+ for sq in board.pieces(chess.QUEEN, our_color) | \
180
+ board.pieces(chess.ROOK, our_color) | \
181
+ board.pieces(chess.BISHOP, our_color) | \
182
+ board.pieces(chess.KNIGHT, our_color):
183
+ if sq == move.from_square:
184
+ continue # This is the piece we're moving — skip
185
+ if _is_hanging(board, sq, our_color):
186
+ hanging_before.add(sq)
187
+
188
+ board_after = board.copy()
189
+ board_after.push(move)
190
+
191
+ for sq in board_after.pieces(chess.QUEEN, our_color) | \
192
+ board_after.pieces(chess.ROOK, our_color) | \
193
+ board_after.pieces(chess.BISHOP, our_color) | \
194
+ board_after.pieces(chess.KNIGHT, our_color):
195
+ if sq == move.to_square:
196
+ continue # Already handled in (a)
197
+ if sq not in hanging_before and _is_hanging(board_after, sq, our_color):
198
+ return True # This piece is newly hanging — it's the real sacrifice
199
+
200
+ return False
201
+
202
+ # ── Move classification ────────────────────────────────────────────────────────
203
+
204
+ COMMENTS = {
205
+ "Book": [
206
+ "A well-known opening move.",
207
+ "Theory — this position has been played thousands of times.",
208
+ "A mainline opening move.",
209
+ ],
210
+ "Brilliant": [
211
+ "A stunning sacrifice that seizes a lasting advantage.",
212
+ "Extraordinary piece sacrifice — the position rewards bold play.",
213
+ "An unexpected sacrifice with deep positional compensation.",
214
+ ],
215
+ "Great": [
216
+ "A critical move that shifts the balance of the game.",
217
+ "Finding this move takes real precision — it dramatically improves the position.",
218
+ "The only move that keeps things in hand. Well found.",
219
+ ],
220
+ "Miss": [
221
+ "A missed opportunity — the opponent's error went unpunished.",
222
+ "After the opponent's mistake, this fails to press the advantage.",
223
+ "The position offered a winning shot, but it slipped away here.",
224
+ ],
225
+ "Best": [
226
+ "The engine's top choice. Precise and principled.",
227
+ "Perfect play — the ideal move in this position.",
228
+ "Exactly what the position demanded.",
229
+ ],
230
+ "Excellent": [
231
+ "A very strong move that keeps the position under control.",
232
+ "Nearly best — a fine practical choice.",
233
+ "A sharp, high-quality response.",
234
+ ],
235
+ "Good": [
236
+ "A solid move that maintains the balance.",
237
+ "Reasonable play — the position stays roughly equal.",
238
+ "A sensible continuation with no serious drawbacks.",
239
+ ],
240
+ "Inaccuracy": [
241
+ "A slight imprecision — a better option was available.",
242
+ "Not a serious error, but leaves something on the table.",
243
+ "The position allowed for more here.",
244
+ ],
245
+ "Mistake": [
246
+ "An error that hands the opponent a meaningful advantage.",
247
+ "This weakens the position more than it needed to.",
248
+ "A significant misstep — the opponent can now press hard.",
249
+ ],
250
+ "Blunder": [
251
+ "A serious blunder that could cost the game.",
252
+ "A major error — this dramatically changes the evaluation.",
253
+ "Devastating. The position collapses after this move.",
254
+ ],
255
+ }
256
+
257
+ def _material_gain(board_before: 'chess.Board', board_after: 'chess.Board', our_color: chess.Color) -> int:
258
+ """
259
+ Net material change for our_color between two board states, in pawn units.
260
+ Positive = we gained material, negative = we lost material.
261
+ Only counts pieces worth >= 1 (i.e. everything except kings).
262
+ """
263
+ def count(board, color):
264
+ total = 0
265
+ for pt, val in PIECE_VALUES.items():
266
+ if pt == chess.KING:
267
+ continue
268
+ total += len(board.pieces(pt, color)) * val
269
+ return total
270
+
271
+ our_before = count(board_before, our_color)
272
+ our_after = count(board_after, our_color)
273
+ opp_before = count(board_before, not our_color)
274
+ opp_after = count(board_after, not our_color)
275
+
276
+ # Gain = what we kept/gained minus what we lost,
277
+ # measured against what the opponent lost (captures)
278
+ return (our_after - our_before) - (opp_after - opp_before)
279
+
280
+
281
+ def get_comment(classification: str) -> str:
282
+ return random.choice(COMMENTS.get(classification, ["—"]))
283
+
284
+ def classify_move(
285
+ player_ep_before: float,
286
+ player_ep_after: float,
287
+ player_ep_second_best: float | None,
288
+ is_best: bool,
289
+ move_rank: int | None,
290
+ is_sacrifice: bool,
291
+ opponent_blunder_swing: float | None,
292
+ ep_before_opponent_blunder: float | None,
293
+ board_before: 'chess.Board | None' = None,
294
+ board_after: 'chess.Board | None' = None,
295
+ our_color: 'chess.Color | None' = None,
296
+ ) -> str:
297
+ ep_loss = player_ep_before - player_ep_after
298
+
299
+ # ── Brilliant ──────────────────────────────────────────────────────────────
300
+ # Best move + piece sacrifice + lands in a good position + significant material swing.
301
+ # Two paths to Brilliant:
302
+ # 1. Normal: wasn't already near-completely-winning (< 0.97).
303
+ # 2. Was already winning but the sacrifice dramatically improves the position
304
+ # (ep jump >= 0.15) -- e.g. forcing bishop sac into a mating attack.
305
+ # Downgrade to Great if the material net gain is <= 2 pawns: a tiny material
306
+ # pickup doesn't justify Brilliant even if every other condition is met.
307
+ if is_best and is_sacrifice:
308
+ ep_jump = player_ep_after - player_ep_before
309
+ already_winning = player_ep_before >= 0.97
310
+ lands_well = player_ep_after >= 0.45 # equal or better after sac is fine
311
+ if lands_well and (not already_winning or ep_jump >= 0.15):
312
+ # Check material net gain — if boards provided, downgrade to Great
313
+ # when the immediate material swing is trivial (<= 2 pawn units).
314
+ if board_before is not None and board_after is not None and our_color is not None:
315
+ mat_gain = _material_gain(board_before, board_after, our_color)
316
+ if mat_gain <= 2:
317
+ return "Great"
318
+ return "Brilliant"
319
+
320
+ # ── Great ──────────────────────────────────────────────────────────────────
321
+ if is_best:
322
+ was_losing = player_ep_before < 0.45
323
+ is_equal = 0.44 <= player_ep_after <= 0.62
324
+ is_winning = player_ep_after > 0.55
325
+ major_swing = was_losing and (is_equal or is_winning)
326
+
327
+ only_good = (
328
+ player_ep_second_best is not None
329
+ and player_ep_before - player_ep_second_best > 0.15
330
+ )
331
+
332
+ if major_swing or only_good:
333
+ return "Great"
334
+
335
+ # ── Miss ───────────────────────────────────────────────────────────────────
336
+ if (
337
+ opponent_blunder_swing is not None
338
+ and opponent_blunder_swing > 0.10
339
+ and ep_before_opponent_blunder is not None
340
+ and player_ep_after <= ep_before_opponent_blunder + 0.02
341
+ ):
342
+ return "Miss"
343
+
344
+ # ── EP table ───────────────────────────────────────────────────────────────
345
+ ep_loss = max(0.0, ep_loss) # cap negatives (position improved beyond eval)
346
+
347
+ # is_best is checked first — float rounding can produce a tiny non-zero
348
+ # ep_loss even for the engine's top move, so we must not let the threshold
349
+ # bands override a confirmed best-move result.
350
+ if is_best:
351
+ return "Best"
352
+ if ep_loss <= 0.02:
353
+ return "Excellent"
354
+ if ep_loss <= 0.05:
355
+ return "Good"
356
+ if ep_loss <= 0.10:
357
+ return "Inaccuracy"
358
+ if ep_loss <= 0.20:
359
+ return "Mistake"
360
+ return "Blunder"
361
+
362
+ # ── Continuation formatting ────���───────────────────────────────────────────────
363
+
364
+ def format_continuation(moves_san: list[str], move_number: int, player_color: str) -> str:
365
+ """Format a list of SAN continuation moves with proper move numbers.
366
+
367
+ After white plays move N → continuation starts with black at N, then white at N+1
368
+ After black plays move N → continuation starts with white at N+1
369
+ """
370
+ if not moves_san:
371
+ return ""
372
+
373
+ parts: list[str] = []
374
+
375
+ if player_color == "white":
376
+ # Next is black's response at the same move number
377
+ next_is_white = False
378
+ num = move_number
379
+ else:
380
+ # Next is white's move, which is move_number + 1
381
+ next_is_white = True
382
+ num = move_number + 1
383
+
384
+ for i, san in enumerate(moves_san):
385
+ if next_is_white:
386
+ parts.append(f"{num}.")
387
+ parts.append(san)
388
+ next_is_white = False
389
+ else:
390
+ if i == 0:
391
+ # First black continuation move: needs the "N..." prefix
392
+ parts.append(f"{num}...")
393
+ parts.append(san)
394
+ next_is_white = True
395
+ num += 1 # After black plays, white's next turn is N+1
396
+
397
+ return " ".join(parts)
398
+
399
+ # ── Main analysis entry point ──────────────────────────────────────────────────
400
+
401
+ def analyze_game(pgn_text: str, depth: int, progress_cb):
402
+ """
403
+ Analyze a full PGN game. Calls progress_cb({type, message, progress, [data]}).
404
+ """
405
+ pgn_io = io.StringIO(pgn_text)
406
+ game = chess.pgn.read_game(pgn_io)
407
+
408
+ if game is None:
409
+ progress_cb({"type": "error", "message": "Could not parse PGN. Please check the notation."})
410
+ return
411
+
412
+ white = game.headers.get("White", "White")
413
+ black = game.headers.get("Black", "Black")
414
+
415
+ moves_list = list(game.mainline_moves())
416
+ total = len(moves_list)
417
+
418
+ if total == 0:
419
+ progress_cb({"type": "error", "message": "The PGN contains no moves."})
420
+ return
421
+
422
+ progress_cb({"type": "progress", "message": "Initializing Stockfish engine…", "progress": 0.0})
423
+
424
+ sf_path = _find_stockfish()
425
+ try:
426
+ engine = chess.engine.SimpleEngine.popen_uci(sf_path)
427
+ except FileNotFoundError:
428
+ progress_cb({"type": "error",
429
+ "message": f"Stockfish not found (tried '{sf_path}'). Install Stockfish and ensure it is on your PATH."})
430
+ return
431
+
432
+ try:
433
+ # Build board snapshots: boards[i] is the state BEFORE move i
434
+ boards: list[chess.Board] = []
435
+ b = game.board()
436
+ for mv in moves_list:
437
+ boards.append(b.copy())
438
+ b.push(mv)
439
+ boards.append(b.copy()) # final position after all moves
440
+
441
+ # Analyse every position with MultiPV=5
442
+ multipv: list[list[dict]] = []
443
+ ep_white: list[float] = []
444
+
445
+ for i, board_snap in enumerate(boards):
446
+ if i < total:
447
+ msg = f"Analyzing move {i + 1} of {total}…"
448
+ prog = i / total * 0.90
449
+ else:
450
+ msg = "Finalizing analysis…"
451
+ prog = 0.93
452
+
453
+ progress_cb({"type": "progress", "message": msg, "progress": prog})
454
+
455
+ infos = engine.analyse(board_snap, chess.engine.Limit(depth=depth), multipv=5)
456
+ multipv.append(infos)
457
+ ep_white.append(get_ep_white(infos[0]))
458
+
459
+ # Classify each move
460
+ progress_cb({"type": "progress", "message": "Classifying moves…", "progress": 0.96})
461
+
462
+ results = []
463
+
464
+ for i, move in enumerate(moves_list):
465
+ board_snap = boards[i]
466
+ turn = board_snap.turn
467
+ color = "white" if turn == chess.WHITE else "black"
468
+
469
+ move_san = board_snap.san(move)
470
+ move_uci = move.uci()
471
+ fen_before = board_snap.fen()
472
+ fen_after = boards[i + 1].fen()
473
+
474
+ ep_w_before = ep_white[i]
475
+ ep_w_after = ep_white[i + 1]
476
+
477
+ if turn == chess.WHITE:
478
+ player_ep_before = ep_w_before
479
+ player_ep_after = ep_w_after
480
+ else:
481
+ player_ep_before = 1.0 - ep_w_before
482
+ player_ep_after = 1.0 - ep_w_after
483
+
484
+ # Best move
485
+ best_move_obj = multipv[i][0]["pv"][0]
486
+ best_move_san = board_snap.san(best_move_obj)
487
+ best_move_uci = best_move_obj.uci()
488
+ is_best = (move.uci() == best_move_uci)
489
+
490
+ # Second-best EP (for "only good move" detection)
491
+ player_ep_second_best: float | None = None
492
+ if len(multipv[i]) > 1:
493
+ ep_sb_w = get_ep_white(multipv[i][1])
494
+ player_ep_second_best = ep_sb_w if turn == chess.WHITE else 1.0 - ep_sb_w
495
+
496
+ # Rank among top-5
497
+ move_rank: int | None = None
498
+ for rank, info in enumerate(multipv[i], 1):
499
+ if info["pv"][0].uci() == move.uci():
500
+ move_rank = rank
501
+ break
502
+
503
+ # Sacrifice?
504
+ is_sacrifice = check_sacrifice(board_snap, move)
505
+
506
+ # Miss detection
507
+ opponent_blunder_swing: float | None = None
508
+ ep_before_opponent_blunder: float | None = None
509
+
510
+ if i >= 1:
511
+ ep_w_prev = ep_white[i - 1]
512
+ if turn == chess.WHITE:
513
+ swing = ep_w_before - ep_w_prev
514
+ pre_blunder = ep_w_prev
515
+ else:
516
+ swing = (1.0 - ep_w_before) - (1.0 - ep_w_prev)
517
+ pre_blunder = 1.0 - ep_w_prev
518
+
519
+ if swing > 0.10:
520
+ opponent_blunder_swing = swing
521
+ ep_before_opponent_blunder = pre_blunder
522
+
523
+ # Book move check — if the resulting position is in the ECO db,
524
+ # classify immediately regardless of EP; opening theory trumps evaluation.
525
+ book_entry = lookup_book(fen_after)
526
+ if book_entry:
527
+ classification = "Book"
528
+ opening_name = book_entry.get("name", "")
529
+ opening_eco = book_entry.get("eco", "")
530
+ else:
531
+ opening_name = ""
532
+ opening_eco = ""
533
+ classification = classify_move(
534
+ player_ep_before=player_ep_before,
535
+ player_ep_after=player_ep_after,
536
+ player_ep_second_best=player_ep_second_best,
537
+ is_best=is_best,
538
+ move_rank=move_rank,
539
+ is_sacrifice=is_sacrifice,
540
+ opponent_blunder_swing=opponent_blunder_swing,
541
+ ep_before_opponent_blunder=ep_before_opponent_blunder,
542
+ board_before=board_snap,
543
+ board_after=boards[i + 1],
544
+ our_color=turn,
545
+ )
546
+
547
+ # Continuation: engine's best line from the position after this move
548
+ continuation_san: list[str] = []
549
+ if multipv[i + 1] and "pv" in multipv[i + 1][0]:
550
+ temp = boards[i + 1].copy()
551
+ for cont_mv in multipv[i + 1][0]["pv"][:6]:
552
+ try:
553
+ continuation_san.append(temp.san(cont_mv))
554
+ temp.push(cont_mv)
555
+ except Exception:
556
+ break
557
+
558
+ ep_loss = max(0.0, player_ep_before - player_ep_after)
559
+
560
+ results.append({
561
+ "move_number": (i // 2) + 1,
562
+ "ply": i,
563
+ "color": color,
564
+ "san": move_san,
565
+ "uci": move_uci,
566
+ "from_square": chess.square_name(move.from_square),
567
+ "to_square": chess.square_name(move.to_square),
568
+ "classification": classification,
569
+ "ep_loss": round(ep_loss, 4),
570
+ "ep_before": round(player_ep_before, 4),
571
+ "ep_after": round(player_ep_after, 4),
572
+ "best_move_san": best_move_san if not is_best else None,
573
+ "best_move_uci": best_move_uci if not is_best else None,
574
+ "continuation": continuation_san,
575
+ "continuation_fmt": format_continuation(continuation_san,
576
+ (i // 2) + 1, color),
577
+ "fen_before": fen_before,
578
+ "fen_after": fen_after,
579
+ "is_best": is_best,
580
+ "comment": get_comment(classification),
581
+ "opening_name": opening_name,
582
+ "opening_eco": opening_eco,
583
+ })
584
+
585
+ progress_cb({
586
+ "type": "complete",
587
+ "message": "Analysis complete!",
588
+ "progress": 1.0,
589
+ "data": {
590
+ "white": white,
591
+ "black": black,
592
+ "initial_fen": game.board().fen(),
593
+ "moves": results,
594
+ "summary": _compute_summary(results),
595
+ }
596
+ })
597
+
598
+ finally:
599
+ engine.quit()
600
+
601
+
602
+ # ── Summary stats ──────────────────────────────────────────────────────────────
603
+
604
+ ALL_CLASSIFICATIONS = [
605
+ "Book", "Brilliant", "Great", "Best", "Excellent", "Good",
606
+ "Inaccuracy", "Mistake", "Blunder", "Miss",
607
+ ]
608
+
609
+ def _compute_summary(moves: list[dict]) -> dict:
610
+ """Return per-player classification counts and accuracy."""
611
+ stats = {}
612
+ for color in ("white", "black"):
613
+ player_moves = [m for m in moves if m["color"] == color]
614
+
615
+ counts = {cls: 0 for cls in ALL_CLASSIFICATIONS}
616
+ for m in player_moves:
617
+ cls = m["classification"]
618
+ if cls in counts:
619
+ counts[cls] += 1
620
+
621
+ # Accuracy: average fraction of winning chances preserved each move.
622
+ # For each move: score = ep_after / max(ep_before, 0.01), clamped 0-1.
623
+ # Gives 100% for Best/Brilliant, degrades proportionally with EP loss.
624
+ if player_moves:
625
+ scores = [
626
+ max(0.0, min(1.0, m["ep_after"] / max(m["ep_before"], 0.01)))
627
+ for m in player_moves
628
+ ]
629
+ accuracy = round(sum(scores) / len(scores) * 100, 1)
630
+ else:
631
+ accuracy = 0.0
632
+
633
+ stats[color] = {"accuracy": accuracy, "counts": counts}
634
+
635
+ return stats