Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line234567891011121314151617186 unmodified lines2526272829303132333435363738394011 unmodified lines5253545556572 unmodified lines6061626364651 unmodified line6768697071728 unmodified lines81828384858687888919 unmodified lines10911011111211311411518 unmodified lines1341351361371381391401411421431441451461471481491 unmodified line1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941952 unmodified lines1981992002012022032042054 unmodified lines21021121221321421521617 unmodified lines2342352362372382394 unmodified lines2442452462472482492502512522532542552562572585 unmodified lines2642652662672682692702712722732749 unmodified lines2842852862872882894 unmodified lines2942952962972982993003013022 unmodified lines3053063073083093103113123133143153161 unmodified lineimport torchimport numpy as npimport refrom transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGanfrom datasets import load_datasetimport soundfile as sfimport ioimport tempfileimport osfrom pydub import AudioSegmentfrom pydub.silence import split_on_silenceimport nltkfrom nltk.tokenize import sent_tokenizeimport warningswarnings.filterwarnings("ignore")# Download required NLTK data6 unmodified linesdef __init__(self):print("Loading TTS models...")# Load SpeechT5 models (free and high quality)self.processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")self.model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")self.vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")# Load speaker embeddings datasetembeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")self.speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)print("Models loaded successfully!")def preprocess_text(self, text):"""Clean and prepare text for TTS"""11 unmodified lines'vs.': 'versus','e.g.': 'for example','i.e.': 'that is',}for abbr, full in abbreviations.items():2 unmodified lines# Handle numbers (basic)text = re.sub(r'\b(\d+)\b', lambda m: self.number_to_words(int(m.group())), text)return textdef number_to_words(self, num):1 unmodified lineif num == 0:return "zero"ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen","sixteen", "seventeen", "eighteen", "nineteen"]8 unmodified lineselif num < 1000:return ones[num // 100] + " hundred" + ("" if num % 100 == 0 else " " + self.number_to_words(num % 100))else:return str(num) # Fallback for larger numbersdef chunk_text(self, text, max_length=500):"""Split text into manageable chunks while preserving sentence boundaries"""sentences = sent_tokenize(text)chunks = []19 unmodified lineschunks.append(temp_chunk.strip())temp_chunk = wordelse:chunks.append(word) # Single word longer than limitelse:temp_chunk += " " + word if temp_chunk else wordif temp_chunk:18 unmodified linesdef generate_speech_chunk(self, text_chunk):"""Generate speech for a single text chunk"""try:inputs = self.processor(text=text_chunk, return_tensors="pt")speech = self.model.generate_speech(inputs["input_ids"],self.speaker_embeddings,vocoder=self.vocoder)return speech.numpy()except Exception as e:print(f"Error generating speech for chunk: {e}")return np.array([])def generate_long_speech(self, text, progress_callback=None):"""Generate speech for long text by processing in chunks"""1 unmodified linetext = self.preprocess_text(text)# Split into chunkschunks = self.chunk_text(text)print(f"Split text into {len(chunks)} chunks")if not chunks:return np.array([]), 16000# Generate speech for each chunkaudio_segments = []total_chunks = len(chunks)for i, chunk in enumerate(chunks):if progress_callback:progress_callback(f"Processing chunk {i+1}/{total_chunks}: {chunk[:50]}...")speech_chunk = self.generate_speech_chunk(chunk)if len(speech_chunk) > 0:audio_segments.append(speech_chunk)# Add small pause between chunks (200ms of silence)pause_duration = int(0.2 * 16000) # 200ms at 16kHzsilence = np.zeros(pause_duration)audio_segments.append(silence)if not audio_segments:return np.array([]), 16000# Concatenate all audio segmentsfinal_audio = np.concatenate(audio_segments)return final_audio, 16000# Initialize TTS systemtts_system = LongFormTTS()def text_to_speech_interface(text, progress=gr.Progress()):"""Main interface function for Gradio"""if not text.strip():return None, "Please enter some text to convert to speech."def progress_callback(message):progress(0.5, desc=message)2 unmodified linesaudio, sample_rate = tts_system.generate_long_speech(text, progress_callback)if len(audio) == 0:return None, "Failed to generate audio. Please try again."progress(0.9, desc="Finalizing audio...")4 unmodified linesprogress(1.0, desc="Complete!")return audio_path, f"β Successfully generated {len(audio)/sample_rate:.1f} seconds of audio!"except Exception as e:error_msg = f"β Error: {str(e)}"17 unmodified linesborder-radius: 10px;margin: 1rem 0;}""") as demo:4 unmodified lines</div>""")with gr.Row():with gr.Column(scale=2):text_input = gr.Textbox(label="π Enter your text",placeholder="Type or paste any text here... No length limit!",lines=10,max_lines=20)generate_btn = gr.Button("π― Generate Speech",variant="primary",5 unmodified lines<div class="feature-box"><h3>β¨ Features</h3><ul><li>π Unlimited text length</li><li>π€ Human-like voice quality</li><li>β‘ Smart text chunking</li><li>π Completely free to use</li><li>π§ Automatic text preprocessing</li></ul></div>""")9 unmodified linestype="filepath")# Event handlersgenerate_btn.click(fn=text_to_speech_interface,4 unmodified lines# Example textsgr.Examples(examples=[["Hello! This is a test of the long-form text-to-speech system. It can handle texts of any length by intelligently splitting them into smaller chunks while maintaining natural flow and pronunciation."],["The quick brown fox jumps over the lazy dog. This sentence contains every letter of the alphabet and is commonly used for testing text-to-speech systems."],["In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole filled with the ends of worms and an oozy smell, nor yet a dry, bare, sandy hole with nothing in it to sit down on or to eat: it was a hobbit-hole, and that means comfort."]],inputs=[text_input])2 unmodified lines<div style="margin-top: 2rem; padding: 1rem; background: #f0f0f0; border-radius: 5px;"><h4>π§ How it works:</h4><ol><li><strong>Text Preprocessing:</strong> Cleans and normalizes your input text</li><li><strong>Smart Chunking:</strong> Splits long text at sentence boundaries</li><li><strong>Speech Generation:</strong> Uses Microsoft's SpeechT5 model for each chunk</li><li><strong>Audio Merging:</strong> Combines all chunks with natural pauses</li></ol><p><em>π‘ Tip: The system works best with well-formatted text with proper punctuation!</em></p></div>""")1 unmodified line2345678910111213141516176 unmodified lines2425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686911 unmodified lines8182838485868788899091922 unmodified lines95969798991001011021031 unmodified line1051061071081091101111121138 unmodified lines12212312412512612712812913019 unmodified lines15015115215315415515618 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified line2092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772 unmodified lines2802812822832842852862874 unmodified lines29229329429529629729829917 unmodified lines3173183193203213223233243253263273284 unmodified lines3333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663675 unmodified lines3733743753763773783793803813823833849 unmodified lines3943953963973983994004014024034044054064074084094104114 unmodified lines4164174184194204214224234244252 unmodified lines4284294304314324334344354364374384391 unmodified lineimport torchimport numpy as npimport refrom transformers import pipelineimport soundfile as sfimport ioimport tempfileimport osfrom pydub import AudioSegmentimport nltkfrom nltk.tokenize import sent_tokenizeimport warningsimport timewarnings.filterwarnings("ignore")# Download required NLTK data6 unmodified linesdef __init__(self):print("Loading TTS models...")# Try multiple TTS approaches for better compatibilityself.tts_pipeline = Noneself.backup_tts = None# Primary: Try Bark (works well on HF Spaces)try:print("Loading Bark TTS...")self.tts_pipeline = pipeline("text-to-speech",model="suno/bark-small",torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,)self.tts_method = "bark"print("β Bark TTS loaded successfully!")except Exception as e:print(f"β Bark TTS failed: {e}")# Backup: Try Parler TTStry:print("Loading Parler TTS...")self.tts_pipeline = pipeline("text-to-speech",model="parler-tts/parler_tts_mini_v0.1",torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,)self.tts_method = "parler"print("β Parler TTS loaded successfully!")except Exception as e:print(f"β Parler TTS failed: {e}")# Final backup: Try FastSpeech2try:print("Loading FastSpeech2...")from TTS.api import TTSself.backup_tts = TTS(model_name="tts_models/en/ljspeech/fastspeech2")self.tts_method = "fastspeech2"print("β FastSpeech2 loaded successfully!")except Exception as e:print(f"β All TTS models failed: {e}")raise Exception("No TTS model could be loaded. Please check the requirements.")def preprocess_text(self, text):"""Clean and prepare text for TTS"""11 unmodified lines'vs.': 'versus','e.g.': 'for example','i.e.': 'that is','St.': 'Street','Ave.': 'Avenue','Blvd.': 'Boulevard','Inc.': 'Incorporated','Corp.': 'Corporation','Ltd.': 'Limited',}for abbr, full in abbreviations.items():2 unmodified lines# Handle numbers (basic)text = re.sub(r'\b(\d+)\b', lambda m: self.number_to_words(int(m.group())), text)# Clean up any problematic characterstext = re.sub(r'[^\w\s\.,!?;:\-\(\)]', '', text)return textdef number_to_words(self, num):1 unmodified lineif num == 0:return "zero"if num > 9999:return str(num) # Keep large numbers as digitsones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen","sixteen", "seventeen", "eighteen", "nineteen"]8 unmodified lineselif num < 1000:return ones[num // 100] + " hundred" + ("" if num % 100 == 0 else " " + self.number_to_words(num % 100))else:return str(num)def chunk_text(self, text, max_length=200):"""Split text into manageable chunks while preserving sentence boundaries"""sentences = sent_tokenize(text)chunks = []19 unmodified lineschunks.append(temp_chunk.strip())temp_chunk = wordelse:chunks.append(word)else:temp_chunk += " " + word if temp_chunk else wordif temp_chunk:18 unmodified linesdef generate_speech_chunk(self, text_chunk):"""Generate speech for a single text chunk"""try:if self.tts_method == "bark":# Bark TTSspeech = self.tts_pipeline(text_chunk)audio = speech["audio"]sampling_rate = speech["sampling_rate"]return audio, sampling_rateelif self.tts_method == "parler":# Parler TTSspeech = self.tts_pipeline(text_chunk)audio = speech["audio"]sampling_rate = speech["sampling_rate"]return audio, sampling_rateelif self.tts_method == "fastspeech2":# FastSpeech2 via TTS librarywith tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:self.backup_tts.tts_to_file(text=text_chunk, file_path=tmp_file.name)audio, sr = sf.read(tmp_file.name)os.unlink(tmp_file.name)return audio, srelse:raise Exception("No TTS method available")except Exception as e:print(f"Error generating speech for chunk: {e}")return None, Nonedef generate_long_speech(self, text, progress_callback=None):"""Generate speech for long text by processing in chunks"""1 unmodified linetext = self.preprocess_text(text)# Split into chunkschunks = self.chunk_text(text, max_length=150) # Smaller chunks for better compatibilityprint(f"Split text into {len(chunks)} chunks")if not chunks:return None, None# Generate speech for each chunkaudio_segments = []sampling_rate = Nonetotal_chunks = len(chunks)for i, chunk in enumerate(chunks):if progress_callback:progress_callback(f"Processing chunk {i+1}/{total_chunks}: {chunk[:30]}...")audio_chunk, sr = self.generate_speech_chunk(chunk)if audio_chunk is not None and len(audio_chunk) > 0:if sampling_rate is None:sampling_rate = sr# Ensure audio is 1Dif len(audio_chunk.shape) > 1:audio_chunk = audio_chunk.mean(axis=1)audio_segments.append(audio_chunk)# Add small pause between chunks (300ms of silence)pause_duration = int(0.3 * sampling_rate)silence = np.zeros(pause_duration)audio_segments.append(silence)# Small delay to prevent overwhelming the systemtime.sleep(0.1)if not audio_segments:return None, None# Concatenate all audio segmentsfinal_audio = np.concatenate(audio_segments)return final_audio, sampling_rate# Initialize TTS systemprint("Initializing TTS system...")try:tts_system = LongFormTTS()print("β TTS system initialized successfully!")except Exception as e:print(f"β Failed to initialize TTS system: {e}")tts_system = Nonedef text_to_speech_interface(text, progress=gr.Progress()):"""Main interface function for Gradio"""if tts_system is None:return None, "β TTS system not available. Please check the logs."if not text.strip():return None, "Please enter some text to convert to speech."if len(text) > 10000:return None, "Text is too long. Please keep it under 10,000 characters for optimal performance."def progress_callback(message):progress(0.5, desc=message)2 unmodified linesaudio, sample_rate = tts_system.generate_long_speech(text, progress_callback)if audio is None or len(audio) == 0:return None, "Failed to generate audio. Please try with shorter text or check your input."progress(0.9, desc="Finalizing audio...")4 unmodified linesprogress(1.0, desc="Complete!")duration = len(audio) / sample_ratereturn audio_path, f"β Successfully generated {duration:.1f} seconds of audio using {tts_system.tts_method.upper()}!"except Exception as e:error_msg = f"β Error: {str(e)}"17 unmodified linesborder-radius: 10px;margin: 1rem 0;}.status-box {background: #f8f9fa;border-left: 4px solid #007bff;padding: 1rem;margin: 1rem 0;}""") as demo:4 unmodified lines</div>""")# Show TTS system statusif tts_system is not None:status_html = f"""<div class="status-box"><h4>π’ System Status: Ready</h4><p>Using <strong>{tts_system.tts_method.upper()}</strong> TTS engine</p></div>"""else:status_html = """<div class="status-box" style="border-left-color: #dc3545;"><h4>π΄ System Status: Error</h4><p>TTS system failed to initialize. Please check the logs.</p></div>"""gr.HTML(status_html)with gr.Row():with gr.Column(scale=2):text_input = gr.Textbox(label="π Enter your text (max 10,000 characters)",placeholder="Type or paste your text here...",lines=8,max_lines=15)char_count = gr.HTML("Character count: 0")generate_btn = gr.Button("π― Generate Speech",variant="primary",5 unmodified lines<div class="feature-box"><h3>β¨ Features</h3><ul><li>π Long text support</li><li>π€ Multiple TTS engines</li><li>β‘ Smart text chunking</li><li>π Completely free</li><li>π§ Auto preprocessing</li><li>π± Mobile friendly</li></ul></div>""")9 unmodified linestype="filepath")# Character counterdef update_char_count(text):count = len(text)color = "green" if count <= 10000 else "red"return f'<span style="color: {color};">Character count: {count}/10,000</span>'text_input.change(fn=update_char_count,inputs=[text_input],outputs=[char_count])# Event handlersgenerate_btn.click(fn=text_to_speech_interface,4 unmodified lines# Example textsgr.Examples(examples=[["Hello! This is a test of the text-to-speech system. It can handle longer texts by splitting them into smaller chunks."],["The quick brown fox jumps over the lazy dog. This sentence contains every letter of the alphabet."],["In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole, but a comfortable hobbit-hole."],["Welcome to our advanced text-to-speech generator. This system uses state-of-the-art AI models to convert your text into natural-sounding speech. You can input texts of various lengths, and the system will intelligently process them to create high-quality audio output."]],inputs=[text_input])2 unmodified lines<div style="margin-top: 2rem; padding: 1rem; background: #f0f0f0; border-radius: 5px;"><h4>π§ How it works:</h4><ol><li><strong>Multiple Engines:</strong> Tries Bark, Parler, or FastSpeech2 TTS models</li><li><strong>Smart Chunking:</strong> Splits long text at natural boundaries</li><li><strong>Audio Processing:</strong> Combines chunks with natural pauses</li><li><strong>Quality Output:</strong> Generates high-quality WAV audio</li></ol><p><em>π‘ Tip: For best results, use well-formatted text with proper punctuation!</em></p></div>""")
app.py+178-55