Spaces:
Sleeping
Sleeping
Update main.py
Browse files1 unmodified line2345671 unmodified line91011121314151624 unmodified lines4142434445464748495051525354555657585960616263646566676869707172737439 unmodified lines11411511611711811912012112212312412512612712812979 unmodified lines20921021121221321431 unmodified lines24624724824925025125225325425525630 unmodified lines2872882892902912925 unmodified lines29829930030130230330430530630730827 unmodified lines336337338339340341150 unmodified lines49249349449549649749849942 unmodified lines54254354454554654754871 unmodified lines6206216226236246251 unmodified linefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dictimport osimport mathimport chess1 unmodified lineimport asyncioimport jsonapp = FastAPI(title="Deepcastle Engine API")# ─── Multiplaying / Challenge Manager ──────────────────────────────────────────class ConnectionManager:def __init__(self):24 unmodified linesmanager = 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()# Relay the message (move, etc.) to others in the same roomawait manager.broadcast(data, match_id, exclude=websocket)except WebSocketDisconnect:manager.disconnect(websocket, match_id)# Notify remaining players that opponent disconnected → they winawait 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)# Allow ALL for easy testing (we can restrict this later if needed)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_methods=["*"],allow_headers=["*"],)# Paths relative to the Docker containerDEEPCASTLE_ENGINE_PATH = os.environ.get("DEEPCASTLE_ENGINE_PATH",39 unmodified linesmoves: 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(DEEPCASTLE_ENGINE_PATH):return {"status": "error", "message": "Missing engine binary: deepcastle"}return {"status": "ok", "engine": "deepcastle"}# Global engine instances to save memory and improve performance_GLOBAL_DEEPCASTLE_ENGINE = None_ENGINE_LOCK = asyncio.Lock()79 unmodified lines# Compatibility alias: analysis now also uses DeepCastle.return await get_deepcastle_engine()def get_normalized_score(info) -> tuple[float, Optional[int]]:"""Returns the score from White's perspective in centipawns."""if "score" not in info:31 unmodified lineslimit = chess.engine.Limit(time=request.time, depth=request.depth)# One search: stats must come from this run (not a separate short analyse).async with _ENGINE_IO_LOCK:result = await engine.play(board, limit, info=chess.engine.INFO_ALL)info = dict(result.info)if not info:info = await engine.analyse(board, limit, info=chess.engine.INFO_ALL)# From White's perspective in CP -> converted to Pawns for UIscore_cp, mate_in = get_normalized_score(info)30 unmodified linesmate_in=mate_in,opening=opening_name)except Exception as e:print(f"Error: {e}")raise HTTPException(status_code=500, detail=str(e))5 unmodified linesboard = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)async with _ENGINE_IO_LOCK:result = await engine.play(board, limit, info=chess.engine.INFO_ALL)info = dict(result.info)if not info:info = await engine.analyse(board, limit, info=chess.engine.INFO_ALL)score_cp, mate_in = get_normalized_score(info)27 unmodified linesmate_in=mate_in,opening=opening_name)except Exception as e:print(f"Analysis move error: {e}")raise HTTPException(status_code=500, detail=str(e))150 unmodified linesanalysis_results = []async with _ENGINE_IO_LOCK:infos_before = await engine.analyse(board, limit, multipv=2)infos_before = infos_before if isinstance(infos_before, list) else [infos_before]counts = {42 unmodified linesfen_history.append(board.fen())async with _ENGINE_IO_LOCK: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]71 unmodified linescounts=counts)except Exception as e:print(f"Analysis Error: {e}")raise HTTPException(status_code=500, detail=str(e))1 unmodified line23456781 unmodified line10111213141524 unmodified lines40414243444539 unmodified lines85868788899079 unmodified lines17017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529631 unmodified lines32832933033133233333433533633733833934034134234334434534634730 unmodified lines3783793803813823833843855 unmodified lines39139239339439539639739839940040140240340440540640740840941027 unmodified lines438439440441442443444445150 unmodified lines59659759859960060160260360460560660760842 unmodified lines65165265365465565665765865966066171 unmodified lines7337347357367377387397401 unmodified linefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dictfrom contextlib import asynccontextmanagerimport osimport mathimport chess1 unmodified lineimport asyncioimport json# ─── Multiplaying / Challenge Manager ──────────────────────────────────────────class ConnectionManager:def __init__(self):24 unmodified linesmanager = ConnectionManager()# Paths relative to the Docker containerDEEPCASTLE_ENGINE_PATH = os.environ.get("DEEPCASTLE_ENGINE_PATH",39 unmodified linesmoves: List[MoveAnalysis]counts: Dict[str, int]# Global engine instances to save memory and improve performance_GLOBAL_DEEPCASTLE_ENGINE = None_ENGINE_LOCK = asyncio.Lock()79 unmodified lines# Compatibility alias: analysis now also uses DeepCastle.return await get_deepcastle_engine()async def shutdown_engine_async() -> None:"""Release UCI subprocess on process exit (deploy / SIGTERM)."""global _GLOBAL_DEEPCASTLE_ENGINEasync with _ENGINE_IO_LOCK:async with _ENGINE_LOCK:eng = _GLOBAL_DEEPCASTLE_ENGINE_GLOBAL_DEEPCASTLE_ENGINE = Noneif eng:try:await asyncio.wait_for(eng.quit(), timeout=5.0)except Exception:passasync def _detach_and_quit_engine(engine) -> None:"""After a hung search, drop the singleton and try to terminate the process."""global _GLOBAL_DEEPCASTLE_ENGINEasync with _ENGINE_LOCK:if _GLOBAL_DEEPCASTLE_ENGINE is engine:_GLOBAL_DEEPCASTLE_ENGINE = Nonetry:await asyncio.wait_for(engine.quit(), timeout=5.0)except Exception:passdef _search_timeout_sec(request_time: float, depth: Optional[int] = None) -> float:"""Wall-clock cap for a single play/analyse (env ENGINE_SEARCH_TIMEOUT_SEC, default 120)."""try:cap = float(os.environ.get("ENGINE_SEARCH_TIMEOUT_SEC", "120"))except ValueError:cap = 120.0cap = max(15.0, min(600.0, cap))if request_time and request_time > 0:return min(cap, max(request_time * 3.0 + 10.0, 30.0))return capdef _analyze_ply_timeout(time_per_move: float) -> float:"""Wall-clock cap per analyse() in /analyze-game (multipv=2 needs headroom)."""try:cap = float(os.environ.get("ENGINE_SEARCH_TIMEOUT_SEC", "120"))except ValueError:cap = 120.0cap = max(15.0, min(600.0, cap))if time_per_move and time_per_move > 0:return min(cap, max(time_per_move * 80.0 + 15.0, 30.0))return capasync def _engine_call(engine, coro, timeout_sec: float):try:return await asyncio.wait_for(coro, timeout=timeout_sec)except asyncio.TimeoutError:await _detach_and_quit_engine(engine)raise HTTPException(status_code=504, detail="Engine search timed out")@asynccontextmanagerasync def lifespan(app: FastAPI):yieldawait shutdown_engine_async()app = FastAPI(title="Deepcastle Engine API", lifespan=lifespan)# Allow ALL for easy testing (we can restrict this later if needed)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_methods=["*"],allow_headers=["*"],)@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, [])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)await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id)@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(DEEPCASTLE_ENGINE_PATH):return {"status": "error", "message": "Missing engine binary: deepcastle"}return {"status": "ok", "engine": "deepcastle"}@app.get("/health/ready")async def health_ready():"""Optional deep check: binary exists and engine answers UCI (for orchestrators)."""if not os.path.exists(DEEPCASTLE_ENGINE_PATH):raise HTTPException(status_code=503, detail="Missing engine binary")try:engine = await get_deepcastle_engine()async with _ENGINE_IO_LOCK:await asyncio.wait_for(engine.ping(), timeout=5.0)return {"status": "ok", "engine": "responsive"}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=503, detail=str(e))def get_normalized_score(info) -> tuple[float, Optional[int]]:"""Returns the score from White's perspective in centipawns."""if "score" not in info:31 unmodified lineslimit = chess.engine.Limit(time=request.time, depth=request.depth)# One search: stats must come from this run (not a separate short analyse).tsec = _search_timeout_sec(request.time, request.depth)async with _ENGINE_IO_LOCK:result = await _engine_call(engine,engine.play(board, limit, info=chess.engine.INFO_ALL),tsec,)info = dict(result.info)if not info:info = await _engine_call(engine,engine.analyse(board, limit, info=chess.engine.INFO_ALL),tsec,)# From White's perspective in CP -> converted to Pawns for UIscore_cp, mate_in = get_normalized_score(info)30 unmodified linesmate_in=mate_in,opening=opening_name)except HTTPException:raiseexcept Exception as e:print(f"Error: {e}")raise HTTPException(status_code=500, detail=str(e))5 unmodified linesboard = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)tsec = _search_timeout_sec(request.time, request.depth)async with _ENGINE_IO_LOCK:result = await _engine_call(engine,engine.play(board, limit, info=chess.engine.INFO_ALL),tsec,)info = dict(result.info)if not info:info = await _engine_call(engine,engine.analyse(board, limit, info=chess.engine.INFO_ALL),tsec,)score_cp, mate_in = get_normalized_score(info)27 unmodified linesmate_in=mate_in,opening=opening_name)except HTTPException:raiseexcept Exception as e:print(f"Analysis move error: {e}")raise HTTPException(status_code=500, detail=str(e))150 unmodified linesanalysis_results = []ply_timeout = _analyze_ply_timeout(request.time_per_move)async with _ENGINE_IO_LOCK:infos_before = await _engine_call(engine,engine.analyse(board, limit, multipv=2),ply_timeout,)infos_before = infos_before if isinstance(infos_before, list) else [infos_before]counts = {42 unmodified linesfen_history.append(board.fen())async with _ENGINE_IO_LOCK:infos_after_raw = await _engine_call(engine,engine.analyse(board, limit, multipv=2),ply_timeout,)infos_after: List[dict] = infos_after_raw if isinstance(infos_after_raw, list) else [infos_after_raw]info_after_dict: dict = infos_after[0]71 unmodified linescounts=counts)except HTTPException:raiseexcept Exception as e:print(f"Analysis Error: {e}")raise HTTPException(status_code=500, detail=str(e))
main.py+161-46