processing_wav2vec2.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # Copyright 2021 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Speech processor class for Wav2Vec2
  16. """
  17. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  18. from ...tokenization_utils_base import AudioInput, PreTokenizedInput, TextInput
  19. from ...utils import auto_docstring
  20. class Wav2Vec2ProcessorKwargs(ProcessingKwargs, total=False):
  21. _defaults = {}
  22. @auto_docstring
  23. class Wav2Vec2Processor(ProcessorMixin):
  24. def __init__(self, feature_extractor, tokenizer):
  25. super().__init__(feature_extractor, tokenizer)
  26. @auto_docstring
  27. def __call__(
  28. self,
  29. audio: AudioInput | None = None,
  30. text: str | list[str] | TextInput | PreTokenizedInput | None = None,
  31. **kwargs: Unpack[Wav2Vec2ProcessorKwargs],
  32. ):
  33. r"""
  34. Returns:
  35. This method returns the results of each `call` method. If both are used, the output is a dictionary containing the results of both.
  36. """
  37. if audio is None and text is None:
  38. raise ValueError("You need to specify either an `audio` or `text` input to process.")
  39. output_kwargs = self._merge_kwargs(
  40. Wav2Vec2ProcessorKwargs,
  41. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  42. **kwargs,
  43. )
  44. if audio is not None:
  45. inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
  46. if text is not None:
  47. encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
  48. if text is None:
  49. return inputs
  50. elif audio is None:
  51. return encodings
  52. else:
  53. inputs["labels"] = encodings["input_ids"]
  54. return inputs
  55. def pad(self, *args, **kwargs):
  56. """
  57. This method operates on batches of extracted features and/or tokenized text. It forwards all arguments to
  58. [`Wav2Vec2FeatureExtractor.pad`] and/or [`PreTrainedTokenizer.pad`] depending on the input modality and returns their outputs. If both modalities are passed, [`Wav2Vec2FeatureExtractor.pad`] and [`PreTrainedTokenizer.pad`] are called.
  59. Args:
  60. input_features:
  61. When the first argument is a dictionary containing a batch of tensors, or the `input_features` argument is present, it is passed to [`Wav2Vec2FeatureExtractor.pad`].
  62. labels:
  63. When the `label` argument is present, it is passed to [`PreTrainedTokenizer.pad`].
  64. Returns:
  65. This method returns the results of each `pad` method. If both are used, the output is a dictionary containing the results of both.
  66. """
  67. input_features = kwargs.pop("input_features", None)
  68. labels = kwargs.pop("labels", None)
  69. if len(args) > 0:
  70. input_features = args[0]
  71. args = args[1:]
  72. if input_features is not None:
  73. input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
  74. if labels is not None:
  75. labels = self.tokenizer.pad(labels, **kwargs)
  76. if labels is None:
  77. return input_features
  78. elif input_features is None:
  79. return labels
  80. else:
  81. input_features["labels"] = labels["input_ids"]
  82. return input_features
  83. @property
  84. def model_input_names(self):
  85. # The processor doesn't return text ids and the model seems to not need them
  86. feature_extractor_input_names = self.feature_extractor.model_input_names
  87. return feature_extractor_input_names + ["labels"]
  88. __all__ = ["Wav2Vec2Processor"]