video_classification.py 7.4 KB

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