
from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


lowerCamelCase	   =logging.get_logger(__name__)

# General docstring
lowerCamelCase	   ="ResNetConfig"

# Base docstring
lowerCamelCase	   ="microsoft/resnet-50"
lowerCamelCase	   =[1, 2_0_4_8, 7, 7]

# Image classification docstring
lowerCamelCase	   ="microsoft/resnet-50"
lowerCamelCase	   ="tiger cat"

lowerCamelCase	   =[
    "microsoft/resnet-50",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]




class 				_lowerCamelCase (      nn.Module ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = 3						,						__SCREAMING_SNAKE_CASE = 1						,						__SCREAMING_SNAKE_CASE = "relu"  )  ->   Tuple:




           """simple docstring"""







           super().__init__()
           UpperCamelCase__    :   Union[str, Any]					=				nn.Convad(
               UpperCamelCase_						,						UpperCamelCase_						,						kernel_size=UpperCamelCase_						,						stride=UpperCamelCase_						,						padding=kernel_size // 2						,						bias=UpperCamelCase_  )
           UpperCamelCase__    :   Optional[int]					=				nn.BatchNormad(UpperCamelCase_  )
           UpperCamelCase__    :   List[Any]					=				ACTaFN[activation] if activation is not None else nn.Identity()






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   List[str]:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				self.convolution(UpperCamelCase_  )
           UpperCamelCase__    :   Tuple					=				self.normalization(UpperCamelCase_  )
           UpperCamelCase__    :   List[Any]					=				self.activation(UpperCamelCase_  )
           return hidden_state




class 				_lowerCamelCase (      nn.Module ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Dict:




           """simple docstring"""







           super().__init__()
           UpperCamelCase__    :   str					=				ResNetConvLayer(
               config.num_channels						,						config.embedding_size						,						kernel_size=7						,						stride=2						,						activation=config.hidden_act  )
           UpperCamelCase__    :   Dict					=				nn.MaxPoolad(kernel_size=3						,						stride=2						,						padding=1  )
           UpperCamelCase__    :   str					=				config.num_channels






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   str:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				pixel_values.shape[1]
           if num_channels != self.num_channels:
                 raise ValueError(
                     '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.'''  )
           UpperCamelCase__    :   Optional[Any]					=				self.embedder(UpperCamelCase_  )
           UpperCamelCase__    :   Any					=				self.pooler(UpperCamelCase_  )
           return embedding




class 				_lowerCamelCase (      nn.Module ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = 2  )  ->   List[Any]:




           """simple docstring"""







           super().__init__()
           UpperCamelCase__    :   str					=				nn.Convad(UpperCamelCase_						,						UpperCamelCase_						,						kernel_size=1						,						stride=UpperCamelCase_						,						bias=UpperCamelCase_  )
           UpperCamelCase__    :   Dict					=				nn.BatchNormad(UpperCamelCase_  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   str					=				self.convolution(UpperCamelCase_  )
           UpperCamelCase__    :   Union[str, Any]					=				self.normalization(UpperCamelCase_  )
           return hidden_state




class 				_lowerCamelCase (      nn.Module ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = 1						,						__SCREAMING_SNAKE_CASE = "relu"  )  ->   List[str]:




           """simple docstring"""







           super().__init__()
           UpperCamelCase__    :   List[Any]					=				in_channels != out_channels or stride != 1
           UpperCamelCase__    :   Any					=				(
               ResNetShortCut(UpperCamelCase_						,						UpperCamelCase_						,						stride=UpperCamelCase_  ) if should_apply_shortcut else nn.Identity()
           )
           UpperCamelCase__    :   Dict					=				nn.Sequential(
               ResNetConvLayer(UpperCamelCase_						,						UpperCamelCase_						,						stride=UpperCamelCase_  )						,						ResNetConvLayer(UpperCamelCase_						,						UpperCamelCase_						,						activation=UpperCamelCase_  )						,						)
           UpperCamelCase__    :   Dict					=				ACTaFN[activation]






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__    :   Dict					=				hidden_state
           UpperCamelCase__    :   int					=				self.layer(UpperCamelCase_  )
           UpperCamelCase__    :   Dict					=				self.shortcut(UpperCamelCase_  )
           hidden_state += residual
           UpperCamelCase__    :   str					=				self.activation(UpperCamelCase_  )
           return hidden_state




class 				_lowerCamelCase (      nn.Module ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = 1						,						__SCREAMING_SNAKE_CASE = "relu"						,						__SCREAMING_SNAKE_CASE = 4  )  ->   Dict:




           """simple docstring"""







           super().__init__()
           UpperCamelCase__    :   List[Any]					=				in_channels != out_channels or stride != 1
           UpperCamelCase__    :   Any					=				out_channels // reduction
           UpperCamelCase__    :   str					=				(
               ResNetShortCut(UpperCamelCase_						,						UpperCamelCase_						,						stride=UpperCamelCase_  ) if should_apply_shortcut else nn.Identity()
           )
           UpperCamelCase__    :   Any					=				nn.Sequential(
               ResNetConvLayer(UpperCamelCase_						,						UpperCamelCase_						,						kernel_size=1  )						,						ResNetConvLayer(UpperCamelCase_						,						UpperCamelCase_						,						stride=UpperCamelCase_  )						,						ResNetConvLayer(UpperCamelCase_						,						UpperCamelCase_						,						kernel_size=1						,						activation=UpperCamelCase_  )						,						)
           UpperCamelCase__    :   str					=				ACTaFN[activation]






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   str:




           """simple docstring"""







           UpperCamelCase__    :   List[Any]					=				hidden_state
           UpperCamelCase__    :   List[str]					=				self.layer(UpperCamelCase_  )
           UpperCamelCase__    :   Tuple					=				self.shortcut(UpperCamelCase_  )
           hidden_state += residual
           UpperCamelCase__    :   Tuple					=				self.activation(UpperCamelCase_  )
           return hidden_state




class 				_lowerCamelCase (      nn.Module ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = 2						,						__SCREAMING_SNAKE_CASE = 2						,						)  ->   Union[str, Any]:




           """simple docstring"""







           super().__init__()

           UpperCamelCase__    :   Dict					=				ResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else ResNetBasicLayer

           UpperCamelCase__    :   List[Any]					=				nn.Sequential(
               # downsampling is done in the first layer with stride of 2
               layer(UpperCamelCase_						,						UpperCamelCase_						,						stride=UpperCamelCase_						,						activation=config.hidden_act  )						,						*[layer(UpperCamelCase_						,						UpperCamelCase_						,						activation=config.hidden_act  ) for _ in range(depth - 1  )]						,						)






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Optional[int]:




           """simple docstring"""







           UpperCamelCase__    :   Any					=				input
           for layer in self.layers:
                 UpperCamelCase__    :   int					=				layer(UpperCamelCase_  )
           return hidden_state




class 				_lowerCamelCase (      nn.Module ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Dict:




           """simple docstring"""







           super().__init__()
           UpperCamelCase__    :   int					=				nn.ModuleList([]  )
           # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
           self.stages.append(
               ResNetStage(
                   UpperCamelCase_						,						config.embedding_size						,						config.hidden_sizes[0]						,						stride=2 if config.downsample_in_first_stage else 1						,						depth=config.depths[0]						,						)  )
           UpperCamelCase__    :   Optional[Any]					=				zip(config.hidden_sizes						,						config.hidden_sizes[1:]  )
           for (in_channels, out_channels), depth in zip(UpperCamelCase_						,						config.depths[1:]  ):
                 self.stages.append(ResNetStage(UpperCamelCase_						,						UpperCamelCase_						,						UpperCamelCase_						,						depth=UpperCamelCase_  )  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = False						,						__SCREAMING_SNAKE_CASE = True  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   List[str]					=				() if output_hidden_states else None

           for stage_module in self.stages:
                 if output_hidden_states:
                       UpperCamelCase__    :   Optional[Any]					=				hidden_states + (hidden_state,)

                 UpperCamelCase__    :   List[Any]					=				stage_module(UpperCamelCase_  )

           if output_hidden_states:
                 UpperCamelCase__    :   List[str]					=				hidden_states + (hidden_state,)

           if not return_dict:
                 return tuple(v for v in [hidden_state, hidden_states] if v is not None  )

           return BaseModelOutputWithNoAttention(
               last_hidden_state=UpperCamelCase_						,						hidden_states=UpperCamelCase_						,						)




class 				_lowerCamelCase (      __lowerCamelCase ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		   =  ResNetConfig
     SCREAMING_SNAKE_CASE_		   =  'resnet'
     SCREAMING_SNAKE_CASE_		   =  'pixel_values'
     SCREAMING_SNAKE_CASE_		   =  True






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Optional[Any]:




           """simple docstring"""







           if isinstance(UpperCamelCase_						,						nn.Convad  ):
                 nn.init.kaiming_normal_(module.weight						,						mode='''fan_out'''						,						nonlinearity='''relu'''  )
           elif isinstance(UpperCamelCase_						,						(nn.BatchNormad, nn.GroupNorm)  ):
                 nn.init.constant_(module.weight						,						1  )
                 nn.init.constant_(module.bias						,						0  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=False  )  ->   Union[str, Any]:




           """simple docstring"""







           if isinstance(UpperCamelCase_						,						UpperCamelCase_  ):
                 UpperCamelCase__    :   Any					=				value
lowerCamelCase	   =R"\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

lowerCamelCase	   =R"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"




@add_start_docstrings(
    '''The bare ResNet model outputting raw features without any specific head on top.'''	,							__lowerCamelCase	,							)
class 				_lowerCamelCase (      __lowerCamelCase ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Any:




           """simple docstring"""







           super().__init__(UpperCamelCase_  )
           UpperCamelCase__    :   int					=				config
           UpperCamelCase__    :   List[Any]					=				ResNetEmbeddings(UpperCamelCase_  )
           UpperCamelCase__    :   Any					=				ResNetEncoder(UpperCamelCase_  )
           UpperCamelCase__    :   int					=				nn.AdaptiveAvgPoolad((1, 1)  )
           # Initialize weights and apply final processing
           self.post_init()






     @add_start_docstrings_to_model_forward(UpperCamelCase_  )
     @add_code_sample_docstrings(
         checkpoint=_CHECKPOINT_FOR_DOC						,						output_type=UpperCamelCase_						,						config_class=_CONFIG_FOR_DOC						,						modality='''vision'''						,						expected_output=_EXPECTED_OUTPUT_SHAPE						,						)
     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = None						,						__SCREAMING_SNAKE_CASE = None  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   Optional[int]					=				(
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )
           UpperCamelCase__    :   Any					=				return_dict if return_dict is not None else self.config.use_return_dict

           UpperCamelCase__    :   List[Any]					=				self.embedder(UpperCamelCase_  )

           UpperCamelCase__    :   Any					=				self.encoder(
               UpperCamelCase_						,						output_hidden_states=UpperCamelCase_						,						return_dict=UpperCamelCase_  )

           UpperCamelCase__    :   Tuple					=				encoder_outputs[0]

           UpperCamelCase__    :   Optional[int]					=				self.pooler(UpperCamelCase_  )

           if not return_dict:
                 return (last_hidden_state, pooled_output) + encoder_outputs[1:]

           return BaseModelOutputWithPoolingAndNoAttention(
               last_hidden_state=UpperCamelCase_						,						pooler_output=UpperCamelCase_						,						hidden_states=encoder_outputs.hidden_states						,						)




@add_start_docstrings(
    '''\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '''	,							__lowerCamelCase	,							)
class 				_lowerCamelCase (      __lowerCamelCase ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE  )  ->   int:




           """simple docstring"""







           super().__init__(UpperCamelCase_  )
           UpperCamelCase__    :   List[str]					=				config.num_labels
           UpperCamelCase__    :   Tuple					=				ResNetModel(UpperCamelCase_  )
           # classification head
           UpperCamelCase__    :   Any					=				nn.Sequential(
               nn.Flatten()						,						nn.Linear(config.hidden_sizes[-1]						,						config.num_labels  ) if config.num_labels > 0 else nn.Identity()						,						)
           # initialize weights and apply final processing
           self.post_init()






     @add_start_docstrings_to_model_forward(UpperCamelCase_  )
     @add_code_sample_docstrings(
         checkpoint=_IMAGE_CLASS_CHECKPOINT						,						output_type=UpperCamelCase_						,						config_class=_CONFIG_FOR_DOC						,						expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT						,						)
     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE = None						,						__SCREAMING_SNAKE_CASE = None						,						__SCREAMING_SNAKE_CASE = None						,						__SCREAMING_SNAKE_CASE = None						,						)  ->   Dict:




           """simple docstring"""







           UpperCamelCase__    :   str					=				return_dict if return_dict is not None else self.config.use_return_dict

           UpperCamelCase__    :   Optional[int]					=				self.resnet(UpperCamelCase_						,						output_hidden_states=UpperCamelCase_						,						return_dict=UpperCamelCase_  )

           UpperCamelCase__    :   Optional[int]					=				outputs.pooler_output if return_dict else outputs[1]

           UpperCamelCase__    :   List[str]					=				self.classifier(UpperCamelCase_  )

           UpperCamelCase__    :   Dict					=				None

           if labels is not None:
                 if self.config.problem_type is None:
                       if self.num_labels == 1:
                             UpperCamelCase__    :   List[str]					=				'''regression'''
                       elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                             UpperCamelCase__    :   Optional[Any]					=				'''single_label_classification'''
                       else:
                             UpperCamelCase__    :   str					=				'''multi_label_classification'''
                 if self.config.problem_type == "regression":
                       UpperCamelCase__    :   int					=				MSELoss()
                       if self.num_labels == 1:
                             UpperCamelCase__    :   Tuple					=				loss_fct(logits.squeeze()						,						labels.squeeze()  )
                       else:
                             UpperCamelCase__    :   str					=				loss_fct(UpperCamelCase_						,						UpperCamelCase_  )
                 elif self.config.problem_type == "single_label_classification":
                       UpperCamelCase__    :   Dict					=				CrossEntropyLoss()
                       UpperCamelCase__    :   str					=				loss_fct(logits.view(-1						,						self.num_labels  )						,						labels.view(-1  )  )
                 elif self.config.problem_type == "multi_label_classification":
                       UpperCamelCase__    :   Dict					=				BCEWithLogitsLoss()
                       UpperCamelCase__    :   int					=				loss_fct(UpperCamelCase_						,						UpperCamelCase_  )

           if not return_dict:
                 UpperCamelCase__    :   Union[str, Any]					=				(logits,) + outputs[2:]
                 return (loss,) + output if loss is not None else output

           return ImageClassifierOutputWithNoAttention(loss=UpperCamelCase_						,						logits=UpperCamelCase_						,						hidden_states=outputs.hidden_states  )




@add_start_docstrings(
    '''\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    '''	,							__lowerCamelCase	,							)
class 				_lowerCamelCase (      __lowerCamelCase	,							__lowerCamelCase ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Union[str, Any]:




           """simple docstring"""







           super().__init__(UpperCamelCase_  )
           super()._init_backbone(UpperCamelCase_  )

           UpperCamelCase__    :   Dict					=				[config.embedding_size] + config.hidden_sizes
           UpperCamelCase__    :   Optional[int]					=				ResNetEmbeddings(UpperCamelCase_  )
           UpperCamelCase__    :   int					=				ResNetEncoder(UpperCamelCase_  )

           # initialize weights and apply final processing
           self.post_init()






     @add_start_docstrings_to_model_forward(UpperCamelCase_  )
     @replace_return_docstrings(output_type=UpperCamelCase_						,						config_class=_CONFIG_FOR_DOC  )
     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = None						,						__SCREAMING_SNAKE_CASE = None  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__    :   Dict					=				return_dict if return_dict is not None else self.config.use_return_dict
           UpperCamelCase__    :   int					=				(
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )

           UpperCamelCase__    :   List[Any]					=				self.embedder(UpperCamelCase_  )

           UpperCamelCase__    :   Optional[int]					=				self.encoder(UpperCamelCase_						,						output_hidden_states=UpperCamelCase_						,						return_dict=UpperCamelCase_  )

           UpperCamelCase__    :   str					=				outputs.hidden_states

           UpperCamelCase__    :   List[str]					=				()
           for idx, stage in enumerate(self.stage_names  ):
                 if stage in self.out_features:
                       feature_maps += (hidden_states[idx],)

           if not return_dict:
                 UpperCamelCase__    :   Union[str, Any]					=				(feature_maps,)
                 if output_hidden_states:
                       output += (outputs.hidden_states,)
                 return output

           return BackboneOutput(
               feature_maps=UpperCamelCase_						,						hidden_states=outputs.hidden_states if output_hidden_states else None						,						attentions=UpperCamelCase_						,						)




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




@add_end_docstrings(UpperCamelCase_ )
class 				_lowerCamelCase (      UpperCamelCase_ ):





     """simple docstring"""







     def __init__(							self						,						*__SCREAMING_SNAKE_CASE						,						**__SCREAMING_SNAKE_CASE  )  ->   Dict:




           """simple docstring"""







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






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE=None						,						__SCREAMING_SNAKE_CASE=None						,						__SCREAMING_SNAKE_CASE=None  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__    :   List[str]					=				{}
           if frame_sampling_rate is not None:
                 UpperCamelCase__    :   Tuple					=				frame_sampling_rate
           if num_frames is not None:
                 UpperCamelCase__    :   str					=				num_frames

           UpperCamelCase__    :   List[str]					=				{}
           if top_k is not None:
                 UpperCamelCase__    :   List[Any]					=				top_k
           return preprocess_params, {}, postprocess_params






     def __call__(							self						,						__SCREAMING_SNAKE_CASE						,						**__SCREAMING_SNAKE_CASE  )  ->   Tuple:




           """simple docstring"""







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






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=None						,						__SCREAMING_SNAKE_CASE=1  )  ->   Optional[Any]:




           """simple docstring"""







           if num_frames is None:
                 UpperCamelCase__    :   Optional[Any]					=				self.model.config.num_frames

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

           UpperCamelCase__    :   Tuple					=				VideoReader(__SCREAMING_SNAKE_CASE  )
           videoreader.seek(0  )

           UpperCamelCase__    :   Optional[int]					=				0
           UpperCamelCase__    :   str					=				num_frames * frame_sampling_rate - 1
           UpperCamelCase__    :   List[Any]					=				np.linspace(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						num=__SCREAMING_SNAKE_CASE						,						dtype=np.intaa  )

           UpperCamelCase__    :   str					=				videoreader.get_batch(__SCREAMING_SNAKE_CASE  ).asnumpy()
           UpperCamelCase__    :   Tuple					=				list(__SCREAMING_SNAKE_CASE  )

           UpperCamelCase__    :   Dict					=				self.image_processor(__SCREAMING_SNAKE_CASE						,						return_tensors=self.framework  )
           return model_inputs






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE  )  ->   Union[str, Any]:




           """simple docstring"""







           UpperCamelCase__    :   Tuple					=				self.model(**__SCREAMING_SNAKE_CASE  )
           return model_outputs






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=5  )  ->   str:




           """simple docstring"""







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

           if self.framework == "pt":
                 UpperCamelCase__    :   Any					=				model_outputs.logits.softmax(-1  )[0]
                 UpperCamelCase__				,UpperCamelCase__    :   List[str]					=				probs.topk(__SCREAMING_SNAKE_CASE  )
           else:
                 raise ValueError(F'''Unsupported framework: {self.framework}'''  )

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


