Spaces:
Sleeping
Sleeping
Upload 2 files
Browse filesAdd long text support
Files changed (2)
- app.py+319-28
- requirements.txt+3-2
2 unmodified lines34567891011121314151617181920212223242526272829303132333411 unmodified lines4647484950512 unmodified lines54555657585960616263646566676869707172737475767778792 unmodified linesimport asyncioimport tempfileimport osasync def get_voices():voices = await edge_tts.list_voices()return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}async def text_to_speech(text, voice, rate, volume, pitch):if not text.strip():return None, "Please enter text to convert."if not voice:return None, "Please select a voice."voice_short_name = voice.split(" - ")[0]rate_str = f"{rate:+d}%"volume_str = f"{volume:+d}%"pitch_str = f"{pitch:+d}Hz"communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, volume=volume_str, pitch=pitch_str)with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:tmp_path = tmp_file.nameawait communicate.save(tmp_path)return tmp_path, Noneasync def tts_interface(text, voice, rate, volume, pitch):audio, warning = await text_to_speech(text, voice, rate, volume, pitch)if warning:return audio, gr.Warning(warning)return audio, Noneasync def create_demo():voices = await get_voices()11 unmodified linesβ’ Choose from 40+ languages and 300+ voicesβ’ Perfect for creating audiobooks, storytelling, and language learning materialsβ’ Ideal for educators, content creators, and language enthusiasts"""default_voice = ""2 unmodified linesdefault_voice = voice_keybreakdemo = gr.Interface(fn=tts_interface,inputs=[gr.Textbox(label="Input Text", lines=5),gr.Dropdown(choices=[""] + list(voices.keys()), label="Select Voice", value=default_voice),gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate Adjustment (%)", step=1),gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Volume Adjustment (%)", step=1),gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)", step=1)],outputs=[gr.Audio(label="Generated Audio", type="filepath"),gr.Markdown(label="Warning", visible=False)],title="Edge TTS Text-to-Speech",description=description,article="Experience the power of Edge TTS for text-to-speech conversion, and explore our advanced Text-to-Video Converter for even more creative possibilities!",analytics_enabled=False,allow_flagging="manual",api_name=None)return demoasync def main():2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427511 unmodified lines2872882892902912922932942952 unmodified lines2982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693702 unmodified linesimport asyncioimport tempfileimport osimport refrom pydub import AudioSegmentimport mathimport timefrom datetime import datetime, timedeltaimport logging# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',handlers=[logging.StreamHandler()])logger = logging.getLogger(__name__)async def get_voices():voices = await edge_tts.list_voices()return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}def format_time_remaining(seconds):"""Format seconds into human readable time remaining"""if seconds < 60:return f"{int(seconds)}s"elif seconds < 3600:minutes = seconds / 60return f"{minutes:.1f}m"else:hours = seconds / 3600return f"{hours:.1f}h"def calculate_eta(start_time, completed_items, total_items):"""Calculate estimated time remaining"""if completed_items == 0:return "Calculating..."elapsed_time = time.time() - start_timetime_per_item = elapsed_time / completed_itemsremaining_items = total_items - completed_itemsremaining_time = time_per_item * remaining_itemsreturn format_time_remaining(remaining_time)def estimate_text_duration(text):"""Estimate speech duration in minutes based on text length"""# Simple heuristic:# For English (space-separated), ~150 words/min# For Chinese (no spaces), ~300 chars/min# We'll use a hybrid approach: count spaces to guess if it's space-separated.if not text:return 0space_count = text.count(' ')total_len = len(text)# If spaces are < 10% of length, assume non-space-separated (like Chinese)if space_count / total_len < 0.1:# Approx 300 chars per minute for Chineseduration = total_len / 300logger.info(f"Estimated duration (char-based): {duration:.2f} min ({total_len} chars)")else:# Approx 150 words per minute for Englishword_count = len(text.split())duration = word_count / 150logger.info(f"Estimated duration (word-based): {duration:.2f} min ({word_count} words)")return durationdef split_text_by_paragraphs(text, max_duration_minutes=5):"""Split text into segments that won't exceed limit with safety margin"""max_duration = max_duration_minutesestimated_duration = estimate_text_duration(text)logger.info(f"Checking segmentation: Duration={estimated_duration:.2f}m, Limit={max_duration}m")if estimated_duration <= max_duration:return [text]logger.info(f"Text duration ({estimated_duration:.2f}m) exceeds limit ({max_duration}m). Splitting...")# Split by paragraphs firstparagraphs = text.split('\n\n')segments = []current_segment = ""for paragraph in paragraphs:paragraph_duration = estimate_text_duration(paragraph)# If single paragraph is too long, split by sentencesif paragraph_duration > max_duration:sentences = re.split(r'[.!?]+', paragraph)for sentence in sentences:sentence = sentence.strip()if not sentence:continueif estimate_text_duration(current_segment + sentence) > max_duration and current_segment:segments.append(current_segment.strip())current_segment = sentence + ". "else:current_segment += sentence + ". "else:if estimate_text_duration(current_segment + paragraph) > max_duration and current_segment:segments.append(current_segment.strip())current_segment = paragraph + "\n\n"else:current_segment += paragraph + "\n\n"if current_segment.strip():segments.append(current_segment.strip())logger.info(f"Split text into {len(segments)} segments.")return segmentsasync def generate_audio_segment(text_segment, voice_short_name, rate_str, volume_str, pitch_str, segment_index):"""Generate audio for a single text segment"""logger.info(f"Generating segment {segment_index}...")communicate = edge_tts.Communicate(text_segment, voice_short_name, rate=rate_str, volume=volume_str, pitch=pitch_str)with tempfile.NamedTemporaryFile(delete=False, suffix=f"_segment_{segment_index}.mp3") as tmp_file:tmp_path = tmp_file.nameawait communicate.save(tmp_path)# Verify segment durationtry:seg_audio = AudioSegment.from_mp3(tmp_path)duration_min = len(seg_audio) / 1000 / 60logger.info(f"Segment {segment_index} generated at {tmp_path} (Duration: {duration_min:.2f} min)")except Exception as e:logger.error(f"Error checking segment {segment_index} duration: {e}")return tmp_pathasync def merge_audio_files(audio_files):"""Merge multiple audio files into one"""if not audio_files:return Noneif len(audio_files) == 1:return audio_files[0]logger.info(f"Merging {len(audio_files)} audio files...")# Load and merge audio segmentscombined = AudioSegment.empty()for audio_file in audio_files:try:segment = AudioSegment.from_mp3(audio_file)combined += segmentexcept Exception as e:logger.error(f"Error merging file {audio_file}: {e}")# Clean up temporary segment filetry:os.remove(audio_file)except:pass# Save merged audiowith tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:merged_path = tmp_file.namecombined.export(merged_path, format="mp3")total_duration_min = len(combined) / 1000 / 60logger.info(f"Merged audio saved to {merged_path} (Total Duration: {total_duration_min:.2f} min)")return merged_pathasync def text_to_speech_generator(text, voice, rate, volume, pitch):"""Generate speech with detailed progress tracking via generator"""if not text.strip():yield None, "Please enter text to convert.", Nonereturnif not voice:yield None, "Please select a voice.", Nonereturnvoice_short_name = voice.split(" - ")[0]rate_str = f"{rate:+d}%"volume_str = f"{volume:+d}%"pitch_str = f"{pitch:+d}Hz"# Check if text is too long and needs segmentationestimated_duration = estimate_text_duration(text)yield 0, "Starting text processing...", Nonelogger.info(f"Starting TTS for text with estimated duration: {estimated_duration:.2f}m")if estimated_duration > 15: # If longer than 15 minutes, split into segmentssegments = split_text_by_paragraphs(text)total_segments = len(segments)segment_info = f"Text split into {total_segments} segments. Total estimated duration: {estimated_duration:.1f} min"yield 5, segment_info, segment_infoif total_segments > 1:# Generate audio for each segment with progress trackingaudio_files = []start_time = time.time()for i, segment in enumerate(segments):if segment.strip():segment_duration = estimate_text_duration(segment)progress = 10 + (80 * i / total_segments) # 10% to 90%eta = calculate_eta(start_time, i, total_segments)status_msg = (f"Generating segment {i+1}/{total_segments}...\n"f"Segment duration: {segment_duration:.1f} min\n"f"ETA: {eta}")logger.info(f"Progress: {status_msg.replace(chr(10), ', ')}")yield progress, status_msg, segment_infoaudio_file = await generate_audio_segment(segment, voice_short_name, rate_str, volume_str, pitch_str, i+1)audio_files.append(audio_file)yield 90, "Merging audio files...", segment_info# Merge all audio filesmerged_audio = await merge_audio_files(audio_files)yield 100, "Audio generation complete! β ", segment_infoyield merged_audio, "Done", segment_inforeturn# For short texts or single segment, use original methodyield 50, "Generating audio...", Nonelogger.info("Generating single segment audio...")communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, volume=volume_str, pitch=pitch_str)with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:tmp_path = tmp_file.nameawait communicate.save(tmp_path)logger.info(f"Audio generated at {tmp_path}")yield 100, "Audio generation complete! β ", Noneyield tmp_path, "Done", Noneasync def tts_interface(text, voice, rate, volume, pitch):"""Enhanced TTS interface with detailed progress tracking"""if not text.strip():yield None, gr.update(visible=False), "Please enter text.", gr.update(visible=False)returnif not voice:yield None, gr.update(visible=False), "Please select a voice.", gr.update(visible=False)returnestimated_duration = estimate_text_duration(text)# Reset UIyield None, gr.update(value="Starting...", visible=True), "Initializing...", gr.update(visible=False)async for result in text_to_speech_generator(text, voice, rate, volume, pitch):if isinstance(result, tuple) and len(result) == 3:# Progress updateprogress_val, status_msg, segment_info = resultif isinstance(progress_val, (int, float)):# It's a progress updatesegment_update = gr.update(value=segment_info, visible=True) if segment_info else gr.update(visible=False)yield None, gr.update(value=status_msg, visible=True), status_msg, segment_updateelse:# It's the final result (path, msg, info)audio_path = progress_valyield audio_path, gr.update(value="Complete!", visible=True), "Generation Complete", gr.update(visible=True)async def create_demo():voices = await get_voices()11 unmodified linesβ’ Choose from 40+ languages and 300+ voicesβ’ Perfect for creating audiobooks, storytelling, and language learning materialsβ’ Ideal for educators, content creators, and language enthusiastsπ **Long Text Support**:Texts longer than 15 minutes will be **automatically segmented** into smaller chunks for processing and then **merged back** into a single high-quality audio file. This ensures stability and allows for unlimited text length!"""default_voice = ""2 unmodified linesdefault_voice = voice_keybreakwith gr.Blocks(title="Edge TTS Text-to-Speech") as demo:gr.Markdown("# Edge TTS Text-to-Speech")gr.Markdown(description)with gr.Row():with gr.Column():text_input = gr.Textbox(label="Input Text", lines=8, placeholder="Enter your text here... Long texts will be automatically segmented if they exceed 15 minutes of speech time.")# Add text analysis infotext_info = gr.Markdown("**Text Analysis**: Enter text to see estimated duration and segment count", visible=True)voice_dropdown = gr.Dropdown(choices=[""] + list(voices.keys()), label="Select Voice", value=default_voice)with gr.Row():rate_slider = gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate (%)", step=1)volume_slider = gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Volume (%)", step=1)pitch_slider = gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch (Hz)", step=1)generate_btn = gr.Button("Generate Audio", variant="primary")with gr.Column():audio_output = gr.Audio(label="Generated Audio", type="filepath")# Progress and status displaywith gr.Group():gr.Markdown("### π Processing Progress")progress_info = gr.Markdown("Ready, click Generate to start...", visible=True)# Processing detailswith gr.Accordion("π Processing Details", open=True) as processing_details:status_output = gr.Markdown("Waiting...", visible=True)# Segment information displaywith gr.Accordion("π Segment Information", open=True) as segment_info:segment_details = gr.Markdown("Segment details will appear here for long texts", visible=True)gr.Markdown("Experience the power of Edge TTS for text-to-speech conversion, and explore our advanced Text-to-Video Converter for even more creative possibilities!")# Add text analysis functiondef analyze_text(text):if not text.strip():return "**Text Analysis**: Enter text to see estimated duration and segment count"duration = estimate_text_duration(text)word_count = len(text.split())char_count = len(text)if duration > 15:segments = split_text_by_paragraphs(text)segment_count = len(segments)return f"**Text Analysis**: {word_count} words, {char_count} characters, ~{duration:.1f} minutes speech time, {segment_count} segments will be generated"else:return f"**Text Analysis**: {word_count} words, {char_count} characters, ~{duration:.1f} minutes speech time"# Update text analysis when text changestext_input.change(fn=analyze_text,inputs=[text_input],outputs=[text_info])generate_btn.click(fn=tts_interface,inputs=[text_input, voice_dropdown, rate_slider, volume_slider, pitch_slider],outputs=[audio_output, progress_info, status_output, segment_details])return demoasync def main():
12edge_tts==7.0.0gradio==5.21.0123edge_tts>=7.0.0gradio>=4.0.0pydub>=0.25.1
app.py+319-28
requirements.txt+3-2