import gradio as gr import os import sys from pathlib import Path import importlib.util # Create examples directory EXAMPLES_DIR = Path("examples") EXAMPLES_DIR.mkdir(exist_ok=True) # Pre-defined Gradio examples EXAMPLES = { "hello_world": { "title": "Hello World Greeter", "description": "A simple app that greets you by name", "code": """ 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 Greeter", description="A simple app that greets you by name" ) """ }, "calculator": { "title": "Simple Calculator", "description": "Perform basic arithmetic operations", "code": """ 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="Simple Calculator", description="Perform basic arithmetic operations" ) """ }, "image_filter": { "title": "Image Filter", "description": "Apply various filters to your images", "code": """ 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", description="Apply various filters to your images" ) """ } } # Function to load and run a specific example def run_example(example_name): example = EXAMPLES.get(example_name) if not example: return None # Create module file module_path = EXAMPLES_DIR / f"{example_name}.py" with open(module_path, "w") as f: f.write(example["code"]) try: # Import the module spec = importlib.util.spec_from_file_location(f"examples.{example_name}", module_path) module = importlib.util.module_from_spec(spec) sys.modules[f"examples.{example_name}"] = module spec.loader.exec_module(module) if hasattr(module, 'demo'): return module.demo except Exception as e: print(f"Error loading example {example_name}: {e}") return None # Main selector interface def example_selector(): """Create a simple selector interface""" def select_example(example_name): """Callback when an example is selected""" demo = run_example(example_name) if demo: demo.launch(server_name="0.0.0.0", server_port=7860) return f"Selected {example_name}, please restart the server to see it." demo = gr.Interface( fn=select_example, inputs=gr.Radio( choices=list(EXAMPLES.keys()), label="Select an example to run", info="Choose one of the examples below" ), outputs=gr.Textbox(label="Status"), title="Gradio Examples Selector", description="Select an example from the list to run it.", allow_flagging=False ) return demo # Get example from environment variables if set def get_example_from_env(): """Check if an example is specified in the environment""" return os.environ.get("GRADIO_EXAMPLE", None) # Main application logic if __name__ == "__main__": # Check if we should load a specific example example_name = get_example_from_env() if example_name in EXAMPLES: demo = run_example(example_name) if demo: print(f"Running example: {example_name}") demo.launch(server_name="0.0.0.0", server_port=7860) else: print(f"Failed to load example: {example_name}, falling back to selector") example_selector().launch(server_name="0.0.0.0", server_port=7860) else: # Run the selector interface example_selector().launch(server_name="0.0.0.0", server_port=7860)