import gradio as gr import pandas as pd import numpy as np # Simple Gradio examples def simple_greet(name): return f"Hello {name}!" def simple_calculator(x, y, operation): if operation == "add": return x + y elif operation == "subtract": return x - y elif operation == "multiply": return x * y elif operation == "divide": return x / y if y != 0 else "Cannot divide by zero" # Simple interface examples (uncomment to use) # demo1 = gr.Interface( # fn=simple_greet, # inputs="text", # outputs="text", # title="Simple Greeter" # ) # demo2 = gr.Interface( # fn=simple_calculator, # inputs=[ # gr.Number(label="First Number"), # gr.Number(label="Second Number"), # gr.Radio(["add", "subtract", "multiply", "divide"], label="Operation") # ], # outputs="text", # title="Calculator" # ) def analyze_data(csv_file, chart_type): """Analyze uploaded CSV and return info""" if csv_file is None: return "Please upload a CSV file" try: # Read the CSV file df = pd.read_csv(csv_file.name) # Get basic info info = f"""📊 Dataset Analysis: 🔢 Shape: {df.shape[0]} rows × {df.shape[1]} columns 📝 Columns: {', '.join(df.columns.tolist())} ❌ Missing values: {df.isnull().sum().sum()} 📈 Numeric columns: {len(df.select_dtypes(include=['number']).columns)} 📋 Text columns: {len(df.select_dtypes(include=['object']).columns)} 💡 Chart type selected: {chart_type} 📋 First 5 rows preview: {df.head().to_string()} 📊 Summary statistics: {df.describe().to_string() if len(df.select_dtypes(include=['number']).columns) > 0 else 'No numeric data for statistics'} """ return info except Exception as e: return f"Error reading file: {str(e)}" def greet(name, enthusiasm): """Simple greeting function""" excitement = "!" * int(enthusiasm) return f"Hello {name}{excitement}" def calculator(num1, operation, num2): """Simple calculator""" if operation == "Add": return num1 + num2 elif operation == "Subtract": return num1 - num2 elif operation == "Multiply": return num1 * num2 elif operation == "Divide": return num1 / num2 if num2 != 0 else "Cannot divide by zero!" # Create Gradio interface with tabs with gr.Blocks(title="Gradio Demo App") as demo: gr.Markdown("# 🚀 Gradio Demo Application") gr.Markdown("This demo showcases various Gradio components and functionalities.") with gr.Tab("📊 Data Analysis"): gr.Markdown("## Upload CSV and Create Visualizations") with gr.Row(): with gr.Column(): csv_input = gr.File(label="Upload CSV File", file_types=[".csv"]) chart_dropdown = gr.Dropdown( choices=["Histogram", "Scatter Plot"], label="Chart Type", value="Histogram" ) analyze_btn = gr.Button("Analyze Data", variant="primary") with gr.Column(): info_output = gr.Textbox(label="Dataset Info", lines=15, max_lines=20) analyze_btn.click( fn=analyze_data, inputs=[csv_input, chart_dropdown], outputs=info_output ) with gr.Tab("👋 Greeting"): gr.Markdown("## Personal Greeting Generator") with gr.Row(): name_input = gr.Textbox(label="Your Name", placeholder="Enter your name") enthusiasm_slider = gr.Slider(1, 10, value=3, label="Enthusiasm Level") greet_output = gr.Textbox(label="Greeting") greet_btn = gr.Button("Generate Greeting") greet_btn.click( fn=greet, inputs=[name_input, enthusiasm_slider], outputs=greet_output ) with gr.Tab("🧮 Calculator"): gr.Markdown("## Simple Calculator") with gr.Row(): num1_input = gr.Number(label="First Number", value=0) operation_radio = gr.Radio( choices=["Add", "Subtract", "Multiply", "Divide"], label="Operation", value="Add" ) num2_input = gr.Number(label="Second Number", value=0) calc_output = gr.Number(label="Result") calc_btn = gr.Button("Calculate", variant="secondary") calc_btn.click( fn=calculator, inputs=[num1_input, operation_radio, num2_input], outputs=calc_output ) with gr.Tab("🎨 Interactive Demo"): gr.Markdown("## Real-time Updates") with gr.Row(): slider_input = gr.Slider(0, 100, value=50, label="Value") checkbox_input = gr.Checkbox(label="Enable Processing", value=True) with gr.Row(): text_output = gr.Textbox(label="Live Output") number_output = gr.Number(label="Processed Value") def process_inputs(value, enabled): if enabled: processed = value * 1.5 message = f"Processing enabled: {value} → {processed}" return message, processed else: return "Processing disabled", value # Real-time updates slider_input.change( fn=process_inputs, inputs=[slider_input, checkbox_input], outputs=[text_output, number_output] ) checkbox_input.change( fn=process_inputs, inputs=[slider_input, checkbox_input], outputs=[text_output, number_output] ) with gr.Tab("📝 Basic Examples"): gr.Markdown("## Simple Gradio Code Examples") gr.Markdown(""" ### Example 1: Simple Greeter ```python def greet(name): return f"Hello {name}!" demo = gr.Interface( fn=greet, inputs="text", outputs="text" ) ``` """) with gr.Row(): simple_name = gr.Textbox(label="Your Name", placeholder="Enter name") simple_greet_output = gr.Textbox(label="Greeting") simple_greet_btn = gr.Button("Greet Me!") simple_greet_btn.click( fn=simple_greet, inputs=simple_name, outputs=simple_greet_output ) gr.Markdown(""" ### Example 2: Calculator with Interface ```python def calculator(x, y, operation): if operation == "add": return x + y # ... other operations demo = gr.Interface( fn=calculator, inputs=[ gr.Number(label="First Number"), gr.Number(label="Second Number"), gr.Radio(["add", "subtract", "multiply", "divide"]) ], outputs="text" ) ``` """) with gr.Row(): calc_x = gr.Number(label="X", value=0) calc_y = gr.Number(label="Y", value=0) calc_op = gr.Radio(["add", "subtract", "multiply", "divide"], label="Operation", value="add") calc_result = gr.Textbox(label="Result") calc_btn = gr.Button("Calculate") calc_btn.click( fn=simple_calculator, inputs=[calc_x, calc_y, calc_op], outputs=calc_result ) gr.Markdown(""" ### Example 3: Custom Layout with Blocks ```python with gr.Blocks() as demo: gr.Markdown("# My App") with gr.Row(): input1 = gr.Textbox() input2 = gr.Slider() output = gr.Textbox() btn = gr.Button("Process") btn.click(fn=my_function, inputs=[input1, input2], outputs=output) demo.launch() ``` """) gr.Markdown("**Key Components:**") gr.Markdown("- `gr.Interface()` - Simple wrapper") gr.Markdown("- `gr.Blocks()` - Custom layouts") gr.Markdown("- `gr.Row()`, `gr.Column()` - Layout containers") gr.Markdown("- `gr.Textbox()`, `gr.Number()`, `gr.Slider()` - Input components") gr.Markdown("- `demo.launch()` - Start the server") # Launch the app if __name__ == "__main__": demo.launch( server_name="0.0.0.0", # Allow external access server_port=7861, # Different port from Dash app share=False, # Set to True to create public link debug=True # Enable debug mode )