Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,52 @@
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
# 建立 pipeline
|
| 5 |
-
pipe = pipeline("image-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# 包裝成 API 函數
|
| 8 |
-
def predict(
|
|
|
|
|
|
|
|
|
|
| 9 |
messages = [
|
| 10 |
{
|
| 11 |
"role": "user",
|
| 12 |
"content": [
|
| 13 |
-
{"type": "image", "
|
| 14 |
{"type": "text", "text": question}
|
| 15 |
]
|
| 16 |
},
|
| 17 |
]
|
| 18 |
-
|
|
|
|
| 19 |
return result[0]["generated_text"]
|
| 20 |
|
| 21 |
# Gradio 介面(同時支援 UI 和 API)
|
| 22 |
iface = gr.Interface(
|
| 23 |
fn=predict,
|
| 24 |
-
inputs=["
|
| 25 |
outputs="text",
|
| 26 |
title="MedGemma API + Demo",
|
| 27 |
-
description="
|
| 28 |
)
|
| 29 |
|
|
|
|
| 30 |
if __name__ == "__main__":
|
| 31 |
-
iface.launch()
|
|
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import gradio as gr
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import requests
|
| 5 |
+
from io import BytesIO
|
| 6 |
|
| 7 |
# 建立 pipeline
|
| 8 |
+
pipe = pipeline("image-to-text", model="google/medgemma-4b-it")
|
| 9 |
+
|
| 10 |
+
# 檢查輸入是否為 URL,如果是,則下載並轉換為 PIL 圖片
|
| 11 |
+
def load_image_from_input(image_input):
|
| 12 |
+
if image_input.startswith("http://") or image_input.startswith("https://"):
|
| 13 |
+
try:
|
| 14 |
+
response = requests.get(image_input)
|
| 15 |
+
img = Image.open(BytesIO(response.content))
|
| 16 |
+
return img
|
| 17 |
+
except Exception as e:
|
| 18 |
+
raise gr.Error(f"無法從 URL 下載圖片: {e}")
|
| 19 |
+
else:
|
| 20 |
+
# 如果不是 URL,就假設是檔案路徑,由 Gradio 自動處理
|
| 21 |
+
return Image.open(image_input)
|
| 22 |
|
| 23 |
# 包裝成 API 函數
|
| 24 |
+
def predict(image_input, question):
|
| 25 |
+
image = load_image_from_input(image_input)
|
| 26 |
+
|
| 27 |
+
# 將輸入轉換為模型所需的 messages 格式
|
| 28 |
messages = [
|
| 29 |
{
|
| 30 |
"role": "user",
|
| 31 |
"content": [
|
| 32 |
+
{"type": "image", "content": image},
|
| 33 |
{"type": "text", "text": question}
|
| 34 |
]
|
| 35 |
},
|
| 36 |
]
|
| 37 |
+
|
| 38 |
+
result = pipe(messages)
|
| 39 |
return result[0]["generated_text"]
|
| 40 |
|
| 41 |
# Gradio 介面(同時支援 UI 和 API)
|
| 42 |
iface = gr.Interface(
|
| 43 |
fn=predict,
|
| 44 |
+
inputs=[gr.Image(type="filepath"), "text"],
|
| 45 |
outputs="text",
|
| 46 |
title="MedGemma API + Demo",
|
| 47 |
+
description="上傳圖片或輸入圖片 URL,以 API 或 UI 測試 MedGemma。"
|
| 48 |
)
|
| 49 |
|
| 50 |
+
# 啟動應用程式
|
| 51 |
if __name__ == "__main__":
|
| 52 |
+
iface.launch()
|