
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 						lowercase__  (						enum.Enum  ):
	A__    :   List[Any]				       =0
	A__    :   Any				       =1
	A__    :   Optional[Any]				       =2





@add_end_docstrings(_a  )
class 						lowercase__  (						_a  ):
	A__    :   Union[str, Any]				       ="""
    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							:   Tuple       ,   *UpperCAmelCase_							:   Optional[Any]       ,   **UpperCAmelCase_							:   int							):
						super().__init__(*__lowerCamelCase       ,   **__lowerCamelCase							)
						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.
											SCREAMING_SNAKE_CASE__													= None
											if self.model.config.prefix is not None:
																SCREAMING_SNAKE_CASE__													= 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.
																SCREAMING_SNAKE_CASE__													= self.XL_PREFIX
											if prefix is not None:
																# Recalculate some generate_kwargs linked to prefix.
																SCREAMING_SNAKE_CASE__													= self._sanitize_parameters(prefix=__lowerCamelCase       ,   **self._forward_params							)
																SCREAMING_SNAKE_CASE__													= {**self._preprocess_params, **preprocess_params}
																SCREAMING_SNAKE_CASE__													= {**self._forward_params, **forward_params}
	def      A_				(			self							:   int       ,   UpperCAmelCase_							:   List[Any]=None       ,   UpperCAmelCase_							:   Optional[int]=None       ,   UpperCAmelCase_							:   Optional[int]=None       ,   UpperCAmelCase_							:   Dict=None       ,   UpperCAmelCase_							:   Optional[int]=None       ,   UpperCAmelCase_							:   Any=None       ,   UpperCAmelCase_							:   Optional[Any]=None       ,   UpperCAmelCase_							:   Optional[Any]=None       ,   **UpperCAmelCase_							:   str       ,   ):
						SCREAMING_SNAKE_CASE__													= {}
						if prefix is not None:
											SCREAMING_SNAKE_CASE__													= prefix
						if prefix:
											SCREAMING_SNAKE_CASE__													= self.tokenizer(
											    __lowerCamelCase       ,   padding=__lowerCamelCase       ,   add_special_tokens=__lowerCamelCase       ,   return_tensors=self.framework							)
											SCREAMING_SNAKE_CASE__													= 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\']'							)
											SCREAMING_SNAKE_CASE__													= handle_long_generation

						preprocess_params.update(__lowerCamelCase							)
						SCREAMING_SNAKE_CASE__													= generate_kwargs

						SCREAMING_SNAKE_CASE__													= {}
						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`'							)
											SCREAMING_SNAKE_CASE__													= 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`'							)
											SCREAMING_SNAKE_CASE__													= ReturnType.TENSORS
						if return_type is not None:
											SCREAMING_SNAKE_CASE__													= return_type
						if clean_up_tokenization_spaces is not None:
											SCREAMING_SNAKE_CASE__													= clean_up_tokenization_spaces

						if stop_sequence is not None:
											SCREAMING_SNAKE_CASE__													= self.tokenizer.encode(__lowerCamelCase       ,   add_special_tokens=__lowerCamelCase							)
											if len(__lowerCamelCase							) > 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.'							)
											SCREAMING_SNAKE_CASE__													= stop_sequence_ids[0]

						return preprocess_params, forward_params, postprocess_params
	def      A_				(			self							:   Dict       ,   *UpperCAmelCase_							:   Any       ,   **UpperCAmelCase_							:   List[str]							):
						# Parse arguments
						if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
											kwargs.update({'add_space_before_punct_symbol': True}							)

						return super()._parse_and_tokenize(*__lowerCamelCase       ,   **__lowerCamelCase							)
	def __call__(			self							:   List[str]       ,   UpperCAmelCase_							:   Optional[int]       ,   **UpperCAmelCase_							:   str							):
						return super().__call__(__lowerCamelCase       ,   **__lowerCamelCase							)
	def      A_				(			self							:   Optional[int]       ,   UpperCAmelCase_							:   List[str]       ,   UpperCAmelCase_							:   Dict=""       ,   UpperCAmelCase_							:   Tuple=None       ,   **UpperCAmelCase_							:   Union[str, Any]							):
						SCREAMING_SNAKE_CASE__													= self.tokenizer(
						    prefix + prompt_text       ,   padding=__lowerCamelCase       ,   add_special_tokens=__lowerCamelCase       ,   return_tensors=self.framework							)
						SCREAMING_SNAKE_CASE__													= prompt_text

						if handle_long_generation == "hole":
											SCREAMING_SNAKE_CASE__													= inputs["""input_ids"""].shape[-1]
											if "max_new_tokens" in generate_kwargs:
																SCREAMING_SNAKE_CASE__													= generate_kwargs["""max_new_tokens"""]
											else:
																SCREAMING_SNAKE_CASE__													= 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:
																SCREAMING_SNAKE_CASE__													= 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'							)

																SCREAMING_SNAKE_CASE__													= inputs["""input_ids"""][:, -keep_length:]
																if "attention_mask" in inputs:
																					SCREAMING_SNAKE_CASE__													= inputs["""attention_mask"""][:, -keep_length:]

						return inputs
	def      A_				(			self							:   str       ,   UpperCAmelCase_							:   int       ,   **UpperCAmelCase_							:   str							):
						SCREAMING_SNAKE_CASE__													= model_inputs["""input_ids"""]
						SCREAMING_SNAKE_CASE__													= model_inputs.get('attention_mask'       ,   __lowerCamelCase							)
						# Allow empty prompts
						if input_ids.shape[1] == 0:
											SCREAMING_SNAKE_CASE__													= None
											SCREAMING_SNAKE_CASE__													= None
											SCREAMING_SNAKE_CASE__													= 1
						else:
											SCREAMING_SNAKE_CASE__													= input_ids.shape[0]
						SCREAMING_SNAKE_CASE__													= 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.
						SCREAMING_SNAKE_CASE__													= generate_kwargs.pop('prefix_length'       ,   0							)
						if prefix_length > 0:
											SCREAMING_SNAKE_CASE__													= """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:
																SCREAMING_SNAKE_CASE__													= generate_kwargs.get('max_length'							) or self.model.config.max_length
																generate_kwargs["max_length"] += prefix_length
											SCREAMING_SNAKE_CASE__													= """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
						SCREAMING_SNAKE_CASE__													= self.model.generate(input_ids=__lowerCamelCase       ,   attention_mask=__lowerCamelCase       ,   **__lowerCamelCase							)
						SCREAMING_SNAKE_CASE__													= generated_sequence.shape[0]
						if self.framework == "pt":
											SCREAMING_SNAKE_CASE__													= generated_sequence.reshape(__lowerCamelCase       ,   out_b // in_b       ,   *generated_sequence.shape[1:]							)
						elif self.framework == "tf":
											SCREAMING_SNAKE_CASE__													= tf.reshape(__lowerCamelCase       ,   (in_b, out_b // in_b, *generated_sequence.shape[1:])							)
						return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}





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

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

																if return_type == ReturnType.FULL_TEXT:
																					SCREAMING_SNAKE_CASE__													= prompt_text + text[prompt_length:]
																else:
																					SCREAMING_SNAKE_CASE__													= text[prompt_length:]

																SCREAMING_SNAKE_CASE__													= {"""generated_text""": all_text}
											records.append(__lowerCamelCase							)

						return records













from collections.abc import Generator
from math import sin

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  bytes					)		->			bytes:






	"""simple docstring"""



	if len(__magic_name__					) != 32:
		raise ValueError("""Input must be of length 32"""					)

	UpperCamelCase     :int          =	B""""""
	for i in [3, 2, 1, 0]:
		little_endian += string_aa[8 * i : 8 * i + 8]
	return little_endian

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  int					)		->			bytes:






	"""simple docstring"""



	if i < 0:
		raise ValueError("""Input must be non-negative"""					)

	UpperCamelCase     :Any          =	format(__magic_name__	,			"""08x"""					)[-8:]
	UpperCamelCase     :Union[str, Any]          =	B""""""
	for i in [3, 2, 1, 0]:
		little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8"""					)
	return little_endian_hex

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  bytes					)		->			bytes:






	"""simple docstring"""



	UpperCamelCase     :str          =	B""""""
	for char in message:
		bit_string += format(__magic_name__	,			"""08b"""					).encode("""utf-8"""					)
	UpperCamelCase     :Any          =	format(len(__magic_name__					)	,			"""064b"""					).encode("""utf-8"""					)

	# Pad bit_string to a multiple of 512 chars
	bit_string += b"1"
	while len(__magic_name__					) % 512 != 448:
		bit_string += b"0"
	bit_string += to_little_endian(start_len[32:]					) + to_little_endian(start_len[:32]					)

	return bit_string

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  bytes					)		->			Generator[list[int], None, None]:






	"""simple docstring"""



	if len(__magic_name__					) % 512 != 0:
		raise ValueError("""Input must have length that's a multiple of 512"""					)

	for pos in range(0	,			len(__magic_name__					)	,			512					):
		UpperCamelCase     :Tuple          =	bit_string[pos : pos + 512]
		UpperCamelCase     :Optional[int]          =	[]
		for i in range(0	,			512	,			32					):
			block_words.append(int(to_little_endian(block[i : i + 32]					)	,			2					)					)
		yield block_words

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  int					)		->			int:






	"""simple docstring"""



	if i < 0:
		raise ValueError("""Input must be non-negative"""					)

	UpperCamelCase     :List[str]          =	format(__magic_name__	,			"""032b"""					)
	UpperCamelCase     :Any          =	""""""
	for c in i_str:
		new_str += "1" if c == "0" else "0"
	return int(__magic_name__	,			2					)

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  int	,			__magic_name__					:  int					)		->			int:






	"""simple docstring"""



	return (a + b) % 2**32

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  int	,			__magic_name__					:  int					)		->			int:






	"""simple docstring"""



	if i < 0:
		raise ValueError("""Input must be non-negative"""					)
	if shift < 0:
		raise ValueError("""Shift must be non-negative"""					)
	return ((i << shift) ^ (i >> (32 - shift))) % 2**32

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  bytes					)		->			bytes:






	"""simple docstring"""



	UpperCamelCase     :Tuple          =	preprocess(__magic_name__					)

	UpperCamelCase     :List[str]          =	[int(2**32 * abs(sin(i + 1					)					)					) for i in range(64					)]

	# Starting states
	UpperCamelCase     :Union[str, Any]          =	0X67_45_23_01
	UpperCamelCase     :Union[str, Any]          =	0XEF_CD_AB_89
	UpperCamelCase     :List[str]          =	0X98_BA_DC_FE
	UpperCamelCase     :int          =	0X10_32_54_76

	UpperCamelCase     :int          =	[
	    7,
	    12,
	    17,
	    22,
	    7,
	    12,
	    17,
	    22,
	    7,
	    12,
	    17,
	    22,
	    7,
	    12,
	    17,
	    22,
	    5,
	    9,
	    14,
	    20,
	    5,
	    9,
	    14,
	    20,
	    5,
	    9,
	    14,
	    20,
	    5,
	    9,
	    14,
	    20,
	    4,
	    11,
	    16,
	    23,
	    4,
	    11,
	    16,
	    23,
	    4,
	    11,
	    16,
	    23,
	    4,
	    11,
	    16,
	    23,
	    6,
	    10,
	    15,
	    21,
	    6,
	    10,
	    15,
	    21,
	    6,
	    10,
	    15,
	    21,
	    6,
	    10,
	    15,
	    21,
	]

	# Process bit string in chunks, each with 16 32-char words
	for block_words in get_block_words(__magic_name__					):
		UpperCamelCase     :Optional[Any]          =	aa
		UpperCamelCase     :Any          =	ba
		UpperCamelCase     :Tuple          =	ca
		UpperCamelCase     :List[str]          =	da

		# Hash current chunk
		for i in range(64					):
			if i <= 15:
				# f = (b & c) | (not_32(b) & d)     # Alternate definition for f
				UpperCamelCase     :int          =	d ^ (b & (c ^ d))
				UpperCamelCase     :Optional[int]          =	i
			elif i <= 31:
				# f = (d & b) | (not_32(d) & c)     # Alternate definition for f
				UpperCamelCase     :str          =	c ^ (d & (b ^ c))
				UpperCamelCase     :Union[str, Any]          =	(5 * i + 1) % 16
			elif i <= 47:
				UpperCamelCase     :str          =	b ^ c ^ d
				UpperCamelCase     :Optional[int]          =	(3 * i + 5) % 16
			else:
				UpperCamelCase     :List[str]          =	c ^ (b | not_aa(__magic_name__					))
				UpperCamelCase     :int          =	(7 * i) % 16
			UpperCamelCase     :Dict          =	(f + a + added_consts[i] + block_words[g]) % 2**32
			UpperCamelCase     :Tuple          =	d
			UpperCamelCase     :str          =	c
			UpperCamelCase     :Tuple          =	b
			UpperCamelCase     :Optional[Any]          =	sum_aa(__magic_name__	,			left_rotate_aa(__magic_name__	,			shift_amounts[i]					)					)

		# Add hashed chunk to running total
		UpperCamelCase     :List[str]          =	sum_aa(__magic_name__	,			__magic_name__					)
		UpperCamelCase     :str          =	sum_aa(__magic_name__	,			__magic_name__					)
		UpperCamelCase     :int          =	sum_aa(__magic_name__	,			__magic_name__					)
		UpperCamelCase     :Optional[Any]          =	sum_aa(__magic_name__	,			__magic_name__					)

	UpperCamelCase     :Optional[Any]          =	reformat_hex(__magic_name__					) + reformat_hex(__magic_name__					) + reformat_hex(__magic_name__					) + reformat_hex(__magic_name__					)
	return digest


if __name__ == "__main__":
	import doctest

	doctest.testmod()
