Hank20041016 commited on
Commit
b44998f
·
verified ·
1 Parent(s): 1318091

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -14
app.py CHANGED
@@ -4,12 +4,11 @@ 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
- # 修正:支援 JPG 檔案上傳
11
  def load_image_from_input(image_input):
12
- # URL 情況
13
  if isinstance(image_input, str) and (image_input.startswith("http://") or image_input.startswith("https://")):
14
  try:
15
  response = requests.get(image_input)
@@ -18,7 +17,7 @@ def load_image_from_input(image_input):
18
  except Exception as e:
19
  raise gr.Error(f"無法從 URL 下載圖片: {e}")
20
  else:
21
- # JPG 檔案上傳情況 - 這裡就是關鍵修正
22
  return Image.open(image_input)
23
 
24
  # 包裝成 API 函數
@@ -30,26 +29,25 @@ def predict(image_input, question):
30
  {
31
  "role": "user",
32
  "content": [
33
- {"type": "image", "image": image}, # 修正:改為 "image"
34
  {"type": "text", "text": question}
35
  ]
36
  },
37
  ]
38
- result = pipe(messages)
 
 
39
  return result[0]["generated_text"]
40
 
41
- # Gradio 介面
42
  iface = gr.Interface(
43
  fn=predict,
44
- inputs=[
45
- gr.Image(type="filepath", file_types=[".jpg", ".jpeg", ".png"]), # 修正:加上檔案類型限制
46
- "text"
47
- ],
48
  outputs="text",
49
  title="MedGemma API + Demo",
50
- description="上傳 JPG 圖片或輸入圖片 URL,以 API 或 UI 測試 MedGemma。"
51
  )
52
 
53
  # 啟動應用程式
54
- if __name__ == "__main__": # 修正:語法錯誤
55
  iface.launch()
 
4
  import requests
5
  from io import BytesIO
6
 
7
+ # 修正:使用正確的 pipeline 類型
8
+ pipe = pipeline("image-text-to-text", model="google/medgemma-4b-it")
9
 
10
+ # 檢查輸入是否為 URL,如果是,則下載並轉換為 PIL 圖片
11
  def load_image_from_input(image_input):
 
12
  if isinstance(image_input, str) and (image_input.startswith("http://") or image_input.startswith("https://")):
13
  try:
14
  response = requests.get(image_input)
 
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 函數
 
29
  {
30
  "role": "user",
31
  "content": [
32
+ {"type": "image", "image": image}, # 使用 "image" 而不是 "url"
33
  {"type": "text", "text": question}
34
  ]
35
  },
36
  ]
37
+
38
+ # 修正:使用 text 參數而不是直接傳遞 messages
39
+ result = pipe(text=messages)
40
  return result[0]["generated_text"]
41
 
42
+ # Gradio 介面(同時支援 UI 和 API)
43
  iface = gr.Interface(
44
  fn=predict,
45
+ inputs=[gr.Image(type="filepath"), "text"],
 
 
 
46
  outputs="text",
47
  title="MedGemma API + Demo",
48
+ description="上傳圖片或輸入圖片 URL,以 API 或 UI 測試 MedGemma。"
49
  )
50
 
51
  # 啟動應用程式
52
+ if __name__ == "__main__":
53
  iface.launch()