본문 바로가기
C.W.K.
Stream
Lesson 02 of 04 · published

Gradio: 10 줄로 ML 데모

~26 min · spaces, gradio

Level 0스카우트
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Gradio에서는 Python 함수가 화면 계약이 돼

함수를 만든 뒤 gr.Interfacegr.Blocks로 감싸면 Gradio가 입력과 출력을 연결해 웹 UI를 제공해. 로컬에서는 demo.launch()가 서버를 열고 Space에서는 런타임이 앱을 시작해.

  • gr.Interface(fn, inputs, outputs)는 함수 하나를 보여 주는 단일 작업 데모에 가장 빨라.
  • gr.Blocks()는 여러 입력·출력, 탭, CSS, 조건부 표시를 직접 배치할 때 써.

대화에는 ChatInterface를 써

gr.ChatInterface는 메시지 이력과 generator 기반 스트리밍 처리를 함께 제공해. handler 안에서 InferenceClient를 부르든 로컬 모델을 부르든 화면 쪽 계약은 유지할 수 있어.

Code

HF 모델의 10 줄 Gradio 데모·python
import gradio as gr
from transformers import pipeline

pipe = pipeline("sentiment-analysis")

def classify(text):
    out = pipe(text)[0]
    return f"{out['label']} ({out['score']:.2f})"

demo = gr.Interface(fn=classify, inputs=gr.Textbox(label="Review"), outputs="text")
demo.launch()
InferenceClient 로 streaming 챗·python
import gradio as gr
from huggingface_hub import InferenceClient

client = InferenceClient(model="meta-llama/Llama-3.1-8B-Instruct", provider="hf-inference")

def chat(message, history):
    messages = [{"role": h[0] and "user" or "assistant", "content": h[1]} for h in history if h]
    messages.append({"role": "user", "content": message})
    stream = client.chat_completion(messages=messages, max_tokens=500, stream=True)
    answer = ""
    for chunk in stream:
        delta = chunk.choices[0].delta.content or ""
        answer += delta
        yield answer

gr.ChatInterface(chat, title="Llama Chat").launch()

External links

Exercise

작은 HF 모델 (예: text classification 또는 whisper-tiny) wrap 하는 Gradio Space 빌드. 로컬 먼저 테스트. Space 에 push. 다른 모델 데모하는 두 번째 탭 추가. 둘 다 side-by-side 동작 검증.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.