init.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import itertools
  2. import pathlib
  3. import typing
  4. import numpy
  5. import scipy.io.wavfile
  6. def split_sequence_by_delimiter(
  7. sequence: typing.Sequence, delimiter: typing.Any, delimiter_min_length: int = 1
  8. ) -> typing.Iterator[typing.Sequence]:
  9. slice_start_index, slice_length = 0, 0
  10. for is_delimiter, group in itertools.groupby(
  11. sequence, key=lambda item: item == delimiter
  12. ):
  13. group_length = sum(1 for _ in group)
  14. if is_delimiter and group_length >= delimiter_min_length:
  15. if slice_length > 0:
  16. yield sequence[slice_start_index : slice_start_index + slice_length]
  17. slice_start_index += slice_length + group_length
  18. slice_length = 0
  19. else:
  20. slice_length += group_length
  21. if slice_length > 0:
  22. yield sequence[slice_start_index : slice_start_index + slice_length]
  23. def trim_where(
  24. # https://docs.python.org/3.8/library/collections.abc.html#collections-abstract-base-classes
  25. sequence: typing.Sequence,
  26. condition: typing.Sequence[bool],
  27. ) -> typing.Sequence:
  28. start = 0
  29. for item_condition in condition:
  30. if item_condition:
  31. start += 1
  32. else:
  33. break
  34. stop = len(sequence)
  35. assert stop == len(condition)
  36. for item_condition in condition[::-1]:
  37. if item_condition:
  38. stop -= 1
  39. else:
  40. break
  41. return sequence[start:stop]
  42. def wavfile_read_mono(
  43. path: typing.Union[pathlib.Path, str]
  44. ) -> typing.Tuple[int, numpy.ndarray]:
  45. # https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.read.html
  46. rate, data = scipy.io.wavfile.read(path)
  47. if len(data.shape) == 1:
  48. return rate, data
  49. data_first_channel = data[:, 0]
  50. for channel_index in range(1, data.shape[1]):
  51. assert (data_first_channel == data[:, channel_index]).all()
  52. return rate, data_first_channel