Lesson 160 — Intermediate
Quick Demos with Gradio & Hugging Face Spaces
Is lesson ka mental model: Function → UI in one call → share link — aur ek line jo demo ka status batati hai, a demo is evidence, not architecture. Is lesson mein tum har Python function ko Gradio Interface se web UI mein badalna, Blocks se chat/streaming banana, Spaces pe push karna, Gradio vs Streamlit vs FastAPI wala decision table, aur demo hygiene seekhoge — demo kahan khatam hota hai, production kahan shuru.
Demo kyun — evidence banao, architecture nahi
Kya hai?
Gradio tumhare Python function ko web UI mein badal deta hai — inputs, buttons, output dikhana — ek call mein. Function signature hi UI ban jaata hai: do inputs do components, tuple output do components. Usi app ko HF Spaces pe push karke public link mil jaata hai.
Kab kaam aata hai?
Model ko karke dikhane ke liye — teammate, reviewer ya user feedback ke liye jaldi. Demo ka kaam hai convince karna ("dekh, kaam karta hai") aur feedback ikattha karna. Backend banana abhi nahi — wo alag decision hai.
Kahan milta hai?
gradio.app/docs ke Interface/Blocks API mein, Hugging Face Spaces (Gradio SDK) mein, aur model research pages ke peeche jo har model ke saath chhota playground dete hain. Production ka raasta L10 LLMOps mein hai — demo uska substitute nahi.
Demo aur product ka farq ek line mein: demo ka kaam hai sach dikhana, product ka kaam hai zimmedari lena. Demo mein kal link badal sakte ho; product mein on-call hota hai, auth hota hai, contract hota hai. Isliye demo ko banaw aur use karo — par uspe SLA mat chadhao.
Gradio Interface — function se UI ek call mein
import gradio as gr
def spam_check(text): # TF-IDF wala chhota checker bhi chalega
words = text.lower().split()
hits = sum(1 for w in words if w in {"free", "winner", "click"})
label = "spam" if hits >= 2 else "ham"
return label, round(hits / max(len(words), 1), 2)
demo = gr.Interface(
fn = spam_check,
inputs = gr.Textbox(lines=3, label="Message"),
outputs = [gr.Label(label="verdict"), gr.Number(label="signal ratio")],
examples = [["free gift winner click here"], ["kal meeting 10 baje"]],
)
demo.launch(share=True) # temporary share link — demo ke liye
- Interface: ek function + inputs list + outputs list — sabse tez tareeka. Function ke return tuple ka order output list ke saath match karna zaroori hai.
- Components: Textbox, Image, Audio, Label, Number, Dropdown — har data type ka apna widget. Component chunna hi contract declare karna hai.
- Examples rows: input ki shakal pehle se dikha deti hai — user ko hint, tumhe quick sanity cases. Demo adoption mein sabse sasta kadam.
- share=True: temporary public link — limited life, gira toh dobara launch karo. Local launch (share chhoda) localhost pe chalta hai, dev ke liye kaafi.
- Docs: gradio.app/docs — har component ka page wahan hai, yaad rakhne ki zarurat nahi.
Blocks, chat aur streaming — Interface chhoti pad jaaye tab
import gradio as gr
# Blocks: layout + event flow tumhare control mein
with gr.Blocks() as chat:
gr.Markdown("## Support assistant (demo)")
msg = gr.Textbox(label="Sawaal")
out = gr.Chatbot(label="Jawab")
btn = gr.Button("Bhejo")
def reply(q, history):
history = history + [[q, "Demo jawab — model yahan plug hoga"]]
yield history # streaming: row by row update
btn.click(reply, [msg, out], [out])
chat.launch()
- Blocks kab: multiple inputs, steps, conditionals, shared state — jab Interface chhoti pad jaaye. Layout aur event wiring dono control mein.
- Chat: Chatbot component conversation history rakhta hai; chat-style helpers bhi milte hain — exact API version dekh kar lo (neeche callout).
- Streaming: generator function (yield) se output chunk-by-chunk — LLM responses ke liye natural: pehla token turant, baaki ruk ruk kar.
- Session state: per-session data ke liye state component — multi-user demo mein shared variable rakhna sabse aam bug hai.
Hugging Face Spaces — push karo, link milega
# Space root pe config (Gradio SDK wala app)
title: spam-check-demo
sdk: gradio # static | gradio | docker
app_file: app.py
license: apache-2.0
# sdk_version pin karo — "latest" chhod doge toh kal app hi na chale
# resources demo-grade: chhota quota, cold start ho sakta hai
# batch job / long training yahan nahi — preview yahan
- Spaces ke teen SDK: static (HTML/JS), Gradio (ML demo ke liye sabse common), Docker (jab control chahiye). Repo + app file + requirements — push, build chalu.
- Demo-grade resources: quota, cold starts, uptime demo-level. Isi liye page pe "demo vs product" label zaroori — resources bhi wahi kehte hain.
- Secrets: platform settings ke env/secrets use karo, code mein hardcode kabhi nahi. Free-tier limits official docs (huggingface.co/docs) se check karo, yaad mat rakho.
- Private bhi auth nahi: andar wala Space bhi access control ka substitute nahi — visibility aur auth alag cheezein hain.
Decision table — Gradio vs Streamlit vs FastAPI
Gradio Streamlit FastAPI
kya banta hai model ka UI dashboard/forms REST API
der mein minutes minutes ghanton (UI khud)
seeds function I/O widgets/data request schema
sahi audience model karke dikhao stakeholder view doosri services
auth/rate limit demo-grade DIY tum likhte ho
prod path backend alag chahiye — wahi L10/L14 wala raasta
stage-wise decision: pehle demo (Gradio), phir dashboard (Streamlit),
contract chahiye toh API (FastAPI) — teeno ek saath bhi chalte hain
- Gradio chuno jab object MODEL hai: inputs/outputs clear hain, feedback chahiye, jaldi dikhana hai. ML demo ka default.
- Streamlit chuno jab data/app dashboard ho: forms, charts, multipage views, stateful app — coding rapid hai, model I/O wrapper nahi.
- FastAPI chuno jab consumers services hain: mobile app, batch jobs, doosre backends — contract = schema + status codes + auth.
- Exclusive nahi hain: Gradio demo ke peeche FastAPI service ho sakti hai, ya Gradio hi internal tool. Decision stage-wise hai, ek baar ka nahi.
Demo hygiene — honesty hi design rule hai
- No real secrets: demo code public hota hai (link + repo). Keys env/settings se, best case mein toh demo ke andar hi nahi.
- Synthetic data: asli customer data kabhi nahi — mock rows banao. Demo ka leak sabse mehnga leak hota hai.
- Timeouts aur loading: heavy imports aur model load se demo khud na toote — lazy load ya chhota model rakho.
- Label clearly: page pe likho "Demo — not a product". Demo vs product ki honesty hi design rule hai.
- Backend nahi hai kyunki: shared process, koi auth story nahi, koi SLA/monitoring nahi — ye teen line interview mein bhi chalti hain.
Demo ko kachra mat samjho — demo se aaya feedback curated eval set ban sakta hai: kya tune kiya, kya tod diya, kaunse inputs aaye. Isi se agla fixed version ya fine-tune ka data banta hai. Demo sirf screenshot nahi, data ka source bhi hai.
Exercise
Question: Function ko ek call mein web UI mein badalne wala sabse tez constructor kaunsa hai?
Question: share=True se milne wala public link permanent hota hai ya temporary?
Question: Spaces ke teen SDKs — static aur gradio ke alawa teesra kaunsa?
Question: Dashboard banana ho toh Gradio ki jagah kaunsa option? (ek shabd)
Question: Demo ko backend se alag karne walo mein se ek: auth, UI widget, ya button?
Common mistakes
- Demo ko backend chadhana: Auth, rate limit, validation aur observability nahi — phir bhi link prod mein bhej diya. Fix: demo evidence hai; contract chahiye toh FastAPI service likho (L10 wala raasta).
- Real secrets ya real data demo mein daal dena: Link public, repo public — leak pakka. Fix: env/secrets platform settings mein, data synthetic, aur README mein demo label.
- Gradio ko FastAPI ka replacement samajhna: Gradio UI wrapper hai, service contract nahi — status codes, auth, validation uske daire se bahar. Fix: dono ko alag roles do — demo vs consumers.
- Version pin kiye bina Spaces deploy: Naye Gradio version ne component API tod di toh kal demo hi nahi chalega. Fix: requirements pin, launch smoke test, phir share link baantna.
Food stall wala tasting counter lagata hai — logon ko chakha kar feedback leta hai (demo). Wo counter hi uska restaurant nahi: roz ki service ke liye kitchen ka license, staff aur delivery system chahiye (backend). Gradio = tasting counter: minutes mein lag jaata hai aur feedback sach deta hai — par usko restaurant mat samjho:
# tasting counter (demo)
demo = gr.Interface(fn=taste, inputs=menu_item, outputs=review)
demo.launch(share=True) # logon ne chakha, feedback aaya
# restaurant (product) — ye demo nahi karega:
# auth | rate limit | logging | SLA | versioned API -> FastAPI service- Q: Gradio Interface kya karta hai? — Ek Python function ko inputs/outputs ke web UI mein wrap karta hai, ek call mein; share link se turant share.
- Q: Gradio, Streamlit, FastAPI — kab kaunsa? — Model I/O demo: Gradio; dashboard/forms: Streamlit; service-to-service contract: FastAPI.
- Q: Demo production kyun nahi? — Koi auth story nahi, rate limit/observability/SLA nahi, demo-grade resources — wrapper vs service ka farq.
- Q: Spaces deploy ke liye kya chahiye? — Repo + config (sdk: gradio, app_file) + pinned requirements; secrets settings se, data synthetic.
- Q: Demo ki asli business value kya hai? — Evidence aur feedback data (curated eval set banta hai) — architecture nahi, tool hai.
Demo bana, share kiya, boundaries bhi clear — yehi L17 ka poora khel: mechanism samajhna (VAE/GAN/diffusion), language ko reward se shape karna (RL), aur usse workflow-demo mein tod kar dikhana. L17 Generative Models & Automation yahan poora hua — ab tum theory ko component, graph aur demo teeno roop mein explain kar sakte ho.