


import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
			import tensorflow as tf

			from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
			from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

__snake_case      = logging.get_logger(__name__)




class  UpperCAmelCase       (							enum.Enum     ):
			lowercase						       =			0
			lowercase						       =			1




@add_end_docstrings(UpperCamelCase__     )
class  UpperCAmelCase       (							UpperCamelCase__     ):
			lowercase						       =			'generated'




			def __init__(    self				:		Any							,							*__magic_name__				:		str							,							**__magic_name__				:		Optional[Any]    ):







						"""simple docstring"""







						super().__init__(*__magic_name__							,							**__magic_name__    )

						self.check_model_type(
						    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
						    if self.framework == """tf"""
						    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING    )




			def 	lowerCamelCase_       (    self				:		str							,							__magic_name__				:		Dict=None							,							__magic_name__				:		Optional[Any]=None							,							__magic_name__				:		List[Any]=None							,							__magic_name__				:		int=None							,							__magic_name__				:		Optional[int]=None							,							__magic_name__				:		Any=None							,							**__magic_name__				:		Optional[int]							,							):







						"""simple docstring"""







						UpperCamelCase								=       {}
						if truncation is not None:
									UpperCamelCase								=       truncation

						UpperCamelCase								=       generate_kwargs

						UpperCamelCase								=       {}
						if return_tensors is not None and return_type is None:
									UpperCamelCase								=       ReturnType.TENSORS if return_tensors else ReturnType.TEXT
						if return_type is not None:
									UpperCamelCase								=       return_type

						if clean_up_tokenization_spaces is not None:
									UpperCamelCase								=       clean_up_tokenization_spaces

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

						return preprocess_params, forward_params, postprocess_params




			def 	lowerCamelCase_       (    self				:		Tuple							,							__magic_name__				:		Optional[Any]							,							__magic_name__				:		List[str]							,							__magic_name__				:		List[Any]    ):







						"""simple docstring"""







						return True




			def 	lowerCamelCase_       (    self				:		str							,							*__magic_name__				:		Tuple							,							__magic_name__				:		List[str]    ):







						"""simple docstring"""







						UpperCamelCase								=       self.model.config.prefix if self.model.config.prefix is not None else """"""
						if isinstance(args[0]							,							__magic_name__    ):
									if self.tokenizer.pad_token_id is None:
												raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input"""    )
									UpperCamelCase								=       ([prefix + arg for arg in args[0]],)
									UpperCamelCase								=       True

						elif isinstance(args[0]							,							__magic_name__    ):
									UpperCamelCase								=       (prefix + args[0],)
									UpperCamelCase								=       False
						else:
									raise ValueError(
									    F' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`'    )
						UpperCamelCase								=       self.tokenizer(*__magic_name__							,							padding=__magic_name__							,							truncation=__magic_name__							,							return_tensors=self.framework    )
						# This is produced by tokenizers but is an invalid generate kwargs
						if "token_type_ids" in inputs:
									del inputs["token_type_ids"]
						return inputs




			def __call__(    self				:		str							,							*__magic_name__				:		Optional[Any]							,							**__magic_name__				:		List[Any]    ):







						"""simple docstring"""







						UpperCamelCase								=       super().__call__(*__magic_name__							,							**__magic_name__    )
						if (
						    isinstance(args[0]							,							__magic_name__    )
						    and all(isinstance(__magic_name__							,							__magic_name__    ) for el in args[0]    )
						    and all(len(__magic_name__    ) == 1 for res in result    )
						):
									return [res[0] for res in result]
						return result




			def 	lowerCamelCase_       (    self				:		List[str]							,							__magic_name__				:		Tuple							,							__magic_name__				:		Tuple=TruncationStrategy.DO_NOT_TRUNCATE							,							**__magic_name__				:		Optional[Any]    ):







						"""simple docstring"""







						UpperCamelCase								=       self._parse_and_tokenize(__magic_name__							,							truncation=__magic_name__							,							**__magic_name__    )
						return inputs




			def 	lowerCamelCase_       (    self				:		Optional[Any]							,							__magic_name__				:		Union[str, Any]							,							**__magic_name__				:		Optional[int]    ):







						"""simple docstring"""







						if self.framework == "pt":
									UpperCamelCase	,	UpperCamelCase								=       model_inputs["""input_ids"""].shape
						elif self.framework == "tf":
									UpperCamelCase	,	UpperCamelCase								=       tf.shape(model_inputs["""input_ids"""]    ).numpy()

						UpperCamelCase								=       generate_kwargs.get("""min_length"""							,							self.model.config.min_length    )
						UpperCamelCase								=       generate_kwargs.get("""max_length"""							,							self.model.config.max_length    )
						self.check_inputs(__magic_name__							,							generate_kwargs["""min_length"""]							,							generate_kwargs["""max_length"""]    )
						UpperCamelCase								=       self.model.generate(**__magic_name__							,							**__magic_name__    )
						UpperCamelCase								=       output_ids.shape[0]
						if self.framework == "pt":
									UpperCamelCase								=       output_ids.reshape(__magic_name__							,							out_b // in_b							,							*output_ids.shape[1:]    )
						elif self.framework == "tf":
									UpperCamelCase								=       tf.reshape(__magic_name__							,							(in_b, out_b // in_b, *output_ids.shape[1:])    )
						return {"output_ids": output_ids}





			def 	lowerCamelCase_       (    self				:		List[Any]							,							__magic_name__				:		List[str]							,							__magic_name__				:		Dict=ReturnType.TEXT							,							__magic_name__				:		List[str]=False    ):







						"""simple docstring"""







						UpperCamelCase								=       []
						for output_ids in model_outputs["output_ids"][0]:
									if return_type == ReturnType.TENSORS:
												UpperCamelCase								=       {F'{self.return_name}_token_ids': output_ids}
									elif return_type == ReturnType.TEXT:
												UpperCamelCase								=       {
												    F'{self.return_name}_text': self.tokenizer.decode(
												        __magic_name__							,							skip_special_tokens=__magic_name__							,							clean_up_tokenization_spaces=__magic_name__							,							)
												}
									records.append(__magic_name__    )
						return records




@add_end_docstrings(UpperCamelCase__     )
class  UpperCAmelCase       (							UpperCamelCase__     ):
			lowercase						       =			'summary'




			def __call__(    self				:		Dict							,							*__magic_name__				:		Any							,							**__magic_name__				:		int    ):







						"""simple docstring"""







						return super().__call__(*__magic_name__							,							**__magic_name__    )





			def 	lowerCamelCase_       (    self				:		Tuple							,							__magic_name__				:		List[Any]							,							__magic_name__				:		Tuple							,							__magic_name__				:		Optional[Any]    ):







						"""simple docstring"""







						if max_length < min_length:
									logger.warning(F'Your min_length={min_length} must be inferior than your max_length={max_length}.'    )

						if input_length < max_length:
									logger.warning(
									    F'Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '
									    """a summarization task, where outputs shorter than the input are typically wanted, you might """
									    F'consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})'    )




@add_end_docstrings(UpperCamelCase__     )
class  UpperCAmelCase       (							UpperCamelCase__     ):
			lowercase						       =			'translation'




			def 	lowerCamelCase_       (    self				:		List[Any]							,							__magic_name__				:		List[str]							,							__magic_name__				:		Dict							,							__magic_name__				:		Optional[Any]    ):







						"""simple docstring"""







						if input_length > 0.9 * max_length:
									logger.warning(
									    F'Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '
									    """increasing your max_length manually, e.g. translator('...', max_length=400)"""    )
						return True




			def 	lowerCamelCase_       (    self				:		Union[str, Any]							,							*__magic_name__				:		Any							,							__magic_name__				:		int=TruncationStrategy.DO_NOT_TRUNCATE							,							__magic_name__				:		Any=None							,							__magic_name__				:		Any=None    ):







						"""simple docstring"""







						if getattr(self.tokenizer							,							"""_build_translation_inputs"""							,							__magic_name__    ):
									return self.tokenizer._build_translation_inputs(
									    *__magic_name__							,							return_tensors=self.framework							,							truncation=__magic_name__							,							src_lang=__magic_name__							,							tgt_lang=__magic_name__    )
						else:
									return super()._parse_and_tokenize(*__magic_name__							,							truncation=__magic_name__    )




			def 	lowerCamelCase_       (    self				:		Tuple							,							__magic_name__				:		Optional[int]=None							,							__magic_name__				:		Union[str, Any]=None							,							**__magic_name__				:		Optional[Any]    ):







						"""simple docstring"""







						UpperCamelCase	,	UpperCamelCase	,	UpperCamelCase								=       super()._sanitize_parameters(**__magic_name__    )
						if src_lang is not None:
									UpperCamelCase								=       src_lang
						if tgt_lang is not None:
									UpperCamelCase								=       tgt_lang
						if src_lang is None and tgt_lang is None:
									# Backward compatibility, direct arguments use is preferred.
									UpperCamelCase								=       kwargs.get("""task"""							,							self.task    )
									UpperCamelCase								=       task.split("""_"""    )
									if task and len(__magic_name__    ) == 4:
												# translation, XX, to YY
												UpperCamelCase								=       items[1]
												UpperCamelCase								=       items[3]
						return preprocess_params, forward_params, postprocess_params





			def __call__(    self				:		List[str]							,							*__magic_name__				:		Dict							,							**__magic_name__				:		Tuple    ):







						"""simple docstring"""







						return super().__call__(*__magic_name__							,							**__magic_name__    )






'''simple docstring'''
import enum
import shutil
import sys


lowercase__				, lowercase__											=shutil.get_terminal_size()

lowercase__											={'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'}







class   a_ (      enum.Enum					):
			lowerCamelCase__	:			int       =    0
			lowerCamelCase__	:			Union[str, Any]       =    1







def      UpperCamelCase_				(      A__  ,      A__=""						):
	sys.stdout.write(str(A__						) + end						)
	sys.stdout.flush()






def      UpperCamelCase_				(      A__  ,      A__  ,      A__=""						):
	forceWrite(F'''\u001b[{color}m{content}\u001b[0m'''  ,      A__						)






def      UpperCamelCase_				(      ):
	forceWrite("""\r"""						)






def      UpperCamelCase_				(      A__  ,      A__						):
	forceWrite(F'''\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}'''						)






def      UpperCamelCase_				(      ):
	forceWrite(""" """ * TERMINAL_WIDTH						)
	reset_cursor()






def      UpperCamelCase_				(      ):
	reset_cursor()
	forceWrite("""-""" * TERMINAL_WIDTH						)
