-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1905 lines (1546 loc) · 72.7 KB
/
main.py
File metadata and controls
executable file
·1905 lines (1546 loc) · 72.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Stream-Polyglot CLI
Multilingual video/audio translation and subtitle generation tool
Usage:
python -m main video.mp4 --lang eng:cmn --audio --subtitle [--output path/to/out/]
"""
import argparse
import sys
import os
import requests
import subprocess
import tempfile
import threading
from pathlib import Path
from dotenv import load_dotenv
from tqdm import tqdm
# Import audio timeline segmentation
from audio_timeline import segment_with_timeline
# Import SRT utilities
from srt_utils import generate_srt_content, save_srt_file, parse_srt_file, extract_bilingual_text
class Colors:
"""ANSI color codes for terminal output"""
HEADER = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
END = '\033[0m'
BOLD = '\033[1m'
def print_header(text):
"""Print colored header"""
print(f"\n{Colors.HEADER}{Colors.BOLD}{text}{Colors.END}")
def print_success(text):
"""Print success message"""
print(f"{Colors.GREEN}✓ {text}{Colors.END}")
def print_error(text):
"""Print error message"""
print(f"{Colors.RED}✗ {text}{Colors.END}", file=sys.stderr)
def print_info(text):
"""Print info message"""
print(f"{Colors.CYAN}ℹ {text}{Colors.END}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.YELLOW}⚠ {text}{Colors.END}")
def check_file_exists(file_path):
"""Check if input file exists"""
path = Path(file_path)
if not path.exists():
print_error(f"File not found: {file_path}")
return False
if not path.is_file():
print_error(f"Not a file: {file_path}")
return False
return True
def check_m4t_server(api_url):
"""Check if m4t API server is accessible"""
try:
response = requests.get(f"{api_url}/health", timeout=5)
if response.status_code == 200:
print_success(f"m4t API server is accessible at {api_url}")
return True
else:
print_error(f"m4t API server returned status {response.status_code}")
return False
except requests.exceptions.ConnectionError:
print_error(f"Cannot connect to m4t API server at {api_url}")
print_info("Make sure the m4t server is running (cd ~/work/m4t && ./start_dev.sh)")
return False
except requests.exceptions.Timeout:
print_error(f"Connection timeout to m4t API server at {api_url}")
return False
except Exception as e:
print_error(f"Error connecting to m4t API server: {e}")
return False
def parse_language_pair(lang_pair):
"""Parse language pair string like 'eng:cmn' into (source, target)"""
if ':' not in lang_pair:
print_error(f"Invalid language pair format: '{lang_pair}'")
print_info("Expected format: 'source:target' (e.g., 'eng:cmn', 'jpn:eng')")
return None, None
parts = lang_pair.split(':')
if len(parts) != 2:
print_error(f"Invalid language pair format: '{lang_pair}'")
print_info("Expected format: 'source:target' (e.g., 'eng:cmn', 'jpn:eng')")
return None, None
source_lang, target_lang = parts[0].strip(), parts[1].strip()
if not source_lang or not target_lang:
print_error(f"Invalid language pair format: '{lang_pair}'")
print_info("Both source and target languages must be specified")
return None, None
return source_lang, target_lang
def infer_language_from_srt_filename(srt_path):
"""
Infer source and target language from SRT filename
Expected format: xxx.source-target.srt (e.g., video.eng-cmn.srt)
Returns:
Tuple of (source_lang, target_lang) or (None, None) if not found
"""
import re
filename = Path(srt_path).stem
# Pattern: filename.source-target (e.g., video.eng-cmn)
# Match 2-3 letter language codes before .srt extension
match = re.search(r'\.([a-z]{2,3})-([a-z]{2,3})$', filename)
if match:
source_lang = match.group(1)
target_lang = match.group(2)
return source_lang, target_lang
return None, None
def get_video_info(video_path):
"""Get basic video file information"""
path = Path(video_path)
size_mb = path.stat().st_size / (1024 * 1024)
print_header("Video File Information")
print_info(f"File: {path.name}")
print_info(f"Path: {path.absolute()}")
print_info(f"Size: {size_mb:.2f} MB")
print_info(f"Extension: {path.suffix}")
def extract_audio(video_path, output_audio_path):
"""Extract audio from video file using FFmpeg"""
try:
cmd = [
'ffmpeg',
'-i', video_path,
'-vn', # No video
'-acodec', 'pcm_s16le', # PCM 16-bit little-endian
'-ar', '16000', # Sample rate 16kHz (required by m4t)
'-ac', '1', # Mono
'-y', # Overwrite output file
output_audio_path
]
print_info(f"Extracting audio from video...")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding='utf-8', # Explicitly use UTF-8 encoding for Windows
errors='replace' # Replace invalid characters instead of crashing
)
if result.returncode != 0:
print_error(f"FFmpeg error: {result.stderr}")
return False
print_success(f"Audio extracted to: {output_audio_path}")
return True
except FileNotFoundError:
print_error("FFmpeg not found. Please install FFmpeg.")
return False
except Exception as e:
print_error(f"Error extracting audio: {e}")
return False
def speech_to_text_translation(audio_path, source_lang, target_lang, api_url, verbose=True):
"""Call m4t API for speech-to-text translation"""
try:
if verbose:
print_info(f"Translating speech from {source_lang} to {target_lang}...")
# Read audio file
with open(audio_path, 'rb') as f:
audio_data = f.read()
# Prepare multipart form data
files = {
'audio': ('audio.wav', audio_data, 'audio/wav')
}
data = {
'source_lang': source_lang,
'target_lang': target_lang
}
# Call m4t S2TT API
response = requests.post(
f"{api_url}/v1/speech-to-text-translation",
files=files,
data=data,
timeout=300 # 5 minutes timeout for long audio
)
if response.status_code == 200:
result = response.json()
return result
else:
print_error(f"API error: {response.status_code}")
print_error(f"Response: {response.text}")
return None
except requests.exceptions.Timeout:
print_error("Request timeout. Audio file might be too long.")
return None
except Exception as e:
print_error(f"Error calling m4t API: {e}")
return None
def speech_to_speech_translation(audio_path, source_lang, target_lang, api_url, speaker_id=0, verbose=True):
"""Call m4t API for speech-to-speech translation"""
try:
if verbose:
print_info(f"Translating speech from {source_lang} to {target_lang}...")
if speaker_id != 0:
print_info(f"Using speaker voice ID: {speaker_id}")
# Read audio file
with open(audio_path, 'rb') as f:
audio_data = f.read()
# Prepare multipart form data
files = {
'audio': ('audio.wav', audio_data, 'audio/wav')
}
data = {
'source_lang': source_lang,
'target_lang': target_lang,
'response_format': 'json', # Get JSON with base64 audio
'speaker_id': speaker_id
}
# Call m4t S2ST API
response = requests.post(
f"{api_url}/v1/speech-to-speech-translation",
files=files,
data=data,
timeout=300 # 5 minutes timeout for long audio
)
if response.status_code == 200:
result = response.json()
return result
else:
print_error(f"API error: {response.status_code}")
print_error(f"Response: {response.text}")
return None
except requests.exceptions.Timeout:
print_error("Request timeout. Audio file might be too long.")
return None
except Exception as e:
print_error(f"Error calling m4t S2ST API: {e}")
return None
def save_audio_to_file(audio_data, sample_rate, output_path):
"""Save audio array to WAV file"""
try:
import numpy as np
import soundfile as sf
# Convert list to numpy array
audio_array = np.array(audio_data, dtype=np.float32)
# Save to WAV file
sf.write(output_path, audio_array, sample_rate)
print_success(f"Audio saved to: {output_path}")
return True
except ImportError as e:
print_error(f"Missing required library: {e}")
print_info("Please install: pip install numpy soundfile")
return False
except Exception as e:
print_error(f"Error saving audio file: {e}")
return False
def save_base64_audio_to_file(audio_base64, output_path):
"""Decode base64 audio and save to WAV file"""
try:
import base64
# Decode base64 audio
audio_bytes = base64.b64decode(audio_base64)
# Write to file
with open(output_path, 'wb') as f:
f.write(audio_bytes)
print_success(f"Audio saved to: {output_path}")
return True
except Exception as e:
print_error(f"Error saving audio file: {e}")
return False
def audio_split(audio_path, api_url, verbose=True, max_chunk_duration=300.0):
"""
Call m4t API for audio splitting (vocals + accompaniment)
For long audio files, splits into chunks on client side to avoid network timeout.
Args:
audio_path: Path to audio file
api_url: m4t API server URL
verbose: Print info messages
max_chunk_duration: Maximum chunk duration in seconds (default: 300s = 5 minutes)
Returns:
Tuple of (vocals_bytes, accompaniment_bytes, sample_rate) or (None, None, None) on error
"""
try:
import soundfile as sf
# Load audio to check duration
audio_array, sr = sf.read(audio_path, dtype='float32')
total_duration = len(audio_array) / sr
if verbose:
print_info(f"Audio duration: {total_duration:.2f}s")
# If audio is short enough, process directly
if total_duration <= max_chunk_duration:
return _audio_split_direct(audio_path, api_url, verbose)
# For long audio, process in chunks
if verbose:
print_info(f"Audio exceeds {max_chunk_duration}s, processing in chunks...")
return _audio_split_chunked(audio_array, sr, api_url, max_chunk_duration, verbose)
except Exception as e:
print_error(f"Error in audio split: {e}")
return None, None, None
def _audio_split_direct(audio_path, api_url, verbose=True):
"""
Direct audio split for short audio files (<= 5 minutes)
"""
try:
if verbose:
print_info(f"Splitting audio into vocals and accompaniment...")
# Read audio file
with open(audio_path, 'rb') as f:
audio_data = f.read()
# Prepare multipart form data
files = {
'audio': ('audio.wav', audio_data, 'audio/wav')
}
# Call m4t audio-split API
response = requests.post(
f"{api_url}/v1/audio-split",
files=files,
timeout=300 # 5 minutes timeout
)
if response.status_code == 200:
result = response.json()
# Decode base64 audio streams
import base64
vocals_base64 = result.get('vocals_audio_base64', '')
accompaniment_base64 = result.get('accompaniment_audio_base64', '')
sample_rate = result.get('sample_rate', 16000)
vocals_bytes = base64.b64decode(vocals_base64)
accompaniment_bytes = base64.b64decode(accompaniment_base64)
if verbose:
print_success(f"Audio split completed (sample rate: {sample_rate} Hz)")
return vocals_bytes, accompaniment_bytes, sample_rate
else:
print_error(f"Audio split API error: {response.status_code}")
print_error(f"Response: {response.text}")
return None, None, None
except requests.exceptions.Timeout:
print_error("Request timeout during audio split.")
return None, None, None
except Exception as e:
print_error(f"Error calling audio-split API: {e}")
return None, None, None
def _audio_split_chunked(audio_array, sr, api_url, chunk_duration, verbose=True):
"""
Split long audio into chunks, process each chunk via API, then concatenate results
Args:
audio_array: Full audio array
sr: Sample rate
api_url: m4t API server URL
chunk_duration: Duration of each chunk in seconds
verbose: Print info messages
Returns:
Tuple of (vocals_bytes, accompaniment_bytes, sample_rate)
"""
import soundfile as sf
import base64
import io
import numpy as np
total_duration = len(audio_array) / sr
chunk_samples = int(chunk_duration * sr)
num_chunks = int(np.ceil(total_duration / chunk_duration))
if verbose:
print_info(f"Processing {num_chunks} chunks of {chunk_duration}s each...")
vocals_chunks = []
accompaniment_chunks = []
result_sr = 16000 # Default sample rate
for i in range(num_chunks):
start_sample = i * chunk_samples
end_sample = min((i + 1) * chunk_samples, len(audio_array))
chunk_array = audio_array[start_sample:end_sample]
chunk_start_time = start_sample / sr
chunk_end_time = end_sample / sr
if verbose:
print_info(f"Processing chunk {i+1}/{num_chunks}: {chunk_start_time:.1f}s - {chunk_end_time:.1f}s")
# Save chunk to temporary WAV in memory
chunk_buffer = io.BytesIO()
sf.write(chunk_buffer, chunk_array, sr, format='WAV')
chunk_buffer.seek(0)
chunk_bytes = chunk_buffer.read()
# Send chunk to API
try:
files = {
'audio': (f'chunk_{i}.wav', chunk_bytes, 'audio/wav')
}
response = requests.post(
f"{api_url}/v1/audio-split",
files=files,
timeout=300
)
if response.status_code != 200:
print_error(f"Chunk {i+1}/{num_chunks} failed: {response.status_code}")
return None, None, None
result = response.json()
result_sr = result.get('sample_rate', 16000)
# Decode base64 audio streams
vocals_base64 = result.get('vocals_audio_base64', '')
accompaniment_base64 = result.get('accompaniment_audio_base64', '')
vocals_chunk_bytes = base64.b64decode(vocals_base64)
accompaniment_chunk_bytes = base64.b64decode(accompaniment_base64)
# Load as arrays for concatenation
vocals_chunk_array, _ = sf.read(io.BytesIO(vocals_chunk_bytes), dtype='float32')
accompaniment_chunk_array, _ = sf.read(io.BytesIO(accompaniment_chunk_bytes), dtype='float32')
vocals_chunks.append(vocals_chunk_array)
accompaniment_chunks.append(accompaniment_chunk_array)
except Exception as e:
print_error(f"Error processing chunk {i+1}/{num_chunks}: {e}")
return None, None, None
# Concatenate all chunks
if verbose:
print_info("Concatenating processed chunks...")
vocals_array = np.concatenate(vocals_chunks)
accompaniment_array = np.concatenate(accompaniment_chunks)
# Convert concatenated arrays back to bytes
vocals_buffer = io.BytesIO()
accompaniment_buffer = io.BytesIO()
sf.write(vocals_buffer, vocals_array, result_sr, format='WAV')
sf.write(accompaniment_buffer, accompaniment_array, result_sr, format='WAV')
vocals_buffer.seek(0)
accompaniment_buffer.seek(0)
vocals_bytes = vocals_buffer.read()
accompaniment_bytes = accompaniment_buffer.read()
if verbose:
print_success(f"Audio split completed: {len(vocals_array)/result_sr:.2f}s processed")
return vocals_bytes, accompaniment_bytes, result_sr
def audio_split_background(audio_path, api_url, cache_dir):
"""
Run audio splitting in background thread and save results when ready
Args:
audio_path: Path to audio file
api_url: m4t API server URL
cache_dir: Cache directory to save split audio
"""
try:
print_info("Starting audio split in background...")
vocals_bytes, accompaniment_bytes, _ = audio_split(audio_path, api_url, verbose=False)
if vocals_bytes and accompaniment_bytes:
# Save vocals and accompaniment to cache directory
split_cache_dir = cache_dir / 'split'
os.makedirs(split_cache_dir, exist_ok=True)
vocals_cache_path = split_cache_dir / 'vocals.wav'
accompaniment_cache_path = split_cache_dir / 'accompaniment.wav'
with open(vocals_cache_path, 'wb') as f:
f.write(vocals_bytes)
with open(accompaniment_cache_path, 'wb') as f:
f.write(accompaniment_bytes)
print_success(f"✓ Audio split completed")
print_success(f" Vocals: {vocals_cache_path}")
print_success(f" Accompaniment: {accompaniment_cache_path}")
else:
print_warning("Audio split failed in background")
except Exception as e:
print_error(f"Background audio split error: {e}")
def voice_clone_translation(ref_audio_path, text, text_language, prompt_text, prompt_language, api_url, seed=-1, verbose=True, cache_dir=None, segment_index=None):
"""
Call m4t API for voice cloning
Args:
ref_audio_path: Path to reference audio file
text: Text to synthesize in target language
text_language: Language code for text (SeamlessM4T or GPT-SoVITS code)
prompt_text: Transcription of reference audio (source language)
prompt_language: Language code for reference audio
api_url: m4t API server URL
seed: Random seed for reproducibility (-1 for random)
verbose: Print info messages
cache_dir: Cache directory for dumping intermediate audio (required if verbose=True)
segment_index: Segment index for naming intermediate audio files
Returns:
Audio bytes or None on error
"""
try:
if verbose:
print_info(f"Voice cloning: {text_language} text with {prompt_language} reference...")
# Read reference audio file
with open(ref_audio_path, 'rb') as f:
audio_data = f.read()
# Prepare multipart form data
files = {
'audio': ('reference.wav', audio_data, 'audio/wav')
}
data = {
'text': text,
'text_language': text_language,
'prompt_text': prompt_text,
'prompt_language': prompt_language,
'seed': str(seed)
}
# Call m4t voice-clone API
response = requests.post(
f"{api_url}/v1/voice-clone",
files=files,
data=data,
timeout=120 # 2 minutes timeout
)
if response.status_code == 200:
result = response.json()
# Decode base64 audio
import base64
audio_base64 = result.get('output_audio_base64', '')
audio_bytes = base64.b64decode(audio_base64)
# Dump intermediate audio if verbose mode is enabled
if verbose and cache_dir and segment_index is not None:
debug_dir = Path(cache_dir) / 'voice_clone_debug'
os.makedirs(debug_dir, exist_ok=True)
# Create descriptive filename with index, languages, and truncated text
# Truncate text to avoid overly long filenames
text_preview = text[:30].replace(' ', '_').replace('/', '_').replace('\\', '_')
if len(text) > 30:
text_preview += '...'
debug_filename = f"segment_{segment_index:04d}_{prompt_language}-{text_language}_{text_preview}.wav"
debug_path = debug_dir / debug_filename
# Save audio bytes to file
with open(debug_path, 'wb') as f:
f.write(audio_bytes)
print_info(f"Saved intermediate audio: {debug_path.name}")
return audio_bytes
else:
print_error(f"Voice clone API error: {response.status_code}")
print_error(f"Response: {response.text}")
return None
except requests.exceptions.Timeout:
print_error("Request timeout during voice cloning")
return None
except Exception as e:
print_error(f"Error calling voice-clone API: {e}")
return None
def load_timeline_cache(cache_dir):
"""Load cached timeline data if available"""
import json
timeline_json_path = os.path.join(cache_dir, 'timeline.json')
if not os.path.exists(timeline_json_path):
return None, None
try:
with open(timeline_json_path, 'r') as f:
cache_data = json.load(f)
timeline = cache_data.get('timeline', [])
metadata = cache_data.get('metadata', {})
# Verify all fragment files exist
fragments_dir = cache_data.get('fragments_dir', '')
if not fragments_dir or not os.path.exists(fragments_dir):
return None, None
for fragment in timeline:
fragment_path = os.path.join(fragments_dir, fragment['file'])
if not os.path.exists(fragment_path):
return None, None
return timeline, metadata
except Exception as e:
print_warning(f"Failed to load timeline cache: {e}")
return None, None
def save_timeline_cache(timeline, metadata, cache_dir, fragments_dir):
"""Save timeline data to cache file"""
import json
os.makedirs(cache_dir, exist_ok=True)
timeline_json_path = os.path.join(cache_dir, 'timeline.json')
cache_data = {
'timeline': timeline,
'metadata': metadata,
'fragments_dir': fragments_dir
}
try:
with open(timeline_json_path, 'w') as f:
json.dump(cache_data, f, indent=2)
return True
except Exception as e:
print_warning(f"Failed to save timeline cache: {e}")
return False
def process_video(input_file, source_lang, target_lang, generate_audio, generate_subtitle, subtitle_source_lang, output_dir, api_url, speaker_id=0, split_audio=False, run_subtitle_refiner=False):
"""Process video file for translation"""
print_header("Stream-Polyglot Video Translation")
# Check input file
if not check_file_exists(input_file):
return 1
# Show video info
get_video_info(input_file)
# Check m4t server
if not check_m4t_server(api_url):
return 1
# Determine output settings
print_header("Translation Configuration")
print_info(f"Source language: {source_lang}")
print_info(f"Target language: {target_lang}")
if subtitle_source_lang:
print_info(f"Subtitle source language: {subtitle_source_lang}")
print_info(f"Generate subtitles: {'Yes' if generate_subtitle else 'No'}")
print_info(f"Generate audio dubbing: {'Yes' if generate_audio else 'No'}")
if split_audio:
print_info(f"Audio splitting: Yes (vocals for segmentation)")
if output_dir:
print_info(f"Output directory: {output_dir}")
else:
# Default output same directory as input
input_path = Path(input_file)
output_dir = input_path.parent
print_info(f"Output directory: {output_dir} (default)")
# Check if at least one output is requested
if not generate_audio and not generate_subtitle:
print_warning("Neither --audio nor --subtitle specified")
print_info("Nothing to generate. Please specify at least one output option:")
print_info(" --subtitle Generate subtitle file")
print_info(" --audio Generate audio dubbing")
return 1
# Prepare cache directory for timeline data
input_path = Path(input_file)
cache_dir = output_dir / '.stream-polyglot-cache' / input_path.stem
os.makedirs(cache_dir, exist_ok=True)
# Process subtitle generation with timeline
if generate_subtitle:
print_header("Subtitle Generation with Timeline")
print_info(f"Audio language: {source_lang}")
print_info(f"Subtitle language: {target_lang}")
# Try to load cached timeline first
cached_timeline, cached_metadata = load_timeline_cache(cache_dir)
if cached_timeline and cached_metadata:
print_success("Found cached timeline data, skipping segmentation")
timeline = cached_timeline
metadata = cached_metadata
fragments_dir = cached_metadata.get('fragments_dir', '')
fragment_count = len(timeline)
total_duration = metadata.get('total_duration', 0)
print_info(f"Using {fragment_count} cached speech fragments")
print_info(f"Total audio duration: {total_duration:.2f}s")
# If split_audio is requested, extract audio and run splitting in background
if split_audio:
# Use cache directory for temporary audio (won't be auto-deleted)
split_audio_dir = cache_dir / 'temp_audio'
os.makedirs(split_audio_dir, exist_ok=True)
tmp_audio_path = str(split_audio_dir / 'extracted_audio.wav')
print_info("Extracting audio for splitting...")
if extract_audio(input_file, tmp_audio_path):
# Start audio splitting in background thread
split_thread = threading.Thread(
target=audio_split_background,
args=(tmp_audio_path, api_url, cache_dir),
daemon=True
)
split_thread.start()
print_info("Audio splitting started in background (processing continues...)")
else:
# Need to segment audio - create persistent cache directory for fragments
print_info("No cached timeline found, performing segmentation...")
fragments_dir = str(cache_dir / 'fragments')
os.makedirs(fragments_dir, exist_ok=True)
with tempfile.TemporaryDirectory() as temp_dir:
tmp_audio_path = os.path.join(temp_dir, 'extracted_audio.wav')
try:
# Step 1: Extract audio from video
print_info("Step 1/4: Extracting audio from video...")
if not extract_audio(input_file, tmp_audio_path):
return 1
# Step 1.5: Split audio if --split flag is set (run in background)
audio_for_segmentation = tmp_audio_path
if split_audio:
# Start audio splitting in background thread
split_thread = threading.Thread(
target=audio_split_background,
args=(tmp_audio_path, api_url, cache_dir),
daemon=True
)
split_thread.start()
print_info("Audio splitting started in background (processing continues...)")
# Step 2: Segment audio with timeline
print_info("Step 2/4: Segmenting audio with VAD-based timeline...")
timeline, metadata = segment_with_timeline(
audio_path=audio_for_segmentation,
output_dir=fragments_dir,
chunk_duration=30.0,
m4t_api_url=api_url,
save_timeline=False
)
fragment_count = len(timeline)
total_duration = metadata.get('total_duration', 0)
print_success(f"Segmented into {fragment_count} speech fragments")
print_info(f"Total audio duration: {total_duration:.2f}s")
# Save timeline to cache with fragments_dir
metadata['fragments_dir'] = fragments_dir
if split_audio:
metadata['split_audio'] = True
save_timeline_cache(timeline, metadata, cache_dir, fragments_dir)
print_success("Timeline cached for future use")
except Exception as e:
print_error(f"Error during audio extraction/segmentation: {e}")
import traceback
traceback.print_exc()
return 1
try:
# Step 3: Translate each fragment
print_info(f"Step 3/4: Translating {fragment_count} fragments...")
subtitles = []
# Use tqdm progress bar
with tqdm(total=fragment_count, desc="Translating", unit="fragment",
bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]',
ncols=80) as pbar:
for i, fragment in enumerate(timeline):
fragment_path = os.path.join(fragments_dir, fragment['file'])
source_text = None
# If subtitle_source_lang is set, transcribe source language first
if subtitle_source_lang:
try:
with open(fragment_path, 'rb') as f:
audio_data = f.read()
files = {'audio': ('audio.wav', audio_data, 'audio/wav')}
data = {'language': source_lang}
response = requests.post(
f"{api_url}/v1/transcribe",
files=files,
data=data,
timeout=60
)
if response.status_code == 200:
asr_result = response.json()
source_text = asr_result.get('output_text', '').strip()
except Exception as e:
tqdm.write(f"{Colors.RED}✗ Fragment {i}: Source transcription failed: {e}{Colors.END}")
# Translate fragment to target language
result = speech_to_text_translation(fragment_path, source_lang, target_lang, api_url, verbose=False)
translated_text = None
if result and result.get('output_text'):
translated_text = result['output_text'].strip()
# Build subtitle entry if we have at least one text (source or target)
if translated_text or source_text:
# Construct combined text based on what's available
if subtitle_source_lang:
# Bilingual mode: target on first line, source on second line
if translated_text and source_text:
# Both succeeded - ideal case
combined_text = f"{translated_text}\n{source_text}"
elif translated_text:
# Only target succeeded - show target with empty source line
combined_text = f"{translated_text}\n"
elif source_text:
# Only source succeeded - show empty target line with source
combined_text = f"\n{source_text}"
else:
# Should not reach here due to outer if condition
combined_text = ""
else:
# Single language mode: only use translated text
if translated_text:
combined_text = translated_text
else:
# Translation failed, skip this fragment in single-lang mode
tqdm.write(f"{Colors.YELLOW}⚠ Fragment {i}: Translation failed, skipping{Colors.END}")
pbar.update(1)
continue
subtitles.append({
'start': fragment['start'],
'end': fragment['end'],
'text': combined_text
})
else:
# Both failed in bilingual mode, or translation failed in single-lang mode
tqdm.write(f"{Colors.YELLOW}⚠ Fragment {i}: All transcription/translation failed, skipping{Colors.END}")
# Update progress bar
pbar.update(1)
# Step 4: Generate and save SRT files
print_info(f"Step 4/4: Generating SRT subtitle files...")
if not subtitles:
print_error("No subtitles generated")
return 1
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Generate output filename
input_path = Path(input_file)
# If bilingual mode, use format like "video.eng-cmn.srt"
if subtitle_source_lang:
output_srt_filename = f"{input_path.stem}.{source_lang}-{target_lang}.srt"
subtitle_type = "Bilingual"
else:
output_srt_filename = f"{input_path.stem}.{target_lang}.srt"
subtitle_type = "Target language"
output_srt_path = Path(output_dir) / output_srt_filename
# Generate and save SRT
srt_content = generate_srt_content(subtitles, merge_short=True)
if save_srt_file(srt_content, str(output_srt_path)):
print_success(f"{subtitle_type} subtitle saved: {output_srt_path}")
# Run subtitle-refiner if requested
if run_subtitle_refiner:
print_header("Running Subtitle Refiner")
print_info("Refining subtitle translations with LLM...")
refiner_path = Path(__file__).parent / 'subtitle-refiner'
try:
# Use Popen with cwd parameter (cross-platform compatible)
process = subprocess.Popen(
['node', 'dist/index.js', str(output_srt_path)],
cwd=str(refiner_path), # Change directory using cwd parameter
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True,
encoding='utf-8', # Explicitly use UTF-8 encoding for Windows compatibility
errors='replace' # Replace invalid characters instead of crashing
)
# Stream output line by line
for line in process.stdout:
print(line, end='')
# Wait for process to complete
return_code = process.wait()
if return_code == 0:
print_success("Subtitle refinement completed")
else:
print_error(f"Subtitle refiner failed with exit code {return_code}")
print_warning("Continuing with unrefined subtitle...")
except Exception as e:
print_error(f"Error running subtitle refiner: {e}")
print_warning("Continuing with unrefined subtitle...")
else:
print_error(f"Failed to save {subtitle_type.lower()} subtitle")
return 1
# Print summary
print_header("Subtitle Generation Result")
print_success(f"Generated {len(subtitles)} subtitle entries")