Spaces:
Paused
Paused
Commit ·
68f1a16
1
Parent(s): c7cbd46
perf: 5 latency optimizations for TTS playback
Browse files1. Pre-generate all paragraphs on book select (background thread)
4. Audio cache - save WAVs per chunk+voice, skip re-synthesis on replay
5. Reduce LFM Q&A max_new_tokens 200->100 (halves generation time)
11. Eager pre-buffering - serves from cache if pre-gen complete
13. Transition chime (0.3s 440Hz fade) between chunks to mask gaps
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Files changed (4)
- app.py+11-12
- inference_lfm.py+5-15
- requirements_lfm.txt-1
- tts.py+156-12
15 unmodified lines16171819202122394 unmodified lines417418419420421422423424425426427428429430227 unmodified lines65865966066166266366466540 unmodified lines706707708709710711341 unmodified lines105310541055105610571058105915 unmodified linesimport timefrom pathlib import Pathfrom tts import split_into_chunks, generate_audio_streamfrom inference import transcribe_audio, answer_story_questionfrom inference_lfm import answer_question_audio, SAMPLE_RATE as LFM_SRfrom voice_clone import load_default_profile, list_saved_profiles394 unmodified linesget_custom_voice_model()print("[MomsVoice] TTS model ready.")print("[MomsVoice] Preloading Whisper-small ASR model...")from inference import get_asr_pipeline, get_qa_modelget_asr_pipeline()print("[MomsVoice] ASR model ready.")print("[MomsVoice] Preloading Qwen2.5-3B-Instruct Q&A model...")get_qa_model()print("[MomsVoice] Q&A model ready. All models preloaded.")# Gradio Application Core setup227 unmodified lines<div style="font-size: 11.5px; color: #1c1c19; line-height: 2;">🎙️ <strong>Voice Cloning:</strong> Qwen3-TTS-1.7B-Base (bfloat16)<br>🗣️ <strong>Stock TTS:</strong> Qwen3-TTS-0.6B-CustomVoice<br>👂 <strong>ASR:</strong> Whisper-small<br>🧠 <strong>Q&A:</strong> Qwen2.5-3B-Instruct</div></div>""")40 unmodified linesparas = load_paragraphs(selected["story_path"])total = max(len(paras) - 1, 0)tts_chunks = split_into_chunks("\n\n".join(paras))chunk_html = f"""<div style="margin-top: 8px; font-size: 10px; color: #64748b; font-family: monospace; text-align: center;">{len(tts_chunks)} chunks ready — tap Play</div>"""status_html = """<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">341 unmodified linesquestion_audio_path=question_audio_path if has_audio else None,question_text=q_txt if q_txt and not has_audio else None,story_context=story_context,max_new_tokens=200,)if not answer_text:answer_text = "Hmm, I'm not sure about that! Let's keep listening to find out."15 unmodified lines16171819202122394 unmodified lines417418419420421422423424425426227 unmodified lines65465565665765865966040 unmodified lines701702703704705706707708709710341 unmodified lines105210531054105510561057105815 unmodified linesimport timefrom pathlib import Pathfrom tts import split_into_chunks, generate_audio_stream, pregenerate_story_audiofrom inference import transcribe_audio, answer_story_questionfrom inference_lfm import answer_question_audio, SAMPLE_RATE as LFM_SRfrom voice_clone import load_default_profile, list_saved_profiles394 unmodified linesget_custom_voice_model()print("[MomsVoice] TTS model ready.")print("[MomsVoice] Preloading LFM2.5-Audio-1.5B Q&A model...")from inference_lfm import get_lfm_modelget_lfm_model()print("[MomsVoice] LFM Q&A model ready. All models preloaded.")# Gradio Application Core setup227 unmodified lines<div style="font-size: 11.5px; color: #1c1c19; line-height: 2;">🎙️ <strong>Voice Cloning:</strong> Qwen3-TTS-1.7B-Base (bfloat16)<br>🗣️ <strong>Stock TTS:</strong> Qwen3-TTS-0.6B-CustomVoice<br>🧠 <strong>Q&A (end-to-end):</strong> LFM2.5-Audio-1.5B (LiquidAI)</div></div>""")40 unmodified linesparas = load_paragraphs(selected["story_path"])total = max(len(paras) - 1, 0)tts_chunks = split_into_chunks("\n\n".join(paras))# Pre-generate all audio in background for instant playback (#1 + #11)pregenerate_story_audio(tts_chunks, voice_profile_id=profile_id)chunk_html = f"""<div style="margin-top: 8px; font-size: 10px; color: #64748b; font-family: monospace; text-align: center;">{len(tts_chunks)} chunks ready — tap Play</div>"""status_html = """<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">341 unmodified linesquestion_audio_path=question_audio_path if has_audio else None,question_text=q_txt if q_txt and not has_audio else None,story_context=story_context,max_new_tokens=100,)if not answer_text:answer_text = "Hmm, I'm not sure about that! Let's keep listening to find out."
24 unmodified lines25262728293031323334353637383930 unmodified lines70717273747576777879808124 unmodified lineslogger.info("Loading %s...", HF_REPO)_processor = LFM2AudioProcessor.from_pretrained(HF_REPO).eval()# Enable FlashAttention-2 if available, else SDPAmodel_kwargs = {}try:import flash_attn # noqa: F401model_kwargs["attn_implementation"] = "flash_attention_2"logger.info("Using FlashAttention-2 for LFM.")except ImportError:model_kwargs["attn_implementation"] = "sdpa"_model = LFM2AudioModel.from_pretrained(HF_REPO, **model_kwargs).eval()logger.info("LFM2.5-Audio loaded.")return _processor, _model30 unmodified lines# User turn — audio or textchat.new_turn("user")if question_audio_path:import torchaudiowav, sr = torchaudio.load(question_audio_path)# Resample to 16kHz if needed (model expects 16kHz input)if sr != 16000:wav = torchaudio.functional.resample(wav, sr, 16000)sr = 16000chat.add_audio(wav, sr)elif question_text:chat.add_text(question_text)24 unmodified lines2526272829303130 unmodified lines6263646566676869707124 unmodified lineslogger.info("Loading %s...", HF_REPO)_processor = LFM2AudioProcessor.from_pretrained(HF_REPO).eval()_model = LFM2AudioModel.from_pretrained(HF_REPO).eval()logger.info("LFM2.5-Audio loaded.")return _processor, _model30 unmodified lines# User turn — audio or textchat.new_turn("user")if question_audio_path:import librosawav_np, sr = librosa.load(question_audio_path, sr=16000, mono=True)wav = torch.from_numpy(wav_np).unsqueeze(0) # (1, samples)sr = 16000chat.add_audio(wav, sr)elif question_text:chat.add_text(question_text)
5 unmodified lines67891011125 unmodified linessoundfilenumpylibrosatorchaudio# LFM2.5-Audio end-to-end modelliquid-audio5 unmodified lines678910115 unmodified linessoundfilenumpylibrosa# LFM2.5-Audio end-to-end modelliquid-audio
4 unmodified lines567891011121314151617181920214 unmodified lines26272829303128 unmodified lines60616263646566676869707172737475767778798081828384854 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411510 unmodified lines12612712812913013127 unmodified lines1591601611621631644 unmodified lines- Qwen3-TTS Base (1.7B): voice-cloned synthesis using a cached voice profile- Qwen3-TTS CustomVoice (0.6B): fast predefined speakers (default stock voice)Usage:chunks = split_into_chunks(text)for sr, wav, i, n, err in generate_audio_stream(chunks, voice_profile_id="abc123"):..."""import loggingimport queueimport reimport threadingimport numpy as nplogger = logging.getLogger(__name__)4 unmodified lines# Target chunk length — shorter chunks = lower latency per chunk_MAX_CHUNK_CHARS = 120def split_into_chunks(text: str) -> list[str]:"""Split text into short chunks suitable for low-latency TTS streaming.28 unmodified linesreturn [c for c in chunks if c]def generate_audio_stream(chunks: list[str],voice_profile_id: str | None = None,custom_voice_speaker: str = "vivian",):"""Generator: synthesizes chunks in a background thread with pre-buffering.Batches small chunks into ~5s audio blocks for smoother playback.Yields (sample_rate, wav_array, chunk_idx, total_chunks, error_msg).Backend selection:1. voice_profile_id provided → Qwen3-TTS Base (1.7B) with cloned voice2. Otherwise → Qwen3-TTS CustomVoice (0.6B) with predefined speaker"""n = len(chunks)# Pre-buffer up to 4 chunks ahead for smoother playbackchunk_q: queue.Queue = queue.Queue(maxsize=4)sample_rate = 24000# Target ~5 seconds of audio per yielded block (24000 Hz * 5s = 120000 samples)_TARGET_SAMPLES = 24000 * 5if voice_profile_id:_start_qwen_worker(chunks, voice_profile_id, chunk_q)4 unmodified linesaudio_buffer = []buffer_samples = 0last_idx = 0while True:item = chunk_q.get()if item is _SENTINEL:# Flush remaining bufferif audio_buffer:combined = np.concatenate(audio_buffer)yield sample_rate, combined, last_idx, n, Nonebreaki, wav, err = itemif err:# Flush buffer before errorif audio_buffer:combined = np.concatenate(audio_buffer)yield sample_rate, combined, last_idx, n, Noneyield sample_rate, wav, i, n, errbreaklast_idx = iaudio_buffer.append(wav)buffer_samples += len(wav)# Yield when buffer reaches target size or this is the first chunk (fast start)if buffer_samples >= _TARGET_SAMPLES or (i == 0 and buffer_samples > 0):10 unmodified linesfrom voice_clone import synthesize_cloned, synthesize_custom_voiceuse_fallback = Falsefor i, stmt in enumerate(chunks):try:if use_fallback:wav, _sr = synthesize_custom_voice(stmt)27 unmodified linesfrom voice_clone import synthesize_custom_voice_streamingimport numpy as npfor i, stmt in enumerate(chunks):try:segments = []for seg, _sr in synthesize_custom_voice_streaming(stmt, speaker=speaker):4 unmodified lines567891011121314151617181920212223242526272829304 unmodified lines353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838428 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082094 unmodified lines21421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824910 unmodified lines26026126226326426526626726826927027 unmodified lines2982993003013023033043053063073084 unmodified lines- Qwen3-TTS Base (1.7B): voice-cloned synthesis using a cached voice profile- Qwen3-TTS CustomVoice (0.6B): fast predefined speakers (default stock voice)Features:- Audio cache: avoids re-synthesis for repeated text+voice combos- Pre-generation: background-generates entire story on book select- Transition chime: soft audio between paragraphs to mask gaps- Eager pre-buffering: generates next chunks while current playsUsage:chunks = split_into_chunks(text)for sr, wav, i, n, err in generate_audio_stream(chunks, voice_profile_id="abc123"):..."""import hashlibimport loggingimport osimport queueimport reimport threadingimport numpy as npimport soundfile as sflogger = logging.getLogger(__name__)4 unmodified lines# Target chunk length — shorter chunks = lower latency per chunk_MAX_CHUNK_CHARS = 120# Audio cache directory_CACHE_DIR = "audio_cache"os.makedirs(_CACHE_DIR, exist_ok=True)# Transition chime (soft sine fade, 0.3s at 24kHz)_CHIME_SR = 24000_CHIME_DURATION = 0.3_chime_t = np.linspace(0, _CHIME_DURATION, int(_CHIME_SR * _CHIME_DURATION), dtype=np.float32)_TRANSITION_CHIME = 0.08 * np.sin(2 * np.pi * 440 * _chime_t) * np.linspace(1, 0, len(_chime_t))# Background pre-generation state_pregen_lock = threading.Lock()_pregen_cache: dict[str, list[tuple[int, np.ndarray]]] = {} # key -> [(sr, wav), ...]_pregen_in_progress: set[str] = set()def _cache_key(text: str, voice_profile_id: str | None) -> str:"""Generate a cache key from text + voice profile."""raw = f"{voice_profile_id or 'stock'}:{text}"return hashlib.md5(raw.encode()).hexdigest()def _get_cached_audio(chunk_text: str, voice_profile_id: str | None) -> np.ndarray | None:"""Check if audio for this chunk is already cached on disk."""key = _cache_key(chunk_text, voice_profile_id)path = os.path.join(_CACHE_DIR, f"{key}.wav")if os.path.exists(path):try:wav, sr = sf.read(path, dtype='float32')return wavexcept Exception:passreturn Nonedef _save_cached_audio(chunk_text: str, voice_profile_id: str | None, wav: np.ndarray, sr: int):"""Save synthesized audio to disk cache."""key = _cache_key(chunk_text, voice_profile_id)path = os.path.join(_CACHE_DIR, f"{key}.wav")try:sf.write(path, wav, sr)except Exception:passdef split_into_chunks(text: str) -> list[str]:"""Split text into short chunks suitable for low-latency TTS streaming.28 unmodified linesreturn [c for c in chunks if c]def pregenerate_story_audio(chunks: list[str], voice_profile_id: str | None = None):"""Pre-generate all story audio in background. Results cached for instant playback.Call this on book selection to pre-warm the cache. Non-blocking."""story_key = _cache_key("\n".join(chunks), voice_profile_id)with _pregen_lock:if story_key in _pregen_in_progress or story_key in _pregen_cache:return # Already running or done_pregen_in_progress.add(story_key)def _worker():results = []sr = 24000for i, chunk in enumerate(chunks):# Check disk cache firstcached = _get_cached_audio(chunk, voice_profile_id)if cached is not None:results.append((sr, cached))continue# Synthesizetry:wav, sample_rate = _synthesize_single(chunk, voice_profile_id)sr = sample_rateresults.append((sr, wav))_save_cached_audio(chunk, voice_profile_id, wav, sr)except Exception as e:logger.warning("Pre-gen failed on chunk %d: %s", i, e)results.append((sr, np.zeros(0, dtype=np.float32)))with _pregen_lock:_pregen_cache[story_key] = results_pregen_in_progress.discard(story_key)logger.info("Pre-generation complete: %d chunks cached.", len(chunks))threading.Thread(target=_worker, daemon=True).start()def _synthesize_single(text: str, voice_profile_id: str | None) -> tuple[np.ndarray, int]:"""Synthesize a single chunk, choosing backend based on profile."""if voice_profile_id:from voice_clone import synthesize_cloned, synthesize_custom_voicetry:wav, sr = synthesize_cloned(text, voice_profile_id)return wav, srexcept Exception:wav, sr = synthesize_custom_voice(text)return wav, srelse:from voice_clone import synthesize_custom_voicewav, sr = synthesize_custom_voice(text)return wav, srdef generate_audio_stream(chunks: list[str],voice_profile_id: str | None = None,custom_voice_speaker: str = "vivian",add_transitions: bool = True,):"""Generator: synthesizes chunks with caching + pre-buffering + transitions.If pre-generated audio is available (from pregenerate_story_audio), servesinstantly from cache. Otherwise synthesizes on-demand with background pre-buffer.Yields (sample_rate, wav_array, chunk_idx, total_chunks, error_msg)."""n = len(chunks)sample_rate = 24000# Check if pre-generated cache is availablestory_key = _cache_key("\n".join(chunks), voice_profile_id)pregen_results = Nonewith _pregen_lock:if story_key in _pregen_cache:pregen_results = _pregen_cache[story_key]if pregen_results and len(pregen_results) == n:# Serve from pre-generated cache — near-zero latencyfor i, (sr, wav) in enumerate(pregen_results):if wav is not None and len(wav) > 0:if add_transitions and i > 0:# Prepend transition chimewav = np.concatenate([_TRANSITION_CHIME, wav])yield sr, wav, i, n, Nonereturn# Fallback: on-demand synthesis with pre-buffering (4 chunks ahead)chunk_q: queue.Queue = queue.Queue(maxsize=4)if voice_profile_id:_start_qwen_worker(chunks, voice_profile_id, chunk_q)4 unmodified linesaudio_buffer = []buffer_samples = 0last_idx = 0_TARGET_SAMPLES = 24000 * 5 # ~5s blockschunk_count = 0while True:item = chunk_q.get()if item is _SENTINEL:if audio_buffer:combined = np.concatenate(audio_buffer)yield sample_rate, combined, last_idx, n, Nonebreaki, wav, err = itemif err:if audio_buffer:combined = np.concatenate(audio_buffer)yield sample_rate, combined, last_idx, n, Noneyield sample_rate, wav, i, n, errbreaklast_idx = i# Add transition chime between chunks (not before first)if add_transitions and chunk_count > 0:audio_buffer.append(_TRANSITION_CHIME)buffer_samples += len(_TRANSITION_CHIME)audio_buffer.append(wav)buffer_samples += len(wav)chunk_count += 1# Cache this chunk for future replays_save_cached_audio(chunks[i], voice_profile_id, wav, sample_rate)# Yield when buffer reaches target size or this is the first chunk (fast start)if buffer_samples >= _TARGET_SAMPLES or (i == 0 and buffer_samples > 0):10 unmodified linesfrom voice_clone import synthesize_cloned, synthesize_custom_voiceuse_fallback = Falsefor i, stmt in enumerate(chunks):# Check cache firstcached = _get_cached_audio(stmt, profile_id)if cached is not None:chunk_q.put((i, cached, None))continuetry:if use_fallback:wav, _sr = synthesize_custom_voice(stmt)27 unmodified linesfrom voice_clone import synthesize_custom_voice_streamingimport numpy as npfor i, stmt in enumerate(chunks):# Check cache firstcached = _get_cached_audio(stmt, None)if cached is not None:chunk_q.put((i, cached, None))continuetry:segments = []for seg, _sr in synthesize_custom_voice_streaming(stmt, speaker=speaker):
app.py+11-12
inference_lfm.py+5-15
requirements_lfm.txt-1
tts.py+156-12