Spaces:
Running
Running
Update sentiment.py
Browse files- sentiment.py +14 -4
sentiment.py
CHANGED
@@ -1,6 +1,10 @@
|
|
1 |
import requests
|
2 |
from config import HEADERS
|
3 |
|
|
|
|
|
|
|
|
|
4 |
# 轉換英文分類為中文
|
5 |
def translate_sentiment(label):
|
6 |
if "positive" in label.lower():
|
@@ -24,10 +28,16 @@ def convert_confidence(score):
|
|
24 |
else:
|
25 |
return f"❌ **極低信心(建議忽略)** ({percentage}%)"
|
26 |
|
27 |
-
# 調用 Hugging Face API 進行情緒分析
|
28 |
-
def analyze_sentiment(text, model_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
try:
|
30 |
-
API_URL = f"https://api-inference.huggingface.co/models/{model_id}"
|
31 |
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
|
32 |
result = response.json()
|
33 |
|
@@ -36,7 +46,7 @@ def analyze_sentiment(text, model_id):
|
|
36 |
confidence = result[0]["score"]
|
37 |
confidence_label = convert_confidence(confidence)
|
38 |
|
39 |
-
return f"**情緒分類**: {sentiment}\n**AI 判斷的信心度**: {confidence_label}", confidence
|
40 |
else:
|
41 |
return "⚠️ **無法分析文本,請稍後再試**", 0.0
|
42 |
|
|
|
1 |
import requests
|
2 |
from config import HEADERS
|
3 |
|
4 |
+
# 📌 預設載入的模型
|
5 |
+
CURRENT_MODEL = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
|
6 |
+
API_URL = f"https://api-inference.huggingface.co/models/{CURRENT_MODEL}"
|
7 |
+
|
8 |
# 轉換英文分類為中文
|
9 |
def translate_sentiment(label):
|
10 |
if "positive" in label.lower():
|
|
|
28 |
else:
|
29 |
return f"❌ **極低信心(建議忽略)** ({percentage}%)"
|
30 |
|
31 |
+
# 📌 調用 Hugging Face API 進行情緒分析
|
32 |
+
def analyze_sentiment(text, model_id=None):
|
33 |
+
global CURRENT_MODEL, API_URL
|
34 |
+
|
35 |
+
# 📌 **只在模型變更時更新 API URL**
|
36 |
+
if model_id and model_id != CURRENT_MODEL:
|
37 |
+
CURRENT_MODEL = model_id
|
38 |
+
API_URL = f"https://api-inference.huggingface.co/models/{CURRENT_MODEL}"
|
39 |
+
|
40 |
try:
|
|
|
41 |
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
|
42 |
result = response.json()
|
43 |
|
|
|
46 |
confidence = result[0]["score"]
|
47 |
confidence_label = convert_confidence(confidence)
|
48 |
|
49 |
+
return f"**情緒分類**: {sentiment}\n**AI 判斷的信心度**: {confidence_label}", confidence
|
50 |
else:
|
51 |
return "⚠️ **無法分析文本,請稍後再試**", 0.0
|
52 |
|