





"""simple docstring"""





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

_UpperCamelCase							=      logging.get_logger(__name__)
class 		SCREAMING_SNAKE_CASE_							(    enum.Enum   ):
				"""simple docstring"""
				__snake_case   :       Optional[int]	 =		0
				__snake_case   :       Optional[Any]	 =		1

@add_end_docstrings(snake_case__   )
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""
				__snake_case   :       List[str]	 =		"""generated"""




				def __init__(     self  :str						,    *__lowercase  :Optional[int]						,    **__lowercase  :List[Any]			):
											super().__init__(*__lowercase						,    **__lowercase			)

											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 					__lowercase  (     self  :Tuple						,    __lowercase  :Any=None						,    __lowercase  :Tuple=None						,    __lowercase  :List[str]=None						,    __lowercase  :Tuple=None						,    __lowercase  :int=None						,    __lowercase  :str=None						,    **__lowercase  :Optional[Any]						,    ):
											__lowerCamelCase      :      Dict         ={}
											if truncation is not None:
																		__lowerCamelCase      :      Tuple         =truncation

											__lowerCamelCase      :      str         =generate_kwargs

											__lowerCamelCase      :      List[Any]         ={}
											if return_tensors is not None and return_type is None:
																		__lowerCamelCase      :      Any         =ReturnType.TENSORS if return_tensors else ReturnType.TEXT
											if return_type is not None:
																		__lowerCamelCase      :      str         =return_type

											if clean_up_tokenization_spaces is not None:
																		__lowerCamelCase      :      int         =clean_up_tokenization_spaces

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

											return preprocess_params, forward_params, postprocess_params




				def 					__lowercase  (     self  :Optional[int]						,    __lowercase  :int						,    __lowercase  :int						,    __lowercase  :int			):
											return True




				def 					__lowercase  (     self  :Any						,    *__lowercase  :Any						,    __lowercase  :List[Any]			):
											__lowerCamelCase      :      Tuple         =self.model.config.prefix if self.model.config.prefix is not None else ''''''
											if isinstance(args[0]						,    __lowercase			):
																		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'''			)
																		__lowerCamelCase      :      List[Any]         =([prefix + arg for arg in args[0]],)
																		__lowerCamelCase      :      Optional[int]         =True

											elif isinstance(args[0]						,    __lowercase			):
																		__lowerCamelCase      :      Dict         =(prefix + args[0],)
																		__lowerCamelCase      :      Any         =False
											else:
																		raise ValueError(
																		    f' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`'			)
											__lowerCamelCase      :      Optional[int]         =self.tokenizer(*__lowercase						,    padding=__lowercase						,    truncation=__lowercase						,    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  :Union[str, Any]						,    *__lowercase  :Union[str, Any]						,    **__lowercase  :List[Any]			):
											__lowerCamelCase      :      List[str]         =super().__call__(*__lowercase						,    **__lowercase			)
											if (
											    isinstance(args[0]						,    __lowercase			)
											    and all(isinstance(__lowercase						,    __lowercase			) for el in args[0]			)
											    and all(len(__lowercase			) == 1 for res in result			)
											):
																		return [res[0] for res in result]
											return result




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :Tuple						,    __lowercase  :Union[str, Any]=TruncationStrategy.DO_NOT_TRUNCATE						,    **__lowercase  :List[Any]			):
											__lowerCamelCase      :      Optional[Any]         =self._parse_and_tokenize(__lowercase						,    truncation=__lowercase						,    **__lowercase			)
											return inputs




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :Any						,    **__lowercase  :List[str]			):
											if self.framework == "pt":
																		__lowerCamelCase    ,						__lowerCamelCase      :      Tuple         =model_inputs['''input_ids'''].shape
											elif self.framework == "tf":
																		__lowerCamelCase    ,						__lowerCamelCase      :      str         =tf.shape(model_inputs['''input_ids''']			).numpy()

											__lowerCamelCase      :      List[Any]         =generate_kwargs.get('''min_length'''						,    self.model.config.min_length			)
											__lowerCamelCase      :      Optional[int]         =generate_kwargs.get('''max_length'''						,    self.model.config.max_length			)
											self.check_inputs(__lowercase						,    generate_kwargs['''min_length''']						,    generate_kwargs['''max_length''']			)
											__lowerCamelCase      :      Any         =self.model.generate(**__lowercase						,    **__lowercase			)
											__lowerCamelCase      :      int         =output_ids.shape[0]
											if self.framework == "pt":
																		__lowerCamelCase      :      Tuple         =output_ids.reshape(__lowercase						,    out_b // in_b						,    *output_ids.shape[1:]			)
											elif self.framework == "tf":
																		__lowerCamelCase      :      Any         =tf.reshape(__lowercase						,    (in_b, out_b // in_b, *output_ids.shape[1:])			)
											return {"output_ids": output_ids}




				def 					__lowercase  (     self  :Any						,    __lowercase  :List[str]						,    __lowercase  :Tuple=ReturnType.TEXT						,    __lowercase  :str=False			):
											__lowerCamelCase      :      Any         =[]
											for output_ids in model_outputs["output_ids"][0]:
																		if return_type == ReturnType.TENSORS:
																									__lowerCamelCase      :      Optional[int]         ={f'{self.return_name}_token_ids': output_ids}
																		elif return_type == ReturnType.TEXT:
																									__lowerCamelCase      :      Union[str, Any]         ={
																									    f'{self.return_name}_text': self.tokenizer.decode(
																									        __lowercase						,    skip_special_tokens=__lowercase						,    clean_up_tokenization_spaces=__lowercase						,    )
																									}
																		records.append(__lowercase			)
											return records

@add_end_docstrings(snake_case__   )
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""
				__snake_case   :       Any	 =		"""summary"""




				def __call__(     self  :Tuple						,    *__lowercase  :str						,    **__lowercase  :Tuple			):
											return super().__call__(*__lowercase						,    **__lowercase			)




				def 					__lowercase  (     self  :Union[str, Any]						,    __lowercase  :int						,    __lowercase  :int						,    __lowercase  :int			):
											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(snake_case__   )
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""
				__snake_case   :       Union[str, Any]	 =		"""translation"""




				def 					__lowercase  (     self  :Optional[Any]						,    __lowercase  :int						,    __lowercase  :int						,    __lowercase  :int			):
											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 					__lowercase  (     self  :Tuple						,    *__lowercase  :Optional[Any]						,    __lowercase  :Optional[Any]=TruncationStrategy.DO_NOT_TRUNCATE						,    __lowercase  :Union[str, Any]=None						,    __lowercase  :Dict=None			):
											if getattr(self.tokenizer						,    '''_build_translation_inputs'''						,    __lowercase			):
																		return self.tokenizer._build_translation_inputs(
																		    *__lowercase						,    return_tensors=self.framework						,    truncation=__lowercase						,    src_lang=__lowercase						,    tgt_lang=__lowercase			)
											else:
																		return super()._parse_and_tokenize(*__lowercase						,    truncation=__lowercase			)




				def 					__lowercase  (     self  :Optional[int]						,    __lowercase  :Dict=None						,    __lowercase  :List[str]=None						,    **__lowercase  :Union[str, Any]			):
											__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase      :      Optional[int]         =super()._sanitize_parameters(**__lowercase			)
											if src_lang is not None:
																		__lowerCamelCase      :      Union[str, Any]         =src_lang
											if tgt_lang is not None:
																		__lowerCamelCase      :      List[str]         =tgt_lang
											if src_lang is None and tgt_lang is None:
																		# Backward compatibility, direct arguments use is preferred.
																		__lowerCamelCase      :      List[str]         =kwargs.get('''task'''						,    self.task			)
																		__lowerCamelCase      :      Any         =task.split('''_'''			)
																		if task and len(__lowercase			) == 4:
																									# translation, XX, to YY
																									__lowerCamelCase      :      Tuple         =items[1]
																									__lowerCamelCase      :      List[Any]         =items[3]
											return preprocess_params, forward_params, postprocess_params




				def __call__(     self  :Any						,    *__lowercase  :Dict						,    **__lowercase  :Optional[int]			):
											return super().__call__(*__lowercase						,    **__lowercase			)











"""simple docstring"""





import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


_UpperCamelCase							=      False
try:
							_UpperCamelCase							=      _is_package_available('google.colab')
except ModuleNotFoundError:
							pass
@input.register
class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




				def __init__(     self  :Union[str, Any]						,    __lowercase  :str = None						,    __lowercase  :list = []			):
											__lowerCamelCase      :      Any         =0
											__lowerCamelCase      :      List[str]         =choices
											__lowerCamelCase      :      int         =prompt
											if sys.platform == "win32":
																		__lowerCamelCase      :      Dict         ='''*'''
											else:
																		__lowerCamelCase      :      Union[str, Any]         ='''➔ '''




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :Any						,    __lowercase  :str = ""			):
											if sys.platform != "win32":
																		writeColor(self.choices[index]						,    32						,    __lowercase			)
											else:
																		forceWrite(self.choices[index]						,    __lowercase			)




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :int			):
											if index == self.position:
																		forceWrite(f' {self.arrow_char} '			)
																		self.write_choice(__lowercase			)
											else:
																		forceWrite(f'    {self.choices[index]}'			)
											reset_cursor()




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :Direction						,    __lowercase  :int = 1			):
											__lowerCamelCase      :      List[str]         =self.position
											if direction == Direction.DOWN:
																		if self.position + 1 >= len(self.choices			):
																									return
																		self.position += num_spaces
											else:
																		if self.position - 1 < 0:
																									return
																		self.position -= num_spaces
											clear_line()
											self.print_choice(__lowercase			)
											move_cursor(__lowercase						,    direction.name			)
											self.print_choice(self.position			)




				@input.mark(KEYMAP['''up''']			)
				def 					__lowercase  (     self  :Union[str, Any]			):
											self.move_direction(Direction.UP			)




				@input.mark(KEYMAP['''down''']			)
				def 					__lowercase  (     self  :Union[str, Any]			):
											self.move_direction(Direction.DOWN			)




				@input.mark(KEYMAP['''newline''']			)
				def 					__lowercase  (     self  :Any			):
											move_cursor(len(self.choices			) - self.position						,    '''DOWN'''			)
											return self.position




				@input.mark(KEYMAP['''interrupt''']			)
				def 					__lowercase  (     self  :Any			):
											move_cursor(len(self.choices			) - self.position						,    '''DOWN'''			)
											raise KeyboardInterrupt




				@input.mark_multiple(*[KEYMAP[str(__lowercase			)] for number in range(10			)]			)
				def 					__lowercase  (     self  :Any			):
											__lowerCamelCase      :      Tuple         =int(chr(self.current_selection			)			)
											__lowerCamelCase      :      Dict         =index - self.position
											if index == self.position:
																		return
											if index < len(self.choices			):
																		if self.position > index:
																									self.move_direction(Direction.UP						,    -movement			)
																		elif self.position < index:
																									self.move_direction(Direction.DOWN						,    __lowercase			)
																		else:
																									return
											else:
																		return




				def 					__lowercase  (     self  :Optional[int]						,    __lowercase  :int = 0			):
											if self.prompt:
																		linebreak()
																		forceWrite(self.prompt						,    '''\n'''			)
																		if in_colab:
																									forceWrite('''Please input a choice index (starting from 0), and press enter'''						,    '''\n'''			)
																		else:
																									forceWrite('''Please select a choice using the arrow or number keys, and selecting with enter'''						,    '''\n'''			)
											__lowerCamelCase      :      Union[str, Any]         =default_choice
											for i in range(len(self.choices			)			):
																		self.print_choice(__lowercase			)
																		forceWrite('''\n'''			)
											move_cursor(len(self.choices			) - self.position						,    '''UP'''			)
											with cursor.hide():
																		while True:
																									if in_colab:
																																try:
																																							__lowerCamelCase      :      Union[str, Any]         =int(builtins.input()			)
																																except ValueError:
																																							__lowerCamelCase      :      Optional[Any]         =default_choice
																									else:
																																__lowerCamelCase      :      Dict         =self.handle_input()
																									if choice is not None:
																																reset_cursor()
																																for _ in range(len(self.choices			) + 1			):
																																							move_cursor(1						,    '''UP'''			)
																																							clear_line()
																																self.write_choice(__lowercase						,    '''\n'''			)
																																return choice




