콘텐츠로 이동

Gradio Blocks

Gradio 문서 정보

필요한 모듈 설치

!pip install gradio

Blocks을 활용한 가장 간단한 예제

import gradio as gr

with gr.Blocks() as demo:
    gr.Label("Hello World!")

demo.launch()

Markdown으로 제목 표시하기

import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown(
    """
    # Hello World!
    Start typing below to see the output.
    """)

demo.launch()

Markdown 참고자료

https://gist.github.com/ihoneymon/652be052a0727ad59601

Markdown 사례

import gradio as gr
with gr.Blocks() as demo:
    gr.Markdown(
    """
    # 제목1
    ## 제목2
    ### 제목3
    수업 내용입니다. **ChatGPT** 과정입니다.
    """)
demo.launch()

Blocks안에 이미지 표시하기

import gradio as gr

with gr.Blocks() as demo:
    gr.Image("dog1.jpg")

demo.launch()

이미지와 설명 문구

import gradio as gr

with gr.Blocks() as demo:

    gr.Markdown(
    """
    # My Dog
    Here is my doc.
    """)

    gr.Image("dog1.jpg")

demo.launch()

문자열 입력받기

import gradio as gr


with gr.Blocks() as demo:
    n = gr.Textbox(label="이름")

demo.launch()

여러 개의 문자열 입력받기

import gradio as gr


with gr.Blocks() as demo:
    n = gr.Textbox(label="이름")
    b = gr.Textbox(label="결과")

demo.launch()

버튼 추가하기

import gradio as gr

with gr.Blocks() as demo:
    n = gr.Textbox(label="이름")
    b = gr.Textbox(label="결과")
    greet_btn = gr.Button("실행")

demo.launch()

버튼에 함수 연동하기

import gradio as gr

def greet(a):
    return "Hello " + a + "!"

with gr.Blocks() as demo:

    n = gr.Textbox(label="이름")
    b = gr.Textbox(label="결과")

    greet_btn = gr.Button("실행")
    greet_btn.click(fn=greet, inputs=n, outputs=b)

demo.launch()

여러 개의 함수 파라메터 사용하기

import gradio as gr

def greet(a, b):
    return a + "," + b + " 입니다."

with gr.Blocks() as demo:

    n1 = gr.Textbox(label="이름")
    n2 = gr.Textbox(label="나이")
    r = gr.Textbox(label="결과")

    greet_btn = gr.Button("실행")
    greet_btn.click(fn=greet, inputs=[n1, n2], outputs=r)

demo.launch()

값 더하기

import gradio as gr

def greet(a, b):
    return a + b

with gr.Blocks() as demo:

    n1 = gr.Textbox(label="이름")
    n2 = gr.Textbox(label="나이")
    r = gr.Textbox(label="결과")
    greet_btn = gr.Button("더하기")

    greet_btn.click(fn=greet, inputs=[n1, n2], outputs=r)

demo.launch()

숫자로 입력받고 값 더하기

import gradio as gr

def sum(a, b, c):
    return a + b + c

with gr.Blocks() as demo:
    with gr.Row():
        num1 = gr.Number(label="a")
        num2 = gr.Number(label="b")
        num3 = gr.Number(label="c")

    output = gr.Number(label="Sum")

    exe_btn = gr.Button("실행")
    exe_btn.click(fn=sum, inputs=[num1, num2, num3], outputs=output)

demo.launch()

슬라이더로 값 입력받기

import gradio as gr

def sum(a, b, c):
    return a + b + c

with gr.Blocks() as demo:
    with gr.Row():
        num1 = gr.Slider(1, 10)
        num2 = gr.Slider(1, 10)
        num3 = gr.Slider(1, 10)

    output = gr.Number(label="Sum")

    exe_btn = gr.Button("실행")
    exe_btn.click(fn=sum, inputs=[num1, num2, num3], outputs=output)

demo.launch()

두 개의 버튼을 사용하기

import gradio as gr

# 버튼 클릭 시 실행될 함수 정의
def button1_action():
    return "버튼 1이 클릭되었습니다!"

def button2_action():
    return "버튼 2가 클릭되었습니다!"

# Blocks 사용하여 인터페이스 생성
with gr.Blocks() as demo:
    # Markdown으로 제목 추가
    gr.Markdown("# 두 개의 버튼을 배치")
    gr.Markdown("이 예제에서는 두 개의 버튼을 사용하는 예시를 보여줍니다.")

    # 2개의 버튼을 정의
    button1 = gr.Button("버튼 1")
    button2 = gr.Button("버튼 2")

    # 버튼 클릭 시 실행될 출력 필드
    output = gr.Textbox(label="출력")

    # 각 버튼에 클릭 이벤트와 출력 연결
    button1.click(fn=button1_action, outputs=output)
    button2.click(fn=button2_action, outputs=output)

# 인터페이스 실행
demo.launch()

Row()를 활용하여 같은 줄에 2개의 버튼을 표시하기

import gradio as gr

# 버튼 클릭 시 실행될 함수 정의
def button1_action():
    return "버튼 1이 클릭되었습니다!"

def button2_action():
    return "버튼 2가 클릭되었습니다!"

# Blocks 사용하여 인터페이스 생성
with gr.Blocks() as demo:
    # Markdown으로 제목 추가
    gr.Markdown("# 두 개의 버튼을 Row() 안에 배치")
    gr.Markdown("이 예제에서는 두 개의 버튼을 가로로 나란히 배치하고 각 버튼을 클릭 시 메시지를 반환합니다.")

    # Row() 안에 두 개의 버튼을 배치
    with gr.Row():
        button1 = gr.Button("버튼 1")
        button2 = gr.Button("버튼 2")

    # 버튼 클릭 시 실행될 출력 필드
    output = gr.Textbox(label="출력")

    # 각 버튼에 클릭 이벤트와 출력 연결
    button1.click(fn=button1_action, outputs=output)
    button2.click(fn=button2_action, outputs=output)

# 인터페이스 실행
demo.launch()

Row()에서의 다른 형태의 컴포넌트 적용1

import gradio as gr

# 버튼 클릭 시 실행될 함수 정의
def button1_action():
    return "버튼 1이 클릭되었습니다!"

def button2_action():
    return "버튼 2가 클릭되었습니다!"

# Blocks 사용하여 인터페이스 생성
with gr.Blocks() as demo:
    # Markdown으로 제목 추가
    gr.Markdown("# 두 개의 버튼을 Row() 안에 배치")
    gr.Markdown("이 예제에서는 두 개의 버튼을 가로로 나란히 배치하고 각 버튼을 클릭 시 메시지를 반환합니다.")

    # Row() 안에 두 개의 버튼을 배치
    with gr.Row():
        textbox = gr.Textbox()
        button1 = gr.Button("버튼 1")
        button2 = gr.Button("버튼 2")

    # 버튼 클릭 시 실행될 출력 필드
    output = gr.Textbox(label="출력")

    # 각 버튼에 클릭 이벤트와 출력 연결
    button1.click(fn=button1_action, outputs=output)
    button2.click(fn=button2_action, outputs=output)

# 인터페이스 실행
demo.launch()

Row()에서의 다른 형태의 컴포넌트 적용2

import gradio as gr

# 버튼 클릭 시 실행될 함수 정의
def button1_action():
    return "버튼 1이 클릭되었습니다!"

def button2_action():
    return "버튼 2가 클릭되었습니다!"

# Blocks 사용하여 인터페이스 생성
with gr.Blocks() as demo:
    # Markdown으로 제목 추가
    gr.Markdown("# 두 개의 버튼을 Row() 안에 배치")
    gr.Markdown("이 예제에서는 두 개의 버튼을 가로로 나란히 배치하고 각 버튼을 클릭 시 메시지를 반환합니다.")

    # Row() 안에 두 개의 버튼을 배치
    with gr.Row(equal_height=True):
        textbox = gr.Textbox()
        button1 = gr.Button("버튼 1")
        button2 = gr.Button("버튼 2")

    # 버튼 클릭 시 실행될 출력 필드
    output = gr.Textbox(label="출력")

    # 각 버튼에 클릭 이벤트와 출력 연결
    button1.click(fn=button1_action, outputs=output)
    button2.click(fn=button2_action, outputs=output)

# 인터페이스 실행
demo.launch()

서로 다른 크기를 갖는 버튼 설정

import gradio as gr

# 버튼 클릭 시 실행될 함수 정의
def button1_action():
    return "버튼 1이 클릭되었습니다!"

def button2_action():
    return "버튼 2가 클릭되었습니다!"

def button3_action():
    return "버튼 3이 클릭되었습니다!"

# Blocks 사용하여 인터페이스 생성
with gr.Blocks() as demo:
    # Markdown으로 제목 추가
    gr.Markdown("# 3개의 버튼을 Row() 안에 배치")
    gr.Markdown("이 예제에서는 3개의 버튼을 가로로 나란히 배치하고 각 버튼을 클릭 시 메시지를 반환합니다.")

    # Row() 안에 두 개의 버튼을 배치
    with gr.Row():
        button1 = gr.Button("Button 1", scale=0)
        button2 = gr.Button("Button 2", scale=1)
        button3 = gr.Button("Button 3", scale=2)

    # 버튼 클릭 시 실행될 출력 필드
    output = gr.Textbox(label="출력")

    # 각 버튼에 클릭 이벤트와 출력 연결
    button1.click(fn=button1_action, outputs=output)
    button2.click(fn=button2_action, outputs=output)
    button3.click(fn=button3_action, outputs=output)

# 인터페이스 실행
demo.launch()

Row와 Column을 이용한 레이아웃 구성

import gradio as gr

with gr.Blocks() as demo:

    with gr.Row():
        text1 = gr.Textbox(label="t1")
        slider2 = gr.Textbox(label="s2")
        drop3 = gr.Dropdown(["a", "b", "c"], label="d3")

    with gr.Row():

        with gr.Column(scale=1, min_width=300):
            text1 = gr.Textbox(label="prompt 1")
            text2 = gr.Textbox(label="prompt 2")
            inbtw = gr.Button("Between")
            text4 = gr.Textbox(label="prompt 1")
            text5 = gr.Textbox(label="prompt 2")

        with gr.Column(scale=2, min_width=300):
            img1 = gr.Image("images/cheetah.jpg")
            btn = gr.Button("Go")

demo.launch()

동적으로 컴포넌트를 보이게 하거나 숨기기

import gradio as gr

def change_textbox(choice):
    if choice == "short":
        return gr.Textbox(lines=2, visible=True)
    elif choice == "long":
        return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet")
    else:
        return gr.Textbox(visible=False)

with gr.Blocks() as demo:
    radio = gr.Radio(
        ["short", "long", "none"], label="What kind of essay would you like to write?"
    )
    text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)
    radio.change(fn=change_textbox, inputs=radio, outputs=text)

demo.launch()

간단한 HTML 사례

import gradio as gr

with gr.Blocks() as demo:

    gr.HTML(
    """
    Hello
    """)

demo.launch()

탭 메뉴와 아코디언 효과

import numpy as np
import gradio as gr

def flip_text(x):
    return x[::-1]

def flip_image(x):
    return np.fliplr(x)

with gr.Blocks() as demo:
    gr.Markdown("Flip text or image files using this demo.")
    with gr.Tab("Flip Text"):
        text_input = gr.Textbox()
        text_output = gr.Textbox()
        text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")

    with gr.Accordion("Open for More!", open=False):
        gr.Markdown("Look at me...")
        temp_slider = gr.Slider(
            0, 1,
            value=0.1,
            step=0.1,
            interactive=True,
            label="Slide me",
        )

    text_button.click(flip_text, inputs=text_input, outputs=text_output)
    image_button.click(flip_image, inputs=image_input, outputs=image_output)

demo.launch()