processing_whisper.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2022 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 Whisper
  16. """
  17. from ...processing_utils import ProcessorMixin
  18. from ...utils import auto_docstring
  19. @auto_docstring
  20. class WhisperProcessor(ProcessorMixin):
  21. def __init__(self, feature_extractor, tokenizer):
  22. super().__init__(feature_extractor, tokenizer)
  23. def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
  24. return self.tokenizer.get_decoder_prompt_ids(task=task, language=language, no_timestamps=no_timestamps)
  25. @auto_docstring
  26. def __call__(self, *args, **kwargs):
  27. audio = kwargs.pop("audio", None)
  28. sampling_rate = kwargs.pop("sampling_rate", None)
  29. text = kwargs.pop("text", None)
  30. if len(args) > 0:
  31. audio = args[0]
  32. args = args[1:]
  33. if audio is None and text is None:
  34. raise ValueError("You need to specify either an `audio` or `text` input to process.")
  35. if audio is not None:
  36. inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
  37. if text is not None:
  38. encodings = self.tokenizer(text, **kwargs)
  39. if text is None:
  40. return inputs
  41. elif audio is None:
  42. return encodings
  43. else:
  44. inputs["labels"] = encodings["input_ids"]
  45. return inputs
  46. def get_prompt_ids(self, text: str, return_tensors="np"):
  47. return self.tokenizer.get_prompt_ids(text, return_tensors=return_tensors)
  48. __all__ = ["WhisperProcessor"]