shiue2000 commited on
Commit
fb7598d
·
verified ·
1 Parent(s): 10ead86

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -3
app.py CHANGED
@@ -8,6 +8,10 @@ import random
8
  import networkx as nx
9
  from datetime import datetime, timedelta
10
  import gradio as gr
 
 
 
 
11
 
12
  # 中文顯示設置
13
  plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'Arial Unicode MS', 'SimHei', 'DejaVu Sans']
@@ -24,12 +28,17 @@ history_file = "history_sentiment.csv"
24
  try:
25
  from transformers import pipeline
26
  sentiment_pipeline = pipeline("sentiment-analysis", model="lxyuan/distilbert-base-multilingual-cased-sentiments-student")
27
- def sentiment(text): return sentiment_pipeline(text)[0]
 
 
28
  except:
29
- def sentiment(text): return {"label": random.choice(["positive", "negative"]), "score": 0.5}
 
 
30
 
31
  # 模擬抓貼文
32
  def fetch_tweets(candidate):
 
33
  return pd.DataFrame([
34
  {
35
  "日期": datetime.now() - timedelta(days=random.randint(0, days_back - 1)),
@@ -52,7 +61,14 @@ def plot_to_base64(fig):
52
  # 主分析函數
53
  def run_analysis():
54
  try:
 
 
 
 
 
 
55
  # 抓貼文與情緒分析
 
56
  all_df = pd.concat([fetch_tweets(c) for c in candidates], ignore_index=True)
57
  all_df['情緒'] = all_df['內容'].apply(lambda x: sentiment(x)['label'])
58
  all_df['信心度'] = all_df['內容'].apply(lambda x: sentiment(x)['score'])
@@ -170,8 +186,10 @@ def run_analysis():
170
  """
171
 
172
  # HTML template
173
- with open("templates/index.html", encoding='utf-8') as f:
 
174
  html_template = f.read()
 
175
  html_content = html_template.format(
176
  report_date=datetime.now().strftime('%Y-%m-%d %H:%M'),
177
  img_b64_today=img_b64_today,
@@ -185,11 +203,14 @@ def run_analysis():
185
  news_summary=news_summary,
186
  news_table=news_table
187
  )
 
188
  return html_content
189
  except Exception as e:
 
190
  return f"<pre>❌ 輿情分析執行失敗:\n{traceback.format_exc()}</pre>"
191
 
192
  # Gradio 前端
193
  if __name__ == "__main__":
 
194
  iface = gr.Interface(fn=run_analysis, inputs=[], outputs=gr.HTML(), title="高雄市長選戰輿情分析")
195
  iface.launch(server_name="0.0.0.0", server_port=7860)
 
8
  import networkx as nx
9
  from datetime import datetime, timedelta
10
  import gradio as gr
11
+ import logging
12
+
13
+ # 設置日誌
14
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
15
 
16
  # 中文顯示設置
17
  plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'Arial Unicode MS', 'SimHei', 'DejaVu Sans']
 
28
  try:
29
  from transformers import pipeline
30
  sentiment_pipeline = pipeline("sentiment-analysis", model="lxyuan/distilbert-base-multilingual-cased-sentiments-student")
31
+ def sentiment(text):
32
+ logging.info(f"Performing sentiment analysis on text: {text[:50]}...")
33
+ return sentiment_pipeline(text)[0]
34
  except:
35
+ def sentiment(text):
36
+ logging.warning("Sentiment model failed to load, using random fallback.")
37
+ return {"label": random.choice(["positive", "negative"]), "score": 0.5}
38
 
39
  # 模擬抓貼文
40
  def fetch_tweets(candidate):
41
+ logging.info(f"Fetching tweets for candidate: {candidate}")
42
  return pd.DataFrame([
43
  {
44
  "日期": datetime.now() - timedelta(days=random.randint(0, days_back - 1)),
 
61
  # 主分析函數
62
  def run_analysis():
63
  try:
64
+ # 檢查模板檔案
65
+ template_path = "templates/index.html"
66
+ if not os.path.exists(template_path):
67
+ logging.error(f"Template file {template_path} not found.")
68
+ return f"<pre>❌ 模板檔案 {template_path} 不存在</pre>"
69
+
70
  # 抓貼文與情緒分析
71
+ logging.info("Fetching and analyzing tweets...")
72
  all_df = pd.concat([fetch_tweets(c) for c in candidates], ignore_index=True)
73
  all_df['情緒'] = all_df['內容'].apply(lambda x: sentiment(x)['label'])
74
  all_df['信心度'] = all_df['內容'].apply(lambda x: sentiment(x)['score'])
 
186
  """
187
 
188
  # HTML template
189
+ logging.info(f"Loading template from {template_path}")
190
+ with open(template_path, encoding='utf-8') as f:
191
  html_template = f.read()
192
+ logging.info("Formatting HTML template...")
193
  html_content = html_template.format(
194
  report_date=datetime.now().strftime('%Y-%m-%d %H:%M'),
195
  img_b64_today=img_b64_today,
 
203
  news_summary=news_summary,
204
  news_table=news_table
205
  )
206
+ logging.info("HTML content generated successfully.")
207
  return html_content
208
  except Exception as e:
209
+ logging.error(f"Analysis failed: {str(e)}")
210
  return f"<pre>❌ 輿情分析執行失敗:\n{traceback.format_exc()}</pre>"
211
 
212
  # Gradio 前端
213
  if __name__ == "__main__":
214
+ logging.info("Starting Gradio interface...")
215
  iface = gr.Interface(fn=run_analysis, inputs=[], outputs=gr.HTML(), title="高雄市長選戰輿情分析")
216
  iface.launch(server_name="0.0.0.0", server_port=7860)