Spaces:
Sleeping
Sleeping
Update main.py
Browse files10 unmodified lines1112131415161718225 unmodified lines2442452462472482492502512522532542552562572582 unmodified lines2612622632642652662672682694 unmodified lines2742752762772782792802812822832841 unmodified line28628728828929029129229329429529632 unmodified lines3293303313323333343353363373383397 unmodified lines34734834935035135235314 unmodified lines36836937037137237337437537637737837938038138238338438538638712 unmodified lines40040140240340440540662 unmodified lines46947047147247347447547647747847948048148248350 unmodified lines53453553653753853954054154254354454554654754854955055155255361 unmodified lines61561661761861962062149 unmodified lines671672673674675676677183 unmodified lines86186286386486586686786886987010 unmodified linesimport asyncioimport jsonimport gcimport psutil# βββ Multiplayer / Challenge Manager ββββββββββββββββββββββββββββββββββββββββββclass ConnectionManager:def __init__(self):225 unmodified lines# βββ Background Memory Cleanup Task βββββββββββββββββββββββββββββββββββββββββββ# RAM threshold in MB above which engine hash is also cleared (tune to your HF plan)_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "400"))# How often to run the cleanup in seconds (default: 5 minutes)_RAM_CLEANUP_INTERVAL_SEC = int(os.environ.get("RAM_CLEANUP_INTERVAL_SEC", "300"))async def memory_cleanup_task():"""Background task that runs every 5 minutes.- Always nudges Python GC to free unreferenced objects.- If RAM exceeds threshold, also clears engine hash table."""while True:2 unmodified linesprocess = psutil.Process(os.getpid())mem_mb = process.memory_info().rss / 1024 / 1024# Always run Python GCgc.collect()if mem_mb > _RAM_CLEANUP_THRESHOLD_MB:print(f"[CLEANUP] RAM at {mem_mb:.1f}MB (threshold {_RAM_CLEANUP_THRESHOLD_MB}MB) β clearing engine hash")engine = _GLOBAL_DEEPCASTLE_ENGINE4 unmodified linesawait _clear_engine_hash(engine)except Exception:passgc.collect()after_mb = process.memory_info().rss / 1024 / 1024print(f"[CLEANUP] Done. RAM: {mem_mb:.1f}MB β {after_mb:.1f}MB")else:print(f"[CLEANUP] RAM at {mem_mb:.1f}MB β OK, no action needed")except Exception as e:print(f"[CLEANUP] Error during cleanup: {e}")1 unmodified line@asynccontextmanagerasync def lifespan(app: FastAPI):# Start background memory cleanup task on bootcleanup_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)")yield# On shutdown: cancel cleanup task then quit enginecleanup_task.cancel()try:await cleanup_task32 unmodified linesexcept WebSocketDisconnect:manager.disconnect(websocket, match_id)await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id)gc.collect()except Exception:manager.disconnect(websocket, match_id)await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id)gc.collect()# βββ Health & Monitoring βββββββββββββββββββββββββββββββββββββββββββββββββββββββ7 unmodified linesdef health():if not os.path.exists(DEEPCASTLE_ENGINE_PATH):return {"status": "error", "message": "Missing engine binary: deepcastle"}gc.collect()return {"status": "ok", "engine": "deepcastle"}14 unmodified lines@app.get("/ram")def ram_usage():"""Monitor RAM usage β call this anytime to check memory health."""process = psutil.Process(os.getpid())mem = process.memory_info()mem_mb = mem.rss / 1024 / 1024return {"rss_mb": round(mem_mb, 2), # actual RAM used"vms_mb": round(mem.vms / 1024 / 1024, 2), # virtual memory"threshold_mb": _RAM_CLEANUP_THRESHOLD_MB, # cleanup trigger"cleanup_interval_sec": _RAM_CLEANUP_INTERVAL_SEC, # how often cleanup runs"status": "high" if mem_mb > _RAM_CLEANUP_THRESHOLD_MB else "ok","active_rooms": len(manager.active_connections), # live websocket rooms"active_connections": sum(len(v) for v in manager.active_connections.values()),}12 unmodified linesengine = await get_deepcastle_engine()async with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)gc.collect()return {"status": "ok", "message": "Engine hash cleared"}except HTTPException:raise62 unmodified lineselse:breakpv = " ".join(pv_parts)del pv_board # FIX: Free board copyscore_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 result # FIX: Free engine resultdel info # FIX: Free info dictreturn MoveResponse(bestmove=best_move,50 unmodified lineselse:breakpv = " ".join(pv_parts)del pv_board # FIX: Free board copyscore_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 result # FIX: Free engine resultdel info # FIX: Free info dict# FIX: Clear hash after hint β one-shot search, no continuity neededasync with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)gc.collect()return MoveResponse(bestmove=best_move,61 unmodified linesreturn Falseb = chess.Board(fen_two_moves_ago)result = b.piece_at(previous_move.to_square) is not Nonedel b # FIX: Free temp boardreturn resultdef get_material_difference(board: chess.Board) -> int:49 unmodified linesreturn Falseend_diff = get_material_difference(sim_board)del sim_board # FIX: Free temp boardmat_diff = end_diff - start_diffplayer_rel = mat_diff if white_to_play else -mat_diffreturn player_rel < 0183 unmodified linesaccuracy = max(10.0, min(100.0, 100.0 * math.exp(-0.005 * avg_cpl)))estimated_elo = int(max(400, min(3600, round(3600 * math.exp(-0.015 * avg_cpl)))))# FIX: Clear engine hash after full game analysis β analysis fills hash very fastasync with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)gc.collect()return AnalyzeResponse(accuracy=round(accuracy, 1),10 unmodified lines11121314151617181920212223242526272829303132333435225 unmodified lines2612622632642652662672682692702712722732 unmodified lines2762772782792802814 unmodified lines2862872882892902912922932942952962972981 unmodified line30030130230330430530630730832 unmodified lines3413423433443453463473483493503517 unmodified lines35936036136236336436514 unmodified lines38038138238338438538638738838939039139239339439539639712 unmodified lines41041141241341441541662 unmodified lines47948048148248348448548648748848949049149249350 unmodified lines54454554654754854955055155255355455555655755855956056156256361 unmodified lines62562662762862963063149 unmodified lines681682683684685686687183 unmodified lines87187287387487587687787887988010 unmodified linesimport asyncioimport jsonimport gcimport ctypesimport psutil# βββ Force memory back to OS (Linux/HF compatible) ββββββββββββββββββββββββββββdef force_memory_release():"""Run GC twice (catches cyclic references missed on first pass),then call malloc_trim to return freed pages back to the OS.Without this, Python holds freed memory in its own pool andthe OS still shows high RAM even after objects are deleted."""gc.collect()gc.collect()try:ctypes.CDLL("libc.so.6").malloc_trim(0)except Exception:pass# βββ Multiplayer / Challenge Manager ββββββββββββββββββββββββββββββββββββββββββclass ConnectionManager:def __init__(self):225 unmodified lines# βββ Background Memory Cleanup Task βββββββββββββββββββββββββββββββββββββββββββ_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "400"))_RAM_CLEANUP_INTERVAL_SEC = int(os.environ.get("RAM_CLEANUP_INTERVAL_SEC", "300"))async def memory_cleanup_task():"""Background task that runs every 5 minutes.- Always runs GC twice and malloc_trim to return memory to OS.- If RAM exceeds threshold, also clears engine hash table."""while True:2 unmodified linesprocess = psutil.Process(os.getpid())mem_mb = process.memory_info().rss / 1024 / 1024if mem_mb > _RAM_CLEANUP_THRESHOLD_MB:print(f"[CLEANUP] RAM at {mem_mb:.1f}MB (threshold {_RAM_CLEANUP_THRESHOLD_MB}MB) β clearing engine hash")engine = _GLOBAL_DEEPCASTLE_ENGINE4 unmodified linesawait _clear_engine_hash(engine)except Exception:passforce_memory_release()after_mb = process.memory_info().rss / 1024 / 1024print(f"[CLEANUP] Done. RAM: {mem_mb:.1f}MB β {after_mb:.1f}MB")else:# Always nudge GC + malloc_trim even when RAM is fineforce_memory_release()print(f"[CLEANUP] RAM at {mem_mb:.1f}MB β OK")except Exception as e:print(f"[CLEANUP] Error during cleanup: {e}")1 unmodified line@asynccontextmanagerasync 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)")yieldcleanup_task.cancel()try:await cleanup_task32 unmodified linesexcept WebSocketDisconnect:manager.disconnect(websocket, match_id)await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id)force_memory_release()except Exception:manager.disconnect(websocket, match_id)await manager.broadcast(json.dumps({"type": "opponent_disconnected"}), match_id)force_memory_release()# βββ Health & Monitoring βββββββββββββββββββββββββββββββββββββββββββββββββββββββ7 unmodified linesdef health():if not os.path.exists(DEEPCASTLE_ENGINE_PATH):return {"status": "error", "message": "Missing engine binary: deepcastle"}force_memory_release()return {"status": "ok", "engine": "deepcastle"}14 unmodified lines@app.get("/ram")def ram_usage():"""Monitor RAM usage β call anytime to check memory health."""process = psutil.Process(os.getpid())mem = process.memory_info()mem_mb = mem.rss / 1024 / 1024return {"rss_mb": round(mem_mb, 2),"vms_mb": round(mem.vms / 1024 / 1024, 2),"threshold_mb": _RAM_CLEANUP_THRESHOLD_MB,"cleanup_interval_sec": _RAM_CLEANUP_INTERVAL_SEC,"status": "high" if mem_mb > _RAM_CLEANUP_THRESHOLD_MB else "ok","active_rooms": len(manager.active_connections),"active_connections": sum(len(v) for v in manager.active_connections.values()),}12 unmodified linesengine = await get_deepcastle_engine()async with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)force_memory_release()return {"status": "ok", "message": "Engine hash cleared"}except HTTPException:raise62 unmodified lineselse: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 inforeturn MoveResponse(bestmove=best_move,50 unmodified lineselse: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 info# FIX: Clear hash + force memory back to OS after hintasync with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)force_memory_release()return MoveResponse(bestmove=best_move,61 unmodified linesreturn Falseb = chess.Board(fen_two_moves_ago)result = b.piece_at(previous_move.to_square) is not Nonedel breturn resultdef get_material_difference(board: chess.Board) -> int:49 unmodified linesreturn Falseend_diff = get_material_difference(sim_board)del sim_boardmat_diff = end_diff - start_diffplayer_rel = mat_diff if white_to_play else -mat_diffreturn player_rel < 0183 unmodified linesaccuracy = max(10.0, min(100.0, 100.0 * math.exp(-0.005 * avg_cpl)))estimated_elo = int(max(400, min(3600, round(3600 * math.exp(-0.015 * avg_cpl)))))# FIX: Clear engine hash + force memory back to OS after full game analysisasync with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)force_memory_release()return AnalyzeResponse(accuracy=round(accuracy, 1),
main.py+45-35