Spaces:
Running
Running
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941953 unmodified lines199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274import gradio as grimport asyncioimport threadingimport osimport randomimport tracebackfrom queue import Queue # For communication if needed, though run_coroutine_threadsafe handles resultsfrom poke_env.player import Player, RandomPlayerfrom poke_env import AccountConfiguration, ServerConfigurationfrom agents import OpenAIAgent # Assuming this exists# --- Global variables ---random_player: Player | None = Noneopenai_agent: Player | None = Nonepoke_env_loop: asyncio.AbstractEventLoop | None = None # Store the dedicated looppoke_env_thread: threading.Thread | None = Noneagents_initialized = Falseinit_lock = threading.Lock() # Keep the lock for initialization logic# --- Configuration ---custom_config = ServerConfiguration("wss://jofthomas.com/showdown/websocket","https://jofthomas.com/showdown/action.php")RANDOM_PLAYER_BASE_NAME = "RandomAgent"OPENAI_AGENT_BASE_NAME = "OpenAIAgent" # Note: Your code uses "MistralAgent" for OpenAI configDEFAULT_BATTLE_FORMAT = "gen9randombattle"# --- Background Thread and Loop Management ---def run_poke_env_loop():"""Target function for the background thread. Runs the asyncio loop."""global poke_env_looptry:print("Starting dedicated poke-env event loop...")poke_env_loop = asyncio.new_event_loop()asyncio.set_event_loop(poke_env_loop)# Keep the loop running indefinitelypoke_env_loop.run_forever()except Exception as e:print(f"!!! Error in poke-env background loop: {e}")traceback.print_exc()finally:if poke_env_loop and poke_env_loop.is_running():poke_env_loop.stop() # Gracefully stop if possible# Consider loop.close() after stopping if resources need explicit releaseprint("Poke-env event loop stopped.")poke_env_loop = None # Clear the loop variableasync def initialize_agents_async():"""Coroutine to initialize agents within the dedicated loop."""global random_player, openai_agent, agents_initialized# Generate random suffixesrandom_player_suffix = random.randint(1000, 999999)# openai_agent_suffix = random.randint(1000, 999999) # Not used in current configrandom_player_username = f"{RANDOM_PLAYER_BASE_NAME}{random_player_suffix}"# Your code uses a fixed name and password from env var for the second agentopenai_agent_username = "MistralAgent" # Or use OPENAI_AGENT_BASE_NAME + suffix if intendedrandom_account_config = AccountConfiguration(random_player_username, None)openai_password = os.environ.get('SHOWDOWN_PSWD')if not openai_password:print("!!! WARNING: SHOWDOWN_PSWD environment variable not set for OpenAI agent.")# Decide how to handle this - maybe prevent OpenAI agent init?# For now, we'll let it potentially fail during init below.openai_account_config = AccountConfiguration(openai_agent_username, openai_password)print(f"Using RandomPlayer username: {random_account_config.username}")print(f"Using OpenAIAgent username: {openai_account_config.username}")with init_lock:if agents_initialized:print("Agents already initialized.")returnprint("Initializing agents...")try:print(f"Initializing RandomPlayer ({random_account_config.username})...")random_player = RandomPlayer(account_configuration=random_account_config,server_configuration=custom_config,battle_format=DEFAULT_BATTLE_FORMAT,# Explicitly provide the loop if poke-env supports it, otherwise it uses asyncio.get_event_loop()# loop=poke_env_loop # Check poke-env docs if 'loop' parameter is accepted)print("RandomPlayer initialized.")print(f"Initializing OpenAIAgent ({openai_account_config.username})...")openai_agent = OpenAIAgent(account_configuration=openai_account_config,server_configuration=custom_config,battle_format=DEFAULT_BATTLE_FORMAT,# loop=poke_env_loop # Check poke-env docs if 'loop' parameter is accepted)# Add a small delay or check for connection status if needed# await asyncio.sleep(2) # Example: Allow time for connection# Add checks like: if random_player.logged_in and openai_agent.logged_in:print("OpenAIAgent initialized.")agents_initialized = Trueprint("Agent initialization complete.")# else: raise RuntimeError("One or more agents failed to log in.")except Exception as e:print(f"!!! Error during agent initialization: {e}")traceback.print_exc()# Reset globals if init fails partiallyif isinstance(random_player, Player): random_player.close() # Attempt cleanup if possibleif isinstance(openai_agent, Player): openai_agent.close()random_player = Noneopenai_agent = Noneagents_initialized = Falsedef start_poke_env_thread():"""Starts the background thread for the poke-env event loop and agent initialization."""global poke_env_thread, poke_env_loopif poke_env_thread is None or not poke_env_thread.is_alive():print("Starting poke-env background thread and loop...")poke_env_thread = threading.Thread(target=run_poke_env_loop, daemon=True)poke_env_thread.start()# Wait briefly for the loop to start before scheduling init# A more robust way would use threading.Event or Queueimport timetime.sleep(1)if poke_env_loop:print("Scheduling agent initialization...")# Schedule the async initialization function to run on the background loopfuture = asyncio.run_coroutine_threadsafe(initialize_agents_async(), poke_env_loop)# Optionally wait for init to finish or handle errorstry:future.result(timeout=60) # Wait for initialization up to 60 secondsprint("Agent initialization scheduled and completed.")except Exception as e:print(f"!!! Agent initialization failed: {e}")# Handle the case where init itself failed# The background loop thread will still be running unless it crashed.else:print("!!! Error: poke-env loop did not start correctly.")elif agents_initialized:print("Agents already initialized.")else:print("Poke-env thread already running (initialization might be in progress or failed).")# --- Battle Invitation Logic (Revised) ---# Keep the async function as is, but improve logging slightlyasync def send_battle_invite_async(player: Player, username: str, battle_format: str = DEFAULT_BATTLE_FORMAT):"""Sends a challenge using the provided player object."""# Check player state *before* attemptingplayer_name = getattr(player, 'username', 'unknown player')is_connected = getattr(player, 'connected', False)is_logged_in = getattr(player, 'logged_in', False)print(f"Sending invite: Player={player_name}, Connected={is_connected}, LoggedIn={is_logged_in}")if not is_connected or not is_logged_in:# Maybe try to reconnect or log in here if poke-env supports it easily?# await player.log_in(player.account_configuration.username, player.account_configuration.password) # Examplereturn f"Error: Player {player_name} is not connected or logged in."if player is None: # Should be caught before callingreturn "Error: The selected player is not available/initialized."if not username or not username.strip():return "Error: Please enter a valid Showdown username."try:print(f"Attempting to send challenge from {player.username} to {username} in format {battle_format}")# Ensure challenge format is correct if needed# Check player._battle_format vs battle_format if necessaryawait player.send_challenges(username, n_challenges=1) # Pass format if neededreturn f"Battle invitation ({battle_format}) sent to {username} from bot {player.username}! Check Showdown."except Exception as e:print(f"Error sending challenge from {player_name}:")traceback.print_exc() # Print full stack trace# Consider what state the player might be in now.# Resetting the player state might be needed but is complex.return f"Error sending challenge: {str(e)}. Check console logs."# Wrapper for Gradio (Revised)def invite_to_battle(agent_choice: str, username: str):"""Selects the agent and initiates the battle invitation via the background loop."""global random_player, openai_agent, agents_initialized, poke_env_loopif not agents_initialized or poke_env_loop is None or not poke_env_loop.is_running():# Maybe try starting again? Or just inform user.start_poke_env_thread() # Attempt to start if not runningreturn "Agents are not ready or the background process is not running. Please wait a moment and try again."selected_player: Player | None = Noneif agent_choice == "Random Player":3 unmodified lineselif agent_choice == "OpenAI Agent":selected_player = openai_agentif selected_player is None:return "Error: OpenAI Agent not available. Check initialization logs and SHOWDOWN_PSWD."else:return "Error: Invalid agent choice selected."username_clean = username.strip()if not username_clean:return "Please enter your Showdown username."# Ensure we have a valid player before proceedingif selected_player is None:# This case should ideally be caught by the checks above, but double-check.return "Error: Could not select a valid player agent."# --- Crucial Change: Use run_coroutine_threadsafe ---try:# Schedule the async function on the dedicated poke-env loopfuture = asyncio.run_coroutine_threadsafe(send_battle_invite_async(selected_player, username_clean, DEFAULT_BATTLE_FORMAT),poke_env_loop)# Wait for the result from the background loop with a timeoutresult = future.result(timeout=30) # Adjust timeout as neededreturn resultexcept TimeoutError:print(f"Timeout waiting for challenge result from {getattr(selected_player, 'username', agent_choice)}")return "Error: Sending challenge timed out. The bot might be busy or disconnected."except Exception as e:# This catches errors in scheduling or retrieving the result,# or unexpected errors from the coroutine itself if not caught internally.print(f"Unexpected error in invite_to_battle scheduling/execution: {e}")traceback.print_exc()return f"An unexpected error occurred: {e}"# --- Gradio UI Definition (Mostly Unchanged) ---iframe_code = """<iframe src="https://jofthomas.com/play.pokemonshowdown.com/testclient.html" width="100%" height="800" style="border: none;" referrerpolicy="no-referrer"></iframe>"""def main_app():"""Creates and returns the Gradio application interface."""# Start the background thread and loop when the app startsstart_poke_env_thread()with gr.Blocks(title="Pokemon Showdown Agent") as demo:# ... (rest of your UI definition is likely fine) ...gr.Markdown("# Pokémon Battle Agent")agent_dropdown = gr.Dropdown(label="Select Agent",choices=["Random Player", "OpenAI Agent"],value="Random Player",scale=1)name_input = gr.Textbox("your name")battle_button = gr.Button('Battle invitation')gr.Markdown("### Pokémon Showdown Interface")gr.Markdown("Log in/use the username you entered above.")gr.HTML(iframe_code)battle_button.click(fn=invite_to_battle,inputs=[agent_dropdown, name_input],outputs=gr.Textbox(label="Status") # Add an output Textbox to display results/errors)return demo# --- Main execution block ---if __name__ == "__main__":app = main_app()# Add proper app closing logic if needed to shut down the loop/thread gracefully# For simple cases, daemon thread might be enough, but explicit shutdown is better.app.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451463 unmodified lines150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265# app.pyimport gradio as grimport asyncioimport threadingimport osimport random # <-- Import the random module# Import poke-env componentsfrom poke_env.player import Player, RandomPlayerfrom poke_env import AccountConfiguration,ServerConfiguration# Import your custom agentfrom agents import OpenAIAgent# --- Global variables for players and thread ---random_player: Player | None = Noneopenai_agent: Player | None = Noneagent_init_thread: threading.Thread | None = Noneinit_lock = threading.Lock() # To prevent race conditions during initagents_initialized = False# --- Configuration ---custom_config = ServerConfiguration("wss://jofthomas.com/showdown/websocket", # WebSocket URL"https://jofthomas.com/showdown/action.php" # Authentication URL)# --- Dynamic Account Configuration ---# Define base names for the botsRANDOM_PLAYER_BASE_NAME = "RandomAgent"OPENAI_AGENT_BASE_NAME = "OpenAIAgent" # You can change this if you likeDEFAULT_BATTLE_FORMAT = "gen9randombattle"# --- Agent Initialization ---def initialize_agents_sync():"""Initializes both player agents in a background thread."""global random_player, openai_agent, agents_initialized# Generate random suffixes (4-6 digits, i.e., 1000 to 999999)random_player_suffix = random.randint(1000, 999999)openai_agent_suffix = random.randint(1000, 999999)# Construct full usernamesrandom_player_username = f"{RANDOM_PLAYER_BASE_NAME}{random_player_suffix}"openai_agent_username = f"{OPENAI_AGENT_BASE_NAME}{openai_agent_suffix}"# Create AccountConfiguration objects with dynamic usernames and no password (guest)random_account_config = AccountConfiguration(random_player_username, None)openai_account_config = AccountConfiguration(openai_agent_username, None)# Optional: Print the generated usernames for confirmation when the script startsprint(f"Using RandomPlayer username: {random_account_config.username}")print(f"Using OpenAIAgent username: {openai_account_config.username}")# Ensure this runs only oncewith init_lock:if agents_initialized:print("Agents already initialized.")returnprint("Initializing agents...")# We need an event loop in this new thread for player initializationloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)try:# Initialize Random Player - PASSING THE CONFIGURATION# Use the dynamically generated username from random_account_configprint(f"Initializing RandomPlayer ({random_account_config.username})...")random_player = RandomPlayer(account_configuration=random_account_config, # <-- Pass the configserver_configuration=custom_config,battle_format=DEFAULT_BATTLE_FORMAT)print("RandomPlayer initialized.")# Initialize OpenAI Agent - PASSING THE CONFIGURATION# Use the dynamically generated username from openai_account_configprint(f"Initializing OpenAIAgent ({openai_account_config.username})...")openai_agent = OpenAIAgent(account_configuration=openai_account_config, # <-- Pass the configserver_configuration=custom_config,battle_format=DEFAULT_BATTLE_FORMAT)print("OpenAIAgent initialized.")agents_initialized = Trueprint("Agent initialization complete.")except Exception as e:print(f"!!! Error during agent initialization: {e}")# Reset globals if init fails partiallyrandom_player = Noneopenai_agent = Noneagents_initialized = False# Note: Don't close the loop here, the players might need it running implicitly# loop.close()# Function to start the initialization threaddef start_agent_initialization():"""Starts the agent initialization thread if not already running."""global agent_init_threadif not agents_initialized and (agent_init_thread is None or not agent_init_thread.is_alive()):print("Starting agent initialization thread...")agent_init_thread = threading.Thread(target=initialize_agents_sync, daemon=True)agent_init_thread.start()elif agents_initialized:print("Agents already initialized, no need to start thread.")else:print("Initialization thread already running.")# --- Battle Invitation Logic ---# Using player.username SHOULD automatically use the assigned usernameasync def send_battle_invite_async(player: Player, username: str, battle_format: str = DEFAULT_BATTLE_FORMAT):"""Sends a challenge using the provided player object."""if player is None:return "Error: The selected player is not available/initialized."if not username or not username.strip():return "Error: Please enter a valid Showdown username."try:# player.username should reflect the name set in AccountConfigurationprint(f"Attempting to send challenge from {player.username} to {username} in format {battle_format}")print(player) # Keep this for debugging if needed# Pass the battle_format if you want it to be different from player's defaultawait player.send_challenges(username, n_challenges=1) # Pass format herereturn f"Battle invitation ({battle_format}) sent to {username} from bot {player.username}! Check Showdown."except Exception as e:# Log the full error for debuggingimport traceback# Make sure player.username exists even if there's an error before login completesplayer_name = getattr(player, 'username', 'unknown player')print(f"Error sending challenge from {player_name}:")traceback.print_exc() # Print stack tracereturn f"Error sending challenge: {str(e)}. Check console logs."# Wrapper for the async function to use in Gradio, handling agent selectiondef invite_to_battle(agent_choice: str, username: str):"""Selects the agent and initiates the battle invitation."""global random_player, openai_agent, agents_initializedif not agents_initialized:# Try to initialize if the button is clicked before init finishesstart_agent_initialization()return "Agents are initializing, please wait a few seconds and try again."selected_player: Player | None = Noneif agent_choice == "Random Player":3 unmodified lineselif agent_choice == "OpenAI Agent":selected_player = openai_agentif selected_player is None:# Check if API key might be the issueif not os.getenv("OPENAI_API_KEY"):return "Error: OpenAI Agent not available. OPENAI_API_KEY is missing."else:return "Error: OpenAI Agent not available. Initialization might have failed. Check logs."else:return "Error: Invalid agent choice selected."# Ensure username is providedusername_clean = username.strip()if not username_clean:return "Please enter your Showdown username."# Run the async challenge function in a managed event looptry:# Try to get the existing loop from the init thread or create a new onetry:loop = asyncio.get_running_loop()except RuntimeError:print("No running event loop, creating new one for challenge.")loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)# If the main loop is running, schedule the task; otherwise, run until completeif loop.is_running():# Schedule the coroutine and wait for its resultfuture = asyncio.run_coroutine_threadsafe(# Pass the default battle format explicitly if neededsend_battle_invite_async(selected_player, username_clean, DEFAULT_BATTLE_FORMAT),loop)result = future.result(timeout=30) # Add a timeoutelse:result = loop.run_until_complete(# Pass the default battle format explicitly if neededsend_battle_invite_async(selected_player, username_clean, DEFAULT_BATTLE_FORMAT))return resultexcept TimeoutError:return "Error: Sending challenge timed out."except Exception as e:print(f"Unexpected error in invite_to_battle's async execution: {e}")import tracebacktraceback.print_exc()return f"An unexpected error occurred: {e}"# --- Gradio UI Definition ---# iframe code to embed Pokemon Showdown (using official URL)iframe_code = """<iframesrc="https://jofthomas.com/play.pokemonshowdown.com/testclient.html"width="100%"height="800"style="border: none;"referrerpolicy="no-referrer"></iframe>"""def main_app():"""Creates and returns the Gradio application interface."""# Start agent initialization when the app is defined/loadedstart_agent_initialization()# Using gr.Blocks. The default layout should stretch reasonably wide.with gr.Blocks(title="Pokemon Showdown Agent") as demo:gr.Markdown("# Pokémon Battle Agent")gr.Markdown("Select an agent, enter **your** Showdown username ""(the one you are logged in with below), and click Send Invite.""Note : you can just select a random set of character as long as someone registered does not already use this username")# --- Row for Controls at the Top ---with gr.Row():# Place controls hereagent_dropdown = gr.Dropdown(label="Select Agent",choices=["Random Player", "OpenAI Agent"],value="Random Player",scale=1 # Give dropdown reasonable space)name_input = gr.Textbox(label="Your Pokémon Showdown Username",placeholder="Enter username used in Showdown below",scale=2 # Give name input more relative space)battle_button = gr.Button("Send Battle Invitation", scale=1) # Button takes less space# --- Section for the IFrame below the controls ---gr.Markdown("### Pokémon Showdown Interface")gr.Markdown("Log in/use the username you entered above.")# The HTML component containing the iframe will take up the available widthgr.HTML(iframe_code)# --- Connect button click to the invitation function ---battle_button.click(fn=invite_to_battle,inputs=[agent_dropdown, name_input],)return demo# --- Main execution block ---if __name__ == "__main__":# Create and launch the Gradio appapp = main_app()# You might need to configure server_name and server_port depending on your deployment environment# Use app.launch(share=True) for a public link (if needed and safe)app.launch() # server_name="0.0.0.0" # To make accessible on network
app.py+155-164