prepare_data.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import logging
  2. import os
  3. import shutil
  4. from multiprocessing import Pool
  5. import kaldiio
  6. import numpy as np
  7. import torch.distributed as dist
  8. import torchaudio
  9. def filter_wav_text(data_dir, dataset):
  10. wav_file = os.path.join(data_dir, dataset, "wav.scp")
  11. text_file = os.path.join(data_dir, dataset, "text")
  12. with open(wav_file) as f_wav, open(text_file) as f_text:
  13. wav_lines = f_wav.readlines()
  14. text_lines = f_text.readlines()
  15. os.rename(wav_file, "{}.bak".format(wav_file))
  16. os.rename(text_file, "{}.bak".format(text_file))
  17. wav_dict = {}
  18. for line in wav_lines:
  19. parts = line.strip().split()
  20. if len(parts) < 2:
  21. continue
  22. wav_dict[parts[0]] = parts[1]
  23. text_dict = {}
  24. for line in text_lines:
  25. parts = line.strip().split()
  26. if len(parts) < 2:
  27. continue
  28. text_dict[parts[0]] = " ".join(parts[1:])
  29. filter_count = 0
  30. with open(wav_file, "w") as f_wav, open(text_file, "w") as f_text:
  31. for sample_name, wav_path in wav_dict.items():
  32. if sample_name in text_dict.keys():
  33. f_wav.write(sample_name + " " + wav_path + "\n")
  34. f_text.write(sample_name + " " + text_dict[sample_name] + "\n")
  35. else:
  36. filter_count += 1
  37. logging.info("{}/{} samples in {} are filtered because of the mismatch between wav.scp and text".
  38. format(filter_count, len(wav_lines), dataset))
  39. def wav2num_frame(wav_path, frontend_conf):
  40. waveform, sampling_rate = torchaudio.load(wav_path)
  41. n_frames = (waveform.shape[1] * 1000.0) / (sampling_rate * frontend_conf["frame_shift"] * frontend_conf["lfr_n"])
  42. feature_dim = frontend_conf["n_mels"] * frontend_conf["lfr_m"]
  43. return n_frames, feature_dim
  44. def calc_shape_core(root_path, args, idx):
  45. file_name = args.data_file_names.split(",")[0]
  46. data_name = args.dataset_conf.get("data_names", "speech,text").split(",")[0]
  47. scp_file = os.path.join(root_path, "{}.{}".format(file_name, idx))
  48. shape_file = os.path.join(root_path, "{}_shape.{}".format(data_name, idx))
  49. with open(scp_file) as f:
  50. lines = f.readlines()
  51. data_type = args.dataset_conf.get("data_types", "sound,text").split(",")[0]
  52. if data_type == "sound":
  53. frontend_conf = args.frontend_conf
  54. dataset_conf = args.dataset_conf
  55. length_min = dataset_conf.speech_length_min if hasattr(dataset_conf, "{}_length_min".format(data_name)) else -1
  56. length_max = dataset_conf.speech_length_max if hasattr(dataset_conf, "{}_length_max".format(data_name)) else -1
  57. with open(shape_file, "w") as f:
  58. for line in lines:
  59. sample_name, wav_path = line.strip().split()
  60. n_frames, feature_dim = wav2num_frame(wav_path, frontend_conf)
  61. write_flag = True
  62. if n_frames > 0 and length_min > 0:
  63. write_flag = n_frames >= length_min
  64. if n_frames > 0 and length_max > 0:
  65. write_flag = n_frames <= length_max
  66. if write_flag:
  67. f.write("{} {},{}\n".format(sample_name, str(int(np.ceil(n_frames))), str(int(feature_dim))))
  68. f.flush()
  69. elif data_type == "kaldi_ark":
  70. dataset_conf = args.dataset_conf
  71. length_min = dataset_conf.speech_length_min if hasattr(dataset_conf, "{}_length_min".format(data_name)) else -1
  72. length_max = dataset_conf.speech_length_max if hasattr(dataset_conf, "{}_length_max".format(data_name)) else -1
  73. with open(shape_file, "w") as f:
  74. for line in lines:
  75. sample_name, feature_path = line.strip().split()
  76. feature = kaldiio.load_mat(feature_path)
  77. n_frames, feature_dim = feature.shape
  78. if n_frames > 0 and length_min > 0:
  79. write_flag = n_frames >= length_min
  80. if n_frames > 0 and length_max > 0:
  81. write_flag = n_frames <= length_max
  82. if write_flag:
  83. f.write("{} {},{}\n".format(sample_name, str(int(np.ceil(n_frames))), str(int(feature_dim))))
  84. f.flush()
  85. elif data_type == "text":
  86. with open(shape_file, "w") as f:
  87. for line in lines:
  88. sample_name, text = line.strip().split(maxsplit=1)
  89. n_tokens = len(text.split())
  90. f.write("{} {}\n".format(sample_name, str(int(np.ceil(n_tokens)))))
  91. f.flush()
  92. else:
  93. raise RuntimeError("Unsupported data_type: {}".format(data_type))
  94. def calc_shape(args, dataset, nj=64):
  95. data_name = args.dataset_conf.get("data_names", "speech,text").split(",")[0]
  96. shape_path = os.path.join(args.data_dir, dataset, "{}_shape".format(data_name))
  97. if os.path.exists(shape_path):
  98. logging.info('Shape file for small dataset already exists.')
  99. return
  100. split_shape_path = os.path.join(args.data_dir, dataset, "{}_shape_files".format(data_name))
  101. if os.path.exists(split_shape_path):
  102. shutil.rmtree(split_shape_path)
  103. os.mkdir(split_shape_path)
  104. # split
  105. file_name = args.data_file_names.split(",")[0]
  106. scp_file = os.path.join(args.data_dir, dataset, file_name)
  107. with open(scp_file) as f:
  108. lines = f.readlines()
  109. num_lines = len(lines)
  110. num_job_lines = num_lines // nj
  111. start = 0
  112. for i in range(nj):
  113. end = start + num_job_lines
  114. file = os.path.join(split_shape_path, "{}.{}".format(file_name, str(i + 1)))
  115. with open(file, "w") as f:
  116. if i == nj - 1:
  117. f.writelines(lines[start:])
  118. else:
  119. f.writelines(lines[start:end])
  120. start = end
  121. p = Pool(nj)
  122. for i in range(nj):
  123. p.apply_async(calc_shape_core, args=(split_shape_path, args, str(i + 1)))
  124. logging.info("Generating shape files, please wait a few minutes...")
  125. p.close()
  126. p.join()
  127. # combine
  128. with open(shape_path, "w") as f:
  129. for i in range(nj):
  130. job_file = os.path.join(split_shape_path, "{}_shape.{}".format(data_name, str(i + 1)))
  131. with open(job_file) as job_f:
  132. lines = job_f.readlines()
  133. f.writelines(lines)
  134. logging.info('Generating shape files done.')
  135. def generate_data_list(args, data_dir, dataset, nj=64):
  136. data_names = args.dataset_conf.get("data_names", "speech,text").split(",")
  137. file_names = args.data_file_names.split(",")
  138. concat_data_name = "_".join(data_names)
  139. list_file = os.path.join(data_dir, dataset, "{}_data.list".format(concat_data_name))
  140. if os.path.exists(list_file):
  141. logging.info('Data list for large dataset already exists.')
  142. return
  143. split_path = os.path.join(data_dir, dataset, "split")
  144. if os.path.exists(split_path):
  145. shutil.rmtree(split_path)
  146. os.mkdir(split_path)
  147. data_lines_list = []
  148. for file_name in file_names:
  149. with open(os.path.join(data_dir, dataset, file_name)) as f:
  150. lines = f.readlines()
  151. data_lines_list.append(lines)
  152. num_lines = len(data_lines_list[0])
  153. num_job_lines = num_lines // nj
  154. start = 0
  155. for i in range(nj):
  156. end = start + num_job_lines
  157. split_path_nj = os.path.join(split_path, str(i + 1))
  158. os.mkdir(split_path_nj)
  159. for file_id, file_name in enumerate(file_names):
  160. file = os.path.join(split_path_nj, file_name)
  161. with open(file, "w") as f:
  162. if i == nj - 1:
  163. f.writelines(data_lines_list[file_id][start:])
  164. else:
  165. f.writelines(data_lines_list[file_id][start:end])
  166. start = end
  167. with open(list_file, "w") as f_data:
  168. for i in range(nj):
  169. path = ""
  170. for file_name in file_names:
  171. path = path + " " + os.path.join(split_path, str(i + 1), file_name)
  172. f_data.write(path + "\n")
  173. def prepare_data(args, distributed_option):
  174. distributed = distributed_option.distributed
  175. if not distributed or distributed_option.dist_rank == 0:
  176. if hasattr(args, "filter_input") and args.filter_input:
  177. filter_wav_text(args.data_dir, args.train_set)
  178. filter_wav_text(args.data_dir, args.valid_set)
  179. if args.dataset_type == "small":
  180. calc_shape(args, args.train_set)
  181. calc_shape(args, args.valid_set)
  182. if args.dataset_type == "large":
  183. generate_data_list(args, args.data_dir, args.train_set)
  184. generate_data_list(args, args.data_dir, args.valid_set)
  185. data_names = args.dataset_conf.get("data_names", "speech,text").split(",")
  186. data_types = args.dataset_conf.get("data_types", "sound,text").split(",")
  187. file_names = args.data_file_names.split(",")
  188. print("data_names: {}, data_types: {}, file_names: {}".format(data_names, data_types, file_names))
  189. assert len(data_names) == len(data_types) == len(file_names)
  190. if args.dataset_type == "small":
  191. args.train_shape_file = [os.path.join(args.data_dir, args.train_set, "{}_shape".format(data_names[0]))]
  192. args.valid_shape_file = [os.path.join(args.data_dir, args.valid_set, "{}_shape".format(data_names[0]))]
  193. args.train_data_path_and_name_and_type, args.valid_data_path_and_name_and_type = [], []
  194. for file_name, data_name, data_type in zip(file_names, data_names, data_types):
  195. args.train_data_path_and_name_and_type.append(
  196. ["{}/{}/{}".format(args.data_dir, args.train_set, file_name), data_name, data_type])
  197. args.valid_data_path_and_name_and_type.append(
  198. ["{}/{}/{}".format(args.data_dir, args.valid_set, file_name), data_name, data_type])
  199. else:
  200. concat_data_name = "_".join(data_names)
  201. args.train_data_file = os.path.join(args.data_dir, args.train_set, "{}_data.list".format(concat_data_name))
  202. args.valid_data_file = os.path.join(args.data_dir, args.valid_set, "{}_data.list".format(concat_data_name))
  203. if distributed:
  204. dist.barrier()