prepare_data.py 10 KB

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