prepare_data.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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:])
  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("{}/{} samples in {} are filtered because of the mismatch between wav.scp and text".
  37. format(filter_count, len(wav_lines), dataset))
  38. def wav2num_frame(wav_path, frontend_conf):
  39. waveform, sampling_rate = torchaudio.load(wav_path)
  40. n_frames = (waveform.shape[1] * 1000.0) / (sampling_rate * frontend_conf["frame_shift"] * frontend_conf["lfr_n"])
  41. feature_dim = frontend_conf["n_mels"] * frontend_conf["lfr_m"]
  42. return n_frames, feature_dim
  43. def calc_shape_core(root_path, args, idx):
  44. wav_scp_file = os.path.join(root_path, "wav.scp.{}".format(idx))
  45. shape_file = os.path.join(root_path, "speech_shape.{}".format(idx))
  46. with open(wav_scp_file) as f:
  47. lines = f.readlines()
  48. frontend_conf = args.frontend_conf
  49. dataset_conf = args.dataset_conf
  50. speech_length_min = dataset_conf.speech_length_min if hasattr(dataset_conf, "speech_length_min") else -1
  51. speech_length_max = dataset_conf.speech_length_max if hasattr(dataset_conf, "speech_length_max") else -1
  52. with open(shape_file, "w") as f:
  53. for line in lines:
  54. sample_name, wav_path = line.strip().split()
  55. n_frames, feature_dim = wav2num_frame(wav_path, frontend_conf)
  56. write_flag = True
  57. if n_frames > 0 and speech_length_min > 0:
  58. write_flag = n_frames >= speech_length_min
  59. if n_frames > 0 and speech_length_max > 0:
  60. write_flag = n_frames <= speech_length_max
  61. if write_flag:
  62. f.write("{} {},{}\n".format(sample_name, str(int(np.ceil(n_frames))), str(int(feature_dim))))
  63. f.flush()
  64. def calc_shape(args, dataset, nj=64):
  65. shape_path = os.path.join(args.data_dir, dataset, "speech_shape")
  66. if os.path.exists(shape_path):
  67. logging.info('Shape file for small dataset already exists.')
  68. return
  69. split_shape_path = os.path.join(args.data_dir, dataset, "shape_files")
  70. if os.path.exists(split_shape_path):
  71. shutil.rmtree(split_shape_path)
  72. os.mkdir(split_shape_path)
  73. # split
  74. wav_scp_file = os.path.join(args.data_dir, dataset, "wav.scp")
  75. with open(wav_scp_file) as f:
  76. lines = f.readlines()
  77. num_lines = len(lines)
  78. num_job_lines = num_lines // nj
  79. start = 0
  80. for i in range(nj):
  81. end = start + num_job_lines
  82. file = os.path.join(split_shape_path, "wav.scp.{}".format(str(i + 1)))
  83. with open(file, "w") as f:
  84. if i == nj - 1:
  85. f.writelines(lines[start:])
  86. else:
  87. f.writelines(lines[start:end])
  88. start = end
  89. p = Pool(nj)
  90. for i in range(nj):
  91. p.apply_async(calc_shape_core, args=(split_shape_path, args, str(i + 1)))
  92. logging.info("Generating shape files, please wait a few minutes...")
  93. p.close()
  94. p.join()
  95. # combine
  96. with open(shape_path, "w") as f:
  97. for i in range(nj):
  98. job_file = os.path.join(split_shape_path, "speech_shape.{}".format(str(i + 1)))
  99. with open(job_file) as job_f:
  100. lines = job_f.readlines()
  101. f.writelines(lines)
  102. logging.info('Generating shape files done.')
  103. def generate_data_list(data_dir, dataset, nj=64):
  104. list_file = os.path.join(data_dir, dataset, "data.list")
  105. if os.path.exists(list_file):
  106. logging.info('Data list for large dataset already exists.')
  107. return
  108. split_path = os.path.join(data_dir, dataset, "split")
  109. if os.path.exists(split_path):
  110. shutil.rmtree(split_path)
  111. os.mkdir(split_path)
  112. with open(os.path.join(data_dir, dataset, "wav.scp")) as f_wav:
  113. wav_lines = f_wav.readlines()
  114. with open(os.path.join(data_dir, dataset, "text")) as f_text:
  115. text_lines = f_text.readlines()
  116. num_lines = len(wav_lines)
  117. num_job_lines = num_lines // nj
  118. start = 0
  119. for i in range(nj):
  120. end = start + num_job_lines
  121. split_path_nj = os.path.join(split_path, str(i + 1))
  122. os.mkdir(split_path_nj)
  123. wav_file = os.path.join(split_path_nj, "wav.scp")
  124. text_file = os.path.join(split_path_nj, "text")
  125. with open(wav_file, "w") as fw, open(text_file, "w") as ft:
  126. if i == nj - 1:
  127. fw.writelines(wav_lines[start:])
  128. ft.writelines(text_lines[start:])
  129. else:
  130. fw.writelines(wav_lines[start:end])
  131. ft.writelines(text_lines[start:end])
  132. start = end
  133. with open(list_file, "w") as f_data:
  134. for i in range(nj):
  135. wav_path = os.path.join(split_path, str(i + 1), "wav.scp")
  136. text_path = os.path.join(split_path, str(i + 1), "text")
  137. f_data.write(wav_path + " " + text_path + "\n")
  138. def prepare_data(args, distributed_option):
  139. distributed = distributed_option.distributed
  140. if not distributed or distributed_option.dist_rank == 0:
  141. filter_wav_text(args.data_dir, args.train_set)
  142. filter_wav_text(args.data_dir, args.valid_set)
  143. if args.dataset_type == "small":
  144. calc_shape(args, args.train_set)
  145. calc_shape(args, args.valid_set)
  146. if args.dataset_type == "large":
  147. generate_data_list(args.data_dir, args.train_set)
  148. generate_data_list(args.data_dir, args.valid_set)
  149. if args.dataset_type == "small":
  150. args.train_shape_file = [os.path.join(args.data_dir, args.train_set, "speech_shape")]
  151. args.valid_shape_file = [os.path.join(args.data_dir, args.valid_set, "speech_shape")]
  152. data_names = args.dataset_conf.get("data_names", "speech,text").split(",")
  153. data_types = args.dataset_conf.get("data_types", "sound,text").split(",")
  154. args.train_data_path_and_name_and_type = [
  155. ["{}/{}/wav.scp".format(args.data_dir, args.train_set), data_names[0], data_types[0]],
  156. ["{}/{}/text".format(args.data_dir, args.train_set), data_names[1], data_types[1]]
  157. ]
  158. args.valid_data_path_and_name_and_type = [
  159. ["{}/{}/wav.scp".format(args.data_dir, args.valid_set), data_names[0], data_types[0]],
  160. ["{}/{}/text".format(args.data_dir, args.valid_set), data_names[1], data_types[1]]
  161. ]
  162. if args.embed_path is not None:
  163. args.train_data_path_and_name_and_type[0].append(
  164. "{}/embed/kaldi_ark".format(os.path.join(args.embed_path, "embeds", args.train_set, "embeds.scp")))
  165. args.valid_data_path_and_name_and_type[0].append(
  166. "{}/embed/kaldi_ark".format(os.path.join(args.embed_path, "embeds", args.dev_set, "embeds.scp")))
  167. else:
  168. args.train_data_file = os.path.join(args.data_dir, args.train_set, "data.list")
  169. args.valid_data_file = os.path.join(args.data_dir, args.valid_set, "data.list")
  170. if distributed:
  171. dist.barrier()