from importlib import import_module

from .logging import get_logger


lowerCamelCase__  =					get_logger(__name__)




class 					_UpperCAmelCase			:



 '''simple docstring'''




 def __init__(		self				:   List[Any]							, lowercase_				:   str							, lowercase_				:   Union[str, Any]=None)						->	Union[str, Any]:


   """simple docstring"""







   _UpperCamelCase           =    attrs or []
   if module is not None:
     for key in module.__dict__:
       if key in attrs or not key.startswith("__"):
         setattr(self							, lowercase_							, getattr(lowercase_							, lowercase_))
   _UpperCamelCase           =    module._original_module if isinstance(lowercase_							, _PatchedModuleObj) else module




class 					_UpperCAmelCase			:



 '''simple docstring'''




 __A			       =					[]







 def __init__(		self				:   Optional[int]							, lowercase_				:   Optional[int]							, lowercase_				:   str							, lowercase_				:   Optional[int]							, lowercase_				:   List[str]=None)						->	int:


   """simple docstring"""







   _UpperCamelCase           =    obj
   _UpperCamelCase           =    target
   _UpperCamelCase           =    new
   _UpperCamelCase           =    target.split(".")[0]
   _UpperCamelCase           =    {}
   _UpperCamelCase           =    attrs or []







 def __enter__(		self				:   List[str])						->	List[Any]:


   """simple docstring"""







   *_UpperCamelCase      ,						_UpperCamelCase           =    self.target.split(".")

   # Patch modules:
   # it's used to patch attributes of submodules like "os.path.join";
   # in this case we need to patch "os" and "os.path"

   for i in range(len(lowercase_)):
     try:
       _UpperCamelCase           =    import_module(".".join(submodules[: i + 1]))
     except ModuleNotFoundError:
       continue
     # We iterate over all the globals in self.obj in case we find "os" or "os.path"
     for attr in self.obj.__dir__():
       _UpperCamelCase           =    getattr(self.obj							, lowercase_)
       # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
       # This allows to patch renamed modules like "from os import path as ospath".
       if obj_attr is submodule or (
           (isinstance(lowercase_							, _PatchedModuleObj) and obj_attr._original_module is submodule)
       ):
         _UpperCamelCase           =    obj_attr
         # patch at top level
         setattr(self.obj							, lowercase_							, _PatchedModuleObj(lowercase_							, attrs=self.attrs))
         _UpperCamelCase           =    getattr(self.obj							, lowercase_)
         # construct lower levels patches
         for key in submodules[i + 1 :]:
           setattr(lowercase_							, lowercase_							, _PatchedModuleObj(getattr(lowercase_							, lowercase_							, lowercase_)							, attrs=self.attrs))
           _UpperCamelCase           =    getattr(lowercase_							, lowercase_)
         # finally set the target attribute
         setattr(lowercase_							, lowercase_							, self.new)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

   if submodules:  # if it's an attribute of a submodule like "os.path.join"
     try:
       _UpperCamelCase           =    getattr(import_module(".".join(lowercase_))							, lowercase_)
     except (AttributeError, ModuleNotFoundError):
       return
     # We iterate over all the globals in self.obj in case we find "os.path.join"
     for attr in self.obj.__dir__():
       # We don't check for the name of the global, but rather if its value *is* "os.path.join".
       # This allows to patch renamed attributes like "from os.path import join as pjoin".
       if getattr(self.obj							, lowercase_) is attr_value:
         _UpperCamelCase           =    getattr(self.obj							, lowercase_)
         setattr(self.obj							, lowercase_							, self.new)
   elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
     _UpperCamelCase           =    globals()["__builtins__"][target_attr]
     setattr(self.obj							, lowercase_							, self.new)
   else:
     raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.')







 def __exit__(		self				:   Tuple							, *lowercase_				:   Any)						->	List[str]:


   """simple docstring"""







   for attr in list(self.original):
     setattr(self.obj							, lowercase_							, self.original.pop(lowercase_))







 def 		__UpperCAmelCase				(		self				:   Union[str, Any])						->	Tuple:


   """simple docstring"""







   self.__enter__()
   self._active_patches.append(self)







 def 		__UpperCAmelCase				(		self				:   List[Any])						->	Optional[Any]:


   """simple docstring"""







   try:
     self._active_patches.remove(self)
   except ValueError:
     # If the patch hasn't been started this will fail
     return None

   return self.__exit__()





import time
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
   import torch

   from transformers.generation import (
       MaxLengthCriteria,
       MaxNewTokensCriteria,
       MaxTimeCriteria,
       StoppingCriteriaList,
       validate_stopping_criteria,
   )




@require_torch
class 					_UpperCAmelCase			(     unittest.TestCase  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   List[Any]							, lowercase_				:   Dict)						->	Optional[Any]:


   """simple docstring"""







   _UpperCamelCase           =    3
   _UpperCamelCase           =    250

   _UpperCamelCase           =    ids_tensor((batch_size, length)							, lowercase_)
   _UpperCamelCase           =    torch.ones((batch_size, length)							, device=lowercase_							, dtype=torch.float) / length
   return input_ids, scores







 def 		__UpperCAmelCase				(		self				:   Any)						->	Optional[int]:


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)

   _UpperCamelCase           =    StoppingCriteriaList(
       [
           MaxLengthCriteria(max_length=10),
           MaxTimeCriteria(max_time=0.1),
       ])

   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(9)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(10)
   self.assertTrue(criteria(lowercase_							, lowercase_))







 def 		__UpperCAmelCase				(		self				:   Tuple)						->	int:


   """simple docstring"""







   _UpperCamelCase           =    MaxLengthCriteria(max_length=10)

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(9)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(10)
   self.assertTrue(criteria(lowercase_							, lowercase_))







 def 		__UpperCAmelCase				(		self				:   Optional[int])						->	int:


   """simple docstring"""







   _UpperCamelCase           =    MaxNewTokensCriteria(start_length=5							, max_new_tokens=5)

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(9)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(10)
   self.assertTrue(criteria(lowercase_							, lowercase_))

   _UpperCamelCase           =    StoppingCriteriaList([criteria])
   self.assertEqual(criteria_list.max_length							, 10)







 def 		__UpperCAmelCase				(		self				:   int)						->	str:


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)

   _UpperCamelCase           =    MaxTimeCriteria(max_time=0.1)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase           =    MaxTimeCriteria(max_time=0.1							, initial_timestamp=time.time() - 0.2)
   self.assertTrue(criteria(lowercase_							, lowercase_))







 def 		__UpperCAmelCase				(		self				:   Optional[int])						->	Tuple:


   """simple docstring"""







   validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)])							, 10)

   with self.assertWarns(lowercase_):
     validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)])							, 11)

   _UpperCamelCase           =    validate_stopping_criteria(StoppingCriteriaList()							, 11)

   self.assertEqual(len(lowercase_)							, 1)




