Spaces:
Sleeping
Sleeping
Update sentiment.py
Browse files- sentiment.py +23 -13
sentiment.py
CHANGED
|
@@ -2,12 +2,21 @@ import requests
|
|
| 2 |
import logging
|
| 3 |
from config import HEADERS, MODEL_OPTIONS, DEFAULT_MODEL
|
| 4 |
|
| 5 |
-
# 設定 logging
|
| 6 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 7 |
|
| 8 |
CURRENT_MODEL = DEFAULT_MODEL
|
| 9 |
API_URL = f"https://api-inference.huggingface.co/models/{CURRENT_MODEL}"
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
# 📌 呼叫 Hugging Face API 進行情緒分析
|
| 12 |
def analyze_sentiment(text, model_name=None):
|
| 13 |
global CURRENT_MODEL, API_URL
|
|
@@ -19,14 +28,24 @@ def analyze_sentiment(text, model_name=None):
|
|
| 19 |
|
| 20 |
try:
|
| 21 |
logging.info("🚀 發送 API 請求...")
|
|
|
|
|
|
|
|
|
|
| 22 |
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
|
| 23 |
response.raise_for_status()
|
| 24 |
result = response.json()
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
if isinstance(result, list) and len(result) > 0:
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
| 30 |
return f"**情緒分類**: {sentiment}\n**AI 信心度**: {confidence*100:.2f}%", confidence
|
| 31 |
else:
|
| 32 |
return "⚠️ **無法分析文本,請稍後再試**", 0.0
|
|
@@ -34,12 +53,3 @@ def analyze_sentiment(text, model_name=None):
|
|
| 34 |
except requests.exceptions.RequestException as e:
|
| 35 |
logging.error(f"❌ API 請求錯誤: {e}")
|
| 36 |
return f"❌ **API 請求錯誤**: {str(e)}", 0.0
|
| 37 |
-
except ValueError as e:
|
| 38 |
-
logging.error(f"❌ JSON 解碼錯誤: {e}")
|
| 39 |
-
return f"❌ **JSON 解碼錯誤**: {str(e)}", 0.0
|
| 40 |
-
except KeyError as e:
|
| 41 |
-
logging.error(f"❌ 字典鍵錯誤: {e}")
|
| 42 |
-
return f"❌ **字典鍵錯誤**: {str(e)}", 0.0
|
| 43 |
-
except Exception as e:
|
| 44 |
-
logging.error(f"❌ 未知錯誤: {e}")
|
| 45 |
-
return f"❌ **未知錯誤**: {str(e)}", 0.0
|
|
|
|
| 2 |
import logging
|
| 3 |
from config import HEADERS, MODEL_OPTIONS, DEFAULT_MODEL
|
| 4 |
|
|
|
|
| 5 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 6 |
|
| 7 |
CURRENT_MODEL = DEFAULT_MODEL
|
| 8 |
API_URL = f"https://api-inference.huggingface.co/models/{CURRENT_MODEL}"
|
| 9 |
|
| 10 |
+
# 📌 **轉換英文分類為台灣用語**
|
| 11 |
+
def translate_sentiment(label):
|
| 12 |
+
label = label.lower()
|
| 13 |
+
if "positive" in label:
|
| 14 |
+
return "😃 **開心、正面**"
|
| 15 |
+
elif "neutral" in label:
|
| 16 |
+
return "😐 **普通、沒特別感覺**"
|
| 17 |
+
else:
|
| 18 |
+
return "😡 **負面、沒那麼開心**"
|
| 19 |
+
|
| 20 |
# 📌 呼叫 Hugging Face API 進行情緒分析
|
| 21 |
def analyze_sentiment(text, model_name=None):
|
| 22 |
global CURRENT_MODEL, API_URL
|
|
|
|
| 28 |
|
| 29 |
try:
|
| 30 |
logging.info("🚀 發送 API 請求...")
|
| 31 |
+
print(f"📢 [Debug] API URL: {API_URL}")
|
| 32 |
+
print(f"📢 [Debug] 輸入文本: {text}")
|
| 33 |
+
|
| 34 |
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
|
| 35 |
response.raise_for_status()
|
| 36 |
result = response.json()
|
| 37 |
+
|
| 38 |
+
print(f"📢 [Debug] API 回應: {result}")
|
| 39 |
+
|
| 40 |
+
# 📌 **修正回應格式**
|
| 41 |
+
if isinstance(result, list) and len(result) > 0 and isinstance(result[0], list):
|
| 42 |
+
result = result[0] # 取得內層列表
|
| 43 |
|
| 44 |
if isinstance(result, list) and len(result) > 0:
|
| 45 |
+
# 取得最高分的情緒分類
|
| 46 |
+
best_sentiment = max(result, key=lambda x: x["score"])
|
| 47 |
+
sentiment = translate_sentiment(best_sentiment["label"]) # ✅ **轉換為台灣用語**
|
| 48 |
+
confidence = best_sentiment["score"]
|
| 49 |
return f"**情緒分類**: {sentiment}\n**AI 信心度**: {confidence*100:.2f}%", confidence
|
| 50 |
else:
|
| 51 |
return "⚠️ **無法分析文本,請稍後再試**", 0.0
|
|
|
|
| 53 |
except requests.exceptions.RequestException as e:
|
| 54 |
logging.error(f"❌ API 請求錯誤: {e}")
|
| 55 |
return f"❌ **API 請求錯誤**: {str(e)}", 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|