Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,6 @@
|
|
| 4 |
import snscrape.modules.twitter as sntwitter
|
| 5 |
import pandas as pd
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
-
from transformers import pipeline
|
| 8 |
import matplotlib.pyplot as plt
|
| 9 |
import io
|
| 10 |
import base64
|
|
@@ -27,12 +26,17 @@ history_file = "history_sentiment.csv"
|
|
| 27 |
max_retries = 3 # 貼文抓取失敗重試次數
|
| 28 |
|
| 29 |
# -----------------------------
|
| 30 |
-
#
|
| 31 |
# -----------------------------
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
model="uer/roberta-base-finetuned-sentiment-chinese"
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
# -----------------------------
|
| 38 |
# 主分析函數
|
|
@@ -59,8 +63,8 @@ def run_analysis():
|
|
| 59 |
time.sleep(3)
|
| 60 |
df_tweets = pd.DataFrame(all_tweets, columns=["日期", "使用者", "內容", "候選人"])
|
| 61 |
# 2. 情緒分析
|
| 62 |
-
df_tweets['情緒'] = df_tweets['內容'].apply(lambda x: sentiment(x)[
|
| 63 |
-
df_tweets['信心度'] = df_tweets['內容'].apply(lambda x: sentiment(x)[
|
| 64 |
# 統計每位候選人情緒比例
|
| 65 |
summary = df_tweets.groupby(['候選人', '情緒']).size().unstack(fill_value=0)
|
| 66 |
summary['總貼文'] = summary.sum(axis=1)
|
|
|
|
| 4 |
import snscrape.modules.twitter as sntwitter
|
| 5 |
import pandas as pd
|
| 6 |
from datetime import datetime, timedelta
|
|
|
|
| 7 |
import matplotlib.pyplot as plt
|
| 8 |
import io
|
| 9 |
import base64
|
|
|
|
| 26 |
max_retries = 3 # 貼文抓取失敗重試次數
|
| 27 |
|
| 28 |
# -----------------------------
|
| 29 |
+
# 情緒分析模型 (嘗試加載 transformers,若失敗則使用預設值)
|
| 30 |
# -----------------------------
|
| 31 |
+
try:
|
| 32 |
+
from transformers import pipeline
|
| 33 |
+
sentiment = pipeline("sentiment-analysis", model="uer/roberta-base-finetuned-sentiment-chinese")
|
| 34 |
+
except ImportError as e:
|
| 35 |
+
print(f"⚠️ 警告: {e}. 情緒分析將使用預設值 (positive/negative 隨機分配)。")
|
| 36 |
+
def sentiment_dummy(text):
|
| 37 |
+
import random
|
| 38 |
+
return [{"label": random.choice(["positive", "negative"]), "score": 0.5}][0]
|
| 39 |
+
sentiment = sentiment_dummy
|
| 40 |
|
| 41 |
# -----------------------------
|
| 42 |
# 主分析函數
|
|
|
|
| 63 |
time.sleep(3)
|
| 64 |
df_tweets = pd.DataFrame(all_tweets, columns=["日期", "使用者", "內容", "候選人"])
|
| 65 |
# 2. 情緒分析
|
| 66 |
+
df_tweets['情緒'] = df_tweets['內容'].apply(lambda x: sentiment(x)['label'])
|
| 67 |
+
df_tweets['信心度'] = df_tweets['內容'].apply(lambda x: sentiment(x)['score'])
|
| 68 |
# 統計每位候選人情緒比例
|
| 69 |
summary = df_tweets.groupby(['候選人', '情緒']).size().unstack(fill_value=0)
|
| 70 |
summary['總貼文'] = summary.sum(axis=1)
|