Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import os
|
4 |
+
|
5 |
+
# 設定 Hugging Face API
|
6 |
+
API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-xlm-roberta-base-sentiment"
|
7 |
+
|
8 |
+
# 從環境變數讀取 API 金鑰(建議這樣做以保護隱私)
|
9 |
+
HF_API_KEY = os.getenv("HF_API_KEY") # 你可以在 .bashrc 或 .zshrc 設定環境變數
|
10 |
+
HEADERS = {"Authorization": f"Bearer {HF_API_KEY}"}
|
11 |
+
|
12 |
+
# 轉換英文分類為中文
|
13 |
+
def translate_sentiment(label):
|
14 |
+
if "positive" in label.lower():
|
15 |
+
return "😃 **正向**"
|
16 |
+
elif "neutral" in label.lower():
|
17 |
+
return "😐 **中立**"
|
18 |
+
else:
|
19 |
+
return "😡 **負向**"
|
20 |
+
|
21 |
+
# 轉換信心度為更直觀的等級
|
22 |
+
def convert_confidence(score):
|
23 |
+
percentage = round(score * 100) # 轉換為百分比
|
24 |
+
if score >= 0.90:
|
25 |
+
return f"🌟 **極高信心** ({percentage}%)"
|
26 |
+
elif score >= 0.75:
|
27 |
+
return f"✅ **高信心** ({percentage}%)"
|
28 |
+
elif score >= 0.50:
|
29 |
+
return f"⚠️ **中等信心** ({percentage}%)"
|
30 |
+
elif score >= 0.30:
|
31 |
+
return f"❓ **低信心** ({percentage}%)"
|
32 |
+
else:
|
33 |
+
return f"❌ **極低信心(建議忽略)** ({percentage}%)"
|
34 |
+
|
35 |
+
# 調用 Hugging Face API 進行情緒分析
|
36 |
+
def analyze_sentiment(text):
|
37 |
+
try:
|
38 |
+
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
|
39 |
+
result = response.json()
|
40 |
+
|
41 |
+
if isinstance(result, list) and len(result) > 0:
|
42 |
+
sentiment = translate_sentiment(result[0]["label"]) # 翻譯情緒
|
43 |
+
confidence = result[0]["score"]
|
44 |
+
confidence_label = convert_confidence(confidence) # 轉換信心度
|
45 |
+
|
46 |
+
return f"**情緒分類**: {sentiment}\n**信心度**: {confidence_label}"
|
47 |
+
else:
|
48 |
+
return "⚠️ **無法分析文本,請稍後再試**"
|
49 |
+
|
50 |
+
except Exception as e:
|
51 |
+
return f"❌ **錯誤**: {str(e)}"
|
52 |
+
|
53 |
+
# 建立 Gradio 介面
|
54 |
+
iface = gr.Interface(
|
55 |
+
fn=analyze_sentiment,
|
56 |
+
inputs=gr.Textbox(lines=2, placeholder="請輸入文本(支援多語言)..."),
|
57 |
+
outputs=gr.Markdown(label="分析結果"),
|
58 |
+
title="多語言情緒分析 AI",
|
59 |
+
description="請輸入一段話,AI 會分析它的情緒(正向 / 中立 / 負向),並提供信心度。",
|
60 |
+
theme="compact"
|
61 |
+
)
|
62 |
+
|
63 |
+
# 啟動 Web 應用
|
64 |
+
iface.launch()
|