


'''simple docstring'''



from importlib import import_module

from .logging import get_logger


__lowercase	:						Tuple       =	get_logger(__name__)





class 							__UpperCamelCase				:




	def __init__(   self						,				__a						,				__a=None							):

						'''simple docstring'''





						__a			:       List[Any]					    =  attrs or []
						if module is not None:
											for key in module.__dict__:
																if key in attrs or not key.startswith('__'							):
																					setattr(self						,				__a						,				getattr(__a						,				__a							)							)
						__a			:       Dict					    =  module._original_module if isinstance(__a						,				_PatchedModuleObj							) else module





class 							__UpperCamelCase				:
	A_				=    []




	def __init__(   self						,				__a						,				__a						,				__a						,				__a=None							):

						'''simple docstring'''





						__a			:       int					    =  obj
						__a			:       Union[str, Any]					    =  target
						__a			:       int					    =  new
						__a			:       Dict					    =  target.split('.'							)[0]
						__a			:       Any					    =  {}
						__a			:       Any					    =  attrs or []




	def __enter__(   self							):

						'''simple docstring'''





						*__a    ,				__a			:       Dict					    =  self.target.split('.'							)

						# Patch modules:
						# it's used to patch attributes of submodules like "os.path.join";
						# in this case we need to patch "os" and "os.path"

						for i in range(len(__a							)							):
											try:
																__a			:       str					    =  import_module('.'.join(submodules[: i + 1]							)							)
											except ModuleNotFoundError:
																continue
											# We iterate over all the globals in self.obj in case we find "os" or "os.path"
											for attr in self.obj.__dir__():
																__a			:       Optional[int]					    =  getattr(self.obj						,				__a							)
																# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																# This allows to patch renamed modules like "from os import path as ospath".
																if obj_attr is submodule or (
																    (isinstance(__a						,				_PatchedModuleObj							) and obj_attr._original_module is submodule)
																):
																					__a			:       List[str]					    =  obj_attr
																					# patch at top level
																					setattr(self.obj						,				__a						,				_PatchedModuleObj(__a						,				attrs=self.attrs							)							)
																					__a			:       List[str]					    =  getattr(self.obj						,				__a							)
																					# construct lower levels patches
																					for key in submodules[i + 1 :]:
																										setattr(__a						,				__a						,				_PatchedModuleObj(getattr(__a						,				__a						,				__a							)						,				attrs=self.attrs							)							)
																										__a			:       str					    =  getattr(__a						,				__a							)
																					# finally set the target attribute
																					setattr(__a						,				__a						,				self.new							)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

						if submodules:  # if it's an attribute of a submodule like "os.path.join"
											try:
																__a			:       Any					    =  getattr(import_module('.'.join(__a							)							)						,				__a							)
											except (AttributeError, ModuleNotFoundError):
																return
											# We iterate over all the globals in self.obj in case we find "os.path.join"
											for attr in self.obj.__dir__():
																# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																# This allows to patch renamed attributes like "from os.path import join as pjoin".
																if getattr(self.obj						,				__a							) is attr_value:
																					__a			:       List[Any]					    =  getattr(self.obj						,				__a							)
																					setattr(self.obj						,				__a						,				self.new							)
						elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
											__a			:       str					    =  globals()['__builtins__'][target_attr]
											setattr(self.obj						,				__a						,				self.new							)
						else:
											raise RuntimeError(f"""Tried to patch attribute {target_attr} instead of a submodule."""							)




	def __exit__(   self						,				*__a							):

						'''simple docstring'''





						for attr in list(self.original							):
											setattr(self.obj						,				__a						,				self.original.pop(__a							)							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						self.__enter__()
						self._active_patches.append(self							)





	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						try:
											self._active_patches.remove(self							)
						except ValueError:
											# If the patch hasn't been started this will fail
											return None

						return self.__exit__()








'''simple docstring'''


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	:       Any      	=	logging.get_logger(__name__)

@add_end_docstrings(_a		)
class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    def __init__(  self      :					Any  ,						*UpperCamelCase__      :					Dict  ,						**UpperCamelCase__      :					Union[str, Any] ):


       """simple docstring"""







       super().__init__(*UpperCamelCase__  ,						**UpperCamelCase__ )
       requires_backends(self  ,						'decord' )
       self.check_model_type(UpperCamelCase__ )






    def  A       (  self      :					Optional[int]  ,						UpperCamelCase__      :					Optional[int]=None  ,						UpperCamelCase__      :					Optional[Any]=None  ,						UpperCamelCase__      :					Optional[Any]=None ):


       """simple docstring"""







       UpperCamelCase					=  {}
       if frame_sampling_rate is not None:
          UpperCamelCase					=  frame_sampling_rate
       if num_frames is not None:
          UpperCamelCase					=  num_frames

       UpperCamelCase					=  {}
       if top_k is not None:
          UpperCamelCase					=  top_k
       return preprocess_params, {}, postprocess_params






    def __call__(  self      :					List[str]  ,						UpperCamelCase__      :					Union[str, List[str]]  ,						**UpperCamelCase__      :					Dict ):


       """simple docstring"""







       return super().__call__(UpperCamelCase__  ,						**UpperCamelCase__ )






    def  A       (  self      :					Tuple  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Tuple=None  ,						UpperCamelCase__      :					Tuple=1 ):


       """simple docstring"""







       if num_frames is None:
          UpperCamelCase					=  self.model.config.num_frames

       if video.startswith('http://' ) or video.startswith('https://' ):
          UpperCamelCase					=  BytesIO(requests.get(UpperCamelCase__ ).content )

       UpperCamelCase					=  VideoReader(UpperCamelCase__ )
       videoreader.seek(0 )

       UpperCamelCase					=  0
       UpperCamelCase					=  num_frames * frame_sampling_rate - 1
       UpperCamelCase					=  np.linspace(UpperCamelCase__  ,						UpperCamelCase__  ,						num=UpperCamelCase__  ,						dtype=np.intaa )

       UpperCamelCase					=  videoreader.get_batch(UpperCamelCase__ ).asnumpy()
       UpperCamelCase					=  list(UpperCamelCase__ )

       UpperCamelCase					=  self.image_processor(UpperCamelCase__  ,						return_tensors=self.framework )
       return model_inputs






    def  A       (  self      :					Union[str, Any]  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  self.model(**UpperCamelCase__ )
       return model_outputs






    def  A       (  self      :					int  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					List[Any]=5 ):


       """simple docstring"""







       if top_k > self.model.config.num_labels:
          UpperCamelCase					=  self.model.config.num_labels

       if self.framework == "pt":
          UpperCamelCase					=  model_outputs.logits.softmax(-1 )[0]
          UpperCamelCase				,      UpperCamelCase					=  probs.topk(UpperCamelCase__ )
       else:
          raise ValueError(f"""Unsupported framework: {self.framework}""" )

       UpperCamelCase					=  scores.tolist()
       UpperCamelCase					=  ids.tolist()
       return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase__  ,						UpperCamelCase__ )]

