GuglielmoTor commited on
Commit
d0c3617
Β·
verified Β·
1 Parent(s): bff5b73

Update mentions_dashboard.py

Browse files
Files changed (1) hide show
  1. mentions_dashboard.py +62 -39
mentions_dashboard.py CHANGED
@@ -1,27 +1,36 @@
1
- import json
2
  import time
3
- import re
4
- import os
5
  from datetime import datetime
6
-
7
  from urllib.parse import quote
8
- from requests_oauthlib import OAuth2Session
9
- from textblob import TextBlob
10
  import matplotlib.pyplot as plt
 
11
 
12
  from sessions import create_session
13
 
 
 
14
 
15
  def extract_text_from_commentary(commentary):
 
16
  return re.sub(r"{.*?}", "", commentary).strip()
17
 
18
-
19
- def analyze_sentiment(text):
20
- return TextBlob(text).sentiment.polarity
21
-
 
 
 
 
 
 
 
 
 
 
22
 
23
  def generate_mentions_dashboard(comm_client_id, comm_token_dict):
24
-
25
  org_urn = "urn:li:organization:19010008"
26
  encoded_urn = quote(org_urn, safe='')
27
 
@@ -40,7 +49,6 @@ def generate_mentions_dashboard(comm_client_id, comm_token_dict):
40
 
41
  all_notifications = []
42
  start = 0
43
-
44
  while True:
45
  url = f"{base_url}&start={start}"
46
  resp = session.get(url)
@@ -57,7 +65,6 @@ def generate_mentions_dashboard(comm_client_id, comm_token_dict):
57
  start += len(elements)
58
  time.sleep(0.5)
59
 
60
- # Extract mentions and their share URNs
61
  mention_shares = [e.get("generatedActivity") for e in all_notifications if e.get("action") == "SHARE_MENTION"]
62
  mention_data = []
63
 
@@ -77,44 +84,60 @@ def generate_mentions_dashboard(comm_client_id, comm_token_dict):
77
  continue
78
 
79
  commentary = extract_text_from_commentary(commentary_raw)
80
- sentiment = analyze_sentiment(commentary)
81
  timestamp = post.get("createdAt", 0)
82
  dt = datetime.fromtimestamp(timestamp / 1000.0)
83
 
84
  mention_data.append({
85
  "date": dt,
86
  "text": commentary,
87
- "sentiment": sentiment
88
  })
89
 
90
- # Save HTML
91
- html_parts = ["<h2 style='text-align:center;'>πŸ“£ Mentions Sentiment Dashboard</h2>"]
 
 
 
92
  for mention in mention_data:
 
93
  html_parts.append(f"""
94
- <div style='border:1px solid #ccc; border-radius:10px; padding:15px; margin:10px;'>
95
- <p><strong>Date:</strong> {mention["date"].strftime('%Y-%m-%d')}</p>
96
- <p>{mention["text"]}</p>
97
- <p><strong>Sentiment:</strong> {mention["sentiment"]:.2f}</p>
98
  </div>
99
  """)
100
 
101
- html_path = "mentions_dashboard.html"
102
- with open(html_path, "w", encoding="utf-8") as f:
103
- f.write("\n".join(html_parts))
 
 
 
 
104
 
105
- # Plot
106
  if mention_data:
107
- dates = [m["date"] for m in mention_data]
108
- sentiments = [m["sentiment"] for m in mention_data]
109
-
110
- plt.figure(figsize=(10, 5))
111
- plt.plot(dates, sentiments, marker='o', linestyle='-', color='blue')
112
- plt.title("Sentiment Over Time")
113
- plt.xlabel("Date")
114
- plt.ylabel("Sentiment")
115
- plt.grid(True)
116
- plt.tight_layout()
117
- plt.savefig("mentions_sentiment_plot.png")
118
- plt.close()
119
-
120
- return html_path
 
 
 
 
 
 
 
 
 
 
 
1
  import time
 
 
2
  from datetime import datetime
3
+ from collections import defaultdict
4
  from urllib.parse import quote
5
+
 
6
  import matplotlib.pyplot as plt
7
+ from transformers import pipeline
8
 
9
  from sessions import create_session
10
 
11
+ # Load transformer-based sentiment model globally
12
+ sentiment_pipeline = pipeline("text-classification", model="tabularisai/multilingual-sentiment-analysis")
13
 
14
  def extract_text_from_commentary(commentary):
15
+ import re
16
  return re.sub(r"{.*?}", "", commentary).strip()
17
 
18
+ def classify_sentiment(text):
19
+ try:
20
+ result = sentiment_pipeline(text[:512]) # Limit to 512 chars for transformers
21
+ label = result[0]['label'].upper()
22
+ if label in ['POSITIVE', 'VERY POSITIVE']:
23
+ return 'Positive πŸ‘'
24
+ elif label in ['NEGATIVE', 'VERY NEGATIVE']:
25
+ return 'Negative πŸ‘Ž'
26
+ elif label == 'NEUTRAL':
27
+ return 'Neutral 😐'
28
+ else:
29
+ return 'Unknown'
30
+ except Exception as e:
31
+ return 'Error'
32
 
33
  def generate_mentions_dashboard(comm_client_id, comm_token_dict):
 
34
  org_urn = "urn:li:organization:19010008"
35
  encoded_urn = quote(org_urn, safe='')
36
 
 
49
 
50
  all_notifications = []
51
  start = 0
 
52
  while True:
53
  url = f"{base_url}&start={start}"
54
  resp = session.get(url)
 
65
  start += len(elements)
66
  time.sleep(0.5)
67
 
 
68
  mention_shares = [e.get("generatedActivity") for e in all_notifications if e.get("action") == "SHARE_MENTION"]
69
  mention_data = []
70
 
 
84
  continue
85
 
86
  commentary = extract_text_from_commentary(commentary_raw)
87
+ sentiment_label = classify_sentiment(commentary)
88
  timestamp = post.get("createdAt", 0)
89
  dt = datetime.fromtimestamp(timestamp / 1000.0)
90
 
91
  mention_data.append({
92
  "date": dt,
93
  "text": commentary,
94
+ "sentiment": sentiment_label
95
  })
96
 
97
+ # --- HTML rendering ---
98
+ html_parts = [
99
+ "<h2 style='text-align:center;'>πŸ“£ Mentions Sentiment Dashboard</h2>"
100
+ ]
101
+
102
  for mention in mention_data:
103
+ short_text = (mention["text"][:200] + "…") if len(mention["text"]) > 200 else mention["text"]
104
  html_parts.append(f"""
105
+ <div style='border:1px solid #ddd; border-radius:12px; padding:15px; margin:15px; box-shadow:2px 2px 8px rgba(0,0,0,0.05); background:#fafafa;'>
106
+ <p><strong>πŸ“… Date:</strong> {mention["date"].strftime('%Y-%m-%d')}</p>
107
+ <p style='color:#333;'>{short_text}</p>
108
+ <p><strong>Sentiment:</strong> {mention["sentiment"]}</p>
109
  </div>
110
  """)
111
 
112
+ html_content = "\n".join(html_parts)
113
+
114
+ # --- Plotting ---
115
+ from matplotlib.figure import Figure
116
+ fig = Figure(figsize=(12, 6))
117
+ ax = fig.subplots()
118
+ fig.subplots_adjust(bottom=0.2)
119
 
 
120
  if mention_data:
121
+ # Sort by date
122
+ mention_data.sort(key=lambda x: x["date"])
123
+
124
+ date_labels = [m["date"].strftime('%Y-%m-%d') for m in mention_data]
125
+ sentiment_scores = [1 if m["sentiment"] == "Positive πŸ‘" else
126
+ -1 if m["sentiment"] == "Negative πŸ‘Ž" else
127
+ 0 for m in mention_data]
128
+
129
+ ax.plot(date_labels, sentiment_scores, marker='o', linestyle='-', color='#0073b1')
130
+ ax.set_title("πŸ“Š Mention Sentiment Over Time")
131
+ ax.set_xlabel("Date")
132
+ ax.set_ylabel("Sentiment Score (1=πŸ‘, 0=😐, -1=οΏ½οΏ½οΏ½οΏ½)")
133
+ ax.tick_params(axis='x', rotation=45)
134
+ ax.grid(True, linestyle='--', alpha=0.6)
135
+ ax.set_ylim([-1.2, 1.2])
136
+ else:
137
+ ax.text(0.5, 0.5, "No mention sentiment data available.",
138
+ ha='center', va='center', transform=ax.transAxes, fontsize=12, color='grey')
139
+ ax.set_xticks([])
140
+ ax.set_yticks([])
141
+ ax.set_title("πŸ“Š Mention Sentiment Over Time")
142
+
143
+ return html_content, fig