iterable_dataset.py 15 KB

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