jimmyvu commited on
Commit
5bbc9a7
·
verified ·
1 Parent(s): 95224b5

Add model files

Browse files
Files changed (6) hide show
  1. README.md +160 -3
  2. config.json +108 -0
  3. tokenizer.py +952 -0
  4. xtts-v2.safetensors +3 -0
  5. xtts2_config.py +228 -0
  6. xtts2_modeling.py +1070 -0
README.md CHANGED
@@ -1,3 +1,160 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - coqui/XTTS-v2
5
+ ---
6
+ # Auralis 🌌
7
+
8
+ ## Model Details 🛠️
9
+
10
+ **Model Name:** Auralis
11
+
12
+ **Model Architecture:** Based on [Coqui XTTS-v2](https://huggingface.co/coqui/XTTS-v2)
13
+
14
+ **License:**
15
+ - license: Apache 2.0
16
+ - base_model: XTTS-v2 Components [Coqui AI License](https://coqui.ai/cpml)
17
+
18
+ **Language Support:** English, Spanish, French, German, Italian, Portuguese, Polish, Turkish, Russian, Dutch, Czech, Arabic, Chinese (Simplified), Hungarian, Korean, Japanese, Hindi
19
+
20
+ **Developed by:** [AstraMind.ai](https://www.astramind.ai)
21
+
22
+ **GitHub:** [AstraMind AI](https://github.com/astramind-ai/Auralis/tree/main)
23
+
24
+ **Primary Use Case:** Text-to-Speech (TTS) generation for real-world applications, including books, dialogues, and multilingual tasks.
25
+
26
+ ---
27
+
28
+ ## Model Description 🚀
29
+
30
+ Auralis transforms text into natural, high-quality speech with exceptional speed and scalability. It is powered by [Coqui XTTS-v2](https://huggingface.co/coqui/XTTS-v2) and optimized for both consumer-grade and high-performance GPUs. Auralis is designed to meet real-world needs like long-text processing, voice cloning, and concurrent request handling.
31
+
32
+ ### Key Features:
33
+ - **Warp-Speed Processing:** Generate speech for an entire novel (e.g., Harry Potter) in ~10 minutes.
34
+ - **Hardware Friendly:** Requires <10GB VRAM on a single NVIDIA RTX 3090.
35
+ - **Scalable:** Handles multiple requests simultaneously.
36
+ - **Streaming:** Seamlessly processes long texts in a streaming format.
37
+ - **Custom Voices:** Enables voice cloning from short reference audio.
38
+
39
+ ---
40
+
41
+ ## Quick Start ⭐
42
+
43
+ ```python
44
+ from auralis import TTS, TTSRequest
45
+
46
+ # Initialize the model
47
+ tts = TTS().from_pretrained("AstraMindAI/xtts2-gpt")
48
+
49
+ # Create a TTS request
50
+ request = TTSRequest(
51
+ text="Hello Earth! This is Auralis speaking.",
52
+ speaker_files=["reference.wav"]
53
+ )
54
+
55
+ # Generate speech
56
+ output = tts.generate_speech(request)
57
+ output.save("output.wav")
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Ebook Generation 📚
63
+
64
+ Auralis converting ebooks into audio formats at lightning speed. For Python script, check out [ebook_audio_generator.py](https://github.com/astramind-ai/Auralis/blob/main/examples/vocalize_a_ebook.py).
65
+
66
+ ```python
67
+ def process_book(chapter_file: str, speaker_file: str):
68
+ # Read chapter
69
+ with open(chapter_file, 'r') as f:
70
+ chapter = f.read()
71
+
72
+ # You can pass the whole book, auralis will take care of splitting
73
+
74
+ request = TTSRequest(
75
+ text=chapter,
76
+ speaker_files=[speaker_file],
77
+ audio_config=AudioPreprocessingConfig(
78
+ enhance_speech=True,
79
+ normalize=True
80
+ )
81
+ )
82
+
83
+ output = tts.generate_speech(request)
84
+
85
+ output.play()
86
+ output.save("chapter_output.wav")
87
+
88
+ # Example usage
89
+ process_book("chapter1.txt", "reference_voice.wav")
90
+ ```
91
+
92
+ ---
93
+
94
+ ## Intended Use 🌟
95
+
96
+ Auralis is designed for:
97
+ - **Content Creators:** Generate audiobooks, podcasts, or voiceovers.
98
+ - **Developers:** Integrate TTS into applications via a simple Python API.
99
+ - **Accessibility**: Providing audio versions of digital content for people with visual or reading difficulties.
100
+ - **Multilingual Scenarios:** Convert text to speech in multiple supported languages.
101
+
102
+ ---
103
+
104
+ ## Performance 📊
105
+
106
+ **Benchmarks on NVIDIA RTX 3090:**
107
+ - Short phrases (<100 characters): ~1 second
108
+ - Medium texts (<1,000 characters): ~5-10 seconds
109
+ - Full books (~100,000 characters): ~10 minutes
110
+
111
+ **Memory Usage:**
112
+ - Base VRAM: ~4GB
113
+ - Peak VRAM: ~10GB
114
+
115
+ ---
116
+
117
+ ## Model Features 🛸
118
+
119
+ 1. **Speed & Efficiency:**
120
+ - Smart batching for rapid processing of long texts.
121
+ - Memory-optimized for consumer GPUs.
122
+
123
+ 2. **Easy Integration:**
124
+ - Python API with support for synchronous and asynchronous workflows.
125
+ - Streaming mode for continuous playback during generation.
126
+
127
+ 3. **Audio Quality Enhancements:**
128
+ - Background noise reduction.
129
+ - Voice clarity and volume normalization.
130
+ - Customizable audio preprocessing.
131
+
132
+ 4. **Multilingual Support:**
133
+ - Automatic language detection.
134
+ - High-quality speech in 15+ languages.
135
+
136
+ 5. **Customization:**
137
+ - Voice cloning using short reference clips.
138
+ - Adjustable parameters for tone, pacing, and language.
139
+
140
+ ---
141
+
142
+ ## Limitations & Ethical Considerations ⚠️
143
+
144
+ - **Voice Cloning Risks:** Auralis supports voice cloning, which may raise ethical concerns about misuse. Use responsibly and ensure proper consent.
145
+ - **Accent Limitations:** While robust for many languages, accents and intonations may vary based on the input.
146
+
147
+ ---
148
+
149
+ ## Citation 📜
150
+
151
+ If you use Auralis in your research or projects, please cite:
152
+
153
+ ```bibtex
154
+ @misc{auralis2024,
155
+ author = {AstraMind AI},
156
+ title = {Auralis: High-Performance Text-to-Speech Engine},
157
+ year = {2024},
158
+ url = {https://huggingface.co/AstraMindAI/auralis}
159
+ }
160
+ ```
config.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "xtts",
3
+ "architectures": [
4
+ "XttsGPT"
5
+ ],
6
+ "audio_config": {
7
+ "fmax": 8000,
8
+ "fmin": 0,
9
+ "hop_length": 256,
10
+ "mel_channels": 80,
11
+ "mel_norms_file": null,
12
+ "n_fft": 1024,
13
+ "output_sample_rate": 24000,
14
+ "power": 1.0,
15
+ "sample_rate": 22050,
16
+ "win_length": 1024
17
+ },
18
+ "d_vector_dim": 512,
19
+ "decoder_input_dim": 1024,
20
+ "num_chars": 255,
21
+ "duration_const": 102400,
22
+ "output_hop_length": 256,
23
+ "input_sample_rate": 22050,
24
+ "output_sample_rate": 24000,
25
+ "gpt": {
26
+ "model_type": "xtts_gpt"
27
+ },
28
+ "gpt_config": {
29
+ "model_type": "xtts_gpt",
30
+ "architectures": [
31
+ "XttsGPT"
32
+ ],
33
+ "vocab_size": 7544,
34
+ "hidden_size": 1024,
35
+ "num_hidden_layers": 30,
36
+ "num_attention_heads": 16,
37
+ "n_inner": 4096,
38
+ "number_text_tokens": 7544,
39
+ "num_audio_tokens": 1026,
40
+ "max_audio_tokens": 605,
41
+ "start_audio_token": 1024,
42
+ "stop_audio_token": 1025,
43
+ "max_text_tokens": 402,
44
+ "max_prompt_tokens": 70,
45
+ "activation_function": "gelu_new",
46
+ "attn_pdrop": 0.1,
47
+ "layer_norm_epsilon": 1e-05,
48
+ "initializer_range": 0.02,
49
+ "use_masking_gt_prompt_approach": true,
50
+ "use_perceiver_resampler": true,
51
+ "kv_cache": true,
52
+ "enable_redaction": false,
53
+ "reorder_and_upcast_attn": false,
54
+ "scale_attn_by_inverse_layer_idx": false,
55
+ "auto_map": {
56
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
57
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
58
+ "AutoTokenizer": "AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast"
59
+ },
60
+ "languages": [
61
+ "en",
62
+ "es",
63
+ "fr",
64
+ "de",
65
+ "it",
66
+ "pt",
67
+ "pl",
68
+ "tr",
69
+ "ru",
70
+ "nl",
71
+ "cs",
72
+ "ar",
73
+ "zh-cn",
74
+ "hu",
75
+ "ko",
76
+ "ja",
77
+ "vi"
78
+ ]
79
+ },
80
+ "gpt_code_stride_len": 1024,
81
+ "cond_d_vector_in_each_upsampling_layer": true,
82
+ "auto_map": {
83
+ "AutoConfig": "AstraMindAI/xtts2--xtts2_config.XTTSConfig",
84
+ "AutoModelForCausalLM": "AstraMindAI/xtts2--xtts2_modeling.Xtts",
85
+ "AutoTokenizer": "AstraMindAI/xtts2--tokenizer.XTTSTokenizerFast"
86
+ },
87
+ "languages": [
88
+ "en",
89
+ "es",
90
+ "fr",
91
+ "de",
92
+ "it",
93
+ "pt",
94
+ "pl",
95
+ "tr",
96
+ "ru",
97
+ "nl",
98
+ "cs",
99
+ "ar",
100
+ "zh-cn",
101
+ "hu",
102
+ "ko",
103
+ "ja",
104
+ "vi"
105
+ ],
106
+ "tokenizer_file": "",
107
+ "transformers_version": "4.46.0"
108
+ }
tokenizer.py ADDED
@@ -0,0 +1,952 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import List, Optional, Union, Dict, Any
3
+ from functools import cached_property
4
+
5
+ import pypinyin
6
+ import torch
7
+ from hangul_romanize import Transliter
8
+ from hangul_romanize.rule import academic
9
+ from num2words import num2words
10
+ from spacy.lang.ar import Arabic
11
+ from spacy.lang.en import English
12
+ from spacy.lang.es import Spanish
13
+ from spacy.lang.ja import Japanese
14
+ from spacy.lang.zh import Chinese
15
+ from spacy.lang.vi import Vietnamese
16
+ from transformers import PreTrainedTokenizerFast, BatchEncoding
17
+ from transformers.tokenization_utils_base import TruncationStrategy, PaddingStrategy
18
+ from tokenizers import Tokenizer
19
+ from tokenizers.pre_tokenizers import WhitespaceSplit
20
+ from tokenizers.processors import TemplateProcessing
21
+
22
+ from auralis.models.xttsv2.components.tts.layers.xtts.zh_num2words import TextNorm as zh_num2words
23
+
24
+ import cutlet
25
+
26
+ def get_spacy_lang(lang):
27
+ if lang == "zh":
28
+ return Chinese()
29
+ elif lang == "ja":
30
+ return Japanese()
31
+ elif lang == "ar":
32
+ return Arabic()
33
+ elif lang == "es":
34
+ return Spanish()
35
+ elif lang == "vi":
36
+ return Vietnamese()
37
+ else:
38
+ # For most languages, English does the job
39
+ return English()
40
+
41
+
42
+ def find_best_split_point(text: str, target_pos: int, window_size: int = 30) -> int:
43
+ """
44
+ Find best split point near target position considering punctuation and language markers.
45
+ added for better sentence splitting in TTS.
46
+ """
47
+ # Define split markers by priority
48
+ markers = [
49
+ # Strong breaks (longest pause)
50
+ (r'[.!?؟။။။]+[\s]*', 1.0), # Periods, exclamation, question (multi-script)
51
+ (r'[\n\r]+\s*[\n\r]+', 1.0), # Multiple newlines
52
+ (r'[:|;;:;][\s]*', 0.9), # Colons, semicolons (multi-script)
53
+
54
+ # Medium breaks
55
+ (r'[,,،、][\s]*', 0.8), # Commas (multi-script)
56
+ (r'[)}\])】』»›》\s]+', 0.7), # Closing brackets/parentheses
57
+ (r'[-—−]+[\s]*', 0.7), # Dashes
58
+
59
+ # Weak breaks
60
+ (r'\s+[&+=/\s]+\s+', 0.6), # Special characters with spaces
61
+ (r'[\s]+', 0.5), # Any whitespace as last resort
62
+ ]
63
+
64
+ # Calculate window boundaries
65
+ start = max(0, target_pos - window_size)
66
+ end = min(len(text), target_pos + window_size)
67
+ window = text[start:end]
68
+
69
+ best_pos = target_pos
70
+ best_score = 0
71
+
72
+ for pattern, priority in markers:
73
+ matches = list(re.finditer(pattern, window))
74
+ for match in matches:
75
+ # Calculate position score based on distance from target
76
+ pos = start + match.end()
77
+ distance = abs(pos - target_pos)
78
+ distance_score = 1 - (distance / (window_size * 2))
79
+
80
+ # Combine priority and position scores
81
+ score = priority * distance_score
82
+
83
+ if score > best_score:
84
+ best_score = score
85
+ best_pos = pos
86
+
87
+ return best_pos
88
+
89
+
90
+ def split_sentence(text: str, lang: str, text_split_length: int = 250) -> List[str]:
91
+ """
92
+ Enhanced sentence splitting with language awareness and optimal breakpoints.
93
+
94
+ Args:
95
+ text: Input text to split
96
+ lang: Language code
97
+ text_split_length: Target length for splits
98
+
99
+ Returns:
100
+ List of text splits optimized for TTS
101
+ """
102
+ text = text.strip()
103
+ if len(text) <= text_split_length:
104
+ return [text]
105
+
106
+ nlp = get_spacy_lang(lang)
107
+ if "sentencizer" not in nlp.pipe_names:
108
+ nlp.add_pipe("sentencizer")
109
+
110
+ # Get base sentences using spaCy
111
+ doc = nlp(text)
112
+ sentences = list(doc.sents)
113
+
114
+ splits = []
115
+ current_split = []
116
+ current_length = 0
117
+
118
+ for sent in sentences:
119
+ sentence_text = str(sent).strip()
120
+ sentence_length = len(sentence_text)
121
+
122
+ # If sentence fits in current split
123
+ if current_length + sentence_length <= text_split_length:
124
+ current_split.append(sentence_text)
125
+ current_length += sentence_length + 1
126
+
127
+ # Handle long sentences
128
+ elif sentence_length > text_split_length:
129
+ # Add current split if exists
130
+ if current_split:
131
+ splits.append(" ".join(current_split))
132
+ current_split = []
133
+ current_length = 0
134
+
135
+ # Split long sentence at optimal points
136
+ remaining = sentence_text
137
+ while len(remaining) > text_split_length:
138
+ split_pos = find_best_split_point(
139
+ remaining,
140
+ text_split_length,
141
+ window_size=30
142
+ )
143
+
144
+ # Add split and continue with remainder
145
+ splits.append(remaining[:split_pos].strip())
146
+ remaining = remaining[split_pos:].strip()
147
+
148
+ # Handle remaining text
149
+ if remaining:
150
+ current_split = [remaining]
151
+ current_length = len(remaining)
152
+
153
+ # Start new split
154
+ else:
155
+ splits.append(" ".join(current_split))
156
+ current_split = [sentence_text]
157
+ current_length = sentence_length
158
+
159
+ # Add final split if needed
160
+ if current_split:
161
+ splits.append(" ".join(current_split))
162
+
163
+ cleaned_sentences = [s[:-1]+' ' if s.endswith('.') else s for s in splits if s] # prevents annoying sounds in italian
164
+ # Clean up splits
165
+ return cleaned_sentences
166
+
167
+ _whitespace_re = re.compile(r"\s+")
168
+
169
+ # List of (regular expression, replacement) pairs for abbreviations:
170
+ _abbreviations = {
171
+ "en": [
172
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
173
+ for x in [
174
+ ("mrs", "misess"),
175
+ ("mr", "mister"),
176
+ ("dr", "doctor"),
177
+ ("st", "saint"),
178
+ ("co", "company"),
179
+ ("jr", "junior"),
180
+ ("maj", "major"),
181
+ ("gen", "general"),
182
+ ("drs", "doctors"),
183
+ ("rev", "reverend"),
184
+ ("lt", "lieutenant"),
185
+ ("hon", "honorable"),
186
+ ("sgt", "sergeant"),
187
+ ("capt", "captain"),
188
+ ("esq", "esquire"),
189
+ ("ltd", "limited"),
190
+ ("col", "colonel"),
191
+ ("ft", "fort"),
192
+ ]
193
+ ],
194
+ "es": [
195
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
196
+ for x in [
197
+ ("sra", "señora"),
198
+ ("sr", "señor"),
199
+ ("dr", "doctor"),
200
+ ("dra", "doctora"),
201
+ ("st", "santo"),
202
+ ("co", "compañía"),
203
+ ("jr", "junior"),
204
+ ("ltd", "limitada"),
205
+ ]
206
+ ],
207
+ "fr": [
208
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
209
+ for x in [
210
+ ("mme", "madame"),
211
+ ("mr", "monsieur"),
212
+ ("dr", "docteur"),
213
+ ("st", "saint"),
214
+ ("co", "compagnie"),
215
+ ("jr", "junior"),
216
+ ("ltd", "limitée"),
217
+ ]
218
+ ],
219
+ "de": [
220
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
221
+ for x in [
222
+ ("fr", "frau"),
223
+ ("dr", "doktor"),
224
+ ("st", "sankt"),
225
+ ("co", "firma"),
226
+ ("jr", "junior"),
227
+ ]
228
+ ],
229
+ "pt": [
230
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
231
+ for x in [
232
+ ("sra", "senhora"),
233
+ ("sr", "senhor"),
234
+ ("dr", "doutor"),
235
+ ("dra", "doutora"),
236
+ ("st", "santo"),
237
+ ("co", "companhia"),
238
+ ("jr", "júnior"),
239
+ ("ltd", "limitada"),
240
+ ]
241
+ ],
242
+ "it": [
243
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
244
+ for x in [
245
+ # ("sig.ra", "signora"),
246
+ ("sig", "signore"),
247
+ ("dr", "dottore"),
248
+ ("st", "santo"),
249
+ ("co", "compagnia"),
250
+ ("jr", "junior"),
251
+ ("ltd", "limitata"),
252
+ ]
253
+ ],
254
+ "pl": [
255
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
256
+ for x in [
257
+ ("p", "pani"),
258
+ ("m", "pan"),
259
+ ("dr", "doktor"),
260
+ ("sw", "święty"),
261
+ ("jr", "junior"),
262
+ ]
263
+ ],
264
+ "ar": [
265
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
266
+ for x in [
267
+ # There are not many common abbreviations in Arabic as in English.
268
+ ]
269
+ ],
270
+ "zh": [
271
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
272
+ for x in [
273
+ # Chinese doesn't typically use abbreviations in the same way as Latin-based scripts.
274
+ ]
275
+ ],
276
+ "cs": [
277
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
278
+ for x in [
279
+ ("dr", "doktor"), # doctor
280
+ ("ing", "inženýr"), # engineer
281
+ ("p", "pan"), # Could also map to pani for woman but no easy way to do it
282
+ # Other abbreviations would be specialized and not as common.
283
+ ]
284
+ ],
285
+ "ru": [
286
+ (re.compile("\\b%s\\b" % x[0], re.IGNORECASE), x[1])
287
+ for x in [
288
+ ("г-жа", "госпожа"), # Mrs.
289
+ ("г-н", "господин"), # Mr.
290
+ ("д-р", "доктор"), # doctor
291
+ # Other abbreviations are less common or specialized.
292
+ ]
293
+ ],
294
+ "nl": [
295
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
296
+ for x in [
297
+ ("dhr", "de heer"), # Mr.
298
+ ("mevr", "mevrouw"), # Mrs.
299
+ ("dr", "dokter"), # doctor
300
+ ("jhr", "jonkheer"), # young lord or nobleman
301
+ # Dutch uses more abbreviations, but these are the most common ones.
302
+ ]
303
+ ],
304
+ "tr": [
305
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
306
+ for x in [
307
+ ("b", "bay"), # Mr.
308
+ ("byk", "büyük"), # büyük
309
+ ("dr", "doktor"), # doctor
310
+ # Add other Turkish abbreviations here if needed.
311
+ ]
312
+ ],
313
+ "hu": [
314
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
315
+ for x in [
316
+ ("dr", "doktor"), # doctor
317
+ ("b", "bácsi"), # Mr.
318
+ ("nőv", "nővér"), # nurse
319
+ # Add other Hungarian abbreviations here if needed.
320
+ ]
321
+ ],
322
+ "ko": [
323
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
324
+ for x in [
325
+ # Korean doesn't typically use abbreviations in the same way as Latin-based scripts.
326
+ ]
327
+ ],
328
+ "vi": [
329
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
330
+ for x in [
331
+ # Vietnamese doesn't typically use abbreviations in the same way as Latin-based scripts.
332
+ ]
333
+ ],
334
+ }
335
+
336
+ def expand_abbreviations_multilingual(text, lang="en"):
337
+ if lang in _abbreviations:
338
+ for regex, replacement in _abbreviations[lang]:
339
+ text = re.sub(regex, replacement, text)
340
+ return text
341
+
342
+ _symbols_multilingual = {
343
+ "en": [
344
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
345
+ for x in [
346
+ ("&", " and "),
347
+ ("@", " at "),
348
+ ("%", " percent "),
349
+ ("#", " hash "),
350
+ ("$", " dollar "),
351
+ ("£", " pound "),
352
+ ("°", " degree "),
353
+ ]
354
+ ],
355
+ "es": [
356
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
357
+ for x in [
358
+ ("&", " y "),
359
+ ("@", " arroba "),
360
+ ("%", " por ciento "),
361
+ ("#", " numeral "),
362
+ ("$", " dolar "),
363
+ ("£", " libra "),
364
+ ("°", " grados "),
365
+ ]
366
+ ],
367
+ "fr": [
368
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
369
+ for x in [
370
+ ("&", " et "),
371
+ ("@", " arobase "),
372
+ ("%", " pour cent "),
373
+ ("#", " dièse "),
374
+ ("$", " dollar "),
375
+ ("£", " livre "),
376
+ ("°", " degrés "),
377
+ ]
378
+ ],
379
+ "de": [
380
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
381
+ for x in [
382
+ ("&", " und "),
383
+ ("@", " at "),
384
+ ("%", " prozent "),
385
+ ("#", " raute "),
386
+ ("$", " dollar "),
387
+ ("£", " pfund "),
388
+ ("°", " grad "),
389
+ ]
390
+ ],
391
+ "pt": [
392
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
393
+ for x in [
394
+ ("&", " e "),
395
+ ("@", " arroba "),
396
+ ("%", " por cento "),
397
+ ("#", " cardinal "),
398
+ ("$", " dólar "),
399
+ ("£", " libra "),
400
+ ("°", " graus "),
401
+ ]
402
+ ],
403
+ "it": [
404
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
405
+ for x in [
406
+ ("&", " e "),
407
+ ("@", " chiocciola "),
408
+ ("%", " per cento "),
409
+ ("#", " cancelletto "),
410
+ ("$", " dollaro "),
411
+ ("£", " sterlina "),
412
+ ("°", " gradi "),
413
+ ]
414
+ ],
415
+ "pl": [
416
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
417
+ for x in [
418
+ ("&", " i "),
419
+ ("@", " małpa "),
420
+ ("%", " procent "),
421
+ ("#", " krzyżyk "),
422
+ ("$", " dolar "),
423
+ ("£", " funt "),
424
+ ("°", " stopnie "),
425
+ ]
426
+ ],
427
+ "ar": [
428
+ # Arabic
429
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
430
+ for x in [
431
+ ("&", " و "),
432
+ ("@", " على "),
433
+ ("%", " في المئة "),
434
+ ("#", " رقم "),
435
+ ("$", " دولار "),
436
+ ("£", " جنيه "),
437
+ ("°", " درجة "),
438
+ ]
439
+ ],
440
+ "zh": [
441
+ # Chinese
442
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
443
+ for x in [
444
+ ("&", " 和 "),
445
+ ("@", " 在 "),
446
+ ("%", " 百分之 "),
447
+ ("#", " 号 "),
448
+ ("$", " 美元 "),
449
+ ("£", " 英镑 "),
450
+ ("°", " 度 "),
451
+ ]
452
+ ],
453
+ "cs": [
454
+ # Czech
455
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
456
+ for x in [
457
+ ("&", " a "),
458
+ ("@", " na "),
459
+ ("%", " procento "),
460
+ ("#", " křížek "),
461
+ ("$", " dolar "),
462
+ ("£", " libra "),
463
+ ("°", " stupně "),
464
+ ]
465
+ ],
466
+ "ru": [
467
+ # Russian
468
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
469
+ for x in [
470
+ ("&", " и "),
471
+ ("@", " собака "),
472
+ ("%", " процентов "),
473
+ ("#", " номер "),
474
+ ("$", " доллар "),
475
+ ("£", " фунт "),
476
+ ("°", " градус "),
477
+ ]
478
+ ],
479
+ "nl": [
480
+ # Dutch
481
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
482
+ for x in [
483
+ ("&", " en "),
484
+ ("@", " bij "),
485
+ ("%", " procent "),
486
+ ("#", " hekje "),
487
+ ("$", " dollar "),
488
+ ("£", " pond "),
489
+ ("°", " graden "),
490
+ ]
491
+ ],
492
+ "tr": [
493
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
494
+ for x in [
495
+ ("&", " ve "),
496
+ ("@", " at "),
497
+ ("%", " yüzde "),
498
+ ("#", " diyez "),
499
+ ("$", " dolar "),
500
+ ("£", " sterlin "),
501
+ ("°", " derece "),
502
+ ]
503
+ ],
504
+ "hu": [
505
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
506
+ for x in [
507
+ ("&", " és "),
508
+ ("@", " kukac "),
509
+ ("%", " százalék "),
510
+ ("#", " kettőskereszt "),
511
+ ("$", " dollár "),
512
+ ("£", " font "),
513
+ ("°", " fok "),
514
+ ]
515
+ ],
516
+ "ko": [
517
+ # Korean
518
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
519
+ for x in [
520
+ ("&", " 그리고 "),
521
+ ("@", " 에 "),
522
+ ("%", " 퍼센트 "),
523
+ ("#", " 번호 "),
524
+ ("$", " 달러 "),
525
+ ("£", " 파운드 "),
526
+ ("°", " 도 "),
527
+ ]
528
+ ],
529
+ "vi": [
530
+ (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
531
+ for x in [
532
+ ("&", " và "),
533
+ ("@", " tại "),
534
+ ("%", " phần trăm "),
535
+ ("#", " thăng "),
536
+ ("$", " đô-la "),
537
+ ("£", " bảng "),
538
+ ("°", " độ "),
539
+ ]
540
+ ],
541
+ }
542
+
543
+ def expand_symbols_multilingual(text, lang="en"):
544
+ if lang in _symbols_multilingual:
545
+ for regex, replacement in _symbols_multilingual[lang]:
546
+ text = re.sub(regex, replacement, text)
547
+ text = text.replace(" ", " ") # Ensure there are no double spaces
548
+ return text.strip()
549
+
550
+ _ordinal_re = {
551
+ "en": re.compile(r"([0-9]+)(st|nd|rd|th)"),
552
+ "es": re.compile(r"([0-9]+)(º|ª|er|o|a|os|as)"),
553
+ "fr": re.compile(r"([0-9]+)(º|ª|er|re|e|ème)"),
554
+ "de": re.compile(r"([0-9]+)(st|nd|rd|th|º|ª|\.(?=\s|$))"),
555
+ "pt": re.compile(r"([0-9]+)(º|ª|o|a|os|as)"),
556
+ "it": re.compile(r"([0-9]+)(º|°|ª|o|a|i|e)"),
557
+ "pl": re.compile(r"([0-9]+)(º|ª|st|nd|rd|th)"),
558
+ "ar": re.compile(r"([0-9]+)(ون|ين|ث|ر|ى)"),
559
+ "cs": re.compile(r"([0-9]+)\.(?=\s|$)"), # In Czech, a dot is often used after the number to indicate ordinals.
560
+ "ru": re.compile(r"([0-9]+)(-й|-я|-е|-ое|-ье|-го)"),
561
+ "nl": re.compile(r"([0-9]+)(de|ste|e)"),
562
+ "tr": re.compile(r"([0-9]+)(\.|inci|nci|uncu|üncü|\.)"),
563
+ "hu": re.compile(r"([0-9]+)(\.|adik|edik|odik|edik|ödik|ödike|ik)"),
564
+ "ko": re.compile(r"([0-9]+)(번째|번|차|째)"),
565
+ "vi": re.compile(r"(thứ) ([0-9]+)"),
566
+ }
567
+ _number_re = re.compile(r"[0-9]+")
568
+ # noinspection Annotator
569
+ _currency_re = {
570
+ "USD": re.compile(r"((\$[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+\$))"),
571
+ "GBP": re.compile(r"((£[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+£))"),
572
+ "EUR": re.compile(r"(([0-9\.\,]*[0-9]+€)|((€[0-9\.\,]*[0-9]+)))"),
573
+ }
574
+
575
+ _comma_number_re = re.compile(r"\b\d{1,3}(,\d{3})*(\.\d+)?\b")
576
+ _dot_number_re = re.compile(r"\b\d{1,3}(\.\d{3})*(\,\d+)?\b")
577
+ _decimal_number_re = re.compile(r"([0-9]+[.,][0-9]+)")
578
+
579
+ def _remove_commas(m):
580
+ text = m.group(0)
581
+ if "," in text:
582
+ text = text.replace(",", "")
583
+ return text
584
+
585
+ def _remove_dots(m):
586
+ text = m.group(0)
587
+ if "." in text:
588
+ text = text.replace(".", "")
589
+ return text
590
+
591
+ def _expand_decimal_point(m, lang="en"):
592
+ amount = m.group(1).replace(",", ".")
593
+ return num2words(float(amount), lang=lang if lang != "cs" else "cz")
594
+
595
+ def _expand_currency(m, lang="en", currency="USD"):
596
+ amount = float((re.sub(r"[^\d.]", "", m.group(0).replace(",", "."))))
597
+ full_amount = num2words(amount, to="currency", currency=currency, lang=lang if lang != "cs" else "cz")
598
+
599
+ and_equivalents = {
600
+ "en": ", ",
601
+ "es": " con ",
602
+ "fr": " et ",
603
+ "de": " und ",
604
+ "pt": " e ",
605
+ "it": " e ",
606
+ "pl": ", ",
607
+ "cs": ", ",
608
+ "ru": ", ",
609
+ "nl": ", ",
610
+ "ar": ", ",
611
+ "tr": ", ",
612
+ "hu": ", ",
613
+ "ko": ", ",
614
+ "vi": ", ",
615
+ }
616
+
617
+ if amount.is_integer():
618
+ last_and = full_amount.rfind(and_equivalents.get(lang, ", "))
619
+ if last_and != -1:
620
+ full_amount = full_amount[:last_and]
621
+
622
+ return full_amount
623
+
624
+ def _expand_ordinal(m, lang="en"):
625
+ return num2words(int(m.group(1)), ordinal=True, lang=lang if lang != "cs" else "cz")
626
+
627
+ def _expand_number(m, lang="en"):
628
+ return num2words(int(m.group(0)), lang=lang if lang != "cs" else "cz")
629
+
630
+ def expand_numbers_multilingual(text, lang="en"):
631
+ if lang == "zh":
632
+ text = zh_num2words()(text)
633
+ else:
634
+ if lang in ["en", "ru"]:
635
+ text = re.sub(_comma_number_re, _remove_commas, text)
636
+ else:
637
+ text = re.sub(_dot_number_re, _remove_dots, text)
638
+ try:
639
+ text = re.sub(_currency_re["GBP"], lambda m: _expand_currency(m, lang, "GBP"), text)
640
+ text = re.sub(_currency_re["USD"], lambda m: _expand_currency(m, lang, "USD"), text)
641
+ text = re.sub(_currency_re["EUR"], lambda m: _expand_currency(m, lang, "EUR"), text)
642
+ except Exception as e:
643
+ pass
644
+ if lang != "tr":
645
+ text = re.sub(_decimal_number_re, lambda m: _expand_decimal_point(m, lang), text)
646
+ if lang in _ordinal_re:
647
+ text = re.sub(_ordinal_re[lang], lambda m: _expand_ordinal(m, lang), text)
648
+ text = re.sub(_number_re, lambda m: _expand_number(m, lang), text)
649
+ return text
650
+
651
+ def lowercase(text):
652
+ return text.lower()
653
+
654
+ def collapse_whitespace(text):
655
+ return re.sub(_whitespace_re, " ", text)
656
+
657
+ def multilingual_cleaners(text, lang):
658
+ text = text.replace('"', "")
659
+ if lang == "tr":
660
+ text = text.replace("İ", "i")
661
+ text = text.replace("Ö", "ö")
662
+ text = text.replace("Ü", "ü")
663
+ text = lowercase(text)
664
+ text = expand_numbers_multilingual(text, lang)
665
+ text = expand_abbreviations_multilingual(text, lang)
666
+ text = expand_symbols_multilingual(text, lang=lang)
667
+ text = collapse_whitespace(text)
668
+ return text
669
+
670
+ def basic_cleaners(text):
671
+ """Basic pipeline that lowercases and collapses whitespace without transliteration."""
672
+ text = lowercase(text)
673
+ text = collapse_whitespace(text)
674
+ return text
675
+
676
+ def chinese_transliterate(text):
677
+ return "".join(
678
+ [p[0] for p in pypinyin.pinyin(text, style=pypinyin.Style.TONE3, heteronym=False, neutral_tone_with_five=True)]
679
+ )
680
+
681
+ def japanese_cleaners(text, katsu):
682
+ text = katsu.romaji(text)
683
+ text = lowercase(text)
684
+ return text
685
+
686
+ def korean_transliterate(text, transliter):
687
+ return transliter.translit(text)
688
+
689
+ # Fast Tokenizer Class
690
+
691
+ class XTTSTokenizerFast(PreTrainedTokenizerFast):
692
+ """
693
+ Fast Tokenizer implementation for XTTS model using HuggingFace's PreTrainedTokenizerFast
694
+ """
695
+
696
+ def __init__(
697
+ self,
698
+ vocab_file: str = None,
699
+ tokenizer_object: Optional[Tokenizer] = None,
700
+ unk_token: str = "[UNK]",
701
+ pad_token: str = "[PAD]",
702
+ bos_token: str = "[START]",
703
+ eos_token: str = "[STOP]",
704
+ auto_map: dict = {"AutoTokenizer": ["AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast", None]},
705
+ clean_up_tokenization_spaces: bool = True,
706
+ **kwargs
707
+ ):
708
+ if tokenizer_object is None and vocab_file is not None:
709
+ tokenizer_object = Tokenizer.from_file(vocab_file)
710
+
711
+ if tokenizer_object is not None:
712
+ # Configure the tokenizer
713
+ tokenizer_object.pre_tokenizer = WhitespaceSplit()
714
+ tokenizer_object.post_processor = TemplateProcessing(
715
+ single=f"{bos_token} $A {eos_token}",
716
+ special_tokens=[
717
+ (bos_token, tokenizer_object.token_to_id(bos_token)),
718
+ (eos_token, tokenizer_object.token_to_id(eos_token)),
719
+ ],
720
+ )
721
+
722
+ super().__init__(
723
+ tokenizer_object=tokenizer_object,
724
+ unk_token=unk_token,
725
+ pad_token=pad_token,
726
+ bos_token=bos_token,
727
+ eos_token=eos_token,
728
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
729
+ **kwargs
730
+ )
731
+
732
+ # Character limits per language
733
+ self.char_limits = {
734
+ "en": 250, "de": 253, "fr": 273, "es": 239,
735
+ "it": 213, "pt": 203, "pl": 224, "zh": 82,
736
+ "ar": 166, "cs": 186, "ru": 182, "nl": 251,
737
+ "tr": 226, "ja": 71, "hu": 224, "ko": 95,
738
+ "vi": 200,
739
+ }
740
+
741
+ # Initialize language tools
742
+ self._katsu = None
743
+ self._korean_transliter = Transliter(academic)
744
+
745
+ # Ensure pad_token_id is set
746
+ if self.pad_token_id is None:
747
+ self.pad_token_id = self.tokenizer.token_to_id(self.pad_token)
748
+
749
+ @cached_property
750
+ def katsu(self):
751
+ if self._katsu is None:
752
+ self._katsu = cutlet.Cutlet()
753
+ return self._katsu
754
+
755
+ def preprocess_text(self, text: str, lang: str) -> str:
756
+ """Apply text preprocessing for language"""
757
+ base_lang = lang.split("-")[0] # remove region
758
+ if base_lang in {"ar", "cs", "de", "en", "es", "fr", "hu", "it",
759
+ "nl", "pl", "pt", "ru", "tr", "zh", "ko", "vi"}:
760
+ text = multilingual_cleaners(text, base_lang)
761
+ if base_lang == "zh":
762
+ text = chinese_transliterate(text)
763
+ if base_lang == "ko":
764
+ text = korean_transliterate(text, self._korean_transliter)
765
+ elif base_lang == "ja":
766
+ text = japanese_cleaners(text, self.katsu)
767
+ else:
768
+ text = basic_cleaners(text)
769
+ return text
770
+
771
+ def batch_encode_with_split(self, texts: Union[str, List[str]], lang: Union[str, List[str]],
772
+ **kwargs) -> torch.Tensor:
773
+ """
774
+ Split texts into smaller chunks based on language character limits and encode them using HuggingFace fast tokenizer.
775
+ strictly mimic the xttsv2 tokenizer
776
+ """
777
+ # Convert single inputs to lists
778
+ if isinstance(texts, str):
779
+ texts = [texts]
780
+ if isinstance(lang, str):
781
+ lang = [lang]
782
+ # Ensure lang list matches texts list
783
+ if len(lang) == 1 and len(texts) > 1:
784
+ lang = lang * len(texts)
785
+
786
+ # Check if texts and lang have the same length
787
+ if len(texts) != len(lang):
788
+ raise ValueError(f"Number of texts ({len(texts)}) does not match number of languages ({len(lang)}).")
789
+
790
+ chunk_list = []
791
+ max_splits = 0
792
+
793
+ # For each text, split into chunks based on character limit
794
+ for text, text_lang in zip(texts, lang):
795
+ # Get language character limit
796
+ base_lang = text_lang.split("-")[0]
797
+ char_limit = self.char_limits.get(base_lang, 250)
798
+
799
+ # Clean and preprocess
800
+ #text = self.preprocess_text(text, text_lang) we do this in the hidden function
801
+
802
+ # Split text into sentences/chunks based on language
803
+ chunk_list = split_sentence(text, base_lang, text_split_length=char_limit)
804
+
805
+ # Ensure the tokenizer is a fast tokenizer
806
+ if not self.is_fast:
807
+ raise ValueError("The tokenizer must be a fast tokenizer.")
808
+
809
+ # Encode all chunks using the fast tokenizer
810
+ encoding: BatchEncoding = self(
811
+ chunk_list,
812
+ lang = lang,
813
+ add_special_tokens=False,
814
+ padding=False,
815
+ **kwargs
816
+ )
817
+
818
+ # The 'input_ids' tensor will have shape [total_chunks, max_sequence_length]
819
+ return encoding['input_ids'] # Tensor of shape [total_chunks, sequence_length]
820
+
821
+ def _batch_encode_plus(
822
+ self,
823
+ batch_text_or_text_pairs,
824
+ add_special_tokens: bool = True,
825
+ padding_strategy=PaddingStrategy.DO_NOT_PAD,
826
+ truncation_strategy=TruncationStrategy.DO_NOT_TRUNCATE,
827
+ max_length: Optional[int] = None,
828
+ stride: int = 0,
829
+ is_split_into_words: bool = False,
830
+ pad_to_multiple_of: Optional[int] = None,
831
+ return_tensors: Optional[str] = None,
832
+ return_token_type_ids: Optional[bool] = None,
833
+ return_attention_mask: Optional[bool] = None,
834
+ return_overflowing_tokens: bool = False,
835
+ return_special_tokens_mask: bool = False,
836
+ return_offsets_mapping: bool = False,
837
+ return_length: bool = False,
838
+ verbose: bool = True,
839
+ **kwargs
840
+ ) -> Dict[str, Any]:
841
+ """
842
+ Override batch encoding to handle language-specific preprocessing
843
+ """
844
+ lang = kwargs.pop("lang", ["en"] * len(batch_text_or_text_pairs))
845
+ if isinstance(lang, str):
846
+ lang = [lang]
847
+ # Ensure lang list matches texts list
848
+ if len(lang) == 1 and len(batch_text_or_text_pairs) > 1:
849
+ lang = lang * len(batch_text_or_text_pairs)
850
+
851
+ # Check if batch_text_or_text_pairs and lang have the same length
852
+ if len(batch_text_or_text_pairs) != len(lang):
853
+ raise ValueError(f"Number of texts ({len(batch_text_or_text_pairs)}) does not match number of languages ({len(lang)}).")
854
+
855
+ # Preprocess each text in the batch with its corresponding language
856
+ processed_texts = []
857
+ for text, text_lang in zip(batch_text_or_text_pairs, lang):
858
+ if isinstance(text, str):
859
+ # Check length and preprocess
860
+ #self.check_input_length(text, text_lang)
861
+ processed_text = self.preprocess_text(text, text_lang)
862
+
863
+ # Format text with language tag and spaces
864
+ base_lang = text_lang.split("-")[0]
865
+ lang_code = "zh-cn" if base_lang == "zh" else base_lang
866
+ processed_text = f"[{lang_code}]{processed_text}"
867
+ processed_text = processed_text.replace(" ", "[SPACE]")
868
+
869
+ processed_texts.append(processed_text)
870
+ else:
871
+ processed_texts.append(text)
872
+
873
+ # Call the parent class's encoding method with processed texts
874
+ return super()._batch_encode_plus(
875
+ processed_texts,
876
+ add_special_tokens=add_special_tokens,
877
+ padding_strategy=padding_strategy,
878
+ truncation_strategy=truncation_strategy,
879
+ max_length=max_length,
880
+ stride=stride,
881
+ is_split_into_words=is_split_into_words,
882
+ pad_to_multiple_of=pad_to_multiple_of,
883
+ return_tensors=return_tensors,
884
+ return_token_type_ids=return_token_type_ids,
885
+ return_attention_mask=return_attention_mask,
886
+ return_overflowing_tokens=return_overflowing_tokens,
887
+ return_special_tokens_mask=return_special_tokens_mask,
888
+ return_offsets_mapping=return_offsets_mapping,
889
+ return_length=return_length,
890
+ verbose=verbose,
891
+ **kwargs
892
+ )
893
+
894
+
895
+ def __call__(
896
+ self,
897
+ text: Union[str, List[str]],
898
+ lang: Union[str, List[str]] = "en",
899
+ add_special_tokens: bool = True,
900
+ padding: Union[bool, str, PaddingStrategy] = False,
901
+ truncation: Union[bool, str, TruncationStrategy] = False,
902
+ max_length: Optional[int] = None,
903
+ stride: int = 0,
904
+ return_tensors: Optional[str] = None,
905
+ return_token_type_ids: Optional[bool] = None,
906
+ return_attention_mask: Optional[bool] = True,
907
+ **kwargs
908
+ ):
909
+ """
910
+ Main tokenization method
911
+ """
912
+ # Convert single string to list for batch processing
913
+ if isinstance(text, str):
914
+ text = [text]
915
+ if isinstance(lang, str):
916
+ lang = [lang]
917
+ # Ensure lang list matches texts list
918
+ if len(lang) == 1 and len(text) > 1:
919
+ lang = lang * len(text)
920
+
921
+ # Ensure text and lang lists have same length
922
+ if len(text) != len(lang):
923
+ raise ValueError(f"Number of texts ({len(text)}) does not match number of languages ({len(lang)}).")
924
+
925
+ # Convert padding strategy
926
+ if isinstance(padding, bool):
927
+ padding_strategy = PaddingStrategy.LONGEST if padding else PaddingStrategy.DO_NOT_PAD
928
+ else:
929
+ padding_strategy = PaddingStrategy(padding)
930
+
931
+ # Convert truncation strategy
932
+ if isinstance(truncation, bool):
933
+ truncation_strategy = TruncationStrategy.LONGEST_FIRST if truncation else TruncationStrategy.DO_NOT_TRUNCATE
934
+ else:
935
+ truncation_strategy = TruncationStrategy(truncation)
936
+
937
+ # Use the batch encoding method
938
+ encoded = self._batch_encode_plus(
939
+ text,
940
+ add_special_tokens=add_special_tokens,
941
+ padding_strategy=padding_strategy,
942
+ truncation_strategy=truncation_strategy,
943
+ max_length=max_length,
944
+ stride=stride,
945
+ return_tensors=return_tensors,
946
+ return_token_type_ids=return_token_type_ids,
947
+ return_attention_mask=return_attention_mask,
948
+ lang=lang,
949
+ **kwargs
950
+ )
951
+
952
+ return encoded
xtts-v2.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:130a9659aed2056d094e6d73f31474685d414f98747a61835a153038991e01ef
3
+ size 352299952
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 = 7544, # gpt_number_text_tokens in original
45
+ number_text_tokens: int = 7544, # 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", "vi",
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 ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
434
+ output_sample_rate=self.hifi_config.output_sample_rate,
435
+ output_hop_length=self.hifi_config.output_hop_length,
436
+ ar_mel_length_compression=self.hifi_config.gpt_code_stride_len,
437
+ decoder_input_dim=self.hifi_config.decoder_input_dim,
438
+ d_vector_dim=self.hifi_config.d_vector_dim,
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
517
+
518
+ # Download and load configs
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
537
+ model = cls(
538
+ hifi_config=hifi_config,
539
+ gpt_config=gpt_config,
540
+ tensor_parallel_size=tensor_parallel_size,
541
+ **kwargs
542
+ )
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