Update app.py
Browse files5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141155 unmodified linesimport chess.svgimport torchimport torch.nn as nnimport numpy as npimport gradio as grfrom seleniumbase import SB# --- 1. THE BRAIN (RL Model Skeleton) ---class ChessNet(nn.Module):def __init__(self):super().__init__()self.conv = nn.Sequential(nn.Conv2d(12, 64, kernel_size=3, padding=1),nn.ReLU(),nn.Flatten(),nn.Linear(64 * 8 * 8, 1) # Simple Value Network)def forward(self, x): return self.conv(x)# --- 2. GLOBAL STATE ---class GlobalState:def __init__(self):self.board = chess.Board()self.status = "Initializing Display..."self.last_move = "None"self.model = ChessNet().eval() # Evaluation modestate = GlobalState()# --- 3. THE BOT LOGIC (Lichess Scraper) ---def run_bot():# Use Hugging Face Secrets for these!USER = os.getenv("LICHESS_USER", "YourUsername")PASS = os.getenv("LICHESS_PASS", "YourPassword")# uc=True bypasses bot detection; headless=True runs without a monitorwith SB(uc=True, headless=True) as sb:try:state.status = "Logging into Lichess..."sb.uc_open_with_reconnect("https://lichess.org/login", 5)# Simple login automationsb.type("#form3-username", USER)sb.type("#form3-password", PASS)sb.click("button.submit")time.sleep(5)state.status = "Searching for a game..."sb.open("https://lichess.org/?any#hook") # Joins a random open lobbywhile True:# 1. Detect if a game is active by looking for the boardif sb.is_element_visible(".cg-wrap"):state.status = "Game Active"# 2. Check if it is our turn (simplified logic)# In a real scenario, you'd scrape the 'moves' list to sync state.boardif state.board.turn == chess.WHITE:legal_moves = list(state.board.legal_moves)if legal_moves:move = random.choice(legal_moves) # Replace with model.predict()# 3. Human-like clicking on the Lichess boardfrom_sq = chess.square_name(move.from_square)to_sq = chess.square_name(move.to_square)state.status = f"Moving {from_sq} to {to_sq}"sb.click(f'.square[data-square="{from_sq}"]')time.sleep(random.uniform(0.2, 0.5))sb.click(f'.square[data-square="{to_sq}"]')state.board.push(move)state.last_move = move.uci()time.sleep(2)except Exception as e:state.status = f"Critical Error: {str(e)[:50]}"# --- 4. THE LIVE DASHBOARD (Gradio 6.0 Style) ---def get_live_update():# Generate the SVG of the current board stateboard_svg = chess.svg.board(state.board, size=400)return board_svg, state.last_move, state.statuswith gr.Blocks() as demo:gr.Markdown("# ♟️ Lichess RL Bot Live Dashboard")with gr.Row():board_output = gr.HTML(label="Live Board")with gr.Column():move_info = gr.Label(label="Last Bot Move")status_info = gr.Label(label="System Status")# Gradio 6.0 Timer for live updatesrefresh_timer = gr.Timer(2.0)refresh_timer.tick(fn=get_live_update,outputs=[board_output, move_info, status_info])if __name__ == "__main__":# Start the bot in a background threadthreading.Thread(target=run_bot, daemon=True).start()# LAUNCH: Crucial for Hugging Face "Leaking"demo.launch(server_name="0.0.0.0",server_port=7860,theme=gr.themes.Soft())5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121135 unmodified linesimport chess.svgimport torchimport torch.nn as nnimport gradio as grfrom seleniumbase import SBfrom huggingface_hub import HfApi# --- 1. ULTRA-LIGHT BRAIN (Fast Inference) ---class BulletNet(nn.Module):def __init__(self):super().__init__()self.net = nn.Sequential(nn.Linear(64, 128),nn.ReLU(),nn.Linear(128, 64),nn.Flatten(),nn.Linear(64, 1))def forward(self, x): return self.net(x)# --- 2. SHARED STATE ---class State:def __init__(self):self.board = chess.Board()self.status = "System Booting..."self.last_move = "None"self.active_game = Falsestate = State()# --- 3. HIGH-SPEED BOT ENGINE ---def run_bullet_bot():USER = os.getenv("LICHESS_USER")PASS = os.getenv("LICHESS_PASS")with SB(uc=True, headless=True) as sb:try:# Loginstate.status = "Logging in..."sb.uc_open_with_reconnect("https://lichess.org/login", 5)sb.type("#form3-username", USER)sb.type("#form3-password", PASS)sb.click("button.submit")time.sleep(3)# Auto-join 1+0 Bullet Hookstate.status = "Searching 1+0 Bullet..."sb.open("https://lichess.org/setup/hook")while True:# FAST CHECK: Is the board present?if sb.is_element_visible(".cg-wrap"):state.active_game = True# 1. Scrape FEN directly from DOM (Instant)raw_fen = sb.get_attribute(".cg-wrap", "data-fen")if raw_fen and raw_fen != state.board.fen():state.board = chess.Board(raw_fen)# 2. Check Turn (Assume we play as White for this logic)if state.board.turn == chess.WHITE:state.status = "⚡ MOVING"legal_moves = list(state.board.legal_moves)if legal_moves:# Decision Logicmove = random.choice(legal_moves)uci = move.uci()from_sq, to_sq = uci[:2], uci[2:]# 3. JS INJECTION (Bypasses Mouse Simulation)js_move = f"document.querySelector('.cg-wrap').chessground.move('{from_sq}', '{to_sq}')"sb.execute_script(js_move)state.last_move = ucitime.sleep(0.1) # Small jitter to prevent instant flagelse:if state.active_game:state.status = "Game Ended. Seeking new match..."sb.open("https://lichess.org/setup/hook")state.active_game = Falsestate.board.reset()time.sleep(0.05) # 20Hz Polling rate for Bullet speedsexcept Exception as e:state.status = f"Bot Error: {str(e)[:40]}"# --- 4. LIVE DASHBOARD ---def update_ui():# Only render SVG if game state changed to save CPUboard_svg = chess.svg.board(state.board, size=400)return board_svg, state.last_move, state.statuswith gr.Blocks() as demo:gr.Markdown("# ⚡ High-Speed Bullet Bot Dashboard")with gr.Row():view = gr.HTML()with gr.Column():m_info = gr.Label(label="Last Move")s_info = gr.Label(label="Status")timer = gr.Timer(1.0) # UI updates slower than the bot to save RAMtimer.tick(update_ui, outputs=[view, m_info, s_info])if __name__ == "__main__":threading.Thread(target=run_bullet_bot, daemon=True).start()demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Monochrome())
app.py+67-69