Spaces:
Sleeping
Sleeping
Update main.py
Browse files8 unmodified lines9101112131415161718191220212223242526116 unmodified lines14314414514614714814915030 unmodified lines18118218317217317417517617717817918018418518618773 unmodified lines261262263264265266267268269270271272273274275276135 unmodified lines41241341440140241541641741841961 unmodified lines4814824834704714724844854864874884894744754904914924934949 unmodified lines5045055064914924935075085095105115125135145155165175185195205218 unmodified lines5305315325335348 unmodified linesimport asyncioimport json
@asynccontextmanagerasync def lifespan(app: FastAPI): # Startup: Initialize the engine pool await pool.start() yield # Shutdown: Clean up the engine pool await pool.stop()
app = FastAPI(title="Deepcastle Engine API")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 lines await 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 processes await asyncio.sleep(0.5) except Exception as e: print(f" [!] Failed to start engine {i+1}: {e}")
30 unmodified lines except: pass
pool = 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()pool = EnginePool(size=4)
def get_normalized_score(info) -> tuple[float, Optional[int]]: """Returns the score from White's perspective in centipawns."""73 unmodified lines win_chances = 2.0 / (1.0 + math.exp(MULTIPLIER * cp_ceiled)) - 1.0 return 50.0 + 50.0 * win_chances
def 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_after else: diff = (100.0 - win_pct_before) - (100.0 - win_pct_after) accuracy = 103.1668 * math.exp(-0.04354 * max(0.0, diff)) - 3.1669 return max(0.0, min(100.0, accuracy))
def get_win_percentage(info: dict) -> float: score = info.get("score") if not score:135 unmodified lines player_is_white = (request.player_color.lower() == "white") fen_history = [board.fen()] move_history = [] total_cpl = 0.0 player_moves_count = 0 player_move_accuracies: List[float] = [] player_cpls: List[float] = [] # keep for estimated_elo current_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_after cpl = max(0, -move_gain) cpl = min(cpl, 1000.0) cpl = 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: total_cpl += cpl player_moves_count += 1 player_move_accuracies.append(move_acc) player_cpls.append(cpl) counts[cls] = counts.get(cls, 0) + 1 analysis_results.append(MoveAnalysis(9 unmodified lines )) infos_before = infos_after
avg_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)))) # NEW β Lichess win%-based accuracy if player_move_accuracies: # Lichess uses harmonic mean blended with arithmetic mean arithmetic_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.0 else: accuracy = 0.0
# Elo from avg CPL using exponential decay calibrated to your 3600 engine avg_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 lines
if __name__ == "__main__": import uvicorn # Hugging Face Spaces port is 7860 uvicorn.run(app, host="0.0.0.0", port=7860)main.py+46-20