File size: 38,571 Bytes
7b4057d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# Refer codes: https://github.com/nguyenvulebinh/lyric-alignment/blob/main/data_preparation/README.md
# !pip install -q pydub
###########################################################################def

import os
import glob
import re
import random
import string

import json
from tqdm.contrib.concurrent import process_map  # or thread_map

from pydub import AudioSegment
from pydub.effects import strip_silence

import IPython.display as ipd
from IPython.display import Audio

import subprocess
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import Pool
from tqdm import tqdm

import IPython.display as ipd
from IPython.display import Audio

import soundfile as sf
import librosa

###########################################################################def
def pydub_play(sound_file,start_time,end_time):
  """

  start_time, end_time = ms

  pydub_play('/content/songs/Anh_Cho_Em_Mùa_Xuân_ZZEB7E0F.mp3',37390,39250)



  """
  #from pydub import AudioSegment
  #import IPython.display as ipd
  #from IPython.display import Audio

  ext = sound_file[-3:]
  audio_file = AudioSegment.from_file(sound_file, format=ext)
  audio = audio_file[start_time:end_time]
  audio.export(f'demo.{ext}',format=ext)
  ipd.display(ipd.Audio(f'demo.{ext}'))


def torch_play(sound_file,start_time,end_time):
  """

  start_time, end_time = ms

  torch_play('/content/songs/Anh_Cho_Em_Mùa_Xuân_ZZEB7E0F.mp3',37390,39250)



  """
  import torchaudio
  import IPython.display as ipd
  from IPython.display import Audio

  waveform, sample_rate = torchaudio.load(sound_file)

  start_sample = int(start_time / 1000 * sample_rate)
  end_sample = int(end_time / 1000 * sample_rate)
  audio_to_play = waveform[:, start_sample:end_sample]
  torchaudio.save('output.wav', audio_to_play, sample_rate)
  ipd.display(Audio('output.wav'))



###########################################################################def

def file_wav_16k(args):
    """

    use for MFA alignment



    """
    
    input_sound, out_dir = args

    os.makedirs(out_dir, exist_ok=True)
    name = os.path.basename(input_sound)
    name = os.path.splitext(name)[0]
    output_sound= f'{out_dir}/{name}.wav'

    command = [
        "ffmpeg",
        "-y", "-i", input_sound,
        "-ar", "16000",  # Set sample rate to 16000 Hz
        "-ac", "1",      # Set number of channels to 2 (stereo)
        "-acodec", "pcm_s16le",  # Use WAV encoder
        output_sound
    ]

    try:
        subprocess.run(command, check=True,stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError as error:
        print(f"Conversion failed: {error}")



def folder_to_wav_16k(in_dir, out_dir):
    """ """
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')

    with Pool() as pool:
        with tqdm(total=len(files), desc="Converting MP3 to WAV") as pbar:
            for _ in pool.imap_unordered(file_wav_16k, zip(files, [out_dir] * len(files))):  # Pass arguments as tuples
                pbar.update()

###########################################################################def


def check_file(filepath):
    """

    Hàm kiểm tra file âm thanh, nếu không hợp lệ thì xóa file đó.

    """
    try:
        # Đọc dữ liệu âm thanh với soundfile (sf)
        data, sample_rate = sf.read(filepath)
        return True  # Nếu file hợp lệ
    except Exception as e:
        # Nếu có lỗi, xóa file và thông báo lỗi
        os.remove(filepath)
        print(f"Removed {filepath} due to error: {e}")
        return False

def remove_invalid_sound(in_dir):
    """

    Hàm quét các file âm thanh trong thư mục, kiểm tra và xóa những file không hợp lệ.

    """
    # Lấy danh sách các file âm thanh trong thư mục
    files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')

    print('Start multiprocessing')

    # Sử dụng multiprocessing Pool để xử lý nhiều file cùng lúc
    with Pool() as pool:
        results = []
        for file in files:
            # Đảm bảo args là một tuple (file,)
            result = pool.apply_async(check_file, args=(file,))
            results.append(result)

        pool.close()

        # Sử dụng tqdm để hiển thị thanh tiến độ
        for _ in tqdm(results, desc="Processing files"):
            _.get()

        pool.join()
        
        

def remove_bad_sound(x_files):
  """

  remove invalid/bad sound files in list x_files

  x_files = get_audio_files('/content/raw_data')

  remove_bad_sound(x_files)

  

  """
  #import os

  for filepath in tqdm(x_files):
    if not is_valid_sound(filepath):
      os.remove(filepath)
      print(f"\tDeleted invalid sound file: {filepath}")

###########################################################################def
def name_no_ext(folder,ext='txt'):
  """ """
  import os
  x_name = []
  files = os.listdir(folder)
  for file in files:
    if file.endswith(f'.{ext}'):
      name = os.path.splitext(file)[0]
      x_name.append(name)  
  return x_name


def the_same_name(dir_1,dir_2,ext1,ext2):
  """

  the_same_name(dir_1,dir_2,'TextGrid','mp3')



  """
  x1_name = name_no_ext(dir_1,ext1)
  x2_name = name_no_ext(dir_2,ext2)
  common = set(x1_name) & set(x2_name)
  return list(common)



def get_pair_files(dir_1,dir_2,ext1,ext2):
  """

  get_pair_files(dir_1,dir_2,'TextGrid','mp3')



  """
  x1_name = name_no_ext(dir_1,ext1)
  x2_name = name_no_ext(dir_2,ext2)
  common = set(x1_name) & set(x2_name)
  return list(common)



def remove_unpaired_files(folder_path,ext1,ext2):
  """

  remove_unpaired_files('/content/songs','mp3','lrc')



  """  
  x_common = the_same_name(folder_path,folder_path,ext1,ext2)
  
  files = glob.glob(f'{folder_path}/*')
  len(files)
  for file in files:
    name = os.path.basename(file)
    name = os.path.splitext(name)[0]
    if name not in x_common:
      print(file)
      os.system(f'rm -f "{file}"')
      
###########################################################################def

time_lyric_regex = r"[\[|<](\d\d):(\d\d.\d\d)[\]|>](.*)"
time_regex = r"[\[|<](\d\d):(\d\d.\d\d)[\]|>]"

def ignore_line(text):
    text_lower = text.lower().replace(' ', '').strip(' -.?!,)("\'…“”*_[]')
    if text_lower.startswith('bàihát:') or text_lower.startswith('casĩ:') or text_lower.startswith('cakhúc:') or text_lower.startswith('sángtác:') or text_lower.startswith('trìnhbày:') or text_lower.startswith('lyricby:') or text_lower.startswith('đk') :
        return True
    if len(text.strip(' -.?!,)("\'…“”*_[]')) == 0:
        return True
    return False

def ignore_file(text):
    matches = list(re.finditer(time_regex, text, re.MULTILINE))
    if len(matches) > 0:
        return True
    

def handle_lrc(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.read().strip().split('\n')
    
    timestamp = []
    text = []
    
    label = []
    try:
        for line in lines:
            matches = list(re.finditer(time_lyric_regex, line, re.MULTILINE))
            if len(matches) > 0:
                if ignore_file(matches[0].group(3)):
                    return
                if not ignore_line(matches[0].group(3)):
                    start_time = int(float(matches[0].group(1)) * 60 * 1000) + int(float(matches[0].group(2)) * 1000)
                    timestamp.append(start_time)
                    text.append(matches[0].group(3).strip())
                    
    except:
        print(file_path)
        return
    
    timestamp = timestamp[3:]
    text = text[3:]
    # print(len(text),len(timestamp))
    return text, timestamp  

###########################################################################def
def random_name(num_letters=5):
  """

  """
  #import random
  #import string

  random_letters = random.choices(string.ascii_lowercase, k=num_letters)
  random_string = ''.join(random_letters)

  random_number = random.randint(10000, 99999)
  out = f'{random_string}_{random_number}'
  return out

###########################################################################def
# 3 parameters
# args = sound_file,out_dir,num_seq   

def pydub_split(args):
  """

  start_time, end_time = ms

  args = sound_file,out_dir,num_seq   

  

  """
  import os
  from pydub import AudioSegment

  sound_file,out_dir,num_seq = args   # 3 parameters

  os.makedirs(out_dir, exist_ok=True)

  subtile_file = f'{sound_file[:-4]}.lrc'
  text, timestamp = handle_lrc(subtile_file)

  ext = sound_file[-3:]
  audio_file = AudioSegment.from_file(sound_file, format=ext)

  for k in range(len(text)):
    #print(k)
    if k+num_seq < len(text):
      sentence = " ".join(text[k:k+num_seq])
      dur = timestamp[k+num_seq] - timestamp[k]
      len_text = len(sentence.split())
      if dur < 20000:
        new_name = random_name(5)
        audio = audio_file[timestamp[k]:timestamp[k+num_seq]]
        audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
        with open(f'{out_dir}/{new_name}.lab','w') as f:
          f.write(sentence.lower())
      else:
        sentence = " ".join(text[k:k+num_seq-1])
        dur = timestamp[k+num_seq-1] - timestamp[k]
        if dur < 20000:
          new_name = random_name(5)
          audio = audio_file[timestamp[k]:timestamp[k+num_seq-1]]
          audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            f.write(sentence.lower())
    # the last
    elif k+num_seq == len(text):
      sentence = " ".join(text[k:k+num_seq])
      dur = timestamp[-1] - timestamp[k]
      len_text = len(sentence.split())
      if dur < 20000:
        new_name = random_name(5)
        audio = audio_file[timestamp[k]:timestamp[-1]]
        audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
        with open(f'{out_dir}/{new_name}.lab','w') as f:
          f.write(sentence.lower())


def _zing_split(in_dir, out_dir,num_seq=4):
    """ """
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3')

    with Pool() as pool:
        with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
            for _ in pool.imap_unordered(pydub_split, zip(files, [out_dir] * len(files), [num_seq] * len(files))):
                pbar.update()

###########################################################################def
def remove_bad_lrc(lrc_dir):
  """

  """
  import os
  import glob
  from tqdm import tqdm
  
  files = glob.glob(f'{lrc_dir}/*.lrc')
  print(f'num_files: {len(files)}')
  for file in tqdm(files):
    try:
      text, timestamp = handle_lrc(file)
    except Exception as e:
      print(f"Error in splitting files: {e}")
      os.remove(file)
      print(f'removed {file}')  

###########################################################################def
def _split_1(args):
  """

  start_time, end_time = ms

  slide window + overlay 

  

  """
  #import os
  #from pydub import AudioSegment

  sound_file,out_dir,num_seg = args   # 3 parameters

  #os.makedirs(out_dir, exist_ok=True)

  subtile_file = f'{sound_file[:-4]}.lrc'
  text, timestamp = handle_lrc(subtile_file)

  ext = sound_file[-3:]
  audio_file = AudioSegment.from_file(sound_file, format=ext)

  for k in range(len(text)):
    if k+num_seg < len(text):
      sentence = " ".join(text[k:k+num_seg])
      #print(sentence)
      dur = timestamp[k+num_seg] - timestamp[k]
      len_text = len(sentence.split())
      if dur < 30000:
        new_name = random_name(5)
        audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
        audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
        with open(f'{out_dir}/{new_name}.lab','w') as f:
          f.write(sentence.lower())
      else:
        sentence = " ".join(text[k:k+num_seg-1])
        #print(sentence)
        dur = timestamp[k+num_seg-1] - timestamp[k]
        if dur < 30000:
          new_name = random_name(5)
          audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
          audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            f.write(sentence.lower())
    # the last
    elif k+num_seg == len(text):
      sentence = " ".join(text[k:k+num_seg])
      #print(sentence)
      dur = timestamp[-1] - timestamp[k]
      len_text = len(sentence.split())
      if dur < 30000:
        new_name = random_name(5)
        audio = audio_file[timestamp[k]:timestamp[-1]]
        audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
        with open(f'{out_dir}/{new_name}.lab','w') as f:
          f.write(sentence.lower())


def _split_2(args):
  """

  start_time, end_time = ms

  slide window, no overlay

  

  """
  #import os
  #from pydub import AudioSegment

  sound_file,out_dir,num_seg = args   # 3 parameters

  #os.makedirs(out_dir, exist_ok=True)

  subtile_file = f'{sound_file[:-4]}.lrc'
  text, timestamp = handle_lrc(subtile_file)

  ext = sound_file[-3:]
  audio_file = AudioSegment.from_file(sound_file, format=ext)

  for k in range(0,len(text),num_seg):
    #print(k)
    if k + num_seg < len(text):
      sentence = " ".join(text[k:k+num_seg])
      #print(sentence)
      dur = timestamp[k+num_seg] - timestamp[k]
      len_text = len(sentence.split())
      if dur < 30000:
        new_name = random_name(5)
        audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
        audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
        with open(f'{out_dir}/{new_name}.lab','w') as f:
          f.write(sentence.lower())
      else:
        sentence = " ".join(text[k:k+num_seg-1])
        #print(sentence)
        dur = timestamp[k+num_seg-1] - timestamp[k]
        if dur < 30000:
          new_name = random_name(5)
          audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
          audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            f.write(sentence.lower())
    else: # the last
      sentence = " ".join(text[k:])
      #print(sentence)
      dur = timestamp[-1] - timestamp[k]
      len_text = len(sentence.split())
      if dur < 30000:
        new_name = random_name(5)
        audio = audio_file[timestamp[k]:timestamp[-1]]
        audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
        with open(f'{out_dir}/{new_name}.lab','w') as f:
          f.write(sentence.lower())



def _zing_split(in_dir, out_dir,num_seg=4,overlay='yes'):
    """ """
    import os
    import glob
    
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3')

    with Pool() as pool:
        with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
            if overlay.lower() == 'yes':
              for _ in pool.imap_unordered(split_1, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
                  pbar.update()
            else:
              for _ in pool.imap_unordered(split_2, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
                  pbar.update()


def _zing_split(in_dir, out_dir,num_seg=4,overlay='yes'):
    """ """
    import os
    import glob
    
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3')

    with Pool() as pool:
        with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
            try:
              if overlay.lower() == 'yes':
                for _ in pool.imap_unordered(split_1, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
                    pbar.update()
              else:
                for _ in pool.imap_unordered(split_2, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
                    pbar.update()
            except:
              pass
###########################################################################def

def check_and_remove_empty_folder(folder_path):
    """

    """
    if os.path.exists(folder_path):
        if not os.listdir(folder_path):
            os.rmdir(folder_path)
            print(f"Removed empty directory: {folder_path}")


def split_one(sound_file,out_dir,num_seg):
  """

  This use for manual transcription checking, augmentation  

  

  """
  import os

  song_name = random_name(5)
  out_dir = f'{out_dir}/{song_name}'
  os.makedirs(out_dir, exist_ok=True)   

  try:
    subtile_file = f'{sound_file[:-4]}.lrc'
    text, timestamp = handle_lrc(subtile_file)

    ext = sound_file[-3:]
    audio_file = AudioSegment.from_file(sound_file, format=ext)

    for k in range(len(text)):
      if k+num_seg < len(text):
        sentence = " ".join(text[k:k+num_seg])
        #print(sentence)
        dur = timestamp[k+num_seg] - timestamp[k]
        len_text = len(sentence.split())
        if dur < 30000:
          #print(k)
          new_name = f'{song_name}_{k:02d}'
          audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
          audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            #f.write(sentence.lower())
            f.write(sentence)
        else:
          sentence = " ".join(text[k:k+num_seg-1])
          #print(sentence)
          dur = timestamp[k+num_seg-1] - timestamp[k]
          if dur < 30000:
            #print(k)
            new_name = f'{song_name}_{k:02d}'
            audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
            audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
            with open(f'{out_dir}/{new_name}.lab','w') as f:
              #f.write(sentence.lower())
              f.write(sentence)
      # the last
      elif k+num_seg == len(text):
        sentence = " ".join(text[k:k+num_seg])
        #print(sentence)
        dur = timestamp[-1] - timestamp[k]
        len_text = len(sentence.split())
        if dur < 30000:
          #print(k)
          new_name = f'{song_name}_{k:02d}'
          audio = audio_file[timestamp[k]:timestamp[-1]]
          audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            #f.write(sentence.lower())
            f.write(sentence)

  except Exception as e:
    print(f"\nError processing {sound_file}: {e}")

  check_and_remove_empty_folder(out_dir)
  # Finished


def mp_split_one(in_dir,out_dir):
    """

    """
    import os
    import glob

    from tqdm import tqdm
    from multiprocessing import Pool
    
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')

    print('Start multiprocessing')
    
    with Pool() as pool:
        results = [pool.apply_async(split_one, args=(file, out_dir, 1)) for file in files]
    
        # Dùng tqdm để hiển thị tiến trình
        for result in tqdm(results, desc="Processing files"):
            result.get()  # Đảm bảo chờ quá trình hoàn thành


###########################################################################def
# Split sounds from Audacity transcription

def audacity_split_one(audio_file,out_dir):
    """

    """
    import os

    song_name = random_name(5)
    out_dir = f'{out_dir}/{song_name}'
    os.makedirs(out_dir, exist_ok=True)   

    # Đọc file âm thanh
    y, sr = librosa.load(audio_file, sr=None)

    # Đọc nội dung từ file text
    subtile_file = f'{audio_file[:-4]}.txt'
    with open(subtile_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # Lặp qua từng dòng trong file transcription để cắt và lưu file
    for i, line in enumerate(lines):
        parts = line.strip().split('\t')
        start_time = float(parts[0])
        end_time = float(parts[1])
        content = parts[2] if len(parts) > 2 else ""
        #print(content)

        start_sample = int(start_time * sr)
        end_sample = int(end_time * sr)

        # Cắt đoạn âm thanh
        segment = y[start_sample:end_sample]

        # Tạo tên file cho đoạn âm thanh
        segment_file = f'{out_dir}/{song_name}_{i+1:02d}.mp3'
        
        # Lưu đoạn âm thanh
        sf.write(segment_file, segment, sr)
        #print(f'Saved: {segment_file}')

        # Tạo file lab tương ứng
        with open(f'{out_dir}/{song_name}_{i+1:02d}.lab', 'w', encoding='utf-8') as lab_file:
            lab_file.write(content)
    print(f'\nSaved to {out_dir}')            



def mp_audacity(in_dir,out_dir):
    """

    """
    import os
    import glob

    from tqdm import tqdm
    from multiprocessing import Pool
    
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')

    print('Start multiprocessing')
    
    with Pool() as pool:
        results = [pool.apply_async(audacity_split_one, args=(file, out_dir)) for file in files]
    
        # Dùng tqdm để hiển thị tiến trình
        for result in tqdm(results, desc="Processing files"):
            result.get()  # Đảm bảo chờ quá trình hoàn thành



###########################################################################def

def split_1(sound_file,out_dir,num_seg):
  """

  start_time, end_time = ms

  slide window + overlay 

  

  """
  try:
    subtile_file = f'{sound_file[:-4]}.lrc'
    text, timestamp = handle_lrc(subtile_file)

    ext = sound_file[-3:]
    audio_file = AudioSegment.from_file(sound_file, format=ext)

    for k in range(len(text)):
      if k+num_seg < len(text):
        sentence = " ".join(text[k:k+num_seg])
        #print(sentence)
        dur = timestamp[k+num_seg] - timestamp[k]
        len_text = len(sentence.split())
        if dur < 30000:
          new_name = random_name(5)
          audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
          audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            #f.write(sentence.lower())
            f.write(sentence)
        else:
          sentence = " ".join(text[k:k+num_seg-1])
          #print(sentence)
          dur = timestamp[k+num_seg-1] - timestamp[k]
          if dur < 30000:
            new_name = random_name(5)
            audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
            audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
            with open(f'{out_dir}/{new_name}.lab','w') as f:
              #f.write(sentence.lower())
              f.write(sentence)
      # the last
      elif k+num_seg == len(text):
        sentence = " ".join(text[k:k+num_seg])
        #print(sentence)
        dur = timestamp[-1] - timestamp[k]
        len_text = len(sentence.split())
        if dur < 30000:
          new_name = random_name(5)
          audio = audio_file[timestamp[k]:timestamp[-1]]
          audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            #f.write(sentence.lower())
            f.write(sentence)

  except Exception as e:
    print(f"\nError processing {sound_file}: {e}")



def split_2(sound_file,out_dir,num_seg):
  """

  start_time, end_time = ms

  slide window, no overlay

  

  """

  try:
    subtile_file = f'{sound_file[:-4]}.lrc'
    text, timestamp = handle_lrc(subtile_file)

    ext = sound_file[-3:]
    audio_file = AudioSegment.from_file(sound_file, format=ext)

    for k in range(0,len(text),num_seg):
      #print(k)
      if k + num_seg < len(text):
        sentence = " ".join(text[k:k+num_seg])
        #print(sentence)
        dur = timestamp[k+num_seg] - timestamp[k]
        len_text = len(sentence.split())
        if dur < 30000:
          new_name = random_name(5)
          audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
          audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            #f.write(sentence.lower())
            f.write(sentence)
        else:
          sentence = " ".join(text[k:k+num_seg-1])
          #print(sentence)
          dur = timestamp[k+num_seg-1] - timestamp[k]
          if dur < 30000:
            new_name = random_name(5)
            audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
            audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
            with open(f'{out_dir}/{new_name}.lab','w') as f:
              #f.write(sentence.lower())
              f.write(sentence)
      else: # the last
        sentence = " ".join(text[k:])
        #print(sentence)
        dur = timestamp[-1] - timestamp[k]
        len_text = len(sentence.split())
        if dur < 30000:
          new_name = random_name(5)
          audio = audio_file[timestamp[k]:timestamp[-1]]
          audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
          with open(f'{out_dir}/{new_name}.lab','w') as f:
            #f.write(sentence.lower())
            f.write(sentence)

  except Exception as e:
    print(f"\nError processing {sound_file}: {e}")



def zing_split(in_dir, out_dir, num_seg=4, overlay='yes'):
    """Split audio files into multiple segments using multiprocessing."""
    import os
    import glob

    from tqdm import tqdm
    from multiprocessing import Pool


    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3')

    print('Multiprocessing...')
    with Pool() as pool:
        results = []
        for file in files:
            if overlay.lower() == 'yes':
                result = pool.apply_async(split_1, args=(file, out_dir, num_seg))
            else:
                result = pool.apply_async(split_2, args=(file, out_dir, num_seg))
            results.append(result)

        pool.close()

        # Use tqdm to display the progress bar
        for _ in tqdm(results, desc="Processing files"):
            _.get()

        pool.join()


###########################################################################def

def trim_head_tail(sound,head_threshold=-30, tail_threshold=-40, chunk_size=10):
  """

  sound = AudioSegment.from_file(wav_in)



  """
  #from pydub import AudioSegment
  
  forward = sound
  reverse = sound.reverse()
  dur1 = 0 # ms
  dur2 = 0 # ms
  sound_len = len(sound)

  assert chunk_size > 0 # to avoid infinite loop
  while forward[dur1:dur1+chunk_size].dBFS < head_threshold and dur1 < len(forward):
      dur1 += chunk_size
      forward = sound[dur1:]

  while reverse[dur2:dur2+chunk_size].dBFS < tail_threshold and dur2 < len(reverse):
      dur2 += chunk_size
      reverse = sound[dur2:]
  
  #print(dur1,dur2)
  sound = sound[dur1:sound_len-dur2]
  #print(f"trim: heading={dur1}ms, tail={dur2}ms")
  return sound

def trim_middle(sound,silence_len=250, silence_thresh=-35, padding=100):
  """

  sound = AudioSegment.from_file(sound_file)

  if found silence_len(ms) < silence_thresh(dB) will be replace with padding(ms)

  """  
  #from pydub.effects import strip_silence
  #before_len = len(sound)
  trimed_sound = strip_silence(sound, silence_len=silence_len, silence_thresh=silence_thresh, padding=padding)
  #after_len = len(trimed_sound)
  #print(f'trimed: {before_len - after_len}ms')
  return trimed_sound


def _del_silence_file(args):
  """ """
  sound_file, out_folder = args

  try:
    sound = AudioSegment.from_file(sound_file)
    trim1 = trim_middle(sound, silence_len=150, silence_thresh=-35, padding=5)
    trim2 = trim_head_tail(trim1, head_threshold=-30, tail_threshold=-50, chunk_size=10)
    trim2.export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:],bitrate='256k')
  except Exception as e:
    #print(f"Error processing {sound_file}: {e}")
    pass


def del_silence_file(sound_file, out_folder):
  """ """
  #sound_file, out_folder = args

  try:
    sound = AudioSegment.from_file(sound_file)
    trim1 = trim_middle(sound, silence_len=200, silence_thresh=-35, padding=100)
    trim2 = trim_head_tail(trim1, head_threshold=-30, tail_threshold=-50, chunk_size=10)
    #trim2.export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:],bitrate='256k')
    trim2.set_channels(1).export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:], bitrate='256k')

  except Exception as e:
    #print(f"Error processing {sound_file}: {e}")
    pass



def _del_silence_folder(in_dir, out_dir):
    """ """
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3')

    with Pool() as pool:
        with tqdm(total=len(files), desc="Remove silence") as pbar:
            for _ in pool.imap_unordered(del_silence_file, zip(files, [out_dir] * len(files))):  # Pass arguments as tuples
                pbar.update()


def _del_silence_folder(in_dir, out_dir):
    """ """
    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
    
    for file in tqdm(files):
      del_silence_file(file, out_dir)



def del_silence_folder(in_dir,out_dir):
    """

    """
    import os
    import glob

    from tqdm import tqdm
    from multiprocessing import Pool


    os.makedirs(out_dir, exist_ok=True)
    files = glob.glob(f'{in_dir}/*.mp3')

    print('Multiprocessing...')
    with Pool() as pool:
        results = []
        for file in files:
            result = pool.apply_async(del_silence_file, args=(file, out_dir))
            results.append(result)

        pool.close()

        # Use tqdm to display the progress bar
        for _ in tqdm(results, desc="Processing files"):
            _.get()

        pool.join()

###########################################################################def

def play_pair(audio_file,lab_ext='lab'):
  """ """
  #import IPython.display as ipd
  #from IPython.display import Audio
  text = open(f'{audio_file[:-4]}.{lab_ext}').read()
  print(text)
  ipd.display(ipd.Audio(audio_file))


def play_random(sound_dir,num_sound=5):
  """

  play random sounds in folder

  

  """
  import glob
  import random

  files = glob.glob(f'{sound_dir}/*.mp3') + glob.glob(f'{sound_dir}/*.wav')
  print(f'Number of sound files: {len(files)}\n')
  k = random.randint(0,len(files)-num_sound)

  for file in files[k:k+num_sound]:
    print(file)
    play_pair(file)  





def test_subtitle(sound_file,num_seq=4):
  """

  files = glob.glob('/content/Hà_Trần_Vocals/*.mp3')

  files.sort()

  for file in files[:5]:

    print(file)

    test_subtitle(file,3)

  

  """
  import os
  import random
  from pydub import AudioSegment
 
  out_dir = "tmp_dir"
  os.makedirs(out_dir, exist_ok=True)
  os.system(f"rm -f {out_dir}/*")


  subtile_file = f'{sound_file[:-4]}.lrc'
  text, timestamp = handle_lrc(subtile_file)

  ext = sound_file[-3:]
  audio_file = AudioSegment.from_file(sound_file, format=ext)

  for k in range(5):
    #print(k)
    if k+num_seq < len(text):
      sentence = " ".join(text[k:k+num_seq])
      dur = timestamp[k+num_seq] - timestamp[k]
      len_text = len(sentence.split())
      if dur < 20000:
        new_name = random_name(5)
        audio = audio_file[timestamp[k]:timestamp[k+num_seq]]
        audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
        with open(f'{out_dir}/{new_name}.lab','w') as f:
          f.write(sentence.lower())

  files = glob.glob(f'{out_dir}/*.mp3')
  print(f'num_samples: {len(files)}')
  k = random.randint(0,2)
  play_pair(files[k])
  #for file in files[:1]:
  #  play_pair(file)


###########################################################################def
def _split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20):
  """

  in_dir = '/content/Thu_Phuong_clean'

  out_dir = '/content/Thu_Phuong_recheck'

  split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20)



  """
  import glob
  from tqdm import tqdm
  import shutil

  ext1 = pair_ext[0]  # mp3/wav
  ext2 = pair_ext[1]  # lab/txt

  files = glob.glob(f'{in_dir}/*.{ext1}')
  print(f'Number of files: {len(files)}')  
  
  for i in tqdm(range(len(files) // window)):
    move_files = files[i * window: (i + 1) * window]
    dir_name = f"{out_dir}/{i:04d}"
    os.makedirs(dir_name, exist_ok=True)    
    for file in move_files:
      shutil.copy(file,dir_name)
      shutil.copy(f'{file[:-4]}.{ext2}',dir_name)



def split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20):
  """

  in_dir = '/content/Thu_Phuong_clean'

  out_dir = '/content/Thu_Phuong_recheck'

  split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20)

  split_folder(in_dir,out_dir,pair_ext=['mp3','lab'],window=20)



  """
  import glob
  from tqdm import tqdm
  import shutil

  ext1 = pair_ext[0]  # mp3/wav
  ext2 = pair_ext[1]  # lab/txt

  pair_files = get_pair_files(in_dir,in_dir,ext1,ext2)
  for i in tqdm(range(len(pair_files) // window)):
    copy_files = pair_files[i * window: (i + 1) * window]
    
    dir_name = f"{out_dir}/{i:04d}"
    os.makedirs(dir_name, exist_ok=True)
    for name in copy_files:   
      file1 = f'{in_dir}/{name}.{ext1}'
      file2 = f'{in_dir}/{name}.{ext2}'
      shutil.copy(file1,dir_name)
      shutil.copy(file2,dir_name)      


def combine_pair(in_dir,out_dir):
  """

  copy all files in subfolders to a target folder

  make pair files (mp3+lab), remove unpaired files



  """
  import os
  import shutil
  from tqdm import tqdm

  os.makedirs(out_dir, exist_ok=True)    

  x_files = []
  for path, subdirs, files in os.walk(in_dir):
    for file in files:
      full_path = os.path.join(path, file)
      x_files.append(full_path)

  for file in tqdm(x_files):
    shutil.copy(file,out_dir)
  print(f"\nCopied {len(x_files)} files to {out_dir}")

  # make pair files
  remove_unpaired_files(f'{out_dir}','mp3','lab')
  files = glob.glob(f'{out_dir}/*.mp3')
  print('-'*100)
  print(f'Final number of MP3 files: {len(files)}')
  print('-'*100)



###########################################################################def
# Check and delete bad files with: play_wav, checkbox, text/lab

def show_audio(folder_path,start_id,end_id):
  """

  """
  import os
  import glob

  from IPython.display import Audio, display
  import ipywidgets as widgets

  files = [file for file in os.listdir(folder_path) if file.endswith('.mp3') or file.endswith('.wav')]
  files.sort()
  delete_checkboxes = [widgets.Checkbox(description=file, value=False) for file in files[start_id:end_id]]

  for checkbox, file in zip(delete_checkboxes, files[start_id:end_id]):
      name = os.path.splitext(file)[0]
      text = open(f'{folder_path}/{name}.lab').read()
      print('-'*100)
      print(text)
      display(checkbox, Audio(folder_path + '/' + file))

  return delete_checkboxes,files[start_id:end_id]


def remove_files(folder_path, delete_checkboxes, files):
  """

  """
  import os
  from tqdm import tqdm

  files_to_delete = [file for checkbox, file in zip(delete_checkboxes, files) if checkbox.value]
  for file in tqdm(files_to_delete):
    file_path = f'{folder_path}/' + file
    print(file_path)
    os.remove(file_path)

###########################################################################def

def get_audio_files(folder_path):
  """

  x_files = get_audio_files('/content/raw_data')

  

  """
  import os

  audio_files = []
  for root, _, files in os.walk(folder_path):
    for filename in files:
      if filename.endswith(".mp3") or filename.endswith(".wav"):
        filepath = os.path.join(root, filename)
        audio_files.append(filepath)
  return audio_files

def get_dur(sound_file):
  """ """
  x,sr = sf.read(sound_file)
  dur = x.size/sr # unit = senconds(s)
  return dur


def total_time(elapsed_time):
  """    

  total_dur = 0

  for file in tqdm(x_files):

  dur = get_dur(file)

  total_dur = total_dur + dur

  

  total_time(int(total_dur))

  > 15h:17m:50s

  

  """
  if elapsed_time < 60:
    print(f"\n{elapsed_time:02d}s")

  elif elapsed_time >=60 and elapsed_time < 3600:
    minutes, seconds = divmod(elapsed_time, 60)
    print(f"\n{minutes:02d}m:{seconds:02d}s")

  else:
    hours, remainder = divmod(elapsed_time, 3600)
    minutes, seconds = divmod(remainder, 60)
    print(f"\nTotal time: {hours}h:{minutes:02d}m:{seconds:02d}s")


def report_time(folder):
  """

  report_time('/content/Ha_Tran_clean_small_dirs/0000')

  > Total time: 2h:40m:33s

  

  """
  x_files = get_audio_files(folder)

  total_dur = 0
  for file in tqdm(x_files):
    dur = get_dur(file)
    total_dur = total_dur + dur
  
  total_time(int(total_dur))

###########################################################################def

def clean_lab(lab_dir,min_len=8,max_len=25):
  """

  """
  import glob
  from tqdm import tqdm
  import os

  count = 0
  files = glob.glob(f'{lab_dir}/*.lab')
  print(f'num_files: {len(files)}')
  for file in tqdm(files):
    words =open(file).read()
    words = words.split()
    if len(words) > max_len or len(words) < min_len:
      os.remove(file)
      count = count + 1
  print(f'\nDeleted {count} files')


###########################################################################def