Text-to-Speech
Transformers
Safetensors
English
emotra_tts
feature-extraction
emotional-tts
emotion-transition
cosyvoice2
emotra-tts
custom_code
Instructions to use RetentionLabs/EmoTra-TTS with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use RetentionLabs/EmoTra-TTS with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-to-speech", model="RetentionLabs/EmoTra-TTS", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("RetentionLabs/EmoTra-TTS", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 16,171 Bytes
45b5d4f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | # Copyright 2026 The EmoTra-TTS Authors (LightSpeed, Tianchi Liu), Alibaba Inc. (CosyVoice, authors: Xiang Lyu,
# Zhihao Du), the HuggingFace Inc. team, TICTAP-11 and b-re-w. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Processor class for EmoTra-TTS."""
import json
import os
from pathlib import Path
from typing import Optional, Union
import numpy as np
from safetensors.torch import load_file, save_file
import torch
import torch.nn.functional as F
import torchaudio
from transformers.feature_extraction_utils import BatchFeature
from transformers.models.qwen2.tokenization_qwen2 import Qwen2Tokenizer
from transformers.processing_utils import ProcessorMixin
from .configuration_emotra_tts import CosyVoiceV2Config
from .feature_extraction_emotra_tts import CosyVoiceV2FeatureExtractor
from .modeling_emotra_tts import configure_speech_tokenizer_precision, CosyVoiceV2SpeechTokenizer
__all__ = [
"EmoTraTTSProcessor",
"PROCESSOR_CONFIG",
"SPEAKER_EMBEDDING_FILE",
"SPEECH_TOKENIZER_WEIGHTS",
"cast_floating_inputs",
]
PROCESSOR_CONFIG = "processor_config.json"
SPEECH_TOKENIZER_WEIGHTS = "speech_tokenizer.safetensors"
SPEAKER_EMBEDDING_FILE = "speaker_embedding.safetensors"
def cast_floating_inputs(module: torch.nn.Module, inputs: tuple) -> tuple:
r"""
Forward pre-hook that moves the floating point inputs of `module` to the device and dtype of its first parameter.
Args:
module (`torch.nn.Module`):
The hooked module.
inputs (`tuple`):
Positional inputs of the forward call.
Returns:
`tuple`: The inputs, with every floating point tensor cast.
"""
parameter = next(module.parameters())
return tuple(
value.to(device=parameter.device, dtype=parameter.dtype)
if isinstance(value, torch.Tensor) and value.is_floating_point()
else value
for value in inputs
)
class EmoTraTTSProcessor(ProcessorMixin):
r"""
Constructs the EmoTra-TTS processor. It wraps the CosyVoice2 text tokenizer (Qwen2 with the CosyVoice2 special
tokens), the 24 kHz mel spectrogram extractor of the flow matching model, the CosyVoice2 supervised semantic speech
tokenizer and the fixed speaker embedding the model was trained with.
EmoTra-TTS is fine tuned on one speaker and its flow matching model reads one fixed CAM++ embedding of a neutral
recording of that speaker. [`~EmoTraTTSProcessor.__call__`] returns that embedding with the text ids. The speech
tokenizer and the mel extractor are only needed to build training inputs.
Args:
tokenizer ([`Qwen2Tokenizer`]):
Text tokenizer.
feature_extractor ([`CosyVoiceV2FeatureExtractor`]):
Mel spectrogram extractor of the flow matching model.
speaker_embedding (`torch.Tensor` of shape `(speaker_embedding_dim,)`):
The fixed speaker embedding.
speech_tokenizer_path (`str`, *optional*):
Path of `speech_tokenizer.safetensors`, loaded on first use.
speech_token_mel_bins (`int`, *optional*, defaults to 128):
Number of mel bins of the log mel spectrogram the speech tokenizer consumes.
token_mel_ratio (`int`, *optional*, defaults to 2):
Number of mel frames per speech token.
"""
attributes: list[str] = []
speech_tokenizer_sampling_rate = 16000
def __init__(
self,
tokenizer: Qwen2Tokenizer,
feature_extractor: CosyVoiceV2FeatureExtractor,
speaker_embedding: torch.Tensor,
speech_tokenizer_path: Optional[str] = None,
speech_token_mel_bins: int = 128,
token_mel_ratio: int = 2,
**kwargs,
):
self.tokenizer = tokenizer
self.feature_extractor = feature_extractor
self.speaker_embedding = speaker_embedding
self.speech_tokenizer_path = speech_tokenizer_path
self.speech_token_mel_bins = speech_token_mel_bins
self.token_mel_ratio = token_mel_ratio
self._speech_token_features = None
self._speech_tokenizer = None
@classmethod
def get_attributes(cls) -> list[str]:
return []
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "EmoTraTTSProcessor":
r"""
Reads the processor from a local folder or a Hub repository: `processor_config.json`, the tokenizer files,
`speaker_embedding.safetensors` and, on first use, `speech_tokenizer.safetensors`.
Args:
pretrained_model_name_or_path (`str` or `os.PathLike`):
Folder or repository id.
kwargs:
`revision`, `cache_dir`, `token` and `local_files_only` go to the download; the rest overrides the
saved arguments.
Returns:
[`EmoTraTTSProcessor`]: The processor.
"""
from transformers.utils.hub import cached_file
download = {key: kwargs.pop(key) for key in ("revision", "cache_dir", "token", "local_files_only") if key in kwargs}
for key in ("trust_remote_code", "_from_auto", "_commit_hash", "subfolder"):
kwargs.pop(key, None)
source = str(pretrained_model_name_or_path)
saved = json.loads(Path(cached_file(source, PROCESSOR_CONFIG, **download)).read_text())
for key in ("processor_class", "auto_map"):
saved.pop(key, None)
feature_extractor = CosyVoiceV2FeatureExtractor(**saved.pop("feature_extractor"))
tokenizer = Qwen2Tokenizer.from_pretrained(source, **download)
speaker_embedding = load_file(cached_file(source, SPEAKER_EMBEDDING_FILE, **download))["speaker_embedding"]
speech_tokenizer_path = cached_file(source, SPEECH_TOKENIZER_WEIGHTS, **download)
return cls(
tokenizer=tokenizer,
feature_extractor=feature_extractor,
speaker_embedding=speaker_embedding,
speech_tokenizer_path=speech_tokenizer_path,
**{**saved, **kwargs},
)
def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs) -> list[str]:
r"""
Writes `processor_config.json`, the tokenizer files, `speaker_embedding.safetensors` and
`speech_tokenizer.safetensors`.
Args:
save_directory (`str` or `os.PathLike`):
Folder.
kwargs:
Unused.
Returns:
`list[str]`: The written files.
"""
save_directory = Path(save_directory)
save_directory.mkdir(parents=True, exist_ok=True)
feature_extractor = self.feature_extractor.to_dict()
for key in ("mel_filters", "feature_extractor_type", "processor_class"):
feature_extractor.pop(key, None)
content = {
"processor_class": type(self).__name__,
"feature_extractor": feature_extractor,
"speech_token_mel_bins": self.speech_token_mel_bins,
"token_mel_ratio": self.token_mel_ratio,
"auto_map": {"AutoProcessor": f"processing_emotra_tts.{type(self).__name__}"},
}
written = [str(save_directory / PROCESSOR_CONFIG)]
(save_directory / PROCESSOR_CONFIG).write_text(json.dumps(content, indent=2) + "\n")
written += list(self.tokenizer.save_pretrained(str(save_directory)))
save_file({"speaker_embedding": self.speaker_embedding.contiguous()}, str(save_directory / SPEAKER_EMBEDDING_FILE))
written.append(str(save_directory / SPEAKER_EMBEDDING_FILE))
save_file(
{name: tensor.detach().cpu().contiguous() for name, tensor in self.speech_tokenizer.state_dict().items()},
str(save_directory / SPEECH_TOKENIZER_WEIGHTS),
)
written.append(str(save_directory / SPEECH_TOKENIZER_WEIGHTS))
return written
@property
def speech_token_feature_extractor(self):
"""
Returns:
[`WhisperFeatureExtractor`]: The log mel extractor feeding the speech tokenizer.
"""
if self._speech_token_features is None:
from transformers import WhisperFeatureExtractor
self._speech_token_features = WhisperFeatureExtractor(
feature_size=self.speech_token_mel_bins, sampling_rate=self.speech_tokenizer_sampling_rate
)
return self._speech_token_features
@property
def speech_tokenizer(self) -> CosyVoiceV2SpeechTokenizer:
"""
Returns:
[`CosyVoiceV2SpeechTokenizer`]: The speech tokenizer in evaluation mode, BF16 except its finite scalar
quantizer, which stays FP32 (see [`configure_speech_tokenizer_precision`]).
"""
if self._speech_tokenizer is None:
tokenizer = CosyVoiceV2SpeechTokenizer(CosyVoiceV2Config())
configure_speech_tokenizer_precision(tokenizer)
tokenizer.load_state_dict(load_file(self.speech_tokenizer_path))
tokenizer.register_forward_pre_hook(cast_floating_inputs)
self._speech_tokenizer = tokenizer.eval()
return self._speech_tokenizer
def _resample(self, waveform: torch.Tensor, sampling_rate: Optional[int], target_rate: int) -> torch.Tensor:
waveform = waveform.reshape(1, -1).float()
if sampling_rate is not None and sampling_rate != target_rate:
waveform = torchaudio.functional.resample(waveform, sampling_rate, target_rate)
return waveform
def encode_speech_tokens(
self, audio: Union[np.ndarray, torch.Tensor], sampling_rate: Optional[int] = None
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Turns a waveform into supervised semantic speech tokens.
Args:
audio (`np.ndarray` or `torch.Tensor`):
Mono waveform.
sampling_rate (`int`, *optional*):
Rate of `audio`.
Returns:
`tuple(torch.Tensor)`: the speech token ids of shape `(1, speech_length)` and their length.
Raises:
ValueError: If the waveform is longer than thirty seconds.
"""
waveform = self._resample(
audio if isinstance(audio, torch.Tensor) else torch.as_tensor(np.asarray(audio)),
sampling_rate,
self.speech_tokenizer_sampling_rate,
)
if waveform.shape[1] / self.speech_tokenizer_sampling_rate > 30:
raise ValueError("the CosyVoice v1 speech tokenizer does not support audio longer than 30 seconds")
features = self.speech_token_feature_extractor(
waveform.squeeze(0).numpy(),
sampling_rate=self.speech_tokenizer_sampling_rate,
padding=False,
return_tensors="pt",
).input_features
lengths = torch.tensor([features.shape[2]], dtype=torch.int32)
with torch.no_grad():
speech_token_ids = self.speech_tokenizer(features, lengths).to(torch.int32)
return speech_token_ids, torch.tensor([speech_token_ids.shape[1]], dtype=torch.int32)
def speech_features(
self, waveforms: torch.Tensor, waveform_lengths: torch.Tensor, sampling_rate: int
) -> list[torch.Tensor]:
r"""
Extracts the flow-model log mel features from same-device waveform batches.
Args:
waveforms (`torch.Tensor`):
Padded mono waveforms of shape `(batch_size, num_samples)`.
waveform_lengths (`torch.Tensor`):
Unpadded sample counts of shape `(batch_size,)`.
sampling_rate (`int`):
Rate of every waveform. It must equal the feature extractor's sampling rate.
Returns:
`list[torch.Tensor]`: One `(num_frames, feature_size)` feature matrix per input waveform.
Raises:
ValueError: If the tensors have invalid shapes, a waveform is too short for the reflection padding, or the
sampling rate differs from the extractor rate.
"""
if waveforms.ndim != 2 or waveform_lengths.ndim != 1 or len(waveforms) != len(waveform_lengths):
raise ValueError("waveforms and waveform_lengths must have shapes (batch, samples) and (batch,)")
if waveforms.device != waveform_lengths.device:
raise ValueError("waveforms and waveform_lengths must share a device")
if sampling_rate != self.feature_extractor.sampling_rate:
raise ValueError("speech_features requires the feature extractor sampling rate")
if torch.any(waveform_lengths < 1) or torch.any(waveform_lengths > waveforms.shape[1]):
raise ValueError("waveform_lengths must select nonempty waveform prefixes")
padding = int((self.feature_extractor.n_fft - self.feature_extractor.hop_length) / 2)
if torch.any(waveform_lengths <= padding + 1):
raise ValueError(f"every waveform must be longer than {padding + 1} samples for the reflection padding")
padded = F.pad(waveforms.float(), (padding, padding))
for index, length in enumerate(waveform_lengths.tolist()):
padded[index, :padding] = waveforms[index, 1 : padding + 1].flip(0)
padded[index, padding + length : padding + length + padding] = waveforms[
index, length - padding - 1 : length - 1
].flip(0)
spectrogram = torch.stft(
padded,
self.feature_extractor.n_fft,
hop_length=self.feature_extractor.hop_length,
win_length=self.feature_extractor.win_length,
window=torch.hann_window(self.feature_extractor.win_length, device=waveforms.device),
center=False,
pad_mode="reflect",
normalized=False,
onesided=True,
return_complex=True,
)
spectrogram = torch.sqrt(torch.view_as_real(spectrogram).pow(2).sum(-1) + 1e-9)
mel_filters = torch.from_numpy(self.feature_extractor.mel_filters).to(spectrogram)
features = torch.log(torch.clamp(torch.matmul(mel_filters, spectrogram), min=1e-5)).transpose(1, 2)
frame_lengths = (waveform_lengths + 2 * padding - self.feature_extractor.n_fft) // self.feature_extractor.hop_length + 1
return [feature[:length] for feature, length in zip(features, frame_lengths.tolist(), strict=True)]
def _tokenize(self, text: Union[str, list[str]], prefix: str, **kwargs) -> dict:
encoded = self.tokenizer(
text, add_special_tokens=False, return_tensors="pt", **{"padding": True, "padding_side": "right", **kwargs}
)
attention_mask = encoded["attention_mask"]
return {
f"{prefix}input_ids": encoded["input_ids"].to(torch.int32),
f"{prefix}input_lengths": attention_mask.sum(dim=1).to(torch.int32),
f"{prefix}attention_mask": attention_mask,
}
def __call__(self, text: Union[str, list[str]], **kwargs) -> BatchFeature:
"""
Args:
text (`str` or `list[str]`):
Text to synthesize, or a batch of texts.
kwargs:
Forwarded to the text tokenizer.
Returns:
[`BatchFeature`]: `input_ids`, `input_lengths` and `attention_mask`, right padded, and
`speaker_embedding` of shape `(batch_size, speaker_embedding_dim)`, the fixed speaker embedding repeated
for every text.
"""
data = self._tokenize(text, "", **kwargs)
batch_size = data["input_ids"].shape[0]
data["speaker_embedding"] = self.speaker_embedding.reshape(1, -1).expand(batch_size, -1).clone()
return BatchFeature(data)
|