Michael Hu commited on
Commit
7495571
·
1 Parent(s): 37aaac6

refactor tts module

Browse files
.vercel/project.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"projectName":"trae_5altap2j"}
dia/__init__.py DELETED
File without changes
dia/audio.py DELETED
@@ -1,185 +0,0 @@
1
- import typing as tp
2
-
3
- import torch
4
-
5
-
6
- def build_delay_indices(B: int, T: int, C: int, delay_pattern: tp.List[int]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
7
- """
8
- Precompute (t_idx_BxTxC, indices_BTCx3) so that out[t, c] = in[t - delay[c], c].
9
- Negative t_idx => BOS; t_idx >= T => PAD.
10
- """
11
- delay_arr = torch.tensor(delay_pattern, dtype=torch.int32)
12
-
13
- t_idx_BxT = torch.broadcast_to(
14
- torch.arange(T, dtype=torch.int32)[None, :],
15
- [B, T],
16
- )
17
- t_idx_BxTx1 = t_idx_BxT[..., None]
18
- t_idx_BxTxC = t_idx_BxTx1 - delay_arr.view(1, 1, C)
19
-
20
- b_idx_BxTxC = torch.broadcast_to(
21
- torch.arange(B, dtype=torch.int32).view(B, 1, 1),
22
- [B, T, C],
23
- )
24
- c_idx_BxTxC = torch.broadcast_to(
25
- torch.arange(C, dtype=torch.int32).view(1, 1, C),
26
- [B, T, C],
27
- )
28
-
29
- # We must clamp time indices to [0..T-1] so gather_nd equivalent won't fail
30
- t_clamped_BxTxC = torch.clamp(t_idx_BxTxC, 0, T - 1)
31
-
32
- indices_BTCx3 = torch.stack(
33
- [
34
- b_idx_BxTxC.reshape(-1),
35
- t_clamped_BxTxC.reshape(-1),
36
- c_idx_BxTxC.reshape(-1),
37
- ],
38
- dim=1,
39
- ).long() # Ensure indices are long type for indexing
40
-
41
- return t_idx_BxTxC, indices_BTCx3
42
-
43
-
44
- def apply_audio_delay(
45
- audio_BxTxC: torch.Tensor,
46
- pad_value: int,
47
- bos_value: int,
48
- precomp: tp.Tuple[torch.Tensor, torch.Tensor],
49
- ) -> torch.Tensor:
50
- """
51
- Applies the delay pattern to batched audio tokens using precomputed indices,
52
- inserting BOS where t_idx < 0 and PAD where t_idx >= T.
53
-
54
- Args:
55
- audio_BxTxC: [B, T, C] int16 audio tokens (or int32/float)
56
- pad_value: the padding token
57
- bos_value: the BOS token
58
- precomp: (t_idx_BxTxC, indices_BTCx3) from build_delay_indices
59
-
60
- Returns:
61
- result_BxTxC: [B, T, C] delayed audio tokens
62
- """
63
- device = audio_BxTxC.device # Get device from input tensor
64
- t_idx_BxTxC, indices_BTCx3 = precomp
65
- t_idx_BxTxC = t_idx_BxTxC.to(device) # Move precomputed indices to device
66
- indices_BTCx3 = indices_BTCx3.to(device)
67
-
68
- # Equivalent of tf.gather_nd using advanced indexing
69
- # Ensure indices are long type if not already (build_delay_indices should handle this)
70
- gathered_flat = audio_BxTxC[indices_BTCx3[:, 0], indices_BTCx3[:, 1], indices_BTCx3[:, 2]]
71
- gathered_BxTxC = gathered_flat.view(audio_BxTxC.shape)
72
-
73
- # Create masks on the correct device
74
- mask_bos = t_idx_BxTxC < 0 # => place bos_value
75
- mask_pad = t_idx_BxTxC >= audio_BxTxC.shape[1] # => place pad_value
76
-
77
- # Create scalar tensors on the correct device
78
- bos_tensor = torch.tensor(bos_value, dtype=audio_BxTxC.dtype, device=device)
79
- pad_tensor = torch.tensor(pad_value, dtype=audio_BxTxC.dtype, device=device)
80
-
81
- # If mask_bos, BOS; else if mask_pad, PAD; else original gather
82
- # All tensors should now be on the same device
83
- result_BxTxC = torch.where(mask_bos, bos_tensor, torch.where(mask_pad, pad_tensor, gathered_BxTxC))
84
-
85
- return result_BxTxC
86
-
87
-
88
- def build_revert_indices(B: int, T: int, C: int, delay_pattern: tp.List[int]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
89
- """
90
- Precompute indices for the revert operation using PyTorch.
91
-
92
- Returns:
93
- A tuple (t_idx_BxTxC, indices_BTCx3) where:
94
- - t_idx_BxTxC is a tensor of shape [B, T, C] computed as time indices plus the delay.
95
- - indices_BTCx3 is a tensor of shape [B*T*C, 3] used for gathering, computed from:
96
- batch indices, clamped time indices, and channel indices.
97
- """
98
- # Use default device unless specified otherwise; assumes inputs might define device later
99
- device = None # Or determine dynamically if needed, e.g., from a model parameter
100
-
101
- delay_arr = torch.tensor(delay_pattern, dtype=torch.int32, device=device)
102
-
103
- t_idx_BT1 = torch.broadcast_to(torch.arange(T, device=device).unsqueeze(0), [B, T])
104
- t_idx_BT1 = t_idx_BT1.unsqueeze(-1)
105
-
106
- t_idx_BxTxC = torch.minimum(
107
- t_idx_BT1 + delay_arr.view(1, 1, C),
108
- torch.tensor(T - 1, device=device),
109
- )
110
- b_idx_BxTxC = torch.broadcast_to(torch.arange(B, device=device).view(B, 1, 1), [B, T, C])
111
- c_idx_BxTxC = torch.broadcast_to(torch.arange(C, device=device).view(1, 1, C), [B, T, C])
112
-
113
- indices_BTCx3 = torch.stack(
114
- [
115
- b_idx_BxTxC.reshape(-1),
116
- t_idx_BxTxC.reshape(-1),
117
- c_idx_BxTxC.reshape(-1),
118
- ],
119
- axis=1,
120
- ).long() # Ensure indices are long type
121
-
122
- return t_idx_BxTxC, indices_BTCx3
123
-
124
-
125
- def revert_audio_delay(
126
- audio_BxTxC: torch.Tensor,
127
- pad_value: int,
128
- precomp: tp.Tuple[torch.Tensor, torch.Tensor],
129
- T: int,
130
- ) -> torch.Tensor:
131
- """
132
- Reverts a delay pattern from batched audio tokens using precomputed indices (PyTorch version).
133
-
134
- Args:
135
- audio_BxTxC: Input delayed audio tensor
136
- pad_value: Padding value for out-of-bounds indices
137
- precomp: Precomputed revert indices tuple containing:
138
- - t_idx_BxTxC: Time offset indices tensor
139
- - indices_BTCx3: Gather indices tensor for original audio
140
- T: Original sequence length before padding
141
-
142
- Returns:
143
- Reverted audio tensor with same shape as input
144
- """
145
- t_idx_BxTxC, indices_BTCx3 = precomp
146
- device = audio_BxTxC.device # Get device from input tensor
147
-
148
- # Move precomputed indices to the same device as audio_BxTxC if they aren't already
149
- t_idx_BxTxC = t_idx_BxTxC.to(device)
150
- indices_BTCx3 = indices_BTCx3.to(device)
151
-
152
- # Using PyTorch advanced indexing (equivalent to tf.gather_nd or np equivalent)
153
- gathered_flat = audio_BxTxC[indices_BTCx3[:, 0], indices_BTCx3[:, 1], indices_BTCx3[:, 2]]
154
- gathered_BxTxC = gathered_flat.view(audio_BxTxC.size()) # Use .size() for robust reshaping
155
-
156
- # Create pad_tensor on the correct device
157
- pad_tensor = torch.tensor(pad_value, dtype=audio_BxTxC.dtype, device=device)
158
- # Create T tensor on the correct device for comparison
159
- T_tensor = torch.tensor(T, device=device)
160
-
161
- result_BxTxC = torch.where(t_idx_BxTxC >= T_tensor, pad_tensor, gathered_BxTxC) # Changed np.where to torch.where
162
-
163
- return result_BxTxC
164
-
165
-
166
- @torch.no_grad()
167
- @torch.inference_mode()
168
- def decode(
169
- model,
170
- audio_codes,
171
- ):
172
- """
173
- Decodes the given frames into an output audio waveform
174
- """
175
- if len(audio_codes) != 1:
176
- raise ValueError(f"Expected one frame, got {len(audio_codes)}")
177
-
178
- try:
179
- audio_values = model.quantizer.from_codes(audio_codes)
180
- audio_values = model.decode(audio_values[0])
181
-
182
- return audio_values
183
- except Exception as e:
184
- print(f"Error in decode method: {str(e)}")
185
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dia/config.py DELETED
@@ -1,187 +0,0 @@
1
- """Configuration management module for the Dia model.
2
-
3
- This module provides comprehensive configuration management for the Dia model,
4
- utilizing Pydantic for validation. It defines configurations for data processing,
5
- model architecture (encoder and decoder), and training settings.
6
-
7
- Key components:
8
- - DataConfig: Parameters for data loading and preprocessing.
9
- - EncoderConfig: Architecture details for the encoder module.
10
- - DecoderConfig: Architecture details for the decoder module.
11
- - ModelConfig: Combined model architecture settings.
12
- - TrainingConfig: Training hyperparameters and settings.
13
- - DiaConfig: Master configuration combining all components.
14
- """
15
-
16
- import os
17
- from typing import Annotated
18
-
19
- from pydantic import BaseModel, BeforeValidator, Field
20
-
21
-
22
- class DataConfig(BaseModel, frozen=True):
23
- """Configuration for data loading and preprocessing.
24
-
25
- Attributes:
26
- text_length: Maximum length of text sequences (must be multiple of 128).
27
- audio_length: Maximum length of audio sequences (must be multiple of 128).
28
- channels: Number of audio channels.
29
- text_pad_value: Value used for padding text sequences.
30
- audio_eos_value: Value representing the end of audio sequences.
31
- audio_bos_value: Value representing the beginning of audio sequences.
32
- audio_pad_value: Value used for padding audio sequences.
33
- delay_pattern: List of delay values for each audio channel.
34
- """
35
-
36
- text_length: Annotated[int, BeforeValidator(lambda x: (x + 127) // 128 * 128)] = Field(gt=0, multiple_of=128)
37
- audio_length: Annotated[int, BeforeValidator(lambda x: (x + 127) // 128 * 128)] = Field(gt=0, multiple_of=128)
38
- channels: int = Field(default=9, gt=0, multiple_of=1)
39
- text_pad_value: int = Field(default=0)
40
- audio_eos_value: int = Field(default=1024)
41
- audio_pad_value: int = Field(default=1025)
42
- audio_bos_value: int = Field(default=1026)
43
- delay_pattern: list[Annotated[int, Field(ge=0)]] = Field(default_factory=lambda: [0, 8, 9, 10, 11, 12, 13, 14, 15])
44
-
45
- def __hash__(self) -> int:
46
- """Generate a hash based on all fields of the config."""
47
- return hash(
48
- (
49
- self.text_length,
50
- self.audio_length,
51
- self.channels,
52
- self.text_pad_value,
53
- self.audio_pad_value,
54
- self.audio_bos_value,
55
- self.audio_eos_value,
56
- tuple(self.delay_pattern),
57
- )
58
- )
59
-
60
-
61
- class EncoderConfig(BaseModel, frozen=True):
62
- """Configuration for the encoder component of the Dia model.
63
-
64
- Attributes:
65
- n_layer: Number of transformer layers.
66
- n_embd: Embedding dimension.
67
- n_hidden: Hidden dimension size in the MLP layers.
68
- n_head: Number of attention heads.
69
- head_dim: Dimension per attention head.
70
- """
71
-
72
- n_layer: int = Field(gt=0)
73
- n_embd: int = Field(gt=0)
74
- n_hidden: int = Field(gt=0)
75
- n_head: int = Field(gt=0)
76
- head_dim: int = Field(gt=0)
77
-
78
-
79
- class DecoderConfig(BaseModel, frozen=True):
80
- """Configuration for the decoder component of the Dia model.
81
-
82
- Attributes:
83
- n_layer: Number of transformer layers.
84
- n_embd: Embedding dimension.
85
- n_hidden: Hidden dimension size in the MLP layers.
86
- gqa_query_heads: Number of query heads for grouped-query self-attention.
87
- kv_heads: Number of key/value heads for grouped-query self-attention.
88
- gqa_head_dim: Dimension per query head for grouped-query self-attention.
89
- cross_query_heads: Number of query heads for cross-attention.
90
- cross_head_dim: Dimension per cross-attention head.
91
- """
92
-
93
- n_layer: int = Field(gt=0)
94
- n_embd: int = Field(gt=0)
95
- n_hidden: int = Field(gt=0)
96
- gqa_query_heads: int = Field(gt=0)
97
- kv_heads: int = Field(gt=0)
98
- gqa_head_dim: int = Field(gt=0)
99
- cross_query_heads: int = Field(gt=0)
100
- cross_head_dim: int = Field(gt=0)
101
-
102
-
103
- class ModelConfig(BaseModel, frozen=True):
104
- """Main configuration container for the Dia model architecture.
105
-
106
- Attributes:
107
- encoder: Configuration for the encoder component.
108
- decoder: Configuration for the decoder component.
109
- src_vocab_size: Size of the source (text) vocabulary.
110
- tgt_vocab_size: Size of the target (audio code) vocabulary.
111
- dropout: Dropout probability applied within the model.
112
- normalization_layer_epsilon: Epsilon value for normalization layers (e.g., LayerNorm).
113
- weight_dtype: Data type for model weights (e.g., "float32", "bfloat16").
114
- rope_min_timescale: Minimum timescale for Rotary Positional Embeddings (RoPE).
115
- rope_max_timescale: Maximum timescale for Rotary Positional Embeddings (RoPE).
116
- """
117
-
118
- encoder: EncoderConfig
119
- decoder: DecoderConfig
120
- src_vocab_size: int = Field(default=128, gt=0)
121
- tgt_vocab_size: int = Field(default=1028, gt=0)
122
- dropout: float = Field(default=0.0, ge=0.0, lt=1.0)
123
- normalization_layer_epsilon: float = Field(default=1.0e-5, ge=0.0)
124
- weight_dtype: str = Field(default="float32", description="Weight precision")
125
- rope_min_timescale: int = Field(default=1, description="Timescale For global Attention")
126
- rope_max_timescale: int = Field(default=10_000, description="Timescale For global Attention")
127
-
128
-
129
- class TrainingConfig(BaseModel, frozen=True):
130
- pass
131
-
132
-
133
- class DiaConfig(BaseModel, frozen=True):
134
- """Master configuration for the Dia model.
135
-
136
- Combines all sub-configurations into a single validated object.
137
-
138
- Attributes:
139
- version: Configuration version string.
140
- model: Model architecture configuration.
141
- training: Training process configuration (precision settings).
142
- data: Data loading and processing configuration.
143
- """
144
-
145
- version: str = Field(default="1.0")
146
- model: ModelConfig
147
- # TODO: remove training. this is just for backward compatibility
148
- training: TrainingConfig | None = Field(default=None)
149
- data: DataConfig
150
-
151
- def save(self, path: str) -> None:
152
- """Save the current configuration instance to a JSON file.
153
-
154
- Ensures the parent directory exists and the file has a .json extension.
155
-
156
- Args:
157
- path: The target file path to save the configuration.
158
-
159
- Raises:
160
- ValueError: If the path is not a file with a .json extension.
161
- """
162
- os.makedirs(os.path.dirname(path), exist_ok=True)
163
- config_json = self.model_dump_json(indent=2)
164
- with open(path, "w") as f:
165
- f.write(config_json)
166
-
167
- @classmethod
168
- def load(cls, path: str) -> "DiaConfig | None":
169
- """Load and validate a Dia configuration from a JSON file.
170
-
171
- Args:
172
- path: The path to the configuration file.
173
-
174
- Returns:
175
- A validated DiaConfig instance if the file exists and is valid,
176
- otherwise None if the file is not found.
177
-
178
- Raises:
179
- ValueError: If the path does not point to an existing .json file.
180
- pydantic.ValidationError: If the JSON content fails validation against the DiaConfig schema.
181
- """
182
- try:
183
- with open(path, "r") as f:
184
- content = f.read()
185
- return cls.model_validate_json(content)
186
- except FileNotFoundError:
187
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dia/layers.py DELETED
@@ -1,624 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.nn.functional as F
4
- from huggingface_hub import PyTorchModelHubMixin
5
- from torch import Tensor
6
- from torch.nn import RMSNorm
7
-
8
- from .config import DiaConfig
9
- from .state import DecoderInferenceState, EncoderInferenceState, KVCache
10
-
11
-
12
- def _normalize_axes(axes: tuple[int, ...], ndim: int) -> tuple[int, ...]:
13
- return tuple(ax if ax >= 0 else ndim + ax for ax in axes)
14
-
15
-
16
- class DenseGeneral(nn.Module):
17
- """
18
- PyTorch equivalent of flax.linen.DenseGeneral with shapes defined at init.
19
-
20
- Stores weights (`kernel`) in the same layout as Jax and uses torch.tensordot
21
- for the generalized matrix multiplication. Weight/bias shapes are calculated
22
- and parameters created during initialization based on config.
23
- `load_weights` validates shapes and copies data.
24
-
25
- Attributes:
26
- axis (Tuple[int, ...]): Input axis or axes to contract.
27
- in_shapes (Tuple[int, ...]): Sizes of the input dimensions specified by `axis`.
28
- out_features (Tuple[int, ...]): Shape of the output features (non-contracted dims).
29
- use_bias (bool): Whether to add a bias term.
30
- weight (nn.Parameter): The kernel parameter.
31
- bias (Optional[nn.Parameter]): The bias parameter (if use_bias=True).
32
- """
33
-
34
- def __init__(
35
- self,
36
- in_shapes: tuple[int, ...],
37
- out_features: tuple[int, ...],
38
- axis: tuple[int, ...] = (-1,),
39
- weight_dtype: torch.dtype | None = None,
40
- device: torch.device | None = None,
41
- ):
42
- super().__init__()
43
- self.in_shapes = in_shapes
44
- self.out_features = out_features
45
- self.axis = axis
46
- self.kernel_shape = self.in_shapes + self.out_features
47
-
48
- factory_kwargs = {"device": device, "dtype": weight_dtype}
49
- self.weight = nn.Parameter(torch.empty(self.kernel_shape, **factory_kwargs))
50
-
51
- def forward(self, inputs: Tensor) -> Tensor:
52
- norm_axis = _normalize_axes(self.axis, inputs.ndim)
53
- kernel_contract_axes = tuple(range(len(norm_axis)))
54
-
55
- output = torch.tensordot(
56
- inputs.to(self.weight.dtype),
57
- self.weight,
58
- dims=(norm_axis, kernel_contract_axes),
59
- ).to(inputs.dtype)
60
- return output
61
-
62
-
63
- class MlpBlock(nn.Module):
64
- """MLP block using DenseGeneral."""
65
-
66
- def __init__(self, embed_dim: int, intermediate_dim: int, compute_dtype: torch.dtype):
67
- super().__init__()
68
- self.dtype = compute_dtype
69
-
70
- self.wi_fused = DenseGeneral(
71
- in_shapes=(embed_dim,),
72
- out_features=(2, intermediate_dim),
73
- axis=(-1,),
74
- weight_dtype=compute_dtype,
75
- )
76
-
77
- self.wo = DenseGeneral(
78
- in_shapes=(intermediate_dim,),
79
- out_features=(embed_dim,),
80
- axis=(-1,),
81
- weight_dtype=compute_dtype,
82
- )
83
-
84
- def forward(self, x: torch.Tensor) -> torch.Tensor:
85
- """Forward pass."""
86
- fused_x = self.wi_fused(x)
87
-
88
- gate = fused_x[..., 0, :]
89
- up = fused_x[..., 1, :]
90
-
91
- hidden = torch.mul(F.silu(gate), up).to(self.dtype)
92
-
93
- output = self.wo(hidden)
94
- return output
95
-
96
-
97
- class RotaryEmbedding(nn.Module):
98
- """Rotary Position Embedding (RoPE) implementation in PyTorch."""
99
-
100
- def __init__(
101
- self,
102
- embedding_dims: int,
103
- min_timescale: int = 1,
104
- max_timescale: int = 10000,
105
- dtype: torch.dtype = torch.float32,
106
- ):
107
- super().__init__()
108
- if embedding_dims % 2 != 0:
109
- raise ValueError("Embedding dim must be even for RoPE.")
110
- self.embedding_dims = embedding_dims
111
- self.min_timescale = min_timescale
112
- self.max_timescale = max_timescale
113
- self.compute_dtype = dtype
114
-
115
- half_embedding_dim = embedding_dims // 2
116
- fraction = (2.0 * torch.arange(0, half_embedding_dim)) / embedding_dims
117
- timescale = (self.min_timescale * (self.max_timescale / self.min_timescale) ** fraction).to(torch.float32)
118
- self.register_buffer("timescale", timescale, persistent=False)
119
-
120
- def forward(self, inputs: torch.Tensor, position: torch.Tensor):
121
- """Applies RoPE."""
122
- position = position.unsqueeze(-1).unsqueeze(-1)
123
- sinusoid_inp = position / self.timescale
124
- sin = torch.sin(sinusoid_inp)
125
- cos = torch.cos(sinusoid_inp)
126
- first_half, second_half = torch.chunk(inputs.to(torch.float32), 2, dim=-1)
127
- first_part = first_half * cos - second_half * sin
128
- second_part = second_half * cos + first_half * sin
129
- return torch.cat((first_part.to(self.compute_dtype), second_part.to(self.compute_dtype)), dim=-1)
130
-
131
-
132
- class Attention(nn.Module):
133
- """Attention using DenseGeneral."""
134
-
135
- def __init__(
136
- self,
137
- config: DiaConfig,
138
- q_embed_dim: int,
139
- kv_embed_dim: int,
140
- num_query_heads: int,
141
- num_kv_heads: int,
142
- head_dim: int,
143
- compute_dtype: torch.dtype,
144
- is_cross_attn: bool = False,
145
- out_embed_dim: int | None = None,
146
- ):
147
- super().__init__()
148
- self.num_query_heads = num_query_heads
149
- self.num_kv_heads = num_kv_heads
150
- self.head_dim = head_dim
151
- self.is_cross_attn = is_cross_attn
152
- self.output_dim = out_embed_dim if out_embed_dim is not None else q_embed_dim
153
- self.projected_query_dim = num_query_heads * head_dim
154
- if num_query_heads % num_kv_heads != 0:
155
- raise ValueError(f"num_query_heads ({num_query_heads}) must be divisible by num_kv_heads ({num_kv_heads})")
156
- self.num_gqa_groups = num_query_heads // num_kv_heads
157
-
158
- # --- Projection Layers using DenseGeneral ---
159
- self.q_proj = DenseGeneral(
160
- in_shapes=(q_embed_dim,),
161
- out_features=(num_query_heads, head_dim),
162
- axis=(-1,),
163
- weight_dtype=compute_dtype,
164
- )
165
- self.k_proj = DenseGeneral(
166
- in_shapes=(kv_embed_dim,),
167
- out_features=(num_kv_heads, head_dim),
168
- axis=(-1,),
169
- weight_dtype=compute_dtype,
170
- )
171
- self.v_proj = DenseGeneral(
172
- in_shapes=(kv_embed_dim,),
173
- out_features=(num_kv_heads, head_dim),
174
- axis=(-1,),
175
- weight_dtype=compute_dtype,
176
- )
177
- self.o_proj = DenseGeneral(
178
- in_shapes=(num_query_heads, head_dim),
179
- out_features=(self.output_dim,),
180
- axis=(-2, -1),
181
- weight_dtype=compute_dtype,
182
- )
183
-
184
- # --- Rotary Embedding ---
185
- self.rotary_emb = RotaryEmbedding(
186
- embedding_dims=self.head_dim,
187
- min_timescale=config.model.rope_min_timescale,
188
- max_timescale=config.model.rope_max_timescale,
189
- dtype=compute_dtype,
190
- )
191
-
192
- def forward(
193
- self,
194
- Xq: torch.Tensor, # (B, T, D) T = 1 in AR generation
195
- Xkv: torch.Tensor, # (B, S, E) S = 1 in AR generation
196
- q_positions: torch.Tensor, # (B, T)
197
- kv_positions: torch.Tensor | None = None, # (B, S)
198
- attn_mask: torch.Tensor | None = None, # None in Decoder Self Attention, Valid mask in Others
199
- cache: KVCache | None = None, # None in Encoder, KVCache in Decoder
200
- prefill: bool = False,
201
- is_causal: bool = False,
202
- ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
203
- """
204
- Performs attention calculation with optional KV caching.
205
-
206
- Args:
207
- Xq: Query tensor (B, T, D). T=1 during single-step decoding.
208
- Xkv: Key/Value source tensor (B, S, E). S=1 during single-step decoding for self-attn.
209
- q_positions: Positions for queries (B, T).
210
- kv_positions: Positions for keys/values (B, S). If None, uses q_positions.
211
- attn_mask: Attention mask.
212
- cache: KVCache.
213
- prefill: If True, use prefill mode.
214
-
215
- Returns:
216
- A tuple containing:
217
- - output: The attention output tensor (B, T, output_dim).
218
- - present_kv: The K/V state to be cached for the next step ((B, N, S_new, H), (B, N, S_new, H)). For self-attn, S_new = S_past + S. For cross-attn, S_new = S_kv.
219
- """
220
- if kv_positions is None:
221
- kv_positions = q_positions
222
- original_dtype = Xq.dtype
223
-
224
- Xq_BxTxNxH = self.q_proj(Xq)
225
- Xq_BxTxNxH = self.rotary_emb(Xq_BxTxNxH, position=q_positions)
226
- Xq_BxNxTxH = Xq_BxTxNxH.transpose(1, 2)
227
-
228
- attn_k: torch.Tensor | None = None
229
- attn_v: torch.Tensor | None = None
230
-
231
- if self.is_cross_attn:
232
- attn_k, attn_v = cache.k, cache.v
233
- else:
234
- Xk_BxSxKxH = self.k_proj(Xkv) # (B, S, K, H)
235
- Xv_BxSxKxH = self.v_proj(Xkv) # (B, S, K, H)
236
- Xk_BxSxKxH = self.rotary_emb(Xk_BxSxKxH, position=kv_positions) # (B, S, K, H)
237
-
238
- Xk_BxKxSxH = Xk_BxSxKxH.transpose(1, 2) # (B, K, S, H)
239
- Xv_BxKxSxH = Xv_BxSxKxH.transpose(1, 2) # (B, K, S, H)
240
-
241
- if cache is None:
242
- attn_k = Xk_BxKxSxH
243
- attn_v = Xv_BxKxSxH
244
- else:
245
- if prefill:
246
- attn_k, attn_v = Xk_BxKxSxH, Xv_BxKxSxH
247
- cache.prefill(attn_k, attn_v)
248
- else:
249
- attn_k, attn_v = cache.update(Xk_BxKxSxH, Xv_BxKxSxH)
250
-
251
- attn_output = F.scaled_dot_product_attention(
252
- Xq_BxNxTxH,
253
- attn_k,
254
- attn_v,
255
- attn_mask=attn_mask,
256
- scale=1.0,
257
- enable_gqa=self.num_gqa_groups > 1,
258
- is_causal=is_causal,
259
- )
260
-
261
- attn_output = attn_output.transpose(1, 2).contiguous() # (B, T, N, H)
262
- output = self.o_proj(attn_output)
263
-
264
- return output.to(original_dtype)
265
-
266
-
267
- class EncoderLayer(nn.Module):
268
- """Transformer Encoder Layer using DenseGeneral."""
269
-
270
- def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
271
- super().__init__()
272
- self.config = config
273
- model_config = config.model
274
- enc_config = config.model.encoder
275
- embed_dim = enc_config.n_embd
276
- self.compute_dtype = compute_dtype
277
-
278
- self.pre_sa_norm = RMSNorm(
279
- embed_dim,
280
- eps=model_config.normalization_layer_epsilon,
281
- dtype=torch.float32,
282
- )
283
- self.self_attention = Attention(
284
- config,
285
- q_embed_dim=embed_dim,
286
- kv_embed_dim=embed_dim,
287
- num_query_heads=enc_config.n_head,
288
- num_kv_heads=enc_config.n_head,
289
- head_dim=enc_config.head_dim,
290
- compute_dtype=compute_dtype,
291
- is_cross_attn=False,
292
- out_embed_dim=embed_dim,
293
- )
294
- self.post_sa_norm = RMSNorm(
295
- embed_dim,
296
- eps=model_config.normalization_layer_epsilon,
297
- dtype=torch.float32,
298
- )
299
- self.mlp = MlpBlock(embed_dim=embed_dim, intermediate_dim=enc_config.n_hidden, compute_dtype=compute_dtype)
300
-
301
- def forward(
302
- self,
303
- x: torch.Tensor,
304
- state: EncoderInferenceState,
305
- ) -> torch.Tensor:
306
- residual = x
307
- x_norm = self.pre_sa_norm(x).to(self.compute_dtype)
308
-
309
- sa_out = self.self_attention(
310
- Xq=x_norm,
311
- Xkv=x_norm,
312
- q_positions=state.positions,
313
- kv_positions=state.positions,
314
- attn_mask=state.attn_mask,
315
- )
316
- x = residual + sa_out
317
-
318
- residual = x
319
- x_norm = self.post_sa_norm(x).to(self.compute_dtype)
320
- mlp_out = self.mlp(x_norm)
321
- x = residual + mlp_out
322
-
323
- return x
324
-
325
-
326
- class Encoder(nn.Module):
327
- """Transformer Encoder Stack using DenseGeneral."""
328
-
329
- def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
330
- super().__init__()
331
- self.config = config
332
- model_config = config.model
333
- enc_config = config.model.encoder
334
- self.compute_dtype = compute_dtype
335
-
336
- self.embedding = nn.Embedding(
337
- model_config.src_vocab_size,
338
- enc_config.n_embd,
339
- dtype=compute_dtype,
340
- )
341
- self.layers = nn.ModuleList([EncoderLayer(config, compute_dtype) for _ in range(enc_config.n_layer)])
342
- self.norm = RMSNorm(
343
- enc_config.n_embd,
344
- eps=model_config.normalization_layer_epsilon,
345
- dtype=torch.float32,
346
- )
347
-
348
- def forward(
349
- self,
350
- x_ids: torch.Tensor,
351
- state: EncoderInferenceState,
352
- ) -> torch.Tensor:
353
- x = self.embedding(x_ids)
354
-
355
- for layer in self.layers:
356
- x = layer(x, state)
357
-
358
- x = self.norm(x).to(self.compute_dtype)
359
- return x
360
-
361
-
362
- class DecoderLayer(nn.Module):
363
- """Transformer Decoder Layer using DenseGeneral."""
364
-
365
- def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
366
- super().__init__()
367
- self.config = config
368
- model_config = config.model
369
- dec_config = config.model.decoder
370
- enc_config = config.model.encoder
371
- dec_embed_dim = dec_config.n_embd
372
- enc_embed_dim = enc_config.n_embd
373
- self.compute_dtype = compute_dtype
374
-
375
- # Norms
376
- self.pre_sa_norm = RMSNorm(
377
- dec_embed_dim,
378
- eps=model_config.normalization_layer_epsilon,
379
- dtype=torch.float32,
380
- )
381
- self.pre_ca_norm = RMSNorm(
382
- dec_embed_dim,
383
- eps=model_config.normalization_layer_epsilon,
384
- dtype=torch.float32,
385
- )
386
- self.pre_mlp_norm = RMSNorm(
387
- dec_embed_dim,
388
- eps=model_config.normalization_layer_epsilon,
389
- dtype=torch.float32,
390
- )
391
-
392
- # Self-Attention (GQA) with Causal Masking
393
- self.self_attention = Attention(
394
- config,
395
- q_embed_dim=dec_embed_dim,
396
- kv_embed_dim=dec_embed_dim,
397
- num_query_heads=dec_config.gqa_query_heads,
398
- num_kv_heads=dec_config.kv_heads,
399
- head_dim=dec_config.gqa_head_dim,
400
- compute_dtype=compute_dtype,
401
- is_cross_attn=False,
402
- out_embed_dim=dec_embed_dim,
403
- )
404
- # Cross-Attention (MHA)
405
- self.cross_attention = Attention(
406
- config=config,
407
- q_embed_dim=dec_embed_dim,
408
- kv_embed_dim=enc_embed_dim, # Note kv_embed_dim
409
- num_query_heads=dec_config.cross_query_heads,
410
- num_kv_heads=dec_config.cross_query_heads,
411
- head_dim=dec_config.cross_head_dim,
412
- compute_dtype=compute_dtype,
413
- is_cross_attn=True,
414
- out_embed_dim=dec_embed_dim,
415
- )
416
- # MLP
417
- self.mlp = MlpBlock(
418
- embed_dim=dec_embed_dim,
419
- intermediate_dim=dec_config.n_hidden,
420
- compute_dtype=compute_dtype,
421
- )
422
-
423
- def forward(
424
- self,
425
- x: torch.Tensor,
426
- state: DecoderInferenceState,
427
- self_attn_cache: KVCache | None = None,
428
- cross_attn_cache: KVCache | None = None,
429
- prefill: bool = False,
430
- ) -> torch.Tensor:
431
- residual = x
432
- x_norm = self.pre_sa_norm(x).to(self.compute_dtype)
433
-
434
- sa_out = self.self_attention(
435
- Xq=x_norm, # (2, 1, D)
436
- Xkv=x_norm, # (2, 1, D)
437
- q_positions=state.dec_positions, # (2, 1)
438
- kv_positions=state.dec_positions, # (2, 1)
439
- attn_mask=None,
440
- cache=self_attn_cache,
441
- prefill=prefill,
442
- is_causal=prefill,
443
- )
444
-
445
- x = residual + sa_out
446
-
447
- residual = x
448
- x_norm = self.pre_ca_norm(x).to(self.compute_dtype)
449
- ca_out = self.cross_attention(
450
- Xq=x_norm,
451
- Xkv=state.enc_out,
452
- q_positions=state.dec_positions,
453
- kv_positions=state.enc_positions,
454
- attn_mask=state.dec_cross_attn_mask,
455
- cache=cross_attn_cache,
456
- )
457
- x = residual + ca_out
458
-
459
- residual = x
460
- x_norm = self.pre_mlp_norm(x).to(self.compute_dtype)
461
- mlp_out = self.mlp(x_norm)
462
- x = residual + mlp_out
463
-
464
- return x
465
-
466
-
467
- class Decoder(nn.Module):
468
- """Transformer Decoder Stack using DenseGeneral."""
469
-
470
- def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
471
- super().__init__()
472
- self.config = config
473
- model_config = config.model
474
- dec_config = config.model.decoder
475
- data_config = config.data
476
- self.num_channels = data_config.channels
477
- self.num_layers = dec_config.n_layer
478
-
479
- self.embeddings = nn.ModuleList(
480
- [
481
- nn.Embedding(model_config.tgt_vocab_size, dec_config.n_embd, dtype=compute_dtype)
482
- for _ in range(self.num_channels)
483
- ]
484
- )
485
- self.layers = nn.ModuleList(
486
- [DecoderLayer(config=config, compute_dtype=compute_dtype) for _ in range(self.num_layers)]
487
- )
488
-
489
- self.norm = RMSNorm(
490
- dec_config.n_embd,
491
- eps=model_config.normalization_layer_epsilon,
492
- dtype=torch.float32,
493
- )
494
-
495
- self.logits_dense = DenseGeneral(
496
- in_shapes=(dec_config.n_embd,),
497
- out_features=(self.num_channels, model_config.tgt_vocab_size),
498
- axis=(-1,),
499
- weight_dtype=compute_dtype,
500
- )
501
-
502
- def precompute_cross_attn_cache(
503
- self,
504
- enc_out: torch.Tensor, # (B, S, E)
505
- enc_positions: torch.Tensor, # (B, S)
506
- ) -> list[KVCache]:
507
- """
508
- Computes the Key and Value tensors for cross-attention for each layer from the encoder output.
509
- """
510
- per_layer_kv_cache: list[KVCache] = []
511
-
512
- for layer in self.layers:
513
- cross_attn_module = layer.cross_attention
514
- k_proj = cross_attn_module.k_proj(enc_out)
515
- v_proj = cross_attn_module.v_proj(enc_out)
516
-
517
- k_proj = cross_attn_module.rotary_emb(k_proj, position=enc_positions)
518
- k = k_proj.transpose(1, 2)
519
- v = v_proj.transpose(1, 2)
520
-
521
- per_layer_kv_cache.append(KVCache.from_kv(k, v))
522
-
523
- return per_layer_kv_cache
524
-
525
- def decode_step(
526
- self,
527
- tgt_ids_Bx1xC: torch.Tensor, # [B, 1, C]
528
- state: DecoderInferenceState,
529
- ) -> torch.Tensor:
530
- """
531
- Performs a single decoding step, managing KV caches layer by layer.
532
-
533
- Returns:
534
- A tuple containing:
535
- - logits_Bx1xCV: The final output logits for the current step (B, 1, C*V), cast to float32.
536
- """
537
-
538
- x = None
539
- for i in range(self.num_channels):
540
- channel_tokens = tgt_ids_Bx1xC[..., i]
541
- channel_embed = self.embeddings[i](channel_tokens)
542
- x = channel_embed if x is None else x + channel_embed
543
-
544
- for i, layer in enumerate(self.layers):
545
- self_cache = state.self_attn_cache[i]
546
- cross_cache = state.cross_attn_cache[i]
547
- x = layer(
548
- x, # (2, 1, D)
549
- state,
550
- self_attn_cache=self_cache,
551
- cross_attn_cache=cross_cache,
552
- )
553
-
554
- x = self.norm(x)
555
- logits_Bx1xCxV = self.logits_dense(x)
556
-
557
- return logits_Bx1xCxV.to(torch.float32)
558
-
559
- def forward(self, tgt_ids_BxTxC: torch.Tensor, state: DecoderInferenceState) -> torch.Tensor:
560
- """
561
- Forward pass for the Decoder stack, managing KV caches.
562
-
563
- Args:
564
- tgt_ids_BxTxC: Target token IDs (B, T, C).
565
- encoder_out: Output from the encoder (B, S, E).
566
- tgt_positions: Positions for target sequence (B, T).
567
- src_positions: Positions for source sequence (B, S).
568
- self_attn_mask: Mask for self-attention.
569
- cross_attn_mask: Mask for cross-attention.
570
- past_key_values: List containing the self-attention KV cache for each layer
571
- from the previous decoding step. `len(past_key_values)` should
572
- equal `num_layers`.
573
- precomputed_cross_attn_kv: A single tuple containing the pre-computed K/V cache
574
- derived from `encoder_out`. This is passed identically
575
- to all layers.
576
-
577
- Returns:
578
- A tuple containing:
579
- - logits: The final output logits (B, T, C * V), cast to float32.
580
- - present_key_values: A list containing the updated self-attention KV cache
581
- for each layer for the *current* decoding step.
582
- """
583
- _, _, num_channels_in = tgt_ids_BxTxC.shape
584
- assert num_channels_in == self.num_channels, "Input channels mismatch"
585
-
586
- # Embeddings
587
- x = None
588
- for i in range(self.num_channels):
589
- channel_tokens = tgt_ids_BxTxC[..., i]
590
- channel_embed = self.embeddings[i](channel_tokens)
591
- x = channel_embed if x is None else x + channel_embed
592
-
593
- for i, layer in enumerate(self.layers):
594
- self_cache = state.self_attn_cache[i]
595
- cross_cache = state.cross_attn_cache[i]
596
- x = layer(x, state, self_attn_cache=self_cache, cross_attn_cache=cross_cache, prefill=True)
597
-
598
- # Final Norm
599
- x = self.norm(x)
600
- logits_BxTxCxV = self.logits_dense(x)
601
-
602
- return logits_BxTxCxV.to(torch.float32)
603
-
604
-
605
- class DiaModel(
606
- nn.Module,
607
- PyTorchModelHubMixin,
608
- repo_url="https://github.com/nari-labs/dia",
609
- pipeline_tag="text-to-speech",
610
- license="apache-2.0",
611
- coders={
612
- DiaConfig: (
613
- lambda x: x.model_dump(),
614
- lambda data: DiaConfig.model_validate(data),
615
- ),
616
- },
617
- ):
618
- """PyTorch Dia Model using DenseGeneral."""
619
-
620
- def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
621
- super().__init__()
622
- self.config = config
623
- self.encoder = Encoder(config, compute_dtype)
624
- self.decoder = Decoder(config, compute_dtype)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dia/model.py DELETED
@@ -1,455 +0,0 @@
1
- import time
2
- from enum import Enum
3
-
4
- import dac
5
- import numpy as np
6
- import torch
7
- import torchaudio
8
-
9
- from .audio import apply_audio_delay, build_delay_indices, build_revert_indices, decode, revert_audio_delay
10
- from .config import DiaConfig
11
- from .layers import DiaModel
12
- from .state import DecoderInferenceState, DecoderOutput, EncoderInferenceState
13
-
14
-
15
- DEFAULT_SAMPLE_RATE = 44100
16
-
17
-
18
- def _get_default_device():
19
- if torch.cuda.is_available():
20
- return torch.device("cuda")
21
- elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
22
- return torch.device("mps")
23
- return torch.device("cpu")
24
-
25
-
26
- def _sample_next_token(
27
- logits_BCxV: torch.Tensor,
28
- temperature: float,
29
- top_p: float,
30
- cfg_filter_top_k: int | None = None,
31
- ) -> torch.Tensor:
32
- if temperature == 0.0:
33
- return torch.argmax(logits_BCxV, dim=-1)
34
-
35
- logits_BCxV = logits_BCxV / temperature
36
- if cfg_filter_top_k is not None:
37
- _, top_k_indices_BCxV = torch.topk(logits_BCxV, k=cfg_filter_top_k, dim=-1)
38
- mask = torch.ones_like(logits_BCxV, dtype=torch.bool)
39
- mask.scatter_(dim=-1, index=top_k_indices_BCxV, value=False)
40
- logits_BCxV = logits_BCxV.masked_fill(mask, -torch.inf)
41
-
42
- if top_p < 1.0:
43
- probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
44
- sorted_probs_BCxV, sorted_indices_BCxV = torch.sort(probs_BCxV, dim=-1, descending=True)
45
- cumulative_probs_BCxV = torch.cumsum(sorted_probs_BCxV, dim=-1)
46
-
47
- sorted_indices_to_remove_BCxV = cumulative_probs_BCxV > top_p
48
- sorted_indices_to_remove_BCxV[..., 1:] = sorted_indices_to_remove_BCxV[..., :-1].clone()
49
- sorted_indices_to_remove_BCxV[..., 0] = 0
50
-
51
- indices_to_remove_BCxV = torch.zeros_like(sorted_indices_to_remove_BCxV)
52
- indices_to_remove_BCxV.scatter_(dim=-1, index=sorted_indices_BCxV, src=sorted_indices_to_remove_BCxV)
53
- logits_BCxV = logits_BCxV.masked_fill(indices_to_remove_BCxV, -torch.inf)
54
-
55
- final_probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
56
-
57
- sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
58
- sampled_indices_C = sampled_indices_BC.squeeze(-1)
59
- return sampled_indices_C
60
-
61
-
62
- class ComputeDtype(str, Enum):
63
- FLOAT32 = "float32"
64
- FLOAT16 = "float16"
65
- BFLOAT16 = "bfloat16"
66
-
67
- def to_dtype(self) -> torch.dtype:
68
- if self == ComputeDtype.FLOAT32:
69
- return torch.float32
70
- elif self == ComputeDtype.FLOAT16:
71
- return torch.float16
72
- elif self == ComputeDtype.BFLOAT16:
73
- return torch.bfloat16
74
- else:
75
- raise ValueError(f"Unsupported compute dtype: {self}")
76
-
77
-
78
- class Dia:
79
- def __init__(
80
- self,
81
- config: DiaConfig,
82
- compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32,
83
- device: torch.device | None = None,
84
- ):
85
- """Initializes the Dia model.
86
-
87
- Args:
88
- config: The configuration object for the model.
89
- device: The device to load the model onto. If None, will automatically select the best available device.
90
-
91
- Raises:
92
- RuntimeError: If there is an error loading the DAC model.
93
- """
94
- super().__init__()
95
- self.config = config
96
- self.device = device if device is not None else _get_default_device()
97
- if isinstance(compute_dtype, str):
98
- compute_dtype = ComputeDtype(compute_dtype)
99
- self.compute_dtype = compute_dtype.to_dtype()
100
- self.model = DiaModel(config, self.compute_dtype)
101
- self.dac_model = None
102
-
103
- @classmethod
104
- def from_local(
105
- cls,
106
- config_path: str,
107
- checkpoint_path: str,
108
- compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32,
109
- device: torch.device | None = None,
110
- ) -> "Dia":
111
- """Loads the Dia model from local configuration and checkpoint files.
112
-
113
- Args:
114
- config_path: Path to the configuration JSON file.
115
- checkpoint_path: Path to the model checkpoint (.pth) file.
116
- device: The device to load the model onto. If None, will automatically select the best available device.
117
-
118
- Returns:
119
- An instance of the Dia model loaded with weights and set to eval mode.
120
-
121
- Raises:
122
- FileNotFoundError: If the config or checkpoint file is not found.
123
- RuntimeError: If there is an error loading the checkpoint.
124
- """
125
- config = DiaConfig.load(config_path)
126
- if config is None:
127
- raise FileNotFoundError(f"Config file not found at {config_path}")
128
-
129
- dia = cls(config, compute_dtype, device)
130
-
131
- try:
132
- state_dict = torch.load(checkpoint_path, map_location=dia.device)
133
- dia.model.load_state_dict(state_dict)
134
- except FileNotFoundError:
135
- raise FileNotFoundError(f"Checkpoint file not found at {checkpoint_path}")
136
- except Exception as e:
137
- raise RuntimeError(f"Error loading checkpoint from {checkpoint_path}") from e
138
-
139
- dia.model.to(dia.device)
140
- dia.model.eval()
141
- dia._load_dac_model()
142
- return dia
143
-
144
- @classmethod
145
- def from_pretrained(
146
- cls,
147
- model_name: str = "nari-labs/Dia-1.6B",
148
- compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32,
149
- device: torch.device | None = None,
150
- ) -> "Dia":
151
- """Loads the Dia model from a Hugging Face Hub repository.
152
-
153
- Downloads the configuration and checkpoint files from the specified
154
- repository ID and then loads the model.
155
-
156
- Args:
157
- model_name: The Hugging Face Hub repository ID (e.g., "nari-labs/Dia-1.6B").
158
- compute_dtype: The computation dtype to use.
159
- device: The device to load the model onto. If None, will automatically select the best available device.
160
-
161
- Returns:
162
- An instance of the Dia model loaded with weights and set to eval mode.
163
-
164
- Raises:
165
- FileNotFoundError: If config or checkpoint download/loading fails.
166
- RuntimeError: If there is an error loading the checkpoint.
167
- """
168
- if isinstance(compute_dtype, str):
169
- compute_dtype = ComputeDtype(compute_dtype)
170
- loaded_model = DiaModel.from_pretrained(model_name, compute_dtype=compute_dtype.to_dtype())
171
- config = loaded_model.config
172
- dia = cls(config, compute_dtype, device)
173
-
174
- dia.model = loaded_model
175
- dia.model.to(dia.device)
176
- dia.model.eval()
177
- dia._load_dac_model()
178
- return dia
179
-
180
- def _load_dac_model(self):
181
- try:
182
- dac_model_path = dac.utils.download()
183
- dac_model = dac.DAC.load(dac_model_path).to(self.device)
184
- except Exception as e:
185
- raise RuntimeError("Failed to load DAC model") from e
186
- self.dac_model = dac_model
187
-
188
- def _prepare_text_input(self, text: str) -> torch.Tensor:
189
- """Encodes text prompt, pads, and creates attention mask and positions."""
190
- text_pad_value = self.config.data.text_pad_value
191
- max_len = self.config.data.text_length
192
-
193
- byte_text = text.encode("utf-8")
194
- replaced_bytes = byte_text.replace(b"[S1]", b"\x01").replace(b"[S2]", b"\x02")
195
- text_tokens = list(replaced_bytes)
196
-
197
- current_len = len(text_tokens)
198
- padding_needed = max_len - current_len
199
- if padding_needed <= 0:
200
- text_tokens = text_tokens[:max_len]
201
- padded_text_np = np.array(text_tokens, dtype=np.uint8)
202
- else:
203
- padded_text_np = np.pad(
204
- text_tokens,
205
- (0, padding_needed),
206
- mode="constant",
207
- constant_values=text_pad_value,
208
- ).astype(np.uint8)
209
-
210
- src_tokens = torch.from_numpy(padded_text_np).to(torch.long).to(self.device).unsqueeze(0) # [1, S]
211
- return src_tokens
212
-
213
- def _prepare_audio_prompt(self, audio_prompt: torch.Tensor | None) -> tuple[torch.Tensor, int]:
214
- num_channels = self.config.data.channels
215
- audio_bos_value = self.config.data.audio_bos_value
216
- audio_pad_value = self.config.data.audio_pad_value
217
- delay_pattern = self.config.data.delay_pattern
218
- max_delay_pattern = max(delay_pattern)
219
-
220
- prefill = torch.full(
221
- (1, num_channels),
222
- fill_value=audio_bos_value,
223
- dtype=torch.int,
224
- device=self.device,
225
- )
226
-
227
- prefill_step = 1
228
-
229
- if audio_prompt is not None:
230
- prefill_step += audio_prompt.shape[0]
231
- prefill = torch.cat([prefill, audio_prompt], dim=0)
232
-
233
- delay_pad_tensor = torch.full(
234
- (max_delay_pattern, num_channels), fill_value=-1, dtype=torch.int, device=self.device
235
- )
236
- prefill = torch.cat([prefill, delay_pad_tensor], dim=0)
237
-
238
- delay_precomp = build_delay_indices(
239
- B=1,
240
- T=prefill.shape[0],
241
- C=num_channels,
242
- delay_pattern=delay_pattern,
243
- )
244
-
245
- prefill = apply_audio_delay(
246
- audio_BxTxC=prefill.unsqueeze(0),
247
- pad_value=audio_pad_value,
248
- bos_value=audio_bos_value,
249
- precomp=delay_precomp,
250
- ).squeeze(0)
251
-
252
- return prefill, prefill_step
253
-
254
- def _prepare_generation(self, text: str, audio_prompt: str | torch.Tensor | None, verbose: bool):
255
- enc_input_cond = self._prepare_text_input(text)
256
- enc_input_uncond = torch.zeros_like(enc_input_cond)
257
- enc_input = torch.cat([enc_input_uncond, enc_input_cond], dim=0)
258
-
259
- if isinstance(audio_prompt, str):
260
- audio_prompt = self.load_audio(audio_prompt)
261
- prefill, prefill_step = self._prepare_audio_prompt(audio_prompt)
262
-
263
- if verbose:
264
- print("generate: data loaded")
265
-
266
- enc_state = EncoderInferenceState.new(self.config, enc_input_cond)
267
- encoder_out = self.model.encoder(enc_input, enc_state)
268
-
269
- dec_cross_attn_cache = self.model.decoder.precompute_cross_attn_cache(encoder_out, enc_state.positions)
270
- dec_state = DecoderInferenceState.new(
271
- self.config, enc_state, encoder_out, dec_cross_attn_cache, self.compute_dtype
272
- )
273
- dec_output = DecoderOutput.new(self.config, self.device)
274
- dec_output.prefill(prefill, prefill_step)
275
-
276
- dec_step = prefill_step - 1
277
- if dec_step > 0:
278
- dec_state.prepare_step(0, dec_step)
279
- tokens_BxTxC = dec_output.get_tokens_at(0, dec_step).unsqueeze(0).expand(2, -1, -1)
280
- self.model.decoder.forward(tokens_BxTxC, dec_state)
281
-
282
- return dec_state, dec_output
283
-
284
- def _decoder_step(
285
- self,
286
- tokens_Bx1xC: torch.Tensor,
287
- dec_state: DecoderInferenceState,
288
- cfg_scale: float,
289
- temperature: float,
290
- top_p: float,
291
- cfg_filter_top_k: int,
292
- ) -> torch.Tensor:
293
- audio_eos_value = self.config.data.audio_eos_value
294
- logits_Bx1xCxV = self.model.decoder.decode_step(tokens_Bx1xC, dec_state)
295
-
296
- logits_last_BxCxV = logits_Bx1xCxV[:, -1, :, :]
297
- uncond_logits_CxV = logits_last_BxCxV[0, :, :]
298
- cond_logits_CxV = logits_last_BxCxV[1, :, :]
299
-
300
- logits_CxV = cond_logits_CxV + cfg_scale * (cond_logits_CxV - uncond_logits_CxV)
301
- logits_CxV[:, audio_eos_value + 1 :] = -torch.inf
302
- logits_CxV[1:, audio_eos_value:] = -torch.inf
303
-
304
- pred_C = _sample_next_token(
305
- logits_CxV.float(),
306
- temperature=temperature,
307
- top_p=top_p,
308
- cfg_filter_top_k=cfg_filter_top_k,
309
- )
310
- return pred_C
311
-
312
- def _generate_output(self, generated_codes: torch.Tensor) -> np.ndarray:
313
- num_channels = self.config.data.channels
314
- seq_length = generated_codes.shape[0]
315
- delay_pattern = self.config.data.delay_pattern
316
- audio_pad_value = self.config.data.audio_pad_value
317
- max_delay_pattern = max(delay_pattern)
318
-
319
- revert_precomp = build_revert_indices(
320
- B=1,
321
- T=seq_length,
322
- C=num_channels,
323
- delay_pattern=delay_pattern,
324
- )
325
-
326
- codebook = revert_audio_delay(
327
- audio_BxTxC=generated_codes.unsqueeze(0),
328
- pad_value=audio_pad_value,
329
- precomp=revert_precomp,
330
- T=seq_length,
331
- )[:, :-max_delay_pattern, :]
332
-
333
- min_valid_index = 0
334
- max_valid_index = 1023
335
- invalid_mask = (codebook < min_valid_index) | (codebook > max_valid_index)
336
- codebook[invalid_mask] = 0
337
-
338
- audio = decode(self.dac_model, codebook.transpose(1, 2))
339
-
340
- return audio.squeeze().cpu().numpy()
341
-
342
- def load_audio(self, audio_path: str) -> torch.Tensor:
343
- audio, sr = torchaudio.load(audio_path, channels_first=True) # C, T
344
- if sr != DEFAULT_SAMPLE_RATE:
345
- audio = torchaudio.functional.resample(audio, sr, DEFAULT_SAMPLE_RATE)
346
- audio = audio.to(self.device).unsqueeze(0) # 1, C, T
347
- audio_data = self.dac_model.preprocess(audio, DEFAULT_SAMPLE_RATE)
348
- _, encoded_frame, _, _, _ = self.dac_model.encode(audio_data) # 1, C, T
349
- return encoded_frame.squeeze(0).transpose(0, 1)
350
-
351
- def save_audio(self, path: str, audio: np.ndarray):
352
- import soundfile as sf
353
-
354
- sf.write(path, audio, DEFAULT_SAMPLE_RATE)
355
-
356
- @torch.inference_mode()
357
- def generate(
358
- self,
359
- text: str,
360
- max_tokens: int | None = None,
361
- cfg_scale: float = 3.0,
362
- temperature: float = 1.3,
363
- top_p: float = 0.95,
364
- use_torch_compile: bool = False,
365
- cfg_filter_top_k: int = 35,
366
- audio_prompt: str | torch.Tensor | None = None,
367
- audio_prompt_path: str | None = None,
368
- use_cfg_filter: bool | None = None,
369
- verbose: bool = False,
370
- ) -> np.ndarray:
371
- audio_eos_value = self.config.data.audio_eos_value
372
- audio_pad_value = self.config.data.audio_pad_value
373
- delay_pattern = self.config.data.delay_pattern
374
- max_tokens = self.config.data.audio_length if max_tokens is None else max_tokens
375
- max_delay_pattern = max(delay_pattern)
376
- self.model.eval()
377
-
378
- if audio_prompt_path:
379
- print("Warning: audio_prompt_path is deprecated. Use audio_prompt instead.")
380
- audio_prompt = audio_prompt_path
381
- if use_cfg_filter is not None:
382
- print("Warning: use_cfg_filter is deprecated.")
383
-
384
- if verbose:
385
- total_start_time = time.time()
386
-
387
- dec_state, dec_output = self._prepare_generation(text, audio_prompt, verbose)
388
- dec_step = dec_output.prefill_step - 1
389
-
390
- bos_countdown = max_delay_pattern
391
- eos_detected = False
392
- eos_countdown = -1
393
-
394
- if use_torch_compile:
395
- step_fn = torch.compile(self._decoder_step, mode="default")
396
- else:
397
- step_fn = self._decoder_step
398
-
399
- if verbose:
400
- print("generate: starting generation loop")
401
- if use_torch_compile:
402
- print("generate: by using use_torch_compile=True, the first step would take long")
403
- start_time = time.time()
404
-
405
- while dec_step < max_tokens:
406
- dec_state.prepare_step(dec_step)
407
- tokens_Bx1xC = dec_output.get_tokens_at(dec_step).unsqueeze(0).expand(2, -1, -1)
408
- pred_C = step_fn(
409
- tokens_Bx1xC,
410
- dec_state,
411
- cfg_scale,
412
- temperature,
413
- top_p,
414
- cfg_filter_top_k,
415
- )
416
-
417
- if (not eos_detected and pred_C[0] == audio_eos_value) or dec_step == max_tokens - max_delay_pattern - 1:
418
- eos_detected = True
419
- eos_countdown = max_delay_pattern
420
-
421
- if eos_countdown > 0:
422
- step_after_eos = max_delay_pattern - eos_countdown
423
- for i, d in enumerate(delay_pattern):
424
- if step_after_eos == d:
425
- pred_C[i] = audio_eos_value
426
- elif step_after_eos > d:
427
- pred_C[i] = audio_pad_value
428
- eos_countdown -= 1
429
-
430
- bos_countdown = max(0, bos_countdown - 1)
431
- dec_output.update_one(pred_C, dec_step + 1, bos_countdown > 0)
432
-
433
- if eos_countdown == 0:
434
- break
435
-
436
- dec_step += 1
437
- if verbose and dec_step % 86 == 0:
438
- duration = time.time() - start_time
439
- print(
440
- f"generate step {dec_step}: speed={86 / duration:.3f} tokens/s, realtime factor={1 / duration:.3f}x"
441
- )
442
- start_time = time.time()
443
-
444
- if dec_output.prefill_step >= dec_step + 1:
445
- print("Warning: Nothing generated")
446
- return None
447
-
448
- generated_codes = dec_output.generated_tokens[dec_output.prefill_step : dec_step + 1, :]
449
-
450
- if verbose:
451
- total_step = dec_step + 1 - dec_output.prefill_step
452
- total_duration = time.time() - total_start_time
453
- print(f"generate: total step={total_step}, total duration={total_duration:.3f}s")
454
-
455
- return self._generate_output(generated_codes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dia/state.py DELETED
@@ -1,207 +0,0 @@
1
- from dataclasses import dataclass
2
-
3
- import torch
4
-
5
- from .config import DiaConfig
6
-
7
-
8
- def create_attn_mask(
9
- q_padding_mask_1d: torch.Tensor,
10
- k_padding_mask_1d: torch.Tensor,
11
- device: torch.device,
12
- is_causal: bool = False,
13
- ) -> torch.Tensor:
14
- """
15
- Creates the attention mask (self or cross) mimicking JAX segment ID logic.
16
- """
17
- B1, Tq = q_padding_mask_1d.shape
18
- B2, Tk = k_padding_mask_1d.shape
19
- assert B1 == B2, "Query and key batch dimensions must match"
20
-
21
- p_mask_q = q_padding_mask_1d.unsqueeze(2) # Shape [B, Tq, 1]
22
- p_mask_k = k_padding_mask_1d.unsqueeze(1) # Shape [B, 1, Tk]
23
-
24
- # Condition A: Non-padding query attends to non-padding key
25
- non_pad_attends_non_pad = p_mask_q & p_mask_k # Shape [B, Tq, Tk]
26
-
27
- # Condition B: Padding query attends to padding key
28
- pad_attends_pad = (~p_mask_q) & (~p_mask_k) # Shape [B, Tq, Tk]
29
-
30
- # Combine: True if padding status is compatible (both non-pad OR both pad)
31
- mask = non_pad_attends_non_pad | pad_attends_pad # Shape [B, Tq, Tk]
32
-
33
- if is_causal:
34
- assert Tq == Tk, "Causal mask requires query and key sequence lengths to be equal"
35
- causal_mask_2d = torch.tril(torch.ones((Tq, Tk), dtype=torch.bool, device=device)) # Shape [Tq, Tk]
36
- causal_mask = mask & causal_mask_2d # Shape [B, Tq, Tk]
37
- return causal_mask.unsqueeze(1) # Shape [B, 1, Tq, Tk]
38
- else:
39
- return mask.unsqueeze(1) # Shape [B, 1, Tq, Tk]
40
-
41
-
42
- @dataclass
43
- class EncoderInferenceState:
44
- """Parameters specifically for encoder inference."""
45
-
46
- max_seq_len: int
47
- device: torch.device
48
- positions: torch.Tensor
49
- padding_mask: torch.Tensor
50
- attn_mask: torch.Tensor
51
-
52
- @classmethod
53
- def new(cls, config: DiaConfig, cond_src: torch.Tensor) -> "EncoderInferenceState":
54
- """Creates EtorchrInferenceParams from DiaConfig and a device."""
55
- device = cond_src.device
56
-
57
- positions = (
58
- torch.arange(config.data.text_length, dtype=torch.float32, device=device).unsqueeze(0).expand(2, -1)
59
- )
60
- padding_mask = (cond_src != config.data.text_pad_value).to(device).expand(2, -1)
61
- attn_mask = create_attn_mask(padding_mask, padding_mask, device, is_causal=False)
62
-
63
- return cls(
64
- max_seq_len=config.data.text_length,
65
- device=device,
66
- positions=positions,
67
- padding_mask=padding_mask,
68
- attn_mask=attn_mask,
69
- )
70
-
71
-
72
- class KVCache:
73
- def __init__(
74
- self,
75
- num_heads: int,
76
- max_len: int,
77
- head_dim: int,
78
- dtype: torch.dtype,
79
- device: torch.device,
80
- k: torch.Tensor | None = None,
81
- v: torch.Tensor | None = None,
82
- ):
83
- self.k = torch.zeros((2, num_heads, max_len, head_dim), dtype=dtype, device=device) if k is None else k
84
- self.v = torch.zeros((2, num_heads, max_len, head_dim), dtype=dtype, device=device) if v is None else v
85
- self.current_idx = torch.tensor(0)
86
-
87
- @classmethod
88
- def from_kv(cls, k: torch.Tensor, v: torch.Tensor) -> "KVCache":
89
- return cls(
90
- num_heads=k.shape[1],
91
- max_len=k.shape[2],
92
- head_dim=k.shape[3],
93
- dtype=k.dtype,
94
- device=k.device,
95
- k=k,
96
- v=v,
97
- )
98
-
99
- def update(self, k: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
100
- self.k[:, :, self.current_idx : self.current_idx + 1, :] = k
101
- self.v[:, :, self.current_idx : self.current_idx + 1, :] = v
102
- self.current_idx += 1
103
- return self.k[:, :, : self.current_idx, :], self.v[:, :, : self.current_idx, :]
104
-
105
- def prefill(self, k: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
106
- prefill_len = k.shape[2]
107
- self.k[:, :, :prefill_len, :] = k
108
- self.v[:, :, :prefill_len, :] = v
109
- self.current_idx = prefill_len - 1
110
-
111
-
112
- @dataclass
113
- class DecoderInferenceState:
114
- """Parameters specifically for decoder inference."""
115
-
116
- device: torch.device
117
- dtype: torch.dtype
118
- enc_out: torch.Tensor
119
- enc_positions: torch.Tensor
120
- dec_positions: torch.Tensor
121
- dec_cross_attn_mask: torch.Tensor
122
- self_attn_cache: list[KVCache]
123
- cross_attn_cache: list[KVCache]
124
-
125
- @classmethod
126
- def new(
127
- cls,
128
- config: DiaConfig,
129
- enc_state: EncoderInferenceState,
130
- enc_out: torch.Tensor,
131
- dec_cross_attn_cache: list[KVCache],
132
- compute_dtype: torch.dtype,
133
- ) -> "DecoderInferenceState":
134
- """Creates DecoderInferenceParams from DiaConfig and a device."""
135
- device = enc_out.device
136
- max_audio_len = config.data.audio_length
137
-
138
- dec_positions = torch.full((2, 1), fill_value=0, dtype=torch.long, device=device)
139
- tgt_padding_mask = torch.ones((2, 1), dtype=torch.bool, device=device)
140
- dec_cross_attn_mask = create_attn_mask(tgt_padding_mask, enc_state.padding_mask, device, is_causal=False)
141
-
142
- self_attn_cache = [
143
- KVCache(
144
- config.model.decoder.kv_heads,
145
- max_audio_len,
146
- config.model.decoder.gqa_head_dim,
147
- compute_dtype,
148
- device,
149
- )
150
- for _ in range(config.model.decoder.n_layer)
151
- ]
152
-
153
- return cls(
154
- device=device,
155
- dtype=compute_dtype,
156
- enc_out=enc_out,
157
- enc_positions=enc_state.positions,
158
- dec_positions=dec_positions,
159
- dec_cross_attn_mask=dec_cross_attn_mask,
160
- self_attn_cache=self_attn_cache,
161
- cross_attn_cache=dec_cross_attn_cache,
162
- )
163
-
164
- def prepare_step(self, step_from: int, step_to: int | None = None) -> None:
165
- if step_to is None:
166
- step_to = step_from + 1
167
- self.dec_positions = (
168
- torch.arange(step_from, step_to, dtype=torch.float32, device=self.device).unsqueeze(0).expand(2, -1)
169
- )
170
-
171
-
172
- @dataclass
173
- class DecoderOutput:
174
- generated_tokens: torch.Tensor
175
- prefill_step: int
176
-
177
- @classmethod
178
- def new(cls, config: DiaConfig, device: torch.device) -> "DecoderOutput":
179
- max_audio_len = config.data.audio_length
180
- return cls(
181
- generated_tokens=torch.full(
182
- (max_audio_len, config.data.channels),
183
- fill_value=-1,
184
- dtype=torch.int,
185
- device=device,
186
- ),
187
- prefill_step=0,
188
- )
189
-
190
- def get_tokens_at(self, step_from: int, step_to: int | None = None) -> torch.Tensor:
191
- if step_to is None:
192
- step_to = step_from + 1
193
- return self.generated_tokens[step_from:step_to, :]
194
-
195
- def update_one(self, dec_out: torch.Tensor, step: int, apply_mask: bool = False):
196
- if apply_mask:
197
- mask = self.generated_tokens[step : step + 1, :] == -1
198
- self.generated_tokens[step : step + 1, :] = torch.where(
199
- mask, dec_out, self.generated_tokens[step : step + 1, :]
200
- )
201
- else:
202
- self.generated_tokens[step : step + 1, :] = dec_out
203
-
204
- def prefill(self, dec_out: torch.Tensor, prefill_step: int):
205
- length = dec_out.shape[0]
206
- self.generated_tokens[0:length, :] = dec_out
207
- self.prefill_step = prefill_step
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dia_app_gradio.py DELETED
@@ -1,378 +0,0 @@
1
- import tempfile
2
- import time
3
- from pathlib import Path
4
- from typing import Optional, Tuple
5
- import spaces
6
-
7
- import gradio as gr
8
- import numpy as np
9
- import soundfile as sf
10
- import torch
11
-
12
- from dia.model import Dia
13
-
14
-
15
- # Load Nari model and config
16
- print("Loading Nari model...")
17
- try:
18
- # Use the function from inference.py
19
- model = Dia.from_pretrained("nari-labs/Dia-1.6B", compute_dtype="float32")
20
- except Exception as e:
21
- print(f"Error loading Nari model: {e}")
22
- raise
23
-
24
-
25
- @spaces.GPU
26
- def run_inference(
27
- text_input: str,
28
- audio_prompt_input: Optional[Tuple[int, np.ndarray]],
29
- max_new_tokens: int,
30
- cfg_scale: float,
31
- temperature: float,
32
- top_p: float,
33
- cfg_filter_top_k: int,
34
- speed_factor: float,
35
- ):
36
- """
37
- Runs Nari inference using the globally loaded model and provided inputs.
38
- Uses temporary files for text and audio prompt compatibility with inference.generate.
39
- """
40
- # global model, device # Access global model, config, device
41
-
42
- if not text_input or text_input.isspace():
43
- raise gr.Error("Text input cannot be empty.")
44
-
45
- temp_txt_file_path = None
46
- temp_audio_prompt_path = None
47
- output_audio = (44100, np.zeros(1, dtype=np.float32))
48
-
49
- try:
50
- prompt_path_for_generate = None
51
- if audio_prompt_input is not None:
52
- sr, audio_data = audio_prompt_input
53
- # Check if audio_data is valid
54
- if (
55
- audio_data is None or audio_data.size == 0 or audio_data.max() == 0
56
- ): # Check for silence/empty
57
- gr.Warning("Audio prompt seems empty or silent, ignoring prompt.")
58
- else:
59
- # Save prompt audio to a temporary WAV file
60
- with tempfile.NamedTemporaryFile(
61
- mode="wb", suffix=".wav", delete=False
62
- ) as f_audio:
63
- temp_audio_prompt_path = f_audio.name # Store path for cleanup
64
-
65
- # Basic audio preprocessing for consistency
66
- # Convert to float32 in [-1, 1] range if integer type
67
- if np.issubdtype(audio_data.dtype, np.integer):
68
- max_val = np.iinfo(audio_data.dtype).max
69
- audio_data = audio_data.astype(np.float32) / max_val
70
- elif not np.issubdtype(audio_data.dtype, np.floating):
71
- gr.Warning(
72
- f"Unsupported audio prompt dtype {audio_data.dtype}, attempting conversion."
73
- )
74
- # Attempt conversion, might fail for complex types
75
- try:
76
- audio_data = audio_data.astype(np.float32)
77
- except Exception as conv_e:
78
- raise gr.Error(
79
- f"Failed to convert audio prompt to float32: {conv_e}"
80
- )
81
-
82
- # Ensure mono (average channels if stereo)
83
- if audio_data.ndim > 1:
84
- if audio_data.shape[0] == 2: # Assume (2, N)
85
- audio_data = np.mean(audio_data, axis=0)
86
- elif audio_data.shape[1] == 2: # Assume (N, 2)
87
- audio_data = np.mean(audio_data, axis=1)
88
- else:
89
- gr.Warning(
90
- f"Audio prompt has unexpected shape {audio_data.shape}, taking first channel/axis."
91
- )
92
- audio_data = (
93
- audio_data[0]
94
- if audio_data.shape[0] < audio_data.shape[1]
95
- else audio_data[:, 0]
96
- )
97
- audio_data = np.ascontiguousarray(
98
- audio_data
99
- ) # Ensure contiguous after slicing/mean
100
-
101
- # Write using soundfile
102
- try:
103
- sf.write(
104
- temp_audio_prompt_path, audio_data, sr, subtype="FLOAT"
105
- ) # Explicitly use FLOAT subtype
106
- prompt_path_for_generate = temp_audio_prompt_path
107
- print(
108
- f"Created temporary audio prompt file: {temp_audio_prompt_path} (orig sr: {sr})"
109
- )
110
- except Exception as write_e:
111
- print(f"Error writing temporary audio file: {write_e}")
112
- raise gr.Error(f"Failed to save audio prompt: {write_e}")
113
-
114
- # 3. Run Generation
115
-
116
- start_time = time.time()
117
-
118
- # Use torch.inference_mode() context manager for the generation call
119
- with torch.inference_mode():
120
- output_audio_np = model.generate(
121
- text_input,
122
- max_tokens=max_new_tokens,
123
- cfg_scale=cfg_scale,
124
- temperature=temperature,
125
- top_p=top_p,
126
- cfg_filter_top_k=cfg_filter_top_k, # Pass the value here
127
- use_torch_compile=False, # Keep False for Gradio stability
128
- audio_prompt=prompt_path_for_generate,
129
- )
130
-
131
- end_time = time.time()
132
- print(f"Generation finished in {end_time - start_time:.2f} seconds.")
133
-
134
- # 4. Convert Codes to Audio
135
- if output_audio_np is not None:
136
- # Get sample rate from the loaded DAC model
137
- output_sr = 44100
138
-
139
- # --- Slow down audio ---
140
- original_len = len(output_audio_np)
141
- # Ensure speed_factor is positive and not excessively small/large to avoid issues
142
- speed_factor = max(0.1, min(speed_factor, 5.0))
143
- target_len = int(
144
- original_len / speed_factor
145
- ) # Target length based on speed_factor
146
- if (
147
- target_len != original_len and target_len > 0
148
- ): # Only interpolate if length changes and is valid
149
- x_original = np.arange(original_len)
150
- x_resampled = np.linspace(0, original_len - 1, target_len)
151
- resampled_audio_np = np.interp(x_resampled, x_original, output_audio_np)
152
- output_audio = (
153
- output_sr,
154
- resampled_audio_np.astype(np.float32),
155
- ) # Use resampled audio
156
- print(
157
- f"Resampled audio from {original_len} to {target_len} samples for {speed_factor:.2f}x speed."
158
- )
159
- else:
160
- output_audio = (
161
- output_sr,
162
- output_audio_np,
163
- ) # Keep original if calculation fails or no change
164
- print(f"Skipping audio speed adjustment (factor: {speed_factor:.2f}).")
165
- # --- End slowdown ---
166
-
167
- print(
168
- f"Audio conversion successful. Final shape: {output_audio[1].shape}, Sample Rate: {output_sr}"
169
- )
170
-
171
- # Explicitly convert to int16 to prevent Gradio warning
172
- if (
173
- output_audio[1].dtype == np.float32
174
- or output_audio[1].dtype == np.float64
175
- ):
176
- audio_for_gradio = np.clip(output_audio[1], -1.0, 1.0)
177
- audio_for_gradio = (audio_for_gradio * 32767).astype(np.int16)
178
- output_audio = (output_sr, audio_for_gradio)
179
- print("Converted audio to int16 for Gradio output.")
180
-
181
- else:
182
- print("\nGeneration finished, but no valid tokens were produced.")
183
- # Return default silence
184
- gr.Warning("Generation produced no output.")
185
-
186
- except Exception as e:
187
- print(f"Error during inference: {e}")
188
- import traceback
189
-
190
- traceback.print_exc()
191
- # Re-raise as Gradio error to display nicely in the UI
192
- raise gr.Error(f"Inference failed: {e}")
193
-
194
- finally:
195
- # 5. Cleanup Temporary Files defensively
196
- if temp_txt_file_path and Path(temp_txt_file_path).exists():
197
- try:
198
- Path(temp_txt_file_path).unlink()
199
- print(f"Deleted temporary text file: {temp_txt_file_path}")
200
- except OSError as e:
201
- print(
202
- f"Warning: Error deleting temporary text file {temp_txt_file_path}: {e}"
203
- )
204
- if temp_audio_prompt_path and Path(temp_audio_prompt_path).exists():
205
- try:
206
- Path(temp_audio_prompt_path).unlink()
207
- print(f"Deleted temporary audio prompt file: {temp_audio_prompt_path}")
208
- except OSError as e:
209
- print(
210
- f"Warning: Error deleting temporary audio prompt file {temp_audio_prompt_path}: {e}"
211
- )
212
-
213
- return output_audio
214
-
215
-
216
- # --- Create Gradio Interface ---
217
- css = """
218
- #col-container {max-width: 90%; margin-left: auto; margin-right: auto;}
219
- """
220
- # Attempt to load default text from example.txt
221
- default_text = "[S1] Dia is an open weights text to dialogue model. \n[S2] You get full control over scripts and voices. \n[S1] Wow. Amazing. (laughs) \n[S2] Try it now on Git hub or Hugging Face."
222
- example_txt_path = Path("./example.txt")
223
- if example_txt_path.exists():
224
- try:
225
- default_text = example_txt_path.read_text(encoding="utf-8").strip()
226
- if not default_text: # Handle empty example file
227
- default_text = "Example text file was empty."
228
- except Exception as e:
229
- print(f"Warning: Could not read example.txt: {e}")
230
-
231
-
232
- # Build Gradio UI
233
- with gr.Blocks(css=css) as demo:
234
- gr.Markdown("# Nari Text-to-Speech Synthesis")
235
-
236
- with gr.Row(equal_height=False):
237
- with gr.Column(scale=1):
238
- text_input = gr.Textbox(
239
- label="Input Text",
240
- placeholder="Enter text here...",
241
- value=default_text,
242
- lines=5, # Increased lines
243
- )
244
- audio_prompt_input = gr.Audio(
245
- label="Audio Prompt (Optional)",
246
- show_label=True,
247
- sources=["upload", "microphone"],
248
- type="numpy",
249
- )
250
- with gr.Accordion("Generation Parameters", open=False):
251
- max_new_tokens = gr.Slider(
252
- label="Max New Tokens (Audio Length)",
253
- minimum=860,
254
- maximum=3072,
255
- value=model.config.data.audio_length, # Use config default if available, else fallback
256
- step=50,
257
- info="Controls the maximum length of the generated audio (more tokens = longer audio).",
258
- )
259
- cfg_scale = gr.Slider(
260
- label="CFG Scale (Guidance Strength)",
261
- minimum=1.0,
262
- maximum=5.0,
263
- value=3.0, # Default from inference.py
264
- step=0.1,
265
- info="Higher values increase adherence to the text prompt.",
266
- )
267
- temperature = gr.Slider(
268
- label="Temperature (Randomness)",
269
- minimum=1.0,
270
- maximum=1.5,
271
- value=1.3, # Default from inference.py
272
- step=0.05,
273
- info="Lower values make the output more deterministic, higher values increase randomness.",
274
- )
275
- top_p = gr.Slider(
276
- label="Top P (Nucleus Sampling)",
277
- minimum=0.80,
278
- maximum=1.0,
279
- value=0.95, # Default from inference.py
280
- step=0.01,
281
- info="Filters vocabulary to the most likely tokens cumulatively reaching probability P.",
282
- )
283
- cfg_filter_top_k = gr.Slider(
284
- label="CFG Filter Top K",
285
- minimum=15,
286
- maximum=50,
287
- value=30,
288
- step=1,
289
- info="Top k filter for CFG guidance.",
290
- )
291
- speed_factor_slider = gr.Slider(
292
- label="Speed Factor",
293
- minimum=0.8,
294
- maximum=1.0,
295
- value=0.94,
296
- step=0.02,
297
- info="Adjusts the speed of the generated audio (1.0 = original speed).",
298
- )
299
-
300
- run_button = gr.Button("Generate Audio", variant="primary")
301
-
302
- with gr.Column(scale=1):
303
- audio_output = gr.Audio(
304
- label="Generated Audio",
305
- type="numpy",
306
- autoplay=False,
307
- )
308
-
309
- # Link button click to function
310
- run_button.click(
311
- fn=run_inference,
312
- inputs=[
313
- text_input,
314
- audio_prompt_input,
315
- max_new_tokens,
316
- cfg_scale,
317
- temperature,
318
- top_p,
319
- cfg_filter_top_k,
320
- speed_factor_slider,
321
- ],
322
- outputs=[audio_output], # Add status_output here if using it
323
- api_name="generate_audio",
324
- )
325
-
326
- # Add examples (ensure the prompt path is correct or remove it if example file doesn't exist)
327
- example_prompt_path = "./example_prompt.mp3" # Adjust if needed
328
- examples_list = [
329
- [
330
- "[S1] Oh fire! Oh my goodness! What's the procedure? What to we do people? The smoke could be coming through an air duct! \n[S2] Oh my god! Okay.. it's happening. Everybody stay calm! \n[S1] What's the procedure... \n[S2] Everybody stay fucking calm!!!... Everybody fucking calm down!!!!! \n[S1] No! No! If you touch the handle, if its hot there might be a fire down the hallway! ",
331
- None,
332
- 3072,
333
- 3.0,
334
- 1.3,
335
- 0.95,
336
- 35,
337
- 0.94,
338
- ],
339
- [
340
- "[S1] Open weights text to dialogue model. \n[S2] You get full control over scripts and voices. \n[S1] I'm biased, but I think we clearly won. \n[S2] Hard to disagree. (laughs) \n[S1] Thanks for listening to this demo. \n[S2] Try it now on Git hub and Hugging Face. \n[S1] If you liked our model, please give us a star and share to your friends. \n[S2] This was Nari Labs.",
341
- example_prompt_path if Path(example_prompt_path).exists() else None,
342
- 3072,
343
- 3.0,
344
- 1.3,
345
- 0.95,
346
- 35,
347
- 0.94,
348
- ],
349
- ]
350
-
351
- if examples_list:
352
- gr.Examples(
353
- examples=examples_list,
354
- inputs=[
355
- text_input,
356
- audio_prompt_input,
357
- max_new_tokens,
358
- cfg_scale,
359
- temperature,
360
- top_p,
361
- cfg_filter_top_k,
362
- speed_factor_slider,
363
- ],
364
- outputs=[audio_output],
365
- fn=run_inference,
366
- cache_examples=False,
367
- label="Examples (Click to Run)",
368
- )
369
- else:
370
- gr.Markdown("_(No examples configured or example prompt file missing)_")
371
-
372
- # --- Launch the App ---
373
- if __name__ == "__main__":
374
- print("Launching Gradio interface...")
375
-
376
- # set `GRADIO_SERVER_NAME`, `GRADIO_SERVER_PORT` env vars to override default values
377
- # use `GRADIO_SERVER_NAME=0.0.0.0` for Docker
378
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/tts.py CHANGED
@@ -1,72 +1,125 @@
1
  import logging
 
 
 
 
 
 
 
 
 
 
2
 
3
  # Configure logging
4
  logger = logging.getLogger(__name__)
5
 
6
- # Import the factory pattern implementation
7
- from utils.tts_factory import TTSFactory
8
 
9
- # Import base classes
10
- from utils.tts_base import TTSEngineBase, DummyTTSEngine
11
-
12
- # Import engine-specific modules
13
- from utils.tts_engines import (
14
- get_available_engines,
15
- create_engine,
16
- KokoroTTSEngine,
17
- KokoroSpaceTTSEngine,
18
- DiaTTSEngine
19
- )
 
 
 
 
 
 
 
 
 
 
20
 
21
- # Import legacy functions for backward compatibility
22
- from utils.tts_kokoro import generate_speech as kokoro_generate_speech
23
- from utils.tts_kokoro_space import generate_speech as kokoro_space_generate_speech
24
- from utils.tts_dia import generate_speech as dia_generate_speech
25
 
26
- # Convenience function to get the best available TTS engine
27
- def get_best_engine(lang_code: str = 'z') -> TTSEngineBase:
28
- """Get the best available TTS engine
29
 
30
  Args:
 
 
31
  lang_code (str): Language code for the engine
32
 
33
  Returns:
34
- TTSEngineBase: An instance of the best available TTS engine
35
  """
36
- return TTSFactory.create_engine(None, lang_code)
37
-
38
- # Function to get a TTS engine instance (for backward compatibility)
39
- def get_tts_engine(engine_type: str = None, lang_code: str = 'z') -> TTSEngineBase:
40
- """Get a TTS engine instance
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- This function is maintained for backward compatibility with app.py.
43
- New code should use the factory pattern implementation directly.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  Args:
46
- engine_type (str, optional): Type of engine to create ('kokoro', 'kokoro_space', 'dia', 'dummy')
47
- If None, the best available engine will be used
48
- lang_code (str): Language code for the engine
 
 
49
 
50
  Returns:
51
- TTSEngineBase: An instance of a TTS engine
52
  """
53
- return TTSFactory.create_engine(engine_type, lang_code)
 
54
 
55
- # Legacy function for backward compatibility
56
- def generate_speech(text: str, language: str = "z", voice: str = "af_heart", speed: float = 1.0) -> str:
57
- """Generate speech using the best available TTS engine
58
-
59
- This is a legacy function maintained for backward compatibility.
60
- New code should use the factory pattern implementation directly.
61
 
62
  Args:
63
  text (str): Input text to synthesize
64
- language (str): Language code
 
65
  voice (str): Voice ID to use
66
  speed (float): Speech speed multiplier
67
 
68
- Returns:
69
- str: Path to the generated audio file
70
  """
71
- engine = get_best_engine(language)
72
- return engine.generate_speech(text, voice, speed)
 
1
  import logging
2
+ from typing import Optional, Generator, Tuple, List, Dict, Any
3
+ import numpy as np
4
+
5
+ # Import the base class and dummy implementation
6
+ from utils.tts_simplified import TTSBase, DummyTTS
7
+
8
+ # Import the specific TTS implementations
9
+ from utils.tts_kokoro_simplified import KokoroTTS, KOKORO_AVAILABLE
10
+ from utils.tts_dia_simplified import DiaTTS, DIA_AVAILABLE
11
+ from utils.tts_cosyvoice2_simplified import CosyVoice2TTS, COSYVOICE2_AVAILABLE
12
 
13
  # Configure logging
14
  logger = logging.getLogger(__name__)
15
 
 
 
16
 
17
+ def get_available_engines() -> List[str]:
18
+ """Get a list of available TTS engines
19
+
20
+ Returns:
21
+ List[str]: List of available engine names
22
+ """
23
+ available = []
24
+
25
+ if KOKORO_AVAILABLE:
26
+ available.append('kokoro')
27
+
28
+ if DIA_AVAILABLE:
29
+ available.append('dia')
30
+
31
+ if COSYVOICE2_AVAILABLE:
32
+ available.append('cosyvoice2')
33
+
34
+ # Dummy is always available
35
+ available.append('dummy')
36
+
37
+ return available
38
 
 
 
 
 
39
 
40
+ def get_tts_engine(engine_type: Optional[str] = None, lang_code: str = 'z') -> TTSBase:
41
+ """Get a TTS engine instance
 
42
 
43
  Args:
44
+ engine_type (str, optional): Type of engine to create ('kokoro', 'dia', 'cosyvoice2', 'dummy')
45
+ If None, the best available engine will be used
46
  lang_code (str): Language code for the engine
47
 
48
  Returns:
49
+ TTSBase: An instance of a TTS engine
50
  """
51
+ # Get available engines
52
+ available_engines = get_available_engines()
53
+ logger.info(f"Available TTS engines: {available_engines}")
54
+
55
+ # If engine_type is specified, try to create that specific engine
56
+ if engine_type is not None:
57
+ if engine_type == 'kokoro' and KOKORO_AVAILABLE:
58
+ logger.info("Creating Kokoro TTS engine")
59
+ return KokoroTTS(lang_code)
60
+ elif engine_type == 'dia' and DIA_AVAILABLE:
61
+ logger.info("Creating Dia TTS engine")
62
+ return DiaTTS(lang_code)
63
+ elif engine_type == 'cosyvoice2' and COSYVOICE2_AVAILABLE:
64
+ logger.info("Creating CosyVoice2 TTS engine")
65
+ return CosyVoice2TTS(lang_code)
66
+ elif engine_type == 'dummy':
67
+ logger.info("Creating Dummy TTS engine")
68
+ return DummyTTS(lang_code)
69
+ else:
70
+ logger.warning(f"Requested engine '{engine_type}' is not available")
71
 
72
+ # If no specific engine is requested or the requested engine is not available,
73
+ # use the best available engine based on priority
74
+ priority_order = ['cosyvoice2', 'kokoro', 'dia', 'dummy']
75
+ for engine in priority_order:
76
+ if engine in available_engines:
77
+ logger.info(f"Using best available engine: {engine}")
78
+ if engine == 'kokoro':
79
+ return KokoroTTS(lang_code)
80
+ elif engine == 'dia':
81
+ return DiaTTS(lang_code)
82
+ elif engine == 'cosyvoice2':
83
+ return CosyVoice2TTS(lang_code)
84
+ elif engine == 'dummy':
85
+ return DummyTTS(lang_code)
86
+
87
+ # Fallback to dummy engine if no engines are available
88
+ logger.warning("No TTS engines available, falling back to dummy engine")
89
+ return DummyTTS(lang_code)
90
+
91
+
92
+ def generate_speech(text: str, engine_type: Optional[str] = None, lang_code: str = 'z',
93
+ voice: str = 'default', speed: float = 1.0) -> Optional[str]:
94
+ """Generate speech using the specified or best available TTS engine
95
 
96
  Args:
97
+ text (str): Input text to synthesize
98
+ engine_type (str, optional): Type of engine to use
99
+ lang_code (str): Language code
100
+ voice (str): Voice ID to use
101
+ speed (float): Speech speed multiplier
102
 
103
  Returns:
104
+ Optional[str]: Path to the generated audio file or None if generation fails
105
  """
106
+ engine = get_tts_engine(engine_type, lang_code)
107
+ return engine.generate_speech(text, voice, speed)
108
 
109
+
110
+ def generate_speech_stream(text: str, engine_type: Optional[str] = None, lang_code: str = 'z',
111
+ voice: str = 'default', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
112
+ """Generate speech stream using the specified or best available TTS engine
 
 
113
 
114
  Args:
115
  text (str): Input text to synthesize
116
+ engine_type (str, optional): Type of engine to use
117
+ lang_code (str): Language code
118
  voice (str): Voice ID to use
119
  speed (float): Speech speed multiplier
120
 
121
+ Yields:
122
+ tuple: (sample_rate, audio_data) pairs for each segment
123
  """
124
+ engine = get_tts_engine(engine_type, lang_code)
125
+ yield from engine.generate_speech_stream(text, voice, speed)
utils/tts_README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TTS Structure
2
+
3
+ This directory contains a Text-to-Speech (TTS) implementation that supports three specific models:
4
+
5
+ 1. Kokoro: https://github.com/hexgrad/kokoro
6
+ 2. Dia: https://github.com/nari-labs/dia
7
+ 3. CosyVoice2: https://github.com/nari-labs/dia
8
+
9
+ ## Structure
10
+
11
+ The TTS implementation follows a simple, clean structure:
12
+
13
+ - `tts.py`: Contains the base `TTSBase` abstract class and `DummyTTS` implementation
14
+ - `tts_kokoro.py`: Kokoro TTS implementation
15
+ - `tts_dia.py`: Dia TTS implementation
16
+ - `tts_cosyvoice2.py`: CosyVoice2 TTS implementation
17
+ - `tts_main.py`: Main entry point for TTS functionality
18
+
19
+ ## Usage
20
+
21
+ ```python
22
+ # Import the main TTS functions
23
+ from utils.tts_main import generate_speech, generate_speech_stream, get_tts_engine
24
+
25
+ # Generate speech using the best available engine
26
+ audio_path = generate_speech("Hello, world!")
27
+
28
+ # Generate speech using a specific engine
29
+ audio_path = generate_speech("Hello, world!", engine_type="kokoro")
30
+
31
+ # Generate speech with specific parameters
32
+ audio_path = generate_speech(
33
+ "Hello, world!",
34
+ engine_type="dia",
35
+ lang_code="en",
36
+ voice="default",
37
+ speed=1.0
38
+ )
39
+
40
+ # Generate speech stream
41
+ for sample_rate, audio_data in generate_speech_stream("Hello, world!"):
42
+ # Process audio data
43
+ pass
44
+
45
+ # Get a specific TTS engine instance
46
+ engine = get_tts_engine("kokoro")
47
+ audio_path = engine.generate_speech("Hello, world!")
48
+ ```
49
+
50
+ ## Error Handling
51
+
52
+ All TTS implementations include robust error handling:
53
+
54
+ 1. Each implementation checks for the availability of its dependencies
55
+ 2. If a specific engine fails, it automatically falls back to the `DummyTTS` implementation
56
+ 3. The main module prioritizes engines based on availability
57
+
58
+ ## Adding New Engines
59
+
60
+ To add a new TTS engine:
61
+
62
+ 1. Create a new file `tts_<engine_name>.py`
63
+ 2. Implement a class that inherits from `TTSBase`
64
+ 3. Add the engine to the available engines list in `tts_main.py`
utils/tts_base.py CHANGED
@@ -1,50 +1,46 @@
 
1
  import os
2
  import time
3
- import logging
4
- import soundfile as sf
5
  import numpy as np
 
 
6
  from abc import ABC, abstractmethod
7
- from typing import Tuple, Generator, Optional
8
 
9
  # Configure logging
10
  logger = logging.getLogger(__name__)
11
 
12
- class TTSEngineBase(ABC):
 
13
  """Base class for all TTS engines
14
 
15
  This abstract class defines the interface that all TTS engines must implement.
16
- It also provides common utility methods for file handling and audio generation.
17
  """
18
 
19
  def __init__(self, lang_code: str = 'z'):
20
  """Initialize the TTS engine
21
 
22
  Args:
23
- lang_code (str): Language code ('a' for US English, 'b' for British English,
24
- 'j' for Japanese, 'z' for Mandarin Chinese)
25
- Note: Not all engines support all language codes
26
  """
27
  self.lang_code = lang_code
28
- logger.info(f"Initializing {self.__class__.__name__} with language code: {lang_code}")
29
 
30
  @abstractmethod
31
- def generate_speech(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Optional[str]:
32
  """Generate speech from text
33
 
34
  Args:
35
  text (str): Input text to synthesize
36
- voice (str): Voice ID to use (e.g., 'af_heart', 'af_bella', etc.)
37
- Note: Not all engines support all voices
38
- speed (float): Speech speed multiplier (0.5 to 2.0)
39
- Note: Not all engines support speed adjustment
40
 
41
  Returns:
42
- Optional[str]: Path to the generated audio file, or None if generation fails
43
  """
44
  pass
45
 
46
- def generate_speech_stream(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
47
- """Generate speech from text and yield each segment
 
48
 
49
  Args:
50
  text (str): Input text to synthesize
@@ -54,93 +50,75 @@ class TTSEngineBase(ABC):
54
  Yields:
55
  tuple: (sample_rate, audio_data) pairs for each segment
56
  """
57
- # Default implementation: generate full audio and yield as a single chunk
58
- output_path = self.generate_speech(text, voice, speed)
59
- audio_data, sample_rate = sf.read(output_path)
60
- yield sample_rate, audio_data
61
-
62
- def _create_output_dir(self) -> str:
63
- """Create output directory for audio files
64
-
65
- Returns:
66
- str: Path to the output directory
67
- """
68
- output_dir = "temp/outputs"
69
- os.makedirs(output_dir, exist_ok=True)
70
- return output_dir
71
 
72
- def _generate_output_path(self, prefix: str = "output") -> str:
73
- """Generate a unique output path for audio files
74
 
75
  Args:
76
- prefix (str): Prefix for the output filename
 
77
 
78
  Returns:
79
  str: Path to the output file
80
  """
81
- output_dir = self._create_output_dir()
82
- timestamp = int(time.time())
83
- return f"{output_dir}/{prefix}_{timestamp}.wav"
 
 
84
 
85
 
86
- class DummyTTSEngine(TTSEngineBase):
87
- """Dummy TTS engine that generates a simple sine wave
88
 
89
- This engine is used as a fallback when no other engines are available.
90
  """
91
 
92
- def __init__(self, lang_code: str = 'z'):
93
- super().__init__(lang_code)
94
- logger.warning("Using dummy TTS implementation as no other engines are available")
95
-
96
- def generate_speech(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> str:
97
- """Generate a dummy audio file with a simple sine wave
98
 
99
  Args:
100
  text (str): Input text (not used)
101
  voice (str): Voice ID (not used)
102
- speed (float): Speed multiplier (not used)
103
 
104
  Returns:
105
- str: Path to the generated dummy audio file
106
  """
107
  logger.info(f"Generating dummy speech for text length: {len(text)}")
108
 
109
- # Generate unique output path
110
- output_path = self._generate_output_path("dummy")
111
-
112
  # Generate a simple sine wave
113
  sample_rate = 24000
114
- duration = 3.0 # seconds
115
- t = np.linspace(0, duration, int(sample_rate * duration), False)
116
- tone = np.sin(2 * np.pi * 440 * t) * 0.3
117
 
118
- # Save the audio file
119
- logger.info(f"Saving dummy audio to {output_path}")
120
- sf.write(output_path, tone, sample_rate)
121
- logger.info(f"Dummy audio generation complete: {output_path}")
122
 
 
123
  return output_path
124
 
125
- def generate_speech_stream(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
126
- """Generate dummy audio chunks with simple sine waves
127
 
128
  Args:
129
  text (str): Input text (not used)
130
  voice (str): Voice ID (not used)
131
- speed (float): Speed multiplier (not used)
132
 
133
  Yields:
134
- tuple: (sample_rate, audio_data) pairs for each dummy segment
135
  """
136
  logger.info(f"Generating dummy speech stream for text length: {len(text)}")
137
 
 
138
  sample_rate = 24000
139
- duration = 1.0 # seconds per chunk
 
 
140
 
141
- # Create 3 chunks of dummy audio
142
- for i in range(3):
143
- t = np.linspace(0, duration, int(sample_rate * duration), False)
144
- freq = 440 + (i * 220) # Different frequency for each chunk
145
- tone = np.sin(2 * np.pi * freq * t) * 0.3
146
- yield sample_rate, tone
 
1
+ import logging
2
  import os
3
  import time
 
 
4
  import numpy as np
5
+ import soundfile as sf
6
+ from typing import Optional, Generator, Tuple, List
7
  from abc import ABC, abstractmethod
 
8
 
9
  # Configure logging
10
  logger = logging.getLogger(__name__)
11
 
12
+
13
+ class TTSBase(ABC):
14
  """Base class for all TTS engines
15
 
16
  This abstract class defines the interface that all TTS engines must implement.
 
17
  """
18
 
19
  def __init__(self, lang_code: str = 'z'):
20
  """Initialize the TTS engine
21
 
22
  Args:
23
+ lang_code (str): Language code for the engine
 
 
24
  """
25
  self.lang_code = lang_code
 
26
 
27
  @abstractmethod
28
+ def generate_speech(self, text: str, voice: str = 'default', speed: float = 1.0) -> Optional[str]:
29
  """Generate speech from text
30
 
31
  Args:
32
  text (str): Input text to synthesize
33
+ voice (str): Voice ID to use
34
+ speed (float): Speech speed multiplier
 
 
35
 
36
  Returns:
37
+ Optional[str]: Path to the generated audio file or None if generation fails
38
  """
39
  pass
40
 
41
+ @abstractmethod
42
+ def generate_speech_stream(self, text: str, voice: str = 'default', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
43
+ """Generate speech stream from text
44
 
45
  Args:
46
  text (str): Input text to synthesize
 
50
  Yields:
51
  tuple: (sample_rate, audio_data) pairs for each segment
52
  """
53
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ def _generate_output_path(self, prefix: str = "tts", extension: str = "wav") -> str:
56
+ """Generate a unique output path for the audio file
57
 
58
  Args:
59
+ prefix (str): Prefix for the filename
60
+ extension (str): File extension
61
 
62
  Returns:
63
  str: Path to the output file
64
  """
65
+ timestamp = int(time.time() * 1000)
66
+ filename = f"{prefix}_{timestamp}.{extension}"
67
+ output_dir = os.path.join(os.getcwd(), "output")
68
+ os.makedirs(output_dir, exist_ok=True)
69
+ return os.path.join(output_dir, filename)
70
 
71
 
72
+ class DummyTTS(TTSBase):
73
+ """Dummy TTS engine that generates sine wave audio
74
 
75
+ This class is used as a fallback when no other TTS engine is available.
76
  """
77
 
78
+ def generate_speech(self, text: str, voice: str = 'default', speed: float = 1.0) -> str:
79
+ """Generate a dummy sine wave audio file
 
 
 
 
80
 
81
  Args:
82
  text (str): Input text (not used)
83
  voice (str): Voice ID (not used)
84
+ speed (float): Speech speed multiplier (not used)
85
 
86
  Returns:
87
+ str: Path to the generated audio file
88
  """
89
  logger.info(f"Generating dummy speech for text length: {len(text)}")
90
 
 
 
 
91
  # Generate a simple sine wave
92
  sample_rate = 24000
93
+ duration = min(len(text) / 20, 10) # Rough approximation of speech duration
94
+ t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
95
+ audio = 0.5 * np.sin(2 * np.pi * 440 * t) # 440 Hz sine wave
96
 
97
+ # Save to file
98
+ output_path = self._generate_output_path(prefix="dummy")
99
+ sf.write(output_path, audio, sample_rate)
 
100
 
101
+ logger.info(f"Generated dummy audio: {output_path}")
102
  return output_path
103
 
104
+ def generate_speech_stream(self, text: str, voice: str = 'default', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
105
+ """Generate a dummy sine wave audio stream
106
 
107
  Args:
108
  text (str): Input text (not used)
109
  voice (str): Voice ID (not used)
110
+ speed (float): Speech speed multiplier (not used)
111
 
112
  Yields:
113
+ tuple: (sample_rate, audio_data) pairs
114
  """
115
  logger.info(f"Generating dummy speech stream for text length: {len(text)}")
116
 
117
+ # Generate a simple sine wave
118
  sample_rate = 24000
119
+ duration = min(len(text) / 20, 10) # Rough approximation of speech duration
120
+ t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
121
+ audio = 0.5 * np.sin(2 * np.pi * 440 * t) # 440 Hz sine wave
122
 
123
+ # Yield the audio data
124
+ yield sample_rate, audio
 
 
 
 
utils/tts_cascading.py DELETED
@@ -1,112 +0,0 @@
1
- import logging
2
- from typing import List, Tuple, Generator, Optional
3
- import numpy as np
4
-
5
- from utils.tts_base import TTSEngineBase, DummyTTSEngine
6
- from utils.tts_engines import create_engine
7
-
8
- # Configure logging
9
- logger = logging.getLogger(__name__)
10
-
11
- class CascadingTTSEngine(TTSEngineBase):
12
- """Cascading TTS engine implementation
13
-
14
- This engine tries multiple TTS engines in order until one succeeds.
15
- It provides a fallback mechanism to maximize the chances of getting
16
- quality speech output.
17
- """
18
-
19
- def __init__(self, engine_types: List[str], lang_code: str = 'z'):
20
- """Initialize the cascading TTS engine
21
-
22
- Args:
23
- engine_types (List[str]): List of engine types to try in order
24
- lang_code (str): Language code for the engines
25
- """
26
- super().__init__(lang_code)
27
- self.engine_types = engine_types
28
- self.lang_code = lang_code
29
- logger.info(f"Initialized cascading TTS engine with engines: {engine_types}")
30
-
31
- def generate_speech(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> str:
32
- """Generate speech by trying multiple engines in order
33
-
34
- Args:
35
- text (str): Input text to synthesize
36
- voice (str): Voice ID to use
37
- speed (float): Speech speed multiplier
38
-
39
- Returns:
40
- str: Path to the generated audio file
41
- """
42
- logger.info(f"Generating speech with cascading engine for text length: {len(text)}")
43
-
44
- # Try each engine in order
45
- for engine_type in self.engine_types:
46
- try:
47
- logger.info(f"Trying TTS engine: {engine_type}")
48
- engine = create_engine(engine_type, self.lang_code)
49
-
50
- # Generate speech with the current engine
51
- result = engine.generate_speech(text, voice, speed)
52
-
53
- # If the engine returned a valid result, return it
54
- if result is not None:
55
- logger.info(f"Successfully generated speech with {engine_type}")
56
- return result
57
-
58
- logger.warning(f"TTS engine {engine_type} failed to generate speech, trying next engine")
59
- except Exception as e:
60
- logger.error(f"Error with TTS engine {engine_type}: {str(e)}")
61
- logger.error(f"Error type: {type(e).__name__}")
62
- logger.warning(f"Trying next TTS engine")
63
-
64
- # If all engines failed, fall back to dummy engine
65
- logger.warning("All TTS engines failed, falling back to dummy engine")
66
- return DummyTTSEngine(self.lang_code).generate_speech(text, voice, speed)
67
-
68
- def generate_speech_stream(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
69
- """Generate speech stream by trying multiple engines in order
70
-
71
- Args:
72
- text (str): Input text to synthesize
73
- voice (str): Voice ID to use
74
- speed (float): Speech speed multiplier
75
-
76
- Yields:
77
- tuple: (sample_rate, audio_data) pairs for each segment
78
- """
79
- logger.info(f"Generating speech stream with cascading engine for text length: {len(text)}")
80
-
81
- # Try each engine in order
82
- for engine_type in self.engine_types:
83
- try:
84
- logger.info(f"Trying TTS engine for streaming: {engine_type}")
85
- engine = create_engine(engine_type, self.lang_code)
86
-
87
- # Create a generator for the current engine
88
- generator = engine.generate_speech_stream(text, voice, speed)
89
-
90
- # Try to get the first chunk to verify the engine works
91
- first_chunk = next(generator, None)
92
- if first_chunk is not None:
93
- # Engine produced a valid first chunk, yield it and continue with this engine
94
- logger.info(f"Successfully started speech stream with {engine_type}")
95
- yield first_chunk
96
-
97
- # Yield the rest of the chunks from this engine
98
- for chunk in generator:
99
- yield chunk
100
-
101
- # Successfully streamed all chunks, return
102
- return
103
-
104
- logger.warning(f"TTS engine {engine_type} failed to generate speech stream, trying next engine")
105
- except Exception as e:
106
- logger.error(f"Error with TTS engine {engine_type} streaming: {str(e)}")
107
- logger.error(f"Error type: {type(e).__name__}")
108
- logger.warning(f"Trying next TTS engine for streaming")
109
-
110
- # If all engines failed, fall back to dummy engine
111
- logger.warning("All TTS engines failed for streaming, falling back to dummy engine")
112
- yield from DummyTTSEngine(self.lang_code).generate_speech_stream(text, voice, speed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/tts_cosyvoice2.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import numpy as np
3
+ import soundfile as sf
4
+ from typing import Optional, Generator, Tuple
5
+
6
+ from utils.tts_simplified import TTSBase, DummyTTS
7
+
8
+ # Configure logging
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # Flag to track CosyVoice2 availability
12
+ COSYVOICE2_AVAILABLE = False
13
+ DEFAULT_SAMPLE_RATE = 24000
14
+
15
+ # Try to import CosyVoice2 dependencies
16
+ try:
17
+ import torch
18
+ # Import CosyVoice2 - assuming it's installed and has a similar API to Dia
19
+ # since they're both from nari-labs according to the GitHub link
20
+ from cosyvoice2.model import CosyVoice2
21
+ COSYVOICE2_AVAILABLE = True
22
+ logger.info("CosyVoice2 TTS engine is available")
23
+ except ImportError:
24
+ logger.warning("CosyVoice2 TTS engine is not available")
25
+ except ModuleNotFoundError as e:
26
+ logger.warning(f"CosyVoice2 TTS engine is not available: {str(e)}")
27
+ COSYVOICE2_AVAILABLE = False
28
+
29
+
30
+ def _get_model():
31
+ """Lazy-load the CosyVoice2 model
32
+
33
+ Returns:
34
+ CosyVoice2 or None: The CosyVoice2 model or None if not available
35
+ """
36
+ if not COSYVOICE2_AVAILABLE:
37
+ logger.warning("CosyVoice2 TTS engine is not available")
38
+ return None
39
+
40
+ try:
41
+ import torch
42
+ from cosyvoice2.model import CosyVoice2
43
+
44
+ # Initialize the model
45
+ model = CosyVoice2.from_pretrained()
46
+ logger.info("CosyVoice2 model successfully loaded")
47
+ return model
48
+ except ImportError as e:
49
+ logger.error(f"Failed to import CosyVoice2 dependencies: {str(e)}")
50
+ return None
51
+ except FileNotFoundError as e:
52
+ logger.error(f"Failed to load CosyVoice2 model files: {str(e)}")
53
+ return None
54
+ except Exception as e:
55
+ logger.error(f"Failed to initialize CosyVoice2 model: {str(e)}")
56
+ return None
57
+
58
+
59
+ class CosyVoice2TTS(TTSBase):
60
+ """CosyVoice2 TTS engine implementation
61
+
62
+ This engine uses the CosyVoice2 model for TTS generation.
63
+ """
64
+
65
+ def __init__(self, lang_code: str = 'z'):
66
+ """Initialize the CosyVoice2 TTS engine
67
+
68
+ Args:
69
+ lang_code (str): Language code for the engine
70
+ """
71
+ super().__init__(lang_code)
72
+ self.model = None
73
+
74
+ def _ensure_model(self):
75
+ """Ensure the model is loaded
76
+
77
+ Returns:
78
+ bool: True if model is available, False otherwise
79
+ """
80
+ if self.model is None:
81
+ self.model = _get_model()
82
+
83
+ return self.model is not None
84
+
85
+ def generate_speech(self, text: str, voice: str = 'default', speed: float = 1.0) -> Optional[str]:
86
+ """Generate speech using CosyVoice2 TTS engine
87
+
88
+ Args:
89
+ text (str): Input text to synthesize
90
+ voice (str): Voice ID (may not be used in CosyVoice2)
91
+ speed (float): Speech speed multiplier (may not be used in CosyVoice2)
92
+
93
+ Returns:
94
+ Optional[str]: Path to the generated audio file or None if generation fails
95
+ """
96
+ logger.info(f"Generating speech with CosyVoice2 for text length: {len(text)}")
97
+
98
+ # Check if CosyVoice2 is available
99
+ if not COSYVOICE2_AVAILABLE:
100
+ logger.warning("CosyVoice2 TTS engine is not available, falling back to dummy TTS")
101
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
102
+
103
+ # Ensure model is loaded
104
+ if not self._ensure_model():
105
+ logger.warning("Failed to load CosyVoice2 model, falling back to dummy TTS")
106
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
107
+
108
+ try:
109
+ import torch
110
+
111
+ # Generate unique output path
112
+ output_path = self._generate_output_path(prefix="cosyvoice2")
113
+
114
+ # Generate audio
115
+ with torch.inference_mode():
116
+ # Assuming CosyVoice2 has a similar API to Dia
117
+ output_audio_np = self.model.generate(
118
+ text,
119
+ max_tokens=None,
120
+ cfg_scale=3.0,
121
+ temperature=1.3,
122
+ top_p=0.95,
123
+ use_torch_compile=False,
124
+ verbose=False
125
+ )
126
+
127
+ if output_audio_np is not None:
128
+ logger.info(f"Successfully generated audio with CosyVoice2 (length: {len(output_audio_np)})")
129
+ sf.write(output_path, output_audio_np, DEFAULT_SAMPLE_RATE)
130
+ logger.info(f"CosyVoice2 audio generation complete: {output_path}")
131
+ return output_path
132
+ else:
133
+ logger.warning("CosyVoice2 model returned None for audio output")
134
+ logger.warning("Falling back to dummy TTS")
135
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
136
+
137
+ except Exception as e:
138
+ logger.error(f"Error generating speech with CosyVoice2: {str(e)}", exc_info=True)
139
+ logger.warning("CosyVoice2 TTS engine failed, falling back to dummy TTS")
140
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
141
+
142
+ def generate_speech_stream(self, text: str, voice: str = 'default', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
143
+ """Generate speech stream using CosyVoice2 TTS engine
144
+
145
+ Args:
146
+ text (str): Input text to synthesize
147
+ voice (str): Voice ID (may not be used in CosyVoice2)
148
+ speed (float): Speech speed multiplier (may not be used in CosyVoice2)
149
+
150
+ Yields:
151
+ tuple: (sample_rate, audio_data) pairs for each segment
152
+ """
153
+ logger.info(f"Generating speech stream with CosyVoice2 for text length: {len(text)}")
154
+
155
+ # Check if CosyVoice2 is available
156
+ if not COSYVOICE2_AVAILABLE:
157
+ logger.warning("CosyVoice2 TTS engine is not available, falling back to dummy TTS")
158
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
159
+ return
160
+
161
+ # Ensure model is loaded
162
+ if not self._ensure_model():
163
+ logger.warning("Failed to load CosyVoice2 model, falling back to dummy TTS")
164
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
165
+ return
166
+
167
+ try:
168
+ import torch
169
+
170
+ # Generate audio
171
+ with torch.inference_mode():
172
+ # Assuming CosyVoice2 has a similar API to Dia
173
+ output_audio_np = self.model.generate(
174
+ text,
175
+ max_tokens=None,
176
+ cfg_scale=3.0,
177
+ temperature=1.3,
178
+ top_p=0.95,
179
+ use_torch_compile=False,
180
+ verbose=False
181
+ )
182
+
183
+ if output_audio_np is not None:
184
+ logger.info(f"Successfully generated audio with CosyVoice2 (length: {len(output_audio_np)})")
185
+ yield DEFAULT_SAMPLE_RATE, output_audio_np
186
+ else:
187
+ logger.warning("CosyVoice2 model returned None for audio output")
188
+ logger.warning("Falling back to dummy TTS")
189
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
190
+
191
+ except Exception as e:
192
+ logger.error(f"Error generating speech stream with CosyVoice2: {str(e)}", exc_info=True)
193
+ logger.warning("CosyVoice2 TTS engine failed, falling back to dummy TTS")
194
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
utils/tts_dia.py CHANGED
@@ -1,135 +1,207 @@
1
- import os
2
- import time
3
  import logging
4
  import numpy as np
5
  import soundfile as sf
6
- from pathlib import Path
7
- from typing import Optional
 
8
 
9
  # Configure logging
10
- logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
  # Flag to track Dia availability
14
  DIA_AVAILABLE = False
 
15
 
16
- # Try to import required dependencies
17
  try:
18
  import torch
19
- # Try to import Dia, which will try to import dac
20
- try:
21
- from dia.model import Dia
22
- DIA_AVAILABLE = True
23
- logger.info("Dia TTS engine is available")
24
- except ModuleNotFoundError as e:
25
- if "dac" in str(e):
26
- logger.warning("Dia TTS engine is not available due to missing 'dac' module")
27
- else:
28
- logger.warning(f"Dia TTS engine is not available: {str(e)}")
29
- DIA_AVAILABLE = False
30
  except ImportError:
31
- logger.warning("Torch not available, Dia TTS engine cannot be used")
 
 
 
 
 
32
  DIA_AVAILABLE = False
33
 
34
- # Constants
35
- DEFAULT_SAMPLE_RATE = 44100
36
- DEFAULT_MODEL_NAME = "nari-labs/Dia-1.6B"
37
-
38
- # Global model instance (lazy loaded)
39
- _model = None
40
-
41
 
42
  def _get_model():
43
- """Lazy-load the Dia model to avoid loading it until needed"""
44
- global _model
45
 
46
- # Check if Dia is available before attempting to load
 
 
47
  if not DIA_AVAILABLE:
48
- logger.warning("Dia is not available, cannot load model")
49
- raise ImportError("Dia module is not available")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- if _model is None:
52
- logger.info("Loading Dia model...")
53
  try:
54
- # Check if torch is available with correct version
55
- logger.info(f"PyTorch version: {torch.__version__}")
56
- logger.info(f"CUDA available: {torch.cuda.is_available()}")
57
- if torch.cuda.is_available():
58
- logger.info(f"CUDA version: {torch.version.cuda}")
59
- logger.info(f"GPU device: {torch.cuda.get_device_name(0)}")
60
 
61
- # Check if model path exists
62
- logger.info(f"Attempting to load model from: {DEFAULT_MODEL_NAME}")
63
 
64
- # Load the model with detailed logging
65
- logger.info("Initializing Dia model...")
66
- _model = Dia.from_pretrained(DEFAULT_MODEL_NAME, compute_dtype="float16")
 
 
 
 
 
 
 
 
 
67
 
68
- # Log model details
69
- logger.info(f"Dia model loaded successfully")
70
- logger.info(f"Model type: {type(_model).__name__}")
71
- # Check if model has parameters method (PyTorch models do, but Dia might not)
72
- if hasattr(_model, 'parameters'):
73
- logger.info(f"Model device: {next(_model.parameters()).device}")
74
  else:
75
- logger.info("Model device: Device information not available for Dia model")
76
- except ImportError as import_err:
77
- logger.error(f"Import error loading Dia model: {import_err}")
78
- logger.error(f"This may indicate missing dependencies")
79
- raise
80
- except FileNotFoundError as file_err:
81
- logger.error(f"File not found error loading Dia model: {file_err}")
82
- logger.error(f"Model path may be incorrect or inaccessible")
83
- raise
 
84
  except Exception as e:
85
- logger.error(f"Error loading Dia model: {e}", exc_info=True)
86
- logger.error(f"Error type: {type(e).__name__}")
87
- logger.error(f"This may indicate incompatible versions or missing CUDA support")
88
- raise
89
- return _model
90
-
91
-
92
- def generate_speech(text: str, language: str = "zh") -> str:
93
- """Public interface for TTS generation using Dia model
94
 
95
- This is a legacy function maintained for backward compatibility.
96
- New code should use the factory pattern implementation directly.
97
-
98
- Args:
99
- text (str): Input text to synthesize
100
- language (str): Language code (not used in Dia model, kept for API compatibility)
101
 
102
- Returns:
103
- str: Path to the generated audio file
104
- """
105
- logger.info(f"Legacy Dia generate_speech called with text length: {len(text)}")
106
-
107
- # Check if Dia is available
108
- if not DIA_AVAILABLE:
109
- logger.warning("Dia is not available, falling back to dummy TTS engine")
110
- from utils.tts_base import DummyTTSEngine
111
- dummy_engine = DummyTTSEngine(language)
112
- return dummy_engine.generate_speech(text)
113
-
114
- # Use the new implementation via factory pattern
115
- try:
116
- # Import here to avoid circular imports
117
- from utils.tts_engines import DiaTTSEngine
118
 
119
- # Create a Dia engine and generate speech
120
- dia_engine = DiaTTSEngine(language)
121
- return dia_engine.generate_speech(text)
122
- except ModuleNotFoundError as e:
123
- logger.error(f"Module not found error in Dia generate_speech: {str(e)}")
124
- if "dac" in str(e):
125
- logger.warning("Dia TTS engine failed due to missing 'dac' module, falling back to dummy TTS")
126
- # Fall back to dummy TTS
127
- from utils.tts_base import DummyTTSEngine
128
- dummy_engine = DummyTTSEngine(language)
129
- return dummy_engine.generate_speech(text)
130
- except Exception as e:
131
- logger.error(f"Error in legacy Dia generate_speech: {str(e)}", exc_info=True)
132
- # Fall back to dummy TTS
133
- from utils.tts_base import DummyTTSEngine
134
- dummy_engine = DummyTTSEngine(language)
135
- return dummy_engine.generate_speech(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import logging
2
  import numpy as np
3
  import soundfile as sf
4
+ from typing import Optional, Generator, Tuple
5
+
6
+ from utils.tts_simplified import TTSBase, DummyTTS
7
 
8
  # Configure logging
 
9
  logger = logging.getLogger(__name__)
10
 
11
  # Flag to track Dia availability
12
  DIA_AVAILABLE = False
13
+ DEFAULT_SAMPLE_RATE = 24000
14
 
15
+ # Try to import Dia dependencies
16
  try:
17
  import torch
18
+ from dia.model import Dia
19
+ DIA_AVAILABLE = True
20
+ logger.info("Dia TTS engine is available")
 
 
 
 
 
 
 
 
21
  except ImportError:
22
+ logger.warning("Dia TTS engine is not available")
23
+ except ModuleNotFoundError as e:
24
+ if "dac" in str(e):
25
+ logger.warning("Dia TTS engine is not available due to missing 'dac' module")
26
+ else:
27
+ logger.warning(f"Dia TTS engine is not available: {str(e)}")
28
  DIA_AVAILABLE = False
29
 
 
 
 
 
 
 
 
30
 
31
  def _get_model():
32
+ """Lazy-load the Dia model
 
33
 
34
+ Returns:
35
+ Dia or None: The Dia model or None if not available
36
+ """
37
  if not DIA_AVAILABLE:
38
+ logger.warning("Dia TTS engine is not available")
39
+ return None
40
+
41
+ try:
42
+ import torch
43
+ from dia.model import Dia
44
+
45
+ # Initialize the model
46
+ model = Dia.from_pretrained()
47
+ logger.info("Dia model successfully loaded")
48
+ return model
49
+ except ImportError as e:
50
+ logger.error(f"Failed to import Dia dependencies: {str(e)}")
51
+ return None
52
+ except FileNotFoundError as e:
53
+ logger.error(f"Failed to load Dia model files: {str(e)}")
54
+ return None
55
+ except Exception as e:
56
+ logger.error(f"Failed to initialize Dia model: {str(e)}")
57
+ return None
58
+
59
+
60
+ class DiaTTS(TTSBase):
61
+ """Dia TTS engine implementation
62
+
63
+ This engine uses the Dia model for TTS generation.
64
+ """
65
+
66
+ def __init__(self, lang_code: str = 'z'):
67
+ """Initialize the Dia TTS engine
68
+
69
+ Args:
70
+ lang_code (str): Language code for the engine
71
+ """
72
+ super().__init__(lang_code)
73
+ self.model = None
74
+
75
+ def _ensure_model(self):
76
+ """Ensure the model is loaded
77
+
78
+ Returns:
79
+ bool: True if model is available, False otherwise
80
+ """
81
+ if self.model is None:
82
+ self.model = _get_model()
83
+
84
+ return self.model is not None
85
+
86
+ def generate_speech(self, text: str, voice: str = 'default', speed: float = 1.0) -> Optional[str]:
87
+ """Generate speech using Dia TTS engine
88
+
89
+ Args:
90
+ text (str): Input text to synthesize
91
+ voice (str): Voice ID (not used in Dia)
92
+ speed (float): Speech speed multiplier (not used in Dia)
93
+
94
+ Returns:
95
+ Optional[str]: Path to the generated audio file or None if generation fails
96
+ """
97
+ logger.info(f"Generating speech with Dia for text length: {len(text)}")
98
+
99
+ # Check if Dia is available
100
+ if not DIA_AVAILABLE:
101
+ logger.warning("Dia TTS engine is not available, falling back to dummy TTS")
102
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
103
+
104
+ # Ensure model is loaded
105
+ if not self._ensure_model():
106
+ logger.warning("Failed to load Dia model, falling back to dummy TTS")
107
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
108
 
 
 
109
  try:
110
+ import torch
 
 
 
 
 
111
 
112
+ # Generate unique output path
113
+ output_path = self._generate_output_path(prefix="dia")
114
 
115
+ # Generate audio
116
+ with torch.inference_mode():
117
+ output_audio_np = self.model.generate(
118
+ text,
119
+ max_tokens=None,
120
+ cfg_scale=3.0,
121
+ temperature=1.3,
122
+ top_p=0.95,
123
+ cfg_filter_top_k=35,
124
+ use_torch_compile=False,
125
+ verbose=False
126
+ )
127
 
128
+ if output_audio_np is not None:
129
+ logger.info(f"Successfully generated audio with Dia (length: {len(output_audio_np)})")
130
+ sf.write(output_path, output_audio_np, DEFAULT_SAMPLE_RATE)
131
+ logger.info(f"Dia audio generation complete: {output_path}")
132
+ return output_path
 
133
  else:
134
+ logger.warning("Dia model returned None for audio output")
135
+ logger.warning("Falling back to dummy TTS")
136
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
137
+
138
+ except ModuleNotFoundError as e:
139
+ if "dac" in str(e):
140
+ logger.warning("Dia TTS engine failed due to missing 'dac' module, falling back to dummy TTS")
141
+ else:
142
+ logger.error(f"Module not found error in Dia TTS: {str(e)}")
143
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
144
  except Exception as e:
145
+ logger.error(f"Error generating speech with Dia: {str(e)}", exc_info=True)
146
+ logger.warning("Dia TTS engine failed, falling back to dummy TTS")
147
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
 
 
 
 
 
 
148
 
149
+ def generate_speech_stream(self, text: str, voice: str = 'default', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
150
+ """Generate speech stream using Dia TTS engine
 
 
 
 
151
 
152
+ Args:
153
+ text (str): Input text to synthesize
154
+ voice (str): Voice ID (not used in Dia)
155
+ speed (float): Speech speed multiplier (not used in Dia)
156
+
157
+ Yields:
158
+ tuple: (sample_rate, audio_data) pairs for each segment
159
+ """
160
+ logger.info(f"Generating speech stream with Dia for text length: {len(text)}")
 
 
 
 
 
 
 
161
 
162
+ # Check if Dia is available
163
+ if not DIA_AVAILABLE:
164
+ logger.warning("Dia TTS engine is not available, falling back to dummy TTS")
165
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
166
+ return
167
+
168
+ # Ensure model is loaded
169
+ if not self._ensure_model():
170
+ logger.warning("Failed to load Dia model, falling back to dummy TTS")
171
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
172
+ return
173
+
174
+ try:
175
+ import torch
176
+
177
+ # Generate audio
178
+ with torch.inference_mode():
179
+ output_audio_np = self.model.generate(
180
+ text,
181
+ max_tokens=None,
182
+ cfg_scale=3.0,
183
+ temperature=1.3,
184
+ top_p=0.95,
185
+ cfg_filter_top_k=35,
186
+ use_torch_compile=False,
187
+ verbose=False
188
+ )
189
+
190
+ if output_audio_np is not None:
191
+ logger.info(f"Successfully generated audio with Dia (length: {len(output_audio_np)})")
192
+ yield DEFAULT_SAMPLE_RATE, output_audio_np
193
+ else:
194
+ logger.warning("Dia model returned None for audio output")
195
+ logger.warning("Falling back to dummy TTS")
196
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
197
+
198
+ except ModuleNotFoundError as e:
199
+ if "dac" in str(e):
200
+ logger.warning("Dia TTS engine failed due to missing 'dac' module, falling back to dummy TTS")
201
+ else:
202
+ logger.error(f"Module not found error in Dia TTS: {str(e)}")
203
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
204
+ except Exception as e:
205
+ logger.error(f"Error generating speech stream with Dia: {str(e)}", exc_info=True)
206
+ logger.warning("Dia TTS engine failed, falling back to dummy TTS")
207
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
utils/tts_dia_space.py DELETED
@@ -1,154 +0,0 @@
1
- import os
2
- import time
3
- import logging
4
- import requests
5
- import numpy as np
6
- import soundfile as sf
7
- from typing import Optional, Tuple, Generator
8
-
9
- # Configure logging
10
- logging.basicConfig(level=logging.INFO)
11
- logger = logging.getLogger(__name__)
12
-
13
- # Constants
14
- DEFAULT_SAMPLE_RATE = 44100
15
- DEFAULT_API_URL = "https://droolingpanda-dia-tts-server.hf.space"
16
- DEFAULT_MODEL = "dia-1.6b"
17
-
18
- # Global client instance (lazy loaded)
19
- _client = None
20
-
21
-
22
- def _get_client():
23
- """Lazy-load the Dia Space client to avoid loading it until needed"""
24
- global _client
25
- if _client is None:
26
- logger.info("Loading Dia Space client...")
27
- try:
28
- # Import requests if not already imported
29
- import requests
30
-
31
- # Initialize the client (just a session for now)
32
- logger.info("Initializing Dia Space client")
33
- _client = requests.Session()
34
-
35
- # Test connection to the API
36
- response = _client.get(f"{DEFAULT_API_URL}/docs")
37
- if response.status_code == 200:
38
- logger.info("Dia Space client loaded successfully")
39
- logger.info(f"Client type: {type(_client).__name__}")
40
- else:
41
- logger.warning(f"Dia Space API returned status code {response.status_code}")
42
- except ImportError as import_err:
43
- logger.error(f"Import error loading Dia Space client: {import_err}")
44
- logger.error("This may indicate missing dependencies")
45
- raise
46
- except Exception as e:
47
- logger.error(f"Error loading Dia Space client: {e}", exc_info=True)
48
- logger.error(f"Error type: {type(e).__name__}")
49
- raise
50
- return _client
51
-
52
-
53
- def generate_speech(text: str, language: str = "zh", voice: str = "S1", response_format: str = "wav", speed: float = 1.0) -> str:
54
- """Public interface for TTS generation using Dia Space API
55
-
56
- This is a legacy function maintained for backward compatibility.
57
- New code should use the factory pattern implementation directly.
58
-
59
- Args:
60
- text (str): Input text to synthesize
61
- language (str): Language code (not used in Dia Space, kept for API compatibility)
62
- voice (str): Voice mode to use ('S1', 'S2', 'dialogue', or filename for clone)
63
- response_format (str): Audio format ('wav', 'mp3', 'opus')
64
- speed (float): Speech speed multiplier
65
-
66
- Returns:
67
- str: Path to the generated audio file
68
- """
69
- logger.info(f"Legacy Dia Space generate_speech called with text length: {len(text)}")
70
-
71
- # Use the new implementation via factory pattern
72
- from utils.tts_engines import DiaSpaceTTSEngine
73
-
74
- try:
75
- # Create a Dia Space engine and generate speech
76
- dia_space_engine = DiaSpaceTTSEngine(language)
77
- return dia_space_engine.generate_speech(text, voice, speed, response_format)
78
- except Exception as e:
79
- logger.error(f"Error in legacy Dia Space generate_speech: {str(e)}", exc_info=True)
80
- # Fall back to dummy TTS
81
- from utils.tts_base import DummyTTSEngine
82
- dummy_engine = DummyTTSEngine()
83
- return dummy_engine.generate_speech(text)
84
-
85
-
86
- def _create_output_dir() -> str:
87
- """Create output directory for audio files
88
-
89
- Returns:
90
- str: Path to the output directory
91
- """
92
- output_dir = "temp/outputs"
93
- os.makedirs(output_dir, exist_ok=True)
94
- return output_dir
95
-
96
-
97
- def _generate_output_path(prefix: str = "output", extension: str = "wav") -> str:
98
- """Generate a unique output path for audio files
99
-
100
- Args:
101
- prefix (str): Prefix for the output filename
102
- extension (str): File extension for the output file
103
-
104
- Returns:
105
- str: Path to the output file
106
- """
107
- output_dir = _create_output_dir()
108
- timestamp = int(time.time())
109
- return f"{output_dir}/{prefix}_{timestamp}.{extension}"
110
-
111
-
112
- def _call_dia_api(text: str, voice: str = "S1", response_format: str = "wav", speed: float = 1.0) -> bytes:
113
- """Call the Dia Space API to generate speech
114
-
115
- Args:
116
- text (str): Input text to synthesize
117
- voice (str): Voice mode to use ('S1', 'S2', 'dialogue', or filename for clone)
118
- response_format (str): Audio format ('wav', 'mp3', 'opus')
119
- speed (float): Speech speed multiplier
120
-
121
- Returns:
122
- bytes: Audio data
123
- """
124
- client = _get_client()
125
-
126
- # Prepare the request payload
127
- payload = {
128
- "model": DEFAULT_MODEL,
129
- "input": text,
130
- "voice": voice,
131
- "response_format": response_format,
132
- "speed": speed
133
- }
134
-
135
- # Make the API request
136
- logger.info(f"Calling Dia Space API with voice: {voice}, format: {response_format}, speed: {speed}")
137
- try:
138
- response = client.post(
139
- f"{DEFAULT_API_URL}/v1/audio/speech",
140
- json=payload,
141
- headers={"Content-Type": "application/json"}
142
- )
143
-
144
- # Check for successful response
145
- if response.status_code == 200:
146
- logger.info("Dia Space API call successful")
147
- return response.content
148
- else:
149
- logger.error(f"Dia Space API returned error: {response.status_code}")
150
- logger.error(f"Response: {response.text}")
151
- raise Exception(f"Dia Space API error: {response.status_code}")
152
- except Exception as e:
153
- logger.error(f"Error calling Dia Space API: {str(e)}", exc_info=True)
154
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/tts_engines.py DELETED
@@ -1,419 +0,0 @@
1
- import logging
2
- import time
3
- import os
4
- import numpy as np
5
- import soundfile as sf
6
- from typing import Dict, List, Optional, Tuple, Generator, Any, Union
7
-
8
- from utils.tts_base import TTSEngineBase, DummyTTSEngine
9
-
10
- # Configure logging
11
- logger = logging.getLogger(__name__)
12
-
13
- # Flag to track TTS engine availability
14
- KOKORO_AVAILABLE = False
15
- KOKORO_SPACE_AVAILABLE = True
16
- DIA_AVAILABLE = False
17
- DIA_SPACE_AVAILABLE = True
18
-
19
- # Try to import Kokoro
20
- try:
21
- from kokoro import KPipeline
22
- KOKORO_AVAILABLE = True
23
- logger.info("Kokoro TTS engine is available")
24
- except AttributeError as e:
25
- # Specifically catch the EspeakWrapper.set_data_path error
26
- if "EspeakWrapper" in str(e) and "set_data_path" in str(e):
27
- logger.warning("Kokoro import failed due to EspeakWrapper.set_data_path issue, falling back to Kokoro FastAPI server")
28
- else:
29
- # Re-raise if it's a different error
30
- logger.error(f"Kokoro import failed with unexpected error: {str(e)}")
31
- raise
32
- except ImportError:
33
- logger.warning("Kokoro TTS engine is not available")
34
-
35
- # Try to import Dia dependencies to check availability
36
- try:
37
- import torch
38
- from dia.model import Dia
39
- DIA_AVAILABLE = True
40
- logger.info("Dia TTS engine is available")
41
- except ImportError:
42
- logger.warning("Dia TTS engine is not available")
43
- except ModuleNotFoundError as e:
44
- if "dac" in str(e):
45
- logger.warning("Dia TTS engine is not available due to missing 'dac' module")
46
- else:
47
- logger.warning(f"Dia TTS engine is not available: {str(e)}")
48
- DIA_AVAILABLE = False
49
-
50
-
51
- class KokoroTTSEngine(TTSEngineBase):
52
- """Kokoro TTS engine implementation
53
-
54
- This engine uses the Kokoro library for TTS generation.
55
- """
56
-
57
- def __init__(self, lang_code: str = 'z'):
58
- super().__init__(lang_code)
59
- try:
60
- self.pipeline = KPipeline(lang_code=lang_code)
61
- logger.info("Kokoro TTS engine successfully initialized")
62
- except Exception as e:
63
- logger.error(f"Failed to initialize Kokoro pipeline: {str(e)}")
64
- logger.error(f"Error type: {type(e).__name__}")
65
- raise
66
-
67
- def generate_speech(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Optional[str]:
68
- """Generate speech using Kokoro TTS engine
69
-
70
- Args:
71
- text (str): Input text to synthesize
72
- voice (str): Voice ID to use (e.g., 'af_heart', 'af_bella', etc.)
73
- speed (float): Speech speed multiplier (0.5 to 2.0)
74
-
75
- Returns:
76
- Optional[str]: Path to the generated audio file or None if generation fails
77
- """
78
- logger.info(f"Generating speech with Kokoro for text length: {len(text)}")
79
-
80
- # Generate unique output path
81
- output_path = self._generate_output_path()
82
-
83
- # Generate speech
84
- generator = self.pipeline(text, voice=voice, speed=speed)
85
- for _, _, audio in generator:
86
- logger.info(f"Saving Kokoro audio to {output_path}")
87
- sf.write(output_path, audio, 24000)
88
- break
89
-
90
- logger.info(f"Kokoro audio generation complete: {output_path}")
91
- return output_path
92
-
93
- def generate_speech_stream(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
94
- """Generate speech stream using Kokoro TTS engine
95
-
96
- Args:
97
- text (str): Input text to synthesize
98
- voice (str): Voice ID to use
99
- speed (float): Speech speed multiplier
100
-
101
- Yields:
102
- tuple: (sample_rate, audio_data) pairs for each segment
103
- """
104
- logger.info(f"Generating speech stream with Kokoro for text length: {len(text)}")
105
-
106
- # Generate speech stream
107
- generator = self.pipeline(text, voice=voice, speed=speed)
108
- for _, _, audio in generator:
109
- yield 24000, audio
110
-
111
-
112
- class KokoroSpaceTTSEngine(TTSEngineBase):
113
- """Kokoro Space TTS engine implementation
114
-
115
- This engine uses the Kokoro FastAPI server for TTS generation.
116
- """
117
-
118
- def __init__(self, lang_code: str = 'z'):
119
- super().__init__(lang_code)
120
- try:
121
- from gradio_client import Client
122
- self.client = Client("Remsky/Kokoro-TTS-Zero")
123
- logger.info("Kokoro Space TTS engine successfully initialized")
124
- except Exception as e:
125
- logger.error(f"Failed to initialize Kokoro Space client: {str(e)}")
126
- logger.error(f"Error type: {type(e).__name__}")
127
- raise
128
-
129
- def generate_speech(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Optional[str]:
130
- """Generate speech using Kokoro Space TTS engine
131
-
132
- Args:
133
- text (str): Input text to synthesize
134
- voice (str): Voice ID to use (e.g., 'af_heart', 'af_bella', etc.)
135
- speed (float): Speech speed multiplier (0.5 to 2.0)
136
-
137
- Returns:
138
- Optional[str]: Path to the generated audio file or None if generation fails
139
- """
140
- logger.info(f"Generating speech with Kokoro Space for text length: {len(text)}")
141
- logger.info(f"Text to generate speech on is: {text[:50]}..." if len(text) > 50 else f"Text to generate speech on is: {text}")
142
-
143
- # Generate unique output path
144
- output_path = self._generate_output_path()
145
-
146
- try:
147
- # Use af_nova as the default voice for Kokoro Space
148
- voice_to_use = 'af_nova' if voice == 'af_heart' else voice
149
-
150
- # Generate speech
151
- result = self.client.predict(
152
- text=text,
153
- voice_names=voice_to_use,
154
- speed=speed,
155
- api_name="/generate_speech_from_ui"
156
- )
157
- logger.info(f"Received audio from Kokoro FastAPI server: {result}")
158
-
159
- # Process the result and save to output_path
160
- # Return the result path directly if it's a string
161
- if isinstance(result, str) and os.path.exists(result):
162
- return result
163
- else:
164
- logger.warning("Unexpected result from Kokoro Space")
165
- return None
166
-
167
- except Exception as e:
168
- logger.error(f"Failed to generate speech from Kokoro FastAPI server: {str(e)}")
169
- logger.error(f"Error type: {type(e).__name__}")
170
- logger.info("Kokoro Space TTS engine failed")
171
- return None
172
-
173
-
174
- class DiaTTSEngine(TTSEngineBase):
175
- """Dia TTS engine implementation
176
-
177
- This engine uses the Dia model for TTS generation.
178
- """
179
-
180
- def __init__(self, lang_code: str = 'z'):
181
- super().__init__(lang_code)
182
- # Dia doesn't need initialization here, it will be lazy-loaded when needed
183
- logger.info("Dia TTS engine initialized (lazy loading)")
184
-
185
- def generate_speech(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Optional[str]:
186
- """Generate speech using Dia TTS engine
187
-
188
- Args:
189
- text (str): Input text to synthesize
190
- voice (str): Voice ID (not used in Dia)
191
- speed (float): Speech speed multiplier (not used in Dia)
192
-
193
- Returns:
194
- Optional[str]: Path to the generated audio file or None if generation fails
195
- """
196
- logger.info(f"Generating speech with Dia for text length: {len(text)}")
197
-
198
- try:
199
- # Import here to avoid circular imports
200
- from utils.tts_dia import generate_speech as dia_generate_speech, DIA_AVAILABLE
201
-
202
- # Check if Dia is available
203
- if not DIA_AVAILABLE:
204
- logger.warning("Dia TTS engine is not available")
205
- return None
206
-
207
- logger.info("Successfully imported Dia speech generation function")
208
-
209
- # Call Dia's generate_speech function
210
- # Note: Dia's function expects a language parameter, not voice or speed
211
- output_path = dia_generate_speech(text, language=self.lang_code)
212
- logger.info(f"Generated audio with Dia: {output_path}")
213
- return output_path
214
- except ModuleNotFoundError as e:
215
- if "dac" in str(e):
216
- logger.warning("Dia TTS engine failed due to missing 'dac' module")
217
- return None
218
- raise
219
- except Exception as e:
220
- logger.error(f"Error generating speech with Dia: {str(e)}", exc_info=True)
221
- logger.warning("Dia TTS engine failed")
222
- return None
223
-
224
-
225
- class DiaSpaceTTSEngine(TTSEngineBase):
226
- """Dia Space TTS engine implementation
227
-
228
- This engine uses the Dia TTS Server API for speech generation.
229
- """
230
-
231
- def __init__(self, lang_code: str = 'z'):
232
- super().__init__(lang_code)
233
- try:
234
- # Import here to avoid circular imports
235
- from utils.tts_dia_space import _get_client
236
- self.client = _get_client()
237
- logger.info("Dia Space TTS engine successfully initialized")
238
- except Exception as e:
239
- logger.error(f"Failed to initialize Dia Space client: {str(e)}")
240
- logger.error(f"Error type: {type(e).__name__}")
241
- raise
242
-
243
- def generate_speech(self, text: str, voice: str = 'S1', speed: float = 1.0, response_format: str = 'wav') -> Optional[str]:
244
- """Generate speech using Dia Space TTS engine
245
-
246
- Args:
247
- text (str): Input text to synthesize
248
- voice (str): Voice mode to use ('S1', 'S2', 'dialogue', or filename for clone)
249
- speed (float): Speech speed multiplier
250
- response_format (str): Audio format ('wav', 'mp3', 'opus')
251
-
252
- Returns:
253
- Optional[str]: Path to the generated audio file or None if generation fails
254
- """
255
- logger.info(f"Generating speech with Dia Space for text length: {len(text)}")
256
-
257
- try:
258
- # Import here to avoid circular imports
259
- from utils.tts_dia_space import _call_dia_api, _generate_output_path
260
-
261
- # Call the Dia Space API
262
- audio_data = _call_dia_api(text, voice, response_format, speed)
263
-
264
- # Save the audio data to a file
265
- output_path = _generate_output_path(prefix="dia_space", extension=response_format)
266
- with open(output_path, 'wb') as f:
267
- f.write(audio_data)
268
-
269
- logger.info(f"Generated audio with Dia Space: {output_path}")
270
- return output_path
271
- except Exception as e:
272
- logger.error(f"Failed to generate speech from Dia Space API: {str(e)}")
273
- logger.error(f"Error type: {type(e).__name__}")
274
- logger.info("Dia Space TTS engine failed")
275
- return None
276
-
277
- except ImportError as import_err:
278
- logger.error(f"Dia TTS generation failed due to import error: {str(import_err)}")
279
- logger.error("Dia Space TTS engine failed")
280
- return None
281
-
282
- except Exception as dia_error:
283
- logger.error(f"Dia TTS generation failed: {str(dia_error)}", exc_info=True)
284
- logger.error(f"Error type: {type(dia_error).__name__}")
285
- logger.error("Dia Space TTS engine failed")
286
- return None
287
-
288
- def generate_speech_stream(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
289
- """Generate speech stream using Dia TTS engine
290
-
291
- Args:
292
- text (str): Input text to synthesize
293
- voice (str): Voice ID (not used in Dia)
294
- speed (float): Speech speed multiplier (not used in Dia)
295
-
296
- Yields:
297
- tuple: (sample_rate, audio_data) pairs for each segment
298
- """
299
- logger.info(f"Generating speech stream with Dia for text length: {len(text)}")
300
-
301
- try:
302
- # Import required modules
303
- from utils.tts_dia import _get_model, DEFAULT_SAMPLE_RATE, DIA_AVAILABLE
304
-
305
- # Check if Dia is available
306
- if not DIA_AVAILABLE:
307
- logger.warning("Dia TTS engine is not available, falling back to dummy audio stream")
308
- yield from DummyTTSEngine(self.lang_code).generate_speech_stream(text, voice, speed)
309
- return
310
-
311
- import torch
312
-
313
- # Get the Dia model
314
- model = _get_model()
315
-
316
- # Generate audio
317
- with torch.inference_mode():
318
- output_audio_np = model.generate(
319
- text,
320
- max_tokens=None,
321
- cfg_scale=3.0,
322
- temperature=1.3,
323
- top_p=0.95,
324
- cfg_filter_top_k=35,
325
- use_torch_compile=False,
326
- verbose=False
327
- )
328
-
329
- if output_audio_np is not None:
330
- logger.info(f"Successfully generated audio with Dia (length: {len(output_audio_np)})")
331
- yield DEFAULT_SAMPLE_RATE, output_audio_np
332
- else:
333
- logger.warning("Dia model returned None for audio output")
334
- logger.warning("Falling back to dummy audio stream")
335
- yield from DummyTTSEngine(self.lang_code).generate_speech_stream(text, voice, speed)
336
-
337
- except ModuleNotFoundError as e:
338
- if "dac" in str(e):
339
- logger.warning("Dia TTS streaming failed due to missing 'dac' module, falling back to dummy audio stream")
340
- else:
341
- logger.error(f"Module not found error in Dia TTS streaming: {str(e)}")
342
- yield from DummyTTSEngine(self.lang_code).generate_speech_stream(text, voice, speed)
343
-
344
- except ImportError as import_err:
345
- logger.error(f"Dia TTS streaming failed due to import error: {str(import_err)}")
346
- logger.error("Falling back to dummy audio stream")
347
- yield from DummyTTSEngine(self.lang_code).generate_speech_stream(text, voice, speed)
348
-
349
- except Exception as dia_error:
350
- logger.error(f"Dia TTS streaming failed: {str(dia_error)}", exc_info=True)
351
- logger.error(f"Error type: {type(dia_error).__name__}")
352
- logger.error("Falling back to dummy audio stream")
353
- yield from DummyTTSEngine(self.lang_code).generate_speech_stream(text, voice, speed)
354
-
355
-
356
- def get_available_engines() -> List[str]:
357
- """Get a list of available TTS engines
358
-
359
- Returns:
360
- List[str]: List of available engine names
361
- """
362
- available = []
363
-
364
- if KOKORO_AVAILABLE:
365
- available.append('kokoro')
366
-
367
- if KOKORO_SPACE_AVAILABLE:
368
- available.append('kokoro_space')
369
-
370
- if DIA_AVAILABLE:
371
- available.append('dia')
372
-
373
- if DIA_SPACE_AVAILABLE:
374
- available.append('dia_space')
375
-
376
- # Dummy is always available
377
- available.append('dummy')
378
-
379
- return available
380
-
381
-
382
- def create_engine(engine_type: str, lang_code: str = 'z') -> TTSEngineBase:
383
- """Create a specific TTS engine
384
-
385
- Args:
386
- engine_type (str): Type of engine to create ('kokoro', 'kokoro_space', 'dia', 'dia_space', 'dummy')
387
- lang_code (str): Language code for the engine
388
-
389
- Returns:
390
- TTSEngineBase: An instance of the requested TTS engine
391
-
392
- Raises:
393
- ValueError: If the requested engine type is not supported
394
- """
395
- if engine_type == 'kokoro':
396
- if not KOKORO_AVAILABLE:
397
- raise ValueError("Kokoro TTS engine is not available")
398
- return KokoroTTSEngine(lang_code)
399
-
400
- elif engine_type == 'kokoro_space':
401
- if not KOKORO_SPACE_AVAILABLE:
402
- raise ValueError("Kokoro Space TTS engine is not available")
403
- return KokoroSpaceTTSEngine(lang_code)
404
-
405
- elif engine_type == 'dia':
406
- if not DIA_AVAILABLE:
407
- raise ValueError("Dia TTS engine is not available")
408
- return DiaTTSEngine(lang_code)
409
-
410
- elif engine_type == 'dia_space':
411
- if not DIA_SPACE_AVAILABLE:
412
- raise ValueError("Dia Space TTS engine is not available")
413
- return DiaSpaceTTSEngine(lang_code)
414
-
415
- elif engine_type == 'dummy':
416
- return DummyTTSEngine(lang_code)
417
-
418
- else:
419
- raise ValueError(f"Unsupported TTS engine type: {engine_type}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/tts_factory.py DELETED
@@ -1,77 +0,0 @@
1
- import logging
2
- from typing import Optional, List
3
-
4
- # Configure logging
5
- logger = logging.getLogger(__name__)
6
-
7
- # Import the base class
8
- from utils.tts_base import TTSEngineBase, DummyTTSEngine
9
- from utils.tts_cascading import CascadingTTSEngine
10
-
11
- class TTSFactory:
12
- """Factory class for creating TTS engines
13
-
14
- This class is responsible for creating the appropriate TTS engine based on
15
- availability and configuration.
16
- """
17
-
18
- @staticmethod
19
- def create_engine(engine_type: Optional[str] = None, lang_code: str = 'z') -> TTSEngineBase:
20
- """Create a TTS engine instance
21
-
22
- Args:
23
- engine_type (str, optional): Type of engine to create ('kokoro', 'kokoro_space', 'dia', 'dummy')
24
- If None, the best available engine will be used
25
- lang_code (str): Language code for the engine
26
-
27
- Returns:
28
- TTSEngineBase: An instance of a TTS engine
29
- """
30
- from utils.tts_engines import get_available_engines, create_engine
31
-
32
- # Get available engines
33
- available_engines = get_available_engines()
34
- logger.info(f"Available TTS engines: {available_engines}")
35
-
36
- # If engine_type is specified, try to create that specific engine
37
- if engine_type is not None:
38
- if engine_type in available_engines:
39
- logger.info(f"Creating requested engine: {engine_type}")
40
- engine = create_engine(engine_type, lang_code)
41
- return engine
42
- else:
43
- logger.warning(f"Requested engine '{engine_type}' is not available")
44
-
45
- # Fall back to dummy engine if no engines are available
46
- if not available_engines or (len(available_engines) == 1 and available_engines[0] == 'dummy'):
47
- logger.warning("No TTS engines available, falling back to dummy engine")
48
- return DummyTTSEngine(lang_code)
49
-
50
- return TTSFactory.create_cascading_engine(available_engines, lang_code)
51
-
52
- @staticmethod
53
- def create_cascading_engine(available_engines: List[str], lang_code: str = 'z') -> TTSEngineBase:
54
- """Create a cascading TTS engine that tries multiple engines in order
55
-
56
- Args:
57
- available_engines (List[str]): List of available engine names
58
- lang_code (str): Language code for the engines
59
-
60
- Returns:
61
- TTSEngineBase: A cascading TTS engine instance
62
- """
63
- from utils.tts_engines import create_engine
64
-
65
- # Define the priority order for engines
66
- priority_order = ['kokoro', 'kokoro_space', 'dia', 'dia_space', 'dummy']
67
-
68
- # Filter and sort available engines by priority
69
- engines_by_priority = [engine for engine in priority_order if engine in available_engines]
70
-
71
- # Always ensure dummy is the last fallback
72
- if 'dummy' not in engines_by_priority:
73
- engines_by_priority.append('dummy')
74
-
75
- logger.info(f"Creating cascading engine with priority: {engines_by_priority}")
76
-
77
- return CascadingTTSEngine(engines_by_priority, lang_code)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/tts_kokoro.py CHANGED
@@ -1,106 +1,148 @@
1
- import os
2
- import time
3
  import logging
4
  import numpy as np
5
  import soundfile as sf
6
- from typing import Optional, Tuple, Generator
 
 
7
 
8
  # Configure logging
9
- logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
12
- # Constants
13
- DEFAULT_SAMPLE_RATE = 24000
14
 
15
- # Global model instance (lazy loaded)
16
- _pipeline = None
 
 
 
 
 
 
 
 
17
 
18
 
19
  def _get_pipeline(lang_code: str = 'z'):
20
- """Lazy-load the Kokoro pipeline to avoid loading it until needed"""
21
- global _pipeline
22
- if _pipeline is None:
23
- logger.info("Loading Kokoro pipeline...")
24
- try:
25
- # Import Kokoro
26
- from kokoro import KPipeline
27
-
28
- # Initialize the pipeline
29
- logger.info(f"Initializing Kokoro pipeline with language code: {lang_code}")
30
- _pipeline = KPipeline(lang_code=lang_code)
31
-
32
- # Log pipeline details
33
- logger.info(f"Kokoro pipeline loaded successfully")
34
- logger.info(f"Pipeline type: {type(_pipeline).__name__}")
35
- except ImportError as import_err:
36
- logger.error(f"Import error loading Kokoro pipeline: {import_err}")
37
- logger.error(f"This may indicate missing dependencies")
38
- raise
39
- except Exception as e:
40
- logger.error(f"Error loading Kokoro pipeline: {e}", exc_info=True)
41
- logger.error(f"Error type: {type(e).__name__}")
42
- raise
43
- return _pipeline
44
-
45
-
46
- def generate_speech(text: str, language: str = "z", voice: str = "af_heart", speed: float = 1.0) -> str:
47
- """Public interface for TTS generation using Kokoro model
48
-
49
- This is a legacy function maintained for backward compatibility.
50
- New code should use the factory pattern implementation directly.
51
 
52
  Args:
53
- text (str): Input text to synthesize
54
- language (str): Language code ('a' for US English, 'b' for British English,
55
- 'j' for Japanese, 'z' for Mandarin Chinese)
56
- voice (str): Voice ID to use (e.g., 'af_heart', 'af_bella', etc.)
57
- speed (float): Speech speed multiplier (0.5 to 2.0)
58
 
59
  Returns:
60
- str: Path to the generated audio file
61
  """
62
- logger.info(f"Legacy Kokoro generate_speech called with text length: {len(text)}")
63
-
64
- # Use the new implementation via factory pattern
65
- from utils.tts_engines import KokoroTTSEngine
66
 
67
  try:
68
- # Create a Kokoro engine and generate speech
69
- kokoro_engine = KokoroTTSEngine(language)
70
- return kokoro_engine.generate_speech(text, voice, speed)
71
  except Exception as e:
72
- logger.error(f"Error in legacy Kokoro generate_speech: {str(e)}", exc_info=True)
73
- # Fall back to dummy TTS
74
- from utils.tts_base import DummyTTSEngine
75
- dummy_engine = DummyTTSEngine()
76
- return dummy_engine.generate_speech(text)
77
 
78
 
79
- def generate_speech_stream(text: str, language: str = "z", voice: str = "af_heart", speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
80
- """Generate speech stream using Kokoro TTS engine
81
 
82
- Args:
83
- text (str): Input text to synthesize
84
- language (str): Language code
85
- voice (str): Voice ID to use
86
- speed (float): Speech speed multiplier
87
-
88
- Yields:
89
- tuple: (sample_rate, audio_data) pairs for each segment
90
  """
91
- logger.info(f"Generating speech stream with Kokoro for text length: {len(text)}")
92
 
93
- try:
94
- # Get the Kokoro pipeline
95
- pipeline = _get_pipeline(language)
96
 
97
- # Generate speech stream
98
- generator = pipeline(text, voice=voice, speed=speed)
99
- for _, _, audio in generator:
100
- yield DEFAULT_SAMPLE_RATE, audio
101
- except Exception as e:
102
- logger.error(f"Error in Kokoro generate_speech_stream: {str(e)}", exc_info=True)
103
- # Fall back to dummy TTS
104
- from utils.tts_base import DummyTTSEngine
105
- dummy_engine = DummyTTSEngine()
106
- yield from dummy_engine.generate_speech_stream(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import logging
2
  import numpy as np
3
  import soundfile as sf
4
+ from typing import Optional, Generator, Tuple
5
+
6
+ from utils.tts_simplified import TTSBase, DummyTTS
7
 
8
  # Configure logging
 
9
  logger = logging.getLogger(__name__)
10
 
11
+ # Flag to track Kokoro availability
12
+ KOKORO_AVAILABLE = False
13
 
14
+ # Try to import Kokoro
15
+ try:
16
+ from kokoro import KPipeline
17
+ KOKORO_AVAILABLE = True
18
+ logger.info("Kokoro TTS engine is available")
19
+ except ImportError:
20
+ logger.warning("Kokoro TTS engine is not available")
21
+ except Exception as e:
22
+ logger.error(f"Kokoro import failed with unexpected error: {str(e)}")
23
+ KOKORO_AVAILABLE = False
24
 
25
 
26
  def _get_pipeline(lang_code: str = 'z'):
27
+ """Lazy-load the Kokoro pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  Args:
30
+ lang_code (str): Language code for the pipeline
 
 
 
 
31
 
32
  Returns:
33
+ KPipeline or None: The Kokoro pipeline or None if not available
34
  """
35
+ if not KOKORO_AVAILABLE:
36
+ logger.warning("Kokoro TTS engine is not available")
37
+ return None
 
38
 
39
  try:
40
+ pipeline = KPipeline(lang_code=lang_code)
41
+ logger.info("Kokoro pipeline successfully loaded")
42
+ return pipeline
43
  except Exception as e:
44
+ logger.error(f"Failed to initialize Kokoro pipeline: {str(e)}")
45
+ return None
 
 
 
46
 
47
 
48
+ class KokoroTTS(TTSBase):
49
+ """Kokoro TTS engine implementation
50
 
51
+ This engine uses the Kokoro library for TTS generation.
 
 
 
 
 
 
 
52
  """
 
53
 
54
+ def __init__(self, lang_code: str = 'z'):
55
+ """Initialize the Kokoro TTS engine
 
56
 
57
+ Args:
58
+ lang_code (str): Language code for the engine
59
+ """
60
+ super().__init__(lang_code)
61
+ self.pipeline = None
62
+
63
+ def _ensure_pipeline(self):
64
+ """Ensure the pipeline is loaded
65
+
66
+ Returns:
67
+ bool: True if pipeline is available, False otherwise
68
+ """
69
+ if self.pipeline is None:
70
+ self.pipeline = _get_pipeline(self.lang_code)
71
+
72
+ return self.pipeline is not None
73
+
74
+ def generate_speech(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Optional[str]:
75
+ """Generate speech using Kokoro TTS engine
76
+
77
+ Args:
78
+ text (str): Input text to synthesize
79
+ voice (str): Voice ID to use (e.g., 'af_heart', 'af_bella', etc.)
80
+ speed (float): Speech speed multiplier (0.5 to 2.0)
81
+
82
+ Returns:
83
+ Optional[str]: Path to the generated audio file or None if generation fails
84
+ """
85
+ logger.info(f"Generating speech with Kokoro for text length: {len(text)}")
86
+
87
+ # Check if Kokoro is available
88
+ if not KOKORO_AVAILABLE:
89
+ logger.warning("Kokoro TTS engine is not available, falling back to dummy TTS")
90
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
91
+
92
+ # Ensure pipeline is loaded
93
+ if not self._ensure_pipeline():
94
+ logger.warning("Failed to load Kokoro pipeline, falling back to dummy TTS")
95
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
96
+
97
+ try:
98
+ # Generate unique output path
99
+ output_path = self._generate_output_path(prefix="kokoro")
100
+
101
+ # Generate speech
102
+ generator = self.pipeline(text, voice=voice, speed=speed)
103
+ for _, _, audio in generator:
104
+ logger.info(f"Saving Kokoro audio to {output_path}")
105
+ sf.write(output_path, audio, 24000)
106
+ break
107
+
108
+ logger.info(f"Kokoro audio generation complete: {output_path}")
109
+ return output_path
110
+ except Exception as e:
111
+ logger.error(f"Error generating speech with Kokoro: {str(e)}", exc_info=True)
112
+ logger.warning("Kokoro TTS engine failed, falling back to dummy TTS")
113
+ return DummyTTS(self.lang_code).generate_speech(text, voice, speed)
114
+
115
+ def generate_speech_stream(self, text: str, voice: str = 'af_heart', speed: float = 1.0) -> Generator[Tuple[int, np.ndarray], None, None]:
116
+ """Generate speech stream using Kokoro TTS engine
117
+
118
+ Args:
119
+ text (str): Input text to synthesize
120
+ voice (str): Voice ID to use
121
+ speed (float): Speech speed multiplier
122
+
123
+ Yields:
124
+ tuple: (sample_rate, audio_data) pairs for each segment
125
+ """
126
+ logger.info(f"Generating speech stream with Kokoro for text length: {len(text)}")
127
+
128
+ # Check if Kokoro is available
129
+ if not KOKORO_AVAILABLE:
130
+ logger.warning("Kokoro TTS engine is not available, falling back to dummy TTS")
131
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
132
+ return
133
+
134
+ # Ensure pipeline is loaded
135
+ if not self._ensure_pipeline():
136
+ logger.warning("Failed to load Kokoro pipeline, falling back to dummy TTS")
137
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
138
+ return
139
+
140
+ try:
141
+ # Generate speech stream
142
+ generator = self.pipeline(text, voice=voice, speed=speed)
143
+ for _, _, audio in generator:
144
+ yield 24000, audio
145
+ except Exception as e:
146
+ logger.error(f"Error generating speech stream with Kokoro: {str(e)}", exc_info=True)
147
+ logger.warning("Kokoro TTS engine failed, falling back to dummy TTS")
148
+ yield from DummyTTS(self.lang_code).generate_speech_stream(text, voice, speed)
utils/tts_kokoro_space.py DELETED
@@ -1,100 +0,0 @@
1
- import os
2
- import time
3
- import logging
4
- import numpy as np
5
- import soundfile as sf
6
- from typing import Optional, Tuple, Generator
7
-
8
- # Configure logging
9
- logging.basicConfig(level=logging.INFO)
10
- logger = logging.getLogger(__name__)
11
-
12
- # Constants
13
- DEFAULT_SAMPLE_RATE = 24000
14
-
15
- # Global client instance (lazy loaded)
16
- _client = None
17
-
18
-
19
- def _get_client():
20
- """Lazy-load the Kokoro Space client to avoid loading it until needed"""
21
- global _client
22
- if _client is None:
23
- logger.info("Loading Kokoro Space client...")
24
- try:
25
- # Import gradio client
26
- from gradio_client import Client
27
-
28
- # Initialize the client
29
- logger.info("Initializing Kokoro Space client")
30
- _client = Client("Remsky/Kokoro-TTS-Zero")
31
-
32
- # Log client details
33
- logger.info("Kokoro Space client loaded successfully")
34
- logger.info(f"Client type: {type(_client).__name__}")
35
- except ImportError as import_err:
36
- logger.error(f"Import error loading Kokoro Space client: {import_err}")
37
- logger.error("This may indicate missing dependencies")
38
- raise
39
- except Exception as e:
40
- logger.error(f"Error loading Kokoro Space client: {e}", exc_info=True)
41
- logger.error(f"Error type: {type(e).__name__}")
42
- raise
43
- return _client
44
-
45
-
46
- def generate_speech(text: str, language: str = "z", voice: str = "af_nova", speed: float = 1.0) -> str:
47
- """Public interface for TTS generation using Kokoro Space
48
-
49
- This is a legacy function maintained for backward compatibility.
50
- New code should use the factory pattern implementation directly.
51
-
52
- Args:
53
- text (str): Input text to synthesize
54
- language (str): Language code (not used in Kokoro Space, kept for API compatibility)
55
- voice (str): Voice ID to use (e.g., 'af_nova', 'af_bella', etc.)
56
- speed (float): Speech speed multiplier (0.5 to 2.0)
57
-
58
- Returns:
59
- str: Path to the generated audio file
60
- """
61
- logger.info(f"Legacy Kokoro Space generate_speech called with text length: {len(text)}")
62
-
63
- # Use the new implementation via factory pattern
64
- from utils.tts_engines import KokoroSpaceTTSEngine
65
-
66
- try:
67
- # Create a Kokoro Space engine and generate speech
68
- kokoro_space_engine = KokoroSpaceTTSEngine(language)
69
- return kokoro_space_engine.generate_speech(text, voice, speed)
70
- except Exception as e:
71
- logger.error(f"Error in legacy Kokoro Space generate_speech: {str(e)}", exc_info=True)
72
- # Fall back to dummy TTS
73
- from utils.tts_base import DummyTTSEngine
74
- dummy_engine = DummyTTSEngine()
75
- return dummy_engine.generate_speech(text)
76
-
77
-
78
- def _create_output_dir() -> str:
79
- """Create output directory for audio files
80
-
81
- Returns:
82
- str: Path to the output directory
83
- """
84
- output_dir = "temp/outputs"
85
- os.makedirs(output_dir, exist_ok=True)
86
- return output_dir
87
-
88
-
89
- def _generate_output_path(prefix: str = "output") -> str:
90
- """Generate a unique output path for audio files
91
-
92
- Args:
93
- prefix (str): Prefix for the output filename
94
-
95
- Returns:
96
- str: Path to the output file
97
- """
98
- output_dir = _create_output_dir()
99
- timestamp = int(time.time())
100
- return f"{output_dir}/{prefix}_{timestamp}.wav"