processing_clap.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # coding=utf-8
  2. # Copyright 2023 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """
  16. Audio/Text processor class for CLAP
  17. """
  18. from ...processing_utils import ProcessorMixin
  19. from ...tokenization_utils_base import BatchEncoding
  20. class ClapProcessor(ProcessorMixin):
  21. r"""
  22. Constructs a CLAP processor which wraps a CLAP feature extractor and a RoBerta tokenizer into a single processor.
  23. [`ClapProcessor`] offers all the functionalities of [`ClapFeatureExtractor`] and [`RobertaTokenizerFast`]. See the
  24. [`~ClapProcessor.__call__`] and [`~ClapProcessor.decode`] for more information.
  25. Args:
  26. feature_extractor ([`ClapFeatureExtractor`]):
  27. The audio processor is a required input.
  28. tokenizer ([`RobertaTokenizerFast`]):
  29. The tokenizer is a required input.
  30. """
  31. feature_extractor_class = "ClapFeatureExtractor"
  32. tokenizer_class = ("RobertaTokenizer", "RobertaTokenizerFast")
  33. def __init__(self, feature_extractor, tokenizer):
  34. super().__init__(feature_extractor, tokenizer)
  35. def __call__(self, text=None, audios=None, return_tensors=None, **kwargs):
  36. """
  37. Main method to prepare for the model one or several sequences(s) and audio(s). This method forwards the `text`
  38. and `kwargs` arguments to RobertaTokenizerFast's [`~RobertaTokenizerFast.__call__`] if `text` is not `None` to
  39. encode the text. To prepare the audio(s), this method forwards the `audios` and `kwrags` arguments to
  40. ClapFeatureExtractor's [`~ClapFeatureExtractor.__call__`] if `audios` is not `None`. Please refer to the
  41. doctsring of the above two methods for more information.
  42. Args:
  43. text (`str`, `List[str]`, `List[List[str]]`):
  44. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  45. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  46. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  47. audios (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
  48. The audio or batch of audios to be prepared. Each audio can be NumPy array or PyTorch tensor. In case
  49. of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels,
  50. and T the sample length of the audio.
  51. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  52. If set, will return tensors of a particular framework. Acceptable values are:
  53. - `'tf'`: Return TensorFlow `tf.constant` objects.
  54. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  55. - `'np'`: Return NumPy `np.ndarray` objects.
  56. - `'jax'`: Return JAX `jnp.ndarray` objects.
  57. Returns:
  58. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  59. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  60. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  61. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  62. `None`).
  63. - **audio_features** -- Audio features to be fed to a model. Returned when `audios` is not `None`.
  64. """
  65. sampling_rate = kwargs.pop("sampling_rate", None)
  66. if text is None and audios is None:
  67. raise ValueError("You have to specify either text or audios. Both cannot be none.")
  68. if text is not None:
  69. encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
  70. if audios is not None:
  71. audio_features = self.feature_extractor(
  72. audios, sampling_rate=sampling_rate, return_tensors=return_tensors, **kwargs
  73. )
  74. if text is not None and audios is not None:
  75. encoding.update(audio_features)
  76. return encoding
  77. elif text is not None:
  78. return encoding
  79. else:
  80. return BatchEncoding(data=dict(**audio_features), tensor_type=return_tensors)
  81. def batch_decode(self, *args, **kwargs):
  82. """
  83. This method forwards all its arguments to RobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  84. refer to the docstring of this method for more information.
  85. """
  86. return self.tokenizer.batch_decode(*args, **kwargs)
  87. def decode(self, *args, **kwargs):
  88. """
  89. This method forwards all its arguments to RobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer
  90. to the docstring of this method for more information.
  91. """
  92. return self.tokenizer.decode(*args, **kwargs)
  93. @property
  94. def model_input_names(self):
  95. tokenizer_input_names = self.tokenizer.model_input_names
  96. feature_extractor_input_names = self.feature_extractor.model_input_names
  97. return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names))