iterable_dataset.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 soundfile
  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', 'm4a', 'ogg', 'opus', 'wav', 'wma']
  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. DATA_TYPES = {
  54. "sound": lambda x: torchaudio.load(x)[0][0].numpy(),
  55. "kaldi_ark": load_kaldi,
  56. "bytes": load_bytes,
  57. "waveform": lambda x: x,
  58. "npy": np.load,
  59. "text_int": lambda x: np.loadtxt(
  60. StringIO(x), ndmin=1, dtype=np.long, delimiter=" "
  61. ),
  62. "csv_int": lambda x: np.loadtxt(StringIO(x), ndmin=1, dtype=np.long, delimiter=","),
  63. "text_float": lambda x: np.loadtxt(
  64. StringIO(x), ndmin=1, dtype=np.float32, delimiter=" "
  65. ),
  66. "csv_float": lambda x: np.loadtxt(
  67. StringIO(x), ndmin=1, dtype=np.float32, delimiter=","
  68. ),
  69. "text": lambda x: x,
  70. }
  71. class IterableESPnetDataset(IterableDataset):
  72. """Pytorch Dataset class for ESPNet.
  73. Examples:
  74. >>> dataset = IterableESPnetDataset([('wav.scp', 'input', 'sound'),
  75. ... ('token_int', 'output', 'text_int')],
  76. ... )
  77. >>> for uid, data in dataset:
  78. ... data
  79. {'input': per_utt_array, 'output': per_utt_array}
  80. """
  81. def __init__(
  82. self,
  83. path_name_type_list: Collection[Tuple[any, str, str]],
  84. preprocess: Callable[
  85. [str, Dict[str, np.ndarray]], Dict[str, np.ndarray]
  86. ] = None,
  87. float_dtype: str = "float32",
  88. int_dtype: str = "long",
  89. key_file: str = None,
  90. ):
  91. assert check_argument_types()
  92. if len(path_name_type_list) == 0:
  93. raise ValueError(
  94. '1 or more elements are required for "path_name_type_list"'
  95. )
  96. path_name_type_list = copy.deepcopy(path_name_type_list)
  97. self.preprocess = preprocess
  98. self.float_dtype = float_dtype
  99. self.int_dtype = int_dtype
  100. self.key_file = key_file
  101. self.debug_info = {}
  102. non_iterable_list = []
  103. self.path_name_type_list = []
  104. if not isinstance(path_name_type_list[0], Tuple):
  105. path = path_name_type_list[0]
  106. name = path_name_type_list[1]
  107. _type = path_name_type_list[2]
  108. self.debug_info[name] = path, _type
  109. if _type not in DATA_TYPES:
  110. non_iterable_list.append((path, name, _type))
  111. else:
  112. self.path_name_type_list.append((path, name, _type))
  113. else:
  114. for path, name, _type in path_name_type_list:
  115. self.debug_info[name] = path, _type
  116. if _type not in DATA_TYPES:
  117. non_iterable_list.append((path, name, _type))
  118. else:
  119. self.path_name_type_list.append((path, name, _type))
  120. if len(non_iterable_list) != 0:
  121. # Some types doesn't support iterable mode
  122. self.non_iterable_dataset = ESPnetDataset(
  123. path_name_type_list=non_iterable_list,
  124. preprocess=preprocess,
  125. float_dtype=float_dtype,
  126. int_dtype=int_dtype,
  127. )
  128. else:
  129. self.non_iterable_dataset = None
  130. self.apply_utt2category = False
  131. def has_name(self, name) -> bool:
  132. return name in self.debug_info
  133. def names(self) -> Tuple[str, ...]:
  134. return tuple(self.debug_info)
  135. def __repr__(self):
  136. _mes = self.__class__.__name__
  137. _mes += "("
  138. for name, (path, _type) in self.debug_info.items():
  139. _mes += f'\n {name}: {{"path": "{path}", "type": "{_type}"}}'
  140. _mes += f"\n preprocess: {self.preprocess})"
  141. return _mes
  142. def __iter__(self) -> Iterator[Tuple[Union[str, int], Dict[str, np.ndarray]]]:
  143. count = 0
  144. 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"):
  145. data = {}
  146. value = self.path_name_type_list[0][0]
  147. uid = 'utt_id'
  148. name = self.path_name_type_list[0][1]
  149. _type = self.path_name_type_list[0][2]
  150. func = DATA_TYPES[_type]
  151. array = func(value)
  152. data[name] = array
  153. if self.preprocess is not None:
  154. data = self.preprocess(uid, data)
  155. for name in data:
  156. count += 1
  157. value = data[name]
  158. if not isinstance(value, np.ndarray):
  159. raise RuntimeError(
  160. f'All values must be converted to np.ndarray object '
  161. f'by preprocessing, but "{name}" is still {type(value)}.')
  162. # Cast to desired type
  163. if value.dtype.kind == 'f':
  164. value = value.astype(self.float_dtype)
  165. elif value.dtype.kind == 'i':
  166. value = value.astype(self.int_dtype)
  167. else:
  168. raise NotImplementedError(
  169. f'Not supported dtype: {value.dtype}')
  170. data[name] = value
  171. yield uid, data
  172. 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"):
  173. data = {}
  174. value = self.path_name_type_list[0][0]
  175. uid = os.path.basename(self.path_name_type_list[0][0]).split(".")[0]
  176. name = self.path_name_type_list[0][1]
  177. _type = self.path_name_type_list[0][2]
  178. if _type == "sound":
  179. audio_type = os.path.basename(value).split(".")[1].lower()
  180. if audio_type not in SUPPORT_AUDIO_TYPE_SETS:
  181. raise NotImplementedError(
  182. f'Not supported audio type: {audio_type}')
  183. func = DATA_TYPES[_type]
  184. array = func(value)
  185. data[name] = array
  186. if self.preprocess is not None:
  187. data = self.preprocess(uid, data)
  188. for name in data:
  189. count += 1
  190. value = data[name]
  191. if not isinstance(value, np.ndarray):
  192. raise RuntimeError(
  193. f'All values must be converted to np.ndarray object '
  194. f'by preprocessing, but "{name}" is still {type(value)}.')
  195. # Cast to desired type
  196. if value.dtype.kind == 'f':
  197. value = value.astype(self.float_dtype)
  198. elif value.dtype.kind == 'i':
  199. value = value.astype(self.int_dtype)
  200. else:
  201. raise NotImplementedError(
  202. f'Not supported dtype: {value.dtype}')
  203. data[name] = value
  204. yield uid, data
  205. else:
  206. if self.key_file is not None:
  207. uid_iter = (
  208. line.rstrip().split(maxsplit=1)[0]
  209. for line in open(self.key_file, encoding="utf-8")
  210. )
  211. elif len(self.path_name_type_list) != 0:
  212. uid_iter = (
  213. line.rstrip().split(maxsplit=1)[0]
  214. for line in open(self.path_name_type_list[0][0], encoding="utf-8")
  215. )
  216. else:
  217. uid_iter = iter(self.non_iterable_dataset)
  218. files = [open(lis[0], encoding="utf-8") for lis in self.path_name_type_list]
  219. worker_info = torch.utils.data.get_worker_info()
  220. linenum = 0
  221. for count, uid in enumerate(uid_iter, 1):
  222. # If num_workers>=1, split keys
  223. if worker_info is not None:
  224. if (count - 1) % worker_info.num_workers != worker_info.id:
  225. continue
  226. # 1. Read a line from each file
  227. while True:
  228. keys = []
  229. values = []
  230. for f in files:
  231. linenum += 1
  232. try:
  233. line = next(f)
  234. except StopIteration:
  235. raise RuntimeError(f"{uid} is not found in the files")
  236. sps = line.rstrip().split(maxsplit=1)
  237. if len(sps) != 2:
  238. raise RuntimeError(
  239. f"This line doesn't include a space:"
  240. f" {f}:L{linenum}: {line})"
  241. )
  242. key, value = sps
  243. keys.append(key)
  244. values.append(value)
  245. for k_idx, k in enumerate(keys):
  246. if k != keys[0]:
  247. raise RuntimeError(
  248. f"Keys are mismatched. Text files (idx={k_idx}) is "
  249. f"not sorted or not having same keys at L{linenum}"
  250. )
  251. # If the key is matched, break the loop
  252. if len(keys) == 0 or keys[0] == uid:
  253. break
  254. # 2. Load the entry from each line and create a dict
  255. data = {}
  256. # 2.a. Load data streamingly
  257. for value, (path, name, _type) in zip(values, self.path_name_type_list):
  258. if _type == "sound":
  259. audio_type = os.path.basename(value).split(".")[1].lower()
  260. if audio_type not in SUPPORT_AUDIO_TYPE_SETS:
  261. raise NotImplementedError(
  262. f'Not supported audio type: {audio_type}')
  263. func = DATA_TYPES[_type]
  264. # Load entry
  265. array = func(value)
  266. data[name] = array
  267. if self.non_iterable_dataset is not None:
  268. # 2.b. Load data from non-iterable dataset
  269. _, from_non_iterable = self.non_iterable_dataset[uid]
  270. data.update(from_non_iterable)
  271. # 3. [Option] Apply preprocessing
  272. # e.g. funasr.train.preprocessor:CommonPreprocessor
  273. if self.preprocess is not None:
  274. data = self.preprocess(uid, data)
  275. # 4. Force data-precision
  276. for name in data:
  277. value = data[name]
  278. if not isinstance(value, np.ndarray):
  279. raise RuntimeError(
  280. f"All values must be converted to np.ndarray object "
  281. f'by preprocessing, but "{name}" is still {type(value)}.'
  282. )
  283. # Cast to desired type
  284. if value.dtype.kind == "f":
  285. value = value.astype(self.float_dtype)
  286. elif value.dtype.kind == "i":
  287. value = value.astype(self.int_dtype)
  288. else:
  289. raise NotImplementedError(f"Not supported dtype: {value.dtype}")
  290. data[name] = value
  291. yield uid, data
  292. if count == 0:
  293. raise RuntimeError("No iteration")