File size: 9,066 Bytes
b6ac3ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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()