npy_scp.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import collections.abc
  2. from pathlib import Path
  3. from typing import Union
  4. import numpy as np
  5. from typeguard import check_argument_types
  6. from funasr.fileio.read_text import read_2column_text
  7. class NpyScpWriter:
  8. """Writer class for a scp file of numpy file.
  9. Examples:
  10. key1 /some/path/a.npy
  11. key2 /some/path/b.npy
  12. key3 /some/path/c.npy
  13. key4 /some/path/d.npy
  14. ...
  15. >>> writer = NpyScpWriter('./data/', './data/feat.scp')
  16. >>> writer['aa'] = numpy_array
  17. >>> writer['bb'] = numpy_array
  18. """
  19. def __init__(self, outdir: Union[Path, str], scpfile: Union[Path, str]):
  20. assert check_argument_types()
  21. self.dir = Path(outdir)
  22. self.dir.mkdir(parents=True, exist_ok=True)
  23. scpfile = Path(scpfile)
  24. scpfile.parent.mkdir(parents=True, exist_ok=True)
  25. self.fscp = scpfile.open("w", encoding="utf-8")
  26. self.data = {}
  27. def get_path(self, key):
  28. return self.data[key]
  29. def __setitem__(self, key, value):
  30. assert isinstance(value, np.ndarray), type(value)
  31. p = self.dir / f"{key}.npy"
  32. p.parent.mkdir(parents=True, exist_ok=True)
  33. np.save(str(p), value)
  34. self.fscp.write(f"{key} {p}\n")
  35. # Store the file path
  36. self.data[key] = str(p)
  37. def __enter__(self):
  38. return self
  39. def __exit__(self, exc_type, exc_val, exc_tb):
  40. self.close()
  41. def close(self):
  42. self.fscp.close()
  43. class NpyScpReader(collections.abc.Mapping):
  44. """Reader class for a scp file of numpy file.
  45. Examples:
  46. key1 /some/path/a.npy
  47. key2 /some/path/b.npy
  48. key3 /some/path/c.npy
  49. key4 /some/path/d.npy
  50. ...
  51. >>> reader = NpyScpReader('npy.scp')
  52. >>> array = reader['key1']
  53. """
  54. def __init__(self, fname: Union[Path, str]):
  55. assert check_argument_types()
  56. self.fname = Path(fname)
  57. self.data = read_2column_text(fname)
  58. def get_path(self, key):
  59. return self.data[key]
  60. def __getitem__(self, key) -> np.ndarray:
  61. p = self.data[key]
  62. return np.load(p)
  63. def __contains__(self, item):
  64. return item
  65. def __len__(self):
  66. return len(self.data)
  67. def __iter__(self):
  68. return iter(self.data)
  69. def keys(self):
  70. return self.data.keys()