sentiment-analysis / sentiment.py
dayuian's picture
Update sentiment.py
3dd72e9 verified
raw
history blame
1.23 kB
import requests
from config import HEADERS
# 📌 預設載入的模型
CURRENT_MODEL = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
API_URL = f"https://api-inference.huggingface.co/models/{CURRENT_MODEL}"
def analyze_sentiment(text, model_id=None):
global CURRENT_MODEL, API_URL
# 📌 **只在模型變更時更新 API URL**
if model_id and model_id != CURRENT_MODEL:
CURRENT_MODEL = model_id
API_URL = f"https://api-inference.huggingface.co/models/{CURRENT_MODEL}"
print(f"🔄 重新載入模型: {CURRENT_MODEL}")
try:
print("🚀 發送 API 請求...")
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
result = response.json()
print(f"✅ API 回應: {result}")
if isinstance(result, list) and len(result) > 0:
sentiment = result[0]["label"]
confidence = result[0]["score"]
return f"**情緒分類**: {sentiment}\n**AI 信心度**: {confidence*100:.2f}%", confidence
else:
return "⚠️ **無法分析文本,請稍後再試**", 0.0
except Exception as e:
print(f"❌ API 錯誤: {e}")
return f"❌ **錯誤**: {str(e)}", 0.0