Spaces:
Sleeping
Sleeping
Update services/podcast_service.py
Browse files1234567899 unmodified lines19202122232425262728293031329 unmodified lines4243444546474835 unmodified lines848586878889909192939495969798991001016 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431443 unmodified lines14814915015115215315415515615715815916016116216316416516616726 unmodified lines194195196197198199200201202203204205206207from __future__ import annotationsimport loggingimport osimport reimport tempfileimport uuidfrom datetime import datetimefrom pathlib import Path9 unmodified linesTEMPERATURE = 0.7TIMEOUT_SEC = 90# Bark voice presets for the two hostsHOST_A_VOICE = "v2/en_speaker_6" # deeper male voiceHOST_B_VOICE = "v2/en_speaker_9" # female voice# Max chars per Bark chunk (Bark struggles with long inputs)BARK_CHUNK_CHARS = 220# Output dir for audio files — must be accessible by GradioAUDIO_OUTPUT_DIR = Path("assets/podcasts")9 unmodified lines- Sam explains concepts clearly with examples and analogies- The conversation should feel natural, not like a lecture- Cover the key points from the summary- Length: 10–15 exchanges (back-and-forth lines)FORMAT RULES (strictly follow these):- Every line must start with either "Alex:" or "Sam:" followed by a space35 unmodified linesreturn "\n".join(parts)def _chunk_text(text: str, max_chars: int) -> list[str]:"""Split text into chunks at sentence boundaries for Bark TTS."""sentences = re.split(r'(?<=[.!?])\s+', text.strip())chunks = []current = ""for sent in sentences:if len(current) + len(sent) + 1 <= max_chars:current = (current + " " + sent).strip()else:if current:chunks.append(current)# If single sentence is too long, hard-split itif len(sent) > max_chars:for i in range(0, len(sent), max_chars):chunks.append(sent[i:i + max_chars])6 unmodified linesdef _synthesize_audio(lines: list[tuple[str, str]], output_path: Path) -> bool:"""Synthesize podcast audio using Bark TTS.Concatenates per-speaker audio chunks into a single WAV file.Returns True on success, False on failure."""try:import numpy as npfrom bark import SAMPLE_RATE, generate_audio, preload_modelsimport scipy.io.wavfile as wavlogger.info("Loading Bark models...")preload_models()all_audio: list[np.ndarray] = []silence = np.zeros(int(SAMPLE_RATE * 0.4), dtype=np.float32) # 0.4s pause between turnsfor speaker, text in lines:voice_preset = HOST_A_VOICE if speaker == "Alex" else HOST_B_VOICEchunks = _chunk_text(text, BARK_CHUNK_CHARS)for chunk in chunks:try:audio_array = generate_audio(chunk, history_prompt=voice_preset)all_audio.append(audio_array.astype(np.float32))except Exception as chunk_err:logger.warning("Bark chunk failed for speaker %s: %s", speaker, chunk_err)all_audio.append(silence)if not all_audio:return Falsecombined = np.concatenate(all_audio)# Normalize to prevent clippingmax_val = np.max(np.abs(combined))if max_val > 0:combined = combined / max_val * 0.953 unmodified lineslogger.info("Podcast audio saved to %s", output_path)return Trueexcept ImportError:logger.warning("Bark not installed. Skipping TTS. Install with: pip install bark")return Falseexcept Exception as e:logger.error("Bark TTS failed: %s", e)return Falsedef generate_podcast(notebook: Notebook, summary_content: str) -> Artifact:"""Generate a podcast artifact:1. Generate script via HF InferenceClient2. Synthesize audio via Bark TTSReturns an Artifact with content=markdown script and audio_path set if TTS succeeded."""token = os.environ.get("HF_TOKEN")client = InferenceClient(token=token, timeout=TIMEOUT_SEC)26 unmodified lineslogger.error("Podcast script generation failed: %s", e)lines = [("Alex", "Welcome to the podcast! Unfortunately we ran into an issue generating today's episode."),("Sam", f"The script generation failed with error: {e}. Please try again."),("Alex", "Thanks for listening, and we'll be back with a full episode soon!"),]# Build markdown script for displaymarkdown_script = _script_to_markdown(lines)# Synthesize audioaudio_filename = f"podcast_{uuid.uuid4().hex[:12]}.wav"audio_path = AUDIO_OUTPUT_DIR / audio_filenameaudio_success = _synthesize_audio(lines, audio_path)1234567899 unmodified lines1920212223242526272829303132339 unmodified lines4344454647484935 unmodified lines8586878889909192939495969798991006 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651663 unmodified lines17017117217317417517617717817918018118218318418518618718818926 unmodified lines216217218219220221222223224225226227from __future__ import annotationsimport ioimport loggingimport osimport reimport uuidfrom datetime import datetimefrom pathlib import Path9 unmodified linesTEMPERATURE = 0.7TIMEOUT_SEC = 90# Two different HF TTS models for distinct host voices — runs via HF Inference API,# no local model download needed, works fine on free SpacesTTS_MODEL_ALEX = "espnet/kan-bayashi_ljspeech_vits" # Host AlexTTS_MODEL_SAM = "facebook/mms-tts-eng" # Host Sam# Max chars per TTS requestTTS_CHUNK_CHARS = 300# Output dir for audio — must be accessible by Gradio's /file= endpointAUDIO_OUTPUT_DIR = Path("assets/podcasts")9 unmodified lines- Sam explains concepts clearly with examples and analogies- The conversation should feel natural, not like a lecture- Cover the key points from the summary- Length: 10-15 exchanges (back-and-forth lines)FORMAT RULES (strictly follow these):- Every line must start with either "Alex:" or "Sam:" followed by a space35 unmodified linesreturn "\n".join(parts)def _chunk_text(text: str, max_chars: int = TTS_CHUNK_CHARS) -> list[str]:"""Split text into chunks at sentence boundaries."""sentences = re.split(r'(?<=[.!?])\s+', text.strip())chunks, current = [], ""for sent in sentences:if len(current) + len(sent) + 1 <= max_chars:current = (current + " " + sent).strip()else:if current:chunks.append(current)if len(sent) > max_chars:for i in range(0, len(sent), max_chars):chunks.append(sent[i:i + max_chars])6 unmodified linesdef _synthesize_audio(lines: list[tuple[str, str]], output_path: Path) -> bool:"""Synthesize podcast audio using HF Inference API TTS.Calls the API per chunk, concatenates raw audio bytes, saves as WAV.Returns True on success, False on failure."""try:import numpy as npimport scipy.io.wavfile as wavtoken = os.environ.get("HF_TOKEN")client = InferenceClient(token=token, timeout=TIMEOUT_SEC)SAMPLE_RATE = 22050 # Standard for most HF TTS modelsall_audio: list[np.ndarray] = []silence = np.zeros(int(SAMPLE_RATE * 0.5), dtype=np.float32)for speaker, text in lines:tts_model = TTS_MODEL_ALEX if speaker == "Alex" else TTS_MODEL_SAMchunks = _chunk_text(text)for chunk in chunks:try:# text_to_speech returns raw audio bytesaudio_bytes = client.text_to_speech(chunk, model=tts_model)# Parse WAV bytes using scipyrate, data = wav.read(io.BytesIO(audio_bytes))# Normalize to float32if data.dtype == np.int16:audio_float = data.astype(np.float32) / 32768.0elif data.dtype == np.int32:audio_float = data.astype(np.float32) / 2147483648.0else:audio_float = data.astype(np.float32)# Handle stereo → monoif audio_float.ndim == 2:audio_float = audio_float.mean(axis=1)# Resample if needed (simple approach: just use as-is, note the rate)if rate != SAMPLE_RATE:SAMPLE_RATE = rate # Use whatever rate the model returnsall_audio.append(audio_float)except Exception as chunk_err:logger.warning("TTS chunk failed for %s: %s", speaker, chunk_err)all_audio.append(silence)if not all_audio:return Falsecombined = np.concatenate(all_audio)max_val = np.max(np.abs(combined))if max_val > 0:combined = combined / max_val * 0.953 unmodified lineslogger.info("Podcast audio saved to %s", output_path)return Trueexcept ImportError as e:logger.warning("scipy not installed, skipping TTS: %s", e)return Falseexcept Exception as e:logger.error("TTS synthesis failed: %s", e)return Falsedef generate_podcast(notebook: Notebook, summary_content: str) -> Artifact:"""Generate a podcast artifact:1. Generate two-host script via HF InferenceClient (Qwen)2. Synthesize audio via HF Inference API TTS (no local models)Returns an Artifact with markdown script + audio_path if TTS succeeded."""token = os.environ.get("HF_TOKEN")client = InferenceClient(token=token, timeout=TIMEOUT_SEC)26 unmodified lineslogger.error("Podcast script generation failed: %s", e)lines = [("Alex", "Welcome to the podcast! Unfortunately we ran into an issue generating today's episode."),("Sam", f"The script generation failed. Please try again."),("Alex", "Thanks for listening — we'll be back soon!"),]markdown_script = _script_to_markdown(lines)audio_filename = f"podcast_{uuid.uuid4().hex[:12]}.wav"audio_path = AUDIO_OUTPUT_DIR / audio_filenameaudio_success = _synthesize_audio(lines, audio_path)
services/podcast_service.py+55-35