feat(video_lesson): narrate with the Settings TTS provider

Video Lesson narration only ever used edge-tts, whatever TTS provider the
user configured. When the Settings provider is not Edge, speak each
sentence through synthesize_speech (so every catalog provider works:
OpenAI, a local OpenAI-compatible Kokoro/Piper server, MiniMax, ...),
decode it to PCM with ffmpeg for exact per-sentence caption offsets, join
the sentences with a short pause and encode the mp3 the player expects.
Any failure falls back to Edge for that line, then to silent captions.
Needs ffmpeg on PATH; without it the Settings path is skipped.
This commit is contained in:
Amar Tinawi
2026-10-30 15:29:17 +04:00
parent 645a54c621
commit 32372c7916
2 changed files with 134 additions and 4 deletions

View File

@@ -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,78 @@ 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
out, err = await proc.communicate(data)
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
pcm = bytearray()
captions: list[tuple[int, str]] = []
for sentence in (s.strip() for s in _SENTENCE_END.split(text)):
if not sentence:
continue
audio, _ = await synthesize_speech(sentence, strip_markdown=False)
decoded = await _ffmpeg(
["-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 +172,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 +214,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",
]

View File

@@ -54,3 +54,37 @@ 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