GuglielmoTor commited on
Commit
020aa7b
·
verified ·
1 Parent(s): 6923fc7

Update analytics_data_processing.py

Browse files
Files changed (1) hide show
  1. analytics_data_processing.py +346 -0
analytics_data_processing.py CHANGED
@@ -1,6 +1,7 @@
1
  import pandas as pd
2
  from datetime import datetime, timedelta, time
3
  import logging
 
4
 
5
  # Configure logging for this module
6
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
@@ -154,3 +155,348 @@ def prepare_filtered_analytics_data(token_state_value, date_filter_option, custo
154
  logging.info(f"Processed - Filtered Merged Posts: {len(filtered_merged_posts_data)} rows, Filtered Mentions: {len(filtered_mentions_data)} rows, Date-Filtered Follower Stats: {len(date_filtered_follower_stats_df)} rows.")
155
 
156
  return filtered_merged_posts_data, filtered_mentions_data, date_filtered_follower_stats_df, raw_follower_stats_df, start_dt_filter, end_dt_filter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pandas as pd
2
  from datetime import datetime, timedelta, time
3
  import logging
4
+ import numpy as np
5
 
6
  # Configure logging for this module
7
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
 
155
  logging.info(f"Processed - Filtered Merged Posts: {len(filtered_merged_posts_data)} rows, Filtered Mentions: {len(filtered_mentions_data)} rows, Date-Filtered Follower Stats: {len(date_filtered_follower_stats_df)} rows.")
156
 
157
  return filtered_merged_posts_data, filtered_mentions_data, date_filtered_follower_stats_df, raw_follower_stats_df, start_dt_filter, end_dt_filter
158
+
159
+ # --- Helper function to generate textual data summaries for chatbot ---
160
+ def generate_chatbot_data_summaries(
161
+ plot_configs_list,
162
+ filtered_merged_posts_df,
163
+ filtered_mentions_df,
164
+ date_filtered_follower_stats_df, # Expected to contain 'follower_gains_monthly'
165
+ raw_follower_stats_df, # Expected to contain other demographics like 'follower_geo', 'follower_industry'
166
+ token_state_value
167
+ ):
168
+ """
169
+ Generates textual summaries for each plot ID to be used by the chatbot,
170
+ based on the corrected understanding of DataFrame structures and follower count columns.
171
+ """
172
+ data_summaries = {}
173
+
174
+ # --- Date and Config Columns from token_state ---
175
+ # For Posts
176
+ date_col_posts = token_state_value.get("config_date_col_posts", "published_at")
177
+ media_type_col_name = token_state_value.get("config_media_type_col", "media_type")
178
+ eb_labels_col_name = token_state_value.get("config_eb_labels_col", "li_eb_label")
179
+ # For Mentions
180
+ date_col_mentions = token_state_value.get("config_date_col_mentions", "date")
181
+ mentions_sentiment_col = "sentiment_label" # As per user's mention df structure
182
+
183
+ # For Follower Stats - Actual column names provided by user
184
+ follower_count_organic_col = "follower_count_organic"
185
+ follower_count_paid_col = "follower_count_paid"
186
+
187
+ # For Follower Stats (Demographics from raw_follower_stats_df)
188
+ follower_demographics_type_col = "follower_count_type" # Column indicating 'follower_geo', 'follower_industry'
189
+ follower_demographics_category_col = "category_name" # Column indicating 'USA', 'Technology'
190
+
191
+ # For Follower Gains/Growth (from date_filtered_follower_stats_df)
192
+ follower_gains_type_col = "follower_count_type" # Should be 'follower_gains_monthly'
193
+ follower_gains_date_col = "category_name" # This is 'YYYY-MM-DD'
194
+
195
+ # --- Helper: Safely convert to datetime ---
196
+ def safe_to_datetime(series, errors='coerce'):
197
+ return pd.to_datetime(series, errors=errors)
198
+
199
+ # --- Prepare DataFrames (copy and convert dates) ---
200
+ if filtered_merged_posts_df is not None and not filtered_merged_posts_df.empty:
201
+ posts_df = filtered_merged_posts_df.copy()
202
+ if date_col_posts in posts_df.columns:
203
+ posts_df[date_col_posts] = safe_to_datetime(posts_df[date_col_posts])
204
+ else:
205
+ logging.warning(f"Date column '{date_col_posts}' not found in posts_df for chatbot summary.")
206
+ else:
207
+ posts_df = pd.DataFrame()
208
+
209
+ if filtered_mentions_df is not None and not filtered_mentions_df.empty:
210
+ mentions_df = filtered_mentions_df.copy()
211
+ if date_col_mentions in mentions_df.columns:
212
+ mentions_df[date_col_mentions] = safe_to_datetime(mentions_df[date_col_mentions])
213
+ else:
214
+ logging.warning(f"Date column '{date_col_mentions}' not found in mentions_df for chatbot summary.")
215
+ else:
216
+ mentions_df = pd.DataFrame()
217
+
218
+ # For date_filtered_follower_stats_df (monthly gains)
219
+ if date_filtered_follower_stats_df is not None and not date_filtered_follower_stats_df.empty:
220
+ follower_monthly_df = date_filtered_follower_stats_df.copy()
221
+ if follower_gains_type_col in follower_monthly_df.columns:
222
+ follower_monthly_df = follower_monthly_df[follower_monthly_df[follower_gains_type_col] == 'follower_gains_monthly'].copy()
223
+
224
+ if follower_gains_date_col in follower_monthly_df.columns:
225
+ follower_monthly_df['datetime_obj'] = safe_to_datetime(follower_monthly_df[follower_gains_date_col])
226
+ follower_monthly_df = follower_monthly_df.dropna(subset=['datetime_obj'])
227
+
228
+ # Calculate total gains
229
+ if follower_count_organic_col in follower_monthly_df.columns and follower_count_paid_col in follower_monthly_df.columns:
230
+ follower_monthly_df[follower_count_organic_col] = pd.to_numeric(follower_monthly_df[follower_count_organic_col], errors='coerce').fillna(0)
231
+ follower_monthly_df[follower_count_paid_col] = pd.to_numeric(follower_monthly_df[follower_count_paid_col], errors='coerce').fillna(0)
232
+ follower_monthly_df['total_monthly_gains'] = follower_monthly_df[follower_count_organic_col] + follower_monthly_df[follower_count_paid_col]
233
+ elif follower_count_organic_col in follower_monthly_df.columns: # Only organic exists
234
+ follower_monthly_df[follower_count_organic_col] = pd.to_numeric(follower_monthly_df[follower_count_organic_col], errors='coerce').fillna(0)
235
+ follower_monthly_df['total_monthly_gains'] = follower_monthly_df[follower_count_organic_col]
236
+ elif follower_count_paid_col in follower_monthly_df.columns: # Only paid exists
237
+ follower_monthly_df[follower_count_paid_col] = pd.to_numeric(follower_monthly_df[follower_count_paid_col], errors='coerce').fillna(0)
238
+ follower_monthly_df['total_monthly_gains'] = follower_monthly_df[follower_count_paid_col]
239
+ else:
240
+ logging.warning(f"Neither '{follower_count_organic_col}' nor '{follower_count_paid_col}' found in follower_monthly_df for total gains calculation.")
241
+ follower_monthly_df['total_monthly_gains'] = 0 # Avoid KeyError later
242
+ else:
243
+ logging.warning(f"Date column '{follower_gains_date_col}' (from category_name) not found in follower_monthly_df for chatbot summary.")
244
+ if 'datetime_obj' not in follower_monthly_df.columns:
245
+ follower_monthly_df['datetime_obj'] = pd.NaT
246
+ if 'total_monthly_gains' not in follower_monthly_df.columns:
247
+ follower_monthly_df['total_monthly_gains'] = 0
248
+ else:
249
+ follower_monthly_df = pd.DataFrame(columns=[follower_gains_date_col, 'total_monthly_gains', 'datetime_obj'])
250
+
251
+
252
+ if raw_follower_stats_df is not None and not raw_follower_stats_df.empty:
253
+ follower_demographics_df = raw_follower_stats_df.copy()
254
+ # Calculate total followers for demographics
255
+ if follower_count_organic_col in follower_demographics_df.columns and follower_count_paid_col in follower_demographics_df.columns:
256
+ follower_demographics_df[follower_count_organic_col] = pd.to_numeric(follower_demographics_df[follower_count_organic_col], errors='coerce').fillna(0)
257
+ follower_demographics_df[follower_count_paid_col] = pd.to_numeric(follower_demographics_df[follower_count_paid_col], errors='coerce').fillna(0)
258
+ follower_demographics_df['total_follower_count'] = follower_demographics_df[follower_count_organic_col] + follower_demographics_df[follower_count_paid_col]
259
+ elif follower_count_organic_col in follower_demographics_df.columns:
260
+ follower_demographics_df[follower_count_organic_col] = pd.to_numeric(follower_demographics_df[follower_count_organic_col], errors='coerce').fillna(0)
261
+ follower_demographics_df['total_follower_count'] = follower_demographics_df[follower_count_organic_col]
262
+ elif follower_count_paid_col in follower_demographics_df.columns:
263
+ follower_demographics_df[follower_count_paid_col] = pd.to_numeric(follower_demographics_df[follower_count_paid_col], errors='coerce').fillna(0)
264
+ follower_demographics_df['total_follower_count'] = follower_demographics_df[follower_count_paid_col]
265
+ else:
266
+ logging.warning(f"Neither '{follower_count_organic_col}' nor '{follower_count_paid_col}' found in follower_demographics_df for total count calculation.")
267
+ if 'total_follower_count' not in follower_demographics_df.columns:
268
+ follower_demographics_df['total_follower_count'] = 0
269
+ else:
270
+ follower_demographics_df = pd.DataFrame()
271
+
272
+
273
+ for plot_cfg in plot_configs_list:
274
+ plot_id = plot_cfg["id"]
275
+ plot_label = plot_cfg["label"]
276
+ summary_text = f"No specific data summary available for '{plot_label}' for the selected period."
277
+
278
+ try:
279
+ # --- FOLLOWER STATS ---
280
+ if plot_id == "followers_count": # Uses follower_monthly_df
281
+ if not follower_monthly_df.empty and 'total_monthly_gains' in follower_monthly_df.columns and 'datetime_obj' in follower_monthly_df.columns and not follower_monthly_df['datetime_obj'].isnull().all():
282
+ df_summary = follower_monthly_df[['datetime_obj', 'total_monthly_gains']].copy()
283
+ df_summary['datetime_obj'] = df_summary['datetime_obj'].dt.strftime('%Y-%m-%d')
284
+ df_summary.rename(columns={'datetime_obj': 'Date', 'total_monthly_gains': 'Total Monthly Gains'}, inplace=True)
285
+ summary_text = f"Follower Count (Total Monthly Gains):\n{df_summary.sort_values(by='Date').tail(5).to_string(index=False)}"
286
+ else:
287
+ summary_text = f"Follower count data (total monthly gains) is unavailable or incomplete for '{plot_label}'."
288
+
289
+ elif plot_id == "followers_growth_rate": # Uses follower_monthly_df
290
+ if not follower_monthly_df.empty and 'total_monthly_gains' in follower_monthly_df.columns and 'datetime_obj' in follower_monthly_df.columns and not follower_monthly_df['datetime_obj'].isnull().all():
291
+ df_calc = follower_monthly_df.sort_values(by='datetime_obj').copy()
292
+ # Growth rate is calculated on the total monthly gains (which are changes, not cumulative counts)
293
+ # To calculate growth rate of followers, we'd need cumulative follower count.
294
+ # The plot logic also uses pct_change on the gains themselves.
295
+ # If 'total_monthly_gains' represents the *change* in followers, then pct_change on this is rate of change of gains.
296
+ # If it represents the *cumulative* followers at that point, then pct_change is follower growth rate.
297
+ # Assuming 'total_monthly_gains' is the *change* for the month, like the plot logic.
298
+ df_calc['total_monthly_gains'] = pd.to_numeric(df_calc['total_monthly_gains'], errors='coerce')
299
+ if len(df_calc) >= 2:
300
+ # Calculate cumulative sum to get follower count if 'total_monthly_gains' are indeed just gains
301
+ # If your 'total_monthly_gains' already IS the total follower count at end of month, remove next line
302
+ # For now, assuming it's GAINS, so we need cumulative for growth rate of total followers.
303
+ # However, the original plot logic applies pct_change directly to 'follower_gains_monthly'.
304
+ # Let's stick to pct_change on the gains/count column for consistency with plot.
305
+
306
+ # If 'total_monthly_gains' is the actual follower count for that month:
307
+ df_calc['growth_rate_monthly'] = df_calc['total_monthly_gains'].pct_change() * 100
308
+ df_calc['growth_rate_monthly'] = df_calc['growth_rate_monthly'].round(2)
309
+ df_calc.replace([np.inf, -np.inf], np.nan, inplace=True) # Handle division by zero if a gain was 0
310
+
311
+ df_summary = df_calc[['datetime_obj', 'growth_rate_monthly']].dropna().copy()
312
+ df_summary['datetime_obj'] = df_summary['datetime_obj'].dt.strftime('%Y-%m-%d')
313
+ df_summary.rename(columns={'datetime_obj': 'Date', 'growth_rate_monthly': 'Growth Rate (%)'}, inplace=True)
314
+ if not df_summary.empty:
315
+ summary_text = f"Follower Growth Rate (Monthly % based on Total Follower Count/Gains):\n{df_summary.sort_values(by='Date').tail(5).to_string(index=False)}"
316
+ else:
317
+ summary_text = f"Not enough data points or valid transitions to calculate follower growth rate for '{plot_label}'."
318
+ else:
319
+ summary_text = f"Not enough data points (need at least 2) to calculate follower growth rate for '{plot_label}'."
320
+ else:
321
+ summary_text = f"Follower growth rate data (total monthly gains) is unavailable or incomplete for '{plot_label}'."
322
+
323
+ elif plot_id in ["followers_by_location", "followers_by_role", "followers_by_industry", "followers_by_seniority"]:
324
+ demographic_type_map = {
325
+ "followers_by_location": "follower_geo",
326
+ "followers_by_role": "follower_function",
327
+ "followers_by_industry": "follower_industry",
328
+ "followers_by_seniority": "follower_seniority"
329
+ }
330
+ current_demographic_type = demographic_type_map.get(plot_id)
331
+ if not follower_demographics_df.empty and \
332
+ follower_demographics_type_col in follower_demographics_df.columns and \
333
+ follower_demographics_category_col in follower_demographics_df.columns and \
334
+ 'total_follower_count' in follower_demographics_df.columns: # Check for the calculated total
335
+
336
+ df_filtered_demographics = follower_demographics_df[
337
+ follower_demographics_df[follower_demographics_type_col] == current_demographic_type
338
+ ].copy()
339
+
340
+ if not df_filtered_demographics.empty:
341
+ df_summary = df_filtered_demographics.groupby(follower_demographics_category_col)['total_follower_count'].sum().reset_index()
342
+ df_summary.rename(columns={follower_demographics_category_col: 'Category', 'total_follower_count': 'Total Follower Count'}, inplace=True)
343
+ top_5 = df_summary.nlargest(5, 'Total Follower Count')
344
+ summary_text = f"Top 5 {plot_label} (Total Followers):\n{top_5.to_string(index=False)}"
345
+ else:
346
+ summary_text = f"No data available for demographic type '{current_demographic_type}' in '{plot_label}'."
347
+ else:
348
+ summary_text = f"Follower demographic data columns (including total_follower_count) are missing or incomplete for '{plot_label}'."
349
+
350
+ # --- POSTS STATS ---
351
+ elif plot_id == "engagement_rate":
352
+ if not posts_df.empty and 'engagement' in posts_df.columns and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
353
+ df_resampled = posts_df.set_index(date_col_posts)['engagement'].resample('W').mean().reset_index()
354
+ df_resampled['engagement'] = pd.to_numeric(df_resampled['engagement'], errors='coerce').round(2)
355
+ df_summary = df_resampled[[date_col_posts, 'engagement']].dropna().copy()
356
+ df_summary[date_col_posts] = df_summary[date_col_posts].dt.strftime('%Y-%m-%d')
357
+ summary_text = f"Engagement Rate Over Time (Weekly Avg %):\n{df_summary.sort_values(by=date_col_posts).tail(5).to_string(index=False)}"
358
+ else:
359
+ summary_text = f"Engagement rate data is unavailable for '{plot_label}'."
360
+
361
+ elif plot_id == "reach_over_time":
362
+ if not posts_df.empty and 'reach' in posts_df.columns and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
363
+ df_resampled = posts_df.set_index(date_col_posts)['reach'].resample('W').sum().reset_index()
364
+ df_resampled['reach'] = pd.to_numeric(df_resampled['reach'], errors='coerce')
365
+ df_summary = df_resampled[[date_col_posts, 'reach']].dropna().copy()
366
+ df_summary[date_col_posts] = df_summary[date_col_posts].dt.strftime('%Y-%m-%d')
367
+ summary_text = f"Reach Over Time (Weekly Sum):\n{df_summary.sort_values(by=date_col_posts).tail(5).to_string(index=False)}"
368
+ else:
369
+ summary_text = f"Reach data is unavailable for '{plot_label}'."
370
+
371
+ elif plot_id == "impressions_over_time":
372
+ if not posts_df.empty and 'impressionCount' in posts_df.columns and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
373
+ df_resampled = posts_df.set_index(date_col_posts)['impressionCount'].resample('W').sum().reset_index()
374
+ df_resampled['impressionCount'] = pd.to_numeric(df_resampled['impressionCount'], errors='coerce')
375
+ df_summary = df_resampled[[date_col_posts, 'impressionCount']].dropna().copy()
376
+ df_summary[date_col_posts] = df_summary[date_col_posts].dt.strftime('%Y-%m-%d')
377
+ df_summary.rename(columns={'impressionCount': 'Impressions'}, inplace=True)
378
+ summary_text = f"Impressions Over Time (Weekly Sum):\n{df_summary.sort_values(by=date_col_posts).tail(5).to_string(index=False)}"
379
+ else:
380
+ summary_text = f"Impressions data is unavailable for '{plot_label}'."
381
+
382
+ elif plot_id == "likes_over_time":
383
+ if not posts_df.empty and 'likeCount' in posts_df.columns and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
384
+ df_resampled = posts_df.set_index(date_col_posts)['likeCount'].resample('W').sum().reset_index()
385
+ df_resampled['likeCount'] = pd.to_numeric(df_resampled['likeCount'], errors='coerce')
386
+ df_summary = df_resampled[[date_col_posts, 'likeCount']].dropna().copy()
387
+ df_summary[date_col_posts] = df_summary[date_col_posts].dt.strftime('%Y-%m-%d')
388
+ df_summary.rename(columns={'likeCount': 'Likes'}, inplace=True)
389
+ summary_text = f"Likes Over Time (Weekly Sum):\n{df_summary.sort_values(by=date_col_posts).tail(5).to_string(index=False)}"
390
+ else:
391
+ summary_text = f"Likes data is unavailable for '{plot_label}'."
392
+
393
+ elif plot_id == "clicks_over_time":
394
+ if not posts_df.empty and 'clickCount' in posts_df.columns and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
395
+ df_resampled = posts_df.set_index(date_col_posts)['clickCount'].resample('W').sum().reset_index()
396
+ df_resampled['clickCount'] = pd.to_numeric(df_resampled['clickCount'], errors='coerce')
397
+ df_summary = df_resampled[[date_col_posts, 'clickCount']].dropna().copy()
398
+ df_summary[date_col_posts] = df_summary[date_col_posts].dt.strftime('%Y-%m-%d')
399
+ df_summary.rename(columns={'clickCount': 'Clicks'}, inplace=True)
400
+ summary_text = f"Clicks Over Time (Weekly Sum):\n{df_summary.sort_values(by=date_col_posts).tail(5).to_string(index=False)}"
401
+ else:
402
+ summary_text = f"Clicks data is unavailable for '{plot_label}'."
403
+
404
+ elif plot_id == "shares_over_time":
405
+ if not posts_df.empty and 'shareCount' in posts_df.columns and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
406
+ df_resampled = posts_df.set_index(date_col_posts)['shareCount'].resample('W').sum().reset_index()
407
+ df_resampled['shareCount'] = pd.to_numeric(df_resampled['shareCount'], errors='coerce')
408
+ df_summary = df_resampled[[date_col_posts, 'shareCount']].dropna().copy()
409
+ df_summary[date_col_posts] = df_summary[date_col_posts].dt.strftime('%Y-%m-%d')
410
+ df_summary.rename(columns={'shareCount': 'Shares'}, inplace=True)
411
+ summary_text = f"Shares Over Time (Weekly Sum):\n{df_summary.sort_values(by=date_col_posts).tail(5).to_string(index=False)}"
412
+ elif 'shareCount' not in posts_df.columns and not posts_df.empty : # Check if posts_df is not empty before assuming column is the only issue
413
+ summary_text = f"Shares data column ('shareCount') not found for '{plot_label}'."
414
+ else:
415
+ summary_text = f"Shares data is unavailable for '{plot_label}'."
416
+
417
+ elif plot_id == "comments_over_time":
418
+ if not posts_df.empty and 'commentCount' in posts_df.columns and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
419
+ df_resampled = posts_df.set_index(date_col_posts)['commentCount'].resample('W').sum().reset_index()
420
+ df_resampled['commentCount'] = pd.to_numeric(df_resampled['commentCount'], errors='coerce')
421
+ df_summary = df_resampled[[date_col_posts, 'commentCount']].dropna().copy()
422
+ df_summary[date_col_posts] = df_summary[date_col_posts].dt.strftime('%Y-%m-%d')
423
+ df_summary.rename(columns={'commentCount': 'Comments'}, inplace=True)
424
+ summary_text = f"Comments Over Time (Weekly Sum):\n{df_summary.sort_values(by=date_col_posts).tail(5).to_string(index=False)}"
425
+ else:
426
+ summary_text = f"Comments data is unavailable for '{plot_label}'."
427
+
428
+ elif plot_id == "comments_sentiment":
429
+ comment_sentiment_col_posts = "sentiment"
430
+ if not posts_df.empty and comment_sentiment_col_posts in posts_df.columns:
431
+ sentiment_counts = posts_df[comment_sentiment_col_posts].value_counts().reset_index()
432
+ sentiment_counts.columns = ['Sentiment', 'Count']
433
+ summary_text = f"Comments Sentiment Breakdown (Posts Data):\n{sentiment_counts.to_string(index=False)}"
434
+ else:
435
+ summary_text = f"Comment sentiment data ('{comment_sentiment_col_posts}') is unavailable for '{plot_label}'."
436
+
437
+ elif plot_id == "post_frequency_cs":
438
+ if not posts_df.empty and date_col_posts in posts_df.columns and not posts_df[date_col_posts].isnull().all():
439
+ post_counts_weekly = posts_df.set_index(date_col_posts).resample('W').size().reset_index(name='post_count')
440
+ post_counts_weekly.rename(columns={date_col_posts: 'Week', 'post_count': 'Posts'}, inplace=True)
441
+ post_counts_weekly['Week'] = post_counts_weekly['Week'].dt.strftime('%Y-%m-%d (Week of)')
442
+ summary_text = f"Post Frequency (Weekly):\n{post_counts_weekly.sort_values(by='Week').tail(5).to_string(index=False)}"
443
+ else:
444
+ summary_text = f"Post frequency data is unavailable for '{plot_label}'."
445
+
446
+ elif plot_id == "content_format_breakdown_cs":
447
+ if not posts_df.empty and media_type_col_name in posts_df.columns:
448
+ format_counts = posts_df[media_type_col_name].value_counts().reset_index()
449
+ format_counts.columns = ['Format', 'Count']
450
+ summary_text = f"Content Format Breakdown:\n{format_counts.nlargest(5, 'Count').to_string(index=False)}"
451
+ else:
452
+ summary_text = f"Content format data ('{media_type_col_name}') is unavailable for '{plot_label}'."
453
+
454
+ elif plot_id == "content_topic_breakdown_cs":
455
+ if not posts_df.empty and eb_labels_col_name in posts_df.columns:
456
+ try:
457
+ # Ensure the column is not all NaN before trying to check for lists or explode
458
+ if posts_df[eb_labels_col_name].notna().any():
459
+ if posts_df[eb_labels_col_name].apply(lambda x: isinstance(x, list)).any():
460
+ topic_counts = posts_df.explode(eb_labels_col_name)[eb_labels_col_name].value_counts().reset_index()
461
+ else:
462
+ topic_counts = posts_df[eb_labels_col_name].value_counts().reset_index()
463
+ topic_counts.columns = ['Topic', 'Count']
464
+ summary_text = f"Content Topic Breakdown (Top 5):\n{topic_counts.nlargest(5, 'Count').to_string(index=False)}"
465
+ else:
466
+ summary_text = f"Content topic data ('{eb_labels_col_name}') contains no valid topics for '{plot_label}'."
467
+ except Exception as e_topic:
468
+ logging.warning(f"Could not process topic breakdown for '{eb_labels_col_name}': {e_topic}")
469
+ summary_text = f"Content topic data ('{eb_labels_col_name}') could not be processed for '{plot_label}'."
470
+ else:
471
+ summary_text = f"Content topic data ('{eb_labels_col_name}') is unavailable for '{plot_label}'."
472
+
473
+ # --- MENTIONS STATS ---
474
+ elif plot_id == "mention_analysis_volume":
475
+ if not mentions_df.empty and date_col_mentions in mentions_df.columns and not mentions_df[date_col_mentions].isnull().all():
476
+ mentions_over_time = mentions_df.set_index(date_col_mentions).resample('W').size().reset_index(name='mention_count')
477
+ mentions_over_time.rename(columns={date_col_mentions: 'Week', 'mention_count': 'Mentions'}, inplace=True)
478
+ mentions_over_time['Week'] = mentions_over_time['Week'].dt.strftime('%Y-%m-%d (Week of)')
479
+ if not mentions_over_time.empty:
480
+ summary_text = f"Mentions Volume (Weekly):\n{mentions_over_time.sort_values(by='Week').tail(5).to_string(index=False)}"
481
+ else:
482
+ summary_text = f"No mention activity found for '{plot_label}' in the selected period."
483
+ else:
484
+ summary_text = f"Mentions volume data is unavailable for '{plot_label}'."
485
+
486
+ elif plot_id == "mention_analysis_sentiment":
487
+ if not mentions_df.empty and mentions_sentiment_col in mentions_df.columns:
488
+ sentiment_counts = mentions_df[mentions_sentiment_col].value_counts().reset_index()
489
+ sentiment_counts.columns = ['Sentiment', 'Count']
490
+ summary_text = f"Mentions Sentiment Breakdown:\n{sentiment_counts.to_string(index=False)}"
491
+ else:
492
+ summary_text = f"Mention sentiment data ('{mentions_sentiment_col}') is unavailable for '{plot_label}'."
493
+
494
+ data_summaries[plot_id] = summary_text
495
+ except KeyError as e:
496
+ logging.warning(f"KeyError generating summary for {plot_id} ('{plot_label}'): {e}. Using default summary.")
497
+ data_summaries[plot_id] = f"Data summary generation error for '{plot_label}' (missing column: {e})."
498
+ except Exception as e:
499
+ logging.error(f"Error generating summary for {plot_id} ('{plot_label}'): {e}", exc_info=True)
500
+ data_summaries[plot_id] = f"Error generating data summary for '{plot_label}'."
501
+
502
+ return data_summaries