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

Delete analyzer.py

Browse files
Files changed (1) hide show
  1. analyzer.py +0 -597
analyzer.py DELETED
@@ -1,597 +0,0 @@
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 get_comment(classification: str) -> str:
258
- return random.choice(COMMENTS.get(classification, ["—"]))
259
-
260
- def classify_move(
261
- player_ep_before: float,
262
- player_ep_after: float,
263
- player_ep_second_best: float | None,
264
- is_best: bool,
265
- move_rank: int | None,
266
- is_sacrifice: bool,
267
- opponent_blunder_swing: float | None,
268
- ep_before_opponent_blunder: float | None,
269
- ) -> str:
270
- ep_loss = player_ep_before - player_ep_after
271
-
272
- # ── Brilliant ──────────────────────────────────────────────────────────────
273
- # Best move + piece sacrifice + lands in a good position.
274
- # Two paths to Brilliant:
275
- # 1. Normal: wasn't already near-completely-winning (< 0.97).
276
- # 2. Was already winning but the sacrifice dramatically improves the position
277
- # (ep jump >= 0.15) -- e.g. forcing bishop sac into a mating attack.
278
- if is_best and is_sacrifice:
279
- ep_jump = player_ep_after - player_ep_before
280
- already_winning = player_ep_before >= 0.97
281
- lands_well = player_ep_after >= 0.45 # equal or better after sac is fine
282
- if lands_well and (not already_winning or ep_jump >= 0.15):
283
- return "Brilliant"
284
-
285
- # ── Great ──────────────────────────────────────────────────────────────────
286
- if is_best:
287
- was_losing = player_ep_before < 0.45
288
- is_equal = 0.44 <= player_ep_after <= 0.62
289
- is_winning = player_ep_after > 0.55
290
- major_swing = was_losing and (is_equal or is_winning)
291
-
292
- only_good = (
293
- player_ep_second_best is not None
294
- and player_ep_before - player_ep_second_best > 0.15
295
- )
296
-
297
- if major_swing or only_good:
298
- return "Great"
299
-
300
- # ── Miss ───────────────────────────────────────────────────────────────────
301
- if (
302
- opponent_blunder_swing is not None
303
- and opponent_blunder_swing > 0.10
304
- and ep_before_opponent_blunder is not None
305
- and player_ep_after <= ep_before_opponent_blunder + 0.02
306
- ):
307
- return "Miss"
308
-
309
- # ── EP table ───────────────────────────────────────────────────────────────
310
- ep_loss = max(0.0, ep_loss) # cap negatives (position improved beyond eval)
311
-
312
- # is_best is checked first — float rounding can produce a tiny non-zero
313
- # ep_loss even for the engine's top move, so we must not let the threshold
314
- # bands override a confirmed best-move result.
315
- if is_best:
316
- return "Best"
317
- if ep_loss <= 0.02:
318
- return "Excellent"
319
- if ep_loss <= 0.05:
320
- return "Good"
321
- if ep_loss <= 0.10:
322
- return "Inaccuracy"
323
- if ep_loss <= 0.20:
324
- return "Mistake"
325
- return "Blunder"
326
-
327
- # ── Continuation formatting ────────────────────────────────────────────────────
328
-
329
- def format_continuation(moves_san: list[str], move_number: int, player_color: str) -> str:
330
- """Format a list of SAN continuation moves with proper move numbers.
331
-
332
- After white plays move N → continuation starts with black at N, then white at N+1
333
- After black plays move N → continuation starts with white at N+1
334
- """
335
- if not moves_san:
336
- return ""
337
-
338
- parts: list[str] = []
339
-
340
- if player_color == "white":
341
- # Next is black's response at the same move number
342
- next_is_white = False
343
- num = move_number
344
- else:
345
- # Next is white's move, which is move_number + 1
346
- next_is_white = True
347
- num = move_number + 1
348
-
349
- for i, san in enumerate(moves_san):
350
- if next_is_white:
351
- parts.append(f"{num}.")
352
- parts.append(san)
353
- next_is_white = False
354
- else:
355
- if i == 0:
356
- # First black continuation move: needs the "N..." prefix
357
- parts.append(f"{num}...")
358
- parts.append(san)
359
- next_is_white = True
360
- num += 1 # After black plays, white's next turn is N+1
361
-
362
- return " ".join(parts)
363
-
364
- # ── Main analysis entry point ──────────────────────────────────────────────────
365
-
366
- def analyze_game(pgn_text: str, depth: int, progress_cb):
367
- """
368
- Analyze a full PGN game. Calls progress_cb({type, message, progress, [data]}).
369
- """
370
- pgn_io = io.StringIO(pgn_text)
371
- game = chess.pgn.read_game(pgn_io)
372
-
373
- if game is None:
374
- progress_cb({"type": "error", "message": "Could not parse PGN. Please check the notation."})
375
- return
376
-
377
- white = game.headers.get("White", "White")
378
- black = game.headers.get("Black", "Black")
379
-
380
- moves_list = list(game.mainline_moves())
381
- total = len(moves_list)
382
-
383
- if total == 0:
384
- progress_cb({"type": "error", "message": "The PGN contains no moves."})
385
- return
386
-
387
- progress_cb({"type": "progress", "message": "Initializing Stockfish engine…", "progress": 0.0})
388
-
389
- sf_path = _find_stockfish()
390
- try:
391
- engine = chess.engine.SimpleEngine.popen_uci(sf_path)
392
- except FileNotFoundError:
393
- progress_cb({"type": "error",
394
- "message": f"Stockfish not found (tried '{sf_path}'). Install Stockfish and ensure it is on your PATH."})
395
- return
396
-
397
- try:
398
- # Build board snapshots: boards[i] is the state BEFORE move i
399
- boards: list[chess.Board] = []
400
- b = game.board()
401
- for mv in moves_list:
402
- boards.append(b.copy())
403
- b.push(mv)
404
- boards.append(b.copy()) # final position after all moves
405
-
406
- # Analyse every position with MultiPV=5
407
- multipv: list[list[dict]] = []
408
- ep_white: list[float] = []
409
-
410
- for i, board_snap in enumerate(boards):
411
- if i < total:
412
- msg = f"Analyzing move {i + 1} of {total}…"
413
- prog = i / total * 0.90
414
- else:
415
- msg = "Finalizing analysis…"
416
- prog = 0.93
417
-
418
- progress_cb({"type": "progress", "message": msg, "progress": prog})
419
-
420
- infos = engine.analyse(board_snap, chess.engine.Limit(depth=depth), multipv=5)
421
- multipv.append(infos)
422
- ep_white.append(get_ep_white(infos[0]))
423
-
424
- # Classify each move
425
- progress_cb({"type": "progress", "message": "Classifying moves…", "progress": 0.96})
426
-
427
- results = []
428
-
429
- for i, move in enumerate(moves_list):
430
- board_snap = boards[i]
431
- turn = board_snap.turn
432
- color = "white" if turn == chess.WHITE else "black"
433
-
434
- move_san = board_snap.san(move)
435
- move_uci = move.uci()
436
- fen_before = board_snap.fen()
437
- fen_after = boards[i + 1].fen()
438
-
439
- ep_w_before = ep_white[i]
440
- ep_w_after = ep_white[i + 1]
441
-
442
- if turn == chess.WHITE:
443
- player_ep_before = ep_w_before
444
- player_ep_after = ep_w_after
445
- else:
446
- player_ep_before = 1.0 - ep_w_before
447
- player_ep_after = 1.0 - ep_w_after
448
-
449
- # Best move
450
- best_move_obj = multipv[i][0]["pv"][0]
451
- best_move_san = board_snap.san(best_move_obj)
452
- best_move_uci = best_move_obj.uci()
453
- is_best = (move.uci() == best_move_uci)
454
-
455
- # Second-best EP (for "only good move" detection)
456
- player_ep_second_best: float | None = None
457
- if len(multipv[i]) > 1:
458
- ep_sb_w = get_ep_white(multipv[i][1])
459
- player_ep_second_best = ep_sb_w if turn == chess.WHITE else 1.0 - ep_sb_w
460
-
461
- # Rank among top-5
462
- move_rank: int | None = None
463
- for rank, info in enumerate(multipv[i], 1):
464
- if info["pv"][0].uci() == move.uci():
465
- move_rank = rank
466
- break
467
-
468
- # Sacrifice?
469
- is_sacrifice = check_sacrifice(board_snap, move)
470
-
471
- # Miss detection
472
- opponent_blunder_swing: float | None = None
473
- ep_before_opponent_blunder: float | None = None
474
-
475
- if i >= 1:
476
- ep_w_prev = ep_white[i - 1]
477
- if turn == chess.WHITE:
478
- swing = ep_w_before - ep_w_prev
479
- pre_blunder = ep_w_prev
480
- else:
481
- swing = (1.0 - ep_w_before) - (1.0 - ep_w_prev)
482
- pre_blunder = 1.0 - ep_w_prev
483
-
484
- if swing > 0.10:
485
- opponent_blunder_swing = swing
486
- ep_before_opponent_blunder = pre_blunder
487
-
488
- # Book move check — if the resulting position is in the ECO db,
489
- # classify immediately regardless of EP; opening theory trumps evaluation.
490
- book_entry = lookup_book(fen_after)
491
- if book_entry:
492
- classification = "Book"
493
- opening_name = book_entry.get("name", "")
494
- opening_eco = book_entry.get("eco", "")
495
- else:
496
- opening_name = ""
497
- opening_eco = ""
498
- classification = classify_move(
499
- player_ep_before=player_ep_before,
500
- player_ep_after=player_ep_after,
501
- player_ep_second_best=player_ep_second_best,
502
- is_best=is_best,
503
- move_rank=move_rank,
504
- is_sacrifice=is_sacrifice,
505
- opponent_blunder_swing=opponent_blunder_swing,
506
- ep_before_opponent_blunder=ep_before_opponent_blunder,
507
- )
508
-
509
- # Continuation: engine's best line from the position after this move
510
- continuation_san: list[str] = []
511
- if multipv[i + 1] and "pv" in multipv[i + 1][0]:
512
- temp = boards[i + 1].copy()
513
- for cont_mv in multipv[i + 1][0]["pv"][:6]:
514
- try:
515
- continuation_san.append(temp.san(cont_mv))
516
- temp.push(cont_mv)
517
- except Exception:
518
- break
519
-
520
- ep_loss = max(0.0, player_ep_before - player_ep_after)
521
-
522
- results.append({
523
- "move_number": (i // 2) + 1,
524
- "ply": i,
525
- "color": color,
526
- "san": move_san,
527
- "uci": move_uci,
528
- "from_square": chess.square_name(move.from_square),
529
- "to_square": chess.square_name(move.to_square),
530
- "classification": classification,
531
- "ep_loss": round(ep_loss, 4),
532
- "ep_before": round(player_ep_before, 4),
533
- "ep_after": round(player_ep_after, 4),
534
- "best_move_san": best_move_san if not is_best else None,
535
- "best_move_uci": best_move_uci if not is_best else None,
536
- "continuation": continuation_san,
537
- "continuation_fmt": format_continuation(continuation_san,
538
- (i // 2) + 1, color),
539
- "fen_before": fen_before,
540
- "fen_after": fen_after,
541
- "is_best": is_best,
542
- "comment": get_comment(classification),
543
- "opening_name": opening_name,
544
- "opening_eco": opening_eco,
545
- })
546
-
547
- progress_cb({
548
- "type": "complete",
549
- "message": "Analysis complete!",
550
- "progress": 1.0,
551
- "data": {
552
- "white": white,
553
- "black": black,
554
- "initial_fen": game.board().fen(),
555
- "moves": results,
556
- "summary": _compute_summary(results),
557
- }
558
- })
559
-
560
- finally:
561
- engine.quit()
562
-
563
-
564
- # ── Summary stats ──────────────────────────────────────────────────────────────
565
-
566
- ALL_CLASSIFICATIONS = [
567
- "Book", "Brilliant", "Great", "Best", "Excellent", "Good",
568
- "Inaccuracy", "Mistake", "Blunder", "Miss",
569
- ]
570
-
571
- def _compute_summary(moves: list[dict]) -> dict:
572
- """Return per-player classification counts and accuracy."""
573
- stats = {}
574
- for color in ("white", "black"):
575
- player_moves = [m for m in moves if m["color"] == color]
576
-
577
- counts = {cls: 0 for cls in ALL_CLASSIFICATIONS}
578
- for m in player_moves:
579
- cls = m["classification"]
580
- if cls in counts:
581
- counts[cls] += 1
582
-
583
- # Accuracy: average fraction of winning chances preserved each move.
584
- # For each move: score = ep_after / max(ep_before, 0.01), clamped 0-1.
585
- # Gives 100% for Best/Brilliant, degrades proportionally with EP loss.
586
- if player_moves:
587
- scores = [
588
- max(0.0, min(1.0, m["ep_after"] / max(m["ep_before"], 0.01)))
589
- for m in player_moves
590
- ]
591
- accuracy = round(sum(scores) / len(scores) * 100, 1)
592
- else:
593
- accuracy = 0.0
594
-
595
- stats[color] = {"accuracy": accuracy, "counts": counts}
596
-
597
- return stats