import os import shutil import zipfile import gradio as gr import torch from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, ) ZIP_PATH = "model.zip" EXTRACT_DIR = "./model" MODEL_DIR = os.path.join( EXTRACT_DIR, "final_model" ) DEVICE = torch.device("cpu") # ========================================== # 解壓模型 # ========================================== def prepare_model(): config_path = os.path.join( MODEL_DIR, "config.json" ) if os.path.isfile(config_path): print( "模型已解壓完成", flush=True ) return if not os.path.isfile(ZIP_PATH): raise FileNotFoundError( "找不到 model.zip" ) if os.path.exists(EXTRACT_DIR): shutil.rmtree( EXTRACT_DIR ) os.makedirs( EXTRACT_DIR, exist_ok=True ) print( "正在解壓 model.zip...", flush=True ) with zipfile.ZipFile( ZIP_PATH, "r" ) as zip_ref: zip_ref.extractall( EXTRACT_DIR ) print( "模型解壓完成", flush=True ) prepare_model() # ========================================== # 載入模型 # ========================================== print( "正在載入 tokenizer...", flush=True ) tokenizer = AutoTokenizer.from_pretrained( MODEL_DIR, local_files_only=True ) print( "正在載入 BERT...", flush=True ) model = ( AutoModelForSequenceClassification .from_pretrained( MODEL_DIR, local_files_only=True ) ) model.to(DEVICE) model.eval() print( "✅ BERT V3 載入成功", flush=True ) LABEL_MAP = { 0: "詐騙訊息", 1: "正常訊息" } # ========================================== # 預測 # ========================================== def predict(text): text = str(text).strip() if not text: return "請輸入文字" inputs = tokenizer( text, return_tensors="pt", truncation=True, max_length=256 ) inputs = { key: value.to(DEVICE) for key, value in inputs.items() } with torch.inference_mode(): outputs = model( **inputs ) probs = torch.softmax( outputs.logits, dim=-1 )[0] scam = ( probs[0].item() * 100 ) normal = ( probs[1].item() * 100 ) pred_id = int( torch.argmax( probs ).item() ) label = LABEL_MAP[ pred_id ] confidence = ( probs[pred_id] .item() * 100 ) return ( f"🔍 判斷結果:{label}\n\n" f"📊 模型信心度:{confidence:.2f}%\n\n" f"🚨 詐騙機率:{scam:.2f}%\n" f"✅ 正常機率:{normal:.2f}%" ) # ========================================== # Gradio # ========================================== demo = gr.Interface( fn=predict, inputs=gr.Textbox( lines=6, label="訊息內容" ), outputs=gr.Textbox( label="判斷結果", lines=10 ), title=( "BERT V3 " "詐騙訊息辨識" ), api_name="predict" ) if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=7860, ssr_mode=False, show_error=True )