rairo commited on
Commit
680ccc9
·
verified ·
1 Parent(s): e55bf70

Delete sozo_gen.py

Browse files
Files changed (1) hide show
  1. sozo_gen.py +0 -872
sozo_gen.py DELETED
@@ -1,872 +0,0 @@
1
- # sozo_gen.py
2
-
3
- import os
4
- import re
5
- import json
6
- import logging
7
- import uuid
8
- import io
9
- from pathlib import Path
10
- import pandas as pd
11
- import numpy as np
12
- import matplotlib
13
- matplotlib.use("Agg")
14
- import matplotlib.pyplot as plt
15
- from matplotlib.animation import FuncAnimation, FFMpegWriter
16
- import seaborn as sns
17
- from scipy import stats
18
- from PIL import Image, ImageDraw, ImageFont
19
- import cv2
20
- import inspect
21
- import tempfile
22
- import subprocess
23
- from typing import Dict, List, Tuple, Any
24
- from langchain_google_genai import ChatGoogleGenerativeAI
25
- from google import genai
26
- import requests
27
- # In sozo_gen.py, near the other google imports
28
- from google.genai import types as genai_types
29
- import math # Add this import at the top of your sozo_gen.py file
30
- import shutil
31
- # --- Configuration ---
32
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - [%(funcName)s] - %(message)s')
33
- FPS, WIDTH, HEIGHT = 24, 1280, 720
34
- MAX_CHARTS, VIDEO_SCENES = 5, 5
35
- MAX_CONTEXT_TOKENS = 750000
36
-
37
- # --- API Initialization ---
38
- API_KEY = os.getenv("GOOGLE_API_KEY")
39
- if not API_KEY:
40
- raise ValueError("GOOGLE_API_KEY environment variable not set.")
41
-
42
- PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
43
-
44
- # --- Helper Functions ---
45
- def load_dataframe_safely(buf, name: str):
46
- ext = Path(name).suffix.lower()
47
- df = (pd.read_excel if ext in (".xlsx", ".xls") else pd.read_csv)(buf)
48
- df.columns = df.columns.astype(str).str.strip()
49
- df = df.dropna(how="all")
50
- if df.empty or len(df.columns) == 0: raise ValueError("No usable data found")
51
- return df
52
-
53
- def deepgram_tts(txt: str, voice_model: str):
54
- DG_KEY = os.getenv("DEEPGRAM_API_KEY")
55
- if not DG_KEY or not txt: return None
56
- txt = re.sub(r"[^\w\s.,!?;:-]", "", txt)
57
- try:
58
- r = requests.post("https://api.deepgram.com/v1/speak", params={"model": voice_model}, headers={"Authorization": f"Token {DG_KEY}", "Content-Type": "application/json"}, json={"text": txt}, timeout=30)
59
- r.raise_for_status()
60
- return r.content
61
- except Exception as e:
62
- logging.error(f"Deepgram TTS failed: {e}")
63
- return None
64
-
65
- def generate_silence_mp3(duration: float, out: Path):
66
- subprocess.run([ "ffmpeg", "-y", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono", "-t", f"{duration:.3f}", "-q:a", "9", str(out)], check=True, capture_output=True)
67
-
68
- def audio_duration(path: str) -> float:
69
- try:
70
- res = subprocess.run([ "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", path], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
71
- return float(res.stdout.strip())
72
- except Exception: return 5.0
73
-
74
- TAG_RE = re.compile( r'[<[]\s*generate_?chart\s*[:=]?\s*[\"\'“”]?(?P<d>[^>\"\'”\]]+?)[\"\'“”]?\s*[>\]]', re.I, )
75
- TAG_RE_PEXELS = re.compile( r'[<[]\s*generate_?stock_?video\s*[:=]?\s*[\"\'“”]?(?P<d>[^>\"\'”\]]+?)[\"\'“”]?\s*[>\]]', re.I, )
76
- extract_chart_tags = lambda t: list( dict.fromkeys(m.group("d").strip() for m in TAG_RE.finditer(t or "")) )
77
- extract_pexels_tags = lambda t: list( dict.fromkeys(m.group("d").strip() for m in TAG_RE_PEXELS.finditer(t or "")) )
78
-
79
- re_scene = re.compile(r"^\s*scene\s*\d+[:.\- ]*", re.I | re.M)
80
- def clean_narration(txt: str) -> str:
81
- txt = TAG_RE.sub("", txt); txt = TAG_RE_PEXELS.sub("", txt); txt = re_scene.sub("", txt)
82
- phrases_to_remove = [r"chart tag", r"chart_tag", r"narration", r"stock video tag"]
83
- for phrase in phrases_to_remove: txt = re.sub(phrase, "", txt, flags=re.IGNORECASE)
84
- txt = re.sub(r"\s*\([^)]*\)", "", txt); txt = re.sub(r"[\*#_]", "", txt)
85
- return re.sub(r"\s{2,}", " ", txt).strip()
86
-
87
- def placeholder_img() -> Image.Image: return Image.new("RGB", (WIDTH, HEIGHT), (230, 230, 230))
88
-
89
- def _sanitize_for_json(data):
90
- """Recursively sanitizes a dict/list for JSON compliance."""
91
- if isinstance(data, dict):
92
- return {k: _sanitize_for_json(v) for k, v in data.items()}
93
- if isinstance(data, list):
94
- return [_sanitize_for_json(i) for i in data]
95
- if isinstance(data, float) and (math.isnan(data) or math.isinf(data)):
96
- return None
97
- return data
98
-
99
- def detect_dataset_domain(df: pd.DataFrame) -> str:
100
- """Analyzes column names to detect the dataset's primary domain."""
101
- domain_keywords = {
102
- "health insurance": ["charges", "bmi", "smoker", "beneficiary"],
103
- "finance": ["revenue", "profit", "cost", "budget", "expense", "stock"],
104
- "marketing": ["campaign", "conversion", "click", "customer", "segment"],
105
- "survey": ["satisfaction", "rating", "feedback", "opinion", "score"],
106
- "food": ["nutrition", "calories", "ingredients", "restaurant"]
107
- }
108
- columns_lower = [col.lower() for col in df.columns]
109
- for domain, keywords in domain_keywords.items():
110
- if any(keyword in col for col in columns_lower for keyword in keywords):
111
- logging.info(f"Dataset domain detected: {domain}")
112
- return domain
113
- logging.info("No specific dataset domain detected, using generic terms.")
114
- return "data"
115
-
116
- # NEW: Keyword extraction for better Pexels searches
117
- def extract_keywords_for_query(text: str, llm) -> str:
118
- prompt = f"""
119
- Extract a maximum of 3 key nouns or verbs from the following text to use as a search query for a stock video.
120
- Focus on concrete actions and subjects.
121
- Example: 'Our analysis shows a significant growth in quarterly revenue and strong partnerships.' -> 'data analysis growth'
122
- Output only the search query keywords, separated by spaces.
123
-
124
- Text: "{text}"
125
- """
126
- try:
127
- response = llm.invoke(prompt).content.strip()
128
- return response if response else text
129
- except Exception as e:
130
- logging.error(f"Keyword extraction failed: {e}. Using original text.")
131
- return text
132
-
133
- # UPDATED: Pexels search now loops short videos
134
- def search_and_download_pexels_video(query: str, duration: float, out_path: Path) -> str:
135
- if not PEXELS_API_KEY:
136
- logging.warning("PEXELS_API_KEY not set. Cannot fetch stock video.")
137
- return None
138
- try:
139
- headers = {"Authorization": PEXELS_API_KEY}
140
- params = {"query": query, "per_page": 10, "orientation": "landscape"}
141
- response = requests.get("https://api.pexels.com/videos/search", headers=headers, params=params, timeout=20)
142
- response.raise_for_status()
143
- videos = response.json().get('videos', [])
144
- if not videos:
145
- logging.warning(f"No Pexels videos found for query: '{query}'")
146
- return None
147
-
148
- video_to_download = None
149
- for video in videos:
150
- for f in video.get('video_files', []):
151
- if f.get('quality') == 'hd' and f.get('width') >= 1280:
152
- video_to_download = f['link']
153
- break
154
- if video_to_download:
155
- break
156
-
157
- if not video_to_download:
158
- logging.warning(f"No suitable HD video file found for query: '{query}'")
159
- return None
160
-
161
- with requests.get(video_to_download, stream=True, timeout=60) as r:
162
- r.raise_for_status()
163
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_dl_file:
164
- for chunk in r.iter_content(chunk_size=8192):
165
- temp_dl_file.write(chunk)
166
- temp_dl_path = Path(temp_dl_file.name)
167
-
168
- # UPDATED: Added -stream_loop -1 to loop short videos
169
- cmd = [
170
- "ffmpeg", "-y",
171
- "-stream_loop", "-1", # Loop the input video
172
- "-i", str(temp_dl_path),
173
- "-vf", f"scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=decrease,pad={WIDTH}:{HEIGHT}:(ow-iw)/2:(oh-ih)/2,setsar=1",
174
- "-t", f"{duration:.3f}", # Cut the looped video to the exact duration
175
- "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an",
176
- str(out_path)
177
- ]
178
- subprocess.run(cmd, check=True, capture_output=True)
179
- temp_dl_path.unlink()
180
- return str(out_path)
181
-
182
- except Exception as e:
183
- logging.error(f"Pexels video processing failed for query '{query}': {e}")
184
- if 'temp_dl_path' in locals() and temp_dl_path.exists():
185
- temp_dl_path.unlink()
186
- return None
187
-
188
- class ChartSpecification:
189
- def __init__(self, chart_type: str, title: str, x_col: str, y_col: str = None, size_col: str = None, agg_method: str = None, filter_condition: str = None, top_n: int = None, color_scheme: str = "professional"):
190
- self.chart_type = chart_type; self.title = title; self.x_col = x_col; self.y_col = y_col; self.size_col = size_col
191
- self.agg_method = agg_method or "sum"; self.filter_condition = filter_condition; self.top_n = top_n; self.color_scheme = color_scheme
192
-
193
- class ChartGenerator:
194
- def __init__(self, llm, df: pd.DataFrame):
195
- self.llm = llm; self.df = df
196
-
197
- def generate_chart_spec(self, description: str, context: Dict) -> ChartSpecification:
198
- spec_prompt = f"""
199
- You are a data visualization expert. Based on the dataset context and chart description, generate a precise chart specification.
200
- **Dataset Context:** {json.dumps(context, indent=2)}
201
- **Chart Request:** {description}
202
- **Return a JSON specification with these exact fields:**
203
- {{
204
- "chart_type": "bar|pie|line|scatter|hist|heatmap|area|bubble",
205
- "title": "Professional chart title",
206
- "x_col": "column_name_for_x_axis_or_null_for_heatmap",
207
- "y_col": "column_name_for_y_axis_or_null",
208
- "size_col": "column_name_for_bubble_size_or_null",
209
- "agg_method": "sum|mean|count|max|min|null",
210
- "top_n": "number_for_top_n_filtering_or_null"
211
- }}
212
- Return only the JSON specification, no additional text.
213
- """
214
- try:
215
- response = self.llm.invoke(spec_prompt).content.strip()
216
- if response.startswith("```json"): response = response[7:-3]
217
- elif response.startswith("```"): response = response[3:-3]
218
- spec_dict = json.loads(response)
219
- valid_keys = [p.name for p in inspect.signature(ChartSpecification).parameters.values() if p.name not in ['reasoning', 'filter_condition', 'color_scheme']]
220
- filtered_dict = {k: v for k, v in spec_dict.items() if k in valid_keys}
221
- return ChartSpecification(**filtered_dict)
222
- except Exception as e:
223
- logging.error(f"Spec generation failed: {e}. Using fallback.")
224
- numeric_cols = context.get('schema', {}).get('numeric_columns', list(self.df.select_dtypes(include=['number']).columns))
225
- categorical_cols = context.get('schema', {}).get('categorical_columns', list(self.df.select_dtypes(exclude=['number']).columns))
226
- ctype = "bar"
227
- for t in ["pie", "line", "scatter", "hist", "heatmap", "area", "bubble"]:
228
- if t in description.lower(): ctype = t
229
- x = categorical_cols[0] if categorical_cols else self.df.columns[0]
230
- y = numeric_cols[0] if numeric_cols and len(self.df.columns) > 1 else (self.df.columns[1] if len(self.df.columns) > 1 else None)
231
- return ChartSpecification(ctype, description, x, y)
232
-
233
- def execute_chart_spec(spec: ChartSpecification, df: pd.DataFrame, output_path: Path) -> bool:
234
- try:
235
- plot_data = prepare_plot_data(spec, df)
236
- fig, ax = plt.subplots(figsize=(12, 8)); plt.style.use('default')
237
- if spec.chart_type == "bar": ax.bar(plot_data.index.astype(str), plot_data.values, color='#2E86AB', alpha=0.8); ax.set_xlabel(spec.x_col); ax.set_ylabel(spec.y_col); ax.tick_params(axis='x', rotation=45)
238
- elif spec.chart_type == "pie": ax.pie(plot_data.values, labels=plot_data.index, autopct='%1.1f%%', startangle=90); ax.axis('equal')
239
- elif spec.chart_type == "line": ax.plot(plot_data.index, plot_data.values, marker='o', linewidth=2, color='#A23B72'); ax.set_xlabel(spec.x_col); ax.set_ylabel(spec.y_col); ax.grid(True, alpha=0.3)
240
- elif spec.chart_type == "scatter": ax.scatter(plot_data.iloc[:, 0], plot_data.iloc[:, 1], alpha=0.6, color='#F18F01'); ax.set_xlabel(spec.x_col); ax.set_ylabel(spec.y_col); ax.grid(True, alpha=0.3)
241
- elif spec.chart_type == "hist": ax.hist(plot_data.values, bins=20, color='#C73E1D', alpha=0.7, edgecolor='black'); ax.set_xlabel(spec.x_col); ax.set_ylabel('Frequency'); ax.grid(True, alpha=0.3)
242
- elif spec.chart_type == "area": ax.fill_between(plot_data.index, plot_data.values, color="#4E79A7", alpha=0.4); ax.plot(plot_data.index, plot_data.values, color="#4E79A7", alpha=0.8); ax.set_xlabel(spec.x_col); ax.set_ylabel(spec.y_col); ax.grid(True, alpha=0.3)
243
- elif spec.chart_type == "heatmap": sns.heatmap(plot_data, annot=True, cmap="viridis", ax=ax); plt.xticks(rotation=45, ha="right"); plt.yticks(rotation=0)
244
- elif spec.chart_type == "bubble":
245
- sizes = (plot_data[spec.size_col] - plot_data[spec.size_col].min() + 1) / (plot_data[spec.size_col].max() - plot_data[spec.size_col].min() + 1) * 2000 + 50
246
- ax.scatter(plot_data[spec.x_col], plot_data[spec.y_col], s=sizes, alpha=0.6, color='#59A14F'); ax.set_xlabel(spec.x_col); ax.set_ylabel(spec.y_col); ax.grid(True, alpha=0.3)
247
-
248
- ax.set_title(spec.title, fontsize=14, fontweight='bold', pad=20); plt.tight_layout()
249
- plt.savefig(output_path, dpi=300, bbox_inches='tight', facecolor='white'); plt.close()
250
- return True
251
- except Exception as e: logging.error(f"Static chart generation failed for '{spec.title}': {e}"); return False
252
-
253
- def prepare_plot_data(spec: ChartSpecification, df: pd.DataFrame):
254
- if spec.chart_type not in ["heatmap"]:
255
- if spec.x_col not in df.columns or (spec.y_col and spec.y_col not in df.columns): raise ValueError(f"Invalid columns in chart spec: {spec.x_col}, {spec.y_col}")
256
-
257
- if spec.chart_type in ["bar", "pie"]:
258
- if not spec.y_col: return df[spec.x_col].value_counts().nlargest(spec.top_n or 10)
259
- grouped = df.groupby(spec.x_col)[spec.y_col].agg(spec.agg_method or 'sum')
260
- return grouped.nlargest(spec.top_n or 10)
261
- elif spec.chart_type in ["line", "area"]: return df.set_index(spec.x_col)[spec.y_col].sort_index()
262
- elif spec.chart_type == "scatter": return df[[spec.x_col, spec.y_col]].dropna()
263
- elif spec.chart_type == "bubble":
264
- if not spec.size_col or spec.size_col not in df.columns: raise ValueError("Bubble chart requires a valid size_col.")
265
- return df[[spec.x_col, spec.y_col, spec.size_col]].dropna()
266
- elif spec.chart_type == "hist": return df[spec.x_col].dropna()
267
- elif spec.chart_type == "heatmap":
268
- numeric_cols = df.select_dtypes(include=np.number).columns
269
- if not numeric_cols.any(): raise ValueError("Heatmap requires numeric columns.")
270
- return df[numeric_cols].corr()
271
- return df[spec.x_col]
272
-
273
- # UPDATED: animate_chart now uses blit=False for accurate timing
274
-
275
- def animate_chart(spec: ChartSpecification, df: pd.DataFrame, dur: float, out: Path, fps: int = FPS) -> str:
276
- plot_data = prepare_plot_data(spec, df)
277
- frames = math.ceil(dur * fps)
278
- fig, ax = plt.subplots(figsize=(WIDTH / 100, HEIGHT / 100), dpi=100)
279
- plt.tight_layout(pad=3.0)
280
- ctype = spec.chart_type
281
-
282
- init_func, update_func = None, None
283
-
284
- if ctype == "line":
285
- plot_data = plot_data.sort_index()
286
- x_full, y_full = plot_data.index, plot_data.values
287
-
288
- ax.set_xlim(x_full.min(), x_full.max())
289
- ax.set_ylim(y_full.min() * 0.9, y_full.max() * 1.1)
290
- ax.set_title(spec.title); ax.grid(alpha=.3); ax.set_xlabel(spec.x_col); ax.set_ylabel(spec.y_col)
291
-
292
- line, = ax.plot([], [], lw=2, color='#A23B72')
293
- markers, = ax.plot([], [], 'o', color='#A23B72', markersize=5)
294
-
295
- def init():
296
- line.set_data([], [])
297
- markers.set_data([], [])
298
- return line, markers
299
- def update(i):
300
- k = max(2, int(len(x_full) * (i / (frames - 1))))
301
- line.set_data(x_full[:k], y_full[:k])
302
- markers.set_data(x_full[:k], y_full[:k])
303
- return line, markers
304
- init_func, update_func = init, update
305
-
306
- anim = FuncAnimation(fig, update, init_func=init, frames=frames, blit=True, interval=1000 / fps)
307
- anim.save(str(out), writer=FFMpegWriter(fps=fps), dpi=144)
308
- plt.close(fig)
309
- return str(out)
310
-
311
- # Fallback to the slightly slower but reliable blit=False for other types
312
- # This ensures stability across all chart types while the line chart is optimized
313
- if ctype == "bar":
314
- bars = ax.bar(plot_data.index.astype(str), np.zeros_like(plot_data.values, dtype=float), color="#1f77b4")
315
- ax.set_ylim(0, plot_data.max() * 1.1 if not pd.isna(plot_data.max()) and plot_data.max() > 0 else 1)
316
- ax.set_title(spec.title); plt.xticks(rotation=45, ha="right")
317
- def init(): return bars
318
- def update(i):
319
- for b, h in zip(bars, plot_data.values): b.set_height(h * (i / (frames - 1)))
320
- return bars
321
- init_func, update_func = init, update
322
- elif ctype == "scatter":
323
- x_full, y_full = plot_data.iloc[:, 0], plot_data.iloc[:, 1]
324
- slope, intercept, _, _, _ = stats.linregress(x_full, y_full)
325
- reg_line_x = np.array([x_full.min(), x_full.max()])
326
- reg_line_y = slope * reg_line_x + intercept
327
- scat = ax.scatter([], [], alpha=0.7, color='#F18F01')
328
- line, = ax.plot([], [], 'r--', lw=2)
329
- ax.set_xlim(x_full.min(), x_full.max()); ax.set_ylim(y_full.min(), y_full.max())
330
- ax.set_title(spec.title); ax.grid(alpha=.3); ax.set_xlabel(spec.x_col); ax.set_ylabel(spec.y_col)
331
- def init():
332
- scat.set_offsets(np.empty((0, 2))); line.set_data([], [])
333
- return []
334
- def update(i):
335
- point_frames = int(frames * 0.7)
336
- if i <= point_frames:
337
- k = max(1, int(len(x_full) * (i / point_frames)))
338
- scat.set_offsets(plot_data.iloc[:k].values)
339
- else:
340
- line_frame = i - point_frames; line_total_frames = frames - point_frames
341
- current_x = reg_line_x[0] + (reg_line_x[1] - reg_line_x[0]) * (line_frame / line_total_frames)
342
- line.set_data([reg_line_x[0], current_x], [reg_line_y[0], slope * current_x + intercept])
343
- return []
344
- init_func, update_func = init, update
345
- elif ctype == "pie":
346
- wedges, _, _ = ax.pie(plot_data, labels=plot_data.index, startangle=90, autopct='%1.1f%%')
347
- ax.set_title(spec.title); ax.axis('equal')
348
- def init(): [w.set_alpha(0) for w in wedges]; return []
349
- def update(i): [w.set_alpha(i / (frames - 1)) for w in wedges]; return []
350
- init_func, update_func = init, update
351
- elif ctype == "hist":
352
- _, _, patches = ax.hist(plot_data, bins=20, alpha=0)
353
- ax.set_title(spec.title); ax.set_xlabel(spec.x_col); ax.set_ylabel("Frequency")
354
- def init(): [p.set_alpha(0) for p in patches]; return []
355
- def update(i): [p.set_alpha((i / (frames - 1)) * 0.7) for p in patches]; return []
356
- init_func, update_func = init, update
357
- elif ctype == "heatmap":
358
- sns.heatmap(plot_data, annot=True, cmap="viridis", ax=ax, alpha=0)
359
- ax.set_title(spec.title)
360
- def init(): ax.collections[0].set_alpha(0); return []
361
- def update(i): ax.collections[0].set_alpha(i / (frames - 1)); return []
362
- init_func, update_func = init, update
363
- else:
364
- ax.text(0.5, 0.5, f"'{ctype}' animation not implemented", ha='center', va='center')
365
- def init(): return []
366
- def update(i): return []
367
- init_func, update_func = init, update
368
-
369
- anim = FuncAnimation(fig, update_func, init_func=init_func, frames=frames, blit=False, interval=1000 / fps)
370
- anim.save(str(out), writer=FFMpegWriter(fps=fps), dpi=144)
371
- plt.close(fig)
372
- return str(out)
373
-
374
- def safe_chart(desc: str, df: pd.DataFrame, dur: float, out: Path, context: Dict) -> str:
375
- try:
376
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=API_KEY, temperature=0.1)
377
- chart_generator = ChartGenerator(llm, df)
378
- chart_spec = chart_generator.generate_chart_spec(desc, context)
379
- return animate_chart(chart_spec, df, dur, out)
380
- except Exception as e:
381
- logging.error(f"Chart animation failed for '{desc}': {e}. Raising exception to trigger fallback.")
382
- raise e # Raise exception to be caught by the video generator's fallback logic
383
-
384
- def concat_media(file_paths: List[str], output_path: Path):
385
- valid_paths = [p for p in file_paths if Path(p).exists() and Path(p).stat().st_size > 100]
386
- if not valid_paths: raise ValueError("No valid media files to concatenate.")
387
- if len(valid_paths) == 1: import shutil; shutil.copy2(valid_paths[0], str(output_path)); return
388
- list_file = output_path.with_suffix(".txt")
389
- with open(list_file, 'w') as f:
390
- for path in valid_paths: f.write(f"file '{Path(path).resolve()}'\n")
391
- cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", str(list_file), "-c", "copy", str(output_path)]
392
- try:
393
- subprocess.run(cmd, check=True, capture_output=True, text=True)
394
- finally:
395
- list_file.unlink(missing_ok=True)
396
-
397
- def sanitize_for_firebase_key(text: str) -> str:
398
- forbidden_chars = ['.', '$', '#', '[', ']', '/']
399
- for char in forbidden_chars:
400
- text = text.replace(char, '_')
401
- return text
402
-
403
- def analyze_data_intelligence(df: pd.DataFrame) -> Dict:
404
- numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
405
- categorical_cols = df.select_dtypes(exclude=['number']).columns.tolist()
406
- is_timeseries = any('date' in col.lower() or 'time' in col.lower() for col in df.columns)
407
- opportunities = []
408
- if is_timeseries: opportunities.append("temporal trends")
409
- if len(numeric_cols) > 1: opportunities.append("correlations between metrics")
410
- if len(categorical_cols) > 0 and len(numeric_cols) > 0: opportunities.append("segmentation by category")
411
- if df.isnull().sum().sum() > 0: opportunities.append("impact of missing data")
412
- return {
413
- "insight_opportunities": opportunities,
414
- "is_timeseries": is_timeseries,
415
- "has_correlations": len(numeric_cols) > 1,
416
- "has_segments": len(categorical_cols) > 0 and len(numeric_cols) > 0
417
- }
418
-
419
- def generate_visualization_strategy(intelligence: Dict) -> str:
420
- strategy = "Vary your visualizations to keep the report engaging. "
421
- if intelligence["is_timeseries"]: strategy += "Use 'line' or 'area' charts to explore temporal trends. "
422
- if intelligence["has_correlations"]: strategy += "Use 'scatter' or 'heatmap' charts to reveal correlations. "
423
- if intelligence["has_segments"]: strategy += "Use 'bar' or 'pie' charts to compare segments. "
424
- return strategy
425
-
426
- def get_augmented_context(df: pd.DataFrame, user_ctx: str) -> Dict:
427
- """Creates a detailed, JSON-safe summary of the dataframe for the AI."""
428
- numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
429
- categorical_cols = df.select_dtypes(exclude=['number']).columns.tolist()
430
-
431
- context = {
432
- "user_context": user_ctx,
433
- "dataset_shape": {"rows": df.shape[0], "columns": df.shape[1]},
434
- "schema": {"numeric_columns": numeric_cols, "categorical_columns": categorical_cols},
435
- "data_previews": {}
436
- }
437
-
438
- for col in categorical_cols[:5]:
439
- unique_vals = df[col].unique()
440
- context["data_previews"][col] = {
441
- "count": len(unique_vals),
442
- "values": unique_vals[:5].tolist()
443
- }
444
-
445
- for col in numeric_cols[:5]:
446
- context["data_previews"][col] = {
447
- "mean": df[col].mean(),
448
- "min": df[col].min(),
449
- "max": df[col].max()
450
- }
451
-
452
- # Sanitize the entire structure before returning
453
- return _sanitize_for_json(json.loads(json.dumps(context, default=str)))
454
-
455
- def generate_report_draft(buf, name: str, ctx: str, uid: str, project_id: str, bucket):
456
- logging.info(f"Generating guided storyteller report draft for project {project_id}")
457
- df = load_dataframe_safely(buf, name)
458
- llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=API_KEY, temperature=0.3)
459
-
460
- data_context_str, context_for_charts = "", {}
461
- try:
462
- df_json = df.to_json(orient='records')
463
- estimated_tokens = len(df_json) / 4
464
- if estimated_tokens < MAX_CONTEXT_TOKENS:
465
- logging.info(f"Using full JSON context for report generation.")
466
- data_context_str = f"Here is the full dataset in JSON format:\n{df_json}"
467
- context_for_charts = get_augmented_context(df, ctx)
468
- else:
469
- raise ValueError("Dataset too large for full context.")
470
- except Exception as e:
471
- logging.warning(f"Falling back to augmented summary context for report generation: {e}")
472
- augmented_context = get_augmented_context(df, ctx)
473
- data_context_str = f"The full dataset is too large to display. Here is a detailed summary:\n{json.dumps(augmented_context, indent=2)}"
474
- context_for_charts = augmented_context
475
-
476
- md = ""
477
- try:
478
- # --- Pass 1: The "Visualization Strategist" ---
479
- strategist_prompt = f"""
480
- You are a data visualization expert. Your task is to create a diverse palette of unique and impactful charts for a data storyteller.
481
- Based on the provided data context, identify the 4-5 most distinct and insightful stories that can be visualized.
482
-
483
- **Data Context:**
484
- {data_context_str}
485
-
486
- **Your Goal:**
487
- Your primary goal is to select a **diverse palette of chart types**. A high-quality response will use a mix of different charts from the available list to create a visually engaging and comprehensive report. **Do not use the same chart type more than twice.**
488
-
489
- **Strategic Hints:**
490
- - Consider a `histogram` to show the distribution of a key variable (like age or bmi).
491
- - Consider a `pie chart` for a clear part-to-whole relationship (e.g., smoker vs. non-smoker proportions).
492
- - Consider a `heatmap` if the dataset has multiple numeric columns and you believe the overall pattern of their correlations is a key insight in itself.
493
-
494
- **Output Format:**
495
- Return ONLY a valid JSON array of strings. Each string must be a unique chart description tag.
496
-
497
- Example:
498
- ["bar | Average Charges by Smoker Status", "scatter | Charges vs. BMI", "hist | Distribution of Beneficiary Ages", "pie | Regional Proportions"]
499
- """
500
- logging.info("Executing Visualization Strategist Pass...")
501
- strategist_response = llm.invoke(strategist_prompt).content.strip()
502
- if strategist_response.startswith("```json"):
503
- strategist_response = strategist_response[7:-3]
504
- chart_palette = json.loads(strategist_response)
505
- logging.info(f"Strategist Pass successful. Palette has {len(chart_palette)} unique charts.")
506
-
507
- # --- Pass 2: The "Master Storyteller" ---
508
- storyteller_prompt = f"""
509
- You are an elite data storyteller and business intelligence expert. Your mission is to write a comprehensive, flowing narrative that analyzes the entire dataset provided. Your goal is to create a captivating story that **drives action**.
510
-
511
- **Data Context:**
512
- {data_context_str}
513
-
514
- **Narrative Construction Guidelines:**
515
- 1. **Use Compelling Headers:** Structure your report with multiple sections using Markdown headings (`##` or `###`). Do not write one long block of text. Create curiosity with your headers (e.g., 'The Smoking Premium: A Costly Habit', 'Geographic Hotspots: Where Charges Are Highest').
516
- 2. **Weave a Story:** Don't just describe the charts one by one. Connect the findings together. For example, how does 'age' relate to 'smoker status' and how do they both impact 'charges'?
517
- 3. **Drive to Action:** Conclude your report with a dedicated section titled `## Actionable Recommendations`. Based on your analysis, provide specific, data-driven suggestions that a business leader could implement.
518
-
519
- **Your Toolbox (Most Important):**
520
- To support your story with visuals, you have been provided with a pre-approved 'palette' of unique charts. As you write your narrative, you **must** integrate each of these chart tags, one time, at the most logical point in the story.
521
- - You **must** use every chart tag from the provided palette exactly once.
522
- - Do **not** repeat chart tags.
523
- - Do **not** invent new chart tags.
524
- - Insert the tags in the format `<generate_chart: "the_description">`.
525
-
526
- **Chart Palette:**
527
- {json.dumps(chart_palette, indent=2)}
528
-
529
- Now, write the complete, comprehensive Markdown report.
530
- """
531
- logging.info("Executing Master Storyteller Pass...")
532
- md = llm.invoke(storyteller_prompt).content.strip()
533
- logging.info("Master Storyteller Pass successful.")
534
-
535
- except Exception as e:
536
- logging.error(f"Guided Storyteller system failed: {e}. Reverting to single-pass fallback.")
537
- fallback_prompt = f"""
538
- You are an elite data storyteller and business intelligence expert. Your mission is to uncover the compelling, hidden narrative in this dataset and present it as a captivating story in Markdown format that drives action.
539
- **Data Context:** {data_context_str}
540
- **Your Grounding Rules (Most Important):**
541
- 1. **Strict Accuracy:** Your entire analysis and narrative **must strictly** use the column names provided in the 'Data Context' section.
542
- 2. **Chart Support:** Wherever a key finding is made, you **must** support it with a chart tag: `<generate_chart: "chart_type | a specific, compelling description">`.
543
- 3. **Chart Accuracy:** The column names used in your chart descriptions **must** also be an exact match from the provided data context.
544
- Now, begin your report. Let the data's story unfold naturally.
545
- """
546
- md = llm.invoke(fallback_prompt).content.strip()
547
-
548
- chart_descs = extract_chart_tags(md)[:MAX_CHARTS]
549
- chart_urls = {}
550
- chart_generator = ChartGenerator(llm, df)
551
-
552
- for desc in chart_descs:
553
- safe_desc = sanitize_for_firebase_key(desc)
554
- md = md.replace(f'<generate_chart: "{desc}">', f'<generate_chart: "{safe_desc}">')
555
- md = md.replace(f'<generate_chart: {desc}>', f'<generate_chart: "{safe_desc}">')
556
-
557
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file:
558
- img_path = Path(temp_file.name)
559
- try:
560
- chart_spec = chart_generator.generate_chart_spec(desc, context_for_charts)
561
- if execute_chart_spec(chart_spec, df, img_path):
562
- blob_name = f"sozo_projects/{uid}/{project_id}/charts/{uuid.uuid4().hex}.png"
563
- blob = bucket.blob(blob_name)
564
- blob.upload_from_filename(str(img_path))
565
- chart_urls[safe_desc] = blob.public_url
566
- finally:
567
- if os.path.exists(img_path):
568
- os.unlink(img_path)
569
-
570
- return {"raw_md": md, "chartUrls": chart_urls, "data_context": context_for_charts}
571
-
572
- def generate_single_chart(df: pd.DataFrame, description: str, uid: str, project_id: str, bucket):
573
- logging.info(f"Generating single chart '{description}' for project {project_id}")
574
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=API_KEY, temperature=0.1)
575
- chart_generator = ChartGenerator(llm, df)
576
- context = get_augmented_context(df, "")
577
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file:
578
- img_path = Path(temp_file.name)
579
- try:
580
- chart_spec = chart_generator.generate_chart_spec(description, context)
581
- if execute_chart_spec(chart_spec, df, img_path):
582
- blob_name = f"sozo_projects/{uid}/{project_id}/charts/{uuid.uuid4().hex}.png"
583
- blob = bucket.blob(blob_name)
584
- blob.upload_from_filename(str(img_path))
585
- logging.info(f"Uploaded single chart to {blob.public_url}")
586
- return blob.public_url
587
- finally:
588
- if os.path.exists(img_path):
589
- os.unlink(img_path)
590
- return None
591
-
592
-
593
- def generate_video_from_project(df: pd.DataFrame, raw_md: str, data_context: Dict, uid: str, project_id: str, voice_model: str, bucket):
594
- logging.info(f"Generating video for project {project_id} with voice {voice_model}")
595
- llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=API_KEY, temperature=0.2)
596
-
597
- domain = detect_dataset_domain(df)
598
-
599
- story_prompt = f"""
600
- Based on the following report, create a script for a {VIDEO_SCENES}-scene video.
601
- 1. The first scene MUST be an "Introduction". It must contain narration and a stock video tag like: <generate_stock_video: "search query">.
602
- 2. The last scene MUST be a "Conclusion". It must also contain narration and a stock video tag.
603
- 3. The middle scenes should each contain narration and one chart tag from the report.
604
- 4. Separate each scene with '[SCENE_BREAK]'.
605
- Report: {raw_md}
606
- Only output the script, no extra text.
607
- """
608
- script = llm.invoke(story_prompt).content.strip()
609
- scenes = [s.strip() for s in script.split("[SCENE_BREAK]") if s.strip()]
610
- video_parts, audio_parts, temps = [], [], []
611
- total_audio_duration = 0.0
612
- conclusion_video_path = None
613
-
614
- for i, sc in enumerate(scenes):
615
- mp4 = Path(tempfile.gettempdir()) / f"{uuid.uuid4()}.mp4"
616
- narrative = clean_narration(sc)
617
- if not narrative:
618
- logging.warning(f"Scene {i+1} has no narration, skipping.")
619
- continue
620
-
621
- audio_bytes = deepgram_tts(narrative, voice_model)
622
- mp3 = Path(tempfile.gettempdir()) / f"{uuid.uuid4()}.mp3"
623
- audio_dur = 5.0
624
- if audio_bytes:
625
- mp3.write_bytes(audio_bytes)
626
- audio_dur = audio_duration(str(mp3))
627
- if audio_dur <= 0.1: audio_dur = 5.0
628
- else:
629
- generate_silence_mp3(audio_dur, mp3)
630
-
631
- audio_parts.append(str(mp3)); temps.append(mp3)
632
- total_audio_duration += audio_dur
633
-
634
- video_dur = audio_dur + 1.5
635
-
636
- try:
637
- # --- Primary Visual Generation ---
638
- chart_descs = extract_chart_tags(sc)
639
- pexels_descs = extract_pexels_tags(sc)
640
- is_conclusion_scene = any(k in narrative.lower() for k in ["conclusion", "summary", "in closing", "final thoughts"])
641
-
642
- if pexels_descs:
643
- logging.info(f"Scene {i+1}: Processing Pexels scene.")
644
- base_keywords = extract_keywords_for_query(narrative, llm)
645
- final_query = f"{base_keywords} {domain}"
646
- video_path = search_and_download_pexels_video(final_query, video_dur, mp4)
647
- if not video_path: raise ValueError("Pexels search returned no results for chained query.")
648
- video_parts.append(video_path)
649
- if is_conclusion_scene:
650
- conclusion_video_path = video_path
651
- elif chart_descs:
652
- logging.info(f"Scene {i+1}: Primary attempt with animated chart.")
653
- if not chart_descs: raise ValueError("AI script failed to provide a chart tag for this scene.")
654
- safe_chart(chart_descs[0], df, video_dur, mp4, data_context)
655
- video_parts.append(str(mp4))
656
- else:
657
- raise ValueError("No visual tag found in scene script.")
658
- except Exception as e:
659
- logging.warning(f"Scene {i+1}: Primary visual failed ({e}). Triggering Fallback Tier 1.")
660
- # --- Fallback Tier 1: Context-Aware Pexels Replacement ---
661
- try:
662
- fallback_keywords = extract_keywords_for_query(narrative, llm)
663
- final_fallback_query = f"{fallback_keywords} {domain}"
664
- logging.info(f"Fallback Tier 1: Searching Pexels with query: '{final_fallback_query}'")
665
-
666
- video_path = search_and_download_pexels_video(final_fallback_query, video_dur, mp4)
667
- if not video_path: raise ValueError("Fallback Pexels search returned no results.")
668
-
669
- video_parts.append(video_path)
670
- logging.info(f"Scene {i+1}: Successfully recovered with a relevant Pexels video.")
671
- except Exception as fallback_e:
672
- # --- Fallback Tier 2: Looping Conclusion Failsafe ---
673
- logging.error(f"Scene {i+1}: Fallback Tier 1 also failed ({fallback_e}). Marking for final failsafe.")
674
- video_parts.append("FALLBACK_NEEDED")
675
-
676
- temps.append(mp4)
677
-
678
- if not conclusion_video_path:
679
- logging.warning("No conclusion video was generated; creating a generic one for fallbacks.")
680
- fallback_mp4 = Path(tempfile.gettempdir()) / f"{uuid.uuid4()}.mp4"
681
- conclusion_video_path = search_and_download_pexels_video(f"data visualization abstract {domain}", 5.0, fallback_mp4)
682
- if conclusion_video_path: temps.append(fallback_mp4)
683
-
684
- final_video_parts = []
685
- for part in video_parts:
686
- if part == "FALLBACK_NEEDED":
687
- if conclusion_video_path:
688
- fallback_copy_path = Path(tempfile.gettempdir()) / f"fallback_{uuid.uuid4().hex}.mp4"
689
- shutil.copy(conclusion_video_path, fallback_copy_path)
690
- temps.append(fallback_copy_path)
691
- final_video_parts.append(str(fallback_copy_path))
692
- logging.info(f"Applying unique copy of conclusion video as fallback for a failed scene.")
693
- else:
694
- logging.error("Cannot apply fallback; no conclusion video available. A scene will be missing.")
695
- else:
696
- final_video_parts.append(part)
697
-
698
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_vid, \
699
- tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_aud, \
700
- tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as final_vid, \
701
- tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as branded_vid:
702
-
703
- silent_vid_path = Path(temp_vid.name)
704
- audio_mix_path = Path(temp_aud.name)
705
- final_vid_path = Path(final_vid.name)
706
- branded_vid_path = Path(branded_vid.name)
707
-
708
- concat_media(final_video_parts, silent_vid_path)
709
- concat_media(audio_parts, audio_mix_path)
710
-
711
- cmd = [
712
- "ffmpeg", "-y", "-i", str(silent_vid_path), "-i", str(audio_mix_path),
713
- "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac",
714
- "-map", "0:v:0", "-map", "1:a:0",
715
- "-t", f"{total_audio_duration:.3f}",
716
- str(final_vid_path)
717
- ]
718
- subprocess.run(cmd, check=True, capture_output=True)
719
-
720
- upload_path = final_vid_path
721
- logo_path = Path("sozob.png")
722
-
723
- if logo_path.exists():
724
- logging.info("Logo 'sozob.png' found. Adding full-screen end-card.")
725
- duration_for_filter = total_audio_duration
726
-
727
- filter_complex = f"[1:v]scale={WIDTH}:{HEIGHT}[logo];[0:v][logo]overlay=0:0:enable='gte(t,{duration_for_filter - 2})'"
728
-
729
- logo_cmd = [
730
- "ffmpeg", "-y",
731
- "-i", str(final_vid_path),
732
- "-i", str(logo_path),
733
- "-filter_complex", filter_complex,
734
- "-map", "0:a",
735
- "-c:a", "copy",
736
- "-c:v", "libx264", "-pix_fmt", "yuv420p",
737
- str(branded_vid_path)
738
- ]
739
- try:
740
- subprocess.run(logo_cmd, check=True, capture_output=True)
741
- upload_path = branded_vid_path
742
- except subprocess.CalledProcessError as e:
743
- logging.error(f"Failed to add logo end-card. Uploading unbranded video. Error: {e.stderr.decode()}")
744
- else:
745
- logging.warning("Logo 'sozob.png' not found in root directory. Skipping end-card.")
746
-
747
- blob_name = f"sozo_projects/{uid}/{project_id}/video.mp4"
748
- blob = bucket.blob(blob_name)
749
- blob.upload_from_filename(str(upload_path))
750
- logging.info(f"Uploaded video to {blob.public_url}")
751
-
752
- for p in temps + [silent_vid_path, audio_mix_path, final_vid_path, branded_vid_path]:
753
- if os.path.exists(p): os.unlink(p)
754
-
755
- return blob.public_url
756
- return None
757
-
758
- # In sozo_gen.py, add these new functions at the end of the file
759
-
760
- def generate_image_with_gemini(prompt: str) -> Image.Image:
761
- """Generates an image using the specified Gemini model and client configuration."""
762
- logging.info(f"Generating Gemini image with prompt: '{prompt}'")
763
- try:
764
- # Use the genai.Client as per the correct implementation
765
- client = genai.Client(api_key=API_KEY)
766
- full_prompt = f"A professional, 3d digital art style illustration for a business presentation: {prompt}"
767
-
768
- response = client.models.generate_content(
769
- model="gemini-2.0-flash-exp",
770
- contents=full_prompt,
771
- config=genai_types.GenerateContentConfig(
772
- response_modalities=["Text", "Image"]
773
- ),
774
- )
775
-
776
- # Find the image part in the response
777
- img_part = next((part for part in response.candidates[0].content.parts if part.content_type == "Image"), None)
778
-
779
- if img_part:
780
- # The content is already bytes, so we can open it directly
781
- return Image.open(io.BytesIO(img_part.content)).convert("RGB")
782
- else:
783
- logging.error("Gemini response did not contain an image.")
784
- return None
785
- except Exception as e:
786
- logging.error(f"Gemini image generation failed: {e}")
787
- return None
788
-
789
- def generate_slides_from_report(raw_md: str, chart_urls: dict, uid: str, project_id: str, bucket, llm):
790
- """
791
- Uses an AI planner to convert a report into a 10-slide presentation deck.
792
- """
793
- logging.info(f"Generating slides for project {project_id}")
794
-
795
- planner_prompt = f"""
796
- You are an expert presentation designer. Your task is to convert the following data analysis report into a concise and visually engaging 10-slide deck.
797
-
798
- **Full Report Content:**
799
- ---
800
- {raw_md}
801
- ---
802
-
803
- **Instructions:**
804
- 1. Read the entire report to understand the core narrative and key findings.
805
- 2. Create a plan for exactly 10 slides.
806
- 3. For each slide, define a `title` and short `content` (2-3 bullet points or a brief paragraph).
807
- 4. For the visual on each slide, you must decide between two types:
808
- - If a report section is supported by an existing chart (indicated by a `<generate_chart:...>` tag), you **must** use it. Set `visual_type: "existing_chart"` and `visual_ref: "the exact chart description from the tag"`.
809
- - For key points without a chart (like introductions, conclusions, or text-only insights), you **must** request a new image. Set `visual_type: "new_image"` and `visual_ref: "a concise, descriptive prompt for an AI to generate a 3D digital art style illustration"`.
810
- 5. You must request exactly 3-4 new images to balance the presentation.
811
-
812
- **Output Format:**
813
- Return ONLY a valid JSON array of 10 slide objects. Do not include any other text or markdown formatting.
814
-
815
- Example:
816
- [
817
- {{ "slide_number": 1, "title": "Introduction", "content": "...", "visual_type": "new_image", "visual_ref": "A 3D illustration of a rising stock chart" }},
818
- {{ "slide_number": 2, "title": "Sales by Region", "content": "...", "visual_type": "existing_chart", "visual_ref": "bar | Sales by Region" }},
819
- ...
820
- ]
821
- """
822
-
823
- try:
824
- plan_response = llm.invoke(planner_prompt).content.strip()
825
- if plan_response.startswith("```json"):
826
- plan_response = plan_response[7:-3]
827
- slide_plan = json.loads(plan_response)
828
- except Exception as e:
829
- logging.error(f"Failed to generate or parse slide plan: {e}")
830
- return None
831
-
832
- final_slides = []
833
- for slide in slide_plan:
834
- try:
835
- image_url = None
836
- visual_type = slide.get("visual_type")
837
- visual_ref = slide.get("visual_ref")
838
-
839
- if visual_type == "existing_chart":
840
- sanitized_ref = sanitize_for_firebase_key(visual_ref)
841
- image_url = chart_urls.get(sanitized_ref)
842
- if not image_url:
843
- logging.warning(f"Could not find existing chart for ref: '{visual_ref}' (sanitized: '{sanitized_ref}')")
844
-
845
- elif visual_type == "new_image":
846
- img = generate_image_with_gemini(visual_ref)
847
- if img:
848
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file:
849
- img_path = Path(temp_file.name)
850
- img.save(img_path, format="PNG")
851
-
852
- blob_name = f"sozo_projects/{uid}/{project_id}/slides/slide_{uuid.uuid4().hex}.png"
853
- blob = bucket.blob(blob_name)
854
- blob.upload_from_filename(str(img_path))
855
- image_url = blob.public_url
856
- logging.info(f"Uploaded new slide image to {image_url}")
857
- os.unlink(img_path)
858
-
859
- if not image_url:
860
- logging.warning(f"Visual generation failed for slide {slide.get('slide_number')}. Skipping visual for this slide.")
861
-
862
- final_slides.append({
863
- "slide_number": slide.get("slide_number"),
864
- "title": slide.get("title"),
865
- "content": slide.get("content"),
866
- "image_url": image_url or ""
867
- })
868
- except Exception as slide_e:
869
- logging.error(f"Failed to process slide {slide.get('slide_number')}: {slide_e}")
870
- continue
871
-
872
- return final_slides