
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


lowerCamelCase_  :	Dict 				=					logging.get_logger(__name__)


lowerCamelCase_  :	Dict 				=					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     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			@add_start_docstrings(snake_case_ )
			def __call__(    self	:    Union[str, Any]  ,		snake_case_	:    torch.LongTensor  ,		snake_case_	:    torch.FloatTensor  ,		**snake_case_	:    Union[str, Any] ):
							raise NotImplementedError("""StoppingCriteria needs to be subclassed""" )




class     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			def __init__(    self	:    Optional[int]  ,		snake_case_	:    int  ,		snake_case_	:    Optional[int] = None ):
							UpperCamelCase_:							Optional[Any]		=  max_length
							UpperCamelCase_:							Any		=  max_position_embeddings




			@add_start_docstrings(snake_case_ )
			def __call__(    self	:    int  ,		snake_case_	:    torch.LongTensor  ,		snake_case_	:    torch.FloatTensor  ,		**snake_case_	:    List[str] ):
							UpperCamelCase_:							Optional[int]		=  input_ids.shape[-1]
							UpperCamelCase_:							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     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			def __init__(    self	:    Optional[int]  ,		snake_case_	:    int  ,		snake_case_	:    int ):
							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."""  ,		snake_case_  ,		)
							UpperCamelCase_:							str		=  start_length
							UpperCamelCase_:							Optional[Any]		=  max_new_tokens
							UpperCamelCase_:							Optional[Any]		=  start_length + max_new_tokens




			@add_start_docstrings(snake_case_ )
			def __call__(    self	:    List[Any]  ,		snake_case_	:    torch.LongTensor  ,		snake_case_	:    torch.FloatTensor  ,		**snake_case_	:    Union[str, Any] ):
							return input_ids.shape[-1] >= self.max_length




class     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			def __init__(    self	:    Any  ,		snake_case_	:    float  ,		snake_case_	:    Optional[float] = None ):
							UpperCamelCase_:							Optional[Any]		=  max_time
							UpperCamelCase_:							Dict		=  time.time() if initial_timestamp is None else initial_timestamp




			@add_start_docstrings(snake_case_ )
			def __call__(    self	:    Optional[Any]  ,		snake_case_	:    torch.LongTensor  ,		snake_case_	:    torch.FloatTensor  ,		**snake_case_	:    Tuple ):
							return time.time() - self.initial_timestamp > self.max_time




class     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			@add_start_docstrings(snake_case_ )
			def __call__(    self	:    List[str]  ,		snake_case_	:    torch.LongTensor  ,		snake_case_	:    torch.FloatTensor  ,		**snake_case_	:    List[str] ):
							return any(criteria(snake_case_  ,		snake_case_ ) for criteria in self )




			@property
			def  lowerCAmelCase__		(    self	:    Any ):
							for stopping_criterium in self:
											if isinstance(snake_case_  ,		snake_case_ ):
															return stopping_criterium.max_length
											elif isinstance(snake_case_  ,		snake_case_ ):
															return stopping_criterium.max_length
							return None







def     A__   (  lowerCamelCase       ,      lowerCamelCase  )					->		StoppingCriteriaList:
				UpperCamelCase_:							Tuple		=  stopping_criteria.max_length
				UpperCamelCase_:							Optional[int]		=  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








from datasets.utils.patching import _PatchedModuleObj, patch_submodule

from . import _test_patching







def     A__   (  )					->		Union[str, Any]:
				import os as original_os
				from os import path as original_path
				from os import rename as original_rename
				from os.path import dirname as original_dirname
				from os.path import join as original_join

				assert _test_patching.os is original_os
				assert _test_patching.path is original_path
				assert _test_patching.join is original_join

				assert _test_patching.renamed_os is original_os
				assert _test_patching.renamed_path is original_path
				assert _test_patching.renamed_join is original_join

				UpperCamelCase_:							Optional[int]		=  """__test_patch_submodule_mock__"""
				with patch_submodule(_test_patching       ,      """os.path.join"""       ,      lowerCamelCase  ):
								# Every way to access os.path.join must be patched, and the rest must stay untouched

								# check os.path.join
								assert isinstance(_test_patching.os       ,      _PatchedModuleObj  )
								assert isinstance(_test_patching.os.path       ,      _PatchedModuleObj  )
								assert _test_patching.os.path.join is mock

								# check path.join
								assert isinstance(_test_patching.path       ,      _PatchedModuleObj  )
								assert _test_patching.path.join is mock

								# check join
								assert _test_patching.join is mock

								# check that the other attributes are untouched
								assert _test_patching.os.rename is original_rename
								assert _test_patching.path.dirname is original_dirname
								assert _test_patching.os.path.dirname is original_dirname

								# Even renamed modules or objects must be patched

								# check renamed_os.path.join
								assert isinstance(_test_patching.renamed_os       ,      _PatchedModuleObj  )
								assert isinstance(_test_patching.renamed_os.path       ,      _PatchedModuleObj  )
								assert _test_patching.renamed_os.path.join is mock

								# check renamed_path.join
								assert isinstance(_test_patching.renamed_path       ,      _PatchedModuleObj  )
								assert _test_patching.renamed_path.join is mock

								# check renamed_join
								assert _test_patching.renamed_join is mock

								# check that the other attributes are untouched
								assert _test_patching.renamed_os.rename is original_rename
								assert _test_patching.renamed_path.dirname is original_dirname
								assert _test_patching.renamed_os.path.dirname is original_dirname

				# check that everthing is back to normal when the patch is over

				assert _test_patching.os is original_os
				assert _test_patching.path is original_path
				assert _test_patching.join is original_join

				assert _test_patching.renamed_os is original_os
				assert _test_patching.renamed_path is original_path
				assert _test_patching.renamed_join is original_join







def     A__   (  )					->		Union[str, Any]:
				assert _test_patching.open is open

				UpperCamelCase_:							List[Any]		=  """__test_patch_submodule_builtin_mock__"""
				# _test_patching has "open" in its globals
				assert _test_patching.open is open
				with patch_submodule(_test_patching       ,      """open"""       ,      lowerCamelCase  ):
								assert _test_patching.open is mock

				# check that everthing is back to normal when the patch is over

				assert _test_patching.open is open







def     A__   (  )					->		Optional[Any]:
				# pandas.read_csv is not present in _test_patching
				UpperCamelCase_:							Optional[Any]		=  """__test_patch_submodule_missing_mock__"""
				with patch_submodule(_test_patching       ,      """pandas.read_csv"""       ,      lowerCamelCase  ):
								pass







def     A__   (  )					->		Any:
				# builtin should always be mocked even if they're not in the globals
				# in case they're loaded at one point
				UpperCamelCase_:							List[Any]		=  """__test_patch_submodule_missing_builtin_mock__"""
				# _test_patching doesn't have "len" in its globals
				assert getattr(_test_patching       ,      """len"""       ,      lowerCamelCase  ) is None
				with patch_submodule(_test_patching       ,      """len"""       ,      lowerCamelCase  ):
								assert _test_patching.len is mock
				assert _test_patching.len is len







def     A__   (  )					->		Any:
				UpperCamelCase_:							Dict		=  """__test_patch_submodule_start_and_stop_mock__"""
				UpperCamelCase_:							List[str]		=  patch_submodule(_test_patching       ,      """open"""       ,      lowerCamelCase  )
				assert _test_patching.open is open
				patch.start()
				assert _test_patching.open is mock
				patch.stop()
				assert _test_patching.open is open







def     A__   (  )					->		List[str]:
				from os import rename as original_rename
				from os.path import dirname as original_dirname
				from os.path import join as original_join

				UpperCamelCase_:							Optional[Any]		=  """__test_patch_submodule_successive_join__"""
				UpperCamelCase_:							Any		=  """__test_patch_submodule_successive_dirname__"""
				UpperCamelCase_:							Dict		=  """__test_patch_submodule_successive_rename__"""
				assert _test_patching.os.path.join is original_join
				assert _test_patching.os.path.dirname is original_dirname
				assert _test_patching.os.rename is original_rename

				with patch_submodule(_test_patching       ,      """os.path.join"""       ,      lowerCamelCase  ):
								with patch_submodule(_test_patching       ,      """os.rename"""       ,      lowerCamelCase  ):
												with patch_submodule(_test_patching       ,      """os.path.dirname"""       ,      lowerCamelCase  ):
																assert _test_patching.os.path.join is mock_join
																assert _test_patching.os.path.dirname is mock_dirname
																assert _test_patching.os.rename is mock_rename

    # try another order
				with patch_submodule(_test_patching       ,      """os.rename"""       ,      lowerCamelCase  ):
								with patch_submodule(_test_patching       ,      """os.path.join"""       ,      lowerCamelCase  ):
												with patch_submodule(_test_patching       ,      """os.path.dirname"""       ,      lowerCamelCase  ):
																assert _test_patching.os.path.join is mock_join
																assert _test_patching.os.path.dirname is mock_dirname
																assert _test_patching.os.rename is mock_rename

				assert _test_patching.os.path.join is original_join
				assert _test_patching.os.path.dirname is original_dirname
				assert _test_patching.os.rename is original_rename







def     A__   (  )					->		Union[str, Any]:
				UpperCamelCase_:							Dict		=  """__test_patch_submodule_doesnt_exist_mock__"""
				with patch_submodule(_test_patching       ,      """__module_that_doesn_exist__.__attribute_that_doesn_exist__"""       ,      lowerCamelCase  ):
								pass
				with patch_submodule(_test_patching       ,      """os.__attribute_that_doesn_exist__"""       ,      lowerCamelCase  ):
								pass






