





"""simple docstring"""
import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image

from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
__UpperCamelCase			:		Any		    =   logging.get_logger(__name__)

def 						_SCREAMING_SNAKE_CASE       ():
 lowerCAmelCase  							=      DetaConfig(
     num_queries=900   ,			encoder_ffn_dim=2048   ,			decoder_ffn_dim=2048   ,			num_feature_levels=5   ,			assign_first_stage=_UpperCAmelCase   ,			with_box_refine=_UpperCAmelCase   ,			two_stage=_UpperCAmelCase   ,			)

 # set labels
 lowerCAmelCase  							=      91
 lowerCAmelCase  							=      'huggingface/label-files'
 lowerCAmelCase  							=      'coco-detection-id2label.json'
 lowerCAmelCase  							=      json.load(open(cached_download(hf_hub_url(_UpperCAmelCase   ,			_UpperCAmelCase   ,			repo_type='dataset'       )       )   ,			'r'       )       )
 lowerCAmelCase  							=      {int(_UpperCAmelCase       ): v for k, v in idalabel.items()}
 lowerCAmelCase  							=      idalabel
 lowerCAmelCase  							=      {v: k for k, v in idalabel.items()}

 return config

def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  Tuple       ):
 lowerCAmelCase  							=      []

 # stem
 # fmt: off
 rename_keys.append(('backbone.0.body.conv1.weight', 'model.backbone.model.embedder.embedder.convolution.weight')       )
 rename_keys.append(('backbone.0.body.bn1.weight', 'model.backbone.model.embedder.embedder.normalization.weight')       )
 rename_keys.append(('backbone.0.body.bn1.bias', 'model.backbone.model.embedder.embedder.normalization.bias')       )
 rename_keys.append(('backbone.0.body.bn1.running_mean', 'model.backbone.model.embedder.embedder.normalization.running_mean')       )
 rename_keys.append(('backbone.0.body.bn1.running_var', 'model.backbone.model.embedder.embedder.normalization.running_var')       )
 # stages
 for stage_idx in range(len(config.backbone_config.depths       )       ):
  for layer_idx in range(config.backbone_config.depths[stage_idx]       ):
   # shortcut
   if layer_idx == 0:
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var',
        )       )
   # 3 convs
   for i in range(3       ):
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean',
        )       )
    rename_keys.append(
        (
            F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var',
            F'model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var',
        )       )
    # transformer encoder
 for i in range(config.encoder_layers       ):
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight', F'model.encoder.layers.{i}.self_attn.sampling_offsets.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias', F'model.encoder.layers.{i}.self_attn.sampling_offsets.bias')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.attention_weights.weight', F'model.encoder.layers.{i}.self_attn.attention_weights.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.attention_weights.bias', F'model.encoder.layers.{i}.self_attn.attention_weights.bias')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.value_proj.weight', F'model.encoder.layers.{i}.self_attn.value_proj.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.value_proj.bias', F'model.encoder.layers.{i}.self_attn.value_proj.bias')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.output_proj.weight', F'model.encoder.layers.{i}.self_attn.output_proj.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.output_proj.bias', F'model.encoder.layers.{i}.self_attn.output_proj.bias')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.norm1.weight', F'model.encoder.layers.{i}.self_attn_layer_norm.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.norm1.bias', F'model.encoder.layers.{i}.self_attn_layer_norm.bias')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.linear1.weight', F'model.encoder.layers.{i}.fc1.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.linear1.bias', F'model.encoder.layers.{i}.fc1.bias')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.linear2.weight', F'model.encoder.layers.{i}.fc2.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.linear2.bias', F'model.encoder.layers.{i}.fc2.bias')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.norm2.weight', F'model.encoder.layers.{i}.final_layer_norm.weight')       )
  rename_keys.append((F'transformer.encoder.layers.{i}.norm2.bias', F'model.encoder.layers.{i}.final_layer_norm.bias')       )

 # transformer decoder
 for i in range(config.decoder_layers       ):
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight', F'model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias', F'model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.attention_weights.weight', F'model.decoder.layers.{i}.encoder_attn.attention_weights.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.attention_weights.bias', F'model.decoder.layers.{i}.encoder_attn.attention_weights.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.value_proj.weight', F'model.decoder.layers.{i}.encoder_attn.value_proj.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.value_proj.bias', F'model.decoder.layers.{i}.encoder_attn.value_proj.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.output_proj.weight', F'model.decoder.layers.{i}.encoder_attn.output_proj.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.output_proj.bias', F'model.decoder.layers.{i}.encoder_attn.output_proj.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.norm1.weight', F'model.decoder.layers.{i}.encoder_attn_layer_norm.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.norm1.bias', F'model.decoder.layers.{i}.encoder_attn_layer_norm.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.self_attn.out_proj.weight', F'model.decoder.layers.{i}.self_attn.out_proj.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.self_attn.out_proj.bias', F'model.decoder.layers.{i}.self_attn.out_proj.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.norm2.weight', F'model.decoder.layers.{i}.self_attn_layer_norm.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.norm2.bias', F'model.decoder.layers.{i}.self_attn_layer_norm.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.linear1.weight', F'model.decoder.layers.{i}.fc1.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.linear1.bias', F'model.decoder.layers.{i}.fc1.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.linear2.weight', F'model.decoder.layers.{i}.fc2.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.linear2.bias', F'model.decoder.layers.{i}.fc2.bias')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.norm3.weight', F'model.decoder.layers.{i}.final_layer_norm.weight')       )
  rename_keys.append((F'transformer.decoder.layers.{i}.norm3.bias', F'model.decoder.layers.{i}.final_layer_norm.bias')       )

 # fmt: on

 return rename_keys

def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  List[str]   ,			_UpperCAmelCase :  List[Any]   ,			_UpperCAmelCase :  List[str]       ):
 lowerCAmelCase  							=      dct.pop(_UpperCAmelCase       )
 lowerCAmelCase  							=      val

def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  int   ,			_UpperCAmelCase :  Union[str, Any]       ):
 # transformer decoder self-attention layers
 lowerCAmelCase  							=      config.d_model
 for i in range(config.decoder_layers       ):
  # read in weights + bias of input projection layer of self-attention
  lowerCAmelCase  							=      state_dict.pop(F'transformer.decoder.layers.{i}.self_attn.in_proj_weight'       )
  lowerCAmelCase  							=      state_dict.pop(F'transformer.decoder.layers.{i}.self_attn.in_proj_bias'       )
  # next, add query, keys and values (in that order) to the state dict
  lowerCAmelCase  							=      in_proj_weight[:hidden_size, :]
  lowerCAmelCase  							=      in_proj_bias[:hidden_size]
  lowerCAmelCase  							=      in_proj_weight[
      hidden_size : hidden_size * 2, :
  ]
  lowerCAmelCase  							=      in_proj_bias[hidden_size : hidden_size * 2]
  lowerCAmelCase  							=      in_proj_weight[-hidden_size:, :]
  lowerCAmelCase  							=      in_proj_bias[-hidden_size:]

def 						_SCREAMING_SNAKE_CASE       ():
 lowerCAmelCase  							=      'http://images.cocodataset.org/val2017/000000039769.jpg'
 lowerCAmelCase  							=      Image.open(requests.get(_UpperCAmelCase   ,			stream=_UpperCAmelCase       ).raw       )

 return im

@torch.no_grad()
def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  Optional[Any]   ,			_UpperCAmelCase :  Tuple   ,			_UpperCAmelCase :  Optional[Any]       ):
 lowerCAmelCase  							=      get_deta_config()

 # load original state dict
 if model_name == "deta-resnet-50":
  lowerCAmelCase  							=      'adet_checkpoint0011.pth'
 elif model_name == "deta-resnet-50-24-epochs":
  lowerCAmelCase  							=      'adet_2x_checkpoint0023.pth'
 else:
  raise ValueError(F'Model name {model_name} not supported'       )
 lowerCAmelCase  							=      hf_hub_download(repo_id='nielsr/deta-checkpoints'   ,			filename=_UpperCAmelCase       )
 lowerCAmelCase  							=      torch.load(_UpperCAmelCase   ,			map_location='cpu'       )['model']

 # rename keys
 lowerCAmelCase  							=      create_rename_keys(_UpperCAmelCase       )
 for src, dest in rename_keys:
  rename_key(_UpperCAmelCase   ,			_UpperCAmelCase   ,			_UpperCAmelCase       )
 read_in_decoder_q_k_v(_UpperCAmelCase   ,			_UpperCAmelCase       )

 # fix some prefixes
 for key in state_dict.copy().keys():
  if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
   lowerCAmelCase  							=      state_dict.pop(_UpperCAmelCase       )
   lowerCAmelCase  							=      val
  if "input_proj" in key:
   lowerCAmelCase  							=      state_dict.pop(_UpperCAmelCase       )
   lowerCAmelCase  							=      val
  if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
   lowerCAmelCase  							=      state_dict.pop(_UpperCAmelCase       )
   lowerCAmelCase  							=      val

    # finally, create HuggingFace model and load state dict
 lowerCAmelCase  							=      DetaForObjectDetection(_UpperCAmelCase       )
 model.load_state_dict(_UpperCAmelCase       )
 model.eval()

 lowerCAmelCase  							=      'cuda' if torch.cuda.is_available() else 'cpu'
 model.to(_UpperCAmelCase       )

 # load image processor
 lowerCAmelCase  							=      DetaImageProcessor(format='coco_detection'       )

 # verify our conversion on image
 lowerCAmelCase  							=      prepare_img()
 lowerCAmelCase  							=      processor(images=_UpperCAmelCase   ,			return_tensors='pt'       )
 lowerCAmelCase  							=      encoding['pixel_values']
 lowerCAmelCase  							=      model(pixel_values.to(_UpperCAmelCase       )       )

 # verify logits
 if model_name == "deta-resnet-50":
  lowerCAmelCase  							=      torch.tensor(
      [[-7.3978, -2.5406, -4.1668], [-8.2684, -3.9933, -3.8096], [-7.0515, -3.7973, -5.8516]]       )
  lowerCAmelCase  							=      torch.tensor([[0.5043, 0.4973, 0.9998], [0.2542, 0.5489, 0.4748], [0.5490, 0.2765, 0.0570]]       )
 elif model_name == "deta-resnet-50-24-epochs":
  lowerCAmelCase  							=      torch.tensor(
      [[-7.1688, -2.4857, -4.8669], [-7.8630, -3.8154, -4.2674], [-7.2730, -4.1865, -5.5323]]       )
  lowerCAmelCase  							=      torch.tensor([[0.5021, 0.4971, 0.9994], [0.2546, 0.5486, 0.4731], [0.1686, 0.1986, 0.2142]]       )

 assert torch.allclose(outputs.logits[0, :3, :3]   ,			expected_logits.to(_UpperCAmelCase       )   ,			atol=1e-4       )
 assert torch.allclose(outputs.pred_boxes[0, :3, :3]   ,			expected_boxes.to(_UpperCAmelCase       )   ,			atol=1e-4       )
 print('Everything ok!'       )

 if pytorch_dump_folder_path:
  # Save model and processor
  logger.info(F'Saving PyTorch model and processor to {pytorch_dump_folder_path}...'       )
  Path(_UpperCAmelCase       ).mkdir(exist_ok=_UpperCAmelCase       )
  model.save_pretrained(_UpperCAmelCase       )
  processor.save_pretrained(_UpperCAmelCase       )

 # Push to hub
 if push_to_hub:
  print('Pushing model and processor to hub...'       )
  model.push_to_hub(F'jozhang97/{model_name}'       )
  processor.push_to_hub(F'jozhang97/{model_name}'       )


if __name__ == "__main__":
       __UpperCamelCase			:		Optional[int]		    =   argparse.ArgumentParser()

       parser.add_argument(
           '''--model_name''',
           type=str,
           default='''deta-resnet-50''',
           choices=['''deta-resnet-50''', '''deta-resnet-50-24-epochs'''],
           help='''Name of the model you\'d like to convert.''',
       )
       parser.add_argument(
           '''--pytorch_dump_folder_path''',
           default=None,
           type=str,
           help='''Path to the folder to output PyTorch model.''',
       )
       parser.add_argument(
           '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
       )
       __UpperCamelCase			:		Optional[Any]		    =   parser.parse_args()
       convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)












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


lowerCAmelCase_        =			logging.get_logger(__name__)

lowerCAmelCase_        =			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"""),
    ]
)

lowerCAmelCase_        =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)


def 			lowerCamelCase_		(					lowerCAmelCase:		str )->						Tuple:
  for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
    if class_name in processors:
      _snake_case      : Optional[Any]														=		model_type_to_module_name(lowerCAmelCase )

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

  for processor in PROCESSOR_MAPPING._extra_content.values():
    if getattr(lowerCAmelCase			,							'__name__'			,							lowerCAmelCase ) == 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.
  _snake_case      : Union[str, Any]														=		importlib.import_module('transformers' )
  if hasattr(lowerCAmelCase			,							lowerCAmelCase ):
    return getattr(lowerCAmelCase			,							lowerCAmelCase )

  return None







class 				_lowerCAmelCase			:


  '''simple docstring'''







  def __init__(					self					:    Optional[Any]							):


    '''simple docstring'''





    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 UpperCamelCase_       (					cls					:    Optional[Any]					, UpperCamelCase					:    Optional[Any]					, **UpperCamelCase					:    Dict							):


    '''simple docstring'''





    _snake_case      : Optional[int]														=		kwargs.pop('config'					, UpperCamelCase							)
    _snake_case      : str														=		kwargs.pop('trust_remote_code'					, UpperCamelCase							)
    _snake_case      : List[Any]														=		True

    _snake_case      : str														=		None
    _snake_case      : str														=		None

    # First, let's see if we have a preprocessor config.
    # Filter the kwargs for `get_file_from_repo`.
    _snake_case      : Dict														=		{
        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
    _snake_case      : List[Any]														=		get_file_from_repo(
        UpperCamelCase					, UpperCamelCase					, **UpperCamelCase							)
    if preprocessor_config_file is not None:
      _snake_case							,    _snake_case      : Optional[int]														=		ImageProcessingMixin.get_image_processor_dict(UpperCamelCase					, **UpperCamelCase							)
      _snake_case      : List[str]														=		config_dict.get('processor_class'					, UpperCamelCase							)
      if "AutoProcessor" in config_dict.get('auto_map'					, {}							):
        _snake_case      : Optional[Any]														=		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:
      _snake_case							,    _snake_case      : Union[str, Any]														=		FeatureExtractionMixin.get_feature_extractor_dict(UpperCamelCase					, **UpperCamelCase							)
      _snake_case      : int														=		config_dict.get('processor_class'					, UpperCamelCase							)
      if "AutoProcessor" in config_dict.get('auto_map'					, {}							):
        _snake_case      : str														=		config_dict['auto_map']['AutoProcessor']

    if processor_class is None:
      # Next, let's check whether the processor class is saved in a tokenizer
      _snake_case      : Union[str, Any]														=		get_file_from_repo(
          UpperCamelCase					, UpperCamelCase					, **UpperCamelCase							)
      if tokenizer_config_file is not None:
        with open(UpperCamelCase					, encoding='utf-8'							) as reader:
          _snake_case      : Optional[int]														=		json.load(UpperCamelCase							)

        _snake_case      : int														=		config_dict.get('processor_class'					, UpperCamelCase							)
        if "AutoProcessor" in config_dict.get('auto_map'					, {}							):
          _snake_case      : str														=		config_dict['auto_map']['AutoProcessor']

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

      # And check if the config contains the processor class.
      _snake_case      : str														=		getattr(UpperCamelCase					, 'processor_class'					, UpperCamelCase							)
      if hasattr(UpperCamelCase					, 'auto_map'							) and "AutoProcessor" in config.auto_map:
        _snake_case      : Any														=		config.auto_map['AutoProcessor']

    if processor_class is not None:
      _snake_case      : Tuple														=		processor_class_from_name(UpperCamelCase							)

    _snake_case      : int														=		processor_auto_map is not None
    _snake_case      : Optional[int]														=		processor_class is not None or type(UpperCamelCase							) in PROCESSOR_MAPPING
    _snake_case      : Union[str, Any]														=		resolve_trust_remote_code(
        UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)

    if has_remote_code and trust_remote_code:
      _snake_case      : List[str]														=		get_class_from_dynamic_module(
          UpperCamelCase					, UpperCamelCase					, **UpperCamelCase							)
      _snake_case      : Optional[Any]														=		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 UpperCamelCase_       (					UpperCamelCase					:    int					, UpperCamelCase					:    str							):


    '''simple docstring'''





    PROCESSOR_MAPPING.register(UpperCamelCase					, UpperCamelCase							)




