video_classification.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # Copyright 2024 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 warnings
  15. from io import BytesIO
  16. from typing import Any, Optional, Union, overload
  17. import requests
  18. from ..utils import (
  19. add_end_docstrings,
  20. is_av_available,
  21. is_torch_available,
  22. logging,
  23. requires_backends,
  24. )
  25. from .base import Pipeline, build_pipeline_init_args
  26. if is_av_available():
  27. import av
  28. import numpy as np
  29. if is_torch_available():
  30. from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES
  31. logger = logging.get_logger(__name__)
  32. @add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
  33. class VideoClassificationPipeline(Pipeline):
  34. """
  35. Video classification pipeline using any `AutoModelForVideoClassification`. This pipeline predicts the class of a
  36. video.
  37. This video classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  38. `"video-classification"`.
  39. See the list of available models on
  40. [huggingface.co/models](https://huggingface.co/models?filter=video-classification).
  41. """
  42. _load_processor = False
  43. _load_image_processor = True
  44. _load_feature_extractor = False
  45. _load_tokenizer = False
  46. def __init__(self, *args, **kwargs):
  47. super().__init__(*args, **kwargs)
  48. requires_backends(self, "av")
  49. self.check_model_type(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES)
  50. def _sanitize_parameters(self, top_k=None, num_frames=None, frame_sampling_rate=None, function_to_apply=None):
  51. preprocess_params = {}
  52. if frame_sampling_rate is not None:
  53. preprocess_params["frame_sampling_rate"] = frame_sampling_rate
  54. if num_frames is not None:
  55. preprocess_params["num_frames"] = num_frames
  56. postprocess_params = {}
  57. if top_k is not None:
  58. postprocess_params["top_k"] = top_k
  59. if function_to_apply is not None:
  60. if function_to_apply not in ["softmax", "sigmoid", "none"]:
  61. raise ValueError(
  62. f"Invalid value for `function_to_apply`: {function_to_apply}. "
  63. "Valid options are ['softmax', 'sigmoid', 'none']"
  64. )
  65. postprocess_params["function_to_apply"] = function_to_apply
  66. else:
  67. postprocess_params["function_to_apply"] = "softmax"
  68. return preprocess_params, {}, postprocess_params
  69. @overload
  70. def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ...
  71. @overload
  72. def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
  73. def __call__(self, inputs: Optional[Union[str, list[str]]] = None, **kwargs):
  74. """
  75. Assign labels to the video(s) passed as inputs.
  76. Args:
  77. inputs (`str`, `list[str]`):
  78. The pipeline handles three types of videos:
  79. - A string containing a http link pointing to a video
  80. - A string containing a local path to a video
  81. The pipeline accepts either a single video or a batch of videos, which must then be passed as a string.
  82. Videos in a batch must all be in the same format: all as http links or all as local paths.
  83. top_k (`int`, *optional*, defaults to 5):
  84. The number of top labels that will be returned by the pipeline. If the provided number is higher than
  85. the number of labels available in the model configuration, it will default to the number of labels.
  86. num_frames (`int`, *optional*, defaults to `self.model.config.num_frames`):
  87. The number of frames sampled from the video to run the classification on. If not provided, will default
  88. to the number of frames specified in the model configuration.
  89. frame_sampling_rate (`int`, *optional*, defaults to 1):
  90. The sampling rate used to select frames from the video. If not provided, will default to 1, i.e. every
  91. frame will be used.
  92. function_to_apply(`str`, *optional*, defaults to "softmax"):
  93. The function to apply to the model output. By default, the pipeline will apply the softmax function to
  94. the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
  95. built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
  96. post-processing.
  97. Return:
  98. A list of dictionaries or a list of list of dictionaries containing result. If the input is a single video,
  99. will return a list of `top_k` dictionaries, if the input is a list of several videos, will return a list of list of
  100. `top_k` dictionaries corresponding to the videos.
  101. The dictionaries contain the following keys:
  102. - **label** (`str`) -- The label identified by the model.
  103. - **score** (`int`) -- The score attributed by the model for that label.
  104. """
  105. # After deprecation of this is completed, remove the default `None` value for `images`
  106. if "videos" in kwargs:
  107. warnings.warn(
  108. "The `videos` argument has been renamed to `inputs`. In version 5 of Transformers, `videos` will no longer be accepted",
  109. FutureWarning,
  110. )
  111. inputs = kwargs.pop("videos")
  112. if inputs is None:
  113. raise ValueError("Cannot call the video-classification pipeline without an inputs argument!")
  114. return super().__call__(inputs, **kwargs)
  115. def preprocess(self, video, num_frames=None, frame_sampling_rate=1):
  116. if num_frames is None:
  117. num_frames = self.model.config.num_frames
  118. if video.startswith("http://") or video.startswith("https://"):
  119. video = BytesIO(requests.get(video).content)
  120. container = av.open(video)
  121. start_idx = 0
  122. end_idx = num_frames * frame_sampling_rate - 1
  123. indices = np.linspace(start_idx, end_idx, num=num_frames, dtype=np.int64)
  124. video = read_video_pyav(container, indices)
  125. video = list(video)
  126. model_inputs = self.image_processor(video, return_tensors=self.framework)
  127. if self.framework == "pt":
  128. model_inputs = model_inputs.to(self.dtype)
  129. return model_inputs
  130. def _forward(self, model_inputs):
  131. model_outputs = self.model(**model_inputs)
  132. return model_outputs
  133. def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"):
  134. if top_k > self.model.config.num_labels:
  135. top_k = self.model.config.num_labels
  136. if self.framework == "pt":
  137. if function_to_apply == "softmax":
  138. probs = model_outputs.logits[0].softmax(-1)
  139. elif function_to_apply == "sigmoid":
  140. probs = model_outputs.logits[0].sigmoid()
  141. else:
  142. probs = model_outputs.logits[0]
  143. scores, ids = probs.topk(top_k)
  144. else:
  145. raise ValueError(f"Unsupported framework: {self.framework}")
  146. scores = scores.tolist()
  147. ids = ids.tolist()
  148. return [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
  149. def read_video_pyav(container, indices):
  150. frames = []
  151. container.seek(0)
  152. start_index = indices[0]
  153. end_index = indices[-1]
  154. for i, frame in enumerate(container.decode(video=0)):
  155. if i > end_index:
  156. break
  157. if i >= start_index and i in indices:
  158. frames.append(frame)
  159. return np.stack([x.to_ndarray(format="rgb24") for x in frames])