SuhasGholkar commited on
Commit
bffd18e
·
verified ·
1 Parent(s): eaa5c2f

Update src/video_export.py

Browse files
Files changed (1) hide show
  1. src/video_export.py +148 -27
src/video_export.py CHANGED
@@ -8,6 +8,9 @@ from PIL import Image, ImageDraw, ImageFont
8
  from moviepy.editor import ImageClip, concatenate_videoclips
9
  from moviepy.audio.io.AudioFileClip import AudioFileClip
10
  from gtts import gTTS
 
 
 
11
 
12
  from src.utils import APP_DIR
13
 
@@ -24,6 +27,45 @@ def _get_font(size: int):
24
  return ImageFont.truetype(p, size=size)
25
  return ImageFont.load_default()
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def _draw_multiline(draw, text, xy, font, fill, max_w, leading=6):
28
  text = (text or "").strip()
29
  if not text:
@@ -166,33 +208,112 @@ def render_admin_export_video_tab(conn):
166
  except Exception as e:
167
  st.error(f"Video generation failed: {e}")
168
 
169
- def export_records_to_video(rows, out_path: str | None = None) -> str:
170
  """
171
- Adapter so other modules can export a list of chat rows to a video.
172
- Expects `rows` as a list of dicts with keys like:
173
- id, timestamp, user_message, bot_reply, intent, sentiment, resolution, ftr_ms, user_id
174
- Returns the path to the generated MP4 file.
 
175
  """
176
- # If you already have a builder function, just forward to it, e.g.:
177
- # return build_chat_video(rows, out_path)
178
-
179
- # Otherwise, if your file already has a function that does the same work
180
- # under a different name, forward to it here:
181
- # return create_video_from_chats(rows, out_path)
182
-
183
- # If you previously had a UI function only (render_admin_export_video_tab),
184
- # leave that as-is and keep this as the programmatic entry point that
185
- # your admin_export uses. Implement it by calling your internal routines.
186
- from pathlib import Path
187
-
188
- # Example fallback implementation if you already wrote a core builder:
189
- if 'build_chat_video' in globals():
190
- return build_chat_video(rows, out_path)
191
-
192
- # If you don’t have any builder available, raise a helpful error.
193
- raise RuntimeError(
194
- "export_records_to_video() is not implemented in src/video_export.py. "
195
- "Please implement it or forward it to your existing video builder "
196
- "(e.g. build_chat_video)."
197
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
 
 
8
  from moviepy.editor import ImageClip, concatenate_videoclips
9
  from moviepy.audio.io.AudioFileClip import AudioFileClip
10
  from gtts import gTTS
11
+ import Textwrap
12
+ from pathlib import Path
13
+ import imageio.v2 as imageio
14
 
15
  from src.utils import APP_DIR
16
 
 
27
  return ImageFont.truetype(p, size=size)
28
  return ImageFont.load_default()
29
 
30
+ def _font_try(paths, size):
31
+ """Try multiple font paths, fallback to PIL default."""
32
+ for p in paths:
33
+ try:
34
+ return ImageFont.truetype(p, size)
35
+ except Exception:
36
+ pass
37
+ return ImageFont.load_default()
38
+
39
+
40
+ def _wrap(draw, text, font, max_width_px):
41
+ """Word-wrap text to fit pixel width using PIL measurement."""
42
+ if not text:
43
+ return [""]
44
+ words = text.split()
45
+ lines, cur = [], []
46
+ for w in words:
47
+ test = " ".join(cur + [w])
48
+ w_px = draw.textlength(test, font=font)
49
+ if w_px <= max_width_px:
50
+ cur.append(w)
51
+ else:
52
+ if cur:
53
+ lines.append(" ".join(cur))
54
+ cur = [w]
55
+ if cur:
56
+ lines.append(" ".join(cur))
57
+ return lines
58
+
59
+
60
+ def _draw_block(draw, x, y, text, font, fill, max_width_px, line_spacing=8):
61
+ """Draw wrapped text block and return new y position."""
62
+ for line in _wrap(draw, text, font, max_width_px):
63
+ draw.text((x, y), line, font=font, fill=fill)
64
+ y += font.size + line_spacing
65
+ return y
66
+
67
+
68
+
69
  def _draw_multiline(draw, text, xy, font, fill, max_w, leading=6):
70
  text = (text or "").strip()
71
  if not text:
 
208
  except Exception as e:
209
  st.error(f"Video generation failed: {e}")
210
 
211
+ def export_records_to_video(rows, out_path: str | None = None, secs_per_slide: float = 3.0) -> str:
212
  """
213
+ Build a silent MP4 slideshow from chat rows.
214
+ Each 'row' should be a dict with keys: id, timestamp, user_message, bot_reply
215
+ Optional keys used in footer: intent, sentiment, resolution, ftr_ms
216
+
217
+ Returns the absolute path to the generated MP4.
218
  """
219
+ if not rows:
220
+ raise ValueError("No rows provided for video export.")
221
+
222
+ # Output path
223
+ out_path = out_path or str(Path("/mnt/data") / f"chat_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.mp4")
224
+ Path(out_path).parent.mkdir(parents=True, exist_ok=True)
225
+
226
+ # Canvas & theme
227
+ W, H = 1280, 720
228
+ margin = 60
229
+ box_w = W - margin * 2
230
+
231
+ bg = (247, 249, 252) # page background
232
+ card = (255, 255, 255) # card background
233
+ brand = (38, 110, 241) # brand blue
234
+ text_primary = (23, 37, 61) # main text
235
+ text_muted = (71, 85, 105) # muted
236
+ separator = (229, 231, 235) # border line
237
+
238
+ # Fonts (try DejaVu first; fallback to PIL default)
239
+ font_paths = [
240
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
241
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Book.ttf",
242
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
243
+ ]
244
+ font_title = _font_try(font_paths, 40)
245
+ font_label = _font_try(font_paths, 24)
246
+ font_body = _font_try(font_paths, 28)
247
+ font_footer = _font_try(font_paths, 22)
248
+
249
+ frames = []
250
+
251
+ # Build one slide image per row
252
+ for r in rows:
253
+ img = Image.new("RGB", (W, H), bg)
254
+ draw = ImageDraw.Draw(img)
255
+
256
+ # Card background
257
+ card_rect = [margin, margin, W - margin, H - margin]
258
+ draw.rounded_rectangle(card_rect, radius=24, fill=card, outline=separator, width=1)
259
+
260
+ x = margin + 40
261
+ y = margin + 30
262
+
263
+ # Title
264
+ timestamp = r.get("timestamp") or ""
265
+ try:
266
+ # normalize if stored as ISO
267
+ if isinstance(timestamp, str) and len(timestamp) >= 19:
268
+ # leave as is; you can pretty-format if you like
269
+ pass
270
+ except Exception:
271
+ pass
272
+
273
+ title = f"Olist E-commerce Chat • {timestamp} • ID {r.get('id','')}"
274
+ draw.text((x, y), title, font=font_title, fill=text_primary)
275
+ y += font_title.size + 20
276
+
277
+ # Separator
278
+ draw.line([(x, y), (W - margin - 40, y)], fill=separator, width=2)
279
+ y += 24
280
+
281
+ # Customer block
282
+ draw.text((x, y), "Customer", font=font_label, fill=brand)
283
+ y += font_label.size + 8
284
+ y = _draw_block(draw, x, y, r.get("user_message", ""), font_body, text_primary, box_w)
285
+ y += 16
286
+
287
+ # Assistant block
288
+ draw.text((x, y), "Assistant", font=font_label, fill=brand)
289
+ y += font_label.size + 8
290
+ y = _draw_block(draw, x, y, r.get("bot_reply", ""), font_body, text_primary, box_w)
291
+ y += 16
292
+
293
+ # Footer meta (optional)
294
+ meta_bits = []
295
+ if r.get("intent"): meta_bits.append(f"Intent: {r['intent']}")
296
+ if r.get("sentiment"): meta_bits.append(f"Sentiment: {r['sentiment']}")
297
+ if r.get("resolution"): meta_bits.append(f"Resolution: {r['resolution']}")
298
+ if r.get("ftr_ms"): meta_bits.append(f"Latency: {r['ftr_ms']} ms")
299
+ meta_text = " • ".join(meta_bits)
300
+
301
+ if meta_text:
302
+ # separator near bottom
303
+ y2 = H - margin - 80
304
+ draw.line([(x, y2), (W - margin - 40, y2)], fill=separator, width=1)
305
+ draw.text((x, y2 + 20), meta_text, font=font_footer, fill=text_muted)
306
+
307
+ frames.append(img)
308
+
309
+ # Write MP4 (silent) – duplicate each slide to control duration
310
+ fps = 30
311
+ frames_per_slide = max(1, int(secs_per_slide * fps))
312
+
313
+ with imageio.get_writer(out_path, format="ffmpeg", mode="I", fps=fps, codec="libx264", quality=8) as writer:
314
+ for im in frames:
315
+ arr = imageio.asarray(im)
316
+ for _ in range(frames_per_slide):
317
+ writer.append_data(arr)
318
 
319
+ return str(Path(out_path).resolve())