


import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


A__:   List[str]    =	logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
A__:   str    =	direct_transformers_import(Path(__file__).parent)


A__:   Optional[int]    =	{
    '''AutoTokenizer''': '''PreTrainedTokenizerBase''',
    '''AutoFeatureExtractor''': '''FeatureExtractionMixin''',
    '''AutoImageProcessor''': '''ImageProcessingMixin''',
}







class A__	(						UpperCAmelCase__				):
      __UpperCamelCase	:  List[str]     	=							["feature_extractor", "tokenizer"]
      # Names need to be attr_class for attr in attributes
      __UpperCamelCase	:  int     	=							None
      __UpperCamelCase	:  Optional[Any]     	=							None
      __UpperCamelCase	:  Optional[int]     	=							None






      def __init__(			self      :Any					,						*SCREAMING_SNAKE_CASE      :Optional[Any]					,						**SCREAMING_SNAKE_CASE      :Tuple     )	-> Tuple:




             '''simple docstring'''
             # Sanitize args and kwargs
             for key in kwargs:
                    if key not in self.attributes:
                           raise TypeError(f"Unexpected keyword argument {key}."     )
             for arg, attribute_name in zip(SCREAMING_SNAKE_CASE					,						self.attributes     ):
                    if attribute_name in kwargs:
                           raise TypeError(f"Got multiple values for argument {attribute_name}."     )
                    else:
                           _a   :			Any					 =arg

             if len(SCREAMING_SNAKE_CASE     ) != len(self.attributes     ):
                    raise ValueError(
                        f"This processor requires {len(self.attributes     )} arguments: {', '.join(self.attributes     )}. Got "
                        f"{len(SCREAMING_SNAKE_CASE     )} arguments instead."     )

             # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
             for attribute_name, arg in kwargs.items():
                    _a   :			Union[str, Any]					 =getattr(self					,						f"{attribute_name}_class"     )
                    # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
                    _a   :			Union[str, Any]					 =AUTO_TO_BASE_CLASS_MAPPING.get(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     )
                    if isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ):
                           _a   :			Union[str, Any]					 =tuple(getattr(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ) for n in class_name if n is not None     )
                    else:
                           _a   :			Any					 =getattr(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     )

                    if not isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ):
                           raise ValueError(
                               f"Received a {type(SCREAMING_SNAKE_CASE     ).__name__} for argument {attribute_name}, but a {class_name} was expected."     )

                    setattr(self					,						SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     )






      def __repr__(			self      :Any     )	-> Tuple:




             '''simple docstring'''
             _a   :			List[str]					 =[f"- {name}: {repr(getattr(self					,						SCREAMING_SNAKE_CASE     )     )}" for name in self.attributes]
             _a   :			Union[str, Any]					 ="""\n""".join(SCREAMING_SNAKE_CASE     )
             return f"{self.__class__.__name__}:\n{attributes_repr}"






      def __UpperCAmelCase	(			self      :int					,						SCREAMING_SNAKE_CASE      :List[Any]					,						SCREAMING_SNAKE_CASE      :bool = False					,						**SCREAMING_SNAKE_CASE      :Optional[int]     )	-> List[Any]:




             '''simple docstring'''
             os.makedirs(SCREAMING_SNAKE_CASE					,						exist_ok=SCREAMING_SNAKE_CASE     )

             if push_to_hub:
                    _a   :			Tuple					 =kwargs.pop("""commit_message"""					,						SCREAMING_SNAKE_CASE     )
                    _a   :			Union[str, Any]					 =kwargs.pop("""repo_id"""					,						save_directory.split(os.path.sep     )[-1]     )
                    _a   :			str					 =self._create_repo(SCREAMING_SNAKE_CASE					,						**SCREAMING_SNAKE_CASE     )
                    _a   :			int					 =self._get_files_timestamps(SCREAMING_SNAKE_CASE     )
             # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
             # loaded from the Hub.
             if self._auto_class is not None:
                    _a   :			Dict					 =[getattr(self					,						SCREAMING_SNAKE_CASE     ) for attribute_name in self.attributes]
                    _a   :			Tuple					 =[(a.init_kwargs if isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ) else a) for a in attrs]
                    custom_object_save(self					,						SCREAMING_SNAKE_CASE					,						config=SCREAMING_SNAKE_CASE     )

             for attribute_name in self.attributes:
                    _a   :			List[Any]					 =getattr(self					,						SCREAMING_SNAKE_CASE     )
                    # Include the processor class in the attribute config so this processor can then be reloaded with the
                    # `AutoProcessor` API.
                    if hasattr(SCREAMING_SNAKE_CASE					,						"""_set_processor_class"""     ):
                           attribute._set_processor_class(self.__class__.__name__     )
                    attribute.save_pretrained(SCREAMING_SNAKE_CASE     )

             if self._auto_class is not None:
                    # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
                    for attribute_name in self.attributes:
                           _a   :			int					 =getattr(self					,						SCREAMING_SNAKE_CASE     )
                           if isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ):
                                  del attribute.init_kwargs["auto_map"]

             if push_to_hub:
                    self._upload_modified_files(
                        SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE					,						commit_message=SCREAMING_SNAKE_CASE					,						token=kwargs.get("""use_auth_token"""     )					,						)






      @classmethod
      def __UpperCAmelCase	(			cls      :str					,						SCREAMING_SNAKE_CASE      :Union[str, os.PathLike]					,						SCREAMING_SNAKE_CASE      :Optional[Union[str, os.PathLike]] = None					,						SCREAMING_SNAKE_CASE      :bool = False					,						SCREAMING_SNAKE_CASE      :bool = False					,						SCREAMING_SNAKE_CASE      :Optional[Union[str, bool]] = None					,						SCREAMING_SNAKE_CASE      :str = "main"					,						**SCREAMING_SNAKE_CASE      :List[str]					,						)	-> str:




             '''simple docstring'''
             _a   :			Union[str, Any]					 =cache_dir
             _a   :			List[str]					 =force_download
             _a   :			Tuple					 =local_files_only
             _a   :			List[Any]					 =revision

             _a   :			Any					 =kwargs.pop("""use_auth_token"""					,						SCREAMING_SNAKE_CASE     )
             if use_auth_token is not None:
                    warnings.warn(
                        """The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers."""					,						SCREAMING_SNAKE_CASE     )
                    if token is not None:
                           raise ValueError(
                               """`token` and `use_auth_token` are both specified. Please set only the argument `token`."""     )
                    _a   :			Dict					 =use_auth_token

             if token is not None:
                    # change to `token` in a follow-up PR
                    _a   :			Optional[Any]					 =token

             _a   :			str					 =cls._get_arguments_from_pretrained(SCREAMING_SNAKE_CASE					,						**SCREAMING_SNAKE_CASE     )
             return cls(*SCREAMING_SNAKE_CASE     )






      @classmethod
      def __UpperCAmelCase	(			cls      :Dict					,						SCREAMING_SNAKE_CASE      :Any="AutoProcessor"     )	-> Optional[Any]:




             '''simple docstring'''
             if not isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ):
                    _a   :			Tuple					 =auto_class.__name__

             import transformers.models.auto as auto_module

             if not hasattr(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ):
                    raise ValueError(f"{auto_class} is not a valid auto class."     )

             _a   :			Optional[Any]					 =auto_class






      @classmethod
      def __UpperCAmelCase	(			cls      :int					,						SCREAMING_SNAKE_CASE      :Any					,						**SCREAMING_SNAKE_CASE      :int     )	-> Tuple:




             '''simple docstring'''
             _a   :			Optional[Any]					 =[]
             for attribute_name in cls.attributes:
                    _a   :			List[str]					 =getattr(cls					,						f"{attribute_name}_class"     )
                    if isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ):
                           _a   :			List[str]					 =tuple(getattr(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ) if n is not None else None for n in class_name     )
                           _a   :			Union[str, Any]					 =kwargs.get("""use_fast"""					,						SCREAMING_SNAKE_CASE     )
                           if use_fast and classes[1] is not None:
                                  _a   :			Any					 =classes[1]
                           else:
                                  _a   :			int					 =classes[0]
                    else:
                           _a   :			Any					 =getattr(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     )

                    args.append(attribute_class.from_pretrained(SCREAMING_SNAKE_CASE					,						**SCREAMING_SNAKE_CASE     )     )
             return args






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




             '''simple docstring'''
             _a   :			Any					 =getattr(self					,						self.attributes[0]     )
             return getattr(SCREAMING_SNAKE_CASE					,						"""model_input_names"""					,						SCREAMING_SNAKE_CASE     )

A__:   Optional[Any]    =	copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
   A__:   Dict    =	ProcessorMixin.push_to_hub.__doc__.format(
       object='''processor''', object_class='''AutoProcessor''', object_files='''processor files'''
   )






'''simple docstring'''







import copy
from typing import Dict

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING
from ..bit import BitConfig


A__:   List[Any]    =	logging.get_logger(__name__)

A__:   List[Any]    =	{
    '''google/vit-hybrid-base-bit-384''': '''https://huggingface.co/vit-hybrid-base-bit-384/resolve/main/config.json''',
    # See all ViT hybrid models at https://huggingface.co/models?filter=vit
}







class A__	(						UpperCAmelCase__				):
      __UpperCamelCase	:  Dict     	=							"vit-hybrid"






      def __init__(			self      :List[Any]					,						SCREAMING_SNAKE_CASE      :Dict=None					,						SCREAMING_SNAKE_CASE      :Any=7_6_8					,						SCREAMING_SNAKE_CASE      :Optional[Any]=1_2					,						SCREAMING_SNAKE_CASE      :int=1_2					,						SCREAMING_SNAKE_CASE      :Any=3_0_7_2					,						SCREAMING_SNAKE_CASE      :List[str]="gelu"					,						SCREAMING_SNAKE_CASE      :str=0.0					,						SCREAMING_SNAKE_CASE      :Dict=0.0					,						SCREAMING_SNAKE_CASE      :Dict=0.02					,						SCREAMING_SNAKE_CASE      :Tuple=1e-12					,						SCREAMING_SNAKE_CASE      :List[Any]=2_2_4					,						SCREAMING_SNAKE_CASE      :Union[str, Any]=1					,						SCREAMING_SNAKE_CASE      :List[Any]=3					,						SCREAMING_SNAKE_CASE      :Optional[Any]=[1, 1_0_2_4, 2_4, 2_4]					,						SCREAMING_SNAKE_CASE      :Optional[Any]=True					,						**SCREAMING_SNAKE_CASE      :Dict					,						)	-> List[Any]:




             '''simple docstring'''
             super().__init__(**SCREAMING_SNAKE_CASE     )

             if backbone_config is None:
                    logger.info("""`backbone_config` is `None`. Initializing the config with a `BiT` backbone."""     )
                    _a   :			Optional[int]					 ={
                        """global_padding""": """same""",
                        """layer_type""": """bottleneck""",
                        """depths""": [3, 4, 9],
                        """out_features""": ["""stage3"""],
                        """embedding_dynamic_padding""": True,
                    }

             if isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     ):
                    if "model_type" in backbone_config:
                           _a   :			Dict					 =CONFIG_MAPPING[backbone_config["""model_type"""]]
                    else:
                           logger.info(
                               """`model_type` is not found in `backbone_config`. Use `Bit` as the backbone configuration class."""     )
                           _a   :			List[str]					 =BitConfig
                    _a   :			List[Any]					 =backbone_config_class(**SCREAMING_SNAKE_CASE     )

             _a   :			str					 =backbone_featmap_shape
             _a   :			Dict					 =backbone_config
             _a   :			Tuple					 =hidden_size
             _a   :			Union[str, Any]					 =num_hidden_layers
             _a   :			Tuple					 =num_attention_heads
             _a   :			int					 =intermediate_size
             _a   :			Any					 =hidden_act
             _a   :			Union[str, Any]					 =hidden_dropout_prob
             _a   :			Any					 =attention_probs_dropout_prob
             _a   :			Tuple					 =initializer_range
             _a   :			int					 =layer_norm_eps
             _a   :			Union[str, Any]					 =image_size
             _a   :			str					 =patch_size
             _a   :			Optional[int]					 =num_channels
             _a   :			Union[str, Any]					 =qkv_bias






      def __UpperCAmelCase	(			self      :Optional[Any]     )	-> Dict[str, any]:




             '''simple docstring'''
             _a   :			Dict					 =copy.deepcopy(self.__dict__     )
             _a   :			Tuple					 =self.backbone_config.to_dict()
             _a   :			str					 =self.__class__.model_type
             return output


