Spaces:
Sleeping
Sleeping
File size: 1,228 Bytes
798086e a3452de 798086e 4c62000 3dd72e9 4c62000 3dd72e9 4c62000 798086e 3dd72e9 798086e 3dd72e9 798086e 3dd72e9 798086e 3dd72e9 798086e d0d7338 798086e 3dd72e9 d0d7338 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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
|