Spaces:
Sleeping
Sleeping
import gradio as gr | |
import requests | |
import os | |
# 設定 Hugging Face API | |
API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-xlm-roberta-base-sentiment" | |
# 從環境變數讀取 API 金鑰(建議這樣做以保護隱私) | |
HF_API_KEY = os.getenv("HF_API_KEY") # 你可以在 .bashrc 或 .zshrc 設定環境變數 | |
HEADERS = {"Authorization": f"Bearer {HF_API_KEY}"} | |
# 轉換英文分類為中文 | |
def translate_sentiment(label): | |
if "positive" in label.lower(): | |
return "😃 **正向**" | |
elif "neutral" in label.lower(): | |
return "😐 **中立**" | |
else: | |
return "😡 **負向**" | |
# 轉換信心度為更直觀的等級 | |
def convert_confidence(score): | |
percentage = round(score * 100) # 轉換為百分比 | |
if score >= 0.90: | |
return f"🌟 **極高信心** ({percentage}%)" | |
elif score >= 0.75: | |
return f"✅ **高信心** ({percentage}%)" | |
elif score >= 0.50: | |
return f"⚠️ **中等信心** ({percentage}%)" | |
elif score >= 0.30: | |
return f"❓ **低信心** ({percentage}%)" | |
else: | |
return f"❌ **極低信心(建議忽略)** ({percentage}%)" | |
# 調用 Hugging Face API 進行情緒分析 | |
def analyze_sentiment(text): | |
try: | |
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text}) | |
result = response.json() | |
if isinstance(result, list) and len(result) > 0: | |
sentiment = translate_sentiment(result[0]["label"]) # 翻譯情緒 | |
confidence = result[0]["score"] | |
confidence_label = convert_confidence(confidence) # 轉換信心度 | |
return f"**情緒分類**: {sentiment}\n**信心度**: {confidence_label}" | |
else: | |
return "⚠️ **無法分析文本,請稍後再試**" | |
except Exception as e: | |
return f"❌ **錯誤**: {str(e)}" | |
# 建立 Gradio 介面 | |
iface = gr.Interface( | |
fn=analyze_sentiment, | |
inputs=gr.Textbox(lines=2, placeholder="請輸入文本(支援多語言)..."), | |
outputs=gr.Markdown(label="分析結果"), | |
title="多語言情緒分析 AI", | |
description="請輸入一段話,AI 會分析它的情緒(正向 / 中立 / 負向),並提供信心度。", | |
theme="compact" | |
) | |
# 啟動 Web 應用 | |
iface.launch() | |