Sentiment / app.py
cwadayi's picture
Create app.py
f5157f9 verified
import gradio as gr
from transformers import pipeline
# --- 步驟 1:載入 Hugging Face Pipeline (書中第 5 章核心) ---
# 我們指定一個針對中文評論微調過的模型 (uer/roberta-base-finetuned-dianping-chinese)
# task="sentiment-analysis" 會自動處理文字輸入到模型輸出的所有細節
print("正在下載並載入模型,請稍候...")
classifier = pipeline("sentiment-analysis", model="uer/roberta-base-finetuned-dianping-chinese")
# --- 步驟 2:定義處理函式 ---
def analyze_text(text):
# Pipeline 的輸出格式通常是 [{'label': 'positive (mysql)', 'score': 0.99}]
# 這裡我們做一點處理,讓 Gradio 更容易顯示
results = classifier(text)
label = results[0]['label']
score = results[0]['score']
# 將標籤轉為中文顯示
chinese_label = "正面/滿意 😊" if "positive" in label else "負面/不滿 😡"
# 回傳給 Gradio 的格式 (標籤與信心分數)
return {chinese_label: score}
# --- 步驟 3:建立 Gradio 介面 ---
# 這是您最熟悉的部分,建立輸入框與輸出區
demo = gr.Interface(
fn=analyze_text,
inputs=gr.Textbox(lines=3, placeholder="請輸入一段中文文字(例如:這本書寫得真好!)..."),
outputs=gr.Label(num_top_classes=1, label="分析結果"),
title="Hugging Face 中文情感分析器",
description="輸入一段文字,AI 會自動判斷其情緒傾向。(基於 BERT/RoBERTa 模型)",
examples=[
["這本書的內容深入淺出,對我學習 NLP 幫助很大!"],
["運送速度太慢了,書角還有點摺痕,失望。"],
["地震預警系統的反應速度對於防災至關重要。"]
]
)
# 啟動網頁
if __name__ == "__main__":
demo.launch()