Spaces:
Sleeping
Sleeping
Update main.py
Browse files12342 unmodified lines7891011121314151 unmodified line1718192021222324252627284 unmodified lines3334353637383940414243444546474827 unmodified lines7677787980811 unmodified line8384858687881 unmodified line909192939495969798991001011021031 unmodified line105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dict2 unmodified linesimport chessimport chess.engineimport asyncioapp = FastAPI(title="Deepcastle Engine API")app.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_headers=["*"],)ENGINE_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.0depth: Optional[int] = Noneclass MoveResponse(BaseModel):4 unmodified linesnps: intpv: strclass AnalyzeRequest(BaseModel):moves: List[str]time_per_move: float = 0.1player_color: str = "white"class MoveAnalysis(BaseModel):move_num: intsan: strfen: strclassification: strcpl: floatscore_before: floatscore_after: float27 unmodified linesreturn enginedef get_normalized_score(info, turn_color=chess.WHITE):if "score" not in info:return 0.0raw = info["score"].white()1 unmodified linereturn 10000.0 if (raw.mate() or 0) > 0 else -10000.0return raw.score() or 0.0@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest):engine = None1 unmodified lineengine = await get_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 = get_normalized_score(info)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="")finally:if engine: await engine.quit()@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest):engine = None1 unmodified lineengine = await get_engine()board = chess.Board()limit = chess.engine.Limit(time=request.time_per_move)analysis_results, total_cpl, player_moves_count = [], 0, 0counts = {"Brilliant": 0, "Great": 0, "Best": 0, "Excellent": 0, "Good": 0, "Inaccuracy": 0, "Mistake": 0, "Blunder": 0}info_before = await engine.analyse(board, limit)current_score = get_normalized_score(info_before)player_is_white = (request.player_color.lower() == "white")for i, san_move in enumerate(request.moves):is_player_turn = board.turn == (chess.WHITE if player_is_white else chess.BLACK)score_before = current_scoretry:board.push_san(san_move)except Exception: breakinfo_after = await engine.analyse(board, limit)current_score = get_normalized_score(info_after)if is_player_turn:cpl = max(0, score_before - current_score if player_is_white else current_score - score_before)cpl = min(cpl, 1000.0)total_cpl += cplplayer_moves_count += 1if cpl <= 15: cls = "Best"elif cpl <= 35: cls = "Excellent"elif cpl <= 75: cls = "Good"elif cpl <= 150: cls = "Inaccuracy"elif cpl <= 300: cls = "Mistake"else: cls = "Blunder"counts[cls] += 1analysis_results.append(MoveAnalysis(move_num=i+1, san=san_move, fen=board.fen(), classification=cls, cpl=cpl, score_before=score_before/100, score_after=current_score/100))avg_cpl = total_cpl / max(1, player_moves_count)accuracy = max(10.0, min(100.0, 100.0 * math.exp(-0.005 * avg_cpl)))estimated_elo = int(max(400, min(3600, 3600 - (avg_cpl * 20))))return AnalyzeResponse(accuracy=round(accuracy, 1), estimated_elo=estimated_elo, moves=analysis_results, counts=counts)finally:if engine: await engine.quit()if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)12342 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960611 unmodified line636465666768697071727374754 unmodified lines808182838485868788899091929394959627 unmodified lines1241251261271281291301 unmodified line1321331341351361371381 unmodified line1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921 unmodified line194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dict2 unmodified linesimport chessimport chess.engineimport asyncioimport jsonapp = FastAPI(title="Deepcastle Engine API")# βββ Multiplaying / Challenge Manager ββββββββββββββββββββββββββββββββββββββββββclass ConnectionManager:def __init__(self):# match_id -> list of websocketsself.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)try:while True:data = await websocket.receive_text()# Relay the message (move, chat, etc) to others in the same roomawait manager.broadcast(data, match_id, exclude=websocket)except WebSocketDisconnect:manager.disconnect(websocket, match_id)except Exception:manager.disconnect(websocket, match_id)# Allow ALL for easy testing (we can restrict this later if needed)app.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_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):4 unmodified linesnps: intpv: str# βββ New Analysis Types ββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass AnalyzeRequest(BaseModel):moves: List[str] # e.g., ["e4", "e5", "Nf3", "Nc6", ...]time_per_move: float = 0.1 # quick eval per moveplayer_color: str = "white"class MoveAnalysis(BaseModel):move_num: intsan: strfen: strclassification: str # Best, Excellent, Good, Inaccuracy, Mistake, Blunder, Brilliantcpl: floatscore_before: floatscore_after: float27 unmodified linesreturn enginedef get_normalized_score(info, turn_color=chess.WHITE):"""Returns the score from White's perspective in centipawns."""if "score" not in info:return 0.0raw = info["score"].white()1 unmodified linereturn 10000.0 if (raw.mate() or 0) > 0 else -10000.0return raw.score() or 0.0# βββ Engine Inference Route ββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest):engine = None1 unmodified lineengine = await get_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 = 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)# Map mate score to pawns representation to not break old UIscore_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=depth,nodes=nodes,nps=nps,pv=pv)except Exception as e:print(f"Error: {e}")raise HTTPException(status_code=500, detail=str(e))finally:if engine:try:await engine.quit()except Exception:pass# βββ Game Review Route βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest):engine = None1 unmodified lineengine = await get_engine()board = chess.Board()limit = chess.engine.Limit(time=request.time_per_move)analysis_results = []# We need the pre-move evaluation of the very first positioninfo_before = await engine.analyse(board, limit)current_score = get_normalized_score(info_before)# To track accuracytotal_cpl = 0player_moves_count = 0counts = {"Brilliant": 0, "Great": 0, "Best": 0,"Excellent": 0, "Good": 0, "Inaccuracy": 0,"Mistake": 0, "Blunder": 0}player_is_white = (request.player_color.lower() == "white")for i, san_move in enumerate(request.moves):is_player_turn = board.turn == chess.WHITE if player_is_white else board.turn == chess.BLACK# The current_score is the score BEFORE this movescore_before = current_score# Push movetry:move = board.parse_san(san_move)board.push(move)except Exception:break # Invalid move, stop analysis here# Get eval AFTER moveinfo_after = await engine.analyse(board, limit)score_after = get_normalized_score(info_after)# Update current score for next iterationcurrent_score = score_after# Only analyze the player's movesif is_player_turn:# Calculate Centipawn Loss (diff between score before and score after)# If player is White, positive score is good. If White drops from +100 to +50 -> CPL = 50.# If player is Black, negative score is good. If Black rises from -100 to -50 -> CPL = 50.if player_is_white:cpl = max(0, score_before - score_after)else:cpl = max(0, score_after - score_before)# Cap CPL to 1000 so one massive blunder doesn't utterly ruin the statscpl = min(cpl, 1000.0)total_cpl += cplplayer_moves_count += 1# Classification mappingif cpl <= 15:cls = "Best"elif cpl <= 35:cls = "Excellent"elif cpl <= 75:cls = "Good"elif cpl <= 150:cls = "Inaccuracy"elif cpl <= 300:cls = "Mistake"else:cls = "Blunder"counts[cls] += 1analysis_results.append(MoveAnalysis(move_num=i+1,san=san_move,fen=board.fen(),classification=cls,cpl=cpl,score_before=score_before / 100.0,score_after=score_after / 100.0))# Win probability matching accuracy formula# Accuracy = 100 * exp(-0.02 * avg_cpl) smoothedavg_cpl = total_cpl / max(1, player_moves_count)# Simple heuristic mapping for Accuracy & Elo# 0 avg loss -> 100%# ~100 avg loss -> ~60%accuracy = max(10.0, min(100.0, 100.0 * math.exp(-0.005 * avg_cpl)))# Estimate Elo based slightly on accuracy# This is a fun heuristic metricestimated_elo = int(max(400, min(3600, 3600 - (avg_cpl * 20))))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))finally:if engine:try:await engine.quit()except Exception:passif __name__ == "__main__":import uvicorn# Hugging Face Spaces port is 7860uvicorn.run(app, host="0.0.0.0", port=7860)
main.py+185-23