



from importlib import import_module

from .logging import get_logger


__UpperCAmelCase          =       get_logger(__name__)



class 				lowerCAmelCase_		:
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_=None       )     ->		Union[str, Any]:
          UpperCamelCase    :  int							=	attrs or []
          if module is not None:
             for key in module.__dict__:
                if key in attrs or not key.startswith('__'       ):
                   setattr(self,			SCREAMING_SNAKE_CASE_,			getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       )       )
          UpperCamelCase    :  Any							=	module._original_module if isinstance(SCREAMING_SNAKE_CASE_,			_PatchedModuleObj       ) else module






class 				lowerCAmelCase_		:
       UpperCAmelCase__				:					Tuple        =  []
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_=None       )     ->		Tuple:
          UpperCamelCase    :  Tuple							=	obj
          UpperCamelCase    :  Optional[int]							=	target
          UpperCamelCase    :  Dict							=	new
          UpperCamelCase    :  int							=	target.split('.'       )[0]
          UpperCamelCase    :  Optional[int]							=	{}
          UpperCamelCase    :  Optional[int]							=	attrs or []
       def __enter__(			self       )     ->		List[Any]:
          *UpperCamelCase	,     UpperCamelCase    :  Dict							=	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(SCREAMING_SNAKE_CASE_       )       ):
             try:
                UpperCamelCase    :  Dict							=	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    :  Union[str, Any]							=	getattr(self.obj,			SCREAMING_SNAKE_CASE_       )
                # 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(SCREAMING_SNAKE_CASE_,			_PatchedModuleObj       ) and obj_attr._original_module is submodule)
                ):
                   UpperCamelCase    :  Dict							=	obj_attr
                   # patch at top level
                   setattr(self.obj,			SCREAMING_SNAKE_CASE_,			_PatchedModuleObj(SCREAMING_SNAKE_CASE_,			attrs=self.attrs       )       )
                   UpperCamelCase    :  List[str]							=	getattr(self.obj,			SCREAMING_SNAKE_CASE_       )
                   # construct lower levels patches
                   for key in submodules[i + 1 :]:
                      setattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			_PatchedModuleObj(getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       ),			attrs=self.attrs       )       )
                      UpperCamelCase    :  Optional[int]							=	getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       )
                   # finally set the target attribute
                   setattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			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    :  List[str]							=	getattr(import_module('.'.join(SCREAMING_SNAKE_CASE_       )       ),			SCREAMING_SNAKE_CASE_       )
             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,			SCREAMING_SNAKE_CASE_       ) is attr_value:
                   UpperCamelCase    :  Optional[int]							=	getattr(self.obj,			SCREAMING_SNAKE_CASE_       )
                   setattr(self.obj,			SCREAMING_SNAKE_CASE_,			self.new       )
          elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
             UpperCamelCase    :  Union[str, Any]							=	globals()['__builtins__'][target_attr]
             setattr(self.obj,			SCREAMING_SNAKE_CASE_,			self.new       )
          else:
             raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule."""       )
       def __exit__(			self,			*SCREAMING_SNAKE_CASE_       )     ->		Dict:
          for attr in list(self.original       ):
             setattr(self.obj,			SCREAMING_SNAKE_CASE_,			self.original.pop(SCREAMING_SNAKE_CASE_       )       )
       def 					snake_case_       (			self       )     ->		Union[str, Any]:
          self.__enter__()
          self._active_patches.append(self       )






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

          return self.__exit__()








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


__UpperCAmelCase          =       {
    '''configuration_transfo_xl''': ['''TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TransfoXLConfig'''],
    '''tokenization_transfo_xl''': ['''TransfoXLCorpus''', '''TransfoXLTokenizer'''],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __UpperCAmelCase          =       [
        '''TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST''',
        '''AdaptiveEmbedding''',
        '''TransfoXLForSequenceClassification''',
        '''TransfoXLLMHeadModel''',
        '''TransfoXLModel''',
        '''TransfoXLPreTrainedModel''',
        '''load_tf_weights_in_transfo_xl''',
    ]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __UpperCAmelCase          =       [
        '''TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST''',
        '''TFAdaptiveEmbedding''',
        '''TFTransfoXLForSequenceClassification''',
        '''TFTransfoXLLMHeadModel''',
        '''TFTransfoXLMainLayer''',
        '''TFTransfoXLModel''',
        '''TFTransfoXLPreTrainedModel''',
    ]


if TYPE_CHECKING:
    from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig
    from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_transfo_xl import (
            TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
            AdaptiveEmbedding,
            TransfoXLForSequenceClassification,
            TransfoXLLMHeadModel,
            TransfoXLModel,
            TransfoXLPreTrainedModel,
            load_tf_weights_in_transfo_xl,
        )

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_transfo_xl import (
            TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
            TFAdaptiveEmbedding,
            TFTransfoXLForSequenceClassification,
            TFTransfoXLLMHeadModel,
            TFTransfoXLMainLayer,
            TFTransfoXLModel,
            TFTransfoXLPreTrainedModel,
        )

else:
    import sys

    __UpperCAmelCase          =       _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



