ドキュメントが整っていなかったので手順をまとめました。
参考
How to curl a Gradio App
https://www.freddyboulton.com/blog/gradio-curl
コードの準備
以下のapp.pyファイルを作成する。
import gradio as gr
from transformers import pipeline
pipe = pipeline(
task="depth-estimation",
model="depth-anything/Depth-Anything-V2-Small-hf",
)
def estimate_depth(image):
return pipe(image)["depth"]
demo = gr.Interface(
api_name='estimate_depth',
fn=estimate_depth,
inputs=gr.Image(type="pil", label="Input Image"),
outputs=gr.Image(type="pil", label="Estimated Depth"),
examples=[
[
"https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
]
],
title="Depth Estimation",
)
if __name__ == "__main__":
demo.launch(
server_name="127.0.0.1",
server_port=7870,
)
ポイント
APIの入出力形式は、Gradioのインターフェース定義部分gr.Interface(... inputs=gr.Image(...
で決まる。今回は画像入力となる。
run Gradio App
python app.py
なお、以下にアクセスするとAPIの呼び出し方の説明が見れる。
http://127.0.0.1:7870/?view=api
Curl API
カレントディレクトリに深度推定したい画像0.png
を用意して、Bashから以下のコマンドを実行する。
__TARGET_URL__=http://127.0.0.1:7870 \
&& curl -s -F files=@0.png "${__TARGET_URL__}/upload" \
| jq -r '.[0]' \
| { read INPUT_FILE_PATH; curl -X POST "${__TARGET_URL__}/call/estimate_depth" -s -H "Content-Type: application/json" -d "$(cat <<EOF
{
"data": [
{
"orig_name" : "0.png",
"path": "$INPUT_FILE_PATH"
}
]
}
EOF
)"; } \
| jq -r '.event_id' \
| { read EVENT_ID; curl -s -N "${__TARGET_URL__}/call/estimate_depth/$EVENT_ID" ;} \
| sed -n 's/^data: //p' | jq -r '.[0].path' \
| { read IMAGE_PATH; curl -s -o image.webp ${__TARGET_URL__}/file=$IMAGE_PATH; }
成功すると、カレントディレクトリにimage.webpが保存される。
コマンドの内容
-
画像をアップロードする
curl -s -F files=@0.png "${__TARGET_URL__}/upload"
- ローカルのファイル
0.png
を指定されたURLにアップロードし、アップロードされたファイルのパスをJSON形式で取得します。
-
深度推定リクエストを送信する
-
アップロードされたファイルのパスを抽出して変数に格納する
jq -r '.[0]' | { read INPUT_FILE_PATH; }
- JSONレスポンスからファイルパスを抽出し、
INPUT_FILE_PATH
変数に格納します。
-
深度推定リクエストを送信する
curl -X POST "${__TARGET_URL__}/call/estimate_depth" -s -H "Content-Type: application/json" -d "$(cat <<EOF ... EOF)"
- 抽出したファイルパスと元のファイル名を使用して、深度推定のリクエストをサーバーに送信します。
-
アップロードされたファイルのパスを抽出して変数に格納する
-
深度推定結果を取得する
-
イベントIDを取得する
jq -r '.event_id' | { read EVENT_ID; }
- 深度推定リクエストのレスポンスからイベントIDを抽出し、
EVENT_ID
変数に格納します。
-
イベントIDを使用して深度推定の処理結果を取得する
curl -s -N "${__TARGET_URL__}/call/estimate_depth/$EVENT_ID"
- イベントIDを用いて、サーバーから深度推定の結果(深度画像のパス)をストリーミング形式で取得します。
-
深度画像のパスを抽出して変数に格納する
sed -n 's/^data: //p' | jq -r '.[0].path' | { read IMAGE_PATH; }
- 取得したストリーミングデータから深度画像のパスを抽出し、
IMAGE_PATH
変数に格納します。
-
イベントIDを取得する
-
深度画像をダウンロードする
curl -s -o image.webp ${__TARGET_URL__}/file=$IMAGE_PATH
- 抽出した深度画像のパスを使用して、深度画像を
image.webp
という名前でローカルにダウンロードします。