prepare_data.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import logging
  2. import os
  3. import shutil
  4. from multiprocessing import Pool
  5. import numpy as np
  6. import torch.distributed as dist
  7. import torchaudio
  8. def filter_wav_text(data_dir, dataset):
  9. wav_file = os.path.join(data_dir, dataset, "wav.scp")
  10. text_file = os.path.join(data_dir, dataset, "text")
  11. with open(wav_file) as f_wav, open(text_file) as f_text:
  12. wav_lines = f_wav.readlines()
  13. text_lines = f_text.readlines()
  14. os.rename(wav_file, "{}.bak".format(wav_file))
  15. os.rename(text_file, "{}.bak".format(text_file))
  16. wav_dict = {}
  17. for line in wav_lines:
  18. parts = line.strip().split()
  19. if len(parts) < 2:
  20. continue
  21. wav_dict[parts[0]] = parts[1]
  22. text_dict = {}
  23. for line in text_lines:
  24. parts = line.strip().split()
  25. if len(parts) < 2:
  26. continue
  27. text_dict[parts[0]] = " ".join(parts[1:]).lower()
  28. filter_count = 0
  29. with open(wav_file, "w") as f_wav, open(text_file, "w") as f_text:
  30. for sample_name, wav_path in wav_dict.items():
  31. if sample_name in text_dict.keys():
  32. f_wav.write(sample_name + " " + wav_path + "\n")
  33. f_text.write(sample_name + " " + text_dict[sample_name] + "\n")
  34. else:
  35. filter_count += 1
  36. logging.info(
  37. "{}/{} samples in {} are filtered because of the mismatch between wav.scp and text".format(len(wav_lines),
  38. filter_count,
  39. dataset))
  40. def wav2num_frame(wav_path, frontend_conf):
  41. waveform, sampling_rate = torchaudio.load(wav_path)
  42. n_frames = (waveform.shape[1] * 1000.0) / (sampling_rate * frontend_conf["frame_shift"] * frontend_conf["lfr_n"])
  43. feature_dim = frontend_conf["n_mels"] * frontend_conf["lfr_m"]
  44. return n_frames, feature_dim
  45. def calc_shape_core(root_path, args, idx):
  46. wav_scp_file = os.path.join(root_path, "wav.scp.{}".format(idx))
  47. shape_file = os.path.join(root_path, "speech_shape.{}".format(idx))
  48. with open(wav_scp_file) as f:
  49. lines = f.readlines()
  50. frontend_conf = args.frontend_conf
  51. dataset_conf = args.dataset_conf
  52. speech_length_min = dataset_conf.speech_length_min if hasattr(dataset_conf, "speech_length_min") else -1
  53. speech_length_max = dataset_conf.speech_length_max if hasattr(dataset_conf, "speech_length_max") else -1
  54. with open(shape_file, "w") as f:
  55. for line in lines:
  56. sample_name, wav_path = line.strip().split()
  57. n_frames, feature_dim = wav2num_frame(wav_path, frontend_conf)
  58. write_flag = True
  59. if n_frames > 0 and speech_length_min > 0:
  60. write_flag = n_frames >= speech_length_min
  61. if n_frames > 0 and speech_length_max > 0:
  62. write_flag = n_frames <= speech_length_max
  63. if write_flag:
  64. f.write("{} {},{}\n".format(sample_name, str(int(np.ceil(n_frames))), str(int(feature_dim))))
  65. f.flush()
  66. def calc_shape(args, dataset, nj=32):
  67. shape_path = os.path.join(args.data_dir, dataset, "speech_shape")
  68. if os.path.exists(shape_path):
  69. logging.info('Shape file for small dataset already exists.')
  70. return
  71. split_shape_path = os.path.join(args.data_dir, dataset, "shape_files")
  72. if os.path.exists(split_shape_path):
  73. shutil.rmtree(split_shape_path)
  74. os.mkdir(split_shape_path)
  75. # split
  76. wav_scp_file = os.path.join(args.data_dir, dataset, "wav.scp")
  77. with open(wav_scp_file) as f:
  78. lines = f.readlines()
  79. num_lines = len(lines)
  80. num_job_lines = num_lines // nj
  81. start = 0
  82. for i in range(nj):
  83. end = start + num_job_lines
  84. file = os.path.join(shape_path, "wav.scp.{}".format(str(i + 1)))
  85. with open(file, "w") as f:
  86. if i == nj - 1:
  87. f.writelines(lines[start:])
  88. else:
  89. f.writelines(lines[start:end])
  90. start = end
  91. p = Pool(nj)
  92. for i in range(nj):
  93. p.apply_async(calc_shape_core, args=(split_shape_path, args, str(i + 1)))
  94. logging.info("Generating shape files, please wait a few minutes...")
  95. p.close()
  96. p.join()
  97. # combine
  98. with open(shape_path, "w") as f:
  99. for i in range(nj):
  100. job_file = os.path.join(split_shape_path, "speech_shape.{}".format(str(i + 1)))
  101. with open(job_file) as job_f:
  102. lines = job_f.readlines()
  103. f.writelines(lines)
  104. logging.info('Generating shape files done.')
  105. def generate_data_list(data_dir, dataset, nj=100):
  106. list_file = os.path.join(data_dir, dataset, "data.list")
  107. if os.path.exists(list_file):
  108. logging.info('Data list for large dataset already exists.')
  109. return
  110. split_path = os.path.join(data_dir, dataset, "split")
  111. if os.path.exists(split_path):
  112. shutil.rmtree(split_path)
  113. os.mkdir(split_path)
  114. with open(os.path.join(data_dir, dataset, "wav.scp")) as f_wav:
  115. wav_lines = f_wav.readlines()
  116. with open(os.path.join(data_dir, dataset, "text")) as f_text:
  117. text_lines = f_text.readlines()
  118. num_lines = len(wav_lines)
  119. num_job_lines = num_lines // nj
  120. start = 0
  121. for i in range(nj):
  122. end = start + num_job_lines
  123. split_path_nj = os.path.join(split_path, str(i + 1))
  124. os.mkdir(split_path_nj)
  125. wav_file = os.path.join(split_path_nj, "wav.scp")
  126. text_file = os.path.join(split_path_nj, "text")
  127. with open(wav_file, "w") as fw, open(text_file, "w") as ft:
  128. if i == nj - 1:
  129. fw.writelines(wav_lines[start:])
  130. ft.writelines(text_lines[start:])
  131. else:
  132. fw.writelines(wav_lines[start:end])
  133. ft.writelines(text_lines[start:end])
  134. start = end
  135. with open(list_file, "w") as f_data:
  136. for i in range(nj):
  137. wav_path = os.path.join(split_path, str(i + 1), "wav.scp")
  138. text_path = os.path.join(split_path, str(i + 1), "text")
  139. f_data.write(wav_path + " " + text_path + "\n")
  140. def prepare_data(args, distributed_option):
  141. if args.dataset_type == "small" and args.train_data_path_and_name_and_type is not None:
  142. return
  143. if args.dataset_type == "large" and args.train_data_file is not None:
  144. return
  145. distributed = distributed_option.distributed
  146. if not distributed or distributed_option.dist_rank == 0:
  147. filter_wav_text(args.data_dir, args.train_set)
  148. filter_wav_text(args.data_dir, args.dev_set)
  149. if args.dataset_type == "small" and args.train_shape_file is None:
  150. calc_shape(args, args.train_set)
  151. calc_shape(args, args.dev_set)
  152. if args.dataset_type == "large" and args.train_data_file is None:
  153. generate_data_list(args.data_dir, args.train_set)
  154. generate_data_list(args.data_dir, args.dev_set)
  155. args.train_shape_file = [os.path.join(args.data_dir, args.train_set, "speech_shape")]
  156. args.valid_shape_file = [os.path.join(args.data_dir, args.dev_set, "speech_shape")]
  157. args.train_data_file = os.path.join(args.data_dir, args.train_set, "data.list")
  158. args.valid_data_file = os.path.join(args.data_dir, args.dev_set, "data.list")
  159. if distributed:
  160. dist.barrier()