Spaces:
Running
Running
Create sentiment.py
Browse files- sentiment.py +43 -0
sentiment.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
from config import API_URL, HEADERS
|
3 |
+
|
4 |
+
# 轉換英文分類為中文
|
5 |
+
def translate_sentiment(label):
|
6 |
+
if "positive" in label.lower():
|
7 |
+
return "😃 **正向**"
|
8 |
+
elif "neutral" in label.lower():
|
9 |
+
return "😐 **中立**"
|
10 |
+
else:
|
11 |
+
return "😡 **負向**"
|
12 |
+
|
13 |
+
# 轉換信心度為更直觀的等級(加上百分比)
|
14 |
+
def convert_confidence(score):
|
15 |
+
percentage = round(score * 100)
|
16 |
+
if score >= 0.90:
|
17 |
+
return f"🌟 **極高信心** ({percentage}%)"
|
18 |
+
elif score >= 0.75:
|
19 |
+
return f"✅ **高信心** ({percentage}%)"
|
20 |
+
elif score >= 0.50:
|
21 |
+
return f"⚠️ **中等信心** ({percentage}%)"
|
22 |
+
elif score >= 0.30:
|
23 |
+
return f"❓ **低信心** ({percentage}%)"
|
24 |
+
else:
|
25 |
+
return f"❌ **極低信心(建議忽略)** ({percentage}%)"
|
26 |
+
|
27 |
+
# 調用 Hugging Face API 進行情緒分析
|
28 |
+
def analyze_sentiment(text):
|
29 |
+
try:
|
30 |
+
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
|
31 |
+
result = response.json()
|
32 |
+
|
33 |
+
if isinstance(result, list) and len(result) > 0:
|
34 |
+
sentiment = translate_sentiment(result[0]["label"])
|
35 |
+
confidence = result[0]["score"]
|
36 |
+
confidence_label = convert_confidence(confidence)
|
37 |
+
|
38 |
+
return f"**情緒分類**: {sentiment}\n**AI判斷的信心度為**: {confidence_label}"
|
39 |
+
else:
|
40 |
+
return "⚠️ **無法分析文本,請稍後再試**"
|
41 |
+
|
42 |
+
except Exception as e:
|
43 |
+
return f"❌ **錯誤**: {str(e)}"
|