Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import torch
|
| 3 |
import numpy as np
|
| 4 |
import re
|
| 5 |
import soundfile as sf
|
|
@@ -9,90 +8,62 @@ import nltk
|
|
| 9 |
from nltk.tokenize import sent_tokenize
|
| 10 |
import warnings
|
| 11 |
import time
|
| 12 |
-
from
|
| 13 |
-
from datasets import load_dataset
|
| 14 |
|
| 15 |
warnings.filterwarnings("ignore")
|
| 16 |
|
| 17 |
-
# Download required NLTK data
|
| 18 |
try:
|
| 19 |
nltk.data.find('tokenizers/punkt')
|
| 20 |
-
nltk.data.find('tokenizers/punkt_tab') # This is the missing one!
|
| 21 |
except LookupError:
|
| 22 |
-
nltk.download(
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
class LongFormTTS:
|
| 26 |
def __init__(self):
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
print("Loading SpeechT5 TTS...")
|
| 31 |
-
self.processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
|
| 32 |
-
self.model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
|
| 33 |
-
self.vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
|
| 34 |
-
# Load speaker embeddings
|
| 35 |
-
print("Loading speaker embeddings...")
|
| 36 |
-
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
|
| 37 |
-
# Use a different speaker embedding for more variety
|
| 38 |
-
self.speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
|
| 39 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 40 |
-
self.model = self.model.to(self.device)
|
| 41 |
-
self.vocoder = self.vocoder.to(self.device)
|
| 42 |
-
self.speaker_embeddings = self.speaker_embeddings.to(self.device)
|
| 43 |
-
print("β
SpeechT5 loaded successfully!")
|
| 44 |
-
except Exception as e:
|
| 45 |
-
print(f"β Failed to load SpeechT5: {e}")
|
| 46 |
-
raise Exception(f"TTS model loading failed: {e}")
|
| 47 |
|
| 48 |
def preprocess_text(self, text):
|
| 49 |
"""Clean and prepare text for TTS"""
|
| 50 |
-
# Remove extra whitespace
|
| 51 |
text = re.sub(r'\s+', ' ', text.strip())
|
| 52 |
-
# Handle common abbreviations
|
| 53 |
abbreviations = {
|
| 54 |
-
'Dr.': 'Doctor',
|
| 55 |
-
'
|
| 56 |
-
'
|
| 57 |
-
'
|
| 58 |
-
'
|
| 59 |
-
'
|
| 60 |
-
'
|
| 61 |
-
'e.g.': 'for example',
|
| 62 |
-
'i.e.': 'that is',
|
| 63 |
-
'St.': 'Street',
|
| 64 |
-
'Ave.': 'Avenue',
|
| 65 |
-
'Blvd.': 'Boulevard',
|
| 66 |
-
'Inc.': 'Incorporated',
|
| 67 |
-
'Corp.': 'Corporation',
|
| 68 |
-
'Ltd.': 'Limited',
|
| 69 |
-
'U.S.': 'United States',
|
| 70 |
-
'U.K.': 'United Kingdom',
|
| 71 |
-
'Ph.D.': 'PhD',
|
| 72 |
-
'M.D.': 'MD',
|
| 73 |
}
|
| 74 |
for abbr, full in abbreviations.items():
|
| 75 |
text = text.replace(abbr, full)
|
| 76 |
-
# Convert numbers to words (enhanced)
|
| 77 |
text = re.sub(r'\b(\d{1,4})\b', lambda m: self.number_to_words(int(m.group())), text)
|
| 78 |
-
# Handle years differently (keep as numbers if between 1000-2100)
|
| 79 |
text = re.sub(r'\b(1[0-9]{3}|20[0-9]{2}|2100)\b', lambda m: m.group(), text)
|
| 80 |
-
# Clean up problematic characters but keep essential punctuation
|
| 81 |
text = re.sub(r'[^\w\s\.,!?;:\-\(\)\'"]', ' ', text)
|
| 82 |
-
text = re.sub(r'\s+', ' ', text)
|
| 83 |
return text.strip()
|
| 84 |
|
| 85 |
def number_to_words(self, num):
|
| 86 |
-
"""Convert numbers to words"""
|
| 87 |
-
if num == 0:
|
| 88 |
-
return "zero"
|
| 89 |
-
# Keep larger numbers as digits to avoid very long text
|
| 90 |
-
if num > 9999:
|
| 91 |
-
return str(num)
|
| 92 |
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
|
| 93 |
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
|
| 94 |
"sixteen", "seventeen", "eighteen", "nineteen"]
|
| 95 |
-
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
|
|
|
|
|
|
|
|
|
|
| 96 |
if num < 10:
|
| 97 |
return ones[num]
|
| 98 |
elif num < 20:
|
|
@@ -100,7 +71,7 @@ class LongFormTTS:
|
|
| 100 |
elif num < 100:
|
| 101 |
return tens[num // 10] + ("" if num % 10 == 0 else " " + ones[num % 10])
|
| 102 |
elif num < 1000:
|
| 103 |
-
return ones[num // 100] + " hundred" + ("
|
| 104 |
else:
|
| 105 |
thousands = num // 1000
|
| 106 |
remainder = num % 1000
|
|
@@ -109,102 +80,54 @@ class LongFormTTS:
|
|
| 109 |
result += " " + self.number_to_words(remainder)
|
| 110 |
return result
|
| 111 |
|
| 112 |
-
def chunk_text(self, text, max_length=
|
| 113 |
-
"""Split text into manageable chunks"""
|
| 114 |
sentences = sent_tokenize(text)
|
| 115 |
chunks = []
|
| 116 |
current_chunk = ""
|
| 117 |
for sentence in sentences:
|
| 118 |
-
sentence = sentence.strip()
|
| 119 |
-
if not sentence:
|
| 120 |
-
continue
|
| 121 |
-
# If adding this sentence would exceed limit
|
| 122 |
if len(current_chunk + " " + sentence) > max_length:
|
| 123 |
-
# Save current chunk if it exists
|
| 124 |
if current_chunk:
|
| 125 |
chunks.append(current_chunk.strip())
|
| 126 |
-
|
| 127 |
-
if len(sentence) > max_length:
|
| 128 |
-
words = sentence.split()
|
| 129 |
-
temp_chunk = ""
|
| 130 |
-
for word in words:
|
| 131 |
-
if len(temp_chunk + " " + word) > max_length:
|
| 132 |
-
if temp_chunk:
|
| 133 |
-
chunks.append(temp_chunk.strip())
|
| 134 |
-
temp_chunk = word
|
| 135 |
-
else:
|
| 136 |
-
# Single word too long, just add it
|
| 137 |
-
chunks.append(word)
|
| 138 |
-
else:
|
| 139 |
-
temp_chunk = temp_chunk + " " + word if temp_chunk else word
|
| 140 |
-
current_chunk = temp_chunk
|
| 141 |
-
else:
|
| 142 |
-
current_chunk = sentence
|
| 143 |
else:
|
| 144 |
current_chunk = current_chunk + " " + sentence if current_chunk else sentence
|
| 145 |
-
# Add the last chunk
|
| 146 |
if current_chunk:
|
| 147 |
chunks.append(current_chunk.strip())
|
| 148 |
return [chunk for chunk in chunks if chunk.strip()]
|
| 149 |
|
| 150 |
-
def generate_speech_chunk(self, text_chunk):
|
| 151 |
-
"""Generate speech for a single chunk"""
|
| 152 |
try:
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
with torch.no_grad():
|
| 156 |
-
speech = self.model.generate_speech(
|
| 157 |
-
inputs["input_ids"],
|
| 158 |
-
self.speaker_embeddings,
|
| 159 |
-
vocoder=self.vocoder
|
| 160 |
-
)
|
| 161 |
-
# Convert to numpy and move to CPU
|
| 162 |
-
if isinstance(speech, torch.Tensor):
|
| 163 |
-
speech = speech.cpu().numpy()
|
| 164 |
-
return speech
|
| 165 |
except Exception as e:
|
| 166 |
print(f"Error generating speech for chunk: {e}")
|
| 167 |
-
print(f"Chunk text: {text_chunk}")
|
| 168 |
return None
|
| 169 |
|
| 170 |
-
def generate_long_speech(self, text, progress_callback=None):
|
| 171 |
-
"""Generate speech for long text"""
|
| 172 |
-
# Preprocess text
|
| 173 |
processed_text = self.preprocess_text(text)
|
| 174 |
-
print(f"Original length: {len(text)}, Processed length: {len(processed_text)}")
|
| 175 |
-
# Split into chunks
|
| 176 |
chunks = self.chunk_text(processed_text)
|
| 177 |
print(f"Split into {len(chunks)} chunks")
|
| 178 |
-
if not chunks:
|
| 179 |
-
return None, None
|
| 180 |
-
# Generate speech for each chunk
|
| 181 |
audio_segments = []
|
| 182 |
-
|
|
|
|
| 183 |
for i, chunk in enumerate(chunks):
|
| 184 |
if progress_callback:
|
| 185 |
progress_callback(f"Processing chunk {i+1}/{len(chunks)}: {chunk[:40]}{'...' if len(chunk) > 40 else ''}")
|
| 186 |
print(f"Processing chunk {i+1}: {chunk}")
|
| 187 |
-
audio_chunk = self.generate_speech_chunk(chunk)
|
| 188 |
-
if audio_chunk is not None
|
| 189 |
-
|
| 190 |
-
if len(audio_chunk.shape) > 1:
|
| 191 |
-
audio_chunk = np.mean(audio_chunk, axis=0)
|
| 192 |
-
audio_segments.append(audio_chunk)
|
| 193 |
-
# Add pause between chunks (400ms)
|
| 194 |
-
pause_samples = int(0.4 * sample_rate)
|
| 195 |
-
silence = np.zeros(pause_samples)
|
| 196 |
audio_segments.append(silence)
|
| 197 |
-
# Small delay to prevent overwhelming the system
|
| 198 |
time.sleep(0.1)
|
|
|
|
| 199 |
if not audio_segments:
|
| 200 |
return None, None
|
| 201 |
-
|
| 202 |
final_audio = np.concatenate(audio_segments)
|
| 203 |
-
# Normalize audio to prevent clipping
|
| 204 |
max_val = np.max(np.abs(final_audio))
|
| 205 |
if max_val > 0:
|
| 206 |
final_audio = final_audio / max_val * 0.95
|
| 207 |
-
return final_audio, sample_rate
|
| 208 |
|
| 209 |
|
| 210 |
# Global TTS system
|
|
@@ -217,43 +140,37 @@ except Exception as e:
|
|
| 217 |
tts_system = None
|
| 218 |
|
| 219 |
|
| 220 |
-
def text_to_speech_interface(text, progress=gr.Progress()):
|
| 221 |
-
"""Main Gradio interface function"""
|
| 222 |
if tts_system is None:
|
| 223 |
return None, "β TTS system is not available. Please check the logs."
|
| 224 |
if not text or not text.strip():
|
| 225 |
return None, "β οΈ Please enter some text to convert to speech."
|
| 226 |
-
# Text length check
|
| 227 |
if len(text) > 50000:
|
| 228 |
-
return None, "β οΈ Text is too long. Please keep it under 50,000 characters
|
| 229 |
|
| 230 |
def progress_callback(message):
|
| 231 |
progress(0.5, desc=message)
|
| 232 |
|
| 233 |
try:
|
| 234 |
progress(0.1, desc="π Starting text-to-speech conversion...")
|
| 235 |
-
|
| 236 |
-
audio
|
| 237 |
-
|
| 238 |
-
return None, "β Failed to generate audio. Please try with different text."
|
| 239 |
progress(0.9, desc="πΎ Saving audio file...")
|
| 240 |
-
|
| 241 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
| 242 |
sf.write(tmp_file.name, audio, sample_rate)
|
| 243 |
audio_path = tmp_file.name
|
| 244 |
progress(1.0, desc="β
Complete!")
|
| 245 |
duration = len(audio) / sample_rate
|
| 246 |
return audio_path, f"β
Generated {duration:.1f} seconds of audio successfully!"
|
| 247 |
except Exception as e:
|
| 248 |
-
|
| 249 |
-
print(f"TTS Error: {e}")
|
| 250 |
-
return None, error_msg
|
| 251 |
|
| 252 |
|
| 253 |
# Create Gradio interface
|
| 254 |
def create_interface():
|
| 255 |
with gr.Blocks(
|
| 256 |
-
title="π€ Long-Form Text-to-Speech",
|
| 257 |
theme=gr.themes.Soft(),
|
| 258 |
css="""
|
| 259 |
.main-header {
|
|
@@ -264,40 +181,24 @@ def create_interface():
|
|
| 264 |
-webkit-text-fill-color: transparent;
|
| 265 |
background-clip: text;
|
| 266 |
}
|
| 267 |
-
.feature-box {
|
| 268 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 269 |
-
color: white;
|
| 270 |
-
padding: 1.5rem;
|
| 271 |
-
border-radius: 15px;
|
| 272 |
-
margin: 1rem 0;
|
| 273 |
-
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
|
| 274 |
-
}
|
| 275 |
-
.status-box {
|
| 276 |
-
padding: 1rem;
|
| 277 |
-
border-radius: 10px;
|
| 278 |
-
margin: 1rem 0;
|
| 279 |
-
border-left: 4px solid #28a745;
|
| 280 |
-
background: #f8f9fa;
|
| 281 |
-
}
|
| 282 |
"""
|
| 283 |
) as demo:
|
| 284 |
gr.HTML("""
|
| 285 |
<div class="main-header">
|
| 286 |
<h1>π€ Long-Form Text-to-Speech Generator</h1>
|
| 287 |
-
<p style="color: #666; font-size: 1.1em;">
|
| 288 |
</div>
|
| 289 |
""")
|
| 290 |
-
# System status
|
| 291 |
if tts_system:
|
| 292 |
gr.HTML("""
|
| 293 |
-
<div
|
| 294 |
<h4>π’ System Ready</h4>
|
| 295 |
-
<p>Using <strong>
|
| 296 |
</div>
|
| 297 |
""")
|
| 298 |
else:
|
| 299 |
gr.HTML("""
|
| 300 |
-
<div
|
| 301 |
<h4>π΄ System Error</h4>
|
| 302 |
<p>TTS system failed to initialize. Please refresh the page.</p>
|
| 303 |
</div>
|
|
@@ -312,95 +213,52 @@ def create_interface():
|
|
| 312 |
info="Supports any length text with automatic chunking for optimal quality"
|
| 313 |
)
|
| 314 |
char_count = gr.HTML("<span style='color: #666;'>Character count: 0 / 50,000</span>")
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
variant="primary",
|
| 318 |
-
size="lg",
|
| 319 |
-
scale=1
|
| 320 |
-
)
|
| 321 |
with gr.Column(scale=1):
|
| 322 |
gr.HTML("""
|
| 323 |
-
<div
|
| 324 |
<h3>β¨ Key Features</h3>
|
| 325 |
<ul style="margin: 0; padding-left: 1.2em;">
|
| 326 |
<li>π Handles long texts</li>
|
| 327 |
-
<li>π
|
| 328 |
<li>β‘ Smart text processing</li>
|
| 329 |
<li>π§ Auto chunking</li>
|
| 330 |
-
<li
|
| 331 |
-
<li>π± Mobile friendly</li>
|
| 332 |
-
<li>π΅ High quality audio</li>
|
| 333 |
</ul>
|
| 334 |
</div>
|
| 335 |
""")
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
interactive=False,
|
| 340 |
-
value="Ready to generate speech! Enter some text above."
|
| 341 |
-
)
|
| 342 |
-
audio_output = gr.Audio(
|
| 343 |
-
label="π Generated Speech",
|
| 344 |
-
type="filepath",
|
| 345 |
-
show_download_button=True
|
| 346 |
-
)
|
| 347 |
-
# Character counter
|
| 348 |
def update_char_count(text):
|
| 349 |
count = len(text) if text else 0
|
| 350 |
color = "#28a745" if count <= 50000 else "#dc3545"
|
| 351 |
return f'<span style="color: {color};">Character count: {count:,} / 50,000</span>'
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
outputs=[char_count]
|
| 356 |
-
)
|
| 357 |
-
# Generate button click
|
| 358 |
generate_btn.click(
|
| 359 |
fn=text_to_speech_interface,
|
| 360 |
-
inputs=[text_input],
|
| 361 |
outputs=[audio_output, status_output],
|
| 362 |
show_progress=True
|
| 363 |
)
|
| 364 |
-
|
| 365 |
gr.Examples(
|
| 366 |
examples=[
|
| 367 |
-
["Hello! Welcome to our advanced text-to-speech system. This technology can convert any written text into natural-sounding human speech."],
|
| 368 |
-
["The quick brown fox jumps over the lazy dog. This pangram contains every letter of the English alphabet and is perfect for testing speech synthesis."],
|
| 369 |
-
["
|
| 370 |
-
["Artificial intelligence has revolutionized many aspects of our daily lives. From voice assistants to recommendation systems, AI technologies are becoming increasingly sophisticated and accessible to everyone."],
|
| 371 |
-
["Once upon a time, in a land far away, there lived a wise old wizard who possessed the power to transform written words into spoken language. This magical ability brought stories to life for all who listened."]
|
| 372 |
],
|
| 373 |
-
inputs=[text_input],
|
| 374 |
label="π Try These Examples"
|
| 375 |
)
|
| 376 |
-
|
| 377 |
-
gr.HTML("""
|
| 378 |
-
<div style="margin-top: 2rem; padding: 1.5rem; background: #f8f9fa; border-radius: 10px; border-left: 4px solid #007bff;">
|
| 379 |
-
<h4>π§ How It Works</h4>
|
| 380 |
-
<ol style="margin: 0.5rem 0; padding-left: 1.5rem;">
|
| 381 |
-
<li><strong>Text Processing:</strong> Automatically cleans and normalizes your input text</li>
|
| 382 |
-
<li><strong>Smart Chunking:</strong> Splits long text at natural sentence boundaries</li>
|
| 383 |
-
<li><strong>Neural Synthesis:</strong> Uses Microsoft's SpeechT5 model for speech generation</li>
|
| 384 |
-
<li><strong>Audio Assembly:</strong> Combines all chunks with natural pauses</li>
|
| 385 |
-
</ol>
|
| 386 |
-
<h4 style="margin-top: 1rem;">π‘ Tips for Best Results</h4>
|
| 387 |
-
<ul style="margin: 0.5rem 0; padding-left: 1.5rem;">
|
| 388 |
-
<li>Use proper punctuation for natural pauses and intonation</li>
|
| 389 |
-
<li>Spell out abbreviations if you want them pronounced fully</li>
|
| 390 |
-
<li>Well-formatted text produces the most natural speech</li>
|
| 391 |
-
<li>The system automatically handles common abbreviations and numbers</li>
|
| 392 |
-
</ul>
|
| 393 |
-
</div>
|
| 394 |
-
""")
|
| 395 |
return demo
|
| 396 |
|
| 397 |
|
| 398 |
# Launch the application
|
| 399 |
if __name__ == "__main__":
|
| 400 |
demo = create_interface()
|
| 401 |
-
demo.launch(
|
| 402 |
-
server_name="0.0.0.0",
|
| 403 |
-
server_port=7860,
|
| 404 |
-
share=True,
|
| 405 |
-
ssr_mode=False
|
| 406 |
-
)
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import re
|
| 4 |
import soundfile as sf
|
|
|
|
| 8 |
from nltk.tokenize import sent_tokenize
|
| 9 |
import warnings
|
| 10 |
import time
|
| 11 |
+
from TTS.api import TTS
|
|
|
|
| 12 |
|
| 13 |
warnings.filterwarnings("ignore")
|
| 14 |
|
| 15 |
+
# Download required NLTK data
|
| 16 |
try:
|
| 17 |
nltk.data.find('tokenizers/punkt')
|
|
|
|
| 18 |
except LookupError:
|
| 19 |
+
nltk.download('punkt')
|
| 20 |
|
| 21 |
+
# Load Coqui TTS model
|
| 22 |
+
print("π Loading Coqui TTS models...")
|
| 23 |
+
try:
|
| 24 |
+
# This will download the model automatically if not found
|
| 25 |
+
tts = TTS(model_name="tts_models/en/vctk/vits", progress_bar=False, gpu=False)
|
| 26 |
+
print("β
Coqui TTS loaded successfully!")
|
| 27 |
+
speakers = tts.speakers
|
| 28 |
+
print(f"Available Speakers: {speakers}")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"β Failed to load Coqui TTS: {e}")
|
| 31 |
+
tts = None
|
| 32 |
+
speakers = []
|
| 33 |
|
| 34 |
class LongFormTTS:
|
| 35 |
def __init__(self):
|
| 36 |
+
self.tts = tts
|
| 37 |
+
self.speakers = speakers
|
| 38 |
+
self.sample_rate = 22050 # Coqui default sample rate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
def preprocess_text(self, text):
|
| 41 |
"""Clean and prepare text for TTS"""
|
|
|
|
| 42 |
text = re.sub(r'\s+', ' ', text.strip())
|
|
|
|
| 43 |
abbreviations = {
|
| 44 |
+
'Dr.': 'Doctor', 'Mr.': 'Mister', 'Mrs.': 'Missus',
|
| 45 |
+
'Ms.': 'Miss', 'Prof.': 'Professor', 'etc.': 'etcetera',
|
| 46 |
+
'vs.': 'versus', 'e.g.': 'for example', 'i.e.': 'that is',
|
| 47 |
+
'St.': 'Street', 'Ave.': 'Avenue', 'Blvd.': 'Boulevard',
|
| 48 |
+
'Inc.': 'Incorporated', 'Corp.': 'Corporation', 'Ltd.': 'Limited',
|
| 49 |
+
'U.S.': 'United States', 'U.K.': 'United Kingdom',
|
| 50 |
+
'Ph.D.': 'PhD', 'M.D.': 'MD'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
}
|
| 52 |
for abbr, full in abbreviations.items():
|
| 53 |
text = text.replace(abbr, full)
|
|
|
|
| 54 |
text = re.sub(r'\b(\d{1,4})\b', lambda m: self.number_to_words(int(m.group())), text)
|
|
|
|
| 55 |
text = re.sub(r'\b(1[0-9]{3}|20[0-9]{2}|2100)\b', lambda m: m.group(), text)
|
|
|
|
| 56 |
text = re.sub(r'[^\w\s\.,!?;:\-\(\)\'"]', ' ', text)
|
|
|
|
| 57 |
return text.strip()
|
| 58 |
|
| 59 |
def number_to_words(self, num):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
|
| 61 |
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
|
| 62 |
"sixteen", "seventeen", "eighteen", "nineteen"]
|
| 63 |
+
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
|
| 64 |
+
"eighty", "ninety"]
|
| 65 |
+
if num == 0:
|
| 66 |
+
return "zero"
|
| 67 |
if num < 10:
|
| 68 |
return ones[num]
|
| 69 |
elif num < 20:
|
|
|
|
| 71 |
elif num < 100:
|
| 72 |
return tens[num // 10] + ("" if num % 10 == 0 else " " + ones[num % 10])
|
| 73 |
elif num < 1000:
|
| 74 |
+
return ones[num // 100] + " hundred" + (" " + self.number_to_words(num % 100)).strip()
|
| 75 |
else:
|
| 76 |
thousands = num // 1000
|
| 77 |
remainder = num % 1000
|
|
|
|
| 80 |
result += " " + self.number_to_words(remainder)
|
| 81 |
return result
|
| 82 |
|
| 83 |
+
def chunk_text(self, text, max_length=200):
|
|
|
|
| 84 |
sentences = sent_tokenize(text)
|
| 85 |
chunks = []
|
| 86 |
current_chunk = ""
|
| 87 |
for sentence in sentences:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
if len(current_chunk + " " + sentence) > max_length:
|
|
|
|
| 89 |
if current_chunk:
|
| 90 |
chunks.append(current_chunk.strip())
|
| 91 |
+
current_chunk = sentence
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
else:
|
| 93 |
current_chunk = current_chunk + " " + sentence if current_chunk else sentence
|
|
|
|
| 94 |
if current_chunk:
|
| 95 |
chunks.append(current_chunk.strip())
|
| 96 |
return [chunk for chunk in chunks if chunk.strip()]
|
| 97 |
|
| 98 |
+
def generate_speech_chunk(self, text_chunk, speaker):
|
|
|
|
| 99 |
try:
|
| 100 |
+
audio = self.tts.tts(text=text_chunk, speaker=speaker)
|
| 101 |
+
return audio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
except Exception as e:
|
| 103 |
print(f"Error generating speech for chunk: {e}")
|
|
|
|
| 104 |
return None
|
| 105 |
|
| 106 |
+
def generate_long_speech(self, text, speaker=None, progress_callback=None):
|
|
|
|
|
|
|
| 107 |
processed_text = self.preprocess_text(text)
|
|
|
|
|
|
|
| 108 |
chunks = self.chunk_text(processed_text)
|
| 109 |
print(f"Split into {len(chunks)} chunks")
|
|
|
|
|
|
|
|
|
|
| 110 |
audio_segments = []
|
| 111 |
+
silence = np.zeros(int(0.4 * self.sample_rate), dtype=np.float32)
|
| 112 |
+
|
| 113 |
for i, chunk in enumerate(chunks):
|
| 114 |
if progress_callback:
|
| 115 |
progress_callback(f"Processing chunk {i+1}/{len(chunks)}: {chunk[:40]}{'...' if len(chunk) > 40 else ''}")
|
| 116 |
print(f"Processing chunk {i+1}: {chunk}")
|
| 117 |
+
audio_chunk = self.generate_speech_chunk(chunk, speaker)
|
| 118 |
+
if audio_chunk is not None:
|
| 119 |
+
audio_segments.append(np.array(audio_chunk))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
audio_segments.append(silence)
|
|
|
|
| 121 |
time.sleep(0.1)
|
| 122 |
+
|
| 123 |
if not audio_segments:
|
| 124 |
return None, None
|
| 125 |
+
|
| 126 |
final_audio = np.concatenate(audio_segments)
|
|
|
|
| 127 |
max_val = np.max(np.abs(final_audio))
|
| 128 |
if max_val > 0:
|
| 129 |
final_audio = final_audio / max_val * 0.95
|
| 130 |
+
return final_audio, self.sample_rate
|
| 131 |
|
| 132 |
|
| 133 |
# Global TTS system
|
|
|
|
| 140 |
tts_system = None
|
| 141 |
|
| 142 |
|
| 143 |
+
def text_to_speech_interface(text, speaker="p225", progress=gr.Progress()):
|
|
|
|
| 144 |
if tts_system is None:
|
| 145 |
return None, "β TTS system is not available. Please check the logs."
|
| 146 |
if not text or not text.strip():
|
| 147 |
return None, "β οΈ Please enter some text to convert to speech."
|
|
|
|
| 148 |
if len(text) > 50000:
|
| 149 |
+
return None, "β οΈ Text is too long. Please keep it under 50,000 characters."
|
| 150 |
|
| 151 |
def progress_callback(message):
|
| 152 |
progress(0.5, desc=message)
|
| 153 |
|
| 154 |
try:
|
| 155 |
progress(0.1, desc="π Starting text-to-speech conversion...")
|
| 156 |
+
audio, sample_rate = tts_system.generate_long_speech(text, speaker, progress_callback)
|
| 157 |
+
if audio is None:
|
| 158 |
+
return None, "β Failed to generate audio."
|
|
|
|
| 159 |
progress(0.9, desc="πΎ Saving audio file...")
|
| 160 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
|
|
|
|
| 161 |
sf.write(tmp_file.name, audio, sample_rate)
|
| 162 |
audio_path = tmp_file.name
|
| 163 |
progress(1.0, desc="β
Complete!")
|
| 164 |
duration = len(audio) / sample_rate
|
| 165 |
return audio_path, f"β
Generated {duration:.1f} seconds of audio successfully!"
|
| 166 |
except Exception as e:
|
| 167 |
+
return None, f"β Error: {str(e)}"
|
|
|
|
|
|
|
| 168 |
|
| 169 |
|
| 170 |
# Create Gradio interface
|
| 171 |
def create_interface():
|
| 172 |
with gr.Blocks(
|
| 173 |
+
title="π€ Long-Form Text-to-Speech (Coqui)",
|
| 174 |
theme=gr.themes.Soft(),
|
| 175 |
css="""
|
| 176 |
.main-header {
|
|
|
|
| 181 |
-webkit-text-fill-color: transparent;
|
| 182 |
background-clip: text;
|
| 183 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
"""
|
| 185 |
) as demo:
|
| 186 |
gr.HTML("""
|
| 187 |
<div class="main-header">
|
| 188 |
<h1>π€ Long-Form Text-to-Speech Generator</h1>
|
| 189 |
+
<p style="color: #666; font-size: 1.1em;">Choose a voice and transform any text into expressive human-like speech</p>
|
| 190 |
</div>
|
| 191 |
""")
|
|
|
|
| 192 |
if tts_system:
|
| 193 |
gr.HTML("""
|
| 194 |
+
<div style="padding: 1rem; border-radius: 10px; margin: 1rem 0; border-left: 4px solid #28a745; background: #f8f9fa;">
|
| 195 |
<h4>π’ System Ready</h4>
|
| 196 |
+
<p>Using <strong>Coqui TTS</strong> with multiple speaker support</p>
|
| 197 |
</div>
|
| 198 |
""")
|
| 199 |
else:
|
| 200 |
gr.HTML("""
|
| 201 |
+
<div style="padding: 1rem; border-radius: 10px; margin: 1rem 0; border-left: 4px solid #dc3545; background: #f8d7da;">
|
| 202 |
<h4>π΄ System Error</h4>
|
| 203 |
<p>TTS system failed to initialize. Please refresh the page.</p>
|
| 204 |
</div>
|
|
|
|
| 213 |
info="Supports any length text with automatic chunking for optimal quality"
|
| 214 |
)
|
| 215 |
char_count = gr.HTML("<span style='color: #666;'>Character count: 0 / 50,000</span>")
|
| 216 |
+
speaker_dropdown = gr.Dropdown(choices=tts_system.speakers if tts_system else [], value="p225", label="π£οΈ Choose Voice")
|
| 217 |
+
generate_btn = gr.Button("π― Generate Speech", variant="primary", size="lg", scale=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
with gr.Column(scale=1):
|
| 219 |
gr.HTML("""
|
| 220 |
+
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 1.5rem; border-radius: 15px; margin: 1rem 0; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
|
| 221 |
<h3>β¨ Key Features</h3>
|
| 222 |
<ul style="margin: 0; padding-left: 1.2em;">
|
| 223 |
<li>π Handles long texts</li>
|
| 224 |
+
<li>π Multiple human voices</li>
|
| 225 |
<li>β‘ Smart text processing</li>
|
| 226 |
<li>π§ Auto chunking</li>
|
| 227 |
+
<li>π΅ Natural-sounding speech</li>
|
|
|
|
|
|
|
| 228 |
</ul>
|
| 229 |
</div>
|
| 230 |
""")
|
| 231 |
+
status_output = gr.Textbox(label="π Status", interactive=False, value="Ready to generate speech! Enter some text above.")
|
| 232 |
+
audio_output = gr.Audio(label="π Generated Speech", type="filepath", show_download_button=True)
|
| 233 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
def update_char_count(text):
|
| 235 |
count = len(text) if text else 0
|
| 236 |
color = "#28a745" if count <= 50000 else "#dc3545"
|
| 237 |
return f'<span style="color: {color};">Character count: {count:,} / 50,000</span>'
|
| 238 |
+
|
| 239 |
+
text_input.change(fn=update_char_count, inputs=[text_input], outputs=[char_count])
|
| 240 |
+
|
|
|
|
|
|
|
|
|
|
| 241 |
generate_btn.click(
|
| 242 |
fn=text_to_speech_interface,
|
| 243 |
+
inputs=[text_input, speaker_dropdown],
|
| 244 |
outputs=[audio_output, status_output],
|
| 245 |
show_progress=True
|
| 246 |
)
|
| 247 |
+
|
| 248 |
gr.Examples(
|
| 249 |
examples=[
|
| 250 |
+
["Hello! Welcome to our advanced text-to-speech system. This technology can convert any written text into natural-sounding human speech.", "p225"],
|
| 251 |
+
["The quick brown fox jumps over the lazy dog. This pangram contains every letter of the English alphabet and is perfect for testing speech synthesis.", "p226"],
|
| 252 |
+
["Artificial intelligence has revolutionized many aspects of our daily lives.", "p227"],
|
|
|
|
|
|
|
| 253 |
],
|
| 254 |
+
inputs=[text_input, speaker_dropdown],
|
| 255 |
label="π Try These Examples"
|
| 256 |
)
|
| 257 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
return demo
|
| 259 |
|
| 260 |
|
| 261 |
# Launch the application
|
| 262 |
if __name__ == "__main__":
|
| 263 |
demo = create_interface()
|
| 264 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|