cwadayi commited on
Commit
f5157f9
·
verified ·
1 Parent(s): 3eee2c5

Create app.py

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