Update app.py
Browse files5 unmodified lines67899101113121513141516191718192324202627282122232431323334353637383940414243444546472526272850293052533132553334573536593738394041426465666768697071727374757677784344454647484950515253545556575859608081828361626364858687888990919293949596976566676869707172737475767778799910010110210310410510610710810980818283112113114115848586878889117118909192931209495122123969798125126991001011021031041051061071081091101301111121131141155 unmodified linesimport chess.svgimport torchimport torch.nn as nnimport torch.optim as optimimport numpy as npimport gradio as grfrom seleniumbase import SBfrom huggingface_hub import HfApi
# --- 1. THE BRAIN (RL Model) ---# --- 1. THE BRAIN (RL Model Skeleton) ---class ChessNet(nn.Module): def __init__(self): super().__init__() # Input: 8x8 board with 12 piece types self.conv = nn.Sequential( nn.Conv2d(12, 64, kernel_size=3, padding=1), nn.ReLU(), nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.ReLU(), nn.Flatten(), nn.Linear(128 * 8 * 8, 512), nn.ReLU(), nn.Linear(512, 1) # Outputs 'Value' of the board nn.Linear(64 * 8 * 8, 1) # Simple Value Network ) def forward(self, x): return self.conv(x)
def forward(self, x): return self.conv(x)
def board_to_tensor(board): """ Converts python-chess board to a 12x8x8 tensor """ layer_dict = {chess.PAWN: 0, chess.KNIGHT: 1, chess.BISHOP: 2, chess.ROOK: 3, chess.QUEEN: 4, chess.KING: 5} tensor = np.zeros((12, 8, 8), dtype=np.float32) for square, piece in board.piece_map().items(): row, col = divmod(square, 8) p_type = layer_dict[piece.piece_type] if piece.color == chess.BLACK: p_type += 6 tensor[p_type, row, col] = 1 return torch.from_numpy(tensor).unsqueeze(0)
# --- 2. THE STATE MANAGER ---class BotState:# --- 2. GLOBAL STATE ---class GlobalState: def __init__(self): self.board = chess.Board() self.status = "Initializing..." self.status = "Initializing Display..." self.last_move = "None" self.model = ChessNet() self.optimizer = optim.Adam(self.model.parameters(), lr=0.001) self.model = ChessNet().eval() # Evaluation mode
state = BotState()state = GlobalState()
# --- 3. THE BOT LOGIC (Selenium) ---# --- 3. THE BOT LOGIC (Lichess Scraper) ---def run_bot(): # Use Hugging Face Secrets for Login # 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 monitor with SB(uc=True, headless=True) as sb: state.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") state.status = "Searching for game..." sb.open("https://lichess.org/?any#hook") # Join a random game while True: try: # 1. Check if it's our turn (Scrape the Lichess move list) if sb.is_element_visible(".moves"): # Update local state.board based on move list # (Simplified for this example) try: state.status = "Logging into Lichess..." sb.uc_open_with_reconnect("https://lichess.org/login", 5) # Simple login automation sb.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 lobby while True: # 1. Detect if a game is active by looking for the board if sb.is_element_visible(".cg-wrap"): state.status = "Game Active" if state.board.turn == chess.WHITE: # Change based on your color state.status = "Thinking..." # RL Decision: Pick the move that results in highest board value # 2. Check if it is our turn (simplified logic) # In a real scenario, you'd scrape the 'moves' list to sync state.board if state.board.turn == chess.WHITE: legal_moves = list(state.board.legal_moves) best_move = random.choice(legal_moves) # Start with random # Execute Move in Browser # Lichess uses 'cg-board'. We click start and end squares. from_sq = chess.square_name(best_move.from_square) to_sq = chess.square_name(best_move.to_square) sb.click(f'.square[data-square="{from_sq}"]') time.sleep(random.uniform(0.1, 0.3)) sb.click(f'.square[data-square="{to_sq}"]') state.board.push(best_move) state.last_move = best_move.uci() if legal_moves: move = random.choice(legal_moves) # Replace with model.predict() # 3. Human-like clicking on the Lichess board from_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(1) # Check for game end and Learn if state.board.is_game_over(): reward = 1 if state.board.result() == "1-0" else -1 # Perform RL Update logic here state.board.reset() state.status = "Game Over. Learning..." except Exception as e: state.status = f"Error: {str(e)[:50]}" time.sleep(2) except Exception as e: state.status = f"Critical Error: {str(e)[:50]}"
# --- 4. THE LIVE DASHBOARD ---def refresh_ui(): svg = chess.svg.board(state.board, size=350) return svg, state.last_move, state.status# --- 4. THE LIVE DASHBOARD (Gradio 6.0 Style) ---def get_live_update(): # Generate the SVG of the current board state board_svg = chess.svg.board(state.board, size=400) return board_svg, state.last_move, state.status
with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("## ♟️ Lichess RL Bot Live Stream")with gr.Blocks() as demo: gr.Markdown("# ♟️ Lichess RL Bot Live Dashboard") with gr.Row(): display = gr.HTML() board_output = gr.HTML(label="Live Board") with gr.Column(): m_lbl = gr.Label(label="Last Move") s_lbl = gr.Label(label="System Status") move_info = gr.Label(label="Last Bot Move") status_info = gr.Label(label="System Status") timer = gr.Timer(1.5) timer.tick(refresh_ui, outputs=[display, m_lbl, s_lbl]) # Gradio 6.0 Timer for live updates refresh_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 thread threading.Thread(target=run_bot, daemon=True).start() # LAUNCH: Crucial for Hugging Face "Leaking" demo.launch() demo.launch( server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft() )app.py+72-87