Spaces:
Running
Running
Update app.py
Browse files12345567678910111011121314131516171617181920192122232324242526262728273031323334353637383940414243444546474849282930313233345253353637385539404157584243444546606162474849506465666768697051525354555657585960616263646566676869708271728485867374757677787980928182949583849798998586878810310489901079110911092939411411511611711811912012112212312412512612712812913013113213313413513613713813914014114214395969798991001011021031041051061451071081471481491501091101521111121131141551561571581591601611621631641651661151161171691701181191201211731741751221231241251261271281291301311791801811321331341841351361861871371381391891901911921401411421431441451463 unmodified lines150151152202153154155156157158159160161162163164165210211212213214215166167217218219220221222223168169170171172173174175176177178179180181182183184185186187188189190191192226227193194229230231195196197198199200236237201202203204205206207208209210211212213214241242215216217218219245220247248249250251252221222223224225254255226227228229230231232233234235236237238239240241242243244245246247248249250251252253263254255265256257258259260261262272273274263264265# app.pyimport gradio as grimport asyncioimport threadingimport osimport randomimport tracebackfrom queue import Queue # For communication if needed, though run_coroutine_threadsafe handles resultsimport random # <-- Import the random module
# Import poke-env componentsfrom poke_env.player import Player, RandomPlayerfrom poke_env import AccountConfiguration, ServerConfigurationfrom agents import OpenAIAgent # Assuming this existsfrom poke_env import AccountConfiguration,ServerConfiguration# Import your custom agentfrom agents import OpenAIAgent
# --- Global variables ---# --- Global variables for players and thread ---random_player: Player | None = Noneopenai_agent: Player | None = Nonepoke_env_loop: asyncio.AbstractEventLoop | None = None # Store the dedicated looppoke_env_thread: threading.Thread | None = Noneagent_init_thread: threading.Thread | None = Noneinit_lock = threading.Lock() # To prevent race conditions during initagents_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" "wss://jofthomas.com/showdown/websocket", # WebSocket URL "https://jofthomas.com/showdown/action.php" # Authentication URL)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_loop try: 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 indefinitely poke_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 release print("Poke-env event loop stopped.") poke_env_loop = None # Clear the loop variable# --- Dynamic Account Configuration ---# Define base names for the botsRANDOM_PLAYER_BASE_NAME = "RandomAgent"OPENAI_AGENT_BASE_NAME = "OpenAIAgent" # You can change this if you like
DEFAULT_BATTLE_FORMAT = "gen9randombattle"
async def initialize_agents_async(): """Coroutine to initialize agents within the dedicated loop."""# --- Agent Initialization ---def initialize_agents_sync(): """Initializes both player agents in a background thread.""" global random_player, openai_agent, agents_initialized # Generate random suffixes # 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) # Not used in current config
openai_agent_suffix = random.randint(1000, 999999) # Construct full usernames random_player_username = f"{RANDOM_PLAYER_BASE_NAME}{random_player_suffix}" # Your code uses a fixed name and password from env var for the second agent openai_agent_username = "MistralAgent" # Or use OPENAI_AGENT_BASE_NAME + suffix if intended
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_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)
openai_account_config = AccountConfiguration(openai_agent_username, None) # Optional: Print the generated usernames for confirmation when the script starts print(f"Using RandomPlayer username: {random_account_config.username}") print(f"Using OpenAIAgent username: {openai_account_config.username}")
# Ensure this runs only once with init_lock: if agents_initialized: print("Agents already initialized.") return print("Initializing agents...") # We need an event loop in this new thread for player initialization loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: # Initialize Random Player - PASSING THE CONFIGURATION # Use the dynamically generated username from random_account_config print(f"Initializing RandomPlayer ({random_account_config.username})...") random_player = RandomPlayer( account_configuration=random_account_config, account_configuration=random_account_config, # <-- Pass the 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 battle_format=DEFAULT_BATTLE_FORMAT ) print("RandomPlayer initialized.")
# Initialize OpenAI Agent - PASSING THE CONFIGURATION # Use the dynamically generated username from openai_account_config print(f"Initializing OpenAIAgent ({openai_account_config.username})...") openai_agent = OpenAIAgent( account_configuration=openai_account_config, account_configuration=openai_account_config, # <-- Pass the config server_configuration=custom_config, battle_format=DEFAULT_BATTLE_FORMAT, # loop=poke_env_loop # Check poke-env docs if 'loop' parameter is accepted battle_format=DEFAULT_BATTLE_FORMAT ) # 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 = True print("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 partially if isinstance(random_player, Player): random_player.close() # Attempt cleanup if possible if isinstance(openai_agent, Player): openai_agent.close() random_player = None openai_agent = None agents_initialized = False
def start_poke_env_thread(): """Starts the background thread for the poke-env event loop and agent initialization.""" global poke_env_thread, poke_env_loop if 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 Queue import time time.sleep(1)
if poke_env_loop: print("Scheduling agent initialization...") # Schedule the async initialization function to run on the background loop future = asyncio.run_coroutine_threadsafe(initialize_agents_async(), poke_env_loop) # Optionally wait for init to finish or handle errors try: future.result(timeout=60) # Wait for initialization up to 60 seconds print("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.")
# 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_thread if 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.") print("Agents already initialized, no need to start thread.") else: print("Poke-env thread already running (initialization might be in progress or failed).")
# --- Battle Invitation Logic (Revised) --- print("Initialization thread already running.")
# Keep the async function as is, but improve logging slightly# --- 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.""" # Check player state *before* attempting player_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) # Example return f"Error: Player {player_name} is not connected or logged in."
if player is None: # Should be caught before calling 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."
return "Error: Please enter a valid Showdown username." try: # player.username should reflect the name set in AccountConfiguration 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 necessary await player.send_challenges(username, n_challenges=1) # Pass format if needed print(player) # Keep this for debugging if needed # Pass the battle_format if you want it to be different from player's default await player.send_challenges(username, n_challenges=1) # Pass format here return f"Battle invitation ({battle_format}) sent to {username} from bot {player.username}! Check Showdown." except Exception as e: # Log the full error for debugging import traceback # Make sure player.username exists even if there's an error before login completes player_name = getattr(player, 'username', 'unknown player') 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. traceback.print_exc() # Print stack trace return f"Error sending challenge: {str(e)}. Check console logs."
# Wrapper for Gradio (Revised)# 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 via the background loop.""" global random_player, openai_agent, agents_initialized, poke_env_loop """Selects the agent and initiates the battle invitation.""" global random_player, openai_agent, agents_initialized
if 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 running return "Agents are not ready or the background process is not running. Please wait a moment and try again." if not agents_initialized: # Try to initialize if the button is clicked before init finishes start_agent_initialization() return "Agents are initializing, please wait a few seconds and try again."
selected_player: Player | None = None if agent_choice == "Random Player":3 unmodified lines elif agent_choice == "OpenAI Agent": selected_player = openai_agent if selected_player is None: return "Error: OpenAI Agent not available. Check initialization logs and SHOWDOWN_PSWD." # Check if API key might be the issue if 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 provided username_clean = username.strip() if not username_clean: return "Please enter your Showdown username."
# Ensure we have a valid player before proceeding if 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 --- # Run the async challenge function in a managed event loop try: # Schedule the async function on the dedicated poke-env loop future = 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 timeout result = future.result(timeout=30) # Adjust timeout as needed # Try to get the existing loop from the init thread or create a new one try: 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 complete if loop.is_running(): # Schedule the coroutine and wait for its result future = asyncio.run_coroutine_threadsafe( # Pass the default battle format explicitly if needed send_battle_invite_async(selected_player, username_clean, DEFAULT_BATTLE_FORMAT), loop ) result = future.result(timeout=30) # Add a timeout else: result = loop.run_until_complete( # Pass the default battle format explicitly if needed send_battle_invite_async(selected_player, username_clean, DEFAULT_BATTLE_FORMAT) )
return result except 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." return "Error: Sending challenge timed out." 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}") print(f"Unexpected error in invite_to_battle's async execution: {e}") import traceback 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>"""# --- Gradio UI Definition ---# iframe code to embed Pokemon Showdown (using official URL)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 starts start_poke_env_thread() # Start agent initialization when the app is defined/loaded start_agent_initialization()
# Using gr.Blocks. The default layout should stretch reasonably wide. 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 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" ) name_input = gr.Textbox("your name") battle_button = gr.Button('Battle invitation')
# --- Row for Controls at the Top --- with gr.Row(): # Place controls here agent_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 width gr.HTML(iframe_code)
# --- Connect button click to the invitation function --- 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__": # Create and launch the Gradio app 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() # 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 networkapp.py+155-164