Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
+
from huggingface_hub import HfApi, create_repo
|
| 6 |
+
|
| 7 |
+
# モデルのONNXエクスポート関数
|
| 8 |
+
def convert_to_onnx_and_deploy(model_repo, input_text, hf_token, repo_name):
|
| 9 |
+
try:
|
| 10 |
+
# Hugging Faceトークンを設定
|
| 11 |
+
os.environ["HUGGINGFACE_HUB_TOKEN"] = hf_token
|
| 12 |
+
|
| 13 |
+
# モデルとトークナイザーの読み込み
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained(model_repo)
|
| 15 |
+
model = AutoModelForCausalLM.from_pretrained(model_repo)
|
| 16 |
+
|
| 17 |
+
# 入力テキストをトークナイズ
|
| 18 |
+
inputs = tokenizer(input_text, return_tensors="pt")
|
| 19 |
+
|
| 20 |
+
# ONNXファイルの保存
|
| 21 |
+
onnx_file = f"{repo_name}.onnx"
|
| 22 |
+
torch.onnx.export(
|
| 23 |
+
model,
|
| 24 |
+
inputs['input_ids'],
|
| 25 |
+
onnx_file,
|
| 26 |
+
input_names=['input_ids'],
|
| 27 |
+
output_names=['output'],
|
| 28 |
+
dynamic_axes={'input_ids': {0: 'batch_size'}, 'output': {0: 'batch_size'}}
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# モデルをHugging Face Hubにデプロイ
|
| 32 |
+
api = HfApi()
|
| 33 |
+
create_repo(repo_name, private=True) # プライベートリポジトリを作成
|
| 34 |
+
api.upload_file(onnx_file, repo_id=repo_name) # ONNXファイルをアップロード
|
| 35 |
+
|
| 36 |
+
return f"ONNXモデルが作成され、リポジトリにデプロイされました: {repo_name}"
|
| 37 |
+
except Exception as e:
|
| 38 |
+
return str(e)
|
| 39 |
+
|
| 40 |
+
# Gradioインターフェース
|
| 41 |
+
iface = gr.Interface(
|
| 42 |
+
fn=convert_to_onnx_and_deploy,
|
| 43 |
+
inputs=[
|
| 44 |
+
gr.Textbox(label="モデルリポジトリ(例: rinna/japanese-gpt2-medium)"),
|
| 45 |
+
gr.Textbox(label="入力テキスト"),
|
| 46 |
+
gr.Textbox(label="Hugging Faceトークン", type="password"), # パスワード入力タイプ
|
| 47 |
+
gr.Textbox(label="デプロイ先リポジトリ名") # デプロイ先のリポジトリ名
|
| 48 |
+
],
|
| 49 |
+
outputs="text",
|
| 50 |
+
title="ONNX変換とモデルデプロイ機能",
|
| 51 |
+
description="指定したHugging FaceのモデルリポジトリをONNX形式に変換し、デプロイします。"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# 使用するポート番号を指定してインターフェースを起動
|
| 55 |
+
iface.launch() # 7865ポートを指定
|