audio_classification.py 11 KB

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