diff --git a/deeptutor/agents/video_lesson/narration.py b/deeptutor/agents/video_lesson/narration.py index 195d7cc67..c90d24086 100644 --- a/deeptutor/agents/video_lesson/narration.py +++ b/deeptutor/agents/video_lesson/narration.py @@ -1,7 +1,9 @@ """Voice-over for video lessons: speak each scene's narration and time its captions. -Speech comes from edge-tts (the free read-aloud voices behind Microsoft Edge; no API -key). When the package is missing or the service fails, a scene keeps its captions, +Speech comes from the text-to-speech provider chosen in Settings when it is not Edge +(any provider ``synthesize_speech`` supports, e.g. OpenAI, a local OpenAI-compatible +Kokoro or Piper server, MiniMax), and otherwise from edge-tts (the free read-aloud +voices behind Microsoft Edge; no API key). When both fail, a scene keeps its captions, timed from an estimated speaking rate, and plays silently. """ @@ -15,6 +17,7 @@ import json import logging import math import re +import shutil logger = logging.getLogger(__name__) @@ -25,6 +28,9 @@ _CHARS_PER_SECOND = {"zh": 4.2, "en": 15.0} _MP3_BYTES_PER_SECOND = 48_000 / 8 # edge-tts streams 24 kHz, 48 kbit/s mono mp3 _TICKS_PER_SECOND = 10_000_000 # edge-tts boundary offsets are in 100 ns units _PARALLEL = 4 +_PCM_RATE = 24_000 +_PCM_BYTES_PER_SECOND = _PCM_RATE * 2 # 16-bit mono +_SENTENCE_GAP = bytes(int(_PCM_BYTES_PER_SECOND * 0.15) // 2 * 2) # 0.15 s of silence _SENTENCE_END = re.compile(r"(?<=[。!?;!?])|(?<=[.;])\s+") @@ -87,6 +93,102 @@ def _configured_voice(language: str) -> str | None: return voice if voice.lower().startswith(_lang(language)) else None +def _settings_provider() -> str | None: + """The Settings TTS provider when it is configured and is not Edge (``speak`` covers Edge).""" + if not shutil.which("ffmpeg"): + return None + try: + from deeptutor.services.config.provider_runtime import resolve_tts_runtime_config + + provider = getattr(resolve_tts_runtime_config(), "provider_name", "") or "" + except Exception: + return None + return provider if provider and provider != "edge" else None + + +async def _ffmpeg(args: list[str], data: bytes) -> bytes: + proc = await asyncio.create_subprocess_exec( + "ffmpeg", + "-v", + "error", + *args, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) # nosec B603 - fixed argv + try: + out, err = await asyncio.wait_for(proc.communicate(data), timeout=60) + except (TimeoutError, asyncio.CancelledError): + if proc.returncode is None: + proc.kill() + await proc.wait() + raise + if proc.returncode != 0 or not out: + raise RuntimeError(f"ffmpeg failed: {err.decode(errors='ignore')[:200]}") + return out + + +async def speak_with_settings(text: str) -> Clip: + """Speak ``text`` with the Settings TTS provider, one request per sentence. + + Providers return different containers (mp3, wav, opus, pcm...) and few report word or + sentence timings, so each sentence is decoded to PCM: its length is the exact + caption offset, and the joined clip is re-encoded as the mp3 the player expects. + """ + from deeptutor.services.voice import synthesize_speech + from deeptutor.services.voice.audio import _parse_pcm_content_type + + pcm = bytearray() + captions: list[tuple[int, str]] = [] + for sentence in (s.strip() for s in _SENTENCE_END.split(text)): + if not sentence: + continue + audio, content_type = await synthesize_speech(sentence, strip_markdown=False) + pcm_format = _parse_pcm_content_type(content_type) + input_args = [] + if pcm_format is not None: + rate, channels = pcm_format + input_args = ["-f", "s16le", "-ar", str(rate), "-ac", str(channels)] + decoded = await _ffmpeg( + [ + *input_args, + "-i", + "pipe:0", + "-f", + "s16le", + "-ar", + str(_PCM_RATE), + "-ac", + "1", + "pipe:1", + ], + audio, + ) + captions.append((round(len(pcm) / _PCM_BYTES_PER_SECOND * FPS), sentence)) + pcm += decoded + _SENTENCE_GAP + if not captions: + raise RuntimeError("the TTS provider returned no audio") + mp3 = await _ffmpeg( + [ + "-f", + "s16le", + "-ar", + str(_PCM_RATE), + "-ac", + "1", + "-i", + "pipe:0", + "-b:a", + "64k", + "-f", + "mp3", + "pipe:1", + ], + bytes(pcm), + ) + return Clip(text, math.ceil(len(pcm) / _PCM_BYTES_PER_SECOND * FPS), captions, mp3) + + async def narrate( lines: list[NarrationLine], language: str, cache: dict[str, Clip] | None = None ) -> dict[str, Clip]: @@ -94,12 +196,21 @@ async def narrate( cache = {} if cache is None else cache voiced = importlib.util.find_spec("edge_tts") is not None voice = _configured_voice(language) or VOICES[_lang(language)] + provider = _settings_provider() gate = asyncio.Semaphore(_PARALLEL) async def one(text: str) -> Clip: if text not in cache: clip = None - if voiced: + if provider: + async with gate: + try: + clip = await asyncio.wait_for( + speak_with_settings(text), SPEAK_TIMEOUT_S * 2 + ) + except Exception as exc: # fall back to Edge for this line + logger.warning("video lesson narration via %s failed: %s", provider, exc) + if clip is None and voiced: async with gate: try: clip = await asyncio.wait_for(speak(text, voice), SPEAK_TIMEOUT_S) @@ -127,4 +238,13 @@ def voice_module(clips: dict[str, Clip]) -> str: return "export const VOICE = " + json.dumps(data, ensure_ascii=False) + ";\n" -__all__ = ["Clip", "NarrationLine", "VOICES", "estimate", "narrate", "speak", "voice_module"] +__all__ = [ + "Clip", + "NarrationLine", + "VOICES", + "estimate", + "narrate", + "speak", + "speak_with_settings", + "voice_module", +] diff --git a/tests/agents/video_lesson/test_narration.py b/tests/agents/video_lesson/test_narration.py index 4d7015828..82551354c 100644 --- a/tests/agents/video_lesson/test_narration.py +++ b/tests/agents/video_lesson/test_narration.py @@ -54,3 +54,90 @@ def test_settings_edge_voice_is_used_for_its_language(monkeypatch) -> None: def test_non_edge_tts_settings_keep_the_default_voice(monkeypatch) -> None: _tts(monkeypatch, provider_name="openai", voice="alloy") assert narration._configured_voice("en") is None + + +def test_settings_tts_provider_is_used_before_edge(monkeypatch) -> None: + async def settings(text: str) -> Clip: + return Clip(text, 30, [(0, text)], b"SETTINGS") + + async def edge(text: str, voice: str) -> Clip: + raise AssertionError("Edge must not be called when the Settings provider works") + + monkeypatch.setattr(narration, "_settings_provider", lambda: "openai") + monkeypatch.setattr(narration, "speak_with_settings", settings) + monkeypatch.setattr(narration, "speak", edge) + clips = asyncio.run(narration.narrate([NarrationLine("s1", "One line.")], "en")) + assert clips["s1"].audio == b"SETTINGS" + + +def test_settings_tts_failure_falls_back_to_edge(monkeypatch) -> None: + async def settings(text: str) -> Clip: + raise RuntimeError("provider down") + + async def edge(text: str, voice: str) -> Clip: + return Clip(text, 30, [(0, text)], b"EDGE") + + monkeypatch.setattr(narration, "_settings_provider", lambda: "openai") + monkeypatch.setattr(narration, "speak_with_settings", settings) + monkeypatch.setattr(narration, "speak", edge) + monkeypatch.setattr(narration.importlib.util, "find_spec", lambda name: object()) + clips = asyncio.run(narration.narrate([NarrationLine("s1", "One line.")], "en")) + assert clips["s1"].audio == b"EDGE" + + +def test_edge_settings_leave_narration_to_edge(monkeypatch) -> None: + _tts(monkeypatch, provider_name="edge", voice="en-US-AvaNeural") + assert narration._settings_provider() is None + + +def test_settings_pcm_preserves_input_rate_and_channels(monkeypatch): + from deeptutor.agents.video_lesson import narration + + calls = [] + + async def synthesize(*args, **kwargs): + return b"\0" * 3200, "audio/pcm;rate=16000;channels=2" + + async def convert(args, data): + calls.append(args) + return b"\0" * 4800 + + monkeypatch.setattr("deeptutor.services.voice.synthesize_speech", synthesize) + monkeypatch.setattr(narration, "_ffmpeg", convert) + asyncio.run(narration.speak_with_settings("Hello")) + assert calls[0][:8] == ["-f", "s16le", "-ar", "16000", "-ac", "2", "-i", "pipe:0"] + + +def test_ffmpeg_is_killed_and_reaped_when_cancelled(monkeypatch): + from deeptutor.agents.video_lesson import narration + + class Process: + returncode = None + killed = waited = False + + async def communicate(self, data): + raise asyncio.CancelledError + + def kill(self): + self.killed = True + + async def wait(self): + self.waited = True + + proc = Process() + + async def create(*args, **kwargs): + return proc + + monkeypatch.setattr(asyncio, "create_subprocess_exec", create) + + async def check(): + try: + await narration._ffmpeg([], b"audio") + except asyncio.CancelledError: + pass + else: + raise AssertionError("cancellation was swallowed") + + asyncio.run(check()) + assert proc.killed and proc.waited