videogen/tests/reelforge/test_voice_emotion.py
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

229 lines
8.5 KiB
Python

"""Voice emotion/delivery presets (Arcads "full emotion control" / InVideo
"emotional inflections" parity).
Covers the shared catalog (``app.services.tts.emotion``) and its three
ElevenLabs call sites:
* ``app.services.voice.elevenlabs_tts`` — the plain (no-timestamps) adapter.
* ``app.services.tts.elevenlabs_timestamps.elevenlabs_tts_with_timestamps`` —
the default, word-timing-carrying adapter the main ReelForge pipeline uses.
* ``app.domains.routing.providers.voice_gen.ElevenLabsVoiceAdapter`` — the
media-gateway/catalog adapter used by avatars and standalone voice jobs.
No network: ``requests.post`` is monkeypatched everywhere.
"""
from __future__ import annotations
import base64
from types import SimpleNamespace
import pytest
from app.services import voice
from app.services.tts import elevenlabs_timestamps, emotion
_NEUTRAL = {
"stability": 0.5,
"similarity_boost": 0.75,
"style": 0.0,
"use_speaker_boost": True,
}
# --------------------------------------------------------------------------- #
# Pure catalog
# --------------------------------------------------------------------------- #
def test_neutral_matches_the_legacy_hardcoded_values():
"""`neutral` must reproduce exactly what every call site hardcoded before
this module existed, so a caller that sends no emotion gets byte-identical
behaviour to before this feature shipped."""
assert emotion.resolve_voice_settings("") == _NEUTRAL
assert emotion.resolve_voice_settings(None) == _NEUTRAL
assert emotion.resolve_voice_settings("neutral") == _NEUTRAL
@pytest.mark.parametrize("value", ["EXCITED", " calm ", "Urgent", "Persuasive"])
def test_normalize_emotion_is_case_and_whitespace_insensitive(value):
assert emotion.normalize_emotion(value) == value.strip().lower()
@pytest.mark.parametrize("value", [None, "", " ", "not-a-real-emotion", 42, object()])
def test_normalize_emotion_never_raises_and_falls_back_to_neutral(value):
assert emotion.normalize_emotion(value) == emotion.DEFAULT_EMOTION
def test_every_named_preset_is_a_valid_elevenlabs_voice_settings_shape():
assert len(emotion.EMOTIONS) >= 5 # a real catalog, not a token gesture
for name in emotion.EMOTIONS:
settings = emotion.resolve_voice_settings(name)
assert set(settings) == {"stability", "similarity_boost", "style", "use_speaker_boost"}
assert 0.0 <= settings["stability"] <= 1.0
assert 0.0 <= settings["similarity_boost"] <= 1.0
assert 0.0 <= settings["style"] <= 1.0
assert settings["use_speaker_boost"] is True
def test_non_neutral_presets_are_distinct_from_neutral():
for name in emotion.EMOTIONS:
if name == "neutral":
continue
assert emotion.resolve_voice_settings(name) != _NEUTRAL
def test_resolve_voice_settings_returns_independent_copies():
a = emotion.resolve_voice_settings("excited")
a["stability"] = -1.0
assert emotion.resolve_voice_settings("excited")["stability"] != -1.0
# --------------------------------------------------------------------------- #
# app.services.voice.elevenlabs_tts
# --------------------------------------------------------------------------- #
class _FakeResponse:
def __init__(self, *, status_code=200, content=b"", payload=None):
self.status_code = status_code
self.content = content
self._payload = payload or {}
self.text = ""
def json(self):
return self._payload
def test_elevenlabs_tts_sends_the_resolved_voice_settings(monkeypatch, tmp_path):
monkeypatch.setitem(voice.config.elevenlabs, "api_key", "test-key")
captured = {}
def fake_post(url, json=None, headers=None, timeout=None):
captured["json"] = json
return _FakeResponse(status_code=200, content=b"fake-mp3-bytes")
monkeypatch.setattr(voice.requests, "post", fake_post)
monkeypatch.setattr(
voice,
"AudioFileClip",
lambda path: SimpleNamespace(duration=1.23, close=lambda: None),
)
out_file = str(tmp_path / "out.mp3")
result = voice.elevenlabs_tts(
"hello world", "voice123", out_file, voice_emotion="excited"
)
assert result is not None
assert captured["json"]["voice_settings"] == emotion.resolve_voice_settings("excited")
def test_elevenlabs_tts_defaults_to_neutral_when_no_emotion_given(monkeypatch, tmp_path):
monkeypatch.setitem(voice.config.elevenlabs, "api_key", "test-key")
captured = {}
def fake_post(url, json=None, headers=None, timeout=None):
captured["json"] = json
return _FakeResponse(status_code=200, content=b"fake-mp3-bytes")
monkeypatch.setattr(voice.requests, "post", fake_post)
monkeypatch.setattr(
voice,
"AudioFileClip",
lambda path: SimpleNamespace(duration=1.0, close=lambda: None),
)
out_file = str(tmp_path / "out.mp3")
voice.elevenlabs_tts("hello", "voice123", out_file)
assert captured["json"]["voice_settings"] == _NEUTRAL
# --------------------------------------------------------------------------- #
# app.services.tts.elevenlabs_timestamps.elevenlabs_tts_with_timestamps
# --------------------------------------------------------------------------- #
def _alignment_payload(text: str) -> dict:
n = len(text)
return {
"audio_base64": base64.b64encode(b"fake-mp3-bytes").decode(),
"alignment": {
"characters": list(text),
"character_start_times_seconds": [i * 0.1 for i in range(n)],
"character_end_times_seconds": [(i + 1) * 0.1 for i in range(n)],
},
}
def test_elevenlabs_timestamps_sends_the_resolved_voice_settings(monkeypatch, tmp_path):
monkeypatch.setitem(elevenlabs_timestamps.config.elevenlabs, "api_key", "test-key")
captured = {}
def fake_post(url, json=None, headers=None, params=None, timeout=None):
captured["json"] = json
return _FakeResponse(status_code=200, payload=_alignment_payload("hi"))
monkeypatch.setattr(elevenlabs_timestamps.requests, "post", fake_post)
out_file = str(tmp_path / "out.mp3")
result = elevenlabs_timestamps.elevenlabs_tts_with_timestamps(
"hi", "voice123", out_file, voice_emotion="dramatic"
)
assert result is not None
assert captured["json"]["voice_settings"] == emotion.resolve_voice_settings("dramatic")
def test_elevenlabs_timestamps_unknown_emotion_falls_back_to_neutral(monkeypatch, tmp_path):
monkeypatch.setitem(elevenlabs_timestamps.config.elevenlabs, "api_key", "test-key")
captured = {}
def fake_post(url, json=None, headers=None, params=None, timeout=None):
captured["json"] = json
return _FakeResponse(status_code=200, payload=_alignment_payload("hi"))
monkeypatch.setattr(elevenlabs_timestamps.requests, "post", fake_post)
out_file = str(tmp_path / "out.mp3")
elevenlabs_timestamps.elevenlabs_tts_with_timestamps(
"hi", "voice123", out_file, voice_emotion="not-a-real-emotion"
)
assert captured["json"]["voice_settings"] == _NEUTRAL
# --------------------------------------------------------------------------- #
# app.domains.routing.providers.voice_gen.ElevenLabsVoiceAdapter
# --------------------------------------------------------------------------- #
def test_gateway_elevenlabs_adapter_sends_the_resolved_voice_settings():
from app.domains.routing.providers.voice_gen import ElevenLabsVoiceAdapter
captured = {}
class _FakeSession:
def request(self, method, url, headers=None, json=None, timeout=None):
captured["json"] = json
return SimpleNamespace(status_code=200, content=b"ok", headers={})
adapter = ElevenLabsVoiceAdapter(
api_key="test-key", session=_FakeSession(), host_fn=lambda data: "https://r2/clip.mp3"
)
clip = adapter.submit(prompt="hello", voice_id="voice123", emotion="persuasive")
assert clip.output_url == "https://r2/clip.mp3"
assert captured["json"]["voice_settings"] == emotion.resolve_voice_settings("persuasive")
def test_gateway_elevenlabs_adapter_defaults_to_neutral():
from app.domains.routing.providers.voice_gen import ElevenLabsVoiceAdapter
captured = {}
class _FakeSession:
def request(self, method, url, headers=None, json=None, timeout=None):
captured["json"] = json
return SimpleNamespace(status_code=200, content=b"ok", headers={})
adapter = ElevenLabsVoiceAdapter(
api_key="test-key", session=_FakeSession(), host_fn=lambda data: "https://r2/clip.mp3"
)
adapter.submit(prompt="hello", voice_id="voice123")
assert captured["json"]["voice_settings"] == _NEUTRAL