Spaces:
Runtime error
Runtime error
Michael Falk commited on
Commit ·
fee60bf
1
Parent(s): e00315f
Added analysis
Browse filesFiles changed (6)
- README.md+21
- app.py+68-10
- data/openings/all.tsv+2-2
- examples/travelhawk-chess.com.pgnAdded+20
- src/ai_agents.py → src/ai.pyRenamed+21-5
- src/chess_engine.py+42-14
14 unmodified lines15161714 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference14 unmodified lines15161718192021222324252627282930313233343536373814 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Chess Coach## Introduction## Tech Stack- Gradio 6- OpenAI Agents SDK- python-chess- stockfish engine- chess-openings database## Get started### AuthorMichael Falk### Credits- https://github.com/lichess-org/chess-openings
2 unmodified lines345678945 unmodified lines555657585960615 unmodified lines6768697071727374757677787980818283843 unmodified lines88899091929344 unmodified lines1381391401411421431441451461471481491501511528 unmodified lines1611621631641651661671681691701711729 unmodified lines1821831841851861871882 unmodified linesimport asyncioimport sys # Import sys to detect OSimport src.ui_helpers as ui_helpersfrom src.ai_agents import call_ai_agents_asyncimport src.chess_engine as chess_enginefrom src import mcp_serverfrom chess import STARTING_BOARD_FEN45 unmodified linessvg = chess_engine.render_board(fens[id])return svg, iddef load_game(pgn, log_msgs):if not chess_engine.is_valid_pgn(pgn):status = "⚠️ Invalid PGN format. Please check your input."return gr.update(), [], "", 0, status, log_msgs5 unmodified lineslog_msgs.append(log_msg)return gr.update(selected=2), fens, svg, 0, "", log_msgsdef analyze_game(pgn):"""Analyze the chess game"""chess_game = load_pgn(pgn)board = chess_game.board()# Analyze openingopening = ""# call ai agent#result = asyncio.run(call_ai_agents_async(pgn))return opening# Main Gradio Walkthrough UIgame_examples = load_examples()3 unmodified linesmove_index = gr.State(0)fen_list = gr.State([])log_msgs = gr.State([])with gr.Sidebar():gr.Markdown("""44 unmodified linesboard = gr.HTML()with gr.Row():prev_btn = gr.Button("◀", size="sm", scale=0)play_btn = gr.Button("Play", size="sm", scale=0)next_btn = gr.Button("▶", size="sm", scale=0)move_text = gr.Markdown(f"Move {move_index.value} / {len(fen_list.value)}")with gr.Column():gr.Markdown("## 🧠 Coach Insights")gr.Markdown("### Opening Recognition")opening = gr.Markdown()gr.Markdown("### Critical Moves")gr.Markdown("### Key Insights")gr.Markdown("### Lessons")move_index_display = gr.Markdown()analysis_output = gr.JSON(label="Analysis Output")8 unmodified linespgn_files.change(fn=file_to_text, inputs=pgn_files, outputs=pgn_text)analyze_game_btn.click(fn=load_game,inputs=[pgn_text, log_msgs],outputs=[walkthrough, fen_list, board, move_index, status_msg, log_msgs],)move_index.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)fen_list.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)9 unmodified linesoutputs=[board, move_index])back_btn.click(lambda: gr.Walkthrough(selected=1), outputs=walkthrough)"""deep_analysis_btn.click(fn=analyze_game,2 unmodified lines345678945 unmodified lines555657585960616263646566676869707172735 unmodified lines7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291303 unmodified lines13413513613713813914044 unmodified lines1851861871881891901911921931941951961971981992002012028 unmodified lines2112122132142152162172182192202212222232242252262272282292309 unmodified lines2402412422432442452462 unmodified linesimport asyncioimport sys # Import sys to detect OSimport src.ui_helpers as ui_helpersimport src.ai as aiimport src.chess_engine as chess_enginefrom src import mcp_serverfrom chess import STARTING_BOARD_FEN45 unmodified linessvg = chess_engine.render_board(fens[id])return svg, iddef format_critical_moments(moments):lines = []for m in moments:lines.append(f"**Move {m['move']}**, "f"Played: `{m['played']}`, Best: `{m['best']}`, "f"Eval: {m['eval_before']} → {m['eval_after']}")return "\n\n".join(lines)def load_game(pgn, log_msgs):log_msgs = []if not chess_engine.is_valid_pgn(pgn):status = "⚠️ Invalid PGN format. Please check your input."return gr.update(), [], "", 0, status, log_msgs5 unmodified lineslog_msgs.append(log_msg)return gr.update(selected=2), fens, svg, 0, "", log_msgsdef analyze_game(pgn, log_msgs):"""Analyze the chess game"""# Analyze openingopening = chess_engine.get_opening(pgn)if opening["opening_name"] == "Unkown Opening":log_msg = "❌ Opening not detected"else:log_msg = "✅ Opening detected"log_msgs.append(log_msg)opening_text = f"""{opening["opening_name"]}{opening["pgn"]}"""svg = chess_engine.render_board(opening["fen"], 150)log_msgs.append("⏳ Start chess engine")yield opening_text, svg, {}, "", "", log_msgs# evaluate chess game with stockfishanalysis, critical = asyncio.run(chess_engine.analyze_pgn(pgn))critical_moments_str = format_critical_moments(critical)log_msgs.append("✅ Chess moves evaluated")log_msgs.append("✅ Critical moments identified")yield opening_text, svg, analysis, critical_moments_str, "", log_msgskey_insight_prompt = f"""You are a chess coach. Please get one precise key insight of the following game. Keep it very short:{analysis}"""key_insights = ai.call_ai(key_insight_prompt)print(key_insights)return opening_text, svg, analysis, critical_moments_str, key_insights, log_msgsdef go_back(log_msgs):"""Go back to import game page"""log_msgs = ["🔒 Waiting for input"]return gr.update(selected=1), log_msgs# Main Gradio Walkthrough UIgame_examples = load_examples()3 unmodified linesmove_index = gr.State(0)fen_list = gr.State([])log_msgs = gr.State([])move_evals = gr.State([])with gr.Sidebar():gr.Markdown("""44 unmodified linesboard = gr.HTML()with gr.Row():prev_btn = gr.Button("◀", size="sm", scale=0)#play_btn = gr.Button("Play", size="sm", scale=0)next_btn = gr.Button("▶", size="sm", scale=0)move_text = gr.Markdown(f"Move {move_index.value} / {len(fen_list.value)}")with gr.Column():gr.Markdown("## 🧠 Coach Insights")gr.Markdown("### Opening Recognition")opening = gr.Markdown()board_opening = gr.HTML()gr.Markdown("### Critical Moves")critical_moves_text = gr.Markdown()gr.Markdown("### Key Insights")key_insights_text = gr.Markdown()gr.Markdown("### Lessons")move_index_display = gr.Markdown()analysis_output = gr.JSON(label="Analysis Output")8 unmodified linespgn_files.change(fn=file_to_text, inputs=pgn_files, outputs=pgn_text)# load game on chessboardanalyze_game_btn.click(fn=load_game,inputs=[pgn_text, log_msgs],outputs=[walkthrough, fen_list, board, move_index, status_msg, log_msgs],)# start analyzing gameanalyze_game_btn.click(fn=analyze_game,inputs=[pgn_text, log_msgs],outputs=[opening, board_opening, analysis_output, critical_moves_text, key_insights_text, log_msgs],)move_index.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)fen_list.change(lambda x,y: f"Move {x} / {len(y)-1}", [move_index, fen_list], move_text)9 unmodified linesoutputs=[board, move_index])back_btn.click(go_back, inputs=log_msgs, outputs=[walkthrough, log_msgs])"""deep_analysis_btn.click(fn=analyze_game,
123416 unmodified lines21222324252627A00 Amar Opening 1. Nh3 g1h3 rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq -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 -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 -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 -16 unmodified linesA00 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 -A00 Grob Opening: Grob Gambit 1. g4 d5 2. Bg2 g2g4 d7d5 f1g2 rnbqkbnr/ppp1pppp/8/3p4/6P1/8/PPPPPPBP/RNBQK1NR b KQkq -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 -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 -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 -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 -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 -123416 unmodified lines21222324252627A00 Amar Opening 1. Nh3 g1h3 rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq -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 -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 -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 -16 unmodified linesA00 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 -A00 Grob Opening: Grob Gambit 1. g4 d5 2. Bg2 g2g4 d7d5 f1g2 rnbqkbnr/ppp1pppp/8/3p4/6P1/8/PPPPPPBP/RNBQK1NR b KQkq -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 -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 -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 -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 -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 -
1234567891011121314151617181920[Event "Live Chess"][Site "Chess.com"][Date "2025.11.11"][Round "?"][White "travelhawk"][Black "bero203"][Result "1-0"][TimeControl "180+2"][WhiteElo "883"][BlackElo "857"][Termination "travelhawk hat durch Aufgabe gewonnen"][ECO "A02"][EndTime "22:45:19 GMT+0000"][Link "https://www.chess.com/game/live/145401631086"]
1. f4 b6 2. Nf3 Bb7 3. e3 g6 4. Bc4 Bg7 5. d4 d6 6. O-O Nd7 7. Nc3 Ngf6 8. Bd2c5 9. d5 Nh5 10. e4 Bxc3 11. Bxc3 Nxf4 12. Bxh8 f6 13. Qd2 Nh5 14. Qh6 Qc7 15.Qxh7 O-O-O 16. Bg7 Nxg7 17. Qxg7 g5 18. Qxe7 Rg8 19. Qe6 Rh8 20. Bb5 Rd8 21.Bxd7+ Rxd7 22. Qxf6 Kb8 23. Qxg5 Bc8 24. c4 Rg7 25. Qh6 Rh7 26. Qe3 Qg7 27. Ng5Bh3 28. Nxh3 Rxh3 29. Qxh3 Qxg2+ 30. Qxg2 1-08 unmodified lines91011121314158 unmodified lines24252627282930313224 unmodified lines57585960616263648 unmodified linesimport asynciofrom typing import Any, Dictfrom subprocess import Popen, PIPEfrom chess_mcp.server import mcpfrom pydantic import BaseModeldotenv.load_dotenv()8 unmodified linesapi_key=API_KEY)set_default_openai_client(client)agent_model = OpenAIResponsesModel(model=MODEL_NAME, openai_client=client)def get_mcp_server_client() -> MCPServerStreamableHttp:"""Returns an MCP server client connected to the running MCP server.24 unmodified linesprint(f"Error calling AI agents: {e}", file=sys.stderr)raiseif __name__ == "__main__":# For testing purposes, run the agent with a sample usernametest_username = "13,4"result = asyncio.run(call_ai_agents_async(test_username))print("Final Result:", result)8 unmodified lines910111213148 unmodified lines2324252627282930313233343536373839404142434445464724 unmodified lines7273747576777879808 unmodified linesimport asynciofrom typing import Any, Dictfrom subprocess import Popen, PIPEfrom pydantic import BaseModeldotenv.load_dotenv()8 unmodified linesapi_key=API_KEY)sync_client = OpenAI(base_url=BASE_API_URL,api_key=API_KEY)set_default_openai_client(client)agent_model = OpenAIResponsesModel(model=MODEL_NAME, openai_client=client)def call_ai(prompt: str) -> str:"""Call the OpenAI Responses API with a simple prompt and return the text output."""response = sync_client.responses.create(model=MODEL_NAME,input=prompt,reasoning={"effort": "low"})return response.output_textdef get_mcp_server_client() -> MCPServerStreamableHttp:"""Returns an MCP server client connected to the running MCP server.24 unmodified linesprint(f"Error calling AI agents: {e}", file=sys.stderr)raiseif __name__ == "__main__":pgn = call_ai("Give me a random PGN (chess game).")print(pgn)
5 unmodified lines678910113 unmodified lines1516171819202122232425262727 unmodified lines555657585960612 unmodified lines6465666768694 unmodified lines7475767778798081829 unmodified lines92939495969798991001011021 unmodified line10410510610710810911016 unmodified lines1271281291301311321331341351361371381391401411428 unmodified lines1511521531541551565 unmodified linesimport ioimport osimport sys# Dictionary to hold openings dataopenings = {}3 unmodified linesprint("Loading openings database...")with open("data/openings/all.tsv", "r", encoding="utf-8") as file:for line in file.readlines():# Each line format: ECO_CODE \t Opening Name \t Opening Movesparts = line.strip().split("\t")if len(parts) >= 2:eco_code = parts[0]opening_name = parts[1]openings[eco_code] = opening_nameprint(f"Loaded {len(openings)} openings from database.")def load_pgn(pgn_text: str) -> chess.pgn.Game:"""27 unmodified linesexcept Exception:return Falseasync def analyze_pgn(pgn_string, fast_mode=True):# PGN → Moves (0.01s, nativ)game = chess.pgn.read_game(io.StringIO(pgn_string))board = game.board()2 unmodified linesengine = chess.engine.SimpleEngine.popen_uci(engine_path)analysis = []# Get initial evaluation from White's perspectiveinfo = engine.analyse(board, chess.engine.Limit(time=0.1))4 unmodified linesboard.push(move)time_limit = 0.1 if fast_mode else 1.0info = engine.analyse(board, chess.engine.Limit(time=time_limit))current_wp_eval = info['score'].white().score(mate_score=10000)is_blunder = False9 unmodified linesif (current_wp_eval - last_wp_eval) > 100:is_blunder = Trueanalysis.append({'nr': i+1,'move': str(move),'fen': board.fen(),'eval': info['score'].relative.score(mate_score=10000)/100,'best_move': str(info['pv'][0]) if info.get('pv') else None,'is_blunder': is_blunder})1 unmodified linelast_wp_eval = current_wp_evalengine.quit()return analysisasync def analyze_fen_position(fen_string: str, analysis_time: float = 3.0):16 unmodified lines'variation': [str(move) for move in info['pv']] if info['pv'] else []}def get_opening_name(eco_code: str) -> str:"""Return opening name for given ECO code using the loaded openings dict."""return openings.get(eco_code, "Unknown Opening")def render_board(fen: str) -> str:"""Render a chess position from FEN to SVG."""board = chess.Board(fen)return chess.svg.board(board,size=550,)def analyze_game_handler(pgn):8 unmodified lines# yield resultsif __name__ == "__main__":import os5 unmodified lines67891011123 unmodified lines16171819202122232425262727 unmodified lines5556575859606162636465666768692 unmodified lines727374757677784 unmodified lines83848586878889909 unmodified lines1001011021031041051061071081091101111121131141151161171181191201 unmodified line12212312412512612712816 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671688 unmodified lines1771781791801811821831845 unmodified linesimport ioimport osimport sysimport re# Dictionary to hold openings dataopenings = {}3 unmodified linesprint("Loading openings database...")with open("data/openings/all.tsv", "r", encoding="utf-8") as file:for line in file.readlines():# Each line format: ECO_CODE \t Opening Name \t PGN \t UCI \t Opening Moves (FEN)parts = line.strip().split("\t")if len(parts) >= 5:eco_code = parts[0]openings[eco_code] = { "opening_name": parts[1], "pgn": parts[2], "fen": parts[4]}print(f"Loaded {len(openings)} openings from database.")def load_pgn(pgn_text: str) -> chess.pgn.Game:"""27 unmodified linesexcept Exception:return Falsedef explain(delta):if delta <= -1.5:return "Serious blunder losing material or initiative"if delta <= -1:return "Positional disadvantage or pawn loss"return "Reasonable move"async def analyze_pgn(pgn_string):# PGN → Moves (0.01s, nativ)game = chess.pgn.read_game(io.StringIO(pgn_string))board = game.board()2 unmodified linesengine = chess.engine.SimpleEngine.popen_uci(engine_path)analysis = []critical = []# Get initial evaluation from White's perspectiveinfo = engine.analyse(board, chess.engine.Limit(time=0.1))4 unmodified linesboard.push(move)time_limit = 0.1info = engine.analyse(board, chess.engine.Limit(time=time_limit))current_wp_eval = info['score'].white().score(mate_score=10000)is_blunder = False9 unmodified linesif (current_wp_eval - last_wp_eval) > 100:is_blunder = Trueif is_blunder == True:critical.append({"move": i+1,"played": str(move),"best": str(info['pv'][0]) if info.get('pv') else None,"eval_before": last_wp_eval/100,"eval_after": current_wp_eval/100})analysis.append({'nr': i+1,'move': str(move),'fen': board.fen(),'eval_before': last_wp_eval/100,'eval': current_wp_eval/100,'best_move': str(info['pv'][0]) if info.get('pv') else None,'is_blunder': is_blunder})1 unmodified linelast_wp_eval = current_wp_evalengine.quit()return analysis, criticalasync def analyze_fen_position(fen_string: str, analysis_time: float = 3.0):16 unmodified lines'variation': [str(move) for move in info['pv']] if info['pv'] else []}def get_opening(pgn: str) -> str:"""Return opening name for given ECO code inside PGN using the loaded openings dict."""pattern = re.compile(r'\[ECO\s+"([^"]+)"\]')matches = pattern.findall(pgn)if len(matches) > 0:eco_code = matches[0]else:return "Unkown Opening"return openings.get(eco_code, "Unknown Opening")def render_board(fen: str, size: int = 550) -> str:"""Render a chess position from FEN to SVG."""board = chess.Board(fen)return chess.svg.board(board,size=size,)def analyze_game_handler(pgn):8 unmodified lines# yield resultsload_openings_db()if __name__ == "__main__":import os
README.md+21
app.py+68-10
data/openings/all.tsv+2-2
examples/travelhawk-chess.com.pgnAdded+20
src/ai_agents.py → src/ai.pyRenamed+21-5
src/chess_engine.py+42-14