

'''simple docstring'''





import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...image_processing_utils import ImageProcessingMixin
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


UpperCamelCase_    						=       logging.get_logger(__name__)

UpperCamelCase_    						=       OrderedDict(
    [
        ("""align""", """EfficientNetImageProcessor"""),
        ("""beit""", """BeitImageProcessor"""),
        ("""bit""", """BitImageProcessor"""),
        ("""blip""", """BlipImageProcessor"""),
        ("""blip-2""", """BlipImageProcessor"""),
        ("""bridgetower""", """BridgeTowerImageProcessor"""),
        ("""chinese_clip""", """ChineseCLIPImageProcessor"""),
        ("""clip""", """CLIPImageProcessor"""),
        ("""clipseg""", """ViTImageProcessor"""),
        ("""conditional_detr""", """ConditionalDetrImageProcessor"""),
        ("""convnext""", """ConvNextImageProcessor"""),
        ("""convnextv2""", """ConvNextImageProcessor"""),
        ("""cvt""", """ConvNextImageProcessor"""),
        ("""data2vec-vision""", """BeitImageProcessor"""),
        ("""deformable_detr""", """DeformableDetrImageProcessor"""),
        ("""deit""", """DeiTImageProcessor"""),
        ("""deta""", """DetaImageProcessor"""),
        ("""detr""", """DetrImageProcessor"""),
        ("""dinat""", """ViTImageProcessor"""),
        ("""donut-swin""", """DonutImageProcessor"""),
        ("""dpt""", """DPTImageProcessor"""),
        ("""efficientformer""", """EfficientFormerImageProcessor"""),
        ("""efficientnet""", """EfficientNetImageProcessor"""),
        ("""flava""", """FlavaImageProcessor"""),
        ("""focalnet""", """BitImageProcessor"""),
        ("""git""", """CLIPImageProcessor"""),
        ("""glpn""", """GLPNImageProcessor"""),
        ("""groupvit""", """CLIPImageProcessor"""),
        ("""imagegpt""", """ImageGPTImageProcessor"""),
        ("""instructblip""", """BlipImageProcessor"""),
        ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""),
        ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""),
        ("""levit""", """LevitImageProcessor"""),
        ("""mask2former""", """Mask2FormerImageProcessor"""),
        ("""maskformer""", """MaskFormerImageProcessor"""),
        ("""mgp-str""", """ViTImageProcessor"""),
        ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""),
        ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""),
        ("""mobilevit""", """MobileViTImageProcessor"""),
        ("""mobilevit""", """MobileViTImageProcessor"""),
        ("""mobilevitv2""", """MobileViTImageProcessor"""),
        ("""nat""", """ViTImageProcessor"""),
        ("""oneformer""", """OneFormerImageProcessor"""),
        ("""owlvit""", """OwlViTImageProcessor"""),
        ("""perceiver""", """PerceiverImageProcessor"""),
        ("""pix2struct""", """Pix2StructImageProcessor"""),
        ("""poolformer""", """PoolFormerImageProcessor"""),
        ("""regnet""", """ConvNextImageProcessor"""),
        ("""resnet""", """ConvNextImageProcessor"""),
        ("""sam""", """SamImageProcessor"""),
        ("""segformer""", """SegformerImageProcessor"""),
        ("""swiftformer""", """ViTImageProcessor"""),
        ("""swin""", """ViTImageProcessor"""),
        ("""swin2sr""", """Swin2SRImageProcessor"""),
        ("""swinv2""", """ViTImageProcessor"""),
        ("""table-transformer""", """DetrImageProcessor"""),
        ("""timesformer""", """VideoMAEImageProcessor"""),
        ("""tvlt""", """TvltImageProcessor"""),
        ("""upernet""", """SegformerImageProcessor"""),
        ("""van""", """ConvNextImageProcessor"""),
        ("""videomae""", """VideoMAEImageProcessor"""),
        ("""vilt""", """ViltImageProcessor"""),
        ("""vit""", """ViTImageProcessor"""),
        ("""vit_hybrid""", """ViTHybridImageProcessor"""),
        ("""vit_mae""", """ViTImageProcessor"""),
        ("""vit_msn""", """ViTImageProcessor"""),
        ("""xclip""", """CLIPImageProcessor"""),
        ("""yolos""", """YolosImageProcessor"""),
    ]
)

UpperCamelCase_    						=       _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)






def 				_lowerCAmelCase			(   __magic_name__						:     str						)				->  List[Any]:
						for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
												if class_name in extractors:
																		lowercase :							Tuple    		=model_type_to_module_name(__magic_name__						)

																		lowercase :							Optional[int]    		=importlib.import_module(f'''.{module_name}'''   , '''transformers.models'''						)
																		try:
																								return getattr(__magic_name__   , __magic_name__						)
																		except AttributeError:
																								continue

						for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
												if getattr(__magic_name__   , '''__name__'''   , __magic_name__						) == class_name:
																		return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
						lowercase :							int    		=importlib.import_module('''transformers'''						)
						if hasattr(__magic_name__   , __magic_name__						):
												return getattr(__magic_name__   , __magic_name__						)

						return None






def 				_lowerCAmelCase			(   __magic_name__						:     Union[str, os.PathLike]   , __magic_name__						:     Optional[Union[str, os.PathLike]] = None   , __magic_name__						:     bool = False   , __magic_name__						:     bool = False   , __magic_name__						:     Optional[Dict[str, str]] = None   , __magic_name__						:     Optional[Union[bool, str]] = None   , __magic_name__						:     Optional[str] = None   , __magic_name__						:     bool = False   , **__magic_name__						:     Optional[Any]   , )				->  str:
						lowercase :							List[str]    		=get_file_from_repo(
						    __magic_name__   , __magic_name__   , cache_dir=__magic_name__   , force_download=__magic_name__   , resume_download=__magic_name__   , proxies=__magic_name__   , use_auth_token=__magic_name__   , revision=__magic_name__   , local_files_only=__magic_name__   , )
						if resolved_config_file is None:
												logger.info(
												    '''Could not locate the image processor configuration file, will try to use the model config instead.'''						)
												return {}

						with open(__magic_name__   , encoding='''utf-8'''						) as reader:
												return json.load(__magic_name__						)







class 		__SCREAMING_SNAKE_CASE							:







				def __init__(       self     :		Any   ):
										'''simple docstring'''
										raise EnvironmentError(
										    '''AutoImageProcessor is designed to be instantiated '''
										    '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.'''   )







				@classmethod
				@replace_list_option_in_docstrings(UpperCAmelCase__   )
				def  lowerCamelCase_	(       cls     :		str		,					UpperCAmelCase__     :		List[str]		,					**UpperCAmelCase__     :		List[Any]   ):
										'''simple docstring'''
										lowercase :							Union[str, Any]    		=kwargs.pop('''config'''		,					UpperCAmelCase__   )
										lowercase :							List[str]    		=kwargs.pop('''trust_remote_code'''		,					UpperCAmelCase__   )
										lowercase :							Optional[Any]    		=True

										lowercase		,	lowercase :							Tuple    		=ImageProcessingMixin.get_image_processor_dict(UpperCAmelCase__		,					**UpperCAmelCase__   )
										lowercase :							List[str]    		=config_dict.get('''image_processor_type'''		,					UpperCAmelCase__   )
										lowercase :							Optional[Any]    		=None
										if "AutoImageProcessor" in config_dict.get('''auto_map'''		,					{}   ):
																lowercase :							Optional[Any]    		=config_dict['''auto_map''']['''AutoImageProcessor''']

										# If we still don't have the image processor class, check if we're loading from a previous feature extractor config
										# and if so, infer the image processor class from there.
										if image_processor_class is None and image_processor_auto_map is None:
																lowercase :							Union[str, Any]    		=config_dict.pop('''feature_extractor_type'''		,					UpperCAmelCase__   )
																if feature_extractor_class is not None:
																						logger.warning(
																						    '''Could not find image processor class in the image processor config or the model config. Loading'''
																						    ''' based on pattern matching with the model\'s feature extractor configuration.'''   )
																						lowercase :							Tuple    		=feature_extractor_class.replace('''FeatureExtractor'''		,					'''ImageProcessor'''   )
																if "AutoFeatureExtractor" in config_dict.get('''auto_map'''		,					{}   ):
																						lowercase :							Tuple    		=config_dict['''auto_map''']['''AutoFeatureExtractor''']
																						lowercase :							List[str]    		=feature_extractor_auto_map.replace('''FeatureExtractor'''		,					'''ImageProcessor'''   )
																						logger.warning(
																						    '''Could not find image processor auto map in the image processor config or the model config.'''
																						    ''' Loading based on pattern matching with the model\'s feature extractor configuration.'''   )

        # If we don't find the image processor class in the image processor config, let's try the model config.
										if image_processor_class is None and image_processor_auto_map is None:
																if not isinstance(UpperCAmelCase__		,					UpperCAmelCase__   ):
																						lowercase :							Tuple    		=AutoConfig.from_pretrained(UpperCAmelCase__		,					**UpperCAmelCase__   )
																# It could be in `config.image_processor_type``
																lowercase :							Any    		=getattr(UpperCAmelCase__		,					'''image_processor_type'''		,					UpperCAmelCase__   )
																if hasattr(UpperCAmelCase__		,					'''auto_map'''   ) and "AutoImageProcessor" in config.auto_map:
																						lowercase :							Optional[Any]    		=config.auto_map['''AutoImageProcessor''']

										if image_processor_class is not None:
																lowercase :							Any    		=image_processor_class_from_name(UpperCAmelCase__   )

										lowercase :							str    		=image_processor_auto_map is not None
										lowercase :							Dict    		=image_processor_class is not None or type(UpperCAmelCase__   ) in IMAGE_PROCESSOR_MAPPING
										lowercase :							Tuple    		=resolve_trust_remote_code(
										    UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__   )

										if has_remote_code and trust_remote_code:
																lowercase :							Optional[int]    		=get_class_from_dynamic_module(
																    UpperCAmelCase__		,					UpperCAmelCase__		,					**UpperCAmelCase__   )
																lowercase :							Union[str, Any]    		=kwargs.pop('''code_revision'''		,					UpperCAmelCase__   )
																if os.path.isdir(UpperCAmelCase__   ):
																						image_processor_class.register_for_auto_class()
																return image_processor_class.from_dict(UpperCAmelCase__		,					**UpperCAmelCase__   )
										elif image_processor_class is not None:
																return image_processor_class.from_dict(UpperCAmelCase__		,					**UpperCAmelCase__   )
										# Last try: we use the IMAGE_PROCESSOR_MAPPING.
										elif type(UpperCAmelCase__   ) in IMAGE_PROCESSOR_MAPPING:
																lowercase :							str    		=IMAGE_PROCESSOR_MAPPING[type(UpperCAmelCase__   )]
																return image_processor_class.from_dict(UpperCAmelCase__		,					**UpperCAmelCase__   )

										raise ValueError(
										    F'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a '''
										    F'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following '''
										    F'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys()   )}'''   )







				@staticmethod
				def  lowerCamelCase_	(       UpperCAmelCase__     :		Any		,					UpperCAmelCase__     :		Optional[Any]   ):
										'''simple docstring'''
										IMAGE_PROCESSOR_MAPPING.register(UpperCAmelCase__		,					UpperCAmelCase__   )








'''simple docstring'''





from dataclasses import asdict, dataclass
from typing import Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_    						=       logging.get_logger(__name__)

# TODO Update this
UpperCamelCase_    						=       {
    """facebook/esm-1b""": """https://huggingface.co/facebook/esm-1b/resolve/main/config.json""",
    # See all ESM models at https://huggingface.co/models?filter=esm
}





class 		__SCREAMING_SNAKE_CASE							(			lowercase__      ):
				lowerCamelCase_		       =    'esm'







				def __init__(       self     :		Optional[Any]		,					UpperCAmelCase__     :		str=None		,					UpperCAmelCase__     :		Dict=None		,					UpperCAmelCase__     :		Any=None		,					UpperCAmelCase__     :		int=768		,					UpperCAmelCase__     :		Union[str, Any]=12		,					UpperCAmelCase__     :		List[Any]=12		,					UpperCAmelCase__     :		Optional[Any]=3072		,					UpperCAmelCase__     :		Dict=0.1		,					UpperCAmelCase__     :		int=0.1		,					UpperCAmelCase__     :		int=1026		,					UpperCAmelCase__     :		Tuple=0.02		,					UpperCAmelCase__     :		Optional[int]=1E-12		,					UpperCAmelCase__     :		List[Any]="absolute"		,					UpperCAmelCase__     :		int=True		,					UpperCAmelCase__     :		Dict=None		,					UpperCAmelCase__     :		str=False		,					UpperCAmelCase__     :		int=False		,					UpperCAmelCase__     :		Optional[Any]=None		,					UpperCAmelCase__     :		List[str]=None		,					**UpperCAmelCase__     :		int		,					):
										'''simple docstring'''
										super().__init__(pad_token_id=UpperCAmelCase__		,					mask_token_id=UpperCAmelCase__		,					**UpperCAmelCase__   )

										lowercase :							Any    		=vocab_size
										lowercase :							List[Any]    		=hidden_size
										lowercase :							Any    		=num_hidden_layers
										lowercase :							Optional[Any]    		=num_attention_heads
										lowercase :							Tuple    		=intermediate_size
										lowercase :							int    		=hidden_dropout_prob
										lowercase :							Dict    		=attention_probs_dropout_prob
										lowercase :							Optional[int]    		=max_position_embeddings
										lowercase :							Union[str, Any]    		=initializer_range
										lowercase :							Tuple    		=layer_norm_eps
										lowercase :							Union[str, Any]    		=position_embedding_type
										lowercase :							List[Any]    		=use_cache
										lowercase :							Dict    		=emb_layer_norm_before
										lowercase :							Optional[Any]    		=token_dropout
										lowercase :							Union[str, Any]    		=is_folding_model
										if is_folding_model:
																if esmfold_config is None:
																						logger.info('''No esmfold_config supplied for folding model, using default values.'''   )
																						lowercase :							Any    		=EsmFoldConfig()
																elif isinstance(UpperCAmelCase__		,					UpperCAmelCase__   ):
																						lowercase :							Optional[int]    		=EsmFoldConfig(**UpperCAmelCase__   )
																lowercase :							Union[str, Any]    		=esmfold_config
																if vocab_list is None:
																						logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!'''   )
																						lowercase :							int    		=get_default_vocab_list()
																else:
																						lowercase :							Tuple    		=vocab_list
										else:
																lowercase :							Union[str, Any]    		=None
																lowercase :							Dict    		=None
										if self.esmfold_config is not None and getattr(self.esmfold_config		,					'''use_esm_attn_map'''		,					UpperCAmelCase__   ):
																raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!'''   )







				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase :							Union[str, Any]    		=super().to_dict()
										if isinstance(self.esmfold_config		,					UpperCAmelCase__   ):
																lowercase :							Optional[Any]    		=self.esmfold_config.to_dict()
										return output





@dataclass
class 		__SCREAMING_SNAKE_CASE							:
				lowerCamelCase_		       =    None
				lowerCamelCase_		       =    True
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    0

				lowerCamelCase_		       =    True
				lowerCamelCase_		       =    False

				lowerCamelCase_		       =    1_28
				lowerCamelCase_		       =    None







				def  lowerCamelCase_	(       self     :		Tuple   ):
										'''simple docstring'''
										if self.trunk is None:
																lowercase :							str    		=TrunkConfig()
										elif isinstance(self.trunk		,					UpperCAmelCase__   ):
																lowercase :							int    		=TrunkConfig(**self.trunk   )







				def  lowerCamelCase_	(       self     :		List[Any]   ):
										'''simple docstring'''
										lowercase :							str    		=asdict(self   )
										lowercase :							Union[str, Any]    		=self.trunk.to_dict()
										return output





@dataclass
class 		__SCREAMING_SNAKE_CASE							:
				lowerCamelCase_		       =    48
				lowerCamelCase_		       =    10_24
				lowerCamelCase_		       =    1_28
				lowerCamelCase_		       =    32
				lowerCamelCase_		       =    32
				lowerCamelCase_		       =    32
				lowerCamelCase_		       =    0
				lowerCamelCase_		       =    0
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    4
				lowerCamelCase_		       =    1_28
				lowerCamelCase_		       =    None







				def  lowerCamelCase_	(       self     :		List[str]   ):
										'''simple docstring'''
										if self.structure_module is None:
																lowercase :							Any    		=StructureModuleConfig()
										elif isinstance(self.structure_module		,					UpperCAmelCase__   ):
																lowercase :							Union[str, Any]    		=StructureModuleConfig(**self.structure_module   )

										if self.max_recycles <= 0:
																raise ValueError(F'''`max_recycles` should be positive, got {self.max_recycles}.'''   )
										if self.sequence_state_dim % self.sequence_state_dim != 0:
																raise ValueError(
																    '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got'''
																    F''' {self.sequence_state_dim} and {self.sequence_state_dim}.'''   )
										if self.pairwise_state_dim % self.pairwise_state_dim != 0:
																raise ValueError(
																    '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got'''
																    F''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.'''   )

										lowercase :							str    		=self.sequence_state_dim // self.sequence_head_width
										lowercase :							int    		=self.pairwise_state_dim // self.pairwise_head_width

										if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
																raise ValueError(
																    '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got'''
																    F''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.'''   )
										if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
																raise ValueError(
																    '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got'''
																    F''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.'''   )
										if self.pairwise_state_dim % 2 != 0:
																raise ValueError(F'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.'''   )

										if self.dropout >= 0.4:
																raise ValueError(F'''`dropout` should not be greater than 0.4, got {self.dropout}.'''   )







				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										lowercase :							List[Any]    		=asdict(self   )
										lowercase :							Any    		=self.structure_module.to_dict()
										return output





@dataclass
class 		__SCREAMING_SNAKE_CASE							:
				lowerCamelCase_		       =    3_84
				lowerCamelCase_		       =    1_28
				lowerCamelCase_		       =    16
				lowerCamelCase_		       =    1_28
				lowerCamelCase_		       =    12
				lowerCamelCase_		       =    4
				lowerCamelCase_		       =    8
				lowerCamelCase_		       =    0.1
				lowerCamelCase_		       =    8
				lowerCamelCase_		       =    1
				lowerCamelCase_		       =    2
				lowerCamelCase_		       =    7
				lowerCamelCase_		       =    10
				lowerCamelCase_		       =    1E-8
				lowerCamelCase_		       =    1E5







				def  lowerCamelCase_	(       self     :		Dict   ):
										'''simple docstring'''
										return asdict(self   )






def 				_lowerCAmelCase			(   )				->  Optional[int]:
						return (
						    "<cls>",
						    "<pad>",
						    "<eos>",
						    "<unk>",
						    "L",
						    "A",
						    "G",
						    "V",
						    "S",
						    "E",
						    "R",
						    "T",
						    "I",
						    "D",
						    "P",
						    "K",
						    "Q",
						    "N",
						    "F",
						    "Y",
						    "M",
						    "H",
						    "W",
						    "C",
						    "X",
						    "B",
						    "U",
						    "Z",
						    "O",
						    ".",
						    "-",
						    "<null_1>",
						    "<mask>",
						)





