import json import gradio as gr import time import modal import threading import tempfile import os import re import asyncio from concurrent.futures import ThreadPoolExecutor # Note: TTS and visualization features are disabled for HF Spaces compatibility # These require system-level dependencies not available in the cloud environment print("šŸŒ Starting Agentic Ecosystem Simulator for Hugging Face Spaces...") # Initialize Modal app for simplified functions app = modal.App("agentic-ecosystem-simple") def simulate_ecosystem_step(environment): """Main orchestration function - runs the text-based ecosystem simulation using Modal""" if not environment or not environment.strip(): return None, [], "Please provide an environment description.", None try: print(f"🌱 Simulating ecosystem for environment: {environment}") # Call deployed Modal function using the new API f = modal.Function.from_name("agentic-ecosystem-simple", "simulate_ecosystem") results = f.remote(environment) # Check for errors if 'error' in results and results['error']: print(f"āŒ Error in simulation: {results['error']}") return None, [], f"Simulation error: {results['error']}", None # Process species data species_list = results['species'] print(f"āœ“ Generated {len(species_list)} species") # Process events and summary events = results['events'] summary = results['summary'] print("āœ“ Generated events and summary") print("šŸŽ‰ Ecosystem simulation completed!") return ( species_list, events, summary, "šŸ”‡ Audio narration not available in HF Spaces environment" ) except Exception as e: print(f"Error in ecosystem simulation: {e}") return None, [], f"Simulation error: {str(e)}", None def check_modal_deployment(): """Check if Modal is properly configured""" try: # Try to lookup the deployed function using new API f = modal.Function.from_name("agentic-ecosystem-simple", "simulate_ecosystem") return "āœ… Modal is properly configured and deployed!\n\nThe ecosystem simulator is ready to use." except Exception as e: return f"āŒ Modal error: {str(e)}\nPlease ensure Modal functions are deployed and accessible." # Create custom nature-themed color scheme nature_theme = gr.themes.Soft().set( body_background_fill="#d4edda", # Light green background background_fill_primary="#e8f5e8", # Medium light green background_fill_secondary="#d6ebf5", # Light blue block_background_fill="#f8f9fa", # Off-white for content blocks button_primary_background_fill="#1e7e34", # Forest green for primary buttons button_primary_background_fill_hover="#28a745", # Medium green on hover button_primary_text_color="#ffffff", button_secondary_background_fill="#c3e6cb", # Light green for secondary buttons button_secondary_background_fill_hover="#b3d7e6", # Light blue on hover button_secondary_text_color="#155724" # Dark green text ) with gr.Blocks(title="Agentic Ecosystem Simulator", theme=nature_theme, css=""" /* Additional custom CSS for nature theme */ .gradio-container { background: linear-gradient(135deg, #c8e6c8 0%, #b8d4e8 50%, #d0e2f0 100%); min-height: 100vh; } /* Card-like styling for content blocks */ .block { background: rgba(248, 249, 250, 0.95); border-radius: 8px; border: 1px solid #6c9a6c; box-shadow: 0 2px 8px rgba(28, 126, 52, 0.1); } /* Nature-themed headers */ h1, h2, h3 { color: #155724; text-shadow: 1px 1px 2px rgba(28, 126, 52, 0.15); } """) as demo: gr.Markdown(""" # šŸŒ Agentic Ecosystem Simulator ## Powered by Modal Cloud Functions Welcome to the Cloud-Based Ecosystem Simulator! This application uses multiple AI models working together through Modal cloud functions to create and simulate a living ecosystem through text. **How it works:** 1. **🧬 Species Generation** - AI creates plants and animals specifically adapted to your environment 2. **šŸ”„ Interaction Simulation** - AI simulates ecological interactions specific to your environment 3. **šŸ“‹ Ecosystem Summary** - Key events are summarized with environmental context 4. **🌿 Environment Analysis** - Your input is analyzed for environment type, climate, time, season & more **The more detailed your environment description, the more tailored your ecosystem will be!** šŸš€ **Status**: Running on Hugging Face Spaces with Modal cloud backend āš ļø **Note**: Audio narration and visualization features are disabled in this cloud environment """) with gr.Row(): with gr.Column(scale=2): environment_input = gr.Textbox( label="🌿 Environment Description (be specific and detailed!)", placeholder="e.g., 'tropical rainforest with morning mist and flowering vines', 'desert oasis with palm trees and rocky outcrops at sunset'", lines=3, value="temperate meadow in spring morning with wildflowers and gentle breeze" ) simulate_btn = gr.Button("šŸš€ Simulate Ecosystem Day", variant="primary", size="lg") modal_status = gr.Textbox( label="šŸ–„ļø Modal Status", value="Click 'Check Modal' to see connection status", lines=4, interactive=False ) check_modal_btn = gr.Button("šŸ” Check Modal Connection", variant="secondary") with gr.Column(scale=3): species_output = gr.JSON( label="🧬 Generated Species", show_label=True ) with gr.Row(): with gr.Column(): events_output = gr.Textbox( label="šŸ“… Day's Events", lines=8, show_label=True ) with gr.Column(): summary_output = gr.Textbox( label="šŸ“‹ Ecosystem Summary", lines=8, show_label=True ) audio_status = gr.Textbox( label="šŸŽµ Audio Status", value="šŸ”‡ Audio narration not available in HF Spaces environment", lines=2, interactive=False ) # Event handlers simulate_btn.click( fn=simulate_ecosystem_step, inputs=[environment_input], outputs=[species_output, events_output, summary_output, audio_status] ) check_modal_btn.click( fn=check_modal_deployment, outputs=[modal_status] ) # Add example environments gr.Markdown(""" ### šŸ’” Detailed Environments to Try: **Try adding environmental details like:** - **Time of day**: morning, afternoon, evening, night - **Season**: spring, summer, autumn, winter - **Weather**: misty, sunny, rainy, cloudy, stormy - **Features**: rocky, sandy, flowering, foggy, lush, sparse **Example environments with rich details:** - `tropical rainforest with morning mist and flowering plants` - `desert oasis with palm trees and rocky outcrops at sunset` - `temperate forest clearing in autumn with golden leaves` - `alpine meadow with wildflowers on a spring morning` - `wetland marsh with reeds and shallow water during summer evening` - `volcanic island with unique flora adapting to the harsh terrain` - `underground cave system with phosphorescent fungi and still pools` - `arctic tundra with hardy vegetation under the midnight sun` ### šŸ”§ Technical Details This simulator demonstrates **agentic AI orchestration** by chaining together multiple specialized AI models: - Environment analysis and parsing - Species generation based on habitat conditions - Ecological interaction simulation - Narrative summary generation All processing happens in the cloud via Modal, making this a true **serverless AI application**. """) if __name__ == "__main__": print("\n" + "="*60) print("šŸŒ AGENTIC ECOSYSTEM SIMULATOR - HUGGING FACE SPACES") print("="*60) print("\nšŸš€ Starting Hugging Face Spaces interface...") print("\nšŸ“‹ SETUP STATUS:") print("āœ… Modal cloud functions ready") print("āœ… Hugging Face Spaces compatible version") print("āš ļø Audio and visualization features disabled for cloud compatibility") print("\n✨ Ready to simulate ecosystems!") print("="*60) demo.launch()