gradio
gradioは、Pythonを使って機械学習モデルのデモ用UIを簡単に作成できるライブラリで、テキストや画像、音声、動画などを扱えるインタラクティブなWebインターフェースを構築し、公開リンクで共有したりHugging Face SpacesにデプロイしたりするSkill。
📜 元の英語説明(参考)
Python library for building ML demo UIs with minimal code. Create interactive web interfaces for models with text, image, audio, and video inputs/outputs. Share demos via public links or deploy to Hugging Face Spaces.
🇯🇵 日本人クリエイター向け解説
gradioは、Pythonを使って機械学習モデルのデモ用UIを簡単に作成できるライブラリで、テキストや画像、音声、動画などを扱えるインタラクティブなWebインターフェースを構築し、公開リンクで共有したりHugging Face SpacesにデプロイしたりするSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o gradio.zip https://jpskill.com/download/14957.zip && unzip -o gradio.zip && rm gradio.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/14957.zip -OutFile "$d\gradio.zip"; Expand-Archive "$d\gradio.zip" -DestinationPath $d -Force; ri "$d\gradio.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
gradio.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
gradioフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Gradio
インストール
# Gradio のインストール
pip install gradio
クイックスタート — シンプルなインターフェース
# hello.py — テキストインターフェースを持つ最小限の Gradio アプリ
import gradio as gr
def greet(name: str, intensity: int) -> str:
return "Hello, " + name + "!" * intensity
demo = gr.Interface(
fn=greet,
inputs=["text", gr.Slider(1, 10, value=1, label="Excitement")],
outputs="text",
title="Greeting Generator",
description="Enter your name and excitement level.",
)
demo.launch() # http://localhost:7860 を開きます
チャットインターフェース
# chatbot.py — ストリーミング応答でチャットボット UI を構築する
import gradio as gr
from openai import OpenAI
client = OpenAI()
def chat(message: str, history: list) -> str:
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for h in history:
messages.append({"role": "user", "content": h[0]})
if h[1]:
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": message})
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
stream=True,
)
partial = ""
for chunk in response:
if chunk.choices[0].delta.content:
partial += chunk.choices[0].delta.content
yield partial
demo = gr.ChatInterface(
fn=chat,
title="AI Chat",
description="Chat with GPT-4",
examples=["Tell me a joke", "Explain quantum computing"],
)
demo.launch()
画像分類
# image_classifier.py — 事前学習済みモデルを使用した画像分類デモ
import gradio as gr
from transformers import pipeline
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
def classify(image):
results = classifier(image)
return {r["label"]: r["score"] for r in results}
demo = gr.Interface(
fn=classify,
inputs=gr.Image(type="pil"),
outputs=gr.Label(num_top_classes=5),
title="Image Classifier",
examples=["cat.jpg", "dog.jpg"],
)
demo.launch()
Blocks API (カスタムレイアウト)
# blocks_app.py — Blocks API を使用して複雑なレイアウトを構築する
import gradio as gr
def process_text(text: str, operation: str) -> str:
if operation == "Uppercase":
return text.upper()
elif operation == "Lowercase":
return text.lower()
elif operation == "Word Count":
return f"Word count: {len(text.split())}"
return text
with gr.Blocks(title="Text Processor", theme=gr.themes.Soft()) as demo:
gr.Markdown("# Text Processing Tool")
with gr.Row():
with gr.Column(scale=2):
text_input = gr.Textbox(label="Input Text", lines=5, placeholder="Enter text here...")
operation = gr.Radio(
choices=["Uppercase", "Lowercase", "Word Count"],
label="Operation",
value="Uppercase",
)
submit_btn = gr.Button("Process", variant="primary")
with gr.Column(scale=1):
output = gr.Textbox(label="Result", lines=5)
submit_btn.click(fn=process_text, inputs=[text_input, operation], outputs=output)
demo.launch()
ファイルのアップロードとダウンロード
# file_processing.py — ファイルのアップロードを処理し、ダウンロード可能な出力を提供する
import gradio as gr
import pandas as pd
def analyze_csv(file) -> tuple[str, str]:
df = pd.read_csv(file.name)
summary = f"Rows: {len(df)}, Columns: {len(df.columns)}\n\n"
summary += f"Columns: {', '.join(df.columns)}\n\n"
summary += df.describe().to_string()
output_path = "/tmp/summary.csv"
df.describe().to_csv(output_path)
return summary, output_path
demo = gr.Interface(
fn=analyze_csv,
inputs=gr.File(label="Upload CSV"),
outputs=[gr.Textbox(label="Summary"), gr.File(label="Download Summary")],
)
demo.launch()
認証と共有
# auth_and_share.py — 認証を追加し、パブリック共有リンクを作成する
import gradio as gr
def secret_fn(text):
return f"Secret processed: {text}"
demo = gr.Interface(fn=secret_fn, inputs="text", outputs="text")
# 認証とパブリックリンクを使用して起動
demo.launch(
auth=("admin", "password123"), # 簡単な認証
share=True, # パブリック URL を作成します (72 時間)
server_port=7860,
)
Hugging Face Spaces へのデプロイ
# Hugging Face に Space を作成する
pip install huggingface_hub
huggingface-cli repo create my-demo --type space --space-sdk gradio
# クローンしてプッシュ
git clone https://huggingface.co/spaces/username/my-demo
cd my-demo
# app.py と requirements.txt を追加してプッシュ
git add . && git commit -m "Initial demo" && git push
# requirements.txt — Hugging Face Spaces デプロイメントの依存関係
gradio==4.44.0
transformers
torch
API アクセス
# api_client.py — 任意の Gradio アプリを API として使用する
from gradio_client import Client
client = Client("username/my-demo") # またはローカル URL
result = client.predict(
"Hello world", # 入力テキスト
api_name="/predict",
)
print(result)
主要な概念
gr.Interface: 関数から UI へのシンプルなマッピング — 1 つの関数、入力、出力gr.Blocks: 複雑なマルチステップアプリケーション向けの柔軟なレイアウトシステムgr.ChatInterface: 履歴管理を備えた専用のチャットボット UI- 共有:
share=Trueは一時的なパブリック URL を作成します。永続的なホスティングのための Spaces - コンポーネント: 30 以上の組み込みコンポーネント — Image、Audio、Video、File、DataFrame、Plot など
- API: すべての Gradio アプリは、
/api/に REST API を自動的に取得します - キューイング: 同時ユーザーを処理するための組み込みのリクエストキューイング
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Gradio
Installation
# Install Gradio
pip install gradio
Quick Start — Simple Interface
# hello.py — Minimal Gradio app with a text interface
import gradio as gr
def greet(name: str, intensity: int) -> str:
return "Hello, " + name + "!" * intensity
demo = gr.Interface(
fn=greet,
inputs=["text", gr.Slider(1, 10, value=1, label="Excitement")],
outputs="text",
title="Greeting Generator",
description="Enter your name and excitement level.",
)
demo.launch() # Opens http://localhost:7860
Chat Interface
# chatbot.py — Build a chatbot UI with streaming responses
import gradio as gr
from openai import OpenAI
client = OpenAI()
def chat(message: str, history: list) -> str:
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for h in history:
messages.append({"role": "user", "content": h[0]})
if h[1]:
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": message})
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
stream=True,
)
partial = ""
for chunk in response:
if chunk.choices[0].delta.content:
partial += chunk.choices[0].delta.content
yield partial
demo = gr.ChatInterface(
fn=chat,
title="AI Chat",
description="Chat with GPT-4",
examples=["Tell me a joke", "Explain quantum computing"],
)
demo.launch()
Image Classification
# image_classifier.py — Image classification demo with a pre-trained model
import gradio as gr
from transformers import pipeline
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
def classify(image):
results = classifier(image)
return {r["label"]: r["score"] for r in results}
demo = gr.Interface(
fn=classify,
inputs=gr.Image(type="pil"),
outputs=gr.Label(num_top_classes=5),
title="Image Classifier",
examples=["cat.jpg", "dog.jpg"],
)
demo.launch()
Blocks API (Custom Layouts)
# blocks_app.py — Build complex layouts with the Blocks API
import gradio as gr
def process_text(text: str, operation: str) -> str:
if operation == "Uppercase":
return text.upper()
elif operation == "Lowercase":
return text.lower()
elif operation == "Word Count":
return f"Word count: {len(text.split())}"
return text
with gr.Blocks(title="Text Processor", theme=gr.themes.Soft()) as demo:
gr.Markdown("# Text Processing Tool")
with gr.Row():
with gr.Column(scale=2):
text_input = gr.Textbox(label="Input Text", lines=5, placeholder="Enter text here...")
operation = gr.Radio(
choices=["Uppercase", "Lowercase", "Word Count"],
label="Operation",
value="Uppercase",
)
submit_btn = gr.Button("Process", variant="primary")
with gr.Column(scale=1):
output = gr.Textbox(label="Result", lines=5)
submit_btn.click(fn=process_text, inputs=[text_input, operation], outputs=output)
demo.launch()
File Upload and Download
# file_processing.py — Handle file uploads and provide downloadable outputs
import gradio as gr
import pandas as pd
def analyze_csv(file) -> tuple[str, str]:
df = pd.read_csv(file.name)
summary = f"Rows: {len(df)}, Columns: {len(df.columns)}\n\n"
summary += f"Columns: {', '.join(df.columns)}\n\n"
summary += df.describe().to_string()
output_path = "/tmp/summary.csv"
df.describe().to_csv(output_path)
return summary, output_path
demo = gr.Interface(
fn=analyze_csv,
inputs=gr.File(label="Upload CSV"),
outputs=[gr.Textbox(label="Summary"), gr.File(label="Download Summary")],
)
demo.launch()
Authentication and Sharing
# auth_and_share.py — Add authentication and create a public share link
import gradio as gr
def secret_fn(text):
return f"Secret processed: {text}"
demo = gr.Interface(fn=secret_fn, inputs="text", outputs="text")
# Launch with auth and public link
demo.launch(
auth=("admin", "password123"), # Simple auth
share=True, # Creates a public URL (72h)
server_port=7860,
)
Deploy to Hugging Face Spaces
# Create a Space on Hugging Face
pip install huggingface_hub
huggingface-cli repo create my-demo --type space --space-sdk gradio
# Clone and push
git clone https://huggingface.co/spaces/username/my-demo
cd my-demo
# Add app.py and requirements.txt, then push
git add . && git commit -m "Initial demo" && git push
# requirements.txt — Dependencies for Hugging Face Spaces deployment
gradio==4.44.0
transformers
torch
API Access
# api_client.py — Use any Gradio app as an API
from gradio_client import Client
client = Client("username/my-demo") # Or local URL
result = client.predict(
"Hello world", # Input text
api_name="/predict",
)
print(result)
Key Concepts
gr.Interface: Simple function-to-UI mapping — one function, inputs, outputsgr.Blocks: Flexible layout system for complex multi-step applicationsgr.ChatInterface: Purpose-built chatbot UI with history management- Sharing:
share=Truecreates a temporary public URL; Spaces for permanent hosting - Components: 30+ built-in components — Image, Audio, Video, File, DataFrame, Plot, etc.
- API: Every Gradio app automatically gets a REST API at
/api/ - Queuing: Built-in request queuing for handling concurrent users