Spaces:
Sleeping
Sleeping
Update main.py
Browse files8 unmodified lines910111213141516116 unmodified lines13313413513613713830 unmodified lines16917017117217317417517617717817918018118218373 unmodified lines257258259260261262135 unmodified lines39839940040140240340440561 unmodified lines4674684694704714724734744754764774789 unmodified lines4884894904914924934944954968 unmodified lines5055065075088 unmodified linesimport asyncioimport jsonapp = FastAPI(title="Deepcastle Engine API")from contextlib import asynccontextmanagerclass ConnectionManager:def __init__(self):# match_id -> list of websockets116 unmodified linesawait self.engines.put(engine)self.all_engines.append(engine)print(f" [+] Engine {i+1}/{self.size} ready.")except Exception as e:print(f" [!] Failed to start engine {i+1}: {e}")30 unmodified linesexcept:passpool = EnginePool(size=8)@app.on_event("startup")async def startup_event():await pool.start()@app.on_event("shutdown")async def shutdown_event():await pool.stop()def get_normalized_score(info) -> tuple[float, Optional[int]]:"""Returns the score from White's perspective in centipawns."""73 unmodified lineswin_chances = 2.0 / (1.0 + math.exp(MULTIPLIER * cp_ceiled)) - 1.0return 50.0 + 50.0 * win_chancesdef get_win_percentage(info: dict) -> float:score = info.get("score")if not score:135 unmodified linesplayer_is_white = (request.player_color.lower() == "white")fen_history = [board.fen()]move_history = []total_cpl = 0.0player_moves_count = 0current_score, _ = get_normalized_score(infos_before[0])for i, san_move in enumerate(request.moves):61 unmodified lines)move_gain = score_after - score_before if is_white_turn else score_before - score_aftercpl = max(0, -move_gain)cpl = min(cpl, 1000.0)if is_player_turn:total_cpl += cplplayer_moves_count += 1counts[cls] = counts.get(cls, 0) + 1analysis_results.append(MoveAnalysis(9 unmodified lines))infos_before = infos_afteravg_cpl = total_cpl / max(1, player_moves_count)accuracy = max(10.0, min(100.0, 100.0 * math.exp(-0.005 * avg_cpl)))estimated_elo = int(max(400, min(3600, 3600 - (avg_cpl * 20))))return AnalyzeResponse(accuracy=round(accuracy, 1),8 unmodified linesif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)8 unmodified lines91011121314151617181920212223242526116 unmodified lines14314414514614714814915030 unmodified lines18118218318418518618773 unmodified lines261262263264265266267268269270271272273274275276135 unmodified lines41241341441541641741841961 unmodified lines4814824834844854864874884894904914924934949 unmodified lines5045055065075085095105115125135145155165175185195205218 unmodified lines5305315325335348 unmodified linesimport asyncioimport json@asynccontextmanagerasync def lifespan(app: FastAPI):# Startup: Initialize the engine poolawait pool.start()yield# Shutdown: Clean up the engine poolawait pool.stop()app = FastAPI(title="Deepcastle Engine API", lifespan=lifespan)from contextlib import asynccontextmanager# βββ Multiplaying / Challenge Manager ββββββββββββββββββββββββββββββββββββββββββclass ConnectionManager:def __init__(self):# match_id -> list of websockets116 unmodified linesawait self.engines.put(engine)self.all_engines.append(engine)print(f" [+] Engine {i+1}/{self.size} ready.")# Give the system some room to breathe between processesawait asyncio.sleep(0.5)except Exception as e:print(f" [!] Failed to start engine {i+1}: {e}")30 unmodified linesexcept:passpool = EnginePool(size=4)def get_normalized_score(info) -> tuple[float, Optional[int]]:"""Returns the score from White's perspective in centipawns."""73 unmodified lineswin_chances = 2.0 / (1.0 + math.exp(MULTIPLIER * cp_ceiled)) - 1.0return 50.0 + 50.0 * win_chancesdef get_move_accuracy(win_pct_before: float, win_pct_after: float, is_white_move: bool) -> float:"""Lichess-style win%-based per-move accuracy (0β100)."""if is_white_move:diff = win_pct_before - win_pct_afterelse:diff = (100.0 - win_pct_before) - (100.0 - win_pct_after)accuracy = 103.1668 * math.exp(-0.04354 * max(0.0, diff)) - 3.1669return max(0.0, min(100.0, accuracy))def get_win_percentage(info: dict) -> float:score = info.get("score")if not score:135 unmodified linesplayer_is_white = (request.player_color.lower() == "white")fen_history = [board.fen()]move_history = []player_move_accuracies: List[float] = []player_cpls: List[float] = [] # keep for estimated_elocurrent_score, _ = get_normalized_score(infos_before[0])for i, san_move in enumerate(request.moves):61 unmodified lines)move_gain = score_after - score_before if is_white_turn else score_before - score_aftercpl = max(0.0, min(1000.0, -move_gain))# Lichess-style per-move accuracy using win%move_acc = get_move_accuracy(win_pct_before, win_pct_after, is_white_turn)if is_player_turn:player_move_accuracies.append(move_acc)player_cpls.append(cpl)counts[cls] = counts.get(cls, 0) + 1analysis_results.append(MoveAnalysis(9 unmodified lines))infos_before = infos_after# NEW β Lichess win%-based accuracyif player_move_accuracies:# Lichess uses harmonic mean blended with arithmetic meanarithmetic_mean = sum(player_move_accuracies) / len(player_move_accuracies)harmonic_mean = len(player_move_accuracies) / sum(1.0 / max(a, 0.1) for a in player_move_accuracies)accuracy = (arithmetic_mean + harmonic_mean) / 2.0else:accuracy = 0.0# Elo from avg CPL using exponential decay calibrated to your 3600 engineavg_cpl = sum(player_cpls) / max(1, len(player_cpls))estimated_elo = int(max(400, min(3600, round(3600 * math.exp(-0.01 * avg_cpl)))))return AnalyzeResponse(accuracy=round(accuracy, 1),8 unmodified linesif __name__ == "__main__":import uvicorn# Hugging Face Spaces port is 7860uvicorn.run(app, host="0.0.0.0", port=7860)
main.py+46-20