"""Funções que o CenaForge acrescentou ao serviço herdado do dropsz_voice. Vozes Edge (sem arquivo local), vozes de personagem do usuário (voz base + RVC), saída WAV para o render, transcrição com tempos (legenda) e recarga do catálogo pelo painel. """ import hashlib import json import os from dataclasses import replace from pathlib import Path import numpy as np import pytest from app.catalog import load_catalog from app.engine import edge_rate from tests.conftest import HEADERS, body pytestmark = pytest.mark.anyio ONE_SECOND = b"OggS" + b"x" * 100 def stt_headers(detail: str, key: str = "ep01:legenda") -> dict: return { **HEADERS, "Content-Type": "audio/ogg", "X-Idempotency-Key": key, "X-Audio-Duration-Ms": "1000", "X-Language": "pt-BR", "X-Detail": detail, } def add_edge_voice(settings) -> None: catalog = json.loads(settings.catalog_path.read_text()) catalog["voices"].append({ "id": "pt-br-francisca", "name": "Francisca", "language": "pt-BR", "engine": "edge", "edgeVoice": "pt-BR-FranciscaNeural", "sampleRate": 24000, "source": "edge", "license": "edge", "gender": "female", }) settings.catalog_path.write_text(json.dumps(catalog)) def add_user_voice(settings, tmp_path: Path, model_sha: str | None = None) -> Path: folder = settings.models_dir / "rvc" / "heroi" folder.mkdir(parents=True, exist_ok=True) (folder / "heroi.pth").write_bytes(b"pesos-rvc") (folder / "heroi.index").write_bytes(b"indice") user = tmp_path / "user-voices.json" user.write_text(json.dumps({"voices": [{ "id": "heroi", "name": "Herói", "baseVoice": "pt-br-test", "rvc": { "model": "rvc/heroi/heroi.pth", "modelSha256": model_sha or hashlib.sha256(b"pesos-rvc").hexdigest(), "index": "rvc/heroi/heroi.index", "indexSha256": hashlib.sha256(b"indice").hexdigest(), "pitch": 2, }, }]})) return user def test_edge_rate(): assert edge_rate(1.0) == "+0%" assert edge_rate(1.25) == "+25%" assert edge_rate(0.8) == "-20%" def test_edge_voice_needs_no_local_file(settings): add_edge_voice(settings) voices = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir) edge = voices["pt-br-francisca"] assert edge.engine == "edge" and edge.model is None and edge.edge_voice == "pt-BR-FranciscaNeural" # Revisão estável: a mesma voz Edge sempre cai na mesma chave de cache. again = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir) assert again["pt-br-francisca"].revision == edge.revision def test_user_voice_is_verified_and_bad_one_is_skipped(settings, tmp_path, caplog): user = add_user_voice(settings, tmp_path) voices = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir, True, user) heroi = voices["heroi"] assert heroi.user and heroi.base_voice == "pt-br-test" and heroi.rvc["pitch"] == 2 assert heroi.rvc["modelPath"].name == "heroi.pth" and not heroi.default user = add_user_voice(settings, tmp_path, model_sha="0" * 64) voices = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir, True, user) assert "heroi" not in voices and "pt-br-test" in voices # a voz quebrada não derruba as outras assert "voz do usuário ignorada" in caplog.text async def test_user_voice_descriptor_and_rvc_disabled(make_client, settings, tmp_path): user = add_user_voice(settings, tmp_path) async with make_client(user_catalog_path=user) as client: described = (await client.get("/v1/voices/heroi", headers=HEADERS)).json() response = await client.post("/v1/synthesize", json=body(voiceId="heroi"), headers=HEADERS) assert described["engine"] == "tts+rvc" and described["user"] is True and described["baseVoice"] == "pt-br-test" assert described["rvc"] == {"pitch": 2, "f0Method": "rmvpe", "indexRate": 0.5, "protect": 0.33, "hasIndex": True} assert "heroi.pth" not in json.dumps(described) # nunca o caminho do arquivo assert response.status_code == 501 and response.json()["error"]["code"] == "rvc_disabled" async def test_wav_output_for_render(make_client): async with make_client() as client: wav = await client.post("/v1/synthesize", json=body(params={"format": "wav"}), headers=HEADERS) ogg = await client.post("/v1/synthesize", json=body("req-00000002"), headers=HEADERS) assert wav.status_code == 200 and wav.headers["content-type"] == "audio/wav" assert wav.content[:4] == b"RIFF" assert ogg.content[:4] == b"OggS" @pytest.mark.parametrize("detail", ["segments", "words"]) async def test_transcribe_with_timestamps(make_client, stt_engine, detail): async with make_client() as client: response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers(detail)) data = response.json() assert response.status_code == 200 and data["durationS"] == pytest.approx(1.0) [segment] = data["segments"] assert segment["text"] == "valeu pela live" and segment["start"] == 0.0 if detail == "words": assert [w["text"] for w in segment["words"]] == ["valeu", "pela", "live"] assert segment["words"][-1]["end"] == pytest.approx(1.0) else: assert "words" not in segment assert stt_engine.details == [detail] async def test_detail_changes_the_job(make_client, stt_engine): # Mesma idempotencyKey com outro detalhe = outro conteúdo: conflito, não resposta errada do cache. async with make_client() as client: await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers("text")) response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers("words")) assert response.status_code == 409 async def test_reload_picks_up_new_user_voice(make_client, settings, tmp_path): user = tmp_path / "user-voices.json" async with make_client(user_catalog_path=user) as client: assert (await client.get("/v1/voices/heroi", headers=HEADERS)).status_code == 404 add_user_voice(settings, tmp_path) reloaded = await client.post("/v1/voices/reload", headers=HEADERS) assert reloaded.json() == {"status": "ok", "count": 2} assert (await client.get("/v1/voices/heroi", headers=HEADERS)).status_code == 200 def _add_catalog_voice(settings, voice_id: str, model: str = "piper/fake.onnx") -> None: catalog = json.loads(settings.catalog_path.read_text()) catalog["voices"].append({ "id": voice_id, "name": "Nova", "language": "pt-BR", "engine": "fake", "model": model, "config": "piper/fake.onnx.json", "sampleRate": 22050, "source": "teste", "license": "teste", }) settings.catalog_path.write_text(json.dumps(catalog)) stat = settings.catalog_path.stat() # Garante data de modificação diferente mesmo em sistema de arquivos com resolução grossa. os.utime(settings.catalog_path, ns=(stat.st_atime_ns, stat.st_mtime_ns + 10_000_000_000)) @pytest.mark.anyio async def test_catalog_change_shows_up_without_reload(make_client, settings): async with make_client() as client: assert (await client.get("/v1/voices/pt-br-nova", headers=HEADERS)).status_code == 404 _add_catalog_voice(settings, "pt-br-nova") listed = await client.get("/v1/voices", headers=HEADERS) assert "pt-br-nova" in [v["id"] for v in listed.json()["items"]] @pytest.mark.anyio async def test_broken_catalog_change_keeps_current_voices(make_client, settings): async with make_client() as client: _add_catalog_voice(settings, "pt-br-quebrada", model="piper/ausente.onnx") listed = await client.get("/v1/voices", headers=HEADERS) assert listed.status_code == 200 assert [v["id"] for v in listed.json()["items"]] == ["pt-br-test"] def test_real_decoder_reads_wav_and_mp3_like_containers(): import io import soundfile from app.decode import decode_audio from app.errors import InvalidAudio tone = (np.sin(np.arange(22050) * 2 * np.pi * 220 / 22050) * 8000).astype(np.int16) buffer = io.BytesIO() soundfile.write(buffer, tone, 22050, format="WAV", subtype="PCM_16") samples = decode_audio(buffer.getvalue(), 16000, max_seconds=10) assert samples.dtype == np.float32 and abs(samples.size / 16000 - 1.0) < 0.05 pcm = decode_audio(buffer.getvalue(), 24000, max_seconds=10, sample_format="s16") assert pcm.dtype == np.int16 with pytest.raises(InvalidAudio): decode_audio(b"isto nao e audio", 16000, max_seconds=10) def test_settings_defaults_point_inside_project(monkeypatch): from app.config import PROJECT_ROOT, Settings monkeypatch.setenv("VOICE_SERVICE_KEY", "k" * 40) for name in ("VOICE_MODELS_DIR", "VOICE_DATA_DIR", "VOICE_STT_MODEL", "VOICE_DEVICE"): monkeypatch.delenv(name, raising=False) settings = Settings.from_env() assert settings.models_dir == PROJECT_ROOT / "data" / "voice" / "models" assert settings.device in ("auto", "cuda", "cpu") monkeypatch.setenv("VOICE_MODELS_DIR", "outra/pasta") assert Settings.from_env().models_dir == PROJECT_ROOT / "outra" / "pasta" # relativo = raiz do projeto assert replace(settings, device="cpu").device == "cpu" async def test_duration_header_is_optional(make_client, stt_engine): headers = {k: v for k, v in stt_headers("text", key="sem-duracao").items() if k != "X-Audio-Duration-Ms"} async with make_client() as client: ok = await client.post("/v1/transcribe", content=ONE_SECOND, headers=headers) # O teto continua valendo pelo áudio decodificado (61 s > 60 s do fixture). long = await client.post("/v1/transcribe", content=b"OggS" + b"x" * 6100, headers={**headers, "X-Idempotency-Key": "longo"}) assert ok.status_code == 200 and ok.json()["text"] == "valeu pela live" assert long.status_code == 422 and long.json()["error"]["code"] == "audio_too_long" @pytest.mark.parametrize( ("smi", "busy"), [("7000, 10", False), ("1024, 10", True), ("7000, 99", True)], ) def test_gpu_busy_reason_reads_nvidia_smi(monkeypatch, smi, busy): import subprocess from types import SimpleNamespace from app import device monkeypatch.setattr(subprocess, "run", lambda *a, **k: SimpleNamespace(stdout=smi + "\n")) reason = device.gpu_busy_reason() assert (reason is not None) == busy if busy: assert "GPU ocupada" in reason def test_gpu_busy_reason_without_nvidia_smi(monkeypatch): import subprocess from app import device def boom(*a, **k): raise FileNotFoundError("nvidia-smi") monkeypatch.setattr(subprocess, "run", boom) assert device.gpu_busy_reason() is None # sem a ferramenta, não bloqueia a GPU def _write_catalog(settings, extra: dict) -> None: catalog = json.loads(settings.catalog_path.read_text()) catalog["voices"].append({ "id": "extra", "name": "Extra", "language": "pt-BR", "sampleRate": 24000, "source": "teste", "license": "teste", **extra, }) settings.catalog_path.write_text(json.dumps(catalog)) def test_catalog_reads_kokoro_and_google_voices(settings): _write_catalog(settings, {"engine": "kokoro", "model": "piper/fake.onnx", "config": "piper/fake.onnx.json", "kokoroVoice": "pf_dora"}) voice = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir)["extra"] assert (voice.engine, voice.engine_voice, voice.engine_lang) == ("kokoro", "pf_dora", "pt-br") catalog = json.loads(settings.catalog_path.read_text()) catalog["voices"][-1] = {**catalog["voices"][-1], "engine": "google", "googleTld": "pt"} settings.catalog_path.write_text(json.dumps(catalog)) voice = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir)["extra"] assert (voice.engine, voice.engine_voice, voice.engine_lang) == ("google", "pt", "pt") def test_kokoro_voice_without_style_is_rejected(settings): from app.config import ConfigError _write_catalog(settings, {"engine": "kokoro", "model": "piper/fake.onnx", "config": "piper/fake.onnx.json"}) with pytest.raises(ConfigError, match="kokoroVoice"): load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir) @pytest.mark.anyio async def test_online_flag_follows_engine(make_client, settings): _write_catalog(settings, {"engine": "google"}) async with make_client() as client: items = {v["id"]: v for v in (await client.get("/v1/voices", headers=HEADERS)).json()["items"]} assert items["extra"]["offline"] is False and items["pt-br-test"]["offline"] is True def test_azure_ssml_escapes_text_and_sets_rate(): from app.engine import AzureEngine voice = replace(_azure_voice(), engine_voice="pt-BR-FabioNeural") ssml = AzureEngine("k", "eastus").ssml(voice, 'Oi "x" & tchau', 1.25).decode("utf-8") assert "<b>" in ssml and "&" in ssml and "" not in ssml assert 'name="pt-BR-FabioNeural"' in ssml and 'xml:lang="pt-BR"' in ssml and 'rate="+25%"' in ssml assert "xmlns='http://www.w3.org/2001/10/synthesis'" in ssml def _azure_voice(): from app.catalog import Voice return Voice(id="azure-x", name="X", language="pt-BR", engine="azure", model=None, config=None, sample_rate=24000, default=False, source="t", license="t", revision="r", engine_voice="pt-BR-FabioNeural") def test_azure_synthesis_sends_key_and_decodes_wav(monkeypatch): import io import urllib.request import soundfile from app.engine import AzureEngine tone = (np.sin(np.arange(24000) * 2 * np.pi * 220 / 24000) * 8000).astype(np.int16) buffer = io.BytesIO() soundfile.write(buffer, tone, 24000, format="WAV", subtype="PCM_16") seen = {} class FakeResponse(io.BytesIO): def __enter__(self): return self def __exit__(self, *exc): return False def fake_urlopen(request, timeout): seen["url"], seen["key"] = request.full_url, request.get_header("Ocp-apim-subscription-key") return FakeResponse(buffer.getvalue()) monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen) pcm = AzureEngine("segredo", "brazilsouth").synthesize(_azure_voice(), "Olá", 1.0, 10) assert seen == {"url": "https://brazilsouth.tts.speech.microsoft.com/cognitiveservices/v1", "key": "segredo"} assert pcm.sample_rate == 24000 and abs(pcm.duration_s - 1.0) < 0.05 @pytest.mark.anyio async def test_azure_voices_hidden_without_key(make_client, settings): _write_catalog(settings, {"engine": "azure", "azureVoice": "pt-BR-FabioNeural"}) async with make_client() as client: ids = [v["id"] for v in (await client.get("/v1/voices", headers=HEADERS)).json()["items"]] assert "extra" not in ids async with make_client(azure_key="chave") as client: items = {v["id"]: v for v in (await client.get("/v1/voices", headers=HEADERS)).json()["items"]} assert items["extra"]["offline"] is False and items["extra"]["provider"] == "azure" def _add_clone_voice(settings, tmp_path, consent=True): reference = settings.models_dir / "clone" / "clone-eu" / "reference.wav" reference.parent.mkdir(parents=True) reference.write_bytes(b"RIFF-fake-wav") entry = { "id": "clone-eu", "name": "Eu", "kind": "clone", "gender": "male", "source": "minha voz", "license": "minha", "consent": consent, "clone": {"reference": "clone/clone-eu/reference.wav", "referenceSha256": hashlib.sha256(b"RIFF-fake-wav").hexdigest(), "exaggeration": 0.7}, } user = tmp_path / "user-voices.json" user.write_text(json.dumps({"voices": [entry]})) return user def test_clone_voice_loads_with_consent(settings, tmp_path): user = _add_clone_voice(settings, tmp_path) voice = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir, user_catalog_path=user)["clone-eu"] assert (voice.engine, voice.user, voice.engine_lang) == ("clone", True, "pt") assert voice.clone == {"exaggeration": 0.7, "cfgWeight": 0.5} and voice.model.name == "reference.wav" def test_clone_voice_without_consent_is_skipped(settings, tmp_path): user = _add_clone_voice(settings, tmp_path, consent=False) voices = load_catalog(settings.catalog_path, settings.lock_path, settings.models_dir, user_catalog_path=user) assert "clone-eu" not in voices def test_clone_engine_reports_worker_down(): from app.engine import CloneEngine from app.errors import CloneUnavailable voice = replace(_azure_voice(), engine="clone", model=Path("x.wav"), clone={"exaggeration": 0.5, "cfgWeight": 0.5}) with pytest.raises(CloneUnavailable): CloneEngine(4599, "k", timeout_s=2).synthesize(voice, "Olá", 1.0, 10)