1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Gradio入門】Gradioのよく使うメソッドと実装例

Last updated at Posted at 2025-10-07

Gradioの基本

Gradioの概要

GradioはDeepLearningなどの学習結果に基づいてWebアプリケーションを作成する際に用いるPythonのライブラリです。

Gradioのインストールとサンプルコードの実行

Gradioは下記を実行することでPyPIから入手することができます。

$ pip install gradio

次にGradioのサンプルコードを実行します。

sample1.py
import gradio as gr


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

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()

上記のようなコードをsample1.pyに保存し、下記のコマンドを実行することでGradioの動作確認を行うことができます。

$ python sample1.py

・実行結果

* Running on local URL:  http://127.0.0.1:7860

実行後にブラウザからhttp://127.0.0.1:7860にアクセスすると下記のような画面が確認できます。

Gradio1.png

上記の画面が出力されていればGradioのインストールは成功しているので詳しい実装例については次節で取り扱います。

Interfaceクラスの活用

前項のsample_1_1.pyでも用いたInterfaceクラスはPythonの任意の関数に基づいてデモを迅速に構築するにあたって用いられます。

sample_1_1.py
import gradio as gr


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

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()

fninputsoutputs

Interfaceクラスはfninputsoutputsの3つのパラメータによって初期化されます。3つのパラメータはそれぞれ下記のように理解すると良いです。

パラメータ 役割
fn Interfaceによって高度化する関数、fnで与える関数の引数がinputsからの入力、returnで返す返り値がoutputsに対応する
inputs 入力フォームの型などを指定するパラメータ、リストを引数に与える場合は要素の数だけ画面から値を入力する
outputs 入力フォームの型などを指定するパラメータ、リストを引数に与える場合は要素の数だけ画面に値が出力される

Multiple Input and Output Components

inputsoutputsで複数の入力と出力を取り扱う場合は下記のようなスクリプトを実行すれば良いです。

sample_1_2.py
import gradio as gr

def greet(name, is_morning, temperature):
    salutation = "Good morning" if is_morning else "Good evening"
    greeting = f"{salutation} {name}. It is {temperature} degrees today"
    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()

・実行結果(http://127.0.0.1:7860)
Gradio2.png

Components Attributes

inputsoutputsの初期値やフォームのフォーマットは下記のように指定することができます。

sample_1_3.py
import gradio as gr

def greet(name, intensity):
    return "Hello, " + name + "!" * intensity

demo = gr.Interface(
    fn=greet,
    inputs=["text", gr.Slider(value=2, minimum=1, maximum=10, step=1)],
    outputs=[gr.Textbox(label="greeting", lines=3)],
)

demo.launch()

・実行結果(http://127.0.0.1:7860)
Gradio3.png

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?