
from io import BytesIO
from typing import List, Union

import requests

from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_decord_available():
 import numpy as np
 from decord import VideoReader


if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING

__lowerCAmelCase    :	str						=						logging.get_logger(__name__)


@add_end_docstrings(UpperCamelCase__					)
class   __lowerCAmelCase		(		UpperCamelCase__					):



      """simple docstring"""







      def __init__(					self						:				Optional[Any] ,				*_snake_case						:				Optional[Any] ,				**_snake_case						:				List[Any] ):
          super().__init__(*lowerCAmelCase__ ,				**lowerCAmelCase__ )
          requires_backends(self ,				'''decord''' )
          self.check_model_type(lowerCAmelCase__ )




      def 						snake_case_	(					self						:				List[Any] ,				_snake_case						:				List[str]=None ,				_snake_case						:				Dict=None ,				_snake_case						:				Union[str, Any]=None ):
          __lowercase						:	int					=				{}
          if frame_sampling_rate is not None:
              __lowercase						:	Dict					=				frame_sampling_rate
          if num_frames is not None:
              __lowercase						:	List[str]					=				num_frames

          __lowercase						:	str					=				{}
          if top_k is not None:
              __lowercase						:	Optional[int]					=				top_k
          return preprocess_params, {}, postprocess_params




      def __call__(					self						:				Dict ,				_snake_case						:				Any ,				**_snake_case						:				int ):
          return super().__call__(lowerCAmelCase__ ,				**lowerCAmelCase__ )




      def 						snake_case_	(					self						:				int ,				_snake_case						:				Optional[int] ,				_snake_case						:				Dict=None ,				_snake_case						:				Union[str, Any]=1 ):




          if num_frames is None:
              __lowercase						:	Any					=				self.model.config.num_frames

          if video.startswith('''http://''' ) or video.startswith('''https://''' ):
              __lowercase						:	Any					=				BytesIO(requests.get(lowerCAmelCase__ ).content )

          __lowercase						:	str					=				VideoReader(lowerCAmelCase__ )
          videoreader.seek(0 )

          __lowercase						:	Optional[Any]					=				0
          __lowercase						:	str					=				num_frames * frame_sampling_rate - 1
          __lowercase						:	Union[str, Any]					=				np.linspace(lowerCAmelCase__ ,				lowerCAmelCase__ ,				num=lowerCAmelCase__ ,				dtype=np.intaa )

          __lowercase						:	List[Any]					=				videoreader.get_batch(lowerCAmelCase__ ).asnumpy()
          __lowercase						:	Tuple					=				list(lowerCAmelCase__ )

          __lowercase						:	Dict					=				self.image_processor(lowerCAmelCase__ ,				return_tensors=self.framework )
          return model_inputs




      def 						snake_case_	(					self						:				List[str] ,				_snake_case						:				Optional[Any] ):
          __lowercase						:	Tuple					=				self.model(**lowerCAmelCase__ )
          return model_outputs




      def 						snake_case_	(					self						:				Optional[Any] ,				_snake_case						:				int ,				_snake_case						:				Dict=5 ):




          if top_k > self.model.config.num_labels:
              __lowercase						:	Dict					=				self.model.config.num_labels

          if self.framework == "pt":
              __lowercase						:	Tuple					=				model_outputs.logits.softmax(-1 )[0]
              __lowercase						:	Any					=				probs.topk(lowerCAmelCase__ )
          else:
              raise ValueError(F'Unsupported framework: {self.framework}' )

          __lowercase						:	Optional[int]					=				scores.tolist()
          __lowercase						:	Dict					=				ids.tolist()
          return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowerCAmelCase__ ,				lowerCAmelCase__ )]









def      _A       (		SCREAMING_SNAKE_CASE     :   list						):





  """simple docstring"""



  if not isinstance(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						):
    raise ValueError("Input series is not valid, valid series - [2, 4, 6]"						)
  if len(SCREAMING_SNAKE_CASE						) == 0:
    raise ValueError("Input list must be a non empty list"						)
  if len(SCREAMING_SNAKE_CASE						) == 1:
    return True
  a__	:					Union[str, Any]										=series[1] - series[0]
  for index in range(len(SCREAMING_SNAKE_CASE						) - 1						):
    if series[index + 1] - series[index] != common_diff:
      return False
  return True
def      _A       (		SCREAMING_SNAKE_CASE     :   list						):





  """simple docstring"""



  if not isinstance(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						):
    raise ValueError("Input series is not valid, valid series - [2, 4, 6]"						)
  if len(SCREAMING_SNAKE_CASE						) == 0:
    raise ValueError("Input list must be a non empty list"						)
  a__	:					Any										=0
  for val in series:
    answer += val
  return answer / len(SCREAMING_SNAKE_CASE						)


if __name__ == "__main__":
     import doctest

     doctest.testmod()






