Spaces:
Running
Running
Update mentions_dashboard.py
Browse files- 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 |
-
|
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 |
-
|
20 |
-
|
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 |
-
|
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":
|
88 |
})
|
89 |
|
90 |
-
#
|
91 |
-
html_parts = [
|
|
|
|
|
|
|
92 |
for mention in mention_data:
|
|
|
93 |
html_parts.append(f"""
|
94 |
-
<div style='border:1px solid #
|
95 |
-
<p><strong
|
96 |
-
<p>{
|
97 |
-
<p><strong>Sentiment:</strong> {mention["sentiment"]
|
98 |
</div>
|
99 |
""")
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
|
|
|
|
|
|
|
|
|
104 |
|
105 |
-
# Plot
|
106 |
if mention_data:
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|