seifwaked commited on
Commit
62078e1
·
verified ·
1 Parent(s): 6d6c853

Upload 8 files

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