Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
# 初始化 OpenAI 客戶端,對接 Hugging Face Router
|
| 6 |
+
client = OpenAI(
|
| 7 |
+
base_url="https://router.huggingface.co/v1",
|
| 8 |
+
api_key=os.environ.get("HF_TOKEN"),
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
def analyze_image(image, prompt):
|
| 12 |
+
if image is None:
|
| 13 |
+
return "請先上傳一張圖片!"
|
| 14 |
+
|
| 15 |
+
# 若沒有輸入提示詞,給予預設值
|
| 16 |
+
if not prompt or prompt.strip() == "":
|
| 17 |
+
prompt = "Describe this image in one sentence."
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
# 呼叫模型(支援多模態輸入)
|
| 21 |
+
completion = client.chat.completions.create(
|
| 22 |
+
model="google/gemma-4-31B-it:novita",
|
| 23 |
+
messages=[
|
| 24 |
+
{
|
| 25 |
+
"role": "user",
|
| 26 |
+
"content": [
|
| 27 |
+
{"type": "text", "text": prompt},
|
| 28 |
+
{"type": "image_url", "image_url": {"url": image}}
|
| 29 |
+
]
|
| 30 |
+
}
|
| 31 |
+
],
|
| 32 |
+
max_tokens=300
|
| 33 |
+
)
|
| 34 |
+
return completion.choices[0].message.content
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return f"發生錯誤:{str(e)}"
|
| 37 |
+
|
| 38 |
+
# 建立 Gradio 網頁介面
|
| 39 |
+
demo = gr.Interface(
|
| 40 |
+
fn=analyze_image,
|
| 41 |
+
inputs=[
|
| 42 |
+
gr.Image(type="filepath", label="上傳圖片"),
|
| 43 |
+
gr.Textbox(label="輸入提示詞 (Prompt)", value="Describe this image in one sentence.")
|
| 44 |
+
],
|
| 45 |
+
outputs=gr.Textbox(label="模型回應"),
|
| 46 |
+
title="Gemma 多模態影像分析助手",
|
| 47 |
+
description="透過 Hugging Face Router 呼叫 gemma-4-31B-it 模型進行影像辨識與分析。"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
demo.launch()
|