unknown commited on
Commit
34ccbcb
·
1 Parent(s): 549ee89

cache all error messages and add support to fix mac gpu issues

Browse files
Files changed (1) hide show
  1. finetune_gradio.py +71 -29
finetune_gradio.py CHANGED
@@ -9,19 +9,16 @@ from glob import glob
9
  import librosa
10
  import numpy as np
11
  from scipy.io import wavfile
12
- from tqdm import tqdm
13
  import shutil
14
  import time
15
 
16
  import json
17
- from datasets import Dataset
18
  from model.utils import convert_char_to_pinyin
19
  import signal
20
  import psutil
21
  import platform
22
  import subprocess
23
  from datasets.arrow_writer import ArrowWriter
24
- from datasets import load_dataset, load_from_disk
25
 
26
  import json
27
 
@@ -265,8 +262,20 @@ def start_training(dataset_name="",
265
  finetune=True,
266
  ):
267
 
 
268
  global training_process
269
 
 
 
 
 
 
 
 
 
 
 
 
270
  # Check if a training process is already running
271
  if training_process is not None:
272
  return "Train run already!",gr.update(interactive=False),gr.update(interactive=True)
@@ -346,6 +355,8 @@ def transcribe_all(name_project,audio_files,language,user=False,progress=gr.Prog
346
  path_project_wavs = os.path.join(path_project,"wavs")
347
  file_metadata = os.path.join(path_project,"metadata.csv")
348
 
 
 
349
  if os.path.isdir(path_project_wavs):
350
  shutil.rmtree(path_project_wavs)
351
 
@@ -356,16 +367,17 @@ def transcribe_all(name_project,audio_files,language,user=False,progress=gr.Prog
356
 
357
  if user:
358
  file_audios = [file for format in ('*.wav', '*.ogg', '*.opus', '*.mp3', '*.flac') for file in glob(os.path.join(path_dataset, format))]
 
359
  else:
360
  file_audios = audio_files
361
-
362
- print([file_audios])
363
 
364
  alpha = 0.5
365
  _max = 1.0
366
  slicer = Slicer(24000)
367
 
368
  num = 0
 
369
  data=""
370
  for file_audio in progress.tqdm(file_audios, desc="transcribe files",total=len((file_audios))):
371
 
@@ -381,18 +393,26 @@ def transcribe_all(name_project,audio_files,language,user=False,progress=gr.Prog
381
  if(tmp_max>1):chunk/=tmp_max
382
  chunk = (chunk / tmp_max * (_max * alpha)) + (1 - alpha) * chunk
383
  wavfile.write(file_segment,24000, (chunk * 32767).astype(np.int16))
 
 
 
 
384
 
385
- text=transcribe(file_segment,language)
386
- text = text.lower().strip().replace('"',"")
387
 
388
- data+= f"{name_segment}|{text}\n"
 
 
389
 
390
- num+=1
391
-
392
  with open(file_metadata,"w",encoding="utf-8") as f:
393
  f.write(data)
394
-
395
- return f"transcribe complete samples : {num} in path {path_project_wavs}"
 
 
 
 
 
396
 
397
  def format_seconds_to_hms(seconds):
398
  hours = int(seconds / 3600)
@@ -408,6 +428,8 @@ def create_metadata(name_project,progress=gr.Progress()):
408
  file_raw = os.path.join(path_project,"raw.arrow")
409
  file_duration = os.path.join(path_project,"duration.json")
410
  file_vocab = os.path.join(path_project,"vocab.txt")
 
 
411
 
412
  with open(file_metadata,"r",encoding="utf-8") as f:
413
  data=f.read()
@@ -419,11 +441,18 @@ def create_metadata(name_project,progress=gr.Progress()):
419
  count=data.split("\n")
420
  lenght=0
421
  result=[]
 
422
  for line in progress.tqdm(data.split("\n"),total=count):
423
  sp_line=line.split("|")
424
  if len(sp_line)!=2:continue
425
- name_audio,text = sp_line[:2]
 
426
  file_audio = os.path.join(path_project_wavs, name_audio + ".wav")
 
 
 
 
 
427
  duraction = get_audio_duration(file_audio)
428
  if duraction<2 and duraction>15:continue
429
  if len(text)<4:continue
@@ -439,6 +468,10 @@ def create_metadata(name_project,progress=gr.Progress()):
439
 
440
  lenght+=duraction
441
 
 
 
 
 
442
  min_second = round(min(duration_list),2)
443
  max_second = round(max(duration_list),2)
444
 
@@ -450,9 +483,15 @@ def create_metadata(name_project,progress=gr.Progress()):
450
  json.dump({"duration": duration_list}, f, ensure_ascii=False)
451
 
452
  file_vocab_finetune = "data/Emilia_ZH_EN_pinyin/vocab.txt"
 
453
  shutil.copy2(file_vocab_finetune, file_vocab)
454
-
455
- return f"prepare complete \nsamples : {len(text_list)}\ntime data : {format_seconds_to_hms(lenght)}\nmin sec : {min_second}\nmax sec : {max_second}\nfile_arrow : {file_raw}\n"
 
 
 
 
 
456
 
457
  def check_user(value):
458
  return gr.update(visible=not value),gr.update(visible=value)
@@ -468,13 +507,16 @@ def calculate_train(name_project,batch_size_type,max_samples,learning_rate,num_w
468
  duration_list = data['duration']
469
  samples = len(duration_list)
470
 
471
- gpu_properties = torch.cuda.get_device_properties(0)
472
- total_memory = gpu_properties.total_memory / (1024 ** 3)
 
 
 
473
 
474
  if batch_size_type=="frame":
475
  batch = int(total_memory * 0.5)
476
  batch = (lambda num: num + 1 if num % 2 != 0 else num)(batch)
477
- batch_size_per_gpu = int(36800 / batch )
478
  else:
479
  batch_size_per_gpu = int(total_memory / 8)
480
  batch_size_per_gpu = (lambda num: num + 1 if num % 2 != 0 else num)(batch_size_per_gpu)
@@ -509,13 +551,12 @@ def extract_and_save_ema_model(checkpoint_path: str, new_checkpoint_path: str) -
509
  if ema_model_state_dict is not None:
510
  new_checkpoint = {'ema_model_state_dict': ema_model_state_dict}
511
  torch.save(new_checkpoint, new_checkpoint_path)
512
- print(f"New checkpoint saved at: {new_checkpoint_path}")
513
  else:
514
- print("No 'ema_model_state_dict' found in the checkpoint.")
515
 
516
  except Exception as e:
517
- print(f"An error occurred: {e}")
518
-
519
 
520
  def vocab_check(project_name):
521
  name_project = project_name + "_pinyin"
@@ -524,12 +565,17 @@ def vocab_check(project_name):
524
  file_metadata = os.path.join(path_project, "metadata.csv")
525
 
526
  file_vocab="data/Emilia_ZH_EN_pinyin/vocab.txt"
 
 
527
 
528
  with open(file_vocab,"r",encoding="utf-8") as f:
529
  data=f.read()
530
 
531
  vocab = data.split("\n")
532
 
 
 
 
533
  with open(file_metadata,"r",encoding="utf-8") as f:
534
  data=f.read()
535
 
@@ -548,6 +594,7 @@ def vocab_check(project_name):
548
 
549
  if miss_symbols==[]:info ="You can train using your language !"
550
  else:info = f"The following symbols are missing in your language : {len(miss_symbols)}\n\n" + "\n".join(miss_symbols)
 
551
  return info
552
 
553
 
@@ -652,8 +699,9 @@ with gr.Blocks() as app:
652
  with gr.TabItem("reduse checkpoint"):
653
  txt_path_checkpoint = gr.Text(label="path checkpoint :")
654
  txt_path_checkpoint_small = gr.Text(label="path output :")
 
655
  reduse_button = gr.Button("reduse")
656
- reduse_button.click(fn=extract_and_save_ema_model,inputs=[txt_path_checkpoint,txt_path_checkpoint_small])
657
 
658
  with gr.TabItem("vocab check experiment"):
659
  check_button = gr.Button("check vocab")
@@ -680,10 +728,4 @@ def main(port, host, share, api):
680
  )
681
 
682
  if __name__ == "__main__":
683
- name="my_speak"
684
-
685
- #create_data_project(name)
686
- #transcribe_all(name)
687
- #create_metadata(name)
688
-
689
  main()
 
9
  import librosa
10
  import numpy as np
11
  from scipy.io import wavfile
 
12
  import shutil
13
  import time
14
 
15
  import json
 
16
  from model.utils import convert_char_to_pinyin
17
  import signal
18
  import psutil
19
  import platform
20
  import subprocess
21
  from datasets.arrow_writer import ArrowWriter
 
22
 
23
  import json
24
 
 
262
  finetune=True,
263
  ):
264
 
265
+
266
  global training_process
267
 
268
+ path_project = os.path.join(path_data, dataset_name + "_pinyin")
269
+
270
+ if os.path.isdir(path_project)==False:
271
+ yield f"There is not project with name {dataset_name}",gr.update(interactive=True),gr.update(interactive=False)
272
+ return
273
+
274
+ file_raw = os.path.join(path_project,"raw.arrow")
275
+ if os.path.isfile(file_raw)==False:
276
+ yield f"There is no file {file_raw}",gr.update(interactive=True),gr.update(interactive=False)
277
+ return
278
+
279
  # Check if a training process is already running
280
  if training_process is not None:
281
  return "Train run already!",gr.update(interactive=False),gr.update(interactive=True)
 
355
  path_project_wavs = os.path.join(path_project,"wavs")
356
  file_metadata = os.path.join(path_project,"metadata.csv")
357
 
358
+ if audio_files is None:return "You need to load an audio file."
359
+
360
  if os.path.isdir(path_project_wavs):
361
  shutil.rmtree(path_project_wavs)
362
 
 
367
 
368
  if user:
369
  file_audios = [file for format in ('*.wav', '*.ogg', '*.opus', '*.mp3', '*.flac') for file in glob(os.path.join(path_dataset, format))]
370
+ if file_audios==[]:return "No audio file was found in the dataset."
371
  else:
372
  file_audios = audio_files
373
+
 
374
 
375
  alpha = 0.5
376
  _max = 1.0
377
  slicer = Slicer(24000)
378
 
379
  num = 0
380
+ error_num = 0
381
  data=""
382
  for file_audio in progress.tqdm(file_audios, desc="transcribe files",total=len((file_audios))):
383
 
 
393
  if(tmp_max>1):chunk/=tmp_max
394
  chunk = (chunk / tmp_max * (_max * alpha)) + (1 - alpha) * chunk
395
  wavfile.write(file_segment,24000, (chunk * 32767).astype(np.int16))
396
+
397
+ try:
398
+ text=transcribe(file_segment,language)
399
+ text = text.lower().strip().replace('"',"")
400
 
401
+ data+= f"{name_segment}|{text}\n"
 
402
 
403
+ num+=1
404
+ except:
405
+ error_num +=1
406
 
 
 
407
  with open(file_metadata,"w",encoding="utf-8") as f:
408
  f.write(data)
409
+
410
+ if error_num!=[]:
411
+ error_text=f"\nerror files : {error_num}"
412
+ else:
413
+ error_text=""
414
+
415
+ return f"transcribe complete samples : {num}\npath : {path_project_wavs}{error_text}"
416
 
417
  def format_seconds_to_hms(seconds):
418
  hours = int(seconds / 3600)
 
428
  file_raw = os.path.join(path_project,"raw.arrow")
429
  file_duration = os.path.join(path_project,"duration.json")
430
  file_vocab = os.path.join(path_project,"vocab.txt")
431
+
432
+ if os.path.isfile(file_metadata)==False: return "The file was not found in " + file_metadata
433
 
434
  with open(file_metadata,"r",encoding="utf-8") as f:
435
  data=f.read()
 
441
  count=data.split("\n")
442
  lenght=0
443
  result=[]
444
+ error_files=[]
445
  for line in progress.tqdm(data.split("\n"),total=count):
446
  sp_line=line.split("|")
447
  if len(sp_line)!=2:continue
448
+ name_audio,text = sp_line[:2]
449
+
450
  file_audio = os.path.join(path_project_wavs, name_audio + ".wav")
451
+
452
+ if os.path.isfile(file_audio)==False:
453
+ error_files.append(file_audio)
454
+ continue
455
+
456
  duraction = get_audio_duration(file_audio)
457
  if duraction<2 and duraction>15:continue
458
  if len(text)<4:continue
 
468
 
469
  lenght+=duraction
470
 
471
+ if duration_list==[]:
472
+ error_files_text="\n".join(error_files)
473
+ return f"Error: No audio files found in the specified path : \n{error_files_text}"
474
+
475
  min_second = round(min(duration_list),2)
476
  max_second = round(max(duration_list),2)
477
 
 
483
  json.dump({"duration": duration_list}, f, ensure_ascii=False)
484
 
485
  file_vocab_finetune = "data/Emilia_ZH_EN_pinyin/vocab.txt"
486
+ if os.path.isfile(file_vocab_finetune==False):return "Error: Vocabulary file 'Emilia_ZH_EN_pinyin' not found!"
487
  shutil.copy2(file_vocab_finetune, file_vocab)
488
+
489
+ if error_files!=[]:
490
+ error_text="error files\n" + "\n".join(error_files)
491
+ else:
492
+ error_text=""
493
+
494
+ return f"prepare complete \nsamples : {len(text_list)}\ntime data : {format_seconds_to_hms(lenght)}\nmin sec : {min_second}\nmax sec : {max_second}\nfile_arrow : {file_raw}\n{error_text}"
495
 
496
  def check_user(value):
497
  return gr.update(visible=not value),gr.update(visible=value)
 
507
  duration_list = data['duration']
508
  samples = len(duration_list)
509
 
510
+ if torch.cuda.is_available():
511
+ gpu_properties = torch.cuda.get_device_properties(0)
512
+ total_memory = gpu_properties.total_memory / (1024 ** 3)
513
+ elif torch.backends.mps.is_available():
514
+ total_memory = psutil.virtual_memory().available / (1024 ** 3)
515
 
516
  if batch_size_type=="frame":
517
  batch = int(total_memory * 0.5)
518
  batch = (lambda num: num + 1 if num % 2 != 0 else num)(batch)
519
+ batch_size_per_gpu = int(38400 / batch )
520
  else:
521
  batch_size_per_gpu = int(total_memory / 8)
522
  batch_size_per_gpu = (lambda num: num + 1 if num % 2 != 0 else num)(batch_size_per_gpu)
 
551
  if ema_model_state_dict is not None:
552
  new_checkpoint = {'ema_model_state_dict': ema_model_state_dict}
553
  torch.save(new_checkpoint, new_checkpoint_path)
554
+ return f"New checkpoint saved at: {new_checkpoint_path}"
555
  else:
556
+ return "No 'ema_model_state_dict' found in the checkpoint."
557
 
558
  except Exception as e:
559
+ return f"An error occurred: {e}"
 
560
 
561
  def vocab_check(project_name):
562
  name_project = project_name + "_pinyin"
 
565
  file_metadata = os.path.join(path_project, "metadata.csv")
566
 
567
  file_vocab="data/Emilia_ZH_EN_pinyin/vocab.txt"
568
+ if os.path.isfile(file_vocab)==False:
569
+ return f"the file {file_vocab} not found !"
570
 
571
  with open(file_vocab,"r",encoding="utf-8") as f:
572
  data=f.read()
573
 
574
  vocab = data.split("\n")
575
 
576
+ if os.path.isfile(file_metadata)==False:
577
+ return f"the file {file_metadata} not found !"
578
+
579
  with open(file_metadata,"r",encoding="utf-8") as f:
580
  data=f.read()
581
 
 
594
 
595
  if miss_symbols==[]:info ="You can train using your language !"
596
  else:info = f"The following symbols are missing in your language : {len(miss_symbols)}\n\n" + "\n".join(miss_symbols)
597
+
598
  return info
599
 
600
 
 
699
  with gr.TabItem("reduse checkpoint"):
700
  txt_path_checkpoint = gr.Text(label="path checkpoint :")
701
  txt_path_checkpoint_small = gr.Text(label="path output :")
702
+ txt_info_reduse = gr.Text(label="info",value="")
703
  reduse_button = gr.Button("reduse")
704
+ reduse_button.click(fn=extract_and_save_ema_model,inputs=[txt_path_checkpoint,txt_path_checkpoint_small],outputs=[txt_info_reduse])
705
 
706
  with gr.TabItem("vocab check experiment"):
707
  check_button = gr.Button("check vocab")
 
728
  )
729
 
730
  if __name__ == "__main__":
 
 
 
 
 
 
731
  main()