
from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


lowerCamelCase	   =logging.get_logger(__name__)


lowerCamelCase	   ={
    "Salesforce/codegen-350M-nl": "https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json",
    "Salesforce/codegen-350M-multi": "https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json",
    "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json",
    "Salesforce/codegen-2B-nl": "https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json",
    "Salesforce/codegen-2B-multi": "https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json",
    "Salesforce/codegen-2B-mono": "https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json",
    "Salesforce/codegen-6B-nl": "https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json",
    "Salesforce/codegen-6B-multi": "https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json",
    "Salesforce/codegen-6B-mono": "https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json",
    "Salesforce/codegen-16B-nl": "https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json",
    "Salesforce/codegen-16B-multi": "https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json",
    "Salesforce/codegen-16B-mono": "https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json",
}




class 				_lowerCamelCase (      UpperCAmelCase__ ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		   =  'codegen'
     SCREAMING_SNAKE_CASE_		   =  {
         'max_position_embeddings': 'n_positions',
         'hidden_size': 'n_embd',
         'num_attention_heads': 'n_head',
         'num_hidden_layers': 'n_layer',
     }






     def __init__(							self						,						__SCREAMING_SNAKE_CASE=5_0_4_0_0						,						__SCREAMING_SNAKE_CASE=2_0_4_8						,						__SCREAMING_SNAKE_CASE=2_0_4_8						,						__SCREAMING_SNAKE_CASE=4_0_9_6						,						__SCREAMING_SNAKE_CASE=2_8						,						__SCREAMING_SNAKE_CASE=1_6						,						__SCREAMING_SNAKE_CASE=6_4						,						__SCREAMING_SNAKE_CASE=None						,						__SCREAMING_SNAKE_CASE="gelu_new"						,						__SCREAMING_SNAKE_CASE=0.0						,						__SCREAMING_SNAKE_CASE=0.0						,						__SCREAMING_SNAKE_CASE=0.0						,						__SCREAMING_SNAKE_CASE=1e-5						,						__SCREAMING_SNAKE_CASE=0.02						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE=5_0_2_5_6						,						__SCREAMING_SNAKE_CASE=5_0_2_5_6						,						__SCREAMING_SNAKE_CASE=False						,						**__SCREAMING_SNAKE_CASE						,						)  ->   str:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				vocab_size
           UpperCamelCase__    :   Any					=				n_ctx
           UpperCamelCase__    :   str					=				n_positions
           UpperCamelCase__    :   Any					=				n_embd
           UpperCamelCase__    :   List[Any]					=				n_layer
           UpperCamelCase__    :   Tuple					=				n_head
           UpperCamelCase__    :   List[Any]					=				n_inner
           UpperCamelCase__    :   List[Any]					=				rotary_dim
           UpperCamelCase__    :   Tuple					=				activation_function
           UpperCamelCase__    :   Any					=				resid_pdrop
           UpperCamelCase__    :   List[str]					=				embd_pdrop
           UpperCamelCase__    :   List[Any]					=				attn_pdrop
           UpperCamelCase__    :   Optional[Any]					=				layer_norm_epsilon
           UpperCamelCase__    :   Optional[Any]					=				initializer_range
           UpperCamelCase__    :   Tuple					=				use_cache

           UpperCamelCase__    :   Any					=				bos_token_id
           UpperCamelCase__    :   str					=				eos_token_id

           super().__init__(
               bos_token_id=__SCREAMING_SNAKE_CASE						,						eos_token_id=__SCREAMING_SNAKE_CASE						,						tie_word_embeddings=__SCREAMING_SNAKE_CASE						,						**__SCREAMING_SNAKE_CASE  )




class 				_lowerCamelCase (      UpperCAmelCase__ ):





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = "default"						,						__SCREAMING_SNAKE_CASE = None						,						__SCREAMING_SNAKE_CASE = False						,						)  ->   Optional[Any]:




           """simple docstring"""







           super().__init__(__SCREAMING_SNAKE_CASE						,						task=__SCREAMING_SNAKE_CASE						,						patching_specs=__SCREAMING_SNAKE_CASE						,						use_past=__SCREAMING_SNAKE_CASE  )
           if not getattr(self._config						,						'''pad_token_id'''						,						__SCREAMING_SNAKE_CASE  ):
                 # TODO: how to do that better?
                 UpperCamelCase__    :   Dict					=				0






     @property
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Mapping[str, Mapping[int, str]]:




           """simple docstring"""







           UpperCamelCase__    :   Optional[int]					=				OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}  )
           if self.use_past:
                 self.fill_with_past_key_values_(__SCREAMING_SNAKE_CASE						,						direction='''inputs'''  )
                 UpperCamelCase__    :   Any					=				{0: """batch""", 1: """past_sequence + sequence"""}
           else:
                 UpperCamelCase__    :   Optional[Any]					=				{0: """batch""", 1: """sequence"""}

           return common_inputs






     @property
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           return self._config.n_layer






     @property
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           return self._config.n_head






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE = -1						,						__SCREAMING_SNAKE_CASE = -1						,						__SCREAMING_SNAKE_CASE = False						,						__SCREAMING_SNAKE_CASE = None						,						)  ->   Mapping[str, Any]:




           """simple docstring"""







           UpperCamelCase__    :   Union[str, Any]					=				super(__SCREAMING_SNAKE_CASE						,						self  ).generate_dummy_inputs(
               __SCREAMING_SNAKE_CASE						,						batch_size=__SCREAMING_SNAKE_CASE						,						seq_length=__SCREAMING_SNAKE_CASE						,						is_pair=__SCREAMING_SNAKE_CASE						,						framework=__SCREAMING_SNAKE_CASE  )

           # We need to order the input in the way they appears in the forward()
           UpperCamelCase__    :   int					=				OrderedDict({'''input_ids''': common_inputs['''input_ids''']}  )

           # Need to add the past_keys
           if self.use_past:
                 if not is_torch_available():
                       raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''  )
                 else:
                       import torch

                       UpperCamelCase__    :   int					=				common_inputs["""input_ids"""].shape
                       # Not using the same length for past_key_values
                       UpperCamelCase__    :   Dict					=				seqlen + 2
                       UpperCamelCase__    :   List[str]					=				(
                           batch,
                           self.num_attention_heads,
                           past_key_values_length,
                           self._config.hidden_size // self.num_attention_heads,
                       )
                       UpperCamelCase__    :   Any					=				[
                           (torch.zeros(__SCREAMING_SNAKE_CASE  ), torch.zeros(__SCREAMING_SNAKE_CASE  )) for _ in range(self.num_layers  )
                       ]

           UpperCamelCase__    :   Dict					=				common_inputs["""attention_mask"""]
           if self.use_past:
                 UpperCamelCase__    :   int					=				ordered_inputs["""attention_mask"""].dtype
                 UpperCamelCase__    :   Any					=				torch.cat(
                     [ordered_inputs['''attention_mask'''], torch.ones(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						dtype=__SCREAMING_SNAKE_CASE  )]						,						dim=1  )

           return ordered_inputs






     @property
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           return 1_3




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  )]


