processing_musicgen.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. Text/audio processor class for MusicGen
  17. """
  18. from typing import Any
  19. import numpy as np
  20. from ...processing_utils import ProcessorMixin
  21. from ...utils import to_numpy
  22. class MusicgenProcessor(ProcessorMixin):
  23. r"""
  24. Constructs a MusicGen processor which wraps an EnCodec feature extractor and a T5 tokenizer into a single processor
  25. class.
  26. [`MusicgenProcessor`] offers all the functionalities of [`EncodecFeatureExtractor`] and [`TTokenizer`]. See
  27. [`~MusicgenProcessor.__call__`] and [`~MusicgenProcessor.decode`] for more information.
  28. Args:
  29. feature_extractor (`EncodecFeatureExtractor`):
  30. An instance of [`EncodecFeatureExtractor`]. The feature extractor is a required input.
  31. tokenizer (`T5Tokenizer`):
  32. An instance of [`T5Tokenizer`]. The tokenizer is a required input.
  33. """
  34. feature_extractor_class = "EncodecFeatureExtractor"
  35. tokenizer_class = ("T5Tokenizer", "T5TokenizerFast")
  36. def __init__(self, feature_extractor, tokenizer):
  37. super().__init__(feature_extractor, tokenizer)
  38. self.current_processor = self.feature_extractor
  39. self._in_target_context_manager = False
  40. def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
  41. return self.tokenizer.get_decoder_prompt_ids(task=task, language=language, no_timestamps=no_timestamps)
  42. def __call__(self, *args, **kwargs):
  43. """
  44. Forwards the `audio` argument to EncodecFeatureExtractor's [`~EncodecFeatureExtractor.__call__`] and the `text`
  45. argument to [`~T5Tokenizer.__call__`]. Please refer to the docstring of the above two methods for more
  46. information.
  47. """
  48. # For backward compatibility
  49. if self._in_target_context_manager:
  50. return self.current_processor(*args, **kwargs)
  51. if len(args) > 0:
  52. kwargs["audio"] = args[0]
  53. return super().__call__(*args, **kwargs)
  54. def batch_decode(self, *args, **kwargs):
  55. """
  56. This method is used to decode either batches of audio outputs from the MusicGen model, or batches of token ids
  57. from the tokenizer. In the case of decoding token ids, this method forwards all its arguments to T5Tokenizer's
  58. [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information.
  59. """
  60. audio_values = kwargs.pop("audio", None)
  61. padding_mask = kwargs.pop("padding_mask", None)
  62. if len(args) > 0:
  63. audio_values = args[0]
  64. args = args[1:]
  65. if audio_values is not None:
  66. return self._decode_audio(audio_values, padding_mask=padding_mask)
  67. else:
  68. return self.tokenizer.batch_decode(*args, **kwargs)
  69. def _decode_audio(self, audio_values, padding_mask: Any = None) -> list[np.ndarray]:
  70. """
  71. This method strips any padding from the audio values to return a list of numpy audio arrays.
  72. """
  73. audio_values = to_numpy(audio_values)
  74. bsz, channels, seq_len = audio_values.shape
  75. if padding_mask is None:
  76. return list(audio_values)
  77. padding_mask = to_numpy(padding_mask)
  78. # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
  79. # token (so that the generated audio values are **not** treated as padded tokens)
  80. difference = seq_len - padding_mask.shape[-1]
  81. padding_value = 1 - self.feature_extractor.padding_value
  82. padding_mask = np.pad(padding_mask, ((0, 0), (0, difference)), "constant", constant_values=padding_value)
  83. audio_values = audio_values.tolist()
  84. for i in range(bsz):
  85. sliced_audio = np.asarray(audio_values[i])[
  86. padding_mask[i][None, :] != self.feature_extractor.padding_value
  87. ]
  88. audio_values[i] = sliced_audio.reshape(channels, -1)
  89. return audio_values
  90. __all__ = ["MusicgenProcessor"]