rahulmolasi commited on
Commit
96e006f
·
verified ·
1 Parent(s): 82a3187

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -88
app.py CHANGED
@@ -1,8 +1,9 @@
1
  """
2
- Two-Speaker Podcast Web App (Free HF Space)
3
  - Auto podcast after adding documents (no question needed)
4
  - Engaging script: hook → setup → 3 segments → mini-story → recap/CTA
5
- - Two voices via gTTS accent + tempo (Host: UK, Guest: AU)
 
6
  - Chroma persistent client in ./chroma_db
7
  - SentenceTransformer MiniLM-L3-v2 (lazy load)
8
  """
@@ -36,10 +37,17 @@ TARGET_MINUTES = float(os.environ.get("TARGET_MINUTES", "2.5"))
36
  WPM = int(os.environ.get("WPM", "170"))
37
  TARGET_WORDS = int(TARGET_MINUTES * WPM)
38
 
39
- # Voice accents (free-tier gTTS approximation of gender)
40
  HOST_TLD = os.environ.get("HOST_TLD", "co.uk") # UK English
41
  GUEST_TLD = os.environ.get("GUEST_TLD", "com.au")# Australian English
42
 
 
 
 
 
 
 
 
43
  os.makedirs(AUDIO_OUT_DIR, exist_ok=True)
44
 
45
  # --------------------------
@@ -49,7 +57,7 @@ os.makedirs(CHROMA_DIR, exist_ok=True)
49
  client = chromadb.PersistentClient(
50
  path=CHROMA_DIR,
51
  settings=Settings(anonymized_telemetry=False)
52
- ) # [docs confirm path + settings usage]
53
 
54
  # --------------------------
55
  # Lazy embeddings
@@ -151,7 +159,6 @@ def add_documents_for_user(username: str, files: List[str]) -> str:
151
  return f"Indexed {total_chunks} chunks into {get_collection_name(username)}."
152
 
153
  def retrieve_context(username: str, query: str = "", k: int = 12) -> List[str]:
154
- # If query empty, use centroid-like approach: query with a generic prompt to surface broad coverage
155
  col = ensure_collection(username)
156
  if query and query.strip():
157
  q_vec = embed_texts([query.strip()])[0]
@@ -162,7 +169,6 @@ def retrieve_context(username: str, query: str = "", k: int = 12) -> List[str]:
162
  except Exception:
163
  return []
164
  else:
165
- # No question: approximate coverage by querying with multiple generic anchors
166
  anchors = [
167
  "overview and key points",
168
  "main ideas and practical steps",
@@ -177,7 +183,6 @@ def retrieve_context(username: str, query: str = "", k: int = 12) -> List[str]:
177
  all_docs.extend(docs[0])
178
  except Exception:
179
  pass
180
- # Deduplicate while preserving order
181
  seen = set()
182
  deduped = []
183
  for d in all_docs:
@@ -192,8 +197,6 @@ def retrieve_context(username: str, query: str = "", k: int = 12) -> List[str]:
192
  SHOW_NAME = "Signal & Summary"
193
 
194
  def synthesize_dialogue(username: str, query: str, context_docs: List[str], min_words: int = TARGET_WORDS) -> str:
195
- # Build a structured two-speaker script targeting min_words.
196
- # Keep labels in transcript; TTS will strip them.
197
  ctx_points = []
198
  for d in context_docs:
199
  s = " ".join(d.split())
@@ -204,20 +207,21 @@ def synthesize_dialogue(username: str, query: str, context_docs: List[str], min_
204
  G = lambda t: f"Guest: {t}"
205
 
206
  parts = []
207
- # Cold open hook (no welcome phrase)
208
  if query and query.strip():
209
  qtxt = query.strip()
210
- parts.append(H(f"Let’s start bold: what if {qtxt} could be simplified into one move today?"))
211
- parts.append(G("That’s ambitious—let’s make it real. By the end, there’s a specific next step."))
212
  else:
213
- parts.append(H("Let’s cut through noise and get to the signal."))
214
- parts.append(G("Agreed—clear steps, minimal fluff, and one practical commitment at the end."))
215
 
216
- # Setup with stakes
217
  parts.append(H("Why this matters: attention is scarce, constraints are real, and experiments beat debates."))
218
- # Context highlights woven naturally
 
219
  if ctx_points:
220
- parts.append(G("Ground truth from the reading, without jargon:"))
221
  for c in ctx_points[:6]:
222
  parts.append(G(f"- {c}"))
223
 
@@ -225,20 +229,20 @@ def synthesize_dialogue(username: str, query: str, context_docs: List[str], min_
225
  parts.append(H("Segment 1 — Define the problem without buzzwords."))
226
  parts.append(G("Write it in one sentence. If it needs a paragraph, the scope is off."))
227
  parts.append(H("Segment 2 — Constraints as design tools."))
228
- parts.append(G("Constraints don’t block progress—they focus it. Choose one that forces a useful trade‑off."))
229
  parts.append(H("Segment 3 — Practice over opinion."))
230
- parts.append(G("Ship a thin slice in seven days, measure one leading indicator, and ignore vanity metrics."))
231
 
232
  # Mini story
233
  parts.append(H("Quick story: we narrowed to a single user path and iteration speed doubled."))
234
  parts.append(G("Because decisions moved from meetings to real feedback, and that changed everything."))
235
 
236
  # Recap + CTA
237
- parts.append(H("Recap: define clearly, use constraints, and ship the smallest thing that teaches."))
238
- parts.append(G("Call to action: draft the one sentence, pick one constraint, commit to a seven‑day experiment."))
239
  parts.append(H(f"That’s today on {SHOW_NAME}. Keep it specific, keep it human."))
240
 
241
- # Pad to target words with natural back‑and‑forth
242
  base_words = sum(len(p.split()) for p in parts)
243
  if base_words < min_words:
244
  beats = [
@@ -246,7 +250,7 @@ def synthesize_dialogue(username: str, query: str, context_docs: List[str], min_
246
  G("Answer: the one that reaches a real user and returns a signal within days, not months."),
247
  H("What if the result is messy or negative?"),
248
  G("That’s data. Shorten the loop, adjust scope, and try again—momentum matters."),
249
- H("Final note: clarity scales; cleverness does not."),
250
  G("Keep it measurable and kind. Then press record—metaphorically and literally."),
251
  ]
252
  i = 0
@@ -259,69 +263,100 @@ def synthesize_dialogue(username: str, query: str, context_docs: List[str], min_
259
  return "\n".join(parts)
260
 
261
  # --------------------------
262
- # TTS: two accents + tempo
263
  # --------------------------
264
- def tts_line_to_file(text: str, speaker: str, lang: str = "en", tld: str = "co.uk", slow: bool = False) -> str:
265
- # Strip labels so they aren't spoken
266
- spoken = text
267
- if spoken.startswith("Host:"):
268
- spoken = spoken[len("Host:"):].lstrip()
269
- elif spoken.startswith("Guest:"):
270
- spoken = spoken[len("Guest:"):].lstrip()
271
- out_path = os.path.join(AUDIO_OUT_DIR, f"{int(time.time())}_{speaker}_{uuid.uuid4().hex[:6]}.mp3")
 
 
272
  tts = gTTS(text=spoken, lang=lang, tld=tld, slow=slow)
273
- tts.save(out_path)
274
- return out_path # Always path to the just-created MP3
275
 
276
- def generate_two_voice_audio(dialogue: str) -> str:
277
- # Always base synthesis on the dialogue variable provided here.
 
 
278
  try:
279
- from pydub import AudioSegment, effects
280
- # Build segments per line with contrasting accents
281
- seg_meta = []
282
- for line in dialogue.splitlines():
283
- line = line.strip()
284
- if not line:
285
- continue
286
- if line.startswith("Guest:"):
287
- seg_meta.append((tts_line_to_file(line, "guest", lang="en", tld=GUEST_TLD, slow=False), "guest"))
288
- else:
289
- seg_meta.append((tts_line_to_file(line, "host", lang="en", tld=HOST_TLD, slow=False), "host"))
290
-
291
- # Concatenate and lightly adjust tempo per speaker
292
- final = None
293
- for path, who in seg_meta:
294
- seg = AudioSegment.from_file(path, format="mp3")
295
- if who == "host":
296
- seg = effects.speedup(seg, playback_speed=1.06, crossfade=0)
297
  else:
298
- seg = effects.speedup(seg, playback_speed=0.95, crossfade=0)
299
- final = seg if final is None else final + seg
300
-
301
- out_path = os.path.join(AUDIO_OUT_DIR, f"{int(time.time())}_podcast_{uuid.uuid4().hex[:6]}.mp3")
302
- final.export(out_path, format="mp3")
303
  return out_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
 
 
 
 
 
305
  except Exception:
306
- # Fallback: still speak the exact dialogue variable; do NOT use any static text
307
- merged_text = "\n".join(
308
- [l.replace("Host:", "").replace("Guest:", "").strip()
309
- for l in dialogue.splitlines() if l.strip()]
310
- )
311
- single = tts_line_to_file(merged_text, "podcast", lang="en", tld=HOST_TLD, slow=False)
312
- return single or ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
  def answer_with_podcast_for_user(username: str, query: str = "") -> Tuple[str, str]:
315
  docs = retrieve_context(username, query=query, k=12)
316
  dialogue = synthesize_dialogue(username, query, docs, min_words=TARGET_WORDS)
317
  audio_path = generate_two_voice_audio(dialogue)
318
- return dialogue, audio_path # Return the fresh dialogue and its MP3 path
319
 
320
- def on_generate(username, query, pwd):
321
- if not check_password(pwd):
322
- return "Invalid password.", None
323
- dlg, audio = answer_with_podcast_for_user(username, query=query or "")
324
- return dlg, audio # Textbox gets dlg; Audio gets the new filepath
325
  # --------------------------
326
  # Gradio UI
327
  # --------------------------
@@ -346,8 +381,7 @@ def main_ui():
346
  add_docs_btn = gr.Button("Add Documents")
347
  add_docs_output = gr.Label(value="")
348
  with gr.Column():
349
- # Question is optional; auto generation triggers after adding docs
350
- query_input = gr.Textbox(label="(Optional) Add a focus question", value="")
351
  generate_btn = gr.Button("Generate Podcast")
352
  podcast_text_output = gr.Textbox(label="Generated Dialogue", lines=18)
353
  podcast_audio_output = gr.Audio(label="Download Podcast", type="filepath")
@@ -358,11 +392,9 @@ def main_ui():
358
 
359
  def on_add_docs(username, files, pwd):
360
  if not check_password(pwd):
361
- return "Invalid password."
362
  msg = add_documents_for_user(username, files)
363
- # Auto-generate podcast immediately (no question needed)
364
  dlg, audio = answer_with_podcast_for_user(username, query="")
365
- # Update both the add_docs label and the outputs via chained events below
366
  return msg, dlg, audio
367
 
368
  def on_generate(username, query, pwd):
@@ -372,26 +404,32 @@ def main_ui():
372
  return dlg, audio
373
 
374
  login_btn.click(on_login, inputs=password, outputs=login_msg)
375
- # On add_docs, also update the podcast outputs so generation is automatic
376
- add_docs_btn.click(on_add_docs, inputs=[username_input, upload_files, password],
377
- outputs=[add_docs_output, podcast_text_output, podcast_audio_output])
378
 
379
- # Manual regenerate
380
- generate_btn.click(on_generate, inputs=[username_input, query_input, password],
381
- outputs=[podcast_text_output, podcast_audio_output])
 
 
382
 
383
- # Optional: also trigger on file upload directly (auto on change)
384
  def on_files_uploaded(files, username, pwd):
385
- # only act if already logged in
386
  if not check_password(pwd):
387
  return gr.update(), gr.update(), gr.update()
388
  msg = add_documents_for_user(username, files)
389
  dlg, audio = answer_with_podcast_for_user(username, query="")
390
  return msg, dlg, audio
391
 
392
- # Bind .upload event so dropping files can auto-generate without clicking "Add Documents"
393
- upload_files.upload(on_files_uploaded, inputs=[upload_files, username_input, password],
394
- outputs=[add_docs_output, podcast_text_output, podcast_audio_output])
 
 
 
 
 
 
 
 
395
 
396
  demo.launch()
397
 
 
1
  """
2
+ Two-Speaker Podcast Web App (ElevenLabs + gTTS Fallback)
3
  - Auto podcast after adding documents (no question needed)
4
  - Engaging script: hook → setup → 3 segments → mini-story → recap/CTA
5
+ - Primary TTS: ElevenLabs (two named voices) if configured
6
+ - Fallback TTS: gTTS accents + tempo contrast (Host: UK, Guest: AU)
7
  - Chroma persistent client in ./chroma_db
8
  - SentenceTransformer MiniLM-L3-v2 (lazy load)
9
  """
 
37
  WPM = int(os.environ.get("WPM", "170"))
38
  TARGET_WORDS = int(TARGET_MINUTES * WPM)
39
 
40
+ # gTTS accents (free-tier approximation of different speakers)
41
  HOST_TLD = os.environ.get("HOST_TLD", "co.uk") # UK English
42
  GUEST_TLD = os.environ.get("GUEST_TLD", "com.au")# Australian English
43
 
44
+ # ElevenLabs config (optional)
45
+ ELEVEN_API_KEY = os.environ.get("ELEVEN_API_KEY", "")
46
+ ELEVEN_MODEL_ID = os.environ.get("ELEVEN_MODEL_ID", "eleven_multilingual_v2")
47
+ ELEVEN_HOST_VOICE_ID = os.environ.get("ELEVEN_HOST_VOICE_ID", "")
48
+ ELEVEN_GUEST_VOICE_ID = os.environ.get("ELEVEN_GUEST_VOICE_ID", "")
49
+ USE_ELEVEN = bool(ELEVEN_API_KEY and (ELEVEN_HOST_VOICE_ID or ELEVEN_GUEST_VOICE_ID))
50
+
51
  os.makedirs(AUDIO_OUT_DIR, exist_ok=True)
52
 
53
  # --------------------------
 
57
  client = chromadb.PersistentClient(
58
  path=CHROMA_DIR,
59
  settings=Settings(anonymized_telemetry=False)
60
+ ) # Persistent local store [web:15]
61
 
62
  # --------------------------
63
  # Lazy embeddings
 
159
  return f"Indexed {total_chunks} chunks into {get_collection_name(username)}."
160
 
161
  def retrieve_context(username: str, query: str = "", k: int = 12) -> List[str]:
 
162
  col = ensure_collection(username)
163
  if query and query.strip():
164
  q_vec = embed_texts([query.strip()])[0]
 
169
  except Exception:
170
  return []
171
  else:
 
172
  anchors = [
173
  "overview and key points",
174
  "main ideas and practical steps",
 
183
  all_docs.extend(docs[0])
184
  except Exception:
185
  pass
 
186
  seen = set()
187
  deduped = []
188
  for d in all_docs:
 
197
  SHOW_NAME = "Signal & Summary"
198
 
199
  def synthesize_dialogue(username: str, query: str, context_docs: List[str], min_words: int = TARGET_WORDS) -> str:
 
 
200
  ctx_points = []
201
  for d in context_docs:
202
  s = " ".join(d.split())
 
207
  G = lambda t: f"Guest: {t}"
208
 
209
  parts = []
210
+ # Cold open hook (no generic welcomes)
211
  if query and query.strip():
212
  qtxt = query.strip()
213
+ parts.append(H(f"Here’s a thought: what if {qtxt} could be simplified to one move today?"))
214
+ parts.append(G("Let’s see if that holds—by the end, there’s a concrete next step."))
215
  else:
216
+ parts.append(H("Let’s cut the noise and dial in the signal."))
217
+ parts.append(G("Clear steps, minimal fluff, and one practical commitment at the end."))
218
 
219
+ # Stakes
220
  parts.append(H("Why this matters: attention is scarce, constraints are real, and experiments beat debates."))
221
+
222
+ # Natural context highlights
223
  if ctx_points:
224
+ parts.append(G("From the background, said plainly:"))
225
  for c in ctx_points[:6]:
226
  parts.append(G(f"- {c}"))
227
 
 
229
  parts.append(H("Segment 1 — Define the problem without buzzwords."))
230
  parts.append(G("Write it in one sentence. If it needs a paragraph, the scope is off."))
231
  parts.append(H("Segment 2 — Constraints as design tools."))
232
+ parts.append(G("Constraints don’t block progress—they focus it. Choose one to force a useful trade‑off."))
233
  parts.append(H("Segment 3 — Practice over opinion."))
234
+ parts.append(G("Ship a thin slice in seven days, measure one leading indicator, ignore vanity metrics."))
235
 
236
  # Mini story
237
  parts.append(H("Quick story: we narrowed to a single user path and iteration speed doubled."))
238
  parts.append(G("Because decisions moved from meetings to real feedback, and that changed everything."))
239
 
240
  # Recap + CTA
241
+ parts.append(H("Recap: define clearly, use constraints, ship the smallest thing that teaches."))
242
+ parts.append(G("Your move: write the one sentence, pick one constraint, commit to a seven‑day experiment."))
243
  parts.append(H(f"That’s today on {SHOW_NAME}. Keep it specific, keep it human."))
244
 
245
+ # Pad to target words
246
  base_words = sum(len(p.split()) for p in parts)
247
  if base_words < min_words:
248
  beats = [
 
250
  G("Answer: the one that reaches a real user and returns a signal within days, not months."),
251
  H("What if the result is messy or negative?"),
252
  G("That’s data. Shorten the loop, adjust scope, and try again—momentum matters."),
253
+ H("Final note: clarity scales; cleverness doesn’t."),
254
  G("Keep it measurable and kind. Then press record—metaphorically and literally."),
255
  ]
256
  i = 0
 
263
  return "\n".join(parts)
264
 
265
  # --------------------------
266
+ # TTS: ElevenLabs + gTTS fallback
267
  # --------------------------
268
+ def strip_labels(text: str) -> str:
269
+ if text.startswith("Host:"):
270
+ return text[len("Host:"):].lstrip()
271
+ if text.startswith("Guest:"):
272
+ return text[len("Guest:"):].lstrip()
273
+ return text
274
+
275
+ def tts_line_to_file_gtts(text: str, speaker: str, lang: str = "en", tld: str = "co.uk", slow: bool = False) -> str:
276
+ spoken = strip_labels(text)
277
+ path = os.path.join(AUDIO_OUT_DIR, f"{int(time.time())}_{speaker}_{uuid.uuid4().hex[:6]}.mp3")
278
  tts = gTTS(text=spoken, lang=lang, tld=tld, slow=slow)
279
+ tts.save(path)
280
+ return path
281
 
282
+ def tts_line_to_file_eleven(text: str, voice_id: str, speaker: str) -> str:
283
+ # Uses official SDK convert; on error returns None for fallback
284
+ spoken = strip_labels(text)
285
+ out_path = os.path.join(AUDIO_OUT_DIR, f"{int(time.time())}_{speaker}_{uuid.uuid4().hex[:6]}.mp3")
286
  try:
287
+ from elevenlabs.client import ElevenLabs # pip install elevenlabs
288
+ client_el = ElevenLabs(api_key=ELEVEN_API_KEY)
289
+ audio = client_el.text_to_speech.convert(
290
+ text=spoken,
291
+ voice_id=voice_id,
292
+ model_id=ELEVEN_MODEL_ID,
293
+ output_format="mp3_44100_128"
294
+ ) # May return an iterator of chunks
295
+ with open(out_path, "wb") as f:
296
+ if hasattr(audio, "__iter__") and not isinstance(audio, (bytes, bytearray)):
297
+ for chunk in audio:
298
+ if isinstance(chunk, (bytes, bytearray)):
299
+ f.write(chunk)
 
 
 
 
 
300
  else:
301
+ f.write(audio if isinstance(audio, (bytes, bytearray)) else bytes(audio))
 
 
 
 
302
  return out_path
303
+ except Exception:
304
+ return None # Signal fallback
305
+
306
+ def tts_line_to_file_unified(text: str, speaker: str) -> str:
307
+ # Prefer ElevenLabs if configured; else gTTS
308
+ if USE_ELEVEN:
309
+ vid = ELEVEN_HOST_VOICE_ID if speaker == "host" else ELEVEN_GUEST_VOICE_ID
310
+ if vid:
311
+ path = tts_line_to_file_eleven(text, vid, speaker)
312
+ if path:
313
+ return path
314
+ # Fallback to gTTS with contrasting accents
315
+ tld = HOST_TLD if speaker == "host" else GUEST_TLD
316
+ return tts_line_to_file_gtts(text, speaker=speaker, lang="en", tld=tld, slow=False)
317
 
318
+ def generate_two_voice_audio(dialogue: str) -> str:
319
+ # Concatenate segments and lightly adjust tempo per voice (requires pydub + ffmpeg)
320
+ try:
321
+ from pydub import AudioSegment, effects
322
  except Exception:
323
+ merged_text = "\n".join([strip_labels(l) for l in dialogue.splitlines() if l.strip()])
324
+ return tts_line_to_file_unified(merged_text, speaker="host")
325
+
326
+ segs = []
327
+ for line in dialogue.splitlines():
328
+ line = line.strip()
329
+ if not line:
330
+ continue
331
+ if line.startswith("Guest:"):
332
+ segs.append((tts_line_to_file_unified(line, "guest"), "guest"))
333
+ else:
334
+ segs.append((tts_line_to_file_unified(line, "host"), "host"))
335
+
336
+ final = None
337
+ for path, who in segs:
338
+ seg = AudioSegment.from_file(path, format="mp3")
339
+ # Subtle tempo differences for separation
340
+ if who == "host":
341
+ seg = effects.speedup(seg, playback_speed=1.06, crossfade=0)
342
+ else:
343
+ # pydub has speedup; for slowdown <1.0, speedup may distort—keep modest change or skip if artifacts
344
+ try:
345
+ seg = effects.speedup(seg, playback_speed=0.95, crossfade=0)
346
+ except Exception:
347
+ pass
348
+ final = seg if final is None else final + seg
349
+
350
+ out_path = os.path.join(AUDIO_OUT_DIR, f"{int(time.time())}_podcast_{uuid.uuid4().hex[:6]}.mp3")
351
+ final.export(out_path, format="mp3")
352
+ return out_path
353
 
354
  def answer_with_podcast_for_user(username: str, query: str = "") -> Tuple[str, str]:
355
  docs = retrieve_context(username, query=query, k=12)
356
  dialogue = synthesize_dialogue(username, query, docs, min_words=TARGET_WORDS)
357
  audio_path = generate_two_voice_audio(dialogue)
358
+ return dialogue, audio_path or ""
359
 
 
 
 
 
 
360
  # --------------------------
361
  # Gradio UI
362
  # --------------------------
 
381
  add_docs_btn = gr.Button("Add Documents")
382
  add_docs_output = gr.Label(value="")
383
  with gr.Column():
384
+ query_input = gr.Textbox(label="(Optional) Focus question", value="")
 
385
  generate_btn = gr.Button("Generate Podcast")
386
  podcast_text_output = gr.Textbox(label="Generated Dialogue", lines=18)
387
  podcast_audio_output = gr.Audio(label="Download Podcast", type="filepath")
 
392
 
393
  def on_add_docs(username, files, pwd):
394
  if not check_password(pwd):
395
+ return "Invalid password.", None, None
396
  msg = add_documents_for_user(username, files)
 
397
  dlg, audio = answer_with_podcast_for_user(username, query="")
 
398
  return msg, dlg, audio
399
 
400
  def on_generate(username, query, pwd):
 
404
  return dlg, audio
405
 
406
  login_btn.click(on_login, inputs=password, outputs=login_msg)
 
 
 
407
 
408
+ add_docs_btn.click(
409
+ on_add_docs,
410
+ inputs=[username_input, upload_files, password],
411
+ outputs=[add_docs_output, podcast_text_output, podcast_audio_output]
412
+ )
413
 
414
+ # Auto-generate on file upload as well
415
  def on_files_uploaded(files, username, pwd):
 
416
  if not check_password(pwd):
417
  return gr.update(), gr.update(), gr.update()
418
  msg = add_documents_for_user(username, files)
419
  dlg, audio = answer_with_podcast_for_user(username, query="")
420
  return msg, dlg, audio
421
 
422
+ upload_files.upload(
423
+ on_files_uploaded,
424
+ inputs=[upload_files, username_input, password],
425
+ outputs=[add_docs_output, podcast_text_output, podcast_audio_output]
426
+ )
427
+
428
+ generate_btn.click(
429
+ on_generate,
430
+ inputs=[username_input, query_input, password],
431
+ outputs=[podcast_text_output, podcast_audio_output]
432
+ )
433
 
434
  demo.launch()
435