ā” Asynchronous Task Processing in Gradio
Long-running machine learning inferences, data scraping jobs, and file processing tasks can block web servers if executed synchronously. By utilizing Python's async/await syntax and Gradio generator functions, developers can build responsive web applications that execute background workers without freezing the user interface.
Example 1: Definition & Basic Python `async def` Function in Gradio
Demonstrates a fundamental asynchronous Python function (`async def`) integrated into a Gradio Interface.
Python (async_ex1.py)
import gradio as gr
import asyncio
async def async_greet(name):
await asyncio.sleep(1) # Simulate non-blocking async delay
return f"Hello, {name}! Processed asynchronously via Python asyncio."
demo = gr.Interface(
fn=async_greet,
inputs=gr.Textbox(label="Enter Name", value="Nikita"),
outputs=gr.Textbox(label="Async Greeting Result"),
title="Basic Async Greeting App"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Basic Async Greeting App
Click 'Run Async Task' to test async execution.
Example 2: Gradio Built-in `gr.Progress()` for Long Tasks
Utilizes Gradio's built-in
gr.Progress(track=True) object to render smooth progress bars during task execution.
Python (async_ex2.py)
import gradio as gr
import time
def process_with_progress(task_name, progress=gr.Progress()):
progress(0, desc="Starting task...")
time.sleep(0.5)
for i in range(1, 5):
progress(i / 4, desc=f"Processing step {i} of 4...")
time.sleep(0.6)
return f"Task '{task_name}' completed successfully with progress tracking!"
demo = gr.Interface(
fn=process_with_progress,
inputs=gr.Textbox(label="Task Name", value="Dataset Indexing"),
outputs=gr.Textbox(label="Completion Status"),
title="Gradio Built-in Progress Tracker"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Gradio Built-in Progress Tracker
Click 'Start Task with Progress' to run simulation.
Example 3: Non-Blocking Background Job Queue Simulator
Simulates submitting background batch jobs to an active worker queue and tracking status IDs.
Python (async_ex3.py)
import gradio as gr
import time
import uuid
def submit_background_job(job_description):
job_id = str(uuid.uuid4())[:8]
return f"š Job Submitted Successfully!\n- **Job ID:** `JOB-{job_id}`\n- **Description:** {job_description}\n- **Status:** Processing in background worker queue..."
demo = gr.Interface(
fn=submit_background_job,
inputs=gr.Textbox(label="Job Description", value="Batch render 500 product images"),
outputs=gr.Markdown(label="Job Submission Ticket"),
title="Background Job Queue Dispatcher"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Background Job Queue Dispatcher
Click 'Dispatch Job' to submit background task.
Example 4: Concurrent Task Execution using `asyncio.gather`
Executes multiple async sub-tasks concurrently and aggregates their results using
asyncio.gather.
Python (async_ex4.py)
import gradio as gr
import asyncio
async def fetch_api(source_name):
await asyncio.sleep(0.8)
return f"Data from {source_name}: Success (200 OK)"
async def run_concurrent_fetches(query):
sources = ["OpenAI API", "Anthropic API", "Local Ollama"]
results = await asyncio.gather(*(fetch_api(src) for src in sources))
return f"Query: '{query}'\n\n" + "\n".join(results)
demo = gr.Interface(
fn=run_concurrent_fetches,
inputs=gr.Textbox(label="Query", value="Fetch multi-LLM telemetry"),
outputs=gr.Textbox(label="Concurrent Aggregated Output", lines=5),
title="Concurrent Async API Aggregator"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Concurrent Async API Aggregator
Click 'Run Concurrent Tasks' to execute asyncio.gather.
Example 5: Async Generator Streaming Status Logs
Streams progressive background execution logs asynchronously using
async def generator functions with yield.
Python (async_ex5.py)
import gradio as gr
import asyncio
async def async_log_streamer(task_type):
logs = [
f"ā” Initializing async worker for '{task_type}'...",
"š Connecting to remote data stream...",
"āļø Processing asynchronous batches...",
"ā
Task finished successfully!"
]
output = ""
for log in logs:
output += log + "\n"
await asyncio.sleep(0.5)
yield output
demo = gr.Interface(
fn=async_log_streamer,
inputs=gr.Textbox(label="Task Type", value="Web Scraping Pipeline"),
outputs=gr.Textbox(label="Live Async Logs", lines=5),
title="Async Generator Log Streamer"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Async Generator Log Streamer
Click 'Start Async Stream' to stream logs asynchronously.
Example 6: Polling Task Status with Check Intervals
Simulates polling an active background task status endpoint until completion.
Python (async_ex6.py)
import gradio as gr
import time
def poll_task_status(task_id):
for status in ["Queued (0%)", "Running (33%)", "Optimizing (66%)", "Completed (100%)"]:
time.sleep(0.5)
yield f"Task ID `{task_id}` ā Status: {status}"
demo = gr.Interface(
fn=poll_task_status,
inputs=gr.Textbox(label="Task ID", value="TASK-9921"),
outputs=gr.Textbox(label="Polling Status Output"),
title="Task Status Polling Simulator"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Task Status Polling Simulator
Click 'Poll Task Status' to view polling sequence.
Example 7: Async File Conversion & Background Packaging
Simulates an async background job converting uploaded datasets into ZIP download archives.
Python (async_ex7.py)
import gradio as gr
import time
def async_package_files(file):
filename = file.name if file else "dataset.csv"
time.sleep(1)
return f"š¦ Background Packaging Complete!\n- **Source File:** {filename}\n- **Archive:** `/tmp/exported_archive.zip`\n- **Status:** Ready for download."
demo = gr.Interface(
fn=async_package_files,
inputs=gr.File(label="Upload Dataset File"),
outputs=gr.Markdown(label="Export Result"),
title="Async File Packaging Worker"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Async File Packaging Worker
Click 'Package in Background' to simulate export worker.
Example 8: Async Task Cancellation & Timeout Handler
Implements timeout boundaries for long-running async operations to prevent server resource exhaustion.
Python (async_ex8.py)
import gradio as gr
import asyncio
async def timeout_protected_task(timeout_seconds):
try:
await asyncio.sleep(float(timeout_seconds))
return "ā
Task completed successfully within timeout limits."
except asyncio.CancelledError:
return "ā ļø Task timed out and was cancelled by the background controller."
demo = gr.Interface(
fn=timeout_protected_task,
inputs=gr.Textbox(label="Timeout Limit (seconds)", value="2"),
outputs=gr.Textbox(label="Execution Result"),
title="Async Timeout & Cancellation Guard"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Async Timeout & Cancellation Guard
Click 'Run Protected Task' to test timeout guard.
Example 9: Background Email Notification Dispatcher Worker
Dispatches background email notification tasks asynchronously so users do not experience web page lag.
Python (async_ex9.py)
import gradio as gr
import time
def dispatch_notification_worker(recipient):
time.sleep(0.6)
return f"š§ Background Email Dispatched Successfully!\n- **Recipient:** {recipient}\n- **Template:** Nikita-Infotech Booking Confirmation\n- **Worker ID:** `WORKER-44`"
demo = gr.Interface(
fn=dispatch_notification_worker,
inputs=gr.Textbox(label="Recipient Email", value="nikita@nikita-infotech.com"),
outputs=gr.Markdown(label="Dispatch Confirmation"),
title="Background Email Worker"
)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
### Background Email Worker
Click 'Dispatch Email in Background' to run email worker.
Example 10: Enterprise Asynchronous Operations Hub (`gr.Blocks`)
Combines background task queues, live worker telemetry, and async execution panels into an enterprise dashboard using
gr.Blocks.
Python (async_ex10.py)
import gradio as gr
import asyncio
async def run_enterprise_async_hub(command):
await asyncio.sleep(0.5)
return f"š Enterprise Async Hub executed command: '{command}'\n- Active Background Workers: 8\n- Queue Health: Optimal š¢"
with gr.Blocks() as demo:
gr.Markdown("# š Enterprise Asynchronous Operations Hub")
with gr.Row():
worker_status = gr.Textbox(label="Worker Pool Status", value="8 Active Workers | 0 Queued Jobs")
server_load = gr.Textbox(label="CPU / Memory Telemetry", value="CPU: 18% | RAM: 3.8GB")
cmd_in = gr.Textbox(label="Admin Background Command", value="purge_expired_cache_jobs")
btn = gr.Button("Execute Async Command", variant="primary")
out_box = gr.Textbox(label="Execution Result Log", lines=4)
btn.click(run_enterprise_async_hub, inputs=cmd_in, outputs=out_box)
if __name__ == "__main__":
demo.launch()
š„ļø Live Interactive Web UI Simulator
# š Enterprise Asynchronous Operations Hub
Workers: 8 Active š¢
CPU: 18% | RAM: 3.8GB
Click 'Execute Async Command' to run enterprise worker hub.