nakas's picture
Update app.py
f9b48f4 verified
raw
history blame
11.7 kB
import streamlit as st
import gradio as gr
import importlib.util
import sys
import tempfile
import os
from pathlib import Path
import inspect
import types
import shutil
import uuid
# Configure the Streamlit page
st.set_page_config(
page_title="Gradio Examples Hub",
page_icon="🧩",
layout="wide"
)
# Directory structure
EXAMPLES_DIR = Path("gradio_examples")
EXAMPLES_DIR.mkdir(exist_ok=True)
# Make sure we have a __init__.py file in the examples directory
init_file = EXAMPLES_DIR / "__init__.py"
if not init_file.exists():
init_file.touch()
# Ensure the examples directory is in the Python path
if str(EXAMPLES_DIR.absolute()) not in sys.path:
sys.path.insert(0, str(EXAMPLES_DIR.absolute()))
# Create session state for tracking the current app
if 'current_app' not in st.session_state:
st.session_state.current_app = None
st.session_state.current_app_module = None
st.session_state.app_interface = None
# 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"], ["Streamlit"]]
)
""",
"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"
)
""",
"text_analysis": """
import gradio as gr
def analyze_text(text):
if not text:
return "Please enter some text"
char_count = len(text)
word_count = len(text.split())
line_count = len(text.splitlines())
return f"Characters: {char_count}\\nWords: {word_count}\\nLines: {line_count}"
demo = gr.Interface(
fn=analyze_text,
inputs=gr.Textbox(label="Enter Text", lines=5),
outputs=gr.Textbox(label="Analysis"),
title="Text Analysis Tool",
description="Count characters, words, and lines in text",
examples=[
["Hello, world!"],
["This is an example.\\nIt has multiple lines.\\nThree lines in total."],
["The quick brown fox jumps over the lazy dog."]
]
)
""",
"chatbot": """
import gradio as gr
def respond(message, history):
# Simple echo bot for demonstration
return f"You said: {message}"
demo = gr.ChatInterface(
fn=respond,
title="Echo Bot",
description="A simple chatbot that echoes your messages",
examples=["Hello", "What's your name?", "Tell me a joke"]
)
""",
"audio_player": """
import gradio as gr
import numpy as np
def generate_tone(frequency, duration):
sr = 44100 # Sample rate
t = np.linspace(0, duration, int(sr * duration), False)
tone = 0.5 * np.sin(2 * np.pi * frequency * t)
return sr, tone
demo = gr.Interface(
fn=generate_tone,
inputs=[
gr.Slider(110, 880, 440, label="Frequency (Hz)"),
gr.Slider(0.1, 5, 1, label="Duration (seconds)")
],
outputs=gr.Audio(type="numpy"),
title="Tone Generator",
description="Generate a sine wave tone with the specified frequency and duration"
)
"""
}
def load_example(example_name):
"""Load a Gradio example from the examples directory or create it if it doesn't exist"""
# Generate a unique module name to avoid caching issues
module_name = f"gradio_examples.{example_name}_{uuid.uuid4().hex[:8]}"
file_path = EXAMPLES_DIR / f"{module_name.split('.')[-1]}.py"
# Write the example code to a file
with open(file_path, "w") as f:
f.write(EXAMPLES[example_name])
# Import the module
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
# Return the module and Gradio demo
return module, module.demo
def create_custom_example(code):
"""Create a custom Gradio example from code"""
# Generate a unique module name
module_name = f"gradio_examples.custom_{uuid.uuid4().hex[:8]}"
file_path = EXAMPLES_DIR / f"{module_name.split('.')[-1]}.py"
# Write the code to a file
with open(file_path, "w") as f:
f.write(code)
# Import the module
try:
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
# Check if the module has a demo attribute
if hasattr(module, 'demo'):
return module, module.demo, None
else:
return None, None, "No 'demo' variable found in the code"
except Exception as e:
return None, None, f"Error loading code: {str(e)}"
def stop_current_app():
"""Stop the currently running Gradio app"""
if st.session_state.app_interface:
# Close the Gradio interface
try:
st.session_state.app_interface.close()
except:
pass
# Clear the current app from session state
st.session_state.current_app = None
st.session_state.current_app_module = None
st.session_state.app_interface = None
# Create the Streamlit UI
st.title("🧩 Gradio Examples Hub")
st.write("Discover and run various Gradio examples directly in this app.")
# Create tabs for different sections
tab_examples, tab_custom = st.tabs(["Built-in Examples", "Custom Code"])
# Built-in Examples tab
with tab_examples:
st.header("Built-in Examples")
# Example selection
example_options = list(EXAMPLES.keys())
example_names = {
"hello_world": "Hello World",
"calculator": "Simple Calculator",
"image_filter": "Image Filter",
"text_analysis": "Text Analysis",
"chatbot": "Simple Chatbot",
"audio_player": "Audio Tone Generator"
}
selected_example = st.selectbox(
"Select an example",
example_options,
format_func=lambda x: example_names.get(x, x)
)
# Show description
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 to images (grayscale, invert, sepia).",
"text_analysis": "Count characters, words, and lines in text.",
"chatbot": "A simple echo chatbot example.",
"audio_player": "Generate audio tones with adjustable frequency and duration."
}
st.write(example_descriptions.get(selected_example, ""))
# Show code
with st.expander("View Code"):
st.code(EXAMPLES[selected_example], language="python")
# Run example button
if st.button("Run Example", key="run_example"):
stop_current_app() # Stop any running app
with st.spinner("Loading example..."):
# Load the example
module, demo = load_example(selected_example)
# Update session state
st.session_state.current_app = selected_example
st.session_state.current_app_module = module
st.session_state.app_interface = demo
# Rerun the app to refresh the UI
st.experimental_rerun()
# Custom Code tab
with tab_custom:
st.header("Custom Gradio Code")
st.write("Write or paste your own Gradio code here.")
# Code editor
custom_code = st.text_area(
"Gradio Code",
height=300,
placeholder="# Paste your Gradio code here\nimport gradio as gr\n\n# Define your functions\ndef my_function(input):\n return input\n\n# Create the interface\ndemo = gr.Interface(...)"
)
# Run custom code button
if st.button("Run Custom Code", key="run_custom"):
if not custom_code.strip():
st.error("Please enter some code")
else:
stop_current_app() # Stop any running app
with st.spinner("Loading custom code..."):
# Create the custom example
module, demo, error = create_custom_example(custom_code)
if error:
st.error(error)
else:
# Update session state
st.session_state.current_app = "custom"
st.session_state.current_app_module = module
st.session_state.app_interface = demo
# Rerun the app to refresh the UI
st.experimental_rerun()
# Display the current app if there is one
st.header("Current App")
if st.session_state.current_app:
app_name = st.session_state.current_app
demo = st.session_state.app_interface
# Create a container for the app
app_container = st.container()
app_container.write(f"Running: {example_names.get(app_name, 'Custom App')}")
# Create a unique key for the app
app_key = f"app_{app_name}_{uuid.uuid4().hex[:8]}"
# Render the Gradio interface directly in Streamlit
with app_container:
gr.Interface.load(
fn=demo,
title=demo._title,
description=getattr(demo, "_description", ""),
).render()
# Stop button
if st.button("Stop App", key="stop_app"):
stop_current_app()
st.experimental_rerun()
else:
st.info("No app is currently running. Select an example or create a custom app to get started.")
# Footer
st.markdown("---")
st.markdown("### About this App")
st.write(
"This Streamlit app demonstrates how to dynamically load and run Gradio interfaces. "
"It showcases integration between Streamlit for the main application UI and Gradio for "
"interactive demos."
)