Gradioの基本
Gradioの概要
Gradio
はDeepLearningなどの学習結果に基づいてWebアプリケーションを作成する際に用いるPython
のライブラリです。
Gradioのインストールとサンプルコードの実行
Gradio
は下記を実行することでPyPIから入手することができます。
$ pip install gradio
次にGradio
のサンプルコードを実行します。
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
にアクセスすると下記のような画面が確認できます。
上記の画面が出力されていればGradio
のインストールは成功しているので詳しい実装例については次節で取り扱います。
Interfaceクラスの活用
前項のsample_1_1.py
でも用いたInterface
クラスはPython
の任意の関数に基づいてデモを迅速に構築するにあたって用いられます。
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()
fn
・inputs
・outputs
Interface
クラスはfn
、inputs
、outputs
の3つのパラメータによって初期化されます。3つのパラメータはそれぞれ下記のように理解すると良いです。
パラメータ | 役割 |
---|---|
fn |
Interface によって高度化する関数、fn で与える関数の引数がinputs からの入力、return で返す返り値がoutputs に対応する |
inputs |
入力フォームの型などを指定するパラメータ、リストを引数に与える場合は要素の数だけ画面から値を入力する |
outputs |
入力フォームの型などを指定するパラメータ、リストを引数に与える場合は要素の数だけ画面に値が出力される |
Multiple Input and Output Components
inputs
やoutputs
で複数の入力と出力を取り扱う場合は下記のようなスクリプトを実行すれば良いです。
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()
Components Attributes
inputs
やoutputs
の初期値やフォームのフォーマットは下記のように指定することができます。
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()