Python library for easily interacting with trained machine learning models
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Support functions and classes for progress tracking, notifications, examples, state management, and integration with external systems to enhance Gradio application functionality.
Classes and functions for tracking progress of long-running operations with visual indicators and user feedback.
class Progress:
def __init__(self, track_tqdm=False):
"""
Progress tracking for long-running iterators.
Parameters:
- track_tqdm: Whether to automatically track tqdm progress bars
"""
def __call__(self, progress, desc=None, total=None, unit="steps"):
"""
Update progress indicator.
Parameters:
- progress: Progress value (0-1 for percentage, or current/total)
- desc: Description of current operation
- total: Total number of steps (if not using 0-1 scale)
- unit: Unit name for progress display
"""
def tqdm(self, iterable, *args, **kwargs):
"""
Wrap iterable with progress tracking.
Parameters:
- iterable: Iterable to track progress for
- Additional tqdm arguments for customization
Returns:
- Progress-wrapped iterable
"""
def update(self, n=1):
"""Increment progress by n steps."""
def close(self):
"""Close progress indicator."""Usage examples:
import gradio as gr
import time
def long_task(progress=gr.Progress()):
progress(0, desc="Starting...")
for i in progress.tqdm(range(100), desc="Processing"):
time.sleep(0.1) # Simulate work
progress(1.0, desc="Complete!")
return "Task finished!"
def manual_progress(progress=gr.Progress()):
total_steps = 50
for i in range(total_steps):
# Update with fraction
progress(i / total_steps, desc=f"Step {i+1}/{total_steps}")
time.sleep(0.1)
return "Manual progress complete!"
# Use in interface
gr.Interface(
fn=long_task,
inputs=None,
outputs="text"
)Functions for displaying user notifications including informational messages, warnings, success indicators, and error alerts.
def Info(message):
"""
Display information notification.
Parameters:
- message: Information message to display
"""
def Warning(message):
"""
Display warning notification.
Parameters:
- message: Warning message to display
"""
def Success(message):
"""
Display success notification.
Parameters:
- message: Success message to display
"""
class Error(Exception):
"""
Gradio-specific error exception for user-facing error messages.
Parameters:
- message: Error message to display to user
"""
def __init__(self, message):
self.message = message
super().__init__(message)Usage examples:
import gradio as gr
def process_data(data):
if not data:
gr.Warning("No data provided, using defaults")
data = "default_value"
try:
result = complex_operation(data)
gr.Success("Data processed successfully!")
return result
except ValueError as e:
gr.Error(f"Invalid data format: {e}")
return None
except Exception as e:
gr.Info("Processing failed, but this is recoverable")
return fallback_processing(data)
def validate_input(text):
if len(text) < 5:
raise gr.Error("Input must be at least 5 characters long")
gr.Info("Input validation passed")
return text.upper()Class for managing and displaying example datasets with interactive selection and automatic input population.
class Examples:
def __init__(
self,
examples,
inputs,
outputs=None,
fn=None,
cache_examples=None,
examples_per_page=10,
label="Examples",
elem_id=None,
run_on_click=False,
preprocess=True,
postprocess=True,
api_name="load_example",
batch=False,
**kwargs
):
"""
Example data management and display system.
Parameters:
- examples: List of example inputs (one per row)
- inputs: List of input components that examples correspond to
- outputs: List of output components to populate (optional)
- fn: Function to run when example is selected
- cache_examples: Whether to cache example outputs
- examples_per_page: Number of examples to show per page
- label: Label for examples section
- run_on_click: Whether to run function when example clicked
- preprocess: Whether to preprocess example data
- postprocess: Whether to postprocess example outputs
- api_name: API endpoint name for examples
- batch: Whether to process examples in batches
"""
def create(self):
"""Create examples component."""
def load_from_cache(self, example_id):
"""Load cached example result."""
def cache(self):
"""Cache all example results."""Usage examples:
import gradio as gr
def text_classifier(text):
# Simple sentiment classification
if "good" in text.lower() or "great" in text.lower():
return "Positive"
elif "bad" in text.lower() or "terrible" in text.lower():
return "Negative"
else:
return "Neutral"
with gr.Blocks() as demo:
text_input = gr.Textbox(label="Text to classify")
classification_output = gr.Textbox(label="Classification")
submit_btn = gr.Button("Classify")
# Add examples
examples = gr.Examples(
examples=[
["This movie is really great!"],
["I had a terrible experience."],
["The weather is okay today."],
["Absolutely fantastic service!"],
["Not good at all, very disappointing."]
],
inputs=text_input,
outputs=classification_output,
fn=text_classifier,
cache_examples=True,
run_on_click=True
)
submit_btn.click(text_classifier, text_input, classification_output)Helper functions for dynamically updating component properties and managing component state during runtime.
def update(
value=None,
visible=None,
interactive=None,
label=None,
info=None,
elem_id=None,
elem_classes=None,
**kwargs
):
"""
Component property update utility for dynamic interface changes.
Parameters:
- value: New component value
- visible: Whether component should be visible
- interactive: Whether component should be interactive
- label: New component label
- info: New info text
- elem_id: New element ID
- elem_classes: New CSS classes
- Additional component-specific properties
Returns:
- Update dictionary for component modification
"""
def skip():
"""
Processing skip flag for conditional execution.
Returns:
- Special value indicating to skip this output
"""Usage examples:
import gradio as gr
def toggle_component(visible):
if visible:
return gr.update(visible=False, value="Hidden!")
else:
return gr.update(visible=True, value="Visible!")
def conditional_processing(input_text, should_process):
if not should_process:
return gr.skip() # Don't update output
return input_text.upper()
def dynamic_update(choice):
if choice == "text":
return gr.update(
label="Text Input",
placeholder="Enter text here...",
visible=True,
interactive=True
)
elif choice == "number":
return gr.update(
label="Number Input",
placeholder="Enter number...",
visible=True,
interactive=True
)
else:
return gr.update(visible=False)
with gr.Blocks() as demo:
choice = gr.Radio(["text", "number", "hidden"], label="Input Type")
dynamic_input = gr.Textbox(label="Dynamic Input")
toggle_btn = gr.Button("Toggle Visibility")
choice.change(dynamic_update, choice, dynamic_input)
toggle_btn.click(toggle_component, dynamic_input, dynamic_input)Functions for component rendering, display management, and interface control.
def render(component):
"""
Component rendering and display function.
Parameters:
- component: Component to render
Returns:
- Rendered component
"""Utility classes and functions for handling file operations, data processing, and system integration.
class FileSize:
def __init__(self, size_bytes):
"""
File size utility class with formatting.
Parameters:
- size_bytes: File size in bytes
"""
def human_readable(self):
"""Convert to human-readable format (KB, MB, GB)."""
def to_mb(self):
"""Convert to megabytes."""
def to_gb(self):
"""Convert to gigabytes."""
# Configuration constants
NO_RELOAD = object() # Flag to disable automatic reload functionality
IS_WASM = False # WebAssembly environment detection flag
def get_package_version():
"""
Package version retrieval utility.
Returns:
- Current Gradio version string
"""
def set_static_paths(paths):
"""
Static file path configuration for custom assets.
Parameters:
- paths: List of paths to serve as static files
"""Usage examples:
import gradio as gr
def file_info(file):
if file is None:
return "No file uploaded"
# Get file size
size = gr.FileSize(file.size)
return f"""
File: {file.orig_name}
Size: {size.human_readable()}
Path: {file.path}
"""
def check_environment():
version = gr.get_package_version()
is_wasm = gr.IS_WASM
return f"Gradio version: {version}, WASM: {is_wasm}"
# Configure static file serving
gr.set_static_paths(["/path/to/custom/assets"])
with gr.Blocks() as demo:
file_input = gr.File(label="Upload File")
file_info_output = gr.Textbox(label="File Information")
env_info_output = gr.Textbox(label="Environment")
file_input.change(file_info, file_input, file_info_output)
# Show environment info on load
demo.load(check_environment, outputs=env_info_output)Advanced state management helpers for complex applications with persistent data and session handling.
class BrowserState:
def __init__(self, value=None, **kwargs):
"""
Browser-specific state management for client-side persistence.
Parameters:
- value: Initial state value
"""
def close_all():
"""Close all running Gradio interfaces and clean up resources."""Usage examples:
import gradio as gr
def increment_session_counter(count):
return count + 1
def reset_session_counter():
return 0
def save_to_browser(data):
# Browser state persists across page reloads
return data
with gr.Blocks() as demo:
# Session state (resets on page reload)
session_count = gr.State(0)
# Browser state (persists across reloads)
persistent_data = gr.BrowserState("")
count_display = gr.Number(label="Session Count")
increment_btn = gr.Button("Increment")
reset_btn = gr.Button("Reset")
persistent_input = gr.Textbox(label="Persistent Data")
save_btn = gr.Button("Save to Browser")
increment_btn.click(
increment_session_counter,
session_count,
[session_count, count_display]
)
reset_btn.click(
reset_session_counter,
outputs=[session_count, count_display]
)
save_btn.click(
save_to_browser,
persistent_input,
persistent_data
)Internationalization and localization utilities for multi-language interfaces.
class I18n:
def __init__(self, locale="en", translations=None):
"""
Internationalization and localization support.
Parameters:
- locale: Default locale code (e.g., "en", "es", "fr")
- translations: Dictionary of translations
"""
def t(self, key, **kwargs):
"""
Translate text key with optional parameters.
Parameters:
- key: Translation key
- kwargs: Variables for string formatting
Returns:
- Translated string
"""
def set_locale(self, locale):
"""Change current locale."""
def load_translations(self, translations):
"""Load translation dictionary."""Usage example:
import gradio as gr
# Set up internationalization
i18n = gr.I18n("en", {
"en": {
"welcome": "Welcome to the app!",
"submit": "Submit",
"result": "Result: {value}"
},
"es": {
"welcome": "¡Bienvenido a la aplicación!",
"submit": "Enviar",
"result": "Resultado: {value}"
}
})
def process_with_i18n(text, locale):
i18n.set_locale(locale)
result = text.upper()
return i18n.t("result", value=result)
with gr.Blocks() as demo:
gr.Markdown(i18n.t("welcome"))
text_input = gr.Textbox()
locale_choice = gr.Radio(["en", "es"], value="en", label="Language")
submit_btn = gr.Button(i18n.t("submit"))
output = gr.Textbox()
submit_btn.click(process_with_i18n, [text_input, locale_choice], output)Tools for development, debugging, and development environment integration.
def load_ipython_extension(ipython):
"""
Jupyter notebook integration for IPython environments.
Parameters:
- ipython: IPython instance for magic command registration
"""Usage in Jupyter notebooks:
# Load Gradio IPython extension
%load_ext gradio
# Use Gradio magic commands
%%gradio
def my_function(x):
return x * 2
gr.Interface(my_function, "number", "number")Utilities for optimizing performance and resource usage in production environments.
# Disable auto-reload for production
demo = gr.Blocks()
demo.queue(default_concurrency_limit=10)
# Configure static file caching
gr.set_static_paths(["/static"], cache_headers=True)
# Use NO_RELOAD flag
if gr.NO_RELOAD:
# Production configuration
demo.launch(server_name="0.0.0.0", server_port=7860)
else:
# Development configuration
demo.launch(share=True, debug=True)Install with Tessl CLI
npx tessl i tessl/pypi-gradio