Update app.py
Browse files35 unmodified lines363738394041422 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283841 unmodified line86878889909192939495969798991001011021031041051061071081091101111121132 unmodified lines1161171181191201211229 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523630 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131235 unmodified linesVOICE_EN = "en-IN-NeerjaNeural"# Pre-compiled regex patterns for speedURL_PATTERN = re.compile(r'https?://[^\s<>"\']+|www\.[^\s<>"\']+')TAG_PATTERN = re.compile(r'<[^>]*>|[<>]')BRACKET_PATTERN = re.compile(r'[\{\}\[\]]')2 unmodified linesSENTENCE_PATTERN = re.compile(r'(?<=[.!?])\s+')SUB_PATTERN = re.compile(r'(?<=[,;:])\s+')@lru_cache(maxsize=1024)def clean_text_for_tts(text):"""Cleans text before TTS with optimized regex and caching."""if not text:return ""text = str(text).strip()text = html.unescape(text)text = URL_PATTERN.sub('', text)text = TAG_PATTERN.sub('', text)text = BRACKET_PATTERN.sub('', text)text = SPECIAL_CHAR_PATTERN.sub('', text)text = text.replace('\\n', ' ').replace('\\t', ' ').replace('\\r', ' ')for keyword in ['voice', 'speak', 'prosody', 'ssml', 'xmlns']:text = text.replace(keyword, '').replace(keyword.upper(), '')text = unicodedata.normalize('NFKD', text)text = WHITESPACE_PATTERN.sub(' ', text)return text.strip()async def generate_safe_audio(text, voice, semaphore):"""Generate clean audio with rate limiting."""async with semaphore:cleaned_text = clean_text_for_tts(text)if not cleaned_text:return Nonetemp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')fname = temp_file.nametemp_file.close()try:comm = edge_tts.Communicate(cleaned_text, voice=voice)await comm.save(fname)1 unmodified lineexcept Exception as e:print(f"Error generating audio: {e}")if os.path.exists(fname):try:os.unlink(fname)except:passreturn None@lru_cache(maxsize=256)def smart_text_chunking(text, max_chars=80):"""Cached text chunking for speed."""text = clean_text_for_tts(text)if not text:return tuple()sentences = SENTENCE_PATTERN.split(text)chunks = []for sentence in sentences:sentence = sentence.strip()if not sentence:continueif len(sentence) <= max_chars:chunks.append(sentence)else:2 unmodified linespart = part.strip()if not part:continueif len(part) <= max_chars:chunks.append(part)else:9 unmodified linescurrent_chunk = wordif current_chunk:chunks.append(current_chunk.strip())return tuple(chunk for chunk in chunks if chunk.strip())def process_audio_segment_fast(audio_file):"""Fast audio processing in separate thread."""try:if not os.path.exists(audio_file):return Nonesegment = AudioSegment.from_file(audio_file)segment = normalize(segment)if len(segment) > 200:try:segment = segment.strip_silence(silence_len=50, silence_thresh=-40)except:passreturn segmentexcept Exception as e:print(f"Warning: Error processing audio segment: {e}")return Nonefinally:try:if os.path.exists(audio_file):os.unlink(audio_file)except:passasync def bilingual_tts_optimized(text, output_file="audio0.mp3", VOICE_TA=None, max_concurrent=10):"""Ultra-optimized bilingual TTS with parallel processing."""print("Starting optimized bilingual TTS processing...")try:chunks = smart_text_chunking(text)if not chunks:print("Error: No valid text chunks after cleaning")return Noneprint(f"Processing {len(chunks)} text chunks with max {max_concurrent} concurrent requests...")is_bilingual_tamil = VOICE_TA is not None and "ta-IN" in VOICE_TAsemaphore = asyncio.Semaphore(max_concurrent)tasks = []for i, chunk in enumerate(chunks):is_tamil = any('\u0B80' <= char <= '\u0BFF' for char in chunk)voice = VOICE_TA if (is_bilingual_tamil and is_tamil) else (VOICE_TA or VOICE_EN)tasks.append(generate_safe_audio(chunk, voice, semaphore))audio_files = await asyncio.gather(*tasks, return_exceptions=True)processed_audio_files = [f for f in audio_files if isinstance(f, str) and f and os.path.exists(f)]if not processed_audio_files:print("Error: No audio was successfully generated")return Noneprint(f"Successfully generated {len(processed_audio_files)} audio segments")with ThreadPoolExecutor(max_workers=min(len(processed_audio_files), 8)) as executor:audio_segments = list(executor.map(process_audio_segment_fast, processed_audio_files))audio_segments = [seg for seg in audio_segments if seg is not None]if not audio_segments:print("Error: No audio segments were successfully processed")return Noneprint("Merging audio segments...")merged_audio = audio_segments[0]pause = AudioSegment.silent(duration=200)for segment in audio_segments[1:]:merged_audio += pause + segmentprint("Applying final audio processing...")merged_audio = merged_audio.compress_dynamic_range(threshold=-20.0,ratio=4.0,attack=5.0,release=50.0)merged_audio = normalize(merged_audio)merged_audio.export(output_file, format="mp3", bitrate="192k")print(f"✅ Audio successfully generated: {output_file}")return output_fileexcept Exception as main_error:print(f"Main error in bilingual TTS: {main_error}")traceback.print_exc()return Noneasync def generate_tts_optimized(id, lines, lang):"""Optimized TTS generation function."""voice = {30 unmodified lines"Czech": "cs-CZ-VlastaNeural","Hungarian": "hu-HU-NoemiNeural"}audio_name = f"audio{id}.mp3"audio_path = os.path.join(AUDIO_DIR, audio_name)if "&&&" in lang:listf = lang.split("&&&")text = listf[0].strip()lang_name = listf[1].strip() if len(listf) > 1 else "English"voice_to_use = voice.get(lang_name, VOICE_EN)else:text = lines[id] if isinstance(lines, (list, tuple)) and id < len(lines) else str(lines)voice_to_use = voice.get(lang, VOICE_EN)output = await bilingual_tts_optimized(text, audio_path, voice_to_use, max_concurrent=15)if output and os.path.exists(audio_path):try:audio = MP3(audio_path)duration = audio.info.lengthreturn duration, audio_pathexcept Exception as e:print(f"Error reading audio file: {e}")return None, Nonereturn None, Nonedef audio_func(id, lines, lang):"""Synchronous wrapper for audio generation."""try:loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)try:return loop.run_until_complete(generate_tts_optimized(id, lines, lang))finally:loop.close()except Exception as e:print(f"Error in audio_func: {e}")traceback.print_exc()return None, Nonedef create_manim_script(problem_data, script_path, audio_path, scale=1):35 unmodified lines363738394041422 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283841 unmodified line86878889909192939495969798991001011021031041051061071081092 unmodified lines1121131141151161171189 unmodified lines12812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523630 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829935 unmodified linesVOICE_EN = "en-IN-NeerjaNeural"# Pre-compiled regex patterns for speed (compiled once, reused many times)URL_PATTERN = re.compile(r'https?://[^\s<>"\']+|www\.[^\s<>"\']+')TAG_PATTERN = re.compile(r'<[^>]*>|[<>]')BRACKET_PATTERN = re.compile(r'[\{\}\[\]]')2 unmodified linesSENTENCE_PATTERN = re.compile(r'(?<=[.!?])\s+')SUB_PATTERN = re.compile(r'(?<=[,;:])\s+')@lru_cache(maxsize=1024) # Cache cleaned text to avoid re-processingdef clean_text_for_tts(text):"""Cleans text before TTS with optimized regex and caching."""if not text:return ""text = str(text).strip()text = html.unescape(text)# Use pre-compiled patterns (much faster)text = URL_PATTERN.sub('', text)text = TAG_PATTERN.sub('', text)text = BRACKET_PATTERN.sub('', text)text = SPECIAL_CHAR_PATTERN.sub('', text)text = text.replace('\\n', ' ').replace('\\t', ' ').replace('\\r', ' ')# Batch remove keywords (faster than multiple re.sub calls)for keyword in ['voice', 'speak', 'prosody', 'ssml', 'xmlns']:text = text.replace(keyword, '').replace(keyword.upper(), '')text = unicodedata.normalize('NFKD', text)text = WHITESPACE_PATTERN.sub(' ', text)return text.strip()async def generate_safe_audio(text, voice, semaphore):"""Generate clean audio with rate limiting."""async with semaphore: # Limit concurrent TTS requestscleaned_text = clean_text_for_tts(text)if not cleaned_text:return Nonetemp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')fname = temp_file.nametemp_file.close()try:comm = edge_tts.Communicate(cleaned_text, voice=voice)await comm.save(fname)1 unmodified lineexcept Exception as e:print(f"Error generating audio: {e}")if os.path.exists(fname):os.unlink(fname)return None@lru_cache(maxsize=256)def smart_text_chunking(text, max_chars=80):"""Cached text chunking for speed."""text = clean_text_for_tts(text)if not text:return tuple() # Return tuple for hashability (required by lru_cache)sentences = SENTENCE_PATTERN.split(text)chunks = []for sentence in sentences:sentence = sentence.strip()if not sentence:continueif len(sentence) <= max_chars:chunks.append(sentence)else:2 unmodified linespart = part.strip()if not part:continueif len(part) <= max_chars:chunks.append(part)else:9 unmodified linescurrent_chunk = wordif current_chunk:chunks.append(current_chunk.strip())return tuple(chunk for chunk in chunks if chunk.strip())def process_audio_segment_fast(audio_file):"""Fast audio processing in separate thread."""try:segment = AudioSegment.from_file(audio_file)segment = normalize(segment)# Only strip silence for longer segmentsif len(segment) > 200:try:segment = segment.strip_silence(silence_len=50, silence_thresh=-40)except:pass # Skip if failsreturn segmentexcept Exception as e:print(f"Warning: Error processing audio segment: {e}")return Nonefinally:# Cleanup temp file immediatelytry:if os.path.exists(audio_file):os.unlink(audio_file)except:passasync def bilingual_tts_optimized(text, output_file="audio0.mp3", VOICE_TA=None, max_concurrent=10):"""Ultra-optimized bilingual TTS with parallel processing."""print("Starting optimized bilingual TTS processing...")try:chunks = smart_text_chunking(text)if not chunks:print("Error: No valid text chunks after cleaning")return Noneprint(f"Processing {len(chunks)} text chunks with max {max_concurrent} concurrent requests...")is_bilingual_tamil = VOICE_TA is not None and "ta-IN" in VOICE_TA# Semaphore to limit concurrent TTS requests (prevents rate limiting)semaphore = asyncio.Semaphore(max_concurrent)# Prepare all taskstasks = []for i, chunk in enumerate(chunks):is_tamil = any('\u0B80' <= char <= '\u0BFF' for char in chunk)voice = VOICE_TA if (is_bilingual_tamil and is_tamil) else (VOICE_TA or VOICE_EN)tasks.append(generate_safe_audio(chunk, voice, semaphore))# Generate all audio files concurrentlyaudio_files = await asyncio.gather(*tasks, return_exceptions=True)# Filter successful filesprocessed_audio_files = [f for f in audio_files if isinstance(f, str) and f]if not processed_audio_files:print("Error: No audio was successfully generated")return Noneprint(f"Successfully generated {len(processed_audio_files)} audio segments")# Process audio segments in parallel using ThreadPoolExecutorwith ThreadPoolExecutor(max_workers=min(len(processed_audio_files), 8)) as executor:audio_segments = list(executor.map(process_audio_segment_fast, processed_audio_files))# Filter out None segmentsaudio_segments = [seg for seg in audio_segments if seg is not None]if not audio_segments:print("Error: No audio segments were successfully processed")return None# Merge audio segments (fast concatenation)print("Merging audio segments...")merged_audio = audio_segments[0]pause = AudioSegment.silent(duration=200)for segment in audio_segments[1:]:merged_audio += pause + segment# Apply final processing (compression and normalization)print("Applying final audio processing...")merged_audio = merged_audio.compress_dynamic_range(threshold=-20.0,ratio=4.0,attack=5.0,release=50.0)merged_audio = normalize(merged_audio)# Export with high qualitymerged_audio.export(output_file, format="mp3", bitrate="192k")print(f"✅ Audio successfully generated: {output_file}")return output_fileexcept Exception as main_error:print(f"Main error in bilingual TTS: {main_error}")return Noneasync def generate_tts_optimized(id, lines, lang):"""Optimized TTS generation function."""voice = {30 unmodified lines"Czech": "cs-CZ-VlastaNeural","Hungarian": "hu-HU-NoemiNeural"}audio_name = f"audio{id}.mp3"audio_path = os.path.join(AUDIO_DIR, audio_name)if "&&&" in lang:listf = lang.split("&&&")text = listf[0].strip()lang_name = listf[1].strip()voice_to_use = voice.get(lang_name, VOICE_EN)else:text = lines[id]voice_to_use = voice.get(lang, VOICE_EN)# Increase max_concurrent for more speed (adjust based on your system)output = await bilingual_tts_optimized(text, audio_path, voice_to_use, max_concurrent=15)if output and os.path.exists(audio_path):audio = MP3(audio_path)duration = audio.info.lengthreturn duration, audio_pathreturn None, Nonedef audio_func(id, lines, lang):"""Synchronous wrapper for audio generation."""return asyncio.run(generate_tts_optimized(id, lines, lang))def create_manim_script(problem_data, script_path, audio_path, scale=1):
app.py+67-80