Spaces:
Restarting
Restarting
Update analytics_data_processing.py
Browse files- analytics_data_processing.py +75 -31
analytics_data_processing.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
import pandas as pd
|
2 |
-
from datetime import datetime, timedelta, time
|
3 |
import logging
|
4 |
|
5 |
# Configure logging for this module
|
@@ -23,8 +23,8 @@ def filter_dataframe_by_date(df, date_column, start_date, end_date):
|
|
23 |
# Drop rows where date conversion might have failed (NaT) or was originally NaT
|
24 |
df_copy.dropna(subset=[date_column], inplace=True)
|
25 |
if df_copy.empty:
|
26 |
-
|
27 |
-
|
28 |
|
29 |
# Normalize to midnight. This preserves timezone information if present.
|
30 |
df_copy[date_column] = df_copy[date_column].dt.normalize()
|
@@ -39,45 +39,55 @@ def filter_dataframe_by_date(df, date_column, start_date, end_date):
|
|
39 |
logging.error(f"Error processing date column '{date_column}': {e}", exc_info=True)
|
40 |
return pd.DataFrame()
|
41 |
|
42 |
-
df_filtered = df_copy # df_copy is now processed and potentially filtered by dropna
|
43 |
-
# No need for: df_filtered = df_copy.dropna(subset=[date_column]) again here.
|
44 |
-
if df_filtered.empty: # Check again in case all rows were dropped or some other issue.
|
45 |
-
logging.info(f"Filter by date: DataFrame became empty after processing date column '{date_column}'.")
|
46 |
-
return pd.DataFrame()
|
47 |
-
|
48 |
# Convert start_date and end_date (which are naive Python datetime or naive Pandas Timestamp)
|
49 |
# to naive pandas Timestamps and normalize them.
|
50 |
start_dt_obj = pd.to_datetime(start_date, errors='coerce').normalize() if start_date else None
|
51 |
end_dt_obj = pd.to_datetime(end_date, errors='coerce').normalize() if end_date else None
|
52 |
|
53 |
# Perform the filtering
|
|
|
54 |
if start_dt_obj and end_dt_obj:
|
55 |
-
|
56 |
elif start_dt_obj:
|
57 |
-
|
58 |
elif end_dt_obj:
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
|
63 |
def prepare_filtered_analytics_data(token_state_value, date_filter_option, custom_start_date, custom_end_date):
|
64 |
"""
|
65 |
-
Retrieves data from token_state, determines date range, filters posts and
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
"""
|
69 |
logging.info(f"Preparing filtered analytics data. Filter: {date_filter_option}, Custom Start: {custom_start_date}, Custom End: {custom_end_date}")
|
70 |
|
71 |
-
posts_df = token_state_value.get("bubble_posts_df", pd.DataFrame())
|
72 |
-
mentions_df = token_state_value.get("bubble_mentions_df", pd.DataFrame())
|
73 |
-
follower_stats_df = token_state_value.get("bubble_follower_stats_df", pd.DataFrame())
|
|
|
74 |
|
75 |
date_column_posts = token_state_value.get("config_date_col_posts", "published_at")
|
76 |
date_column_mentions = token_state_value.get("config_date_col_mentions", "date")
|
|
|
|
|
77 |
|
78 |
-
# Determine date range for filtering
|
79 |
current_datetime_obj = datetime.now()
|
80 |
-
current_time_normalized = current_datetime_obj.replace(hour=0, minute=0, second=0, microsecond=0)
|
81 |
|
82 |
end_dt_filter = current_time_normalized
|
83 |
start_dt_filter = None
|
@@ -87,10 +97,7 @@ def prepare_filtered_analytics_data(token_state_value, date_filter_option, custo
|
|
87 |
elif date_filter_option == "Last 30 Days":
|
88 |
start_dt_filter = current_time_normalized - timedelta(days=29)
|
89 |
elif date_filter_option == "Custom Range":
|
90 |
-
# custom_start_date and custom_end_date are strings from gr.DateTime(type="string")
|
91 |
-
# Convert to pandas Timestamp (which will be naive if input string is naive) then normalize using pandas method
|
92 |
start_dt_filter_temp = pd.to_datetime(custom_start_date, errors='coerce')
|
93 |
-
# .replace() on pandas Timestamp normalizes time part
|
94 |
start_dt_filter = start_dt_filter_temp.replace(hour=0, minute=0, second=0, microsecond=0) if pd.notna(start_dt_filter_temp) else None
|
95 |
|
96 |
end_dt_filter_temp = pd.to_datetime(custom_end_date, errors='coerce')
|
@@ -98,15 +105,52 @@ def prepare_filtered_analytics_data(token_state_value, date_filter_option, custo
|
|
98 |
|
99 |
logging.info(f"Date range for filtering: Start: {start_dt_filter}, End: {end_dt_filter}")
|
100 |
|
101 |
-
#
|
102 |
-
|
103 |
-
if not posts_df.empty:
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
filtered_mentions_data = pd.DataFrame()
|
107 |
-
if not mentions_df.empty:
|
108 |
filtered_mentions_data = filter_dataframe_by_date(mentions_df, date_column_mentions, start_dt_filter, end_dt_filter)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
-
logging.info(f"Processed - Filtered
|
111 |
|
112 |
-
return
|
|
|
1 |
import pandas as pd
|
2 |
+
from datetime import datetime, timedelta, time
|
3 |
import logging
|
4 |
|
5 |
# Configure logging for this module
|
|
|
23 |
# Drop rows where date conversion might have failed (NaT) or was originally NaT
|
24 |
df_copy.dropna(subset=[date_column], inplace=True)
|
25 |
if df_copy.empty:
|
26 |
+
logging.info(f"Filter by date: DataFrame empty after to_datetime and dropna for column '{date_column}'.")
|
27 |
+
return pd.DataFrame()
|
28 |
|
29 |
# Normalize to midnight. This preserves timezone information if present.
|
30 |
df_copy[date_column] = df_copy[date_column].dt.normalize()
|
|
|
39 |
logging.error(f"Error processing date column '{date_column}': {e}", exc_info=True)
|
40 |
return pd.DataFrame()
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
# Convert start_date and end_date (which are naive Python datetime or naive Pandas Timestamp)
|
43 |
# to naive pandas Timestamps and normalize them.
|
44 |
start_dt_obj = pd.to_datetime(start_date, errors='coerce').normalize() if start_date else None
|
45 |
end_dt_obj = pd.to_datetime(end_date, errors='coerce').normalize() if end_date else None
|
46 |
|
47 |
# Perform the filtering
|
48 |
+
# df_filtered is already df_copy which has NaNs dropped and dates processed
|
49 |
if start_dt_obj and end_dt_obj:
|
50 |
+
df_filtered_final = df_copy[(df_copy[date_column] >= start_dt_obj) & (df_copy[date_column] <= end_dt_obj)]
|
51 |
elif start_dt_obj:
|
52 |
+
df_filtered_final = df_copy[df_copy[date_column] >= start_dt_obj]
|
53 |
elif end_dt_obj:
|
54 |
+
df_filtered_final = df_copy[df_copy[date_column] <= end_dt_obj]
|
55 |
+
else:
|
56 |
+
df_filtered_final = df_copy # No date filtering if neither start_date nor end_date is provided
|
57 |
+
|
58 |
+
if df_filtered_final.empty:
|
59 |
+
logging.info(f"Filter by date: DataFrame became empty after applying date range to column '{date_column}'.")
|
60 |
+
|
61 |
+
return df_filtered_final
|
62 |
|
63 |
|
64 |
def prepare_filtered_analytics_data(token_state_value, date_filter_option, custom_start_date, custom_end_date):
|
65 |
"""
|
66 |
+
Retrieves data from token_state, determines date range, filters posts, mentions, and follower time-series data.
|
67 |
+
Merges posts with post stats.
|
68 |
+
Returns:
|
69 |
+
- filtered_merged_posts_df: Posts merged with stats, filtered by date.
|
70 |
+
- filtered_mentions_df: Mentions filtered by date.
|
71 |
+
- date_filtered_follower_stats_df: Follower stats filtered by date (for time-series plots).
|
72 |
+
- raw_follower_stats_df: Unfiltered follower stats (for demographic plots).
|
73 |
+
- start_dt_filter: Determined start date for filtering.
|
74 |
+
- end_dt_filter: Determined end date for filtering.
|
75 |
"""
|
76 |
logging.info(f"Preparing filtered analytics data. Filter: {date_filter_option}, Custom Start: {custom_start_date}, Custom End: {custom_end_date}")
|
77 |
|
78 |
+
posts_df = token_state_value.get("bubble_posts_df", pd.DataFrame()).copy()
|
79 |
+
mentions_df = token_state_value.get("bubble_mentions_df", pd.DataFrame()).copy()
|
80 |
+
follower_stats_df = token_state_value.get("bubble_follower_stats_df", pd.DataFrame()).copy()
|
81 |
+
post_stats_df = token_state_value.get("bubble_post_stats_df", pd.DataFrame()).copy() # Fetch post_stats_df
|
82 |
|
83 |
date_column_posts = token_state_value.get("config_date_col_posts", "published_at")
|
84 |
date_column_mentions = token_state_value.get("config_date_col_mentions", "date")
|
85 |
+
# Assuming follower_stats_df has a 'date' column for time-series data
|
86 |
+
date_column_followers = token_state_value.get("config_date_col_followers", "date")
|
87 |
|
88 |
+
# Determine date range for filtering
|
89 |
current_datetime_obj = datetime.now()
|
90 |
+
current_time_normalized = current_datetime_obj.replace(hour=0, minute=0, second=0, microsecond=0)
|
91 |
|
92 |
end_dt_filter = current_time_normalized
|
93 |
start_dt_filter = None
|
|
|
97 |
elif date_filter_option == "Last 30 Days":
|
98 |
start_dt_filter = current_time_normalized - timedelta(days=29)
|
99 |
elif date_filter_option == "Custom Range":
|
|
|
|
|
100 |
start_dt_filter_temp = pd.to_datetime(custom_start_date, errors='coerce')
|
|
|
101 |
start_dt_filter = start_dt_filter_temp.replace(hour=0, minute=0, second=0, microsecond=0) if pd.notna(start_dt_filter_temp) else None
|
102 |
|
103 |
end_dt_filter_temp = pd.to_datetime(custom_end_date, errors='coerce')
|
|
|
105 |
|
106 |
logging.info(f"Date range for filtering: Start: {start_dt_filter}, End: {end_dt_filter}")
|
107 |
|
108 |
+
# Merge posts_df and post_stats_df
|
109 |
+
merged_posts_df = pd.DataFrame()
|
110 |
+
if not posts_df.empty and not post_stats_df.empty:
|
111 |
+
# Assuming posts_df has 'id' and post_stats_df has 'post_id' for merging
|
112 |
+
if 'id' in posts_df.columns and 'post_id' in post_stats_df.columns:
|
113 |
+
merged_posts_df = pd.merge(posts_df, post_stats_df, left_on='id', right_on='post_id', how='left')
|
114 |
+
logging.info(f"Merged posts_df ({len(posts_df)} rows) and post_stats_df ({len(post_stats_df)} rows) into merged_posts_df ({len(merged_posts_df)} rows).")
|
115 |
+
else:
|
116 |
+
logging.warning("Cannot merge posts_df and post_stats_df due to missing 'id' or 'post_id' columns.")
|
117 |
+
# Fallback to using posts_df if merge fails but provide an empty df for stats-dependent plots
|
118 |
+
merged_posts_df = posts_df # Or handle as an error / empty DF for those plots
|
119 |
+
elif not posts_df.empty:
|
120 |
+
logging.warning("post_stats_df is empty. Proceeding with posts_df only for plots that don't require stats.")
|
121 |
+
merged_posts_df = posts_df # Create necessary columns with NaN if they are expected by plots
|
122 |
+
# For columns expected from post_stats_df, add them with NaNs if not present
|
123 |
+
expected_stat_cols = ['engagement', 'impressionCount', 'clickCount', 'likeCount', 'commentCount', 'shareCount']
|
124 |
+
for col in expected_stat_cols:
|
125 |
+
if col not in merged_posts_df.columns:
|
126 |
+
merged_posts_df[col] = pd.NA
|
127 |
+
|
128 |
+
|
129 |
+
# Filter DataFrames by date
|
130 |
+
filtered_merged_posts_data = pd.DataFrame()
|
131 |
+
if not merged_posts_df.empty and date_column_posts in merged_posts_df.columns:
|
132 |
+
filtered_merged_posts_data = filter_dataframe_by_date(merged_posts_df, date_column_posts, start_dt_filter, end_dt_filter)
|
133 |
+
elif not merged_posts_df.empty:
|
134 |
+
logging.warning(f"Date column '{date_column_posts}' not found in merged_posts_df. Returning unfiltered merged posts data.")
|
135 |
+
filtered_merged_posts_data = merged_posts_df # Or apply other logic
|
136 |
|
137 |
filtered_mentions_data = pd.DataFrame()
|
138 |
+
if not mentions_df.empty and date_column_mentions in mentions_df.columns:
|
139 |
filtered_mentions_data = filter_dataframe_by_date(mentions_df, date_column_mentions, start_dt_filter, end_dt_filter)
|
140 |
+
elif not mentions_df.empty:
|
141 |
+
logging.warning(f"Date column '{date_column_mentions}' not found in mentions_df. Returning unfiltered mentions data.")
|
142 |
+
filtered_mentions_data = mentions_df
|
143 |
+
|
144 |
+
date_filtered_follower_stats_df = pd.DataFrame()
|
145 |
+
raw_follower_stats_df = follower_stats_df.copy() # For demographic plots, use raw (or latest snapshot logic)
|
146 |
+
|
147 |
+
if not follower_stats_df.empty and date_column_followers in follower_stats_df.columns:
|
148 |
+
date_filtered_follower_stats_df = filter_dataframe_by_date(follower_stats_df, date_column_followers, start_dt_filter, end_dt_filter)
|
149 |
+
elif not follower_stats_df.empty:
|
150 |
+
logging.warning(f"Date column '{date_column_followers}' not found in follower_stats_df. Time-series follower plots might be empty or use unfiltered data.")
|
151 |
+
# Decide if date_filtered_follower_stats_df should be raw_follower_stats_df or empty
|
152 |
+
date_filtered_follower_stats_df = follower_stats_df # Or pd.DataFrame() if strict filtering is required
|
153 |
|
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
|