-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy_xtts_trainer.py
2035 lines (1718 loc) · 88 KB
/
easy_xtts_trainer.py
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 argparse
import os
import json
import random
import shutil
import subprocess
from pathlib import Path
from pydub import AudioSegment
from pydub.silence import detect_leading_silence
import csv
import torch
import torchaudio
from TTS.config.shared_configs import BaseDatasetConfig
from TTS.tts.datasets import load_tts_samples
from TTS.tts.layers.xtts.trainer.gpt_trainer import GPTArgs, GPTTrainer, GPTTrainerConfig, XttsAudioConfig
from TTS.utils.manage import ModelManager
from trainer import Trainer, TrainerArgs
import gc
from datetime import datetime
import requests
from tqdm import tqdm
import re
import logging
import sys
import time
from dataclasses import dataclass, asdict
from typing import List, Dict, Tuple, Optional, Literal
import json
from pathlib import Path
from scipy import signal
import numpy as np
from df.enhance import enhance, init_df, load_audio, save_audio
import soundfile as sf
import librosa
import traceback
conda_path = Path("../conda/Scripts/conda.exe")
class AudioProcessor:
def __init__(self, target_sr: int = 22050):
self.target_sr = target_sr
self.deepfilter_model = None
self.df_state = None
# Compression profiles optimized for different voice types
self.compression_profiles: Dict = {
'male': {
'threshold': -18,
'ratio': 3.0,
'attack': 0.020,
'release': 0.150,
'knee_width': 6
},
'female': {
'threshold': -16,
'ratio': 2.5,
'attack': 0.015,
'release': 0.120,
'knee_width': 4
},
'neutral': {
'threshold': -17,
'ratio': 2.75,
'attack': 0.018,
'release': 0.135,
'knee_width': 5
}
}
# De-essing profiles
self.dess_profiles: Dict = {
'low': {
'threshold': 0.15,
'ratio': 2.5,
'makeup_gain': 0.5,
'reduction_factor': 0.3,
'freq_range': (4500, 9000)
},
'high': {
'threshold': 0.25,
'ratio': 3.5,
'makeup_gain': 0.4,
'reduction_factor': 0.5,
'freq_range': (5000, 10000)
}
}
self.segment_window_ms = 200 # Window for finding cut points
self.analysis_window_ms = 2 # Window for energy analysis
def apply_fades(self, audio: np.ndarray, sr: int, fade_in_ms: Optional[int] = None,
fade_out_ms: Optional[int] = None) -> np.ndarray:
"""
Apply fade-in and/or fade-out effects to audio.
Args:
audio: Input audio array
sr: Sample rate
fade_in_ms: Duration of fade-in in milliseconds
fade_out_ms: Duration of fade-out in milliseconds
Returns:
Audio with fades applied
"""
try:
# Make a copy to avoid modifying the original array
audio = audio.copy()
# Convert ms to samples
fade_in_samples = int((fade_in_ms / 1000) * sr) if fade_in_ms else 0
fade_out_samples = int((fade_out_ms / 1000) * sr) if fade_out_ms else 0
# Apply fade-in
if fade_in_samples > 0:
if fade_in_samples >= len(audio):
fade_in_samples = len(audio) // 2 # Limit to half the audio length
fade_in = np.linspace(0, 1, fade_in_samples)
audio[:fade_in_samples] *= fade_in
# Apply fade-out
if fade_out_samples > 0:
if fade_out_samples >= len(audio):
fade_out_samples = len(audio) // 2 # Limit to half the audio length
fade_out = np.linspace(1, 0, fade_out_samples)
audio[-fade_out_samples:] *= fade_out
return audio
except Exception as e:
print(f"Error applying fades: {str(e)}")
return audio
def remove_trailing_silence(self, audio: np.ndarray, sr: int, silence_threshold=-50.0, chunk_size=10) -> np.ndarray:
"""
Remove trailing silence using pydub's detect_leading_silence function.
Args:
audio: Input audio array
sr: Sample rate
silence_threshold: The threshold (in dB) below which is considered silence
chunk_size: Size of chunks to analyze (in ms)
Returns:
Trimmed audio array with trailing silence removed
"""
try:
# Convert numpy array to AudioSegment
audio_segment = AudioSegment(
audio.tobytes(),
frame_rate=sr,
sample_width=audio.dtype.itemsize,
channels=1 if len(audio.shape) == 1 else audio.shape[1]
)
# Detect trailing silence by reversing the audio
trailing_silence = detect_leading_silence(
audio_segment.reverse(),
silence_threshold=silence_threshold,
chunk_size=chunk_size
)
# Convert milliseconds to samples
samples_to_remove = int((trailing_silence / 1000) * sr)
# Trim the audio
if samples_to_remove > 0:
return audio[:-samples_to_remove]
return audio
except Exception as e:
print(f"Error in remove_trailing_silence: {str(e)}")
return audio
def find_lowest_energy_point(self, audio: AudioSegment, start_time: float, end_time: float, is_start_cut: bool = True) -> float:
"""
Find the absolute quietest point using 2ms subwindows.
is_start_cut: True if looking for start cut (100ms max), False for end cut (200ms max)
"""
try:
# Convert times to milliseconds
start_ms = int(start_time * 1000)
end_ms = int(end_time * 1000)
if end_ms <= start_ms:
return start_time
# Apply maximum window constraints
window_duration_ms = end_ms - start_ms
max_window_ms = 100 if is_start_cut else 200
if window_duration_ms > max_window_ms:
if is_start_cut:
start_ms = end_ms - max_window_ms
else:
end_ms = start_ms + max_window_ms
window_duration_ms = max_window_ms
window = audio[start_ms:end_ms]
# Fixed 2ms subwindows
subwindow_size_ms = 2
num_subwindows = window_duration_ms // subwindow_size_ms
print(f"\nAnalyzing {window_duration_ms}ms window from {start_time:.3f}s to {end_time:.3f}s")
print(f"Dividing into {num_subwindows} subwindows of {subwindow_size_ms}ms each")
if subwindow_size_ms < 2 or num_subwindows < 1:
print(f"Window too small ({window_duration_ms}ms), using midpoint")
return (start_time + end_time) / 2
samples = np.array(window.get_array_of_samples(), dtype=np.float32)
sample_silence_threshold = 1e-4
# Analyze each subwindow
subwindow_data = []
for i in range(num_subwindows):
start_idx = i * len(samples) // num_subwindows
end_idx = (i + 1) * len(samples) // num_subwindows
subwindow = samples[start_idx:end_idx]
# Check for true silence
silence_ratio = np.sum(np.abs(subwindow) < sample_silence_threshold) / len(subwindow)
is_silent = silence_ratio > 0.95
# Calculate RMS energy
rms = np.sqrt(np.mean(subwindow**2))
db = 20 * np.log10(max(rms, 1e-5))
subwindow_start_time = start_time + (i * window_duration_ms / num_subwindows) / 1000
subwindow_center = subwindow_start_time + (subwindow_size_ms / 2000)
print(f"Subwindow {i+1}: {db:.1f}dB, silence_ratio: {silence_ratio:.2f}, center at {subwindow_center:.3f}s")
subwindow_data.append({
'index': i,
'db': db,
'center_time': subwindow_center,
'is_silent': is_silent,
'start_time': subwindow_start_time,
'end_time': subwindow_start_time + (subwindow_size_ms / 1000),
'samples': subwindow
})
if not subwindow_data:
return (start_time + end_time) / 2
# First check for true silence
silent_windows = [w for w in subwindow_data if w['is_silent']]
if silent_windows:
# Find the silent window with lowest energy
optimal_window = min(silent_windows, key=lambda x: x['db'])
# Find the absolute lowest point within this window
min_sample_idx = np.argmin(np.abs(optimal_window['samples']))
relative_time = min_sample_idx / len(optimal_window['samples']) * subwindow_size_ms / 1000
optimal_time = optimal_window['start_time'] + relative_time
print(f"Found true silence at {optimal_time:.3f}s")
else:
# Find the window with lowest energy
optimal_window = min(subwindow_data, key=lambda x: x['db'])
# Find the absolute lowest point within this window
min_sample_idx = np.argmin(np.abs(optimal_window['samples']))
relative_time = min_sample_idx / len(optimal_window['samples']) * subwindow_size_ms / 1000
optimal_time = optimal_window['start_time'] + relative_time
print(f"Found lowest energy point ({optimal_window['db']:.1f}dB) at {optimal_time:.3f}s")
final_time = max(start_time, min(end_time, optimal_time))
if final_time != optimal_time:
print(f"Adjusted time to {final_time:.3f}s to stay within bounds")
return final_time
except Exception as e:
print(f"Error in find_lowest_energy_point: {str(e)}")
return (start_time + end_time) / 2
def find_optimal_cut_points(self, segments: List[Dict], audio: AudioSegment) -> List[Dict[str, Tuple[float, Optional[float], Optional[float]]]]:
"""
Find optimal cut points between segments by analyzing the quietest point
between contextual words and segments.
"""
if not segments:
return []
cut_points = []
audio_length_sec = len(audio) / 1000 # Convert to seconds
# Define window sizes at the start of the method
max_start_window = 0.1 # 100ms for start cuts
max_end_window = 0.3 # 300ms for end cuts
# Create debug log file in the same directory as the audio
debug_log_path = Path(segments[0]['words'][0].get('audio_file', 'debug')).parent / 'cut_points_debug.log'
with open(debug_log_path, 'w', encoding='utf-8') as debug_log:
debug_log.write("Cut Points Analysis Debug Log\n")
debug_log.write("===========================\n")
debug_log.write(f"Audio duration: {audio_length_sec:.3f}s\n")
debug_log.write(f"Number of segments: {len(segments)}\n")
debug_log.write(f"Max start window: {max_start_window*1000:.0f}ms\n")
debug_log.write(f"Max end window: {max_end_window*1000:.0f}ms\n\n")
for i in range(len(segments)):
curr_segment = segments[i]
curr_first_word = next((w for w in curr_segment["words"] if "start" in w), None)
curr_last_word = next((w for w in reversed(curr_segment["words"]) if "end" in w), None)
if not curr_first_word or not curr_last_word:
debug_log.write(f"\nSkipping segment {i} - Missing word timestamps\n")
continue
# Log segment details
debug_log.write(f"\n{'='*20} Segment {i} {'='*20}\n")
debug_log.write(f"Text: {' '.join(w['word'] for w in curr_segment['words'])}\n")
debug_log.write(f"Duration: {curr_last_word['end'] - curr_first_word['start']:.3f}s\n")
debug_log.write(f"Words: {len(curr_segment['words'])}\n")
debug_log.write("\nWord timings:\n")
for word in curr_segment['words']:
if 'start' in word and 'end' in word:
duration = word['end'] - word['start']
debug_log.write(f" '{word['word']}': {word['start']:.3f}s - {word['end']:.3f}s ({duration*1000:.0f}ms)\n")
# Context - previous word's end time and next word's start time
prev_word_end = None
next_word_start = None
# Get previous segment info
if i > 0:
prev_segment = segments[i-1]
prev_last_word = next((w for w in reversed(prev_segment["words"]) if "end" in w), None)
if prev_last_word:
prev_word_end = prev_last_word["end"]
debug_log.write(f"\nPrevious context: '{prev_last_word['word']}' ending at {prev_word_end:.3f}s\n")
else:
debug_log.write(f"\nFirst segment - no previous word\n")
# Get next segment info
if i < len(segments) - 1:
next_segment = segments[i+1]
next_first_word = next((w for w in next_segment["words"] if "start" in w), None)
if next_first_word:
next_word_start = next_first_word["start"]
debug_log.write(f"Next context: '{next_first_word['word']}' starting at {next_word_start:.3f}s\n")
else:
debug_log.write(f"Last segment - no next word\n")
# Calculate search windows
start_search_end = curr_first_word["start"]
if prev_word_end is not None and (start_search_end - prev_word_end) < max_start_window:
# If previous word is closer than 100ms, look back to that word
# But ensure at least 50ms window
start_search_start = min(prev_word_end, start_search_end - 0.05)
else:
# Otherwise only look back 100ms
start_search_start = max(0, start_search_end - max_start_window)
end_search_start = curr_last_word["end"]
if next_word_start is not None and (next_word_start - end_search_start) < max_end_window:
# If next word is closer than 200ms, look forward to that word
end_search_end = next_word_start
else:
# Otherwise only look forward 200ms
end_search_end = min(audio_length_sec, end_search_start + max_end_window)
debug_log.write("\nSearching for cut points:\n")
debug_log.write(f"Start window: {start_search_start:.3f}s - {start_search_end:.3f}s ({(start_search_end-start_search_start)*1000:.0f}ms)\n")
debug_log.write(f"End window: {end_search_start:.3f}s - {end_search_end:.3f}s ({(end_search_end-end_search_start)*1000:.0f}ms)\n")
# Find optimal points
start_time = self.find_lowest_energy_point(audio, start_search_start, start_search_end, is_start_cut=True)
end_time = self.find_lowest_energy_point(audio, end_search_start, end_search_end, is_start_cut=False)
cut_points.append({
"start": start_time,
"end": end_time,
"prev_word_end": prev_word_end,
"next_word_start": next_word_start
})
# Log final results
debug_log.write("\nFinal cut points:\n")
debug_log.write(f"Start cut at: {start_time:.3f}s\n")
debug_log.write(f" Distance from search start: {(start_time-start_search_start)*1000:.0f}ms\n")
debug_log.write(f" Distance to first word: {(curr_first_word['start']-start_time)*1000:.0f}ms\n")
if prev_word_end is not None:
debug_log.write(f" Gap from previous word: {(start_time-prev_word_end)*1000:.0f}ms\n")
debug_log.write(f"End cut at: {end_time:.3f}s\n")
debug_log.write(f" Distance from search start: {(end_time-end_search_start)*1000:.0f}ms\n")
debug_log.write(f" Distance from last word: {(end_time-curr_last_word['end'])*1000:.0f}ms\n")
if next_word_start is not None:
debug_log.write(f" Gap to next word: {(next_word_start-end_time)*1000:.0f}ms\n")
debug_log.write(f"Final segment duration: {end_time-start_time:.3f}s\n")
debug_log.write("="*50 + "\n")
return cut_points
def check_for_abrupt_ending(self, audio: np.ndarray, sr: int, threshold_ms: int = 50) -> bool:
"""
Check if audio segment ends abruptly using multiple factors with more sensitive thresholds.
"""
try:
# Convert audio to float32 and normalize
if audio.dtype != np.float32:
audio = audio.astype(np.float32)
if np.max(np.abs(audio)) > 1.0:
audio = audio / np.max(np.abs(audio))
# Analyze the final portion of audio
tail_ms = 100 # Look at final 100ms
tail_samples = min(int((tail_ms / 1000) * sr), len(audio) // 3)
tail = audio[-tail_samples:]
# Calculate RMS energy in small windows
window_ms = 5 # 5ms windows for finer resolution
window_size = int((window_ms / 1000) * sr)
windows = np.array_split(tail, tail_samples // window_size)
energy = np.array([np.sqrt(np.mean(w**2)) for w in windows])
# Calculate metrics
end_energy = np.mean(energy[-3:])
peak_energy = np.max(energy)
energy_ratio = end_energy / peak_energy
# Calculate energy slope at the end
if len(energy) >= 4:
end_slope = (energy[-1] - energy[-4]) / 3
else:
end_slope = 0
# Zero-crossing analysis
zcr_windows = np.array_split(tail, 4)
zcr_rates = [np.sum(np.abs(np.diff(np.signbit(w)))) / len(w) for w in zcr_windows]
zcr_variance = np.var(zcr_rates)
zcr_change = abs(zcr_rates[-1] - np.mean(zcr_rates[:-1])) if len(zcr_rates) > 1 else 0
# Check for sudden amplitude drop
amplitude_envelope = np.abs(tail)
final_samples = amplitude_envelope[-int(0.01 * sr):] # Last 10ms
sudden_drop = np.mean(final_samples) < 0.1 * np.mean(amplitude_envelope)
# More sensitive thresholds
is_abrupt = (
(energy_ratio > 0.5 or # Energy doesn't drop enough
end_slope > 0 or # Energy increases at the end
zcr_variance > 0.05 or # Irregular zero crossings
zcr_change > 0.3 or # Sudden change in zero-crossing rate
sudden_drop) # Sudden amplitude drop
and
end_energy > 0.1 # Ensure there's significant energy at the end
)
# Print detailed analysis if it's abrupt
if is_abrupt:
print("\nAbrupt ending detected:")
print(f"Energy ratio: {energy_ratio:.3f} (> 0.5 suggests abrupt)")
print(f"End slope: {end_slope:.3f} (positive suggests abrupt)")
print(f"ZCR variance: {zcr_variance:.3f} (> 0.05 suggests abrupt)")
print(f"ZCR change: {zcr_change:.3f} (> 0.3 suggests abrupt)")
print(f"Sudden drop: {sudden_drop}")
print(f"End energy: {end_energy:.3f}")
return is_abrupt
except Exception as e:
print(f"Error in check_for_abrupt_ending: {str(e)}")
print(f"Audio shape: {audio.shape if isinstance(audio, np.ndarray) else 'invalid'}")
print(f"Audio type: {audio.dtype if isinstance(audio, np.ndarray) else 'invalid'}")
return False
def _calculate_zcr_variance(self, audio: np.ndarray) -> float:
"""Calculate zero-crossing rate variance with adaptive windowing."""
window_size = len(audio) // 4
zcr_groups = [
np.sum(np.abs(np.diff(np.signbit(g)))) / len(g)
for g in np.array_split(audio, max(4, len(audio) // window_size))
]
return np.var(zcr_groups)
def process_segments(self, input_path: str, segments: List[Dict], output_dir: Path, args) -> List[Dict[str, str]]:
try:
# Load audio file
audio = AudioSegment.from_wav(input_path)
# Track statistics for final report
total_segments = len(segments)
discarded_segments = []
# Apply negative offset to last words
adjusted_segments = []
for segment in segments:
if segment['words']:
# Create a deep copy of the segment
adjusted_segment = {
'words': segment['words'][:-1], # All words except last
'text': segment['text']
}
# Adjust the last word's end time
last_word = segment['words'][-1].copy()
if 'end' in last_word:
base_offset = args.negative_offset_last_word / 1000
if any(last_word['word'].strip().endswith(p) for p in '.!?'):
offset = base_offset * 2
else:
offset = base_offset
last_word['end'] = max(
last_word['start'],
last_word['end'] - offset
)
adjusted_segment['words'].append(last_word)
adjusted_segments.append(adjusted_segment)
cut_points = self.find_optimal_cut_points(adjusted_segments, audio)
processed_segments = []
print(f"\nProcessing {total_segments} segments from {Path(input_path).name}...")
# Process each segment
for i, cut_point in enumerate(cut_points):
start_ms = int(cut_point["start"] * 1000)
end_ms = int(cut_point["end"] * 1000)
# Extract segment
segment_audio = audio[start_ms:end_ms]
segment_duration = len(segment_audio) / 1000.0 # duration in seconds
segment_text = " ".join(w["word"] for w in adjusted_segments[i]["words"]).strip()
# Check for abrupt ending if flag is set
if args.discard_abrupt:
samples = np.array(segment_audio.get_array_of_samples(), dtype=np.float32)
samples = samples / max(np.max(np.abs(samples)), 1) # Normalize to [-1, 1]
if self.check_for_abrupt_ending(samples, segment_audio.frame_rate):
discarded_segments.append({
"index": i,
"duration": segment_duration,
"text": segment_text,
"reason": "abrupt ending"
})
print(f"\n⚠️ Discarding segment {i}:")
print(f" Duration: {segment_duration:.2f}s")
print(f" Text: \"{segment_text}\"")
continue
# Generate output filename
output_path = output_dir / f"{Path(input_path).stem}_segment_{i}.wav"
# Export raw segment
segment_audio.export(str(output_path), format="wav")
# Apply audio processing chain
if any([args.normalize is not None, args.dess, args.denoise,
args.compress, args.fade_in > 0, args.fade_out > 0, args.trim]):
success = self.process_audio(
str(output_path),
str(output_path),
normalize_target=-float(args.normalize) if args.normalize else None,
dess_profile='high' if args.dess else None,
denoise=args.denoise,
compress_profile=args.compress if args.compress else None,
fade_in_ms=args.fade_in,
fade_out_ms=args.fade_out,
trim=args.trim
)
if not success:
discarded_segments.append({
"index": i,
"duration": segment_duration,
"text": segment_text,
"reason": "processing failed"
})
print(f"\n⚠️ Discarding segment {i}:")
print(f" Duration: {segment_duration:.2f}s")
print(f" Text: \"{segment_text}\"")
print(f" Reason: Audio processing failed")
continue
# Store segment information
processed_segments.append({
"audio_file": str(output_path),
"text": segment_text,
"speaker_name": "001"
})
# Print final statistics
print("\nSegment Processing Summary:")
print(f"Total segments: {total_segments}")
print(f"Successfully processed: {len(processed_segments)}")
if discarded_segments:
print(f"Discarded segments: {len(discarded_segments)}")
print("\nDiscarded segments details:")
for disc in discarded_segments:
print(f"\nSegment {disc['index']}:")
print(f"Duration: {disc['duration']:.2f}s")
print(f"Text: \"{disc['text']}\"")
print(f"Reason: {disc['reason']}")
return processed_segments
except Exception as e:
print(f"Error processing segments: {str(e)}")
return []
def _init_deepfilter(self):
"""Initialize DeepFilterNet model lazily"""
if self.deepfilter_model is None:
self.deepfilter_model, self.df_state, _ = init_df()
def process_audio(self, input_path: str, output_path: str,
normalize_target: Optional[float] = None,
dess_profile: Optional[str] = None,
denoise: bool = False,
compress_profile: Optional[str] = None,
fade_in_ms: Optional[int] = None,
fade_out_ms: Optional[int] = None,
trim: bool = False) -> bool:
try:
# Load and pre-process audio
if denoise:
# Use DeepFilterNet's own loading and processing functions
self._init_deepfilter()
audio, _ = load_audio(input_path, sr=self.df_state.sr())
# Denoise the audio
audio = enhance(self.deepfilter_model, self.df_state, audio)
# Convert tensor to numpy array
audio = audio.cpu().numpy()
if audio.ndim == 2: # If 2D array (channels, samples)
audio = audio[0] # Take first channel
sr = self.df_state.sr()
else:
# Load audio normally if no denoising needed
audio, sr = sf.read(input_path)
# Validate audio array
if audio is None or len(audio) == 0:
print(f"Error: Empty or invalid audio loaded from {input_path}")
return False
# Ensure audio is floating point with correct range
if audio.dtype != np.float32:
audio = audio.astype(np.float32)
if np.max(np.abs(audio)) > 1.0:
audio = audio / np.max(np.abs(audio))
# Resample if needed
if sr != self.target_sr:
print(f"Resampling from {sr}Hz to {self.target_sr}Hz")
audio = librosa.resample(audio, orig_sr=sr, target_sr=self.target_sr)
sr = self.target_sr
# Process order matters:
# 1. Normalize before compression (if requested)
if normalize_target:
print(f"Normalizing to {normalize_target} LUFS")
audio = self._normalize(audio, target_lufs=normalize_target)
# 2. Compress after normalization
if compress_profile:
print(f"Applying {compress_profile} compression profile")
audio = self._compress(audio, compress_profile)
# 3. De-ess after compression
if dess_profile:
print(f"Applying {dess_profile} de-essing profile")
audio = self._deess(audio, dess_profile)
# 4. Trim silence before fades
if trim:
print("Removing trailing silence")
audio = self.remove_trailing_silence(audio, sr)
# 5. Apply fades after trimming
if fade_in_ms or fade_out_ms:
print(f"Applying fades: in={fade_in_ms}ms, out={fade_out_ms}ms")
audio = self.apply_fades(audio, sr, fade_in_ms, fade_out_ms)
# Final peak normalization to prevent clipping
peak = np.max(np.abs(audio))
if peak > 0.99:
print("Applying final peak normalization")
audio = audio * (0.99 / peak)
# Validate final audio
if np.isnan(audio).any() or np.isinf(audio).any():
print("Error: Audio contains NaN or Inf values after processing")
return False
# Save processed audio
try:
sf.write(output_path, audio, sr)
if not os.path.exists(output_path):
print(f"Error: File not written to {output_path}")
return False
except Exception as e:
print(f"Error saving audio file: {str(e)}")
return False
return True
except Exception as e:
print(f"Error processing audio: {str(e)}")
print(f"Audio shape: {audio.shape if 'audio' in locals() else 'not loaded'}")
print(f"Audio type: {type(audio) if 'audio' in locals() else 'not loaded'}")
print(f"Sample rate: {sr if 'sr' in locals() else 'not loaded'}")
return False
finally:
# Clear any GPU memory if used
if denoise and hasattr(self, 'deepfilter_model'):
if torch.cuda.is_available():
torch.cuda.empty_cache()
def _normalize(self, audio: np.ndarray, target_lufs: float = -16.0) -> np.ndarray:
"""Normalize audio to target LUFS with true peak limiting"""
# Calculate current LUFS
rms = np.sqrt(np.mean(audio**2))
current_lufs = 20 * np.log10(rms) - 0.691
# Calculate required gain
gain = 10 ** ((target_lufs - current_lufs) / 20)
# Apply true peak limiting
peak = np.max(np.abs(audio * gain))
if peak > 0.99:
gain *= 0.99 / peak
return audio * gain
def _compress(self, audio: np.ndarray, profile: Literal['male', 'female', 'neutral']) -> np.ndarray:
"""Dynamic range compression with voice-optimized profiles"""
params = self.compression_profiles[profile]
# Convert threshold to linear
threshold_linear = 10 ** (params['threshold'] / 20)
knee_lower = threshold_linear * (10 ** (-params['knee_width'] / 40))
knee_upper = threshold_linear * (10 ** (params['knee_width'] / 40))
# Calculate gain reduction
gain_reduction = np.zeros_like(audio)
# Below knee
mask_below = np.abs(audio) <= knee_lower
gain_reduction[mask_below] = 0
# Above knee
mask_above = np.abs(audio) >= knee_upper
gain_above = (1 - 1/params['ratio']) * (20 * np.log10(np.abs(audio[mask_above])) - params['threshold'])
gain_reduction[mask_above] = gain_above
# In knee
mask_knee = ~mask_below & ~mask_above
knee_curve = (1 - 1/params['ratio']) * ((20 * np.log10(np.abs(audio[mask_knee])) - params['threshold'] + params['knee_width']/2)**2 / (2 * params['knee_width']))
gain_reduction[mask_knee] = knee_curve
# Apply attack/release envelope
attack_coef = np.exp(-1 / (params['attack'] * self.target_sr))
release_coef = np.exp(-1 / (params['release'] * self.target_sr))
gain_reduction_smoothed = np.zeros_like(gain_reduction)
for i in range(1, len(gain_reduction)):
if gain_reduction[i] <= gain_reduction_smoothed[i-1]:
# Attack phase
gain_reduction_smoothed[i] = attack_coef * gain_reduction_smoothed[i-1] + (1 - attack_coef) * gain_reduction[i]
else:
# Release phase
gain_reduction_smoothed[i] = release_coef * gain_reduction_smoothed[i-1] + (1 - release_coef) * gain_reduction[i]
# Convert gain reduction to linear domain and apply
gain_reduction_linear = 10 ** (gain_reduction_smoothed / 20)
return audio * gain_reduction_linear
def _deess(self, audio: np.ndarray, profile: Literal['low', 'high']) -> np.ndarray:
"""Enhanced de-essing with two profiles"""
params = self.dess_profiles[profile]
# Create bandpass filter for sibilance detection
nyquist = self.target_sr / 2
low_freq = params['freq_range'][0] / nyquist
high_freq = params['freq_range'][1] / nyquist
b, a = signal.butter(4, [low_freq, high_freq], btype='band')
# Extract and process sibilance
sibilants = signal.filtfilt(b, a, audio)
# Calculate adaptive threshold
rms = np.sqrt(np.mean(sibilants**2))
adaptive_threshold = params['threshold'] * rms
# Apply compression to sibilants
mask = np.abs(sibilants) > adaptive_threshold
sibilants[mask] = (
adaptive_threshold +
(np.abs(sibilants[mask]) - adaptive_threshold) / params['ratio']
) * np.sign(sibilants[mask])
# Apply makeup gain
sibilants *= params['makeup_gain']
# Smooth transitions
env_b, env_a = signal.butter(2, 150 / nyquist, btype='low')
smoothed_sibilants = signal.filtfilt(env_b, env_a, sibilants)
# Mix processed sibilants back with original
return audio - smoothed_sibilants * params['reduction_factor']
def process_audio_files(input_files, output_dir, args):
"""Process audio files with the specified effects"""
processor = AudioProcessor(target_sr=args.sample_rate)
for input_file in input_files:
try:
input_path = Path(input_file)
output_path = Path(output_dir) / input_path.name
# Process with selected effects
success = processor.process_audio(
str(input_path),
str(output_path),
normalize_target=-float(args.normalize) if args.normalize else None,
dess_profile='high' if args.dess else None,
denoise=args.denoise,
compress_profile=args.compress if args.compress else None
)
if success:
print(f"Successfully processed: {input_path.name}")
else:
print(f"Failed to process: {input_path.name}")
except Exception as e:
print(f"Error processing {input_file}: {str(e)}")
@dataclass
class TrainingMetrics:
model_name: str
start_time: float
end_time: float = 0
total_audio_duration_minutes: float = 0 # in minutes
total_training_minutes: float = 0
num_samples: int = 0
num_batches: int = 0
num_epochs: int = 0
gradient_accumulation: int = 0
language: str = ""
sample_rate: int = 0
text_losses: List[float] = None
mel_losses: List[float] = None
def __post_init__(self):
self.text_losses = self.text_losses or []
self.mel_losses = self.mel_losses or []
def update_training_time(self):
"""Calculate training time in minutes"""
if self.end_time:
self.total_training_minutes = round((self.end_time - self.start_time) / 60, 2)
def parse_loss_values(self, log_text: str, loss_type: str) -> List[float]:
losses = []
lines = log_text.split('\n')
for line in lines:
if f"avg_loss_{loss_type}_ce:" in line:
log_position = log_text.find(line)
context_before = log_text[max(0, log_position-1000):log_position]
if '> EVALUATION' in context_before:
number_match = re.search(r'\x1b$$\d+m\s*([\d.]+)', line)
if not number_match:
number_match = re.search(r'ce:\s*([\d.]+)', line)
if number_match:
value = float(number_match.group(1))
losses.append(value)
return losses
def update_from_log(self, log_path: Path):
with open(log_path, 'r', encoding='utf-8') as f:
log_text = f.read()
self.text_losses = self.parse_loss_values(log_text, "text")
self.mel_losses = self.parse_loss_values(log_text, "mel")
def calculate_audio_stats(self, audio_segments: List[Dict]):
"""Calculate audio statistics from the training segments"""
self.num_samples = len(audio_segments)
self.num_batches = len(audio_segments) // 2 # assuming batch_size=2
total_seconds = sum(
AudioSegment.from_wav(seg['audio_file']).duration_seconds
for seg in audio_segments
)
self.total_audio_duration_minutes = round(total_seconds / 60, 2)
# def save(self, output_dir: Path):
# metrics_file = output_dir / "training_metrics.json"
# self.update_training_time() # Update training time before saving
# # Create a clean dict without internal tracking fields
# metrics_dict = {
# "model_name": self.model_name,
# "total_training_minutes": self.total_training_minutes,
# "total_audio_duration_minutes": self.total_audio_duration_minutes,
# "num_samples": self.num_samples,
# "num_batches": self.num_batches,
# "num_epochs": self.num_epochs,
# "gradient_accumulation": self.gradient_accumulation,
# "language": self.language,
# "sample_rate": self.sample_rate,
# "text_losses": self.text_losses,
# "mel_losses": self.mel_losses
# }
# with open(metrics_file, 'w', encoding='utf-8') as f:
# json.dump(metrics_dict, f, indent=2)
def parse_arguments():
parser = argparse.ArgumentParser(description="XTTS Model Training App")
parser.add_argument("--source-language", choices=["en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "ko", "hu"], required=True, help="Source language for XTTS")
parser.add_argument("--whisper-model", choices=["medium", "medium.en", "large-v2", "large-v3"], default="large-v3", help="Whisper model to use for transcription")
parser.add_argument("--enhance", action="store_true", help="Enable audio enhancement")
parser.add_argument("-i", "--input", required=True, help="Input folder or single file")
parser.add_argument("--session", help="Name for the session folder")
parser.add_argument("--separate", action="store_true", help="Enable speech separation")
parser.add_argument("--epochs", type=int, default=6, help="Number of training epochs")
parser.add_argument("--xtts-base-model", default="v2.0.2", help="XTTS base model version")
parser.add_argument("--batch", type=int, default=2, help="Batch size")
parser.add_argument("--gradient", type=int, default=1, help="Gradient accumulation levels")
parser.add_argument("--xtts-model-name", help="Name for the trained model")
parser.add_argument("--sample-method", choices=["maximise-punctuation", "punctuation-only", "mixed"], default="maximise-punctuation", help="Method for preparing training samples")
parser.add_argument("-conda_env", help="Name of the Conda environment to use")
parser.add_argument("-conda_path", help="Path to the Conda installation folder")
parser.add_argument("--sample-rate", type=int, choices=[22050, 44100], default=22050,
help="Sample rate for WAV files (default: 22050, recommended for XTTS training)")
parser.add_argument("--max-audio-time", type=float, default=11,
help="Maximum audio duration in seconds (default: 11.6)")
parser.add_argument("--max-text-length", type=int, default=200,
help="Maximum text length in characters (default: 200)")
parser.add_argument("--align-model",
help="""Model to use for phoneme-level alignment. Common options for English include:
- WAV2VEC2_ASR_LARGE_LV60K_960H (largest, most accurate)
- WAV2VEC2_ASR_BASE_960H (medium size)
- WAV2VEC2_ASR_BASE_100H (smallest, fastest)""")
parser.add_argument("--normalize", type=float, nargs='?', const=16.0,
help="Normalize audio to target LUFS (default: -16.0 if no value provided)")
parser.add_argument("--dess", action="store_true",
help="Apply de-essing to reduce sibilance")
parser.add_argument("--denoise", action="store_true",
help="Apply DeepFilterNet noise reduction")
parser.add_argument("--compress", choices=['male', 'female', 'neutral'],
help="Apply dynamic range compression with voice-specific profile")
parser.add_argument("--method-proportion", default="6_4",
help="For mixed method, proportion of maximise-punctuation to punctuation-only (e.g., '6_4' for 60-40 split)")
parser.add_argument("--training-proportion", default="8_2",
help="Proportion of training to validation data (e.g., '8_2' for 80-20 split)")
parser.add_argument("--negative-offset-last-word", type=int, default=50,
help="Subtract this many milliseconds from the end time of the last word in each segment (default: 50)")
parser.add_argument("--breath", action="store_true",
help="Apply breath removal preprocessing")
parser.add_argument("--trim", action="store_true",
help="Automatically trim trailing silence from segments while preserving word endings")
parser.add_argument("--fade-in", type=int, metavar="MS", default=30,
help="Apply fade-in effect for specified milliseconds from start (default: 30ms)")
parser.add_argument("--fade-out", type=int, metavar="MS", default=40,
help="Apply fade-out effect for specified milliseconds from end (default: 40ms)")
parser.add_argument("--discard-abrupt", action="store_true",
help="Detect and discard segments with abrupt endings")
args = parser.parse_args()
# Set default alignment models based on language if not specified by user
if not args.align_model:
language_align_models = {
"pl": "jonatasgrosman/wav2vec2-xls-r-1b-polish",
"nl": "FvH14/wav2vec2-XLSR-53-DutchCommonVoice12",
"de": "jonatasgrosman/wav2vec2-xls-r-1b-german",
"en": "jonatasgrosman/wav2vec2-xls-r-1b-english"
}
args.align_model = language_align_models.get(args.source_language)
# Validate and convert proportions
if args.method_proportion:
try:
max_prop, punct_prop = map(int, args.method_proportion.split('_'))
if max_prop + punct_prop != 10:
raise ValueError("Method proportions must sum to 10")
args.method_proportion = max_prop / 10
except (ValueError, AttributeError):
raise ValueError("Method proportion must be in format 'N_M' where N+M=10 (e.g., '6_4')")
if args.training_proportion:
try:
train_prop, val_prop = map(int, args.training_proportion.split('_'))
if train_prop + val_prop != 10:
raise ValueError("Training proportions must sum to 10")
args.training_proportion = train_prop / 10
except (ValueError, AttributeError):
raise ValueError("Training proportion must be in format 'N_M' where N+M=10 (e.g., '8_2')")
if args.negative_offset_last_word is None: