-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
283 lines (240 loc) · 11.2 KB
/
main.py
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
import streamlit as st
import chess
import chess.pgn
import chess.engine
import chess.svg
from io import StringIO
import random
import pathlib
import pandas as pd
import altair as alt
st.set_page_config(
layout="wide",
initial_sidebar_state="expanded",
page_title="Chesalyser",
page_icon="logos/small.png",
)
def classify_move(score_change, is_capture=False, moved_piece=None):
if is_capture:
if score_change < 30:
return "Best Move", "green"
elif 30 <= score_change < 80:
return "Good Move", "blue"
elif 80 <= score_change < 180:
return "Inaccuracy", "yellow"
elif 180 <= score_change < 350:
return "Mistake", "orange"
else:
return "Blunder", "red"
elif moved_piece == chess.QUEEN:
if score_change < 40:
return "Best Move", "green"
elif 40 <= score_change < 100:
return "Good Move", "blue"
elif 100 <= score_change < 200:
return "Inaccuracy", "yellow"
elif 200 <= score_change < 400:
return "Mistake", "orange"
else:
return "Blunder", "red"
else:
if score_change < 20:
return "Best Move", "green"
elif 20 <= score_change < 70:
return "Good Move", "blue"
elif 70 <= score_change < 150:
return "Inaccuracy", "yellow"
elif 150 <= score_change < 300:
return "Mistake", "orange"
else:
return "Blunder", "red"
def analyze_game(game, engine_path, depth):
engine = chess.engine.SimpleEngine.popen_uci(engine_path)
analysis_results = []
board = game.board()
previous_eval = None
for move_index, move in enumerate(game.mainline_moves()):
is_capture = board.is_capture(move)
from_square = move.from_square
moved_piece = board.piece_type_at(from_square)
current_position = board.copy()
board.push(move)
side_to_move = not board.turn
info = engine.analyse(board, chess.engine.Limit(depth=depth))
current_eval = info["score"].white().score(mate_score=10000)
if previous_eval is None:
score_change = 0
else:
if side_to_move: # White just moved
score_change = previous_eval - current_eval
else: # Black just moved
score_change = current_eval - previous_eval
score_change = abs(score_change)
previous_eval = current_eval
win_probability = 1 / (1 + 10 ** (-current_eval / 400))
move_quality, color = classify_move(score_change, is_capture, moved_piece)
best_move_info = engine.analyse(current_position, chess.engine.Limit(depth=depth))
best_move = best_move_info.get("pv", [None])[0]
analysis_results.append({
"move": move.uci(),
"score": round(win_probability, 3),
"centipawn_eval": current_eval,
"best_move": best_move.uci() if best_move else "None",
"score_change": round(score_change, 1),
"quality": move_quality,
"color": color,
"is_capture": is_capture,
"piece_moved": chess.piece_name(moved_piece) if moved_piece else "None",
})
engine.quit()
return analysis_results
def main():
st.logo("logos/big.png", icon_image="logos/small.png")
file_path = pathlib.Path("style.css")
with open(file_path) as f:
st.html(f"<style>{f.read()}</style>")
st.title(":material/chess_pawn: Chess Game Analyzer")
st.markdown("<hr style='margin: 0px 0px 30px 0px;'>", unsafe_allow_html=True)
with st.sidebar:
st.markdown(
"<div style='background-image: linear-gradient(to top right, #00f0ff, #0e6fff, #8f5bff); border-radius: 8px'><h1 style='text-align: center; padding: 10px; margin: 0px 0px 15px 0px; font-weight: 700;'>⚙ SETTINGS</h1></div>",
unsafe_allow_html=True,
)
with st.container(border=True):
engine_path = st.text_input(
":material/conversion_path: Stockfish Engine Path",
value="stockfish/stockfish-ubuntu-x86-64-sse41-popcnt",
help="Paste your Stockfish engine path here."
)
with st.container(border=True):
pgn_file = st.file_uploader(":material/upload: Upload PGN file", type="pgn")
pgn_text = st.text_area(":material/content_paste: Or paste PGN text here")
with st.container(border=True):
# Depth selection with cheeky phrases
depth_options = {
10: "Beginner mode",
15: "Casual mode",
20: "Serious mode",
25: "Grandmaster mode",
30: "Stockfish mode",
}
depth = st.selectbox(
":material/settings: Select Analysis Depth:",
options=list(depth_options.keys()),
format_func=lambda x: depth_options[x],
)
if pgn_file or pgn_text:
try:
pgn = StringIO(pgn_text if pgn_text else pgn_file.getvalue().decode())
game = chess.pgn.read_game(pgn)
if game is None:
st.error("Invalid PGN file or text. Please check the format.")
return
with st.sidebar:
if st.button(
":material/neurology: ANALYZE GAME",
use_container_width=True,
key="agame",
):
messages = [
"Thinking like Magnus Carlsen...",
"Calculating the best blunder... just kidding!",
"Running Stockfish at full speed!",
"Searching for the brilliancy move!",
"Did you just play a Bongcloud opening? Let's see...",
"Analyzing faster than Hikaru can pre-move!",
"Determining if this was a 200 IQ move or a disaster...",
"Checking if this game belongs in the Hall of Fame or Shame!",
]
with st.spinner(random.choice(messages)):
st.session_state.analysis = analyze_game(
game, engine_path, depth
)
st.session_state.num_moves = len(st.session_state.analysis)
if "analysis" in st.session_state:
with st.container(border=True):
st.write("Tap ꞏ and then use ← and → keys to navigate")
slider = (
st.slider(
"Tap ꞏ and then use ← and → keys to navigate",
1,
st.session_state.num_moves,
1,
label_visibility="collapsed",
)
- 1
)
board = game.board()
for i in range(slider + 1):
board.push(
chess.Move.from_uci(st.session_state.analysis[i]["move"])
)
with st.container(border=True):
col2, col3 = st.columns(2, vertical_alignment="center", gap="small")
with col2:
with st.container(border=True):
with st.container(border=True):
st.write(
f"{game.headers['Black']} ({game.headers['BlackElo']})"
)
svg = chess.svg.board(board=board, size=400)
st.image(svg, width=800)
with st.container(border=True):
st.write(
f"{game.headers['White']} ({game.headers['WhiteElo']})"
)
with col3:
with st.container(border=True):
result = st.session_state.analysis[slider]
st.markdown(
"<div style='background-image: linear-gradient(to top right, #00f0ff, #0e6fff, #8f5bff); border-radius: 6px'><h3 style='text-align: center; padding: 10px; margin: 10px 10px 15px 34px; font-weight: 700;'>GAME REPORT</h3></div>",
unsafe_allow_html=True,
)
st.markdown(f"- **Move**: `{result['move']}`")
st.markdown(
f"- **Win Probability**: `{(result['score'] * 100):.2f}%`"
)
st.markdown(f"- **Best move**: `{result['best_move']}`")
st.markdown(
f"- **Move Quality**: <span style='color:{result['color']}; font-weight:bold;'>{result['quality']}</span>",
unsafe_allow_html=True,
)
# st.markdown(f"- **Expected Points Lost**: `{result['expected_points_lost']:.3f}`")
with st.container(border=True):
# Win Probability Chart with Brush Selection
win_prob_data = pd.DataFrame(
{
"Move Number": range(
1, len(st.session_state.analysis) + 1
),
"Win Probability": [
x["score"]
for x in st.session_state.analysis
],
}
)
brush = alt.selection_interval(encodings=["x"])
win_prob_chart = (
alt.Chart(win_prob_data)
.mark_line()
.encode(
x=alt.X("Move Number:Q", title="Move Number"),
y=alt.Y(
"Win Probability:Q", title="Win Probability"
), # Removed format="%"`
tooltip=["Move Number", "Win Probability"],
)
.properties(
title="Win Probability of White Over Time"
)
.add_selection(brush)
)
st.altair_chart(
win_prob_chart, use_container_width=True
)
except Exception as e:
st.error(f"Error analyzing game: {str(e)}")
with st.sidebar:
st.markdown("###### :gray[Powered by [Stockfish](https://stockfishchess.org/)]")
if __name__ == "__main__":
main()