### 1. Imports and class names setup ### import gradio as gr import os import torch import transformers from model import create_distilbert_model, tokenize_texts_and_labels from transformers import DistilBertForSequenceClassification, DistilBertTokenizer from typing import Tuple, Dict from timeit import default_timer as timer # Setup class names with open("class_names.txt", "r") as f: class_names = [label.strip() for label in f.readlines()] # ['Negative', 'Positive'] # 加載模型與 tokenizer DistilBERT_Model, DistilBERT_Tokenizer = create_distilbert_model(num_classes=2, seed=42) DistilBERT_Model.load_state_dict( torch.load( f=r"DistilBERT_Model_512.pth", # 路徑到保存的檔案 map_location=torch.device("cpu") # 加載到 CPU ) ) # 設定設備 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") DistilBERT_Model.to(device) # 預測函數 def predict(text: str) -> Tuple[Dict[str, float], float]: """ 預測輸入文字的情感,返回預測的機率字典和耗時。 Args: text (str): 要進行情感分析的文本 Returns: Tuple[Dict[str, float], float]: 包含每個類別的機率字典和預測所需的時間 """ # 計時開始 start_time = timer() # 將文本轉為模型輸入格式 test_input = tokenize_texts_and_labels( DistilBERT_Tokenizer, [text], # 傳入單條文本,需封裝為列表 labels=None, # 測試時不需要標籤 max_length=512 ) # 移動輸入到設備(CPU/GPU) inputs = {key: val.to(device) for key, val in test_input.items()} # 模型推理 DistilBERT_Model.eval() # 設定模型為評估模式 with torch.no_grad(): # 禁用梯度計算以加速推理 outputs = DistilBERT_Model(**inputs) logits = outputs.logits # 提取 logits # 計算 softmax 機率 pred_probs = torch.softmax(logits, dim=1) # 將機率與類別名稱對應 pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))} # 計算耗時 pred_time = round(timer() - start_time, 5) return pred_labels_and_probs, pred_time # Gradio predict function def gradio_predict(text): pred_labels_and_probs, pred_time = predict(text) # Get highest probability label predicted_label = max(pred_labels_and_probs, key=pred_labels_and_probs.get) predicted_probability = pred_labels_and_probs[predicted_label] # 給 Gradio 的輸出 # 第一個輸出:主要的情感標籤 sentiment_label = f"{predicted_label} ({predicted_probability:.2f})" # 第二個輸出:詳細的預測數據 details = { "Sentiment": predicted_label, "Probability": f"{predicted_probability:.2f}", "Prediction Time (s)": pred_time, } return sentiment_label, details # 確保返回兩個值 # Gradio Interface title = "DistilBERT Sentiment Classifier 😃/😡" description = ( "A sentiment analysis model powered by DistilBERT. " "Enter a sentence and the model will classify it as Positive or Negative, " "along with the prediction probability and time taken." ) examples = [ ["I love this movie!"], ["This product is terrible."], ["Amazing experience, would highly recommend!"], ["I hate waiting in line for hours."], ["The service was good, but the food was average."] ] # Create Gradio interface demo = gr.Interface( fn=gradio_predict, inputs=gr.Textbox(lines=3, placeholder="Type your sentence here..."), outputs=[ gr.Label(label="Sentiment Prediction"), # 第一個輸出:情感標籤 gr.JSON(label="Details"), # 第二個輸出:詳細信息 ], examples=examples, title=title, description=description ) # Launch the demo! demo.launch(debug=False)