
"""simple docstring"""


import argparse
import os

import align
import numpy as np
import requests
import tensorflow as tf
import torch
from PIL import Image
from tokenizer import Tokenizer

from transformers import (
    AlignConfig,
    AlignModel,
    AlignProcessor,
    BertConfig,
    BertTokenizer,
    EfficientNetConfig,
    EfficientNetImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
__A       						=       logging.get_logger(__name__)



def     _lowerCamelCase(__UpperCamelCase       )				-> Dict:
	_lowerCAmelCase								=tf.image.resize(__UpperCamelCase    , (346, 346)       )
	_lowerCAmelCase								=tf.image.crop_to_bounding_box(__UpperCamelCase    , (346 - 289) // 2    , (346 - 289) // 2    , 289    , 289       )
	return image



def     _lowerCamelCase()				-> Any:
	_lowerCAmelCase								=EfficientNetConfig.from_pretrained("""google/efficientnet-b7"""       )
	_lowerCAmelCase								=289
	_lowerCAmelCase								=640
	_lowerCAmelCase								={"""0""": """LABEL_0""", """1""": """LABEL_1"""}
	_lowerCAmelCase								={"""LABEL_0""": 0, """LABEL_1""": 1}
	_lowerCAmelCase								=[]

	_lowerCAmelCase								=BertConfig()
	_lowerCAmelCase								=AlignConfig.from_text_vision_configs(
	    text_config=__UpperCamelCase    , vision_config=__UpperCamelCase    , projection_dim=640       )
	return config



def     _lowerCamelCase()				-> List[str]:
	_lowerCAmelCase								="""http://images.cocodataset.org/val2017/000000039769.jpg"""
	_lowerCAmelCase								=Image.open(requests.get(__UpperCamelCase    , stream=__UpperCamelCase       ).raw       )
	return im



def     _lowerCamelCase()				-> Any:
	_lowerCAmelCase								=EfficientNetImageProcessor(
	    do_center_crop=__UpperCamelCase    , rescale_factor=1 / 1_27.5    , rescale_offset=__UpperCamelCase    , do_normalize=__UpperCamelCase    , include_top=__UpperCamelCase    , resample=Image.BILINEAR    , )
	_lowerCAmelCase								=BertTokenizer.from_pretrained("""bert-base-uncased"""       )
	_lowerCAmelCase								=64
	_lowerCAmelCase								=AlignProcessor(image_processor=__UpperCamelCase    , tokenizer=__UpperCamelCase       )
	return processor



def     _lowerCamelCase(__UpperCamelCase       )				-> Optional[Any]:
	# EfficientNet image encoder
	_lowerCAmelCase								=[v.split("""_"""       )[0].split("""block"""       )[1] for v in original_param_names if v.startswith("""block"""       )]
	_lowerCAmelCase								=list(set(__UpperCamelCase       )       )
	_lowerCAmelCase								=sorted(__UpperCamelCase       )
	_lowerCAmelCase								=len(__UpperCamelCase       )
	_lowerCAmelCase								={b: str(__UpperCamelCase       ) for b, i in zip(__UpperCamelCase    , range(__UpperCamelCase       )       )}

	_lowerCAmelCase								=[]
	rename_keys.append(("""stem_conv/kernel:0""", """embeddings.convolution.weight""")       )
	rename_keys.append(("""stem_bn/gamma:0""", """embeddings.batchnorm.weight""")       )
	rename_keys.append(("""stem_bn/beta:0""", """embeddings.batchnorm.bias""")       )
	rename_keys.append(("""stem_bn/moving_mean:0""", """embeddings.batchnorm.running_mean""")       )
	rename_keys.append(("""stem_bn/moving_variance:0""", """embeddings.batchnorm.running_var""")       )

	for b in block_names:
		_lowerCAmelCase								=block_name_mapping[b]
		rename_keys.append((F'''block{b}_expand_conv/kernel:0''', F'''encoder.blocks.{hf_b}.expansion.expand_conv.weight''')       )
		rename_keys.append((F'''block{b}_expand_bn/gamma:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.weight''')       )
		rename_keys.append((F'''block{b}_expand_bn/beta:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.bias''')       )
		rename_keys.append(
		    (F'''block{b}_expand_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.running_mean''')       )
		rename_keys.append(
		    (F'''block{b}_expand_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.running_var''')       )
		rename_keys.append(
		    (F'''block{b}_dwconv/depthwise_kernel:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight''')       )
		rename_keys.append((F'''block{b}_bn/gamma:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight''')       )
		rename_keys.append((F'''block{b}_bn/beta:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias''')       )
		rename_keys.append(
		    (F'''block{b}_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean''')       )
		rename_keys.append(
		    (F'''block{b}_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var''')       )

		rename_keys.append((F'''block{b}_se_reduce/kernel:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.reduce.weight''')       )
		rename_keys.append((F'''block{b}_se_reduce/bias:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.reduce.bias''')       )
		rename_keys.append((F'''block{b}_se_expand/kernel:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.expand.weight''')       )
		rename_keys.append((F'''block{b}_se_expand/bias:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.expand.bias''')       )
		rename_keys.append(
		    (F'''block{b}_project_conv/kernel:0''', F'''encoder.blocks.{hf_b}.projection.project_conv.weight''')       )
		rename_keys.append((F'''block{b}_project_bn/gamma:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.weight''')       )
		rename_keys.append((F'''block{b}_project_bn/beta:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.bias''')       )
		rename_keys.append(
		    (F'''block{b}_project_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.running_mean''')       )
		rename_keys.append(
		    (F'''block{b}_project_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.running_var''')       )

	_lowerCAmelCase								={}
	for item in rename_keys:
		if item[0] in original_param_names:
			_lowerCAmelCase								="""vision_model.""" + item[1]

    # BERT text encoder
	_lowerCAmelCase								=[]
	_lowerCAmelCase								="""tf_bert_model/bert"""
	_lowerCAmelCase								="""text_model"""
	for i in range(12       ):
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/self/query/kernel:0''',
		        F'''{new}.encoder.layer.{i}.attention.self.query.weight''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/self/query/bias:0''',
		        F'''{new}.encoder.layer.{i}.attention.self.query.bias''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/self/key/kernel:0''',
		        F'''{new}.encoder.layer.{i}.attention.self.key.weight''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/self/key/bias:0''',
		        F'''{new}.encoder.layer.{i}.attention.self.key.bias''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/self/value/kernel:0''',
		        F'''{new}.encoder.layer.{i}.attention.self.value.weight''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/self/value/bias:0''',
		        F'''{new}.encoder.layer.{i}.attention.self.value.bias''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/output/dense/kernel:0''',
		        F'''{new}.encoder.layer.{i}.attention.output.dense.weight''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/output/dense/bias:0''',
		        F'''{new}.encoder.layer.{i}.attention.output.dense.bias''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0''',
		        F'''{new}.encoder.layer.{i}.attention.output.LayerNorm.weight''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0''',
		        F'''{new}.encoder.layer.{i}.attention.output.LayerNorm.bias''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/intermediate/dense/kernel:0''',
		        F'''{new}.encoder.layer.{i}.intermediate.dense.weight''',
		    )       )
		rename_keys.append(
		    (
		        F'''{old}/encoder/layer_._{i}/intermediate/dense/bias:0''',
		        F'''{new}.encoder.layer.{i}.intermediate.dense.bias''',
		    )       )
		rename_keys.append(
		    (F'''{old}/encoder/layer_._{i}/output/dense/kernel:0''', F'''{new}.encoder.layer.{i}.output.dense.weight''')       )
		rename_keys.append(
		    (F'''{old}/encoder/layer_._{i}/output/dense/bias:0''', F'''{new}.encoder.layer.{i}.output.dense.bias''')       )
		rename_keys.append(
		    (F'''{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0''', F'''{new}.encoder.layer.{i}.output.LayerNorm.weight''')       )
		rename_keys.append(
		    (F'''{old}/encoder/layer_._{i}/output/LayerNorm/beta:0''', F'''{new}.encoder.layer.{i}.output.LayerNorm.bias''')       )

	rename_keys.append((F'''{old}/embeddings/word_embeddings/weight:0''', F'''{new}.embeddings.word_embeddings.weight''')       )
	rename_keys.append(
	    (F'''{old}/embeddings/position_embeddings/embeddings:0''', F'''{new}.embeddings.position_embeddings.weight''')       )
	rename_keys.append(
	    (F'''{old}/embeddings/token_type_embeddings/embeddings:0''', F'''{new}.embeddings.token_type_embeddings.weight''')       )
	rename_keys.append((F'''{old}/embeddings/LayerNorm/gamma:0''', F'''{new}.embeddings.LayerNorm.weight''')       )
	rename_keys.append((F'''{old}/embeddings/LayerNorm/beta:0''', F'''{new}.embeddings.LayerNorm.bias''')       )

	rename_keys.append((F'''{old}/pooler/dense/kernel:0''', F'''{new}.pooler.dense.weight''')       )
	rename_keys.append((F'''{old}/pooler/dense/bias:0''', F'''{new}.pooler.dense.bias''')       )
	rename_keys.append(("""dense/kernel:0""", """text_projection.weight""")       )
	rename_keys.append(("""dense/bias:0""", """text_projection.bias""")       )
	rename_keys.append(("""dense/bias:0""", """text_projection.bias""")       )
	rename_keys.append(("""temperature:0""", """temperature""")       )

	for item in rename_keys:
		if item[0] in original_param_names:
			_lowerCAmelCase								=item[1]
	return key_mapping



def     _lowerCamelCase(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase       )				-> Optional[Any]:
	list(hf_params.keys()       )

	for key, value in tf_params.items():
		if key not in key_mapping:
			continue

		_lowerCAmelCase								=key_mapping[key]
		if "_conv" in key and "kernel" in key:
			_lowerCAmelCase								=torch.from_numpy(__UpperCamelCase       ).permute(3    , 2    , 0    , 1       )
		elif "embeddings" in key:
			_lowerCAmelCase								=torch.from_numpy(__UpperCamelCase       )
		elif "depthwise_kernel" in key:
			_lowerCAmelCase								=torch.from_numpy(__UpperCamelCase       ).permute(2    , 3    , 0    , 1       )
		elif "kernel" in key:
			_lowerCAmelCase								=torch.from_numpy(np.transpose(__UpperCamelCase       )       )
		elif "temperature" in key:
			_lowerCAmelCase								=value
		elif "bn/gamma" or "bn/beta" in key:
			_lowerCAmelCase								=torch.from_numpy(np.transpose(__UpperCamelCase       )       ).squeeze()
		else:
			_lowerCAmelCase								=torch.from_numpy(__UpperCamelCase       )

		# Replace HF parameters with original TF model parameters
		hf_params[hf_key].copy_(__UpperCamelCase       )



@torch.no_grad()
def     _lowerCamelCase(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase       )				-> Dict:
	_lowerCAmelCase								=64
	_lowerCAmelCase								=Tokenizer(__UpperCamelCase       )
	_lowerCAmelCase								=align.Align("""efficientnet-b7"""    , """bert-base"""    , 640    , __UpperCamelCase    , tok.get_vocab_size()       )
	original_model.compile()
	original_model.load_weights(__UpperCamelCase       )

	_lowerCAmelCase								=original_model.trainable_variables
	_lowerCAmelCase								=original_model.non_trainable_variables
	_lowerCAmelCase								={param.name: param.numpy() for param in tf_params}
	for param in tf_non_train_params:
		_lowerCAmelCase								=param.numpy()
	_lowerCAmelCase								=list(tf_params.keys()       )

	# Load HuggingFace model
	_lowerCAmelCase								=get_align_config()
	_lowerCAmelCase								=AlignModel(__UpperCamelCase       ).eval()
	_lowerCAmelCase								=hf_model.state_dict()

	# Create src-to-dst parameter name mapping dictionary
	print("""Converting parameters..."""       )
	_lowerCAmelCase								=rename_keys(__UpperCamelCase       )
	replace_params(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase       )

	# Initialize processor
	_lowerCAmelCase								=get_processor()
	_lowerCAmelCase								=processor(
	    images=prepare_img()    , text="""A picture of a cat"""    , padding="""max_length"""    , max_length=64    , return_tensors="""pt"""       )

	# HF model inference
	hf_model.eval()
	with torch.no_grad():
		_lowerCAmelCase								=hf_model(**__UpperCamelCase       )

	_lowerCAmelCase								=outputs.image_embeds.detach().numpy()
	_lowerCAmelCase								=outputs.text_embeds.detach().numpy()

	# Original model inference
	_lowerCAmelCase								=False
	_lowerCAmelCase								=EfficientNetImageProcessor(
	    do_center_crop=__UpperCamelCase    , do_rescale=__UpperCamelCase    , do_normalize=__UpperCamelCase    , include_top=__UpperCamelCase    , resample=Image.BILINEAR    , )
	_lowerCAmelCase								=tf_image_processor(images=prepare_img()    , return_tensors="""tf"""    , data_format="""channels_last"""       )["""pixel_values"""]
	_lowerCAmelCase								=tok(tf.constant(["""A picture of a cat"""]       )       )

	_lowerCAmelCase								=original_model.image_encoder(__UpperCamelCase    , training=__UpperCamelCase       )
	_lowerCAmelCase								=original_model.text_encoder(__UpperCamelCase    , training=__UpperCamelCase       )

	_lowerCAmelCase								=tf.nn.la_normalize(__UpperCamelCase    , axis=-1       )
	_lowerCAmelCase								=tf.nn.la_normalize(__UpperCamelCase    , axis=-1       )

	# Check whether original and HF model outputs match  -> np.allclose
	if not np.allclose(__UpperCamelCase    , __UpperCamelCase    , atol=1E-3       ):
		raise ValueError("""The predicted image features are not the same."""       )
	if not np.allclose(__UpperCamelCase    , __UpperCamelCase    , atol=1E-3       ):
		raise ValueError("""The predicted text features are not the same."""       )
	print("""Model outputs match!"""       )

	if save_model:
		# Create folder to save model
		if not os.path.isdir(__UpperCamelCase       ):
			os.mkdir(__UpperCamelCase       )
		# Save converted model and image processor
		hf_model.save_pretrained(__UpperCamelCase       )
		processor.save_pretrained(__UpperCamelCase       )

	if push_to_hub:
		# Push model and image processor to hub
		print("""Pushing converted ALIGN to the hub..."""       )
		processor.push_to_hub("""align-base"""       )
		hf_model.push_to_hub("""align-base"""       )


if __name__ == "__main__":
			__A       						=       argparse.ArgumentParser()
			# Required parameters
			parser.add_argument(
			    '--checkpoint_path',
			    default='./weights/model-weights',
			    type=str,
			    help='Path to the pretrained TF ALIGN checkpoint.',
			)
			parser.add_argument(
			    '--pytorch_dump_folder_path',
			    default='hf_model',
			    type=str,
			    help='Path to the output PyTorch model directory.',
			)
			parser.add_argument('--save_model', action='store_true', help='Save model to local')
			parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub')

			__A       						=       parser.parse_args()
			convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)





"""simple docstring"""


import importlib
import inspect
import json
import os
from collections import OrderedDict

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...image_processing_utils import ImageProcessingMixin
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
from ...utils import FEATURE_EXTRACTOR_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,
)
from .feature_extraction_auto import AutoFeatureExtractor
from .image_processing_auto import AutoImageProcessor
from .tokenization_auto import AutoTokenizer


__A       						=       logging.get_logger(__name__)

__A       						=       OrderedDict(
    [
        ('align', 'AlignProcessor'),
        ('altclip', 'AltCLIPProcessor'),
        ('bark', 'BarkProcessor'),
        ('blip', 'BlipProcessor'),
        ('blip-2', 'Blip2Processor'),
        ('bridgetower', 'BridgeTowerProcessor'),
        ('chinese_clip', 'ChineseCLIPProcessor'),
        ('clap', 'ClapProcessor'),
        ('clip', 'CLIPProcessor'),
        ('clipseg', 'CLIPSegProcessor'),
        ('flava', 'FlavaProcessor'),
        ('git', 'GitProcessor'),
        ('groupvit', 'CLIPProcessor'),
        ('hubert', 'Wav2Vec2Processor'),
        ('instructblip', 'InstructBlipProcessor'),
        ('layoutlmv2', 'LayoutLMv2Processor'),
        ('layoutlmv3', 'LayoutLMv3Processor'),
        ('markuplm', 'MarkupLMProcessor'),
        ('mctct', 'MCTCTProcessor'),
        ('mgp-str', 'MgpstrProcessor'),
        ('oneformer', 'OneFormerProcessor'),
        ('owlvit', 'OwlViTProcessor'),
        ('pix2struct', 'Pix2StructProcessor'),
        ('sam', 'SamProcessor'),
        ('sew', 'Wav2Vec2Processor'),
        ('sew-d', 'Wav2Vec2Processor'),
        ('speech_to_text', 'Speech2TextProcessor'),
        ('speech_to_text_2', 'Speech2Text2Processor'),
        ('speecht5', 'SpeechT5Processor'),
        ('trocr', 'TrOCRProcessor'),
        ('tvlt', 'TvltProcessor'),
        ('unispeech', 'Wav2Vec2Processor'),
        ('unispeech-sat', 'Wav2Vec2Processor'),
        ('vilt', 'ViltProcessor'),
        ('vision-text-dual-encoder', 'VisionTextDualEncoderProcessor'),
        ('wav2vec2', 'Wav2Vec2Processor'),
        ('wav2vec2-conformer', 'Wav2Vec2Processor'),
        ('wavlm', 'Wav2Vec2Processor'),
        ('whisper', 'WhisperProcessor'),
        ('xclip', 'XCLIPProcessor'),
    ]
)

__A       						=       _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)



def     _lowerCamelCase(__UpperCamelCase       )				-> Optional[int]:
	for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
		if class_name in processors:
			_lowerCAmelCase								=model_type_to_module_name(__UpperCamelCase       )

			_lowerCAmelCase								=importlib.import_module(F'''.{module_name}'''    , """transformers.models"""       )
			try:
				return getattr(__UpperCamelCase    , __UpperCamelCase       )
			except AttributeError:
				continue

	for processor in PROCESSOR_MAPPING._extra_content.values():
		if getattr(__UpperCamelCase    , """__name__"""    , __UpperCamelCase       ) == class_name:
			return processor

    # 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.
	_lowerCAmelCase								=importlib.import_module("""transformers"""       )
	if hasattr(__UpperCamelCase    , __UpperCamelCase       ):
		return getattr(__UpperCamelCase    , __UpperCamelCase       )

	return None







class 		lowerCamelCase__					:





			'''simple docstring'''



			def __init__(							self  ) ->     str:
				raise EnvironmentError(
				    """AutoProcessor is designed to be instantiated """
				    """using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."""  )



			@classmethod
			@replace_list_option_in_docstrings(__UpperCAmelCase  )
			def 					_lowerCAmelCase		(							cls     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  ) ->     Tuple:
				_lowerCAmelCase								=kwargs.pop("""config"""     ,     __UpperCAmelCase  )
				_lowerCAmelCase								=kwargs.pop("""trust_remote_code"""     ,     __UpperCAmelCase  )
				_lowerCAmelCase								=True

				_lowerCAmelCase								=None
				_lowerCAmelCase								=None

				# First, let's see if we have a preprocessor config.
				# Filter the kwargs for `get_file_from_repo`.
				_lowerCAmelCase								={
				    key: kwargs[key] for key in inspect.signature(__UpperCAmelCase  ).parameters.keys() if key in kwargs
				}
				# Let's start by checking whether the processor class is saved in an image processor
				_lowerCAmelCase								=get_file_from_repo(
				    __UpperCAmelCase     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  )
				if preprocessor_config_file is not None:
					_lowerCAmelCase						,							_lowerCAmelCase								=ImageProcessingMixin.get_image_processor_dict(__UpperCAmelCase     ,     **__UpperCAmelCase  )
					_lowerCAmelCase								=config_dict.get("""processor_class"""     ,     __UpperCAmelCase  )
					if "AutoProcessor" in config_dict.get("""auto_map"""     ,     {}  ):
						_lowerCAmelCase								=config_dict["""auto_map"""]["""AutoProcessor"""]

        # If not found, let's check whether the processor class is saved in a feature extractor config
				if preprocessor_config_file is not None and processor_class is None:
					_lowerCAmelCase						,							_lowerCAmelCase								=FeatureExtractionMixin.get_feature_extractor_dict(__UpperCAmelCase     ,     **__UpperCAmelCase  )
					_lowerCAmelCase								=config_dict.get("""processor_class"""     ,     __UpperCAmelCase  )
					if "AutoProcessor" in config_dict.get("""auto_map"""     ,     {}  ):
						_lowerCAmelCase								=config_dict["""auto_map"""]["""AutoProcessor"""]

				if processor_class is None:
					# Next, let's check whether the processor class is saved in a tokenizer
					_lowerCAmelCase								=get_file_from_repo(
					    __UpperCAmelCase     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  )
					if tokenizer_config_file is not None:
						with open(__UpperCAmelCase     ,     encoding="""utf-8"""  ) as reader:
							_lowerCAmelCase								=json.load(__UpperCAmelCase  )

						_lowerCAmelCase								=config_dict.get("""processor_class"""     ,     __UpperCAmelCase  )
						if "AutoProcessor" in config_dict.get("""auto_map"""     ,     {}  ):
							_lowerCAmelCase								=config_dict["""auto_map"""]["""AutoProcessor"""]

				if processor_class is None:
					# Otherwise, load config, if it can be loaded.
					if not isinstance(__UpperCAmelCase     ,     __UpperCAmelCase  ):
						_lowerCAmelCase								=AutoConfig.from_pretrained(
						    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )

					# And check if the config contains the processor class.
					_lowerCAmelCase								=getattr(__UpperCAmelCase     ,     """processor_class"""     ,     __UpperCAmelCase  )
					if hasattr(__UpperCAmelCase     ,     """auto_map"""  ) and "AutoProcessor" in config.auto_map:
						_lowerCAmelCase								=config.auto_map["""AutoProcessor"""]

				if processor_class is not None:
					_lowerCAmelCase								=processor_class_from_name(__UpperCAmelCase  )

				_lowerCAmelCase								=processor_auto_map is not None
				_lowerCAmelCase								=processor_class is not None or type(__UpperCAmelCase  ) in PROCESSOR_MAPPING
				_lowerCAmelCase								=resolve_trust_remote_code(
				    __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase  )

				if has_remote_code and trust_remote_code:
					_lowerCAmelCase								=get_class_from_dynamic_module(
					    __UpperCAmelCase     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  )
					_lowerCAmelCase								=kwargs.pop("""code_revision"""     ,     __UpperCAmelCase  )
					if os.path.isdir(__UpperCAmelCase  ):
						processor_class.register_for_auto_class()
					return processor_class.from_pretrained(
					    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
				elif processor_class is not None:
					return processor_class.from_pretrained(
					    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
				# Last try: we use the PROCESSOR_MAPPING.
				elif type(__UpperCAmelCase  ) in PROCESSOR_MAPPING:
					return PROCESSOR_MAPPING[type(__UpperCAmelCase  )].from_pretrained(__UpperCAmelCase     ,     **__UpperCAmelCase  )

				# At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
				# tokenizer.
				try:
					return AutoTokenizer.from_pretrained(
					    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
				except Exception:
					try:
						return AutoImageProcessor.from_pretrained(
						    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
					except Exception:
						pass

					try:
						return AutoFeatureExtractor.from_pretrained(
						    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
					except Exception:
						pass

				raise ValueError(
				    f'''Unrecognized processing class in {pretrained_model_name_or_path}. Can\'t instantiate a processor, a '''
				    """tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains"""
				    """the files of at least one of those processing classes."""  )



			@staticmethod
			def 					_lowerCAmelCase		(							__UpperCAmelCase     ,     __UpperCAmelCase  ) ->     Optional[int]:
				PROCESSOR_MAPPING.register(__UpperCAmelCase     ,     __UpperCAmelCase  )



