Spaces:
Sleeping
Sleeping
Update services/podcast_service.py
Browse files7 unmodified lines8910111213141516171819202122232425262728293031323325 unmodified lines5960616263646511 unmodified lines777879808182832 unmodified lines8687888990919213 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916010 unmodified lines1711721731741751761771 unmodified line1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212227 unmodified linesfrom datetime import datetimefrom pathlib import Pathfrom huggingface_hub import InferenceClientfrom state import Artifact, Notebooklogger = logging.getLogger(__name__)GEN_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"MAX_NEW_TOKENS = 2048TEMPERATURE = 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")25 unmodified linesdef _parse_script_lines(raw: str) -> list[tuple[str, str]]:"""Parse script into list of (speaker, text) tuples."""lines = []for line in raw.strip().splitlines():line = line.strip()11 unmodified linesdef _script_to_markdown(lines: list[tuple[str, str]]) -> str:"""Convert parsed lines to readable markdown for display."""parts = ["## ποΈ Podcast Script\n"]for speaker, text in lines:emoji = "π€" if speaker == "Alex" else "π§"2 unmodified linesdef _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:13 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:10 unmodified linesreturn 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)1 unmodified linedef 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)prompt = _build_podcast_prompt(summary_content)try:response = client.chat_completion(model=GEN_MODEL,messages=[{"role": "system","content": ("You are a podcast scriptwriter. Write natural, engaging dialogue between two hosts. ""Every line must start with 'Alex:' or 'Sam:'. No markdown, no stage directions."),},{"role": "user", "content": prompt},],max_tokens=MAX_NEW_TOKENS,temperature=TEMPERATURE,)raw_script = response.choices[0].message.content or ""lines = _parse_script_lines(raw_script)if not lines:raise ValueError("No speaker lines parsed from LLM response.")except Exception as e:logger.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!"),]7 unmodified lines8910111213141516171819202122232425262725 unmodified lines53545556575811 unmodified lines7071727374752 unmodified lines78798081828313 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313410 unmodified lines1451461471481491501511 unmodified line1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811827 unmodified linesfrom datetime import datetimefrom pathlib import Pathimport anthropicfrom state import Artifact, Notebooklogger = logging.getLogger(__name__)MODEL = "claude-haiku-4-5-20251001"MAX_TOKENS = 2048# Two HF TTS models for distinct host voices β runs via HF Inference APITTS_MODEL_ALEX = "espnet/kan-bayashi_ljspeech_vits"TTS_MODEL_SAM = "facebook/mms-tts-eng"TTS_CHUNK_CHARS = 300AUDIO_OUTPUT_DIR = Path("assets/podcasts")25 unmodified linesdef _parse_script_lines(raw: str) -> list[tuple[str, str]]:lines = []for line in raw.strip().splitlines():line = line.strip()11 unmodified linesdef _script_to_markdown(lines: list[tuple[str, str]]) -> str:parts = ["## ποΈ Podcast Script\n"]for speaker, text in lines:emoji = "π€" if speaker == "Alex" else "π§"2 unmodified linesdef _chunk_text(text: str, max_chars: int = TTS_CHUNK_CHARS) -> list[str]:sentences = re.split(r'(?<=[.!?])\s+', text.strip())chunks, current = [], ""for sent in sentences:13 unmodified linesdef _synthesize_audio(lines: list[tuple[str, str]], output_path: Path) -> bool:"""Synthesize audio via HF Inference API TTS. Returns True on success."""try:import numpy as npimport scipy.io.wavfile as wavfrom huggingface_hub import InferenceClienttoken = os.environ.get("HF_TOKEN")client = InferenceClient(token=token, timeout=90)SAMPLE_RATE = 22050all_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_SAMfor chunk in _chunk_text(text):try:audio_bytes = client.text_to_speech(chunk, model=tts_model)rate, data = wav.read(io.BytesIO(audio_bytes))if 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)if audio_float.ndim == 2:audio_float = audio_float.mean(axis=1)if rate != SAMPLE_RATE:SAMPLE_RATE = rateall_audio.append(audio_float)except Exception as e:logger.warning("TTS chunk failed for %s: %s", speaker, e)all_audio.append(silence)if not all_audio:10 unmodified linesreturn Trueexcept ImportError as e:logger.warning("Missing dependency for TTS: %s", e)return Falseexcept Exception as e:logger.error("TTS synthesis failed: %s", e)1 unmodified linedef generate_podcast(notebook: Notebook, summary_content: str) -> Artifact:"""Generate podcast script via Claude + audio via HF TTS."""client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))try:response = client.messages.create(model=MODEL,max_tokens=MAX_TOKENS,system=("You are a podcast scriptwriter. Write natural, engaging dialogue between two hosts. ""Every line must start with 'Alex:' or 'Sam:'. No markdown, no stage directions."),messages=[{"role": "user", "content": _build_podcast_prompt(summary_content)}],)raw_script = response.content[0].text or ""lines = _parse_script_lines(raw_script)if not lines:raise ValueError("No speaker lines parsed from response.")except Exception as e:logger.error("Podcast script generation failed: %s", e)lines = [("Alex", "Welcome to the podcast! Unfortunately we ran into an issue generating today's episode."),("Sam", "The script generation failed. Please try again."),("Alex", "Thanks for listening β we'll be back soon!"),]
services/podcast_service.py+28-68