Spaces:
Running
Running
Add Supertonic 3 MLX Space
Browse filesFiles changed (7)
- .gitattributes+2-34
- README.md+15-6
- app.pyAdded+103
- requirements.txtAdded+8
- supertonic_mlx/__init__.pyAdded+5
- supertonic_mlx/onnx_graph.pyAdded+305
- supertonic_mlx/tts.pyAdded+262
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123*.npz filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text
12345678910111213---title: Supertonic 3emoji: 🌍colorFrom: redcolorTo: purplesdk: gradiosdk_version: 6.14.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122---title: Supertonic 3 MLXemoji: ⚡colorFrom: bluecolorTo: indigosdk: gradiosdk_version: 6.14.0app_file: app.pypinned: falselicense: mitshort_description: Supertonic 3 text-to-speech running with MLXmodels:- mlx-community/supertonic-3---# Supertonic 3 MLXThis Space runs the community MLX conversion of [`Supertone/supertonic-3`](https://huggingface.co/Supertone/supertonic-3).The original ONNX graphs are converted into JSON topology plus NPZ initializers and executed with MLX arrays. The runtime code is available in [`ailuntx/supertonic`](https://github.com/ailuntx/supertonic/tree/add-mlx-backend).The model is compact and runs on CPU fallback in Hugging Face Spaces. For best local performance, run on Apple Silicon with MLX.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103#!/usr/bin/env python3"""Gradio Space for Supertonic 3 MLX."""
from __future__ import annotations
import osfrom functools import lru_cache
import gradio as grimport numpy as npfrom huggingface_hub import snapshot_download
from supertonic_mlx import SupertonicMLX
os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
MODEL_ID = os.environ.get("SUPERTONIC_MLX_MODEL", "mlx-community/supertonic-3")LANGUAGES = [ "en", "ko", "ja", "ar", "bg", "cs", "da", "de", "el", "es", "et", "fi", "fr", "hi", "hr", "hu", "id", "it", "lt", "lv", "nl", "pl", "pt", "ro", "ru", "sk", "sl", "sv", "tr", "uk", "vi", "na",]VOICES = ["M1", "M2", "M3", "M4", "M5", "F1", "F2", "F3", "F4", "F5"]
@lru_cache(maxsize=1)def load_model() -> SupertonicMLX: model_dir = snapshot_download( repo_id=MODEL_ID, repo_type="model", allow_patterns=[ "graphs/*.json", "weights/*.npz", "voice_styles/*.json", "tts.json", "unicode_indexer.json", "mlx_manifest.json", ], ) return SupertonicMLX.from_pretrained(model_dir)
def synthesize(text: str, lang: str, voice: str, total_step: int, speed: float, seed: int): if not text or not text.strip(): return None, "Enter text to synthesize." try: tts = load_model() style = tts.get_voice_style(voice) wav, duration = tts.synthesize( text.strip(), lang, style, total_step=int(total_step), speed=float(speed), seed=int(seed), ) samples = int(tts.sample_rate * float(duration[0])) audio = np.clip(wav[0, :samples], -1.0, 1.0) audio_i16 = (audio * 32767).astype(np.int16) return (tts.sample_rate, audio_i16), f"Done. {samples / tts.sample_rate:.2f}s" except Exception as exc: return None, f"Error: {type(exc).__name__}: {exc}"
with gr.Blocks(title="Supertonic 3 MLX", theme=gr.themes.Soft()) as demo: gr.Markdown( """# Supertonic 3 MLX
Lightning-fast multilingual text-to-speech using the community MLX conversion.""" ) with gr.Row(): with gr.Column(scale=1): text = gr.Textbox( label="Text", lines=5, value="Supertonic 3 is running through an MLX graph runtime.", ) with gr.Row(): lang = gr.Dropdown(LANGUAGES, value="en", label="Language") voice = gr.Dropdown(VOICES, value="M1", label="Voice") with gr.Accordion("Generation Settings", open=False): total_step = gr.Slider(5, 12, value=8, step=1, label="Total Steps") speed = gr.Slider(0.7, 2.0, value=1.05, step=0.05, label="Speed") seed = gr.Number(value=0, precision=0, label="Seed") btn = gr.Button("Generate", variant="primary") with gr.Column(scale=1): audio = gr.Audio(label="Output", type="numpy") status = gr.Textbox(label="Status") btn.click(synthesize, [text, lang, voice, total_step, speed, seed], [audio, status]) gr.Examples( examples=[ ["Supertonic 3 is fast enough for local text to speech.", "en", "M1", 8, 1.05, 0], ["こんにちは。Supertonic 3 の MLX 変換をテストしています。", "ja", "F1", 8, 1.05, 1], ["오늘은 MLX로 실행되는 Supertonic 3를 테스트하고 있습니다.", "ko", "F2", 8, 1.05, 2], ], inputs=[text, lang, voice, total_step, speed, seed], )
if __name__ == "__main__": demo.queue(max_size=8).launch()12345678--index-url https://pypi.org/simple
gradio==6.14.0huggingface_hub>=1.0.0hf_transfermlx[cpu]>=0.31.0numpysoundfile12345"""MLX inference helpers for Supertonic 3."""
from supertonic_mlx.tts import Style, SupertonicMLX
__all__ = ["Style", "SupertonicMLX"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""Small ONNX graph executor for the Supertonic 3 MLX export.
The converter stores ONNX topology as JSON and all initializers/constants inNPZ files. This module executes the subset of ONNX ops used by Supertonic 3with MLX arrays."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
import mlx.core as mximport numpy as np
_NP_DTYPES = { 1: np.float32, 2: np.uint8, 3: np.int8, 4: np.uint16, 5: np.int16, 6: np.int32, 7: np.int64, 9: np.bool_, 10: np.float16, 11: np.float64,}
def _is_mx(x: Any) -> bool: return isinstance(x, mx.array)
def _np(x: Any) -> np.ndarray: if isinstance(x, np.ndarray): return x if isinstance(x, mx.array): return np.array(x) return np.array(x)
def _shape_tuple(x: Any) -> tuple[int, ...]: arr = _np(x).astype(np.int64).reshape(-1) return tuple(int(v) for v in arr)
def _axes(x: Any) -> tuple[int, ...]: return tuple(int(v) for v in _np(x).astype(np.int64).reshape(-1))
def _binary(a: Any, b: Any, fn_mx, fn_np): if _is_mx(a) or _is_mx(b): if not _is_mx(a): a = mx.array(a) if not _is_mx(b): b = mx.array(b) return fn_mx(a, b) return fn_np(a, b)
def _dtype_from_onnx(to: int): if to in (1, 10): return mx.float16 if to == 10 else mx.float32 if to == 7: return mx.int64 if to == 6: return mx.int32 if to == 9: return mx.bool_ return None
class MLXGraph: def __init__(self, graph_json: str | Path, weights_npz: str | Path): with open(graph_json, encoding="utf-8") as f: data = json.load(f) self.inputs = data["inputs"] self.outputs = data["outputs"] self.nodes = data["nodes"] self.weight_map = data["weight_map"] loaded = np.load(weights_npz) self.weights = { name: self._prepare_weight(loaded[key]) for name, key in self.weight_map.items() }
@staticmethod def _prepare_weight(arr: np.ndarray): if arr.dtype.kind in "f": return mx.array(arr) return arr
def __call__(self, **inputs): env: dict[str, Any] = dict(self.weights) for name, value in inputs.items(): if isinstance(value, mx.array): env[name] = value elif isinstance(value, np.ndarray) and value.dtype.kind in "f": env[name] = mx.array(value) else: env[name] = value
for node in self.nodes: op = node["op_type"] ins = [env[name] for name in node["inputs"] if name] attrs = node.get("attrs", {}) out_names = node["outputs"] res = self._run_node(op, ins, attrs) if len(out_names) == 1: env[out_names[0]] = res else: for name, value in zip(out_names, res): env[name] = value
return [env[name] for name in self.outputs]
def _run_node(self, op: str, ins: list[Any], attrs: dict[str, Any]): if op == "Add": return _binary(ins[0], ins[1], lambda a, b: a + b, np.add) if op == "Sub": return _binary(ins[0], ins[1], lambda a, b: a - b, np.subtract) if op == "Mul": return _binary(ins[0], ins[1], lambda a, b: a * b, np.multiply) if op == "Div": return _binary(ins[0], ins[1], lambda a, b: a / b, np.divide) if op == "Pow": return _binary(ins[0], ins[1], lambda a, b: mx.power(a, b), np.power) if op == "Equal": return _binary(ins[0], ins[1], lambda a, b: a == b, np.equal) if op == "Where": cond, x, y = ins if _is_mx(x) or _is_mx(y): return mx.where(mx.array(cond) if not _is_mx(cond) else cond, x, y) return np.where(cond, x, y) if op == "MatMul": return ins[0] @ ins[1] if op == "Gemm": a, b = ins[0], ins[1] if attrs.get("transA", 0): a = a.T if attrs.get("transB", 0): b = b.T y = (float(attrs.get("alpha", 1.0)) * (a @ b)) if len(ins) > 2: y = y + float(attrs.get("beta", 1.0)) * ins[2] return y if op == "Conv": x, w = ins[0], ins[1] bias = ins[2] if len(ins) > 2 else None stride = int(attrs.get("strides", [1])[0]) dilation = int(attrs.get("dilations", [1])[0]) group = int(attrs.get("group", 1)) pads = attrs.get("pads", [0, 0]) x = mx.transpose(x, (0, 2, 1)) if pads and (pads[0] or pads[1]): x = mx.pad(x, [(0, 0), (int(pads[0]), int(pads[1])), (0, 0)]) w = mx.transpose(w, (0, 2, 1)) y = mx.conv1d(x, w, stride=stride, padding=0, dilation=dilation, groups=group) y = mx.transpose(y, (0, 2, 1)) if bias is not None: y = y + bias.reshape(1, -1, 1) return y if op == "BatchNormalization": x, scale, bias, mean, var = ins[:5] eps = float(attrs.get("epsilon", 1e-5)) shape = [1] * len(x.shape) shape[1] = -1 return (x - mean.reshape(shape)) / mx.sqrt(var.reshape(shape) + eps) * scale.reshape(shape) + bias.reshape(shape) if op == "PRelu": x, slope = ins return mx.maximum(x, 0) + slope * mx.minimum(x, 0) if op == "Relu": return mx.maximum(ins[0], 0) if op == "Erf": return mx.erf(ins[0]) if op == "Exp": return mx.exp(ins[0]) if op == "Sin": return mx.sin(ins[0]) if op == "Cos": return mx.cos(ins[0]) if op == "Tanh": return mx.tanh(ins[0]) if op == "Softplus": return mx.logaddexp(ins[0], mx.array(0, dtype=ins[0].dtype)) if op == "Softmax": return mx.softmax(ins[0], axis=int(attrs.get("axis", -1))) if op == "LayerNormalization": x = ins[0] weight = ins[1] if len(ins) > 1 else None bias = ins[2] if len(ins) > 2 else None axis = int(attrs.get("axis", -1)) eps = float(attrs.get("epsilon", 1e-5)) if axis not in (-1, len(x.shape) - 1): raise NotImplementedError("LayerNormalization only supports last axis") return mx.fast.layer_norm(x, weight, bias, eps) if op == "Shape": return np.array(ins[0].shape, dtype=np.int64) if op == "Gather": axis = int(attrs.get("axis", 0)) data, idx = ins if _is_mx(data): return mx.take(data, mx.array(idx), axis=axis) return np.take(data, _np(idx), axis=axis) if op == "Concat": axis = int(attrs.get("axis", 0)) if any(_is_mx(x) for x in ins): return mx.concatenate([x if _is_mx(x) else mx.array(x) for x in ins], axis=axis) return np.concatenate([_np(x) for x in ins], axis=axis) if op == "Unsqueeze": x = ins[0] axes = sorted(_axes(ins[1])) for axis in axes: x = mx.expand_dims(x, axis) if _is_mx(x) else np.expand_dims(x, axis) return x if op == "Squeeze": x = ins[0] axes = _axes(ins[1]) if len(ins) > 1 else None return mx.squeeze(x, axis=axes) if _is_mx(x) else np.squeeze(x, axis=axes) if op == "Reshape": return mx.reshape(ins[0], _shape_tuple(ins[1])) if _is_mx(ins[0]) else np.reshape(ins[0], _shape_tuple(ins[1])) if op == "Transpose": perm = attrs.get("perm") return mx.transpose(ins[0], tuple(perm) if perm else None) if _is_mx(ins[0]) else np.transpose(ins[0], tuple(perm) if perm else None) if op == "Slice": data = ins[0] starts = _np(ins[1]).astype(np.int64).reshape(-1) ends = _np(ins[2]).astype(np.int64).reshape(-1) axes = _np(ins[3]).astype(np.int64).reshape(-1) if len(ins) > 3 else np.arange(len(starts)) steps = _np(ins[4]).astype(np.int64).reshape(-1) if len(ins) > 4 else np.ones_like(starts) slc = [slice(None)] * len(data.shape) for st, en, ax, step in zip(starts, ends, axes, steps): dim = data.shape[int(ax)] st = int(st + dim if st < 0 else st) en = int(en + dim if en < 0 else en) if en > dim: en = dim slc[int(ax)] = slice(st, en, int(step)) return data[tuple(slc)] if op == "Pad": x = ins[0] pads = _np(ins[1]).astype(np.int64).reshape(-1) rank = len(x.shape) pad_width = [(int(pads[i]), int(pads[i + rank])) for i in range(rank)] value = float(_np(ins[2]).reshape(-1)[0]) if len(ins) > 2 else 0.0 mode = attrs.get("mode", "constant") if isinstance(mode, bytes): mode = mode.decode() if _is_mx(x): return mx.pad(x, pad_width, mode="edge" if mode == "edge" else "constant", constant_values=value) return np.pad(x, pad_width, mode="edge" if mode == "edge" else "constant", constant_values=value) if op == "Cast": to = int(attrs["to"]) if _is_mx(ins[0]): dtype = _dtype_from_onnx(to) return ins[0].astype(dtype) if dtype is not None else ins[0] return _np(ins[0]).astype(_NP_DTYPES.get(to, _np(ins[0]).dtype)) if op == "ConstantOfShape": shape = _shape_tuple(ins[0]) value = attrs.get("value") if value is None: return mx.zeros(shape, dtype=mx.float32) arr = np.array(value["data"], dtype=np.dtype(value["dtype"])).reshape(value["shape"]) fill = arr.reshape(-1)[0] if arr.dtype.kind in "f": return mx.full(shape, float(fill), dtype=mx.float32) return np.full(shape, fill, dtype=arr.dtype) if op == "Clip": x = ins[0] lo = _np(ins[1]).reshape(-1)[0] if len(ins) > 1 else None hi = _np(ins[2]).reshape(-1)[0] if len(ins) > 2 else None if _is_mx(x): if lo is not None: x = mx.maximum(x, float(lo)) if hi is not None: x = mx.minimum(x, float(hi)) return x return np.clip(x, lo, hi) if op == "Expand": requested = list(_shape_tuple(ins[1])) input_shape = list(ins[0].shape) rank = max(len(requested), len(input_shape)) requested = [1] * (rank - len(requested)) + requested input_shape = [1] * (rank - len(input_shape)) + input_shape shape = tuple(max(int(a), int(b)) for a, b in zip(requested, input_shape)) return mx.broadcast_to(ins[0], shape) if _is_mx(ins[0]) else np.broadcast_to(ins[0], shape) if op == "Tile": reps = _shape_tuple(ins[1]) return mx.tile(ins[0], reps) if _is_mx(ins[0]) else np.tile(ins[0], reps) if op == "Split": axis = int(attrs.get("axis", 0)) split = _np(ins[1]).astype(np.int64).reshape(-1) if len(ins) > 1 else None if split is None: return mx.split(ins[0], len(split), axis=axis) if _is_mx(ins[0]) else np.array_split(ins[0], len(split), axis=axis) indices = np.cumsum(split)[:-1].tolist() return mx.split(ins[0], indices, axis=axis) if _is_mx(ins[0]) else np.split(ins[0], indices, axis=axis) if op == "ReduceSum": axes = _axes(ins[1]) if len(ins) > 1 else None keepdims = bool(attrs.get("keepdims", 1)) return mx.sum(ins[0], axis=axes, keepdims=keepdims) if op == "Reciprocal": return 1 / ins[0] raise NotImplementedError(f"Unsupported ONNX op: {op}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Supertonic 3 inference with MLX graph assets."""
from __future__ import annotations
import jsonimport refrom contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Pathfrom time import perf_counterfrom typing import Optionalfrom unicodedata import normalize
import mlx.core as mximport numpy as np
from supertonic_mlx.onnx_graph import MLXGraph
AVAILABLE_LANGS = [ "en", "ko", "ja", "ar", "bg", "cs", "da", "de", "el", "es", "et", "fi", "fr", "hi", "hr", "hu", "id", "it", "lt", "lv", "nl", "pl", "pt", "ro", "ru", "sk", "sl", "sv", "tr", "uk", "vi", "na",]
class UnicodeProcessor: def __init__(self, unicode_indexer_path: str | Path): with open(unicode_indexer_path, encoding="utf-8") as f: raw = json.load(f) if isinstance(raw, list): self.indexer = {i: int(v) for i, v in enumerate(raw)} else: self.indexer = {int(k): int(v) for k, v in raw.items()}
def _preprocess_text(self, text: str, lang: str) -> str: text = normalize("NFKD", text) emoji_pattern = re.compile( "[\U0001f600-\U0001f64f\U0001f300-\U0001f5ff\U0001f680-\U0001f6ff" "\U0001f700-\U0001f77f\U0001f780-\U0001f7ff\U0001f800-\U0001f8ff" "\U0001f900-\U0001f9ff\U0001fa00-\U0001fa6f\U0001fa70-\U0001faff" "\u2600-\u26ff\u2700-\u27bf\U0001f1e6-\U0001f1ff]+", flags=re.UNICODE, ) text = emoji_pattern.sub("", text) replacements = { "–": "-", "‑": "-", "—": "-", "_": " ", "\u201c": '"', "\u201d": '"', "\u2018": "'", "\u2019": "'", "´": "'", "`": "'", "[": " ", "]": " ", "|": " ", "/": " ", "#": " ", "→": " ", "←": " ", } for k, v in replacements.items(): text = text.replace(k, v) text = re.sub(r"[♥☆♡©\\]", "", text) for k, v in {"@": " at ", "e.g.,": "for example, ", "i.e.,": "that is, "}.items(): text = text.replace(k, v) for pat, repl in [ (r" ,", ","), (r" \.", "."), (r" !", "!"), (r" \?", "?"), (r" ;", ";"), (r" :", ":"), (r" '", "'"), ]: text = re.sub(pat, repl, text) while '""' in text: text = text.replace('""', '"') while "''" in text: text = text.replace("''", "'") while "``" in text: text = text.replace("``", "`") text = re.sub(r"\s+", " ", text).strip() if not re.search(r"[.!?;:,'\"')\]}…。」』】〉》›»]$", text): text += "." if lang not in AVAILABLE_LANGS: raise ValueError(f"Invalid language: {lang}") return f"<{lang}>{text}</{lang}>"
def __call__(self, text_list: list[str], lang_list: list[str]) -> tuple[np.ndarray, np.ndarray]: text_list = [self._preprocess_text(t, lang) for t, lang in zip(text_list, lang_list)] lengths = np.array([len(text) for text in text_list], dtype=np.int64) text_ids = np.zeros((len(text_list), lengths.max()), dtype=np.int64) for i, text in enumerate(text_list): ids = [self.indexer[ord(char)] for char in text] text_ids[i, : len(ids)] = np.array(ids, dtype=np.int64) return text_ids, length_to_mask(lengths)
@dataclassclass Style: ttl: np.ndarray dp: np.ndarray
class SupertonicMLX: def __init__(self, model_dir: str | Path): self.model_dir = Path(model_dir) with open(self.model_dir / "tts.json", encoding="utf-8") as f: self.cfgs = json.load(f) self.text_processor = UnicodeProcessor(self.model_dir / "unicode_indexer.json") self.duration_predictor = self._load_graph("duration_predictor") self.text_encoder = self._load_graph("text_encoder") self.vector_estimator = self._load_graph("vector_estimator") self.vocoder = self._load_graph("vocoder") self.sample_rate = int(self.cfgs["ae"]["sample_rate"]) self.base_chunk_size = int(self.cfgs["ae"]["base_chunk_size"]) self.chunk_compress_factor = int(self.cfgs["ttl"]["chunk_compress_factor"]) self.ldim = int(self.cfgs["ttl"]["latent_dim"])
def _load_graph(self, name: str) -> MLXGraph: return MLXGraph(self.model_dir / "graphs" / f"{name}.json", self.model_dir / "weights" / f"{name}.npz")
@classmethod def from_pretrained(cls, model_dir: str | Path) -> "SupertonicMLX": return cls(model_dir)
def load_voice_style(self, voice: str | Path | list[str | Path]) -> Style: paths = [voice] if isinstance(voice, (str, Path)) else voice first = json.load(open(paths[0], encoding="utf-8")) ttl_dims = first["style_ttl"]["dims"] dp_dims = first["style_dp"]["dims"] ttl = np.zeros([len(paths), ttl_dims[1], ttl_dims[2]], dtype=np.float32) dp = np.zeros([len(paths), dp_dims[1], dp_dims[2]], dtype=np.float32) for i, path in enumerate(paths): data = json.load(open(path, encoding="utf-8")) ttl[i] = np.array(data["style_ttl"]["data"], dtype=np.float32).reshape(ttl_dims[1], ttl_dims[2]) dp[i] = np.array(data["style_dp"]["data"], dtype=np.float32).reshape(dp_dims[1], dp_dims[2]) return Style(ttl=ttl, dp=dp)
def get_voice_style(self, voice_name: str = "M1") -> Style: return self.load_voice_style(self.model_dir / "voice_styles" / f"{voice_name}.json")
def sample_noisy_latent(self, duration: np.ndarray, seed: Optional[int] = None) -> tuple[np.ndarray, np.ndarray]: rng = np.random.default_rng(seed) bsz = len(duration) wav_len_max = duration.max() * self.sample_rate wav_lengths = (duration * self.sample_rate).astype(np.int64) chunk_size = self.base_chunk_size * self.chunk_compress_factor latent_len = ((wav_len_max + chunk_size - 1) / chunk_size).astype(np.int32) latent_dim = self.ldim * self.chunk_compress_factor noisy_latent = rng.standard_normal((bsz, latent_dim, latent_len)).astype(np.float32) latent_mask = get_latent_mask(wav_lengths, self.base_chunk_size, self.chunk_compress_factor) return noisy_latent * latent_mask, latent_mask
def _infer( self, text_list: list[str], lang_list: list[str], style: Style, total_step: int, speed: float = 1.05, seed: Optional[int] = None, ) -> tuple[np.ndarray, np.ndarray]: text_ids, text_mask = self.text_processor(text_list, lang_list) dur = np.array( self.duration_predictor(text_ids=text_ids, style_dp=style.dp, text_mask=text_mask)[0], dtype=np.float32, ) dur = dur / speed text_emb = self.text_encoder(text_ids=text_ids, style_ttl=style.ttl, text_mask=text_mask)[0] xt, latent_mask = self.sample_noisy_latent(dur, seed=seed) bsz = len(text_list) total_step_np = np.array([total_step] * bsz, dtype=np.float32) for step in range(total_step): current_step = np.array([step] * bsz, dtype=np.float32) xt = self.vector_estimator( noisy_latent=xt, text_emb=text_emb, style_ttl=style.ttl, text_mask=text_mask, latent_mask=latent_mask, current_step=current_step, total_step=total_step_np, )[0] mx.eval(xt) wav = self.vocoder(latent=xt)[0] return np.array(wav, dtype=np.float32), dur
def synthesize( self, text: str, lang: str, voice_style: Style, total_step: int = 8, speed: float = 1.05, seed: Optional[int] = None, silence_duration: float = 0.3, ) -> tuple[np.ndarray, np.ndarray]: if voice_style.ttl.shape[0] != 1: raise ValueError("Single-text synthesis requires a single voice style") max_len = 120 if lang in ("ko", "ja") else 300 wav_cat = None dur_cat = None for i, chunk in enumerate(chunk_text(text, max_len=max_len)): wav, dur = self._infer([chunk], [lang], voice_style, total_step, speed, None if seed is None else seed + i) if wav_cat is None: wav_cat = wav dur_cat = dur else: silence = np.zeros((1, int(silence_duration * self.sample_rate)), dtype=np.float32) wav_cat = np.concatenate([wav_cat, silence, wav], axis=1) dur_cat += dur + silence_duration assert wav_cat is not None and dur_cat is not None return wav_cat, dur_cat
def batch( self, text_list: list[str], lang_list: list[str], voice_style: Style, total_step: int = 8, speed: float = 1.05, seed: Optional[int] = None, ) -> tuple[np.ndarray, np.ndarray]: return self._infer(text_list, lang_list, voice_style, total_step, speed, seed)
def length_to_mask(lengths: np.ndarray, max_len: Optional[int] = None) -> np.ndarray: max_len = int(max_len or lengths.max()) ids = np.arange(0, max_len) mask = (ids < np.expand_dims(lengths, axis=1)).astype(np.float32) return mask.reshape(-1, 1, max_len)
def get_latent_mask(wav_lengths: np.ndarray, base_chunk_size: int, chunk_compress_factor: int) -> np.ndarray: latent_size = base_chunk_size * chunk_compress_factor latent_lengths = (wav_lengths + latent_size - 1) // latent_size return length_to_mask(latent_lengths)
def chunk_text(text: str, max_len: int = 300) -> list[str]: paragraphs = [p.strip() for p in re.split(r"\n\s*\n+", text.strip()) if p.strip()] chunks = [] for paragraph in paragraphs: pattern = r"(?<!Mr\.)(?<!Mrs\.)(?<!Ms\.)(?<!Dr\.)(?<!Prof\.)(?<!Sr\.)(?<!Jr\.)(?<!Ph\.D\.)(?<!etc\.)(?<!e\.g\.)(?<!i\.e\.)(?<!vs\.)(?<!Inc\.)(?<!Ltd\.)(?<!Co\.)(?<!Corp\.)(?<!St\.)(?<!Ave\.)(?<!Blvd\.)(?<!\b[A-Z]\.)(?<=[.!?])\s+" current = "" for sentence in re.split(pattern, paragraph): if len(current) + len(sentence) + 1 <= max_len: current += (" " if current else "") + sentence else: if current: chunks.append(current.strip()) current = sentence if current: chunks.append(current.strip()) return chunks or [text]
@contextmanagerdef timer(label: str): start = perf_counter() yield print(f"{label}: {perf_counter() - start:.3f}s").gitattributes+2-34
README.md+15-6
app.pyAdded+103
requirements.txtAdded+8
supertonic_mlx/__init__.pyAdded+5
supertonic_mlx/onnx_graph.pyAdded+305
supertonic_mlx/tts.pyAdded+262