Spaces:
Sleeping
Sleeping
Update main.py
Browse files271 unmodified lines27227327427527627733 unmodified lines311312313314315316317171 unmodified lines489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536271 unmodified lines_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "300"))_RAM_CLEANUP_INTERVAL_SEC = int(os.environ.get("RAM_CLEANUP_INTERVAL_SEC", "60"))_CLEAR_HASH_AFTER_MOVE = os.environ.get("CLEAR_HASH_AFTER_MOVE", "1").strip().lower() not in {"0", "false", "no", "off"}async def memory_cleanup_task():"""33 unmodified linesasync def lifespan(app: FastAPI):cleanup_task = asyncio.create_task(memory_cleanup_task())print(f"[STARTUP] Memory cleanup task started (every {_RAM_CLEANUP_INTERVAL_SEC}s, threshold {_RAM_CLEANUP_THRESHOLD_MB}MB)")print(f"[STARTUP] Engine hash config: hash_mb={_engine_hash_mb()} clear_after_move={_CLEAR_HASH_AFTER_MOVE}")yieldcleanup_task.cancel()try:171 unmodified linestsec,)score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(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:breakpv = " ".join(pv_parts)del pv_boardscore_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)best_move = result.move.uci()del resultdel inforesponse = MoveResponse(bestmove=best_move,score=score_pawns,depth=depth,nodes=nodes,nps=nps,pv=pv,mate_in=mate_in,opening=opening_name)# On constrained RAM environments (e.g. HF Spaces), keeping hash between# move calls can still cause memory pressure over long games.if _CLEAR_HASH_AFTER_MOVE:async with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)force_memory_release()return responseexcept HTTPException:raiseexcept Exception as e:271 unmodified lines27227327427527627727833 unmodified lines312313314315316317318319320321171 unmodified lines493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543271 unmodified lines_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "300"))_RAM_CLEANUP_INTERVAL_SEC = int(os.environ.get("RAM_CLEANUP_INTERVAL_SEC", "60"))_CLEAR_HASH_AFTER_MOVE = os.environ.get("CLEAR_HASH_AFTER_MOVE", "1").strip().lower() not in {"0", "false", "no", "off"}_RESTART_ENGINE_AFTER_MOVE = os.environ.get("RESTART_ENGINE_AFTER_MOVE", "1").strip().lower() not in {"0", "false", "no", "off"}async def memory_cleanup_task():"""33 unmodified linesasync def lifespan(app: FastAPI):cleanup_task = asyncio.create_task(memory_cleanup_task())print(f"[STARTUP] Memory cleanup task started (every {_RAM_CLEANUP_INTERVAL_SEC}s, threshold {_RAM_CLEANUP_THRESHOLD_MB}MB)")print(f"[STARTUP] Engine config: hash_mb={_engine_hash_mb()} "f"clear_after_move={_CLEAR_HASH_AFTER_MOVE} restart_after_move={_RESTART_ENGINE_AFTER_MOVE}")yieldcleanup_task.cancel()try:171 unmodified linestsec,)score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(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:breakpv = " ".join(pv_parts)del pv_boardscore_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)best_move = result.move.uci()response = MoveResponse(bestmove=best_move,score=score_pawns,depth=depth,nodes=nodes,nps=nps,pv=pv,mate_in=mate_in,opening=opening_name)# IMPORTANT: do reset/clear while holding the engine IO lock so no# other /move call can reuse a half-cleared engine.if _RESTART_ENGINE_AFTER_MOVE:await _detach_and_quit_engine(engine)force_memory_release()elif _CLEAR_HASH_AFTER_MOVE:await _clear_engine_hash(engine)force_memory_release()del resultdel inforeturn responseexcept HTTPException:raiseexcept Exception as e:
main.py+45-38