Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import re
|
| 4 |
import soundfile as sf
|
|
@@ -8,33 +9,44 @@ import nltk
|
|
| 8 |
from nltk.tokenize import sent_tokenize
|
| 9 |
import warnings
|
| 10 |
import time
|
| 11 |
-
from
|
|
|
|
| 12 |
|
| 13 |
warnings.filterwarnings("ignore")
|
| 14 |
|
| 15 |
# Download required NLTK data including punkt_tab
|
| 16 |
try:
|
| 17 |
nltk.data.find('tokenizers/punkt')
|
| 18 |
-
nltk.data.find('tokenizers/punkt_tab')
|
| 19 |
except LookupError:
|
| 20 |
nltk.download(['punkt', 'punkt_tab'], quiet=True)
|
| 21 |
|
| 22 |
|
| 23 |
class LongFormTTS:
|
| 24 |
def __init__(self):
|
| 25 |
-
print("π Loading
|
| 26 |
try:
|
| 27 |
-
# Load
|
| 28 |
-
|
| 29 |
-
self.
|
| 30 |
-
self.
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
-
print(f"β Failed to load
|
| 35 |
-
|
| 36 |
-
self.speakers = []
|
| 37 |
-
|
| 38 |
|
| 39 |
def preprocess_text(self, text):
|
| 40 |
"""Clean and prepare text for TTS"""
|
|
@@ -68,15 +80,14 @@ class LongFormTTS:
|
|
| 68 |
return text.strip()
|
| 69 |
|
| 70 |
def number_to_words(self, num):
|
| 71 |
-
"""Convert numbers to words"""
|
| 72 |
-
if num == 0:
|
| 73 |
-
return "zero"
|
| 74 |
-
if num > 9999:
|
| 75 |
-
return str(num)
|
| 76 |
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
|
| 77 |
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
|
| 78 |
"sixteen", "seventeen", "eighteen", "nineteen"]
|
| 79 |
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
if num < 10:
|
| 81 |
return ones[num]
|
| 82 |
elif num < 20:
|
|
@@ -84,7 +95,7 @@ class LongFormTTS:
|
|
| 84 |
elif num < 100:
|
| 85 |
return tens[num // 10] + ("" if num % 10 == 0 else " " + ones[num % 10])
|
| 86 |
elif num < 1000:
|
| 87 |
-
return ones[num // 100] + " hundred" + ("
|
| 88 |
else:
|
| 89 |
thousands = num // 1000
|
| 90 |
remainder = num % 1000
|
|
@@ -93,7 +104,7 @@ class LongFormTTS:
|
|
| 93 |
result += " " + self.number_to_words(remainder)
|
| 94 |
return result
|
| 95 |
|
| 96 |
-
def chunk_text(self, text, max_length=
|
| 97 |
"""Split text into manageable chunks"""
|
| 98 |
sentences = sent_tokenize(text)
|
| 99 |
chunks = []
|
|
@@ -126,40 +137,55 @@ class LongFormTTS:
|
|
| 126 |
chunks.append(current_chunk.strip())
|
| 127 |
return [chunk for chunk in chunks if chunk.strip()]
|
| 128 |
|
| 129 |
-
def generate_speech_chunk(self, text_chunk,
|
| 130 |
"""Generate speech for a single chunk"""
|
| 131 |
try:
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
print(f"Error generating speech for chunk: {e}")
|
|
|
|
| 135 |
return None
|
| 136 |
|
| 137 |
-
def generate_long_speech(self, text,
|
| 138 |
"""Generate speech for long text"""
|
| 139 |
processed_text = self.preprocess_text(text)
|
|
|
|
| 140 |
chunks = self.chunk_text(processed_text)
|
| 141 |
print(f"Split into {len(chunks)} chunks")
|
|
|
|
|
|
|
|
|
|
| 142 |
audio_segments = []
|
| 143 |
-
|
| 144 |
-
|
| 145 |
for i, chunk in enumerate(chunks):
|
| 146 |
if progress_callback:
|
| 147 |
progress_callback(f"Processing chunk {i+1}/{len(chunks)}: {chunk[:40]}{'...' if len(chunk) > 40 else ''}")
|
| 148 |
print(f"Processing chunk {i+1}: {chunk}")
|
| 149 |
-
audio_chunk = self.generate_speech_chunk(chunk,
|
| 150 |
-
if audio_chunk is not None:
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
audio_segments.append(silence)
|
| 153 |
time.sleep(0.1)
|
| 154 |
-
|
| 155 |
if not audio_segments:
|
| 156 |
return None, None
|
| 157 |
-
|
| 158 |
final_audio = np.concatenate(audio_segments)
|
| 159 |
max_val = np.max(np.abs(final_audio))
|
| 160 |
if max_val > 0:
|
| 161 |
final_audio = final_audio / max_val * 0.95
|
| 162 |
-
return final_audio,
|
| 163 |
|
| 164 |
|
| 165 |
# Global TTS system
|
|
@@ -172,7 +198,8 @@ except Exception as e:
|
|
| 172 |
tts_system = None
|
| 173 |
|
| 174 |
|
| 175 |
-
def text_to_speech_interface(text, speaker="
|
|
|
|
| 176 |
if tts_system is None:
|
| 177 |
return None, "β TTS system is not available. Please check the logs."
|
| 178 |
if not text or not text.strip():
|
|
@@ -186,23 +213,25 @@ def text_to_speech_interface(text, speaker="p225", progress=gr.Progress()):
|
|
| 186 |
try:
|
| 187 |
progress(0.1, desc="π Starting text-to-speech conversion...")
|
| 188 |
audio, sample_rate = tts_system.generate_long_speech(text, speaker, progress_callback)
|
| 189 |
-
if audio is None:
|
| 190 |
return None, "β Failed to generate audio."
|
| 191 |
progress(0.9, desc="πΎ Saving audio file...")
|
| 192 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".
|
| 193 |
sf.write(tmp_file.name, audio, sample_rate)
|
| 194 |
audio_path = tmp_file.name
|
| 195 |
progress(1.0, desc="β
Complete!")
|
| 196 |
duration = len(audio) / sample_rate
|
| 197 |
return audio_path, f"β
Generated {duration:.1f} seconds of audio successfully!"
|
| 198 |
except Exception as e:
|
| 199 |
-
|
|
|
|
|
|
|
| 200 |
|
| 201 |
|
| 202 |
# Create Gradio interface
|
| 203 |
def create_interface():
|
| 204 |
with gr.Blocks(
|
| 205 |
-
title="π€ Long-Form Text-to-Speech
|
| 206 |
theme=gr.themes.Soft(),
|
| 207 |
css="""
|
| 208 |
.main-header {
|
|
@@ -218,14 +247,15 @@ def create_interface():
|
|
| 218 |
gr.HTML("""
|
| 219 |
<div class="main-header">
|
| 220 |
<h1>π€ Long-Form Text-to-Speech Generator</h1>
|
| 221 |
-
<p style="color: #666; font-size: 1.1em;">
|
| 222 |
</div>
|
| 223 |
""")
|
| 224 |
-
|
|
|
|
| 225 |
gr.HTML("""
|
| 226 |
<div style="padding: 1rem; border-radius: 10px; margin: 1rem 0; border-left: 4px solid #28a745; background: #f8f9fa;">
|
| 227 |
<h4>π’ System Ready</h4>
|
| 228 |
-
<p>Using <strong>
|
| 229 |
</div>
|
| 230 |
""")
|
| 231 |
else:
|
|
@@ -235,7 +265,6 @@ def create_interface():
|
|
| 235 |
<p>TTS system failed to initialize. Please refresh the page.</p>
|
| 236 |
</div>
|
| 237 |
""")
|
| 238 |
-
|
| 239 |
with gr.Row():
|
| 240 |
with gr.Column(scale=2):
|
| 241 |
text_input = gr.Textbox(
|
|
@@ -243,12 +272,12 @@ def create_interface():
|
|
| 243 |
placeholder="Type or paste your text here... (Max 50,000 characters)",
|
| 244 |
lines=10,
|
| 245 |
max_lines=20,
|
| 246 |
-
info="Supports any length text with automatic chunking"
|
| 247 |
)
|
| 248 |
char_count = gr.HTML("<span style='color: #666;'>Character count: 0 / 50,000</span>")
|
| 249 |
speaker_dropdown = gr.Dropdown(
|
| 250 |
-
choices=tts_system.
|
| 251 |
-
value=tts_system.
|
| 252 |
label="π£οΈ Choose Voice"
|
| 253 |
)
|
| 254 |
generate_btn = gr.Button("π― Generate Speech", variant="primary", size="lg", scale=1)
|
|
@@ -262,6 +291,7 @@ def create_interface():
|
|
| 262 |
<li>β‘ Smart text processing</li>
|
| 263 |
<li>π§ Auto chunking</li>
|
| 264 |
<li>π΅ Natural-sounding speech</li>
|
|
|
|
| 265 |
</ul>
|
| 266 |
</div>
|
| 267 |
""")
|
|
@@ -284,9 +314,9 @@ def create_interface():
|
|
| 284 |
|
| 285 |
gr.Examples(
|
| 286 |
examples=[
|
| 287 |
-
["Hello! Welcome to our advanced text-to-speech system.", "
|
| 288 |
-
["The quick brown fox jumps over the lazy dog.", "
|
| 289 |
-
["Artificial intelligence has revolutionized many aspects of our
|
| 290 |
],
|
| 291 |
inputs=[text_input, speaker_dropdown],
|
| 292 |
label="π Try These Examples"
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
import numpy as np
|
| 4 |
import re
|
| 5 |
import soundfile as sf
|
|
|
|
| 9 |
from nltk.tokenize import sent_tokenize
|
| 10 |
import warnings
|
| 11 |
import time
|
| 12 |
+
from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
|
| 13 |
+
from datasets import load_dataset
|
| 14 |
|
| 15 |
warnings.filterwarnings("ignore")
|
| 16 |
|
| 17 |
# Download required NLTK data including punkt_tab
|
| 18 |
try:
|
| 19 |
nltk.data.find('tokenizers/punkt')
|
| 20 |
+
nltk.data.find('tokenizers/punkt_tab')
|
| 21 |
except LookupError:
|
| 22 |
nltk.download(['punkt', 'punkt_tab'], quiet=True)
|
| 23 |
|
| 24 |
|
| 25 |
class LongFormTTS:
|
| 26 |
def __init__(self):
|
| 27 |
+
print("π Loading TTS models...")
|
| 28 |
try:
|
| 29 |
+
# Load SpeechT5 - most reliable for HF Spaces
|
| 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 dataset
|
| 35 |
+
print("Loading speaker embeddings...")
|
| 36 |
+
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
|
| 37 |
+
# Store multiple speakers
|
| 38 |
+
self.speakers = {
|
| 39 |
+
f"Speaker {i+1} ({id})": embeddings_dataset[id]["xvector"]
|
| 40 |
+
for i, id in enumerate([7306, 7339, 7341, 7345, 7367, 7422])
|
| 41 |
+
}
|
| 42 |
+
self.speaker_ids = list(self.speakers.keys())
|
| 43 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 44 |
+
self.model = self.model.to(self.device)
|
| 45 |
+
self.vocoder = self.vocoder.to(self.device)
|
| 46 |
+
print("β
SpeechT5 loaded successfully!")
|
| 47 |
except Exception as e:
|
| 48 |
+
print(f"β Failed to load SpeechT5: {e}")
|
| 49 |
+
raise Exception(f"TTS model loading failed: {e}")
|
|
|
|
|
|
|
| 50 |
|
| 51 |
def preprocess_text(self, text):
|
| 52 |
"""Clean and prepare text for TTS"""
|
|
|
|
| 80 |
return text.strip()
|
| 81 |
|
| 82 |
def number_to_words(self, num):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
|
| 84 |
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
|
| 85 |
"sixteen", "seventeen", "eighteen", "nineteen"]
|
| 86 |
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
|
| 87 |
+
if num == 0:
|
| 88 |
+
return "zero"
|
| 89 |
+
if num > 9999:
|
| 90 |
+
return str(num)
|
| 91 |
if num < 10:
|
| 92 |
return ones[num]
|
| 93 |
elif num < 20:
|
|
|
|
| 95 |
elif num < 100:
|
| 96 |
return tens[num // 10] + ("" if num % 10 == 0 else " " + ones[num % 10])
|
| 97 |
elif num < 1000:
|
| 98 |
+
return ones[num // 100] + " hundred" + (" " + self.number_to_words(num % 100)).strip()
|
| 99 |
else:
|
| 100 |
thousands = num // 1000
|
| 101 |
remainder = num % 1000
|
|
|
|
| 104 |
result += " " + self.number_to_words(remainder)
|
| 105 |
return result
|
| 106 |
|
| 107 |
+
def chunk_text(self, text, max_length=400):
|
| 108 |
"""Split text into manageable chunks"""
|
| 109 |
sentences = sent_tokenize(text)
|
| 110 |
chunks = []
|
|
|
|
| 137 |
chunks.append(current_chunk.strip())
|
| 138 |
return [chunk for chunk in chunks if chunk.strip()]
|
| 139 |
|
| 140 |
+
def generate_speech_chunk(self, text_chunk, speaker_embedding):
|
| 141 |
"""Generate speech for a single chunk"""
|
| 142 |
try:
|
| 143 |
+
inputs = self.processor(text=text_chunk, return_tensors="pt").to(self.device)
|
| 144 |
+
with torch.no_grad():
|
| 145 |
+
speech = self.model.generate_speech(
|
| 146 |
+
inputs["input_ids"],
|
| 147 |
+
torch.tensor(speaker_embedding).unsqueeze(0).to(self.device),
|
| 148 |
+
vocoder=self.vocoder
|
| 149 |
+
)
|
| 150 |
+
if isinstance(speech, torch.Tensor):
|
| 151 |
+
speech = speech.cpu().numpy()
|
| 152 |
+
return speech
|
| 153 |
except Exception as e:
|
| 154 |
print(f"Error generating speech for chunk: {e}")
|
| 155 |
+
print(f"Chunk text: {text_chunk}")
|
| 156 |
return None
|
| 157 |
|
| 158 |
+
def generate_long_speech(self, text, speaker_id=None, progress_callback=None):
|
| 159 |
"""Generate speech for long text"""
|
| 160 |
processed_text = self.preprocess_text(text)
|
| 161 |
+
print(f"Original length: {len(text)}, Processed length: {len(processed_text)}")
|
| 162 |
chunks = self.chunk_text(processed_text)
|
| 163 |
print(f"Split into {len(chunks)} chunks")
|
| 164 |
+
if not chunks:
|
| 165 |
+
return None, None
|
| 166 |
+
# Generate speech for each chunk
|
| 167 |
audio_segments = []
|
| 168 |
+
sample_rate = 16000
|
|
|
|
| 169 |
for i, chunk in enumerate(chunks):
|
| 170 |
if progress_callback:
|
| 171 |
progress_callback(f"Processing chunk {i+1}/{len(chunks)}: {chunk[:40]}{'...' if len(chunk) > 40 else ''}")
|
| 172 |
print(f"Processing chunk {i+1}: {chunk}")
|
| 173 |
+
audio_chunk = self.generate_speech_chunk(chunk, self.speakers[speaker_id or self.speaker_ids[0]])
|
| 174 |
+
if audio_chunk is not None and len(audio_chunk) > 0:
|
| 175 |
+
if len(audio_chunk.shape) > 1:
|
| 176 |
+
audio_chunk = np.mean(audio_chunk, axis=0)
|
| 177 |
+
audio_segments.append(audio_chunk)
|
| 178 |
+
pause_samples = int(0.4 * sample_rate)
|
| 179 |
+
silence = np.zeros(pause_samples)
|
| 180 |
audio_segments.append(silence)
|
| 181 |
time.sleep(0.1)
|
|
|
|
| 182 |
if not audio_segments:
|
| 183 |
return None, None
|
|
|
|
| 184 |
final_audio = np.concatenate(audio_segments)
|
| 185 |
max_val = np.max(np.abs(final_audio))
|
| 186 |
if max_val > 0:
|
| 187 |
final_audio = final_audio / max_val * 0.95
|
| 188 |
+
return final_audio, sample_rate
|
| 189 |
|
| 190 |
|
| 191 |
# Global TTS system
|
|
|
|
| 198 |
tts_system = None
|
| 199 |
|
| 200 |
|
| 201 |
+
def text_to_speech_interface(text, speaker="Speaker 1 (7306)", progress=gr.Progress()):
|
| 202 |
+
"""Main Gradio interface function"""
|
| 203 |
if tts_system is None:
|
| 204 |
return None, "β TTS system is not available. Please check the logs."
|
| 205 |
if not text or not text.strip():
|
|
|
|
| 213 |
try:
|
| 214 |
progress(0.1, desc="π Starting text-to-speech conversion...")
|
| 215 |
audio, sample_rate = tts_system.generate_long_speech(text, speaker, progress_callback)
|
| 216 |
+
if audio is None or len(audio) == 0:
|
| 217 |
return None, "β Failed to generate audio."
|
| 218 |
progress(0.9, desc="πΎ Saving audio file...")
|
| 219 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
| 220 |
sf.write(tmp_file.name, audio, sample_rate)
|
| 221 |
audio_path = tmp_file.name
|
| 222 |
progress(1.0, desc="β
Complete!")
|
| 223 |
duration = len(audio) / sample_rate
|
| 224 |
return audio_path, f"β
Generated {duration:.1f} seconds of audio successfully!"
|
| 225 |
except Exception as e:
|
| 226 |
+
error_msg = f"β Error: {str(e)}"
|
| 227 |
+
print(f"TTS Error: {e}")
|
| 228 |
+
return None, error_msg
|
| 229 |
|
| 230 |
|
| 231 |
# Create Gradio interface
|
| 232 |
def create_interface():
|
| 233 |
with gr.Blocks(
|
| 234 |
+
title="π€ Long-Form Text-to-Speech",
|
| 235 |
theme=gr.themes.Soft(),
|
| 236 |
css="""
|
| 237 |
.main-header {
|
|
|
|
| 247 |
gr.HTML("""
|
| 248 |
<div class="main-header">
|
| 249 |
<h1>π€ Long-Form Text-to-Speech Generator</h1>
|
| 250 |
+
<p style="color: #666; font-size: 1.1em;">Transform any text into natural human-like speech using advanced AI</p>
|
| 251 |
</div>
|
| 252 |
""")
|
| 253 |
+
# System status
|
| 254 |
+
if tts_system:
|
| 255 |
gr.HTML("""
|
| 256 |
<div style="padding: 1rem; border-radius: 10px; margin: 1rem 0; border-left: 4px solid #28a745; background: #f8f9fa;">
|
| 257 |
<h4>π’ System Ready</h4>
|
| 258 |
+
<p>Using <strong>Microsoft SpeechT5</strong> - High quality neural text-to-speech</p>
|
| 259 |
</div>
|
| 260 |
""")
|
| 261 |
else:
|
|
|
|
| 265 |
<p>TTS system failed to initialize. Please refresh the page.</p>
|
| 266 |
</div>
|
| 267 |
""")
|
|
|
|
| 268 |
with gr.Row():
|
| 269 |
with gr.Column(scale=2):
|
| 270 |
text_input = gr.Textbox(
|
|
|
|
| 272 |
placeholder="Type or paste your text here... (Max 50,000 characters)",
|
| 273 |
lines=10,
|
| 274 |
max_lines=20,
|
| 275 |
+
info="Supports any length text with automatic chunking for optimal quality"
|
| 276 |
)
|
| 277 |
char_count = gr.HTML("<span style='color: #666;'>Character count: 0 / 50,000</span>")
|
| 278 |
speaker_dropdown = gr.Dropdown(
|
| 279 |
+
choices=tts_system.speaker_ids if tts_system else [],
|
| 280 |
+
value=tts_system.speaker_ids[0] if tts_system and tts_system.speaker_ids else None,
|
| 281 |
label="π£οΈ Choose Voice"
|
| 282 |
)
|
| 283 |
generate_btn = gr.Button("π― Generate Speech", variant="primary", size="lg", scale=1)
|
|
|
|
| 291 |
<li>β‘ Smart text processing</li>
|
| 292 |
<li>π§ Auto chunking</li>
|
| 293 |
<li>π΅ Natural-sounding speech</li>
|
| 294 |
+
<li>π MP3 audio output</li>
|
| 295 |
</ul>
|
| 296 |
</div>
|
| 297 |
""")
|
|
|
|
| 314 |
|
| 315 |
gr.Examples(
|
| 316 |
examples=[
|
| 317 |
+
["Hello! Welcome to our advanced text-to-speech system.", "Speaker 1 (7306)"],
|
| 318 |
+
["The quick brown fox jumps over the lazy dog.", "Speaker 2 (7339)"],
|
| 319 |
+
["Artificial intelligence has revolutionized many aspects of our lives.", "Speaker 3 (7341)"],
|
| 320 |
],
|
| 321 |
inputs=[text_input, speaker_dropdown],
|
| 322 |
label="π Try These Examples"
|