jackwang220 commited on
Commit
cfd26e3
·
verified ·
1 Parent(s): 5b5e0f7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -16
app.py CHANGED
@@ -3,7 +3,7 @@ from transformers import pipeline
3
  from PIL import Image
4
  import torch
5
 
6
- # --- 延後載入:先設為 None,第一次呼叫功能時才載入 ---
7
  _captioner = None
8
  _vqa = None
9
 
@@ -31,8 +31,7 @@ def get_vqa():
31
  def image_captioning(image: Image.Image):
32
  if image is None:
33
  return "請先上傳圖片"
34
- pipe = get_captioner()
35
- out = pipe(image)
36
  return out[0]["generated_text"]
37
 
38
  def visual_question_answer(image: Image.Image, question: str):
@@ -40,8 +39,8 @@ def visual_question_answer(image: Image.Image, question: str):
40
  return "請先上傳圖片"
41
  if not question:
42
  return "請輸入問題"
43
- pipe = get_vqa()
44
- out = pipe(image, question)
45
  return out[0]["answer"]
46
 
47
  # --- UI ---
@@ -64,27 +63,22 @@ with gr.Blocks(title="Vision Language AI 應用") as demo:
64
  text_output_vqa = gr.Textbox(label="AI 的回答")
65
  vqa_button = gr.Button("開始問答")
66
 
67
- # 綁定事件(在 .click 上加 concurrency_limit)
68
  caption_button.click(
69
  fn=image_captioning,
70
  inputs=[image_input_caption],
71
  outputs=[text_output_caption],
72
- concurrency_limit=1, # ← 移到事件層級
73
  )
74
-
75
  vqa_button.click(
76
  fn=visual_question_answer,
77
  inputs=[image_input_vqa, question_input_vqa],
78
  outputs=[text_output_vqa],
79
- concurrency_limit=1, # ← 同上
80
  )
81
 
82
- # 佇列設定:不要再傳 concurrency_count
83
- demo.queue(max_size=10) # 或乾脆 demo.queue() 也可以
84
 
85
- # ★ 在 Spaces 讓後端自動啟動;本地端才需要 launch()
86
- # demo.queue(concurrency_count=1, max_size=10) 放在全域即可
87
- demo.queue(concurrency_count=1, max_size=10)
88
-
89
- if __name__ == "__main__": # 只在本地 run 時才啟動
90
  demo.launch()
 
3
  from PIL import Image
4
  import torch
5
 
6
+ # --- 延後載入 ---
7
  _captioner = None
8
  _vqa = None
9
 
 
31
  def image_captioning(image: Image.Image):
32
  if image is None:
33
  return "請先上傳圖片"
34
+ out = get_captioner()(image)
 
35
  return out[0]["generated_text"]
36
 
37
  def visual_question_answer(image: Image.Image, question: str):
 
39
  return "請先上傳圖片"
40
  if not question:
41
  return "請輸入問題"
42
+ # 部分 transformers 版本要用 dict 參數;若遇到錯誤可改成 get_vqa()({"image": image, "question": question})
43
+ out = get_vqa()(image, question)
44
  return out[0]["answer"]
45
 
46
  # --- UI ---
 
63
  text_output_vqa = gr.Textbox(label="AI 的回答")
64
  vqa_button = gr.Button("開始問答")
65
 
66
+ # 綁定事件:把併發限制放在事件層
67
  caption_button.click(
68
  fn=image_captioning,
69
  inputs=[image_input_caption],
70
  outputs=[text_output_caption],
71
+ concurrency_limit=1,
72
  )
 
73
  vqa_button.click(
74
  fn=visual_question_answer,
75
  inputs=[image_input_vqa, question_input_vqa],
76
  outputs=[text_output_vqa],
77
+ concurrency_limit=1,
78
  )
79
 
80
+ # 佇列(可留可拿掉;不要再用 concurrency_count)
81
+ demo.queue(max_size=10)
82
 
83
+ if __name__ == "__main__":
 
 
 
 
84
  demo.launch()