xinference 1.4.1__py3-none-any.whl → 1.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of xinference might be problematic. Click here for more details.

Files changed (104) hide show
  1. xinference/_version.py +3 -3
  2. xinference/api/restful_api.py +50 -1
  3. xinference/client/restful/restful_client.py +82 -2
  4. xinference/constants.py +3 -0
  5. xinference/core/chat_interface.py +297 -83
  6. xinference/core/model.py +1 -0
  7. xinference/core/progress_tracker.py +16 -8
  8. xinference/core/supervisor.py +45 -1
  9. xinference/core/worker.py +262 -37
  10. xinference/deploy/cmdline.py +33 -1
  11. xinference/model/audio/core.py +11 -1
  12. xinference/model/audio/megatts.py +105 -0
  13. xinference/model/audio/model_spec.json +24 -1
  14. xinference/model/audio/model_spec_modelscope.json +26 -1
  15. xinference/model/core.py +14 -0
  16. xinference/model/embedding/core.py +6 -1
  17. xinference/model/flexible/core.py +6 -1
  18. xinference/model/image/core.py +6 -1
  19. xinference/model/image/model_spec.json +17 -1
  20. xinference/model/image/model_spec_modelscope.json +17 -1
  21. xinference/model/llm/__init__.py +0 -4
  22. xinference/model/llm/core.py +4 -0
  23. xinference/model/llm/llama_cpp/core.py +40 -16
  24. xinference/model/llm/llm_family.json +413 -84
  25. xinference/model/llm/llm_family.py +24 -1
  26. xinference/model/llm/llm_family_modelscope.json +447 -0
  27. xinference/model/llm/mlx/core.py +16 -2
  28. xinference/model/llm/transformers/__init__.py +14 -0
  29. xinference/model/llm/transformers/core.py +30 -6
  30. xinference/model/llm/transformers/gemma3.py +17 -2
  31. xinference/model/llm/transformers/intern_vl.py +28 -18
  32. xinference/model/llm/transformers/minicpmv26.py +21 -2
  33. xinference/model/llm/transformers/qwen-omni.py +308 -0
  34. xinference/model/llm/transformers/qwen2_audio.py +1 -1
  35. xinference/model/llm/transformers/qwen2_vl.py +20 -4
  36. xinference/model/llm/utils.py +11 -1
  37. xinference/model/llm/vllm/core.py +35 -0
  38. xinference/model/llm/vllm/distributed_executor.py +8 -2
  39. xinference/model/rerank/core.py +6 -1
  40. xinference/model/utils.py +118 -1
  41. xinference/model/video/core.py +6 -1
  42. xinference/thirdparty/megatts3/__init__.py +0 -0
  43. xinference/thirdparty/megatts3/tts/frontend_function.py +175 -0
  44. xinference/thirdparty/megatts3/tts/gradio_api.py +93 -0
  45. xinference/thirdparty/megatts3/tts/infer_cli.py +277 -0
  46. xinference/thirdparty/megatts3/tts/modules/aligner/whisper_small.py +318 -0
  47. xinference/thirdparty/megatts3/tts/modules/ar_dur/ar_dur_predictor.py +362 -0
  48. xinference/thirdparty/megatts3/tts/modules/ar_dur/commons/layers.py +64 -0
  49. xinference/thirdparty/megatts3/tts/modules/ar_dur/commons/nar_tts_modules.py +73 -0
  50. xinference/thirdparty/megatts3/tts/modules/ar_dur/commons/rel_transformer.py +403 -0
  51. xinference/thirdparty/megatts3/tts/modules/ar_dur/commons/rot_transformer.py +649 -0
  52. xinference/thirdparty/megatts3/tts/modules/ar_dur/commons/seq_utils.py +342 -0
  53. xinference/thirdparty/megatts3/tts/modules/ar_dur/commons/transformer.py +767 -0
  54. xinference/thirdparty/megatts3/tts/modules/llm_dit/cfm.py +309 -0
  55. xinference/thirdparty/megatts3/tts/modules/llm_dit/dit.py +180 -0
  56. xinference/thirdparty/megatts3/tts/modules/llm_dit/time_embedding.py +44 -0
  57. xinference/thirdparty/megatts3/tts/modules/llm_dit/transformer.py +230 -0
  58. xinference/thirdparty/megatts3/tts/modules/wavvae/decoder/diag_gaussian.py +67 -0
  59. xinference/thirdparty/megatts3/tts/modules/wavvae/decoder/hifigan_modules.py +283 -0
  60. xinference/thirdparty/megatts3/tts/modules/wavvae/decoder/seanet_encoder.py +38 -0
  61. xinference/thirdparty/megatts3/tts/modules/wavvae/decoder/wavvae_v3.py +60 -0
  62. xinference/thirdparty/megatts3/tts/modules/wavvae/encoder/common_modules/conv.py +154 -0
  63. xinference/thirdparty/megatts3/tts/modules/wavvae/encoder/common_modules/lstm.py +51 -0
  64. xinference/thirdparty/megatts3/tts/modules/wavvae/encoder/common_modules/seanet.py +126 -0
  65. xinference/thirdparty/megatts3/tts/utils/audio_utils/align.py +36 -0
  66. xinference/thirdparty/megatts3/tts/utils/audio_utils/io.py +95 -0
  67. xinference/thirdparty/megatts3/tts/utils/audio_utils/plot.py +90 -0
  68. xinference/thirdparty/megatts3/tts/utils/commons/ckpt_utils.py +171 -0
  69. xinference/thirdparty/megatts3/tts/utils/commons/hparams.py +215 -0
  70. xinference/thirdparty/megatts3/tts/utils/text_utils/dict.json +1 -0
  71. xinference/thirdparty/megatts3/tts/utils/text_utils/ph_tone_convert.py +94 -0
  72. xinference/thirdparty/megatts3/tts/utils/text_utils/split_text.py +90 -0
  73. xinference/thirdparty/megatts3/tts/utils/text_utils/text_encoder.py +280 -0
  74. xinference/types.py +10 -0
  75. xinference/utils.py +54 -0
  76. xinference/web/ui/build/asset-manifest.json +6 -6
  77. xinference/web/ui/build/index.html +1 -1
  78. xinference/web/ui/build/static/css/main.0f6523be.css +2 -0
  79. xinference/web/ui/build/static/css/main.0f6523be.css.map +1 -0
  80. xinference/web/ui/build/static/js/main.58bd483c.js +3 -0
  81. xinference/web/ui/build/static/js/main.58bd483c.js.map +1 -0
  82. xinference/web/ui/node_modules/.cache/babel-loader/3bff8cbe9141f937f4d98879a9771b0f48e0e4e0dbee8e647adbfe23859e7048.json +1 -0
  83. xinference/web/ui/node_modules/.cache/babel-loader/4500b1a622a031011f0a291701e306b87e08cbc749c50e285103536b85b6a914.json +1 -0
  84. xinference/web/ui/node_modules/.cache/babel-loader/51709f5d3e53bcf19e613662ef9b91fb9174942c5518987a248348dd4e1e0e02.json +1 -0
  85. xinference/web/ui/node_modules/.cache/babel-loader/69081049f0c7447544b7cfd73dd13d8846c02fe5febe4d81587e95c89a412d5b.json +1 -0
  86. xinference/web/ui/node_modules/.cache/babel-loader/b8551e9775a01b28ae674125c688febe763732ea969ae344512e64ea01bf632e.json +1 -0
  87. xinference/web/ui/node_modules/.cache/babel-loader/bf2b211b0d1b6465eff512d64c869d748f803c5651a7c24e48de6ea3484a7bfe.json +1 -0
  88. xinference/web/ui/src/locales/en.json +2 -1
  89. xinference/web/ui/src/locales/zh.json +2 -1
  90. {xinference-1.4.1.dist-info → xinference-1.5.0.dist-info}/METADATA +127 -114
  91. {xinference-1.4.1.dist-info → xinference-1.5.0.dist-info}/RECORD +96 -60
  92. {xinference-1.4.1.dist-info → xinference-1.5.0.dist-info}/WHEEL +1 -1
  93. xinference/web/ui/build/static/css/main.b494ae7e.css +0 -2
  94. xinference/web/ui/build/static/css/main.b494ae7e.css.map +0 -1
  95. xinference/web/ui/build/static/js/main.5ca4eea1.js +0 -3
  96. xinference/web/ui/build/static/js/main.5ca4eea1.js.map +0 -1
  97. xinference/web/ui/node_modules/.cache/babel-loader/0f0967acaec5df1d45b80010949c258d64297ebbb0f44b8bb3afcbd45c6f0ec4.json +0 -1
  98. xinference/web/ui/node_modules/.cache/babel-loader/27bcada3ee8f89d21184b359f022fc965f350ffaca52c9814c29f1fc37121173.json +0 -1
  99. xinference/web/ui/node_modules/.cache/babel-loader/68249645124f37d01eef83b1d897e751f895bea919b6fb466f907c1f87cebc84.json +0 -1
  100. xinference/web/ui/node_modules/.cache/babel-loader/e547bbb18abb4a474b675a8d5782d25617566bea0af8caa9b836ce5649e2250a.json +0 -1
  101. /xinference/web/ui/build/static/js/{main.5ca4eea1.js.LICENSE.txt → main.58bd483c.js.LICENSE.txt} +0 -0
  102. {xinference-1.4.1.dist-info → xinference-1.5.0.dist-info}/entry_points.txt +0 -0
  103. {xinference-1.4.1.dist-info → xinference-1.5.0.dist-info/licenses}/LICENSE +0 -0
  104. {xinference-1.4.1.dist-info → xinference-1.5.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,154 @@
1
+ # MIT License
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ # Copyright (c) [2023] [Meta Platforms, Inc. and affiliates.]
24
+ # Copyright (c) [2025] [Ziyue Jiang]
25
+ # SPDX-License-Identifier: MIT
26
+ # This file has been modified by Ziyue Jiang on 2025/03/19
27
+ # Original file was released under MIT, with the full license text # available at https://github.com/facebookresearch/encodec/blob/gh-pages/LICENSE.
28
+ # This modified file is released under the same license.
29
+
30
+ """Convolutional layers wrappers and utilities."""
31
+
32
+ import math
33
+ import typing as tp
34
+ import warnings
35
+ import einops
36
+
37
+ import torch
38
+ from torch import nn
39
+ from torch.nn import functional as F
40
+ from torch.nn.utils import spectral_norm, weight_norm
41
+
42
+
43
+ CONV_NORMALIZATIONS = frozenset(['none', 'weight_norm', 'spectral_norm',
44
+ 'time_layer_norm', 'layer_norm', 'time_group_norm'])
45
+
46
+
47
+ def apply_parametrization_norm(module: nn.Module, norm: str = 'none') -> nn.Module:
48
+ assert norm in CONV_NORMALIZATIONS
49
+ if norm == 'weight_norm':
50
+ return weight_norm(module)
51
+ elif norm == 'spectral_norm':
52
+ return spectral_norm(module)
53
+ else:
54
+ return module
55
+
56
+
57
+ def get_norm_module(module: nn.Module, causal: bool = False, norm: str = 'none', **norm_kwargs) -> nn.Module:
58
+ assert norm in CONV_NORMALIZATIONS
59
+ if norm == 'layer_norm':
60
+ assert isinstance(module, nn.modules.conv._ConvNd)
61
+ return ConvLayerNorm(module.out_channels, **norm_kwargs)
62
+ elif norm == 'time_group_norm':
63
+ if causal:
64
+ raise ValueError("GroupNorm doesn't support causal evaluation.")
65
+ assert isinstance(module, nn.modules.conv._ConvNd)
66
+ return nn.GroupNorm(1, module.out_channels, **norm_kwargs)
67
+ else:
68
+ return nn.Identity()
69
+
70
+
71
+ def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int,
72
+ padding_total: int = 0) -> int:
73
+ length = x.shape[-1]
74
+ n_frames = (length - kernel_size + padding_total) / stride + 1
75
+ ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
76
+ return ideal_length - length
77
+
78
+
79
+ def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'zero', value: float = 0.):
80
+ length = x.shape[-1]
81
+ padding_left, padding_right = paddings
82
+ assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
83
+ if mode == 'reflect':
84
+ max_pad = max(padding_left, padding_right)
85
+ extra_pad = 0
86
+ if length <= max_pad:
87
+ extra_pad = max_pad - length + 1
88
+ x = F.pad(x, (0, extra_pad))
89
+ padded = F.pad(x, paddings, mode, value)
90
+ end = padded.shape[-1] - extra_pad
91
+ return padded[..., :end]
92
+ else:
93
+ return F.pad(x, paddings, mode, value)
94
+
95
+
96
+ class ConvLayerNorm(nn.LayerNorm):
97
+ def __init__(self, normalized_shape: tp.Union[int, tp.List[int], torch.Size], **kwargs):
98
+ super().__init__(normalized_shape, **kwargs)
99
+
100
+ def forward(self, x):
101
+ x = einops.rearrange(x, 'b ... t -> b t ...')
102
+ x = super().forward(x)
103
+ x = einops.rearrange(x, 'b t ... -> b ... t')
104
+ return
105
+
106
+
107
+ class NormConv1d(nn.Module):
108
+ def __init__(self, *args, causal: bool = False, norm: str = 'none',
109
+ norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
110
+ super().__init__()
111
+ self.conv = apply_parametrization_norm(nn.Conv1d(*args, **kwargs), norm)
112
+ self.norm = get_norm_module(self.conv, causal, norm, **norm_kwargs)
113
+ self.norm_type = norm
114
+
115
+ def forward(self, x):
116
+ x = self.conv(x)
117
+ x = self.norm(x)
118
+ return x
119
+
120
+
121
+ class SConv1d(nn.Module):
122
+ def __init__(self, in_channels: int, out_channels: int,
123
+ kernel_size: int, stride: int = 1, dilation: int = 1,
124
+ groups: int = 1, bias: bool = True, causal: bool = False,
125
+ norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {},
126
+ pad_mode: str = 'reflect'):
127
+ super().__init__()
128
+ # warn user on unusual setup between dilation and stride
129
+ if stride > 1 and dilation > 1:
130
+ warnings.warn('SConv1d has been initialized with stride > 1 and dilation > 1'
131
+ f' (kernel_size={kernel_size} stride={stride}, dilation={dilation}).')
132
+ self.conv = NormConv1d(in_channels, out_channels, kernel_size, stride,
133
+ dilation=dilation, groups=groups, bias=bias, causal=causal,
134
+ norm=norm, norm_kwargs=norm_kwargs)
135
+ self.causal = causal
136
+ self.pad_mode = pad_mode
137
+
138
+ def forward(self, x):
139
+ B, C, T = x.shape
140
+ kernel_size = self.conv.conv.kernel_size[0]
141
+ stride = self.conv.conv.stride[0]
142
+ dilation = self.conv.conv.dilation[0]
143
+ kernel_size = (kernel_size - 1) * dilation + 1 # effective kernel size with dilations
144
+ padding_total = kernel_size - stride
145
+ extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
146
+ if self.causal:
147
+ # Left padding for causal
148
+ x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode)
149
+ else:
150
+ # Asymmetric padding required for odd strides
151
+ padding_right = padding_total // 2
152
+ padding_left = padding_total - padding_right
153
+ x = pad1d(x, (padding_left, padding_right + extra_padding), mode=self.pad_mode)
154
+ return self.conv(x)
@@ -0,0 +1,51 @@
1
+ # MIT License
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ # Copyright (c) [2023] [Meta Platforms, Inc. and affiliates.]
24
+ # Copyright (c) [2025] [Ziyue Jiang]
25
+ # SPDX-License-Identifier: MIT
26
+ # This file has been modified by Ziyue Jiang on 2025/03/19
27
+ # Original file was released under MIT, with the full license text # available at https://github.com/facebookresearch/encodec/blob/gh-pages/LICENSE.
28
+ # This modified file is released under the same license.
29
+
30
+ """LSTM layers module."""
31
+ from torch import nn
32
+
33
+
34
+ class SLSTM(nn.Module):
35
+ """
36
+ LSTM without worrying about the hidden state, nor the layout of the data.
37
+ Expects input as convolutional layout.
38
+ """
39
+ def __init__(self, dimension: int, num_layers: int = 2, skip: bool = True):
40
+ super().__init__()
41
+ self.skip = skip
42
+ self.lstm = nn.LSTM(dimension, dimension, num_layers)
43
+
44
+ # 修改transpose顺序
45
+ def forward(self, x):
46
+ x1 = x.permute(2, 0, 1)
47
+ y, _ = self.lstm(x1)
48
+ y = y.permute(1, 2, 0)
49
+ if self.skip:
50
+ y = y + x
51
+ return y
@@ -0,0 +1,126 @@
1
+ # MIT License
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ # Copyright (c) [2023] [Meta Platforms, Inc. and affiliates.]
24
+ # Copyright (c) [2025] [Ziyue Jiang]
25
+ # SPDX-License-Identifier: MIT
26
+ # This file has been modified by Ziyue Jiang on 2025/03/19
27
+ # Original file was released under MIT, with the full license text # available at https://github.com/facebookresearch/encodec/blob/gh-pages/LICENSE.
28
+ # This modified file is released under the same license.
29
+
30
+ """Encodec SEANet-based encoder and decoder implementation."""
31
+
32
+ import typing as tp
33
+
34
+ import numpy as np
35
+ import torch.nn as nn
36
+
37
+ from .conv import SConv1d
38
+ from .lstm import SLSTM
39
+
40
+
41
+ class SEANetResnetBlock(nn.Module):
42
+ def __init__(self, dim: int, kernel_sizes: tp.List[int] = [3, 1], dilations: tp.List[int] = [1, 1],
43
+ activation: str = 'ELU', activation_params: dict = {'alpha': 1.0},
44
+ norm: str = 'weight_norm', norm_params: tp.Dict[str, tp.Any] = {}, causal: bool = False,
45
+ pad_mode: str = 'reflect', compress: int = 2, true_skip: bool = True):
46
+ super().__init__()
47
+ assert len(kernel_sizes) == len(dilations), 'Number of kernel sizes should match number of dilations'
48
+ act = getattr(nn, activation)
49
+ hidden = dim // compress
50
+ block = []
51
+ for i, (kernel_size, dilation) in enumerate(zip(kernel_sizes, dilations)):
52
+ in_chs = dim if i == 0 else hidden
53
+ out_chs = dim if i == len(kernel_sizes) - 1 else hidden
54
+ block += [
55
+ act(**activation_params),
56
+ SConv1d(in_chs, out_chs, kernel_size=kernel_size, dilation=dilation,
57
+ norm=norm, norm_kwargs=norm_params,
58
+ causal=causal, pad_mode=pad_mode),
59
+ ]
60
+ self.block = nn.Sequential(*block)
61
+ self.shortcut: nn.Module
62
+ if true_skip:
63
+ self.shortcut = nn.Identity()
64
+ else:
65
+ self.shortcut = SConv1d(dim, dim, kernel_size=1, norm=norm, norm_kwargs=norm_params,
66
+ causal=causal, pad_mode=pad_mode)
67
+
68
+ def forward(self, x):
69
+ return self.shortcut(x) + self.block(x)
70
+
71
+
72
+ class SEANetEncoder(nn.Module):
73
+ def __init__(self, channels: int = 1, dimension: int = 128, n_filters: int = 32, n_residual_layers: int = 1,
74
+ ratios: tp.List[int] = [8, 5, 4, 2], activation: str = 'ELU', activation_params: dict = {'alpha': 1.0},
75
+ norm: str = 'weight_norm', norm_params: tp.Dict[str, tp.Any] = {}, kernel_size: int = 7,
76
+ last_kernel_size: int = 7, residual_kernel_size: int = 3, dilation_base: int = 2, causal: bool = False,
77
+ pad_mode: str = 'reflect', true_skip: bool = False, compress: int = 2, lstm: int = 2):
78
+ super().__init__()
79
+ self.channels = channels
80
+ self.dimension = dimension
81
+ self.n_filters = n_filters
82
+ self.ratios = list(reversed(ratios))
83
+ del ratios
84
+ self.n_residual_layers = n_residual_layers
85
+ self.hop_length = np.prod(self.ratios)
86
+
87
+ act = getattr(nn, activation)
88
+ mult = 1
89
+ model: tp.List[nn.Module] = [
90
+ SConv1d(channels, mult * n_filters, kernel_size, norm=norm, norm_kwargs=norm_params,
91
+ causal=causal, pad_mode=pad_mode)
92
+ ]
93
+ # Downsample to raw audio scale
94
+ for i, ratio in enumerate(self.ratios):
95
+ # Add residual layers
96
+ for j in range(n_residual_layers):
97
+ model += [
98
+ SEANetResnetBlock(mult * n_filters, kernel_sizes=[residual_kernel_size, 1],
99
+ dilations=[dilation_base ** j, 1],
100
+ norm=norm, norm_params=norm_params,
101
+ activation=activation, activation_params=activation_params,
102
+ causal=causal, pad_mode=pad_mode, compress=compress, true_skip=true_skip)]
103
+
104
+ # Add downsampling layers
105
+ model += [
106
+ act(**activation_params),
107
+ SConv1d(mult * n_filters, mult * n_filters * 2,
108
+ kernel_size=ratio * 2, stride=ratio,
109
+ norm=norm, norm_kwargs=norm_params,
110
+ causal=causal, pad_mode=pad_mode),
111
+ ]
112
+ mult *= 2
113
+
114
+ if lstm:
115
+ model += [SLSTM(mult * n_filters, num_layers=lstm)]
116
+
117
+ model += [
118
+ act(**activation_params),
119
+ SConv1d(mult * n_filters, dimension, last_kernel_size, norm=norm, norm_kwargs=norm_params,
120
+ causal=causal, pad_mode=pad_mode)
121
+ ]
122
+
123
+ self.model = nn.Sequential(*model)
124
+
125
+ def forward(self, x):
126
+ return self.model(x)
@@ -0,0 +1,36 @@
1
+ # Copyright 2025 ByteDance and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+
17
+ def mel2token_to_dur(mel2token, T_txt=None, max_dur=None):
18
+ is_torch = isinstance(mel2token, torch.Tensor)
19
+ has_batch_dim = True
20
+ if not is_torch:
21
+ mel2token = torch.LongTensor(mel2token)
22
+ if T_txt is None:
23
+ T_txt = mel2token.max()
24
+ if len(mel2token.shape) == 1:
25
+ mel2token = mel2token[None, ...]
26
+ has_batch_dim = False
27
+ B, _ = mel2token.shape
28
+ dur = mel2token.new_zeros(B, T_txt + 1).scatter_add(1, mel2token, torch.ones_like(mel2token))
29
+ dur = dur[:, 1:]
30
+ if max_dur is not None:
31
+ dur = dur.clamp(max=max_dur)
32
+ if not is_torch:
33
+ dur = dur.numpy()
34
+ if not has_batch_dim:
35
+ dur = dur[0]
36
+ return dur
@@ -0,0 +1,95 @@
1
+ # Copyright 2025 ByteDance and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import io
16
+ import os
17
+ import subprocess
18
+
19
+ import numpy as np
20
+ from scipy.io import wavfile
21
+ import pyloudnorm as pyln
22
+ from pydub import AudioSegment
23
+
24
+
25
+ def to_wav_bytes(wav, sr, norm=False):
26
+ wav = wav.astype(float)
27
+ if norm:
28
+ meter = pyln.Meter(sr) # create BS.1770 meter
29
+ loudness = meter.integrated_loudness(wav)
30
+ wav = pyln.normalize.loudness(wav, loudness, -18.0)
31
+ if np.abs(wav).max() >= 1:
32
+ wav = wav / np.abs(wav).max() * 0.95
33
+ wav = wav * 32767
34
+ bytes_io = io.BytesIO()
35
+ wavfile.write(bytes_io, sr, wav.astype(np.int16))
36
+ return bytes_io.getvalue()
37
+
38
+
39
+ def save_wav(wav_bytes, path):
40
+ with open(path[:-4] + '.wav', 'wb') as file:
41
+ file.write(wav_bytes)
42
+ if path[-4:] == '.mp3':
43
+ to_mp3(path[:-4])
44
+
45
+
46
+ def to_mp3(out_path):
47
+ if out_path[-4:] == '.wav':
48
+ out_path = out_path[:-4]
49
+ subprocess.check_call(
50
+ f'ffmpeg -threads 1 -loglevel error -i "{out_path}.wav" -vn -b:a 192k -y -hide_banner -async 1 "{out_path}.mp3"',
51
+ shell=True, stdin=subprocess.PIPE)
52
+ subprocess.check_call(f'rm -f "{out_path}.wav"', shell=True)
53
+
54
+
55
+ def convert_to_wav(wav_path):
56
+ # Check if the file exists
57
+ if not os.path.exists(wav_path):
58
+ print(f"The file '{wav_path}' does not exist.")
59
+ return
60
+
61
+ # Check if the file already has a .wav extension
62
+ if not wav_path.endswith(".wav"):
63
+ # Define the output path with a .wav extension
64
+ out_path = os.path.splitext(wav_path)[0] + ".wav"
65
+
66
+ # Load the audio file using pydub and convert it to WAV
67
+ audio = AudioSegment.from_file(wav_path)
68
+ audio.export(out_path, format="wav")
69
+
70
+ print(f"Converted '{wav_path}' to '{out_path}'")
71
+
72
+
73
+ def convert_to_wav_bytes(audio_binary):
74
+ # Load the audio binary using pydub and convert it to WAV
75
+ audio = AudioSegment.from_file(io.BytesIO(audio_binary))
76
+ wav_bytes = io.BytesIO()
77
+ audio.export(wav_bytes, format="wav")
78
+ wav_bytes.seek(0)
79
+ return wav_bytes
80
+
81
+
82
+ ''' Smoothly combine audio segments using crossfade transitions." '''
83
+ def combine_audio_segments(segments, crossfade_duration=0.16, sr=24000):
84
+ window_length = int(sr * crossfade_duration)
85
+ hanning_window = np.hanning(2 * window_length)
86
+ # Combine
87
+ for i, segment in enumerate(segments):
88
+ if i == 0:
89
+ combined_audio = segment
90
+ else:
91
+ overlap = combined_audio[-window_length:] * hanning_window[window_length:] + segment[:window_length] * hanning_window[:window_length]
92
+ combined_audio = np.concatenate(
93
+ [combined_audio[:-window_length], overlap, segment[window_length:]]
94
+ )
95
+ return combined_audio
@@ -0,0 +1,90 @@
1
+ # Copyright 2025 ByteDance and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import matplotlib
16
+
17
+ matplotlib.use('Agg')
18
+ import matplotlib.pyplot as plt
19
+ import numpy as np
20
+ import torch
21
+
22
+ LINE_COLORS = ['w', 'r', 'orange', 'k', 'cyan', 'm', 'b', 'lime', 'g', 'brown', 'navy']
23
+
24
+
25
+ def spec_to_figure(spec, vmin=None, vmax=None, title='', f0s=None, dur_info=None, figsize=(12, 6)):
26
+ if isinstance(spec, torch.Tensor):
27
+ spec = spec.cpu().numpy()
28
+ H = spec.shape[1] // 2
29
+ fig = plt.figure(figsize=figsize)
30
+ plt.title(title)
31
+ plt.pcolor(spec.T, vmin=vmin, vmax=vmax)
32
+
33
+ if dur_info is not None:
34
+ assert isinstance(dur_info, dict)
35
+ txt = dur_info['txt']
36
+ dur_gt = dur_info['dur_gt']
37
+ if isinstance(dur_gt, torch.Tensor):
38
+ dur_gt = dur_gt.cpu().numpy()
39
+ dur_gt = np.cumsum(dur_gt).astype(int)
40
+ for i in range(len(dur_gt)):
41
+ shift = (i % 8) + 1
42
+ plt.text(dur_gt[i], shift * 4, txt[i])
43
+ plt.vlines(dur_gt[i], 0, H // 2, colors='b') # blue is gt
44
+ plt.xlim(0, dur_gt[-1])
45
+ if 'dur_pred' in dur_info:
46
+ dur_pred = dur_info['dur_pred']
47
+ if isinstance(dur_pred, torch.Tensor):
48
+ dur_pred = dur_pred.cpu().numpy()
49
+ dur_pred = np.cumsum(dur_pred).astype(int)
50
+ for i in range(len(dur_pred)):
51
+ shift = (i % 8) + 1
52
+ plt.text(dur_pred[i], H + shift * 4, txt[i])
53
+ plt.vlines(dur_pred[i], H, H * 1.5, colors='r') # red is pred
54
+ plt.xlim(0, max(dur_gt[-1], dur_pred[-1]))
55
+ if f0s is not None:
56
+ ax = plt.gca()
57
+ ax2 = ax.twinx()
58
+ # ax.set_xticks()
59
+
60
+ if not isinstance(f0s, dict):
61
+ f0s = {'f0': f0s}
62
+ for i, (k, f0) in enumerate(f0s.items()):
63
+ if f0 is not None:
64
+ if isinstance(f0, torch.Tensor):
65
+ f0 = f0.cpu().numpy()
66
+ ax2.plot(
67
+ np.arange(len(f0)) + 0.5, f0, label=k, c=LINE_COLORS[i], linewidth=1, alpha=0.5)
68
+ ax2.set_ylim(0, 1000)
69
+ ax2.legend()
70
+ return fig
71
+
72
+
73
+ def align_to_figure(align, dur_info):
74
+ if isinstance(align, torch.Tensor):
75
+ align = align.cpu().numpy()
76
+ H = align.shape[1]
77
+ fig = plt.figure(figsize=(12, 6))
78
+ plt.pcolor(align.T, vmin=0, vmax=1)
79
+ if dur_info is not None:
80
+ assert isinstance(dur_info, dict)
81
+ txt = dur_info['txt']
82
+ dur_gt = dur_info['dur_gt']
83
+ if isinstance(dur_gt, torch.Tensor):
84
+ dur_gt = dur_gt.cpu().numpy()
85
+ dur_gt = np.cumsum(dur_gt).astype(int) // 2
86
+ for i in range(len(dur_gt)):
87
+ plt.text(dur_gt[i], i, txt[i], color='red')
88
+ plt.vlines(dur_gt[i], 0, H, colors='b') # blue is gt
89
+ # plt.xlim(0, dur_gt[-1])
90
+ return fig