read_text.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import logging
  2. from pathlib import Path
  3. from typing import Dict
  4. from typing import List
  5. from typing import Union
  6. def read_2column_text(path: Union[Path, str]) -> Dict[str, str]:
  7. """Read a text file having 2 column as dict object.
  8. Examples:
  9. wav.scp:
  10. key1 /some/path/a.wav
  11. key2 /some/path/b.wav
  12. >>> read_2column_text('wav.scp')
  13. {'key1': '/some/path/a.wav', 'key2': '/some/path/b.wav'}
  14. """
  15. data = {}
  16. with Path(path).open("r", encoding="utf-8") as f:
  17. for linenum, line in enumerate(f, 1):
  18. sps = line.rstrip().split(maxsplit=1)
  19. if len(sps) == 1:
  20. k, v = sps[0], ""
  21. else:
  22. k, v = sps
  23. if k in data:
  24. raise RuntimeError(f"{k} is duplicated ({path}:{linenum})")
  25. data[k] = v
  26. return data
  27. def load_num_sequence_text(
  28. path: Union[Path, str], loader_type: str = "csv_int"
  29. ) -> Dict[str, List[Union[float, int]]]:
  30. """Read a text file indicating sequences of number
  31. Examples:
  32. key1 1 2 3
  33. key2 34 5 6
  34. >>> d = load_num_sequence_text('text')
  35. >>> np.testing.assert_array_equal(d["key1"], np.array([1, 2, 3]))
  36. """
  37. if loader_type == "text_int":
  38. delimiter = " "
  39. dtype = int
  40. elif loader_type == "text_float":
  41. delimiter = " "
  42. dtype = float
  43. elif loader_type == "csv_int":
  44. delimiter = ","
  45. dtype = int
  46. elif loader_type == "csv_float":
  47. delimiter = ","
  48. dtype = float
  49. else:
  50. raise ValueError(f"Not supported loader_type={loader_type}")
  51. # path looks like:
  52. # utta 1,0
  53. # uttb 3,4,5
  54. # -> return {'utta': np.ndarray([1, 0]),
  55. # 'uttb': np.ndarray([3, 4, 5])}
  56. d = read_2column_text(path)
  57. # Using for-loop instead of dict-comprehension for debuggability
  58. retval = {}
  59. for k, v in d.items():
  60. try:
  61. retval[k] = [dtype(i) for i in v.split(delimiter)]
  62. except TypeError:
  63. logging.error(f'Error happened with path="{path}", id="{k}", value="{v}"')
  64. raise
  65. return retval