ChessCoach / src /chess_engine.py
Michael Falk
Update
cf2167d
Raw History Blame Contribute Delete
7.1 kB
import chess
import chess.pgn
import chess.engine
import chess.svg
import asyncio
import io
import os
import sys
import re
# Dictionary to hold openings data
openings = {}
def load_openings_db():
"""Load openings database into dictionary (eco -> opening name)."""
print("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:
"""
Load a PGN game from the provided text.
"""
pgn = io.StringIO(pgn_text)
game = chess.pgn.read_game(pgn)
if game is None:
raise ValueError("Invalid PGN format")
return game
def get_moves(game: chess.pgn.Game) -> list:
"""
Extract the list of FEN strings for each move in the game.
"""
moves = []
board = game.board()
for move in game.mainline_moves():
board.push(move)
moves.append(board.fen())
return moves
def is_valid_pgn(pgn_text: str) -> bool:
"""
Check if the provided PGN text is valid.
"""
try:
game = load_pgn(pgn_text)
return game is not None and len(game.errors) == 0
except Exception:
return False
def 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()
engine_path = os.environ.get("CHESS_ENGINE_PATH", "stockfish")
engine = chess.engine.SimpleEngine.popen_uci(engine_path)
analysis = []
critical = []
# Get initial evaluation from White's perspective
info = engine.analyse(board, chess.engine.Limit(time=0.1))
last_wp_eval = info['score'].white().score(mate_score=10000)
for i, move in enumerate(game.mainline_moves()):
turn_before_move = board.turn
board.push(move)
time_limit = 0.1
info = engine.analyse(board, chess.engine.Limit(time=time_limit))
current_wp_eval = info['score'].white().score(mate_score=10000)
is_blunder = False
if last_wp_eval is not None and current_wp_eval is not None:
# If white moved, the eval should not drop a lot
if turn_before_move == chess.WHITE:
# Drop of more than 1 pawn (100 centipawns)
if (last_wp_eval - current_wp_eval) > 70:
is_blunder = True
# If black moved, the eval should not rise a lot
else:
# Rise of more than 1 pawn (100 centipawns)
if (current_wp_eval - last_wp_eval) > 70:
is_blunder = True
if 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
})
last_wp_eval = current_wp_eval
engine.quit()
return analysis, critical
async def analyze_fen_position(fen_string: str, analysis_time: float = 3.0):
"""
Analyzes a single chess position from a FEN string for a given time.
"""
board = chess.Board(fen_string)
engine_path = os.environ.get("CHESS_ENGINE_PATH", "stockfish")
engine = chess.engine.SimpleEngine.popen_uci(engine_path)
info = engine.analyse(board, chess.engine.Limit(time=analysis_time))
engine.quit()
return {
'fen': board.fen(),
'eval': info['score'].relative.score(mate_score=10000)/100,
'best_move': str(info['pv'][0]) if info['pv'] else None,
'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 = 350) -> 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):
# parse PGN
yield ui_helpers.set_value("♞ Parsing Game...")
pgn_text = load_pgn(pgn)
yield ui_helpers.set_value("Start analysis...")
analysis_result = asyncio.run(analyze_pgn(pgn_text))
yield ui_helpers.set_value("Analysis complete.")
yield ui_helpers.set_value(analysis_result)
# run LLM
# yield results
load_openings_db()
if __name__ == "__main__":
import os
load_openings_db()
# --- New code to set CHESS_ENGINE_PATH for testing purposes ---
stockfish_path = os.path.join(sys.path[0], "stockfish", "windows", "stockfish-windows-x86-64-avx2.exe")
if os.path.isfile(stockfish_path):
os.environ["CHESS_ENGINE_PATH"] = stockfish_path
print(f"Test: Set CHESS_ENGINE_PATH to: {stockfish_path}")
else:
print(f"Test: Warning: Stockfish binary not found at '{stockfish_path}'. Please ensure it's in the correct location or in system PATH.")
# --- End of new code ---
# Example usage
example_pgn = """[Event "Example"]
[Event "Live Chess"]
[Site "Chess.com"]
[Date "2025.11.21"]
[Round "?"]
[White "pablitsky"]
[Black "travelhawk"]
[Result "0-1"]
[TimeControl "180+2"]
[WhiteElo "959"]
[BlackElo "919"]
[Termination "travelhawk gewinnt auf Zeit"]
[ECO "A21"]
[EndTime "22:18:21 GMT+0000"]
[Link "https://www.chess.com/game/live/145800054980?move=0"]
1. c4 e5 2. Nc3 Bb4 3. a3 Bxc3 4. dxc3 d6 5. e4 Bg4 6. f3 Be6 7. h4 Nf6 8. Be3
Nbd7 9. Qd2 Nh5 10. Bf2 O-O 11. O-O-O a6 12. g4 Nf4 13. Nh3 Nxh3 14. Rxh3 h5 15.
Rg3 Qxh4 16. Rh3 Qe7 17. Rxh5 b5 18. Bh4 Qe8 19. g5 g6 20. Rh6 Bxc4 21. Bf2 Nc5
22. Bxc5 dxc5 23. Qh2 f5 24. Rh8+ Kf7 25. Qh7+ Ke6 26. Rxf8 Qxf8 27. Qxg6+ Ke7
28. exf5 Bf7 29. f6+ Ke8 0-1
"""
analysis_result = asyncio.run(analyze_pgn(example_pgn, fast_mode=True))
for move_analysis in analysis_result:
print(move_analysis)