import gradio as gr import numpy as np from PIL import Image # Simple function to set matplotlib config dir import os os.environ['MPLCONFIGDIR'] = '/tmp' # Hello World example function def greet(name): return f"Hello, {name}!" # Calculator example function 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 # Image filter example function 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 # Create a Gradio app with all examples presented side by side with gr.Blocks(title="Gradio Examples") as demo: gr.Markdown("# Gradio Examples") gr.Markdown("This app demonstrates three simple Gradio examples: Hello World, Calculator, and Image Filter.") # Layout the examples in a grid with gr.Tabs(): with gr.Tab("Hello World"): with gr.Box(): gr.Markdown("## Hello World Example") gr.Markdown("A simple app that greets you by name.") name_input = gr.Textbox(label="Your Name", value="World") greet_btn = gr.Button("Say Hello") greeting_output = gr.Textbox(label="Greeting") greet_btn.click(fn=greet, inputs=name_input, outputs=greeting_output) with gr.Tab("Calculator"): with gr.Box(): gr.Markdown("## Simple Calculator") gr.Markdown("Perform basic arithmetic operations between two numbers.") num1 = gr.Number(label="First Number", value=5) num2 = gr.Number(label="Second Number", value=3) operation = gr.Radio( ["Add", "Subtract", "Multiply", "Divide"], label="Operation", value="Add" ) calc_btn = gr.Button("Calculate") result = gr.Textbox(label="Result") calc_btn.click(fn=calculate, inputs=[num1, num2, operation], outputs=result) with gr.Tab("Image Filter"): with gr.Box(): gr.Markdown("## Image Filter") gr.Markdown("Apply various filters to images.") image_input = gr.Image(type="pil", label="Input Image") filter_type = gr.Radio( ["Grayscale", "Invert", "Sepia"], label="Filter Type", value="Grayscale" ) filter_btn = gr.Button("Apply Filter") filtered_image = gr.Image(label="Filtered Image") filter_btn.click(fn=apply_filter, inputs=[image_input, filter_type], outputs=filtered_image) # Launch the app if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)