File size: 11,748 Bytes
b867a1d
6e19f63
f9b48f4
 
b867a1d
 
 
f9b48f4
 
 
 
07aeb52
f9b48f4
b867a1d
f9b48f4
 
b867a1d
 
 
f9b48f4
 
 
b867a1d
f9b48f4
 
 
 
b867a1d
f9b48f4
 
 
b867a1d
f9b48f4
 
 
 
 
b867a1d
f9b48f4
 
b867a1d
 
07aeb52
1f2f75f
 
 
b867a1d
 
f9b48f4
b867a1d
 
f9b48f4
 
b867a1d
 
 
 
 
f9b48f4
b867a1d
 
 
 
 
 
 
 
 
1f2f75f
 
b867a1d
 
 
 
 
 
 
 
 
 
 
f9b48f4
 
 
 
 
 
 
b867a1d
 
 
 
 
 
f9b48f4
b867a1d
 
 
 
 
f9b48f4
 
b867a1d
f9b48f4
 
b867a1d
f9b48f4
 
b867a1d
 
 
 
f9b48f4
b867a1d
f9b48f4
b867a1d
 
 
 
 
f9b48f4
b867a1d
 
f9b48f4
b867a1d
f9b48f4
b867a1d
 
 
 
 
1f2f75f
 
 
 
f189ec9
b867a1d
 
 
f189ec9
b867a1d
 
 
 
 
 
 
f9b48f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b867a1d
f9b48f4
 
 
 
 
 
 
 
 
 
 
b867a1d
f9b48f4
 
 
 
 
 
 
 
 
 
b867a1d
 
1f2f75f
f9b48f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b867a1d
f9b48f4
 
 
 
 
f189ec9
f9b48f4
 
 
f189ec9
f9b48f4
 
 
 
 
 
f189ec9
f9b48f4
 
 
b867a1d
f9b48f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f189ec9
f9b48f4
 
 
 
 
 
 
 
 
 
 
b867a1d
f9b48f4
 
 
 
f189ec9
f9b48f4
 
 
 
 
 
f189ec9
f9b48f4
 
 
 
b867a1d
f9b48f4
 
 
 
 
b867a1d
 
f9b48f4
b867a1d
f9b48f4
 
 
 
b867a1d
f9b48f4
 
b867a1d
f9b48f4
 
7928d62
f9b48f4
 
 
b867a1d
f9b48f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b867a1d
f9b48f4
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import gradio as gr
import importlib.util
import sys
import tempfile
import os
from pathlib import Path
import inspect
import types
import shutil
import uuid

# Configure the Streamlit page
st.set_page_config(
    page_title="Gradio Examples Hub",
    page_icon="🧩",
    layout="wide"
)

# Directory structure
EXAMPLES_DIR = Path("gradio_examples")
EXAMPLES_DIR.mkdir(exist_ok=True)

# Make sure we have a __init__.py file in the examples directory
init_file = EXAMPLES_DIR / "__init__.py"
if not init_file.exists():
    init_file.touch()

# Ensure the examples directory is in the Python path
if str(EXAMPLES_DIR.absolute()) not in sys.path:
    sys.path.insert(0, str(EXAMPLES_DIR.absolute()))

# Create session state for tracking the current app
if 'current_app' not in st.session_state:
    st.session_state.current_app = None
    st.session_state.current_app_module = None
    st.session_state.app_interface = None

# Example Gradio apps as Python code
EXAMPLES = {
    "hello_world": """
import gradio as gr

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

demo = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(label="Your Name", placeholder="Enter your name"),
    outputs=gr.Textbox(label="Greeting"),
    title="Hello World App",
    description="A simple app that greets you by name",
    examples=[["World"], ["Gradio"], ["Streamlit"]]
)
""",

    "calculator": """
import gradio as gr
import numpy as np

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="Simple Calculator",
    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 various filters to your images"
)
""",

    "text_analysis": """
import gradio as gr

def analyze_text(text):
    if not text:
        return "Please enter some text"
    
    char_count = len(text)
    word_count = len(text.split())
    line_count = len(text.splitlines())
    
    return f"Characters: {char_count}\\nWords: {word_count}\\nLines: {line_count}"

demo = gr.Interface(
    fn=analyze_text,
    inputs=gr.Textbox(label="Enter Text", lines=5),
    outputs=gr.Textbox(label="Analysis"),
    title="Text Analysis Tool",
    description="Count characters, words, and lines in text",
    examples=[
        ["Hello, world!"],
        ["This is an example.\\nIt has multiple lines.\\nThree lines in total."],
        ["The quick brown fox jumps over the lazy dog."]
    ]
)
""",

    "chatbot": """
import gradio as gr

def respond(message, history):
    # Simple echo bot for demonstration
    return f"You said: {message}"

demo = gr.ChatInterface(
    fn=respond,
    title="Echo Bot",
    description="A simple chatbot that echoes your messages",
    examples=["Hello", "What's your name?", "Tell me a joke"]
)
""",

    "audio_player": """
import gradio as gr
import numpy as np

def generate_tone(frequency, duration):
    sr = 44100  # Sample rate
    t = np.linspace(0, duration, int(sr * duration), False)
    tone = 0.5 * np.sin(2 * np.pi * frequency * t)
    return sr, tone

demo = gr.Interface(
    fn=generate_tone,
    inputs=[
        gr.Slider(110, 880, 440, label="Frequency (Hz)"),
        gr.Slider(0.1, 5, 1, label="Duration (seconds)")
    ],
    outputs=gr.Audio(type="numpy"),
    title="Tone Generator",
    description="Generate a sine wave tone with the specified frequency and duration"
)
"""
}

def load_example(example_name):
    """Load a Gradio example from the examples directory or create it if it doesn't exist"""
    # Generate a unique module name to avoid caching issues
    module_name = f"gradio_examples.{example_name}_{uuid.uuid4().hex[:8]}"
    file_path = EXAMPLES_DIR / f"{module_name.split('.')[-1]}.py"
    
    # Write the example code to a file
    with open(file_path, "w") as f:
        f.write(EXAMPLES[example_name])
    
    # Import the module
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    
    # Return the module and Gradio demo
    return module, module.demo

def create_custom_example(code):
    """Create a custom Gradio example from code"""
    # Generate a unique module name
    module_name = f"gradio_examples.custom_{uuid.uuid4().hex[:8]}"
    file_path = EXAMPLES_DIR / f"{module_name.split('.')[-1]}.py"
    
    # Write the code to a file
    with open(file_path, "w") as f:
        f.write(code)
    
    # Import the module
    try:
        spec = importlib.util.spec_from_file_location(module_name, file_path)
        module = importlib.util.module_from_spec(spec)
        sys.modules[module_name] = module
        spec.loader.exec_module(module)
        
        # Check if the module has a demo attribute
        if hasattr(module, 'demo'):
            return module, module.demo, None
        else:
            return None, None, "No 'demo' variable found in the code"
    except Exception as e:
        return None, None, f"Error loading code: {str(e)}"

def stop_current_app():
    """Stop the currently running Gradio app"""
    if st.session_state.app_interface:
        # Close the Gradio interface
        try:
            st.session_state.app_interface.close()
        except:
            pass
    
    # Clear the current app from session state
    st.session_state.current_app = None
    st.session_state.current_app_module = None
    st.session_state.app_interface = None

# Create the Streamlit UI
st.title("🧩 Gradio Examples Hub")
st.write("Discover and run various Gradio examples directly in this app.")

# Create tabs for different sections
tab_examples, tab_custom = st.tabs(["Built-in Examples", "Custom Code"])

# Built-in Examples tab
with tab_examples:
    st.header("Built-in Examples")
    
    # Example selection
    example_options = list(EXAMPLES.keys())
    example_names = {
        "hello_world": "Hello World",
        "calculator": "Simple Calculator",
        "image_filter": "Image Filter",
        "text_analysis": "Text Analysis",
        "chatbot": "Simple Chatbot",
        "audio_player": "Audio Tone Generator"
    }
    
    selected_example = st.selectbox(
        "Select an example", 
        example_options,
        format_func=lambda x: example_names.get(x, x)
    )
    
    # Show description
    example_descriptions = {
        "hello_world": "A simple app that greets you by name.",
        "calculator": "Perform basic arithmetic operations between two numbers.",
        "image_filter": "Apply various filters to images (grayscale, invert, sepia).",
        "text_analysis": "Count characters, words, and lines in text.",
        "chatbot": "A simple echo chatbot example.",
        "audio_player": "Generate audio tones with adjustable frequency and duration."
    }
    
    st.write(example_descriptions.get(selected_example, ""))
    
    # Show code
    with st.expander("View Code"):
        st.code(EXAMPLES[selected_example], language="python")
    
    # Run example button
    if st.button("Run Example", key="run_example"):
        stop_current_app()  # Stop any running app
        
        with st.spinner("Loading example..."):
            # Load the example
            module, demo = load_example(selected_example)
            
            # Update session state
            st.session_state.current_app = selected_example
            st.session_state.current_app_module = module
            st.session_state.app_interface = demo
            
            # Rerun the app to refresh the UI
            st.experimental_rerun()

# Custom Code tab
with tab_custom:
    st.header("Custom Gradio Code")
    st.write("Write or paste your own Gradio code here.")
    
    # Code editor
    custom_code = st.text_area(
        "Gradio Code", 
        height=300,
        placeholder="# Paste your Gradio code here\nimport gradio as gr\n\n# Define your functions\ndef my_function(input):\n    return input\n\n# Create the interface\ndemo = gr.Interface(...)"
    )
    
    # Run custom code button
    if st.button("Run Custom Code", key="run_custom"):
        if not custom_code.strip():
            st.error("Please enter some code")
        else:
            stop_current_app()  # Stop any running app
            
            with st.spinner("Loading custom code..."):
                # Create the custom example
                module, demo, error = create_custom_example(custom_code)
                
                if error:
                    st.error(error)
                else:
                    # Update session state
                    st.session_state.current_app = "custom"
                    st.session_state.current_app_module = module
                    st.session_state.app_interface = demo
                    
                    # Rerun the app to refresh the UI
                    st.experimental_rerun()

# Display the current app if there is one
st.header("Current App")

if st.session_state.current_app:
    app_name = st.session_state.current_app
    demo = st.session_state.app_interface
    
    # Create a container for the app
    app_container = st.container()
    app_container.write(f"Running: {example_names.get(app_name, 'Custom App')}")
    
    # Create a unique key for the app
    app_key = f"app_{app_name}_{uuid.uuid4().hex[:8]}"
    
    # Render the Gradio interface directly in Streamlit
    with app_container:
        gr.Interface.load(
            fn=demo,
            title=demo._title,
            description=getattr(demo, "_description", ""),
        ).render()
    
    # Stop button
    if st.button("Stop App", key="stop_app"):
        stop_current_app()
        st.experimental_rerun()
else:
    st.info("No app is currently running. Select an example or create a custom app to get started.")

# Footer
st.markdown("---")
st.markdown("### About this App")
st.write(
    "This Streamlit app demonstrates how to dynamically load and run Gradio interfaces. "
    "It showcases integration between Streamlit for the main application UI and Gradio for "
    "interactive demos."
)