Spaces:
Sleeping
Sleeping
Update app.py
Browse filesAdded video support as input
app.py
CHANGED
@@ -1,514 +1,609 @@
|
|
1 |
-
import os
|
2 |
-
import tempfile
|
3 |
-
import json
|
4 |
-
import pandas as pd
|
5 |
-
import gradio as gr
|
6 |
-
from aeneas.executetask import ExecuteTask
|
7 |
-
from aeneas.task import Task
|
8 |
-
import traceback
|
9 |
-
import re
|
10 |
-
import webvtt
|
11 |
-
import threading
|
12 |
-
import uvicorn
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
if
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
result.append(current_line.strip())
|
71 |
-
current_line =
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
srt_output.append(
|
108 |
-
srt_output.append("
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
return
|
121 |
-
|
122 |
-
return
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
# Create
|
209 |
-
|
210 |
-
|
211 |
-
#
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
514 |
main()
|
|
|
1 |
+
import os
|
2 |
+
import tempfile
|
3 |
+
import json
|
4 |
+
import pandas as pd
|
5 |
+
import gradio as gr
|
6 |
+
from aeneas.executetask import ExecuteTask
|
7 |
+
from aeneas.task import Task
|
8 |
+
import traceback
|
9 |
+
import re
|
10 |
+
import webvtt
|
11 |
+
import threading
|
12 |
+
import uvicorn
|
13 |
+
import subprocess
|
14 |
+
import shutil
|
15 |
+
from pathlib import Path
|
16 |
+
|
17 |
+
|
18 |
+
|
19 |
+
def wrap_text(text, max_line_length=29):
|
20 |
+
words = text.split()
|
21 |
+
lines = []
|
22 |
+
current_line = []
|
23 |
+
|
24 |
+
for word in words:
|
25 |
+
if len(' '.join(current_line + [word])) <= max_line_length:
|
26 |
+
current_line.append(word)
|
27 |
+
else:
|
28 |
+
if current_line:
|
29 |
+
lines.append(' '.join(current_line))
|
30 |
+
current_line = [word]
|
31 |
+
|
32 |
+
if current_line:
|
33 |
+
lines.append(' '.join(current_line))
|
34 |
+
|
35 |
+
return '\n'.join(lines)
|
36 |
+
|
37 |
+
|
38 |
+
def segment_text_file(input_content, output_path,):
|
39 |
+
|
40 |
+
words = re.findall(r'\S+', input_content)
|
41 |
+
if not words:
|
42 |
+
return ""
|
43 |
+
|
44 |
+
result = []
|
45 |
+
current_line = ""
|
46 |
+
|
47 |
+
for word in words:
|
48 |
+
remaining_line = ""
|
49 |
+
if len(current_line) + len(word) + 1 <= 58:
|
50 |
+
current_line += word + " "
|
51 |
+
else:
|
52 |
+
if current_line:
|
53 |
+
if '.' in current_line[29:]:
|
54 |
+
crr_line = current_line.split('.')
|
55 |
+
remaining_line = crr_line[-1].strip()
|
56 |
+
if len(crr_line) > 2:
|
57 |
+
current_line = ''.join([cr + "." for cr in crr_line[:-1]])
|
58 |
+
else:
|
59 |
+
current_line = crr_line[0].strip() + '.'
|
60 |
+
|
61 |
+
# Check wrapped lines and extract excess if any
|
62 |
+
wrapped = wrap_text(current_line).split('\n')
|
63 |
+
result1 = '\n'.join(wrapped[2:])
|
64 |
+
if result1:
|
65 |
+
moved_word = result1
|
66 |
+
current_line = current_line.rstrip()
|
67 |
+
if current_line.endswith(moved_word):
|
68 |
+
current_line = current_line[:-(len(moved_word))].rstrip()
|
69 |
+
|
70 |
+
result.append(current_line.strip())
|
71 |
+
current_line = moved_word + " "
|
72 |
+
else:
|
73 |
+
result.append(current_line.strip())
|
74 |
+
current_line = remaining_line + " " + word + " "
|
75 |
+
else:
|
76 |
+
current_line = remaining_line + " " + word + " "
|
77 |
+
|
78 |
+
if current_line:
|
79 |
+
result.append(current_line.strip())
|
80 |
+
|
81 |
+
# Write segmented output
|
82 |
+
with open(output_path, "w", encoding="utf-8") as f:
|
83 |
+
for seg in result:
|
84 |
+
f.write(seg.strip() + "\n")
|
85 |
+
|
86 |
+
|
87 |
+
def convert_to_srt(fragments):
|
88 |
+
def format_timestamp(seconds):
|
89 |
+
h = int(seconds // 3600)
|
90 |
+
m = int((seconds % 3600) // 60)
|
91 |
+
s = int(seconds % 60)
|
92 |
+
ms = int((seconds - int(seconds)) * 1000)
|
93 |
+
return f"{h:02}:{m:02}:{s:02},{ms:03}"
|
94 |
+
|
95 |
+
srt_output = []
|
96 |
+
index = 1
|
97 |
+
for f in fragments:
|
98 |
+
start = float(f.begin)
|
99 |
+
end = float(f.end)
|
100 |
+
text = f.text.strip()
|
101 |
+
|
102 |
+
if end <= start or not text:
|
103 |
+
continue
|
104 |
+
|
105 |
+
lines = wrap_text(text)
|
106 |
+
|
107 |
+
srt_output.append(f"{index}")
|
108 |
+
srt_output.append(f"{format_timestamp(start)} --> {format_timestamp(end)}")
|
109 |
+
srt_output.append(lines)
|
110 |
+
srt_output.append("") # Empty line
|
111 |
+
index += 1
|
112 |
+
|
113 |
+
return "\n".join(srt_output)
|
114 |
+
|
115 |
+
|
116 |
+
def check_ffmpeg():
|
117 |
+
"""Check if FFmpeg is available on the system"""
|
118 |
+
try:
|
119 |
+
subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True)
|
120 |
+
return True
|
121 |
+
except (subprocess.CalledProcessError, FileNotFoundError):
|
122 |
+
return False
|
123 |
+
|
124 |
+
|
125 |
+
def is_video_file(file_path):
|
126 |
+
"""Check if the file is a video file based on extension"""
|
127 |
+
video_extensions = {'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp', '.mpg', '.mpeg'}
|
128 |
+
return Path(file_path).suffix.lower() in video_extensions
|
129 |
+
|
130 |
+
|
131 |
+
def is_audio_file(file_path):
|
132 |
+
"""Check if the file is an audio file based on extension"""
|
133 |
+
audio_extensions = {'.wav', '.mp3', '.flac', '.aac', '.ogg', '.wma', '.m4a', '.opus'}
|
134 |
+
return Path(file_path).suffix.lower() in audio_extensions
|
135 |
+
|
136 |
+
|
137 |
+
def convert_video_to_audio(video_path, output_path):
|
138 |
+
"""Convert video file to audio using FFmpeg"""
|
139 |
+
try:
|
140 |
+
# Use FFmpeg to extract audio from video
|
141 |
+
cmd = [
|
142 |
+
'ffmpeg', '-i', video_path,
|
143 |
+
'-vn', # No video
|
144 |
+
'-acodec', 'libmp3lame', # MP3 codec
|
145 |
+
'-ab', '192k', # Audio bitrate
|
146 |
+
'-ar', '44100', # Sample rate
|
147 |
+
'-y', # Overwrite output file
|
148 |
+
output_path
|
149 |
+
]
|
150 |
+
|
151 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
152 |
+
|
153 |
+
if result.returncode != 0:
|
154 |
+
raise RuntimeError(f"FFmpeg conversion failed: {result.stderr}")
|
155 |
+
|
156 |
+
return True
|
157 |
+
except Exception as e:
|
158 |
+
raise RuntimeError(f"Error converting video to audio: {str(e)}")
|
159 |
+
|
160 |
+
|
161 |
+
def get_media_file_path(media_input):
|
162 |
+
"""Get file path from media input (audio or video)"""
|
163 |
+
if media_input is None:
|
164 |
+
return None
|
165 |
+
|
166 |
+
if isinstance(media_input, str):
|
167 |
+
return media_input
|
168 |
+
elif isinstance(media_input, tuple) and len(media_input) >= 2:
|
169 |
+
return media_input[1] if isinstance(media_input[1], str) else media_input[0]
|
170 |
+
else:
|
171 |
+
print(f"Debug: Unexpected media input type: {type(media_input)}")
|
172 |
+
return str(media_input)
|
173 |
+
|
174 |
+
|
175 |
+
def get_text_file_path(text_input):
|
176 |
+
if text_input is None:
|
177 |
+
return None
|
178 |
+
|
179 |
+
if isinstance(text_input, dict):
|
180 |
+
return text_input['name']
|
181 |
+
elif isinstance(text_input, str):
|
182 |
+
return text_input
|
183 |
+
else:
|
184 |
+
print(f"Debug: Unexpected text input type: {type(text_input)}")
|
185 |
+
return str(text_input)
|
186 |
+
|
187 |
+
|
188 |
+
def process_alignment(media_file, text_file, language, progress=gr.Progress()):
|
189 |
+
|
190 |
+
if media_file is None:
|
191 |
+
return "β Please upload an audio or video file", None, None, "", None, None
|
192 |
+
|
193 |
+
if text_file is None:
|
194 |
+
return "β Please upload a text file", None, None, "", None, None
|
195 |
+
|
196 |
+
# Check if FFmpeg is available
|
197 |
+
if not check_ffmpeg():
|
198 |
+
return "β FFmpeg not found. Please install FFmpeg to process video files.", None, None, "", None, None
|
199 |
+
|
200 |
+
# Initialize variables for cleanup
|
201 |
+
temp_text_file_path = None
|
202 |
+
temp_audio_file_path = None
|
203 |
+
output_file = None
|
204 |
+
|
205 |
+
try:
|
206 |
+
progress(0.1, desc="Initializing...")
|
207 |
+
|
208 |
+
# Create temporary directory for better file handling
|
209 |
+
temp_dir = tempfile.mkdtemp()
|
210 |
+
|
211 |
+
# Get the media file path
|
212 |
+
media_file_path = get_media_file_path(media_file)
|
213 |
+
if not media_file_path:
|
214 |
+
raise ValueError("Could not determine media file path")
|
215 |
+
|
216 |
+
# Verify media file exists
|
217 |
+
if not os.path.exists(media_file_path):
|
218 |
+
raise FileNotFoundError(f"Media file not found: {media_file_path}")
|
219 |
+
|
220 |
+
# Process media file - convert video to audio if needed
|
221 |
+
if is_video_file(media_file_path):
|
222 |
+
progress(0.2, desc="Converting video to audio...")
|
223 |
+
temp_audio_file_path = os.path.join(temp_dir, "extracted_audio.mp3")
|
224 |
+
convert_video_to_audio(media_file_path, temp_audio_file_path)
|
225 |
+
audio_file_path = temp_audio_file_path
|
226 |
+
print(f"Debug: Video converted to audio: {audio_file_path}")
|
227 |
+
elif is_audio_file(media_file_path):
|
228 |
+
audio_file_path = media_file_path
|
229 |
+
print(f"Debug: Using audio file directly: {audio_file_path}")
|
230 |
+
else:
|
231 |
+
raise ValueError("Unsupported file format. Please provide an audio or video file.")
|
232 |
+
|
233 |
+
# Get the text file path
|
234 |
+
text_file_path = get_text_file_path(text_file)
|
235 |
+
if not text_file_path:
|
236 |
+
raise ValueError("Could not determine text file path")
|
237 |
+
|
238 |
+
print(f"Debug: Text file path: {text_file_path}")
|
239 |
+
|
240 |
+
# Verify text file exists and read content
|
241 |
+
if not os.path.exists(text_file_path):
|
242 |
+
raise FileNotFoundError(f"Text file not found: {text_file_path}")
|
243 |
+
|
244 |
+
# Read and validate text content
|
245 |
+
try:
|
246 |
+
with open(text_file_path, 'r', encoding='utf-8') as f:
|
247 |
+
text_content = f.read().strip()
|
248 |
+
except UnicodeDecodeError:
|
249 |
+
# Try with different encoding if UTF-8 fails
|
250 |
+
with open(text_file_path, 'r', encoding='latin-1') as f:
|
251 |
+
text_content = f.read().strip()
|
252 |
+
|
253 |
+
if not text_content:
|
254 |
+
raise ValueError("Text file is empty or contains only whitespace")
|
255 |
+
|
256 |
+
progress(0.3, desc="Processing text file...")
|
257 |
+
|
258 |
+
temp_text_file_path = os.path.join(temp_dir, "input_text.txt")
|
259 |
+
segment_text_file(text_content, temp_text_file_path)
|
260 |
+
|
261 |
+
# Verify temp text file was created
|
262 |
+
if not os.path.exists(temp_text_file_path):
|
263 |
+
raise RuntimeError("Failed to create temporary text file")
|
264 |
+
|
265 |
+
# Create output file path
|
266 |
+
output_file = os.path.join(temp_dir, "alignment_output.json")
|
267 |
+
|
268 |
+
progress(0.4, desc="Creating task configuration...")
|
269 |
+
|
270 |
+
# Create task configuration
|
271 |
+
config_string = f"task_language={language}|is_text_type=plain|os_task_file_format=json"
|
272 |
+
|
273 |
+
# Create and configure the task
|
274 |
+
task = Task(config_string=config_string)
|
275 |
+
|
276 |
+
# Set absolute paths
|
277 |
+
task.audio_file_path_absolute = os.path.abspath(audio_file_path)
|
278 |
+
task.text_file_path_absolute = os.path.abspath(temp_text_file_path)
|
279 |
+
task.sync_map_file_path_absolute = os.path.abspath(output_file)
|
280 |
+
|
281 |
+
progress(0.5, desc="Running alignment... This may take a while...")
|
282 |
+
|
283 |
+
# Execute the alignment
|
284 |
+
ExecuteTask(task).execute()
|
285 |
+
|
286 |
+
progress(0.8, desc="Processing results...")
|
287 |
+
|
288 |
+
# output sync map to file
|
289 |
+
task.output_sync_map_file()
|
290 |
+
|
291 |
+
# Check if output file was created
|
292 |
+
if not os.path.exists(output_file):
|
293 |
+
raise RuntimeError(f"Alignment output file was not created: {output_file}")
|
294 |
+
|
295 |
+
# Read and process results
|
296 |
+
with open(output_file, 'r', encoding='utf-8') as f:
|
297 |
+
results = json.load(f)
|
298 |
+
|
299 |
+
# Read output and convert to SRT
|
300 |
+
fragments = task.sync_map.fragments
|
301 |
+
srt_content = convert_to_srt(fragments)
|
302 |
+
|
303 |
+
srt_path = os.path.join(temp_dir, "output.srt")
|
304 |
+
vtt_path = os.path.join(temp_dir, "output.vtt")
|
305 |
+
with open(srt_path, "w", encoding="utf-8") as f:
|
306 |
+
f.write(srt_content)
|
307 |
+
|
308 |
+
webvtt.from_srt(srt_path).save()
|
309 |
+
|
310 |
+
if 'fragments' not in results or not results['fragments']:
|
311 |
+
raise RuntimeError("No alignment fragments found in results")
|
312 |
+
|
313 |
+
# Create DataFrame for display
|
314 |
+
df_data = []
|
315 |
+
for i, fragment in enumerate(results['fragments']):
|
316 |
+
start_time = float(fragment['begin'])
|
317 |
+
end_time = float(fragment['end'])
|
318 |
+
duration = end_time - start_time
|
319 |
+
text = fragment['lines'][0] if fragment['lines'] else ""
|
320 |
+
|
321 |
+
df_data.append({
|
322 |
+
'Segment': i + 1,
|
323 |
+
'Start (s)': f"{start_time:.3f}",
|
324 |
+
'End (s)': f"{end_time:.3f}",
|
325 |
+
'Duration (s)': f"{duration:.3f}",
|
326 |
+
'Text': text
|
327 |
+
})
|
328 |
+
|
329 |
+
df = pd.DataFrame(df_data)
|
330 |
+
|
331 |
+
# Create summary
|
332 |
+
total_duration = float(results['fragments'][-1]['end']) if results['fragments'] else 0
|
333 |
+
avg_segment_length = total_duration / len(results['fragments']) if results['fragments'] else 0
|
334 |
+
|
335 |
+
file_type = "video" if is_video_file(media_file_path) else "audio"
|
336 |
+
|
337 |
+
summary = f"""
|
338 |
+
π **Alignment Summary**
|
339 |
+
- **Input type:** {file_type.title()} file
|
340 |
+
- **Total segments:** {len(results['fragments'])}
|
341 |
+
- **Total duration:** {total_duration:.3f} seconds
|
342 |
+
- **Average segment length:** {avg_segment_length:.3f} seconds
|
343 |
+
- **Language:** {language}
|
344 |
+
"""
|
345 |
+
|
346 |
+
progress(1.0, desc="Complete!")
|
347 |
+
|
348 |
+
print(f"Debug: Alignment completed successfully with {len(results['fragments'])} fragments")
|
349 |
+
|
350 |
+
return (
|
351 |
+
"β
Alignment completed successfully!",
|
352 |
+
df,
|
353 |
+
output_file, # For download
|
354 |
+
summary,
|
355 |
+
srt_path,
|
356 |
+
vtt_path
|
357 |
+
)
|
358 |
+
|
359 |
+
except Exception as e:
|
360 |
+
print(f"Debug: Exception occurred: {str(e)}")
|
361 |
+
print(f"Debug: Traceback: {traceback.format_exc()}")
|
362 |
+
|
363 |
+
error_msg = f"β Error during alignment: {str(e)}\n\n"
|
364 |
+
error_msg += "**Troubleshooting tips:**\n"
|
365 |
+
error_msg += "- Ensure media file is in supported format (audio: WAV, MP3, FLAC, etc. | video: MP4, AVI, MKV, etc.)\n"
|
366 |
+
error_msg += "- Ensure text file contains the spoken content\n"
|
367 |
+
error_msg += "- Check that text file is in UTF-8 or Latin-1 encoding\n"
|
368 |
+
error_msg += "- Verify both media and text files are not corrupted\n"
|
369 |
+
error_msg += "- Try with a shorter audio/video/text pair first\n"
|
370 |
+
error_msg += "- Make sure FFmpeg and Aeneas dependencies are properly installed\n"
|
371 |
+
error_msg += "- For video files, ensure they contain audio tracks\n"
|
372 |
+
|
373 |
+
if temp_text_file_path:
|
374 |
+
error_msg += f"- Text file was processed from: {text_file_path}\n"
|
375 |
+
|
376 |
+
error_msg += f"\n**Technical details:**\n```\n{traceback.format_exc()}\n```"
|
377 |
+
|
378 |
+
return error_msg, None, None, "", None, None
|
379 |
+
|
380 |
+
finally:
|
381 |
+
# Clean up temporary files
|
382 |
+
try:
|
383 |
+
if temp_text_file_path and os.path.exists(temp_text_file_path):
|
384 |
+
os.unlink(temp_text_file_path)
|
385 |
+
if temp_audio_file_path and os.path.exists(temp_audio_file_path):
|
386 |
+
os.unlink(temp_audio_file_path)
|
387 |
+
print(f"Debug: Cleaned up temporary files")
|
388 |
+
except Exception as cleanup_error:
|
389 |
+
print(f"Debug: Error cleaning up temporary files: {cleanup_error}")
|
390 |
+
|
391 |
+
|
392 |
+
def create_interface():
|
393 |
+
|
394 |
+
with gr.Blocks(title="Aeneas Forced Alignment Tool", theme=gr.themes.Soft()) as interface:
|
395 |
+
gr.Markdown("""
|
396 |
+
# π― Aeneas Forced Alignment Tool
|
397 |
+
|
398 |
+
Upload an audio or video file and provide the corresponding text to generate precise time alignments.
|
399 |
+
Perfect for creating subtitles, analyzing speech patterns, or preparing training data.
|
400 |
+
|
401 |
+
**Supported formats:**
|
402 |
+
- **Audio:** WAV, MP3, FLAC, AAC, OGG, WMA, M4A, OPUS
|
403 |
+
- **Video:** MP4, AVI, MKV, MOV, WMV, FLV, WebM, M4V, 3GP, MPG, MPEG
|
404 |
+
""")
|
405 |
+
|
406 |
+
with gr.Row():
|
407 |
+
with gr.Column(scale=1):
|
408 |
+
gr.Markdown("### π Input Files")
|
409 |
+
|
410 |
+
media_input = gr.File(
|
411 |
+
label="Audio or Video File",
|
412 |
+
file_types=[
|
413 |
+
".wav", ".mp3", ".flac", ".aac", ".ogg", ".wma", ".m4a", ".opus", # Audio
|
414 |
+
".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv", ".webm", ".m4v", ".3gp", ".mpg", ".mpeg" # Video
|
415 |
+
],
|
416 |
+
file_count="single"
|
417 |
+
)
|
418 |
+
|
419 |
+
text_input = gr.File(
|
420 |
+
label="Text File (.txt)",
|
421 |
+
file_types=[".txt"],
|
422 |
+
file_count="single"
|
423 |
+
)
|
424 |
+
|
425 |
+
gr.Markdown("### βοΈ Configuration")
|
426 |
+
|
427 |
+
language_input = gr.Dropdown(
|
428 |
+
choices=["en", "es", "fr", "de", "it", "pt", "ru", "zh", "ja", "ar"],
|
429 |
+
value="en",
|
430 |
+
label="Language Code",
|
431 |
+
info="ISO language code (en=English, es=Spanish, etc.)"
|
432 |
+
)
|
433 |
+
|
434 |
+
process_btn = gr.Button("π Process Alignment", variant="primary", size="lg")
|
435 |
+
|
436 |
+
with gr.Column(scale=2):
|
437 |
+
gr.Markdown("### π Results")
|
438 |
+
|
439 |
+
status_output = gr.Markdown()
|
440 |
+
summary_output = gr.Markdown()
|
441 |
+
|
442 |
+
results_output = gr.Dataframe(
|
443 |
+
label="Alignment Results",
|
444 |
+
headers=["Segment", "Start (s)", "End (s)", "Duration (s)", "Text"],
|
445 |
+
datatype=["number", "str", "str", "str", "str"],
|
446 |
+
interactive=False
|
447 |
+
)
|
448 |
+
|
449 |
+
download_output = gr.File(
|
450 |
+
label="Download JSON Results",
|
451 |
+
visible=False
|
452 |
+
)
|
453 |
+
|
454 |
+
srt_file_output = gr.File(
|
455 |
+
label="Download SRT File",
|
456 |
+
visible=False
|
457 |
+
)
|
458 |
+
|
459 |
+
vtt_file_output = gr.File(
|
460 |
+
label="Download VTT File",
|
461 |
+
visible=False
|
462 |
+
)
|
463 |
+
|
464 |
+
# Event handlers
|
465 |
+
process_btn.click(
|
466 |
+
fn=process_alignment,
|
467 |
+
inputs=[
|
468 |
+
media_input,
|
469 |
+
text_input,
|
470 |
+
language_input,
|
471 |
+
],
|
472 |
+
outputs=[
|
473 |
+
status_output,
|
474 |
+
results_output,
|
475 |
+
download_output,
|
476 |
+
summary_output,
|
477 |
+
srt_file_output,
|
478 |
+
vtt_file_output
|
479 |
+
]
|
480 |
+
).then(
|
481 |
+
fn=lambda x: gr.update(visible=x is not None),
|
482 |
+
inputs=download_output,
|
483 |
+
outputs=download_output
|
484 |
+
).then(
|
485 |
+
fn=lambda x: gr.update(visible=x is not None),
|
486 |
+
inputs=srt_file_output,
|
487 |
+
outputs=srt_file_output
|
488 |
+
).then(
|
489 |
+
fn=lambda x: gr.update(visible=x is not None),
|
490 |
+
inputs=vtt_file_output,
|
491 |
+
outputs=vtt_file_output
|
492 |
+
)
|
493 |
+
|
494 |
+
return interface
|
495 |
+
|
496 |
+
|
497 |
+
def run_fastapi():
|
498 |
+
uvicorn.run(fastapi_app, host="0.0.0.0", port=8000)
|
499 |
+
|
500 |
+
|
501 |
+
def main():
|
502 |
+
try:
|
503 |
+
threading.Thread(target=run_fastapi, daemon=True).start()
|
504 |
+
|
505 |
+
interface = create_interface()
|
506 |
+
print("π Starting Gradio UI on http://localhost:7860")
|
507 |
+
print("π§ FastAPI JSON endpoint available at http://localhost:8000/align")
|
508 |
+
|
509 |
+
interface.launch(
|
510 |
+
server_name="0.0.0.0",
|
511 |
+
server_port=7860,
|
512 |
+
share=False,
|
513 |
+
debug=False
|
514 |
+
)
|
515 |
+
|
516 |
+
except ImportError as e:
|
517 |
+
print("β Missing dependency:", e)
|
518 |
+
except Exception as e:
|
519 |
+
print("β Error launching application:", e)
|
520 |
+
|
521 |
+
|
522 |
+
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
523 |
+
from fastapi.responses import JSONResponse
|
524 |
+
from fastapi.middleware.cors import CORSMiddleware
|
525 |
+
|
526 |
+
fastapi_app = FastAPI()
|
527 |
+
|
528 |
+
fastapi_app.add_middleware(
|
529 |
+
CORSMiddleware,
|
530 |
+
allow_origins=["*"],
|
531 |
+
allow_credentials=True,
|
532 |
+
allow_methods=["*"],
|
533 |
+
allow_headers=["*"],
|
534 |
+
)
|
535 |
+
|
536 |
+
@fastapi_app.post("/align")
|
537 |
+
async def align_api(
|
538 |
+
media_file: UploadFile = File(...),
|
539 |
+
text_file: UploadFile = File(...),
|
540 |
+
language: str = Form(default="en")
|
541 |
+
):
|
542 |
+
try:
|
543 |
+
# Validate text file
|
544 |
+
if not text_file.filename.endswith(".txt"):
|
545 |
+
raise HTTPException(
|
546 |
+
status_code=400,
|
547 |
+
detail="Text file must be a .txt file"
|
548 |
+
)
|
549 |
+
|
550 |
+
# Check if media file is supported
|
551 |
+
media_filename = media_file.filename.lower()
|
552 |
+
audio_extensions = {'.wav', '.mp3', '.flac', '.aac', '.ogg', '.wma', '.m4a', '.opus'}
|
553 |
+
video_extensions = {'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp', '.mpg', '.mpeg'}
|
554 |
+
|
555 |
+
file_ext = Path(media_filename).suffix.lower()
|
556 |
+
if file_ext not in audio_extensions and file_ext not in video_extensions:
|
557 |
+
raise HTTPException(
|
558 |
+
status_code=400,
|
559 |
+
detail=f"Unsupported media file format: {file_ext}. Supported formats: {', '.join(sorted(audio_extensions | video_extensions))}"
|
560 |
+
)
|
561 |
+
|
562 |
+
# Save uploaded files temporarily
|
563 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=file_ext) as temp_media:
|
564 |
+
shutil.copyfileobj(media_file.file, temp_media)
|
565 |
+
media_path = temp_media.name
|
566 |
+
|
567 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode='w+', encoding='utf-8') as temp_text:
|
568 |
+
content = (await text_file.read()).decode('utf-8', errors='ignore')
|
569 |
+
temp_text.write(content)
|
570 |
+
temp_text.flush()
|
571 |
+
text_path = temp_text.name
|
572 |
+
|
573 |
+
# Process alignment
|
574 |
+
status, df, json_path, summary, srt_path, vtt_path = process_alignment(media_path, text_path, language)
|
575 |
+
|
576 |
+
# Clean up uploaded files
|
577 |
+
try:
|
578 |
+
os.unlink(media_path)
|
579 |
+
os.unlink(text_path)
|
580 |
+
except Exception as cleanup_error:
|
581 |
+
print(f"Warning: Error cleaning up uploaded files: {cleanup_error}")
|
582 |
+
|
583 |
+
if "Error" in status or status.startswith("β"):
|
584 |
+
raise HTTPException(status_code=500, detail=status)
|
585 |
+
|
586 |
+
response = {
|
587 |
+
"status": status,
|
588 |
+
"summary": summary,
|
589 |
+
"segments": df.to_dict(orient="records") if df is not None else [],
|
590 |
+
"download_links": {
|
591 |
+
"alignment_json": json_path,
|
592 |
+
"srt": srt_path,
|
593 |
+
"vtt": vtt_path
|
594 |
+
}
|
595 |
+
}
|
596 |
+
|
597 |
+
return JSONResponse(status_code=200, content=response)
|
598 |
+
|
599 |
+
except HTTPException:
|
600 |
+
raise
|
601 |
+
except Exception as e:
|
602 |
+
raise HTTPException(
|
603 |
+
status_code=500,
|
604 |
+
detail=f"Unexpected server error: {str(e)}"
|
605 |
+
)
|
606 |
+
|
607 |
+
|
608 |
+
if __name__ == "__main__":
|
609 |
main()
|