Spaces:
Sleeping
Sleeping
| 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]) # 設定範圍為 0-1 | |
| ax.set_xticks([0, 0.25, 0.5, 0.75, 1]) # 設定刻度 | |
| ax.set_xlabel("信心度(百分比)") # 標題 | |
| return fig | |
| # 📌 建立 Gradio 介面 | |
| def create_ui(): | |
| with gr.Blocks(theme=gr.themes.Soft()) as iface: | |
| gr.Markdown("# 🎯 多語言情緒分析 AI") | |
| gr.Markdown("請輸入一段文字,選擇 AI 模型,AI 會分析其情緒,並提供信心度。") | |
| 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) # 進度條(文字顯示) | |
| result_output = gr.Markdown(label="分析結果") | |
| plot_output = gr.Plot(label="信心度") | |
| # 📌 綁定按鈕功能 | |
| def process_analysis(text, model_name): | |
| progress_bar.update("🔄 AI 模型載入中,請稍後...", visible=True) # 顯示載入進度 | |
| model_id = MODEL_OPTIONS[model_name] # 轉換中文名稱為模型 ID | |
| result, confidence_score = analyze_sentiment(text, model_id) # 調用 API 進行分析 | |
| 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]) | |
| return iface | |