Spaces:
Paused
Paused
Download modules/analysis/stockfish_wrapper.py from SamilG2/BACKEND-CheckScan: direct link, hf CLI and curl.
- Browser
- Download file 6.76 kB
-
https://huggingface.co/spaces/SamilG2/BACKEND-CheckScan/resolve/main/modules/analysis/stockfish_wrapper.py
- Command line
-
hf download hf://spaces/SamilG2/BACKEND-CheckScan/modules/analysis/stockfish_wrapper.py
-
curl -L -o stockfish_wrapper.py https://huggingface.co/spaces/SamilG2/BACKEND-CheckScan/resolve/main/modules/analysis/stockfish_wrapper.py
6.76 kB
| """Wrapper UCI para Stockfish usando python-chess. | |
| Singleton lazy: el motor se inicia en la primera llamada y se reutiliza | |
| entre requests. Si el binario no existe, se lanza FileNotFoundError con | |
| un mensaje claro para que el frontend lo reporte. | |
| """ | |
| import os | |
| import threading | |
| import chess | |
| import chess.engine | |
| import chess.pgn | |
| import io | |
| from config import STOCKFISH_PATH, STOCKFISH_DEPTH, STOCKFISH_THREADS, STOCKFISH_HASH_MB | |
| _engine = None | |
| _lock = threading.Lock() | |
| def _get_engine() -> chess.engine.SimpleEngine: | |
| global _engine | |
| if _engine is not None: | |
| return _engine | |
| with _lock: | |
| if _engine is not None: | |
| return _engine | |
| if not os.path.isfile(STOCKFISH_PATH): | |
| raise FileNotFoundError( | |
| f"Stockfish no encontrado en '{STOCKFISH_PATH}'. " | |
| f"Descargalo de https://stockfishchess.org/download/ y " | |
| f"coloca el binario en backend/engines/ (ver AGENTS.md)." | |
| ) | |
| print(f"[Stockfish] Iniciando motor: {STOCKFISH_PATH}") | |
| eng = chess.engine.SimpleEngine.popen_uci(STOCKFISH_PATH) | |
| eng.configure({"Threads": STOCKFISH_THREADS, "Hash": STOCKFISH_HASH_MB}) | |
| _engine = eng | |
| print(f"[Stockfish] Listo (threads={STOCKFISH_THREADS}, hash={STOCKFISH_HASH_MB}MB, depth={STOCKFISH_DEPTH})") | |
| return _engine | |
| def shutdown(): | |
| """Cierra el motor (llamar al apagar el servidor; opcional).""" | |
| global _engine | |
| if _engine is not None: | |
| try: | |
| _engine.quit() | |
| except Exception: | |
| pass | |
| _engine = None | |
| def _score_to_cp(score: chess.engine.PovScore) -> int: | |
| """Convierte un PovScore a centipawns desde el punto de vista de BLANCAS. | |
| Mate se mapea a ±100000 cp para que las diferencias sigan siendo comparables. | |
| """ | |
| white = score.white() | |
| if white.is_mate(): | |
| mate_in = white.mate() | |
| return 100000 if mate_in > 0 else -100000 | |
| return white.score(mate_score=100000) | |
| def _cp_for_terminal(board: chess.Board) -> int: | |
| """Eval en centipawns para una posición terminal (mate/ahogado/tablas).""" | |
| outcome = board.outcome() | |
| if outcome is None or outcome.winner is None: | |
| return 0 # tablas | |
| return 100000 if outcome.winner == chess.WHITE else -100000 | |
| def analyze_pgn(pgn_text: str, depth: int | None = None) -> dict: | |
| """Analiza un PGN jugada a jugada con Stockfish. | |
| Args: | |
| pgn_text: Movimientos en notación inglesa (SAN). Acepta con o sin headers. | |
| depth: Profundidad. Si es None usa STOCKFISH_DEPTH de config. | |
| Returns: | |
| { | |
| 'depth': int, | |
| 'total_moves': int, | |
| 'moves': [ | |
| { | |
| 'number': int, | |
| 'color': 'white' | 'black', | |
| 'move': str, # SAN jugado | |
| 'eval_antes_cp': int, # eval desde POV blancas, antes de jugar | |
| 'eval_despues_cp': int, # eval desde POV blancas, después de jugar | |
| 'diferencia_cp': int, # eval_despues - eval_antes (signo según color) | |
| 'mejor_jugada': str | None, # SAN de la mejor jugada según Stockfish | |
| 'mejor_eval_cp': int, # eval si se hubiera jugado la mejor | |
| }, | |
| ... | |
| ] | |
| } | |
| """ | |
| engine = _get_engine() | |
| used_depth = depth if depth is not None else STOCKFISH_DEPTH | |
| limit = chess.engine.Limit(depth=used_depth, time=1.0) | |
| # Parsear el PGN. Acepta con headers o solo línea de movimientos. | |
| game = chess.pgn.read_game(io.StringIO(pgn_text)) | |
| if game is None or not list(game.mainline_moves()): | |
| # Intentar como línea suelta de movimientos | |
| board = chess.Board() | |
| moves = [] | |
| for token in pgn_text.split(): | |
| if token.endswith('.') or token.replace('.', '').isdigit(): | |
| continue | |
| try: | |
| moves.append(board.parse_san(token)) | |
| board.push(moves[-1]) | |
| except ValueError: | |
| continue | |
| if not moves: | |
| return {'depth': used_depth, 'total_moves': 0, 'moves': []} | |
| game = chess.pgn.Game() | |
| node = game | |
| for mv in moves: | |
| node = node.add_variation(mv) | |
| board = game.board() | |
| results: list[dict] = [] | |
| for ply_idx, move in enumerate(game.mainline_moves()): | |
| is_white_to_move = board.turn == chess.WHITE | |
| move_san = board.san(move) | |
| # Eval ANTES de la jugada (posición actual) + mejor jugada sugerida | |
| info_before = engine.analyse(board, limit) | |
| score_before = info_before.get("score") | |
| eval_antes_cp = _score_to_cp(score_before) if score_before is not None else 0 | |
| pv = info_before.get("pv") or [] | |
| best_move_san = board.san(pv[0]) if pv else None | |
| # Línea principal (PV) en SAN, para el botón "Explicar" (HU-011): la | |
| # secuencia de mejores jugadas desde esta posición, que el frontend | |
| # reproduce en el tablero. Se limita para no inflar la respuesta. | |
| pv_san = [] | |
| if pv: | |
| tmp = board.copy() | |
| for mv in pv[:8]: # hasta 8 medias jugadas (4 completas) | |
| try: | |
| pv_san.append(tmp.san(mv)) | |
| tmp.push(mv) | |
| except ValueError: | |
| break | |
| # eval_antes_cp ya representa el valor óptimo de esta posición | |
| best_eval_cp = eval_antes_cp | |
| # Aplicar la jugada y evaluar DESPUÉS | |
| board.push(move) | |
| if board.is_game_over(): | |
| eval_despues_cp = _cp_for_terminal(board) | |
| else: | |
| info_after = engine.analyse(board, limit) | |
| score_after = info_after.get("score") | |
| eval_despues_cp = _score_to_cp(score_after) if score_after is not None else eval_antes_cp | |
| # Diferencia desde la perspectiva del jugador que movió. | |
| # Si jugó blancas, perder centipawns es negativo. Si jugó negras, ganar | |
| # centipawns para negras es que white_eval bajó → invertimos signo. | |
| delta = eval_despues_cp - eval_antes_cp | |
| if not is_white_to_move: | |
| delta = -delta | |
| results.append({ | |
| 'number': ply_idx // 2 + 1, | |
| 'color': 'white' if is_white_to_move else 'black', | |
| 'move': move_san, | |
| 'eval_antes_cp': eval_antes_cp, | |
| 'eval_despues_cp': eval_despues_cp, | |
| 'diferencia_cp': delta, | |
| 'mejor_jugada': best_move_san, | |
| 'mejor_eval_cp': best_eval_cp, | |
| 'pv_san': pv_san, | |
| }) | |
| return { | |
| 'depth': used_depth, | |
| 'total_moves': len(results), | |
| 'moves': results, | |
| } | |