-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchess_analyzer.py
More file actions
1088 lines (897 loc) · 37.7 KB
/
Copy pathchess_analyzer.py
File metadata and controls
1088 lines (897 loc) · 37.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Chess Game Analyzer
Operationalizes the process from article.txt:
1. Parses PGN (with variations/comments) using python-chess
2. Runs Stockfish on each position with configurable settings
3. Converts numeric evaluations to descriptive language
4. Sends structured prompt to Gemini API for chapter-based analysis
5. Outputs analysis similar to ChessAnalysis.txt
Author: Based on methodology from article.txt
"""
import os
import re
import sys
import subprocess
import time
from dataclasses import dataclass, field
from typing import Optional, List, Tuple
from pathlib import Path
from datetime import datetime
from io import StringIO
try:
import chess
import chess.pgn
import chess.engine
CHESS_LIBRARY_AVAILABLE = True
except ImportError:
CHESS_LIBRARY_AVAILABLE = False
print("Warning: python-chess library not installed. Install with: pip install python-chess")
# =============================================================================
# CONFIGURATION - Edit these values or pass as command-line arguments
# =============================================================================
# Stockfish path
STOCKFISH_PATH = os.path.expanduser("~/.local/bin/stockfish")
# Stockfish engine settings
STOCKFISH_DEPTH = 18 # Search depth
STOCKFISH_TIME_PER_MOVE = 500 # Time per move in milliseconds
STOCKFISH_THREADS = 1 # Number of CPU threads
STOCKFISH_HASH = 256 # Hash table size in MB
# Gemini API configuration
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
GEMINI_MODEL = "gemini-2.5-flash-lite"
# Analysis behavior
ANALYZE_FROM_PERSPECTIVE = "White" # Analyze from White's or Black's perspective
INCLUDE_PGN_COMMENTS_IN_PROMPT = True # Include existing PGN comments as context
CHAPTER_MIN_MOVES = 8 # Minimum moves per chapter
CHAPTER_MAX_MOVES = 20 # Maximum moves per chapter (soft target)
# =============================================================================
# DATA CLASSES
# =============================================================================
@dataclass
class PositionAnalysis:
"""Stores analysis for a single position."""
move_number: int
side_to_move: str # 'White' or 'Black'
move_san: str
move_uci: str = ""
fen_before: str = ""
fen_after: str = ""
eval_score: float = 0.0 # In pawns (positive = white advantage)
eval_label: str = ""
eval_trend: str = ""
existing_comment: str = "" # Any comment from the original PGN
is_book_move: bool = False # True if this is still in opening book phase
@dataclass
class GameChapter:
"""Represents a logical chapter/phase of the game."""
name: str
start_move: int
end_move: int
positions: List[PositionAnalysis] = field(default_factory=list)
avg_eval: float = 0.0
eval_trend: str = ""
material_balance: str = "equal"
phase_type: str = "middlegame" # opening, middlegame, endgame
@dataclass
class GameMetadata:
"""Stores PGN header information."""
event: str = "?"
site: str = "?"
date: str = "?"
round_: str = "?"
white: str = "?"
black: str = "?"
result: str = "?"
white_elo: str = "?"
black_elo: str = "?"
eco: str = "?"
opening: str = "?"
time_control: str = "?"
annotator: str = "?"
def get_formatted_date(self) -> str:
"""Convert PGN date format to readable format."""
if not self.date or self.date == "?":
return "?"
# Handle YYYY.MM.DD format
if "." in self.date:
parts = self.date.split(".")
try:
year = parts[0]
month = int(parts[1]) if len(parts) > 1 else 1
day = int(parts[2]) if len(parts) > 2 else 1
months = ["", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
return f"{months[month]} {day}, {year}"
except (ValueError, IndexError):
return self.date
# Handle YYYY-MM-DD format
if "-" in self.date:
try:
dt = datetime.strptime(self.date, "%Y-%m-%d")
return dt.strftime("%B %d, %Y").replace(" 0", " ")
except ValueError:
return self.date
return self.date
# =============================================================================
# EVALUATION CONVERTER
# =============================================================================
def convert_eval_to_label(score: float) -> str:
"""
Convert numeric evaluation to descriptive label.
Based on the approach described in article.txt.
"""
abs_score = abs(score)
if abs_score < 0.15:
return "roughly equal"
elif abs_score < 0.35:
return "slightly better for White" if score > 0 else "slightly better for Black"
elif abs_score < 0.75:
return "White has a clear advantage" if score > 0 else "Black has a clear advantage"
elif abs_score < 1.5:
return "White has a significant advantage" if score > 0 else "Black has a significant advantage"
elif abs_score < 3.0:
return "White has a winning advantage" if score > 0 else "Black has a winning advantage"
elif abs_score < 5.0:
return "White has a decisive advantage" if score > 0 else "Black has a decisive advantage"
else:
return "White has a forced mate" if score > 0 else "Black has a forced mate"
def determine_trend(current: float, previous: float, num_positions: int = 1) -> str:
"""
Determine the trend of evaluation change over recent positions.
"""
diff = current - previous
if abs(diff) < 0.2:
return "position relatively unchanged"
elif diff > 0.5:
return "position has significantly improved for White"
elif diff < -0.5:
return "position has significantly worsened for White"
elif diff > 0.2:
return "position has slightly improved for White"
else:
return "position has slightly worsened for White"
# =============================================================================
# CHAPTER DETECTION
# =============================================================================
def detect_chapters(positions: List[PositionAnalysis]) -> List[GameChapter]:
"""
Detect logical chapters/phases in the game based on:
- Move number (opening ~1-12, middlegame ~13-35, endgame ~36+)
- Significant evaluation shifts (>0.5 pawn)
- Material changes (inferred from eval jumps)
- Piece exchanges (queen trades often signal endgame)
Aims to create 4-7 logical chapters like the original analysis.
"""
if not positions:
return []
chapters = []
# First pass: identify natural break points
break_points = [0] # Always start at beginning
for i in range(1, len(positions)):
pos = positions[i]
prev_pos = positions[i - 1] if i > 0 else None
# Check for significant evaluation change
if prev_pos and abs(pos.eval_score - prev_pos.eval_score) > 0.6:
if i - break_points[-1] >= CHAPTER_MIN_MOVES:
break_points.append(i)
# Check for natural phase transitions based on move number
move_num = pos.move_number
# Opening end (around move 10-15)
if move_num == 12 and i - break_points[-1] >= 6:
break_points.append(i)
# Early middlegame transition (around move 20)
if move_num == 20 and i - break_points[-1] >= 8:
break_points.append(i)
# Middlegame to endgame (around move 35-40)
if move_num == 35 and i - break_points[-1] >= 10:
break_points.append(i)
# Late endgame (around move 45-50)
if move_num == 45 and i - break_points[-1] >= 8:
break_points.append(i)
# Ensure we cover all positions
if break_points[-1] < len(positions):
# Check if last chapter is too short - merge with previous
if len(positions) - break_points[-1] < CHAPTER_MIN_MOVES and len(break_points) > 1:
break_points.pop()
# Second pass: create chapters
for i, start_idx in enumerate(break_points):
end_idx = break_points[i + 1] if i + 1 < len(break_points) else len(positions)
chapter_positions = positions[start_idx:end_idx]
if not chapter_positions:
continue
# Calculate chapter statistics
avg_eval = sum(p.eval_score for p in chapter_positions) / len(chapter_positions)
# Determine trend
if len(chapter_positions) >= 2:
trend_diff = chapter_positions[-1].eval_score - chapter_positions[0].eval_score
if abs(trend_diff) < 0.3:
trend = "stable"
elif trend_diff > 0.3:
trend = "improving for White"
else:
trend = "improving for Black"
else:
trend = "stable"
# Determine phase type
first_move = chapter_positions[0].move_number
if first_move <= 12:
phase_type = "opening"
elif first_move <= 35:
phase_type = "middlegame"
else:
phase_type = "endgame"
# Generate descriptive chapter name
name = generate_chapter_name(chapter_positions, avg_eval, phase_type, i)
chapters.append(GameChapter(
name=name,
start_move=chapter_positions[0].move_number,
end_move=chapter_positions[-1].move_number,
positions=chapter_positions,
avg_eval=avg_eval,
eval_trend=trend,
phase_type=phase_type
))
return chapters
def generate_chapter_name(positions: List[PositionAnalysis], avg_eval: float,
phase_type: str, chapter_index: int) -> str:
"""Generate a descriptive chapter name based on position characteristics."""
if not positions:
return f"Phase {chapter_index + 1}"
first_move = positions[0].move_number
# Look for key characteristics
has_tactics = False
has_queen_trade = False
eval_shift = 0
for i in range(1, len(positions)):
eval_change = abs(positions[i].eval_score - positions[i-1].eval_score)
if eval_change > 0.8:
has_tactics = True
eval_shift = positions[i].eval_score - positions[i-1].eval_score
# Check for queen trades (simplified heuristic)
if "Qx" in positions[i].move_san or "Q" not in positions[i].move_san:
has_queen_trade = True
# Generate name based on phase and characteristics
if phase_type == "opening":
# Try to identify opening from first few moves
opening_moves = " ".join([p.move_san for p in positions[:6]])
if "d4 f5" in opening_moves:
return "Dutch Defense Opening Phase"
elif "e4 e5" in opening_moves:
return "Open Game Opening"
elif "d4 d5" in opening_moves:
return "Queen's Gambit Opening Phase"
elif "e4 c5" in opening_moves:
return "Sicilian Defense Opening"
else:
return f"Opening Development Phase"
elif phase_type == "middlegame":
if has_tactics and eval_shift > 0.5:
return "Tactical Breakthrough"
elif has_tactics:
return "Middlegame Tactical Battle"
elif abs(avg_eval) < 0.3:
return "Balanced Minor Piece Middlegame"
elif avg_eval > 0.5:
return "White's Strategic Advantage"
else:
return "Complex Middlegame Maneuvering"
else: # endgame
if has_queen_trade:
return "Queen Endgame"
elif "R" in " ".join([p.move_san for p in positions]):
return "Rook Endgame Battle"
elif abs(avg_eval) > 2:
return "Winning Endgame Conversion"
else:
return "Endgame Technique"
# =============================================================================
# STOCKFISH ANALYZER
# =============================================================================
class StockfishAnalyzer:
"""Interfaces with Stockfish chess engine using UCI protocol."""
def __init__(self,
path: str = STOCKFISH_PATH,
depth: int = STOCKFISH_DEPTH,
time_ms: int = STOCKFISH_TIME_PER_MOVE,
threads: int = STOCKFISH_THREADS,
hash_mb: int = STOCKFISH_HASH):
self.path = path
self.depth = depth
self.time_ms = time_ms
self.threads = threads
self.hash_mb = hash_mb
self.process = None
self._start_engine()
def _start_engine(self):
"""Start Stockfish as a subprocess and configure it."""
if not os.path.exists(self.path):
raise FileNotFoundError(f"Stockfish not found at {self.path}")
self.process = subprocess.Popen(
[self.path],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1
)
# Initialize UCI
self._send_command("uci")
self._read_until("uciok")
# Configure engine
self._send_command(f"setoption name Threads value {self.threads}")
self._send_command(f"setoption name Hash value {self.hash_mb}")
self._send_command("isready")
self._read_until("readyok")
def _send_command(self, cmd: str):
"""Send command to Stockfish."""
if self.process and self.process.stdin:
self.process.stdin.write(cmd + "\n")
self.process.stdin.flush()
def _read_until(self, marker: str, timeout: float = 30.0) -> str:
"""Read output until marker is found."""
output = ""
start = time.time()
while time.time() - start < timeout:
if self.process and self.process.stdout:
line = self.process.stdout.readline()
output += line
if marker in line:
break
if not line: # EOF
break
return output
def analyze_position(self, fen: str) -> float:
"""
Analyze a position and return the evaluation score.
Positive = White advantage, Negative = Black advantage.
"""
self._send_command(f"position fen {fen}")
self._send_command(f"go depth {self.depth} movetime {self.time_ms}")
output = self._read_until("bestmove", timeout=60.0)
# Extract score from output
score = 0.0
for line in output.split('\n'):
if 'score cp' in line:
match = re.search(r'score cp (-?\d+)', line)
if match:
score = int(match.group(1)) / 100.0
elif 'score mate' in line:
match = re.search(r'score mate (-?\d+)', line)
if match:
mate_in = int(match.group(1))
score = 100.0 if mate_in > 0 else -100.0
return score
def close(self):
"""Close Stockfish process."""
if self.process:
self._send_command("quit")
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
# =============================================================================
# PGN PARSER (using python-chess)
# =============================================================================
def parse_pgn_with_chess_library(pgn_content: str) -> Tuple[GameMetadata, List[PositionAnalysis], str]:
"""
Parse PGN using python-chess library.
Handles variations, comments, and annotations properly.
Returns metadata, main line positions, and original PGN comments.
"""
metadata = GameMetadata()
positions = []
pgn_comments = []
# Parse the PGN
pgn_io = StringIO(pgn_content)
game = chess.pgn.read_game(pgn_io)
if not game:
raise ValueError("Failed to parse PGN content")
# Extract metadata
metadata.event = game.headers.get("Event", "?")
metadata.site = game.headers.get("Site", "?")
metadata.date = game.headers.get("Date", "?")
metadata.round_ = game.headers.get("Round", "?")
metadata.white = game.headers.get("White", "?")
metadata.black = game.headers.get("Black", "?")
metadata.result = game.headers.get("Result", "?")
metadata.white_elo = game.headers.get("WhiteElo", "?")
metadata.black_elo = game.headers.get("BlackElo", "?")
metadata.eco = game.headers.get("ECO", "?")
metadata.opening = game.headers.get("Opening", "?")
metadata.time_control = game.headers.get("TimeControl", "?")
metadata.annotator = game.headers.get("Annotator", "?")
# Walk the main line only, collecting positions and comments
board = game.board()
node = game.root()
move_number = 1
side = "White"
prev_eval = 0.0
while node.variations:
# Get the first variation (main line)
child = node.variations[0]
move = child.move
# Get comment before the move
comment_before = node.comment if node.comment else ""
# Get FEN before move
fen_before = board.fen()
# Get SAN and UCI
move_san = board.san(move)
move_uci = move.uci()
# Apply move to get FEN after
board.push(move)
fen_after = board.fen()
# Get comment after the move (on the child node)
comment_after = child.comment if child.comment else ""
full_comment = f"{comment_before} {comment_after}".strip()
# Store comment for prompt
if full_comment:
pgn_comments.append(f"Move {move_number}. {move_san}: {full_comment}")
positions.append(PositionAnalysis(
move_number=move_number,
side_to_move=side,
move_san=move_san,
move_uci=move_uci,
fen_before=fen_before,
fen_after=fen_after,
existing_comment=full_comment
))
# Update for next iteration
node = child
if side == "White":
side = "Black"
else:
side = "White"
move_number += 1
return metadata, positions, "\n".join(pgn_comments)
def parse_pgn_fallback(pgn_content: str) -> Tuple[GameMetadata, List[PositionAnalysis], str]:
"""
Fallback PGN parser if python-chess is not available.
Basic parser that handles standard PGN format.
"""
metadata = GameMetadata()
positions = []
pgn_comments = []
lines = pgn_content.strip().split('\n')
move_text = ""
for line in lines:
line = line.strip()
if not line:
continue
# Header tags
if line.startswith('[') and line.endswith(']'):
match = re.match(r'\[(\w+)\s+"([^"]*)"\]', line)
if match:
tag, value = match.groups()
tag_lower = tag.lower()
if tag_lower == 'event':
metadata.event = value
elif tag_lower == 'site':
metadata.site = value
elif tag_lower == 'date':
metadata.date = value
elif tag_lower == 'round':
metadata.round_ = value
elif tag_lower == 'white':
metadata.white = value
elif tag_lower == 'black':
metadata.black = value
elif tag_lower == 'result':
metadata.result = value
elif tag_lower == 'whiteelo':
metadata.white_elo = value
elif tag_lower == 'blackelo':
metadata.black_elo = value
elif tag_lower == 'eco':
metadata.eco = value
elif tag_lower == 'opening':
metadata.opening = value
else:
move_text += " " + line
# Parse moves (simplified - doesn't handle comments well)
if move_text:
# Extract comments
comment_matches = re.findall(r'\{([^}]*)\}', move_text)
for i, comment in enumerate(comment_matches):
pgn_comments.append(f"Comment {i+1}: {comment.strip()}")
# Remove comments and variations
move_text = re.sub(r'\{[^}]*\}', '', move_text)
move_text = re.sub(r'\([^)]*\)', '', move_text)
move_text = re.sub(r'\s*(1-0|0-1|1/2-1/2|\*)\s*$', '', move_text)
move_tokens = move_text.split()
move_number = 1
side = "White"
for token in move_tokens:
if re.match(r'^\d+\.+$', token) or re.match(r'^\d+$', token):
continue
positions.append(PositionAnalysis(
move_number=move_number,
side_to_move=side,
move_san=token
))
if side == "White":
side = "Black"
else:
side = "White"
move_number += 1
return metadata, positions, "\n".join(pgn_comments)
# =============================================================================
# GEMINI API INTEGRATION
# =============================================================================
def build_analysis_prompt(
metadata: GameMetadata,
chapters: List[GameChapter],
all_positions: List[PositionAnalysis],
pgn_comments: str,
perspective: str = "White"
) -> str:
"""
Build the prompt for Gemini API based on the structure from ChessAnalysis.txt.
Key improvements:
- Include ALL moves (not truncated)
- Structured Deeper Analysis format
- Preserve PGN comments as context
- Clear chapter-by-chapter instructions
"""
formatted_date = metadata.get_formatted_date()
# Build complete move list with evaluations
moves_with_evals = []
current_chapter = 0
for i, pos in enumerate(all_positions):
# Check if we've moved to a new chapter
while (current_chapter < len(chapters) - 1 and
i >= 0 and
chapters[current_chapter].end_move < pos.move_number):
current_chapter += 1
move_str = f"{pos.move_number}. {pos.move_san}" if pos.side_to_move == "White" else f"{pos.move_number}... {pos.move_san}"
eval_str = f"[{pos.eval_label}]"
if pos.eval_trend:
eval_str += f" - {pos.eval_trend}"
# Include existing PGN comment if present
comment_str = ""
if pos.existing_comment:
comment_str = f" /* {pos.existing_comment} */"
moves_with_evals.append(f"{move_str} {eval_str}{comment_str}")
# Format moves by chapter for the prompt
chapter_moves_text = ""
for chap_idx, chapter in enumerate(chapters):
chapter_moves = []
for pos in all_positions:
if chapter.start_move <= pos.move_number <= chapter.end_move:
move_str = f"{pos.move_number}. {pos.move_san}" if pos.side_to_move == "White" else f"... {pos.move_san}"
chapter_moves.append(move_str)
chapter_moves_text += f"\n{chapter.name} (moves {chapter.start_move}-{chapter.end_move}):\n"
chapter_moves_text += " ".join(chapter_moves[:10])
if len(chapter_moves) > 10:
chapter_moves_text += f" ... ({len(chapter_moves)} total moves)"
chapter_moves_text += "\n"
# Build the complete prompt
prompt = f"""You are an expert chess coach and analyst. Analyze the following complete chess game from {perspective}'s perspective.
================================================================================
YOUR TASK
================================================================================
1. Break the game into logical chapters/phases based on the flow of play, evaluation trends, and natural transition points (opening → middlegame → endgame, tactical sequences, material changes, etc.)
2. For EACH chapter, provide analysis in THREE sections:
- "The Big Picture": Strategic narrative (2-3 paragraphs) explaining what was happening, the plans of both sides, and how the position evolved
- "Key Learning Points": 2-3 numbered practical takeaways with clear explanations that an intermediate player can apply
- "Deeper Analysis": Technical analysis with these subsections:
* Critical Decision Points: Key moments where the game could have gone differently
* Pawn Structure Considerations: How the pawn structure evolved and its implications
* Piece Coordination: How well the pieces worked together
3. Use descriptive chess language, NOT numeric evaluations. Focus on plans, themes, and strategic ideas.
4. Explain WHY moves were made, not just WHAT was played.
5. Analyze the COMPLETE game - do not stop early. Cover all phases including the endgame.
================================================================================
GAME INFORMATION
================================================================================
White: {metadata.white}
Black: {metadata.black}
Result: {metadata.result}
Date: {formatted_date}
Opening: {metadata.opening if metadata.opening != "?" else "Not specified"}
================================================================================
COMPLETE GAME MOVES WITH DESCRIPTIVE EVALUATIONS
================================================================================
{chr(10).join(moves_with_evals)}
================================================================================
CHAPTER BREAKDOWN (Suggested)
================================================================================
{chr(10).join([f"Chapter {i+1}: {c.name} (moves {c.start_move}-{c.end_move}) - Avg eval: {c.avg_eval:+.2f}, Trend: {c.eval_trend}" for i, c in enumerate(chapters)])}
================================================================================
EXISTING PGN COMMENTS (for context)
================================================================================
{pgn_comments if pgn_comments else "No existing comments in PGN"}
================================================================================
OUTPUT FORMAT - FOLLOW EXACTLY
================================================================================
Chess Game Analysis ({perspective})
• Date: {formatted_date}
• Players: {metadata.white} ({perspective}) vs. {metadata.black}
• Result: {metadata.result}
[CHAPTER NAME]
[moves in standard PGN format with move numbers, e.g., "1. d4 f5 2. Nc3 Nf6..."]
The Big Picture
[2-3 paragraphs of strategic narrative]
Key Learning Points
1. [First learning point with title and explanation]
2. [Second learning point with title and explanation]
Deeper Analysis
Critical Decision Points:
• [First critical decision with explanation]
• [Second critical decision if applicable]
Pawn Structure Considerations: [How pawn structure affected the position]
Piece Coordination: [How pieces worked together]
[Repeat for ALL chapters - cover the complete game]
================================================================================
Begin your complete analysis now. Remember to analyze ALL moves through the end of the game.
"""
return prompt
def call_gemini_api(prompt: str, api_key: str, model: str = GEMINI_MODEL) -> str:
"""
Call Gemini API and return the response.
"""
import urllib.request
import json
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
headers = {
"Content-Type": "application/json"
}
payload = {
"contents": [{
"parts": [{
"text": prompt
}]
}],
"generationConfig": {
"temperature": 0.7,
"topK": 40,
"topP": 0.95,
"maxOutputTokens": 16384, # Increased for longer games
}
}
data = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(url, data=data, headers=headers, method='POST')
try:
with urllib.request.urlopen(req, timeout=300) as response: # 5 minute timeout
result = json.loads(response.read().decode('utf-8'))
if 'candidates' in result and len(result['candidates']) > 0:
return result['candidates'][0]['content']['parts'][0]['text']
else:
return "Error: No response from API"
except Exception as e:
return f"Error calling API: {str(e)}"
# =============================================================================
# MAIN ANALYSIS PIPELINE
# =============================================================================
def analyze_game(pgn_content: str,
api_key: str,
model: str = GEMINI_MODEL,
perspective: str = "White",
depth: int = STOCKFISH_DEPTH,
time_ms: int = STOCKFISH_TIME_PER_MOVE,
threads: int = STOCKFISH_THREADS,
hash_mb: int = STOCKFISH_HASH,
prompt_only: bool = False,
prompt_output: str = "prompt.txt") -> str:
"""
Complete analysis pipeline.
Args:
prompt_only: If True, only generate and save the prompt without calling API
prompt_output: File path for prompt output when prompt_only is True
"""
print("Parsing PGN...")
# Parse PGN (prefer python-chess if available)
if CHESS_LIBRARY_AVAILABLE:
metadata, positions, pgn_comments = parse_pgn_with_chess_library(pgn_content)
else:
metadata, positions, pgn_comments = parse_pgn_fallback(pgn_content)
if not positions:
return "Error: No moves found in PGN"
print(f"Found {len(positions)} moves: {metadata.white} vs. {metadata.black}")
if pgn_comments:
print(f" Found {len(pgn_comments.split(chr(10)))} existing PGN comments")
# Initialize Stockfish with configuration
print(f"Initializing Stockfish (depth={depth}, time={time_ms}ms, threads={threads}, Hash={hash_mb}MB)...")
try:
sf = StockfishAnalyzer(
depth=depth,
time_ms=time_ms,
threads=threads,
hash_mb=hash_mb
)
except FileNotFoundError as e:
return str(e)
# Analyze each position
print("Analyzing positions with Stockfish...")
prev_eval = 0.0
for i, pos in enumerate(positions):
# Analyze current position
eval_score = sf.analyze_position(pos.fen_before if pos.fen_before else
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
pos.eval_score = eval_score
pos.eval_label = convert_eval_to_label(eval_score)
pos.eval_trend = determine_trend(eval_score, prev_eval, i)
pos.fen_after = pos.fen_before # Update if not set
prev_eval = eval_score
# Progress indicator
if (i + 1) % 10 == 0 or (i + 1) == len(positions):
print(f" Analyzed {i + 1}/{len(positions)} positions...")
sf.close()
# Detect chapters
print("Detecting game chapters...")
chapters = detect_chapters(positions)
print(f" Found {len(chapters)} chapters:")
for i, chap in enumerate(chapters):
print(f" {i+1}. {chap.name} (moves {chap.start_move}-{chap.end_move})")
# Build prompt and call API
print("Building analysis prompt...")
prompt = build_analysis_prompt(metadata, chapters, positions, pgn_comments, perspective)
# If prompt-only mode, save and return
if prompt_only:
with open(prompt_output, 'w') as f:
f.write(prompt)
print(f"Prompt saved to: {prompt_output}")
print("Skipping API call (prompt-only mode)")
return prompt
print(f"Calling Gemini API ({model})...")
print(" (This may take a minute for long games...)")
analysis = call_gemini_api(prompt, api_key, model)
return analysis
# =============================================================================
# CLI INTERFACE
# =============================================================================
def main():
import argparse
parser = argparse.ArgumentParser(
description="Chess Game Analyzer - AI-powered game analysis with Stockfish + Gemini"
)
parser.add_argument(
"pgn_file",
nargs="?",
help="Path to PGN file to analyze"
)
parser.add_argument(
"--pgn-text",
help="PGN content as text (alternative to file)"
)
parser.add_argument(
"--api-key",
default=GEMINI_API_KEY,
help="Gemini API key (or set GEMINI_API_KEY environment variable)"
)
parser.add_argument(
"--model",
default=GEMINI_MODEL,
help=f"Gemini model to use (default: {GEMINI_MODEL})"
)
parser.add_argument(
"--output",
"-o",
help="Output file path (default: stdout)"
)
parser.add_argument(
"--perspective",
choices=["White", "Black"],
default="White",
help="Analyze from player's perspective (default: White)"
)
parser.add_argument(
"--prompt-only",
action="store_true",
help="Generate prompt only, don't call API (saves to prompt.txt)"
)
parser.add_argument(
"--prompt-output",
default="prompt.txt",
help="Output file for prompt (default: prompt.txt)"
)
# Stockfish settings
sf_group = parser.add_argument_group("Stockfish Settings")
sf_group.add_argument(
"--depth",
type=int,
default=STOCKFISH_DEPTH,
help=f"Stockfish search depth (default: {STOCKFISH_DEPTH})"
)
sf_group.add_argument(
"--time",
type=int,
default=STOCKFISH_TIME_PER_MOVE,
help=f"Time per move in ms (default: {STOCKFISH_TIME_PER_MOVE})"
)
sf_group.add_argument(
"--threads",
type=int,
default=STOCKFISH_THREADS,
help=f"CPU threads (default: {STOCKFISH_THREADS})"
)
sf_group.add_argument(
"--hash",
type=int,
dest="hash_mb",
default=STOCKFISH_HASH,
help=f"Hash table size in MB (default: {STOCKFISH_HASH})"
)
args = parser.parse_args()
# Get PGN content
if args.pgn_text:
pgn_content = args.pgn_text
elif args.pgn_file: