Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,604 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 3 |
-
import edge_tts
|
| 4 |
-
import os
|
| 5 |
-
import asyncio
|
| 6 |
-
import uuid
|
| 7 |
-
import re
|
| 8 |
import time
|
| 9 |
-
import
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
import
|
| 13 |
-
from
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __init__(self):
|
| 17 |
-
self.
|
| 18 |
-
self.
|
| 19 |
-
|
| 20 |
-
def get_timing(self, duration):
|
| 21 |
-
start_time = self.current_time
|
| 22 |
-
end_time = start_time + duration
|
| 23 |
-
self.current_time = end_time + self.segment_gap
|
| 24 |
-
return start_time, end_time
|
| 25 |
-
|
| 26 |
-
def get_audio_length(audio_file):
|
| 27 |
-
audio = AudioSegment.from_file(audio_file)
|
| 28 |
-
return len(audio) / 1000
|
| 29 |
|
| 30 |
-
|
| 31 |
-
seconds, ms = divmod(int(milliseconds), 1000)
|
| 32 |
-
mins, secs = divmod(seconds, 60)
|
| 33 |
-
hrs, mins = divmod(mins, 60)
|
| 34 |
-
return f"{hrs:02}:{mins:02}:{secs:02},{ms:03}"
|
| 35 |
|
| 36 |
-
|
| 37 |
-
class
|
| 38 |
-
id: int
|
| 39 |
text: str
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
# Check for natural phrase boundaries
|
| 93 |
-
phrase_starters = {'however', 'therefore', 'moreover', 'furthermore', 'meanwhile', 'although', 'because'}
|
| 94 |
-
if i < len(words) - 1 and words[i+1].lower() in phrase_starters:
|
| 95 |
-
weight = max(weight, 0.6)
|
| 96 |
-
|
| 97 |
-
# Check for conjunctions at natural points
|
| 98 |
-
if i > self.min_segment_words:
|
| 99 |
-
conjunctions = {'and', 'but', 'or', 'nor', 'for', 'yet', 'so'}
|
| 100 |
-
if word.lower() in conjunctions:
|
| 101 |
-
weight = max(weight, 0.4)
|
| 102 |
-
|
| 103 |
-
if weight > 0:
|
| 104 |
-
breaks.append((i, weight))
|
| 105 |
-
|
| 106 |
-
return breaks
|
| 107 |
-
|
| 108 |
-
def split_into_segments(self, text: str) -> List[Segment]:
|
| 109 |
-
# Normalize text and add proper spacing around punctuation
|
| 110 |
-
text = re.sub(r'\s+', ' ', text.strip())
|
| 111 |
-
text = re.sub(r'([.!?,;:])\s*', r'\1 ', text)
|
| 112 |
-
text = re.sub(r'\s+([.!?,;:])', r'\1', text)
|
| 113 |
-
|
| 114 |
-
# First, split into major segments by strong punctuation
|
| 115 |
-
segments = []
|
| 116 |
-
current_segment = []
|
| 117 |
-
current_text = ""
|
| 118 |
-
words = text.split()
|
| 119 |
-
|
| 120 |
-
i = 0
|
| 121 |
-
while i < len(words):
|
| 122 |
-
complexity = self.analyze_sentence_complexity(' '.join(words[i:i + self.words_per_line * 2]))
|
| 123 |
-
breaks = self.find_natural_breaks(' '.join(words[i:i + int(self.max_segment_words * complexity)]))
|
| 124 |
-
|
| 125 |
-
# Find best break point
|
| 126 |
-
best_break = None
|
| 127 |
-
best_weight = 0
|
| 128 |
-
|
| 129 |
-
for break_idx, weight in breaks:
|
| 130 |
-
actual_idx = i + break_idx
|
| 131 |
-
if (actual_idx - i >= self.min_segment_words and
|
| 132 |
-
actual_idx - i <= self.max_segment_words):
|
| 133 |
-
if weight > best_weight:
|
| 134 |
-
best_break = break_idx
|
| 135 |
-
best_weight = weight
|
| 136 |
-
|
| 137 |
-
if best_break is None:
|
| 138 |
-
# If no good break found, use maximum length
|
| 139 |
-
best_break = min(self.words_per_line * self.lines_per_segment, len(words) - i)
|
| 140 |
-
|
| 141 |
-
# Create segment
|
| 142 |
-
segment_words = words[i:i + best_break + 1]
|
| 143 |
-
segment_text = ' '.join(segment_words)
|
| 144 |
-
|
| 145 |
-
# Split segment into lines
|
| 146 |
-
lines = self.split_into_lines(segment_text)
|
| 147 |
-
final_segment_text = '\n'.join(lines)
|
| 148 |
-
|
| 149 |
-
segments.append(Segment(
|
| 150 |
-
id=len(segments) + 1,
|
| 151 |
-
text=final_segment_text
|
| 152 |
-
))
|
| 153 |
-
|
| 154 |
-
i += best_break + 1
|
| 155 |
-
|
| 156 |
-
return segments
|
| 157 |
-
|
| 158 |
-
def split_into_lines(self, text: str) -> List[str]:
|
| 159 |
-
"""Split segment text into natural lines"""
|
| 160 |
-
words = text.split()
|
| 161 |
-
lines = []
|
| 162 |
-
current_line = []
|
| 163 |
-
word_count = 0
|
| 164 |
-
|
| 165 |
-
for word in words:
|
| 166 |
-
current_line.append(word)
|
| 167 |
-
word_count += 1
|
| 168 |
-
|
| 169 |
-
# Check for natural line breaks
|
| 170 |
-
is_break = (
|
| 171 |
-
word_count >= self.words_per_line or
|
| 172 |
-
any(word.endswith(p) for p in '.!?') or
|
| 173 |
-
(word_count >= self.words_per_line * 0.7 and
|
| 174 |
-
any(word.endswith(p) for p in ',;:'))
|
| 175 |
)
|
| 176 |
-
|
| 177 |
-
if is_break:
|
| 178 |
-
lines.append(' '.join(current_line))
|
| 179 |
-
current_line = []
|
| 180 |
-
word_count = 0
|
| 181 |
-
|
| 182 |
-
if current_line:
|
| 183 |
-
lines.append(' '.join(current_line))
|
| 184 |
-
|
| 185 |
-
return lines
|
| 186 |
-
|
| 187 |
-
# IMPROVEMENT 1: Enhanced Error Handling
|
| 188 |
-
class TTSError(Exception):
|
| 189 |
-
"""Custom exception for TTS processing errors"""
|
| 190 |
-
pass
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
try:
|
| 201 |
-
await tts.save(audio_file)
|
| 202 |
-
except Exception as e:
|
| 203 |
-
raise TTSError(f"Failed to generate audio for segment {segment.id}: {str(e)}")
|
| 204 |
-
|
| 205 |
-
if not os.path.exists(audio_file) or os.path.getsize(audio_file) == 0:
|
| 206 |
-
raise TTSError(f"Generated audio file is empty or missing for segment {segment.id}")
|
| 207 |
-
|
| 208 |
-
try:
|
| 209 |
-
segment.audio = AudioSegment.from_file(audio_file)
|
| 210 |
-
# Reduced silence to 30ms for more natural flow
|
| 211 |
-
silence = AudioSegment.silent(duration=30)
|
| 212 |
-
segment.audio = silence + segment.audio + silence
|
| 213 |
-
segment.duration = len(segment.audio)
|
| 214 |
except Exception as e:
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
if not isinstance(e, TTSError):
|
| 220 |
-
raise TTSError(f"Unexpected error processing segment {segment.id}: {str(e)}")
|
| 221 |
-
raise
|
| 222 |
-
finally:
|
| 223 |
-
if os.path.exists(audio_file):
|
| 224 |
-
try:
|
| 225 |
-
os.remove(audio_file)
|
| 226 |
-
except Exception:
|
| 227 |
-
pass # Ignore deletion errors
|
| 228 |
|
| 229 |
-
|
| 230 |
-
class FileManager:
|
| 231 |
-
"""Manages temporary and output files with cleanup capabilities"""
|
| 232 |
-
def __init__(self):
|
| 233 |
-
self.temp_dir = tempfile.mkdtemp(prefix="tts_app_")
|
| 234 |
-
self.output_files = []
|
| 235 |
-
self.max_files_to_keep = 5 # Keep only the 5 most recent output pairs
|
| 236 |
-
|
| 237 |
-
def get_temp_path(self, prefix):
|
| 238 |
-
"""Get a path for a temporary file"""
|
| 239 |
-
return os.path.join(self.temp_dir, f"{prefix}_{uuid.uuid4()}")
|
| 240 |
-
|
| 241 |
-
def create_output_paths(self):
|
| 242 |
-
"""Create paths for output files"""
|
| 243 |
-
unique_id = str(uuid.uuid4())
|
| 244 |
-
audio_path = os.path.join(self.temp_dir, f"final_audio_{unique_id}.mp3")
|
| 245 |
-
srt_path = os.path.join(self.temp_dir, f"final_subtitles_{unique_id}.srt")
|
| 246 |
-
|
| 247 |
-
self.output_files.append((srt_path, audio_path))
|
| 248 |
-
self.cleanup_old_files()
|
| 249 |
-
|
| 250 |
-
return srt_path, audio_path
|
| 251 |
-
|
| 252 |
-
def cleanup_old_files(self):
|
| 253 |
-
"""Clean up old output files, keeping only the most recent ones"""
|
| 254 |
-
if len(self.output_files) > self.max_files_to_keep:
|
| 255 |
-
old_files = self.output_files[:-self.max_files_to_keep]
|
| 256 |
-
for srt_path, audio_path in old_files:
|
| 257 |
-
try:
|
| 258 |
-
if os.path.exists(srt_path):
|
| 259 |
-
os.remove(srt_path)
|
| 260 |
-
if os.path.exists(audio_path):
|
| 261 |
-
os.remove(audio_path)
|
| 262 |
-
except Exception:
|
| 263 |
-
pass # Ignore deletion errors
|
| 264 |
-
|
| 265 |
-
# Update the list to only include files we're keeping
|
| 266 |
-
self.output_files = self.output_files[-self.max_files_to_keep:]
|
| 267 |
|
| 268 |
-
|
| 269 |
-
"""Clean up all managed files"""
|
| 270 |
-
for srt_path, audio_path in self.output_files:
|
| 271 |
-
try:
|
| 272 |
-
if os.path.exists(srt_path):
|
| 273 |
-
os.remove(srt_path)
|
| 274 |
-
if os.path.exists(audio_path):
|
| 275 |
-
os.remove(audio_path)
|
| 276 |
-
except Exception:
|
| 277 |
-
pass # Ignore deletion errors
|
| 278 |
-
|
| 279 |
-
try:
|
| 280 |
-
os.rmdir(self.temp_dir)
|
| 281 |
-
except Exception:
|
| 282 |
-
pass # Ignore if directory isn't empty or can't be removed
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
-
|
| 288 |
-
async def
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
rate: str,
|
| 292 |
-
pitch: str,
|
| 293 |
-
words_per_line: int,
|
| 294 |
-
lines_per_segment: int,
|
| 295 |
-
progress_callback=None,
|
| 296 |
-
parallel: bool = True,
|
| 297 |
-
max_workers: int = 4
|
| 298 |
-
) -> Tuple[str, str]:
|
| 299 |
-
"""Generate accurate SRT with parallel processing option"""
|
| 300 |
-
processor = TextProcessor(words_per_line, lines_per_segment)
|
| 301 |
-
segments = processor.split_into_segments(text)
|
| 302 |
-
|
| 303 |
-
total_segments = len(segments)
|
| 304 |
-
processed_segments = []
|
| 305 |
-
|
| 306 |
-
# Update progress to show segmentation is complete
|
| 307 |
-
if progress_callback:
|
| 308 |
-
progress_callback(0.1, "Text segmentation complete")
|
| 309 |
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
segment_tasks = []
|
| 314 |
-
|
| 315 |
-
# Create a semaphore to limit concurrent tasks
|
| 316 |
-
semaphore = asyncio.Semaphore(max_workers)
|
| 317 |
-
|
| 318 |
-
async def process_with_semaphore(segment):
|
| 319 |
-
async with semaphore:
|
| 320 |
-
nonlocal processed_count
|
| 321 |
-
try:
|
| 322 |
-
result = await process_segment_with_timing(segment, voice, rate, pitch)
|
| 323 |
-
processed_count += 1
|
| 324 |
-
if progress_callback:
|
| 325 |
-
progress = 0.1 + (0.8 * processed_count / total_segments)
|
| 326 |
-
progress_callback(progress, f"Processed {processed_count}/{total_segments} segments")
|
| 327 |
-
return result
|
| 328 |
-
except Exception as e:
|
| 329 |
-
# Handle errors in individual segments
|
| 330 |
-
processed_count += 1
|
| 331 |
-
if progress_callback:
|
| 332 |
-
progress = 0.1 + (0.8 * processed_count / total_segments)
|
| 333 |
-
progress_callback(progress, f"Error in segment {segment.id}: {str(e)}")
|
| 334 |
-
raise
|
| 335 |
-
|
| 336 |
-
# Create tasks for all segments
|
| 337 |
-
for segment in segments:
|
| 338 |
-
segment_tasks.append(process_with_semaphore(segment))
|
| 339 |
-
|
| 340 |
-
# Run all tasks and collect results
|
| 341 |
-
try:
|
| 342 |
-
processed_segments = await asyncio.gather(*segment_tasks)
|
| 343 |
-
except Exception as e:
|
| 344 |
-
if progress_callback:
|
| 345 |
-
progress_callback(0.9, f"Error during parallel processing: {str(e)}")
|
| 346 |
-
raise TTSError(f"Failed during parallel processing: {str(e)}")
|
| 347 |
-
else:
|
| 348 |
-
# Process segments sequentially (original method)
|
| 349 |
-
for i, segment in enumerate(segments):
|
| 350 |
-
try:
|
| 351 |
-
processed_segment = await process_segment_with_timing(segment, voice, rate, pitch)
|
| 352 |
-
processed_segments.append(processed_segment)
|
| 353 |
-
|
| 354 |
-
if progress_callback:
|
| 355 |
-
progress = 0.1 + (0.8 * (i + 1) / total_segments)
|
| 356 |
-
progress_callback(progress, f"Processed {i + 1}/{total_segments} segments")
|
| 357 |
-
except Exception as e:
|
| 358 |
-
if progress_callback:
|
| 359 |
-
progress_callback(0.9, f"Error processing segment {segment.id}: {str(e)}")
|
| 360 |
-
raise TTSError(f"Failed to process segment {segment.id}: {str(e)}")
|
| 361 |
|
| 362 |
-
|
| 363 |
-
|
| 364 |
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
f"{segment.id}\n"
|
| 381 |
-
f"{format_time_ms(segment.start_time)} --> {format_time_ms(segment.end_time)}\n"
|
| 382 |
-
f"{segment.text}\n\n"
|
| 383 |
-
)
|
| 384 |
-
|
| 385 |
-
# Add to final audio with precise positioning
|
| 386 |
-
final_audio = final_audio.append(segment.audio, crossfade=0)
|
| 387 |
-
|
| 388 |
-
# Update timing with precise gap
|
| 389 |
-
current_time = segment.end_time
|
| 390 |
-
|
| 391 |
-
# Export with high precision
|
| 392 |
-
srt_path, audio_path = file_manager.create_output_paths()
|
| 393 |
-
|
| 394 |
-
try:
|
| 395 |
-
# Export with optimized quality settings and compression
|
| 396 |
-
export_params = {
|
| 397 |
-
'format': 'mp3',
|
| 398 |
-
'bitrate': '192k', # Reduced from 320k but still high quality
|
| 399 |
-
'parameters': [
|
| 400 |
-
'-ar', '44100', # Standard sample rate
|
| 401 |
-
'-ac', '2', # Stereo
|
| 402 |
-
'-compression_level', '0', # Best compression
|
| 403 |
-
'-qscale:a', '2' # High quality VBR encoding
|
| 404 |
-
]
|
| 405 |
-
}
|
| 406 |
-
final_audio.export(audio_path, **export_params)
|
| 407 |
-
|
| 408 |
-
with open(srt_path, "w", encoding='utf-8') as f:
|
| 409 |
-
f.write(srt_content)
|
| 410 |
-
except Exception as e:
|
| 411 |
-
if progress_callback:
|
| 412 |
-
progress_callback(1.0, f"Error exporting final files: {str(e)}")
|
| 413 |
-
raise TTSError(f"Failed to export final files: {str(e)}")
|
| 414 |
-
|
| 415 |
-
if progress_callback:
|
| 416 |
-
progress_callback(1.0, "Complete!")
|
| 417 |
-
|
| 418 |
-
return srt_path, audio_path
|
| 419 |
|
| 420 |
-
|
| 421 |
-
async def
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
rate,
|
| 425 |
-
voice,
|
| 426 |
-
words_per_line,
|
| 427 |
-
lines_per_segment,
|
| 428 |
-
parallel_processing,
|
| 429 |
-
progress=gr.Progress()
|
| 430 |
-
):
|
| 431 |
-
# Input validation
|
| 432 |
-
if not text or text.strip() == "":
|
| 433 |
-
return None, None, None, True, "Please enter some text to convert to speech."
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
|
|
|
| 438 |
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
progress(0, "Preparing text...")
|
| 442 |
-
|
| 443 |
-
def update_progress(value, status):
|
| 444 |
-
progress(value, status)
|
| 445 |
-
|
| 446 |
-
srt_path, audio_path = await generate_accurate_srt(
|
| 447 |
-
text,
|
| 448 |
-
voice_options[voice],
|
| 449 |
-
rate_str,
|
| 450 |
-
pitch_str,
|
| 451 |
-
words_per_line,
|
| 452 |
-
lines_per_segment,
|
| 453 |
-
progress_callback=update_progress,
|
| 454 |
-
parallel=parallel_processing
|
| 455 |
-
)
|
| 456 |
-
|
| 457 |
-
# If successful, return results and hide error
|
| 458 |
-
return srt_path, audio_path, audio_path, False, ""
|
| 459 |
-
except TTSError as e:
|
| 460 |
-
# Return specific TTS error
|
| 461 |
-
return None, None, None, True, f"TTS Error: {str(e)}"
|
| 462 |
-
except Exception as e:
|
| 463 |
-
# Return any other error
|
| 464 |
-
return None, None, None, True, f"Unexpected error: {str(e)}"
|
| 465 |
-
|
| 466 |
-
# Voice options dictionary
|
| 467 |
-
voice_options = {
|
| 468 |
-
"Andrew Male": "en-US-AndrewNeural",
|
| 469 |
-
"Jenny Female": "en-US-JennyNeural",
|
| 470 |
-
"Guy Male": "en-US-GuyNeural",
|
| 471 |
-
"Ana Female": "en-US-AnaNeural",
|
| 472 |
-
"Aria Female": "en-US-AriaNeural",
|
| 473 |
-
"Brian Male": "en-US-BrianNeural",
|
| 474 |
-
"Christopher Male": "en-US-ChristopherNeural",
|
| 475 |
-
"Eric Male": "en-US-EricNeural",
|
| 476 |
-
"Michelle Male": "en-US-MichelleNeural",
|
| 477 |
-
"Roger Male": "en-US-RogerNeural",
|
| 478 |
-
"Natasha Female": "en-AU-NatashaNeural",
|
| 479 |
-
"William Male": "en-AU-WilliamNeural",
|
| 480 |
-
"Clara Female": "en-CA-ClaraNeural",
|
| 481 |
-
"Liam Female ": "en-CA-LiamNeural",
|
| 482 |
-
"Libby Female": "en-GB-LibbyNeural",
|
| 483 |
-
"Maisie": "en-GB-MaisieNeural",
|
| 484 |
-
"Ryan": "en-GB-RyanNeural",
|
| 485 |
-
"Sonia": "en-GB-SoniaNeural",
|
| 486 |
-
"Thomas": "en-GB-ThomasNeural",
|
| 487 |
-
"Sam": "en-HK-SamNeural",
|
| 488 |
-
"Yan": "en-HK-YanNeural",
|
| 489 |
-
"Connor": "en-IE-ConnorNeural",
|
| 490 |
-
"Emily": "en-IE-EmilyNeural",
|
| 491 |
-
"Neerja": "en-IN-NeerjaNeural",
|
| 492 |
-
"Prabhat": "en-IN-PrabhatNeural",
|
| 493 |
-
"Asilia": "en-KE-AsiliaNeural",
|
| 494 |
-
"Chilemba": "en-KE-ChilembaNeural",
|
| 495 |
-
"Abeo": "en-NG-AbeoNeural",
|
| 496 |
-
"Ezinne": "en-NG-EzinneNeural",
|
| 497 |
-
"Mitchell": "en-NZ-MitchellNeural",
|
| 498 |
-
"James": "en-PH-JamesNeural",
|
| 499 |
-
"Rosa": "en-PH-RosaNeural",
|
| 500 |
-
"Luna": "en-SG-LunaNeural",
|
| 501 |
-
"Wayne": "en-SG-WayneNeural",
|
| 502 |
-
"Elimu": "en-TZ-ElimuNeural",
|
| 503 |
-
"Imani": "en-TZ-ImaniNeural",
|
| 504 |
-
"Leah": "en-ZA-LeahNeural",
|
| 505 |
-
"Luke": "en-ZA-LukeNeural"
|
| 506 |
-
# Add other voices as needed
|
| 507 |
-
}
|
| 508 |
|
| 509 |
-
#
|
| 510 |
-
|
| 511 |
-
|
| 512 |
|
| 513 |
-
#
|
| 514 |
-
|
| 515 |
-
gr.Markdown("# Advanced TTS with Configurable SRT Generation")
|
| 516 |
-
gr.Markdown("Generate perfectly synchronized audio and subtitles with natural speech patterns.")
|
| 517 |
-
|
| 518 |
-
with gr.Row():
|
| 519 |
-
with gr.Column(scale=3):
|
| 520 |
-
text_input = gr.Textbox(label="Enter Text", lines=10, placeholder="Enter your text here...")
|
| 521 |
-
|
| 522 |
-
with gr.Column(scale=2):
|
| 523 |
-
voice_dropdown = gr.Dropdown(
|
| 524 |
-
label="Select Voice",
|
| 525 |
-
choices=list(voice_options.keys()),
|
| 526 |
-
value="Jenny Female"
|
| 527 |
-
)
|
| 528 |
-
pitch_slider = gr.Slider(
|
| 529 |
-
label="Pitch Adjustment (Hz)",
|
| 530 |
-
minimum=-10,
|
| 531 |
-
maximum=10,
|
| 532 |
-
value=0,
|
| 533 |
-
step=1
|
| 534 |
-
)
|
| 535 |
-
rate_slider = gr.Slider(
|
| 536 |
-
label="Rate Adjustment (%)",
|
| 537 |
-
minimum=-25,
|
| 538 |
-
maximum=25,
|
| 539 |
-
value=0,
|
| 540 |
-
step=1
|
| 541 |
-
)
|
| 542 |
-
|
| 543 |
-
with gr.Row():
|
| 544 |
-
with gr.Column():
|
| 545 |
-
words_per_line = gr.Slider(
|
| 546 |
-
label="Words per Line",
|
| 547 |
-
minimum=3,
|
| 548 |
-
maximum=12,
|
| 549 |
-
value=6,
|
| 550 |
-
step=1,
|
| 551 |
-
info="Controls how many words appear on each line of the subtitle"
|
| 552 |
-
)
|
| 553 |
-
with gr.Column():
|
| 554 |
-
lines_per_segment = gr.Slider(
|
| 555 |
-
label="Lines per Segment",
|
| 556 |
-
minimum=1,
|
| 557 |
-
maximum=4,
|
| 558 |
-
value=2,
|
| 559 |
-
step=1,
|
| 560 |
-
info="Controls how many lines appear in each subtitle segment"
|
| 561 |
-
)
|
| 562 |
-
with gr.Column():
|
| 563 |
-
parallel_processing = gr.Checkbox(
|
| 564 |
-
label="Enable Parallel Processing",
|
| 565 |
-
value=True,
|
| 566 |
-
info="Process multiple segments simultaneously for faster conversion (recommended for longer texts)"
|
| 567 |
-
)
|
| 568 |
-
|
| 569 |
-
submit_btn = gr.Button("Generate Audio & Subtitles")
|
| 570 |
-
|
| 571 |
-
# Add error message component
|
| 572 |
-
error_output = gr.Textbox(label="Status", visible=False)
|
| 573 |
-
|
| 574 |
-
with gr.Row():
|
| 575 |
-
with gr.Column():
|
| 576 |
-
audio_output = gr.Audio(label="Preview Audio")
|
| 577 |
-
with gr.Column():
|
| 578 |
-
srt_file = gr.File(label="Download SRT")
|
| 579 |
-
audio_file = gr.File(label="Download Audio")
|
| 580 |
-
|
| 581 |
-
# Handle button click with manual error handling instead of .catch()
|
| 582 |
-
submit_btn.click(
|
| 583 |
-
fn=process_text_with_progress,
|
| 584 |
-
inputs=[
|
| 585 |
-
text_input,
|
| 586 |
-
pitch_slider,
|
| 587 |
-
rate_slider,
|
| 588 |
-
voice_dropdown,
|
| 589 |
-
words_per_line,
|
| 590 |
-
lines_per_segment,
|
| 591 |
-
parallel_processing
|
| 592 |
-
],
|
| 593 |
-
outputs=[
|
| 594 |
-
srt_file,
|
| 595 |
-
audio_file,
|
| 596 |
-
audio_output,
|
| 597 |
-
error_output,
|
| 598 |
-
error_output
|
| 599 |
-
],
|
| 600 |
-
api_name="generate"
|
| 601 |
-
)
|
| 602 |
|
| 603 |
if __name__ == "__main__":
|
| 604 |
-
app.
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import FileResponse, JSONResponse
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
import gradio as gr
|
| 6 |
+
from typing import Optional, Dict, Any
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import time
|
| 8 |
+
import uvicorn
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import psutil
|
| 11 |
+
import asyncio
|
| 12 |
+
from app import (
|
| 13 |
+
generate_accurate_srt,
|
| 14 |
+
voice_options,
|
| 15 |
+
TTSError,
|
| 16 |
+
FileManager
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# Initialize FastAPI app
|
| 20 |
+
app = FastAPI(
|
| 21 |
+
title="TTS API Service",
|
| 22 |
+
description="Text-to-Speech API with real-time status monitoring",
|
| 23 |
+
version="1.0.0"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Configure CORS
|
| 27 |
+
app.add_middleware(
|
| 28 |
+
CORSMiddleware,
|
| 29 |
+
allow_origins=["*"],
|
| 30 |
+
allow_credentials=True,
|
| 31 |
+
allow_methods=["*"],
|
| 32 |
+
allow_headers=["*"],
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Global state management
|
| 36 |
+
class ProcessingState:
|
| 37 |
def __init__(self):
|
| 38 |
+
self.active_jobs: Dict[str, Dict[str, Any]] = {}
|
| 39 |
+
self.file_manager = FileManager()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
state = ProcessingState()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
# Pydantic models
|
| 44 |
+
class TTSRequest(BaseModel):
|
|
|
|
| 45 |
text: str
|
| 46 |
+
voice: str = "Jenny Female"
|
| 47 |
+
pitch: int = 0
|
| 48 |
+
rate: int = 0
|
| 49 |
+
words_per_line: int = 6
|
| 50 |
+
lines_per_segment: int = 2
|
| 51 |
+
parallel_processing: bool = True
|
| 52 |
+
|
| 53 |
+
class HealthResponse(BaseModel):
|
| 54 |
+
status: str
|
| 55 |
+
timestamp: str
|
| 56 |
+
cpu_usage: float
|
| 57 |
+
memory_usage: float
|
| 58 |
+
active_jobs: int
|
| 59 |
+
|
| 60 |
+
# Progress callback handler
|
| 61 |
+
async def update_job_progress(job_id: str, progress: float, status: str):
|
| 62 |
+
state.active_jobs[job_id].update({
|
| 63 |
+
"progress": progress,
|
| 64 |
+
"status": status,
|
| 65 |
+
"last_update": datetime.now().isoformat()
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
# API endpoints
|
| 69 |
+
@app.post("/api/v1/tts")
|
| 70 |
+
async def create_tts(request: TTSRequest, background_tasks: BackgroundTasks):
|
| 71 |
+
job_id = f"job_{int(time.time())}_{hash(request.text)}"
|
| 72 |
+
|
| 73 |
+
# Initialize job status
|
| 74 |
+
state.active_jobs[job_id] = {
|
| 75 |
+
"id": job_id,
|
| 76 |
+
"status": "queued",
|
| 77 |
+
"progress": 0,
|
| 78 |
+
"created_at": datetime.now().isoformat(),
|
| 79 |
+
"last_update": datetime.now().isoformat(),
|
| 80 |
+
"request": request.dict()
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
async def process_tts():
|
| 84 |
+
try:
|
| 85 |
+
# Format pitch and rate strings
|
| 86 |
+
pitch_str = f"{request.pitch:+d}Hz"
|
| 87 |
+
rate_str = f"{request.rate:+d}%"
|
| 88 |
+
|
| 89 |
+
srt_path, audio_path = await generate_accurate_srt(
|
| 90 |
+
request.text,
|
| 91 |
+
voice_options[request.voice],
|
| 92 |
+
rate_str,
|
| 93 |
+
pitch_str,
|
| 94 |
+
request.words_per_line,
|
| 95 |
+
request.lines_per_segment,
|
| 96 |
+
progress_callback=lambda p, s: update_job_progress(job_id, p, s),
|
| 97 |
+
parallel=request.parallel_processing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
state.active_jobs[job_id].update({
|
| 101 |
+
"status": "completed",
|
| 102 |
+
"progress": 1.0,
|
| 103 |
+
"result": {
|
| 104 |
+
"srt_path": srt_path,
|
| 105 |
+
"audio_path": audio_path
|
| 106 |
+
}
|
| 107 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
except Exception as e:
|
| 109 |
+
state.active_jobs[job_id].update({
|
| 110 |
+
"status": "failed",
|
| 111 |
+
"error": str(e)
|
| 112 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
background_tasks.add_task(process_tts)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
+
return {"job_id": job_id, "status": "queued"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
@app.get("/api/v1/status/{job_id}")
|
| 119 |
+
async def get_job_status(job_id: str):
|
| 120 |
+
if job_id not in state.active_jobs:
|
| 121 |
+
raise HTTPException(status_code=404, detail="Job not found")
|
| 122 |
+
return state.active_jobs[job_id]
|
| 123 |
|
| 124 |
+
@app.get("/api/v1/download/{job_id}/{file_type}")
|
| 125 |
+
async def download_file(job_id: str, file_type: str):
|
| 126 |
+
if job_id not in state.active_jobs:
|
| 127 |
+
raise HTTPException(status_code=404, detail="Job not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
job = state.active_jobs[job_id]
|
| 130 |
+
if job["status"] != "completed":
|
| 131 |
+
raise HTTPException(status_code=400, detail="Job not completed")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
if file_type not in ["audio", "srt"]:
|
| 134 |
+
raise HTTPException(status_code=400, detail="Invalid file type")
|
| 135 |
|
| 136 |
+
file_path = job["result"][f"{file_type}_path"]
|
| 137 |
+
return FileResponse(
|
| 138 |
+
file_path,
|
| 139 |
+
filename=f"tts_output.{file_type}"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
@app.get("/api/v1/health", response_model=HealthResponse)
|
| 143 |
+
async def health_check():
|
| 144 |
+
return {
|
| 145 |
+
"status": "healthy",
|
| 146 |
+
"timestamp": datetime.now().isoformat(),
|
| 147 |
+
"cpu_usage": psutil.cpu_percent(),
|
| 148 |
+
"memory_usage": psutil.virtual_memory().percent,
|
| 149 |
+
"active_jobs": len(state.active_jobs)
|
| 150 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
@app.delete("/api/v1/jobs/{job_id}")
|
| 153 |
+
async def cancel_job(job_id: str):
|
| 154 |
+
if job_id not in state.active_jobs:
|
| 155 |
+
raise HTTPException(status_code=404, detail="Job not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
+
job = state.active_jobs[job_id]
|
| 158 |
+
if job["status"] in ["completed", "failed"]:
|
| 159 |
+
del state.active_jobs[job_id]
|
| 160 |
+
return {"status": "deleted"}
|
| 161 |
|
| 162 |
+
job["status"] = "cancelled"
|
| 163 |
+
return {"status": "cancelled"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
# Initialize Gradio interface
|
| 166 |
+
with gr.Blocks() as gradio_app:
|
| 167 |
+
# ...existing gradio interface code...
|
| 168 |
|
| 169 |
+
# Mount Gradio app
|
| 170 |
+
app = gr.mount_gradio_app(app, gradio_app, path="/")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
if __name__ == "__main__":
|
| 173 |
+
uvicorn.run("fastapi_app:app", host="0.0.0.0", port=8000, reload=True)
|