Download code/tt_raon/api.py from changh95/Raon-Speech-9B: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/api.py
- Command line
-
hf download hf://changh95/Raon-Speech-9B/code/tt_raon/api.py
-
curl -L -o api.py https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/api.py
18.4 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Python API of the Raon-Speech-9B port (every official task; SPEC section 2): | |
| from tt_raon.api import RaonSpeech | |
| m = RaonSpeech.from_config() # RAON_BACKEND=tt (device), cpu (fp32 reference), fake (tests) | |
| m.transcribe("clip.wav") # STT -> {"text", "info"} | |
| m.speech_chat("question.wav") # SpeechChat -> {"text", ...} | |
| m.textqa("What is the gender of the speaker?", audio="clip.wav") | |
| m.chat([{"role": "user", "content": "Hi"}]) # multi-turn chat (text out) | |
| m.tts("Hello!", voice="alice") # TTS -> {"pcm": float32 24 kHz, "sample_rate": 24000, ...} | |
| m.tts_continuation("And then ...", ref_audio="ref.wav", ref_text="...") | |
| m.add_voice("alice", "alice.wav", ref_text=None) # voices: ECAPA embedding (+ Mimi codes of the clip) | |
| Per-request parameters (official names; validated against SPEC 2.1): ``max_new_tokens``, ``temperature``, ``top_k``, | |
| ``top_p``, ``do_sample``, ``seed``, ``ras_enabled``, ``ras_window_size``, ``ras_repetition_threshold``, | |
| ``continuation_silence_frames``, ``max_audio_chunk_length``, ``disable_eos_on_first_output``. Streaming: ``on_text`` | |
| (text deltas) / ``on_audio`` (PCM packets) callbacks. | |
| Device rules: the chip is opened by :func:`open_serving_device` (server: on the MAIN thread) and every model call | |
| runs on one thread. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import os | |
| import re | |
| import threading | |
| import time | |
| from dataclasses import dataclass, field | |
| from typing import Any, Callable, Dict, List, Optional, Sequence, Union | |
| from . import config as C | |
| AudioIn = Union[str, bytes, Any] | |
| _VOICE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$") | |
| PARAM_KEYS = ("max_new_tokens", "temperature", "top_k", "top_p", "do_sample", "ras_enabled", "ras_window_size", | |
| "ras_repetition_threshold", "continuation_silence_frames", "max_audio_chunk_length", | |
| "disable_eos_on_first_output") | |
| def validate_params(task: str, p: Dict[str, Any], cfg: C.ServeConfig) -> Dict[str, Any]: | |
| """Official defaults of ``task`` + user values, range-checked (ValueError -> HTTP 400).""" | |
| q = {k: v for k, v in p.items() if k in PARAM_KEYS and v is not None} | |
| out = C.task_params(task, **q) | |
| mnt = int(out["max_new_tokens"]) | |
| if mnt < 1: | |
| raise ValueError("max_new_tokens must be >= 1") | |
| t = float(out["temperature"]) | |
| if out.get("do_sample", True) and not t > 0: | |
| raise ValueError("temperature must be > 0 (use do_sample=false for greedy)") | |
| k = int(out.get("top_k") or 0) | |
| if k < 0: | |
| raise ValueError("top_k must be >= 0") | |
| if k > cfg.k_max: | |
| if k >= C.TEXT_VOCAB: | |
| k = 0 | |
| else: | |
| raise ValueError(f"top_k={k} exceeds the device sampler cap K_MAX={cfg.k_max} (0 disables top-k)") | |
| out["top_k"] = k | |
| tp = float(out.get("top_p", 1.0)) | |
| if not 0.0 < tp <= 1.0: | |
| raise ValueError("top_p must be in (0, 1]") | |
| w = int(out.get("ras_window_size", 50)) | |
| if not 1 <= w <= cfg.ras_window_max: | |
| raise ValueError(f"ras_window_size must be in [1, {cfg.ras_window_max}]") | |
| th = float(out.get("ras_repetition_threshold", 0.5)) | |
| if not 0.0 <= th <= 1.0: | |
| raise ValueError("ras_repetition_threshold must be in [0, 1]") | |
| sil = int(out.get("continuation_silence_frames", 0) or 0) | |
| if not 0 <= sil <= 8: | |
| raise ValueError("continuation_silence_frames must be in [0, 8]") | |
| mac = out.get("max_audio_chunk_length") | |
| if mac is not None and not 0 < int(mac) <= C.MAX_AUDIO_CHUNK: | |
| raise ValueError(f"max_audio_chunk_length must be in (0, {C.MAX_AUDIO_CHUNK}]") | |
| return out | |
| class Voice: | |
| name: str | |
| ecapa: Any # raw ECAPA embedding [192] fp32 | |
| codes: Optional[Any] = None # Mimi codes of the clip [F, 16] (continuation) | |
| ref_text: Optional[str] = None | |
| seconds: float = 0.0 | |
| created: float = field(default_factory=time.time) | |
| def describe(self) -> Dict[str, Any]: | |
| return {"name": self.name, "seconds": round(self.seconds, 2), "continuation": self.codes is not None, | |
| "ref_text": self.ref_text, "created": int(self.created)} | |
| class VoiceStore: | |
| """Stored voices (derived features only: ECAPA embedding, Mimi codes, transcript); optional directory.""" | |
| def __init__(self, directory: Optional[str] = None, max_voices: int = 256): | |
| self.dir = directory | |
| self.max = int(max_voices) | |
| self.v: Dict[str, Voice] = {} | |
| self._lock = threading.Lock() | |
| if directory and os.path.isdir(directory): | |
| for f in sorted(os.listdir(directory)): | |
| if f.endswith(".safetensors"): | |
| try: | |
| self._load(os.path.join(directory, f)) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| def _load(self, path: str) -> None: | |
| from safetensors import safe_open | |
| with safe_open(path, "pt") as f: | |
| md = f.metadata() or {} | |
| t = {k: f.get_tensor(k) for k in f.keys()} | |
| v = Voice(md.get("name", os.path.basename(path)[:-12]), t["ecapa"], t.get("codes"), md.get("ref_text") or None, | |
| float(md.get("seconds", 0)), float(md.get("created", time.time()))) | |
| self.v[v.name] = v | |
| def add(self, v: Voice) -> Voice: | |
| if not _VOICE_RE.match(v.name): | |
| raise ValueError("voice names: 1-64 characters of [A-Za-z0-9_.-]") | |
| with self._lock: | |
| if v.name not in self.v and len(self.v) >= self.max: | |
| raise ValueError(f"voice store full ({self.max})") | |
| self.v[v.name] = v | |
| if self.dir: | |
| from safetensors.torch import save_file | |
| os.makedirs(self.dir, exist_ok=True) | |
| t = {"ecapa": v.ecapa.float().contiguous()} | |
| if v.codes is not None: | |
| t["codes"] = v.codes.long().contiguous() | |
| md = {"name": v.name, "ref_text": v.ref_text or "", "seconds": str(v.seconds), "created": str(v.created)} | |
| tmp = os.path.join(self.dir, f".{v.name}.tmp") | |
| save_file(t, tmp, metadata=md) | |
| os.replace(tmp, os.path.join(self.dir, f"{v.name}.safetensors")) | |
| return v | |
| def get(self, name: str) -> Voice: | |
| try: | |
| return self.v[name] | |
| except KeyError: | |
| raise KeyError(f"unknown voice {name!r}") from None | |
| def delete(self, name: str) -> None: | |
| with self._lock: | |
| self.v.pop(name) | |
| if self.dir: | |
| p = os.path.join(self.dir, f"{name}.safetensors") | |
| if os.path.exists(p): | |
| os.remove(p) | |
| def list(self) -> List[Dict[str, Any]]: | |
| return [v.describe() for v in self.v.values()] | |
| def prepare_environment(cfg: C.ServeConfig) -> None: | |
| """Point every stage at the resolved weights and the cache directory BEFORE the engine modules are imported | |
| (the megakernel packages read their cache / checkpoint locations at import): RAON_MODEL_DIR, RAON_ECAPA_DIR, | |
| RAON_CKPT (mk_thinker), RAON_TKR_CACHE, RAON_TLK_CACHE, RAON_MK_MIMI_CACHE, RAON_CACHE_DIR.""" | |
| model_dir = cfg.model_dir if os.path.isdir(cfg.model_dir) else C.resolve_weights("raon") | |
| ecapa_dir = cfg.ecapa_dir if os.path.isdir(cfg.ecapa_dir) else C.resolve_weights("ecapa") | |
| os.environ["RAON_MODEL_DIR"] = model_dir | |
| os.environ["RAON_ECAPA_DIR"] = ecapa_dir | |
| os.environ.setdefault("RAON_CKPT", model_dir) | |
| os.environ.setdefault("RAON_TKR_CACHE", os.path.join(cfg.cache_dir, "thinker")) # every cache under cfg.cache_dir | |
| os.environ.setdefault("RAON_TLK_CACHE", os.path.join(cfg.cache_dir, "mk_talker")) | |
| os.environ.setdefault("RAON_MK_MIMI_CACHE", os.path.join(cfg.cache_dir, "mk_mimi")) | |
| object.__setattr__(cfg, "model_dir", model_dir) | |
| object.__setattr__(cfg, "ecapa_dir", ecapa_dir) | |
| def open_serving_device(cfg: C.ServeConfig, log=print): | |
| from .tt.model import open_device | |
| log(f"[raon] opening device {cfg.device_id} (dispatch {cfg.dispatch})") | |
| return open_device(cfg.dispatch, trace_region_size=cfg.trace_region_mb << 20, device_id=cfg.device_id) | |
| class RaonSpeech: | |
| """Every task on one model (``RaonDevice`` for the tt / cpu backends, a stand-in for ``fake``).""" | |
| def __init__(self, model, cfg: C.ServeConfig, voices: Optional[VoiceStore] = None): | |
| self.model, self.cfg = model, cfg | |
| self.voices = voices or VoiceStore(cfg.voices_dir) | |
| def from_config(cls, cfg: Optional[C.ServeConfig] = None, device=None, log=print) -> "RaonSpeech": | |
| cfg = cfg or C.resolve_config() | |
| if cfg.backend == "fake": | |
| from .server.fake import FakeModel | |
| return cls(FakeModel(cfg), cfg) | |
| import torch | |
| torch.set_num_threads(cfg.torch_threads) | |
| prepare_environment(cfg) | |
| from .tt.model import RaonDevice | |
| if cfg.backend == "cpu": | |
| return cls(RaonDevice(None, cfg, engine="host"), cfg) | |
| if device is None: | |
| raise ValueError("backend tt needs an open device (open_serving_device)") | |
| t0 = time.time() | |
| m = RaonDevice(device, cfg) | |
| log(f"[raon] model ready in {time.time() - t0:.0f} s, engines {m.engines}") | |
| return cls(m, cfg) | |
| # ------------------------------------------------------------------ inputs | |
| def _wav(self, a: AudioIn, sample_rate: Optional[int] = None, reference: bool = False): | |
| from .frontend.audio import load_input_audio, load_reference_audio | |
| w = (load_reference_audio if reference else load_input_audio)(a, sample_rate) | |
| if w.numel() == 0: | |
| raise ValueError("empty audio") | |
| return w | |
| def _check_audio_seconds(self, wavs) -> None: | |
| s = sum(int(w.numel()) for w in wavs) / C.SAMPLE_RATE | |
| if s > self.cfg.max_audio_seconds: | |
| raise ValueError(f"{s:.1f} s of audio input exceeds RAON_MAX_AUDIO_SECONDS={self.cfg.max_audio_seconds}") | |
| def _utf8(s: str) -> str: | |
| try: | |
| s.encode("utf-8") | |
| except UnicodeEncodeError: # e.g. a lone surrogate from a JSON "\ud800" escape | |
| raise ValueError("text is not valid Unicode (unpaired surrogate)") from None | |
| return s | |
| def _text(self, s: str) -> str: | |
| from .reference.prompt import check_special_text | |
| if not isinstance(s, str) or not s.strip(): | |
| raise ValueError("text must be a non-empty string") | |
| self._utf8(s) | |
| if len(s) > self.cfg.max_text_chars: | |
| raise ValueError(f"text longer than {self.cfg.max_text_chars} characters") | |
| check_special_text(s) | |
| return s | |
| def _run(self, task: str, params: Dict[str, Any], seed=None, on_text=None, on_audio=None, should_stop=None, | |
| **kw) -> Dict[str, Any]: | |
| p = validate_params(task, params, self.cfg) | |
| res = self.model.run(task, seed=seed, on_text=on_text, on_audio=on_audio, should_stop=should_stop, **kw, **p) | |
| out = {"task": task, "stop": res.stop, "info": res.info, "tokens": len(res.tokens)} | |
| if res.text is not None: | |
| out["text"] = res.text | |
| if res.pcm is not None: | |
| out["pcm"], out["sample_rate"] = res.pcm, C.SAMPLE_RATE | |
| out["seconds"] = float(res.pcm.numel()) / C.SAMPLE_RATE | |
| if res.codes is not None and res.codes.shape[0]: | |
| out["frames"] = int(res.codes.shape[0]) | |
| return out | |
| # ------------------------------------------------------------------ tasks | |
| def transcribe(self, audio: AudioIn, prompt: Optional[str] = None, sample_rate: Optional[int] = None, | |
| **params) -> Dict[str, Any]: | |
| w = self._wav(audio, sample_rate) | |
| self._check_audio_seconds([w]) | |
| return self._run("stt", params, audio=w, prompt=self._text(prompt) if prompt else None, | |
| **_cb(params)) | |
| def speech_chat(self, audio: AudioIn, sample_rate: Optional[int] = None, **params) -> Dict[str, Any]: | |
| w = self._wav(audio, sample_rate) | |
| self._check_audio_seconds([w]) | |
| return self._run("speech_chat", params, audio=w, **_cb(params)) | |
| def textqa(self, text: str, audio: Optional[AudioIn] = None, sample_rate: Optional[int] = None, | |
| **params) -> Dict[str, Any]: | |
| w = self._wav(audio, sample_rate) if audio is not None else None | |
| if w is not None: | |
| self._check_audio_seconds([w]) | |
| return self._run("textqa", params, text=self._text(text), audio=w, **_cb(params)) | |
| def chat(self, messages: Sequence[Dict[str, Any]], force_audio_output: bool = False, | |
| voice: Optional[str] = None, speaker_audio: Optional[AudioIn] = None, **params) -> Dict[str, Any]: | |
| """HF-style messages; audio items ``{"type": "audio", "audio": path | bytes | wav24}``.""" | |
| msgs, wavs = [], [] | |
| for m in messages: | |
| c = m.get("content") | |
| if isinstance(c, list): | |
| items = [] | |
| for it in c: | |
| if it.get("type") == "audio": | |
| w = self._wav(it["audio"], it.get("sample_rate")) | |
| wavs.append(w) | |
| items.append({"type": "audio", "audio": w}) | |
| elif it.get("type") == "text": | |
| items.append({"type": "text", "text": self._utf8(str(it["text"]))}) | |
| else: | |
| items.append(dict(it)) | |
| msgs.append({**m, "content": items}) | |
| else: | |
| if isinstance(c, str): | |
| self._utf8(c) | |
| msgs.append(dict(m)) | |
| self._check_audio_seconds(wavs) | |
| kw: Dict[str, Any] = {"messages": msgs} | |
| if force_audio_output: | |
| sp_row = None | |
| if voice: | |
| sp_row = self._voice_row(voice) | |
| elif speaker_audio is not None: | |
| kw["speaker_wav"] = self._wav(speaker_audio, reference=True) | |
| if sp_row is not None: | |
| kw["speaker_wav"] = _Placeholder() | |
| kw["speaker_row"] = sp_row | |
| return self._run("chat_audio_out" if force_audio_output else "chat", params, **kw, **_cb(params)) | |
| def tts(self, text: str, voice: Optional[str] = None, speaker_audio: Optional[AudioIn] = None, | |
| **params) -> Dict[str, Any]: | |
| kw: Dict[str, Any] = {"text": self._text(text)} | |
| if voice: | |
| kw["speaker_wav"], kw["speaker_row"] = _Placeholder(), self._voice_row(voice) | |
| elif speaker_audio is not None: | |
| kw["speaker_wav"] = self._wav(speaker_audio, reference=True) | |
| return self._run("tts", params, **kw, **_cb(params)) | |
| def tts_continuation(self, text: str, ref_audio: Optional[AudioIn] = None, ref_text: Optional[str] = None, | |
| voice: Optional[str] = None, speaker_audio: Optional[AudioIn] = None, | |
| **params) -> Dict[str, Any]: | |
| """Continue a reference clip (``ref_audio`` + ``ref_text``, or a stored voice registered with its clip).""" | |
| kw: Dict[str, Any] = {"text": self._text(text)} | |
| if voice: | |
| v = self.voices.get(voice) | |
| if v.codes is None: | |
| raise ValueError(f"voice {voice!r} has no stored reference clip (register it with keep_codes=true)") | |
| kw["ref_codes"], kw["ref_text"] = v.codes, ref_text or v.ref_text | |
| kw["speaker_wav"], kw["speaker_row"] = _Placeholder(), self._voice_row(voice) | |
| else: | |
| if ref_audio is None: | |
| raise ValueError("tts_continuation needs ref_audio (or a stored voice)") | |
| ref = self._wav(ref_audio, reference=True) | |
| if ref.numel() / C.SAMPLE_RATE > self.cfg.max_ref_seconds: | |
| raise ValueError(f"reference longer than RAON_MAX_REF_SECONDS={self.cfg.max_ref_seconds}") | |
| kw["ref_audio"] = ref | |
| kw["ref_text"] = ref_text | |
| kw["speaker_wav"] = self._wav(speaker_audio, reference=True) if speaker_audio is not None else ref | |
| if not kw.get("ref_text"): | |
| kw["ref_text"] = self.transcribe(kw.get("ref_audio") if "ref_audio" in kw else None)["text"] \ | |
| if "ref_audio" in kw else None | |
| if not kw["ref_text"]: | |
| raise ValueError("ref_text is required for a stored voice without a transcript") | |
| self._utf8(kw["ref_text"]) | |
| return self._run("tts_continuation", params, **kw, **_cb(params)) | |
| # ------------------------------------------------------------------ voices | |
| def _voice_row(self, name: str): | |
| v = self.voices.get(name) | |
| return self.model.spk.project(v.ecapa) | |
| def add_voice(self, name: str, audio: AudioIn, ref_text: Optional[str] = None, keep_codes: bool = True, | |
| sample_rate: Optional[int] = None) -> Dict[str, Any]: | |
| self._utf8(str(name)) | |
| if ref_text: | |
| self._utf8(ref_text) | |
| w = self._wav(audio, sample_rate, reference=True) | |
| sec = w.numel() / C.SAMPLE_RATE | |
| if sec > self.cfg.max_ref_seconds: | |
| raise ValueError(f"voice clip longer than RAON_MAX_REF_SECONDS={self.cfg.max_ref_seconds}") | |
| e = self.model.spk.embed(w) | |
| codes = self.model.enc.encode(w) if keep_codes else None | |
| return self.voices.add(Voice(name, e, codes, ref_text, sec)).describe() | |
| def info(self) -> Dict[str, Any]: | |
| d = {"model": C.MODEL_NAME, "package": C.PACKAGE_REPO, "license": C.LICENSE, "config": self.cfg.as_dict()} | |
| if hasattr(self.model, "info"): | |
| d.update(self.model.info()) | |
| d["voices"] = len(self.voices.v) | |
| return d | |
| def close(self) -> None: | |
| c = getattr(self.model, "close", None) | |
| if c is not None: | |
| c() | |
| class _Placeholder: | |
| """Stands for a speaker clip whose row is given directly (stored voices): the prompt builder only needs to know | |
| that a speaker is present.""" | |
| shape = (1,) | |
| def __len__(self): | |
| return 1 | |
| def _cb(params: Dict[str, Any]) -> Dict[str, Any]: | |
| """Pop the non-model keys (callbacks, seed) out of ``params``.""" | |
| out = {} | |
| for k in ("on_text", "on_audio", "should_stop", "seed"): | |
| if k in params: | |
| out[k] = params.pop(k) | |
| return out | |