Spaces:
Sleeping
Sleeping
Update main.py
Browse files12345672 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091927 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942953 unmodified lines299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dictimport osimport mathimport chess2 unmodified linesimport jsonfrom contextlib import asynccontextmanager@asynccontextmanagerasync def lifespan(app: FastAPI):# Startup: Initialize the engine poolawait pool.start()yield# Shutdown: Clean up the engine poolawait 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:passmanager = ConnectionManager()@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 joinedawait 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)await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_methods=["*"],allow_headers=["*"],)# 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")class MoveRequest(BaseModel):fen: strtime: float = 1.0 # secondsdepth: Optional[int] = Noneclass MoveResponse(BaseModel):bestmove: strscore: floatdepth: intnodes: intnps: intpv: strmate_in: Optional[int] = Noneopening: Optional[str] = None7 unmodified linesmove_num: intsan: strbest_move: strclassification: stropening: Optional[str] = Nonecpl: floatscore_before: floatscore_after: floatclass AnalyzeResponse(BaseModel):accuracy: floatestimated_elo: intmoves: List[MoveAnalysis]counts: Dict[str, int]@app.get("/")def home():return {"status": "online", "engine": "Deepcastle Hybrid Neural", "platform": "Hugging Face Spaces"}@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 = sizeself.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 processesawait 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 stallingawait engine.configure({"EvalFile": NNUE_PATH, "Hash": 512, "Threads": 1})except Exception:passreturn engine@asynccontextmanagerasync def acquire(self):engine = await self.engines.get()try:yield enginefinally:# Check if engine is still alive, if not, restart ittry:await self.engines.put(engine)except Exception:# If engine is dead, we could restart here, but for now just put backawait 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:passpool = EnginePool(size=4)def get_normalized_score(info) -> tuple[float, Optional[int]]:"""Returns the score from White's perspective in centipawns."""if "score" not in info:return 0.0, Noneraw = info["score"].white()if raw.is_mate():m = raw.mate() or 0return (10000.0 if m > 0 else -10000.0), mreturn 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 UIscore_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:breakelse: breakpv = " ".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, Tupleopenings_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:passdef get_win_percentage_from_cp(cp: int) -> float:cp_ceiled = max(-1000, min(1000, cp))MULTIPLIER = -0.00368208win_chances = 2.0 / (1.0 + math.exp(MULTIPLIER * cp_ceiled)) - 1.0return 50.0 + 50.0 * win_chancesdef 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)."""if is_white_move:diff = win_pct_before - win_pct_afterelse:diff = (100.0 - win_pct_before) - (100.0 - win_pct_after)accuracy = 103.1668 * math.exp(-0.04354 * max(0.0, diff)) - 3.1669return max(0.0, min(100.0, accuracy))def get_win_percentage(info: dict) -> float:score = info.get("score")if not score:return 50.0white_score = score.white()if white_score.is_mate():mate_val = white_score.mate()return 100.0 if mate_val > 0 else 0.0return get_win_percentage_from_cp(white_score.score())def is_losing_or_alt_winning(pos_win_pct: float, alt_win_pct: float, is_white_move: bool) -> bool:is_losing = pos_win_pct < 50.0 if is_white_move else pos_win_pct > 50.0is_alt_winning = alt_win_pct > 97.0 if is_white_move else alt_win_pct < 3.0return is_losing or is_alt_winningdef get_has_changed_outcome(last_win_pct: float, pos_win_pct: float, is_white_move: bool) -> 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:diff = (pos_win_pct - alt_win_pct) * (1 if is_white_move else -1)return diff > 10.0def 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 Falseb = chess.Board(fen_two_moves_ago)return b.piece_at(previous_move.to_square) is not None3 unmodified linesb = sum(values.get(p.piece_type, 0) for p in board.piece_map().values() if p.color == chess.BLACK)return w - bdef get_is_piece_sacrifice(board: chess.Board, played_move: chess.Move, best_pv: list) -> bool:if not best_pv:return Falsestart_diff = get_material_difference(board)white_to_play = board.turn == chess.WHITEsim_board = board.copy()moves = [played_move] + best_pvif len(moves) % 2 == 1:moves = moves[:-1]captured_w = []captured_b = []non_capturing = 1for 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 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 = 1else:non_capturing -= 1if non_capturing < 0:breaksim_board.push(m)else:breakfor p in captured_w[:]:if p in captured_b: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 Falseend_diff = get_material_difference(sim_board)mat_diff = end_diff - start_diffplayer_rel = mat_diff if white_to_play else -mat_diffreturn player_rel < 0def 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: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:is_recapture = Falseif 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 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"@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest):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}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_elocurrent_score, _ = get_normalized_score(infos_before[0])for i, san_move in enumerate(request.moves):is_white_turn = board.turn == chess.WHITEis_player_turn = is_white_turn if player_is_white else not is_white_turnscore_before = current_scoretry:move = board.parse_san(san_move)except Exception:breakinfo_dict = infos_before[0]pv_list = info_dict.get("pv", [])best_move_before = pv_list[0] if pv_list else Nonescore_before, _ = get_normalized_score(info_dict)win_pct_before = get_win_percentage(info_dict)alt_win_pct_before: Optional[float] = Noneif 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)breakboard_before_move = board.copy()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)current_score = score_afterbest_pv_after = info_after_dict.get("pv", [])fen_two_moves_ago = Noneuci_next_two_moves = Noneif len(move_history) >= 2:fen_two_moves_ago = fen_history[-3]uci_next_two_moves = (move_history[-2], move_history[-1])cls = "Book"opening_name = Noneboard_fen_only = board.fen().split(" ")[0]if board_fen_only in openings_db:cls = "Book"opening_name = 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)move_gain = score_after - score_before if is_white_turn else score_before - score_aftercpl = 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)counts[cls] = counts.get(cls, 0) + 1analysis_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))infos_before = infos_after# NEW β Lichess win%-based accuracyif player_move_accuracies:# Lichess uses harmonic mean blended with arithmetic meanarithmetic_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.0else: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 scoringavg_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)except Exception as e:print(f"Analysis Error: {e}")raise HTTPException(status_code=500, detail=str(e))if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)12345672 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445467 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291303 unmodified lines134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dict, Tupleimport osimport mathimport chess2 unmodified linesimport jsonfrom contextlib import asynccontextmanager# βββ 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")# βββ 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:with open(openings_path, "r", encoding="utf-8") as f:openings_db = json.load(f)except Exception:pass# βββ 3. PYDANTIC MODELS (Data Structures) βββββββββββββββββββββββββββββββββββββββββββ# Used for input validation and defining the exact format of the JSON responses.class MoveRequest(BaseModel):fen: strtime: float = 1.0 # Seconds the engine will searchdepth: Optional[int] = Noneclass MoveResponse(BaseModel):bestmove: strscore: float # Pawns (+1.0 for White, -1.0 for Black)depth: intnodes: intnps: intpv: str # Principal Variation (best sequence of moves)mate_in: Optional[int] = Noneopening: Optional[str] = None7 unmodified linesmove_num: intsan: strbest_move: strclassification: str # "Brilliant", "Great", "Best", etc.opening: Optional[str] = Nonecpl: float # Centipawn Loss (0 = perfect)score_before: floatscore_after: floatclass AnalyzeResponse(BaseModel):accuracy: float # Lichess-style (0-100)estimated_elo: int # Calibrated Performance Ratingmoves: List[MoveAnalysis]counts: Dict[str, int] # Count of each classification (2 Blunders, etc.)# βββ 4. CORE MATH & LOGIC HELPERS ββββββββββββββββββββββββββββββββββββββββββββββββββ# These functions calculate win percentages, accuracy, and calibrated Elo scores.def get_normalized_score(info) -> tuple[float, Optional[int]]:"""Normalizes UCI score to centipawns from White's perspective."""if "score" not in info:return 0.0, Noneraw = info["score"].white()if raw.is_mate():m = raw.mate() or 0return (10000.0 if m > 0 else -10000.0), mreturn float(raw.score() or 0.0), Nonedef 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.00368208win_chances = 2.0 / (1.0 + math.exp(MULTIPLIER * cp_ceiled)) - 1.0return 50.0 + 50.0 * win_chancesdef get_move_accuracy(win_pct_before: float, win_pct_after: float, is_white_move: bool) -> float:"""Lichess-style per-move accuracy calculation using exponential decay."""if is_white_move:diff = win_pct_before - win_pct_afterelse:diff = (100.0 - win_pct_before) - (100.0 - win_pct_after)# Formula: 103.16 * exp(-0.04 * diff) - 3.16accuracy = 103.1668 * math.exp(-0.04354 * max(0.0, diff)) - 3.1669return 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.0white_score = score.white()if white_score.is_mate():mate_val = white_score.mate()return 100.0 if mate_val > 0 else 0.0return 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, alt_win_pct, is_white_move) -> bool:is_losing = pos_win_pct < 50.0 if is_white_move else pos_win_pct > 50.0is_alt_winning = alt_win_pct > 97.0 if is_white_move else alt_win_pct < 3.0return is_losing or is_alt_winningdef 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, alt_win_pct, is_white_move) -> bool:diff = (pos_win_pct - alt_win_pct) * (1 if is_white_move else -1)return diff > 10.0def is_simple_recapture(fen_two_moves_ago, previous_move, played_move) -> bool:if previous_move.to_square != played_move.to_square: return Falseb = chess.Board(fen_two_moves_ago)return b.piece_at(previous_move.to_square) is not None3 unmodified linesb = sum(values.get(p.piece_type, 0) for p in board.piece_map().values() if p.color == chess.BLACK)return w - bdef 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 Falsestart_diff = get_material_difference(board)white_to_play = board.turn == chess.WHITEsim_board = board.copy()moves = [played_move] + best_pvif 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 captured_piece: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: breakfor p in captured_w[:]:if p in captured_b: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 Falseend_diff = get_material_difference(sim_board)mat_diff = end_diff - start_diffplayer_rel = mat_diff if white_to_play else -mat_diffreturn player_rel < 0def 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"is_recapture = Falseif 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 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: passmanager = ConnectionManager()# βββ 7. ENGINE POOL (Orchestrator) ββββββββββββββββββββββββββββββββββββββββββββββββββ# Maintains 4 persistent engine processes for high-concurrency instant response.class EnginePool:def __init__(self, size=4):self.size = sizeself.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 bootexcept 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: passreturn engine@asynccontextmanagerasync def acquire(self):"""Yields an engine from the pool and ensures it's returned or restarted."""engine = await self.engines.get()try: yield enginefinally: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: passpool = 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 firstawait pool.start()yield# Cleanup on shutdownawait 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: breakelse: breakscore_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}player_is_white = (request.player_color.lower() == "white")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.WHITEis_player_turn = is_white_turn if player_is_white else not is_white_turnscore_before = current_scoretry: move = board.parse_san(san_move)except Exception: breakinfo_dict = infos_before[0]best_move_before = info_dict.get("pv", [None])[0]win_pct_before = get_win_percentage(info_dict)alt_win_pct_before = Noneif 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); breakboard_before_move = board.copy()board.push(move); move_history.append(move); fen_history.append(board.fen())infos_after_raw = await engine.analyse(board, limit, multipv=2)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_afterfen_two_moves_ago = fen_history[-3] if len(move_history) >= 2 else Noneuci_next_two_moves = (move_history[-2], move_history[-1]) if len(move_history) >= 2 else Noneboard_fen_only = board.fen().split(" ")[0]if board_fen_only in openings_db:cls, opening_name = "Book", openings_db[board_fen_only]else: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", [])), Nonemove_gain = score_after - score_before if is_white_turn else score_before - score_aftercpl = max(0.0, min(1000.0, -move_gain))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)counts[cls] = counts.get(cls, 0) + 1analysis_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_afterif player_move_accuracies: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.0else: accuracy = 0.0avg_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)except Exception as e:raise HTTPException(status_code=500, detail=str(e))# βββ 10. MAIN ENTRY POINT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
main.py+198-360