Update video2.py
Browse files
video2.py
CHANGED
|
@@ -47,16 +47,19 @@ import unicodedata
|
|
| 47 |
import tempfile
|
| 48 |
import os
|
| 49 |
import asyncio
|
| 50 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 51 |
from functools import lru_cache
|
| 52 |
import edge_tts
|
| 53 |
from pydub import AudioSegment
|
| 54 |
-
from pydub.effects import normalize
|
| 55 |
-
from
|
|
|
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
# Pre-compiled regex patterns for speed
|
| 60 |
URL_PATTERN = re.compile(r'https?://[^\s<>"\']+|www\.[^\s<>"\']+')
|
| 61 |
TAG_PATTERN = re.compile(r'<[^>]*>|[<>]')
|
| 62 |
BRACKET_PATTERN = re.compile(r'[\{\}\[\]]')
|
|
@@ -64,44 +67,85 @@ SPECIAL_CHAR_PATTERN = re.compile(r'[#@$%^&*_+=|\\`~]')
|
|
| 64 |
WHITESPACE_PATTERN = re.compile(r'\s+')
|
| 65 |
SENTENCE_PATTERN = re.compile(r'(?<=[.!?])\s+')
|
| 66 |
SUB_PATTERN = re.compile(r'(?<=[,;:])\s+')
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
@lru_cache(maxsize=
|
| 69 |
def clean_text_for_tts(text):
|
| 70 |
-
"""
|
| 71 |
if not text:
|
| 72 |
return ""
|
| 73 |
text = str(text).strip()
|
| 74 |
text = html.unescape(text)
|
| 75 |
|
| 76 |
-
#
|
| 77 |
text = URL_PATTERN.sub('', text)
|
| 78 |
text = TAG_PATTERN.sub('', text)
|
| 79 |
text = BRACKET_PATTERN.sub('', text)
|
| 80 |
text = SPECIAL_CHAR_PATTERN.sub('', text)
|
| 81 |
text = text.replace('\\n', ' ').replace('\\t', ' ').replace('\\r', ' ')
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
text = unicodedata.normalize('NFKD', text)
|
| 88 |
text = WHITESPACE_PATTERN.sub(' ', text)
|
| 89 |
return text.strip()
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
async def generate_safe_audio(text, voice, semaphore):
|
| 92 |
-
"""
|
| 93 |
-
async with semaphore:
|
| 94 |
cleaned_text = clean_text_for_tts(text)
|
| 95 |
if not cleaned_text:
|
| 96 |
return None
|
| 97 |
|
|
|
|
|
|
|
|
|
|
| 98 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
|
| 99 |
fname = temp_file.name
|
| 100 |
temp_file.close()
|
| 101 |
|
| 102 |
try:
|
| 103 |
-
comm = edge_tts.Communicate(
|
| 104 |
await comm.save(fname)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
return fname
|
| 106 |
except Exception as e:
|
| 107 |
print(f"Error generating audio: {e}")
|
|
@@ -109,201 +153,208 @@ async def generate_safe_audio(text, voice, semaphore):
|
|
| 109 |
os.unlink(fname)
|
| 110 |
return None
|
| 111 |
|
| 112 |
-
@lru_cache(maxsize=
|
| 113 |
-
def
|
| 114 |
-
"""
|
| 115 |
text = clean_text_for_tts(text)
|
| 116 |
if not text:
|
| 117 |
-
return
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
sentences = SENTENCE_PATTERN.split(text)
|
| 120 |
chunks = []
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
for
|
| 123 |
-
|
| 124 |
-
if
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
else:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
if
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
current_chunk = ""
|
| 141 |
-
for word in words:
|
| 142 |
-
test_chunk = f"{current_chunk} {word}" if current_chunk else word
|
| 143 |
-
if len(test_chunk) <= max_chars:
|
| 144 |
-
current_chunk = test_chunk
|
| 145 |
-
else:
|
| 146 |
-
if current_chunk:
|
| 147 |
-
chunks.append(current_chunk.strip())
|
| 148 |
-
current_chunk = word
|
| 149 |
-
if current_chunk:
|
| 150 |
-
chunks.append(current_chunk.strip())
|
| 151 |
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
def
|
| 155 |
-
"""
|
| 156 |
try:
|
| 157 |
segment = AudioSegment.from_file(audio_file)
|
| 158 |
-
segment = normalize(segment)
|
| 159 |
|
| 160 |
-
#
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
return segment
|
| 168 |
except Exception as e:
|
| 169 |
-
print(f"Warning: Error
|
| 170 |
return None
|
| 171 |
finally:
|
| 172 |
-
#
|
| 173 |
try:
|
| 174 |
if os.path.exists(audio_file):
|
| 175 |
os.unlink(audio_file)
|
| 176 |
except:
|
| 177 |
pass
|
| 178 |
|
| 179 |
-
async def bilingual_tts_optimized(text, output_file="audio0.mp3", VOICE_TA=None, max_concurrent=
|
| 180 |
-
"""Ultra-optimized bilingual TTS with
|
| 181 |
-
print("Starting
|
| 182 |
|
| 183 |
try:
|
| 184 |
-
chunks =
|
| 185 |
if not chunks:
|
| 186 |
print("Error: No valid text chunks after cleaning")
|
| 187 |
return None
|
| 188 |
|
| 189 |
-
print(f"Processing {len(chunks)}
|
| 190 |
|
| 191 |
-
|
| 192 |
|
| 193 |
-
# Semaphore to limit concurrent TTS requests (prevents rate limiting)
|
| 194 |
semaphore = asyncio.Semaphore(max_concurrent)
|
| 195 |
|
| 196 |
-
# Prepare
|
| 197 |
tasks = []
|
| 198 |
-
for
|
| 199 |
-
|
| 200 |
-
voice = VOICE_TA if (
|
| 201 |
tasks.append(generate_safe_audio(chunk, voice, semaphore))
|
| 202 |
|
| 203 |
-
#
|
| 204 |
audio_files = await asyncio.gather(*tasks, return_exceptions=True)
|
| 205 |
-
|
| 206 |
-
# Filter successful files
|
| 207 |
-
processed_audio_files = [f for f in audio_files if isinstance(f, str) and f]
|
| 208 |
|
| 209 |
if not processed_audio_files:
|
| 210 |
-
print("Error: No audio
|
| 211 |
return None
|
| 212 |
|
| 213 |
-
print(f"
|
| 214 |
|
| 215 |
-
#
|
| 216 |
-
with ThreadPoolExecutor(max_workers=min(len(processed_audio_files),
|
| 217 |
-
audio_segments = list(executor.map(
|
| 218 |
|
| 219 |
-
# Filter out None segments
|
| 220 |
audio_segments = [seg for seg in audio_segments if seg is not None]
|
| 221 |
|
| 222 |
if not audio_segments:
|
| 223 |
-
print("Error: No
|
| 224 |
return None
|
| 225 |
|
| 226 |
-
# Merge
|
| 227 |
-
print("Merging
|
| 228 |
merged_audio = audio_segments[0]
|
| 229 |
-
|
| 230 |
|
| 231 |
-
for segment in audio_segments[1:]:
|
|
|
|
|
|
|
|
|
|
| 232 |
merged_audio += pause + segment
|
|
|
|
| 233 |
|
| 234 |
-
#
|
| 235 |
-
print("Applying final
|
| 236 |
-
merged_audio = merged_audio.compress_dynamic_range(
|
| 237 |
-
threshold=-20.0,
|
| 238 |
-
ratio=4.0,
|
| 239 |
-
attack=5.0,
|
| 240 |
-
release=50.0
|
| 241 |
-
)
|
| 242 |
merged_audio = normalize(merged_audio)
|
| 243 |
|
| 244 |
-
# Export
|
| 245 |
-
merged_audio.export(output_file, format="mp3", bitrate="
|
| 246 |
-
print(f"✅ Audio successfully generated: {output_file}")
|
| 247 |
|
|
|
|
| 248 |
return output_file
|
| 249 |
|
| 250 |
except Exception as main_error:
|
| 251 |
-
print(f"Main error
|
| 252 |
return None
|
| 253 |
|
|
|
|
| 254 |
async def generate_tts_optimized(id, lines, lang):
|
| 255 |
-
"""
|
| 256 |
-
|
| 257 |
-
"English": "en-US-JennyNeural",
|
| 258 |
"Tamil": "ta-IN-PallaviNeural",
|
| 259 |
"Hindi": "hi-IN-SwaraNeural",
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
"Telugu": "te-IN-ShrutiNeural",
|
| 263 |
-
"Bengali": "bn-IN-TanishaaNeural",
|
| 264 |
-
"Marathi": "mr-IN-AarohiNeural",
|
| 265 |
-
"Gujarati": "gu-IN-DhwaniNeural",
|
| 266 |
-
"Punjabi": "pa-IN-VaaniNeural",
|
| 267 |
-
"Urdu": "ur-IN-GulNeural",
|
| 268 |
-
"French": "fr-FR-DeniseNeural",
|
| 269 |
-
"German": "de-DE-KatjaNeural",
|
| 270 |
-
"Spanish": "es-ES-ElviraNeural",
|
| 271 |
-
"Italian": "it-IT-IsabellaNeural",
|
| 272 |
-
"Russian": "ru-RU-SvetlanaNeural",
|
| 273 |
-
"Japanese": "ja-JP-NanamiNeural",
|
| 274 |
-
"Korean": "ko-KR-SunHiNeural",
|
| 275 |
-
"Chinese": "zh-CN-XiaoxiaoNeural",
|
| 276 |
-
"Arabic": "ar-SA-ZariyahNeural",
|
| 277 |
-
"Portuguese": "pt-BR-FranciscaNeural",
|
| 278 |
-
"Dutch": "nl-NL-FennaNeural",
|
| 279 |
-
"Greek": "el-GR-AthinaNeural",
|
| 280 |
-
"Hebrew": "he-IL-HilaNeural",
|
| 281 |
-
"Turkish": "tr-TR-EmelNeural",
|
| 282 |
-
"Polish": "pl-PL-AgnieszkaNeural",
|
| 283 |
-
"Thai": "th-TH-AcharaNeural",
|
| 284 |
-
"Vietnamese": "vi-VN-HoaiMyNeural",
|
| 285 |
-
"Swedish": "sv-SE-SofieNeural",
|
| 286 |
-
"Finnish": "fi-FI-NooraNeural",
|
| 287 |
-
"Czech": "cs-CZ-VlastaNeural",
|
| 288 |
-
"Hungarian": "hu-HU-NoemiNeural"
|
| 289 |
}
|
| 290 |
|
| 291 |
audio_name = f"audio{id}.mp3"
|
| 292 |
-
|
|
|
|
| 293 |
|
| 294 |
if "&&&" in lang:
|
| 295 |
-
|
| 296 |
-
text =
|
| 297 |
-
lang_name =
|
| 298 |
-
|
| 299 |
else:
|
| 300 |
text = lines[id]
|
| 301 |
-
|
|
|
|
| 302 |
|
| 303 |
-
#
|
| 304 |
-
output = await bilingual_tts_optimized(text, audio_path,
|
| 305 |
|
| 306 |
if output and os.path.exists(audio_path):
|
|
|
|
| 307 |
audio = MP3(audio_path)
|
| 308 |
duration = audio.info.length
|
| 309 |
return duration, audio_path
|
|
@@ -311,7 +362,7 @@ async def generate_tts_optimized(id, lines, lang):
|
|
| 311 |
return None, None
|
| 312 |
|
| 313 |
def audio_func(id, lines, lang):
|
| 314 |
-
"""Synchronous wrapper
|
| 315 |
return asyncio.run(generate_tts_optimized(id, lines, lang))
|
| 316 |
|
| 317 |
#-----------------------------
|
|
|
|
| 47 |
import tempfile
|
| 48 |
import os
|
| 49 |
import asyncio
|
| 50 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 51 |
from functools import lru_cache
|
| 52 |
import edge_tts
|
| 53 |
from pydub import AudioSegment
|
| 54 |
+
from pydub.effects import normalize, compress_dynamic_range
|
| 55 |
+
from pydub.playback import play # Optional, for testing
|
| 56 |
+
import langdetect # Added for better language detection per segment (install if needed)
|
| 57 |
|
| 58 |
+
# Default voices - upgraded to higher quality neural voices where possible
|
| 59 |
+
VOICE_EN = "en-IN-NeerjaNeural" # Indian English for better bilingual flow
|
| 60 |
+
VOICE_TA = "ta-IN-PallaviNeural" # High-quality Tamil neural voice
|
| 61 |
|
| 62 |
+
# Pre-compiled regex patterns for speed
|
| 63 |
URL_PATTERN = re.compile(r'https?://[^\s<>"\']+|www\.[^\s<>"\']+')
|
| 64 |
TAG_PATTERN = re.compile(r'<[^>]*>|[<>]')
|
| 65 |
BRACKET_PATTERN = re.compile(r'[\{\}\[\]]')
|
|
|
|
| 67 |
WHITESPACE_PATTERN = re.compile(r'\s+')
|
| 68 |
SENTENCE_PATTERN = re.compile(r'(?<=[.!?])\s+')
|
| 69 |
SUB_PATTERN = re.compile(r'(?<=[,;:])\s+')
|
| 70 |
+
WORD_PATTERN = re.compile(r'\b\w+\b') # For word splitting
|
| 71 |
+
TAMIL_CHAR_PATTERN = re.compile(r'[\u0B80-\u0BFF]') # Tamil Unicode range
|
| 72 |
|
| 73 |
+
@lru_cache(maxsize=2048) # Increased cache size for better hit rate
|
| 74 |
def clean_text_for_tts(text):
|
| 75 |
+
"""Enhanced text cleaning with SSML preparation hooks."""
|
| 76 |
if not text:
|
| 77 |
return ""
|
| 78 |
text = str(text).strip()
|
| 79 |
text = html.unescape(text)
|
| 80 |
|
| 81 |
+
# Aggressive cleaning with pre-compiled patterns
|
| 82 |
text = URL_PATTERN.sub('', text)
|
| 83 |
text = TAG_PATTERN.sub('', text)
|
| 84 |
text = BRACKET_PATTERN.sub('', text)
|
| 85 |
text = SPECIAL_CHAR_PATTERN.sub('', text)
|
| 86 |
text = text.replace('\\n', ' ').replace('\\t', ' ').replace('\\r', ' ')
|
| 87 |
|
| 88 |
+
# Remove TTS-disruptive keywords
|
| 89 |
+
disruptive_keywords = ['voice', 'speak', 'prosody', 'ssml', 'xmlns', '<speak>', '</speak>']
|
| 90 |
+
for keyword in disruptive_keywords:
|
| 91 |
+
text = re.sub(re.escape(keyword), '', text, flags=re.IGNORECASE)
|
| 92 |
|
| 93 |
text = unicodedata.normalize('NFKD', text)
|
| 94 |
text = WHITESPACE_PATTERN.sub(' ', text)
|
| 95 |
return text.strip()
|
| 96 |
|
| 97 |
+
def detect_language(text_segment):
|
| 98 |
+
"""Fast language detection: Tamil if any Tamil chars, else English (or fallback)."""
|
| 99 |
+
if TAMIL_CHAR_PATTERN.search(text_segment):
|
| 100 |
+
return 'ta'
|
| 101 |
+
try:
|
| 102 |
+
# Fallback to langdetect for mixed/ambiguous cases (English default)
|
| 103 |
+
lang = langdetect.detect(text_segment)
|
| 104 |
+
return 'ta' if lang.startswith('ta') else 'en'
|
| 105 |
+
except:
|
| 106 |
+
return 'en'
|
| 107 |
+
|
| 108 |
+
def enhance_with_ssml(text, lang='en'):
|
| 109 |
+
"""Add basic SSML for prosody, emphasis, and breaks to improve naturalness."""
|
| 110 |
+
if not text:
|
| 111 |
+
return text
|
| 112 |
+
|
| 113 |
+
# Basic prosody: Medium rate for clarity, slight pitch adjustment for natural flow
|
| 114 |
+
prosody_rate = 'medium' # Avoid fast/slow extremes for quality
|
| 115 |
+
prosody_pitch = '+5%' if lang == 'en' else '-2%' # Subtle variation per lang
|
| 116 |
+
|
| 117 |
+
# Insert breaks after punctuation for better rhythm
|
| 118 |
+
text = re.sub(r'([.!?])', r'\1<break time="400ms"/>', text)
|
| 119 |
+
text = re.sub(r'([,;:])', r'\1<break time="200ms"/>', text)
|
| 120 |
+
|
| 121 |
+
# Simple emphasis on potential key terms (e.g., capitalize words as proxy)
|
| 122 |
+
text = re.sub(r'\b[A-Z]{2,}\b', r'<emphasis level="moderate">\g<0></emphasis>', text)
|
| 123 |
+
|
| 124 |
+
# Wrap in prosody and speak tags
|
| 125 |
+
ssml = f'<speak><prosody rate="{prosody_rate}" pitch="{prosody_pitch}">{text}</prosody></speak>'
|
| 126 |
+
return ssml
|
| 127 |
+
|
| 128 |
async def generate_safe_audio(text, voice, semaphore):
|
| 129 |
+
"""Enhanced audio generation with SSML and improved error handling."""
|
| 130 |
+
async with semaphore:
|
| 131 |
cleaned_text = clean_text_for_tts(text)
|
| 132 |
if not cleaned_text:
|
| 133 |
return None
|
| 134 |
|
| 135 |
+
# Enhance with SSML before TTS
|
| 136 |
+
ssml_text = enhance_with_ssml(cleaned_text, 'en' if 'en' in voice else 'ta')
|
| 137 |
+
|
| 138 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
|
| 139 |
fname = temp_file.name
|
| 140 |
temp_file.close()
|
| 141 |
|
| 142 |
try:
|
| 143 |
+
comm = edge_tts.Communicate(ssml_text, voice=voice)
|
| 144 |
await comm.save(fname)
|
| 145 |
+
# Quick validation: Check file size > 0
|
| 146 |
+
if os.path.getsize(fname) < 100: # Minimal viable audio
|
| 147 |
+
os.unlink(fname)
|
| 148 |
+
return None
|
| 149 |
return fname
|
| 150 |
except Exception as e:
|
| 151 |
print(f"Error generating audio: {e}")
|
|
|
|
| 153 |
os.unlink(fname)
|
| 154 |
return None
|
| 155 |
|
| 156 |
+
@lru_cache(maxsize=512) # Cache chunking results
|
| 157 |
+
def smart_bilingual_chunking(text, max_chars=70): # Reduced max_chars for finer-grained bilingual switching
|
| 158 |
+
"""Advanced chunking: Split into language-specific word groups for per-word voice switching."""
|
| 159 |
text = clean_text_for_tts(text)
|
| 160 |
if not text:
|
| 161 |
+
return []
|
| 162 |
+
|
| 163 |
+
# Split into words/tokens
|
| 164 |
+
words = re.findall(r'\S+', text) # Non-whitespace tokens
|
| 165 |
|
|
|
|
| 166 |
chunks = []
|
| 167 |
+
current_chunk = []
|
| 168 |
+
current_lang = None
|
| 169 |
|
| 170 |
+
for word in words:
|
| 171 |
+
word_lang = detect_language(word)
|
| 172 |
+
if current_lang is None:
|
| 173 |
+
current_lang = word_lang
|
| 174 |
+
current_chunk.append(word)
|
| 175 |
+
elif word_lang == current_lang:
|
| 176 |
+
current_chunk.append(word)
|
| 177 |
else:
|
| 178 |
+
# End current chunk if length exceeded or lang change
|
| 179 |
+
chunk_text = ' '.join(current_chunk)
|
| 180 |
+
if len(chunk_text) > max_chars:
|
| 181 |
+
# Sub-chunk if too long (rare for words)
|
| 182 |
+
sub_chunks = [chunk_text[i:i+max_chars] for i in range(0, len(chunk_text), max_chars)]
|
| 183 |
+
chunks.extend(sub_chunks)
|
| 184 |
+
else:
|
| 185 |
+
chunks.append(chunk_text)
|
| 186 |
+
current_chunk = [word]
|
| 187 |
+
current_lang = word_lang
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
+
# Add final chunk
|
| 190 |
+
if current_chunk:
|
| 191 |
+
chunk_text = ' '.join(current_chunk)
|
| 192 |
+
if len(chunk_text) > max_chars:
|
| 193 |
+
sub_chunks = [chunk_text[i:i+max_chars] for i in range(0, len(chunk_text), max_chars)]
|
| 194 |
+
chunks.extend(sub_chunks)
|
| 195 |
+
else:
|
| 196 |
+
chunks.append(chunk_text)
|
| 197 |
+
|
| 198 |
+
# Re-insert sentence breaks for flow
|
| 199 |
+
enhanced_chunks = []
|
| 200 |
+
for chunk in chunks:
|
| 201 |
+
enhanced_chunks.append(re.sub(r'\s+', ' ', chunk.strip()))
|
| 202 |
+
|
| 203 |
+
return tuple(enhanced_chunks) # Tuple for lru_cache
|
| 204 |
|
| 205 |
+
def process_audio_segment_enhanced(audio_file):
|
| 206 |
+
"""Advanced post-processing: EQ, de-essing approximation, loudness normalization."""
|
| 207 |
try:
|
| 208 |
segment = AudioSegment.from_file(audio_file)
|
|
|
|
| 209 |
|
| 210 |
+
# High-pass filter to remove rumble (80 Hz)
|
| 211 |
+
segment = segment.high_pass_filter(80)
|
| 212 |
+
|
| 213 |
+
# Low-pass for harshness control (10 kHz)
|
| 214 |
+
segment = segment.low_pass_filter(10000)
|
| 215 |
+
|
| 216 |
+
# Presence boost: Simple mid-range boost simulation via overlay (2-5 kHz approx)
|
| 217 |
+
# For true EQ, consider librosa integration; here, approximate with normalize after gain
|
| 218 |
+
segment = segment + 2 # Gentle overall boost before normalization
|
| 219 |
+
|
| 220 |
+
# Approximate de-essing: Attenuate high frequencies dynamically (simple shelf)
|
| 221 |
+
# For better, use multiband, but pydub limits; cut highs if peaky
|
| 222 |
+
if segment.rms > -20: # If loud, gentle high-cut
|
| 223 |
+
highs = segment.high_pass_filter(5000)
|
| 224 |
+
segment = segment.overlay(highs - 3, gain_during_overlay=-3) # Rough de-ess
|
| 225 |
+
|
| 226 |
+
# Strip silence only for longer segments
|
| 227 |
+
if len(segment) > 300:
|
| 228 |
+
segment = segment.strip_silence(silence_len=60, silence_thresh=-45, padding=20)
|
| 229 |
+
|
| 230 |
+
# Dynamic range compression (enhanced params for TTS)
|
| 231 |
+
segment = compress_dynamic_range(
|
| 232 |
+
segment,
|
| 233 |
+
threshold=-25.0, # Softer threshold for natural dynamics
|
| 234 |
+
ratio=3.0,
|
| 235 |
+
attack=3.0,
|
| 236 |
+
release=100.0
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# Final normalization to approximate -16 LUFS (peak normalize + gain adjust)
|
| 240 |
+
segment = normalize(segment)
|
| 241 |
+
# Adjust to target RMS ~ -18 dB (proxy for LUFS)
|
| 242 |
+
target_rms = -18
|
| 243 |
+
current_rms = segment.rms
|
| 244 |
+
gain_adjust = target_rms - current_rms
|
| 245 |
+
segment = segment + gain_adjust
|
| 246 |
|
| 247 |
return segment
|
| 248 |
except Exception as e:
|
| 249 |
+
print(f"Warning: Error in enhanced audio processing: {e}")
|
| 250 |
return None
|
| 251 |
finally:
|
| 252 |
+
# Immediate cleanup
|
| 253 |
try:
|
| 254 |
if os.path.exists(audio_file):
|
| 255 |
os.unlink(audio_file)
|
| 256 |
except:
|
| 257 |
pass
|
| 258 |
|
| 259 |
+
async def bilingual_tts_optimized(text, output_file="audio0.mp3", VOICE_TA=None, max_concurrent=20): # Increased concurrency
|
| 260 |
+
"""Ultra-optimized bilingual TTS with per-word voice switching, SSML, and advanced post-processing."""
|
| 261 |
+
print("Starting enhanced bilingual TTS processing...")
|
| 262 |
|
| 263 |
try:
|
| 264 |
+
chunks = smart_bilingual_chunking(text)
|
| 265 |
if not chunks:
|
| 266 |
print("Error: No valid text chunks after cleaning")
|
| 267 |
return None
|
| 268 |
|
| 269 |
+
print(f"Processing {len(chunks)} bilingual chunks with max {max_concurrent} concurrent requests...")
|
| 270 |
|
| 271 |
+
is_bilingual = VOICE_TA is not None
|
| 272 |
|
|
|
|
| 273 |
semaphore = asyncio.Semaphore(max_concurrent)
|
| 274 |
|
| 275 |
+
# Prepare tasks with dynamic voice selection per chunk
|
| 276 |
tasks = []
|
| 277 |
+
for chunk in chunks:
|
| 278 |
+
chunk_lang = detect_language(chunk)
|
| 279 |
+
voice = VOICE_TA if (is_bilingual and chunk_lang == 'ta') else VOICE_EN
|
| 280 |
tasks.append(generate_safe_audio(chunk, voice, semaphore))
|
| 281 |
|
| 282 |
+
# Concurrent generation
|
| 283 |
audio_files = await asyncio.gather(*tasks, return_exceptions=True)
|
| 284 |
+
processed_audio_files = [f for f in audio_files if isinstance(f, str) and f and os.path.exists(f)]
|
|
|
|
|
|
|
| 285 |
|
| 286 |
if not processed_audio_files:
|
| 287 |
+
print("Error: No audio generated")
|
| 288 |
return None
|
| 289 |
|
| 290 |
+
print(f"Generated {len(processed_audio_files)} segments")
|
| 291 |
|
| 292 |
+
# Parallel post-processing with more workers
|
| 293 |
+
with ThreadPoolExecutor(max_workers=min(len(processed_audio_files), 12)) as executor: # Increased workers
|
| 294 |
+
audio_segments = list(executor.map(process_audio_segment_enhanced, processed_audio_files))
|
| 295 |
|
|
|
|
| 296 |
audio_segments = [seg for seg in audio_segments if seg is not None]
|
| 297 |
|
| 298 |
if not audio_segments:
|
| 299 |
+
print("Error: No segments processed")
|
| 300 |
return None
|
| 301 |
|
| 302 |
+
# Merge with language-switch pauses (shorter within lang, longer on switch)
|
| 303 |
+
print("Merging segments with adaptive pauses...")
|
| 304 |
merged_audio = audio_segments[0]
|
| 305 |
+
prev_lang = detect_language(chunks[0])
|
| 306 |
|
| 307 |
+
for i, segment in enumerate(audio_segments[1:], 1):
|
| 308 |
+
current_lang = detect_language(chunks[i])
|
| 309 |
+
pause_duration = 100 if current_lang == prev_lang else 300 # Longer pause on lang switch
|
| 310 |
+
pause = AudioSegment.silent(duration=pause_duration)
|
| 311 |
merged_audio += pause + segment
|
| 312 |
+
prev_lang = current_lang
|
| 313 |
|
| 314 |
+
# Final mastering
|
| 315 |
+
print("Applying final mastering...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
merged_audio = normalize(merged_audio)
|
| 317 |
|
| 318 |
+
# Export at higher bitrate for quality
|
| 319 |
+
merged_audio.export(output_file, format="mp3", bitrate="256k") # Upgraded bitrate
|
|
|
|
| 320 |
|
| 321 |
+
print(f"✅ Enhanced audio generated: {output_file}")
|
| 322 |
return output_file
|
| 323 |
|
| 324 |
except Exception as main_error:
|
| 325 |
+
print(f"Main error: {main_error}")
|
| 326 |
return None
|
| 327 |
|
| 328 |
+
# Rest of the code remains similar, but update generate_tts_optimized to use the enhanced function
|
| 329 |
async def generate_tts_optimized(id, lines, lang):
|
| 330 |
+
"""Updated TTS generation with multi-lang support."""
|
| 331 |
+
voice_map = {
|
| 332 |
+
"English": "en-US-JennyNeural", # Upgraded to US for global, or keep en-IN
|
| 333 |
"Tamil": "ta-IN-PallaviNeural",
|
| 334 |
"Hindi": "hi-IN-SwaraNeural",
|
| 335 |
+
# ... (keep existing map, upgrade to Neural where possible)
|
| 336 |
+
# Add more from guide if needed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
}
|
| 338 |
|
| 339 |
audio_name = f"audio{id}.mp3"
|
| 340 |
+
# Assume AUDIO_DIR defined elsewhere
|
| 341 |
+
audio_path = os.path.join(AUDIO_DIR if 'AUDIO_DIR' in globals() else '.', audio_name)
|
| 342 |
|
| 343 |
if "&&&" in lang:
|
| 344 |
+
parts = lang.split("&&&")
|
| 345 |
+
text = parts[0].strip()
|
| 346 |
+
lang_name = parts[1].strip()
|
| 347 |
+
voice_ta = voice_map.get(lang_name, VOICE_EN) # For bilingual
|
| 348 |
else:
|
| 349 |
text = lines[id]
|
| 350 |
+
voice_ta = None # Mono-lang
|
| 351 |
+
lang_name = lang
|
| 352 |
|
| 353 |
+
# Use enhanced bilingual func (handles mono as special case)
|
| 354 |
+
output = await bilingual_tts_optimized(text, audio_path, VOICE_TA=voice_ta, max_concurrent=20)
|
| 355 |
|
| 356 |
if output and os.path.exists(audio_path):
|
| 357 |
+
from mutagen.mp3 import MP3
|
| 358 |
audio = MP3(audio_path)
|
| 359 |
duration = audio.info.length
|
| 360 |
return duration, audio_path
|
|
|
|
| 362 |
return None, None
|
| 363 |
|
| 364 |
def audio_func(id, lines, lang):
|
| 365 |
+
"""Synchronous wrapper."""
|
| 366 |
return asyncio.run(generate_tts_optimized(id, lines, lang))
|
| 367 |
|
| 368 |
#-----------------------------
|