Bennie12 commited on
Commit
40b9204
·
verified ·
1 Parent(s): 57f33d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -6
app.py CHANGED
@@ -1,12 +1,29 @@
1
  import gradio as gr
2
  from bert_explainer import analyze_text, analyze_image
3
  from fastapi import FastAPI
4
- # 🧠 預測函式:供 UI 和 API 共用
 
 
 
5
  api = FastAPI()
6
 
7
- @api.get("/test")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  def test_predict_text():
9
- # 測試文字直接寫死,不需輸入
10
  result = analyze_text("這是測試訊息", explain_mode="cnn")
11
  return {
12
  "status": result["status"],
@@ -14,6 +31,25 @@ def test_predict_text():
14
  "suspicious_keywords": result["suspicious_keywords"]
15
  }
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def predict_text(text, mode):
18
  result = analyze_text(text=text, explain_mode=mode)
19
  return result["status"], f"{result['confidence']}%", ", ".join(result["suspicious_keywords"])
@@ -23,7 +59,6 @@ def predict_image(file_path, mode):
23
  result = analyze_image(f.read(), explain_mode=mode)
24
  return result["status"], f"{result['confidence']}%", ", ".join(result["suspicious_keywords"])
25
 
26
- # 🧩 Gradio UI:兩個 Tab(文字 & 圖片)
27
  with gr.Blocks() as demo:
28
  with gr.Tab("文字模式"):
29
  text_input = gr.Textbox(lines=3, label="輸入文字")
@@ -43,6 +78,8 @@ with gr.Blocks() as demo:
43
  image_output3 = gr.Textbox(label="可疑詞彙")
44
  image_btn.click(fn=predict_image, inputs=[image_input, image_mode], outputs=[image_output1, image_output2, image_output3])
45
 
46
- # ✅ Gradio 支援 API 路由 + 互動功能
 
 
47
  if __name__ == "__main__":
48
- demo.queue().launch()
 
1
  import gradio as gr
2
  from bert_explainer import analyze_text, analyze_image
3
  from fastapi import FastAPI
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ import uvicorn
6
+
7
+ # ✅ 初始化 FastAPI
8
  api = FastAPI()
9
 
10
+ # ✅ 開放 CORS(避免跨網域錯誤)
11
+ api.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_credentials=True,
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
+
19
+ # ✅ API 路由:健康檢查
20
+ @api.get("/health")
21
+ def health_check():
22
+ return {"status": "ok"}
23
+
24
+ # ✅ API 路由:測試文字分析 GET 方法
25
+ @api.get("/run/predict_text")
26
  def test_predict_text():
 
27
  result = analyze_text("這是測試訊息", explain_mode="cnn")
28
  return {
29
  "status": result["status"],
 
31
  "suspicious_keywords": result["suspicious_keywords"]
32
  }
33
 
34
+ # ✅ API 路由:正式 POST 方法
35
+ @api.post("/run/predict_text")
36
+ def predict_text_api(payload: dict):
37
+ try:
38
+ text, mode = payload["data"]
39
+ result = analyze_text(text=text, explain_mode=mode)
40
+ return {
41
+ "data": [
42
+ result["status"],
43
+ f'{result["confidence"]}%',
44
+ ", ".join(result["suspicious_keywords"])
45
+ ]
46
+ }
47
+ except Exception as e:
48
+ return {"error": str(e)}
49
+
50
+ # ✅ API 路由:圖片分析(POST),這裡可延伸實作 predict_image 版本
51
+
52
+ # ✅ Gradio UI 功能
53
  def predict_text(text, mode):
54
  result = analyze_text(text=text, explain_mode=mode)
55
  return result["status"], f"{result['confidence']}%", ", ".join(result["suspicious_keywords"])
 
59
  result = analyze_image(f.read(), explain_mode=mode)
60
  return result["status"], f"{result['confidence']}%", ", ".join(result["suspicious_keywords"])
61
 
 
62
  with gr.Blocks() as demo:
63
  with gr.Tab("文字模式"):
64
  text_input = gr.Textbox(lines=3, label="輸入文字")
 
78
  image_output3 = gr.Textbox(label="可疑詞彙")
79
  image_btn.click(fn=predict_image, inputs=[image_input, image_mode], outputs=[image_output1, image_output2, image_output3])
80
 
81
+ # ✅ 啟用 Gradio + FastAPI 整合
82
+ app = gr.mount_gradio_app(api, demo)
83
+
84
  if __name__ == "__main__":
85
+ uvicorn.run(app, host="0.0.0.0", port=7860)