-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain_app.py
More file actions
4329 lines (3732 loc) · 256 KB
/
main_app.py
File metadata and controls
4329 lines (3732 loc) · 256 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
import sys
import os
from pathlib import Path
import shutil
import time
import numpy as np
import librosa
from pydub import AudioSegment, silence # Keep for merging/exporting, not for VC pre-chunking
from moviepy.editor import VideoFileClip # AudioFileClip, CompositeAudioClip, concatenate_audioclips # Not used directly for now
import soundfile as sf
import yaml
import torch
import torchaudio
from tqdm import tqdm # For console progress during dev, GUI will use progress bar
import ffmpeg
from huggingface_hub import hf_hub_download
import gc #For garbage collection
import subprocess # For direct ffmpeg calls if needed, though moviepy/ffmpeg-python is preferred
from demucs.pretrained import get_model as get_demucs_model
from demucs.apply import apply_model as apply_demucs_model
from demucs.audio import AudioFile as DemucsAudioFile
# --- Gdown Import for Google Drive downloads ---
try:
import gdown
GDOWN_AVAILABLE = True
except ImportError:
GDOWN_AVAILABLE = False
print("Warning: gdown library not found. Automatic download of Speech2RIR model will be disabled.")
print("Install with: pip install gdown")
try:
from scenedetect import open_video, SceneManager
# Import the detectors
from scenedetect.detectors import ContentDetector, HashDetector, AdaptiveDetector, ThresholdDetector, HistogramDetector
SCENEDETECT_AVAILABLE = True
except ImportError:
SCENEDETECT_AVAILABLE = False
print("Warning: PySceneDetect not found. Scene cut detection will be disabled.")
print("Install with: pip install scenedetect[opencv]")
try:
from modules.commons import build_model, load_checkpoint, recursive_munch
from modules.campplus.DTDNN import CAMPPlus
from modules.bigvgan import bigvgan
from modules.rmvpe import RMVPE
from modules.audio import mel_spectrogram
except ImportError as e:
print(f"Error importing from 'modules': {e}. Ensure 'modules' directory is accessible.")
raise
from transformers import AutoFeatureExtractor, WhisperModel
# --- HF_HOME Setup ---
APP_ROOT = Path(__file__).resolve().parent
HF_MODELS_DIR = APP_ROOT / "checkpoints"
HF_MODELS_DIR.mkdir(parents=True, exist_ok=True)
os.environ['HF_HOME'] = str(HF_MODELS_DIR)
print(f"Hugging Face home directory set to: {os.environ['HF_HOME']}")
# --- Speech2RIR Setup ---
S2R_PROJECT_ROOT = HF_MODELS_DIR / "speech2rir"
# Ensure the Speech2RIR project directory exists
S2R_PROJECT_ROOT.mkdir(parents=True, exist_ok=True)
S2R_MODEL_CACHE = None
if S2R_PROJECT_ROOT.is_dir():
sys.path.insert(0, str(S2R_PROJECT_ROOT))
print(f"Added Speech2RIR project root to sys.path: {S2R_PROJECT_ROOT}")
try:
from models.autoencoder.AudioDec import Generator as S2R_Generator
print("Successfully imported Speech2RIR_Generator.")
except ImportError as e:
S2R_Generator = None
print(f"Failed to import s2r_Generator from speech2rir: {e}. Speech2RIR features will be unavailable.")
else:
S2R_Generator = None
print(f"Warning: Speech2RIR project directory not found at {S2R_PROJECT_ROOT}. Speech2RIR features will be unavailable.")
# --- Imports for align-voice-rt60.py ---
try:
from blind_rt60 import BlindRT60
except ImportError:
print("Warning: 'blind_rt60' not found. Please install it (`pip install blind-rt60`) or place 'blind_rt60.py' in the path.")
class BlindRT60:
def __init__(self, *args, **kwargs): pass
def estimate(self, *args, **kwargs): return 0.5
import pyroomacoustics as pra
from pedalboard import Convolution, Pedalboard, Gain
# --- PySide6 Imports ---
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QLineEdit, QFileDialog, QSlider, QCheckBox, QGridLayout, QTabWidget, QSizePolicy,
QProgressBar, QTextEdit, QGroupBox, QScrollArea, QComboBox, QListWidget,
QListWidgetItem, QMessageBox, QSplitter
)
from PySide6.QtCore import Qt, QThread, Signal, Slot, QUrl, QTimer, QRectF, QPointF, QMetaObject
from PySide6.QtGui import QIcon, QPainter, QPen, QColor, QBrush, QPolygonF, QDoubleValidator
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput
from PySide6.QtWidgets import QWidget
try:
from pyannote.audio import Pipeline as PyannotePipeline
PYANNOTE_AVAILABLE = True
except ImportError:
PYANNOTE_AVAILABLE = False
print("Warning: pyannote.audio not found. Speaker diarization will be disabled.")
print("Install with: pip install pyannote.audio")
# --- ClearVoice Imports ---
import modules.clearvoice.networks
try:
from modules.clearvoice.clearvoice import ClearVoice
CLEARVOICE_AVAILABLE = True
except ImportError as e:
CLEARVOICE_AVAILABLE = False
print(f"Warning: ClearVoice library not found or import error: {e}. Target voice cleaning will be disabled.")
# --- Global Variables & Configuration ---
TMP_DIR = Path("./tmp_processing")
VOICE_MODELS_CACHE = None
CLEARVOICE_MODEL_CACHE = None
HUGGING_FACE_TOKEN_PLACEHOLDER = "YOUR_HUGGING_FACE_ACCESS_TOKEN_HERE"
def load_custom_model_from_hf(repo_id, model_filename="pytorch_model.bin", config_filename="config.yml"):
os.makedirs("./checkpoints", exist_ok=True)
model_path = hf_hub_download(repo_id=repo_id, filename=model_filename, cache_dir="./checkpoints")
if config_filename is None:
return model_path
config_path = hf_hub_download(repo_id=repo_id, filename=config_filename, cache_dir="./checkpoints")
return model_path, config_path
# --- Demucs & Mixing Helper Functions ---
def _save_demucs_audio_file(tensor: torch.Tensor, path: str, sample_rate: int, log_callback):
"""Save audio file from a tensor, typically Demucs output."""
try:
audio_numpy = tensor.cpu().numpy()
# Demucs output can be [channels, samples] or [batch, channels, samples]
if audio_numpy.ndim == 3: # [batch, channels, samples]
audio_numpy = audio_numpy.squeeze(0) # Remove batch dim
# Soundfile expects [frames, channels] or [frames,] for mono
# If [channels, samples], transpose it.
if audio_numpy.ndim == 2 and audio_numpy.shape[0] < audio_numpy.shape[1]: # Likely [channels, samples]
audio_numpy = audio_numpy.T # Transpose to [frames, channels]
elif audio_numpy.ndim == 1: # Mono [frames,]
pass # Already in correct shape for soundfile
else: # Should be [frames, channels]
pass
sf.write(path, audio_numpy, sample_rate)
log_callback(f"Saved Demucs component to {path}")
return path
except Exception as e:
log_callback(f"Error saving Demucs audio file {path}: {e}", is_error=True)
raise
def _mix_audio_torchaudio(audio1_path: str, audio2_path: str, output_path: str, volume_ratio_audio1: float, log_callback):
"""Mix two audio files using torchaudio."""
try:
log_callback(f"Mixing {Path(audio1_path).name} ({(volume_ratio_audio1*100):.1f}%) and {Path(audio2_path).name} ({((1.0-volume_ratio_audio1)*100):.1f}%)")
audio1, sr1 = torchaudio.load(audio1_path)
audio2, sr2 = torchaudio.load(audio2_path)
if sr1 != sr2:
log_callback(f"Sample rates differ. Resampling {Path(audio2_path).name} from {sr2}Hz to {sr1}Hz.")
resampler = torchaudio.transforms.Resample(sr2, sr1)
audio2 = resampler(audio2)
if audio1.shape[0] == 1 and audio2.shape[0] == 2: # audio1 is mono, audio2 is stereo
audio1 = audio1.repeat(2, 1)
elif audio2.shape[0] == 1 and audio1.shape[0] == 2: # audio2 is mono, audio1 is stereo
audio2 = audio2.repeat(2, 1)
min_len = min(audio1.shape[1], audio2.shape[1])
if audio1.shape[1] != audio2.shape[1]:
log_callback(f"Audio lengths differ. Trimming to {min_len} samples.")
audio1 = audio1[:, :min_len]
audio2 = audio2[:, :min_len]
mixed_audio = (audio1 * volume_ratio_audio1) + (audio2 * (1.0 - volume_ratio_audio1))
max_val = torch.max(torch.abs(mixed_audio))
if max_val > 1.0: mixed_audio = mixed_audio / max_val # Normalize
torchaudio.save(output_path, mixed_audio, sr1)
log_callback(f"Mixed audio saved to {output_path}")
return output_path
except Exception as e:
log_callback(f"Error during torchaudio mixing: {e}", is_error=True)
raise
# --- Robust Whisper Feature Extractor (Standalone Function) ---
def _process_whisper_features_robust(audio_16k_tensor, whisper_model, whisper_feature_extractor, device):
"""
Process audio through Whisper model to extract features, handling long audio.
audio_16k_tensor: [1, num_samples] tensor on the correct device.
"""
d_model = whisper_model.config.d_model if hasattr(whisper_model, 'config') else whisper_model.encoder.conv1.out_channels # Use out_channels for conv1
audio_16k_tensor = audio_16k_tensor.to(device) # Ensure input tensor is on the correct device
if audio_16k_tensor.size(-1) <= 16000 * 30: # Max 30s for single pass
audio_list_for_extractor = [audio_16k_tensor.squeeze(0).cpu().numpy()]
inputs = whisper_feature_extractor(
audio_list_for_extractor,
return_tensors="pt", return_attention_mask=True, sampling_rate=16000
)
input_features_masked = whisper_model._mask_input_features(
inputs.input_features, attention_mask=inputs.attention_mask
).to(device)
with torch.no_grad(): # Ensure no_grad for inference parts
outputs = whisper_model.encoder(
input_features_masked.to(whisper_model.encoder.dtype),
head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True,
)
features = outputs.last_hidden_state.to(torch.float32)
features = features[:, :audio_16k_tensor.size(-1) // 320 + 1]
else:
overlapping_time_sec = 5
chunk_duration_sec = 30
features_list = []
chunk_duration_samples = 16000 * chunk_duration_sec
overlap_samples = 16000 * overlapping_time_sec
current_original_start_sample = 0
idx = 0
while current_original_start_sample < audio_16k_tensor.size(-1):
idx += 1
conceptual_chunk_start_original = current_original_start_sample
conceptual_chunk_end_original = min(current_original_start_sample + chunk_duration_samples, audio_16k_tensor.size(-1))
whisper_feed_start = max(0, conceptual_chunk_start_original - (overlap_samples if idx > 1 else 0))
whisper_feed_end = conceptual_chunk_end_original
current_whisper_input_chunk = audio_16k_tensor[:, whisper_feed_start:whisper_feed_end]
if current_whisper_input_chunk.size(-1) < (16000 * 0.1): # Min 100ms
if current_original_start_sample >= audio_16k_tensor.size(-1): break
current_original_start_sample = conceptual_chunk_end_original
continue
current_whisper_input_list = [current_whisper_input_chunk.squeeze(0).cpu().numpy()]
inputs = whisper_feature_extractor(
current_whisper_input_list,
return_tensors="pt", return_attention_mask=True, sampling_rate=16000
)
input_features_masked = whisper_model._mask_input_features(
inputs.input_features, attention_mask=inputs.attention_mask
).to(device)
with torch.no_grad(): # Ensure no_grad for inference parts
outputs = whisper_model.encoder(
input_features_masked.to(whisper_model.encoder.dtype),
head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True,
)
chunk_features_full = outputs.last_hidden_state.to(torch.float32)
chunk_features_full = chunk_features_full[:, :current_whisper_input_chunk.size(-1) // 320 + 1]
if idx == 1:
features_to_append = chunk_features_full
else:
overlap_feature_frames_to_discard = overlap_samples // 320
if chunk_features_full.size(1) > overlap_feature_frames_to_discard:
features_to_append = chunk_features_full[:, overlap_feature_frames_to_discard:, :]
else:
features_to_append = torch.empty((1, 0, d_model), device=device, dtype=torch.float32)
if features_to_append.size(1) > 0:
features_list.append(features_to_append)
current_original_start_sample = conceptual_chunk_end_original
if not features_list:
print("Warning: Whisper feature list is empty after chunking. Input audio might be too short or all chunks were skipped.")
return torch.empty((1,0,d_model), device=device, dtype=torch.float32)
features = torch.cat(features_list, dim=1)
return features
# --- Voice Conversion (Adapted from main_app.py) ---
def adjust_f0_semitones_vp2(f0_sequence, n_semitones):
factor = 2 ** (n_semitones / 12)
return f0_sequence * factor
def crossfade_vp2(chunk1, chunk2, overlap):
fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
if len(chunk2) < overlap: # Handle cases where chunk2 is shorter than overlap
overlap_actual = len(chunk2)
chunk2[:overlap_actual] = chunk2[:overlap_actual] * fade_in[:overlap_actual] + \
chunk1[-overlap_actual:] * fade_out[:overlap_actual]
else:
chunk2[:overlap] = chunk2[:overlap] * fade_in + chunk1[-overlap:] * fade_out
return chunk2
def setup_models_vp2(f0_condition, progress_callback):
progress_callback(0, "Setting up models...")
print("Setting up voice conversion models...")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
progress_callback(10, "Loading main DiT model...")
dit_checkpoint_path, dit_config_path = load_custom_model_from_hf(
"Plachta/Seed-VC",
"DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth",
"config_dit_mel_seed_uvit_whisper_small_wavenet.yml"
)
config = yaml.safe_load(open(dit_config_path, 'r'))
model_params = recursive_munch(config['model_params'])
model = build_model(model_params, stage='DiT')
hop_length = config['preprocess_params']['spect_params']['hop_length']
sr = config['preprocess_params']['sr']
model, _, _, _ = load_checkpoint(model, None, dit_checkpoint_path,
load_only_params=True, ignore_modules=[], is_distributed=False)
for key in model:
model[key].eval()
model[key].to(device)
model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)
progress_callback(30, "Loading CAMPPlus model...")
campplus_ckpt_path = load_custom_model_from_hf("funasr/campplus", "campplus_cn_common.bin", config_filename=None)
campplus_model = CAMPPlus(feat_dim=80, embedding_size=192)
campplus_model.load_state_dict(torch.load(campplus_ckpt_path, map_location="cpu"))
campplus_model.eval()
campplus_model.to(device)
progress_callback(50, "Loading BigVGAN model...")
bigvgan_model_instance = bigvgan.BigVGAN.from_pretrained('nvidia/bigvgan_v2_22khz_80band_256x', use_cuda_kernel=False)
bigvgan_model_instance.remove_weight_norm()
bigvgan_model_instance = bigvgan_model_instance.eval().to(device)
progress_callback(70, "Loading Whisper model...")
whisper_name = model_params.speech_tokenizer.whisper_name if hasattr(model_params.speech_tokenizer,
'whisper_name') else "openai/whisper-small"
whisper_model_instance = WhisperModel.from_pretrained(whisper_name, torch_dtype=torch.float16 if device.type == 'cuda' else torch.float32)
# Move to device *after* potential deletion of decoder
if hasattr(whisper_model_instance, 'decoder'): del whisper_model_instance.decoder
whisper_model_instance = whisper_model_instance.to(device) # Ensure it's on device
whisper_feature_extractor_instance = AutoFeatureExtractor.from_pretrained(whisper_name)
mel_fn_args = {
"n_fft": config['preprocess_params']['spect_params']['n_fft'],
"win_size": config['preprocess_params']['spect_params']['win_length'],
"hop_size": config['preprocess_params']['spect_params']['hop_length'],
"num_mels": config['preprocess_params']['spect_params']['n_mels'],
"sampling_rate": sr, "fmin": 0, "fmax": None, "center": False
}
to_mel_instance = lambda x: mel_spectrogram(x, **mel_fn_args)
model_f0_instance, rmvpe_instance, to_mel_f0_instance, bigvgan_44k_model_instance, sr_f0, hop_length_f0 = None, None, None, None, None, None
if f0_condition:
progress_callback(80, "Loading F0 models...")
dit_f0_ckpt_path, dit_f0_config_path = load_custom_model_from_hf(
"Plachta/Seed-VC",
"DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema.pth",
"config_dit_mel_seed_uvit_whisper_base_f0_44k.yml"
)
config_f0 = yaml.safe_load(open(dit_f0_config_path, 'r'))
model_params_f0 = recursive_munch(config_f0['model_params'])
model_f0_instance = build_model(model_params_f0, stage='DiT')
hop_length_f0 = config_f0['preprocess_params']['spect_params']['hop_length']
sr_f0 = config_f0['preprocess_params']['sr']
model_f0_instance, _, _, _ = load_checkpoint(model_f0_instance, None, dit_f0_ckpt_path,
load_only_params=True, ignore_modules=[], is_distributed=False)
for key in model_f0_instance: model_f0_instance[key].eval(); model_f0_instance[key].to(device)
model_f0_instance.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)
rmvpe_model_path = load_custom_model_from_hf("lj1995/VoiceConversionWebUI", "rmvpe.pt", config_filename=None)
rmvpe_instance = RMVPE(rmvpe_model_path, is_half=False, device=device)
mel_fn_args_f0 = {
"n_fft": config_f0['preprocess_params']['spect_params']['n_fft'],
"win_size": config_f0['preprocess_params']['spect_params']['win_length'],
"hop_size": hop_length_f0, "num_mels": config_f0['preprocess_params']['spect_params']['n_mels'],
"sampling_rate": sr_f0, "fmin": 0, "fmax": None, "center": False
}
to_mel_f0_instance = lambda x: mel_spectrogram(x, **mel_fn_args_f0)
bigvgan_44k_model_instance = bigvgan.BigVGAN.from_pretrained('nvidia/bigvgan_v2_44khz_128band_512x', use_cuda_kernel=False)
bigvgan_44k_model_instance.remove_weight_norm()
bigvgan_44k_model_instance = bigvgan_44k_model_instance.eval().to(device)
progress_callback(100, "Models ready.")
models_pack = {
'device': device, 'model': model, 'model_f0': model_f0_instance, 'campplus_model': campplus_model,
'bigvgan_model': bigvgan_model_instance, 'bigvgan_44k_model': bigvgan_44k_model_instance,
'whisper_model': whisper_model_instance, 'whisper_feature_extractor': whisper_feature_extractor_instance,
'rmvpe': rmvpe_instance, 'to_mel': to_mel_instance, 'to_mel_f0': to_mel_f0_instance,
'sr': sr if not f0_condition else sr_f0,
'hop_length': hop_length if not f0_condition else hop_length_f0,
'f0_condition_state': f0_condition
}
print("Voice conversion models set up successfully.")
return models_pack
@torch.no_grad()
@torch.inference_mode()
def voice_conversion_vp2(source_path, target_path, diffusion_steps, length_adjust,
inference_cfg_rate, f0_condition, auto_f0_adjust, pitch_shift, models,
progress_callback=None): # Removed chunk_idx, total_chunks as they are now internal
device = models['device']
inference_module = models['model'] if not f0_condition else models['model_f0']
mel_fn = models['to_mel'] if not f0_condition else models['to_mel_f0']
bigvgan_fn = models['bigvgan_model'] if not f0_condition else models['bigvgan_44k_model']
# Whisper models are passed directly to _process_whisper_features_robust
campplus_model = models['campplus_model']
rmvpe = models['rmvpe']
sr_vc = models['sr']
hop_length = models['hop_length']
max_context_window = sr_vc // hop_length * 30 # For DiT/CFM processing
overlap_frame_len = 16
overlap_wave_len = overlap_frame_len * hop_length
source_audio_orig, sr_orig = librosa.load(source_path, sr=None)
if sr_orig != sr_vc:
source_audio_orig = librosa.resample(source_audio_orig, orig_sr=sr_orig, target_sr=sr_vc)
ref_audio_orig, sr_ref_orig = librosa.load(target_path, sr=None)
if sr_ref_orig != sr_vc:
ref_audio_orig = librosa.resample(ref_audio_orig, orig_sr=sr_ref_orig, target_sr=sr_vc)
if len(ref_audio_orig) > sr_vc * 25:
ref_audio_orig = ref_audio_orig[:sr_vc * 25]
source_audio = torch.tensor(source_audio_orig).unsqueeze(0).float().to(device)
ref_audio = torch.tensor(ref_audio_orig).unsqueeze(0).float().to(device)
# --- Resample for Whisper ---
converted_waves_16k = torchaudio.functional.resample(source_audio, sr_vc, 16000)
ori_waves_16k = torchaudio.functional.resample(ref_audio, sr_vc, 16000)
# --- ROBUST Whisper Feature Extraction ---
models['whisper_model'].to(device) # Ensure on correct device
S_alt = _process_whisper_features_robust(converted_waves_16k, models['whisper_model'], models['whisper_feature_extractor'], device)
S_ori = _process_whisper_features_robust(ori_waves_16k, models['whisper_model'], models['whisper_feature_extractor'], device)
# --- Mel Spectrograms and Style ---
mel = mel_fn(source_audio.float())
mel2 = mel_fn(ref_audio.float())
target_lengths = torch.LongTensor([int(mel.size(2) * length_adjust)]).to(mel.device)
target2_lengths = torch.LongTensor([mel2.size(2)]).to(mel2.device)
feat2 = torchaudio.compliance.kaldi.fbank(ori_waves_16k, num_mel_bins=80, dither=0, sample_frequency=16000)
feat2 = feat2 - feat2.mean(dim=0, keepdim=True)
style2 = campplus_model(feat2.unsqueeze(0))
# --- F0 Processing ---
F0_ori, F0_alt, shifted_f0_alt = None, None, None
if f0_condition and rmvpe:
F0_ori_np = rmvpe.infer_from_audio(ori_waves_16k[0].cpu().numpy(), thred=0.03) # rmvpe expects numpy
F0_alt_np = rmvpe.infer_from_audio(converted_waves_16k[0].cpu().numpy(), thred=0.03)
F0_ori = torch.from_numpy(F0_ori_np).to(device)[None]
F0_alt = torch.from_numpy(F0_alt_np).to(device)[None]
log_f0_alt = torch.log(F0_alt + 1e-5)
if auto_f0_adjust:
voiced_F0_ori = F0_ori[F0_ori > 1]; voiced_F0_alt = F0_alt[F0_alt > 1]
if len(voiced_F0_ori) > 0 and len(voiced_F0_alt) > 0:
median_log_f0_ori = torch.median(torch.log(voiced_F0_ori + 1e-5))
median_log_f0_alt = torch.median(torch.log(voiced_F0_alt + 1e-5))
log_f0_alt[F0_alt > 1] = log_f0_alt[F0_alt > 1] - median_log_f0_alt + median_log_f0_ori
shifted_f0_alt = torch.exp(log_f0_alt)
if pitch_shift != 0:
shifted_f0_alt[F0_alt > 1] = adjust_f0_semitones_vp2(shifted_f0_alt[F0_alt > 1], pitch_shift)
# --- Length Regulation ---
cond, _, _, _, _ = inference_module.length_regulator(S_alt, ylens=target_lengths, n_quantizers=3, f0=shifted_f0_alt)
prompt_condition, _, _, _, _ = inference_module.length_regulator(S_ori, ylens=target2_lengths, n_quantizers=3, f0=F0_ori)
# --- DiT/CFM Processing Loop (Handles its own chunking for acoustic model features) ---
max_source_window_dit = max_context_window - mel2.size(2)
if max_source_window_dit <= 0:
max_source_window_dit = cond.size(1)
print(f"Warning: Reference audio (mel length {mel2.size(2)}) is long. Processing source in one go for DiT/CFM.")
processed_frames_dit = 0
generated_wave_chunks_for_segment = []
previous_vocoder_output_overlap_chunk = None
total_dit_frames = cond.size(1)
num_dit_chunks_for_progress = (total_dit_frames + max_source_window_dit -1) // max_source_window_dit if max_source_window_dit > 0 else 1
current_dit_chunk_idx = 0
while processed_frames_dit < total_dit_frames:
current_dit_chunk_idx += 1
chunk_cond_dit = cond[:, processed_frames_dit : processed_frames_dit + max_source_window_dit]
is_last_dit_chunk = (processed_frames_dit + max_source_window_dit) >= total_dit_frames
cat_condition = torch.cat([prompt_condition, chunk_cond_dit], dim=1)
with torch.autocast(device_type=device.type, dtype=torch.float16 if device.type == 'cuda' else torch.float32):
vc_target_mel = inference_module.cfm.inference(cat_condition,
torch.LongTensor([cat_condition.size(1)]).to(mel2.device),
mel2, style2, None, diffusion_steps,
inference_cfg_rate=inference_cfg_rate)
vc_target_mel = vc_target_mel[:, :, mel2.size(-1):]
vc_wave_chunk = bigvgan_fn(vc_target_mel.float())[0]
if progress_callback:
# Progress is now relative to the DiT loop within this segment
progress_within_segment = (current_dit_chunk_idx / num_dit_chunks_for_progress) * 100
progress_callback(int(progress_within_segment),
f"VC DiT {current_dit_chunk_idx}/{num_dit_chunks_for_progress}: {min(processed_frames_dit + vc_target_mel.size(2), total_dit_frames)}/{total_dit_frames} frames")
if not generated_wave_chunks_for_segment:
if is_last_dit_chunk or overlap_wave_len == 0:
output_wave_for_stitch = vc_wave_chunk[0].cpu().numpy()
else:
output_wave_for_stitch = vc_wave_chunk[0, :-overlap_wave_len].cpu().numpy()
generated_wave_chunks_for_segment.append(output_wave_for_stitch)
previous_vocoder_output_overlap_chunk = vc_wave_chunk[0, -overlap_wave_len:] if overlap_wave_len > 0 else None
elif is_last_dit_chunk or overlap_wave_len == 0:
if previous_vocoder_output_overlap_chunk is not None and overlap_wave_len > 0:
output_wave_for_stitch = crossfade_vp2(previous_vocoder_output_overlap_chunk.cpu().numpy(), vc_wave_chunk[0].cpu().numpy(), overlap_wave_len)
else:
output_wave_for_stitch = vc_wave_chunk[0].cpu().numpy()
generated_wave_chunks_for_segment.append(output_wave_for_stitch)
else:
output_wave_for_stitch = crossfade_vp2(previous_vocoder_output_overlap_chunk.cpu().numpy(), vc_wave_chunk[0, :-overlap_wave_len].cpu().numpy(), overlap_wave_len)
generated_wave_chunks_for_segment.append(output_wave_for_stitch)
previous_vocoder_output_overlap_chunk = vc_wave_chunk[0, -overlap_wave_len:]
if is_last_dit_chunk: break
processed_frames_dit += vc_target_mel.size(2) - (overlap_frame_len if overlap_wave_len > 0 else 0)
if processed_frames_dit >= total_dit_frames: break
final_output_for_segment = np.concatenate(generated_wave_chunks_for_segment) if generated_wave_chunks_for_segment else np.array([], dtype=np.float32)
return sr_vc, final_output_for_segment
# --- RIR Application (Original and New for S2R) ---
def apply_reverb_to_audio_segment( # For simulated RIR
input_audio_path_str: str,
output_audio_path_str: str,
target_sr: int,
room_dim_list: list,
rt60_target: float,
progress_callback=None):
if progress_callback: progress_callback(0, f"Applying reverb: Loading segment {Path(input_audio_path_str).name}")
studio_audio, studio_fs_orig = librosa.load(input_audio_path_str, sr=None, mono=True)
if studio_fs_orig != target_sr:
studio_audio = librosa.resample(studio_audio, orig_sr=studio_fs_orig, target_sr=target_sr)
if studio_audio.ndim == 1:
studio_audio = studio_audio[:, np.newaxis]
studio_audio_pb = studio_audio
elif studio_audio.shape[0] < studio_audio.shape[1]:
studio_audio_pb = studio_audio.T
else:
studio_audio_pb = studio_audio
fs = target_sr
V = np.prod(room_dim_list)
Sx, Sy, Sz = room_dim_list
S_total = 2 * (Sx*Sy + Sx*Sz + Sy*Sz)
if rt60_target <= 0: rt60_target = 0.01
alpha = 0.161 * V / (rt60_target * S_total) if S_total > 0 else 0.5
alpha = np.clip(alpha, 0.01, 0.99)
if progress_callback: progress_callback(30, f"Simulating room (dim: {room_dim_list}, RT60: {rt60_target:.2f}s, alpha: {alpha:.2f})")
try:
room = pra.ShoeBox(room_dim_list, fs=fs, materials=pra.Material(alpha), max_order=15)
except Exception as e:
print(f"Error creating ShoeBox room (dims: {room_dim_list}, alpha: {alpha:.2f}): {e}")
sf.write(output_audio_path_str, studio_audio.squeeze(), fs)
if progress_callback: progress_callback(100, "Room sim failed.")
return
source_pos = [room_dim_list[0]/2, room_dim_list[1]/2, room_dim_list[2]/2]
mic_pos = [source_pos[0] + 1, source_pos[1], source_pos[2]]
mic_pos = [min(max(mic_pos[i], 0.1), room_dim_list[i]-0.1) for i in range(3)]
room.add_source(source_pos)
room.add_microphone_array(pra.MicrophoneArray(np.array([mic_pos]).T, fs=fs))
if progress_callback: progress_callback(60, "Computing RIR...")
try:
room.compute_rir()
if not room.rir or not room.rir[0] or room.rir[0][0] is None or len(room.rir[0][0]) == 0:
raise ValueError("RIR computation failed or resulted in empty RIR.")
rir = room.rir[0][0].astype(np.float32)
except Exception as e:
print(f"RIR computation error: {e}. Skipping reverb.")
sf.write(output_audio_path_str, studio_audio.squeeze(), fs)
if progress_callback: progress_callback(100, "RIR computation failed.")
return
if progress_callback: progress_callback(80, "Applying RIR via Pedalboard...")
convolution = Convolution(rir, sample_rate=fs)
board = Pedalboard([convolution])
output_audio_aligned = board(studio_audio_pb, sample_rate=fs)
sf.write(output_audio_path_str, output_audio_aligned, fs)
if progress_callback: progress_callback(100, "Reverb application complete.")
print(f"Reverberated audio saved to {output_audio_path_str}")
# --- RT60 Estimation Helper ---
def estimate_rt60_from_audio(audio_path_str, progress_callback=None):
if progress_callback: progress_callback(10, "Loading audio for RT60 estimation...")
audio, fs = librosa.load(audio_path_str, sr=None, mono=True)
if progress_callback: progress_callback(50, "Estimating RT60...")
estimator = BlindRT60(fs=fs)
rt60 = estimator.estimate(audio, fs)
if progress_callback: progress_callback(100, f"Estimated RT60: {rt60:.3f}s")
return rt60
# --- Speaker Diarization Helper ---
def extract_speaker_times(rttm_file, target_speaker):
times = []
try:
with open(rttm_file, "r") as f:
for line in f:
if "SPEAKER" in line:
parts = line.split()
if len(parts) >= 8:
try:
speaker_id_from_file = parts[7]
if speaker_id_from_file == target_speaker:
start = float(parts[3])
duration = float(parts[4])
end = start + duration
times.append((start, end))
except (ValueError, IndexError):
print(f"Could not parse RTTM line: {line.strip()}")
continue
except FileNotFoundError:
print(f"RTTM file not found: {rttm_file}")
return times
# --- WaveformWidget (QPainter version, from previous diff) ---
class WaveformWidget(QWidget):
markerClicked = Signal(float, float) # Emit start_sec, end_sec of a clicked visual marker
clickedPosition = Signal(float)
selectionFinalized = Signal(float, float)
def __init__(self, parent_window, *args, **kwargs):
super().__init__(*args, **kwargs)
self.parent_window = parent_window
self.setMinimumHeight(70) # Reduced height to 70% of original 100
self.setMouseTracking(True)
self.y_data_normalized = None
self.duration_sec = 0
self.playback_cursor_pos_sec = 0.0
self.show_playback_cursor = False
self.selection_start_sec = None
self.selection_end_sec = None
self.is_selecting = False
self.is_dragging_playback_cursor = False
self.playback_cursor_handle_width = 10 # pixels, for easier grabbing
self.visual_markers = []
self.waveform_pen = QPen(QColor(0, 0, 255, 180), 1.5)
self.cursor_pen = QPen(Qt.red, 2)
self.selection_brush = QBrush(QColor(0, 0, 255, 50))
def load_audio(self, y_for_plot_normalized, original_sr, original_duration_sec):
self.y_data_normalized = y_for_plot_normalized
self.duration_sec = original_duration_sec
self.playback_cursor_pos_sec = 0.0
self.show_playback_cursor = False
self.selection_start_sec = None
self.selection_end_sec = None
self.is_selecting = False
self.is_dragging_playback_cursor = False
self.visual_markers.clear()
self.update()
def set_playback_cursor(self, time_sec):
if self.duration_sec > 0:
self.playback_cursor_pos_sec = max(0, min(time_sec, self.duration_sec))
self.show_playback_cursor = True
self.update()
def hide_playback_cursor(self):
self.show_playback_cursor = False
self.update()
def add_visual_marker(self, start_sec, end_sec, color=QColor(255, 165, 0, 100)):
if self.duration_sec == 0 or end_sec <= start_sec:
return
self.visual_markers.append((max(0, start_sec), min(self.duration_sec, end_sec), QBrush(color)))
self.visual_markers.sort()
self.update()
def clear_all_visual_markers(self):
self.visual_markers.clear()
self.selection_start_sec = None
self.selection_end_sec = None
self.is_selecting = False
self.is_dragging_playback_cursor = False
self.update()
def get_current_selection(self):
if self.selection_start_sec is not None and self.selection_end_sec is not None:
start = min(self.selection_start_sec, self.selection_end_sec)
end = max(self.selection_start_sec, self.selection_end_sec)
if end > start + 0.01:
return start, end
return None, None
def _time_to_x(self, time_sec):
if self.duration_sec == 0: return 0
return (time_sec / self.duration_sec) * self.width()
def _x_to_time(self, x_pos):
if self.width() == 0: return 0
return (x_pos / self.width()) * self.duration_sec
def paintEvent(self, event):
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
width = self.width()
height = self.height()
# painter.fillRect(self.rect(), Qt.black) # Removed to make background transparent
if self.y_data_normalized is not None and len(self.y_data_normalized) > 0 and self.duration_sec > 0:
for start_s, end_s, brush in self.visual_markers:
x_start = self._time_to_x(start_s)
x_end = self._time_to_x(end_s)
painter.fillRect(QRectF(x_start, 0, x_end - x_start, height), brush)
current_sel = self.get_current_selection()
if current_sel[0] is not None:
sel_x_start = self._time_to_x(current_sel[0])
sel_x_end = self._time_to_x(current_sel[1])
painter.fillRect(QRectF(sel_x_start, 0, sel_x_end - sel_x_start, height), self.selection_brush)
painter.setPen(self.waveform_pen)
num_points = len(self.y_data_normalized)
points_per_pixel = num_points / width if width > 0 else num_points
if points_per_pixel < 1 and num_points > 1:
path = QPolygonF()
for i in range(num_points):
t = (i / (num_points -1)) * self.duration_sec if num_points > 1 else 0
x = self._time_to_x(t)
y_val = self.y_data_normalized[i]
y = height / 2 - (y_val * height / 2.2)
path.append(QPointF(x,y))
painter.drawPolyline(path)
elif num_points > 0 :
for x_pixel in range(width):
start_idx = int(x_pixel * points_per_pixel)
end_idx = int((x_pixel + 1) * points_per_pixel)
if start_idx >= end_idx: end_idx = start_idx + 1
if end_idx > num_points: end_idx = num_points
if start_idx >= num_points: break
segment_data = self.y_data_normalized[start_idx:end_idx]
if len(segment_data) == 0: continue
min_val = np.min(segment_data)
max_val = np.max(segment_data)
y_min = height / 2 - (min_val * height / 2.2)
y_max = height / 2 - (max_val * height / 2.2)
painter.drawLine(QPointF(x_pixel, y_min), QPointF(x_pixel, y_max))
if self.show_playback_cursor:
painter.setPen(self.cursor_pen)
cursor_x = self._time_to_x(self.playback_cursor_pos_sec)
painter.drawLine(QPointF(cursor_x, 0), QPointF(cursor_x, height))
else:
painter.setPen(Qt.white) # Or another contrasting color for your theme
painter.drawText(self.rect(), Qt.AlignCenter, "No audio loaded")
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton and self.y_data_normalized is not None and self.duration_sec > 0:
time_sec = self._x_to_time(event.pos().x())
time_sec = max(0, min(time_sec, self.duration_sec)) # Clamp time
# Check if clicking on the playback cursor handle
if self.show_playback_cursor:
cursor_center_x = self._time_to_x(self.playback_cursor_pos_sec)
handle_half_width = self.playback_cursor_handle_width / 2.0
if cursor_center_x - handle_half_width <= event.pos().x() <= cursor_center_x + handle_half_width:
self.is_dragging_playback_cursor = True
self.is_selecting = False # Prevent selection when dragging cursor
self.set_playback_cursor(time_sec) # Update cursor position immediately
self.clickedPosition.emit(time_sec) # Emit signal to seek audio
self.update()
return # Consume event
# Check if clicking on a visual marker
# This check should happen BEFORE starting a new selection or general seek,
# if marker click is meant to be a distinct action.
clicked_on_marker = False
for i, (m_start_s, m_end_s, _) in enumerate(self.visual_markers):
marker_x_start = self._time_to_x(m_start_s)
marker_x_end = self._time_to_x(m_end_s)
if marker_x_start <= event.pos().x() <= marker_x_end:
self.markerClicked.emit(m_start_s, m_end_s)
clicked_on_marker = True
# If a marker is clicked, we might not want to immediately start a new selection
# or seek, depending on desired UX. For now, we let it proceed.
break
# If not dragging cursor, proceed with normal click (seek and/or start selection)
self.clickedPosition.emit(time_sec)
self.is_selecting = True # Start selection process
self.selection_start_sec = time_sec # For selection
self.selection_end_sec = time_sec # For selection
self.update()
# super().mousePressEvent(event) # Don't call super if we handle it fully
def mouseMoveEvent(self, event):
if self.is_dragging_playback_cursor and self.y_data_normalized is not None and self.duration_sec > 0:
time_sec = self._x_to_time(event.pos().x())
time_sec = max(0, min(time_sec, self.duration_sec)) # Clamp time
self.set_playback_cursor(time_sec) # Updates visual position and calls self.update()
self.clickedPosition.emit(time_sec) # Emit for continuous seeking
elif self.is_selecting and self.y_data_normalized is not None and self.duration_sec > 0:
self.selection_end_sec = self._x_to_time(event.pos().x()) # For selection
self.update() # For selection
# super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.y_data_normalized is not None and self.duration_sec > 0:
if self.is_dragging_playback_cursor:
self.is_dragging_playback_cursor = False
# Final position already set by set_playback_cursor in mouseMove or mousePress
# Emit signal one last time to ensure audio seeks to the final dragged position
time_sec = self._x_to_time(event.pos().x())
time_sec = max(0, min(time_sec, self.duration_sec)) # Clamp time
self.clickedPosition.emit(time_sec)
self.update()
return # Consume event
if self.is_selecting: # Handle selection finalization
self.is_selecting = False
self.selection_end_sec = self._x_to_time(event.pos().x())
start, end = self.get_current_selection()
if start is not None and end is not None:
self.selectionFinalized.emit(start, end)
self.update() # For selection
# super().mouseReleaseEvent(event)
def clear_selection(self):
self.selection_start_sec = None
self.selection_end_sec = None
self.is_selecting = False
self.update()
# --- Worker Thread ---
class WorkerThread(QThread):
progress = Signal(int, str)
finished = Signal(object, str)
log_message = Signal(str, bool) # message, is_error
def __init__(self, func, *args, **kwargs):
super().__init__()
self.func = func
self.args = args
self.kwargs = kwargs
def _progress_callback_adapter(self, value, desc):
self.progress.emit(int(value), desc)
def _log_callback_adapter(self, message, is_error=False):
self.log_message.emit(message, is_error)
def run(self):
try:
self.kwargs['progress_callback'] = self._progress_callback_adapter
# Add log_callback if the target function expects it
if 'log_callback' in self.func.__code__.co_varnames:
self.kwargs['log_callback'] = self._log_callback_adapter
result = self.func(*self.args, **self.kwargs)
self.finished.emit(result, "Task completed successfully.")
except Exception as e:
import traceback
tb_str = traceback.format_exc()
print(f"Error in worker thread: {e}\n{tb_str}")
self.log_message.emit(f"Worker Error: {str(e)}\n{tb_str}", True)
self.finished.emit(None, f"Error: {str(e)}")
# --- Main Window ---
class MainWindow(QMainWindow):
def __init__(self):
# ... (constructor and _init_ui, _connect_signals as before, with WaveformWidget(self)) ...
super().__init__()
self.setWindowTitle("VideoVoiceSwap") # Updated Title
self.setGeometry(50, 50, 1600, 950) # Slightly larger
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.main_layout = QVBoxLayout(self.central_widget)
self.input_mp4_path = None
self.target_voice_path = None
self.output_dir_path = None
self.source_audio_full_path = None
self.source_audio_sr = None
self.source_audio_duration_sec = 0
self.source_video_fps = None # To store video FPS
self.source_time_markers = []
self.swapped_audio_full_path = None
self.swapped_audio_markers = []
self.estimated_rir_path = None # Path to the RIR estimated by Speech2RIR
self.diarization_results = None
self.auto_rir_segment_duration_sec = 20 # Default duration for auto RIR segments
self.scene_cuts_sec = [] # To store detected scene cut timestamps in seconds
self.player = QMediaPlayer()
self.audio_output = QAudioOutput()
self.player.setAudioOutput(self.audio_output)
self.player.positionChanged.connect(self._update_waveform_cursor_on_play)
self.player.playbackStateChanged.connect(self._on_playback_state_changed)
self._init_ui()
self._connect_signals()
TMP_DIR.mkdir(parents=True, exist_ok=True)
self.hf_token = HUGGING_FACE_TOKEN_PLACEHOLDER
self.hf_token_edit.setText(self.hf_token)
self.clearvoice_se_model_name = 'MossFormer2_SE_48K' # Default SE model
self.swapped_audio_waveform_widget.hide()
self.current_worker = None # Explicitly initialize after UI setup
def _init_ui(self):
# --- Top Row Container for Height Adjustment ---
top_row_container = QWidget()
# Estimate current height or set a fixed one. Let's try 220px for a +30px feel.
# Original might be around 150-190px depending on font and spacing.
# Minimum height of input files group + config group + margins.
# An input file row is (LineEdit + Button) ~30-35px. 3 rows = ~100px. Groupbox title ~20px. Total ~120px.
# Config group has multiple elements, let's say ~120-150px. Tab bar itself.
top_row_container.setMinimumHeight(210) # Increased height for the top row
top_row_layout = QHBoxLayout(top_row_container)
# ... (UI setup as before, ensuring WaveformWidget(self) is used) ...
# --- Top Row: File Inputs & Room/HF Token ---
# --- Left Pane for Top Row (Input Files & Global Config) ---
left_top_pane_widget = QWidget()
left_top_pane_layout = QHBoxLayout(left_top_pane_widget) # Changed to QHBoxLayout
left_top_pane_layout.setContentsMargins(0,0,0,0) # Optional: remove inner margins
# left_top_pane_widget.setStyleSheet("border: 1px solid red;") # For debugging layout
input_files_group = QGroupBox("Input Files")
input_files_layout = QVBoxLayout()
mp4_file_layout = QHBoxLayout()
self.mp4_label = QLineEdit("No MP4 file selected")
self.mp4_label.setReadOnly(True)
self.mp4_button = QPushButton("Select Input MP4")
mp4_file_layout.addWidget(self.mp4_label)
mp4_file_layout.addWidget(self.mp4_button)
input_files_layout.addLayout(mp4_file_layout)
wav_file_layout = QHBoxLayout()
self.wav_label = QLineEdit("No Target voice audio file selected")
self.wav_label.setReadOnly(True)
self.wav_button = QPushButton("Select Target Audio")
wav_file_layout.addWidget(self.wav_label)
wav_file_layout.addWidget(self.wav_button)
self.clean_target_voice_button = QPushButton("Clean Target")
self.clean_target_voice_button.setToolTip("Clean Target Voice (Speech Enhancement).\nApply Speech Enhancement to the selected target voice file.\nRequires ClearVoice models and configs.")
self.clean_target_voice_button.setEnabled(False) # Enabled when target wav is selected
wav_file_layout.addWidget(self.clean_target_voice_button)
input_files_layout.addLayout(wav_file_layout)
output_dir_layout = QHBoxLayout()
self.output_dir_label = QLineEdit("No output directory selected")
self.output_dir_label.setReadOnly(True)
self.output_dir_button = QPushButton("Select Output Directory")
output_dir_layout.addWidget(self.output_dir_label)