




import logging
import os
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

from tqdm import auto as tqdm_lib


lowercase_	:				str  				= {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

lowercase_	:				Any  				= logging.WARNING


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						_UpperCAmelCase													=     os.getenv("DATASETS_VERBOSITY"	,    lowercase__						)
						if env_level_str:
												if env_level_str in log_levels:
																		return log_levels[env_level_str]
												else:
																		logging.getLogger().warning(
																		    f"""Unknown option DATASETS_VERBOSITY={env_level_str}, """
																		    f"""has to be one of: { ", ".join(log_levels.keys()						) }"""						)
						return _default_log_level


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						return __name__.split("."						)[0]


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						return logging.getLogger(_get_library_name()						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						_UpperCAmelCase													=     _get_library_root_logger()
						library_root_logger.setLevel(_get_default_logging_level()						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						_UpperCAmelCase													=     _get_library_root_logger()
						library_root_logger.setLevel(logging.NOTSET						)


def 							__SCREAMING_SNAKE_CASE  (			snake_case_ = None						):

						'''simple docstring'''


						if name is None:
												_UpperCAmelCase													=     _get_library_name()
						return logging.getLogger(lowercase__						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						return _get_library_root_logger().getEffectiveLevel()


def 							__SCREAMING_SNAKE_CASE  (			snake_case_						):

						'''simple docstring'''


						_get_library_root_logger().setLevel(lowercase__						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						return set_verbosity(lowercase__						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						return set_verbosity(lowercase__						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						return set_verbosity(lowercase__						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						return set_verbosity(lowercase__						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						_UpperCAmelCase													=     False


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						_UpperCAmelCase													=     True


# Configure the library root logger at the module level (singleton-like)
_configure_library_root_logger()






class     __lowerCAmelCase :







			def __init__(       self    :			str    ,    *snake_case__    :			Dict    ,    **snake_case__    :			List[str]      ):  # pylint: disable=unused-argument




									"""simple docstring"""


									_UpperCAmelCase													=     args[0] if args else None







			def __iter__(       self    :			List[Any]      ):




									"""simple docstring"""


									return iter(self._iterator      )







			def __getattr__(       self    :			Tuple    ,    snake_case__    :			List[Any]      ):




									"""simple docstring"""


									def empty_fn(*snake_case__    :			int    ,    **snake_case__    :			List[Any]      ):  # pylint: disable=unused-argument
															return

									return empty_fn







			def __enter__(       self    :			List[str]      ):




									"""simple docstring"""


									return self







			def __exit__(       self    :			Optional[int]    ,    snake_case__    :			List[Any]    ,    snake_case__    :			List[Any]    ,    snake_case__    :			Optional[Any]      ):




									"""simple docstring"""


									return




lowercase_	:				Any  				= True






class     __lowerCAmelCase :







			def __call__(       self    :			List[Any]    ,    *snake_case__    :			Dict    ,    snake_case__    :			Dict=False    ,    **snake_case__    :			int      ):




									"""simple docstring"""


									if _tqdm_active and not disable:
															return tqdm_lib.tqdm(*snake_case__    ,    **snake_case__      )
									else:
															return EmptyTqdm(*snake_case__    ,    **snake_case__      )







			def UpperCamelCase			(       self    :			Any    ,    *snake_case__    :			List[str]    ,    **snake_case__    :			int      ):




									"""simple docstring"""


									_UpperCAmelCase													=     None
									if _tqdm_active:
															return tqdm_lib.tqdm.set_lock(*snake_case__    ,    **snake_case__      )







			def UpperCamelCase			(       self    :			str      ):




									"""simple docstring"""


									if _tqdm_active:
															return tqdm_lib.tqdm.get_lock()




lowercase_	:				List[Any]  				= _tqdm_cls()


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						global _tqdm_active
						return bool(_tqdm_active						)


def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						global _tqdm_active
						_UpperCAmelCase													=     True





def 							__SCREAMING_SNAKE_CASE  (			):

						'''simple docstring'''


						global _tqdm_active
						_UpperCAmelCase													=     False








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       A    (   enum.Enum ):
							UpperCamelCase_   :							Optional[int]       =0
							UpperCamelCase_   :							Tuple       =1
							UpperCamelCase_   :							Optional[int]       =2





@add_end_docstrings(A_ )
class       A    (   A_ ):
							UpperCamelCase_   :							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      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
									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.
											__lowercase=			None
											if self.model.config.prefix is not None:
													__lowercase=			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.
													__lowercase=			self.XL_PREFIX
											if prefix is not None:
													# Recalculate some generate_kwargs linked to prefix.
													__lowercase,							__lowercase,							__lowercase=			self._sanitize_parameters(prefix=lowerCAmelCase      ,				**self._forward_params					)
													__lowercase=			{**self._preprocess_params, **preprocess_params}
													__lowercase=			{**self._forward_params, **forward_params}


							def 			_A       (self      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				**lowerCAmelCase      ,				):
									__lowercase=			{}
									if prefix is not None:
											__lowercase=			prefix
									if prefix:
											__lowercase=			self.tokenizer(
											    lowerCAmelCase      ,				padding=lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase      ,				return_tensors=self.framework					)
											__lowercase=			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\']'					)
											__lowercase=			handle_long_generation

									preprocess_params.update(lowerCAmelCase					)
									__lowercase=			generate_kwargs

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

									if stop_sequence is not None:
											__lowercase=			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.'					)
											__lowercase=			stop_sequence_ids[0]

									return preprocess_params, forward_params, postprocess_params


							def 			_A       (self      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
									# 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      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									return super().__call__(lowerCAmelCase      ,				**lowerCAmelCase					)


							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase=""      ,				lowerCAmelCase=None      ,				**lowerCAmelCase					):
									__lowercase=			self.tokenizer(
									    prefix + prompt_text      ,				padding=lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase      ,				return_tensors=self.framework					)
									__lowercase=			prompt_text

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

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

									return inputs


							def 			_A       (self      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									__lowercase=			model_inputs['input_ids']
									__lowercase=			model_inputs.get('attention_mask'      ,				lowerCAmelCase					)
									# Allow empty prompts
									if input_ids.shape[1] == 0:
											__lowercase=			None
											__lowercase=			None
											__lowercase=			1
									else:
											__lowercase=			input_ids.shape[0]
									__lowercase=			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.
									__lowercase=			generate_kwargs.pop('prefix_length'      ,				0					)
									if prefix_length > 0:
											__lowercase=			'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:
													__lowercase=			generate_kwargs.get('max_length'					) or self.model.config.max_length
													generate_kwargs["max_length"] += prefix_length
											__lowercase=			'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
									__lowercase=			self.model.generate(input_ids=lowerCAmelCase      ,				attention_mask=lowerCAmelCase      ,				**lowerCAmelCase					)
									__lowercase=			generated_sequence.shape[0]
									if self.framework == "pt":
											__lowercase=			generated_sequence.reshape(lowerCAmelCase      ,				out_b // in_b      ,				*generated_sequence.shape[1:]					)
									elif self.framework == "tf":
											__lowercase=			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      ,				lowerCAmelCase      ,				lowerCAmelCase=ReturnType.FULL_TEXT      ,				lowerCAmelCase=True					):
									__lowercase=			model_outputs['generated_sequence'][0]
									__lowercase=			model_outputs['input_ids']
									__lowercase=			model_outputs['prompt_text']
									__lowercase=			generated_sequence.numpy().tolist()
									__lowercase=			[]
									for sequence in generated_sequence:
											if return_type == ReturnType.TENSORS:
													__lowercase=			{'generated_token_ids': sequence}
											elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
													# Decode text
													__lowercase=			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:
															__lowercase=			0
													else:
															__lowercase=			len(
															    self.tokenizer.decode(
															        input_ids[0]      ,				skip_special_tokens=lowerCAmelCase      ,				clean_up_tokenization_spaces=lowerCAmelCase      ,				)					)

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

													__lowercase=			{'generated_text': all_text}
											records.append(lowerCAmelCase					)

									return records






