Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import gradio as grimport chessimport chess.svgimport threadingimport timefrom seleniumbase import SB# --- Global State ---class GameInfo:def __init__(self):self.board = chess.Board()self.last_move = "Waiting for game..."self.status = "Idle"state = GameInfo()def bot_loop():""" The background thread that plays on Lichess """with SB(uc=True, headless=True) as sb:# 1. Login to Lichess (Use secrets for credentials!)sb.uc_open_with_reconnect("https://lichess.org/login", 5)# Add your login automation here...while True:try:# 2. Check if in a game & Scrape board# (Logic to convert Lichess HTML to FEN goes here)# For now, we simulate the board update:if not state.board.is_game_over():# ML logic would go herestate.status = "Playing..."# Update global state so the UI sees it# state.board.push(move)time.sleep(2) # Don't spam the CPUexcept Exception as e:state.status = f"Error: {e}"time.sleep(5)# --- Gradio UI ---def update_display():""" Generates the SVG board and text for the website """board_svg = chess.svg.board(state.board, size=400)return board_svg, f"Last Move: {state.last_move}", f"Status: {state.status}"with gr.Blocks() as demo:gr.Markdown("# 🤖 Lichess RL Bot Live Tracker")with gr.Row():board_view = gr.HTML() # Displays the SVG boardwith gr.Column():move_label = gr.Label(label="Current Move")status_label = gr.Label(label="Bot Status")# Auto-refresh the UI every 2 secondsdemo.load(update_display, None, [board_view, move_label, status_label], every=2)if __name__ == "__main__":# Start the bot threadt = threading.Thread(target=bot_loop, daemon=True)t.start()# Launch the websitedemo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import osimport timeimport randomimport threadingimport chessimport 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) ---class ChessNet(nn.Module):def __init__(self):super().__init__()# Input: 8x8 board with 12 piece typesself.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)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 += 6tensor[p_type, row, col] = 1return torch.from_numpy(tensor).unsqueeze(0)# --- 2. THE STATE MANAGER ---class BotState:def __init__(self):self.board = chess.Board()self.status = "Initializing..."self.last_move = "None"self.model = ChessNet()self.optimizer = optim.Adam(self.model.parameters(), lr=0.001)state = BotState()# --- 3. THE BOT LOGIC (Selenium) ---def run_bot():# Use Hugging Face Secrets for LoginUSER = os.getenv("LICHESS_USER", "YourUsername")PASS = os.getenv("LICHESS_PASS", "YourPassword")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 gamewhile 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)if state.board.turn == chess.WHITE: # Change based on your colorstate.status = "Thinking..."# RL Decision: Pick the move that results in highest board valuelegal_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()time.sleep(1)# Check for game end and Learnif state.board.is_game_over():reward = 1 if state.board.result() == "1-0" else -1# Perform RL Update logic herestate.board.reset()state.status = "Game Over. Learning..."except Exception as e:state.status = f"Error: {str(e)[:50]}"time.sleep(2)# --- 4. THE LIVE DASHBOARD ---def refresh_ui():svg = chess.svg.board(state.board, size=350)return svg, state.last_move, state.statuswith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("## ♟️ Lichess RL Bot Live Stream")with gr.Row():display = gr.HTML()with gr.Column():m_lbl = gr.Label(label="Last Move")s_lbl = gr.Label(label="System Status")timer = gr.Timer(1.5)timer.tick(refresh_ui, outputs=[display, m_lbl, s_lbl])if __name__ == "__main__":threading.Thread(target=run_bot, daemon=True).start()demo.launch()
app.py+109-43