File size: 6,779 Bytes
6e19f63
f9b48f4
 
b867a1d
e1c280b
b867a1d
07aeb52
e1c280b
 
f9b48f4
b867a1d
e1c280b
f9b48f4
e1c280b
f9b48f4
b867a1d
f9b48f4
 
b867a1d
 
07aeb52
1f2f75f
 
 
b867a1d
 
f9b48f4
b867a1d
 
f9b48f4
e1c280b
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
e1c280b
f9b48f4
e1c280b
 
 
f9b48f4
e1c280b
 
f9b48f4
 
 
e1c280b
f9b48f4
 
 
e1c280b
 
b867a1d
e1c280b
 
 
 
 
f189ec9
e1c280b
 
f189ec9
e1c280b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f189ec9
e1c280b
b867a1d
e1c280b
 
 
 
f9b48f4
e1c280b
 
 
 
 
 
 
f9b48f4
e1c280b
 
 
f9b48f4
e1c280b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import importlib.util
import sys
import os
import tempfile
from pathlib import Path

# Create directory for examples
EXAMPLES_DIR = Path("examples")
EXAMPLES_DIR.mkdir(exist_ok=True)

# Ensure examples directory is in Python path
if str(EXAMPLES_DIR.absolute()) not in sys.path:
    sys.modules["examples"] = type(sys)("examples")
    sys.path.insert(0, str(EXAMPLES_DIR.absolute()))

# 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"], ["User"]]
)
""",

    "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"
)
"""
}

# Function to dynamically load a Gradio example
def load_example(example_name):
    """Load a example module and return the demo instance"""
    # Create a module file
    module_path = EXAMPLES_DIR / f"{example_name}.py"
    
    # Write the example code to the file
    with open(module_path, "w") as f:
        f.write(EXAMPLES[example_name])
    
    # Import the module
    spec = importlib.util.spec_from_file_location(f"examples.{example_name}", module_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    
    # Return the demo object
    return module.demo

# Main selector app
def selector_app():
    with gr.Blocks(title="Gradio Examples Selector") as selector:
        with gr.Row():
            gr.Markdown("# Gradio Examples Hub")
        
        with gr.Row():
            gr.Markdown("Select an example to run:")
        
        example_names = {
            "hello_world": "Hello World Greeter",
            "calculator": "Simple Calculator",
            "image_filter": "Image Filter"
        }
        
        with gr.Row():
            example_dropdown = gr.Dropdown(
                choices=list(EXAMPLES.keys()),
                value="hello_world",
                label="Select Example",
                format_func=lambda x: example_names.get(x, x)
            )
        
        with gr.Row():
            load_btn = gr.Button("Load Example", variant="primary")
        
        # Info area for example descriptions
        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 (grayscale, invert, sepia) to images."
        }
        
        info_box = gr.Markdown(f"**{example_names['hello_world']}**: {example_descriptions['hello_world']}")
        
        # Update description when dropdown changes
        def update_description(example):
            return f"**{example_names[example]}**: {example_descriptions[example]}"
        
        example_dropdown.change(
            update_description,
            inputs=[example_dropdown],
            outputs=[info_box]
        )
        
        # Function to load the selected example
        def load_selected_example(example_name):
            # Return the app name to be loaded
            return example_name
        
        # Connect the load button
        load_btn.click(
            load_selected_example,
            inputs=[example_dropdown],
            outputs=[gr.Textbox(visible=False)]
        )
    
    return selector

# Create a function to determine which app to launch
def get_current_app():
    # Check if an example was requested in the URL
    example_name = None
    
    # Get query parameters from URL
    try:
        import urllib.parse
        query_params = dict(urllib.parse.parse_qsl(os.environ.get('QUERY_STRING', '')))
        example_name = query_params.get('example', None)
    except:
        pass
    
    # If no example specified, return the selector app
    if not example_name or example_name not in EXAMPLES:
        return selector_app()
    
    # Otherwise, load the requested example
    try:
        return load_example(example_name)
    except Exception as e:
        print(f"Error loading example {example_name}: {str(e)}")
        return selector_app()

# Launch the app based on URL parameters
app = get_current_app()

# When an example is selected, redirect to load it
if isinstance(app, gr.Blocks) and app.title == "Gradio Examples Selector":
    @app.load(api_name=False)
    def on_load():
        pass
    
    # Handle example selection
    @app.callback(inputs=[gr.Textbox(visible=False)], outputs=None)
    def on_example_selected(example_name):
        if example_name:
            gr.Blocks.redirect(f"?example={example_name}")

# Launch the appropriate app
app.launch(server_name="0.0.0.0", server_port=7860)