Gradio 상호작용 컴포넌트

KIM DA MI·2024년 1월 15일
0

gradio

목록 보기
4/9
post-thumbnail

Gradio의 상호작용 컴포넌트


상호작용은 Gradio의 중요한 특징이다.
이를 위해 Gradio는 다양한 기능을 사용하여 상호 작용할 수 있다.


🟠 Button

gradio.Button()을 사용하여 value = "Submit"을 지정하고 이벤트 gradio.Button.click()을 추가해 애플리케이션에 제출 버튼을 정의할 수 있다.

import gradio as gr
import os

def combine(a, b):
    return "안녕하세요! " + a + " " + b + " 환영합니다! 😀"

with gr.Blocks() as demo:

    txt = gr.Textbox(label="이름", lines=2)
    txt_2 = gr.Textbox(label="성")
    txt_3 = gr.Textbox(value="", label="결과")
    btn = gr.Button(value="제출")
    btn.click(combine, inputs=[txt, txt_2], outputs=[txt_3])

if __name__ == "__main__":
    demo.launch()


🟠 Check box

슬라이더 외에도 선택 항목을 위해 체크 박스를 추가할 수 있다.
아래의 예시는 시간 선택을 위해 슬라이더와 체크 박스를 결합한 것이다.

import gradio as gr

def sentence_builder(action):
    return f"""{'액션 영화' if action else '코미디 영화'}를 보는 것을 추천드립니다."""

demo = gr.Interface(
    sentence_builder,
    [
        gr.Checkbox(label="액션 영화를 좋아하시나요?"),
    ],
    "text")

if __name__ == "__main__":
    demo.launch()


🟠 Select box

gradio.CheckboxGroup()을 사용하여 선택 항목의 목록을 지정하여 선택 상자를 생성할 수 있다.

import gradio as gr

def meal_planner(time_of_day, meal_options):
    return f"{time_of_day}에는 {' 그리고 '.join(meal_options)}을(를) 드세요."

demo = gr.Interface(
    meal_planner,
    [
        gr.Radio(["아침", "점심", "저녁"], label="어느 시간대인가요?"),
        gr.CheckboxGroup(["토스트", "샌드위치", "과일", "샐러드", "스테이크", "파스타", "초밥", "치킨", "피자", "떡볶이"], label="음식을 선택하세요."),
    ],
    "text")

if __name__ == "__main__":
    demo.launch()


🟠 Date input

현재 Gradio는 위젯을 사용하여 날짜 선택을 지원하지 않는다.
그러나 gradio.Textbox()의 입력으로 datetime을 사용하여 현재 날짜를 포함한 다른 작업을 표시할 수 있다.

import gradio as gr
import datetime

with gr.Blocks() as demo:
    gr.Textbox(datetime.datetime.now)

demo.launch()


🟠 Color picker

랜덤한 색상을 생성하려면 gradio.ColorPicker()를 사용하면 된다.

# pip install opencv-python
import gradio as gr
import cv2
import numpy as np
import random

# 10진수 색상을 16진수 색상으로 변환
def RGB_to_Hex(rgb):
    color = "#"
    for i in rgb:
        num = int(i)
        color += str(hex(num))[-2:].replace("x", "0").upper()
    return color

# 랜덤하게 밝은 색상 또는 어두운 색상 생성
def gen_random_color(is_light=True):
    return (
        random.randint(0, 127) + int(is_light) * 128,
        random.randint(0, 127) + int(is_light) * 128,
        random.randint(0, 127) + int(is_light) * 128,
    )

def change_color(color_style):
    if color_style == "light":
        is_light = True
    elif color_style == "dark":
        is_light = False
    back_color_ = gen_random_color(is_light)  # 랜덤하게 색상 생성
    back_color = RGB_to_Hex(back_color_)  # 16진수로 변환

    # 색상 이미지 그리기
    w, h = 50, 50
    img = np.zeros((h, w, 3), np.uint8)
    cv2.rectangle(img, (0, 0), (w, h), back_color_, thickness=-1)

    return back_color, back_color, img

inputs = [gr.Radio(["light", "dark"], value="light")]

outputs = [
    gr.ColorPicker(label="색상"),
    gr.Textbox(label="16진수 색상"),
    gr.Image(type="numpy", label="색상 이미지"),
]

title = "랜덤 색상 생성기"
description = (
    "제출 버튼을 클릭하면 새로운 색상이 생성됩니다."
)

demo = gr.Interface(
    fn=change_color,
    inputs=inputs,
    outputs=outputs,
    title=title,
    description=description,
)

if __name__ == "__main__":
    demo.launch()


🟠 Slider

gradio.Slider()minimum부터 maximum까지의 범위를 가지며 step 크기로 슬라이더를 생성한다.
슬라이더의 기본 위치는 value로 지정된다.
아래는 minimum = 1, maximum = 12, step = 1인 슬라이더의 예시이다.

import gradio as gr

def workout_planner(start_time, morning, exercise_list):
    return f"""{"오전" if morning else "오후"} {start_time}시에 {"과 함께 ".join(exercise_list)}을(를) 해보세요."""

demo = gr.Interface(
    workout_planner,
    [   gr.Slider(1, 12, value=10, step = 1),
        gr.Checkbox(label="오전에 운동을 하시나요?"),
        gr.CheckboxGroup(["스트레칭", "유산소 운동", "근력 운동", "요가"]),
    ],
    "text")

if __name__ == "__main__":
    demo.launch()


🟠 Dropdown

Gradio의 Dropdown() 함수를 사용하면 가능한 항목 목록 중에서 항목을 지정할 수 있다.
애플리케이션을 기반으로, 사용자가 대신 할 수 있는 작업을 보여주는 추가 매개변수 watch를 정의할 수 있다.

import gradio as gr

def hobby_planner(hour, morning, hobby_list, watch):
    return f"""{"아침" if morning else "오후"} {hour}시에는 물 한 잔을 마시고 {" ".join(hobby_list)}를 하거나 {watch}를 감상하는 것이 좋습니다."""

demo = gr.Interface(
    hobby_planner,
    [
        gr.Slider(1, 12, value=9, step=1),
        gr.Checkbox(label="오전에 취미 활동을 하시나요?"),
        gr.CheckboxGroup(["그림 그리기", "음악 듣기", "요리하기", "산책하기"]),
        gr.Dropdown(["TV 드라마", "영화", "다큐멘터리", "강의"]),
    ],
    "text")

if __name__ == "__main__":
    demo.launch()

0개의 댓글