dayuian's picture
Update ui.py
ad81ace verified
raw
history blame
2.64 kB
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()
categories = ["低", "中等", "高", "極高"]
levels = [0.3, 0.5, 0.75, 0.9]
confidence_category = next((cat for cat, lvl in zip(categories, levels) if score < lvl), "極高")
ax.bar(categories, levels, color=["red", "orange", "yellow", "green"])
ax.set_ylim([0, 1])
ax.set_title(f"信心度分析 ({confidence_category})")
return fig
# 📌 產生可下載的分析報告
def generate_report(text, result, model_name):
report = f"🔍 **分析報告**\n\n📝 **輸入內容**: {text}\n\n📊 **分析結果**:\n{result}\n\n🤖 **使用模型**: {model_name}"
return report
# 📌 建立 Gradio 介面
def create_ui():
with gr.Blocks(theme=gr.themes.Soft()) as iface:
gr.Markdown("# 🎯 多語言情緒分析 AI\n請輸入一段文字,選擇模型,AI 會分析其情緒。")
with gr.Row():
text_input = gr.Textbox(lines=3, placeholder="請輸入文本(支援多語言)...", label="輸入文本")
with gr.Row():
model_selector = gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), value="多語言推特情緒分析 (XLM-RoBERTa)", label="選擇 AI 模型")
analyze_button = gr.Button("分析情緒")
with gr.Row():
result_output = gr.Markdown(label="分析結果")
plot_output = gr.Plot(label="信心度圖表")
report_output = gr.File(label="下載報告")
# 📌 綁定按鈕功能
def process_analysis(text, model_name):
model_id = MODEL_OPTIONS[model_name] # 轉換中文名稱為模型 ID
result = analyze_sentiment(text, model_id) # 調用 API 進行分析
confidence_score = float(result.split("信心度為**: ")[1].split("%")[0]) / 100
plot = plot_confidence(confidence_score)
report = generate_report(text, result, model_name)
return result, plot, report
analyze_button.click(process_analysis, inputs=[text_input, model_selector], outputs=[result_output, plot_output, report_output])
return iface