


"""simple docstring"""





import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf



class 		snake_case_(       enum.Enum			):
					__UpperCamelCase  =					0
					__UpperCamelCase  =					1
					__UpperCamelCase  =					2



@add_end_docstrings(_UpperCAmelCase			)
class 		snake_case_(       _UpperCAmelCase			):
					__UpperCamelCase  =					'''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''






					def __init__(	self  :					Optional[Any]					,				*UpperCamelCase_  :					Dict					,				**UpperCamelCase_  :					List[Any]				):
											super().__init__(*A_					,				**A_				)
											self.check_model_type(
											    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING				)
											if "prefix" not in self._preprocess_params:
																	# This is very specific. The logic is quite complex and needs to be done
																	# as a "default".
																	# It also defines both some preprocess_kwargs and generate_kwargs
																	# which is why we cannot put them in their respective methods.
																	lowerCAmelCase					:	str       =   None
																	if self.model.config.prefix is not None:
																							lowerCAmelCase					:	Tuple       =   self.model.config.prefix
																	if prefix is None and self.model.__class__.__name__ in [
																	    "XLNetLMHeadModel",
																	    "TransfoXLLMHeadModel",
																	    "TFXLNetLMHeadModel",
																	    "TFTransfoXLLMHeadModel",
																	]:
																							# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
																							lowerCAmelCase					:	Tuple       =   self.XL_PREFIX
																	if prefix is not None:
																							# Recalculate some generate_kwargs linked to prefix.
																							lowerCAmelCase,      lowerCAmelCase,      lowerCAmelCase					:	Union[str, Any]       =   self._sanitize_parameters(prefix=A_					,				**self._forward_params				)
																							lowerCAmelCase					:	Tuple       =   {**self._preprocess_params, **preprocess_params}
																							lowerCAmelCase					:	List[str]       =   {**self._forward_params, **forward_params}






					def      lowerCamelCase__     (	self  :					str					,				UpperCamelCase_  :					Tuple=None					,				UpperCamelCase_  :					int=None					,				UpperCamelCase_  :					Union[str, Any]=None					,				UpperCamelCase_  :					List[str]=None					,				UpperCamelCase_  :					str=None					,				UpperCamelCase_  :					Dict=None					,				UpperCamelCase_  :					str=None					,				UpperCamelCase_  :					Optional[int]=None					,				**UpperCamelCase_  :					Any					,				):
											lowerCAmelCase					:	int       =   {}
											if prefix is not None:
																	lowerCAmelCase					:	List[Any]       =   prefix
											if prefix:
																	lowerCAmelCase					:	List[str]       =   self.tokenizer(
																	    A_					,				padding=A_					,				add_special_tokens=A_					,				return_tensors=self.framework				)
																	lowerCAmelCase					:	Tuple       =   prefix_inputs['''input_ids'''].shape[-1]

											if handle_long_generation is not None:
																	if handle_long_generation not in {"hole"}:
																							raise ValueError(
																							    F'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'''
																							    ''' [None, \'hole\']'''				)
																	lowerCAmelCase					:	Optional[Any]       =   handle_long_generation

											preprocess_params.update(A_				)
											lowerCAmelCase					:	List[str]       =   generate_kwargs

											lowerCAmelCase					:	Tuple       =   {}
											if return_full_text is not None and return_type is None:
																	if return_text is not None:
																							raise ValueError('''`return_text` is mutually exclusive with `return_full_text`'''				)
																	if return_tensors is not None:
																							raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`'''				)
																	lowerCAmelCase					:	int       =   ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
											if return_tensors is not None and return_type is None:
																	if return_text is not None:
																							raise ValueError('''`return_text` is mutually exclusive with `return_tensors`'''				)
																	lowerCAmelCase					:	Tuple       =   ReturnType.TENSORS
											if return_type is not None:
																	lowerCAmelCase					:	str       =   return_type
											if clean_up_tokenization_spaces is not None:
																	lowerCAmelCase					:	Optional[Any]       =   clean_up_tokenization_spaces

											if stop_sequence is not None:
																	lowerCAmelCase					:	int       =   self.tokenizer.encode(A_					,				add_special_tokens=A_				)
																	if len(A_				) > 1:
																							warnings.warn(
																							    '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of'''
																							    ''' the stop sequence will be used as the stop sequence string in the interim.'''				)
																	lowerCAmelCase					:	Any       =   stop_sequence_ids[0]

											return preprocess_params, forward_params, postprocess_params






					def      lowerCamelCase__     (	self  :					Any					,				*UpperCamelCase_  :					List[Any]					,				**UpperCamelCase_  :					Tuple				):
											# Parse arguments
											if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
																	kwargs.update({'''add_space_before_punct_symbol''': True}				)

											return super()._parse_and_tokenize(*A_					,				**A_				)






					def __call__(	self  :					Tuple					,				UpperCamelCase_  :					str					,				**UpperCamelCase_  :					Optional[int]				):
											return super().__call__(A_					,				**A_				)






					def      lowerCamelCase__     (	self  :					Optional[Any]					,				UpperCamelCase_  :					List[Any]					,				UpperCamelCase_  :					Union[str, Any]=""					,				UpperCamelCase_  :					int=None					,				**UpperCamelCase_  :					Union[str, Any]				):
											lowerCAmelCase					:	Optional[Any]       =   self.tokenizer(
											    prefix + prompt_text					,				padding=A_					,				add_special_tokens=A_					,				return_tensors=self.framework				)
											lowerCAmelCase					:	Optional[int]       =   prompt_text

											if handle_long_generation == "hole":
																	lowerCAmelCase					:	int       =   inputs['''input_ids'''].shape[-1]
																	if "max_new_tokens" in generate_kwargs:
																							lowerCAmelCase					:	Tuple       =   generate_kwargs['''max_new_tokens''']
																	else:
																							lowerCAmelCase					:	str       =   generate_kwargs.get('''max_length'''					,				self.model.config.max_length				) - cur_len
																							if new_tokens < 0:
																													raise ValueError('''We cannot infer how many new tokens are expected'''				)
																	if cur_len + new_tokens > self.tokenizer.model_max_length:
																							lowerCAmelCase					:	Dict       =   self.tokenizer.model_max_length - new_tokens
																							if keep_length <= 0:
																													raise ValueError(
																													    '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the'''
																													    ''' models max length'''				)

																							lowerCAmelCase					:	List[str]       =   inputs['''input_ids'''][:, -keep_length:]
																							if "attention_mask" in inputs:
																													lowerCAmelCase					:	Optional[int]       =   inputs['''attention_mask'''][:, -keep_length:]

											return inputs






					def      lowerCamelCase__     (	self  :					Optional[Any]					,				UpperCamelCase_  :					Union[str, Any]					,				**UpperCamelCase_  :					Optional[Any]				):
											lowerCAmelCase					:	Optional[int]       =   model_inputs['''input_ids''']
											lowerCAmelCase					:	str       =   model_inputs.get('''attention_mask'''					,				A_				)
											# Allow empty prompts
											if input_ids.shape[1] == 0:
																	lowerCAmelCase					:	Optional[Any]       =   None
																	lowerCAmelCase					:	List[str]       =   None
																	lowerCAmelCase					:	str       =   1
											else:
																	lowerCAmelCase					:	Optional[int]       =   input_ids.shape[0]
											lowerCAmelCase					:	List[Any]       =   model_inputs.pop('''prompt_text'''				)

											# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
											# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
											lowerCAmelCase					:	Optional[int]       =   generate_kwargs.pop('''prefix_length'''					,				0				)
											if prefix_length > 0:
																	lowerCAmelCase					:	Optional[Any]       =   '''max_new_tokens''' in generate_kwargs or (
																	    '''generation_config''' in generate_kwargs
																	    and generate_kwargs['''generation_config'''].max_new_tokens is not None
																	)
																	if not has_max_new_tokens:
																							lowerCAmelCase					:	List[Any]       =   generate_kwargs.get('''max_length'''				) or self.model.config.max_length
																							generate_kwargs["max_length"] += prefix_length
																	lowerCAmelCase					:	Union[str, Any]       =   '''min_new_tokens''' in generate_kwargs or (
																	    '''generation_config''' in generate_kwargs
																	    and generate_kwargs['''generation_config'''].min_new_tokens is not None
																	)
																	if not has_min_new_tokens and "min_length" in generate_kwargs:
																							generate_kwargs["min_length"] += prefix_length

        # BS x SL
											lowerCAmelCase					:	int       =   self.model.generate(input_ids=A_					,				attention_mask=A_					,				**A_				)
											lowerCAmelCase					:	Dict       =   generated_sequence.shape[0]
											if self.framework == "pt":
																	lowerCAmelCase					:	Optional[int]       =   generated_sequence.reshape(A_					,				out_b // in_b					,				*generated_sequence.shape[1:]				)
											elif self.framework == "tf":
																	lowerCAmelCase					:	List[str]       =   tf.reshape(A_					,				(in_b, out_b // in_b, *generated_sequence.shape[1:])				)
											return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}






					def      lowerCamelCase__     (	self  :					int					,				UpperCamelCase_  :					int					,				UpperCamelCase_  :					Optional[Any]=ReturnType.FULL_TEXT					,				UpperCamelCase_  :					str=True				):
											lowerCAmelCase					:	List[str]       =   model_outputs['''generated_sequence'''][0]
											lowerCAmelCase					:	Optional[Any]       =   model_outputs['''input_ids''']
											lowerCAmelCase					:	Union[str, Any]       =   model_outputs['''prompt_text''']
											lowerCAmelCase					:	Optional[Any]       =   generated_sequence.numpy().tolist()
											lowerCAmelCase					:	List[str]       =   []
											for sequence in generated_sequence:
																	if return_type == ReturnType.TENSORS:
																							lowerCAmelCase					:	List[str]       =   {'''generated_token_ids''': sequence}
																	elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
																							# Decode text
																							lowerCAmelCase					:	List[str]       =   self.tokenizer.decode(
																							    A_					,				skip_special_tokens=A_					,				clean_up_tokenization_spaces=A_					,				)

																							# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
																							if input_ids is None:
																													lowerCAmelCase					:	Dict       =   0
																							else:
																													lowerCAmelCase					:	Any       =   len(
																													    self.tokenizer.decode(
																													        input_ids[0]					,				skip_special_tokens=A_					,				clean_up_tokenization_spaces=A_					,				)				)

																							if return_type == ReturnType.FULL_TEXT:
																													lowerCAmelCase					:	Union[str, Any]       =   prompt_text + text[prompt_length:]
																							else:
																													lowerCAmelCase					:	List[str]       =   text[prompt_length:]

																							lowerCAmelCase					:	List[Any]       =   {'''generated_text''': all_text}
																	records.append(A_				)

											return records






"""simple docstring"""





from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


snake_case__		:     Tuple    				=				logging.get_logger(__name__)

snake_case__		:     int    				=				{
    '''facebook/levit-128S''': '''https://huggingface.co/facebook/levit-128S/resolve/main/config.json''',
    # See all LeViT models at https://huggingface.co/models?filter=levit
}



class 		snake_case_(       a__			):
     __UpperCamelCase  =					'''levit'''






     def __init__(	self  :					str					,				UpperCamelCase_  :					Union[str, Any]=2_2_4					,				UpperCamelCase_  :					Union[str, Any]=3					,				UpperCamelCase_  :					Union[str, Any]=3					,				UpperCamelCase_  :					int=2					,				UpperCamelCase_  :					Union[str, Any]=1					,				UpperCamelCase_  :					Tuple=1_6					,				UpperCamelCase_  :					Dict=[1_2_8, 2_5_6, 3_8_4]					,				UpperCamelCase_  :					Optional[Any]=[4, 8, 1_2]					,				UpperCamelCase_  :					Dict=[4, 4, 4]					,				UpperCamelCase_  :					Any=[1_6, 1_6, 1_6]					,				UpperCamelCase_  :					str=0					,				UpperCamelCase_  :					int=[2, 2, 2]					,				UpperCamelCase_  :					Optional[Any]=[2, 2, 2]					,				UpperCamelCase_  :					str=0.02					,				**UpperCamelCase_  :					List[str]					,				):
           super().__init__(**UpperCamelCase_				)
           lowerCAmelCase					:	Tuple       =   image_size
           lowerCAmelCase					:	int       =   num_channels
           lowerCAmelCase					:	Optional[int]       =   kernel_size
           lowerCAmelCase					:	Dict       =   stride
           lowerCAmelCase					:	List[Any]       =   padding
           lowerCAmelCase					:	Dict       =   hidden_sizes
           lowerCAmelCase					:	List[str]       =   num_attention_heads
           lowerCAmelCase					:	Tuple       =   depths
           lowerCAmelCase					:	Dict       =   key_dim
           lowerCAmelCase					:	Union[str, Any]       =   drop_path_rate
           lowerCAmelCase					:	List[Any]       =   patch_size
           lowerCAmelCase					:	Tuple       =   attention_ratio
           lowerCAmelCase					:	Optional[int]       =   mlp_ratio
           lowerCAmelCase					:	Union[str, Any]       =   initializer_range
           lowerCAmelCase					:	List[str]       =   [
               ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
               ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
           ]



class 		snake_case_(       a__			):
     __UpperCamelCase  =					version.parse('''1.11'''			)






     @property
     def      lowerCamelCase__     (	self  :					Tuple				):
           return OrderedDict(
               [
                   ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
               ]				)






     @property
     def      lowerCamelCase__     (	self  :					Optional[Any]				):
           return 1E-4


