jackwang220 commited on
Commit
42fbaaa
·
verified ·
1 Parent(s): c75cdd3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -8
app.py CHANGED
@@ -1,14 +1,70 @@
 
 
 
1
  import gradio as gr
 
 
2
 
3
- def ping(txt):
4
- return "OK: " + (txt or "")
 
 
5
 
6
- with gr.Blocks(title="Sanity Check") as demo:
7
- gr.Markdown("# ✅ Build sanity check")
8
- inp = gr.Textbox(label="Input")
9
- out = gr.Textbox(label="Output")
10
- btn = gr.Button("Run")
11
- btn.click(ping, inputs=inp, outputs=out, concurrency_limit=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  demo.queue(max_size=10)
14
 
 
1
+ # app.py — CPU/免費空間穩定版(Caption only)
2
+ import os
3
+ import gc
4
  import gradio as gr
5
+ from PIL import Image
6
+ from transformers import pipeline
7
 
8
+ # 降低雜訊與多執行緒開銷
9
+ os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
10
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
11
+ os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
12
 
13
+ # 嘗試偵測 torch(若沒裝也能跑,僅用 CPU)
14
+ try:
15
+ import torch # type: ignore
16
+ _HAS_TORCH = True
17
+ except Exception:
18
+ torch = None # type: ignore
19
+ _HAS_TORCH = False
20
+
21
+ # 懶載入:第一次呼叫才建立管線
22
+ _captioner = None
23
+
24
+ def get_device_id():
25
+ if _HAS_TORCH:
26
+ try:
27
+ return 0 if torch.cuda.is_available() else -1
28
+ except Exception:
29
+ return -1
30
+ return -1
31
+
32
+ def get_captioner():
33
+ global _captioner
34
+ if _captioner is None:
35
+ _captioner = pipeline(
36
+ task="image-to-text",
37
+ model="Salesforce/blip-image-captioning-base",
38
+ device=get_device_id(),
39
+ )
40
+ return _captioner
41
+
42
+ def do_caption(image: Image.Image):
43
+ if image is None:
44
+ return "請先上傳圖片。"
45
+ pipe = get_captioner()
46
+ out = pipe(image)
47
+ # 釋放一些暫存(避免長時間使用記憶體升高)
48
+ gc.collect()
49
+ return out[0]["generated_text"]
50
+
51
+ def clear_all():
52
+ return None, ""
53
+
54
+ # ===== UI =====
55
+ with gr.Blocks(title="Vision Language AI 應用(Caption 版)") as demo:
56
+ gr.Markdown("# 🎨 Vision Language AI 應用展示 · Caption")
57
+ gr.Markdown("上傳圖片後按下按鈕,產生文字描述。此版本僅啟用 **Image Captioning**,以確保在免費 CPU 環境穩定執行。")
58
+
59
+ with gr.Row():
60
+ img = gr.Image(type="pil", label="上傳圖片", height=320)
61
+ out = gr.Textbox(label="AI 產生的描述", lines=6, show_copy_button=True)
62
+ with gr.Row():
63
+ run_btn = gr.Button("🚀 產生描述", variant="primary")
64
+ clear_btn = gr.Button("🧹 清除", variant="secondary")
65
+
66
+ run_btn.click(fn=do_caption, inputs=img, outputs=out, concurrency_limit=1)
67
+ clear_btn.click(fn=clear_all, inputs=None, outputs=[img, out], concurrency_limit=1)
68
 
69
  demo.queue(max_size=10)
70