iterable_dataset.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. """Iterable dataset module."""
  2. import copy
  3. from io import StringIO
  4. from pathlib import Path
  5. from typing import Callable
  6. from typing import Collection
  7. from typing import Dict
  8. from typing import Iterator
  9. from typing import Tuple
  10. from typing import Union
  11. import kaldiio
  12. import numpy as np
  13. import torch
  14. import torchaudio
  15. from torch.utils.data.dataset import IterableDataset
  16. from typeguard import check_argument_types
  17. import os.path
  18. from funasr.datasets.dataset import ESPnetDataset
  19. SUPPORT_AUDIO_TYPE_SETS = ['flac', 'mp3', 'ogg', 'opus', 'wav', 'pcm']
  20. def load_kaldi(input):
  21. retval = kaldiio.load_mat(input)
  22. if isinstance(retval, tuple):
  23. assert len(retval) == 2, len(retval)
  24. if isinstance(retval[0], int) and isinstance(retval[1], np.ndarray):
  25. # sound scp case
  26. rate, array = retval
  27. elif isinstance(retval[1], int) and isinstance(retval[0], np.ndarray):
  28. # Extended ark format case
  29. array, rate = retval
  30. else:
  31. raise RuntimeError(f"Unexpected type: {type(retval[0])}, {type(retval[1])}")
  32. # Multichannel wave fie
  33. # array: (NSample, Channel) or (Nsample)
  34. else:
  35. # Normal ark case
  36. assert isinstance(retval, np.ndarray), type(retval)
  37. array = retval
  38. return array
  39. def load_bytes(input):
  40. middle_data = np.frombuffer(input, dtype=np.int16)
  41. middle_data = np.asarray(middle_data)
  42. if middle_data.dtype.kind not in 'iu':
  43. raise TypeError("'middle_data' must be an array of integers")
  44. dtype = np.dtype('float32')
  45. if dtype.kind != 'f':
  46. raise TypeError("'dtype' must be a floating point type")
  47. i = np.iinfo(middle_data.dtype)
  48. abs_max = 2 ** (i.bits - 1)
  49. offset = i.min + abs_max
  50. array = np.frombuffer((middle_data.astype(dtype) - offset) / abs_max, dtype=np.float32)
  51. return array
  52. def load_pcm(input):
  53. with open(input,"rb") as f:
  54. bytes = f.read()
  55. return load_bytes(bytes)
  56. DATA_TYPES = {
  57. "sound": lambda x: torchaudio.load(x)[0][0].numpy(),
  58. "pcm": load_pcm,
  59. "kaldi_ark": load_kaldi,
  60. "bytes": load_bytes,
  61. "waveform": lambda x: x,
  62. "npy": np.load,
  63. "text_int": lambda x: np.loadtxt(
  64. StringIO(x), ndmin=1, dtype=np.long, delimiter=" "
  65. ),
  66. "csv_int": lambda x: np.loadtxt(StringIO(x), ndmin=1, dtype=np.long, delimiter=","),
  67. "text_float": lambda x: np.loadtxt(
  68. StringIO(x), ndmin=1, dtype=np.float32, delimiter=" "
  69. ),
  70. "csv_float": lambda x: np.loadtxt(
  71. StringIO(x), ndmin=1, dtype=np.float32, delimiter=","
  72. ),
  73. "text": lambda x: x,
  74. }
  75. class IterableESPnetDataset(IterableDataset):
  76. """Pytorch Dataset class for ESPNet.
  77. Examples:
  78. >>> dataset = IterableESPnetDataset([('wav.scp', 'input', 'sound'),
  79. ... ('token_int', 'output', 'text_int')],
  80. ... )
  81. >>> for uid, data in dataset:
  82. ... data
  83. {'input': per_utt_array, 'output': per_utt_array}
  84. """
  85. def __init__(
  86. self,
  87. path_name_type_list: Collection[Tuple[any, str, str]],
  88. preprocess: Callable[
  89. [str, Dict[str, np.ndarray]], Dict[str, np.ndarray]
  90. ] = None,
  91. float_dtype: str = "float32",
  92. fs: dict = None,
  93. int_dtype: str = "long",
  94. key_file: str = None,
  95. ):
  96. assert check_argument_types()
  97. if len(path_name_type_list) == 0:
  98. raise ValueError(
  99. '1 or more elements are required for "path_name_type_list"'
  100. )
  101. path_name_type_list = copy.deepcopy(path_name_type_list)
  102. self.preprocess = preprocess
  103. self.float_dtype = float_dtype
  104. self.int_dtype = int_dtype
  105. self.key_file = key_file
  106. self.fs = fs
  107. self.debug_info = {}
  108. non_iterable_list = []
  109. self.path_name_type_list = []
  110. if not isinstance(path_name_type_list[0], Tuple):
  111. path = path_name_type_list[0]
  112. name = path_name_type_list[1]
  113. _type = path_name_type_list[2]
  114. self.debug_info[name] = path, _type
  115. if _type not in DATA_TYPES:
  116. non_iterable_list.append((path, name, _type))
  117. else:
  118. self.path_name_type_list.append((path, name, _type))
  119. else:
  120. for path, name, _type in path_name_type_list:
  121. self.debug_info[name] = path, _type
  122. if _type not in DATA_TYPES:
  123. non_iterable_list.append((path, name, _type))
  124. else:
  125. self.path_name_type_list.append((path, name, _type))
  126. if len(non_iterable_list) != 0:
  127. # Some types doesn't support iterable mode
  128. self.non_iterable_dataset = ESPnetDataset(
  129. path_name_type_list=non_iterable_list,
  130. preprocess=preprocess,
  131. float_dtype=float_dtype,
  132. int_dtype=int_dtype,
  133. )
  134. else:
  135. self.non_iterable_dataset = None
  136. self.apply_utt2category = False
  137. def has_name(self, name) -> bool:
  138. return name in self.debug_info
  139. def names(self) -> Tuple[str, ...]:
  140. return tuple(self.debug_info)
  141. def __repr__(self):
  142. _mes = self.__class__.__name__
  143. _mes += "("
  144. for name, (path, _type) in self.debug_info.items():
  145. _mes += f'\n {name}: {{"path": "{path}", "type": "{_type}"}}'
  146. _mes += f"\n preprocess: {self.preprocess})"
  147. return _mes
  148. def __iter__(self) -> Iterator[Tuple[Union[str, int], Dict[str, np.ndarray]]]:
  149. count = 0
  150. if len(self.path_name_type_list) != 0 and (self.path_name_type_list[0][2] == "bytes" or self.path_name_type_list[0][2] == "waveform"):
  151. linenum = len(self.path_name_type_list)
  152. data = {}
  153. for i in range(linenum):
  154. value = self.path_name_type_list[i][0]
  155. uid = 'utt_id'
  156. name = self.path_name_type_list[i][1]
  157. _type = self.path_name_type_list[i][2]
  158. func = DATA_TYPES[_type]
  159. array = func(value)
  160. if self.fs is not None and (name == "speech" or name == "ref_speech"):
  161. audio_fs = self.fs["audio_fs"]
  162. model_fs = self.fs["model_fs"]
  163. if audio_fs is not None and model_fs is not None:
  164. array = torch.from_numpy(array)
  165. array = array.unsqueeze(0)
  166. array = torchaudio.transforms.Resample(orig_freq=audio_fs,
  167. new_freq=model_fs)(array)
  168. array = array.squeeze(0).numpy()
  169. data[name] = array
  170. if self.preprocess is not None:
  171. data = self.preprocess(uid, data)
  172. for name in data:
  173. count += 1
  174. value = data[name]
  175. if not isinstance(value, np.ndarray):
  176. raise RuntimeError(
  177. f'All values must be converted to np.ndarray object '
  178. f'by preprocessing, but "{name}" is still {type(value)}.')
  179. # Cast to desired type
  180. if value.dtype.kind == 'f':
  181. value = value.astype(self.float_dtype)
  182. elif value.dtype.kind == 'i':
  183. value = value.astype(self.int_dtype)
  184. else:
  185. raise NotImplementedError(
  186. f'Not supported dtype: {value.dtype}')
  187. data[name] = value
  188. yield uid, data
  189. elif len(self.path_name_type_list) != 0 and self.path_name_type_list[0][2] == "sound" and not self.path_name_type_list[0][0].lower().endswith(".scp"):
  190. linenum = len(self.path_name_type_list)
  191. data = {}
  192. for i in range(linenum):
  193. value = self.path_name_type_list[i][0]
  194. uid = os.path.basename(self.path_name_type_list[i][0]).split(".")[0]
  195. name = self.path_name_type_list[i][1]
  196. _type = self.path_name_type_list[i][2]
  197. if _type == "sound":
  198. audio_type = os.path.basename(value).split(".")[-1].lower()
  199. if audio_type not in SUPPORT_AUDIO_TYPE_SETS:
  200. raise NotImplementedError(
  201. f'Not supported audio type: {audio_type}')
  202. if audio_type == "pcm":
  203. _type = "pcm"
  204. func = DATA_TYPES[_type]
  205. array = func(value)
  206. if self.fs is not None and (name == "speech" or name == "ref_speech"):
  207. audio_fs = self.fs["audio_fs"]
  208. model_fs = self.fs["model_fs"]
  209. if audio_fs is not None and model_fs is not None:
  210. array = torch.from_numpy(array)
  211. array = array.unsqueeze(0)
  212. array = torchaudio.transforms.Resample(orig_freq=audio_fs,
  213. new_freq=model_fs)(array)
  214. array = array.squeeze(0).numpy()
  215. data[name] = array
  216. if self.preprocess is not None:
  217. data = self.preprocess(uid, data)
  218. for name in data:
  219. count += 1
  220. value = data[name]
  221. if not isinstance(value, np.ndarray):
  222. raise RuntimeError(
  223. f'All values must be converted to np.ndarray object '
  224. f'by preprocessing, but "{name}" is still {type(value)}.')
  225. # Cast to desired type
  226. if value.dtype.kind == 'f':
  227. value = value.astype(self.float_dtype)
  228. elif value.dtype.kind == 'i':
  229. value = value.astype(self.int_dtype)
  230. else:
  231. raise NotImplementedError(
  232. f'Not supported dtype: {value.dtype}')
  233. data[name] = value
  234. yield uid, data
  235. else:
  236. if self.key_file is not None:
  237. uid_iter = (
  238. line.rstrip().split(maxsplit=1)[0]
  239. for line in open(self.key_file, encoding="utf-8")
  240. )
  241. elif len(self.path_name_type_list) != 0:
  242. uid_iter = (
  243. line.rstrip().split(maxsplit=1)[0]
  244. for line in open(self.path_name_type_list[0][0], encoding="utf-8")
  245. )
  246. else:
  247. uid_iter = iter(self.non_iterable_dataset)
  248. files = [open(lis[0], encoding="utf-8") for lis in self.path_name_type_list]
  249. worker_info = torch.utils.data.get_worker_info()
  250. linenum = 0
  251. for count, uid in enumerate(uid_iter, 1):
  252. # If num_workers>=1, split keys
  253. if worker_info is not None:
  254. if (count - 1) % worker_info.num_workers != worker_info.id:
  255. continue
  256. # 1. Read a line from each file
  257. while True:
  258. keys = []
  259. values = []
  260. for f in files:
  261. linenum += 1
  262. try:
  263. line = next(f)
  264. except StopIteration:
  265. raise RuntimeError(f"{uid} is not found in the files")
  266. sps = line.rstrip().split(maxsplit=1)
  267. if len(sps) != 2:
  268. raise RuntimeError(
  269. f"This line doesn't include a space:"
  270. f" {f}:L{linenum}: {line})"
  271. )
  272. key, value = sps
  273. keys.append(key)
  274. values.append(value)
  275. for k_idx, k in enumerate(keys):
  276. if k != keys[0]:
  277. raise RuntimeError(
  278. f"Keys are mismatched. Text files (idx={k_idx}) is "
  279. f"not sorted or not having same keys at L{linenum}"
  280. )
  281. # If the key is matched, break the loop
  282. if len(keys) == 0 or keys[0] == uid:
  283. break
  284. # 2. Load the entry from each line and create a dict
  285. data = {}
  286. # 2.a. Load data streamingly
  287. for value, (path, name, _type) in zip(values, self.path_name_type_list):
  288. if _type == "sound":
  289. audio_type = os.path.basename(value).split(".")[-1].lower()
  290. if audio_type not in SUPPORT_AUDIO_TYPE_SETS:
  291. raise NotImplementedError(
  292. f'Not supported audio type: {audio_type}')
  293. if audio_type == "pcm":
  294. _type = "pcm"
  295. func = DATA_TYPES[_type]
  296. # Load entry
  297. array = func(value)
  298. if self.fs is not None and name == "speech":
  299. audio_fs = self.fs["audio_fs"]
  300. model_fs = self.fs["model_fs"]
  301. if audio_fs is not None and model_fs is not None:
  302. array = torch.from_numpy(array)
  303. array = array.unsqueeze(0)
  304. array = torchaudio.transforms.Resample(orig_freq=audio_fs,
  305. new_freq=model_fs)(array)
  306. array = array.squeeze(0).numpy()
  307. data[name] = array
  308. if self.non_iterable_dataset is not None:
  309. # 2.b. Load data from non-iterable dataset
  310. _, from_non_iterable = self.non_iterable_dataset[uid]
  311. data.update(from_non_iterable)
  312. # 3. [Option] Apply preprocessing
  313. # e.g. funasr.train.preprocessor:CommonPreprocessor
  314. if self.preprocess is not None:
  315. data = self.preprocess(uid, data)
  316. # 4. Force data-precision
  317. for name in data:
  318. value = data[name]
  319. if not isinstance(value, np.ndarray):
  320. raise RuntimeError(
  321. f"All values must be converted to np.ndarray object "
  322. f'by preprocessing, but "{name}" is still {type(value)}.'
  323. )
  324. # Cast to desired type
  325. if value.dtype.kind == "f":
  326. value = value.astype(self.float_dtype)
  327. elif value.dtype.kind == "i":
  328. value = value.astype(self.int_dtype)
  329. else:
  330. raise NotImplementedError(f"Not supported dtype: {value.dtype}")
  331. data[name] = value
  332. yield uid, data
  333. if count == 0:
  334. raise RuntimeError("No iteration")