import gradio as gr import matplotlib.pyplot as plt from sentiment import analyze_sentiment # 📌 可選擇的模型 MODEL_OPTIONS = { "🌎 多語言推特情緒分析 (XLM-RoBERTa)": "cardiffnlp/twitter-xlm-roberta-base-sentiment", "📖 多語言情緒分析 (BERT)": "nlptown/bert-base-multilingual-uncased-sentiment", "🇬🇧 英語情緒分析 (DistilBERT)": "distilbert-base-uncased-finetuned-sst-2-english" } # 📌 生成信心度條狀圖 def plot_confidence(score): fig, ax = plt.subplots(figsize=(4, 1)) ax.barh(["信心度"], [score], color="blue") ax.set_xlim([0, 1]) ax.set_xticks([0, 0.25, 0.5, 0.75, 1]) ax.set_xlabel("信心度(百分比)") return fig # 📌 Gradio 介面說明 intro_text = """ # 🎯 多語言情緒分析 AI 本應用使用 Hugging Face 的 `XLM-RoBERTa`、`BERT`、`DistilBERT` 模型來進行**多語言情緒分析**。 輸入任何語言的文本,AI 會自動判斷其**情緒分類(正向 / 中立 / 負向)**,並提供**信心度(%)**。 ## 📌 **使用方式** 1️⃣ **輸入一句話或一段文本**(可輸入中文、英文、日文等) 2️⃣ **選擇 AI 模型(預設為 `XLM-RoBERTa`)** 3️⃣ **點擊「分析情緒」** 4️⃣ **查看結果,包括情緒分類 & 信心度** """ developer_info = """ ## 👨‍💻 開發資訊 - **開發者**: 余彦志 (大宇 / ian) - **模型來源**: [Hugging Face](https://huggingface.co/cardiffnlp/twitter-xlm-roberta-base-sentiment) - **技術棧**: `Gradio`、`FastAPI`、`Hugging Face API` - **聯絡方式**: [dayuian@hotmail.com] """ # 📌 建立 Gradio 介面 def create_ui(): with gr.Blocks(theme=gr.themes.Soft()) as iface: gr.Markdown(intro_text) text_input = gr.Textbox(lines=3, placeholder="請輸入文本...", label="輸入文本") model_selector = gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), value="🌎 多語言推特情緒分析 (XLM-RoBERTa)", label="選擇 AI 模型") analyze_button = gr.Button("分析情緒") progress_bar = gr.Textbox(visible=False, label="模型載入進度") result_output = gr.Markdown(label="分析結果") plot_output = gr.Plot(label="信心度") # 📌 綁定按鈕功能 def process_analysis(text, model_name): model_id = MODEL_OPTIONS[model_name] # **只有當選擇的模型與目前使用的模型不一致時,才顯示進度條** if model_id != analyze_sentiment.CURRENT_MODEL: progress_bar.update("🔄 AI 模型載入中,請稍後...", visible=True) result, confidence_score = analyze_sentiment(text, model_id) plot = plot_confidence(confidence_score) progress_bar.update("", visible=False) # 隱藏進度條 return result, plot analyze_button.click(process_analysis, inputs=[text_input, model_selector], outputs=[result_output, plot_output, progress_bar]) gr.Markdown(developer_info) return iface