audio_classification.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # Copyright 2021 The HuggingFace Team. All rights reserved.
  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. import subprocess
  15. from typing import Any, Union
  16. import numpy as np
  17. import requests
  18. from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, is_torchcodec_available, logging
  19. from .base import Pipeline, build_pipeline_init_args
  20. if is_torch_available():
  21. from ..models.auto.modeling_auto import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
  22. logger = logging.get_logger(__name__)
  23. def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.ndarray:
  24. """
  25. Helper function to read an audio file through ffmpeg.
  26. """
  27. ar = f"{sampling_rate}"
  28. ac = "1"
  29. format_for_conversion = "f32le"
  30. ffmpeg_command = [
  31. "ffmpeg",
  32. "-i",
  33. "pipe:0",
  34. "-ac",
  35. ac,
  36. "-ar",
  37. ar,
  38. "-f",
  39. format_for_conversion,
  40. "-hide_banner",
  41. "-loglevel",
  42. "quiet",
  43. "pipe:1",
  44. ]
  45. try:
  46. ffmpeg_process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  47. except FileNotFoundError:
  48. raise ValueError("ffmpeg was not found but is required to load audio files from filename")
  49. output_stream = ffmpeg_process.communicate(bpayload)
  50. out_bytes = output_stream[0]
  51. audio = np.frombuffer(out_bytes, np.float32)
  52. if audio.shape[0] == 0:
  53. raise ValueError("Malformed soundfile")
  54. return audio
  55. @add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True))
  56. class AudioClassificationPipeline(Pipeline):
  57. """
  58. Audio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a
  59. raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio
  60. formats.
  61. Example:
  62. ```python
  63. >>> from transformers import pipeline
  64. >>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks")
  65. >>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
  66. [{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]
  67. ```
  68. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  69. This pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  70. `"audio-classification"`.
  71. See the list of available models on
  72. [huggingface.co/models](https://huggingface.co/models?filter=audio-classification).
  73. """
  74. _load_processor = False
  75. _load_image_processor = False
  76. _load_feature_extractor = True
  77. _load_tokenizer = False
  78. def __init__(self, *args, **kwargs):
  79. # Only set default top_k if explicitly provided
  80. if "top_k" in kwargs and kwargs["top_k"] is None:
  81. kwargs["top_k"] = None
  82. elif "top_k" not in kwargs:
  83. kwargs["top_k"] = 5
  84. super().__init__(*args, **kwargs)
  85. if self.framework != "pt":
  86. raise ValueError(f"The {self.__class__} is only available in PyTorch.")
  87. self.check_model_type(MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES)
  88. def __call__(self, inputs: Union[np.ndarray, bytes, str, dict], **kwargs: Any) -> list[dict[str, Any]]:
  89. """
  90. Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
  91. information.
  92. Args:
  93. inputs (`np.ndarray` or `bytes` or `str` or `dict`):
  94. The inputs is either :
  95. - `str` that is the filename of the audio file, the file will be read at the correct sampling rate
  96. to get the waveform using *ffmpeg*. This requires *ffmpeg* to be installed on the system.
  97. - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the
  98. same way.
  99. - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)
  100. Raw audio at the correct sampling rate (no further check will be done)
  101. - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this
  102. pipeline do the resampling. The dict must be either be in the format `{"sampling_rate": int,
  103. "raw": np.array}`, or `{"sampling_rate": int, "array": np.array}`, where the key `"raw"` or
  104. `"array"` is used to denote the raw audio waveform.
  105. top_k (`int`, *optional*, defaults to None):
  106. The number of top labels that will be returned by the pipeline. If the provided number is `None` or
  107. higher than the number of labels available in the model configuration, it will default to the number of
  108. labels.
  109. function_to_apply(`str`, *optional*, defaults to "softmax"):
  110. The function to apply to the model output. By default, the pipeline will apply the softmax function to
  111. the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
  112. built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
  113. post-processing.
  114. Return:
  115. A list of `dict` with the following keys:
  116. - **label** (`str`) -- The label predicted.
  117. - **score** (`float`) -- The corresponding probability.
  118. """
  119. return super().__call__(inputs, **kwargs)
  120. def _sanitize_parameters(self, top_k=None, function_to_apply=None, **kwargs):
  121. postprocess_params = {}
  122. # If top_k is None, use all labels
  123. if top_k is None:
  124. postprocess_params["top_k"] = self.model.config.num_labels
  125. else:
  126. if top_k > self.model.config.num_labels:
  127. top_k = self.model.config.num_labels
  128. postprocess_params["top_k"] = top_k
  129. if function_to_apply is not None:
  130. if function_to_apply not in ["softmax", "sigmoid", "none"]:
  131. raise ValueError(
  132. f"Invalid value for `function_to_apply`: {function_to_apply}. "
  133. "Valid options are ['softmax', 'sigmoid', 'none']"
  134. )
  135. postprocess_params["function_to_apply"] = function_to_apply
  136. else:
  137. postprocess_params["function_to_apply"] = "softmax"
  138. return {}, {}, postprocess_params
  139. def preprocess(self, inputs):
  140. if isinstance(inputs, str):
  141. if inputs.startswith("http://") or inputs.startswith("https://"):
  142. # We need to actually check for a real protocol, otherwise it's impossible to use a local file
  143. # like http_huggingface_co.png
  144. inputs = requests.get(inputs).content
  145. else:
  146. with open(inputs, "rb") as f:
  147. inputs = f.read()
  148. if isinstance(inputs, bytes):
  149. inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate)
  150. if is_torch_available():
  151. import torch
  152. if isinstance(inputs, torch.Tensor):
  153. inputs = inputs.cpu().numpy()
  154. if is_torchcodec_available():
  155. import torch
  156. import torchcodec
  157. if isinstance(inputs, torchcodec.decoders.AudioDecoder):
  158. _audio_samples = inputs.get_all_samples()
  159. _array = _audio_samples.data
  160. inputs = {"array": _array, "sampling_rate": _audio_samples.sample_rate}
  161. if isinstance(inputs, dict):
  162. inputs = inputs.copy() # So we don't mutate the original dictionary outside the pipeline
  163. # Accepting `"array"` which is the key defined in `datasets` for
  164. # better integration
  165. if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
  166. raise ValueError(
  167. "When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a "
  168. '"raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, '
  169. "containing the sampling_rate associated with that array"
  170. )
  171. _inputs = inputs.pop("raw", None)
  172. if _inputs is None:
  173. # Remove path which will not be used from `datasets`.
  174. inputs.pop("path", None)
  175. _inputs = inputs.pop("array", None)
  176. in_sampling_rate = inputs.pop("sampling_rate")
  177. inputs = _inputs
  178. if in_sampling_rate != self.feature_extractor.sampling_rate:
  179. import torch
  180. if is_torchaudio_available():
  181. from torchaudio import functional as F
  182. else:
  183. raise ImportError(
  184. "torchaudio is required to resample audio samples in AudioClassificationPipeline. "
  185. "The torchaudio package can be installed through: `pip install torchaudio`."
  186. )
  187. inputs = F.resample(
  188. torch.from_numpy(inputs) if isinstance(inputs, np.ndarray) else inputs,
  189. in_sampling_rate,
  190. self.feature_extractor.sampling_rate,
  191. ).numpy()
  192. if not isinstance(inputs, np.ndarray):
  193. raise TypeError("We expect a numpy ndarray or torch tensor as input")
  194. if len(inputs.shape) != 1:
  195. raise ValueError("We expect a single channel audio input for AudioClassificationPipeline")
  196. processed = self.feature_extractor(
  197. inputs, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"
  198. )
  199. if self.dtype is not None:
  200. processed = processed.to(dtype=self.dtype)
  201. return processed
  202. def _forward(self, model_inputs):
  203. model_outputs = self.model(**model_inputs)
  204. return model_outputs
  205. def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"):
  206. if function_to_apply == "softmax":
  207. probs = model_outputs.logits[0].softmax(-1)
  208. elif function_to_apply == "sigmoid":
  209. probs = model_outputs.logits[0].sigmoid()
  210. else:
  211. probs = model_outputs.logits[0]
  212. scores, ids = probs.topk(top_k)
  213. scores = scores.tolist()
  214. ids = ids.tolist()
  215. labels = [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
  216. return labels