Spaces:
Running
Running
Update analytics_fetch_and_rendering.py
Browse files
analytics_fetch_and_rendering.py
CHANGED
@@ -220,6 +220,75 @@ def plot_follower_gains(follower_data):
|
|
220 |
plt.tight_layout()
|
221 |
return fig
|
222 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
|
224 |
def fetch_and_render_analytics(comm_client_id, comm_token):
|
225 |
"""Fetches analytics data and prepares updates for Gradio UI."""
|
@@ -254,8 +323,11 @@ def fetch_and_render_analytics(comm_client_id, comm_token):
|
|
254 |
# If plot generation failed, plot_fig might contain an error message plot
|
255 |
plot_output = gr.update(value=plot_fig, visible=True)
|
256 |
|
257 |
-
|
258 |
-
|
|
|
|
|
|
|
259 |
|
260 |
except (ValueError, requests.exceptions.RequestException) as api_ve:
|
261 |
# Catch specific API or configuration errors from fetch_analytics_data
|
|
|
220 |
plt.tight_layout()
|
221 |
return fig
|
222 |
|
223 |
+
# Add this function below `plot_follower_gains` in your code
|
224 |
+
|
225 |
+
def plot_growth_rate(follower_data, total_follower_count):
|
226 |
+
"""
|
227 |
+
Generates a line chart for Follower Growth Rate (%) on a monthly basis.
|
228 |
+
"""
|
229 |
+
print(f"Plotting follower growth rate from data: {follower_data} and total followers: {total_follower_count}")
|
230 |
+
if not follower_data:
|
231 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
232 |
+
ax.text(0.5, 0.5, 'No data available to calculate growth rate.',
|
233 |
+
horizontalalignment='center', verticalalignment='center',
|
234 |
+
transform=ax.transAxes, fontsize=12, color='grey')
|
235 |
+
ax.set_title('Monthly Follower Growth Rate (%)')
|
236 |
+
ax.set_xticks([])
|
237 |
+
ax.set_yticks([])
|
238 |
+
plt.tight_layout()
|
239 |
+
return fig
|
240 |
+
|
241 |
+
try:
|
242 |
+
follower_data.sort(key=lambda x: x['date'])
|
243 |
+
dates = [entry['date'] for entry in follower_data]
|
244 |
+
total_gains = [entry['organic'] + entry['paid'] for entry in follower_data]
|
245 |
+
|
246 |
+
# Reconstruct monthly total followers backwards from the current total
|
247 |
+
followers_at_end_of_month = []
|
248 |
+
current_total = total_follower_count
|
249 |
+
for gain in reversed(total_gains):
|
250 |
+
followers_at_end_of_month.insert(0, current_total)
|
251 |
+
current_total -= gain
|
252 |
+
|
253 |
+
# followers_at_end_of_month now contains follower totals at end of each month
|
254 |
+
growth_rates = []
|
255 |
+
for i in range(1, len(followers_at_end_of_month)):
|
256 |
+
start = followers_at_end_of_month[i - 1]
|
257 |
+
end = followers_at_end_of_month[i]
|
258 |
+
rate = ((end - start) / start * 100) if start > 0 else 0
|
259 |
+
growth_rates.append(rate)
|
260 |
+
|
261 |
+
# Trim the first date (because we start calculating growth from second month)
|
262 |
+
rate_dates = dates[1:]
|
263 |
+
|
264 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
265 |
+
ax.plot(rate_dates, growth_rates, label='Growth Rate (%)', marker='o', linestyle='-', color='green')
|
266 |
+
ax.set_title('Monthly Follower Growth Rate (%)')
|
267 |
+
ax.set_xlabel('Month (YYYY-MM)')
|
268 |
+
ax.set_ylabel('Growth Rate (%)')
|
269 |
+
ax.grid(True, linestyle='--', alpha=0.6)
|
270 |
+
tick_frequency = max(1, len(rate_dates) // 10)
|
271 |
+
ax.set_xticks(rate_dates[::tick_frequency])
|
272 |
+
ax.tick_params(axis='x', rotation=45, labelsize=9)
|
273 |
+
ax.legend()
|
274 |
+
|
275 |
+
plt.tight_layout()
|
276 |
+
print("Successfully generated growth rate plot.")
|
277 |
+
return fig
|
278 |
+
|
279 |
+
except Exception as e:
|
280 |
+
print(f"ERROR generating growth rate plot: {e}")
|
281 |
+
tb = traceback.format_exc()
|
282 |
+
print(tb)
|
283 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
284 |
+
ax.text(0.5, 0.5, f'Error generating growth rate plot: {e}',
|
285 |
+
horizontalalignment='center', verticalalignment='center',
|
286 |
+
transform=ax.transAxes, fontsize=12, color='red', wrap=True)
|
287 |
+
ax.set_title('Follower Growth Rate Plot Error')
|
288 |
+
plt.tight_layout()
|
289 |
+
return fig
|
290 |
+
|
291 |
+
|
292 |
|
293 |
def fetch_and_render_analytics(comm_client_id, comm_token):
|
294 |
"""Fetches analytics data and prepares updates for Gradio UI."""
|
|
|
323 |
# If plot generation failed, plot_fig might contain an error message plot
|
324 |
plot_output = gr.update(value=plot_fig, visible=True)
|
325 |
|
326 |
+
# Generate follower growth rate plot
|
327 |
+
growth_rate_fig = plot_growth_rate(follower_gains_list)
|
328 |
+
growth_output = gr.update(value=growth_rate_fig, visible=True)
|
329 |
+
|
330 |
+
return count_output, plot_fig, growth_output
|
331 |
|
332 |
except (ValueError, requests.exceptions.RequestException) as api_ve:
|
333 |
# Catch specific API or configuration errors from fetch_analytics_data
|