# SPDX-License-Identifier: Apache-2.0 """HTTP server + Python API on the fake model (no weights, no device). Checks routes, validation, streaming, voices, the main-thread device open/close order and the worker.""" from __future__ import annotations import base64 import io import json import threading import numpy as np import pytest fastapi = pytest.importorskip("fastapi") from fastapi.testclient import TestClient # noqa: E402 def _wav_bytes(seconds=0.5, sr=16000): import soundfile as sf t = np.arange(int(seconds * sr)) / sr buf = io.BytesIO() sf.write(buf, (0.1 * np.sin(2 * np.pi * 300 * t)).astype(np.float32), sr, format="WAV", subtype="PCM_16") return buf.getvalue() @pytest.fixture() def client(monkeypatch, tmp_path): monkeypatch.setenv("RAON_BACKEND", "fake") monkeypatch.setenv("RAON_VOICES", str(tmp_path / "voices")) from tt_raon.server import app as A events = [] def opener(cfg): events.append(("open", threading.get_ident())) return "DEV" def closer(dev): events.append(("close", threading.get_ident(), dev)) def factory(cfg, dev): from tt_raon.api import RaonSpeech from tt_raon.server.fake import FakeModel events.append(("build", threading.current_thread().name)) return RaonSpeech(FakeModel(cfg), cfg) app = A.create_app(model_factory=factory, device_opener=opener, device_closer=closer) with TestClient(app) as c: c.events = events yield c # the chip is opened and closed by the lifespan's thread (the main thread under uvicorn; TestClient runs the # event loop on a portal thread), the model is built on the device worker thread assert events[0][0] == "open" and events[-1][0] == "close" and events[-1][1] == events[0][1] assert events[-1][2] == "DEV" assert events[1][0] == "build" and events[1][1] == "raon-device" def test_health_info_models(client): assert client.get("/health").json()["status"] == "ok" info = client.get("/info").json() assert info["model"] == "Raon-Speech-9B" and info["license"] == "CC BY-NC 4.0" assert client.get("/v1/models").json()["data"][0]["id"] == "Raon-Speech-9B" def test_transcriptions_multipart_and_json(client): r = client.post("/v1/audio/transcriptions", files={"file": ("a.wav", _wav_bytes(), "audio/wav")}, data={"model": "raon", "temperature": "0.2", "seed": "3"}) assert r.status_code == 200, r.text assert r.json()["text"].startswith("this is a fake") r = client.post("/v1/audio/transcriptions", json={"audio": base64.b64encode(_wav_bytes()).decode(), "response_format": "text"}) assert r.status_code == 200 and r.text.startswith("this is") r = client.post("/v1/audio/transcriptions", files={"file": ("a.wav", _wav_bytes(), "audio/wav")}, data={"top_k": "100000000", "top_p": "1.5"}) assert r.status_code == 400 def test_transcriptions_stream(client): with client.stream("POST", "/v1/audio/transcriptions", files={"file": ("a.wav", _wav_bytes(), "audio/wav")}, data={"stream": "true"}) as r: body = b"".join(r.iter_bytes()).decode() events = [json.loads(l[6:]) for l in body.split("\n\n") if l.startswith("data: {")] assert events[0]["type"] == "transcript.text.delta" assert events[-1]["type"] == "transcript.text.done" assert "".join(e["delta"] for e in events[:-1]) == events[-1]["text"] def test_speech_formats_and_stream(client): r = client.post("/v1/audio/speech", json={"input": "Hello", "response_format": "wav"}) assert r.status_code == 200 and r.content[:4] == b"RIFF" r = client.post("/v1/audio/speech", json={"input": "Hello", "response_format": "pcm"}) assert len(r.content) == 2 * 5 * 1920 # 6 fake frames, last one trimmed r = client.post("/v1/audio/speech", json={"input": "Hello", "speed": 2.0}) assert r.status_code == 400 with client.stream("POST", "/v1/audio/speech", json={"input": "Hello", "response_format": "f32", "stream": True}) as r: data = b"".join(r.iter_bytes()) assert len(data) == 4 * 5 * 1920 r = client.post("/tts", json={"text": "Hello", "seed": 1}) assert r.status_code == 200 and r.json()["format"] == "wav" def test_voices_and_cloning(client): r = client.post("/v1/voices", files={"file": ("v.wav", _wav_bytes(1.0), "audio/wav")}, data={"name": "alice", "ref_text": "hello there"}) assert r.status_code == 200, r.text assert any(v["name"] == "alice" for v in client.get("/v1/voices").json()["voices"]) r = client.post("/v1/audio/speech", json={"input": "Hi", "voice": "alice", "response_format": "pcm"}) assert r.status_code == 200 r = client.post("/v1/audio/speech", json={"input": "Hi", "voice": "alice", "continuation": True, "response_format": "pcm"}) assert r.status_code == 200 r = client.post("/v1/audio/speech", json={"input": "Hi", "voice": "bob"}) assert r.status_code == 404 assert client.delete("/v1/voices/alice").status_code == 200 assert client.delete("/v1/voices/alice").status_code == 404 def test_chat_completions(client): audio = base64.b64encode(_wav_bytes()).decode() r = client.post("/v1/chat/completions", json={"messages": [ {"role": "user", "content": [{"type": "input_audio", "input_audio": {"data": audio, "format": "wav"}}, {"type": "text", "text": "What is said?"}]}], "max_tokens": 16}) assert r.status_code == 200, r.text assert r.json()["choices"][0]["message"]["content"].startswith("this is") with client.stream("POST", "/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hi"}], "stream": True}) as r: body = b"".join(r.iter_bytes()).decode() assert body.rstrip().endswith("data: [DONE]") r = client.post("/v1/chat/completions", json={"messages": [{"role": "robot", "content": "x"}]}) assert r.status_code == 400 def test_validate_params(): from tt_raon import config as C from tt_raon.api import validate_params cfg = C.resolve_config({}) p = validate_params("tts", {"temperature": 1.0}, cfg) assert p["ras_enabled"] and p["top_k"] == 20 and p["max_new_tokens"] == 512 assert validate_params("stt", {"top_k": 10 ** 9}, cfg)["top_k"] == 0 for bad in ({"top_k": 100}, {"top_p": 0.0}, {"temperature": 0.0}, {"ras_window_size": 1000}, {"continuation_silence_frames": 9}, {"max_audio_chunk_length": 500000}): with pytest.raises(ValueError): validate_params("tts", bad, cfg) def test_config_refuses_bad_values(): from tt_raon import config as C for env in ({"RAON_PROFILE": "fp4"}, {"RAON_MAX_POSITIONS": "100"}, {"RAON_PREFILL_BUCKETS": "33"}, {"RAON_TALKER_POLICY": "never"}, {"RAON_BACKEND": "gpu"}): with pytest.raises(ValueError): C.resolve_config(env) def test_lone_surrogate_text_is_refused(client): """A JSON "\\ud800" escape decodes to an unpaired surrogate: every text field answers 400, never 500.""" bad = "Hello \ud800 world" hdr = {"Content-Type": "application/json"} for route, body in (("/v1/audio/speech", {"input": bad}), ("/tts", {"text": bad}), ("/v1/chat/completions", {"messages": [{"role": "user", "content": bad}]}), ("/v1/chat/completions", {"messages": [{"role": "user", "content": [{"type": "text", "text": bad}]}]})): r = client.post(route, content=json.dumps(body), headers=hdr) assert r.status_code == 400 and "surrogate" in r.json()["detail"], (route, r.status_code, r.text) def test_bad_audio_and_bodies_are_400(client): """Undecodable / empty audio, invalid JSON for voices, non-object JSON bodies: 400 (never 500).""" hdr = {"Content-Type": "application/json"} bad = base64.b64encode(b"this is not audio at all, just bytes").decode() for route, body in (("/v1/audio/transcriptions", {"audio": bad}), ("/v1/audio/transcriptions", {"audio": ""}), ("/v1/audio/speech", {"input": "Hi.", "speaker_audio": bad}), ("/v1/voices", {"name": "x", "audio": bad})): r = client.post(route, content=json.dumps(body), headers=hdr) assert r.status_code == 400, (route, r.status_code, r.text) r = client.post("/v1/audio/transcriptions", files={"file": ("x.wav", b"garbage!")}) assert r.status_code == 400, r.text r = client.post("/v1/voices", content=b"{not json", headers=hdr) assert r.status_code == 400, r.text for route in ("/v1/audio/speech", "/tts", "/v1/chat/completions", "/v1/voices", "/v1/audio/transcriptions"): r = client.post(route, content=b"[1, 2]", headers=hdr) assert r.status_code == 400, (route, r.status_code, r.text) r = client.post("/v1/chat/completions", content=json.dumps({"messages": ["hi"]}), headers=hdr) assert r.status_code == 400, r.text def test_raw_pcm_with_sample_rate(client): """A headerless s16le mono body + ``sample_rate`` is decoded as raw PCM (JSON and multipart).""" pcm = (np.round(0.1 * np.sin(np.arange(16000) * 0.05) * 32767)).astype("