Spaces:
Sleeping
Sleeping
Update main.py
Browse files68 unmodified lines69707172737450 unmodified lines1251261271281291301311321331341 unmodified line136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178378 unmodified lines55755855956056156256368 unmodified linesallow_headers=["*"],)DEEPCASTLE_ENGINE_PATH = os.environ.get("DEEPCASTLE_ENGINE_PATH",os.environ.get("ENGINE_PATH", "/app/engine_bin/deepcastle"),50 unmodified lines# Global engine instances to save memory and improve performance_GLOBAL_DEEPCASTLE_ENGINE = Noneasync def _get_or_start_engine(engine_path: str, *, role: str, options: Optional[dict] = None):global _GLOBAL_DEEPCASTLE_ENGINEcurrent_engine = _GLOBAL_DEEPCASTLE_ENGINEif current_engine is not None:try:1 unmodified linereturn current_engineexcept Exception:_GLOBAL_DEEPCASTLE_ENGINE = Noneif not os.path.exists(engine_path):raise HTTPException(status_code=500, detail=f"{role} binary NOT FOUND at {engine_path}")try:_, engine = await chess.engine.popen_uci(engine_path)if options:await engine.configure(options)if os.path.exists(NNUE_PATH):try:await engine.configure({"EvalFile": NNUE_PATH})except Exception as ne:print(f"[ERROR] EvalFile load failed: {str(ne)}")else:print(f"[WARNING] EvalFile not found at {NNUE_PATH}")if os.path.exists(NNUE_SMALL_PATH):try:await engine.configure({"EvalFileSmall": NNUE_SMALL_PATH})except Exception as ne:print(f"[ERROR] EvalFileSmall load failed: {str(ne)}")else:print(f"[WARNING] EvalFileSmall not found at {NNUE_SMALL_PATH}")_GLOBAL_DEEPCASTLE_ENGINE = enginereturn engineexcept Exception as e:raise HTTPException(status_code=500, detail=f"{role} crash: {str(e)}")async def get_deepcastle_engine():return await _get_or_start_engine(DEEPCASTLE_ENGINE_PATH,role="deepcastle",options={"Hash": 128, "Threads": 1},)async def get_stockfish_engine():378 unmodified linesanalysis_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),68 unmodified lines6970717273747550 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471 unmodified line149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205378 unmodified lines58458558658758858968 unmodified linesallow_headers=["*"],)# Paths relative to the Docker containerDEEPCASTLE_ENGINE_PATH = os.environ.get("DEEPCASTLE_ENGINE_PATH",os.environ.get("ENGINE_PATH", "/app/engine_bin/deepcastle"),50 unmodified lines# Global engine instances to save memory and improve performance_GLOBAL_DEEPCASTLE_ENGINE = None_ENGINE_LOCK = asyncio.Lock()def _engine_hash_mb() -> int:"""Transposition table size in MB; lower = less RAM (env ENGINE_HASH_MB, default 64)."""try:v = int(os.environ.get("ENGINE_HASH_MB", "64"))except ValueError:v = 64return max(8, min(512, v))async def _get_or_start_engine(engine_path: str, *, role: str, options: Optional[dict] = None):global _GLOBAL_DEEPCASTLE_ENGINE# Fast path: no lock when singleton is already healthy (avoids serializing every /move).current_engine = _GLOBAL_DEEPCASTLE_ENGINEif current_engine is not None:try:1 unmodified linereturn current_engineexcept Exception:_GLOBAL_DEEPCASTLE_ENGINE = Noneelse:_GLOBAL_DEEPCASTLE_ENGINE = Noneasync with _ENGINE_LOCK:current_engine = _GLOBAL_DEEPCASTLE_ENGINEif current_engine is not None:try:if not current_engine.is_terminated():return current_engineexcept Exception:_GLOBAL_DEEPCASTLE_ENGINE = Noneelse:_GLOBAL_DEEPCASTLE_ENGINE = Noneif not os.path.exists(engine_path):raise HTTPException(status_code=500, detail=f"{role} binary NOT FOUND at {engine_path}")try:_, engine = await chess.engine.popen_uci(engine_path)if options:await engine.configure(options)if os.path.exists(NNUE_PATH):try:await engine.configure({"EvalFile": NNUE_PATH})except Exception as ne:print(f"[ERROR] EvalFile load failed: {str(ne)}")else:print(f"[WARNING] EvalFile not found at {NNUE_PATH}")if os.path.exists(NNUE_SMALL_PATH):try:await engine.configure({"EvalFileSmall": NNUE_SMALL_PATH})except Exception as ne:print(f"[ERROR] EvalFileSmall load failed: {str(ne)}")else:print(f"[WARNING] EvalFileSmall not found at {NNUE_SMALL_PATH}")_GLOBAL_DEEPCASTLE_ENGINE = enginereturn engineexcept Exception as e:raise HTTPException(status_code=500, detail=f"{role} crash: {str(e)}")async def get_deepcastle_engine():return await _get_or_start_engine(DEEPCASTLE_ENGINE_PATH,role="deepcastle",options={"Hash": _engine_hash_mb(), "Threads": 1},)async def get_stockfish_engine():378 unmodified linesanalysis_results.append(MoveAnalysis(move_num=i+1,san=san_move,classification=cls,cpl=float(cpl),score_before=float(score_before / 100.0),
main.py+52-26