baseballtoma commited on
Commit
f9c6321
·
verified ·
1 Parent(s): 532dd93

Add Gradio app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # app.py として保存することを想定したコードです
3
+ import gradio as gr
4
+ from PIL import Image as PILImage
5
+ import torch
6
+ from transformers import ViltProcessor, ViltForQuestionAnswering
7
+
8
+ # Hugging Face Hubからファインチューニング済みのモデルとプロセッサーを読み込みます
9
+ # ここでは、先ほどアップロードしたリポジトリIDを指定します
10
+ # TODO: Replace with your actual model repository ID if different from the Space ID
11
+ model_id = "baseballtoma/my-vilt-image-text-classifier-cloud"
12
+
13
+ # 推論に使用するid_to_labelマッピングをここで定義します
14
+ # これはファインチューニング時に使用したマッピングと一致している必要があります
15
+ # 実際のアプリケーションでは、このマッピングをファイルとして保存し、読み込むのがより堅牢です
16
+ # 例: id_to_label = {0: '巻積雲', 1: '積乱雲', 2: '高層雲'}
17
+ # ファインチューニング時に使用したid_to_labelを正確に反映させてください
18
+ app_id_to_label = {0: '巻積雲', 1: '積乱雲', 2: '高層雲'} # <<< Replace with your actual labels and their sorted order mapping
19
+
20
+
21
+ processor = ViltProcessor.from_pretrained(model_id)
22
+ model = ViltForQuestionAnswering.from_pretrained(model_id)
23
+
24
+
25
+ # 推論を実行する関数を定義します
26
+ def predict(image, text):
27
+ if image is None:
28
+ return "画像をアップロードしてください。"
29
+ if not text:
30
+ return "テキストを入力してください。"
31
+
32
+ # PIL ImageをRGBに変換
33
+ image = image.convert("RGB")
34
+
35
+ # 画像とテキストをモデルの入力形式に変換
36
+ encoding = processor(images=image, text=text, return_tensors="pt", padding=True, truncation=True)
37
+
38
+ # 推論を実行 (CPUで実行されることを想定)
39
+ model.eval()
40
+ with torch.no_grad():
41
+ outputs = model(**encoding)
42
+
43
+ # ロジットから最も確率の高いラベルを取得
44
+ logits = outputs.logits
45
+ predicted_class_id = logits.argmax(-1).item()
46
+
47
+ # 予測されたクラスIDを元のテキストラベルに変換します
48
+ if predicted_class_id in app_id_to_label:
49
+ predicted_text = app_id_to_label[predicted_class_id]
50
+ else:
51
+ predicted_text = f"未知のクラスID: {predicted_class_id}"
52
+
53
+
54
+ return predicted_text
55
+
56
+ # Gradioインターフェースを作成します
57
+ iface = gr.Interface(
58
+ fn=predict, # 推論関数
59
+ inputs=[gr.Image(type="pil"), gr.Textbox(label="テキスト(質問)を入力")], # 入力コンポーネント (画像アップロードとテキスト入力)
60
+ outputs="text", # 出力コンポーネント (テキスト)
61
+ title="画像とテキストの分類デモ", # デモのタイトル
62
+ description="画像をアップロードし、テキストを入力して、モデルの予測結果を確認します。" # デモの説明
63
+ )
64
+
65
+ # インターフェースを起動します
66
+ # Hugging Face Spacesでは、このスクリプトが実行されると自動的に起動されます
67
+ # ローカルでテストする場合は、launch()の引数にshare=Trueなどを指定できます
68
+ # iface.launch()