Michael Falk commited on
Commit
fee60bf
·
1 Parent(s): e00315f

Added analysis

Browse files
README.md CHANGED
@@ -15,3 +15,24 @@ tags:
15
  ---
16
 
17
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  ---
16
 
17
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
18
+
19
+ # Chess Coach
20
+
21
+ ## Introduction
22
+
23
+ ## Tech Stack
24
+
25
+ - Gradio 6
26
+ - OpenAI Agents SDK
27
+ - python-chess
28
+ - stockfish engine
29
+ - chess-openings database
30
+
31
+ ## Get started
32
+
33
+ ### Author
34
+ Michael Falk
35
+
36
+ ### Credits
37
+
38
+ - https://github.com/lichess-org/chess-openings
app.py CHANGED
@@ -3,7 +3,7 @@ import os
3
  import asyncio
4
  import sys # Import sys to detect OS
5
  import src.ui_helpers as ui_helpers
6
- from src.ai_agents import call_ai_agents_async
7
  import src.chess_engine as chess_engine
8
  from src import mcp_server
9
  from chess import STARTING_BOARD_FEN
@@ -55,7 +55,19 @@ def prev_move(fens, id):
55
  svg = chess_engine.render_board(fens[id])
56
  return svg, id
57
 
 
 
 
 
 
 
 
 
 
 
58
  def load_game(pgn, log_msgs):
 
 
59
  if not chess_engine.is_valid_pgn(pgn):
60
  status = "⚠️ Invalid PGN format. Please check your input."
61
  return gr.update(), [], "", 0, status, log_msgs
@@ -67,18 +79,52 @@ def load_game(pgn, log_msgs):
67
  log_msgs.append(log_msg)
68
  return gr.update(selected=2), fens, svg, 0, "", log_msgs
69
 
70
- def analyze_game(pgn):
71
  """Analyze the chess game"""
72
- chess_game = load_pgn(pgn)
73
- board = chess_game.board()
74
 
75
  # Analyze opening
76
- opening = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- # call ai agent
79
- #result = asyncio.run(call_ai_agents_async(pgn))
80
 
81
- return opening
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  # Main Gradio Walkthrough UI
84
  game_examples = load_examples()
@@ -88,6 +134,7 @@ with gr.Blocks() as demo:
88
  move_index = gr.State(0)
89
  fen_list = gr.State([])
90
  log_msgs = gr.State([])
 
91
 
92
  with gr.Sidebar():
93
  gr.Markdown("""
@@ -138,15 +185,18 @@ with gr.Blocks() as demo:
138
  board = gr.HTML()
139
  with gr.Row():
140
  prev_btn = gr.Button("◀", size="sm", scale=0)
141
- play_btn = gr.Button("Play", size="sm", scale=0)
142
  next_btn = gr.Button("▶", size="sm", scale=0)
143
  move_text = gr.Markdown(f"Move {move_index.value} / {len(fen_list.value)}")
144
  with gr.Column():
145
  gr.Markdown("## 🧠 Coach Insights")
146
  gr.Markdown("### Opening Recognition")
147
  opening = gr.Markdown()
 
148
  gr.Markdown("### Critical Moves")
 
149
  gr.Markdown("### Key Insights")
 
150
  gr.Markdown("### Lessons")
151
  move_index_display = gr.Markdown()
152
  analysis_output = gr.JSON(label="Analysis Output")
@@ -161,12 +211,20 @@ with gr.Blocks() as demo:
161
 
162
  pgn_files.change(fn=file_to_text, inputs=pgn_files, outputs=pgn_text)
163
 
 
164
  analyze_game_btn.click(
165
  fn=load_game,
166
  inputs=[pgn_text, log_msgs],
167
  outputs=[walkthrough, fen_list, board, move_index, status_msg, log_msgs],
168
  )
169
 
 
 
 
 
 
 
 
170
  move_index.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)
171
  fen_list.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)
172
 
@@ -182,7 +240,7 @@ with gr.Blocks() as demo:
182
  outputs=[board, move_index]
183
  )
184
 
185
- back_btn.click(lambda: gr.Walkthrough(selected=1), outputs=walkthrough)
186
 
187
  """deep_analysis_btn.click(
188
  fn=analyze_game,
 
3
  import asyncio
4
  import sys # Import sys to detect OS
5
  import src.ui_helpers as ui_helpers
6
+ import src.ai as ai
7
  import src.chess_engine as chess_engine
8
  from src import mcp_server
9
  from chess import STARTING_BOARD_FEN
 
55
  svg = chess_engine.render_board(fens[id])
56
  return svg, id
57
 
58
+ def format_critical_moments(moments):
59
+ lines = []
60
+ for m in moments:
61
+ lines.append(
62
+ f"**Move {m['move']}**, "
63
+ f"Played: `{m['played']}`, Best: `{m['best']}`, "
64
+ f"Eval: {m['eval_before']} → {m['eval_after']}"
65
+ )
66
+ return "\n\n".join(lines)
67
+
68
  def load_game(pgn, log_msgs):
69
+ log_msgs = []
70
+
71
  if not chess_engine.is_valid_pgn(pgn):
72
  status = "⚠️ Invalid PGN format. Please check your input."
73
  return gr.update(), [], "", 0, status, log_msgs
 
79
  log_msgs.append(log_msg)
80
  return gr.update(selected=2), fens, svg, 0, "", log_msgs
81
 
82
+ def analyze_game(pgn, log_msgs):
83
  """Analyze the chess game"""
 
 
84
 
85
  # Analyze opening
86
+ opening = chess_engine.get_opening(pgn)
87
+
88
+ if opening["opening_name"] == "Unkown Opening":
89
+ log_msg = "❌ Opening not detected"
90
+ else:
91
+ log_msg = "✅ Opening detected"
92
+ log_msgs.append(log_msg)
93
+
94
+ opening_text = f"""
95
+ {opening["opening_name"]}
96
+ {opening["pgn"]}
97
+ """
98
+
99
+ svg = chess_engine.render_board(opening["fen"], 150)
100
+
101
+ log_msgs.append("⏳ Start chess engine")
102
+
103
+ yield opening_text, svg, {}, "", "", log_msgs
104
+
105
+ # evaluate chess game with stockfish
106
+ analysis, critical = asyncio.run(chess_engine.analyze_pgn(pgn))
107
 
108
+ critical_moments_str = format_critical_moments(critical)
 
109
 
110
+ log_msgs.append("✅ Chess moves evaluated")
111
+ log_msgs.append("✅ Critical moments identified")
112
+ yield opening_text, svg, analysis, critical_moments_str, "", log_msgs
113
+
114
+ key_insight_prompt = f"""
115
+ You are a chess coach. Please get one precise key insight of the following game. Keep it very short:
116
+ {analysis}
117
+ """
118
+ key_insights = ai.call_ai(key_insight_prompt)
119
+ print(key_insights)
120
+
121
+ return opening_text, svg, analysis, critical_moments_str, key_insights, log_msgs
122
+
123
+ def go_back(log_msgs):
124
+ """Go back to import game page"""
125
+ log_msgs = ["🔒 Waiting for input"]
126
+
127
+ return gr.update(selected=1), log_msgs
128
 
129
  # Main Gradio Walkthrough UI
130
  game_examples = load_examples()
 
134
  move_index = gr.State(0)
135
  fen_list = gr.State([])
136
  log_msgs = gr.State([])
137
+ move_evals = gr.State([])
138
 
139
  with gr.Sidebar():
140
  gr.Markdown("""
 
185
  board = gr.HTML()
186
  with gr.Row():
187
  prev_btn = gr.Button("◀", size="sm", scale=0)
188
+ #play_btn = gr.Button("Play", size="sm", scale=0)
189
  next_btn = gr.Button("▶", size="sm", scale=0)
190
  move_text = gr.Markdown(f"Move {move_index.value} / {len(fen_list.value)}")
191
  with gr.Column():
192
  gr.Markdown("## 🧠 Coach Insights")
193
  gr.Markdown("### Opening Recognition")
194
  opening = gr.Markdown()
195
+ board_opening = gr.HTML()
196
  gr.Markdown("### Critical Moves")
197
+ critical_moves_text = gr.Markdown()
198
  gr.Markdown("### Key Insights")
199
+ key_insights_text = gr.Markdown()
200
  gr.Markdown("### Lessons")
201
  move_index_display = gr.Markdown()
202
  analysis_output = gr.JSON(label="Analysis Output")
 
211
 
212
  pgn_files.change(fn=file_to_text, inputs=pgn_files, outputs=pgn_text)
213
 
214
+ # load game on chessboard
215
  analyze_game_btn.click(
216
  fn=load_game,
217
  inputs=[pgn_text, log_msgs],
218
  outputs=[walkthrough, fen_list, board, move_index, status_msg, log_msgs],
219
  )
220
 
221
+ # start analyzing game
222
+ analyze_game_btn.click(
223
+ fn=analyze_game,
224
+ inputs=[pgn_text, log_msgs],
225
+ outputs=[opening, board_opening, analysis_output, critical_moves_text, key_insights_text, log_msgs],
226
+ )
227
+
228
  move_index.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)
229
  fen_list.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)
230
 
 
240
  outputs=[board, move_index]
241
  )
242
 
243
+ back_btn.click(go_back, inputs=log_msgs, outputs=[walkthrough, log_msgs])
244
 
245
  """deep_analysis_btn.click(
246
  fn=analyze_game,
data/openings/all.tsv CHANGED
@@ -1,4 +1,4 @@
1
- A00 Amar Opening 1. Nh3 g1h3 rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq -
2
  A00 Amar Opening: Paris Gambit 1. Nh3 d5 2. g3 e5 3. f4 g1h3 d7d5 g2g3 e7e5 f2f4 rnbqkbnr/ppp2ppp/8/3pp3/5P2/6PN/PPPPP2P/RNBQKB1R b KQkq -
3
  A00 Amar Opening: Paris Gambit, Gent Gambit 1. Nh3 d5 2. g3 e5 3. f4 Bxh3 4. Bxh3 exf4 5. O-O fxg3 6. hxg3 g1h3 d7d5 g2g3 e7e5 f2f4 c8h3 f1h3 e5f4 e1g1 f4g3 h2g3 rn1qkbnr/ppp2ppp/8/3p4/8/6PB/PPPPP3/RNBQ1RK1 b kq -
4
  A00 Amsterdam Attack 1. e3 e5 2. c4 d6 3. Nc3 Nc6 4. b3 Nf6 e2e3 e7e5 c2c4 d7d6 b1c3 b8c6 b2b3 g8f6 r1bqkb1r/ppp2ppp/2np1n2/4p3/2P5/1PN1P3/P2P1PPP/R1BQKBNR w KQkq -
@@ -21,7 +21,7 @@ A00 Grob Opening: Double Grob 1. g4 g5 g2g4 g7g5 rnbqkbnr/pppppp1p/8/6p1/6P1/8/P
21
  A00 Grob Opening: Double Grob, Coca-Cola Gambit 1. g4 g5 2. f4 g2g4 g7g5 f2f4 rnbqkbnr/pppppp1p/8/6p1/5PP1/8/PPPPP2P/RNBQKBNR b KQkq -
22
  A00 Grob Opening: Grob Gambit 1. g4 d5 2. Bg2 g2g4 d7d5 f1g2 rnbqkbnr/ppp1pppp/8/3p4/6P1/8/PPPPPPBP/RNBQK1NR b KQkq -
23
  A00 Grob Opening: Grob Gambit Declined 1. g4 d5 2. Bg2 c6 g2g4 d7d5 f1g2 c7c6 rnbqkbnr/pp2pppp/2p5/3p4/6P1/8/PPPPPPBP/RNBQK1NR w KQkq -
24
- A00 Grob Opening: Grob Gambit, Basman Gambit 1. g4 d5 2. Bg2 h5 3. gxh5 g2g4 d7d5 f1g2 h7h5 g4h5 rnbqkbnr/ppp1ppp1/8/3p3P/8/8/PPPPPPBP/RNBQK1NR b KQkq -
25
  A00 Grob Opening: Grob Gambit, Fritz Gambit 1. g4 d5 2. Bg2 Bxg4 3. c4 g2g4 d7d5 f1g2 c8g4 c2c4 rn1qkbnr/ppp1pppp/8/3p4/2P3b1/8/PP1PPPBP/RNBQK1NR b KQkq -
26
  A00 Grob Opening: Grob Gambit, Fritz Gambit, Romford Countergambit 1. g4 d5 2. Bg2 Bxg4 3. c4 d4 4. Bxb7 Nd7 5. Bxa8 Qxa8 g2g4 d7d5 f1g2 c8g4 c2c4 d5d4 g2b7 b8d7 b7a8 d8a8 q3kbnr/p1pnpppp/8/8/2Pp2b1/8/PP1PPP1P/RNBQK1NR w KQk -
27
  A00 Grob Opening: Grob Gambit, Keres Gambit 1. g4 d5 2. Bg2 e5 3. d4 exd4 4. c3 g2g4 d7d5 f1g2 e7e5 d2d4 e5d4 c2c3 rnbqkbnr/ppp2ppp/8/3p4/3p2P1/2P5/PP2PPBP/RNBQK1NR b KQkq -
 
1
+ A00 Amar Opening 1. Nh3 g1h3 rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq -
2
  A00 Amar Opening: Paris Gambit 1. Nh3 d5 2. g3 e5 3. f4 g1h3 d7d5 g2g3 e7e5 f2f4 rnbqkbnr/ppp2ppp/8/3pp3/5P2/6PN/PPPPP2P/RNBQKB1R b KQkq -
3
  A00 Amar Opening: Paris Gambit, Gent Gambit 1. Nh3 d5 2. g3 e5 3. f4 Bxh3 4. Bxh3 exf4 5. O-O fxg3 6. hxg3 g1h3 d7d5 g2g3 e7e5 f2f4 c8h3 f1h3 e5f4 e1g1 f4g3 h2g3 rn1qkbnr/ppp2ppp/8/3p4/8/6PB/PPPPP3/RNBQ1RK1 b kq -
4
  A00 Amsterdam Attack 1. e3 e5 2. c4 d6 3. Nc3 Nc6 4. b3 Nf6 e2e3 e7e5 c2c4 d7d6 b1c3 b8c6 b2b3 g8f6 r1bqkb1r/ppp2ppp/2np1n2/4p3/2P5/1PN1P3/P2P1PPP/R1BQKBNR w KQkq -
 
21
  A00 Grob Opening: Double Grob, Coca-Cola Gambit 1. g4 g5 2. f4 g2g4 g7g5 f2f4 rnbqkbnr/pppppp1p/8/6p1/5PP1/8/PPPPP2P/RNBQKBNR b KQkq -
22
  A00 Grob Opening: Grob Gambit 1. g4 d5 2. Bg2 g2g4 d7d5 f1g2 rnbqkbnr/ppp1pppp/8/3p4/6P1/8/PPPPPPBP/RNBQK1NR b KQkq -
23
  A00 Grob Opening: Grob Gambit Declined 1. g4 d5 2. Bg2 c6 g2g4 d7d5 f1g2 c7c6 rnbqkbnr/pp2pppp/2p5/3p4/6P1/8/PPPPPPBP/RNBQK1NR w KQkq -
24
+ A00 Grob Opening: Grob Gambit, Basman Gambit 1. g4 d5 2. Bg2 h5 3. gxh5 g2g4 d7d5 f1g2 h7h5 g4h5 rnbqkbnr/ppp1ppp1/8/3p3P/8/8/PPPPPPBP/RNBQK1NR b KQkq -
25
  A00 Grob Opening: Grob Gambit, Fritz Gambit 1. g4 d5 2. Bg2 Bxg4 3. c4 g2g4 d7d5 f1g2 c8g4 c2c4 rn1qkbnr/ppp1pppp/8/3p4/2P3b1/8/PP1PPPBP/RNBQK1NR b KQkq -
26
  A00 Grob Opening: Grob Gambit, Fritz Gambit, Romford Countergambit 1. g4 d5 2. Bg2 Bxg4 3. c4 d4 4. Bxb7 Nd7 5. Bxa8 Qxa8 g2g4 d7d5 f1g2 c8g4 c2c4 d5d4 g2b7 b8d7 b7a8 d8a8 q3kbnr/p1pnpppp/8/8/2Pp2b1/8/PP1PPP1P/RNBQK1NR w KQk -
27
  A00 Grob Opening: Grob Gambit, Keres Gambit 1. g4 d5 2. Bg2 e5 3. d4 exd4 4. c3 g2g4 d7d5 f1g2 e7e5 d2d4 e5d4 c2c3 rnbqkbnr/ppp2ppp/8/3p4/3p2P1/2P5/PP2PPBP/RNBQK1NR b KQkq -
examples/travelhawk-chess.com.pgn ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Event "Live Chess"]
2
+ [Site "Chess.com"]
3
+ [Date "2025.11.11"]
4
+ [Round "?"]
5
+ [White "travelhawk"]
6
+ [Black "bero203"]
7
+ [Result "1-0"]
8
+ [TimeControl "180+2"]
9
+ [WhiteElo "883"]
10
+ [BlackElo "857"]
11
+ [Termination "travelhawk hat durch Aufgabe gewonnen"]
12
+ [ECO "A02"]
13
+ [EndTime "22:45:19 GMT+0000"]
14
+ [Link "https://www.chess.com/game/live/145401631086"]
15
+
16
+ 1. f4 b6 2. Nf3 Bb7 3. e3 g6 4. Bc4 Bg7 5. d4 d6 6. O-O Nd7 7. Nc3 Ngf6 8. Bd2
17
+ c5 9. d5 Nh5 10. e4 Bxc3 11. Bxc3 Nxf4 12. Bxh8 f6 13. Qd2 Nh5 14. Qh6 Qc7 15.
18
+ Qxh7 O-O-O 16. Bg7 Nxg7 17. Qxg7 g5 18. Qxe7 Rg8 19. Qe6 Rh8 20. Bb5 Rd8 21.
19
+ Bxd7+ Rxd7 22. Qxf6 Kb8 23. Qxg5 Bc8 24. c4 Rg7 25. Qh6 Rh7 26. Qe3 Qg7 27. Ng5
20
+ Bh3 28. Nxh3 Rxh3 29. Qxh3 Qxg2+ 30. Qxg2 1-0
src/{ai_agents.py → ai.py} RENAMED
@@ -9,7 +9,6 @@ from agents.extensions.handoff_prompt import prompt_with_handoff_instructions, R
9
  import asyncio
10
  from typing import Any, Dict
11
  from subprocess import Popen, PIPE
12
- from chess_mcp.server import mcp
13
  from pydantic import BaseModel
14
 
15
  dotenv.load_dotenv()
@@ -24,9 +23,25 @@ client = AsyncOpenAI(
24
  api_key=API_KEY
25
  )
26
 
 
 
 
 
 
27
  set_default_openai_client(client)
28
  agent_model = OpenAIResponsesModel(model=MODEL_NAME, openai_client=client)
29
 
 
 
 
 
 
 
 
 
 
 
 
30
  def get_mcp_server_client() -> MCPServerStreamableHttp:
31
  """
32
  Returns an MCP server client connected to the running MCP server.
@@ -57,8 +72,9 @@ async def call_ai_agents_async(username: str) -> Dict[str, Any]:
57
  print(f"Error calling AI agents: {e}", file=sys.stderr)
58
  raise
59
 
 
 
60
  if __name__ == "__main__":
61
- # For testing purposes, run the agent with a sample username
62
- test_username = "13,4"
63
- result = asyncio.run(call_ai_agents_async(test_username))
64
- print("Final Result:", result)
 
9
  import asyncio
10
  from typing import Any, Dict
11
  from subprocess import Popen, PIPE
 
12
  from pydantic import BaseModel
13
 
14
  dotenv.load_dotenv()
 
23
  api_key=API_KEY
24
  )
25
 
26
+ sync_client = OpenAI(
27
+ base_url=BASE_API_URL,
28
+ api_key=API_KEY
29
+ )
30
+
31
  set_default_openai_client(client)
32
  agent_model = OpenAIResponsesModel(model=MODEL_NAME, openai_client=client)
33
 
34
+ def call_ai(prompt: str) -> str:
35
+ """
36
+ Call the OpenAI Responses API with a simple prompt and return the text output.
37
+ """
38
+ response = sync_client.responses.create(
39
+ model=MODEL_NAME,
40
+ input=prompt,
41
+ reasoning={"effort": "low"}
42
+ )
43
+ return response.output_text
44
+
45
  def get_mcp_server_client() -> MCPServerStreamableHttp:
46
  """
47
  Returns an MCP server client connected to the running MCP server.
 
72
  print(f"Error calling AI agents: {e}", file=sys.stderr)
73
  raise
74
 
75
+
76
+
77
  if __name__ == "__main__":
78
+ pgn = call_ai("Give me a random PGN (chess game).")
79
+ print(pgn)
80
+
 
src/chess_engine.py CHANGED
@@ -6,6 +6,7 @@ import asyncio
6
  import io
7
  import os
8
  import sys
 
9
 
10
  # Dictionary to hold openings data
11
  openings = {}
@@ -15,13 +16,12 @@ def load_openings_db():
15
  print("Loading openings database...")
16
  with open("data/openings/all.tsv", "r", encoding="utf-8") as file:
17
  for line in file.readlines():
18
- # Each line format: ECO_CODE \t Opening Name \t Opening Moves
19
  parts = line.strip().split("\t")
20
- if len(parts) >= 2:
21
  eco_code = parts[0]
22
- opening_name = parts[1]
23
- openings[eco_code] = opening_name
24
- print(f"Loaded {len(openings)} openings from database.")
25
 
26
  def load_pgn(pgn_text: str) -> chess.pgn.Game:
27
  """
@@ -55,7 +55,15 @@ def is_valid_pgn(pgn_text: str) -> bool:
55
  except Exception:
56
  return False
57
 
58
- async def analyze_pgn(pgn_string, fast_mode=True):
 
 
 
 
 
 
 
 
59
  # PGN → Moves (0.01s, nativ)
60
  game = chess.pgn.read_game(io.StringIO(pgn_string))
61
  board = game.board()
@@ -64,6 +72,7 @@ async def analyze_pgn(pgn_string, fast_mode=True):
64
  engine = chess.engine.SimpleEngine.popen_uci(engine_path)
65
 
66
  analysis = []
 
67
 
68
  # Get initial evaluation from White's perspective
69
  info = engine.analyse(board, chess.engine.Limit(time=0.1))
@@ -74,9 +83,8 @@ async def analyze_pgn(pgn_string, fast_mode=True):
74
 
75
  board.push(move)
76
 
77
- time_limit = 0.1 if fast_mode else 1.0
78
  info = engine.analyse(board, chess.engine.Limit(time=time_limit))
79
-
80
  current_wp_eval = info['score'].white().score(mate_score=10000)
81
 
82
  is_blunder = False
@@ -92,11 +100,21 @@ async def analyze_pgn(pgn_string, fast_mode=True):
92
  if (current_wp_eval - last_wp_eval) > 100:
93
  is_blunder = True
94
 
 
 
 
 
 
 
 
 
 
95
  analysis.append({
96
  'nr': i+1,
97
  'move': str(move),
98
  'fen': board.fen(),
99
- 'eval': info['score'].relative.score(mate_score=10000)/100,
 
100
  'best_move': str(info['pv'][0]) if info.get('pv') else None,
101
  'is_blunder': is_blunder
102
  })
@@ -104,7 +122,7 @@ async def analyze_pgn(pgn_string, fast_mode=True):
104
  last_wp_eval = current_wp_eval
105
 
106
  engine.quit()
107
- return analysis
108
 
109
 
110
  async def analyze_fen_position(fen_string: str, analysis_time: float = 3.0):
@@ -127,16 +145,24 @@ async def analyze_fen_position(fen_string: str, analysis_time: float = 3.0):
127
  'variation': [str(move) for move in info['pv']] if info['pv'] else []
128
  }
129
 
130
- def get_opening_name(eco_code: str) -> str:
131
- """Return opening name for given ECO code using the loaded openings dict."""
 
 
 
 
 
 
 
 
132
  return openings.get(eco_code, "Unknown Opening")
133
 
134
- def render_board(fen: str) -> str:
135
  """Render a chess position from FEN to SVG."""
136
  board = chess.Board(fen)
137
  return chess.svg.board(
138
  board,
139
- size=550,
140
  )
141
 
142
  def analyze_game_handler(pgn):
@@ -151,6 +177,8 @@ def analyze_game_handler(pgn):
151
  # yield results
152
 
153
 
 
 
154
  if __name__ == "__main__":
155
  import os
156
 
 
6
  import io
7
  import os
8
  import sys
9
+ import re
10
 
11
  # Dictionary to hold openings data
12
  openings = {}
 
16
  print("Loading openings database...")
17
  with open("data/openings/all.tsv", "r", encoding="utf-8") as file:
18
  for line in file.readlines():
19
+ # Each line format: ECO_CODE \t Opening Name \t PGN \t UCI \t Opening Moves (FEN)
20
  parts = line.strip().split("\t")
21
+ if len(parts) >= 5:
22
  eco_code = parts[0]
23
+ openings[eco_code] = { "opening_name": parts[1], "pgn": parts[2], "fen": parts[4]}
24
+ print(f"Loaded {len(openings)} openings from database.")
 
25
 
26
  def load_pgn(pgn_text: str) -> chess.pgn.Game:
27
  """
 
55
  except Exception:
56
  return False
57
 
58
+ def explain(delta):
59
+ if delta <= -1.5:
60
+ return "Serious blunder losing material or initiative"
61
+ if delta <= -1:
62
+ return "Positional disadvantage or pawn loss"
63
+ return "Reasonable move"
64
+
65
+
66
+ async def analyze_pgn(pgn_string):
67
  # PGN → Moves (0.01s, nativ)
68
  game = chess.pgn.read_game(io.StringIO(pgn_string))
69
  board = game.board()
 
72
  engine = chess.engine.SimpleEngine.popen_uci(engine_path)
73
 
74
  analysis = []
75
+ critical = []
76
 
77
  # Get initial evaluation from White's perspective
78
  info = engine.analyse(board, chess.engine.Limit(time=0.1))
 
83
 
84
  board.push(move)
85
 
86
+ time_limit = 0.1
87
  info = engine.analyse(board, chess.engine.Limit(time=time_limit))
 
88
  current_wp_eval = info['score'].white().score(mate_score=10000)
89
 
90
  is_blunder = False
 
100
  if (current_wp_eval - last_wp_eval) > 100:
101
  is_blunder = True
102
 
103
+ if is_blunder == True:
104
+ critical.append({
105
+ "move": i+1,
106
+ "played": str(move),
107
+ "best": str(info['pv'][0]) if info.get('pv') else None,
108
+ "eval_before": last_wp_eval/100,
109
+ "eval_after": current_wp_eval/100
110
+ })
111
+
112
  analysis.append({
113
  'nr': i+1,
114
  'move': str(move),
115
  'fen': board.fen(),
116
+ 'eval_before': last_wp_eval/100,
117
+ 'eval': current_wp_eval/100,
118
  'best_move': str(info['pv'][0]) if info.get('pv') else None,
119
  'is_blunder': is_blunder
120
  })
 
122
  last_wp_eval = current_wp_eval
123
 
124
  engine.quit()
125
+ return analysis, critical
126
 
127
 
128
  async def analyze_fen_position(fen_string: str, analysis_time: float = 3.0):
 
145
  'variation': [str(move) for move in info['pv']] if info['pv'] else []
146
  }
147
 
148
+
149
+ def get_opening(pgn: str) -> str:
150
+ """Return opening name for given ECO code inside PGN using the loaded openings dict."""
151
+ pattern = re.compile(r'\[ECO\s+"([^"]+)"\]')
152
+
153
+ matches = pattern.findall(pgn)
154
+ if len(matches) > 0:
155
+ eco_code = matches[0]
156
+ else:
157
+ return "Unkown Opening"
158
  return openings.get(eco_code, "Unknown Opening")
159
 
160
+ def render_board(fen: str, size: int = 550) -> str:
161
  """Render a chess position from FEN to SVG."""
162
  board = chess.Board(fen)
163
  return chess.svg.board(
164
  board,
165
+ size=size,
166
  )
167
 
168
  def analyze_game_handler(pgn):
 
177
  # yield results
178
 
179
 
180
+ load_openings_db()
181
+
182
  if __name__ == "__main__":
183
  import os
184