Spaces:
Sleeping
Sleeping
Update main.py
Browse files123445672 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748131415161750515253545518192021222357585960616224252664656667686970717227287475762930313233803435363738853940414289434445467 unmodified lines545556103575810559606162631101116465661131141151161176768119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177697071721807374757677787918718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824980818283848586878889258909192939495969798991001011022692701031041051061072751081091101111122771131141151161172821181191201212861221231241252902912921261271281291303 unmodified lines134135136302303304137138139140141307142143310311312313314315316144145146147148320321322149150324325326327328329330331332151152153334335336154155156339340341157158159344160161162348163164351352353354355356357358359360361362165166167364168169367368369370170171172173374174376377378379380381175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308394309310311398399400401402403404312313406407408409314315316411317318319415320417418419321322420421323423424425426324325428326327328329432433434330331436437438439440332333442443444445446334335336337448449450451452453454338339455456457340341460461342343463464465466467468469470471472473474475344345346478479347481348483484349350486487488489490491492493494495496497351352499500353502503504505506507508509510354355356357513514515516517518519358359521360361524362363364365from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dictfrom typing import Optional, List, Dict, Tupleimport osimport mathimport chess2 unmodified linesimport jsonfrom contextlib import asynccontextmanager
@asynccontextmanagerasync def lifespan(app: FastAPI): # Startup: Initialize the engine pool await pool.start() yield # Shutdown: Clean up the engine pool await pool.stop()
app = FastAPI(title="Deepcastle Engine API", lifespan=lifespan)class ConnectionManager: def __init__(self): self.active_connections: Dict[str, List[WebSocket]] = {}
async def connect(self, websocket: WebSocket, match_id: str): await websocket.accept() if match_id not in self.active_connections: self.active_connections[match_id] = [] self.active_connections[match_id].append(websocket)
def disconnect(self, websocket: WebSocket, match_id: str): if match_id in self.active_connections: if websocket in self.active_connections[match_id]: self.active_connections[match_id].remove(websocket) if not self.active_connections[match_id]: del self.active_connections[match_id]
async def broadcast(self, message: str, match_id: str, exclude: WebSocket = None): if match_id in self.active_connections: for connection in self.active_connections[match_id]: if connection != exclude: try: await connection.send_text(message) except Exception: pass
manager = ConnectionManager()# βββ 1. SERVER CONFIGURATION βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# These variables define the paths for the engine and the neural network weights.ENGINE_PATH = os.environ.get("ENGINE_PATH", "/app/engine/deepcastle")NNUE_PATH = os.environ.get("NNUE_PATH", "/app/engine/output.nnue")
@app.websocket("/ws/{match_id}")async def websocket_endpoint(websocket: WebSocket, match_id: str): await manager.connect(websocket, match_id) room = manager.active_connections.get(match_id, []) # Notify others that someone joined await manager.broadcast(json.dumps({"type": "join"}), match_id, exclude=websocket)# βββ 2. OPENINGS DATABASE βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# This loads a pre-populated opening book so the bot can respond instantly during theory.openings_db = {}openings_path = os.path.join(os.path.dirname(__file__), "openings.json")if os.path.exists(openings_path): try: while True: data = await websocket.receive_text() await manager.broadcast(data, match_id, exclude=websocket) except WebSocketDisconnect: manager.disconnect(websocket, match_id) await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id) with open(openings_path, "r", encoding="utf-8") as f: openings_db = json.load(f) except Exception: manager.disconnect(websocket, match_id) await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id)
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],) pass
# Paths relative to the Docker containerENGINE_PATH = os.environ.get("ENGINE_PATH", "/app/engine/deepcastle")NNUE_PATH = os.environ.get("NNUE_PATH", "/app/engine/output.nnue")# βββ 3. PYDANTIC MODELS (Data Structures) βββββββββββββββββββββββββββββββββββββββββββ# Used for input validation and defining the exact format of the JSON responses.
class MoveRequest(BaseModel): fen: str time: float = 1.0 # seconds time: float = 1.0 # Seconds the engine will search depth: Optional[int] = None
class MoveResponse(BaseModel): bestmove: str score: float score: float # Pawns (+1.0 for White, -1.0 for Black) depth: int nodes: int nps: int pv: str pv: str # Principal Variation (best sequence of moves) mate_in: Optional[int] = None opening: Optional[str] = None
7 unmodified lines move_num: int san: str best_move: str classification: str classification: str # "Brilliant", "Great", "Best", etc. opening: Optional[str] = None cpl: float cpl: float # Centipawn Loss (0 = perfect) score_before: float score_after: float
class AnalyzeResponse(BaseModel): accuracy: float estimated_elo: int accuracy: float # Lichess-style (0-100) estimated_elo: int # Calibrated Performance Rating moves: List[MoveAnalysis] counts: Dict[str, int]
@app.get("/")def home(): return {"status": "online", "engine": "Deepcastle Hybrid Neural", "platform": "Hugging Face Spaces"} counts: Dict[str, int] # Count of each classification (2 Blunders, etc.)
@app.get("/health")def health(): if not os.path.exists(ENGINE_PATH): return {"status": "error", "message": "Engine binary not found"} return {"status": "ok", "engine": "Deepcastle"}
class EnginePool: def __init__(self, size=4): self.size = size self.engines = asyncio.Queue() self.all_engines = []
async def start(self): print(f"Initializing engine pool with {self.size} processes...") for i in range(self.size): try: engine = await self._create_engine() await self.engines.put(engine) self.all_engines.append(engine) print(f" [+] Engine {i+1}/{self.size} ready.") # Give the system some room to breathe between processes await asyncio.sleep(0.5) except Exception as e: print(f" [!] Failed to start engine {i+1}: {e}")
async def _create_engine(self): if not os.path.exists(ENGINE_PATH): raise Exception("Engine binary not found") transport, engine = await chess.engine.popen_uci(ENGINE_PATH) if os.path.exists(NNUE_PATH): try: # Set Hash to 512 as requested, keep Threads to 1 to avoid CPU stalling await engine.configure({"EvalFile": NNUE_PATH, "Hash": 512, "Threads": 1}) except Exception: pass return engine
@asynccontextmanager async def acquire(self): engine = await self.engines.get() try: yield engine finally: # Check if engine is still alive, if not, restart it try: await self.engines.put(engine) except Exception: # If engine is dead, we could restart here, but for now just put back await self.engines.put(await self._create_engine())
async def stop(self): print("Shutting down engine pool...") for engine in self.all_engines: try: await engine.quit() except: pass
pool = EnginePool(size=4)# βββ 4. CORE MATH & LOGIC HELPERS ββββββββββββββββββββββββββββββββββββββββββββββββββ# These functions calculate win percentages, accuracy, and calibrated Elo scores.
def get_normalized_score(info) -> tuple[float, Optional[int]]: """Returns the score from White's perspective in centipawns.""" """Normalizes UCI score to centipawns from White's perspective.""" if "score" not in info: return 0.0, None raw = info["score"].white() if raw.is_mate(): m = raw.mate() or 0 return (10000.0 if m > 0 else -10000.0), m return raw.score() or 0.0, None
# βββ Engine Inference Route ββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest): try: async with pool.acquire() as engine: board = chess.Board(request.fen) limit = chess.engine.Limit(time=request.time, depth=request.depth) result = await engine.play(board, limit) info = await engine.analyse(board, limit) # From White's perspective in CP -> converted to Pawns for UI score_cp, mate_in = get_normalized_score(info) depth = info.get("depth", 0) nodes = info.get("nodes", 0) nps = info.get("nps", 0)
pv_board = board.copy() pv_parts = [] for m in info.get("pv", [])[:5]: if m in pv_board.legal_moves: try: pv_parts.append(pv_board.san(m)) pv_board.push(m) except Exception: break else: break pv = " ".join(pv_parts)
score_pawns = score_cp / 100.0 if abs(score_cp) < 9900 else (100.0 if score_cp > 0 else -100.0) board_fen_only = board.fen().split(" ")[0] opening_name = openings_db.get(board_fen_only)
return MoveResponse( bestmove=result.move.uci(), score=score_pawns, depth=depth, nodes=nodes, nps=nps, pv=pv, mate_in=mate_in, opening=opening_name ) except Exception as e: print(f"Error: {e}") raise HTTPException(status_code=500, detail=str(e))
import mathimport jsonimport osfrom typing import Optional, List, Tuple
openings_db = {}openings_path = os.path.join(os.path.dirname(__file__), "openings.json")if os.path.exists(openings_path): try: with open(openings_path, "r", encoding="utf-8") as f: openings_db = json.load(f) except Exception as e: pass return float(raw.score() or 0.0), None
def get_win_percentage_from_cp(cp: int) -> float: """AS-UCI win chance formula (0.0 to 100.0).""" cp_ceiled = max(-1000, min(1000, cp)) MULTIPLIER = -0.00368208 win_chances = 2.0 / (1.0 + math.exp(MULTIPLIER * cp_ceiled)) - 1.0 return 50.0 + 50.0 * win_chances
def get_move_accuracy(win_pct_before: float, win_pct_after: float, is_white_move: bool) -> float: """Lichess-style win%-based per-move accuracy (0β100).""" """Lichess-style per-move accuracy calculation using exponential decay.""" if is_white_move: diff = win_pct_before - win_pct_after else: diff = (100.0 - win_pct_before) - (100.0 - win_pct_after) # Formula: 103.16 * exp(-0.04 * diff) - 3.16 accuracy = 103.1668 * math.exp(-0.04354 * max(0.0, diff)) - 3.1669 return max(0.0, min(100.0, accuracy))
def get_win_percentage(info: dict) -> float: """Extracts win percentage from engine info dictionary.""" score = info.get("score") if not score: return 50.0 if not score: return 50.0 white_score = score.white() if white_score.is_mate(): mate_val = white_score.mate() return 100.0 if mate_val > 0 else 0.0 return get_win_percentage_from_cp(white_score.score()) return get_win_percentage_from_cp(white_score.score() or 0)
# βββ 5. MOVE CLASSIFICATION HELPERS βββββββββββββββββββββββββββββββββββββββββββββββ# These identify Brilliant moves, Sacrifices, Blunders, and Book moves.
def is_losing_or_alt_winning(pos_win_pct: float, alt_win_pct: float, is_white_move: bool) -> bool:def is_losing_or_alt_winning(pos_win_pct, alt_win_pct, is_white_move) -> bool: is_losing = pos_win_pct < 50.0 if is_white_move else pos_win_pct > 50.0 is_alt_winning = alt_win_pct > 97.0 if is_white_move else alt_win_pct < 3.0 return is_losing or is_alt_winning
def get_has_changed_outcome(last_win_pct: float, pos_win_pct: float, is_white_move: bool) -> bool:def get_has_changed_outcome(last_win_pct, pos_win_pct, is_white_move) -> bool: diff = (pos_win_pct - last_win_pct) * (1 if is_white_move else -1) return diff > 10.0 and ((last_win_pct < 50.0 and pos_win_pct > 50.0) or (last_win_pct > 50.0 and pos_win_pct < 50.0))
def get_is_only_good_move(pos_win_pct: float, alt_win_pct: float, is_white_move: bool) -> bool:def get_is_only_good_move(pos_win_pct, alt_win_pct, is_white_move) -> bool: diff = (pos_win_pct - alt_win_pct) * (1 if is_white_move else -1) return diff > 10.0
def is_simple_recapture(fen_two_moves_ago: str, previous_move: chess.Move, played_move: chess.Move) -> bool: if previous_move.to_square != played_move.to_square: return Falsedef is_simple_recapture(fen_two_moves_ago, previous_move, played_move) -> bool: if previous_move.to_square != played_move.to_square: return False b = chess.Board(fen_two_moves_ago) return b.piece_at(previous_move.to_square) is not None
3 unmodified lines b = sum(values.get(p.piece_type, 0) for p in board.piece_map().values() if p.color == chess.BLACK) return w - b
def get_is_piece_sacrifice(board: chess.Board, played_move: chess.Move, best_pv: list) -> bool: if not best_pv: return Falsedef get_is_piece_sacrifice(board: chess.Board, played_move, best_pv: list) -> bool: """Checks if a move is a genuine piece sacrifice by looking at the resulting PV material.""" if not best_pv: return False start_diff = get_material_difference(board) white_to_play = board.turn == chess.WHITE sim_board = board.copy() moves = [played_move] + best_pv if len(moves) % 2 == 1: moves = moves[:-1] captured_w = [] captured_b = [] non_capturing = 1 if len(moves) % 2 == 1: moves = moves[:-1] captured_w, captured_b = [], [] for m in moves: if m in sim_board.legal_moves: captured_piece = sim_board.piece_at(m.to_square) if sim_board.is_en_passant(m): captured_piece = chess.Piece(chess.PAWN, not sim_board.turn) if sim_board.is_en_passant(m): captured_piece = chess.Piece(chess.PAWN, not sim_board.turn) if captured_piece: if sim_board.turn == chess.WHITE: captured_b.append(captured_piece.piece_type) else: captured_w.append(captured_piece.piece_type) non_capturing = 1 else: non_capturing -= 1 if non_capturing < 0: break if sim_board.turn == chess.WHITE: captured_b.append(captured_piece.piece_type) else: captured_w.append(captured_piece.piece_type) sim_board.push(m) else: break else: break for p in captured_w[:]: if p in captured_b: captured_w.remove(p) captured_b.remove(p) captured_w.remove(p); captured_b.remove(p) if abs(len(captured_w) - len(captured_b)) <= 1 and all(p == chess.PAWN for p in captured_w + captured_b): return False end_diff = get_material_difference(sim_board) mat_diff = end_diff - start_diff player_rel = mat_diff if white_to_play else -mat_diff return player_rel < 0
def get_move_classification( last_win_pct: float, pos_win_pct: float, is_white_move: bool, played_move: chess.Move, best_move_before: chess.Move, alt_win_pct: Optional[float], fen_two_moves_ago: Optional[str], uci_next_two_moves: Optional[Tuple[chess.Move, chess.Move]], board_before_move: chess.Board, best_pv_after: list) -> str:def get_move_classification(last_win_pct, pos_win_pct, is_white_move, played_move, best_move_before, alt_win_pct, fen_two_moves_ago, uci_next_two_moves, board_before_move, best_pv_after) -> str: """Classifies a move based on win% change and engine principal variation.""" diff = (pos_win_pct - last_win_pct) * (1 if is_white_move else -1)
if alt_win_pct is not None and diff >= -2.0: if get_is_piece_sacrifice(board_before_move, played_move, best_pv_after): if not is_losing_or_alt_winning(pos_win_pct, alt_win_pct, is_white_move): return "Brilliant"
if alt_win_pct is not None and diff >= -2.0: if not is_losing_or_alt_winning(pos_win_pct, alt_win_pct, is_white_move): return "Brilliant" is_recapture = False if fen_two_moves_ago and uci_next_two_moves: is_recapture = is_simple_recapture(fen_two_moves_ago, uci_next_two_moves[0], uci_next_two_moves[1]) if not is_recapture and not is_losing_or_alt_winning(pos_win_pct, alt_win_pct, is_white_move): if get_has_changed_outcome(last_win_pct, pos_win_pct, is_white_move) or get_is_only_good_move(pos_win_pct, alt_win_pct, is_white_move): return "Great"
if best_move_before and played_move == best_move_before: return "Best"
if get_has_changed_outcome(last_win_pct, pos_win_pct, is_white_move) or get_is_only_good_move(pos_win_pct, alt_win_pct, is_white_move): return "Great" if best_move_before and played_move == best_move_before: return "Best" if diff < -20.0: return "Blunder" if diff < -10.0: return "Mistake" if diff < -5.0: return "Inaccuracy" if diff < -2.0: return "Good" return "Excellent"
# βββ 6. MULTIPLAYER CONNECTION MANAGER βββββββββββββββββββββββββββββββββββββββββββββββ# Handles websocket routing for playing against friends in real-time rooms.class ConnectionManager: def __init__(self): self.active_connections: Dict[str, List[WebSocket]] = {} async def connect(self, websocket: WebSocket, match_id: str): await websocket.accept() if match_id not in self.active_connections: self.active_connections[match_id] = [] self.active_connections[match_id].append(websocket) def disconnect(self, websocket: WebSocket, match_id: str): if match_id in self.active_connections: if websocket in self.active_connections[match_id]: self.active_connections[match_id].remove(websocket) if not self.active_connections[match_id]: del self.active_connections[match_id] async def broadcast(self, message: str, match_id: str, exclude: WebSocket = None): if match_id in self.active_connections: for connection in self.active_connections[match_id]: if connection != exclude: try: await connection.send_text(message) except Exception: pass
manager = ConnectionManager()
# βββ 7. ENGINE POOL (Orchestrator) ββββββββββββββββββββββββββββββββββββββββββββββββββ# Maintains 4 persistent engine processes for high-concurrency instant response.class EnginePool: def __init__(self, size=4): self.size = size self.engines = asyncio.Queue() self.all_engines = [] async def start(self): print(f"Initializing bulletproof engine pool with {self.size} processes...") for i in range(self.size): try: engine = await self._create_engine() await self.engines.put(engine) self.all_engines.append(engine) print(f" [+] Engine {i+1}/{self.size} ready.") await asyncio.sleep(0.5) # Prevent CPU thrashing on boot except Exception as e: print(f" [!] Failed to start engine {i+1}: {e}") async def _create_engine(self): if not os.path.exists(ENGINE_PATH): raise Exception("Engine binary not found") transport, engine = await chess.engine.popen_uci(ENGINE_PATH) if os.path.exists(NNUE_PATH): try: await engine.configure({"EvalFile": NNUE_PATH, "Hash": 512, "Threads": 1}) except Exception: pass return engine @asynccontextmanager async def acquire(self): """Yields an engine from the pool and ensures it's returned or restarted.""" engine = await self.engines.get() try: yield engine finally: try: await self.engines.put(engine) except Exception: await self.engines.put(await self._create_engine()) async def stop(self): for engine in self.all_engines: try: await engine.quit() except: pass
pool = EnginePool(size=4)
# βββ 8. FASTAPI LIFESPAN CONTROLLER ββββββββββββββββββββββββββββββββββββββββββββββββββ# Controls what happens when the server starts and stops on Hugging Face.@asynccontextmanagerasync def lifespan(app: FastAPI): # Initialize the engine pool first await pool.start() yield # Cleanup on shutdown await pool.stop()
app = FastAPI(title="Deepcastle Engine API", lifespan=lifespan)app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
# βββ 9. API ROUTES ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.websocket("/ws/{match_id}")async def websocket_endpoint(websocket: WebSocket, match_id: str): """Handles real-time friend play relay.""" await manager.connect(websocket, match_id) await manager.broadcast(json.dumps({"type": "join"}), match_id, exclude=websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(data, match_id, exclude=websocket) except WebSocketDisconnect: manager.disconnect(websocket, match_id) await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id) except Exception: manager.disconnect(websocket, match_id)
@app.get("/")def home(): return {"status": "online", "engine": "Deepcastle Pro", "platform": "Hugging Face"}
@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest): """Fetches the best engine move for a given FEN position.""" try: async with pool.acquire() as engine: board = chess.Board(request.fen) limit = chess.engine.Limit(time=request.time, depth=request.depth) result = await engine.play(board, limit) info = await engine.analyse(board, limit) score_cp, mate_in = get_normalized_score(info) pv_board = board.copy() pv_parts = [] for m in info.get("pv", [])[:5]: if m in pv_board.legal_moves: try: pv_parts.append(pv_board.san(m)); pv_board.push(m) except Exception: break else: break score_pawns = score_cp / 100.0 if abs(score_cp) < 9900 else (100.0 if score_cp > 0 else -100.0) return MoveResponse(bestmove=result.move.uci(), score=score_pawns, depth=info.get("depth", 0), nodes=info.get("nodes", 0), nps=info.get("nps", 0), pv=" ".join(pv_parts), mate_in=mate_in, opening=openings_db.get(board.fen().split(" ")[0])) except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest): """Performs deep game analysis, classifies moves, and estimates performance Elo.""" try: async with pool.acquire() as engine: board = chess.Board(request.start_fen) if request.start_fen else chess.Board() limit = chess.engine.Limit(time=request.time_per_move) analysis_results = [] infos_before = await engine.analyse(board, limit, multipv=2) infos_before = infos_before if isinstance(infos_before, list) else [infos_before] counts = { "Book": 0, "Brilliant": 0, "Great": 0, "Best": 0, "Excellent": 0, "Good": 0, "Inaccuracy": 0, "Mistake": 0, "Blunder": 0 }
counts = {"Book": 0, "Brilliant": 0, "Great": 0, "Best": 0, "Excellent": 0, "Good": 0, "Inaccuracy": 0, "Mistake": 0, "Blunder": 0} player_is_white = (request.player_color.lower() == "white") fen_history = [board.fen()] move_history = [] player_move_accuracies: List[float] = [] player_cpls: List[float] = [] # keep for estimated_elo fen_history, move_history = [board.fen()], [] player_move_accuracies, player_cpls = [], [] current_score, _ = get_normalized_score(infos_before[0])
for i, san_move in enumerate(request.moves): is_white_turn = board.turn == chess.WHITE is_player_turn = is_white_turn if player_is_white else not is_white_turn score_before = current_score try: move = board.parse_san(san_move) except Exception: try: move = board.parse_san(san_move) except Exception: break break
info_dict = infos_before[0] pv_list = info_dict.get("pv", []) best_move_before = pv_list[0] if pv_list else None score_before, _ = get_normalized_score(info_dict) best_move_before = info_dict.get("pv", [None])[0] win_pct_before = get_win_percentage(info_dict) alt_win_pct_before: Optional[float] = None alt_win_pct_before = None if len(infos_before) > 1: for line in infos_before: if line.get("pv") and line.get("pv")[0] != move: alt_win_pct_before = get_win_percentage(line) break
alt_win_pct_before = get_win_percentage(line); break board_before_move = board.copy() board.push(move) move_history.append(move) fen_history.append(board.fen()) board.push(move); move_history.append(move); fen_history.append(board.fen()) infos_after_raw = await engine.analyse(board, limit, multipv=2) infos_after: List[dict] = infos_after_raw if isinstance(infos_after_raw, list) else [infos_after_raw] info_after_dict: dict = infos_after[0] win_pct_after = get_win_percentage(info_after_dict) score_after, _ = get_normalized_score(info_after_dict) infos_after = infos_after_raw if isinstance(infos_after_raw, list) else [infos_after_raw] info_after_dict = infos_after[0] win_pct_after, (score_after, _) = get_win_percentage(info_after_dict), get_normalized_score(info_after_dict) current_score = score_after best_pv_after = info_after_dict.get("pv", []) fen_two_moves_ago = None uci_next_two_moves = None if len(move_history) >= 2: fen_two_moves_ago = fen_history[-3] uci_next_two_moves = (move_history[-2], move_history[-1]) fen_two_moves_ago = fen_history[-3] if len(move_history) >= 2 else None uci_next_two_moves = (move_history[-2], move_history[-1]) if len(move_history) >= 2 else None
cls = "Book" opening_name = None board_fen_only = board.fen().split(" ")[0] if board_fen_only in openings_db: cls = "Book" opening_name = openings_db[board_fen_only] cls, opening_name = "Book", openings_db[board_fen_only] else: cls = get_move_classification( last_win_pct=win_pct_before, pos_win_pct=win_pct_after, is_white_move=is_white_turn, played_move=move, best_move_before=best_move_before, alt_win_pct=alt_win_pct_before, fen_two_moves_ago=fen_two_moves_ago, uci_next_two_moves=uci_next_two_moves, board_before_move=board_before_move, best_pv_after=best_pv_after ) cls, opening_name = get_move_classification(win_pct_before, win_pct_after, is_white_turn, move, best_move_before, alt_win_pct_before, fen_two_moves_ago, uci_next_two_moves, board_before_move, info_after_dict.get("pv", [])), None move_gain = score_after - score_before if is_white_turn else score_before - score_after cpl = max(0.0, min(1000.0, -move_gain))
# Lichess-style per-move accuracy using win% move_acc = get_move_accuracy(win_pct_before, win_pct_after, is_white_turn)
if is_player_turn: player_move_accuracies.append(move_acc) player_cpls.append(cpl) player_move_accuracies.append(move_acc); player_cpls.append(cpl) counts[cls] = counts.get(cls, 0) + 1 analysis_results.append(MoveAnalysis( move_num=i+1, san=san_move, fen=board.fen(), classification=cls, cpl=float(cpl), score_before=float(score_before / 100.0), score_after=float(score_after / 100.0), best_move=best_move_before.uci() if best_move_before else "", opening=opening_name )) analysis_results.append(MoveAnalysis(move_num=i+1, san=san_move, best_move=best_move_before.uci() if best_move_before else "", classification=cls, opening=opening_name, cpl=float(cpl), score_before=float(score_before / 100.0), score_after=float(score_after / 100.0))) infos_before = infos_after
# NEW β Lichess win%-based accuracy if player_move_accuracies: # Lichess uses harmonic mean blended with arithmetic mean arithmetic_mean = sum(player_move_accuracies) / len(player_move_accuracies) harmonic_mean = len(player_move_accuracies) / sum(1.0 / max(a, 0.1) for a in player_move_accuracies) accuracy = (arithmetic_mean + harmonic_mean) / 2.0 else: accuracy = 0.0
# Elo from avg CPL using exponential decay calibrated to your 3600 engine # Toughened constant from -0.01 to -0.015 for more realistic scoring accuracy = ( (sum(player_move_accuracies) / len(player_move_accuracies)) + (len(player_move_accuracies) / sum(1.0 / max(a, 0.1) for a in player_move_accuracies)) ) / 2.0 else: accuracy = 0.0 avg_cpl = sum(player_cpls) / max(1, len(player_cpls)) estimated_elo = int(max(400, min(3600, round(3600 * math.exp(-0.015 * avg_cpl)))))
return AnalyzeResponse( accuracy=round(accuracy, 1), estimated_elo=estimated_elo, moves=analysis_results, counts=counts ) return AnalyzeResponse(accuracy=round(accuracy, 1), estimated_elo=estimated_elo, moves=analysis_results, counts=counts) except Exception as e: print(f"Analysis Error: {e}") raise HTTPException(status_code=500, detail=str(e))
# βββ 10. MAIN ENTRY POINT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)main.py+198-360