Penny0922 commited on
Commit
e8149a3
·
verified ·
1 Parent(s): 0f3c5ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -1017
app.py CHANGED
@@ -1,83 +1,41 @@
1
  import os
2
- import math
3
  import shutil
4
- import unicodedata
5
  import zipfile
6
 
7
  import gradio as gr
8
  import torch
9
 
10
- from captum.attr import LayerIntegratedGradients
11
  from transformers import (
12
  AutoModelForSequenceClassification,
13
  AutoTokenizer,
14
  )
15
 
16
 
17
- # =========================================================
18
- # 基本設定
19
- # =========================================================
20
-
21
  ZIP_PATH = "model.zip"
22
-
23
  EXTRACT_DIR = "./model"
24
-
25
  MODEL_DIR = os.path.join(
26
  EXTRACT_DIR,
27
- "final_model",
28
  )
29
 
30
  DEVICE = torch.device("cpu")
31
 
32
- MAX_LENGTH = 256
33
-
34
- LABEL_MAP = {
35
- 0: "詐騙訊息",
36
- 1: "真實訊息",
37
- }
38
-
39
-
40
- # Integrated Gradients 積分步數
41
- # CPU Space 不宜太高
42
- IG_STEPS = 24
43
-
44
-
45
- # 最多顯示幾個重要片段
46
- MAX_EXPLANATION_SPANS = 4
47
 
 
 
 
48
 
49
- # 一個片段至少幾個 Token
50
- MIN_SPAN_TOKENS = 2
51
-
52
-
53
- # 一個片段最多幾個 Token
54
- MAX_SPAN_TOKENS = 8
55
-
56
-
57
- # =========================================================
58
- # 解壓縮模型
59
- # =========================================================
60
-
61
- def prepare_model_files():
62
 
63
  config_path = os.path.join(
64
  MODEL_DIR,
65
- "config.json",
66
  )
67
 
68
- weights_path = os.path.join(
69
- MODEL_DIR,
70
- "model.safetensors",
71
- )
72
-
73
- # 已解壓就不用重做
74
- if (
75
- os.path.isfile(config_path)
76
- and os.path.isfile(weights_path)
77
- ):
78
  print(
79
- "模型已經解壓完成。",
80
- flush=True,
81
  )
82
  return
83
 
@@ -93,17 +51,17 @@ def prepare_model_files():
93
 
94
  os.makedirs(
95
  EXTRACT_DIR,
96
- exist_ok=True,
97
  )
98
 
99
  print(
100
- "正在解壓模型……",
101
- flush=True,
102
  )
103
 
104
  with zipfile.ZipFile(
105
  ZIP_PATH,
106
- "r",
107
  ) as zip_ref:
108
 
109
  zip_ref.extractall(
@@ -111,1059 +69,159 @@ def prepare_model_files():
111
  )
112
 
113
  print(
114
- "模型解壓完成。",
115
- flush=True,
116
  )
117
 
118
- if not os.path.isfile(config_path):
119
- raise FileNotFoundError(
120
- f"找不到 {config_path},"
121
- "請確認 ZIP 裡面有 final_model 資料夾。"
122
- )
123
-
124
- if not os.path.isfile(weights_path):
125
- raise FileNotFoundError(
126
- f"找不到 {weights_path},"
127
- "請確認 ZIP 中包含 model.safetensors。"
128
- )
129
-
130
 
131
- # =========================================================
132
- # 準備模型
133
- # =========================================================
134
 
135
- prepare_model_files()
136
 
 
 
 
137
 
138
  print(
139
- "正在載入 tokenizer……",
140
- flush=True,
141
  )
142
 
143
  tokenizer = AutoTokenizer.from_pretrained(
144
  MODEL_DIR,
145
- local_files_only=True,
146
- use_fast=True,
147
  )
148
 
149
 
150
- # offset_mapping 需要 Fast Tokenizer
151
- if not tokenizer.is_fast:
152
- raise RuntimeError(
153
- "目前 Tokenizer 不是 Fast Tokenizer,"
154
- "無法使用 offset_mapping 產生連續文字片段。"
155
- )
156
-
157
-
158
  print(
159
- "正在載入 BERT 模型到 CPU……",
160
- flush=True,
161
  )
162
 
163
  model = (
164
  AutoModelForSequenceClassification
165
  .from_pretrained(
166
  MODEL_DIR,
167
- local_files_only=True,
168
  )
169
  )
170
 
171
- model.to(
172
- DEVICE
173
- )
174
-
175
  model.eval()
176
 
177
 
178
  print(
179
- "模型載入成功。",
180
- flush=True,
181
- )
182
-
183
-
184
- # =========================================================
185
- # Integrated Gradients
186
- # =========================================================
187
-
188
- embedding_layer = (
189
- model.get_input_embeddings()
190
  )
191
 
192
 
193
- def forward_func(
194
- input_ids,
195
- attention_mask,
196
- token_type_ids=None,
197
- ):
198
-
199
- model_inputs = {
200
- "input_ids":
201
- input_ids,
202
-
203
- "attention_mask":
204
- attention_mask,
205
- }
206
-
207
- if token_type_ids is not None:
208
- model_inputs[
209
- "token_type_ids"
210
- ] = token_type_ids
211
-
212
- outputs = model(
213
- **model_inputs
214
- )
215
-
216
- return outputs.logits
217
-
218
-
219
- lig = LayerIntegratedGradients(
220
- forward_func,
221
- embedding_layer,
222
- )
223
-
224
-
225
- print(
226
- "Integrated Gradients 初始化完成。",
227
- flush=True,
228
- )
229
-
230
-
231
- # =========================================================
232
- # Baseline
233
- # =========================================================
234
-
235
- def create_baseline(
236
- input_ids,
237
- ):
238
-
239
- pad_token_id = (
240
- tokenizer.pad_token_id
241
- )
242
-
243
- if pad_token_id is None:
244
- pad_token_id = 0
245
-
246
- baseline = torch.full_like(
247
- input_ids,
248
- pad_token_id,
249
- )
250
-
251
- # CLS / SEP 保留
252
- if tokenizer.cls_token_id is not None:
253
-
254
- baseline[
255
- input_ids
256
- == tokenizer.cls_token_id
257
- ] = tokenizer.cls_token_id
258
-
259
- if tokenizer.sep_token_id is not None:
260
-
261
- baseline[
262
- input_ids
263
- == tokenizer.sep_token_id
264
- ] = tokenizer.sep_token_id
265
-
266
- return baseline
267
-
268
-
269
- # =========================================================
270
- # 文字工具
271
- # =========================================================
272
-
273
- def is_punctuation_only(
274
- text,
275
- ):
276
- """
277
- 判斷是否全部都是標點/空白。
278
- 這不是詐騙規則,只是 UI 清理。
279
- """
280
-
281
- if not text:
282
- return True
283
-
284
- for char in text:
285
-
286
- if char.isspace():
287
- continue
288
-
289
- category = (
290
- unicodedata.category(
291
- char
292
- )
293
- )
294
-
295
- if not category.startswith("P"):
296
- return False
297
-
298
- return True
299
-
300
-
301
- def clean_display_text(
302
- text,
303
- ):
304
- """
305
- 清除片段左右空白。
306
- """
307
-
308
- return text.strip()
309
-
310
-
311
- # =========================================================
312
- # Token Attribution
313
- # =========================================================
314
-
315
- def calculate_token_attributions(
316
- model_inputs,
317
- offsets,
318
- original_text,
319
- predicted_class,
320
- ):
321
-
322
- input_ids = (
323
- model_inputs[
324
- "input_ids"
325
- ]
326
- )
327
-
328
- attention_mask = (
329
- model_inputs[
330
- "attention_mask"
331
- ]
332
- )
333
-
334
- token_type_ids = (
335
- model_inputs.get(
336
- "token_type_ids"
337
- )
338
- )
339
-
340
- baseline_ids = (
341
- create_baseline(
342
- input_ids
343
- )
344
- )
345
-
346
-
347
- # -----------------------------------------------------
348
- # Integrated Gradients
349
- # -----------------------------------------------------
350
-
351
- if token_type_ids is not None:
352
-
353
- attributions, delta = (
354
- lig.attribute(
355
- inputs=input_ids,
356
- baselines=baseline_ids,
357
- additional_forward_args=(
358
- attention_mask,
359
- token_type_ids,
360
- ),
361
- target=predicted_class,
362
- n_steps=IG_STEPS,
363
- return_convergence_delta=True,
364
- )
365
- )
366
-
367
- else:
368
-
369
- attributions, delta = (
370
- lig.attribute(
371
- inputs=input_ids,
372
- baselines=baseline_ids,
373
- additional_forward_args=(
374
- attention_mask,
375
- None,
376
- ),
377
- target=predicted_class,
378
- n_steps=IG_STEPS,
379
- return_convergence_delta=True,
380
- )
381
- )
382
-
383
-
384
- # Embedding dimension → 每 Token 一個分數
385
- token_scores = (
386
- attributions
387
- .sum(dim=-1)
388
- .squeeze(0)
389
- .detach()
390
- .cpu()
391
- )
392
-
393
-
394
- input_ids_cpu = (
395
- input_ids[0]
396
- .detach()
397
- .cpu()
398
- .tolist()
399
- )
400
-
401
- attention_cpu = (
402
- attention_mask[0]
403
- .detach()
404
- .cpu()
405
- .tolist()
406
- )
407
-
408
- tokens = (
409
- tokenizer
410
- .convert_ids_to_tokens(
411
- input_ids_cpu
412
- )
413
- )
414
-
415
-
416
- special_tokens = set(
417
- tokenizer.all_special_tokens
418
- )
419
-
420
-
421
- token_items = []
422
-
423
-
424
- for (
425
- token,
426
- score,
427
- mask,
428
- offset,
429
- ) in zip(
430
- tokens,
431
- token_scores.tolist(),
432
- attention_cpu,
433
- offsets,
434
- ):
435
-
436
- # Padding
437
- if mask == 0:
438
- continue
439
-
440
- # CLS / SEP 等
441
- if token in special_tokens:
442
- continue
443
-
444
- start = int(
445
- offset[0]
446
- )
447
-
448
- end = int(
449
- offset[1]
450
- )
451
-
452
- # Special token 的 offset 常為 (0, 0)
453
- if end <= start:
454
- continue
455
-
456
- piece = (
457
- original_text[
458
- start:end
459
- ]
460
- )
461
-
462
- if not piece:
463
- continue
464
-
465
- token_items.append(
466
- {
467
- "token":
468
- token,
469
-
470
- "text":
471
- piece,
472
-
473
- "start":
474
- start,
475
-
476
- "end":
477
- end,
478
-
479
- "score":
480
- float(score),
481
- }
482
- )
483
-
484
-
485
- convergence_delta = float(
486
- delta
487
- .detach()
488
- .cpu()
489
- .reshape(-1)[0]
490
- .item()
491
- )
492
-
493
-
494
- return (
495
- token_items,
496
- convergence_delta,
497
- )
498
-
499
-
500
- # =========================================================
501
- # Token → 連續片段
502
- # =========================================================
503
-
504
- def build_candidate_spans(
505
- token_items,
506
- original_text,
507
- ):
508
- """
509
- 不使用人工關鍵字。
510
-
511
- 使用 sliding window 對相鄰 Token attribution
512
- 進行聚合��找出模型真正高貢獻的連續文字區域。
513
- """
514
-
515
- candidates = []
516
-
517
- total_tokens = len(
518
- token_items
519
- )
520
-
521
-
522
- for start_index in range(
523
- total_tokens
524
- ):
525
-
526
- for span_length in range(
527
- MIN_SPAN_TOKENS,
528
- MAX_SPAN_TOKENS + 1,
529
- ):
530
-
531
- end_index = (
532
- start_index
533
- + span_length
534
- )
535
-
536
- if end_index > total_tokens:
537
- break
538
-
539
-
540
- group = token_items[
541
- start_index:end_index
542
- ]
543
-
544
-
545
- # ---------------------------------------------
546
- # 必須是原文中相鄰的文字
547
- # ---------------------------------------------
548
-
549
- contiguous = True
550
-
551
- for i in range(
552
- len(group) - 1
553
- ):
554
-
555
- current_end = (
556
- group[i]["end"]
557
- )
558
-
559
- next_start = (
560
- group[i + 1]["start"]
561
- )
562
-
563
- gap_text = (
564
- original_text[
565
- current_end:
566
- next_start
567
- ]
568
- )
569
-
570
- # 如果中間有太長的空隙,
571
- # 就不要硬合成同一句
572
- if len(
573
- gap_text.strip()
574
- ) > 1:
575
- contiguous = False
576
- break
577
-
578
-
579
- if not contiguous:
580
- continue
581
-
582
-
583
- char_start = (
584
- group[0]["start"]
585
- )
586
-
587
- char_end = (
588
- group[-1]["end"]
589
- )
590
-
591
- phrase = clean_display_text(
592
- original_text[
593
- char_start:
594
- char_end
595
- ]
596
- )
597
-
598
-
599
- if not phrase:
600
- continue
601
-
602
-
603
- # 不讓純標點成為使用者解釋
604
- if is_punctuation_only(
605
- phrase
606
- ):
607
- continue
608
-
609
-
610
- positive_scores = [
611
- max(
612
- item["score"],
613
- 0.0,
614
- )
615
- for item in group
616
- ]
617
-
618
-
619
- positive_sum = sum(
620
- positive_scores
621
- )
622
-
623
-
624
- if positive_sum <= 0:
625
- continue
626
-
627
-
628
- # ---------------------------------------------
629
- # 避免單純「越長越高」
630
- #
631
- # score =
632
- # 正向 attribution 總和 / sqrt(token 數)
633
- # ---------------------------------------------
634
-
635
- ranking_score = (
636
- positive_sum
637
- / math.sqrt(
638
- span_length
639
- )
640
- )
641
-
642
-
643
- positive_token_count = sum(
644
- 1
645
- for value
646
- in positive_scores
647
- if value > 0
648
- )
649
-
650
-
651
- # 片段至少需要有一半 Token
652
- # 真正支持目前類別
653
- if (
654
- positive_token_count
655
- / span_length
656
- < 0.5
657
- ):
658
- continue
659
-
660
-
661
- candidates.append(
662
- {
663
- "text":
664
- phrase,
665
-
666
- "start":
667
- char_start,
668
-
669
- "end":
670
- char_end,
671
-
672
- "raw_score":
673
- positive_sum,
674
-
675
- "ranking_score":
676
- ranking_score,
677
-
678
- "token_count":
679
- span_length,
680
- }
681
- )
682
-
683
-
684
- candidates.sort(
685
- key=lambda item:
686
- item["ranking_score"],
687
- reverse=True,
688
- )
689
-
690
-
691
- return candidates
692
-
693
-
694
- # =========================================================
695
- # 選擇不重複片段
696
- # =========================================================
697
-
698
- def spans_overlap(
699
- first,
700
- second,
701
- ):
702
-
703
- return not (
704
- first["end"]
705
- <= second["start"]
706
- or
707
- second["end"]
708
- <= first["start"]
709
- )
710
-
711
-
712
- def select_top_spans(
713
- candidates,
714
- max_spans=MAX_EXPLANATION_SPANS,
715
- ):
716
-
717
- selected = []
718
-
719
-
720
- for candidate in candidates:
721
-
722
- # 避免同一段文字重複顯示
723
- if any(
724
- spans_overlap(
725
- candidate,
726
- existing,
727
- )
728
- for existing in selected
729
- ):
730
- continue
731
-
732
-
733
- # 太短的單字片段不要顯示
734
- visible_length = len(
735
- candidate["text"]
736
- .replace(
737
- " ",
738
- "",
739
- )
740
- )
741
-
742
- if visible_length < 2:
743
- continue
744
-
745
-
746
- selected.append(
747
- candidate
748
- )
749
-
750
-
751
- if len(selected) >= max_spans:
752
- break
753
-
754
-
755
- # 最後按照原文順序
756
- # 不按重要度順序也可以,
757
- # 但 LINE 顯示仍希望重要度排序,
758
- # 所以這裡維持 ranking score。
759
- selected.sort(
760
- key=lambda item:
761
- item["ranking_score"],
762
- reverse=True,
763
- )
764
-
765
-
766
- return selected
767
-
768
-
769
- # =========================================================
770
- # 建立可解釋片段
771
- # =========================================================
772
-
773
- def explain_prediction(
774
- model_inputs,
775
- offsets,
776
- original_text,
777
- predicted_class,
778
- ):
779
-
780
- token_items, delta = (
781
- calculate_token_attributions(
782
- model_inputs=model_inputs,
783
- offsets=offsets,
784
- original_text=original_text,
785
- predicted_class=predicted_class,
786
- )
787
- )
788
-
789
-
790
- candidates = (
791
- build_candidate_spans(
792
- token_items,
793
- original_text,
794
- )
795
- )
796
-
797
-
798
- top_spans = (
799
- select_top_spans(
800
- candidates
801
- )
802
- )
803
-
804
-
805
- return (
806
- top_spans,
807
- token_items,
808
- delta,
809
- )
810
-
811
-
812
- # =========================================================
813
- # 使用者解釋文字
814
- # =========================================================
815
-
816
- def format_span_explanation(
817
- spans,
818
- predicted_class,
819
- ):
820
-
821
- class_name = (
822
- "詐騙"
823
- if predicted_class == 0
824
- else "真實"
825
- )
826
-
827
-
828
- if not spans:
829
-
830
- return (
831
- "目前未找到足夠穩定的連續高貢獻文字片段。\n"
832
- "模型仍是根據整段文字語意進行判斷。"
833
- )
834
-
835
-
836
- total_score = sum(
837
- item["raw_score"]
838
- for item in spans
839
- )
840
-
841
-
842
- lines = [
843
- (
844
- f"以下文字片段對本次"
845
- f"「{class_name}」判斷"
846
- "影響較大:"
847
- )
848
- ]
849
-
850
-
851
- for index, item in enumerate(
852
- spans,
853
- 1,
854
- ):
855
-
856
- if total_score > 0:
857
-
858
- relative = (
859
- item["raw_score"]
860
- / total_score
861
- * 100
862
- )
863
-
864
- else:
865
-
866
- relative = 0.0
867
-
868
-
869
- lines.append(
870
- (
871
- f"\n{index}. "
872
- f"「{item['text']}」\n"
873
- f" → 提高模型判斷為"
874
- f"「{class_name}」的傾向\n"
875
- f" 相對貢獻:"
876
- f"{relative:.1f}%"
877
- )
878
- )
879
-
880
-
881
- lines.append(
882
- (
883
- "\n📌 上述文字片段由 "
884
- "Integrated Gradients "
885
- "計算 Token attribution 後,"
886
- "依原文位置聚合相鄰 Token 產生,"
887
- "不是人工設定的詐騙關鍵字。"
888
- )
889
- )
890
-
891
-
892
- return "\n".join(
893
- lines
894
- )
895
-
896
 
897
- # =========================================================
898
- # Prediction
899
- # =========================================================
900
 
901
- def predict(
902
- text: str,
903
- ) -> str:
904
 
905
- text = text.strip()
906
 
 
907
 
908
  if not text:
 
909
 
910
- return (
911
- "請先輸入要判斷的訊息。"
912
- )
913
-
914
-
915
- # =====================================================
916
- # Tokenize
917
- #
918
- # offsets 只用來做可解釋性,
919
- # 不送進 BERT。
920
- # =====================================================
921
-
922
- encoded = tokenizer(
923
  text,
924
  return_tensors="pt",
925
  truncation=True,
926
- padding=True,
927
- max_length=MAX_LENGTH,
928
- return_offsets_mapping=True,
929
  )
930
 
931
-
932
- offsets = (
933
- encoded.pop(
934
- "offset_mapping"
935
- )[0]
936
- .tolist()
937
- )
938
-
939
-
940
- model_inputs = {
941
  key: value.to(DEVICE)
942
  for key, value
943
- in encoded.items()
944
  }
945
 
946
-
947
- # =====================================================
948
- # 一般 BERT 推論
949
- # =====================================================
950
-
951
  with torch.inference_mode():
952
 
953
  outputs = model(
954
- **model_inputs
955
- )
956
-
957
- probabilities = (
958
- torch.softmax(
959
- outputs.logits,
960
- dim=-1,
961
- )[0]
962
  )
963
 
 
 
 
 
964
 
965
- probabilities = (
966
- probabilities
967
- .detach()
968
- .cpu()
969
  )
970
 
 
 
 
 
971
 
972
  pred_id = int(
973
  torch.argmax(
974
- probabilities
975
  ).item()
976
  )
977
 
 
 
 
978
 
979
- confidence = float(
980
- probabilities[
981
- pred_id
982
- ].item()
983
- * 100
984
- )
985
-
986
-
987
- scam_probability = float(
988
- probabilities[
989
- 0
990
- ].item()
991
- * 100
992
- )
993
-
994
-
995
- real_probability = float(
996
- probabilities[
997
- 1
998
- ].item()
999
  * 100
1000
  )
1001
 
1002
-
1003
- pred_label = LABEL_MAP.get(
1004
- pred_id,
1005
- f"未知類別 {pred_id}",
1006
- )
1007
-
1008
-
1009
- # =====================================================
1010
- # Integrated Gradients
1011
- # =====================================================
1012
-
1013
- try:
1014
-
1015
- (
1016
- important_spans,
1017
- token_items,
1018
- convergence_delta,
1019
- ) = explain_prediction(
1020
- model_inputs=model_inputs,
1021
- offsets=offsets,
1022
- original_text=text,
1023
- predicted_class=pred_id,
1024
- )
1025
-
1026
-
1027
- explanation = (
1028
- format_span_explanation(
1029
- important_spans,
1030
- pred_id,
1031
- )
1032
- )
1033
-
1034
-
1035
- print(
1036
- "IG convergence delta:",
1037
- convergence_delta,
1038
- flush=True,
1039
- )
1040
-
1041
-
1042
- print(
1043
- "重要片段:",
1044
- [
1045
- item["text"]
1046
- for item
1047
- in important_spans
1048
- ],
1049
- flush=True,
1050
- )
1051
-
1052
-
1053
- except Exception as error:
1054
-
1055
- print(
1056
- (
1057
- "Integrated Gradients "
1058
- "片段解釋失敗:"
1059
- f"{error}"
1060
- ),
1061
- flush=True,
1062
- )
1063
-
1064
-
1065
- explanation = (
1066
- "本次 Integrated Gradients "
1067
- "可解釋性計算失敗,"
1068
- "但 BERT 分類結果仍可正常使用。"
1069
- )
1070
-
1071
-
1072
- # =====================================================
1073
- # 安全提醒
1074
- # =====================================================
1075
-
1076
- if pred_id == 0:
1077
-
1078
- advice = (
1079
- "請勿立即匯款、提供銀行帳號、"
1080
- "密碼、信用卡資料或簡訊驗證碼。"
1081
- "建議透過官方管道查證,"
1082
- "必要時撥打 165 反詐騙專線。"
1083
- )
1084
-
1085
- else:
1086
-
1087
- advice = (
1088
- "模型判斷較接近真實訊息,"
1089
- "但模型仍可能誤判。"
1090
- "若內容涉及金錢、帳戶或個人資料,"
1091
- "仍應再次查證。"
1092
- )
1093
-
1094
-
1095
- # =====================================================
1096
- # 回傳結果
1097
- # =====================================================
1098
-
1099
  return (
1100
- f"🔍 判斷結果:{pred_label}\n\n"
1101
-
1102
- f"📊 模型信心度:"
1103
- f"{confidence:.2f}%\n\n"
1104
-
1105
- f"🚨 詐騙機率:"
1106
- f"{scam_probability:.2f}%\n"
1107
-
1108
- f"✅ 真實機率:"
1109
- f"{real_probability:.2f}%\n\n"
1110
-
1111
- "🧠 AI 模型判斷依據"
1112
- "(Integrated Gradients)\n\n"
1113
-
1114
- f"{explanation}\n\n"
1115
-
1116
- f"⚠️ 提醒:{advice}"
1117
  )
1118
 
1119
 
1120
- # =========================================================
1121
  # Gradio
1122
- # =========================================================
1123
 
1124
  demo = gr.Interface(
1125
 
1126
  fn=predict,
1127
 
1128
  inputs=gr.Textbox(
1129
- lines=7,
1130
- label="訊息內容",
1131
- placeholder=(
1132
- "請輸入要判斷的新聞、"
1133
- "貼文或可疑訊息……"
1134
- ),
1135
  ),
1136
 
1137
  outputs=gr.Textbox(
1138
- label="辨識結果",
1139
- lines=20,
1140
  ),
1141
 
1142
  title=(
1143
- "LINE Bot BERT "
1144
- "詐騙/真實訊息辨識 API"
1145
  ),
1146
 
1147
- description=(
1148
- "系統使用 BERT 判斷文字"
1149
- "較接近詐騙或真實訊息,"
1150
- "並使用 Integrated Gradients "
1151
- "分析本次預測的重要文字片段。"
1152
- ),
1153
-
1154
- api_name="predict",
1155
  )
1156
 
1157
 
1158
- # =========================================================
1159
- # 啟動
1160
- # =========================================================
1161
-
1162
  if __name__ == "__main__":
1163
 
1164
  demo.launch(
1165
  server_name="0.0.0.0",
1166
  server_port=7860,
1167
  ssr_mode=False,
1168
- show_error=True,
1169
  )
 
1
  import os
 
2
  import shutil
 
3
  import zipfile
4
 
5
  import gradio as gr
6
  import torch
7
 
 
8
  from transformers import (
9
  AutoModelForSequenceClassification,
10
  AutoTokenizer,
11
  )
12
 
13
 
 
 
 
 
14
  ZIP_PATH = "model.zip"
 
15
  EXTRACT_DIR = "./model"
 
16
  MODEL_DIR = os.path.join(
17
  EXTRACT_DIR,
18
+ "final_model"
19
  )
20
 
21
  DEVICE = torch.device("cpu")
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # ==========================================
25
+ # 解壓模型
26
+ # ==========================================
27
 
28
+ def prepare_model():
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  config_path = os.path.join(
31
  MODEL_DIR,
32
+ "config.json"
33
  )
34
 
35
+ if os.path.isfile(config_path):
 
 
 
 
 
 
 
 
 
36
  print(
37
+ "模型已解壓完成",
38
+ flush=True
39
  )
40
  return
41
 
 
51
 
52
  os.makedirs(
53
  EXTRACT_DIR,
54
+ exist_ok=True
55
  )
56
 
57
  print(
58
+ "正在解壓 model.zip...",
59
+ flush=True
60
  )
61
 
62
  with zipfile.ZipFile(
63
  ZIP_PATH,
64
+ "r"
65
  ) as zip_ref:
66
 
67
  zip_ref.extractall(
 
69
  )
70
 
71
  print(
72
+ "模型解壓完成",
73
+ flush=True
74
  )
75
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ prepare_model()
 
 
78
 
 
79
 
80
+ # ==========================================
81
+ # 載入模型
82
+ # ==========================================
83
 
84
  print(
85
+ "正在載入 tokenizer...",
86
+ flush=True
87
  )
88
 
89
  tokenizer = AutoTokenizer.from_pretrained(
90
  MODEL_DIR,
91
+ local_files_only=True
 
92
  )
93
 
94
 
 
 
 
 
 
 
 
 
95
  print(
96
+ "正在載入 BERT...",
97
+ flush=True
98
  )
99
 
100
  model = (
101
  AutoModelForSequenceClassification
102
  .from_pretrained(
103
  MODEL_DIR,
104
+ local_files_only=True
105
  )
106
  )
107
 
108
+ model.to(DEVICE)
 
 
 
109
  model.eval()
110
 
111
 
112
  print(
113
+ "✅ BERT V3 載入成功",
114
+ flush=True
 
 
 
 
 
 
 
 
 
115
  )
116
 
117
 
118
+ LABEL_MAP = {
119
+ 0: "詐騙訊息",
120
+ 1: "正常訊息"
121
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
 
 
 
123
 
124
+ # ==========================================
125
+ # 預測
126
+ # ==========================================
127
 
128
+ def predict(text):
129
 
130
+ text = str(text).strip()
131
 
132
  if not text:
133
+ return "請輸入文字"
134
 
135
+ inputs = tokenizer(
 
 
 
 
 
 
 
 
 
 
 
 
136
  text,
137
  return_tensors="pt",
138
  truncation=True,
139
+ max_length=256
 
 
140
  )
141
 
142
+ inputs = {
 
 
 
 
 
 
 
 
 
143
  key: value.to(DEVICE)
144
  for key, value
145
+ in inputs.items()
146
  }
147
 
 
 
 
 
 
148
  with torch.inference_mode():
149
 
150
  outputs = model(
151
+ **inputs
 
 
 
 
 
 
 
152
  )
153
 
154
+ probs = torch.softmax(
155
+ outputs.logits,
156
+ dim=-1
157
+ )[0]
158
 
159
+ scam = (
160
+ probs[0].item()
161
+ * 100
 
162
  )
163
 
164
+ normal = (
165
+ probs[1].item()
166
+ * 100
167
+ )
168
 
169
  pred_id = int(
170
  torch.argmax(
171
+ probs
172
  ).item()
173
  )
174
 
175
+ label = LABEL_MAP[
176
+ pred_id
177
+ ]
178
 
179
+ confidence = (
180
+ probs[pred_id]
181
+ .item()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  * 100
183
  )
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  return (
186
+ f"🔍 判斷結果:{label}\n\n"
187
+ f"📊 模型信心度:{confidence:.2f}%\n\n"
188
+ f"🚨 詐騙機率:{scam:.2f}%\n"
189
+ f"✅ 正常機率:{normal:.2f}%"
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  )
191
 
192
 
193
+ # ==========================================
194
  # Gradio
195
+ # ==========================================
196
 
197
  demo = gr.Interface(
198
 
199
  fn=predict,
200
 
201
  inputs=gr.Textbox(
202
+ lines=6,
203
+ label="訊息內容"
 
 
 
 
204
  ),
205
 
206
  outputs=gr.Textbox(
207
+ label="判斷結果",
208
+ lines=10
209
  ),
210
 
211
  title=(
212
+ "BERT V3 "
213
+ "詐騙訊息辨識"
214
  ),
215
 
216
+ api_name="predict"
 
 
 
 
 
 
 
217
  )
218
 
219
 
 
 
 
 
220
  if __name__ == "__main__":
221
 
222
  demo.launch(
223
  server_name="0.0.0.0",
224
  server_port=7860,
225
  ssr_mode=False,
226
+ show_error=True
227
  )