Spaces:
Sleeping
Sleeping
Update main.py
Browse files121 unmodified lines122123124125126127328 unmodified lines45645745845946046146246346446546646746846947047147247347447547647747847948019 unmodified lines50050150250350450510 unmodified lines51651751851952052152252352452552652752852953053153253353453553653753853954054154254354454540 unmodified lines586587588589590591149 unmodified lines741742743744745746165 unmodified lines912913914915916917121 unmodified lines_ENGINE_LOCK = asyncio.Lock()_ENGINE_IO_LOCK = asyncio.Lock()def _engine_hash_mb() -> int:try:328 unmodified lines# βββ Bot Move (/move) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest):try:engine = await get_deepcastle_engine()board = 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)depth, nodes, nps = normalize_search_stats(info)19 unmodified linesdel resultdel inforeturn MoveResponse(bestmove=best_move,10 unmodified linesexcept Exception as e:print(f"Error: {e}")raise HTTPException(status_code=500, detail=str(e))# βββ Hint Move (/analysis-move) βββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analysis-move", response_model=MoveResponse)async def get_analysis_move(request: MoveRequest):try:engine = await get_stockfish_engine()board = 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)depth, nodes, nps = normalize_search_stats(info)40 unmodified linesexcept Exception as e:print(f"Analysis move error: {e}")raise HTTPException(status_code=500, detail=str(e))# βββ Openings DB βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ149 unmodified lines# βββ Game Analysis (/analyze-game) ββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest):try:engine = await get_stockfish_engine()board = chess.Board(request.start_fen) if request.start_fen else chess.Board()165 unmodified linesexcept Exception as e:print(f"Analysis Error: {e}")raise HTTPException(status_code=500, detail=str(e))if __name__ == "__main__":121 unmodified lines122123124125126127128129130131132133134328 unmodified lines46346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649719 unmodified lines51751851952052152252352452552652710 unmodified lines53853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857940 unmodified lines620621622623624625626627149 unmodified lines777778779780781782783784785786787788789790791792165 unmodified lines958959960961962963964965966121 unmodified lines_ENGINE_LOCK = asyncio.Lock()_ENGINE_IO_LOCK = asyncio.Lock()# Global state for monitoring_PENDING_ENGINE_REQUESTS = 0_MAX_PENDING_ENGINE_REQUESTS = 10 # Drop requests if queue is too long to prevent OOM_MAX_PENDING_GAME_REVIEWS = 2 # Max concurrent full game reviews (heavy RAM)_PENDING_GAME_REVIEWS = 0_LOCK_TIMEOUT_SEC = 20.0 # Max wait time in queue before giving updef _engine_hash_mb() -> int:try:328 unmodified lines# βββ Bot Move (/move) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest):global _PENDING_ENGINE_REQUESTSif _PENDING_ENGINE_REQUESTS > _MAX_PENDING_ENGINE_REQUESTS:force_memory_release()raise HTTPException(status_code=429, detail="Server busy β too many analysis requests.")_PENDING_ENGINE_REQUESTS += 1try:engine = await get_deepcastle_engine()board = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)tsec = _search_timeout_sec(request.time, request.depth)try:async with asyncio.timeout(_LOCK_TIMEOUT_SEC):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,)except asyncio.TimeoutError:raise HTTPException(status_code=503, detail="Server overloaded β lock wait timeout.")score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(info)19 unmodified linesdel resultdel info# Match Shield: Force cleanup and hash clear after every move to prevent "Idle Growth"async with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)force_memory_release()return MoveResponse(bestmove=best_move,10 unmodified linesexcept Exception as e:print(f"Error: {e}")raise HTTPException(status_code=500, detail=str(e))finally:_PENDING_ENGINE_REQUESTS -= 1# βββ Hint Move (/analysis-move) βββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analysis-move", response_model=MoveResponse)async def get_analysis_move(request: MoveRequest):global _PENDING_ENGINE_REQUESTSif _PENDING_ENGINE_REQUESTS > _MAX_PENDING_ENGINE_REQUESTS:force_memory_release()raise HTTPException(status_code=429, detail="Server busy β too many analysis requests.")_PENDING_ENGINE_REQUESTS += 1try:engine = await get_stockfish_engine()board = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)tsec = _search_timeout_sec(request.time, request.depth)try:async with asyncio.timeout(_LOCK_TIMEOUT_SEC):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,)except asyncio.TimeoutError:raise HTTPException(status_code=503, detail="Server overloaded β lock wait timeout.")score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(info)40 unmodified linesexcept Exception as e:print(f"Analysis move error: {e}")raise HTTPException(status_code=500, detail=str(e))finally:_PENDING_ENGINE_REQUESTS -= 1# βββ Openings DB βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ149 unmodified lines# βββ Game Analysis (/analyze-game) ββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest):global _PENDING_ENGINE_REQUESTS, _PENDING_GAME_REVIEWSif _PENDING_GAME_REVIEWS >= _MAX_PENDING_GAME_REVIEWS:raise HTTPException(status_code=429, detail="Analysis queue full. Only 2 games can be reviewed at once.")if _PENDING_ENGINE_REQUESTS >= _MAX_PENDING_ENGINE_REQUESTS:raise HTTPException(status_code=429, detail="Server busy β too many moving parts.")_PENDING_ENGINE_REQUESTS += 1_PENDING_GAME_REVIEWS += 1try:engine = await get_stockfish_engine()board = chess.Board(request.start_fen) if request.start_fen else chess.Board()165 unmodified linesexcept Exception as e:print(f"Analysis Error: {e}")raise HTTPException(status_code=500, detail=str(e))finally:_PENDING_ENGINE_REQUESTS -= 1_PENDING_GAME_REVIEWS -= 1if __name__ == "__main__":
main.py+75-26