Tobaly commited on
Commit
a78f087
·
verified ·
1 Parent(s): 6966521

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -490
app.py CHANGED
@@ -10,18 +10,26 @@ import io
10
  import time
11
  from difflib import SequenceMatcher
12
  import gradio as gr
13
- import google.generativeai as genai
14
- from typing import List, Dict, Tuple, Optional
15
- import tempfile
16
  import os
17
 
18
  # Suppress warnings for a cleaner output
19
  warnings.filterwarnings('ignore')
20
 
 
 
 
 
 
 
 
 
21
  def get_now():
22
- """A simple function to get the current time. Can be mocked for testing."""
23
  return datetime.now()
24
 
 
 
 
25
  class ComprehensivePodcastReport:
26
  """
27
  Generates a complete podcast performance report, combining overall analytics
@@ -40,9 +48,6 @@ class ComprehensivePodcastReport:
40
  self.date_range_str = "All Time"
41
  self.start_date = None
42
  self.end_date = None
43
- self.gemini_api_key = None
44
-
45
- # --- DATA LOADING AND PREPARATION METHODS ---
46
 
47
  def _fix_spotify_timestamps(self, timestamp_series):
48
  """Fix Spotify's invalid '24:00:00' timestamps."""
@@ -61,7 +66,6 @@ class ComprehensivePodcastReport:
61
  print(f"❌ Missing a required file: {e}. Please include OnSpotify and EpisodeRankings files.")
62
  raise
63
 
64
- # Optional Files
65
  if 'streams' in file_paths:
66
  self.all_time_data['streams'] = pd.read_csv(file_paths['streams'])
67
  self.all_time_data['streams']['Date'] = pd.to_datetime(self._fix_spotify_timestamps(self.all_time_data['streams']['Time (UTC)']))
@@ -83,64 +87,47 @@ class ComprehensivePodcastReport:
83
  self.end_date = pd.to_datetime(end_date).normalize()
84
  self.date_range_str = f"{self.start_date.strftime('%Y-%m-%d')} to {self.end_date.strftime('%Y-%m-%d')}"
85
  print(f"🔎 Filtering data for period: {self.date_range_str}")
86
-
87
  for key in ['time_series', 'streams']:
88
  if key in self.period_data:
89
  df = self.period_data[key]
90
  self.period_data[key] = df[(df['Date'] >= self.start_date) & (df['Date'] <= self.end_date)]
91
 
92
- # --- EPISODE-SPECIFIC ANALYSIS METHODS ---
93
-
94
  def _normalize_text(self, text):
95
  """Normalizes text for fuzzy string matching."""
96
- text = re.sub(r'[^\u0590-\u05FFa-zA-Z0-9\-]', '', str(text).replace(':', '').replace(' ', ''))
97
- return text.lower()
98
 
99
- def identify_and_prompt_for_episodes(self):
100
- """Identifies episodes in the period and prompts the user for their CSVs."""
101
  episodes_df = self.all_time_data.get('episodes')
102
- if episodes_df is None: return pd.DataFrame()
103
-
104
- episodes_in_period = episodes_df[
105
- (episodes_df['Publish Date'] >= self.start_date) &
106
- (episodes_df['Publish Date'] <= self.end_date)
107
- ].sort_values('Publish Date', ascending=False).reset_index(drop=True)
108
-
109
- total_episodes = len(episodes_in_period)
110
- if total_episodes == 0:
111
- print("\n⚠️ No episodes found published in the selected period.")
112
- else:
113
- print(f"\n📺 Found {total_episodes} episodes published in the period:")
114
- print("="*80)
115
- for _, row in episodes_in_period.iterrows():
116
- print(f" • {row['Episode Title'][:80]} (Published: {row['Publish Date']:%Y-%m-%d})")
117
- print("="*80)
118
- return episodes_in_period
119
 
120
  def load_and_match_episode_csvs(self, uploaded_files, episodes_in_period):
121
  """Matches and loads individual episode CSVs from uploaded files."""
 
122
  print("\n🔍 Matching and loading individual episode CSVs...")
123
- if episodes_in_period.empty:
124
- print(" -> No episodes in period to match against. Skipping.")
125
- return
126
  episodes_in_period['normalized_title'] = episodes_in_period['Episode Title'].apply(self._normalize_text)
127
-
128
- for filename, file_content in uploaded_files.items():
129
  file_type = 'spotify' if 'OnSpotify' in filename else 'all_platforms' if 'StreamsAndDownloads' in filename else None
130
  if not file_type: continue
131
-
132
  clean_filename = re.sub(r'\s*\(\d+\)|\s+\d+(?=\.csv)', '', filename)
133
  normalized_filename = self._normalize_text(clean_filename)
134
- episodes_in_period['similarity'] = episodes_in_period['normalized_title'].apply(
135
- lambda title: SequenceMatcher(None, normalized_filename, title).ratio()
136
- )
137
  best_match = episodes_in_period.loc[episodes_in_period['similarity'].idxmax()]
138
-
139
  if best_match['similarity'] > 0.5:
140
  episode_title = best_match['Episode Title']
141
  print(f" ✅ Matched: {filename[:40]}... -> {episode_title[:40]}...")
142
  try:
143
- df = pd.read_csv(io.StringIO(file_content))
 
144
  df['Date'] = pd.to_datetime(df['Time (UTC)'].str.split(',').str[0], errors='coerce').dt.normalize()
145
  value_col = next((col for col in ['Plays', 'Streams & Downloads'] if col in df.columns), None)
146
  if not value_col: continue
@@ -149,10 +136,6 @@ class ComprehensivePodcastReport:
149
  self.episode_specific_data[episode_title][file_type] = episode_df
150
  except Exception as e:
151
  print(f" -> Error processing file {filename}: {e}")
152
- else:
153
- self.unmatched_episode_csvs.append(filename)
154
-
155
- # --- CORE ANALYTICS AND METRICS ---
156
 
157
  def calculate_key_metrics(self, use_all_time=False):
158
  """Calculate core performance metrics."""
@@ -163,21 +146,11 @@ class ComprehensivePodcastReport:
163
  current_followers = int(ts_followers_cleaned['Followers'].iloc[-1]) if not ts_followers_cleaned.empty else 0
164
  total_plays = ts_data['Plays'].sum()
165
  total_streams = ts_data['Streams'].sum()
166
-
167
- metrics = {
168
- 'total_plays': int(total_plays), 'total_streams': int(total_streams),
169
- 'avg_daily_plays': ts_data['Plays'].mean(),
170
- 'engagement_percentage': (total_streams / max(total_plays, 1)) * 100,
171
- 'current_followers': current_followers
172
- }
173
  if use_all_time:
174
  ep_data = self.all_time_data.get('episodes', pd.DataFrame())
175
- metrics.update({
176
- 'total_episodes': len(ep_data),
177
- 'median_streams_per_episode': ep_data['Streams & Downloads'].median() if not ep_data.empty else 0,
178
- 'performance_benchmark': ep_data['Streams & Downloads'].quantile(0.75) if not ep_data.empty else 0
179
- })
180
- else: # Period specific
181
  ep_data_all = self.all_time_data.get('episodes', pd.DataFrame())
182
  episodes_in_period = ep_data_all[(ep_data_all['Publish Date'] >= self.start_date) & (ep_data_all['Publish Date'] <= self.end_date)]
183
  metrics['performance_benchmark_period'] = episodes_in_period['Streams & Downloads'].quantile(0.75) if not episodes_in_period.empty else 0
@@ -192,11 +165,7 @@ class ComprehensivePodcastReport:
192
  if recent_period.empty or previous_period.empty: return {}
193
  recent_gain = recent_period['Followers'].iloc[-1] - recent_period['Followers'].iloc[0]
194
  previous_gain = previous_period['Followers'].iloc[-1] - previous_period['Followers'].iloc[0]
195
- return {
196
- 'plays_growth_rate_median': ((recent_period['Plays'].median() - previous_period['Plays'].median()) / max(previous_period['Plays'].median(), 1)) * 100,
197
- 'followers_gained': int(recent_gain),
198
- 'follower_growth_rate': ((recent_gain - previous_gain) / max(abs(previous_gain), 1)) * 100 if previous_gain != 0 else float('inf')
199
- }
200
 
201
  def analyze_seasonal_patterns(self):
202
  """Analyze weekly listening patterns."""
@@ -204,10 +173,7 @@ class ComprehensivePodcastReport:
204
  if len(ts_data) < 7: return {}
205
  ts_data['DayOfWeek'] = ts_data['Date'].dt.day_name()
206
  weekly_avg = ts_data.groupby('DayOfWeek')['Plays'].mean()
207
- return {
208
- 'best_day': weekly_avg.idxmax(), 'worst_day': weekly_avg.idxmin(),
209
- 'weekly_consistency': (1 - (weekly_avg.std() / weekly_avg.mean())) * 100 if weekly_avg.mean() > 0 else 0
210
- }
211
 
212
  def _get_platform_share(self, platform_name):
213
  """Helper to get platform share from all-time data."""
@@ -216,8 +182,6 @@ class ComprehensivePodcastReport:
216
  platform_row = apps_df[apps_df['App'] == platform_name]
217
  return platform_row['Percent of Plays'].iloc[0] * 100 if not platform_row.empty else 0.0
218
 
219
- # --- PLOTTING AND VISUALIZATION METHODS ---
220
-
221
  def _add_regression_line(self, ax, x_values, y_values, **kwargs):
222
  """Helper to add a linear regression trendline to a plot."""
223
  if len(x_values) < 2: return
@@ -232,214 +196,76 @@ class ComprehensivePodcastReport:
232
  print("🎨 Generating all performance visualizations...")
233
  plots = []
234
  ts_data = self.period_data['time_series'].sort_values('Date')
235
-
236
- # Daily Plays & Streams
237
  if not ts_data.empty:
238
- fig, ax = plt.subplots(figsize=(12, 6))
239
- ax.plot(ts_data['Date'], ts_data['Plays'], label='Daily Plays (Spotify)', color='blue')
240
- self._add_regression_line(ax, ts_data['Date'], ts_data['Plays'])
241
- ax.set_title(f'{self.client_name} - Daily Plays (OnSpotify)', fontsize=14)
242
- ax.grid(True, alpha=0.3)
243
- ax.legend()
244
- plt.tight_layout()
245
- plots.append(('daily_plays', fig))
246
-
247
  if 'streams' in self.period_data and not self.period_data['streams'].empty:
248
- streams_data = self.period_data['streams'].sort_values('Date')
249
- fig, ax = plt.subplots(figsize=(12, 6))
250
- ax.plot(streams_data['Date'], streams_data['Streams & Downloads'], label='Daily Streams & Downloads', color='green')
251
- self._add_regression_line(ax, streams_data['Date'], streams_data['Streams & Downloads'])
252
- ax.set_title(f'{self.client_name} - Daily Streams & Downloads (All Platforms)', fontsize=14)
253
- ax.grid(True, alpha=0.3)
254
- ax.legend()
255
- plt.tight_layout()
256
- plots.append(('daily_streams', fig))
257
-
258
- # Monthly Plots
259
  graph_start = self.start_date.replace(day=1) if self.start_date.day != 1 else self.start_date
260
  for key, col, color in [('time_series', 'Plays', 'skyblue'), ('streams', 'Streams & Downloads', 'lightgreen')]:
261
  if key in self.all_time_data:
262
- monthly_data = self.all_time_data[key]
263
- monthly_data = monthly_data[(monthly_data['Date'] >= graph_start) & (monthly_data['Date'] <= self.end_date)]
264
  if not monthly_data.empty:
265
- monthly_data['YearMonth'] = monthly_data['Date'].dt.to_period('M')
266
- monthly_values = monthly_data.groupby('YearMonth')[col].sum()
267
- fig, ax = plt.subplots(figsize=(12, 6))
268
- bars = ax.bar(np.arange(len(monthly_values)), monthly_values.values, color=color, edgecolor='navy')
269
- self._add_regression_line(ax, np.arange(len(monthly_values)), monthly_values.values)
270
- ax.set_xticks(np.arange(len(monthly_values)))
271
- ax.set_xticklabels([str(p) for p in monthly_values.index], rotation=45)
272
- ax.set_title(f'{self.client_name} - Monthly {col}', fontsize=14)
273
- ax.legend()
274
- plt.tight_layout()
275
- current_month = pd.Period(get_now(), 'M')
276
- if current_month in monthly_values.index:
277
- bars[monthly_values.index.get_loc(current_month)].set_color('orange')
278
- plots.append((f'monthly_{key}', fig))
279
-
280
- # Advanced Metrics
281
- follower_data = ts_data.dropna(subset=['Followers'])
282
  if not follower_data.empty:
283
- fig, ax = plt.subplots(figsize=(12, 6))
284
- ax.plot(follower_data['Date'], follower_data['Followers'], label='Followers', color='purple')
285
- self._add_regression_line(ax, follower_data['Date'], follower_data['Followers'], label_prefix="Follower Trend")
286
- ax.set_title(f'{self.client_name} - Follower Growth', fontsize=14)
287
- ax.grid(True, alpha=0.3)
288
- ax.legend()
289
- plt.tight_layout()
290
- plots.append(('follower_growth', fig))
291
-
292
  consump_data = ts_data.dropna(subset=['Consumption Hours'])
293
  if not consump_data.empty and consump_data['Consumption Hours'].sum() > 0:
294
- fig, ax = plt.subplots(figsize=(12, 6))
295
- ax.plot(consump_data['Date'], consump_data['Consumption Hours'], label='Hours', color='teal')
296
- self._add_regression_line(ax, consump_data['Date'], consump_data['Consumption Hours'], label_prefix="Consumption Trend")
297
- ax.set_title(f'{self.client_name} - Daily Consumption Hours', fontsize=14)
298
- ax.grid(True, alpha=0.3)
299
- ax.legend()
300
- plt.tight_layout()
301
- plots.append(('consumption_hours', fig))
302
-
303
- ratio_df = ts_data[['Date', 'Streams', 'Plays']].copy()
304
- ratio_df['ratio'] = ratio_df['Streams'] / ratio_df['Plays'].replace(0, np.nan)
305
- ratio_df['ratio_30d_avg'] = ratio_df['ratio'].rolling(30, min_periods=1).mean()
306
- ratio_df.dropna(subset=['ratio_30d_avg'], inplace=True)
307
  if not ratio_df.empty:
308
- fig, ax = plt.subplots(figsize=(12, 6))
309
- ax.plot(ratio_df['Date'], ratio_df['ratio_30d_avg'], label='30-Day Avg Stream/Play Ratio', color='orange')
310
- self._add_regression_line(ax, ratio_df['Date'], ratio_df['ratio_30d_avg'], label_prefix="Ratio Trend")
311
- ax.set_title(f'{self.client_name} - Stream/Play Ratio (30-Day Average)', fontsize=14)
312
- ax.grid(True, alpha=0.3)
313
- ax.legend()
314
- plt.tight_layout()
315
- plots.append(('stream_play_ratio', fig))
316
-
317
- # Audience & Episode Distributions (All-Time)
318
- if 'apps' in self.all_time_data:
319
- fig, ax = plt.subplots(figsize=(8, 8))
320
- self.all_time_data['apps'].head(5).plot.pie(y='Percent of Plays', labels=self.all_time_data['apps']['App'].head(5), autopct='%1.1f%%', ax=ax, legend=False)
321
- ax.set_title(f'{self.client_name} - Platform Distribution', fontsize=14)
322
- ax.set_ylabel('')
323
- plt.tight_layout()
324
- plots.append(('platform_dist', fig))
325
-
326
- if 'devices' in self.all_time_data:
327
- fig, ax = plt.subplots(figsize=(8, 8))
328
- self.all_time_data['devices'].head(5).plot.pie(y='Percent of Plays', labels=self.all_time_data['devices']['Device'].head(5), autopct='%1.1f%%', ax=ax, legend=False)
329
- ax.set_title(f'{self.client_name} - Device Distribution', fontsize=14)
330
- ax.set_ylabel('')
331
- plt.tight_layout()
332
- plots.append(('device_dist', fig))
333
-
334
- if 'geo' in self.all_time_data:
335
- fig, ax = plt.subplots(figsize=(10, 6))
336
- top_geo = self.all_time_data['geo'].head(10)
337
- ax.barh(top_geo['Geo'], top_geo['Percent of Plays'] * 100, color='coral')
338
- ax.set_title(f'{self.client_name} - Top 10 Geographic Markets', fontsize=14)
339
- ax.invert_yaxis()
340
- ax.grid(True, alpha=0.3, axis='x')
341
- plt.tight_layout()
342
- plots.append(('geo_markets', fig))
343
-
344
- ep_data_all = self.all_time_data.get('episodes')
345
  if ep_data_all is not None:
346
- fig, ax = plt.subplots(figsize=(10, 6))
347
- ax.hist(ep_data_all['Streams & Downloads'], bins=30, color='skyblue', edgecolor='navy')
348
- ax.axvline(ep_data_all['Streams & Downloads'].mean(), color='red', linestyle='--', label='Mean')
349
- ax.set_title(f'{self.client_name} - Episode Performance Distribution (All Time)', fontsize=14)
350
- ax.legend()
351
- plt.tight_layout()
352
- plots.append(('ep_dist_all_time', fig))
353
-
354
  episodes_in_period = ep_data_all[(ep_data_all['Publish Date'] >= self.start_date) & (ep_data_all['Publish Date'] <= self.end_date)]
355
  if not episodes_in_period.empty:
356
- fig, ax = plt.subplots(figsize=(10, 6))
357
- ax.hist(episodes_in_period['Streams & Downloads'], bins=15, color='teal', edgecolor='darkslategray')
358
- ax.axvline(episodes_in_period['Streams & Downloads'].mean(), color='red', linestyle='--', label='Mean')
359
- ax.set_title(f'{self.client_name} - Episode Performance (Published in Period)', fontsize=14)
360
- ax.legend()
361
- plt.tight_layout()
362
- plots.append(('ep_dist_period', fig))
363
-
364
  return plots
365
 
366
  def _translate_title(self, hebrew_title):
367
  """Translates a Hebrew title to a short English legend title using Gemini."""
368
- if hebrew_title in self.title_translation_cache:
369
- return self.title_translation_cache[hebrew_title]
370
-
371
- if not self.gemini_api_key:
372
- return hebrew_title[:40] + '...'
373
-
374
  try:
375
- genai.configure(api_key=self.gemini_api_key)
376
- model = genai.GenerativeModel('gemini-2.0-flash-exp')
377
- prompt = f"""Analyze the Hebrew podcast title "{hebrew_title}". Generate a short, readable English legend title formatted as "[Guest Name] - #[Episode Number]". Transliterate the name. If there is no episode number, use only the name. If there is no name, create a concise English summary of the topic. If you recognize מהדורת מוסף in the title, then the output would be: "Investors Panel - #[Episode Number]".The final title must be under 5 words."""
378
- response = model.generate_content(prompt)
379
- time.sleep(1.5)
380
- translated = response.text.strip()
381
- self.title_translation_cache[hebrew_title] = translated
382
- return translated
383
- except Exception as e:
384
- print(f" -> Gemini API Error: {e}")
385
- return hebrew_title[:40] + '...'
386
 
387
  def generate_episode_specific_plots(self, max_episodes=10):
388
  """Generates the cumulative performance plots for individual episodes."""
389
  print("🚀 Generating episode-specific cumulative plots...")
390
  plots = []
391
  if not self.episode_specific_data: return plots
392
-
393
  for data_source in ['spotify', 'all_platforms']:
394
  ep_data_source = {t: d[data_source] for t, d in self.episode_specific_data.items() if data_source in d}
395
  if not ep_data_source: continue
396
-
397
- ep_totals = {title: df['value'].sum() for title, df in ep_data_source.items()}
398
- top_episodes = sorted(ep_totals, key=ep_totals.get, reverse=True)[:max_episodes]
399
-
400
- date_index = pd.date_range(start=self.start_date, end=self.end_date, freq='D')
401
- plot_df = pd.DataFrame(index=date_index)
402
-
403
- for title in top_episodes:
404
- plot_df = plot_df.join(ep_data_source[title].set_index('Date').rename(columns={'value': title}))
405
-
406
  cumulative_df = plot_df.fillna(0).cumsum()
407
- fig, ax = plt.subplots(figsize=(15, 8))
408
-
409
- for h_title in cumulative_df.columns:
410
- ax.plot(cumulative_df.index, cumulative_df[h_title], label=self._translate_title(h_title), linewidth=2.5)
411
-
412
- ax.set_title(f'Cumulative Performance by Date ({data_source.replace("_", " ").title()})', fontsize=16)
413
- ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left')
414
- plt.tight_layout()
415
- plots.append((f'ep_cumul_date_{data_source}', fig))
416
-
417
  airday_df = pd.DataFrame()
418
  for title in top_episodes:
419
- df = ep_data_source[title]
420
- first_play = df[df['value'] > 0]['Date'].min()
421
  if pd.isna(first_play): continue
422
- df_after = df[df['Date'] >= first_play].copy()
423
- airday_df[title] = df_after['value'].cumsum().reset_index(drop=True)
424
-
425
  airday_df['Average'] = airday_df.mean(axis=1)
426
  fig, ax = plt.subplots(figsize=(15, 8))
427
-
428
  for h_title in top_episodes:
429
- if h_title in airday_df.columns:
430
- ax.plot(airday_df.index + 1, airday_df[h_title], label=self._translate_title(h_title), alpha=0.8)
431
-
432
  ax.plot(airday_df.index + 1, airday_df['Average'], 'k--', label='Average', linewidth=2.5)
433
- ax.set_title(f'Cumulative Performance by Air Day ({data_source.replace("_", " ").title()})', fontsize=16)
434
- ax.set_xlabel('Days Since Release')
435
- ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left')
436
- plt.tight_layout()
437
- plots.append((f'ep_cumul_airday_{data_source}', fig))
438
-
439
  return plots
440
 
441
- # --- REPORTING AND ORCHESTRATION ---
442
-
443
  def generate_executive_summary(self, all_time_metrics, period_metrics, trends, seasonal):
444
  """Generates the final executive summary text."""
445
  summary = f"""# {self.client_name} - Podcast Performance Report
@@ -465,26 +291,21 @@ class ComprehensivePodcastReport:
465
  - **Engagement Rate (Streams/Plays)**: {period_metrics.get('engagement_percentage', 0):.1f}%
466
  - **Performance Benchmark (Top 25% of Episodes in Period)**: > {period_metrics.get('performance_benchmark_period', 0):,.0f} streams
467
  """
468
- if trends:
469
- summary += f"""
470
  ### Growth Trends (Comparison of 30-Day Sub-periods)
471
  - **Plays Growth (Median)**: {trends.get('plays_growth_rate_median', 0):+.1f}%
472
  - **Followers Gained**: {trends.get('followers_gained', 0):+,}
473
  - **Follower Growth Rate**: {trends.get('follower_growth_rate', 0):+.1f}% (vs. prior period)
474
  """
475
- if seasonal:
476
- summary += f"""
477
  ### Listening Patterns (Period)
478
  - **Best Day for Plays**: {seasonal.get('best_day')}
479
  - **Worst Day for Plays**: {seasonal.get('worst_day')}
480
  - **Weekly Listening Consistency**: {seasonal.get('weekly_consistency', 0):.1f}%
481
  """
482
  summary += "\n### Audience Insights (All-Time)\n"
483
- if 'geo' in self.all_time_data:
484
- summary += f"- **Primary Market**: {self.all_time_data['geo'].loc[0, 'Geo']} ({self.all_time_data['geo'].loc[0, 'Percent of Plays'] * 100:.1f}% of plays)\n"
485
- if 'apps' in self.all_time_data:
486
- summary += f"- **Platform Mix**: {self._get_platform_share('Spotify'):.1f}% Spotify, {self._get_platform_share('Apple Podcasts'):.1f}% Apple Podcasts\n"
487
-
488
  summary += "\n## 🏆 Top 5 Performing Episodes (All-Time)\n"
489
  ep_data = self.all_time_data.get('episodes')
490
  if ep_data is not None:
@@ -492,255 +313,135 @@ class ComprehensivePodcastReport:
492
  summary += f"{i}. **{row['Episode Title'][:60]}...**\n {row['Streams & Downloads']:,} streams | {row['Publish Date']:%B %Y}\n\n"
493
  return summary
494
 
495
- def run_full_analysis(self, uploaded_episode_files, episodes_in_period, gemini_api_key=None):
496
- """Orchestrates the entire analysis and report generation process."""
497
- self.gemini_api_key = gemini_api_key
498
- print("\n" + "="*60 + "\n🚀 STARTING FULL ANALYSIS & REPORT GENERATION\n" + "="*60)
499
- self.load_and_match_episode_csvs(uploaded_episode_files, episodes_in_period)
500
- all_time_metrics = self.calculate_key_metrics(use_all_time=True)
501
- period_metrics = self.calculate_key_metrics(use_all_time=False)
502
- trends = self.analyze_growth_trends()
503
- seasonal = self.analyze_seasonal_patterns()
504
- summary = self.generate_executive_summary(all_time_metrics, period_metrics, trends, seasonal)
505
- print("\n" + "="*60 + "\n📋 EXECUTIVE SUMMARY\n" + "="*60)
506
- print(summary)
507
- all_plots = self.generate_all_visualizations() + self.generate_episode_specific_plots()
508
- print("\n✅ Analysis Complete.")
509
- return summary, all_plots
510
-
511
-
512
- def process_uploaded_files(files):
513
- """Process uploaded files and return file content dictionary."""
514
- file_contents = {}
515
- if files is None:
516
- return file_contents
517
 
518
- # Handle both single file and list of files
519
- if not isinstance(files, list):
520
- files = [files]
 
 
 
 
521
 
522
- for file in files:
523
- if file is not None and hasattr(file, 'name'):
524
- # Read file content
525
- with open(file.name, 'r', encoding='utf-8') as f:
526
- content = f.read()
527
- file_contents[os.path.basename(file.name)] = content
528
- return file_contents
529
-
530
 
531
- def run_podcast_analysis(client_name, date_from, date_to, gemini_api_key, uploaded_files):
532
- """Main function to run the podcast analysis with Gradio inputs."""
 
 
533
  try:
534
- print(f"🎙️ Starting analysis for: {client_name}")
535
- print(f"📅 Date range: {date_from} to {date_to}")
536
-
537
- # Process uploaded files
538
- if not uploaded_files:
539
- return "❌ Error: No files uploaded. Please upload the required CSV files.", []
540
-
541
- file_contents = process_uploaded_files(uploaded_files)
542
- print(f"📁 Processed {len(file_contents)} files")
543
-
544
- # Separate general files from episode-specific files
545
- file_patterns = {
546
- 'time_series': 'OnSpotify',
547
- 'episodes': 'EpisodeRankings',
548
- 'geo': 'GeoLocation',
549
- 'apps': 'PlaysByApp',
550
- 'devices': 'PlaysByDevice',
551
- 'streams': 'StreamsAndDownloads'
552
- }
553
-
554
- general_files = {}
555
- episode_files = {}
556
-
557
- for filename, content in file_contents.items():
558
- is_general = False
559
- for file_type, pattern in file_patterns.items():
560
- if pattern in filename and not any(ep_pattern in filename for ep_pattern in ['episode', 'Episode']):
561
- general_files[file_type] = io.StringIO(content)
562
- is_general = True
563
- break
564
-
565
- if not is_general:
566
- episode_files[filename] = content
567
-
568
- if len(general_files) < 2: # At minimum need OnSpotify and EpisodeRankings
569
- return "❌ Error: Missing required general files. Please ensure you upload OnSpotify and EpisodeRankings CSV files.", []
570
-
571
- # Initialize analyzer
572
- analyzer = ComprehensivePodcastReport(client_name)
573
- analyzer.load_general_data(general_files)
574
-
575
- # Set date range
576
- if date_to:
577
- end_date = pd.to_datetime(date_to)
578
- else:
579
- end_date = get_now()
580
-
581
- if date_from:
582
- if isinstance(date_from, str) and date_from.isdigit():
583
- # If it's a number of days
584
- start_date = end_date - timedelta(days=int(date_from))
585
- else:
586
- start_date = pd.to_datetime(date_from)
587
- else:
588
- # Use earliest episode date if no start date provided
589
- start_date = analyzer.all_time_data['episodes']['Publish Date'].min()
590
-
591
- analyzer.filter_data_by_date(start_date, end_date)
592
-
593
- # Identify episodes in period
594
- episodes_in_period = analyzer.identify_and_prompt_for_episodes()
595
-
596
- # Run analysis
597
- summary, plots = analyzer.run_full_analysis(episode_files, episodes_in_period, gemini_api_key)
598
 
599
- # Convert plots to images for Gradio
600
- plot_images = []
601
- for plot_name, fig in plots:
602
- # Save figure to temporary file
603
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
604
- fig.savefig(temp_file.name, dpi=150, bbox_inches='tight')
605
- plt.close(fig) # Close the figure to free memory
606
- plot_images.append(temp_file.name)
607
-
608
- return summary, plot_images
609
-
610
- except Exception as e:
611
- import traceback
612
- error_msg = f"❌ Error during analysis: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
613
- print(error_msg)
614
- return error_msg, []
 
 
 
 
615
 
616
 
617
- # Create Gradio Interface
618
- def create_gradio_interface():
619
- """Create the Gradio interface for the podcast analytics tool."""
620
 
621
- with gr.Blocks(title="Valuebell Podcast Analytics", theme=gr.themes.Soft()) as demo:
622
- gr.HTML("""
623
- <div style="text-align: center; margin-bottom: 30px;">
624
- <h1>🎙️ Valuebell Podcast Analytics Dashboard</h1>
625
- <p style="font-size: 18px; color: #666;">
626
- Upload your podcast CSV files to generate comprehensive performance reports
627
- </p>
628
- </div>
629
- """)
630
-
631
- with gr.Row():
632
- with gr.Column(scale=1):
633
- gr.HTML("<h3>📋 Configuration</h3>")
634
-
635
- client_name = gr.Textbox(
636
- label="Client/Podcast Name",
637
- placeholder="Enter the podcast name...",
638
- value="My Podcast"
639
- )
640
-
641
- with gr.Row():
642
- date_from = gr.Textbox(
643
- label="Start Date",
644
- placeholder="YYYY-MM-DD or number of days (e.g., '60' for last 60 days)",
645
- value="60"
646
- )
647
- date_to = gr.Textbox(
648
- label="End Date (optional)",
649
- placeholder="YYYY-MM-DD (leave empty for today)"
650
- )
651
-
652
- gemini_api_key = gr.Textbox(
653
- label="Gemini API Key (optional)",
654
- placeholder="For Hebrew title translation...",
655
- type="password"
656
- )
657
-
658
- gr.HTML("<h3>📁 File Uploads</h3>")
659
- gr.HTML("""
660
- <div style="background-color: #f0f8ff; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
661
- <h4>How to Upload:</h4>
662
- <ul>
663
- <li><strong>Drag & Drop:</strong> Simply drag all your CSV files onto the upload area</li>
664
- <li><strong>Click to Browse:</strong> Click the upload area to select multiple files at once</li>
665
- <li><strong>Bulk Upload:</strong> Upload 20+ files simultaneously - no individual file limits!</li>
666
- <li><strong>Folder Upload:</strong> Select an entire folder containing your CSV files</li>
667
- </ul>
668
- <h4>Required Files:</h4>
669
- <ul>
670
- <li><strong>OnSpotify</strong> CSV (daily plays data)</li>
671
- <li><strong>EpisodeRankings</strong> CSV (episode performance data)</li>
672
- </ul>
673
- <h4>Optional Files:</h4>
674
- <ul>
675
- <li><strong>StreamsAndDownloads</strong> CSV (all platforms data)</li>
676
- <li><strong>GeoLocation</strong> CSV (geographic data)</li>
677
- <li><strong>PlaysByApp</strong> CSV (platform distribution)</li>
678
- <li><strong>PlaysByDevice</strong> CSV (device distribution)</li>
679
- <li>Individual episode CSV files (for detailed episode analysis)</li>
680
- </ul>
681
- </div>
682
- """)
683
-
684
- # Bulk file upload - much cleaner!
685
- files_upload = gr.File(
686
- label="📁 Upload All CSV Files (or drag & drop)",
687
- file_types=[".csv"],
688
- file_count="multiple",
689
- height=120
690
- )
691
-
692
- # Alternative: Directory upload for advanced users
693
- gr.HTML("<p style='text-align: center; margin: 10px 0; color: #666; font-size: 14px;'>💡 Tip: You can also select and upload an entire folder containing your CSV files</p>")
694
-
695
- analyze_btn = gr.Button("🚀 Generate Analytics Report", variant="primary", size="lg")
696
 
697
  with gr.Column(scale=2):
698
- gr.HTML("<h3>📊 Results</h3>")
699
-
700
- summary_output = gr.Markdown(
701
- label="Executive Summary",
702
- value="Upload files and click 'Generate Analytics Report' to see results..."
703
- )
704
-
705
- plots_output = gr.Gallery(
706
- label="Performance Visualizations",
707
- show_label=True,
708
- elem_id="plots-gallery",
709
- columns=2,
710
- rows=3,
711
- height="auto"
712
- )
713
-
714
- # Set up the analysis function
715
- analyze_btn.click(
716
- fn=run_podcast_analysis,
717
- inputs=[client_name, date_from, date_to, gemini_api_key, files_upload],
718
- outputs=[summary_output, plots_output],
719
- show_progress=True
720
- )
721
 
722
- gr.HTML("""
723
- <div style="text-align: center; margin-top: 30px; padding: 20px; background-color: #f8f9fa; border-radius: 8px;">
724
- <h4>💡 Tips for Best Results:</h4>
725
- <ul style="text-align: left; display: inline-block;">
726
- <li>Drag and drop all your CSV files at once for fastest upload</li>
727
- <li>Ensure your CSV files follow Spotify for Creators naming conventions</li>
728
- <li>For Hebrew podcasts, provide a Gemini API key for title translation</li>
729
- <li>Include episode-specific CSV files for detailed performance tracking</li>
730
- <li>Use date ranges that cover complete weeks for better trend analysis</li>
731
- </ul>
732
- </div>
733
- """)
734
-
735
- return demo
736
-
 
 
 
737
 
738
  if __name__ == "__main__":
739
- # Create and launch the Gradio interface
740
- demo = create_gradio_interface()
741
- demo.launch(
742
- share=True,
743
- server_name="0.0.0.0",
744
- server_port=7860,
745
- show_error=True
746
- )
 
10
  import time
11
  from difflib import SequenceMatcher
12
  import gradio as gr
 
 
 
13
  import os
14
 
15
  # Suppress warnings for a cleaner output
16
  warnings.filterwarnings('ignore')
17
 
18
+ # Attempt to import Google Generative AI
19
+ try:
20
+ import google.generativeai as genai
21
+ IS_GENAI_AVAILABLE = True
22
+ except ImportError:
23
+ IS_GENAI_AVAILABLE = False
24
+ print("Warning: google-generativeai library not found. Title translation will be disabled.")
25
+
26
  def get_now():
27
+ """A simple function to get the current time."""
28
  return datetime.now()
29
 
30
+ # ==============================================================================
31
+ # Paste the entire ComprehensivePodcastReport class here
32
+ # ==============================================================================
33
  class ComprehensivePodcastReport:
34
  """
35
  Generates a complete podcast performance report, combining overall analytics
 
48
  self.date_range_str = "All Time"
49
  self.start_date = None
50
  self.end_date = None
 
 
 
51
 
52
  def _fix_spotify_timestamps(self, timestamp_series):
53
  """Fix Spotify's invalid '24:00:00' timestamps."""
 
66
  print(f"❌ Missing a required file: {e}. Please include OnSpotify and EpisodeRankings files.")
67
  raise
68
 
 
69
  if 'streams' in file_paths:
70
  self.all_time_data['streams'] = pd.read_csv(file_paths['streams'])
71
  self.all_time_data['streams']['Date'] = pd.to_datetime(self._fix_spotify_timestamps(self.all_time_data['streams']['Time (UTC)']))
 
87
  self.end_date = pd.to_datetime(end_date).normalize()
88
  self.date_range_str = f"{self.start_date.strftime('%Y-%m-%d')} to {self.end_date.strftime('%Y-%m-%d')}"
89
  print(f"🔎 Filtering data for period: {self.date_range_str}")
 
90
  for key in ['time_series', 'streams']:
91
  if key in self.period_data:
92
  df = self.period_data[key]
93
  self.period_data[key] = df[(df['Date'] >= self.start_date) & (df['Date'] <= self.end_date)]
94
 
 
 
95
  def _normalize_text(self, text):
96
  """Normalizes text for fuzzy string matching."""
97
+ return re.sub(r'[^\u0590-\u05FFa-zA-Z0-9\-]', '', str(text).replace(':', '').replace(' ', '')).lower()
 
98
 
99
+ def identify_episodes_in_period(self):
100
+ """Identifies episodes in the period and returns a formatted string and the dataframe."""
101
  episodes_df = self.all_time_data.get('episodes')
102
+ if episodes_df is None: return "⚠️ EpisodeRankings data is missing.", pd.DataFrame()
103
+ episodes_in_period = episodes_df[(episodes_df['Publish Date'] >= self.start_date) & (episodes_df['Publish Date'] <= self.end_date)].sort_values('Publish Date', ascending=False).reset_index(drop=True)
104
+ if episodes_in_period.empty:
105
+ return "✅ No episodes were published in the selected period. You can proceed to generate the report for general stats.", episodes_in_period
106
+
107
+ output_str = f"📺 Found **{len(episodes_in_period)}** episodes published in the period. Please upload their individual CSVs below:\n\n"
108
+ for _, row in episodes_in_period.iterrows():
109
+ output_str += f"- **{row['Episode Title']}** (Published: {row['Publish Date']:%Y-%m-%d})\n"
110
+ return output_str, episodes_in_period
 
 
 
 
 
 
 
 
111
 
112
  def load_and_match_episode_csvs(self, uploaded_files, episodes_in_period):
113
  """Matches and loads individual episode CSVs from uploaded files."""
114
+ if not uploaded_files or episodes_in_period.empty: return
115
  print("\n🔍 Matching and loading individual episode CSVs...")
 
 
 
116
  episodes_in_period['normalized_title'] = episodes_in_period['Episode Title'].apply(self._normalize_text)
117
+ for file_obj in uploaded_files:
118
+ filename = os.path.basename(file_obj.name)
119
  file_type = 'spotify' if 'OnSpotify' in filename else 'all_platforms' if 'StreamsAndDownloads' in filename else None
120
  if not file_type: continue
 
121
  clean_filename = re.sub(r'\s*\(\d+\)|\s+\d+(?=\.csv)', '', filename)
122
  normalized_filename = self._normalize_text(clean_filename)
123
+ episodes_in_period['similarity'] = episodes_in_period['normalized_title'].apply(lambda title: SequenceMatcher(None, normalized_filename, title).ratio())
 
 
124
  best_match = episodes_in_period.loc[episodes_in_period['similarity'].idxmax()]
 
125
  if best_match['similarity'] > 0.5:
126
  episode_title = best_match['Episode Title']
127
  print(f" ✅ Matched: {filename[:40]}... -> {episode_title[:40]}...")
128
  try:
129
+ with open(file_obj.name, 'r', encoding='utf-8') as f:
130
+ df = pd.read_csv(f)
131
  df['Date'] = pd.to_datetime(df['Time (UTC)'].str.split(',').str[0], errors='coerce').dt.normalize()
132
  value_col = next((col for col in ['Plays', 'Streams & Downloads'] if col in df.columns), None)
133
  if not value_col: continue
 
136
  self.episode_specific_data[episode_title][file_type] = episode_df
137
  except Exception as e:
138
  print(f" -> Error processing file {filename}: {e}")
 
 
 
 
139
 
140
  def calculate_key_metrics(self, use_all_time=False):
141
  """Calculate core performance metrics."""
 
146
  current_followers = int(ts_followers_cleaned['Followers'].iloc[-1]) if not ts_followers_cleaned.empty else 0
147
  total_plays = ts_data['Plays'].sum()
148
  total_streams = ts_data['Streams'].sum()
149
+ metrics = {'total_plays': int(total_plays), 'total_streams': int(total_streams), 'avg_daily_plays': ts_data['Plays'].mean(), 'engagement_percentage': (total_streams / max(total_plays, 1)) * 100, 'current_followers': current_followers}
 
 
 
 
 
 
150
  if use_all_time:
151
  ep_data = self.all_time_data.get('episodes', pd.DataFrame())
152
+ metrics.update({'total_episodes': len(ep_data), 'median_streams_per_episode': ep_data['Streams & Downloads'].median() if not ep_data.empty else 0, 'performance_benchmark': ep_data['Streams & Downloads'].quantile(0.75) if not ep_data.empty else 0})
153
+ else:
 
 
 
 
154
  ep_data_all = self.all_time_data.get('episodes', pd.DataFrame())
155
  episodes_in_period = ep_data_all[(ep_data_all['Publish Date'] >= self.start_date) & (ep_data_all['Publish Date'] <= self.end_date)]
156
  metrics['performance_benchmark_period'] = episodes_in_period['Streams & Downloads'].quantile(0.75) if not episodes_in_period.empty else 0
 
165
  if recent_period.empty or previous_period.empty: return {}
166
  recent_gain = recent_period['Followers'].iloc[-1] - recent_period['Followers'].iloc[0]
167
  previous_gain = previous_period['Followers'].iloc[-1] - previous_period['Followers'].iloc[0]
168
+ return {'plays_growth_rate_median': ((recent_period['Plays'].median() - previous_period['Plays'].median()) / max(previous_period['Plays'].median(), 1)) * 100, 'followers_gained': int(recent_gain), 'follower_growth_rate': ((recent_gain - previous_gain) / max(abs(previous_gain), 1)) * 100 if previous_gain != 0 else float('inf')}
 
 
 
 
169
 
170
  def analyze_seasonal_patterns(self):
171
  """Analyze weekly listening patterns."""
 
173
  if len(ts_data) < 7: return {}
174
  ts_data['DayOfWeek'] = ts_data['Date'].dt.day_name()
175
  weekly_avg = ts_data.groupby('DayOfWeek')['Plays'].mean()
176
+ return {'best_day': weekly_avg.idxmax(), 'worst_day': weekly_avg.idxmin(), 'weekly_consistency': (1 - (weekly_avg.std() / weekly_avg.mean())) * 100 if weekly_avg.mean() > 0 else 0}
 
 
 
177
 
178
  def _get_platform_share(self, platform_name):
179
  """Helper to get platform share from all-time data."""
 
182
  platform_row = apps_df[apps_df['App'] == platform_name]
183
  return platform_row['Percent of Plays'].iloc[0] * 100 if not platform_row.empty else 0.0
184
 
 
 
185
  def _add_regression_line(self, ax, x_values, y_values, **kwargs):
186
  """Helper to add a linear regression trendline to a plot."""
187
  if len(x_values) < 2: return
 
196
  print("🎨 Generating all performance visualizations...")
197
  plots = []
198
  ts_data = self.period_data['time_series'].sort_values('Date')
 
 
199
  if not ts_data.empty:
200
+ fig, ax = plt.subplots(figsize=(12, 6)); ax.plot(ts_data['Date'], ts_data['Plays'], label='Daily Plays (Spotify)', color='blue'); self._add_regression_line(ax, ts_data['Date'], ts_data['Plays']); ax.set_title(f'{self.client_name} - Daily Plays (OnSpotify)', fontsize=14); ax.grid(True, alpha=0.3); ax.legend(); plt.tight_layout(); plots.append(fig)
 
 
 
 
 
 
 
 
201
  if 'streams' in self.period_data and not self.period_data['streams'].empty:
202
+ streams_data = self.period_data['streams'].sort_values('Date'); fig, ax = plt.subplots(figsize=(12, 6)); ax.plot(streams_data['Date'], streams_data['Streams & Downloads'], label='Daily Streams & Downloads', color='green'); self._add_regression_line(ax, streams_data['Date'], streams_data['Streams & Downloads']); ax.set_title(f'{self.client_name} - Daily Streams & Downloads (All Platforms)', fontsize=14); ax.grid(True, alpha=0.3); ax.legend(); plt.tight_layout(); plots.append(fig)
 
 
 
 
 
 
 
 
 
 
203
  graph_start = self.start_date.replace(day=1) if self.start_date.day != 1 else self.start_date
204
  for key, col, color in [('time_series', 'Plays', 'skyblue'), ('streams', 'Streams & Downloads', 'lightgreen')]:
205
  if key in self.all_time_data:
206
+ monthly_data = self.all_time_data[key]; monthly_data = monthly_data[(monthly_data['Date'] >= graph_start) & (monthly_data['Date'] <= self.end_date)]
 
207
  if not monthly_data.empty:
208
+ monthly_data['YearMonth'] = monthly_data['Date'].dt.to_period('M'); monthly_values = monthly_data.groupby('YearMonth')[col].sum()
209
+ fig, ax = plt.subplots(figsize=(12, 6)); bars = ax.bar(np.arange(len(monthly_values)), monthly_values.values, color=color, edgecolor='navy'); self._add_regression_line(ax, np.arange(len(monthly_values)), monthly_values); ax.set_xticks(np.arange(len(monthly_values))); ax.set_xticklabels([str(p) for p in monthly_values.index], rotation=45); ax.set_title(f'{self.client_name} - Monthly {col}', fontsize=14); ax.legend(); plt.tight_layout()
210
+ current_month = pd.Period(get_now(), 'M');
211
+ if current_month in monthly_values.index: bars[monthly_values.index.get_loc(current_month)].set_color('orange')
212
+ plots.append(fig)
213
+ follower_data = ts_data.dropna(subset=['Followers']);
 
 
 
 
 
 
 
 
 
 
 
214
  if not follower_data.empty:
215
+ fig, ax = plt.subplots(figsize=(12, 6)); ax.plot(follower_data['Date'], follower_data['Followers'], label='Followers', color='purple'); self._add_regression_line(ax, follower_data['Date'], follower_data['Followers'], label_prefix="Follower Trend", exclude_last=True); ax.set_title(f'{self.client_name} - Follower Growth', fontsize=14); ax.grid(True, alpha=0.3); ax.legend(); plt.tight_layout(); plots.append(fig)
 
 
 
 
 
 
 
 
216
  consump_data = ts_data.dropna(subset=['Consumption Hours'])
217
  if not consump_data.empty and consump_data['Consumption Hours'].sum() > 0:
218
+ fig, ax = plt.subplots(figsize=(12, 6)); ax.plot(consump_data['Date'], consump_data['Consumption Hours'], label='Hours', color='teal'); self._add_regression_line(ax, consump_data['Date'], consump_data['Consumption Hours'], label_prefix="Consumption Trend", exclude_last=True); ax.set_title(f'{self.client_name} - Daily Consumption Hours', fontsize=14); ax.grid(True, alpha=0.3); ax.legend(); plt.tight_layout(); plots.append(fig)
219
+ ratio_df = ts_data[['Date', 'Streams', 'Plays']].copy(); ratio_df['ratio'] = ratio_df['Streams'] / ratio_df['Plays'].replace(0, np.nan); ratio_df['ratio_30d_avg'] = ratio_df['ratio'].rolling(30, min_periods=1).mean(); ratio_df.dropna(subset=['ratio_30d_avg'], inplace=True)
 
 
 
 
 
 
 
 
 
 
 
220
  if not ratio_df.empty:
221
+ fig, ax = plt.subplots(figsize=(12, 6)); ax.plot(ratio_df['Date'], ratio_df['ratio_30d_avg'], label='30-Day Avg Stream/Play Ratio', color='orange'); self._add_regression_line(ax, ratio_df['Date'], ratio_df['ratio_30d_avg'], label_prefix="Ratio Trend"); ax.set_title(f'{self.client_name} - Stream/Play Ratio (30-Day Average)', fontsize=14); ax.grid(True, alpha=0.3); ax.legend(); plt.tight_layout(); plots.append(fig)
222
+ if 'apps' in self.all_time_data: fig, ax = plt.subplots(figsize=(8, 8)); self.all_time_data['apps'].head(5).plot.pie(y='Percent of Plays', labels=self.all_time_data['apps']['App'].head(5), autopct='%1.1f%%', ax=ax, legend=False); ax.set_title(f'{self.client_name} - Platform Distribution', fontsize=14); ax.set_ylabel(''); plt.tight_layout(); plots.append(fig)
223
+ if 'devices' in self.all_time_data: fig, ax = plt.subplots(figsize=(8, 8)); self.all_time_data['devices'].head(5).plot.pie(y='Percent of Plays', labels=self.all_time_data['devices']['Device'].head(5), autopct='%1.1f%%', ax=ax, legend=False); ax.set_title(f'{self.client_name} - Device Distribution', fontsize=14); ax.set_ylabel(''); plt.tight_layout(); plots.append(fig)
224
+ if 'geo' in self.all_time_data: fig, ax = plt.subplots(figsize=(10, 6)); top_geo = self.all_time_data['geo'].head(10); ax.barh(top_geo['Geo'], top_geo['Percent of Plays'] * 100, color='coral'); ax.set_title(f'{self.client_name} - Top 10 Geographic Markets', fontsize=14); ax.invert_yaxis(); ax.grid(True, alpha=0.3, axis='x'); plt.tight_layout(); plots.append(fig)
225
+ ep_data_all = self.all_time_data.get('episodes');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  if ep_data_all is not None:
227
+ fig, ax = plt.subplots(figsize=(10, 6)); ax.hist(ep_data_all['Streams & Downloads'], bins=30, color='skyblue', edgecolor='navy'); ax.axvline(ep_data_all['Streams & Downloads'].mean(), color='red', linestyle='--', label='Mean'); ax.set_title(f'{self.client_name} - Episode Performance Distribution (All Time)', fontsize=14); ax.legend(); plt.tight_layout(); plots.append(fig)
 
 
 
 
 
 
 
228
  episodes_in_period = ep_data_all[(ep_data_all['Publish Date'] >= self.start_date) & (ep_data_all['Publish Date'] <= self.end_date)]
229
  if not episodes_in_period.empty:
230
+ fig, ax = plt.subplots(figsize=(10, 6)); ax.hist(episodes_in_period['Streams & Downloads'], bins=15, color='teal', edgecolor='darkslategray'); ax.axvline(episodes_in_period['Streams & Downloads'].mean(), color='red', linestyle='--', label='Mean'); ax.set_title(f'{self.client_name} - Episode Performance (Published in Period)', fontsize=14); ax.legend(); plt.tight_layout(); plots.append(fig)
 
 
 
 
 
 
 
231
  return plots
232
 
233
  def _translate_title(self, hebrew_title):
234
  """Translates a Hebrew title to a short English legend title using Gemini."""
235
+ if hebrew_title in self.title_translation_cache: return self.title_translation_cache[hebrew_title]
236
+ if not IS_GENAI_AVAILABLE: return hebrew_title[:40] + '...'
 
 
 
 
237
  try:
238
+ model = genai.GenerativeModel('gemini-2.5-flash'); prompt = f"""Analyze the Hebrew podcast title "{hebrew_title}". Generate a short, readable English legend title formatted as "[Guest Name] - #[Episode Number]". Transliterate the name. If there is no episode number, use only the name. If there is no name, create a concise English summary of the topic. If you recognize מהדורת מוסף in the title, then the output would be: "Investors Panel - #[Episode Number]".The final title must be under 5 words."""; response = model.generate_content(prompt); time.sleep(1.5); translated = response.text.strip(); self.title_translation_cache[hebrew_title] = translated; return translated
239
+ except Exception as e: print(f" -> Gemini API Error: {e}"); return hebrew_title[:40] + '...'
 
 
 
 
 
 
 
 
 
240
 
241
  def generate_episode_specific_plots(self, max_episodes=10):
242
  """Generates the cumulative performance plots for individual episodes."""
243
  print("🚀 Generating episode-specific cumulative plots...")
244
  plots = []
245
  if not self.episode_specific_data: return plots
 
246
  for data_source in ['spotify', 'all_platforms']:
247
  ep_data_source = {t: d[data_source] for t, d in self.episode_specific_data.items() if data_source in d}
248
  if not ep_data_source: continue
249
+ ep_totals = {title: df['value'].sum() for title, df in ep_data_source.items()}; top_episodes = sorted(ep_totals, key=ep_totals.get, reverse=True)[:max_episodes]
250
+ date_index = pd.date_range(start=self.start_date, end=self.end_date, freq='D'); plot_df = pd.DataFrame(index=date_index)
251
+ for title in top_episodes: plot_df = plot_df.join(ep_data_source[title].set_index('Date').rename(columns={'value': title}))
 
 
 
 
 
 
 
252
  cumulative_df = plot_df.fillna(0).cumsum()
253
+ fig, ax = plt.subplots(figsize=(15, 8));
254
+ for h_title in cumulative_df.columns: ax.plot(cumulative_df.index, cumulative_df[h_title], label=self._translate_title(h_title), linewidth=2.5)
255
+ ax.set_title(f'Cumulative Performance by Date ({data_source.replace("_", " ").title()})', fontsize=16); ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left'); plt.tight_layout(); plots.append(fig)
 
 
 
 
 
 
 
256
  airday_df = pd.DataFrame()
257
  for title in top_episodes:
258
+ df = ep_data_source[title]; first_play = df[df['value'] > 0]['Date'].min();
 
259
  if pd.isna(first_play): continue
260
+ df_after = df[df['Date'] >= first_play].copy(); airday_df[title] = df_after['value'].cumsum().reset_index(drop=True)
 
 
261
  airday_df['Average'] = airday_df.mean(axis=1)
262
  fig, ax = plt.subplots(figsize=(15, 8))
 
263
  for h_title in top_episodes:
264
+ if h_title in airday_df.columns: ax.plot(airday_df.index + 1, airday_df[h_title], label=self._translate_title(h_title), alpha=0.8)
 
 
265
  ax.plot(airday_df.index + 1, airday_df['Average'], 'k--', label='Average', linewidth=2.5)
266
+ ax.set_title(f'Cumulative Performance by Air Day ({data_source.replace("_", " ").title()})', fontsize=16); ax.set_xlabel('Days Since Release'); ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left'); plt.tight_layout(); plots.append(fig)
 
 
 
 
 
267
  return plots
268
 
 
 
269
  def generate_executive_summary(self, all_time_metrics, period_metrics, trends, seasonal):
270
  """Generates the final executive summary text."""
271
  summary = f"""# {self.client_name} - Podcast Performance Report
 
291
  - **Engagement Rate (Streams/Plays)**: {period_metrics.get('engagement_percentage', 0):.1f}%
292
  - **Performance Benchmark (Top 25% of Episodes in Period)**: > {period_metrics.get('performance_benchmark_period', 0):,.0f} streams
293
  """
294
+ if trends: summary += f"""
 
295
  ### Growth Trends (Comparison of 30-Day Sub-periods)
296
  - **Plays Growth (Median)**: {trends.get('plays_growth_rate_median', 0):+.1f}%
297
  - **Followers Gained**: {trends.get('followers_gained', 0):+,}
298
  - **Follower Growth Rate**: {trends.get('follower_growth_rate', 0):+.1f}% (vs. prior period)
299
  """
300
+ if seasonal: summary += f"""
 
301
  ### Listening Patterns (Period)
302
  - **Best Day for Plays**: {seasonal.get('best_day')}
303
  - **Worst Day for Plays**: {seasonal.get('worst_day')}
304
  - **Weekly Listening Consistency**: {seasonal.get('weekly_consistency', 0):.1f}%
305
  """
306
  summary += "\n### Audience Insights (All-Time)\n"
307
+ if 'geo' in self.all_time_data: summary += f"- **Primary Market**: {self.all_time_data['geo'].loc[0, 'Geo']} ({self.all_time_data['geo'].loc[0, 'Percent of Plays'] * 100:.1f}% of plays)\n"
308
+ if 'apps' in self.all_time_data: summary += f"- **Platform Mix**: {self._get_platform_share('Spotify'):.1f}% Spotify, {self._get_platform_share('Apple Podcasts'):.1f}% Apple Podcasts\n"
 
 
 
309
  summary += "\n## 🏆 Top 5 Performing Episodes (All-Time)\n"
310
  ep_data = self.all_time_data.get('episodes')
311
  if ep_data is not None:
 
313
  summary += f"{i}. **{row['Episode Title'][:60]}...**\n {row['Streams & Downloads']:,} streams | {row['Publish Date']:%B %Y}\n\n"
314
  return summary
315
 
316
+ # ==============================================================================
317
+ # Gradio specific functions
318
+ # ==============================================================================
319
+
320
+ def process_step_1(api_key, client_name, date_from_str, date_to_str, general_files):
321
+ """Handles the first step of the analysis."""
322
+ if not client_name or not date_from_str or not general_files:
323
+ return None, "", None, gr.update(visible=False), gr.update(visible=False)
324
+
325
+ if IS_GENAI_AVAILABLE and api_key:
326
+ try:
327
+ genai.configure(api_key=api_key)
328
+ print("Gemini API Key configured.")
329
+ except Exception as e:
330
+ print(f"Error configuring Gemini API: {e}")
 
 
 
 
 
 
 
331
 
332
+ file_patterns = {'time_series': 'OnSpotify', 'episodes': 'EpisodeRankings', 'geo': 'GeoLocation', 'apps': 'PlaysByApp', 'devices': 'PlaysByDevice', 'streams': 'StreamsAndDownloads'}
333
+ detected_files = {}
334
+ for f in general_files:
335
+ fname = os.path.basename(f.name)
336
+ for ftype, pattern in file_patterns.items():
337
+ if pattern in fname:
338
+ detected_files[ftype] = f.name
339
 
340
+ if 'time_series' not in detected_files or 'episodes' not in detected_files:
341
+ raise gr.Error("Required files not found. Please upload at least OnSpotify and EpisodeRankings CSVs.")
 
 
 
 
 
 
342
 
343
+ analyzer = ComprehensivePodcastReport(client_name)
344
+ analyzer.load_general_data(detected_files)
345
+
346
+ end_date = pd.to_datetime(date_to_str) if date_to_str else get_now()
347
  try:
348
+ date_from = int(date_from_str)
349
+ start_date = end_date - timedelta(days=date_from)
350
+ except ValueError:
351
+ start_date = pd.to_datetime(date_from_str)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
 
353
+ analyzer.filter_data_by_date(start_date, end_date)
354
+
355
+ episode_list_md, episodes_in_period_df = analyzer.identify_episodes_in_period()
356
+
357
+ # Store the dataframe as a JSON string in the state
358
+ episodes_in_period_json = episodes_in_period_df.to_json(orient='split', date_format='iso')
359
+
360
+ return analyzer, episode_list_md, episodes_in_period_json, gr.update(visible=True), gr.update(visible=True)
361
+
362
+
363
+ def process_step_2(analyzer, episodes_in_period_json, episode_files):
364
+ """Handles the final report generation."""
365
+ if analyzer is None or episodes_in_period_json is None:
366
+ return "Error: Initial processing step was not completed.", [], [], []
367
+
368
+ # Reconstruct dataframe from JSON
369
+ episodes_in_period_df = pd.read_json(io.StringIO(episodes_in_period_json), orient='split')
370
+ # Convert date columns back to datetime
371
+ if 'Publish Date' in episodes_in_period_df.columns:
372
+ episodes_in_period_df['Publish Date'] = pd.to_datetime(episodes_in_period_df['Publish Date'], unit='ms')
373
 
374
 
375
+ analyzer.load_and_match_episode_csvs(episode_files, episodes_in_period_df)
 
 
376
 
377
+ all_time_metrics = analyzer.calculate_key_metrics(use_all_time=True)
378
+ period_metrics = analyzer.calculate_key_metrics(use_all_time=False)
379
+ trends = analyzer.analyze_growth_trends()
380
+ seasonal = analyzer.analyze_seasonal_patterns()
381
+
382
+ summary = analyzer.generate_executive_summary(all_time_metrics, period_metrics, trends, seasonal)
383
+
384
+ general_plots = analyzer.generate_all_visualizations()
385
+ episode_plots = analyzer.generate_episode_specific_plots()
386
+
387
+ all_plots = general_plots + episode_plots
388
+
389
+ # Pad the plots list with Nones if fewer than max plots are generated
390
+ num_plots_to_return = 20 # Should match the number of gr.Plot outputs
391
+ padded_plots = all_plots + [None] * (num_plots_to_return - len(all_plots))
392
+
393
+ return [summary] + padded_plots
394
+
395
+
396
+ # ==============================================================================
397
+ # Gradio UI Layout
398
+ # ==============================================================================
399
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
400
+ gr.Markdown("# 🎙️ Comprehensive Podcast Analytics Report Generator")
401
+ gr.Markdown("A tool to generate in-depth performance reports from Spotify for Podcasters CSV exports.")
402
+
403
+ analyzer_state = gr.State(None)
404
+ episodes_df_state = gr.State(None)
405
+
406
+ with gr.Row():
407
+ with gr.Column(scale=1):
408
+ gr.Markdown("## Step 1: Initial Setup")
409
+ api_key_input = gr.Textbox(label="Gemini API Key", type="password", placeholder="Enter your key for title translation")
410
+ client_name_input = gr.Textbox(label="Client / Podcast Name", placeholder="e.g., The Co-Pilot Podcast")
411
+ date_from_input = gr.Textbox(label="Start Date or Period", placeholder="e.g., 60 (for last 60 days) or 2025-07-01")
412
+ date_to_input = gr.Textbox(label="End Date (Optional)", placeholder="e.g., 2025-08-18 (defaults to today)")
413
+ general_files_input = gr.File(label="Upload General CSVs (OnSpotify, EpisodeRankings, etc.)", file_count="multiple")
414
+ step1_button = gr.Button("1. Process General Files", variant="secondary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
 
416
  with gr.Column(scale=2):
417
+ with gr.Box(visible=False) as step2_box:
418
+ gr.Markdown("## Step 2: Upload Episode Specifics")
419
+ episode_list_output = gr.Markdown("...")
420
+ episode_files_input = gr.File(label="Upload Individual Episode CSVs", file_count="multiple")
421
+ step2_button = gr.Button("2. Generate Full Report", variant="primary")
422
+
423
+ with gr.Box(visible=False) as output_box:
424
+ gr.Markdown("--- \n ## 📊 Full Report")
425
+ summary_output = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
 
427
+ # Create a grid for plots
428
+ plot_outputs = []
429
+ for i in range(5): # 5 rows
430
+ with gr.Row():
431
+ for j in range(4): # 4 columns
432
+ plot_outputs.append(gr.Plot())
433
+
434
+ step1_button.click(
435
+ fn=process_step_1,
436
+ inputs=[api_key_input, client_name_input, date_from_input, date_to_input, general_files_input],
437
+ outputs=[analyzer_state, episode_list_output, episodes_df_state, step2_box, output_box]
438
+ )
439
+
440
+ step2_button.click(
441
+ fn=process_step_2,
442
+ inputs=[analyzer_state, episodes_df_state, episode_files_input],
443
+ outputs=[summary_output] + plot_outputs
444
+ )
445
 
446
  if __name__ == "__main__":
447
+ demo.launch(debug=True)