mlinmg commited on
Commit
73465f7
·
verified ·
1 Parent(s): 8cd94f2

Upload 13 files

Browse files
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ xtts-v2.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ xttsv2_gpt2/gpt2_model.safetensors filter=lfs diff=lfs merge=lfs -text
config.json ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Xtts"
4
+ ],
5
+ "audio_config": {
6
+ "fmax": 8000,
7
+ "fmin": 0,
8
+ "hop_length": 256,
9
+ "mel_channels": 80,
10
+ "mel_norms_file": null,
11
+ "n_fft": 1024,
12
+ "output_sample_rate": 24000,
13
+ "power": 1.0,
14
+ "sample_rate": 22050,
15
+ "win_length": 1024
16
+ },
17
+ "auto_map": {
18
+ "AutoConfig": "AstraMindAI/xtts2--xtts2_config.XTTSConfig",
19
+ "AutoModelForCausalLM": "AstraMindAI/xtts2--xtts2_modeling.Xtts",
20
+ "AutoTokenizer": "AstraMindAI/xtts2--tokenizer.XTTSTokenizerFast"
21
+ },
22
+ "cond_d_vector_in_each_upsampling_layer": true,
23
+ "d_vector_dim": 512,
24
+ "decoder_input_dim": 1024,
25
+ "duration_const": 102400,
26
+ "gpt": {
27
+ "model_type": "xtts_gpt"
28
+ },
29
+ "gpt_code_stride_len": 1024,
30
+ "gpt_config": {
31
+ "_attn_implementation_autoset": false,
32
+ "_name_or_path": "",
33
+ "activation_function": "gelu",
34
+ "add_cross_attention": false,
35
+ "architectures": [
36
+ "XttsGPT"
37
+ ],
38
+ "attn_pdrop": 0.1,
39
+ "audio_config": {
40
+ "mel_channels": 80,
41
+ "output_sample_rate": 24000,
42
+ "sample_rate": 22050
43
+ },
44
+ "auto_map": {
45
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
46
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT"
47
+ },
48
+ "bad_words_ids": null,
49
+ "begin_suppress_tokens": null,
50
+ "bos_token_id": null,
51
+ "chunk_size_feed_forward": 0,
52
+ "cross_attention_hidden_size": null,
53
+ "decoder_input_dim": 1024,
54
+ "decoder_start_token_id": null,
55
+ "diversity_penalty": 0.0,
56
+ "do_sample": false,
57
+ "early_stopping": false,
58
+ "enable_redaction": false,
59
+ "encoder_no_repeat_ngram_size": 0,
60
+ "eos_token_id": null,
61
+ "exponential_decay_length_penalty": null,
62
+ "finetuning_task": null,
63
+ "forced_bos_token_id": null,
64
+ "forced_eos_token_id": null,
65
+ "gpt_batch_size": 1,
66
+ "gpt_max_audio_tokens": 605,
67
+ "hidden_size": 1024,
68
+ "id2label": {
69
+ "0": "LABEL_0",
70
+ "1": "LABEL_1"
71
+ },
72
+ "initializer_range": 0.02,
73
+ "is_decoder": false,
74
+ "is_encoder_decoder": false,
75
+ "kv_cache": true,
76
+ "label2id": {
77
+ "LABEL_0": 0,
78
+ "LABEL_1": 1
79
+ },
80
+ "layer_norm_epsilon": 1e-05,
81
+ "length_penalty": 1.0,
82
+ "max_audio_tokens": 605,
83
+ "max_length": 20,
84
+ "max_prompt_tokens": 70,
85
+ "max_text_tokens": 402,
86
+ "min_length": 0,
87
+ "model_type": "xtts_gpt",
88
+ "n_inner": 4096,
89
+ "no_repeat_ngram_size": 0,
90
+ "num_attention_heads": 16,
91
+ "num_audio_tokens": 1026,
92
+ "num_beam_groups": 1,
93
+ "num_beams": 1,
94
+ "num_hidden_layers": 30,
95
+ "num_return_sequences": 1,
96
+ "number_text_tokens": 6681,
97
+ "output_attentions": false,
98
+ "output_hidden_states": false,
99
+ "output_scores": false,
100
+ "pad_token_id": null,
101
+ "prefix": null,
102
+ "problem_type": null,
103
+ "pruned_heads": {},
104
+ "remove_invalid_values": false,
105
+ "reorder_and_upcast_attn": false,
106
+ "repetition_penalty": 1.0,
107
+ "return_dict": true,
108
+ "return_dict_in_generate": false,
109
+ "scale_attn_by_inverse_layer_idx": false,
110
+ "sep_token_id": null,
111
+ "start_audio_token": 1024,
112
+ "start_text_token": null,
113
+ "stop_audio_token": 1025,
114
+ "stop_text_token": null,
115
+ "suppress_tokens": null,
116
+ "task_specific_params": null,
117
+ "temperature": 1.0,
118
+ "tf_legacy_loss": false,
119
+ "tie_encoder_decoder": false,
120
+ "tie_word_embeddings": true,
121
+ "tokenizer_class": null,
122
+ "top_k": 50,
123
+ "top_p": 1.0,
124
+ "torch_dtype": null,
125
+ "torchscript": false,
126
+ "transformers_version": "4.46.0",
127
+ "typical_p": 1.0,
128
+ "use_bfloat16": false,
129
+ "use_masking_gt_prompt_approach": true,
130
+ "use_perceiver_resampler": true,
131
+ "vocab_size": 6681
132
+ },
133
+ "input_sample_rate": 22050,
134
+ "languages": [
135
+ "en",
136
+ "es",
137
+ "fr",
138
+ "de",
139
+ "it",
140
+ "pt",
141
+ "pl",
142
+ "tr",
143
+ "ru",
144
+ "nl",
145
+ "cs",
146
+ "ar",
147
+ "zh-cn",
148
+ "hu",
149
+ "ko",
150
+ "ja",
151
+ "hi"
152
+ ],
153
+ "model_type": "xtts",
154
+ "num_chars": 255,
155
+ "output_hop_length": 256,
156
+ "output_sample_rate": 24000,
157
+ "tokenizer_file": "",
158
+ "transformers_version": "4.46.0"
159
+ }
tokenizer.py ADDED
@@ -0,0 +1,836 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import textwrap
4
+ from typing import List, Optional, Union, Dict, Any
5
+ from functools import cached_property
6
+
7
+ import pypinyin
8
+ import torch
9
+ from hangul_romanize import Transliter
10
+ from hangul_romanize.rule import academic
11
+ from num2words import num2words
12
+ from spacy.lang.ar import Arabic
13
+ from spacy.lang.en import English
14
+ from spacy.lang.es import Spanish
15
+ from spacy.lang.ja import Japanese
16
+ from spacy.lang.zh import Chinese
17
+ from transformers import PreTrainedTokenizerFast, BatchEncoding
18
+ from transformers.tokenization_utils_base import TruncationStrategy, PaddingStrategy
19
+ from tokenizers import Tokenizer
20
+ from tokenizers.pre_tokenizers import WhitespaceSplit
21
+ from tokenizers.processors import TemplateProcessing
22
+
23
+ from TTS.tts.layers.xtts.zh_num2words import TextNorm as zh_num2words
24
+
25
+ import cutlet
26
+
27
+ # Funzioni di preprocessing del testo
28
+
29
+ def get_spacy_lang(lang):
30
+ if lang == "zh":
31
+ return Chinese()
32
+ elif lang == "ja":
33
+ return Japanese()
34
+ elif lang == "ar":
35
+ return Arabic()
36
+ elif lang == "es":
37
+ return Spanish()
38
+ else:
39
+ # For most languages, English does the job
40
+ return English()
41
+
42
+ def split_sentence(text, lang, text_split_length=250):
43
+ """Preprocess the input text and split into sentences based on language."""
44
+ text_splits = []
45
+ if text_split_length is not None and len(text) >= text_split_length:
46
+ text_splits.append("")
47
+ nlp = get_spacy_lang(lang)
48
+ nlp.add_pipe("sentencizer")
49
+ doc = nlp(text)
50
+ for sentence in doc.sents:
51
+ if len(text_splits[-1]) + len(str(sentence)) <= text_split_length:
52
+ text_splits[-1] += " " + str(sentence)
53
+ text_splits[-1] = text_splits[-1].lstrip()
54
+ elif len(str(sentence)) > text_split_length:
55
+ for line in textwrap.wrap(
56
+ str(sentence),
57
+ width=text_split_length,
58
+ drop_whitespace=True,
59
+ break_on_hyphens=False,
60
+ tabsize=1,
61
+ ):
62
+ text_splits.append(str(line))
63
+ else:
64
+ text_splits.append(str(sentence))
65
+
66
+ if len(text_splits) > 1 and text_splits[0] == "":
67
+ del text_splits[0]
68
+ else:
69
+ text_splits = [text.lstrip()]
70
+
71
+ return text_splits
72
+
73
+ _whitespace_re = re.compile(r"\s+")
74
+
75
+ # List of (regular expression, replacement) pairs for abbreviations:
76
+ _abbreviations = {
77
+ "en": [
78
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
79
+ for x in [
80
+ ("mrs", "misess"),
81
+ ("mr", "mister"),
82
+ ("dr", "doctor"),
83
+ ("st", "saint"),
84
+ ("co", "company"),
85
+ ("jr", "junior"),
86
+ ("maj", "major"),
87
+ ("gen", "general"),
88
+ ("drs", "doctors"),
89
+ ("rev", "reverend"),
90
+ ("lt", "lieutenant"),
91
+ ("hon", "honorable"),
92
+ ("sgt", "sergeant"),
93
+ ("capt", "captain"),
94
+ ("esq", "esquire"),
95
+ ("ltd", "limited"),
96
+ ("col", "colonel"),
97
+ ("ft", "fort"),
98
+ ]
99
+ ],
100
+ "es": [
101
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
102
+ for x in [
103
+ ("sra", "señora"),
104
+ ("sr", "señor"),
105
+ ("dr", "doctor"),
106
+ ("dra", "doctora"),
107
+ ("st", "santo"),
108
+ ("co", "compañía"),
109
+ ("jr", "junior"),
110
+ ("ltd", "limitada"),
111
+ ]
112
+ ],
113
+ "fr": [
114
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
115
+ for x in [
116
+ ("mme", "madame"),
117
+ ("mr", "monsieur"),
118
+ ("dr", "docteur"),
119
+ ("st", "saint"),
120
+ ("co", "compagnie"),
121
+ ("jr", "junior"),
122
+ ("ltd", "limitée"),
123
+ ]
124
+ ],
125
+ "de": [
126
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
127
+ for x in [
128
+ ("fr", "frau"),
129
+ ("dr", "doktor"),
130
+ ("st", "sankt"),
131
+ ("co", "firma"),
132
+ ("jr", "junior"),
133
+ ]
134
+ ],
135
+ "pt": [
136
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
137
+ for x in [
138
+ ("sra", "senhora"),
139
+ ("sr", "senhor"),
140
+ ("dr", "doutor"),
141
+ ("dra", "doutora"),
142
+ ("st", "santo"),
143
+ ("co", "companhia"),
144
+ ("jr", "júnior"),
145
+ ("ltd", "limitada"),
146
+ ]
147
+ ],
148
+ "it": [
149
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
150
+ for x in [
151
+ # ("sig.ra", "signora"),
152
+ ("sig", "signore"),
153
+ ("dr", "dottore"),
154
+ ("st", "santo"),
155
+ ("co", "compagnia"),
156
+ ("jr", "junior"),
157
+ ("ltd", "limitata"),
158
+ ]
159
+ ],
160
+ "pl": [
161
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
162
+ for x in [
163
+ ("p", "pani"),
164
+ ("m", "pan"),
165
+ ("dr", "doktor"),
166
+ ("sw", "święty"),
167
+ ("jr", "junior"),
168
+ ]
169
+ ],
170
+ "ar": [
171
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
172
+ for x in [
173
+ # There are not many common abbreviations in Arabic as in English.
174
+ ]
175
+ ],
176
+ "zh": [
177
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
178
+ for x in [
179
+ # Chinese doesn't typically use abbreviations in the same way as Latin-based scripts.
180
+ ]
181
+ ],
182
+ "cs": [
183
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
184
+ for x in [
185
+ ("dr", "doktor"), # doctor
186
+ ("ing", "inženýr"), # engineer
187
+ ("p", "pan"), # Could also map to pani for woman but no easy way to do it
188
+ # Other abbreviations would be specialized and not as common.
189
+ ]
190
+ ],
191
+ "ru": [
192
+ (re.compile("\\b%s\\b" % x[0], re.IGNORECASE), x[1])
193
+ for x in [
194
+ ("г-жа", "госпожа"), # Mrs.
195
+ ("г-н", "господин"), # Mr.
196
+ ("д-р", "доктор"), # doctor
197
+ # Other abbreviations are less common or specialized.
198
+ ]
199
+ ],
200
+ "nl": [
201
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
202
+ for x in [
203
+ ("dhr", "de heer"), # Mr.
204
+ ("mevr", "mevrouw"), # Mrs.
205
+ ("dr", "dokter"), # doctor
206
+ ("jhr", "jonkheer"), # young lord or nobleman
207
+ # Dutch uses more abbreviations, but these are the most common ones.
208
+ ]
209
+ ],
210
+ "tr": [
211
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
212
+ for x in [
213
+ ("b", "bay"), # Mr.
214
+ ("byk", "büyük"), # büyük
215
+ ("dr", "doktor"), # doctor
216
+ # Add other Turkish abbreviations here if needed.
217
+ ]
218
+ ],
219
+ "hu": [
220
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
221
+ for x in [
222
+ ("dr", "doktor"), # doctor
223
+ ("b", "bácsi"), # Mr.
224
+ ("nőv", "nővér"), # nurse
225
+ # Add other Hungarian abbreviations here if needed.
226
+ ]
227
+ ],
228
+ "ko": [
229
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
230
+ for x in [
231
+ # Korean doesn't typically use abbreviations in the same way as Latin-based scripts.
232
+ ]
233
+ ],
234
+ }
235
+
236
+ def expand_abbreviations_multilingual(text, lang="en"):
237
+ if lang in _abbreviations:
238
+ for regex, replacement in _abbreviations[lang]:
239
+ text = re.sub(regex, replacement, text)
240
+ return text
241
+
242
+ _symbols_multilingual = {
243
+ "en": [
244
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
245
+ for x in [
246
+ ("&", " and "),
247
+ ("@", " at "),
248
+ ("%", " percent "),
249
+ ("#", " hash "),
250
+ ("$", " dollar "),
251
+ ("£", " pound "),
252
+ ("°", " degree "),
253
+ ]
254
+ ],
255
+ "es": [
256
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
257
+ for x in [
258
+ ("&", " y "),
259
+ ("@", " arroba "),
260
+ ("%", " por ciento "),
261
+ ("#", " numeral "),
262
+ ("$", " dolar "),
263
+ ("£", " libra "),
264
+ ("°", " grados "),
265
+ ]
266
+ ],
267
+ "fr": [
268
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
269
+ for x in [
270
+ ("&", " et "),
271
+ ("@", " arobase "),
272
+ ("%", " pour cent "),
273
+ ("#", " dièse "),
274
+ ("$", " dollar "),
275
+ ("£", " livre "),
276
+ ("°", " degrés "),
277
+ ]
278
+ ],
279
+ "de": [
280
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
281
+ for x in [
282
+ ("&", " und "),
283
+ ("@", " at "),
284
+ ("%", " prozent "),
285
+ ("#", " raute "),
286
+ ("$", " dollar "),
287
+ ("£", " pfund "),
288
+ ("°", " grad "),
289
+ ]
290
+ ],
291
+ "pt": [
292
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
293
+ for x in [
294
+ ("&", " e "),
295
+ ("@", " arroba "),
296
+ ("%", " por cento "),
297
+ ("#", " cardinal "),
298
+ ("$", " dólar "),
299
+ ("£", " libra "),
300
+ ("°", " graus "),
301
+ ]
302
+ ],
303
+ "it": [
304
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
305
+ for x in [
306
+ ("&", " e "),
307
+ ("@", " chiocciola "),
308
+ ("%", " per cento "),
309
+ ("#", " cancelletto "),
310
+ ("$", " dollaro "),
311
+ ("£", " sterlina "),
312
+ ("°", " gradi "),
313
+ ]
314
+ ],
315
+ "pl": [
316
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
317
+ for x in [
318
+ ("&", " i "),
319
+ ("@", " małpa "),
320
+ ("%", " procent "),
321
+ ("#", " krzyżyk "),
322
+ ("$", " dolar "),
323
+ ("£", " funt "),
324
+ ("°", " stopnie "),
325
+ ]
326
+ ],
327
+ "ar": [
328
+ # Arabic
329
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
330
+ for x in [
331
+ ("&", " و "),
332
+ ("@", " على "),
333
+ ("%", " في المئة "),
334
+ ("#", " رقم "),
335
+ ("$", " دولار "),
336
+ ("£", " جنيه "),
337
+ ("°", " درجة "),
338
+ ]
339
+ ],
340
+ "zh": [
341
+ # Chinese
342
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
343
+ for x in [
344
+ ("&", " 和 "),
345
+ ("@", " 在 "),
346
+ ("%", " 百分之 "),
347
+ ("#", " 号 "),
348
+ ("$", " 美元 "),
349
+ ("£", " 英镑 "),
350
+ ("°", " 度 "),
351
+ ]
352
+ ],
353
+ "cs": [
354
+ # Czech
355
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
356
+ for x in [
357
+ ("&", " a "),
358
+ ("@", " na "),
359
+ ("%", " procento "),
360
+ ("#", " křížek "),
361
+ ("$", " dolar "),
362
+ ("£", " libra "),
363
+ ("°", " stupně "),
364
+ ]
365
+ ],
366
+ "ru": [
367
+ # Russian
368
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
369
+ for x in [
370
+ ("&", " и "),
371
+ ("@", " собака "),
372
+ ("%", " процентов "),
373
+ ("#", " номер "),
374
+ ("$", " доллар "),
375
+ ("£", " фунт "),
376
+ ("°", " градус "),
377
+ ]
378
+ ],
379
+ "nl": [
380
+ # Dutch
381
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
382
+ for x in [
383
+ ("&", " en "),
384
+ ("@", " bij "),
385
+ ("%", " procent "),
386
+ ("#", " hekje "),
387
+ ("$", " dollar "),
388
+ ("£", " pond "),
389
+ ("°", " graden "),
390
+ ]
391
+ ],
392
+ "tr": [
393
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
394
+ for x in [
395
+ ("&", " ve "),
396
+ ("@", " at "),
397
+ ("%", " yüzde "),
398
+ ("#", " diyez "),
399
+ ("$", " dolar "),
400
+ ("£", " sterlin "),
401
+ ("°", " derece "),
402
+ ]
403
+ ],
404
+ "hu": [
405
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
406
+ for x in [
407
+ ("&", " és "),
408
+ ("@", " kukac "),
409
+ ("%", " százalék "),
410
+ ("#", " kettőskereszt "),
411
+ ("$", " dollár "),
412
+ ("£", " font "),
413
+ ("°", " fok "),
414
+ ]
415
+ ],
416
+ "ko": [
417
+ # Korean
418
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
419
+ for x in [
420
+ ("&", " 그리고 "),
421
+ ("@", " 에 "),
422
+ ("%", " 퍼센트 "),
423
+ ("#", " 번호 "),
424
+ ("$", " 달러 "),
425
+ ("£", " 파운드 "),
426
+ ("°", " 도 "),
427
+ ]
428
+ ],
429
+ }
430
+
431
+ def expand_symbols_multilingual(text, lang="en"):
432
+ if lang in _symbols_multilingual:
433
+ for regex, replacement in _symbols_multilingual[lang]:
434
+ text = re.sub(regex, replacement, text)
435
+ text = text.replace(" ", " ") # Ensure there are no double spaces
436
+ return text.strip()
437
+
438
+ _ordinal_re = {
439
+ "en": re.compile(r"([0-9]+)(st|nd|rd|th)"),
440
+ "es": re.compile(r"([0-9]+)(º|ª|er|o|a|os|as)"),
441
+ "fr": re.compile(r"([0-9]+)(º|ª|er|re|e|ème)"),
442
+ "de": re.compile(r"([0-9]+)(st|nd|rd|th|º|ª|\.(?=\s|$))"),
443
+ "pt": re.compile(r"([0-9]+)(º|ª|o|a|os|as)"),
444
+ "it": re.compile(r"([0-9]+)(º|°|ª|o|a|i|e)"),
445
+ "pl": re.compile(r"([0-9]+)(º|ª|st|nd|rd|th)"),
446
+ "ar": re.compile(r"([0-9]+)(ون|ين|ث|ر|ى)"),
447
+ "cs": re.compile(r"([0-9]+)\.(?=\s|$)"), # In Czech, a dot is often used after the number to indicate ordinals.
448
+ "ru": re.compile(r"([0-9]+)(-й|-я|-е|-ое|-ье|-го)"),
449
+ "nl": re.compile(r"([0-9]+)(de|ste|e)"),
450
+ "tr": re.compile(r"([0-9]+)(\.|inci|nci|uncu|üncü|\.)"),
451
+ "hu": re.compile(r"([0-9]+)(\.|adik|edik|odik|edik|ödik|ödike|ik)"),
452
+ "ko": re.compile(r"([0-9]+)(번째|번|차|째)"),
453
+ }
454
+ _number_re = re.compile(r"[0-9]+")
455
+ _currency_re = {
456
+ "USD": re.compile(r"((\$[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+\$))"),
457
+ "GBP": re.compile(r"((£[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+£))"),
458
+ "EUR": re.compile(r"(([0-9\.\,]*[0-9]+€)|((€[0-9\.\,]*[0-9]+)))"),
459
+ }
460
+
461
+ _comma_number_re = re.compile(r"\b\d{1,3}(,\d{3})*(\.\d+)?\b")
462
+ _dot_number_re = re.compile(r"\b\d{1,3}(\.\d{3})*(\,\d+)?\b")
463
+ _decimal_number_re = re.compile(r"([0-9]+[.,][0-9]+)")
464
+
465
+ def _remove_commas(m):
466
+ text = m.group(0)
467
+ if "," in text:
468
+ text = text.replace(",", "")
469
+ return text
470
+
471
+ def _remove_dots(m):
472
+ text = m.group(0)
473
+ if "." in text:
474
+ text = text.replace(".", "")
475
+ return text
476
+
477
+ def _expand_decimal_point(m, lang="en"):
478
+ amount = m.group(1).replace(",", ".")
479
+ return num2words(float(amount), lang=lang if lang != "cs" else "cz")
480
+
481
+ def _expand_currency(m, lang="en", currency="USD"):
482
+ amount = float((re.sub(r"[^\d.]", "", m.group(0).replace(",", "."))))
483
+ full_amount = num2words(amount, to="currency", currency=currency, lang=lang if lang != "cs" else "cz")
484
+
485
+ and_equivalents = {
486
+ "en": ", ",
487
+ "es": " con ",
488
+ "fr": " et ",
489
+ "de": " und ",
490
+ "pt": " e ",
491
+ "it": " e ",
492
+ "pl": ", ",
493
+ "cs": ", ",
494
+ "ru": ", ",
495
+ "nl": ", ",
496
+ "ar": ", ",
497
+ "tr": ", ",
498
+ "hu": ", ",
499
+ "ko": ", ",
500
+ }
501
+
502
+ if amount.is_integer():
503
+ last_and = full_amount.rfind(and_equivalents.get(lang, ", "))
504
+ if last_and != -1:
505
+ full_amount = full_amount[:last_and]
506
+
507
+ return full_amount
508
+
509
+ def _expand_ordinal(m, lang="en"):
510
+ return num2words(int(m.group(1)), ordinal=True, lang=lang if lang != "cs" else "cz")
511
+
512
+ def _expand_number(m, lang="en"):
513
+ return num2words(int(m.group(0)), lang=lang if lang != "cs" else "cz")
514
+
515
+ def expand_numbers_multilingual(text, lang="en"):
516
+ if lang == "zh":
517
+ text = zh_num2words()(text)
518
+ else:
519
+ if lang in ["en", "ru"]:
520
+ text = re.sub(_comma_number_re, _remove_commas, text)
521
+ else:
522
+ text = re.sub(_dot_number_re, _remove_dots, text)
523
+ try:
524
+ text = re.sub(_currency_re["GBP"], lambda m: _expand_currency(m, lang, "GBP"), text)
525
+ text = re.sub(_currency_re["USD"], lambda m: _expand_currency(m, lang, "USD"), text)
526
+ text = re.sub(_currency_re["EUR"], lambda m: _expand_currency(m, lang, "EUR"), text)
527
+ except Exception as e:
528
+ pass
529
+ if lang != "tr":
530
+ text = re.sub(_decimal_number_re, lambda m: _expand_decimal_point(m, lang), text)
531
+ if lang in _ordinal_re:
532
+ text = re.sub(_ordinal_re[lang], lambda m: _expand_ordinal(m, lang), text)
533
+ text = re.sub(_number_re, lambda m: _expand_number(m, lang), text)
534
+ return text
535
+
536
+ def lowercase(text):
537
+ return text.lower()
538
+
539
+ def collapse_whitespace(text):
540
+ return re.sub(_whitespace_re, " ", text)
541
+
542
+ def multilingual_cleaners(text, lang):
543
+ text = text.replace('"', "")
544
+ if lang == "tr":
545
+ text = text.replace("İ", "i")
546
+ text = text.replace("Ö", "ö")
547
+ text = text.replace("Ü", "ü")
548
+ text = lowercase(text)
549
+ text = expand_numbers_multilingual(text, lang)
550
+ text = expand_abbreviations_multilingual(text, lang)
551
+ text = expand_symbols_multilingual(text, lang=lang)
552
+ text = collapse_whitespace(text)
553
+ return text
554
+
555
+ def basic_cleaners(text):
556
+ """Basic pipeline that lowercases and collapses whitespace without transliteration."""
557
+ text = lowercase(text)
558
+ text = collapse_whitespace(text)
559
+ return text
560
+
561
+ def chinese_transliterate(text):
562
+ return "".join(
563
+ [p[0] for p in pypinyin.pinyin(text, style=pypinyin.Style.TONE3, heteronym=False, neutral_tone_with_five=True)]
564
+ )
565
+
566
+ def japanese_cleaners(text, katsu):
567
+ text = katsu.romaji(text)
568
+ text = lowercase(text)
569
+ return text
570
+
571
+ def korean_transliterate(text, transliter):
572
+ return transliter.translit(text)
573
+
574
+ # Fast Tokenizer Class
575
+
576
+ class XTTSTokenizerFast(PreTrainedTokenizerFast):
577
+ """
578
+ Fast Tokenizer implementation for XTTS model using HuggingFace's PreTrainedTokenizerFast
579
+ """
580
+
581
+ def __init__(
582
+ self,
583
+ vocab_file: str = None,
584
+ tokenizer_object: Optional[Tokenizer] = None,
585
+ unk_token: str = "[UNK]",
586
+ pad_token: str = "[PAD]",
587
+ bos_token: str = "[START]",
588
+ eos_token: str = "[STOP]",
589
+ auto_map: dict = {"AutoTokenizer": ["AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast", None]},
590
+ clean_up_tokenization_spaces: bool = True,
591
+ **kwargs
592
+ ):
593
+ if tokenizer_object is None and vocab_file is not None:
594
+ tokenizer_object = Tokenizer.from_file(vocab_file)
595
+
596
+ if tokenizer_object is not None:
597
+ # Configure the tokenizer
598
+ tokenizer_object.pre_tokenizer = WhitespaceSplit()
599
+ tokenizer_object.post_processor = TemplateProcessing(
600
+ single=f"{bos_token} $A {eos_token}",
601
+ special_tokens=[
602
+ (bos_token, tokenizer_object.token_to_id(bos_token)),
603
+ (eos_token, tokenizer_object.token_to_id(eos_token)),
604
+ ],
605
+ )
606
+
607
+ super().__init__(
608
+ tokenizer_object=tokenizer_object,
609
+ unk_token=unk_token,
610
+ pad_token=pad_token,
611
+ bos_token=bos_token,
612
+ eos_token=eos_token,
613
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
614
+ **kwargs
615
+ )
616
+
617
+ # Character limits per language
618
+ self.char_limits = {
619
+ "en": 250, "de": 253, "fr": 273, "es": 239,
620
+ "it": 213, "pt": 203, "pl": 224, "zh": 82,
621
+ "ar": 166, "cs": 186, "ru": 182, "nl": 251,
622
+ "tr": 226, "ja": 71, "hu": 224, "ko": 95,
623
+ }
624
+
625
+ # Initialize language tools
626
+ self._katsu = None
627
+ self._korean_transliter = Transliter(academic)
628
+
629
+ # Ensure pad_token_id is set
630
+ if self.pad_token_id is None:
631
+ self.pad_token_id = self.tokenizer.token_to_id(self.pad_token)
632
+
633
+ @cached_property
634
+ def katsu(self):
635
+ if self._katsu is None:
636
+ self._katsu = cutlet.Cutlet()
637
+ return self._katsu
638
+
639
+ def preprocess_text(self, text: str, lang: str) -> str:
640
+ """Apply text preprocessing for language"""
641
+ base_lang = lang.split("-")[0] # remove region
642
+ if base_lang in {"ar", "cs", "de", "en", "es", "fr", "hu", "it",
643
+ "nl", "pl", "pt", "ru", "tr", "zh", "ko"}:
644
+ text = multilingual_cleaners(text, base_lang)
645
+ if base_lang == "zh":
646
+ text = chinese_transliterate(text)
647
+ if base_lang == "ko":
648
+ text = korean_transliterate(text, self._korean_transliter)
649
+ elif base_lang == "ja":
650
+ text = japanese_cleaners(text, self.katsu)
651
+ else:
652
+ text = basic_cleaners(text)
653
+ return text
654
+
655
+ def batch_encode_with_split(self, texts: Union[str, List[str]], lang: Union[str, List[str]],
656
+ **kwargs) -> torch.Tensor:
657
+ """
658
+ Split texts into smaller chunks based on language character limits and encode them using HuggingFace fast tokenizer.
659
+ strictly mimic the xttsv2 tokenizer
660
+ """
661
+ # Convert single inputs to lists
662
+ if isinstance(texts, str):
663
+ texts = [texts]
664
+ if isinstance(lang, str):
665
+ lang = [lang]
666
+ # Ensure lang list matches texts list
667
+ if len(lang) == 1 and len(texts) > 1:
668
+ lang = lang * len(texts)
669
+
670
+ # Check if texts and lang have the same length
671
+ if len(texts) != len(lang):
672
+ raise ValueError(f"Number of texts ({len(texts)}) does not match number of languages ({len(lang)}).")
673
+
674
+ chunk_list = []
675
+ max_splits = 0
676
+
677
+ # For each text, split into chunks based on character limit
678
+ for text, text_lang in zip(texts, lang):
679
+ # Get language character limit
680
+ base_lang = text_lang.split("-")[0]
681
+ char_limit = self.char_limits.get(base_lang, 250)
682
+
683
+ # Clean and preprocess
684
+ text = self.preprocess_text(text, text_lang)
685
+
686
+ # Split text into sentences/chunks based on language
687
+ chunk_list = split_sentence(text, base_lang, text_split_length=char_limit)
688
+
689
+ # Ensure the tokenizer is a fast tokenizer
690
+ if not self.is_fast:
691
+ raise ValueError("The tokenizer must be a fast tokenizer.")
692
+
693
+ # Encode all chunks using the fast tokenizer
694
+ encoding: BatchEncoding = self(
695
+ chunk_list,
696
+ lang = lang,
697
+ add_special_tokens=False,
698
+ padding=False,
699
+ **kwargs
700
+ )
701
+
702
+ # The 'input_ids' tensor will have shape [total_chunks, max_sequence_length]
703
+ return encoding['input_ids'] # Tensor of shape [total_chunks, sequence_length]
704
+
705
+ def _batch_encode_plus(
706
+ self,
707
+ batch_text_or_text_pairs,
708
+ add_special_tokens: bool = True,
709
+ padding_strategy=PaddingStrategy.DO_NOT_PAD,
710
+ truncation_strategy=TruncationStrategy.DO_NOT_TRUNCATE,
711
+ max_length: Optional[int] = None,
712
+ stride: int = 0,
713
+ is_split_into_words: bool = False,
714
+ pad_to_multiple_of: Optional[int] = None,
715
+ return_tensors: Optional[str] = None,
716
+ return_token_type_ids: Optional[bool] = None,
717
+ return_attention_mask: Optional[bool] = None,
718
+ return_overflowing_tokens: bool = False,
719
+ return_special_tokens_mask: bool = False,
720
+ return_offsets_mapping: bool = False,
721
+ return_length: bool = False,
722
+ verbose: bool = True,
723
+ **kwargs
724
+ ) -> Dict[str, Any]:
725
+ """
726
+ Override batch encoding to handle language-specific preprocessing
727
+ """
728
+ lang = kwargs.pop("lang", ["en"] * len(batch_text_or_text_pairs))
729
+ if isinstance(lang, str):
730
+ lang = [lang]
731
+ # Ensure lang list matches texts list
732
+ if len(lang) == 1 and len(batch_text_or_text_pairs) > 1:
733
+ lang = lang * len(batch_text_or_text_pairs)
734
+
735
+ # Check if batch_text_or_text_pairs and lang have the same length
736
+ if len(batch_text_or_text_pairs) != len(lang):
737
+ raise ValueError(f"Number of texts ({len(batch_text_or_text_pairs)}) does not match number of languages ({len(lang)}).")
738
+
739
+ # Preprocess each text in the batch with its corresponding language
740
+ processed_texts = []
741
+ for text, text_lang in zip(batch_text_or_text_pairs, lang):
742
+ if isinstance(text, str):
743
+ # Check length and preprocess
744
+ #self.check_input_length(text, text_lang)
745
+ processed_text = self.preprocess_text(text, text_lang)
746
+
747
+ # Format text with language tag and spaces
748
+ base_lang = text_lang.split("-")[0]
749
+ lang_code = "zh-cn" if base_lang == "zh" else base_lang
750
+ processed_text = f"[{lang_code}]{processed_text}"
751
+ processed_text = processed_text.replace(" ", "[SPACE]")
752
+
753
+ processed_texts.append(processed_text)
754
+ else:
755
+ processed_texts.append(text)
756
+
757
+ # Call the parent class's encoding method with processed texts
758
+ return super()._batch_encode_plus(
759
+ processed_texts,
760
+ add_special_tokens=add_special_tokens,
761
+ padding_strategy=padding_strategy,
762
+ truncation_strategy=truncation_strategy,
763
+ max_length=max_length,
764
+ stride=stride,
765
+ is_split_into_words=is_split_into_words,
766
+ pad_to_multiple_of=pad_to_multiple_of,
767
+ return_tensors=return_tensors,
768
+ return_token_type_ids=return_token_type_ids,
769
+ return_attention_mask=return_attention_mask,
770
+ return_overflowing_tokens=return_overflowing_tokens,
771
+ return_special_tokens_mask=return_special_tokens_mask,
772
+ return_offsets_mapping=return_offsets_mapping,
773
+ return_length=return_length,
774
+ verbose=verbose,
775
+ **kwargs
776
+ )
777
+
778
+
779
+ def __call__(
780
+ self,
781
+ text: Union[str, List[str]],
782
+ lang: Union[str, List[str]] = "en",
783
+ add_special_tokens: bool = True,
784
+ padding: Union[bool, str, PaddingStrategy] = False,
785
+ truncation: Union[bool, str, TruncationStrategy] = False,
786
+ max_length: Optional[int] = None,
787
+ stride: int = 0,
788
+ return_tensors: Optional[str] = None,
789
+ return_token_type_ids: Optional[bool] = None,
790
+ return_attention_mask: Optional[bool] = True,
791
+ **kwargs
792
+ ):
793
+ """
794
+ Main tokenization method
795
+ """
796
+ # Convert single string to list for batch processing
797
+ if isinstance(text, str):
798
+ text = [text]
799
+ if isinstance(lang, str):
800
+ lang = [lang]
801
+ # Ensure lang list matches texts list
802
+ if len(lang) == 1 and len(text) > 1:
803
+ lang = lang * len(text)
804
+
805
+ # Ensure text and lang lists have same length
806
+ if len(text) != len(lang):
807
+ raise ValueError(f"Number of texts ({len(text)}) does not match number of languages ({len(lang)}).")
808
+
809
+ # Convert padding strategy
810
+ if isinstance(padding, bool):
811
+ padding_strategy = PaddingStrategy.LONGEST if padding else PaddingStrategy.DO_NOT_PAD
812
+ else:
813
+ padding_strategy = PaddingStrategy(padding)
814
+
815
+ # Convert truncation strategy
816
+ if isinstance(truncation, bool):
817
+ truncation_strategy = TruncationStrategy.LONGEST_FIRST if truncation else TruncationStrategy.DO_NOT_TRUNCATE
818
+ else:
819
+ truncation_strategy = TruncationStrategy(truncation)
820
+
821
+ # Use the batch encoding method
822
+ encoded = self._batch_encode_plus(
823
+ text,
824
+ add_special_tokens=add_special_tokens,
825
+ padding_strategy=padding_strategy,
826
+ truncation_strategy=truncation_strategy,
827
+ max_length=max_length,
828
+ stride=stride,
829
+ return_tensors=return_tensors,
830
+ return_token_type_ids=return_token_type_ids,
831
+ return_attention_mask=return_attention_mask,
832
+ lang=lang,
833
+ **kwargs
834
+ )
835
+
836
+ return encoded
xtts-v2.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3942a405803e6148140be867c3b9d2b601aff053b042e5e933ca89e49371072
3
+ size 345226804
xtts2_config.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass
2
+ from typing import Dict, Optional, List
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ @dataclass
10
+ class GPTAudioConfig:
11
+ """Configuration for GPT audio processing parameters"""
12
+ mel_channels: int = 80
13
+ sample_rate: int = 22050
14
+ output_sample_rate: int = 24000
15
+
16
+ @dataclass
17
+ class XTTSAudioConfig:
18
+ """Configuration for audio processing parameters"""
19
+ sample_rate: int = 22050
20
+ output_sample_rate: int = 24000
21
+ mel_channels: int = 80
22
+ hop_length: int = 256
23
+ win_length: int = 1024
24
+ n_fft: int = 1024
25
+ fmin: int = 0
26
+ fmax: int = 8000
27
+ power: float = 1.0
28
+ mel_norms_file: Optional[str] = None
29
+
30
+
31
+ class XTTSGPTConfig(PretrainedConfig):
32
+ """Configuration class for the GPT component of XTTS."""
33
+ model_type = "xtts_gpt"
34
+
35
+ def __init__(
36
+ self,
37
+ # Model architecture
38
+ hidden_size: int = 1024, # gpt_n_model_channels in original
39
+ n_inner: int = 4096,
40
+ num_hidden_layers: int = 30, # gpt_layers in original
41
+ num_attention_heads: int = 16, # gpt_n_heads in original
42
+
43
+ # Tokenizer settings
44
+ vocab_size: int = 6681, # gpt_number_text_tokens in original
45
+ number_text_tokens: int = 6681, # Explicit text token vocabulary size
46
+ start_text_token: Optional[int] = None,
47
+ stop_text_token: Optional[int] = None,
48
+
49
+ # Audio token settings
50
+ num_audio_tokens: int = 1026, # gpt_num_audio_tokens in original
51
+ start_audio_token: int = 1024, # gpt_start_audio_token in original
52
+ stop_audio_token: int = 1025, # gpt_stop_audio_token in original
53
+
54
+ # Sequence length settings
55
+ max_audio_tokens: int = 605, # gpt_max_audio_tokens in original
56
+ max_text_tokens: int = 402, # gpt_max_text_tokens in original
57
+ max_prompt_tokens: int = 70, # gpt_max_prompt_tokens in original
58
+ gpt_max_audio_tokens: int = 605, # Used for generation
59
+
60
+ # Model behavior settings
61
+ use_masking_gt_prompt_approach: bool = True, # gpt_use_masking_gt_prompt_approach in original
62
+ use_perceiver_resampler: bool = True, # gpt_use_perceiver_resampler in original
63
+ kv_cache: bool = True,
64
+ enable_redaction: bool = False,
65
+
66
+ # GPT batch settings
67
+ gpt_batch_size: int = 1,
68
+
69
+ # Audio processing
70
+ audio_config: Optional[Dict] = None,
71
+
72
+ # Architecture specifics
73
+ layer_norm_epsilon: float = 1e-5,
74
+ initializer_range: float = 0.02,
75
+ add_cross_attention: bool = False,
76
+ scale_attn_by_inverse_layer_idx: bool = False,
77
+ reorder_and_upcast_attn: bool = False,
78
+
79
+ # Size settings for the decoder
80
+ decoder_input_dim: int = 1024,
81
+ architectures=["XttsGPT"],
82
+ auto_map={
83
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
84
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
85
+ },
86
+ activation_function: str = "gelu",
87
+ attn_pdrop: float = 0.1,
88
+ **kwargs
89
+ ):
90
+ super().__init__(**kwargs)
91
+ self.architectures = architectures
92
+ self.auto_map = auto_map
93
+ self.audio_config = GPTAudioConfig(
94
+ **audio_config if audio_config is not None else {}
95
+ )
96
+ self.activation_function = activation_function
97
+ self.attn_pdrop = attn_pdrop
98
+ self.hidden_size = hidden_size
99
+ self.n_inner = n_inner
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.num_attention_heads = num_attention_heads
102
+
103
+ self.vocab_size = vocab_size
104
+ self.number_text_tokens = number_text_tokens
105
+ self.start_text_token = start_text_token
106
+ self.stop_text_token = stop_text_token
107
+
108
+ self.num_audio_tokens = num_audio_tokens
109
+ self.start_audio_token = start_audio_token
110
+ self.stop_audio_token = stop_audio_token
111
+
112
+ self.max_audio_tokens = max_audio_tokens
113
+ self.max_text_tokens = max_text_tokens
114
+ self.max_prompt_tokens = max_prompt_tokens
115
+ self.gpt_max_audio_tokens = gpt_max_audio_tokens
116
+
117
+ self.use_masking_gt_prompt_approach = use_masking_gt_prompt_approach
118
+ self.use_perceiver_resampler = use_perceiver_resampler
119
+ self.kv_cache = kv_cache
120
+ self.enable_redaction = enable_redaction
121
+
122
+ self.gpt_batch_size = gpt_batch_size
123
+
124
+ self.layer_norm_epsilon = layer_norm_epsilon
125
+ self.initializer_range = initializer_range
126
+ self.add_cross_attention = add_cross_attention
127
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
128
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
129
+
130
+ self.decoder_input_dim = decoder_input_dim
131
+
132
+ def to_dict(self) -> Dict:
133
+ """Convert the config to a dictionary."""
134
+ output = super().to_dict()
135
+ output["audio_config"] = asdict(self.audio_config)
136
+ return output
137
+
138
+ @classmethod
139
+ def from_dict(cls, config_dict: Dict, *args, **kwargs) -> "XTTSGPTConfig":
140
+ """Create a config from a dictionary."""
141
+ return cls(**config_dict)
142
+
143
+
144
+ class XTTSConfig(PretrainedConfig):
145
+ """Configuration class for XTTS model components except GPT."""
146
+ model_type = "xtts"
147
+
148
+ def __init__(
149
+ self,
150
+ # Audio settings
151
+ audio_config: Optional[Dict] = None,
152
+ input_sample_rate: int = 22050,
153
+ output_sample_rate: int = 24000,
154
+ output_hop_length: int = 256,
155
+
156
+ # Model architecture
157
+ decoder_input_dim: int = 1024,
158
+ d_vector_dim: int = 512,
159
+ cond_d_vector_in_each_upsampling_layer: bool = True,
160
+
161
+ # Training settings
162
+ gpt_code_stride_len: int = 1024,
163
+ duration_const: int = 102400,
164
+
165
+ # Tokenizer settings
166
+ tokenizer_file: str = "",
167
+ num_chars: int = 255,
168
+
169
+ # Language support
170
+ languages: Optional[List[str]] = None,
171
+
172
+ # GPT configuration
173
+ gpt_config: Optional[Dict] = None,
174
+ architectures=["Xtts"],
175
+ auto_map = {
176
+ "AutoConfig": "AstraMindAI/xtts2--xtts2_config.XTTSConfig",
177
+ "AutoModelForCausalLM": "AstraMindAI/xtts2--xtts2_modeling.Xtts",
178
+ },
179
+ **kwargs
180
+ ):
181
+ super().__init__(**kwargs)
182
+ self.architectures = architectures
183
+ self.auto_map = auto_map
184
+ # Initialize audio config
185
+ self.audio_config = XTTSAudioConfig(
186
+ **audio_config if audio_config is not None else {}
187
+ )
188
+
189
+ self.input_sample_rate = input_sample_rate
190
+ self.output_sample_rate = output_sample_rate
191
+ self.output_hop_length = output_hop_length
192
+
193
+ self.decoder_input_dim = decoder_input_dim
194
+ self.d_vector_dim = d_vector_dim
195
+ self.cond_d_vector_in_each_upsampling_layer = cond_d_vector_in_each_upsampling_layer
196
+
197
+ self.gpt_code_stride_len = gpt_code_stride_len
198
+ self.duration_const = duration_const
199
+
200
+ self.tokenizer_file = tokenizer_file
201
+ self.num_chars = num_chars
202
+
203
+ # Initialize GPT config
204
+ self.gpt = XTTSGPTConfig(**gpt_config if gpt_config is not None else {})
205
+
206
+ if languages is None:
207
+ self.languages = [
208
+ "en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru",
209
+ "nl", "cs", "ar", "zh-cn", "hu", "ko", "ja", "hi"
210
+ ]
211
+ else:
212
+ self.languages = languages
213
+
214
+ def to_dict(self) -> Dict:
215
+ """Convert the config to a dictionary."""
216
+ output = super().to_dict()
217
+ output["audio_config"] = asdict(self.audio_config)
218
+ output["gpt_config"] = self.gpt.to_dict()
219
+ return output
220
+
221
+ @classmethod
222
+ def from_dict(cls, config_dict: Dict, *args, **kwargs) -> "XTTSConfig":
223
+ """Create a config from a dictionary."""
224
+ if "gpt_config" in config_dict:
225
+ gpt_config = config_dict["gpt_config"]
226
+ config_dict = {k: v for k, v in config_dict.items() if k != "gpt_config"}
227
+ return cls(gpt_config=gpt_config, **config_dict)
228
+ return cls(**config_dict)
xtts2_modeling.py CHANGED
@@ -1,81 +1,433 @@
1
  import asyncio
 
 
 
 
 
2
  from dataclasses import dataclass
3
- from typing import Optional, List, Tuple
 
4
  from concurrent.futures import ThreadPoolExecutor
 
 
5
  import torch
6
  import numpy as np
7
- from transformers import PreTrainedModel
 
 
 
 
8
 
9
- from vllm import AsyncLLMEngine, AsyncEngineArgs, SamplingParams, TokensPrompt
10
  from vllm.multimodal import MultiModalDataDict
11
  from vllm.utils import Counter
12
 
13
  from TTS.TTS.tts.layers.xtts.hifigan_decoder import HifiDecoder
14
- from gpt_config import XTTSGPTConfig
15
- from xtts2_config import XTTSConfig
16
- from tokenizer import XTTSTokenizerFast
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
 
19
  @dataclass
20
  class XTTSRequest:
21
  """Container for XTTS inference request data"""
22
  request_id: str
23
- text: str
24
  language: str
25
- gpt_cond_latent: torch.Tensor
26
- speaker_embedding: torch.Tensor
27
  temperature: float = 0.75
28
  top_p: float = 0.85
29
  top_k: int = 50
30
- repetition_penalty: float = 10.0
31
  length_penalty: float = 1.0
32
  do_sample: bool = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
 
35
  @dataclass
36
  class XTTSOutput:
37
- """Container for XTTS inference output"""
38
  request_id: str
39
  wav: np.ndarray
40
- gpt_latents: np.ndarray
41
- speaker_embedding: torch.Tensor
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
43
 
44
- class Xtts(PreTrainedModel):
 
 
 
 
 
 
 
 
 
 
 
45
  """Async XTTS model implementation using VLLM's AsyncEngine."""
46
 
47
  def __init__(self, hifi_config: XTTSConfig, gpt_config: XTTSGPTConfig, tensor_parallel_size: int = 1, **kwargs):
 
 
48
  self.hifi_config = hifi_config
49
  self.gpt_config = gpt_config
 
 
50
  self.tp = tensor_parallel_size
51
  self.tokenizer = XTTSTokenizerFast.from_pretrained("AstraMindAI/xtts2-gpt")
52
  self.request_counter = Counter()
53
  self.executor = ThreadPoolExecutor(max_workers=4) # For CPU-bound tasks
54
- self.init_models()
 
 
55
  self.register_buffer("mel_stats", torch.ones(80))
56
 
57
- @staticmethod
58
- def get_memory_percentage(memory: int) -> float:
59
- """Get memory percentage."""
60
- return memory / torch.cuda.get_device_properties(0).total_memory
 
 
61
 
62
- async def init_models(self):
63
- """Initialize models with AsyncVLLMEngine."""
64
- # Initialize VLLM engine
65
- engine_args = AsyncEngineArgs(
66
- model=self.gpt_config.model_dir,
67
- tensor_parallel_size=self.tp,
68
- dtype="auto ",
69
- max_model_len=self.gpt_config.gpt_max_text_tokens + self.gpt_config.gpt_max_audio_tokens,
70
- gpu_memory_utilization=self.get_memory_percentage(2),# since the model neds 2 gb we need to calc the bare minimum memory
71
- trust_remote_code=True,
72
- skip_tokenizer_init=True, # no need to initialize tokenizer, we use our own
73
- max_num_batched_tokens=4096,
74
- max_num_seqs=256,
75
  )
76
 
77
- self.llm_engine = AsyncLLMEngine.from_engine_args(engine_args)
78
- self.llm_engine = AsyncLLMEngine
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  # Initialize HiFi-GAN decoder
80
  self.hifigan_decoder = HifiDecoder(
81
  input_sample_rate=self.hifi_config.input_sample_rate,
@@ -87,26 +439,78 @@ class Xtts(PreTrainedModel):
87
  cond_d_vector_in_each_upsampling_layer=self.hifi_config.cond_d_vector_in_each_upsampling_layer,
88
  )
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  @classmethod
91
  def from_pretrained(
92
  cls,
93
  pretrained_model_name_or_path: str,
94
- torch_dtype: torch.dtype = torch.float16,
95
  device_map: Optional[str] = "auto",
96
  tensor_parallel_size: int = 1,
97
  **kwargs,
98
  ) -> "Xtts":
99
- """Load pretrained XTTS model from HuggingFace Hub.
100
-
101
- Args:
102
- pretrained_model_name_or_path (str): Path to pretrained weights or HF Hub model id
103
- torch_dtype (torch.dtype, optional): Type to load the model as. Defaults to float16.
104
- device_map (str, optional): Device mapping strategy. Defaults to "auto".
105
- **kwargs: Additional arguments passed to the model.
106
-
107
- Returns:
108
- Xtts: Loaded model instance
109
- """
110
  from huggingface_hub import hf_hub_download
111
  import json
112
  import os
@@ -115,32 +519,18 @@ class Xtts(PreTrainedModel):
115
  if not os.path.exists(pretrained_model_name_or_path):
116
  config_file = hf_hub_download(
117
  repo_id=pretrained_model_name_or_path,
118
- filename="../xtts2_gpt/config.json"
119
  )
120
  with open(config_file, 'r') as f:
121
  config = json.load(f)
122
 
123
- gpt_config_file = hf_hub_download(
124
- repo_id=pretrained_model_name_or_path,
125
- filename="gpt_config.py"
126
- )
127
- with open(gpt_config_file, 'r') as f:
128
- gpt_config = json.loads(f.read())
129
-
130
- hifigan_config_file = hf_hub_download(
131
- repo_id=pretrained_model_name_or_path,
132
- filename="xtts2_config.py"
133
- )
134
- with open(hifigan_config_file, 'r') as f:
135
- hifigan_config = json.loads(f.read())
136
  else:
137
  # Load from local path
138
  with open(os.path.join(pretrained_model_name_or_path, "config.json"), 'r') as f:
139
  config = json.load(f)
140
 
141
-
142
  # Initialize configs
143
- gpt_config = XTTSGPTConfig(**config)
144
  hifi_config = XTTSConfig(**config)
145
 
146
  # Initialize model
@@ -153,107 +543,528 @@ class Xtts(PreTrainedModel):
153
 
154
  # Load model weights
155
  if not os.path.exists(pretrained_model_name_or_path):
156
- gpt_weights = hf_hub_download(
157
- repo_id=pretrained_model_name_or_path,
158
- filename="../xtts2_gpt/xttsv2-gpt.safetensors"
159
- )
160
  hifigan_weights = hf_hub_download(
161
  repo_id=pretrained_model_name_or_path,
162
- filename="xttsv2-hifigan-mel.safetensors"
163
  )
164
  else:
165
- gpt_weights = os.path.join(pretrained_model_name_or_path, "xttsv2-gpt.safetensors")
166
- hifigan_weights = os.path.join(pretrained_model_name_or_path, "xttsv2-hifigan-mel.safetensors")
167
 
168
- # Load GPT weights
169
  import safetensors.torch
170
- state_dict = safetensors.torch.load_file(gpt_weights)
171
- model.gpt.load_state_dict(state_dict)
172
 
173
  # Load HiFi-GAN weights
174
  hifigan_state = safetensors.torch.load_file(hifigan_weights)
175
- model.hifigan_decoder.load_state_dict(hifigan_state)
176
 
177
  # Set model properties
178
  model.config = config
179
 
180
  # Cast model to specified dtype
181
  model = model.to(torch_dtype)
182
-
183
- # Handle device mapping
184
- if device_map:
185
- from accelerate import dispatch_model
186
- model = dispatch_model(model, device_map=device_map)
187
 
188
  return model
189
 
190
- def prepare_inputs(self, text: str, language: str, gpt_cond_latent: torch.Tensor) -> Tuple[List[int], torch.Tensor]:
191
- """Prepare input text with conditioning tokens."""
192
- # Add special tokens and conditioning format
193
- # Format: <|condition|>latent_data<|endofcondition|>text<|endoftext|>
194
- text_tokens = self.tokenizer.encode(text, lang=language)
195
- return text_tokens, gpt_cond_latent
196
 
 
 
 
197
 
 
 
198
 
199
- async def generate_speech_async(self, request: XTTSRequest) -> XTTSOutput:
200
- """Generate speech for a single request asynchronously."""
201
- # Prepare input with conditioning
202
- tokens, gpt_cond_latent = self.prepare_inputs(
203
- request.text,
204
- request.language,
205
- request.gpt_cond_latent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  )
207
 
208
- # Setup sampling parameters
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  sampling_params = SamplingParams(
210
  temperature=request.temperature,
211
  top_p=request.top_p,
 
212
  top_k=request.top_k,
213
- repetition_penalty=request.repetition_penalty,
 
214
  max_tokens=self.gpt_config.gpt_max_audio_tokens,
215
- stop=['</s>', '<|endoftext|>']
216
- )
217
- engine_inputs = TokensPrompt( prompt_token_ids = tokens )
218
- if gpt_cond_latent is not None:
219
- engine_inputs["multi_modal_data"] = MultiModalDataDict({"audio":gpt_cond_latent})
220
- # Generate tokens using VLLM
221
- output_generator = self.llm_engine.generate(
222
- inputs=engine_inputs,
223
- sampling_params=sampling_params,
224
- request_id=request.request_id
225
  )
226
 
227
- async for outputs in output_generator:
228
- # Extract generated tokens
229
- generated_tokens = outputs.outputs[0].token_ids
 
230
 
231
- # Convert to hidden states (this step depends on your model architecture)
232
- hidden_states = await self._tokens_to_hidden_states(generated_tokens)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
- # Generate audio using HiFi-GAN (run in thread pool to avoid blocking)
235
- wav = await asyncio.get_event_loop().run_in_executor(
236
- self.executor,
237
- lambda: self.hifigan_decoder(
238
- hidden_states,
239
- g=request.speaker_embedding
240
- ).cpu().numpy().squeeze()
 
 
 
 
 
 
241
  )
242
 
243
- return XTTSOutput(
244
- request_id=request.request_id,
245
- wav=wav,
246
- gpt_latents=hidden_states.cpu().numpy(),
247
- speaker_embedding=request.speaker_embedding
 
 
 
 
248
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
 
251
- async def _tokens_to_hidden_states(self, tokens: List[int]) -> torch.Tensor:
252
- """Convert generated tokens to hidden states."""
253
- # This implementation depends on your specific model architecture
254
- # You'll need to adapt this based on how your model processes tokens
255
- # This is a placeholder implementation
256
- token_tensor = torch.tensor(tokens, device=self.device)
257
- # Use VLLM's engine to get hidden states
258
- hidden_states = await self.llm_engine.encode(token_tensor)
259
- return hidden_states
 
1
  import asyncio
2
+ import functools
3
+ import logging
4
+ import random
5
+ import time
6
+ import uuid
7
  from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Optional, List, Tuple, Union, AsyncGenerator, Dict, Any
10
  from concurrent.futures import ThreadPoolExecutor
11
+
12
+ import librosa
13
  import torch
14
  import numpy as np
15
+ import torchaudio
16
+ import sounddevice as sd
17
+ import io
18
+ from torch import nn
19
+ from IPython.display import Audio, display
20
 
21
+ from vllm import AsyncLLMEngine, AsyncEngineArgs, SamplingParams, TokensPrompt, RequestOutput
22
  from vllm.multimodal import MultiModalDataDict
23
  from vllm.utils import Counter
24
 
25
  from TTS.TTS.tts.layers.xtts.hifigan_decoder import HifiDecoder
26
+
27
+ from TTS.tts.layers.xtts.latent_encoder import ConditioningEncoder # noqa
28
+ from TTS.tts.layers.xtts.perceiver_encoder import PerceiverResampler # noqa
29
+
30
+ from .xtts2_config import XTTSConfig, XTTSGPTConfig
31
+ from .tokenizer import XTTSTokenizerFast
32
+
33
+ from ..xtts2_gpt.xtts2_gpt_modeling import LearnedPositionEmbeddings
34
+
35
+
36
+ def wav_to_mel_cloning(
37
+ wav,
38
+ mel_norms_file="../experiments/clips_mel_norms.pth",
39
+ mel_norms=None,
40
+ device=torch.device("cpu"),
41
+ n_fft=4096,
42
+ hop_length=1024,
43
+ win_length=4096,
44
+ power=2,
45
+ normalized=False,
46
+ sample_rate=22050,
47
+ f_min=0,
48
+ f_max=8000,
49
+ n_mels=80,
50
+ ):
51
+ mel_stft = torchaudio.transforms.MelSpectrogram(
52
+ n_fft=n_fft,
53
+ hop_length=hop_length,
54
+ win_length=win_length,
55
+ power=power,
56
+ normalized=normalized,
57
+ sample_rate=sample_rate,
58
+ f_min=f_min,
59
+ f_max=f_max,
60
+ n_mels=n_mels,
61
+ norm="slaney",
62
+ ).to(device)
63
+ wav = wav.to(device)
64
+ mel = mel_stft(wav)
65
+ mel = torch.log(torch.clamp(mel, min=1e-5))
66
+ if mel_norms is None:
67
+ mel_norms = torch.load(mel_norms_file, map_location=device)
68
+ mel = mel / mel_norms.unsqueeze(0).unsqueeze(-1)
69
+ return mel
70
+
71
+
72
+ def load_audio(audiopath, sampling_rate):
73
+ audio, lsr = torchaudio.load(audiopath)
74
+
75
+ # Stereo to mono if needed
76
+ if audio.size(0) != 1:
77
+ audio = torch.mean(audio, dim=0, keepdim=True)
78
+
79
+ if lsr != sampling_rate:
80
+ audio = torchaudio.functional.resample(audio, lsr, sampling_rate)
81
+
82
+ # Clip audio invalid values
83
+ audio.clip_(-1, 1)
84
+ return audio
85
 
86
 
87
  @dataclass
88
  class XTTSRequest:
89
  """Container for XTTS inference request data"""
90
  request_id: str
91
+ text: Union[AsyncGenerator[str, None], str]
92
  language: str
93
+ speaker_file: str # Path to the speaker audio file
94
+ generate_every_n_chars: Optional[int] = None
95
  temperature: float = 0.75
96
  top_p: float = 0.85
97
  top_k: int = 50
98
+ repetition_penalty: float = 5.0
99
  length_penalty: float = 1.0
100
  do_sample: bool = True
101
+ max_ref_length: int = 60
102
+ gpt_cond_len: int = 30
103
+ gpt_cond_chunk_len: int = 4
104
+
105
+
106
+ import threading
107
+
108
+ class HiddenStatesCollector:
109
+ def __init__(self):
110
+ self.outputs = {}
111
+ self.lock = threading.Lock()
112
+
113
+ def __call__(self, outputs: Optional[torch.Tensor], request_id: str):
114
+ """Save outputs for a specific request"""
115
+ with self.lock:
116
+ if request_id not in self.outputs:
117
+ self.outputs[request_id] = []
118
+ self.outputs[request_id].append(outputs)
119
+
120
+ def get_hidden_states(self, request_id) -> Optional[torch.Tensor]:
121
+ with self.lock:
122
+ outputs = self.outputs.pop(request_id, None)
123
+ if outputs is not None:
124
+ outputs = torch.cat(outputs, dim=0)
125
+ return outputs
126
+
127
+ def bind_to_request(self, request_id: str):
128
+ def bound_collector(outputs: Optional[torch.Tensor], _request_id: str = None):
129
+ self(outputs, request_id)
130
+ return bound_collector
131
+
132
+ class ExtendedSamplingParams(SamplingParams, kw_only=True):
133
+ """Extended sampling parameters that allows additional fields while maintaining compatibility with SamplingParams.
134
+
135
+ This class inherits from SamplingParams and allows adding new required fields
136
+ without conflicting with the base class's optional fields ordering.
137
+ """
138
+ hidden_state_collector: HiddenStatesCollector # New required field
139
+
140
+
141
+ class LogitsRepetitionPenalizer:
142
+ """A logits processor that applies repetition penalty to prevent repetitive text generation."""
143
+
144
+ def __init__(self, repetition_penalty: float):
145
+ if repetition_penalty < 0:
146
+ raise ValueError("Repetition penalty must be non-negative")
147
+ self.repetition_penalty = repetition_penalty
148
+
149
+ def __call__(self, token_ids: List[int], logits: torch.Tensor) -> torch.Tensor:
150
+ """Apply repetition penalty to the logits based on previous tokens."""
151
+ # If no repetition penalty or no tokens to check, return original logits
152
+ if self.repetition_penalty == 1.0 or not token_ids:
153
+ return logits
154
+
155
+ # Create a mask for the repeated tokens
156
+ repeated_tokens = torch.tensor(token_ids,
157
+ device=logits.device,
158
+ dtype=torch.long)
159
+
160
+ # Get logits of repeated tokens
161
+ repeated_logits = logits[repeated_tokens]
162
+
163
+ # Apply penalty: divide positive logits by penalty, multiply negative logits by penalty
164
+ repeated_logits = torch.where(
165
+ repeated_logits > 0,
166
+ repeated_logits / self.repetition_penalty,
167
+ repeated_logits * self.repetition_penalty
168
+ )
169
+
170
+ # Update only the logits for repeated tokens
171
+ logits[repeated_tokens] = repeated_logits
172
+
173
+ return logits
174
 
175
 
176
  @dataclass
177
  class XTTSOutput:
178
+ """Container for XTTS inference output with integrated audio utilities"""
179
  request_id: str
180
  wav: np.ndarray
181
+ sample_rate: int = 24000
182
+
183
+ def to_tensor(self) -> torch.Tensor:
184
+ """Convert numpy array to torch tensor"""
185
+ if isinstance(self.wav, np.ndarray):
186
+ return torch.from_numpy(self.wav)
187
+ return self.wav
188
+
189
+ def to_bytes(self, format: str = 'wav', sample_width: int = 2) -> bytes:
190
+ """Convert audio to bytes format.
191
+
192
+ Args:
193
+ format: Output format ('wav' or 'raw')
194
+ sample_width: Bit depth (1, 2, or 4 bytes per sample)
195
+
196
+ Returns:
197
+ Audio data as bytes
198
+ """
199
+ # Convert to tensor if needed
200
+ wav_tensor = self.to_tensor()
201
+
202
+ # Ensure correct shape (1, N) for torchaudio
203
+ if wav_tensor.dim() == 1:
204
+ wav_tensor = wav_tensor.unsqueeze(0)
205
+
206
+ # Normalize to [-1, 1]
207
+ wav_tensor = torch.clamp(wav_tensor, -1.0, 1.0)
208
+
209
+ if format == 'wav':
210
+ buffer = io.BytesIO()
211
+ torchaudio.save(
212
+ buffer,
213
+ wav_tensor,
214
+ self.sample_rate,
215
+ format="wav",
216
+ encoding="PCM_S" if sample_width == 2 else "PCM_F",
217
+ bits_per_sample=sample_width * 8
218
+ )
219
+ return buffer.getvalue()
220
+
221
+ elif format == 'raw':
222
+ # Scale to appropriate range based on sample width
223
+ if sample_width == 2: # 16-bit
224
+ wav_tensor = (wav_tensor * 32767).to(torch.int16)
225
+ elif sample_width == 4: # 32-bit
226
+ wav_tensor = (wav_tensor * 2147483647).to(torch.int32)
227
+ else: # 8-bit
228
+ wav_tensor = (wav_tensor * 127).to(torch.int8)
229
+ return wav_tensor.cpu().numpy().tobytes()
230
+
231
+ else:
232
+ raise ValueError(f"Unsupported format: {format}")
233
+
234
+ def save(self,
235
+ filename: Union[str, Path],
236
+ sample_rate: Optional[int] = None,
237
+ format: Optional[str] = None) -> None:
238
+ """Save audio to file.
239
+
240
+ Args:
241
+ filename: Output filename
242
+ sample_rate: Optional new sample rate for resampling
243
+ format: Optional format override (default: inferred from extension)
244
+ """
245
+ wav_tensor = self.to_tensor()
246
+ if wav_tensor.dim() == 1:
247
+ wav_tensor = wav_tensor.unsqueeze(0)
248
+
249
+ # Resample if needed
250
+ if sample_rate and sample_rate != self.sample_rate:
251
+ wav_tensor = torchaudio.functional.resample(
252
+ wav_tensor,
253
+ orig_freq=self.sample_rate,
254
+ new_freq=sample_rate
255
+ )
256
+ else:
257
+ sample_rate = self.sample_rate
258
+
259
+ torchaudio.save(
260
+ filename,
261
+ wav_tensor,
262
+ sample_rate,
263
+ format=format
264
+ )
265
+
266
+ def resample(self, new_sample_rate: int) -> 'XTTSOutput':
267
+ """Create new XTTSOutput with resampled audio.
268
+
269
+ Args:
270
+ new_sample_rate: Target sample rate
271
+
272
+ Returns:
273
+ New XTTSOutput instance with resampled audio
274
+ """
275
+ wav_tensor = self.to_tensor()
276
+ if wav_tensor.dim() == 1:
277
+ wav_tensor = wav_tensor.unsqueeze(0)
278
+
279
+ resampled = torchaudio.functional.resample(
280
+ wav_tensor,
281
+ orig_freq=self.sample_rate,
282
+ new_freq=new_sample_rate
283
+ )
284
+
285
+ return XTTSOutput(
286
+ request_id=self.request_id,
287
+ wav=resampled.squeeze().numpy(),
288
+ sample_rate=new_sample_rate
289
+ )
290
+
291
+ def get_info(self) -> Tuple[int, int, float]:
292
+ """Get audio information.
293
+
294
+ Returns:
295
+ Tuple of (number of samples, sample rate, duration in seconds)
296
+ """
297
+ n_samples = len(self.wav)
298
+ duration = n_samples / self.sample_rate
299
+ return n_samples, self.sample_rate, duration
300
+
301
+ @classmethod
302
+ def from_tensor(cls, request_id: str, tensor: torch.Tensor, sample_rate: int = 24000) -> 'XTTSOutput':
303
+ """Create XTTSOutput from torch tensor.
304
+
305
+ Args:
306
+ request_id: Request identifier
307
+ tensor: Audio tensor
308
+ sample_rate: Sample rate of the audio
309
+
310
+ Returns:
311
+ New XTTSOutput instance
312
+ """
313
+ return cls(
314
+ request_id=request_id,
315
+ wav=tensor.squeeze().cpu().numpy(),
316
+ sample_rate=sample_rate
317
+ )
318
+
319
+ @classmethod
320
+ def from_file(cls, request_id: str, filename: Union[str, Path]) -> 'XTTSOutput':
321
+ """Create XTTSOutput from audio file.
322
+
323
+ Args:
324
+ request_id: Request identifier
325
+ filename: Path to audio file
326
+
327
+ Returns:
328
+ New XTTSOutput instance
329
+ """
330
+ wav_tensor, sample_rate = torchaudio.load(filename)
331
+ return cls.from_tensor(request_id, wav_tensor, sample_rate)
332
+
333
+ def play(self) -> None:
334
+ """Play the audio through the default sound device.
335
+ For use in regular Python scripts/applications."""
336
+ # Ensure the audio is in the correct format
337
+ if isinstance(self.wav, torch.Tensor):
338
+ audio_data = self.wav.cpu().numpy()
339
+ else:
340
+ audio_data = self.wav
341
+
342
+ # Ensure float32 and normalize
343
+ if audio_data.dtype != np.float32:
344
+ audio_data = audio_data.astype(np.float32)
345
+ audio_data = np.clip(audio_data, -1.0, 1.0)
346
+
347
+ # Play the audio
348
+ sd.play(audio_data, self.sample_rate)
349
+ sd.wait() # Wait until the audio is finished playing
350
+
351
+ def display(self) -> Optional[Audio]:
352
+ """Display audio player in Jupyter notebook.
353
+ Returns Audio widget if in notebook, None otherwise."""
354
+ try:
355
+ # Convert to bytes
356
+ audio_bytes = self.to_bytes(format='wav')
357
 
358
+ # Create and display audio widget
359
+ audio_widget = Audio(audio_bytes, rate=self.sample_rate, autoplay=False)
360
+ display(audio_widget)
361
+ return audio_widget
362
+ except Exception as e:
363
+ print(f"Could not display audio widget: {str(e)}")
364
+ print("Try using .play() method instead")
365
+ return None
366
 
367
+ def preview(self) -> None:
368
+ """Smart play method that chooses appropriate playback method."""
369
+ try:
370
+ # Try notebook display first
371
+ if self.display() is None:
372
+ # Fall back to sounddevice if not in notebook
373
+ self.play()
374
+ except Exception as e:
375
+ print(f"Error playing audio: {str(e)}")
376
+
377
+
378
+ class Xtts(nn.Module):
379
  """Async XTTS model implementation using VLLM's AsyncEngine."""
380
 
381
  def __init__(self, hifi_config: XTTSConfig, gpt_config: XTTSGPTConfig, tensor_parallel_size: int = 1, **kwargs):
382
+ super().__init__()
383
+
384
  self.hifi_config = hifi_config
385
  self.gpt_config = gpt_config
386
+ self.mel_bos_token_id = gpt_config.start_audio_token
387
+ self.mel_eos_token_id = gpt_config.stop_audio_token
388
  self.tp = tensor_parallel_size
389
  self.tokenizer = XTTSTokenizerFast.from_pretrained("AstraMindAI/xtts2-gpt")
390
  self.request_counter = Counter()
391
  self.executor = ThreadPoolExecutor(max_workers=4) # For CPU-bound tasks
392
+ self.hidden_states_collector = HiddenStatesCollector()
393
+
394
+ # Register buffer before creating modules
395
  self.register_buffer("mel_stats", torch.ones(80))
396
 
397
+ # Initialize all nn.Module components
398
+ self.conditioning_encoder = ConditioningEncoder(
399
+ gpt_config.audio_config.mel_channels,
400
+ gpt_config.hidden_size,
401
+ num_attn_heads=gpt_config.num_attention_heads
402
+ )
403
 
404
+ self.text_embedding = nn.Embedding(
405
+ gpt_config.number_text_tokens,
406
+ gpt_config.hidden_size
 
 
 
 
 
 
 
 
 
 
407
  )
408
 
409
+ self.text_pos_embedding = (
410
+ LearnedPositionEmbeddings(
411
+ gpt_config.max_text_tokens + 2,
412
+ gpt_config.hidden_size,
413
+ supports_pp=False
414
+ )
415
+ if gpt_config.max_audio_tokens != -1
416
+ else functools.partial(gpt_config.null_position_embeddings, dim=gpt_config.hidden_size)
417
+ )
418
+
419
+ if gpt_config.use_perceiver_resampler:
420
+ self.conditioning_perceiver = PerceiverResampler(
421
+ dim=gpt_config.hidden_size,
422
+ depth=2,
423
+ dim_context=gpt_config.hidden_size,
424
+ num_latents=32,
425
+ dim_head=64,
426
+ heads=8,
427
+ ff_mult=4,
428
+ use_flash_attn=False,
429
+ )
430
+
431
  # Initialize HiFi-GAN decoder
432
  self.hifigan_decoder = HifiDecoder(
433
  input_sample_rate=self.hifi_config.input_sample_rate,
 
439
  cond_d_vector_in_each_upsampling_layer=self.hifi_config.cond_d_vector_in_each_upsampling_layer,
440
  )
441
 
442
+ # Kept for model loading purposes
443
+ self.text_head = nn.Linear(gpt_config.hidden_size, gpt_config.number_text_tokens, bias=True)
444
+ self.final_norm = nn.LayerNorm(gpt_config.hidden_size, eps=1e-5, bias=True)
445
+
446
+ # Initialize VLLM engine at the end
447
+ self.init_vllm_engine()
448
+
449
+ # Semaphore for concurrency control
450
+ self.max_concurrency = 10
451
+ self.semaphore = asyncio.BoundedSemaphore(self.max_concurrency)
452
+
453
+ def half(self):
454
+ # We cannot permit downcasting since it will throw an error while padding
455
+ return
456
+
457
+ def to(self, *args, **kwargs):
458
+ # Block downcasting
459
+ dtype = kwargs.get('dtype', None)
460
+ if dtype == torch.float16 or dtype == torch.bfloat16:
461
+ kwargs['dtype'] = torch.float32
462
+ elif len(args) > 0 and (args[0] == torch.float16 or args[0] == torch.bfloat16):
463
+ args = list(args)
464
+ args[0] = torch.float32
465
+ args = tuple(args)
466
+ return super().to(*args, **kwargs)
467
+
468
+ @property
469
+ def device(self):
470
+ """Get the current device of the model."""
471
+ return next(self.parameters()).device
472
+
473
+ @property
474
+ def dtype(self):
475
+ """Get the current dtype of the model."""
476
+ return next(self.parameters()).dtype
477
+
478
+ @staticmethod
479
+ def get_memory_percentage(memory: int) -> float:
480
+ """Get memory percentage."""
481
+ total_memory = torch.cuda.get_device_properties(0).total_memory
482
+ reserved_memory = torch.cuda.memory_reserved(0)
483
+ allocated_memory = torch.cuda.memory_allocated(0)
484
+ available_memory = total_memory - reserved_memory - allocated_memory
485
+ return memory / available_memory
486
+
487
+ def init_vllm_engine(self):
488
+ """Initialize models with AsyncVLLMEngine."""
489
+ engine_args = AsyncEngineArgs(
490
+ model="AstraMindAI/xtts2-gpt",
491
+ tensor_parallel_size=self.tp,
492
+ dtype="auto",
493
+ disable_log_stats=True,
494
+ max_model_len=self.gpt_config.max_text_tokens + self.gpt_config.max_audio_tokens,
495
+ gpu_memory_utilization=self.get_memory_percentage(3 * 1024 ** 3),
496
+ trust_remote_code=True,
497
+ enforce_eager=True,
498
+ limit_mm_per_prompt={"audio": 1},
499
+ max_num_batched_tokens=7296,
500
+ )
501
+
502
+ self.llm_engine = AsyncLLMEngine.from_engine_args(engine_args)
503
+
504
  @classmethod
505
  def from_pretrained(
506
  cls,
507
  pretrained_model_name_or_path: str,
508
+ torch_dtype: torch.dtype = torch.float32,
509
  device_map: Optional[str] = "auto",
510
  tensor_parallel_size: int = 1,
511
  **kwargs,
512
  ) -> "Xtts":
513
+ """Load pretrained XTTS model from HuggingFace Hub."""
 
 
 
 
 
 
 
 
 
 
514
  from huggingface_hub import hf_hub_download
515
  import json
516
  import os
 
519
  if not os.path.exists(pretrained_model_name_or_path):
520
  config_file = hf_hub_download(
521
  repo_id=pretrained_model_name_or_path,
522
+ filename="config.json"
523
  )
524
  with open(config_file, 'r') as f:
525
  config = json.load(f)
526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527
  else:
528
  # Load from local path
529
  with open(os.path.join(pretrained_model_name_or_path, "config.json"), 'r') as f:
530
  config = json.load(f)
531
 
 
532
  # Initialize configs
533
+ gpt_config = XTTSGPTConfig(**config['gpt_config'])
534
  hifi_config = XTTSConfig(**config)
535
 
536
  # Initialize model
 
543
 
544
  # Load model weights
545
  if not os.path.exists(pretrained_model_name_or_path):
 
 
 
 
546
  hifigan_weights = hf_hub_download(
547
  repo_id=pretrained_model_name_or_path,
548
+ filename="xtts-v2.safetensors"
549
  )
550
  else:
551
+ hifigan_weights = os.path.join(pretrained_model_name_or_path, "xtts-v2.safetensors")
 
552
 
 
553
  import safetensors.torch
 
 
554
 
555
  # Load HiFi-GAN weights
556
  hifigan_state = safetensors.torch.load_file(hifigan_weights)
557
+ model.load_state_dict(hifigan_state)
558
 
559
  # Set model properties
560
  model.config = config
561
 
562
  # Cast model to specified dtype
563
  model = model.to(torch_dtype)
564
+ model = model.to('cuda')
 
 
 
 
565
 
566
  return model
567
 
568
+ @staticmethod
569
+ def load_audio(audio_path: Union[str, Path], sampling_rate: int = 22050) -> torch.Tensor:
570
+ audio, lsr = torchaudio.load(audio_path)
 
 
 
571
 
572
+ # Stereo to mono if needed
573
+ if audio.size(0) != 1:
574
+ audio = torch.mean(audio, dim=0, keepdim=True)
575
 
576
+ if lsr != sampling_rate:
577
+ audio = torchaudio.functional.resample(audio, lsr, sampling_rate)
578
 
579
+ # Clip audio invalid values
580
+ audio.clip_(-1, 1)
581
+ return audio
582
+
583
+ @torch.inference_mode()
584
+ def get_speaker_embedding(self, audio, sr):
585
+ audio_16k = torchaudio.functional.resample(audio, sr, 16000)
586
+ return (
587
+ self.hifigan_decoder.speaker_encoder.forward(audio_16k.to(self.device), l2_norm=True)
588
+ .unsqueeze(-1)
589
+ .to(self.device)
590
+ )
591
+
592
+ @torch.inference_mode()
593
+ def get_gpt_cond_latents(self, audio, sr, length: int = 30, chunk_length: int = 6):
594
+ """Compute the conditioning latents for the GPT model from the given audio."""
595
+ if sr != 22050:
596
+ audio = torchaudio.functional.resample(audio, sr, 22050)
597
+ if length > 0:
598
+ audio = audio[:, : 22050 * length]
599
+ if self.gpt_config.use_perceiver_resampler:
600
+ style_embs = []
601
+ for i in range(0, audio.shape[1], 22050 * chunk_length):
602
+ audio_chunk = audio[:, i: i + 22050 * chunk_length]
603
+
604
+ # if the chunk is too short ignore it
605
+ if audio_chunk.size(-1) < 22050 * 0.33:
606
+ continue
607
+
608
+ mel_chunk = wav_to_mel_cloning(
609
+ audio_chunk,
610
+ mel_norms=self.mel_stats.cpu(),
611
+ n_fft=2048,
612
+ hop_length=256,
613
+ win_length=1024,
614
+ power=2,
615
+ normalized=False,
616
+ sample_rate=22050,
617
+ f_min=0,
618
+ f_max=8000,
619
+ n_mels=80,
620
+ )
621
+ style_emb = self.get_style_emb(mel_chunk.to(self.device), None)
622
+ style_embs.append(style_emb)
623
+
624
+ # mean style embedding
625
+ cond_latent = torch.stack(style_embs).mean(dim=0)
626
+ else:
627
+ mel = wav_to_mel_cloning(
628
+ audio,
629
+ mel_norms=self.mel_stats.cpu(),
630
+ n_fft=4096,
631
+ hop_length=1024,
632
+ win_length=4096,
633
+ power=2,
634
+ normalized=False,
635
+ sample_rate=22050,
636
+ f_min=0,
637
+ f_max=8000,
638
+ n_mels=80,
639
+ )
640
+ cond_latent = self.get_style_emb(mel.to(self.device))
641
+ return cond_latent.transpose(1, 2)
642
+
643
+ @torch.inference_mode()
644
+ def get_conditioning_latents(
645
+ self,
646
+ audio_path,
647
+ max_ref_length=30,
648
+ gpt_cond_len=6,
649
+ gpt_cond_chunk_len=6,
650
+ librosa_trim_db=None,
651
+ sound_norm_refs=False,
652
+ load_sr=22050,
653
+ ):
654
+ """Get the conditioning latents for the GPT model from the given audio."""
655
+ # Deal with multiple references
656
+ assert isinstance(audio_path, str) or isinstance(audio_path, list), "audio_path must be a string or a list."
657
+
658
+ if not isinstance(audio_path, list):
659
+ audio_paths = [audio_path]
660
+ else:
661
+ audio_paths = audio_path
662
+
663
+ speaker_embeddings = []
664
+ audios = []
665
+ for file_path in audio_paths:
666
+ audio = load_audio(file_path, load_sr)
667
+ audio = audio[:, : load_sr * max_ref_length].to(self.device).to(self.dtype)
668
+ if sound_norm_refs:
669
+ audio = (audio / torch.abs(audio).max()) * 0.75
670
+ if librosa_trim_db is not None:
671
+ audio = librosa.effects.trim(audio, top_db=librosa_trim_db)[0]
672
+
673
+ # Compute latents for the decoder
674
+ speaker_embedding = self.get_speaker_embedding(audio, load_sr)
675
+ speaker_embeddings.append(speaker_embedding)
676
+
677
+ audios.append(audio)
678
+
679
+ # Merge all the audios and compute the latents for the GPT
680
+ full_audio = torch.cat(audios, dim=-1)
681
+ gpt_cond_latents = self.get_gpt_cond_latents(
682
+ full_audio, load_sr, length=gpt_cond_len, chunk_length=gpt_cond_chunk_len
683
+ ) # [1, 1024, T]
684
+
685
+ speaker_embedding = torch.stack(speaker_embeddings)
686
+ speaker_embedding = speaker_embedding.mean(dim=0)
687
+
688
+ return gpt_cond_latents, speaker_embedding
689
+
690
+ def get_style_emb(self, cond_input: torch.Tensor, return_latent: bool = False) -> torch.Tensor:
691
+ """Get conditioning embeddings from mel spectrograms."""
692
+ if not return_latent:
693
+ if cond_input.ndim == 4:
694
+ cond_input = cond_input.squeeze(1)
695
+ conds = self.conditioning_encoder(cond_input)
696
+
697
+ if hasattr(self, 'conditioning_perceiver'):
698
+ conds = self.conditioning_perceiver(
699
+ conds.permute(0, 2, 1)
700
+ ).transpose(1, 2)
701
+ else:
702
+ conds = cond_input.unsqueeze(1)
703
+ return conds
704
+
705
+ async def prepare_text_tokens_async(self, text: str, language: str, split_text=False) \
706
+ -> Tuple[List[Union[int, List[int]]], List[torch.Tensor]]:
707
+ """Prepare text tokens for the given text and language."""
708
+
709
+ async def elaborate_tokens(text_tokens: List[int]) -> torch.Tensor:
710
+ text_tokens.insert(0, self.tokenizer.bos_token_id)
711
+ text_tokens.append(self.tokenizer.eos_token_id)
712
+ return torch.tensor(text_tokens).unsqueeze(0).to(self.text_embedding.weight.device)
713
+
714
+ async def embed_tokens(text_tokens: Union[torch.Tensor, List[torch.Tensor]]) -> List[torch.Tensor]:
715
+ embeds = []
716
+ if isinstance(text_tokens, list):
717
+ for list_element in text_tokens:
718
+ embeds.append(self.text_embedding(list_element) + self.text_pos_embedding(list_element))
719
+ else:
720
+ embeds.append(self.text_embedding(text_tokens) + self.text_pos_embedding(text_tokens))
721
+ return embeds
722
+
723
+ fake_tokens_for_audio_generation = []
724
+ if split_text:
725
+ text_tokens = self.tokenizer.batch_encode_with_split(text, lang=[language])
726
+ for idx, text_token in enumerate(text_tokens):
727
+ text_tokens[idx] = await elaborate_tokens(text_token)
728
+ fake_tokens_for_audio_generation.append([1] * len(text_token))
729
+ else:
730
+ text_tokens = self.tokenizer.batch_encode(text, lang=[language])
731
+ text_tokens = await elaborate_tokens(text_tokens)
732
+ fake_tokens_for_audio_generation = [1] * len(text_tokens)
733
+ return fake_tokens_for_audio_generation, await embed_tokens(text_tokens)
734
+
735
+ async def prepare_inputs_async(self, text: str, language: str, speaker_file: Union[str, Path],
736
+ max_ref_length: int, gpt_cond_len: int, gpt_cond_chunk_len: int, split_text: bool) \
737
+ -> Tuple[List[List[int]], List[torch.Tensor], torch.Tensor]:
738
+ """Prepare input text with conditioning tokens. Return combined conditioning latents"""
739
+ # Tokenize text based on the language
740
+ text_tokens, text_embeddings = await self.prepare_text_tokens_async(text, language, split_text)
741
+
742
+ # Load the speaker file and convert it to a tensor
743
+ gpt_cond_latent, speaker_embeddings = await self.get_conditioning_latents_async(
744
+ speaker_file,
745
+ max_ref_length,
746
+ gpt_cond_len,
747
+ gpt_cond_chunk_len
748
+ )
749
+
750
+ cond_latents = []
751
+ for text_embedding in text_embeddings:
752
+ # Concatenate along sequence dimension
753
+ cond_latents.append((torch.cat([gpt_cond_latent, text_embedding], dim=1).squeeze(0)
754
+ .to(self.llm_engine.engine.model_config.dtype)))
755
+
756
+ return text_tokens, cond_latents, speaker_embeddings
757
+
758
+ async def get_conditioning_latents_async(
759
+ self,
760
+ audio_path,
761
+ max_ref_length=30,
762
+ gpt_cond_len=6,
763
+ gpt_cond_chunk_len=6,
764
+ librosa_trim_db=None,
765
+ sound_norm_refs=False,
766
+ load_sr=22050,
767
+ ):
768
+ """Async version of get_conditioning_latents with concurrency control."""
769
+ async with self.semaphore:
770
+ # Run the original get_conditioning_latents in executor
771
+ result = await asyncio.get_event_loop().run_in_executor(
772
+ None,
773
+ functools.partial(self.get_conditioning_latents,
774
+ audio_path,
775
+ max_ref_length,
776
+ gpt_cond_len,
777
+ gpt_cond_chunk_len,
778
+ librosa_trim_db,
779
+ sound_norm_refs,
780
+ load_sr)
781
+ )
782
+ return result
783
+
784
+ async def get_model_logits(self, token_ids: List[int], conditioning: MultiModalDataDict) -> torch.Tensor:
785
+ """Get model logits for a specific request"""
786
+ request_id = uuid.uuid4().hex
787
+
788
+ # Add start and end tokens
789
+ token_ids = [self.mel_bos_token_id] + token_ids + [self.mel_eos_token_id] * 5
790
+
791
+ engine_inputs = TokensPrompt(prompt_token_ids=token_ids)
792
+ engine_inputs["multi_modal_data"] = conditioning
793
+
794
+ # Bind the collector to this request
795
+ bound_collector = self.hidden_states_collector.bind_to_request(request_id)
796
+
797
+ # Set up sampling parameters with the bound collector
798
+ sampling_params = ExtendedSamplingParams(
799
+ detokenize=False,
800
+ max_tokens=1,
801
+ hidden_state_collector=bound_collector,
802
  )
803
 
804
+ # Generate with unique request ID
805
+ generator = self.llm_engine.generate(
806
+ prompt=engine_inputs,
807
+ sampling_params=sampling_params,
808
+ request_id=request_id
809
+ )
810
+
811
+ # Consume the generator with a timeout
812
+ try:
813
+ async def consume_generator():
814
+ async for _ in generator:
815
+ pass
816
+
817
+ await asyncio.wait_for(consume_generator(), timeout=300)
818
+ except asyncio.TimeoutError:
819
+ raise RuntimeError("Timeout while generating logits")
820
+
821
+ # Get the collected hidden states
822
+ hidden_states = self.hidden_states_collector.get_hidden_states(request_id)
823
+
824
+ if hidden_states is None:
825
+ raise RuntimeError(f"No hidden states collected for request {request_id}")
826
+
827
+ return hidden_states[-len(token_ids):, ...].unsqueeze(0).to(self.device).to(self.dtype)
828
+
829
+
830
+ async def process_tokens_to_speech(
831
+ self,
832
+ generators: List[AsyncGenerator[RequestOutput, None]],
833
+ speaker_embeddings: torch.Tensor,
834
+ multimodal_data: List[torch.Tensor],
835
+ chunk_size: int = 20,
836
+ ) -> AsyncGenerator[XTTSOutput, None]:
837
+ """
838
+ Process multiple token generators concurrently and emit results sequentially.
839
+ Uses a queue-based approach to handle multiple generators reliably.
840
+ """
841
+ # Create a queue for each generator to store its results
842
+ queues = [asyncio.Queue() for _ in generators]
843
+
844
+ # Create tasks for processing each generator
845
+ tasks = []
846
+ for i, generator in enumerate(generators):
847
+ task = asyncio.create_task(
848
+ self._process_single_generator(
849
+ generator,
850
+ queues[i],
851
+ speaker_embeddings,
852
+ multimodal_data[i],
853
+ chunk_size
854
+ )
855
+ )
856
+ tasks.append(task)
857
+
858
+ try:
859
+ # Process queues in sequence
860
+ for i, queue in enumerate(queues):
861
+ while True:
862
+ result = await queue.get()
863
+ if result is None:
864
+ # This generator has finished
865
+ break
866
+ else:
867
+ yield result
868
+
869
+ finally:
870
+ # Ensure all tasks are properly cleaned up
871
+ for task in tasks:
872
+ if not task.done():
873
+ task.cancel()
874
+ await asyncio.gather(*tasks, return_exceptions=True)
875
+
876
+ async def _process_single_generator(
877
+ self,
878
+ generator: AsyncGenerator[RequestOutput, None],
879
+ queue: asyncio.Queue,
880
+ speaker_embeddings: torch.Tensor,
881
+ gpt_embed_input: torch.Tensor,
882
+ chunk_size: int
883
+ ) -> None:
884
+ """Process a single generator and put results in its queue."""
885
+ try:
886
+ last_decoded_token = 0
887
+ accumulated_tokens = []
888
+
889
+ async for output in generator:
890
+ # Get new tokens
891
+ new_tokens = output.outputs[0].token_ids[last_decoded_token:]
892
+ accumulated_tokens.extend(new_tokens)
893
+ last_decoded_token = len(accumulated_tokens)
894
+
895
+ # Process tokens when we have enough or it's the final output
896
+ if output.finished:# or len(accumulated_tokens) >= chunk_size: se lascio con acculated token mi ripete gli stesis toke, why??
897
+ # Process the accumulated tokens
898
+ hidden_states = await self.get_model_logits(
899
+ accumulated_tokens,
900
+ {
901
+ "audio": {
902
+ 'embeds': gpt_embed_input,
903
+ "is_logits_only_mode": True
904
+ }
905
+ }
906
+ )
907
+
908
+ # Generate audio segment
909
+ wav = await asyncio.get_event_loop().run_in_executor(
910
+ self.executor,
911
+ lambda: self.hifigan_decoder.inference(
912
+ hidden_states,
913
+ g=speaker_embeddings
914
+ ).cpu().numpy().squeeze()
915
+ )
916
+
917
+ # Put result in queue
918
+ await queue.put(XTTSOutput(
919
+ request_id=output.request_id,
920
+ wav=wav
921
+ ))
922
+
923
+ # Reset accumulated tokens
924
+ accumulated_tokens = []
925
+
926
+ if output.finished:
927
+ break
928
+
929
+ except Exception as e:
930
+ logging.error(f"Error in generator processing: {e}")
931
+ finally:
932
+ # Signal completion
933
+ await queue.put(None)
934
+
935
+ async def generate_speech_async_from_streaming_source(self, request: XTTSRequest) -> AsyncGenerator[XTTSOutput, None]:
936
+ """Generate speech for streaming source of text, making a streaming source of audio tokens and then decoding
937
+ and returning a streaming audio response."""
938
+ assert isinstance(request.text, AsyncGenerator), "Text must be an AsyncGenerator for streaming source."
939
+ # Prepare input with conditioning
940
+ gpt_cond_latent, speaker_embeddings = await self.get_conditioning_latents_async(
941
+ request.speaker_file,
942
+ request.max_ref_length,
943
+ request.gpt_cond_len,
944
+ request.gpt_cond_chunk_len
945
+ )
946
  sampling_params = SamplingParams(
947
  temperature=request.temperature,
948
  top_p=request.top_p,
949
+ detokenize=False,
950
  top_k=request.top_k,
951
+ logits_processors=[LogitsRepetitionPenalizer(request.repetition_penalty)],
952
+ repetition_penalty=1.0, # Since we're handling repetition penalty manually
953
  max_tokens=self.gpt_config.gpt_max_audio_tokens,
954
+ ignore_eos=True, # Ignore the tokenizer eos token since it is for textual generation
955
+ stop_token_ids=[self.mel_eos_token_id],
 
 
 
 
 
 
 
 
956
  )
957
 
958
+ accumulated_text = ""
959
+ async for text in request.text:
960
+ text = text.strip()
961
+ accumulated_text += text
962
 
963
+ if len(accumulated_text) > request.generate_every_n_chars:
964
+ tokens, embeddings = await self.prepare_text_tokens_async(accumulated_text, request.language)
965
+ gpt_embed_input = [torch.cat([gpt_cond_latent, embeddings[0]], dim=0)]
966
+
967
+ engine_inputs = TokensPrompt(prompt_token_ids=tokens)
968
+ if gpt_embed_input is not None:
969
+ engine_inputs["multi_modal_data"] = {"audio": {"embeds": gpt_embed_input, "is_logits_only_mode": False}}
970
+ token_generator = [self.llm_engine.generate(
971
+ prompt=engine_inputs,
972
+ sampling_params=sampling_params,
973
+ request_id=request.request_id,
974
+ )]
975
+ # Process tokens to speech
976
+ async for output in self.process_tokens_to_speech(
977
+ token_generator,
978
+ speaker_embeddings,
979
+ gpt_embed_input,
980
+ chunk_size=50
981
+ ):
982
+ yield output
983
+
984
+ accumulated_text = ""
985
+
986
+ async def generate_speech_from_text_async(self, request: XTTSRequest) -> AsyncGenerator[XTTSOutput, None]:
987
+ """Generate speech for a single request asynchronously."""
988
+ # Prepare input with conditioning
989
+ tokens_list, gpt_embed_inputs, speaker_embeddings = await self.prepare_inputs_async(
990
+ request.text,
991
+ request.language,
992
+ request.speaker_file,
993
+ request.max_ref_length,
994
+ request.gpt_cond_len,
995
+ request.gpt_cond_chunk_len,
996
+ split_text=True # Split text to avoid OOM on big texts
997
+ )
998
 
999
+ # Start all requests in parallel
1000
+ generators = []
1001
+ for seq_index, sequence in enumerate(tokens_list):
1002
+ sampling_params = SamplingParams(
1003
+ temperature=request.temperature,
1004
+ top_p=request.top_p,
1005
+ detokenize=False,
1006
+ top_k=request.top_k,
1007
+ logits_processors=[LogitsRepetitionPenalizer(request.repetition_penalty)],
1008
+ repetition_penalty=1.0, # Since we're handling repetition penalty manually
1009
+ max_tokens=self.gpt_config.gpt_max_audio_tokens,
1010
+ ignore_eos=True, # Ignore the tokenizer eos token since it is for textual generation
1011
+ stop_token_ids=[self.mel_eos_token_id],
1012
  )
1013
 
1014
+ engine_inputs = TokensPrompt(prompt_token_ids=sequence)
1015
+ if gpt_embed_inputs is not None:
1016
+ engine_inputs["multi_modal_data"] = {"audio": {"embeds": gpt_embed_inputs[seq_index], "is_logits_only_mode": False}}
1017
+
1018
+ # Get audio token generator from VLLM
1019
+ token_generator = self.llm_engine.generate(
1020
+ prompt=engine_inputs,
1021
+ sampling_params=sampling_params,
1022
+ request_id=f"{request.request_id}_{seq_index}",
1023
  )
1024
+ generators.append(token_generator)
1025
+
1026
+ # Process tokens to speech
1027
+ async for output in self.process_tokens_to_speech(
1028
+ generators,
1029
+ speaker_embeddings,
1030
+ gpt_embed_inputs,
1031
+ chunk_size=50
1032
+ ):
1033
+ yield output
1034
+
1035
+ def generate_speech_from_text(self, request: XTTSRequest) -> List[XTTSOutput]:
1036
+ """
1037
+ Synchronous wrapper for generate_speech_from_text_async.
1038
+
1039
+ Args:
1040
+ request: XTTSRequest object containing generation parameters
1041
 
1042
+ Returns:
1043
+ List of XTTSOutput containing the generated speech segments
1044
+ """
1045
+
1046
+ async def _collect_outputs():
1047
+ outputs = []
1048
+ async for output in self.generate_speech_from_text_async(request):
1049
+ outputs.append(output)
1050
+ return outputs
1051
+
1052
+ # Run the async code in an event loop
1053
+ import asyncio
1054
+
1055
+ # Get or create an event loop
1056
+ try:
1057
+ loop = asyncio.get_event_loop()
1058
+ except RuntimeError:
1059
+ loop = asyncio.new_event_loop()
1060
+ asyncio.set_event_loop(loop)
1061
+
1062
+ if loop.is_running():
1063
+ # Create a new loop if the current one is running
1064
+ new_loop = asyncio.new_event_loop()
1065
+ results = new_loop.run_until_complete(_collect_outputs())
1066
+ new_loop.close()
1067
+ else:
1068
+ results = loop.run_until_complete(_collect_outputs())
1069
 
1070
+ return results
 
 
 
 
 
 
 
 
xttsv2_gpt2/config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_function": "gelu",
3
+ "architectures": [
4
+ "XttsGPT"
5
+ ],
6
+ "attn_pdrop": 0.1,
7
+ "audio_config": {
8
+ "mel_channels": 80,
9
+ "output_sample_rate": 24000,
10
+ "sample_rate": 22050
11
+ },
12
+ "auto_map": {
13
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
14
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
15
+ "AutoTokenizer": "AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast"
16
+ },
17
+ "decoder_input_dim": 1024,
18
+ "enable_redaction": false,
19
+ "gpt_batch_size": 1,
20
+ "gpt_max_audio_tokens": 605,
21
+ "hidden_size": 1024,
22
+ "initializer_range": 0.02,
23
+ "kv_cache": true,
24
+ "layer_norm_epsilon": 1e-05,
25
+ "max_audio_tokens": 605,
26
+ "max_prompt_tokens": 70,
27
+ "max_text_tokens": 402,
28
+ "model_type": "xtts_gpt",
29
+ "n_inner": 4096,
30
+ "num_attention_heads": 16,
31
+ "num_audio_tokens": 1026,
32
+ "num_hidden_layers": 30,
33
+ "number_text_tokens": 6681,
34
+ "reorder_and_upcast_attn": false,
35
+ "scale_attn_by_inverse_layer_idx": false,
36
+ "start_audio_token": 1024,
37
+ "start_text_token": null,
38
+ "stop_audio_token": 1025,
39
+ "stop_text_token": null,
40
+ "transformers_version": "4.46.0",
41
+ "use_masking_gt_prompt_approach": true,
42
+ "use_perceiver_resampler": true,
43
+ "vocab_size": 6681
44
+ }
xttsv2_gpt2/gpt2_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:104d92b2297c243b64d1417bd5cfda015faca0a670e9bc90088eed0e844f8e35
3
+ size 1522497936
xttsv2_gpt2/gpt_config.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass
2
+ from typing import Dict, Optional, List
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ @dataclass
10
+ class GPTAudioConfig:
11
+ """Configuration for GPT audio processing parameters"""
12
+ mel_channels: int = 80
13
+ sample_rate: int = 22050
14
+ output_sample_rate: int = 24000
15
+
16
+ @dataclass
17
+ class XTTSAudioConfig:
18
+ """Configuration for audio processing parameters"""
19
+ sample_rate: int = 22050
20
+ output_sample_rate: int = 24000
21
+ mel_channels: int = 80
22
+ hop_length: int = 256
23
+ win_length: int = 1024
24
+ n_fft: int = 1024
25
+ fmin: int = 0
26
+ fmax: int = 8000
27
+ power: float = 1.0
28
+ mel_norms_file: Optional[str] = None
29
+
30
+
31
+ class XTTSGPTConfig(PretrainedConfig):
32
+ """Configuration class for the GPT component of XTTS."""
33
+ model_type = "xtts_gpt"
34
+
35
+ def __init__(
36
+ self,
37
+ # Model architecture
38
+ hidden_size: int = 1024, # gpt_n_model_channels in original
39
+ n_inner: int = 4096,
40
+ num_hidden_layers: int = 30, # gpt_layers in original
41
+ num_attention_heads: int = 16, # gpt_n_heads in original
42
+
43
+ # Tokenizer settings
44
+ vocab_size: int = 6681, # gpt_number_text_tokens in original
45
+ number_text_tokens: int = 6681, # Explicit text token vocabulary size
46
+ start_text_token: Optional[int] = None,
47
+ stop_text_token: Optional[int] = None,
48
+
49
+ # Audio token settings
50
+ num_audio_tokens: int = 1026, # gpt_num_audio_tokens in original
51
+ start_audio_token: int = 1024, # gpt_start_audio_token in original
52
+ stop_audio_token: int = 1025, # gpt_stop_audio_token in original
53
+
54
+ # Sequence length settings
55
+ max_audio_tokens: int = 605, # gpt_max_audio_tokens in original
56
+ max_text_tokens: int = 402, # gpt_max_text_tokens in original
57
+ max_prompt_tokens: int = 70, # gpt_max_prompt_tokens in original
58
+ gpt_max_audio_tokens: int = 605, # Used for generation
59
+
60
+ # Model behavior settings
61
+ use_masking_gt_prompt_approach: bool = True, # gpt_use_masking_gt_prompt_approach in original
62
+ use_perceiver_resampler: bool = True, # gpt_use_perceiver_resampler in original
63
+ kv_cache: bool = True,
64
+ enable_redaction: bool = False,
65
+
66
+ # GPT batch settings
67
+ gpt_batch_size: int = 1,
68
+
69
+ # Audio processing
70
+ audio_config: Optional[Dict] = None,
71
+
72
+ # Architecture specifics
73
+ layer_norm_epsilon: float = 1e-5,
74
+ initializer_range: float = 0.02,
75
+ add_cross_attention: bool = False,
76
+ scale_attn_by_inverse_layer_idx: bool = False,
77
+ reorder_and_upcast_attn: bool = False,
78
+
79
+ # Size settings for the decoder
80
+ decoder_input_dim: int = 1024,
81
+ architectures=["XttsGPT"],
82
+ auto_map={
83
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
84
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
85
+ },
86
+ activation_function: str = "gelu",
87
+ attn_pdrop: float = 0.1,
88
+ **kwargs
89
+ ):
90
+ super().__init__(**kwargs)
91
+ self.architectures = architectures
92
+ self.auto_map = auto_map
93
+ self.audio_config = GPTAudioConfig(
94
+ **audio_config if audio_config is not None else {}
95
+ )
96
+ self.activation_function = activation_function
97
+ self.attn_pdrop = attn_pdrop
98
+ self.hidden_size = hidden_size
99
+ self.n_inner = n_inner
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.num_attention_heads = num_attention_heads
102
+
103
+ self.vocab_size = vocab_size
104
+ self.number_text_tokens = number_text_tokens
105
+ self.start_text_token = start_text_token
106
+ self.stop_text_token = stop_text_token
107
+
108
+ self.num_audio_tokens = num_audio_tokens
109
+ self.start_audio_token = start_audio_token
110
+ self.stop_audio_token = stop_audio_token
111
+
112
+ self.max_audio_tokens = max_audio_tokens
113
+ self.max_text_tokens = max_text_tokens
114
+ self.max_prompt_tokens = max_prompt_tokens
115
+ self.gpt_max_audio_tokens = gpt_max_audio_tokens
116
+
117
+ self.use_masking_gt_prompt_approach = use_masking_gt_prompt_approach
118
+ self.use_perceiver_resampler = use_perceiver_resampler
119
+ self.kv_cache = kv_cache
120
+ self.enable_redaction = enable_redaction
121
+
122
+ self.gpt_batch_size = gpt_batch_size
123
+
124
+ self.layer_norm_epsilon = layer_norm_epsilon
125
+ self.initializer_range = initializer_range
126
+ self.add_cross_attention = add_cross_attention
127
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
128
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
129
+
130
+ self.decoder_input_dim = decoder_input_dim
131
+
132
+ def to_dict(self) -> Dict:
133
+ """Convert the config to a dictionary."""
134
+ output = super().to_dict()
135
+ output["audio_config"] = asdict(self.audio_config)
136
+ return output
137
+
138
+ @classmethod
139
+ def from_dict(cls, config_dict: Dict, *args, **kwargs) -> "XTTSGPTConfig":
140
+ """Create a config from a dictionary."""
141
+ return cls(**config_dict)
142
+
143
+
xttsv2_gpt2/special_tokens_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "[START]",
3
+ "eos_token": "[STOP]",
4
+ "pad_token": "[PAD]",
5
+ "unk_token": "[UNK]"
6
+ }
xttsv2_gpt2/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
xttsv2_gpt2/tokenizer.py ADDED
@@ -0,0 +1,887 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import textwrap
4
+ from typing import List, Optional, Union, Dict, Any
5
+ from functools import cached_property
6
+
7
+ import pypinyin
8
+ import torch
9
+ from hangul_romanize import Transliter
10
+ from hangul_romanize.rule import academic
11
+ from num2words import num2words
12
+ from spacy.lang.ar import Arabic
13
+ from spacy.lang.en import English
14
+ from spacy.lang.es import Spanish
15
+ from spacy.lang.ja import Japanese
16
+ from spacy.lang.zh import Chinese
17
+ from transformers import PreTrainedTokenizerFast, BatchEncoding
18
+ from transformers.tokenization_utils_base import TruncationStrategy, PaddingStrategy
19
+ from tokenizers import Tokenizer
20
+ from tokenizers.pre_tokenizers import WhitespaceSplit
21
+ from tokenizers.processors import TemplateProcessing
22
+
23
+ from TTS.tts.layers.xtts.zh_num2words import TextNorm as zh_num2words
24
+
25
+ import cutlet
26
+
27
+ # Funzioni di preprocessing del testo
28
+
29
+ def get_spacy_lang(lang):
30
+ if lang == "zh":
31
+ return Chinese()
32
+ elif lang == "ja":
33
+ return Japanese()
34
+ elif lang == "ar":
35
+ return Arabic()
36
+ elif lang == "es":
37
+ return Spanish()
38
+ else:
39
+ # For most languages, English does the job
40
+ return English()
41
+
42
+ def split_sentence(text, lang, text_split_length=250):
43
+ """Preprocess the input text and split into sentences based on language."""
44
+ text_splits = []
45
+ if text_split_length is not None and len(text) >= text_split_length:
46
+ text_splits.append("")
47
+ nlp = get_spacy_lang(lang)
48
+ nlp.add_pipe("sentencizer")
49
+ doc = nlp(text)
50
+ for sentence in doc.sents:
51
+ if len(text_splits[-1]) + len(str(sentence)) <= text_split_length:
52
+ text_splits[-1] += " " + str(sentence)
53
+ text_splits[-1] = text_splits[-1].lstrip()
54
+ elif len(str(sentence)) > text_split_length:
55
+ for line in textwrap.wrap(
56
+ str(sentence),
57
+ width=text_split_length,
58
+ drop_whitespace=True,
59
+ break_on_hyphens=False,
60
+ tabsize=1,
61
+ ):
62
+ text_splits.append(str(line))
63
+ else:
64
+ text_splits.append(str(sentence))
65
+
66
+ if len(text_splits) > 1 and text_splits[0] == "":
67
+ del text_splits[0]
68
+ else:
69
+ text_splits = [text.lstrip()]
70
+
71
+ return text_splits
72
+
73
+ _whitespace_re = re.compile(r"\s+")
74
+
75
+ # List of (regular expression, replacement) pairs for abbreviations:
76
+ _abbreviations = {
77
+ "en": [
78
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
79
+ for x in [
80
+ ("mrs", "misess"),
81
+ ("mr", "mister"),
82
+ ("dr", "doctor"),
83
+ ("st", "saint"),
84
+ ("co", "company"),
85
+ ("jr", "junior"),
86
+ ("maj", "major"),
87
+ ("gen", "general"),
88
+ ("drs", "doctors"),
89
+ ("rev", "reverend"),
90
+ ("lt", "lieutenant"),
91
+ ("hon", "honorable"),
92
+ ("sgt", "sergeant"),
93
+ ("capt", "captain"),
94
+ ("esq", "esquire"),
95
+ ("ltd", "limited"),
96
+ ("col", "colonel"),
97
+ ("ft", "fort"),
98
+ ]
99
+ ],
100
+ "es": [
101
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
102
+ for x in [
103
+ ("sra", "señora"),
104
+ ("sr", "señor"),
105
+ ("dr", "doctor"),
106
+ ("dra", "doctora"),
107
+ ("st", "santo"),
108
+ ("co", "compañía"),
109
+ ("jr", "junior"),
110
+ ("ltd", "limitada"),
111
+ ]
112
+ ],
113
+ "fr": [
114
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
115
+ for x in [
116
+ ("mme", "madame"),
117
+ ("mr", "monsieur"),
118
+ ("dr", "docteur"),
119
+ ("st", "saint"),
120
+ ("co", "compagnie"),
121
+ ("jr", "junior"),
122
+ ("ltd", "limitée"),
123
+ ]
124
+ ],
125
+ "de": [
126
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
127
+ for x in [
128
+ ("fr", "frau"),
129
+ ("dr", "doktor"),
130
+ ("st", "sankt"),
131
+ ("co", "firma"),
132
+ ("jr", "junior"),
133
+ ]
134
+ ],
135
+ "pt": [
136
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
137
+ for x in [
138
+ ("sra", "senhora"),
139
+ ("sr", "senhor"),
140
+ ("dr", "doutor"),
141
+ ("dra", "doutora"),
142
+ ("st", "santo"),
143
+ ("co", "companhia"),
144
+ ("jr", "júnior"),
145
+ ("ltd", "limitada"),
146
+ ]
147
+ ],
148
+ "it": [
149
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
150
+ for x in [
151
+ # ("sig.ra", "signora"),
152
+ ("sig", "signore"),
153
+ ("dr", "dottore"),
154
+ ("st", "santo"),
155
+ ("co", "compagnia"),
156
+ ("jr", "junior"),
157
+ ("ltd", "limitata"),
158
+ ]
159
+ ],
160
+ "pl": [
161
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
162
+ for x in [
163
+ ("p", "pani"),
164
+ ("m", "pan"),
165
+ ("dr", "doktor"),
166
+ ("sw", "święty"),
167
+ ("jr", "junior"),
168
+ ]
169
+ ],
170
+ "ar": [
171
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
172
+ for x in [
173
+ # There are not many common abbreviations in Arabic as in English.
174
+ ]
175
+ ],
176
+ "zh": [
177
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
178
+ for x in [
179
+ # Chinese doesn't typically use abbreviations in the same way as Latin-based scripts.
180
+ ]
181
+ ],
182
+ "cs": [
183
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
184
+ for x in [
185
+ ("dr", "doktor"), # doctor
186
+ ("ing", "inženýr"), # engineer
187
+ ("p", "pan"), # Could also map to pani for woman but no easy way to do it
188
+ # Other abbreviations would be specialized and not as common.
189
+ ]
190
+ ],
191
+ "ru": [
192
+ (re.compile("\\b%s\\b" % x[0], re.IGNORECASE), x[1])
193
+ for x in [
194
+ ("г-жа", "госпожа"), # Mrs.
195
+ ("г-н", "господин"), # Mr.
196
+ ("д-р", "доктор"), # doctor
197
+ # Other abbreviations are less common or specialized.
198
+ ]
199
+ ],
200
+ "nl": [
201
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
202
+ for x in [
203
+ ("dhr", "de heer"), # Mr.
204
+ ("mevr", "mevrouw"), # Mrs.
205
+ ("dr", "dokter"), # doctor
206
+ ("jhr", "jonkheer"), # young lord or nobleman
207
+ # Dutch uses more abbreviations, but these are the most common ones.
208
+ ]
209
+ ],
210
+ "tr": [
211
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
212
+ for x in [
213
+ ("b", "bay"), # Mr.
214
+ ("byk", "büyük"), # büyük
215
+ ("dr", "doktor"), # doctor
216
+ # Add other Turkish abbreviations here if needed.
217
+ ]
218
+ ],
219
+ "hu": [
220
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
221
+ for x in [
222
+ ("dr", "doktor"), # doctor
223
+ ("b", "bácsi"), # Mr.
224
+ ("nőv", "nővér"), # nurse
225
+ # Add other Hungarian abbreviations here if needed.
226
+ ]
227
+ ],
228
+ "ko": [
229
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
230
+ for x in [
231
+ # Korean doesn't typically use abbreviations in the same way as Latin-based scripts.
232
+ ]
233
+ ],
234
+ }
235
+
236
+ def expand_abbreviations_multilingual(text, lang="en"):
237
+ if lang in _abbreviations:
238
+ for regex, replacement in _abbreviations[lang]:
239
+ text = re.sub(regex, replacement, text)
240
+ return text
241
+
242
+ _symbols_multilingual = {
243
+ "en": [
244
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
245
+ for x in [
246
+ ("&", " and "),
247
+ ("@", " at "),
248
+ ("%", " percent "),
249
+ ("#", " hash "),
250
+ ("$", " dollar "),
251
+ ("£", " pound "),
252
+ ("°", " degree "),
253
+ ]
254
+ ],
255
+ "es": [
256
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
257
+ for x in [
258
+ ("&", " y "),
259
+ ("@", " arroba "),
260
+ ("%", " por ciento "),
261
+ ("#", " numeral "),
262
+ ("$", " dolar "),
263
+ ("£", " libra "),
264
+ ("°", " grados "),
265
+ ]
266
+ ],
267
+ "fr": [
268
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
269
+ for x in [
270
+ ("&", " et "),
271
+ ("@", " arobase "),
272
+ ("%", " pour cent "),
273
+ ("#", " dièse "),
274
+ ("$", " dollar "),
275
+ ("£", " livre "),
276
+ ("°", " degrés "),
277
+ ]
278
+ ],
279
+ "de": [
280
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
281
+ for x in [
282
+ ("&", " und "),
283
+ ("@", " at "),
284
+ ("%", " prozent "),
285
+ ("#", " raute "),
286
+ ("$", " dollar "),
287
+ ("£", " pfund "),
288
+ ("°", " grad "),
289
+ ]
290
+ ],
291
+ "pt": [
292
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
293
+ for x in [
294
+ ("&", " e "),
295
+ ("@", " arroba "),
296
+ ("%", " por cento "),
297
+ ("#", " cardinal "),
298
+ ("$", " dólar "),
299
+ ("£", " libra "),
300
+ ("°", " graus "),
301
+ ]
302
+ ],
303
+ "it": [
304
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
305
+ for x in [
306
+ ("&", " e "),
307
+ ("@", " chiocciola "),
308
+ ("%", " per cento "),
309
+ ("#", " cancelletto "),
310
+ ("$", " dollaro "),
311
+ ("£", " sterlina "),
312
+ ("°", " gradi "),
313
+ ]
314
+ ],
315
+ "pl": [
316
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
317
+ for x in [
318
+ ("&", " i "),
319
+ ("@", " małpa "),
320
+ ("%", " procent "),
321
+ ("#", " krzyżyk "),
322
+ ("$", " dolar "),
323
+ ("£", " funt "),
324
+ ("°", " stopnie "),
325
+ ]
326
+ ],
327
+ "ar": [
328
+ # Arabic
329
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
330
+ for x in [
331
+ ("&", " و "),
332
+ ("@", " على "),
333
+ ("%", " في المئة "),
334
+ ("#", " رقم "),
335
+ ("$", " دولار "),
336
+ ("£", " جنيه "),
337
+ ("°", " درجة "),
338
+ ]
339
+ ],
340
+ "zh": [
341
+ # Chinese
342
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
343
+ for x in [
344
+ ("&", " 和 "),
345
+ ("@", " 在 "),
346
+ ("%", " 百分之 "),
347
+ ("#", " 号 "),
348
+ ("$", " 美元 "),
349
+ ("£", " 英镑 "),
350
+ ("°", " 度 "),
351
+ ]
352
+ ],
353
+ "cs": [
354
+ # Czech
355
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
356
+ for x in [
357
+ ("&", " a "),
358
+ ("@", " na "),
359
+ ("%", " procento "),
360
+ ("#", " křížek "),
361
+ ("$", " dolar "),
362
+ ("£", " libra "),
363
+ ("°", " stupně "),
364
+ ]
365
+ ],
366
+ "ru": [
367
+ # Russian
368
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
369
+ for x in [
370
+ ("&", " и "),
371
+ ("@", " собака "),
372
+ ("%", " процентов "),
373
+ ("#", " номер "),
374
+ ("$", " доллар "),
375
+ ("£", " фунт "),
376
+ ("°", " градус "),
377
+ ]
378
+ ],
379
+ "nl": [
380
+ # Dutch
381
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
382
+ for x in [
383
+ ("&", " en "),
384
+ ("@", " bij "),
385
+ ("%", " procent "),
386
+ ("#", " hekje "),
387
+ ("$", " dollar "),
388
+ ("£", " pond "),
389
+ ("°", " graden "),
390
+ ]
391
+ ],
392
+ "tr": [
393
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
394
+ for x in [
395
+ ("&", " ve "),
396
+ ("@", " at "),
397
+ ("%", " yüzde "),
398
+ ("#", " diyez "),
399
+ ("$", " dolar "),
400
+ ("£", " sterlin "),
401
+ ("°", " derece "),
402
+ ]
403
+ ],
404
+ "hu": [
405
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
406
+ for x in [
407
+ ("&", " és "),
408
+ ("@", " kukac "),
409
+ ("%", " százalék "),
410
+ ("#", " kettőskereszt "),
411
+ ("$", " dollár "),
412
+ ("£", " font "),
413
+ ("°", " fok "),
414
+ ]
415
+ ],
416
+ "ko": [
417
+ # Korean
418
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
419
+ for x in [
420
+ ("&", " 그리고 "),
421
+ ("@", " 에 "),
422
+ ("%", " 퍼센트 "),
423
+ ("#", " 번호 "),
424
+ ("$", " 달러 "),
425
+ ("£", " 파운드 "),
426
+ ("°", " 도 "),
427
+ ]
428
+ ],
429
+ }
430
+
431
+ def expand_symbols_multilingual(text, lang="en"):
432
+ if lang in _symbols_multilingual:
433
+ for regex, replacement in _symbols_multilingual[lang]:
434
+ text = re.sub(regex, replacement, text)
435
+ text = text.replace(" ", " ") # Ensure there are no double spaces
436
+ return text.strip()
437
+
438
+ _ordinal_re = {
439
+ "en": re.compile(r"([0-9]+)(st|nd|rd|th)"),
440
+ "es": re.compile(r"([0-9]+)(º|ª|er|o|a|os|as)"),
441
+ "fr": re.compile(r"([0-9]+)(º|ª|er|re|e|ème)"),
442
+ "de": re.compile(r"([0-9]+)(st|nd|rd|th|º|ª|\.(?=\s|$))"),
443
+ "pt": re.compile(r"([0-9]+)(º|ª|o|a|os|as)"),
444
+ "it": re.compile(r"([0-9]+)(º|°|ª|o|a|i|e)"),
445
+ "pl": re.compile(r"([0-9]+)(º|ª|st|nd|rd|th)"),
446
+ "ar": re.compile(r"([0-9]+)(ون|ين|ث|ر|ى)"),
447
+ "cs": re.compile(r"([0-9]+)\.(?=\s|$)"), # In Czech, a dot is often used after the number to indicate ordinals.
448
+ "ru": re.compile(r"([0-9]+)(-й|-я|-е|-ое|-ье|-го)"),
449
+ "nl": re.compile(r"([0-9]+)(de|ste|e)"),
450
+ "tr": re.compile(r"([0-9]+)(\.|inci|nci|uncu|üncü|\.)"),
451
+ "hu": re.compile(r"([0-9]+)(\.|adik|edik|odik|edik|ödik|ödike|ik)"),
452
+ "ko": re.compile(r"([0-9]+)(번째|번|차|째)"),
453
+ }
454
+ _number_re = re.compile(r"[0-9]+")
455
+ _currency_re = {
456
+ "USD": re.compile(r"((\$[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+\$))"),
457
+ "GBP": re.compile(r"((£[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+£))"),
458
+ "EUR": re.compile(r"(([0-9\.\,]*[0-9]+€)|((€[0-9\.\,]*[0-9]+)))"),
459
+ }
460
+
461
+ _comma_number_re = re.compile(r"\b\d{1,3}(,\d{3})*(\.\d+)?\b")
462
+ _dot_number_re = re.compile(r"\b\d{1,3}(\.\d{3})*(\,\d+)?\b")
463
+ _decimal_number_re = re.compile(r"([0-9]+[.,][0-9]+)")
464
+
465
+ def _remove_commas(m):
466
+ text = m.group(0)
467
+ if "," in text:
468
+ text = text.replace(",", "")
469
+ return text
470
+
471
+ def _remove_dots(m):
472
+ text = m.group(0)
473
+ if "." in text:
474
+ text = text.replace(".", "")
475
+ return text
476
+
477
+ def _expand_decimal_point(m, lang="en"):
478
+ amount = m.group(1).replace(",", ".")
479
+ return num2words(float(amount), lang=lang if lang != "cs" else "cz")
480
+
481
+ def _expand_currency(m, lang="en", currency="USD"):
482
+ amount = float((re.sub(r"[^\d.]", "", m.group(0).replace(",", "."))))
483
+ full_amount = num2words(amount, to="currency", currency=currency, lang=lang if lang != "cs" else "cz")
484
+
485
+ and_equivalents = {
486
+ "en": ", ",
487
+ "es": " con ",
488
+ "fr": " et ",
489
+ "de": " und ",
490
+ "pt": " e ",
491
+ "it": " e ",
492
+ "pl": ", ",
493
+ "cs": ", ",
494
+ "ru": ", ",
495
+ "nl": ", ",
496
+ "ar": ", ",
497
+ "tr": ", ",
498
+ "hu": ", ",
499
+ "ko": ", ",
500
+ }
501
+
502
+ if amount.is_integer():
503
+ last_and = full_amount.rfind(and_equivalents.get(lang, ", "))
504
+ if last_and != -1:
505
+ full_amount = full_amount[:last_and]
506
+
507
+ return full_amount
508
+
509
+ def _expand_ordinal(m, lang="en"):
510
+ return num2words(int(m.group(1)), ordinal=True, lang=lang if lang != "cs" else "cz")
511
+
512
+ def _expand_number(m, lang="en"):
513
+ return num2words(int(m.group(0)), lang=lang if lang != "cs" else "cz")
514
+
515
+ def expand_numbers_multilingual(text, lang="en"):
516
+ if lang == "zh":
517
+ text = zh_num2words()(text)
518
+ else:
519
+ if lang in ["en", "ru"]:
520
+ text = re.sub(_comma_number_re, _remove_commas, text)
521
+ else:
522
+ text = re.sub(_dot_number_re, _remove_dots, text)
523
+ try:
524
+ text = re.sub(_currency_re["GBP"], lambda m: _expand_currency(m, lang, "GBP"), text)
525
+ text = re.sub(_currency_re["USD"], lambda m: _expand_currency(m, lang, "USD"), text)
526
+ text = re.sub(_currency_re["EUR"], lambda m: _expand_currency(m, lang, "EUR"), text)
527
+ except Exception as e:
528
+ pass
529
+ if lang != "tr":
530
+ text = re.sub(_decimal_number_re, lambda m: _expand_decimal_point(m, lang), text)
531
+ if lang in _ordinal_re:
532
+ text = re.sub(_ordinal_re[lang], lambda m: _expand_ordinal(m, lang), text)
533
+ text = re.sub(_number_re, lambda m: _expand_number(m, lang), text)
534
+ return text
535
+
536
+ def lowercase(text):
537
+ return text.lower()
538
+
539
+ def collapse_whitespace(text):
540
+ return re.sub(_whitespace_re, " ", text)
541
+
542
+ def multilingual_cleaners(text, lang):
543
+ text = text.replace('"', "")
544
+ if lang == "tr":
545
+ text = text.replace("İ", "i")
546
+ text = text.replace("Ö", "ö")
547
+ text = text.replace("Ü", "ü")
548
+ text = lowercase(text)
549
+ text = expand_numbers_multilingual(text, lang)
550
+ text = expand_abbreviations_multilingual(text, lang)
551
+ text = expand_symbols_multilingual(text, lang=lang)
552
+ text = collapse_whitespace(text)
553
+ return text
554
+
555
+ def basic_cleaners(text):
556
+ """Basic pipeline that lowercases and collapses whitespace without transliteration."""
557
+ text = lowercase(text)
558
+ text = collapse_whitespace(text)
559
+ return text
560
+
561
+ def chinese_transliterate(text):
562
+ return "".join(
563
+ [p[0] for p in pypinyin.pinyin(text, style=pypinyin.Style.TONE3, heteronym=False, neutral_tone_with_five=True)]
564
+ )
565
+
566
+ def japanese_cleaners(text, katsu):
567
+ text = katsu.romaji(text)
568
+ text = lowercase(text)
569
+ return text
570
+
571
+ def korean_transliterate(text, transliter):
572
+ return transliter.translit(text)
573
+
574
+ # Fast Tokenizer Class
575
+
576
+ class XTTSTokenizerFast(PreTrainedTokenizerFast):
577
+ """
578
+ Fast Tokenizer implementation for XTTS model using HuggingFace's PreTrainedTokenizerFast
579
+ """
580
+
581
+ def __init__(
582
+ self,
583
+ vocab_file: str = None,
584
+ tokenizer_object: Optional[Tokenizer] = None,
585
+ unk_token: str = "[UNK]",
586
+ pad_token: str = "[PAD]",
587
+ bos_token: str = "[START]",
588
+ eos_token: str = "[STOP]",
589
+ auto_map: dict = {"AutoTokenizer": ["AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast", None]},
590
+ clean_up_tokenization_spaces: bool = True,
591
+ **kwargs
592
+ ):
593
+ if tokenizer_object is None and vocab_file is not None:
594
+ tokenizer_object = Tokenizer.from_file(vocab_file)
595
+
596
+ if tokenizer_object is not None:
597
+ # Configure the tokenizer
598
+ tokenizer_object.pre_tokenizer = WhitespaceSplit()
599
+ tokenizer_object.post_processor = TemplateProcessing(
600
+ single=f"{bos_token} $A {eos_token}",
601
+ special_tokens=[
602
+ (bos_token, tokenizer_object.token_to_id(bos_token)),
603
+ (eos_token, tokenizer_object.token_to_id(eos_token)),
604
+ ],
605
+ )
606
+
607
+ super().__init__(
608
+ tokenizer_object=tokenizer_object,
609
+ unk_token=unk_token,
610
+ pad_token=pad_token,
611
+ bos_token=bos_token,
612
+ eos_token=eos_token,
613
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
614
+ **kwargs
615
+ )
616
+
617
+ # Character limits per language
618
+ self.char_limits = {
619
+ "en": 250, "de": 253, "fr": 273, "es": 239,
620
+ "it": 213, "pt": 203, "pl": 224, "zh": 82,
621
+ "ar": 166, "cs": 186, "ru": 182, "nl": 251,
622
+ "tr": 226, "ja": 71, "hu": 224, "ko": 95,
623
+ }
624
+
625
+ # Initialize language tools
626
+ self._katsu = None
627
+ self._korean_transliter = Transliter(academic)
628
+
629
+ # Ensure pad_token_id is set
630
+ if self.pad_token_id is None:
631
+ self.pad_token_id = self.tokenizer.token_to_id(self.pad_token)
632
+
633
+ @cached_property
634
+ def katsu(self):
635
+ if self._katsu is None:
636
+ self._katsu = cutlet.Cutlet()
637
+ return self._katsu
638
+
639
+ def preprocess_text(self, text: str, lang: str) -> str:
640
+ """Apply text preprocessing for language"""
641
+ base_lang = lang.split("-")[0] # remove region
642
+ if base_lang in {"ar", "cs", "de", "en", "es", "fr", "hu", "it",
643
+ "nl", "pl", "pt", "ru", "tr", "zh", "ko"}:
644
+ text = multilingual_cleaners(text, base_lang)
645
+ if base_lang == "zh":
646
+ text = chinese_transliterate(text)
647
+ if base_lang == "ko":
648
+ text = korean_transliterate(text, self._korean_transliter)
649
+ elif base_lang == "ja":
650
+ text = japanese_cleaners(text, self.katsu)
651
+ else:
652
+ text = basic_cleaners(text)
653
+ return text
654
+
655
+ def batch_encode_with_split(self, texts: Union[str, List[str]], lang: Union[str, List[str]],
656
+ **kwargs) -> torch.Tensor:
657
+ """
658
+ Split texts into smaller chunks based on language character limits and encode them using HuggingFace fast tokenizer.
659
+ """
660
+ # Convert single inputs to lists
661
+ if isinstance(texts, str):
662
+ texts = [texts]
663
+ if isinstance(lang, str):
664
+ lang = [lang]
665
+ # Ensure lang list matches texts list
666
+ if len(lang) == 1 and len(texts) > 1:
667
+ lang = lang * len(texts)
668
+
669
+ # Check if texts and lang have the same length
670
+ if len(texts) != len(lang):
671
+ raise ValueError(f"Number of texts ({len(texts)}) does not match number of languages ({len(lang)}).")
672
+
673
+ batch_chunks = []
674
+ max_splits = 0
675
+
676
+ # For each text, split into chunks based on character limit
677
+ for text, text_lang in zip(texts, lang):
678
+ # Get language character limit
679
+ base_lang = text_lang.split("-")[0]
680
+ char_limit = self.char_limits.get(base_lang, 250)
681
+
682
+ # Clean and preprocess
683
+ text = self.preprocess_text(text, text_lang)
684
+
685
+ # Split text into sentences/chunks based on language
686
+ chunks = split_sentence(text, base_lang, text_split_length=char_limit)
687
+
688
+ # Format each chunk
689
+ formatted_chunks = []
690
+ for chunk in chunks:
691
+ lang_code = "zh-cn" if base_lang == "zh" else base_lang
692
+ formatted_chunk = f"[{lang_code}]{chunk}"
693
+ formatted_chunk = formatted_chunk.replace(" ", "[SPACE]")
694
+ formatted_chunks.append(formatted_chunk)
695
+
696
+ batch_chunks.append(formatted_chunks)
697
+ max_splits = max(max_splits, len(formatted_chunks))
698
+
699
+ # Flatten all chunks to a single list for batch encoding
700
+ all_chunks = [chunk for chunks in batch_chunks for chunk in chunks]
701
+
702
+ # Ensure the tokenizer is a fast tokenizer
703
+ if not self.is_fast:
704
+ raise ValueError("The tokenizer must be a fast tokenizer.")
705
+
706
+ # Encode all chunks using the fast tokenizer
707
+ encoding: BatchEncoding = self(
708
+ all_chunks,
709
+ add_special_tokens=False,
710
+ padding=True,
711
+ return_tensors='pt',
712
+ **kwargs
713
+ )
714
+
715
+ # The 'input_ids' tensor will have shape [total_chunks, max_sequence_length]
716
+ input_ids = encoding['input_ids'] # Tensor of shape [total_chunks, sequence_length]
717
+
718
+ # Now, we need to organize this tensor back into the desired shape
719
+ # We'll use 'batch_indices' to keep track of which chunks belong to which text
720
+ batch_indices = []
721
+ idx = 0
722
+ for chunks in batch_chunks:
723
+ batch_indices.append((idx, idx + len(chunks)))
724
+ idx += len(chunks)
725
+
726
+ # Determine max sequence length and add space for special tokens
727
+ max_seq_length = input_ids.size(1) + 2 # +2 for BOS and EOS tokens
728
+
729
+ # Prepare the final tensor
730
+ batch_size = len(texts)
731
+ padded_batch = torch.full(
732
+ (batch_size, max_splits, max_seq_length),
733
+ fill_value=self.pad_token_id,
734
+ dtype=torch.long
735
+ )
736
+
737
+ # Populate the final tensor with BOS and EOS tokens
738
+ for i, (start, end) in enumerate(batch_indices):
739
+ chunks_input_ids = input_ids[start:end]
740
+ num_chunks = chunks_input_ids.size(0)
741
+
742
+ for j in range(num_chunks):
743
+ sequence = chunks_input_ids[j]
744
+ # find the length of the sequence
745
+ seq_len = (sequence != self.pad_token_id).sum().item()
746
+
747
+ # insert BOS
748
+ padded_batch[i, j, 0] = self.bos_token_id
749
+ # insert sequence
750
+ padded_batch[i, j, 1:seq_len + 1] = sequence[:seq_len]
751
+ # insert EOS
752
+ padded_batch[i, j, seq_len + 1] = self.eos_token_id
753
+
754
+ return padded_batch
755
+
756
+ def _batch_encode_plus(
757
+ self,
758
+ batch_text_or_text_pairs,
759
+ add_special_tokens: bool = True,
760
+ padding_strategy=PaddingStrategy.DO_NOT_PAD,
761
+ truncation_strategy=TruncationStrategy.DO_NOT_TRUNCATE,
762
+ max_length: Optional[int] = None,
763
+ stride: int = 0,
764
+ is_split_into_words: bool = False,
765
+ pad_to_multiple_of: Optional[int] = None,
766
+ return_tensors: Optional[str] = None,
767
+ return_token_type_ids: Optional[bool] = None,
768
+ return_attention_mask: Optional[bool] = None,
769
+ return_overflowing_tokens: bool = False,
770
+ return_special_tokens_mask: bool = False,
771
+ return_offsets_mapping: bool = False,
772
+ return_length: bool = False,
773
+ verbose: bool = True,
774
+ **kwargs
775
+ ) -> Dict[str, Any]:
776
+ """
777
+ Override batch encoding to handle language-specific preprocessing
778
+ """
779
+ lang = kwargs.pop("lang", ["en"] * len(batch_text_or_text_pairs))
780
+ if isinstance(lang, str):
781
+ lang = [lang]
782
+ # Ensure lang list matches texts list
783
+ if len(lang) == 1 and len(batch_text_or_text_pairs) > 1:
784
+ lang = lang * len(batch_text_or_text_pairs)
785
+
786
+ # Check if batch_text_or_text_pairs and lang have the same length
787
+ if len(batch_text_or_text_pairs) != len(lang):
788
+ raise ValueError(f"Number of texts ({len(batch_text_or_text_pairs)}) does not match number of languages ({len(lang)}).")
789
+
790
+ # Preprocess each text in the batch with its corresponding language
791
+ processed_texts = []
792
+ for text, text_lang in zip(batch_text_or_text_pairs, lang):
793
+ if isinstance(text, str):
794
+ # Check length and preprocess
795
+ #self.check_input_length(text, text_lang)
796
+ processed_text = self.preprocess_text(text, text_lang)
797
+
798
+ # Format text with language tag and spaces
799
+ base_lang = text_lang.split("-")[0]
800
+ lang_code = "zh-cn" if base_lang == "zh" else base_lang
801
+ processed_text = f"[{lang_code}]{processed_text}"
802
+ processed_text = processed_text.replace(" ", "[SPACE]")
803
+
804
+ processed_texts.append(processed_text)
805
+ else:
806
+ processed_texts.append(text)
807
+
808
+ # Call the parent class's encoding method with processed texts
809
+ return super()._batch_encode_plus(
810
+ processed_texts,
811
+ add_special_tokens=add_special_tokens,
812
+ padding_strategy=padding_strategy,
813
+ truncation_strategy=truncation_strategy,
814
+ max_length=max_length,
815
+ stride=stride,
816
+ is_split_into_words=is_split_into_words,
817
+ pad_to_multiple_of=pad_to_multiple_of,
818
+ return_tensors=return_tensors,
819
+ return_token_type_ids=return_token_type_ids,
820
+ return_attention_mask=return_attention_mask,
821
+ return_overflowing_tokens=return_overflowing_tokens,
822
+ return_special_tokens_mask=return_special_tokens_mask,
823
+ return_offsets_mapping=return_offsets_mapping,
824
+ return_length=return_length,
825
+ verbose=verbose,
826
+ **kwargs
827
+ )
828
+
829
+
830
+ def __call__(
831
+ self,
832
+ text: Union[str, List[str]],
833
+ lang: Union[str, List[str]] = "en",
834
+ add_special_tokens: bool = True,
835
+ padding: Union[bool, str, PaddingStrategy] = False,
836
+ truncation: Union[bool, str, TruncationStrategy] = False,
837
+ max_length: Optional[int] = None,
838
+ stride: int = 0,
839
+ return_tensors: Optional[str] = None,
840
+ return_token_type_ids: Optional[bool] = None,
841
+ return_attention_mask: Optional[bool] = True,
842
+ **kwargs
843
+ ):
844
+ """
845
+ Main tokenization method
846
+ """
847
+ # Convert single string to list for batch processing
848
+ if isinstance(text, str):
849
+ text = [text]
850
+ if isinstance(lang, str):
851
+ lang = [lang]
852
+ # Ensure lang list matches texts list
853
+ if len(lang) == 1 and len(text) > 1:
854
+ lang = lang * len(text)
855
+
856
+ # Ensure text and lang lists have same length
857
+ if len(text) != len(lang):
858
+ raise ValueError(f"Number of texts ({len(text)}) does not match number of languages ({len(lang)}).")
859
+
860
+ # Convert padding strategy
861
+ if isinstance(padding, bool):
862
+ padding_strategy = PaddingStrategy.LONGEST if padding else PaddingStrategy.DO_NOT_PAD
863
+ else:
864
+ padding_strategy = PaddingStrategy(padding)
865
+
866
+ # Convert truncation strategy
867
+ if isinstance(truncation, bool):
868
+ truncation_strategy = TruncationStrategy.LONGEST_FIRST if truncation else TruncationStrategy.DO_NOT_TRUNCATE
869
+ else:
870
+ truncation_strategy = TruncationStrategy(truncation)
871
+
872
+ # Use the batch encoding method
873
+ encoded = self._batch_encode_plus(
874
+ text,
875
+ add_special_tokens=add_special_tokens,
876
+ padding_strategy=padding_strategy,
877
+ truncation_strategy=truncation_strategy,
878
+ max_length=max_length,
879
+ stride=stride,
880
+ return_tensors=return_tensors,
881
+ return_token_type_ids=return_token_type_ids,
882
+ return_attention_mask=return_attention_mask,
883
+ lang=lang,
884
+ **kwargs
885
+ )
886
+
887
+ return encoded
xttsv2_gpt2/tokenizer_config.json ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[STOP]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[SPACE]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "259": {
28
+ "content": "[en]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "260": {
36
+ "content": "[de]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "261": {
44
+ "content": "[START]",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "262": {
52
+ "content": "[fr]",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "267": {
60
+ "content": "[ru]",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "284": {
68
+ "content": "[es]",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "285": {
76
+ "content": "[it]",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "286": {
84
+ "content": "[pt]",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "293": {
92
+ "content": "[cs]",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "294": {
100
+ "content": "[pl]",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "295": {
108
+ "content": "[tr]",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "297": {
116
+ "content": "[nl]",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "5022": {
124
+ "content": "[ar]",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "5023": {
132
+ "content": "[zh-cn]",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "5412": {
140
+ "content": "[ja]",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "5753": {
148
+ "content": "[hu]",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "6152": {
156
+ "content": "[ko]",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "6680": {
164
+ "content": "[hi]",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ },
171
+ "6681": {
172
+ "content": "[PAD]",
173
+ "lstrip": false,
174
+ "normalized": false,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": true
178
+ }
179
+ },
180
+ "auto_map": {"AutoTokenizer": ["AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast", null]},
181
+ "bos_token": "[START]",
182
+ "clean_up_tokenization_spaces": true,
183
+ "eos_token": "[STOP]",
184
+ "max_length": null,
185
+ "model_max_length": 1000000000000000019884624838656,
186
+ "pad_to_multiple_of": null,
187
+ "pad_token": "[PAD]",
188
+ "pad_token_type_id": 0,
189
+ "padding_side": "right",
190
+ "tokenizer_class": "XTTSTokenizerFast",
191
+ "unk_token": "[UNK]"
192
+ }
xttsv2_gpt2/xtts2_gpt_modeling.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import math
3
+ import random
4
+ import uuid
5
+ from array import array
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+ from typing import List, Optional, Union, Iterable, Tuple, Mapping, Dict
11
+
12
+ from torch import Tensor
13
+ from transformers import PretrainedConfig, GPT2Config
14
+ from vllm.attention import AttentionMetadata
15
+ from vllm.config import CacheConfig, MultiModalConfig
16
+ from vllm.distributed import get_pp_group
17
+ from vllm.inputs import InputContext, INPUT_REGISTRY, DecoderOnlyInputs, token_inputs
18
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
19
+ from vllm.model_executor.layers.quantization import QuantizationConfig
20
+ from vllm.model_executor.layers.sampler import Sampler, SamplerOutput
21
+ from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding, ParallelLMHead
22
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
23
+ from vllm.model_executor.models.gpt2 import GPT2Block
24
+ from vllm.model_executor.models.utils import make_layers, make_empty_intermediate_tensors_factory
25
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
26
+ from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalInputs
27
+ from vllm.sequence import IntermediateTensors, SequenceData, VLLM_TOKEN_ID_ARRAY_TYPE
28
+ from vllm.model_executor.models.interfaces import SupportsMultiModal, SupportsPP
29
+
30
+
31
+
32
+ class LearnedPositionEmbeddings(nn.Module):
33
+ def __init__(self, seq_len, model_dim, init=0.02, relative=False, supports_pp=False):
34
+ super().__init__()
35
+ # nn.Embedding
36
+ self.emb = VocabParallelEmbedding(seq_len, model_dim) if supports_pp else nn.Embedding(seq_len, model_dim)
37
+ # Initializing this way is standard for GPT-2
38
+ self.emb.weight.data.normal_(mean=0.0, std=init)
39
+ self.relative = relative
40
+ self.seq_len = seq_len
41
+
42
+ def forward(self, x):
43
+ sl = x.shape[1]
44
+ if self.relative:
45
+ start = random.randint(sl, self.seq_len) - sl
46
+ return self.emb(torch.arange(start, start + sl, device=x.device))
47
+ else:
48
+ return self.emb(torch.arange(0, sl, device=x.device))
49
+
50
+ def get_fixed_embedding(self, ind: torch.Tensor, dev: torch.device) -> torch.Tensor:
51
+ """Get position embeddings with batch support.
52
+
53
+ Handles both single and batched inputs, returning embeddings that can be
54
+ directly added to input embeddings of the same shape.
55
+
56
+ Args:
57
+ ind: Position indices tensor. Can be single or batched
58
+ Shape: [..., seq_len] or [seq_len]
59
+ dev: Target device for the embeddings
60
+
61
+ Returns:
62
+ Position embeddings tensor matching input shape plus embedding dimension
63
+ Shape: [batch_size, seq_len, model_dim] or [1, 1, model_dim]
64
+
65
+ Example:
66
+ >>> pos_emb = LearnedPositionEmbeddings(100, 64)
67
+ >>> # Batched input
68
+ >>> batch_indices = torch.zeros((3, 5)) # batch_size=3, seq_len=5
69
+ >>> embeddings = pos_emb.get_fixed_embedding(batch_indices, 'cuda')
70
+ >>> embeddings.shape # Returns: [3, 5, 64]
71
+ """
72
+ if ind.shape[0] > 1:
73
+ pos_embeddings = []
74
+ for index in ind:
75
+ # Create embeddings for each position in the sequence
76
+ pos_embeddings.append(self.emb(index))
77
+
78
+ # Shape: [1, seq_len, model_dim] -> [batch_size, seq_len, model_dim]
79
+ return torch.stack(pos_embeddings, dim=0)
80
+ else:
81
+ # Handle single input
82
+ # Shape: [1, 1, model_dim]
83
+ return self.emb(torch.tensor([ind], device=dev)).unsqueeze(0)
84
+
85
+
86
+ def get_xtts_max_audio_tokens(ctx: InputContext) -> int:
87
+ """Calculate maximum audio tokens based on text context and audio duration."""
88
+ # Based on GPT config and XTTSv2 settings
89
+ return 608
90
+
91
+
92
+ def dummy_seq_data_for_xtts(
93
+ ctx: InputContext,
94
+ seq_len: int,
95
+ audio_count: int,
96
+ ) -> SequenceData:
97
+ """Create dummy sequence data for XTTS profiling."""
98
+ # Calculate audio token space needed
99
+ max_audio_token_conditioning = ctx.model_config.hf_config.max_prompt_tokens # in xtts prompt = voice conditioning
100
+ audio_placeholder = array(
101
+ VLLM_TOKEN_ID_ARRAY_TYPE,
102
+ [1]
103
+ ) * max_audio_token_conditioning
104
+
105
+ # Add separator between chunks
106
+ audio_token_ids = (audio_placeholder + array(VLLM_TOKEN_ID_ARRAY_TYPE, [1])) * audio_count
107
+
108
+ # Fill remaining sequence with padding
109
+ other_token_ids = array(VLLM_TOKEN_ID_ARRAY_TYPE, [1]) * (seq_len - len(audio_token_ids))
110
+ # not -1 since we add the start audio token
111
+
112
+ return SequenceData(
113
+ audio_token_ids +
114
+ other_token_ids
115
+ )
116
+
117
+ def dummy_conditioning_for_xtts(
118
+ ctx: InputContext,
119
+ seq_len: int,
120
+ audio_count: int,
121
+ ) -> dict:
122
+ """Create dummy conditioning data for XTTS."""
123
+ return {
124
+ "audio": {
125
+ "embeds":[
126
+ torch.zeros(
127
+ (seq_len, ctx.model_config.hf_config.hidden_size),
128
+ dtype=ctx.model_config.dtype) for _ in range(audio_count)
129
+ ],
130
+ "is_logits_only_mode": False,
131
+ }
132
+ }
133
+
134
+
135
+ def dummy_data_for_xtts(
136
+ ctx: InputContext,
137
+ seq_len: int,
138
+ mm_counts: Mapping[str, int],
139
+ ) -> Tuple[SequenceData, dict]:
140
+ """Create complete dummy data for XTTS profiling."""
141
+ audio_count = mm_counts["audio"]
142
+ seq_data = dummy_seq_data_for_xtts(ctx, seq_len, audio_count)
143
+ cond_data = dummy_conditioning_for_xtts(ctx, seq_len, audio_count)
144
+ return seq_data, cond_data
145
+
146
+
147
+ def input_mapper_for_xtts(ctx: InputContext, data: Union[Dict, List[Tensor]]) -> MultiModalInputs:
148
+ """Map input data to XTTS format."""
149
+
150
+ assert isinstance(data, dict), "XTTS MultiModal input data must be a dictionary with keys: 'embeds', 'is_logits_only_mode'"
151
+
152
+ embeds = data.get("embeds")
153
+ is_logits_only_mode = data.get("is_logits_only_mode", False)
154
+
155
+ # Each item should be a torch tensor
156
+ for audio_input in embeds:
157
+ if not isinstance(audio_input, Tensor):
158
+ raise NotImplementedError(f"Unsupported data type: {type(audio_input)}")
159
+
160
+ return MultiModalInputs({"cond_latents": embeds,
161
+ "is_logits_only_mode": is_logits_only_mode,
162
+ })
163
+
164
+
165
+ def input_processor_for_xtts2_gpt(ctx: InputContext, inputs: DecoderOnlyInputs):
166
+ """
167
+ We'll accomodate for the extra contditioning token and for the start audio token,
168
+ we actually insert a -1 repeated for the differecne in length between the conditioning and the tokenized text
169
+ and then we add 1 for the start audio token
170
+ Args:
171
+ ctx:
172
+ inputs:
173
+
174
+ Returns:
175
+
176
+ """
177
+ multi_modal_data = inputs.get("multi_modal_data")
178
+ audio_dict = multi_modal_data['audio']
179
+ audio = audio_dict.get('embeds')
180
+
181
+ is_last_decoding_pass = audio_dict.get("is_logits_only_mode", False)
182
+
183
+ prompt_token_ids = inputs.get("prompt_token_ids")
184
+
185
+ if not is_last_decoding_pass:
186
+ # we fill everything with 0 since we don't actually needs text token ids, it would mess up in the sampling step
187
+ new_token_ids = [1] * (audio.shape[0] + 1) # +1 for the start audio generation token
188
+ else:
189
+ new_token_ids = ([1] * audio.shape[0]) + prompt_token_ids
190
+ # the encoding had already been done externally to reuse the embeddings for later use but we
191
+ # account for the new token that will be added before generation
192
+ new_prompt = None
193
+ return token_inputs(prompt_token_ids=new_token_ids,
194
+ prompt=new_prompt,
195
+ multi_modal_data=multi_modal_data)
196
+
197
+
198
+ @MULTIMODAL_REGISTRY.register_input_mapper("audio", input_mapper_for_xtts)
199
+ @MULTIMODAL_REGISTRY.register_max_multimodal_tokens("audio", get_xtts_max_audio_tokens)
200
+ @INPUT_REGISTRY.register_dummy_data(dummy_data_for_xtts)
201
+ @INPUT_REGISTRY.register_input_processor(input_processor_for_xtts2_gpt)
202
+ class XttsGPT(nn.Module, SupportsMultiModal, SupportsPP):
203
+ def __init__(
204
+ self,
205
+ config: PretrainedConfig,
206
+ multimodal_config: MultiModalConfig,
207
+ cache_config: Optional[CacheConfig] = None,
208
+ quant_config: Optional[QuantizationConfig] = None,
209
+ ):
210
+ super().__init__()
211
+ self.config = config
212
+ self.quant_config = quant_config
213
+
214
+ # Core GPT components
215
+ self.gpt = GPT2Model(
216
+ config,
217
+ cache_config,
218
+ quant_config,
219
+ prefix="gpt"
220
+ )
221
+ self.final_norm = nn.LayerNorm(config.hidden_size, bias=True, eps=config.layer_norm_epsilon)
222
+ # Output head for mel tokens
223
+ self.mel_head = ParallelLMHead(
224
+ config.num_audio_tokens,
225
+ config.hidden_size,
226
+ bias=True,
227
+ quant_config=quant_config,
228
+ prefix="mel_head"
229
+ )
230
+ self.audio_start_generation_token = config.start_audio_token
231
+
232
+ # Initialize logits processor and sampler
233
+ logit_scale = getattr(config, "logit_scale", 1.0)
234
+ self.logits_processor = LogitsProcessor(config.num_audio_tokens,
235
+ config.num_audio_tokens,
236
+ logit_scale)
237
+ self.sampler = Sampler()
238
+
239
+ @staticmethod
240
+ def check_is_logits_only_mode(is_logits_only_mode):
241
+
242
+ # First check if it's a boolean
243
+ if isinstance(is_logits_only_mode, bool):
244
+ return is_logits_only_mode
245
+
246
+ # Then check if it's a tensor
247
+ if torch.is_tensor(is_logits_only_mode):
248
+ # if it's a scalar tensor, return the value
249
+ if is_logits_only_mode.numel() == 1:
250
+ return bool(is_logits_only_mode.item())
251
+ # for non-scalar tensors, check if all elements are the same
252
+ return is_logits_only_mode.any()
253
+
254
+ # Fallback
255
+ return bool(is_logits_only_mode)
256
+
257
+ def _calculate_start_token_indices(self, cond_latents: List[torch.Tensor]) -> List[int]:
258
+ """Calcola gli indici dove inserire i token di start.
259
+
260
+ Args:
261
+ cond_latents: Lista di tensori di condizionamento
262
+
263
+ Returns:
264
+ Lista di indici dove inserire i token di start
265
+ """
266
+ indices = []
267
+ current_idx = 0
268
+
269
+ for cond_latent in cond_latents:
270
+ # Aggiungi la lunghezza del segmento corrente
271
+ current_idx += cond_latent.shape[0]
272
+ # Aggiungi l'indice per il token di start dopo questo segmento
273
+ indices.append(current_idx)
274
+ # Incrementa per il token di start che verrà aggiunto
275
+ current_idx += 1
276
+
277
+ return indices
278
+
279
+ # noinspection PyMethodOverriding
280
+ def forward(
281
+ self,
282
+ input_ids: torch.Tensor,
283
+ positions: torch.Tensor,
284
+ kv_caches: List[torch.Tensor],
285
+ attn_metadata: AttentionMetadata,
286
+ intermediate_tensors: Optional["IntermediateTensors"] = None,
287
+ cond_latents: Optional[torch.Tensor] = None,
288
+ is_logits_only_mode: bool = False,
289
+ **kwargs,
290
+ ) -> Union[torch.Tensor, "IntermediateTensors"]:
291
+ """Forward pass following VLLM pattern."""
292
+ # it is not the first iter either if the cond latents are emtpy or if the kv_caches are not empty
293
+ is_first_iteration = (input_ids==1).all()
294
+
295
+ #assert len(input_ids) == 1 or (cond_latents is not None and not is_first_iteration), "Conditioning data (voice conditioning+text_embeddings) is required for XTTS"
296
+
297
+ is_logits_only_mode = self.check_is_logits_only_mode(is_logits_only_mode)
298
+
299
+ if is_first_iteration:
300
+ # we add it to enable the model to start the generation
301
+ input_ids[-1] = self.audio_start_generation_token
302
+
303
+ hidden_states = self.gpt(
304
+ input_ids=input_ids,
305
+ position_ids=positions,
306
+ kv_caches=kv_caches,
307
+ attn_metadata=attn_metadata,
308
+ intermediate_tensors=intermediate_tensors,
309
+ # this is the conditioning input ( voice conditioning + text_embeds )
310
+ input_embeds=cond_latents,
311
+ is_first_iteration=is_first_iteration,
312
+ is_logits_only_mode=is_logits_only_mode
313
+ )
314
+
315
+ return hidden_states
316
+
317
+ def compute_logits(
318
+ self,
319
+ hidden_states: torch.Tensor,
320
+ sampling_metadata: SamplingMetadata,
321
+ ) -> Optional[torch.Tensor]:
322
+
323
+ # normalize the hidden states
324
+ hidden_states = self.final_norm(hidden_states)
325
+
326
+ # Check if we need to collect hidden states
327
+ sampling_params = sampling_metadata.seq_groups[0].sampling_params
328
+ if hasattr(sampling_params, 'hidden_state_collector'):
329
+ # Call the collector directly with the hidden states
330
+ sampling_params.hidden_state_collector(hidden_states, None) # The request_id is already bound
331
+
332
+ # Compute logits using the mel_head
333
+ logits = self.logits_processor(self.mel_head, hidden_states, sampling_metadata)
334
+ return logits
335
+
336
+ def sample(
337
+ self,
338
+ logits: torch.Tensor,
339
+ sampling_metadata: SamplingMetadata,
340
+ ) -> Optional[SamplerOutput]:
341
+ next_tokens = self.sampler(logits, sampling_metadata)
342
+ return next_tokens
343
+
344
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
345
+ """Load weights following VLLM pattern."""
346
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
347
+ loaded_names = set()
348
+ for name, loaded_weight in weights:
349
+ if name not in params_dict:
350
+ #print(f"Skipping loading of {name} bc it is not found") # used to check if all weights were loaded
351
+ continue
352
+
353
+ param = params_dict[name]
354
+ if "c_attn" in name or "c_proj" in name or "c_fc" in name:
355
+ if name.endswith(".weight"):
356
+ loaded_weight = loaded_weight.t()
357
+
358
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
359
+ weight_loader(param, loaded_weight)
360
+ loaded_names.add(name)
361
+ # used to check if all weights were loaded
362
+ assert set(params_dict.keys()) - loaded_names == set(), \
363
+ (f"Missing weights: {set(params_dict.keys()) - loaded_names}, "
364
+ f"this probably means you are using an incompatible model ")
365
+
366
+ class GPT2Model(nn.Module):
367
+
368
+ def __init__(
369
+ self,
370
+ config: GPT2Config,
371
+ cache_config: Optional[CacheConfig] = None,
372
+ quant_config: Optional[QuantizationConfig] = None,
373
+ prefix: str = "",
374
+ ):
375
+ super().__init__()
376
+ self.config = config
377
+ assert not config.add_cross_attention
378
+ assert not config.scale_attn_by_inverse_layer_idx
379
+ assert not config.reorder_and_upcast_attn
380
+ self.embed_dim = config.hidden_size
381
+ self.wte = VocabParallelEmbedding(config.num_audio_tokens, self.embed_dim)
382
+ self.wpe = (
383
+ LearnedPositionEmbeddings(config.max_audio_tokens + 3, config.decoder_input_dim)
384
+ if config.max_audio_tokens != -1
385
+ else functools.partial(config.null_position_embeddings, dim=config.decoder_input_dim)
386
+ )
387
+ self.start_layer, self.end_layer, self.h = make_layers(
388
+ config.num_hidden_layers,
389
+ lambda prefix: GPT2Block(
390
+ config, cache_config, quant_config, prefix=prefix),
391
+ prefix=f"{prefix}.h")
392
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
393
+ self.make_empty_intermediate_tensors = (
394
+ make_empty_intermediate_tensors_factory(["hidden_states"],
395
+ config.hidden_size))
396
+
397
+
398
+ def forward(
399
+ self,
400
+ input_ids: torch.Tensor,
401
+ position_ids: torch.Tensor,
402
+ kv_caches: List[torch.Tensor],
403
+ attn_metadata: AttentionMetadata,
404
+ intermediate_tensors: Optional[IntermediateTensors],
405
+ # we pass this so that we can concatenate the text and conditioning input
406
+ input_embeds: Optional[torch.Tensor] = None,
407
+ is_first_iteration: bool = False,
408
+ is_logits_only_mode: bool = False,
409
+ ) -> Union[torch.Tensor, IntermediateTensors]:
410
+
411
+ if get_pp_group().is_first_rank:
412
+ # if we are not doing the final conversion from token to latent and it is first pass(prefill)
413
+ if is_first_iteration and not is_logits_only_mode:
414
+ input_ids = input_ids[-1].reshape(1, 1)
415
+ elif is_logits_only_mode:
416
+ # we remove the contidioning input and keep just the audio token
417
+ if isinstance(input_embeds, list):
418
+ starting_idx = []
419
+ for input_embed in input_embeds:
420
+ starting_idx.append(input_embed.shape[0])
421
+ ending_ids = attn_metadata.seq_lens # list
422
+
423
+ # First sequence: from starting_idx[0] to ending_ids[0]
424
+ cumulative_starts = [starting_idx[0]] # First starts at its own index
425
+ cumulative_ends = [ending_ids[0]] # First ends at its ending_id
426
+
427
+ # For subsequent sequences:
428
+ # Start = previous_end + current_start
429
+ # End = previous_end + current_end
430
+ for i in range(1, len(starting_idx)):
431
+ next_start = cumulative_ends[i - 1] + starting_idx[i]
432
+ next_end = cumulative_ends[i - 1] + ending_ids[i]
433
+ cumulative_starts.append(next_start)
434
+ cumulative_ends.append(next_end)
435
+
436
+ ids_for_unpacking = [end-start for start, end in zip(cumulative_starts, cumulative_ends)]
437
+
438
+ input_ids = torch.cat([
439
+ input_ids[start:end].reshape(1, -1)
440
+ for start, end in zip(cumulative_starts, cumulative_ends)
441
+ ], dim=-1)
442
+ position_ids = torch.cat([
443
+ position_ids[start:end].reshape(1, -1)
444
+ for start, end in zip(cumulative_starts, cumulative_ends)
445
+ ], dim= -1).squeeze(0)
446
+ else:
447
+ input_ids = input_ids[input_embeds.shape[1]:].reshape(1, -1)
448
+ position_ids = position_ids[input_embeds.shape[1]:]#.reshape(1, -1)
449
+ else:
450
+ input_ids = input_ids
451
+
452
+ audio_inputs_embeds = self.wte(input_ids).squeeze(0)
453
+
454
+ # weird but they to it like this in the xtts2 model
455
+ position_embeds = self.wpe.get_fixed_embedding(
456
+ position_ids, input_ids.device
457
+ ) if not is_first_iteration \
458
+ else self.wpe(audio_inputs_embeds.reshape(-1, 1)) # we need to reshape to 2D tensor or useless?
459
+
460
+ hidden_states = audio_inputs_embeds + position_embeds
461
+
462
+ if isinstance(input_embeds, list) and is_logits_only_mode:
463
+ hidden_states = list(hidden_states.split(ids_for_unpacking, dim=0))
464
+
465
+ if is_first_iteration or is_logits_only_mode:
466
+ # We concat the text and audio conditioning input in the sequence dimension
467
+ if isinstance(input_embeds, list):
468
+ input_embeds = [input_embed.view(-1, input_embed.shape[-1]) for input_embed in input_embeds]
469
+ else:
470
+ input_embeds = input_embeds.view(-1, input_embeds.shape[-1]) # we ensure we have a 2D tensor
471
+
472
+ if not isinstance(input_embeds, list) and input_embeds.shape[0] == attn_metadata.num_prefill_tokens:
473
+ # this is during profiling, wee need to remove the last token
474
+ # the attn_metadata.num_prefill_tokens(prompt len) should be == to input_embeds.shape[0] - 1
475
+ # to account for the start audio gen embedding that will be cat to the text embeddings
476
+ input_embeds = input_embeds[:-1]
477
+
478
+ if is_first_iteration or is_logits_only_mode:
479
+ # we concatenate the conditioning input to the text conditioning input
480
+ if isinstance(input_embeds, list):
481
+ hidden_states = torch.cat([
482
+ tensor for pair in zip(input_embeds, [hidden_states] * len(input_embeds)
483
+ if not isinstance(hidden_states, list) else hidden_states)
484
+ for tensor in pair
485
+ ], dim=0)
486
+ else:
487
+ hidden_states = torch.cat([input_embeds, hidden_states], dim=0)
488
+
489
+ #flatten the hidden state
490
+ hidden_states = hidden_states.view(-1, self.embed_dim)
491
+ else:
492
+ assert intermediate_tensors is not None
493
+ hidden_states = intermediate_tensors["hidden_states"]
494
+
495
+ for i in range(self.start_layer, self.end_layer):
496
+ layer = self.h[i]
497
+ hidden_states = layer(hidden_states,
498
+ kv_caches[i - self.start_layer],
499
+ attn_metadata)
500
+
501
+ if not get_pp_group().is_last_rank:
502
+ return IntermediateTensors({"hidden_states": hidden_states})
503
+
504
+ hidden_states = self.ln_f(hidden_states)
505
+ return hidden_states