Spaces:
Running
Running
Update analytics_fetch_and_rendering.py
Browse files
analytics_fetch_and_rendering.py
CHANGED
@@ -10,6 +10,7 @@ from sessions import create_session
|
|
10 |
from error_handling import display_error
|
11 |
|
12 |
from Data_Fetching_and_Rendering import fetch_posts_and_stats
|
|
|
13 |
|
14 |
import logging
|
15 |
|
@@ -311,6 +312,79 @@ def plot_eb_content_ratio(data):
|
|
311 |
plt.tight_layout()
|
312 |
return fig
|
313 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
314 |
|
315 |
def fetch_and_render_analytics(client_id, token):
|
316 |
loading = gr.update(value="<p>Loading follower count...</p>", visible=True)
|
@@ -326,6 +400,9 @@ def fetch_and_render_analytics(client_id, token):
|
|
326 |
engagement_data = compute_monthly_avg_engagement_rate(posts)
|
327 |
interaction_data = compute_post_interaction_metrics(posts)
|
328 |
eb_data = compute_eb_content_ratio(posts)
|
|
|
|
|
|
|
329 |
|
330 |
|
331 |
|
@@ -337,7 +414,7 @@ def fetch_and_render_analytics(client_id, token):
|
|
337 |
<p style='font-size:0.9em; color:#777;'>(As of latest data)</p>
|
338 |
</div>
|
339 |
"""
|
340 |
-
return gr.update(value=count_html, visible=True), gr.update(value=plot_follower_gains(gains), visible=True), gr.update(value=plot_growth_rate(gains, count), visible=True), gr.update(value=plot_avg_engagement_rate(engagement_data), visible=True), gr.update(value=plot_interaction_metrics(interaction_data), visible=True), gr.update(value=plot_eb_content_ratio(eb_data), visible=True)
|
341 |
|
342 |
except Exception as e:
|
343 |
error = display_error("Analytics load failed.", e).get('value', "<p style='color:red;'>Error loading data.</p>")
|
|
|
10 |
from error_handling import display_error
|
11 |
|
12 |
from Data_Fetching_and_Rendering import fetch_posts_and_stats
|
13 |
+
from mentions_dashboard import generate_mentions_dashboard
|
14 |
|
15 |
import logging
|
16 |
|
|
|
312 |
plt.tight_layout()
|
313 |
return fig
|
314 |
|
315 |
+
def compute_mention_metrics(mention_data):
|
316 |
+
if not mention_data:
|
317 |
+
return [], []
|
318 |
+
|
319 |
+
monthly_stats = defaultdict(lambda: {"positive": 0, "negative": 0, "neutral": 0, "total": 0})
|
320 |
+
|
321 |
+
for m in mention_data:
|
322 |
+
month = m["date"].strftime("%Y-%m")
|
323 |
+
sentiment = m["sentiment"]
|
324 |
+
monthly_stats[month]["total"] += 1
|
325 |
+
if "Positive" in sentiment:
|
326 |
+
monthly_stats[month]["positive"] += 1
|
327 |
+
elif "Negative" in sentiment:
|
328 |
+
monthly_stats[month]["negative"] += 1
|
329 |
+
elif "Neutral" in sentiment:
|
330 |
+
monthly_stats[month]["neutral"] += 1
|
331 |
+
|
332 |
+
volume_data = []
|
333 |
+
sentiment_data = []
|
334 |
+
sorted_months = sorted(monthly_stats.keys())
|
335 |
+
|
336 |
+
for i, month in enumerate(sorted_months):
|
337 |
+
stats = monthly_stats[month]
|
338 |
+
positive = stats["positive"]
|
339 |
+
negative = stats["negative"]
|
340 |
+
total = stats["total"]
|
341 |
+
|
342 |
+
sentiment_score = ((positive / total) * 100 - (negative / total) * 100) if total else 0
|
343 |
+
sentiment_ratio = (positive / negative) if negative else float('inf')
|
344 |
+
|
345 |
+
sentiment_data.append({
|
346 |
+
"month": month,
|
347 |
+
"score": round(sentiment_score, 2),
|
348 |
+
"ratio": round(sentiment_ratio, 2) if sentiment_ratio != float('inf') else None
|
349 |
+
})
|
350 |
+
|
351 |
+
prev_total = monthly_stats[sorted_months[i - 1]]["total"] if i > 0 else 0
|
352 |
+
change = (((total - prev_total) / prev_total) * 100) if prev_total else None
|
353 |
+
volume_data.append({"month": month, "count": total, "change": round(change, 2) if change is not None else None})
|
354 |
+
|
355 |
+
return volume_data, sentiment_data
|
356 |
+
|
357 |
+
def plot_mention_volume_trend(volume_data):
|
358 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
359 |
+
if not volume_data:
|
360 |
+
ax.text(0.5, 0.5, 'No Mention Volume Data.', ha='center', va='center', transform=ax.transAxes)
|
361 |
+
ax.set_title('Mention Volume Over Time')
|
362 |
+
return fig
|
363 |
+
|
364 |
+
months = [d["month"] for d in volume_data]
|
365 |
+
counts = [d["count"] for d in volume_data]
|
366 |
+
ax.plot(months, counts, marker='o', linestyle='-', color="#1f77b4")
|
367 |
+
ax.set(title="Monthly Mention Volume", xlabel="Month", ylabel="Mentions")
|
368 |
+
ax.tick_params(axis='x', rotation=45)
|
369 |
+
plt.tight_layout()
|
370 |
+
return fig
|
371 |
+
|
372 |
+
def plot_mention_sentiment_score(sentiment_data):
|
373 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
374 |
+
if not sentiment_data:
|
375 |
+
ax.text(0.5, 0.5, 'No Sentiment Score Data.', ha='center', va='center', transform=ax.transAxes)
|
376 |
+
ax.set_title('Mention Sentiment Score')
|
377 |
+
return fig
|
378 |
+
|
379 |
+
months = [d["month"] for d in sentiment_data]
|
380 |
+
scores = [d["score"] for d in sentiment_data]
|
381 |
+
ax.plot(months, scores, marker='o', linestyle='-', color="#ff7f0e")
|
382 |
+
ax.set(title="Monthly Sentiment Score (% Positive - % Negative)", xlabel="Month", ylabel="Score")
|
383 |
+
ax.axhline(0, color='gray', linestyle='--', linewidth=1)
|
384 |
+
ax.tick_params(axis='x', rotation=45)
|
385 |
+
plt.tight_layout()
|
386 |
+
return fig
|
387 |
+
|
388 |
|
389 |
def fetch_and_render_analytics(client_id, token):
|
390 |
loading = gr.update(value="<p>Loading follower count...</p>", visible=True)
|
|
|
400 |
engagement_data = compute_monthly_avg_engagement_rate(posts)
|
401 |
interaction_data = compute_post_interaction_metrics(posts)
|
402 |
eb_data = compute_eb_content_ratio(posts)
|
403 |
+
html, fig, mention_data = generate_mentions_dashboard(client_id, token_dict)
|
404 |
+
volume_data, sentiment_data = compute_mention_metrics(mention_data)
|
405 |
+
|
406 |
|
407 |
|
408 |
|
|
|
414 |
<p style='font-size:0.9em; color:#777;'>(As of latest data)</p>
|
415 |
</div>
|
416 |
"""
|
417 |
+
return gr.update(value=count_html, visible=True), gr.update(value=plot_follower_gains(gains), visible=True), gr.update(value=plot_growth_rate(gains, count), visible=True), gr.update(value=plot_avg_engagement_rate(engagement_data), visible=True), gr.update(value=plot_interaction_metrics(interaction_data), visible=True), gr.update(value=plot_eb_content_ratio(eb_data), visible=True), gr.update(value=plot_mention_volume_trend(volume_data), visible=True), gr.update(value=plot_mention_sentiment_score(sentiment_data), visible=True)
|
418 |
|
419 |
except Exception as e:
|
420 |
error = display_error("Analytics load failed.", e).get('value', "<p style='color:red;'>Error loading data.</p>")
|