import asyncio import logging import pytest from app.stt import FakeSttEngine, join_text, mean_no_speech from tests.conftest import HEADERS, KEY pytestmark = pytest.mark.anyio # Convenção do FakeSttEngine: cada byte depois de "OggS" vale 10 ms de áudio. ONE_SECOND = b"OggS" + b"x" * 100 def stt_headers(key: str = "order:123:transcribe", duration_ms: int = 1000, language: str = "pt-BR", **extra) -> dict: headers = { **HEADERS, "Content-Type": "audio/ogg", "X-Idempotency-Key": key, "X-Audio-Duration-Ms": str(duration_ms), "X-Language": language, } headers.update(extra) return headers async def test_requires_service_key(make_client): async with make_client() as client: no_key = {k: v for k, v in stt_headers().items() if k != "X-Service-Key"} assert (await client.post("/v1/transcribe", content=ONE_SECOND, headers=no_key)).status_code == 401 wrong = stt_headers(**{"X-Service-Key": "x" * len(KEY)}) response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=wrong) assert response.status_code == 401 assert response.json()["error"]["code"] == "unauthorized" assert (await client.get("/v1/transcribe/jobs/abcdefghijkl")).status_code == 401 async def test_ready_with_mean_no_speech_prob(make_client, stt_engine): async with make_client() as client: response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers()) assert response.status_code == 200 assert response.json() == {"status": "ready", "text": "valeu pela live", "noSpeechProb": 0.2} assert response.headers["x-idempotent-replay"] == "false" assert stt_engine.calls == 1 async def test_no_segments_means_no_speech(make_client): async with make_client(stt=FakeSttEngine(text="", probs=())) as client: response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers()) assert response.json() == {"status": "ready", "text": "", "noSpeechProb": 1.0} def test_no_speech_helpers(): assert mean_no_speech([]) == 1.0 assert mean_no_speech([0.2, 0.4]) == pytest.approx(0.3) assert mean_no_speech([1.5]) == 1.0 # preso em 0..1 assert join_text([" oi ", "", " tudo bem"], 4000) == "oi tudo bem" assert len(join_text(["a" * 5000], 4000)) == 4000 async def test_idempotency_replay_and_conflict(make_client, stt_engine): async with make_client() as client: first = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers()) again = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers()) other_audio = await client.post("/v1/transcribe", content=ONE_SECOND + b"y", headers=stt_headers()) assert again.status_code == 200 and again.json() == first.json() assert again.headers["x-idempotent-replay"] == "true" assert stt_engine.calls == 1 # o retry não transcreve de novo assert other_audio.status_code == 409 assert other_audio.json()["error"]["code"] == "idempotency_conflict" @pytest.mark.parametrize( ("overrides", "code", "status"), [ ({"X-Audio-Duration-Ms": "60001"}, "audio_too_long", 422), ({"X-Audio-Duration-Ms": "0"}, "invalid_request", 422), ({"X-Language": "fr"}, "language_not_supported", 422), ({"X-Idempotency-Key": "com espaco"}, "invalid_request", 422), ({"Content-Type": "text/plain"}, "invalid_request", 422), ({"X-Detail": "frases"}, "invalid_request", 422), ], ) async def test_header_validation(make_client, stt_engine, overrides, code, status): async with make_client() as client: response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers(**overrides)) assert response.status_code == status assert response.json()["error"]["code"] == code assert stt_engine.calls == 0 async def test_byte_limit(make_client, stt_engine): async with make_client(stt_max_bytes=1024) as client: response = await client.post("/v1/transcribe", content=b"OggS" + b"x" * 2000, headers=stt_headers()) assert response.status_code == 413 assert response.json()["error"]["code"] == "audio_too_large" assert stt_engine.calls == 0 async def test_decoded_duration_limit(make_client, stt_engine): # Declara 60 s, mas o áudio decodificado tem 61 s: vale o decodificado. async with make_client() as client: response = await client.post( "/v1/transcribe", content=b"OggS" + b"x" * 6100, headers=stt_headers(duration_ms=60000) ) assert response.status_code == 422 assert response.json()["error"]["code"] == "audio_too_long" assert stt_engine.calls == 0 async def test_invalid_audio(make_client): async with make_client() as client: response = await client.post("/v1/transcribe", content=b"RIFFxxxx", headers=stt_headers()) assert response.status_code == 422 assert response.json()["error"]["code"] == "invalid_audio" async def test_pending_then_job_ready(make_client): async with make_client(stt=FakeSttEngine(delay_s=0.3), stt_sync_wait_s=0.0) as client: response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers()) assert response.status_code == 202 pending = response.json() assert pending["status"] == "pending" and pending["retryAfterMs"] >= 500 for _ in range(100): job = await client.get(f"/v1/transcribe/jobs/{pending['jobRef']}", headers=HEADERS) if job.json()["status"] == "ready": break await asyncio.sleep(0.05) assert job.status_code == 200 assert job.json() == {"status": "ready", "text": "valeu pela live", "noSpeechProb": 0.2} async def test_unknown_job_and_disabled(make_client): async with make_client() as client: response = await client.get("/v1/transcribe/jobs/abcdefghijkl", headers=HEADERS) assert response.status_code == 410 assert response.json()["error"]["code"] == "job_not_found" async with make_client(stt=None) as client: response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers()) assert response.status_code == 501 assert response.json()["error"]["code"] == "stt_disabled" async def test_queue_full(make_client): async with make_client(stt=FakeSttEngine(delay_s=0.5), stt_sync_wait_s=0.0, stt_max_queue_per_key=0) as client: first = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers(key="a-1")) assert first.status_code == 202 for _ in range(100): if (await client.get("/v1/status", headers=HEADERS)).json()["queues"]["transcription"]["running"] == 1: break await asyncio.sleep(0.01) second = await client.post("/v1/transcribe", content=ONE_SECOND + b"z", headers=stt_headers(key="b-2")) assert second.status_code == 503 assert second.json()["error"]["code"] == "queue_full" assert second.headers["retry-after"] == "5" async def test_no_text_in_logs(make_client, caplog): secret = "segredo do espectador" caplog.set_level(logging.DEBUG) async with make_client(stt=FakeSttEngine(text=secret)) as client: response = await client.post("/v1/transcribe", content=ONE_SECOND, headers=stt_headers()) assert response.json()["text"] == secret assert secret not in caplog.text assert "transcribe job=" in caplog.text def test_real_ogg_opus_decoder(): # Decodificador de verdade (PyAV), com OGG/Opus gerado pelo mesmo codificador da síntese. import numpy as np from app.audio import encode_ogg_opus from app.engine import Pcm from app.errors import AudioTooLong, InvalidAudio from app.stt import SAMPLE_RATE, decode_ogg_opus tone = (np.sin(np.arange(22050 * 2) * 2 * np.pi * 220 / 22050) * 8000).astype(np.int16) data = encode_ogg_opus(Pcm(tone, 22050)) samples = decode_ogg_opus(data, max_seconds=60) assert samples.dtype == np.float32 assert abs(samples.size / SAMPLE_RATE - 2.0) < 0.1 with pytest.raises(AudioTooLong): decode_ogg_opus(data, max_seconds=1.0) with pytest.raises(InvalidAudio): decode_ogg_opus(b"OggS" + b"\x00" * 64, max_seconds=60)