



'''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

UpperCamelCase_       :  str					=  logging.get_logger(__name__)



@add_end_docstrings(__lowerCamelCase						)
class    lowerCamelCase__				(			__lowerCamelCase						):






      """simple docstring"""




      def __init__(       self							:     Tuple			,*a__							:     List[str]			,**a__							:     List[Any]   ):
             super().__init__(*__lowercase			,**__lowercase   )
             requires_backends(self			,"decord"   )
             self.check_model_type(__lowercase   )




      def lowerCAmelCase_					(       self							:     str			,a__							:     Union[str, Any]=None			,a__							:     str=None			,a__							:     int=None   ):
             a__								= {}
             if frame_sampling_rate is not None:
                    a__								= frame_sampling_rate
             if num_frames is not None:
                    a__								= num_frames

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




      def __call__(       self							:     Optional[Any]			,a__							:     Union[str, List[str]]			,**a__							:     Optional[int]   ):
             return super().__call__(__lowercase			,**__lowercase   )




      def lowerCAmelCase_					(       self							:     str			,a__							:     Tuple			,a__							:     List[Any]=None			,a__							:     int=1   ):







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

             if video.startswith("http://"   ) or video.startswith("https://"   ):
                    a__								= BytesIO(requests.get(__lowercase   ).content   )

             a__								= VideoReader(__lowercase   )
             videoreader.seek(0   )

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

             a__								= videoreader.get_batch(__lowercase   ).asnumpy()
             a__								= list(__lowercase   )

             a__								= self.image_processor(__lowercase			,return_tensors=self.framework   )
             return model_inputs




      def lowerCAmelCase_					(       self							:     int			,a__							:     int   ):
             a__								= self.model(**__lowercase   )
             return model_outputs




      def lowerCAmelCase_					(       self							:     Dict			,a__							:     Any			,a__							:     Optional[Any]=5   ):







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

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

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



'''simple docstring'''

import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging


if TYPE_CHECKING:
       from transformers.pipelines.conversational import Conversation


UpperCAmelCase					 =	logging.get_logger(__name__)

UpperCAmelCase					 =	{'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}

UpperCAmelCase					 =	{
    '''tokenizer_file''': {
        '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''',
    },
}

UpperCAmelCase					 =	{
    '''gpt-neox-20b''': 2048,
}


class 	lowerCAmelCase  (   A ):
       lowerCAmelCase_												=			VOCAB_FILES_NAMES
       lowerCAmelCase_												=			PRETRAINED_VOCAB_FILES_MAP
       lowerCAmelCase_												=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowerCAmelCase_												=			["input_ids", "attention_mask"]







       def __init__(				self      :			Tuple    ,   __lowercase      :			Union[str, Any]=None    ,   __lowercase      :			Union[str, Any]=None    ,   __lowercase      :			str=None    ,   __lowercase      :			Optional[int]="<|endoftext|>"    ,   __lowercase      :			List[Any]="<|endoftext|>"    ,   __lowercase      :			Tuple="<|endoftext|>"    ,   __lowercase      :			Optional[int]=False    ,   **__lowercase      :			List[Any]    ,   ):







            """simple docstring"""







            super().__init__(
                __lowercase    ,   __lowercase    ,   tokenizer_file=__lowercase    ,   unk_token=__lowercase    ,   bos_token=__lowercase    ,   eos_token=__lowercase    ,   add_prefix_space=__lowercase    ,   **__lowercase    ,   )

            __lowercase      		=json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()   )
            if pre_tok_state.get('add_prefix_space'    ,   __lowercase   ) != add_prefix_space:
                 __lowercase      		=getattr(__lowercase    ,   pre_tok_state.pop('type'   )   )
                 __lowercase      		=add_prefix_space
                 __lowercase      		=pre_tok_class(**__lowercase   )

            __lowercase      		=add_prefix_space







       def       snake_case (				self      :			Optional[Any]    ,   __lowercase      :			str    ,   __lowercase      :			Optional[str] = None   ):







            """simple docstring"""







            __lowercase      		=self._tokenizer.model.save(__lowercase    ,   name=__lowercase   )
            return tuple(__lowercase   )







       def       snake_case (				self      :			Optional[Any]    ,   __lowercase      :			"Conversation"   ):







            """simple docstring"""







            __lowercase      		=[]
            for is_user, text in conversation.iter_texts():
                 input_ids.extend(self.encode(__lowercase    ,   add_special_tokens=__lowercase   ) + [self.eos_token_id]   )

            if len(__lowercase   ) > self.model_max_length:
                 __lowercase      		=input_ids[-self.model_max_length :]
            return input_ids


