Gradio Interface
Gradio 문서 정보
Gradio의 Interface 사용하기
- Gradio의 Interface는 가장 코드가 간단한 형태이긴 한데 오히려 내용을 모르면 기능을 추가하기가 어려움
- UI 컴포넌트를 약어로 표시하기 때문에 익숙하지 않으면 더 헷갈릴 수 있음
- Interface 보다는 Blocks를 사용하는 것이 좀더 작성하기 수월함
필요한 모듈 설치
Interface를 활용한 가장 간단한 예제 (위치 인자 사용)
import gradio as gr
def greet(name):
return "Hello, " + name + "!"
demo = gr.Interface(
greet,
"text",
"text",
)
demo.launch()
제목과 설명을 추가한 경우
import gradio as gr
def greet(name):
return "Hello, " + name + "!"
demo = gr.Interface(
greet,
"text",
"text",
title="나의 AI 모델 실행기",
description="함수의 값을 입력해 주세요.",
)
demo.launch()
키워드 인자로 정의한 경우
import gradio as gr
def greet(name):
return "Hello, " + name + "!"
demo = gr.Interface(
fn=greet,
inputs=["text"],
outputs=["text"],
)
demo.launch()
컴포넌트 이름으로 파라미터 정의하기
import gradio as gr
def greet(name):
return "Hello, " + name + "!"
demo = gr.Interface(
fn=greet,
inputs=[gr.Textbox()],
outputs=[gr.Textbox()],
)
demo.launch()
함수 파라메터에 레이블 붙이기
import gradio as gr
def greet(name):
return "Hello, " + name + "!"
demo = gr.Interface(
fn=greet,
inputs=[gr.Textbox(label="이름")],
outputs=[gr.Textbox(label="결과")],
)
demo.launch()
여러 개의 입력 파라메터 사용하기
import gradio as gr
def greet(name, msg):
return "Hello, " + name + ", " + msg
demo = gr.Interface(
fn=greet,
inputs=[gr.Textbox(label="이름"), gr.Textbox(label="메세지")],
outputs=[gr.Textbox(label="결과")],
)
demo.launch()
다양한 타입의 입력 파라메터 사용하기
import gradio as gr
def greet(name, is_morning, temperature):
salutation = ""
if is_morning:
salutation = "즐거운 아침입니다."
else:
salutation = "즐거운 저녁입니다."
greeting = f"{salutation} {name}. 오늘 온도는 {temperature}도 입니다."
celsius = (temperature - 32) * 5 / 9
return greeting, round(celsius, 2)
demo = gr.Interface(
fn=greet,
inputs=["text", "checkbox", gr.Slider(0, 100)],
outputs=["text", "number"],
)
demo.launch()
다양한 컴포넌트를 파라메터로 사용
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
return num1 / num2
demo = gr.Interface(
calculator,
[
"number",
gr.Radio(["add", "subtract", "multiply", "divide"]),
"number"
],
"number",
title="Toy Calculator",
description="Here's a sample toy calculator.",
)
demo.launch()
입력 예시값을 examples를 사용하여 지정
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
return num1 / num2
demo = gr.Interface(
calculator,
[
"number",
gr.Radio(["add", "subtract", "multiply", "divide"]),
"number"
],
"number",
examples=[
[45, "add", 3],
[3.14, "divide", 2],
[144, "multiply", 2.5],
[0, "subtract", 1.2],
],
title="Toy Calculator",
description="Here's a sample toy calculator.",
)
demo.launch()
제목, 설명, 아티클
import gradio as gr
def mymodel(name):
return "Hello, " + name + "!"
demo = gr.Interface(
mymodel,
"text",
"text",
title="나의 AI 모델 실행기",
description="함수의 값을 입력해 주세요.",
article="2025년에 만든 모델입니다.",
)
demo.launch()
입력창에 설명 보이게 하기
import gradio as gr
def mymodel(age):
return str(age) + "살 입니다."
demo = gr.Interface(
mymodel,
gr.Number(label='나이', info='1살 이상 입력해 주세요'),
"text",
title="나의 AI 모델 실행기",
description="함수의 값을 입력해 주세요.",
article="2025년에 만든 모델입니다.",
)
demo.launch()
아코디언 효과 UI로 추가 입력 정의하기
import gradio as gr
def generate_fake_image(prompt, seed, initial_image=None):
return f"Used seed: {seed}", "https://www.alleycat.org/wp-content/uploads/2019/03/FELV-cat.jpg"
demo = gr.Interface(
generate_fake_image,
inputs=["textbox"],
outputs=["textbox", "image"],
additional_inputs=[
gr.Slider(0, 1000),
"image"
]
)
demo.launch()
출력만 있는 경우 (이미지 갤러리)
import time
import gradio as gr
def fake_gan():
time.sleep(1)
images = [
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
]
return images
demo = gr.Interface(
fn=fake_gan,
inputs=None,
outputs=gr.Gallery(label="Generated Images", columns=[2]),
title="FD-GAN",
description="This is a fake demo of a GAN. In reality, the images are randomly chosen from Unsplash.",
)
demo.launch()
입력만 있는 경우
import random
import string
import gradio as gr
def save_image_random_name(image):
random_string = ''.join(random.choices(string.ascii_letters, k=20)) + '.png'
image.save(random_string)
print(f"Saved image to {random_string}!")
demo = gr.Interface(
fn=save_image_random_name,
inputs=gr.Image(type="pil"),
outputs=None,
)
demo.launch()