hivecorp commited on
Commit
c5c349b
·
verified ·
1 Parent(s): 8428946

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -65
app.py CHANGED
@@ -7,90 +7,129 @@ import tempfile
7
  from datetime import timedelta
8
  from pydub import AudioSegment
9
 
10
- # Define the Edge TTS settings
11
  DEFAULT_VOICE = "en-US-AndrewNeural"
12
  DEFAULT_RATE = "-25%"
13
 
14
- # Function to generate TTS audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  async def generate_audio(text, voice=DEFAULT_VOICE, rate=DEFAULT_RATE):
16
  communicate = edge_tts.Communicate(text, voice, rate)
17
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
18
  await communicate.save(temp_audio.name)
19
  return temp_audio.name
20
 
21
- # Function to get audio length in seconds
22
- def get_audio_length(audio_path):
23
- audio = AudioSegment.from_file(audio_path)
24
- return audio.duration_seconds
25
-
26
- # Function to generate and adjust SRT timings
27
- def generate_accurate_srt(text, audio_path):
28
  srt_entries = []
29
- total_duration = get_audio_length(audio_path)
30
- words = text.split()
31
- words_per_segment = 10 # 8-10 words per segment
32
- segment_duration = total_duration / (len(words) // words_per_segment)
33
-
34
- for i in range(0, len(words), words_per_segment):
35
- segment_words = words[i:i+words_per_segment]
36
- start_time = timedelta(seconds=i // words_per_segment * segment_duration)
37
- end_time = timedelta(seconds=(i // words_per_segment + 1) * segment_duration)
38
 
39
- # Ensure each segment has proper punctuation
40
- srt_entry = srt.Subtitle(index=i // words_per_segment + 1,
 
 
 
 
 
41
  start=start_time,
42
  end=end_time,
43
- content=" ".join(segment_words))
 
44
  srt_entries.append(srt_entry)
45
-
46
- # Cross-check timings to fit actual audio length
47
- final_srt = []
48
- current_time = 0
49
- for entry in srt_entries:
50
- entry_duration = (entry.end - entry.start).total_seconds()
51
- adjusted_end = min(current_time + entry_duration, total_duration)
52
- entry.start = timedelta(seconds=current_time)
53
- entry.end = timedelta(seconds=adjusted_end)
54
- final_srt.append(entry)
55
- current_time += entry_duration
56
-
57
- return list(srt.parse(srt.compose(final_srt)))
58
 
59
- # Function to create SRT file with batch processing
60
- def batch_process_srt_and_audio(text_list):
61
- srt_results = []
62
- audio_files = []
63
-
64
- for text in text_list:
65
- audio_path = asyncio.run(generate_audio(text))
66
- srt_content = generate_accurate_srt(text, audio_path)
67
-
68
- srt_path = tempfile.mktemp(suffix=".srt")
69
- with open(srt_path, "w") as srt_file:
70
- srt_file.write(srt.compose(srt_content))
71
-
72
- srt_results.append(srt_path)
73
- audio_files.append(audio_path)
74
-
75
- return srt_results, audio_files
76
 
77
- # Gradio Interface
78
- def process_batch(texts):
79
- srt_files, audio_files = batch_process_srt_and_audio(texts)
80
- audio_previews = [gr.Audio.update(label=f"Audio {i+1}", value=file) for i, file in enumerate(audio_files)]
81
- srt_previews = [gr.File.update(label=f"SRT {i+1}", value=srt_file) for i, srt_file in enumerate(srt_files)]
82
- return audio_previews, srt_previews
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- # Gradio App Interface
85
  with gr.Blocks() as app:
86
- gr.Markdown("### Batch Audio and SRT Generator")
87
- text_inputs = gr.Textbox(placeholder="Enter multiple texts separated by a new line", lines=10, label="Text Input")
88
 
89
  with gr.Row():
90
- audio_preview = gr.Audio(label="Generated Audio", type="filepath")
91
- srt_preview = gr.File(label="Generated SRT")
92
-
93
- process_button = gr.Button("Process Batch")
94
- process_button.click(fn=process_batch, inputs=text_inputs, outputs=[audio_preview, srt_preview])
95
 
96
  app.launch()
 
7
  from datetime import timedelta
8
  from pydub import AudioSegment
9
 
10
+ # Define Edge TTS settings
11
  DEFAULT_VOICE = "en-US-AndrewNeural"
12
  DEFAULT_RATE = "-25%"
13
 
14
+ # Split the script into batches of 300-320 words, keeping punctuation in mind
15
+ def split_into_batches(script, batch_size=320):
16
+ words = script.split()
17
+ batches = []
18
+ current_batch = []
19
+ word_count = 0
20
+
21
+ for word in words:
22
+ current_batch.append(word)
23
+ word_count += 1
24
+ # Check if current batch reached limit or ends with punctuation
25
+ if word_count >= batch_size or word.endswith((".", "?", "!")):
26
+ batches.append(" ".join(current_batch))
27
+ current_batch = []
28
+ word_count = 0
29
+
30
+ if current_batch:
31
+ batches.append(" ".join(current_batch))
32
+
33
+ return batches
34
+
35
+ # Further divide each batch into 5-8 words per segment based on punctuation
36
+ def split_into_segments(batch, segment_size=7):
37
+ words = batch.split()
38
+ segments = []
39
+ segment = []
40
+
41
+ for i, word in enumerate(words):
42
+ segment.append(word)
43
+ if len(segment) >= segment_size or word.endswith((".", "?", "!")):
44
+ segments.append(" ".join(segment))
45
+ segment = []
46
+
47
+ if segment:
48
+ segments.append(" ".join(segment))
49
+
50
+ return segments
51
+
52
+ # Generate TTS audio asynchronously for each segment
53
  async def generate_audio(text, voice=DEFAULT_VOICE, rate=DEFAULT_RATE):
54
  communicate = edge_tts.Communicate(text, voice, rate)
55
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
56
  await communicate.save(temp_audio.name)
57
  return temp_audio.name
58
 
59
+ # Create and adjust SRT for each segment with accurate timing
60
+ async def generate_srt_for_batch(batch_text, batch_index):
61
+ segments = split_into_segments(batch_text)
 
 
 
 
62
  srt_entries = []
63
+ segment_audio_files = []
64
+
65
+ current_time = timedelta(seconds=0)
66
+
67
+ for i, segment in enumerate(segments):
68
+ # Generate audio and get duration for the current segment
69
+ audio_path = await generate_audio(segment)
70
+ segment_audio_files.append(audio_path)
 
71
 
72
+ # Get duration of generated audio
73
+ segment_duration = get_audio_length(audio_path)
74
+
75
+ # Create SRT entry for each segment
76
+ start_time = current_time
77
+ end_time = start_time + timedelta(seconds=segment_duration)
78
+ srt_entry = srt.Subtitle(index=(batch_index * 100) + i + 1,
79
  start=start_time,
80
  end=end_time,
81
+ content=segment)
82
+
83
  srt_entries.append(srt_entry)
84
+ current_time = end_time
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ return srt_entries, segment_audio_files
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ # Get audio length in seconds
89
+ def get_audio_length(audio_path):
90
+ audio = AudioSegment.from_file(audio_path)
91
+ return audio.duration_seconds
92
+
93
+ # Process all batches, generate audio and SRT
94
+ async def process_script(script):
95
+ batches = split_into_batches(script)
96
+ all_srt_entries = []
97
+ all_audio_files = []
98
+
99
+ # Process each batch sequentially (for large scripts, implement concurrency)
100
+ for batch_index, batch_text in enumerate(batches):
101
+ srt_entries, audio_files = await generate_srt_for_batch(batch_text, batch_index)
102
+ all_srt_entries.extend(srt_entries)
103
+ all_audio_files.extend(audio_files)
104
+
105
+ # Concatenate all audio files into one final audio file
106
+ final_audio_path = tempfile.mktemp(suffix=".wav")
107
+ combined_audio = AudioSegment.empty()
108
+ for audio_file in all_audio_files:
109
+ combined_audio += AudioSegment.from_file(audio_file)
110
+ combined_audio.export(final_audio_path, format="wav")
111
+
112
+ # Generate the final SRT file with accurate timings
113
+ final_srt_path = tempfile.mktemp(suffix=".srt")
114
+ with open(final_srt_path, "w") as srt_file:
115
+ srt_file.write(srt.compose(all_srt_entries))
116
+
117
+ return final_audio_path, final_srt_path
118
+
119
+ # Gradio Interface for Script Input and Output
120
+ def generate_output(script):
121
+ final_audio_path, final_srt_path = asyncio.run(process_script(script))
122
+ return final_audio_path, final_srt_path
123
 
 
124
  with gr.Blocks() as app:
125
+ gr.Markdown("### Text to Speech with Batch Processing and SRT Generation")
126
+ text_input = gr.Textbox(placeholder="Enter your script here", lines=10, label="Script Input")
127
 
128
  with gr.Row():
129
+ audio_output = gr.Audio(label="Final Audio", type="filepath")
130
+ srt_output = gr.File(label="Final SRT")
131
+
132
+ process_button = gr.Button("Generate Audio and SRT")
133
+ process_button.click(fn=generate_output, inputs=text_input, outputs=[audio_output, srt_output])
134
 
135
  app.launch()