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)