K-Murder commited on
Commit
0c74273
·
verified ·
1 Parent(s): a1bc99c

Upload 11 files

Browse files
README.md ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "xtts_gpt",
3
+ "architectures": [
4
+ "XttsGPT"
5
+ ],
6
+ "vocab_size": 6681,
7
+ "hidden_size": 1024,
8
+ "num_hidden_layers": 30,
9
+ "num_attention_heads": 16,
10
+ "n_inner": 4096,
11
+ "number_text_tokens": 6681,
12
+ "num_audio_tokens": 1026,
13
+ "max_audio_tokens": 605,
14
+ "start_audio_token": 1024,
15
+ "stop_audio_token": 1025,
16
+ "max_text_tokens": 402,
17
+ "max_prompt_tokens": 70,
18
+ "activation_function": "gelu_new",
19
+ "attn_pdrop": 0.1,
20
+ "layer_norm_epsilon": 1e-05,
21
+ "initializer_range": 0.02,
22
+ "use_masking_gt_prompt_approach": true,
23
+ "use_perceiver_resampler": true,
24
+ "kv_cache": true,
25
+ "enable_redaction": false,
26
+ "reorder_and_upcast_attn": false,
27
+ "scale_attn_by_inverse_layer_idx": false,
28
+ "auto_map": {
29
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
30
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
31
+ "AutoTokenizer": "AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast"
32
+ },
33
+ "languages": [
34
+ "en",
35
+ "es",
36
+ "fr",
37
+ "de",
38
+ "it",
39
+ "pt",
40
+ "pl",
41
+ "tr",
42
+ "ru",
43
+ "nl",
44
+ "cs",
45
+ "ar",
46
+ "zh-cn",
47
+ "hu",
48
+ "ko",
49
+ "ja",
50
+ "hi"
51
+ ]
52
+ }
config.original.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "xtts_gpt",
3
+ "architectures": [
4
+ "XttsGPT"
5
+ ],
6
+ "vocab_size": 6681,
7
+ "hidden_size": 1024,
8
+ "num_hidden_layers": 30,
9
+ "num_attention_heads": 16,
10
+ "n_inner": 4096,
11
+ "number_text_tokens": 6681,
12
+ "num_audio_tokens": 1026,
13
+ "max_audio_tokens": 605,
14
+ "start_audio_token": 1024,
15
+ "stop_audio_token": 1025,
16
+ "max_text_tokens": 402,
17
+ "max_prompt_tokens": 70,
18
+ "activation_function": "gelu_new",
19
+ "attn_pdrop": 0.1,
20
+ "layer_norm_epsilon": 1e-05,
21
+ "initializer_range": 0.02,
22
+ "use_masking_gt_prompt_approach": true,
23
+ "use_perceiver_resampler": true,
24
+ "kv_cache": true,
25
+ "enable_redaction": false,
26
+ "reorder_and_upcast_attn": false,
27
+ "scale_attn_by_inverse_layer_idx": false,
28
+ "auto_map": {
29
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
30
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
31
+ "AutoTokenizer": "AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast"
32
+ },
33
+ "languages": [
34
+ "en",
35
+ "es",
36
+ "fr",
37
+ "de",
38
+ "it",
39
+ "pt",
40
+ "pl",
41
+ "tr",
42
+ "ru",
43
+ "nl",
44
+ "cs",
45
+ "ar",
46
+ "zh-cn",
47
+ "hu",
48
+ "ko",
49
+ "ja",
50
+ "hi"
51
+ ]
52
+ }
gpt2_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:104d92b2297c243b64d1417bd5cfda015faca0a670e9bc90088eed0e844f8e35
3
+ size 1522497936
gpt_config.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass
2
+ from typing import Dict, Optional, List
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ @dataclass
10
+ class GPTAudioConfig:
11
+ """Configuration for GPT audio processing parameters"""
12
+ mel_channels: int = 80
13
+ sample_rate: int = 22050
14
+ output_sample_rate: int = 24000
15
+
16
+ @dataclass
17
+ class XTTSAudioConfig:
18
+ """Configuration for audio processing parameters"""
19
+ sample_rate: int = 22050
20
+ output_sample_rate: int = 24000
21
+ mel_channels: int = 80
22
+ hop_length: int = 256
23
+ win_length: int = 1024
24
+ n_fft: int = 1024
25
+ fmin: int = 0
26
+ fmax: int = 8000
27
+ power: float = 1.0
28
+ mel_norms_file: Optional[str] = None
29
+
30
+
31
+ class XTTSGPTConfig(PretrainedConfig):
32
+ """Configuration class for the GPT component of XTTS."""
33
+ model_type = "xtts_gpt"
34
+
35
+ def __init__(
36
+ self,
37
+ # Model architecture
38
+ hidden_size: int = 1024, # gpt_n_model_channels in original
39
+ n_inner: int = 4096,
40
+ num_hidden_layers: int = 30, # gpt_layers in original
41
+ num_attention_heads: int = 16, # gpt_n_heads in original
42
+
43
+ # Tokenizer settings
44
+ vocab_size: int = 6681, # gpt_number_text_tokens in original
45
+ number_text_tokens: int = 6681, # Explicit text token vocabulary size
46
+ start_text_token: Optional[int] = None,
47
+ stop_text_token: Optional[int] = None,
48
+
49
+ # Audio token settings
50
+ num_audio_tokens: int = 1026, # gpt_num_audio_tokens in original
51
+ start_audio_token: int = 1024, # gpt_start_audio_token in original
52
+ stop_audio_token: int = 1025, # gpt_stop_audio_token in original
53
+
54
+ # Sequence length settings
55
+ max_audio_tokens: int = 605, # gpt_max_audio_tokens in original
56
+ max_text_tokens: int = 402, # gpt_max_text_tokens in original
57
+ max_prompt_tokens: int = 70, # gpt_max_prompt_tokens in original
58
+ gpt_max_audio_tokens: int = 605, # Used for generation
59
+
60
+ # Model behavior settings
61
+ use_masking_gt_prompt_approach: bool = True, # gpt_use_masking_gt_prompt_approach in original
62
+ use_perceiver_resampler: bool = True, # gpt_use_perceiver_resampler in original
63
+ kv_cache: bool = True,
64
+ enable_redaction: bool = False,
65
+
66
+ # GPT batch settings
67
+ gpt_batch_size: int = 1,
68
+
69
+ # Audio processing
70
+ audio_config: Optional[Dict] = None,
71
+
72
+ # Architecture specifics
73
+ layer_norm_epsilon: float = 1e-5,
74
+ initializer_range: float = 0.02,
75
+ add_cross_attention: bool = False,
76
+ scale_attn_by_inverse_layer_idx: bool = False,
77
+ reorder_and_upcast_attn: bool = False,
78
+
79
+ # Size settings for the decoder
80
+ decoder_input_dim: int = 1024,
81
+ architectures=["XttsGPT"],
82
+ auto_map={
83
+ "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
84
+ "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
85
+ },
86
+ activation_function: str = "gelu",
87
+ attn_pdrop: float = 0.1,
88
+ **kwargs
89
+ ):
90
+ super().__init__(**kwargs)
91
+ self.architectures = architectures
92
+ self.auto_map = auto_map
93
+ self.audio_config = GPTAudioConfig(
94
+ **audio_config if audio_config is not None else {}
95
+ )
96
+ self.activation_function = activation_function
97
+ self.attn_pdrop = attn_pdrop
98
+ self.hidden_size = hidden_size
99
+ self.n_inner = n_inner
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.num_attention_heads = num_attention_heads
102
+
103
+ self.vocab_size = vocab_size
104
+ self.number_text_tokens = number_text_tokens
105
+ self.start_text_token = start_text_token
106
+ self.stop_text_token = stop_text_token
107
+
108
+ self.num_audio_tokens = num_audio_tokens
109
+ self.start_audio_token = start_audio_token
110
+ self.stop_audio_token = stop_audio_token
111
+
112
+ self.max_audio_tokens = max_audio_tokens
113
+ self.max_text_tokens = max_text_tokens
114
+ self.max_prompt_tokens = max_prompt_tokens
115
+ self.gpt_max_audio_tokens = gpt_max_audio_tokens
116
+
117
+ self.use_masking_gt_prompt_approach = use_masking_gt_prompt_approach
118
+ self.use_perceiver_resampler = use_perceiver_resampler
119
+ self.kv_cache = kv_cache
120
+ self.enable_redaction = enable_redaction
121
+
122
+ self.gpt_batch_size = gpt_batch_size
123
+
124
+ self.layer_norm_epsilon = layer_norm_epsilon
125
+ self.initializer_range = initializer_range
126
+ self.add_cross_attention = add_cross_attention
127
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
128
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
129
+
130
+ self.decoder_input_dim = decoder_input_dim
131
+
132
+ def to_dict(self) -> Dict:
133
+ """Convert the config to a dictionary."""
134
+ output = super().to_dict()
135
+ output["audio_config"] = asdict(self.audio_config)
136
+ return output
137
+
138
+ @classmethod
139
+ def from_dict(cls, config_dict: Dict, *args, **kwargs) -> "XTTSGPTConfig":
140
+ """Create a config from a dictionary."""
141
+ return cls(**config_dict)
142
+
143
+
special_tokens_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "[START]",
3
+ "eos_token": "[STOP]",
4
+ "pad_token": "[PAD]",
5
+ "unk_token": "[UNK]"
6
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
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
tokenizer_config.json ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[STOP]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[SPACE]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "259": {
28
+ "content": "[en]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "260": {
36
+ "content": "[de]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "261": {
44
+ "content": "[START]",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "262": {
52
+ "content": "[fr]",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "267": {
60
+ "content": "[ru]",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "284": {
68
+ "content": "[es]",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "285": {
76
+ "content": "[it]",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "286": {
84
+ "content": "[pt]",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "293": {
92
+ "content": "[cs]",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "294": {
100
+ "content": "[pl]",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "295": {
108
+ "content": "[tr]",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "297": {
116
+ "content": "[nl]",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "5022": {
124
+ "content": "[ar]",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "5023": {
132
+ "content": "[zh-cn]",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "5412": {
140
+ "content": "[ja]",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "5753": {
148
+ "content": "[hu]",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "6152": {
156
+ "content": "[ko]",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "6680": {
164
+ "content": "[hi]",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ },
171
+ "6681": {
172
+ "content": "[PAD]",
173
+ "lstrip": false,
174
+ "normalized": false,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": true
178
+ }
179
+ },
180
+ "auto_map": {"AutoTokenizer": ["AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast", null]},
181
+ "bos_token": "[START]",
182
+ "clean_up_tokenization_spaces": true,
183
+ "eos_token": "[STOP]",
184
+ "max_length": null,
185
+ "model_max_length": 1000000000000000019884624838656,
186
+ "pad_to_multiple_of": null,
187
+ "pad_token": "[PAD]",
188
+ "pad_token_type_id": 0,
189
+ "padding_side": "right",
190
+ "tokenizer_class": "XTTSTokenizerFast",
191
+ "unk_token": "[UNK]"
192
+ }
xtts2_gpt_modeling.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import math
3
+ from array import array
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.nn import functional as F
8
+ from typing import List, Optional, Union, Iterable, Tuple, Mapping
9
+
10
+ from transformers import PretrainedConfig
11
+ from vllm.attention import AttentionMetadata, Attention
12
+ from vllm.config import CacheConfig, MultiModalConfig
13
+ from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
14
+ from vllm.inputs import InputContext, INPUT_REGISTRY
15
+ from vllm.model_executor.layers.activation import get_act_fn
16
+ from vllm.model_executor.layers.linear import ColumnParallelLinear, QKVParallelLinear, RowParallelLinear
17
+ from vllm.model_executor.layers.quantization import QuantizationConfig
18
+ from vllm.model_executor.layers.sampler import Sampler, SamplerOutput
19
+ from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
20
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
21
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
22
+ from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalInputs
23
+ from vllm.sequence import IntermediateTensors, SequenceData, VLLM_TOKEN_ID_ARRAY_TYPE
24
+ from vllm.model_executor.models.interfaces import SupportsMultiModal, SupportsPP
25
+
26
+ from TTS.tts.layers.xtts.latent_encoder import ConditioningEncoder # noqa
27
+ from TTS.tts.layers.xtts.perceiver_encoder import PerceiverResampler # noqa
28
+
29
+ from TTS.TTS.tts.layers.xtts.gpt import LearnedPositionEmbeddings
30
+
31
+ # Constants for token calculation
32
+ _AUDIO_PLACEHOLDER_TOKEN = 8192 # Using XTTS start_audio_token as placeholder
33
+ _AUDIO_TOKENS_PER_SECOND = 6.25
34
+ _CODE_STRIDE_LEN = 1024
35
+
36
+ class GPT2Attention(nn.Module):
37
+ def __init__(
38
+ self,
39
+ config: PretrainedConfig,
40
+ cache_config: Optional[CacheConfig] = None,
41
+ quant_config: Optional[QuantizationConfig] = None,
42
+ prefix: str = "",
43
+ ):
44
+ super().__init__()
45
+ total_num_heads = config.num_attention_heads
46
+ self.hidden_size = config.hidden_size
47
+ tensor_model_parallel_world_size = get_tensor_model_parallel_world_size()
48
+ assert total_num_heads % tensor_model_parallel_world_size == 0
49
+ self.num_heads = total_num_heads // tensor_model_parallel_world_size
50
+ self.head_dim = self.hidden_size // total_num_heads
51
+ self.scale = self.head_dim**-0.5
52
+
53
+ self.c_attn = QKVParallelLinear(
54
+ self.hidden_size,
55
+ self.head_dim,
56
+ total_num_heads,
57
+ bias=True,
58
+ quant_config=quant_config,
59
+ prefix=f"{prefix}.c_attn",
60
+ )
61
+ self.c_proj = RowParallelLinear(
62
+ self.hidden_size,
63
+ self.hidden_size,
64
+ bias=True,
65
+ quant_config=quant_config,
66
+ prefix=f"{prefix}.c_proj",
67
+ )
68
+ self.attn = Attention(
69
+ self.num_heads,
70
+ self.head_dim,
71
+ scale=self.scale,
72
+ cache_config=cache_config,
73
+ quant_config=quant_config
74
+ )
75
+
76
+ def forward(
77
+ self,
78
+ hidden_states: torch.Tensor,
79
+ kv_cache: torch.Tensor,
80
+ attn_metadata: AttentionMetadata,
81
+ ) -> torch.Tensor:
82
+ qkv, _ = self.c_attn(hidden_states)
83
+ q, k, v = qkv.chunk(chunks=3, dim=-1)
84
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
85
+ attn_output, _ = self.c_proj(attn_output)
86
+ return attn_output
87
+
88
+
89
+ class GPT2MLP(nn.Module):
90
+ def __init__(
91
+ self,
92
+ intermediate_size: int,
93
+ config: PretrainedConfig,
94
+ quant_config: Optional[QuantizationConfig] = None,
95
+ prefix: str = "",
96
+ ):
97
+ super().__init__()
98
+ hidden_size = config.hidden_size
99
+
100
+ self.c_fc = ColumnParallelLinear(
101
+ hidden_size,
102
+ intermediate_size,
103
+ bias=True,
104
+ quant_config=quant_config,
105
+ prefix=f"{prefix}.c_fc",
106
+ )
107
+ self.c_proj = RowParallelLinear(
108
+ intermediate_size,
109
+ hidden_size,
110
+ bias=True,
111
+ quant_config=quant_config,
112
+ prefix=f"{prefix}.c_proj",
113
+ )
114
+ self.act = get_act_fn(config.activation_function, quant_config, intermediate_size)
115
+
116
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
117
+ hidden_states, _ = self.c_fc(hidden_states)
118
+ hidden_states = self.act(hidden_states)
119
+ hidden_states, _ = self.c_proj(hidden_states)
120
+ return hidden_states
121
+
122
+
123
+ class GPT2Block(nn.Module):
124
+ def __init__(
125
+ self,
126
+ config: PretrainedConfig,
127
+ cache_config: Optional[CacheConfig] = None,
128
+ quant_config: Optional[QuantizationConfig] = None,
129
+ prefix: str = "",
130
+ ):
131
+ super().__init__()
132
+ hidden_size = config.hidden_size
133
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
134
+
135
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
136
+ self.attn = GPT2Attention(
137
+ config,
138
+ cache_config,
139
+ quant_config,
140
+ prefix=f"{prefix}.attn"
141
+ )
142
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
143
+ self.mlp = GPT2MLP(
144
+ inner_dim,
145
+ config,
146
+ quant_config,
147
+ prefix=f"{prefix}.mlp"
148
+ )
149
+
150
+ def forward(
151
+ self,
152
+ hidden_states: torch.Tensor,
153
+ kv_cache: torch.Tensor,
154
+ attn_metadata: AttentionMetadata,
155
+ ) -> torch.Tensor:
156
+ residual = hidden_states
157
+ hidden_states = self.ln_1(hidden_states)
158
+ attn_output = self.attn(
159
+ hidden_states=hidden_states,
160
+ kv_cache=kv_cache,
161
+ attn_metadata=attn_metadata,
162
+ )
163
+ hidden_states = attn_output + residual
164
+
165
+ residual = hidden_states
166
+ hidden_states = self.ln_2(hidden_states)
167
+ feed_forward_hidden_states = self.mlp(hidden_states)
168
+ hidden_states = residual + feed_forward_hidden_states
169
+ return hidden_states
170
+
171
+
172
+
173
+ def get_xtts_max_audio_tokens(ctx: InputContext) -> int:
174
+ """Calculate maximum audio tokens based on text context and audio duration."""
175
+ # Based on GPT config and XTTSv2 settings
176
+ return 608
177
+
178
+
179
+ def dummy_seq_data_for_xtts(
180
+ ctx: InputContext,
181
+ seq_len: int,
182
+ audio_count: int,
183
+ ) -> SequenceData:
184
+ """Create dummy sequence data for XTTS profiling."""
185
+ # Calculate audio token space needed
186
+ audio_len_tokens = math.ceil(_AUDIO_TOKENS_PER_SECOND * 5) # Assume 5s per chunk
187
+ audio_placeholder = array(
188
+ VLLM_TOKEN_ID_ARRAY_TYPE,
189
+ [_AUDIO_PLACEHOLDER_TOKEN]
190
+ ) * audio_len_tokens
191
+
192
+ # Add separator between chunks
193
+ audio_token_ids = (audio_placeholder + array(VLLM_TOKEN_ID_ARRAY_TYPE, [0])) * audio_count
194
+
195
+ # Fill remaining sequence with padding
196
+ other_token_ids = array(VLLM_TOKEN_ID_ARRAY_TYPE, [0]) * (seq_len - len(audio_token_ids))
197
+
198
+ return SequenceData(audio_token_ids + other_token_ids)
199
+
200
+
201
+ def dummy_conditioning_for_xtts(
202
+ ctx: InputContext,
203
+ audio_count: int,
204
+ ) -> dict:
205
+ """Create dummy conditioning data for XTTS."""
206
+ return {
207
+ "audio": [(torch.zeros(80, 1024), 22050) for _ in range(audio_count)]
208
+ }
209
+
210
+
211
+ def dummy_data_for_xtts(
212
+ ctx: InputContext,
213
+ seq_len: int,
214
+ mm_counts: Mapping[str, int],
215
+ ) -> Tuple[SequenceData, dict]:
216
+ """Create complete dummy data for XTTS profiling."""
217
+ audio_count = mm_counts["audio"]
218
+ seq_data = dummy_seq_data_for_xtts(ctx, seq_len, audio_count)
219
+ cond_data = dummy_conditioning_for_xtts(ctx, audio_count)
220
+ return (seq_data, cond_data)
221
+
222
+
223
+ def input_mapper_for_xtts(ctx: InputContext, data: object) -> MultiModalInputs:
224
+ """Map input data to XTTS format."""
225
+ if not isinstance(data, list):
226
+ data = [data]
227
+
228
+ # Each item should be a tuple of (mel_spec, sample_rate)
229
+ for audio_input in data:
230
+ if not isinstance(audio_input, tuple):
231
+ raise NotImplementedError(f"Unsupported data type: {type(audio_input)}")
232
+
233
+ return MultiModalInputs({"cond_latents": data})
234
+
235
+
236
+
237
+ @MULTIMODAL_REGISTRY.register_input_mapper("audio", input_mapper_for_xtts)
238
+ @MULTIMODAL_REGISTRY.register_max_multimodal_tokens("audio", get_xtts_max_audio_tokens)
239
+ @INPUT_REGISTRY.register_dummy_data(dummy_data_for_xtts)
240
+ class XttsGPT(nn.Module, SupportsMultiModal, SupportsPP):
241
+ def __init__(
242
+ self,
243
+ config: PretrainedConfig,
244
+ multimodal_config: MultiModalConfig,
245
+ cache_config: Optional[CacheConfig] = None,
246
+ quant_config: Optional["QuantizationConfig"] = None,
247
+ ):
248
+ super().__init__()
249
+ self.config = config
250
+ self.quant_config = quant_config
251
+
252
+ # XTTS specific components
253
+ self.conditioning_encoder = ConditioningEncoder(
254
+ config.audio_config.mel_channels,
255
+ config.hidden_size,
256
+ num_attn_heads=config.num_attention_heads
257
+ )
258
+
259
+ if config.use_perceiver_resampler:
260
+ self.conditioning_perceiver = PerceiverResampler(
261
+ dim=config.hidden_size,
262
+ depth=2,
263
+ dim_context=config.hidden_size,
264
+ num_latents=32,
265
+ dim_head=64,
266
+ heads=8,
267
+ ff_mult=4,
268
+ use_flash_attn=False,
269
+ )
270
+
271
+ # Core GPT components following VLLM pattern
272
+ self.gpt = XttsGPT2Model(
273
+ config,
274
+ cache_config,
275
+ quant_config,
276
+ prefix="gpt"
277
+ )
278
+
279
+ # Prediction heads
280
+ self.text_head = ColumnParallelLinear(
281
+ config.hidden_size,
282
+ config.vocab_size,
283
+ bias=False,
284
+ quant_config=quant_config,
285
+ prefix="text_head"
286
+ )
287
+
288
+ self.mel_head = ColumnParallelLinear(
289
+ config.hidden_size,
290
+ config.num_audio_tokens,
291
+ bias=False,
292
+ quant_config=quant_config,
293
+ prefix="mel_head"
294
+ )
295
+
296
+ self.sampler = Sampler()
297
+
298
+ def get_style_emb(self, cond_input: torch.Tensor, return_latent: bool = False) -> torch.Tensor:
299
+ """Get conditioning embeddings from mel spectrograms."""
300
+ if not return_latent:
301
+ if cond_input.ndim == 4:
302
+ cond_input = cond_input.squeeze(1)
303
+ conds = self.conditioning_encoder(cond_input)
304
+
305
+ if hasattr(self, 'conditioning_perceiver'):
306
+ conds = self.conditioning_perceiver(
307
+ conds.permute(0, 2, 1)
308
+ ).transpose(1, 2)
309
+ else:
310
+ conds = cond_input.unsqueeze(1)
311
+ return conds
312
+
313
+ def forward(self, input_ids: torch.Tensor, positions: torch.Tensor, kv_caches: List[torch.Tensor],
314
+ attn_metadata: AttentionMetadata, intermediate_tensors: Optional[IntermediateTensors] = None,
315
+ cond_latents: Optional[torch.Tensor] = None ) -> torch.Tensor:
316
+ """Forward pass following VLLM pattern."""
317
+ if cond_latents is not None:
318
+ # Combine conditioning with input embeddings
319
+ input_embeds = self.gpt.get_input_embeddings()(input_ids)
320
+ combined_embeds = torch.cat([cond_latents, input_embeds], dim=1)
321
+ hidden_states = self.gpt(
322
+ inputs_embeds=combined_embeds,
323
+ positions=positions,
324
+ kv_caches=kv_caches,
325
+ attn_metadata=attn_metadata,
326
+ intermediate_tensors=intermediate_tensors,
327
+ )
328
+ else:
329
+ hidden_states = self.gpt(
330
+ input_ids=input_ids,
331
+ positions=positions,
332
+ kv_caches=kv_caches,
333
+ attn_metadata=attn_metadata,
334
+ intermediate_tensors=intermediate_tensors,
335
+ )
336
+ return hidden_states
337
+
338
+ def compute_logits( # useless but kept for compatibility
339
+ self,
340
+ hidden_states: torch.Tensor,
341
+ sampling_metadata: SamplingMetadata,
342
+ ) -> torch.Tensor:
343
+ """Compute output logits."""
344
+ text_logits = self.text_head(hidden_states[sampling_metadata.selected_token_indices])
345
+ mel_logits = self.mel_head(hidden_states[sampling_metadata.selected_token_indices])
346
+ return torch.cat([text_logits, mel_logits], dim=1)
347
+
348
+
349
+ def sample(
350
+ self,
351
+ logits: torch.Tensor,
352
+ sampling_metadata: SamplingMetadata,
353
+ ) -> Optional[SamplerOutput]:
354
+ """Sample next tokens using VLLM sampler."""
355
+ return self.sampler(logits, sampling_metadata)
356
+
357
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
358
+ """Load weights following VLLM pattern."""
359
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
360
+
361
+ for name, loaded_weight in weights:
362
+ if name not in params_dict:
363
+ continue
364
+
365
+ param = params_dict[name]
366
+ if "c_attn" in name or "c_proj" in name or "c_fc" in name:
367
+ if name.endswith(".weight"):
368
+ loaded_weight = loaded_weight.t()
369
+
370
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
371
+ weight_loader(param, loaded_weight)
372
+
373
+
374
+ class XttsGPT2Model(nn.Module):
375
+ """VLLM-style implementation of GPT2 core architecture."""
376
+
377
+ def __init__(
378
+ self,
379
+ config: PretrainedConfig,
380
+ cache_config: Optional[CacheConfig] = None,
381
+ quant_config: Optional[QuantizationConfig] = None,
382
+ prefix: str = "",
383
+ ):
384
+ super().__init__()
385
+ self.config = config
386
+
387
+ self.text_embedding = VocabParallelEmbedding(
388
+ config.number_text_tokens,
389
+ config.hidden_size
390
+ )
391
+ self.mel_embedding = VocabParallelEmbedding(
392
+ config.num_audio_tokens,
393
+ config.hidden_size
394
+ )
395
+
396
+ self.text_pos_embedding = (
397
+ LearnedPositionEmbeddings(
398
+ config.max_text_tokens + 2,
399
+ config.hidden_size
400
+ )
401
+ if config.max_audio_tokens != -1
402
+ else functools.partial(config.null_position_embeddings, dim=config.hidden_size)
403
+ )
404
+
405
+ self.mel_pos_embedding = (
406
+ LearnedPositionEmbeddings(
407
+ config.max_audio_tokens + 3,
408
+ config.hidden_size
409
+ )
410
+ if config.max_audio_tokens != -1
411
+ else functools.partial(config.null_position_embeddings, dim=config.hidden_size)
412
+ )
413
+
414
+ self.h = nn.ModuleList([
415
+ GPT2Block(
416
+ config,
417
+ cache_config,
418
+ quant_config,
419
+ prefix=f"{prefix}.h.{i}"
420
+ ) for i in range(config.num_hidden_layers)
421
+ ])
422
+
423
+ self.ln_f = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
424
+
425
+ def get_input_embeddings(self):
426
+ return self.text_embedding
427
+
428
+ def forward(
429
+ self,
430
+ input_ids: Optional[torch.Tensor] = None,
431
+ positions: Optional[torch.Tensor] = None,
432
+ inputs_embeds: Optional[torch.Tensor] = None,
433
+ kv_caches: List[torch.Tensor] = None,
434
+ attn_metadata: AttentionMetadata = None,
435
+ intermediate_tensors: Optional[IntermediateTensors] = None,
436
+ ) -> Union[torch.Tensor, IntermediateTensors]:
437
+ if get_pp_group().is_first_rank:
438
+ if inputs_embeds is None:
439
+ inputs_embeds = self.text_embedding(input_ids)
440
+ hidden_states = inputs_embeds
441
+
442
+ if positions is not None:
443
+ position_embeds = self.text_pos_embedding(positions)
444
+ hidden_states = hidden_states + position_embeds
445
+ else:
446
+ assert intermediate_tensors is not None
447
+ hidden_states = intermediate_tensors["hidden_states"]
448
+
449
+ for i, block in enumerate(self.h):
450
+ hidden_states = block(
451
+ hidden_states,
452
+ kv_caches[i],
453
+ attn_metadata
454
+ )
455
+
456
+ if not get_pp_group().is_last_rank:
457
+ return IntermediateTensors({"hidden_states": hidden_states})
458
+
459
+ hidden_states = self.ln_f(hidden_states)
460
+ return hidden_states