william1324 commited on
Commit
856d4f7
·
verified ·
1 Parent(s): 177da7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -20
app.py CHANGED
@@ -1,31 +1,50 @@
 
1
  from transformers import pipeline
2
  import gradio as gr
3
 
4
  # 載入 Hugging Face 的中文三分類情緒模型
5
  classifier = pipeline("text-classification", model="uer/roberta-base-finetuned-dianping-chinese", tokenizer="uer/roberta-base-finetuned-dianping-chinese")
6
 
7
- # 分析函式
8
- def analyze_sentiment(text):
9
- result = classifier(text)[0]
10
- label = result["label"]
11
- score = round(result["score"], 4)
12
 
13
- if label == "LABEL_0":
14
- sentiment = "負向情緒"
15
- elif label == "LABEL_1":
16
- sentiment = "中立情緒"
17
- elif label == "LABEL_2":
18
- sentiment = "正向情緒"
19
- else:
20
- sentiment = "無法判斷"
21
 
22
- return f"判斷結果:{sentiment}\n信心分數:{score}"
 
 
 
 
 
23
 
24
- # Gradio 介面
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  gr.Interface(
26
- fn=analyze_sentiment,
27
- inputs=gr.Textbox(lines=4, placeholder="請輸入中文內容"),
28
- outputs="text",
29
- title="中文情緒分析系統(正向/中立/負向)",
30
- description="輸入一段中文,模型會自動判斷情緒傾向"
31
  ).launch()
 
1
+ import pandas as pd
2
  from transformers import pipeline
3
  import gradio as gr
4
 
5
  # 載入 Hugging Face 的中文三分類情緒模型
6
  classifier = pipeline("text-classification", model="uer/roberta-base-finetuned-dianping-chinese", tokenizer="uer/roberta-base-finetuned-dianping-chinese")
7
 
8
+ # 分析函式(接收 CSV)
9
+ def analyze_csv(file):
10
+ df = pd.read_csv(file)
 
 
11
 
12
+ # 檢查是否有 "text" 欄位
13
+ if "text" not in df.columns:
14
+ return "錯誤:CSV 檔案中必須包含 'text' 欄位。"
 
 
 
 
 
15
 
16
+ # 對每一列文字做情緒分析
17
+ results = []
18
+ for text in df["text"]:
19
+ result = classifier(str(text))[0]
20
+ label = result["label"]
21
+ score = round(result["score"], 4)
22
 
23
+ if label == "LABEL_0":
24
+ sentiment = "負向"
25
+ elif label == "LABEL_1":
26
+ sentiment = "中立"
27
+ elif label == "LABEL_2":
28
+ sentiment = "正向"
29
+ else:
30
+ sentiment = "未知"
31
+
32
+ results.append({"label": sentiment, "score": score})
33
+
34
+ # 加回原始 dataframe
35
+ df["情緒判斷"] = [r["label"] for r in results]
36
+ df["信心分數"] = [r["score"] for r in results]
37
+
38
+ # 輸出為新的 csv 檔案
39
+ output_file = "/tmp/output.csv"
40
+ df.to_csv(output_file, index=False)
41
+ return output_file
42
+
43
+ # Gradio 介面(接收檔案,回傳檔案)
44
  gr.Interface(
45
+ fn=analyze_csv,
46
+ inputs=gr.File(label="上傳包含 'text' 欄位的 CSV 檔案", file_types=[".csv"]),
47
+ outputs=gr.File(label="下載標註後的 CSV 檔案"),
48
+ title="中文情緒分析系統(批次處理)",
49
+ description="上傳一份 CSV,系統會針對 'text' 欄做情緒分析,並下載結果。"
50
  ).launch()