📊
데이터공학
Gradio
Gradio
ML 데모 UI 빌더. Hugging Face 인수.
Gradio
ML 데모 UI 빌더. Hugging Face 인수.
Gradio는 머신러닝 모델을 위한 웹 기반 데모 UI를 빠르게 구축할 수 있는 Python 라이브러리입니다. 2022년 Hugging Face에 인수되어 허깅페이스 생태계의 핵심 도구로 자리잡았습니다.
| 컴포넌트 | 용도 | 예시 |
|---|---|---|
| gr.Textbox | 텍스트 입출력 | 챗봇, 번역 |
| gr.Image | 이미지 입출력 | 이미지 분류, 생성 |
| gr.Audio | 오디오 입출력 | 음성 인식, TTS |
| gr.Chatbot | 대화형 인터페이스 | LLM 채팅 |
| gr.File | 파일 업로드/다운로드 | 문서 처리 |
# 이미지 분류 모델 데모 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 기반 챗봇 데모
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()
# 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)
# 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()) # 결과 대기