



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


__SCREAMING_SNAKE_CASE           =  False
try:
							__SCREAMING_SNAKE_CASE           =  _is_package_available("""google.colab""")
except ModuleNotFoundError:
							pass

@input.register
class 	lowerCamelCase_    :






						'''simple docstring'''







						def __init__(	self      :			Union[str, Any]	,	__lowerCamelCase      :			List[str] = None	,	__lowerCamelCase      :			str = [] )      ->				Tuple:
									A							:					Any              =						0
									A							:					Optional[Any]              =						choices
									A							:					Union[str, Any]              =						prompt
									if sys.platform == "win32":
												A							:					Optional[int]              =						"*"
									else:
												A							:					Optional[int]              =						"➔ "







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int]	,	__lowerCamelCase      :			str	,	__lowerCamelCase      :			Tuple = "" )      ->				Optional[Any]:
									if sys.platform != "win32":
												writeColor(self.choices[index]	,	32	,	__lowerCamelCase )
									else:
												forceWrite(self.choices[index]	,	__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Any	,	__lowerCamelCase      :			Optional[Any] )      ->				int:
									if index == self.position:
												forceWrite(F""" {self.arrow_char} """ )
												self.write_choice(__lowerCamelCase )
									else:
												forceWrite(F"""    {self.choices[index]}""" )
									reset_cursor()







						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str]	,	__lowerCamelCase      :			List[Any]	,	__lowerCamelCase      :			Optional[Any] = 1 )      ->				Tuple:
									A							:					Tuple              =						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(__lowerCamelCase )
									move_cursor(__lowerCamelCase	,	direction.name )
									self.print_choice(self.position )







						@input.mark(KEYMAP["up"] )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[Any] )      ->				int:
									self.move_direction(Direction.UP )







						@input.mark(KEYMAP["down"] )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[Any] )      ->				int:
									self.move_direction(Direction.DOWN )







						@input.mark(KEYMAP["newline"] )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[Any] )      ->				Any:
									move_cursor(len(self.choices ) - self.position	,	"DOWN" )
									return self.position







						@input.mark(KEYMAP["interrupt"] )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				Any:
									move_cursor(len(self.choices ) - self.position	,	"DOWN" )
									raise KeyboardInterrupt







						@input.mark_multiple(*[KEYMAP[str(__lowerCamelCase )] for number in range(10 )] )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				Union[str, Any]:
									A							:					List[Any]              =						int(chr(self.current_selection ) )
									A							:					str              =						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	,	__lowerCamelCase )
												else:
															return
									else:
												return







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Tuple	,	__lowerCamelCase      :			Any = 0 )      ->				int:
									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" )
									A							:					str              =						default_choice
									for i in range(len(self.choices ) ):
												self.print_choice(__lowerCamelCase )
												forceWrite("\n" )
									move_cursor(len(self.choices ) - self.position	,	"UP" )
									with cursor.hide():
												while True:
															if in_colab:
																		try:
																					A							:					Dict              =						int(builtins.input() )
																		except ValueError:
																					A							:					Dict              =						default_choice
															else:
																		A							:					List[str]              =						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(__lowerCamelCase	,	"\n" )
																		return choice










import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


__SCREAMING_SNAKE_CASE           =  logging.get_logger(__name__)


__SCREAMING_SNAKE_CASE           =  r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""

class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			Optional[int]	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Optional[Any] )      ->				bool:
									raise NotImplementedError("StoppingCriteria needs to be subclassed" )







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						def __init__(	self      :			List[str]	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			Optional[int] = None )      ->				List[Any]:
									A							:					str              =						max_length
									A							:					Optional[int]              =						max_position_embeddings







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			List[str]	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Any )      ->				bool:
									A							:					List[Any]              =						input_ids.shape[-1]
									A							:					Any              =						cur_len >= self.max_length
									if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
												logger.warning_once(
												    "This is a friendly reminder - the current text generation call will exceed the model's predefined "
												    F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """
												    "exceptions, performance degradation, or nothing at all." )
									return is_done







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						def __init__(	self      :			Optional[Any]	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			int )      ->				List[Any]:
									warnings.warn(
									    "The class `MaxNewTokensCriteria` is deprecated. "
									    F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """
									    "with `max_length = start_length + max_new_tokens` instead."	,	__lowerCamelCase	,	)
									A							:					str              =						start_length
									A							:					Optional[Any]              =						max_new_tokens
									A							:					Dict              =						start_length + max_new_tokens







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			int	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Tuple )      ->				bool:
									return input_ids.shape[-1] >= self.max_length







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						def __init__(	self      :			Optional[int]	,	__lowerCamelCase      :			float	,	__lowerCamelCase      :			Optional[float] = None )      ->				List[Any]:
									A							:					str              =						max_time
									A							:					Dict              =						time.time() if initial_timestamp is None else initial_timestamp







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			Any	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Tuple )      ->				bool:
									return time.time() - self.initial_timestamp > self.max_time







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			Union[str, Any]	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			int )      ->				bool:
									return any(criteria(__lowerCamelCase	,	__lowerCamelCase ) for criteria in self )







						@property
						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				Optional[int]:
									for stopping_criterium in self:
												if isinstance(__lowerCamelCase	,	__lowerCamelCase ):
															return stopping_criterium.max_length
												elif isinstance(__lowerCamelCase	,	__lowerCamelCase ):
															return stopping_criterium.max_length
									return None







def 	UpperCAmelCase   (						_lowerCamelCase ,    _lowerCamelCase    ):
			A							:					Optional[int]              =						stopping_criteria.max_length
			A							:					Any              =						deepcopy(_lowerCamelCase    )
			if stopping_max_length is not None and stopping_max_length != max_length:
						warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" ,    _lowerCamelCase    )
			elif stopping_max_length is None:
						new_stopping_criteria.append(MaxLengthCriteria(max_length=_lowerCamelCase    )    )
			return new_stopping_criteria