-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
186 lines (154 loc) Β· 7.39 KB
/
main.py
File metadata and controls
186 lines (154 loc) Β· 7.39 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
#!/usr/bin/env python3
"""
Main application for Chess LLM Analyzer.
"""
import os
import sys
from fetch import ChessComAPI
from analyze import ChessAnalyzer
from explain import ChessExplainer
from report import ReportGenerator
from utils import load_environment, save_username, load_username
def main():
"""Main application entry point."""
print("βοΈ Chess LLM Analyzer")
print("=" * 50)
# Load environment variables
load_environment()
# Check for OpenAI API key
if not os.getenv('OPENAI_API_KEY'):
print("β Error: OPENAI_API_KEY not found in environment variables.")
print("Please set your OpenAI API key in the .env file.")
return
# Initialize components
api = ChessComAPI()
analyzer = ChessAnalyzer()
explainer = ChessExplainer()
report_gen = ReportGenerator()
# Get or load username
username = load_username()
if not username:
username = input("Enter Chess.com username: ").strip()
if not username:
print("Username required.")
return
save_username(username)
else:
print(f"Using saved username: {username}")
change_username = input("Change username? (y/N): ").strip().lower()
if change_username == 'y':
username = input("Enter new Chess.com username: ").strip()
if username:
save_username(username)
else:
print("Username required.")
return
print(f"\nπ Fetching recent games for: {username}")
# Fetch recent games
games = api.get_user_games(username, count=5)
if not games:
print("β No games found for this username.")
return
print(f"β
Found {len(games)} recent games")
# Initialize Stockfish engine
if not analyzer.initialize_engine():
print("β Failed to initialize Stockfish engine.")
print("Make sure Stockfish is installed and accessible.")
return
try:
all_errors = []
# Analyze each game
for i, game in enumerate(games, 1):
print(f"\nπ Analyzing game {i}/{len(games)}...")
pgn = game.get('pgn')
if not pgn:
print(f" β οΈ No PGN data for game {i}")
continue
# Get game info
white = game.get('white', {}).get('username', 'Unknown')
black = game.get('black', {}).get('username', 'Unknown')
result = game.get('result', 'Unknown')
print(f" {white} vs {black} - {result}")
# Analyze the game
errors = analyzer.analyze_game(pgn, username)
if errors:
print(f" β οΈ Found {len(errors)} errors")
# Add game context to errors
for error in errors:
error['game_info'] = {
'game_number': i,
'white': white,
'black': black,
'result': result
}
all_errors.extend(errors)
else:
print(f" β
No errors detected")
print(f"\nπ Analysis Summary:")
print(f" Total games analyzed: {len(games)}")
print(f" Total errors found: {len(all_errors)}")
if all_errors:
# Count error types
blunders = [e for e in all_errors if e['error_type'] == 'Blunder']
mistakes = [e for e in all_errors if e['error_type'] == 'Mistake']
inaccuracies = [e for e in all_errors if e['error_type'] == 'Inaccuracy']
print(f" Blunders: {len(blunders)}")
print(f" Mistakes: {len(mistakes)}")
print(f" Inaccuracies: {len(inaccuracies)}")
# Sort errors by severity (blunders first, then by evaluation change)
all_errors.sort(key=lambda x: (
{'Blunder': 0, 'Mistake': 1, 'Inaccuracy': 2}[x['error_type']],
x['eval_change']
))
# Limit the number of errors to explain (most critical ones)
max_errors_to_explain = min(15, len(all_errors))
# Ask user for confirmation and allow them to adjust the number
estimated_cost = explainer.estimate_cost(max_errors_to_explain)
print(f"\nπ° Estimated cost for {max_errors_to_explain} explanations: ${estimated_cost:.3f}")
adjust_errors = input(f"Explain top {max_errors_to_explain} errors? (y/N/a=adjust): ").strip().lower()
if adjust_errors == 'a':
try:
max_errors_to_explain = int(input(f"Enter number of errors to explain (1-{len(all_errors)}): "))
max_errors_to_explain = max(1, min(max_errors_to_explain, len(all_errors)))
estimated_cost = explainer.estimate_cost(max_errors_to_explain)
print(f"π° New estimated cost: ${estimated_cost:.3f}")
errors_to_explain = all_errors[:max_errors_to_explain]
print(f"\nπ€ Getting AI explanations for top {max_errors_to_explain} errors...")
explained_errors = explainer.explain_errors_batch(errors_to_explain, max_errors_to_explain)
except ValueError:
print("Invalid input, using default.")
errors_to_explain = all_errors[:max_errors_to_explain]
explained_errors = explainer.explain_errors_batch(errors_to_explain, max_errors_to_explain)
elif adjust_errors != 'y':
print("Skipping explanations to save costs.")
explained_errors = []
else:
errors_to_explain = all_errors[:max_errors_to_explain]
print(f"\nπ€ Getting AI explanations for top {max_errors_to_explain} errors...")
explained_errors = explainer.explain_errors_batch(errors_to_explain, max_errors_to_explain)
# Generate report
print(f"\nπ Generating report...")
report_content = report_gen.generate_report(username, games, explained_errors)
# Save report
filename = report_gen.save_report(report_content, username)
print(f"β
Report saved to: {filename}")
# Display summary in terminal
print(f"\nπ Error Summary (Top {len(explained_errors)}):")
for error in explained_errors:
game_info = error['game_info']
print(f"\n{error['error_type']} in Game {game_info['game_number']} (Move {error['move_number']}):")
print(f" {error['san_move']} - Evaluation change: {error['eval_change']:.2f}")
print(f" {error.get('explanation', 'No explanation available.')[:100]}...")
# Show cost summary
if hasattr(explainer, 'total_cost'):
print(f"\nπ° Total API cost: ${explainer.total_cost:.3f}")
else:
print("π No errors found! Great playing!")
except KeyboardInterrupt:
print("\n\nβΉοΈ Analysis interrupted by user.")
except Exception as e:
print(f"\nβ Error during analysis: {e}")
finally:
analyzer.close_engine()
if __name__ == "__main__":
main()