File size: 14,688 Bytes
6e19f63
18bb5b2
70a718e
 
18bb5b2
70a718e
 
cb42996
70a718e
46e69b0
07aeb52
70a718e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5fe8ca
70a718e
 
 
 
 
 
 
 
 
 
 
 
 
18bb5b2
70a718e
18bb5b2
70a718e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18bb5b2
70a718e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb42996
 
 
1f2f75f
 
 
cb42996
 
 
 
18bb5b2
70a718e
 
cb42996
 
18bb5b2
cb42996
 
 
b867a1d
 
 
 
 
 
 
 
1f2f75f
 
b867a1d
 
cb42996
 
 
 
 
 
 
 
18bb5b2
70a718e
 
 
 
 
 
 
cb42996
 
18bb5b2
cb42996
 
 
 
 
b867a1d
 
 
 
f9b48f4
 
b867a1d
f9b48f4
 
b867a1d
f9b48f4
 
b867a1d
 
 
 
f9b48f4
b867a1d
f9b48f4
b867a1d
 
cb42996
 
 
 
 
 
 
18bb5b2
70a718e
 
 
 
 
 
cb42996
 
 
 
ef388e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70a718e
ef388e2
 
 
 
cb42996
70a718e
 
 
ef388e2
70a718e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef388e2
 
 
 
 
70a718e
18bb5b2
ef388e2
70a718e
ef388e2
 
 
 
 
cb42996
70a718e
 
 
 
 
b5fe8ca
ef388e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70a718e
ef388e2
70a718e
ef388e2
70a718e
ef388e2
70a718e
b5fe8ca
70a718e
 
ef388e2
 
70a718e
ef388e2
 
 
 
 
 
e1c280b
70a718e
b54eb41
b5fe8ca
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import gradio as gr
import os
import json
import importlib
import sys
from contextlib import redirect_stdout, redirect_stderr
import io

# Set environment variable to avoid matplotlib permission issues
os.environ['MPLCONFIGDIR'] = '/tmp'

# Example app implementations
APP_REGISTRY = {
    "hello_world": {
        "title": "Hello World",
        "description": "A simple greeting app",
        "function": None  # will be populated
    },
    "calculator": {
        "title": "Calculator",
        "description": "A basic arithmetic calculator",
        "function": None  # will be populated
    },
    "image_filter": {
        "title": "Image Filter",
        "description": "Apply visual effects to images",
        "function": None  # will be populated
    }
}

# Hello World implementation
def create_hello_world():
    def greet(name):
        return f"Hello, {name}!"
    
    demo = gr.Interface(
        fn=greet,
        inputs=gr.Textbox(label="Your Name"),
        outputs=gr.Textbox(label="Greeting"),
        title="Hello World App",
        description="A simple greeting app",
        examples=[["World"], ["Friend"], ["Gradio"]]
    )
    
    return demo

# Calculator implementation
def create_calculator():
    def calculate(num1, num2, operation):
        if operation == "Add":
            return num1 + num2
        elif operation == "Subtract":
            return num1 - num2
        elif operation == "Multiply":
            return num1 * num2
        elif operation == "Divide":
            if num2 == 0:
                return "Error: Division by zero"
            return num1 / num2
    
    demo = gr.Interface(
        fn=calculate,
        inputs=[
            gr.Number(label="First Number"),
            gr.Number(label="Second Number"),
            gr.Radio(["Add", "Subtract", "Multiply", "Divide"], label="Operation")
        ],
        outputs=gr.Textbox(label="Result"),
        title="Calculator App",
        description="Perform basic arithmetic operations",
        examples=[
            [5, 3, "Add"],
            [10, 4, "Subtract"],
            [6, 7, "Multiply"],
            [20, 4, "Divide"]
        ]
    )
    
    return demo

# Image Filter implementation
def create_image_filter():
    def apply_filter(image, filter_type):
        if image is None:
            return None
        
        import numpy as np
        from PIL import Image
        
        img_array = np.array(image)
        
        if filter_type == "Grayscale":
            result = np.mean(img_array, axis=2).astype(np.uint8)
            return Image.fromarray(result)
        elif filter_type == "Invert":
            result = 255 - img_array
            return Image.fromarray(result)
        elif filter_type == "Sepia":
            sepia = np.array([[0.393, 0.769, 0.189],
                             [0.349, 0.686, 0.168],
                             [0.272, 0.534, 0.131]])
            sepia_img = img_array.dot(sepia.T)
            sepia_img[sepia_img > 255] = 255
            return Image.fromarray(sepia_img.astype(np.uint8))
        return image
    
    demo = gr.Interface(
        fn=apply_filter,
        inputs=[
            gr.Image(type="pil"),
            gr.Radio(["Grayscale", "Invert", "Sepia"], label="Filter")
        ],
        outputs=gr.Image(type="pil"),
        title="Image Filter App",
        description="Apply different filters to your images",
        examples=[
            ["https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500", "Grayscale"],
            ["https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500", "Invert"],
            ["https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500", "Sepia"]
        ]
    )
    
    return demo

# Register demo creation functions
APP_REGISTRY["hello_world"]["function"] = create_hello_world
APP_REGISTRY["calculator"]["function"] = create_calculator
APP_REGISTRY["image_filter"]["function"] = create_image_filter

# Example of code for each app as a string (for display purposes)
APP_CODES = {
    "hello_world": """
import gradio as gr

def greet(name):
    return f"Hello, {name}!"

demo = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(label="Your Name"),
    outputs=gr.Textbox(label="Greeting"),
    title="Hello World App",
    description="A simple greeting app",
    examples=[["World"], ["Friend"], ["Gradio"]]
)
""",

    "calculator": """
import gradio as gr

def calculate(num1, num2, operation):
    if operation == "Add":
        return num1 + num2
    elif operation == "Subtract":
        return num1 - num2
    elif operation == "Multiply":
        return num1 * num2
    elif operation == "Divide":
        if num2 == 0:
            return "Error: Division by zero"
        return num1 / num2

demo = gr.Interface(
    fn=calculate,
    inputs=[
        gr.Number(label="First Number"),
        gr.Number(label="Second Number"),
        gr.Radio(["Add", "Subtract", "Multiply", "Divide"], label="Operation")
    ],
    outputs=gr.Textbox(label="Result"),
    title="Calculator App",
    description="Perform basic arithmetic operations",
    examples=[
        [5, 3, "Add"],
        [10, 4, "Subtract"],
        [6, 7, "Multiply"],
        [20, 4, "Divide"]
    ]
)
""",

    "image_filter": """
import gradio as gr
import numpy as np
from PIL import Image

def apply_filter(image, filter_type):
    if image is None:
        return None
        
    img_array = np.array(image)
    
    if filter_type == "Grayscale":
        result = np.mean(img_array, axis=2).astype(np.uint8)
        return Image.fromarray(result)
    elif filter_type == "Invert":
        result = 255 - img_array
        return Image.fromarray(result)
    elif filter_type == "Sepia":
        sepia = np.array([[0.393, 0.769, 0.189],
                         [0.349, 0.686, 0.168],
                         [0.272, 0.534, 0.131]])
        sepia_img = img_array.dot(sepia.T)
        sepia_img[sepia_img > 255] = 255
        return Image.fromarray(sepia_img.astype(np.uint8))
    return image

demo = gr.Interface(
    fn=apply_filter,
    inputs=[
        gr.Image(type="pil"),
        gr.Radio(["Grayscale", "Invert", "Sepia"], label="Filter")
    ],
    outputs=gr.Image(type="pil"),
    title="Image Filter App",
    description="Apply different filters to your images",
    examples=[
        ["https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500", "Grayscale"],
        ["https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500", "Invert"],
        ["https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500", "Sepia"]
    ]
)
"""
}

# Create an endpoint to get the app configuration
def get_app_config(app_name):
    if app_name not in APP_REGISTRY:
        return {"error": f"App '{app_name}' not found"}
    
    return {
        "title": APP_REGISTRY[app_name]["title"],
        "description": APP_REGISTRY[app_name]["description"],
        "code": APP_CODES[app_name]
    }

# Create an endpoint to load an app
def load_app_interface(app_name):
    if app_name not in APP_REGISTRY:
        return None
    
    try:
        # Capture stdout/stderr to prevent it from polluting the response
        stdout_buffer = io.StringIO()
        stderr_buffer = io.StringIO()
        
        with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer):
            app = APP_REGISTRY[app_name]["function"]()
        
        return app
    except Exception as e:
        return None

# Main app with dynamic loading capabilities
def create_main_app():
    with gr.Blocks(title="Dynamic Gradio App Generator", css="#app-container { min-height: 400px; }") as demo:
        gr.Markdown("# 🔄 Dynamic Gradio App Generator")
        gr.Markdown("Select an app type to load it without refreshing the page")
        
        # Create a state variable to track the current app
        current_app = gr.State("none")
        
        with gr.Row():
            with gr.Column(scale=1):
                # App selection area
                gr.Markdown("### Choose an App Template")
                app_selection = gr.Radio(
                    choices=list(APP_REGISTRY.keys()),
                    value="hello_world",
                    label="Available Templates",
                    info="Select a template to view and run it",
                    interactive=True
                )
                
                # Description display
                app_description = gr.Markdown(f"**{APP_REGISTRY['hello_world']['title']}**: {APP_REGISTRY['hello_world']['description']}")
                
                # Load button
                load_btn = gr.Button("Load Selected App", variant="primary")
                
                # Code display
                with gr.Accordion("View Code", open=False):
                    code_display = gr.Code(
                        language="python",
                        value=APP_CODES["hello_world"],
                        label="App Code"
                    )
                
                # Status message
                status_msg = gr.Markdown("Select an app and click 'Load Selected App'")
            
            with gr.Column(scale=2):
                # App container (where the dynamic app will be loaded)
                app_container = gr.HTML(
                    value="<div id='app-container'><p>No app loaded yet. Select an app template and click 'Load Selected App'.</p></div>",
                    label="App Preview"
                )
        
        # Update description and code when selection changes
        def update_description_and_code(selection):
            config = get_app_config(selection)
            return (
                f"**{config['title']}**: {config['description']}",
                config['code']
            )
        
        app_selection.change(
            update_description_and_code,
            inputs=app_selection,
            outputs=[app_description, code_display]
        )
        
        # Function to dynamically load the selected app
        def load_selected_app(app_name):
            try:
                # Clear the previous app
                gr.update(value="<div id='app-container'><p>Loading app...</p></div>")
                
                # Create a new app instance
                selected_app = load_app_interface(app_name)
                if selected_app is None:
                    return (
                        gr.update(value="<div id='app-container'><p>Error loading app. Please try again.</p></div>"),
                        f"Error: Could not load {APP_REGISTRY[app_name]['title']}",
                        app_name
                    )
                
                # Generate a unique ID for this app instance
                app_id = f"app-{app_name}-{id(selected_app)}"
                
                # Create a custom JavaScript function that will inject the app
                js_code = f"""
                <div id="{app_id}-container">
                    <p>Loading {APP_REGISTRY[app_name]['title']}...</p>
                </div>
                <script>
                    (function() {{
                        const appContainer = document.getElementById('{app_id}-container');
                        
                        // Create a timer to check when Gradio is fully loaded
                        const checkInterval = setInterval(() => {{
                            if (window.gradio_config && window.gradioApp) {{
                                clearInterval(checkInterval);
                                
                                // Create a temporary element to mount the app
                                const tempElement = document.createElement('div');
                                document.body.appendChild(tempElement);
                                
                                // Move the app to our container
                                setTimeout(() => {{
                                    try {{
                                        // Find the app elements with the right ID
                                        const appElements = Array.from(
                                            document.querySelectorAll(
                                                `.gradio-container[id^='{app_id}']`
                                            )
                                        );
                                        
                                        if (appElements.length > 0) {{
                                            // Move the app to our container
                                            appContainer.innerHTML = '';
                                            appElements.forEach(el => {{
                                                appContainer.appendChild(el);
                                            }});
                                        }} else {{
                                            appContainer.innerHTML = '<p>App loaded but could not be displayed. Please refresh the page.</p>';
                                        }}
                                    }} catch (e) {{
                                        console.error('Error moving app:', e);
                                        appContainer.innerHTML = '<p>Error loading app: ' + e.message + '</p>';
                                    }}
                                }}, 1000);
                            }}
                        }}, 100);
                    }})();
                </script>
                """
                
                return (
                    gr.update(value=js_code),
                    f"Successfully loaded {APP_REGISTRY[app_name]['title']}",
                    app_name
                )
            except Exception as e:
                error_msg = str(e)
                return (
                    gr.update(value=f"<div id='app-container'><p>Error: {error_msg}</p></div>"),
                    f"Error: {error_msg}",
                    app_name
                )
        
        # Handle the load button click
        load_btn.click(
            load_selected_app,
            inputs=app_selection,
            outputs=[app_container, status_msg, current_app]
        )
    
    return demo

# Create and launch the main app
demo = create_main_app()

# Add endpoints for direct API access to apps
for app_name, app_info in APP_REGISTRY.items():
    app_func = app_info["function"]
    if app_func:
        app = app_func()
        demo = gr.mount_gradio_app(demo, app, f"/{app_name}")

# Launch the app
if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)