๐Ÿ“Š Data Engineering

Gradio

Gradio

An ML demo UI builder. Acquired by Hugging Face.

Detailed Explanation

Gradio is a Python library that lets you quickly build web-based demo UIs for machine learning models. It was acquired by Hugging Face in 2022 and has become a core tool of the Hugging Face ecosystem.

Key Features of Gradio

  • Rapid prototyping: Create an interactive UI with just a few lines of code
  • Various input/output components: Images, audio, text, files, etc.
  • Shareable links: Automatically generates a temporary public URL
  • Hugging Face Spaces integration: Supports free hosting
  • Automatic API generation: Automatically generates REST API endpoints

Main Components

ComponentUse caseExamples
gr.TextboxText Input/OutputChatbot, translation
gr.ImageImage Input/OutputImage classification, generation
gr.AudioAudio Input/OutputSpeech recognition, TTS
gr.ChatbotConversational InterfaceLLM chat
gr.FileFile Upload/DownloadDocument processing

Code Example

Basic Image Classification Demo

# ์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜ ๋ชจ๋ธ ๋ฐ๋ชจ UI
import gradio as gr
from transformers import pipeline

# ์‚ฌ์ „ ํ•™์Šต๋œ ์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜ ๋ชจ๋ธ ๋กœ๋“œ
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")

def classify_image(image):
    """์ด๋ฏธ์ง€๋ฅผ ๋ถ„๋ฅ˜ํ•˜๊ณ  ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜"""
    results = classifier(image)
    return {result['label']: result['score'] for result in results}

# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
demo = gr.Interface(
    fn=classify_image,
    inputs=gr.Image(type="pil", label="์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•˜์„ธ์š”"),
    outputs=gr.Label(num_top_classes=5, label="๋ถ„๋ฅ˜ ๊ฒฐ๊ณผ"),
    title="์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜ ๋ฐ๋ชจ",
    description="์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•˜๋ฉด AI๊ฐ€ ๋ถ„๋ฅ˜ํ•ฉ๋‹ˆ๋‹ค.",
    examples=[
        ["examples/cat.jpg"],
        ["examples/dog.jpg"],
        ["examples/car.jpg"]
    ],
    cache_examples=True
)

demo.launch(share=True)  # ๊ณต๊ฐœ ๋งํฌ ์ƒ์„ฑ

LLM Chatbot Interface

# LLM ๊ธฐ๋ฐ˜ ์ฑ—๋ด‡ ๋ฐ๋ชจ
import gradio as gr
from openai import OpenAI

client = OpenAI()

def chat_with_gpt(message, history):
    """GPT์™€ ๋Œ€ํ™”ํ•˜๋Š” ํ•จ์ˆ˜"""
    # ๋Œ€ํ™” ์ด๋ ฅ์„ OpenAI ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜
    messages = [{"role": "system", "content": "๋‹น์‹ ์€ ์นœ์ ˆํ•œ AI ์–ด์‹œ์Šคํ„ดํŠธ์ž…๋‹ˆ๋‹ค."}]

    for human, assistant in history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": assistant})

    messages.append({"role": "user", "content": message})

    # ์ŠคํŠธ๋ฆฌ๋ฐ ์‘๋‹ต
    response = client.chat.completions.create(
        model="gpt-4",
        messages=messages,
        stream=True
    )

    partial_message = ""
    for chunk in response:
        if chunk.choices[0].delta.content:
            partial_message += chunk.choices[0].delta.content
            yield partial_message

# Chatbot ์ธํ„ฐํŽ˜์ด์Šค
demo = gr.ChatInterface(
    fn=chat_with_gpt,
    title="GPT-4 ์ฑ—๋ด‡",
    description="GPT-4์™€ ๋Œ€ํ™”ํ•ด๋ณด์„ธ์š”!",
    examples=["์•ˆ๋…•ํ•˜์„ธ์š”!", "Python์—์„œ ๋ฆฌ์ŠคํŠธ์™€ ํŠœํ”Œ์˜ ์ฐจ์ด์ ์€?", "์˜ค๋Š˜ ๋‚ ์”จ๊ฐ€ ์–ด๋•Œ?"],
    retry_btn="๋‹ค์‹œ ์‹œ๋„",
    undo_btn="์‹คํ–‰ ์ทจ์†Œ",
    clear_btn="๋Œ€ํ™” ์ดˆ๊ธฐํ™”"
)

demo.launch()

Multi-Input ML Demo (Blocks API)

# Blocks API๋ฅผ ์‚ฌ์šฉํ•œ ๋ณต์žกํ•œ ๋ ˆ์ด์•„์›ƒ
import gradio as gr
import torch
from diffusers import StableDiffusionPipeline

# Stable Diffusion ๋ชจ๋ธ ๋กœ๋“œ
pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)
pipe = pipe.to("cuda")

def generate_image(prompt, negative_prompt, num_steps, guidance_scale):
    """์ด๋ฏธ์ง€ ์ƒ์„ฑ ํ•จ์ˆ˜"""
    image = pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_inference_steps=num_steps,
        guidance_scale=guidance_scale
    ).images[0]
    return image

# Blocks API๋กœ ์ปค์Šคํ…€ ๋ ˆ์ด์•„์›ƒ
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# Stable Diffusion ์ด๋ฏธ์ง€ ์ƒ์„ฑ๊ธฐ")
    gr.Markdown("ํ…์ŠคํŠธ ํ”„๋กฌํ”„ํŠธ๋กœ ์ด๋ฏธ์ง€๋ฅผ ์ƒ์„ฑํ•˜์„ธ์š”!")

    with gr.Row():
        with gr.Column(scale=2):
            prompt = gr.Textbox(
                label="ํ”„๋กฌํ”„ํŠธ",
                placeholder="์ƒ์„ฑํ•˜๊ณ  ์‹ถ์€ ์ด๋ฏธ์ง€๋ฅผ ์„ค๋ช…ํ•˜์„ธ์š”...",
                lines=3
            )
            negative_prompt = gr.Textbox(
                label="๋„ค๊ฑฐํ‹ฐ๋ธŒ ํ”„๋กฌํ”„ํŠธ",
                placeholder="์ œ์™ธํ•˜๊ณ  ์‹ถ์€ ์š”์†Œ...",
                lines=2
            )

            with gr.Row():
                num_steps = gr.Slider(
                    minimum=10, maximum=50, value=30, step=1,
                    label="์ถ”๋ก  ์Šคํ… ์ˆ˜"
                )
                guidance_scale = gr.Slider(
                    minimum=1, maximum=20, value=7.5, step=0.5,
                    label="๊ฐ€์ด๋˜์Šค ์Šค์ผ€์ผ"
                )

            generate_btn = gr.Button("์ด๋ฏธ์ง€ ์ƒ์„ฑ", variant="primary")

        with gr.Column(scale=3):
            output_image = gr.Image(label="์ƒ์„ฑ๋œ ์ด๋ฏธ์ง€", type="pil")

    # ์˜ˆ์ œ
    gr.Examples(
        examples=[
            ["A beautiful sunset over mountains, digital art", "blurry, low quality", 30, 7.5],
            ["A cute robot reading a book, cartoon style", "realistic, photo", 30, 7.5],
        ],
        inputs=[prompt, negative_prompt, num_steps, guidance_scale],
        outputs=output_image,
        fn=generate_image,
        cache_examples=True
    )

    # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
    generate_btn.click(
        fn=generate_image,
        inputs=[prompt, negative_prompt, num_steps, guidance_scale],
        outputs=output_image
    )

# Hugging Face Spaces ๋ฐฐํฌ์šฉ ์„ค์ •
demo.queue()  # ์š”์ฒญ ํ์ž‰ ํ™œ์„ฑํ™”
demo.launch(server_name="0.0.0.0", server_port=7860)

Calling a Gradio App via API

# Gradio ์•ฑ์˜ ์ž๋™ ์ƒ์„ฑ๋œ API ์‚ฌ์šฉํ•˜๊ธฐ
from gradio_client import Client

# Hugging Face Spaces์— ๋ฐฐํฌ๋œ ์•ฑ ์—ฐ๊ฒฐ
client = Client("username/my-gradio-app")

# API ํ˜ธ์ถœ
result = client.predict(
    "Hello, how are you?",  # ์ž…๋ ฅ ํ…์ŠคํŠธ
    api_name="/predict"      # ์—”๋“œํฌ์ธํŠธ
)
print(result)

# ๋น„๋™๊ธฐ ํ˜ธ์ถœ
job = client.submit(
    "Generate a story about AI",
    api_name="/generate"
)
print(job.result())  # ๊ฒฐ๊ณผ ๋Œ€๊ธฐ

Practical Conversation Example

ML Engineer: "I need to demo the model I just trained to my teammates quickly, but I don't have time to develop a frontend."
Senior Engineer: "Try Gradio. You can build a web demo in about 10 lines. With share=True, it also generates a temporary public URL."
ML Engineer: "How do I deploy it permanently?"
Senior Engineer: "You can host it for free on Hugging Face Spaces. You can also use GPUs, or package it with Docker and deploy it to your own server."
ML Engineer: "How is it different from Streamlit?"
Senior Engineer: "Gradio is specialized for ML model demos. It has rich input/output components, and the API is generated automatically. Streamlit is better suited to more general-purpose data apps."

Cautions

Security Considerations

  • share=True links expire after 72 hours - not intended for production use
  • User input validation is required - prevent malicious input
  • Sensitive models require adding authentication

Performance Considerations

  • For large models, enable queue() to manage concurrent requests
  • A model unloading strategy is needed when GPU memory is insufficient
  • Set file size limits when processing images/audio

Deployment Notes

  • The Hugging Face Spaces free tier has resource limits
  • Specify exact versions in requirements.txt
  • Use Git LFS or Hugging Face Hub for model files

Related Terms

Learn More