STREAMING RESPONSES & GENERATORS: 10 REAL-TIME PYTHON YIELD EXAMPLES

Build responsive, real-time streaming applications in Gradio using Python generator functions (yield) for progressive text generation, live logs, and countdown timers.

⚡ Streaming Responses with Python Generators (`yield`)

Standard Python functions use return to send a final computed result all at once. In contrast, generator functions use yield to emit intermediate values progressively over time. In Gradio, passing a generator function to an Interface or ChatInterface instantly transforms static UI outputs into real-time streaming experiences.

Example 1: Definition & Basic Word-by-Word Text Streamer
Demonstrates a fundamental Python generator function yielding words incrementally with timed delays.
Python (stream_ex1.py)
import gradio as gr
import time

def stream_text(prompt):
    text = f"Streaming response for your query: '{prompt}'. Nikita-Infotech delivers real-time AI solutions."
    current = ""
    for word in text.split():
        current += word + " "
        time.sleep(0.1)
        yield current

demo = gr.Interface(
    fn=stream_text,
    inputs=gr.Textbox(label="Enter Prompt", value="Hello Gradio"),
    outputs=gr.Textbox(label="Streamed Output"),
    title="Basic Word-by-Word Text Streamer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Basic Word-by-Word Text Streamer

Enter Prompt: Hello Gradio
Streaming response for your query: 'Hello Gradio'... [Streaming]
Example 2: Live Countdown Timer Generator
Builds a real-time countdown timer that ticks down second by second using time.sleep(1) and yield.
Python (stream_ex2.py)
import gradio as gr
import time

def countdown(seconds):
    try:
        sec = int(seconds)
    except:
        sec = 5
    for i in range(sec, 0, -1):
        yield f"⏳ Countdown remaining: {i} seconds..."
        time.sleep(1)
    yield "🚀 Blast off! Countdown completed successfully."

demo = gr.Interface(
    fn=countdown,
    inputs=gr.Textbox(label="Start Seconds", value="5"),
    outputs=gr.Textbox(label="Timer Display"),
    title="Real-Time Countdown Timer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Real-Time Countdown Timer

Start Seconds: 5
⏳ Countdown remaining: 3 seconds...
Example 3: Server Log Simulation Streamer
Simulates progressive server initialization logs (Apache Tomcat, PHP LAMP stack, database connection) in real-time.
Python (stream_ex3.py)
import gradio as gr
import time

def simulate_server_logs(action):
    logs = [
        "[INFO] Initializing Apache Tomcat server on port 8080...",
        "[SUCCESS] Connected to MySQL database via PDO...",
        "[INFO] Loading Nikita-Infotech modules and CSV visitor logs...",
        "[READY] Application server running and ready for client requests."
    ]
    output = ""
    for log in logs:
        output += log + "\n"
        time.sleep(0.6)
        yield output

demo = gr.Interface(
    fn=simulate_server_logs,
    inputs=gr.Button("Start Server Boot"),
    outputs=gr.Textbox(label="Live Terminal Logs", lines=5),
    title="Server Boot Log Streamer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Server Boot Log Streamer

[INFO] Initializing Apache Tomcat server...
[SUCCESS] Connected to MySQL database via PDO...
Example 4: Progressive Multi-Step Data Processing Pipeline
Streams incremental status updates for multi-stage tasks (Uploading ➔ Parsing ➔ Transforming ➔ Exporting).
Python (stream_ex4.py)
import gradio as gr
import time

def process_pipeline(dataset_name):
    steps = [
        f"📂 Loading dataset '{dataset_name}' into memory...",
        "🔍 Running data cleaning & null value imputation...",
        "⚙️ Executing machine learning feature scaling...",
        "📊 Generating final statistical report and charts...",
        "✅ Pipeline execution completed successfully!"
    ]
    current_status = ""
    for step in steps:
        current_status += step + "\n"
        time.sleep(0.8)
        yield current_status

demo = gr.Interface(
    fn=process_pipeline,
    inputs=gr.Textbox(label="Dataset Name", value="visitor_logs.csv"),
    outputs=gr.Textbox(label="Pipeline Execution Status", lines=6),
    title="Data Processing Pipeline Streamer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Data Processing Pipeline Streamer

Dataset Name: visitor_logs.csv
📂 Loading dataset...
🔍 Running data cleaning...
Example 5: Simulated AI Token-by-Token Chat Streaming
Integrates a streaming generator function inside gr.ChatInterface for real-time typewriter AI chat responses.
Python (stream_ex5.py)
import gradio as gr
import time

def stream_chat(message, history):
    response = f"Hello! I received your message: '{message}'. As an AI assistant built on Gradio, I am streaming this response token by token."
    current = ""
    for word in response.split():
        current += word + " "
        time.sleep(0.04)
        yield current

demo = gr.ChatInterface(
    fn=stream_chat,
    title="Typewriter AI Chat Streaming"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Typewriter AI Chat Streaming

[Chat Feed: Hello! I received your message... (Streaming)]
Example 6: Real-Time Stock Price / Financial Ticker Streamer
Simulates live financial ticker updates fluctuating in price over multiple streaming iterations.
Python (stream_ex6.py)
import gradio as gr
import time
import random

def live_ticker(symbol):
    base_price = 150.00
    report = f"📈 Live Ticker Stream for {symbol.upper()}:\n"
    for i in range(5):
        change = random.uniform(-1.5, 2.0)
        base_price += change
        report += f"Update #{i+1}: Price = ${base_price:.2f} ({'+' if change >=0 else ''}{change:.2f})\n"
        time.sleep(0.7)
        yield report

demo = gr.Interface(
    fn=live_ticker,
    inputs=gr.Textbox(label="Stock / Asset Symbol", value="NIKITA"),
    outputs=gr.Textbox(label="Live Price Ticker", lines=6),
    title="Real-Time Financial Ticker Streamer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Real-Time Financial Ticker Streamer

Stock Symbol: NIKITA
📈 Live Ticker Stream for NIKITA:
Update #1: Price = $151.20 (+1.20)
Example 7: File Upload & Progressive Scanning Progress Bar
Simulates virus or keyword scanning progress percentages on uploaded documents.
Python (stream_ex7.py)
import gradio as gr
import time

def scan_file(file):
    filename = file.name if file else "sample.txt"
    yield f"🛡️ Initializing security scan for: {filename}..."
    time.sleep(0.6)
    yield f"🛡️ Scanning file chunks [ 35% completed ]..."
    time.sleep(0.6)
    yield f"🛡️ Running keyword heuristics [ 80% completed ]..."
    time.sleep(0.6)
    yield f"✅ Scan Complete! 0 threats detected in {filename}."

demo = gr.Interface(
    fn=scan_file,
    inputs=gr.File(label="Upload File to Scan"),
    outputs=gr.Textbox(label="Live Scan Status"),
    title="Progressive File Security Scanner"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Progressive File Security Scanner

Upload File Drop Zone
✅ Scan Complete! 0 threats detected.
Example 8: Interactive Multi-Question Quiz Generator Streamer
Generates and streams quiz questions one after another with incremental pacing.
Python (stream_ex8.py)
import gradio as gr
import time

def generate_quiz(topic):
    questions = [
        f"📝 Question 1 on {topic}: What is the primary use of gr.Interface?",
        f"📝 Question 2 on {topic}: Which Python keyword enables generator functions?",
        f"📝 Question 3 on {topic}: What library is used for DataFrames in Python?"
    ]
    output = ""
    for q in questions:
        output += q + "\n"
        time.sleep(0.8)
        yield output

demo = gr.Interface(
    fn=generate_quiz,
    inputs=gr.Textbox(label="Quiz Topic", value="Gradio Python"),
    outputs=gr.Textbox(label="Streamed Quiz Content", lines=5),
    title="Streamed Quiz Generator"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Streamed Quiz Generator

Quiz Topic: Gradio Python
📝 Question 1 on Gradio Python: What is gr.Interface?
📝 Question 2: Which keyword enables generators?
Example 9: Batch Image Generation & Progressive Gallery Streamer
Streams progressive status updates while rendering synthetic images or batch previews.
Python (stream_ex9.py)
import gradio as gr
import time

def stream_image_gen(prompt):
    yield f"🎨 Initializing diffusion model for prompt: '{prompt}'..."
    time.sleep(0.7)
    yield f"🎨 Denoising latent space [ Step 10 / 30 ]..."
    time.sleep(0.7)
    yield f"🎨 Applying color grading & upscaling [ Step 25 / 30 ]..."
    time.sleep(0.7)
    yield f"✨ Image generation complete! Rendering final output."

demo = gr.Interface(
    fn=stream_image_gen,
    inputs=gr.Textbox(label="Image Prompt", value="Futuristic web development portal"),
    outputs=gr.Textbox(label="Generation Status Log"),
    title="Progressive Image Generation Streamer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Progressive Image Generation Streamer

Image Prompt: Futuristic web development portal
✨ Image generation complete! Rendering final output.
Example 10: Enterprise Real-Time Streaming Dashboard (`gr.Blocks`)
Combines multiple streaming metrics, button triggers, and status panels into an enterprise monitoring layout using gr.Blocks.
Python (stream_ex10.py)
import gradio as gr
import time

def run_diagnostic():
    checks = ["CPU Usage: 24% (Normal)", "Memory: 4.2GB / 16GB", "Active Visitors: 1,420", "Database Latency: 12ms", "All Systems Operational 🟢"]
    output = ""
    for check in checks:
        output += check + "\n"
        time.sleep(0.5)
        yield output

with gr.Blocks() as demo:
    gr.Markdown("# 📊 Enterprise Real-Time Monitoring Hub")
    with gr.Row():
        btn = gr.Button("Run Live Diagnostic", variant="primary")
    metrics_box = gr.Textbox(label="Live System Diagnostics", lines=6)
    
    btn.click(run_diagnostic, outputs=metrics_box)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

# 📊 Enterprise Real-Time Monitoring Hub

CPU Usage: 24% (Normal)
Memory: 4.2GB / 16GB
Active Visitors: 1,420