Penny0922 commited on
Commit
d836e0a
·
verified ·
1 Parent(s): 64a67e8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +165 -0
app.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import zipfile
4
+
5
+ import gradio as gr
6
+ import spaces
7
+ import torch
8
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
9
+
10
+
11
+ ZIP_PATH = "model.zip"
12
+ EXTRACT_DIR = "./model"
13
+ MODEL_DIR = os.path.join(EXTRACT_DIR, "final_model")
14
+
15
+
16
+ def prepare_model_files():
17
+ config_path = os.path.join(MODEL_DIR, "config.json")
18
+ weights_path = os.path.join(MODEL_DIR, "model.safetensors")
19
+
20
+ if os.path.isfile(config_path) and os.path.isfile(weights_path):
21
+ print("模型已經解壓完成。", flush=True)
22
+ return
23
+
24
+ if not os.path.isfile(ZIP_PATH):
25
+ raise FileNotFoundError("找不到 model.zip")
26
+
27
+ if os.path.exists(EXTRACT_DIR):
28
+ shutil.rmtree(EXTRACT_DIR)
29
+
30
+ os.makedirs(EXTRACT_DIR, exist_ok=True)
31
+
32
+ print("正在解壓模型……", flush=True)
33
+
34
+ with zipfile.ZipFile(ZIP_PATH, "r") as zip_ref:
35
+ zip_ref.extractall(EXTRACT_DIR)
36
+
37
+ print("模型解壓完成。", flush=True)
38
+
39
+ if not os.path.isfile(config_path):
40
+ raise FileNotFoundError(
41
+ f"找不到 {config_path},請確認 ZIP 裡面有 final_model 資料夾。"
42
+ )
43
+
44
+ if not os.path.isfile(weights_path):
45
+ raise FileNotFoundError(
46
+ f"找不到 {weights_path},請確認 model.safetensors 已包含在 ZIP 中。"
47
+ )
48
+
49
+
50
+ prepare_model_files()
51
+
52
+ print("正在載入 tokenizer……", flush=True)
53
+
54
+ tokenizer = AutoTokenizer.from_pretrained(
55
+ MODEL_DIR,
56
+ local_files_only=True
57
+ )
58
+
59
+ print("正在載入 BERT 模型到 CPU……", flush=True)
60
+
61
+ model = AutoModelForSequenceClassification.from_pretrained(
62
+ MODEL_DIR,
63
+ local_files_only=True
64
+ )
65
+
66
+ model.eval()
67
+
68
+ print("模型載入成功。", flush=True)
69
+
70
+
71
+ LABEL_MAP = {
72
+ 0: "詐騙訊息",
73
+ 1: "真實訊息"
74
+ }
75
+
76
+
77
+ @spaces.GPU(duration=60)
78
+ def predict(text: str) -> str:
79
+ text = text.strip()
80
+
81
+ if not text:
82
+ return "請先輸入要判斷的訊息。"
83
+
84
+ device = torch.device(
85
+ "cuda" if torch.cuda.is_available() else "cpu"
86
+ )
87
+
88
+ model.to(device)
89
+
90
+ inputs = tokenizer(
91
+ text,
92
+ return_tensors="pt",
93
+ truncation=True,
94
+ padding=True,
95
+ max_length=256
96
+ )
97
+
98
+ inputs = {
99
+ key: value.to(device)
100
+ for key, value in inputs.items()
101
+ }
102
+
103
+ with torch.inference_mode():
104
+ outputs = model(**inputs)
105
+ probabilities = torch.softmax(outputs.logits, dim=-1)[0]
106
+
107
+ probabilities = probabilities.detach().cpu()
108
+
109
+ pred_id = int(torch.argmax(probabilities).item())
110
+ confidence = float(probabilities[pred_id].item() * 100)
111
+
112
+ scam_probability = float(probabilities[0].item() * 100)
113
+ real_probability = float(probabilities[1].item() * 100)
114
+
115
+ pred_label = LABEL_MAP.get(
116
+ pred_id,
117
+ f"未知類別 {pred_id}"
118
+ )
119
+
120
+ if pred_id == 0:
121
+ advice = (
122
+ "請勿立即匯款、提供銀行帳號、密碼、信用卡資料或簡訊驗證碼。"
123
+ "建議透過官方管道查證,必要時撥打 165 反詐騙專線。"
124
+ )
125
+ else:
126
+ advice = (
127
+ "模型判斷較接近真實訊息,但模型仍可能誤判。"
128
+ "若內容涉及金錢、帳戶或個人資料,仍應再次查證。"
129
+ )
130
+
131
+ return (
132
+ f"🔍 判斷結果:{pred_label}\n\n"
133
+ f"📊 信心度:{confidence:.2f}%\n\n"
134
+ f"🚨 詐騙機率:{scam_probability:.2f}%\n"
135
+ f"✅ 真實機率:{real_probability:.2f}%\n\n"
136
+ f"⚠️ 提醒:{advice}"
137
+ )
138
+
139
+
140
+ demo = gr.Interface(
141
+ fn=predict,
142
+ inputs=gr.Textbox(
143
+ lines=6,
144
+ label="訊息內容",
145
+ placeholder="請輸入要判斷的新聞、貼文或可疑訊息……"
146
+ ),
147
+ outputs=gr.Textbox(
148
+ label="辨識結果",
149
+ lines=8
150
+ ),
151
+ title="LINE Bot BERT 詐騙/真實訊息辨識 API",
152
+ description=(
153
+ "輸入文字後,系統會判斷內容較接近詐騙訊息或真實訊息。"
154
+ ),
155
+ api_name="predict"
156
+ )
157
+
158
+
159
+ if __name__ == "__main__":
160
+ demo.launch(
161
+ server_name="0.0.0.0",
162
+ server_port=7860,
163
+ ssr_mode=False,
164
+ show_error=True
165
+ )