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 Key HF_API_KEY = os.getenv("HF_API_KEY") if HF_API_KEY is None: raise ValueError("❌ API Key 未設定,請檢查 Hugging Face Secrets!") 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 介面說明 intro_text = """ # 🎯 多語言情緒分析 AI 本應用使用 Hugging Face 的 `XLM-RoBERTa` 模型來進行**多語言情緒分析**。 輸入任何語言的文本,AI 會自動判斷其**情緒分類(正向 / 中立 / 負向)**,並提供**信心度(%)**。 ## 🔹 **功能特色** ✅ **支援多語言**(繁體中文、英文、法文、日文等) ✅ **即時分析**,不需下載模型 ✅ **提供信心度**,結果更透明 ## 📌 **如何使用** 1️⃣ **輸入一句話或一段文本**(可輸入中文、英文、日文等) 2️⃣ **點擊「分析情緒」** 3️⃣ **查看結果,包括情緒分類 & 信心度** ## ⚠️ **使用須知** - 目前模型適合**一般文本**,但對**諷刺、幽默**等語句可能不準確。 - 若遇到分析錯誤,請**重新輸入文本或稍後再試**。 """ developer_info = """ ## 👨‍💻 開發資訊 - **開發者**: 余彦志 (大宇 / ian) - **模型來源**: [Hugging Face](https://huggingface.co/cardiffnlp/twitter-xlm-roberta-base-sentiment) - **技術棧**: `Gradio`、`FastAPI`、`Hugging Face API` - **聯絡方式**: [dayuian@hotmail.com] """ # 建立 Gradio 介面 with gr.Blocks(theme=gr.themes.Soft()) as iface: # 介面標題與介紹 gr.Markdown(intro_text) # 文字輸入框 with gr.Row(): text_input = gr.Textbox( lines=3, placeholder="請輸入文本(支援多語言)...", label="輸入文本" ) # 按鈕 analyze_button = gr.Button("分析情緒") # 結果顯示區 result_output = gr.Markdown(label="分析結果") # 事件綁定(點擊按鈕後執行分析) analyze_button.click(analyze_sentiment, inputs=text_input, outputs=result_output) # 顯示開發資訊 gr.Markdown(developer_info) # 啟動 Web 應用 iface.launch()