






"""simple docstring"""




import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         XLMForMultipleChoice,
         XLMForQuestionAnswering,
         XLMForQuestionAnsweringSimple,
         XLMForSequenceClassification,
         XLMForTokenClassification,
         XLMModel,
         XLMWithLMHeadModel,
     )
     from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST




class    lowercase_    :






      def __init__(    self     ,     a_     ,     a_=1_3     ,     a_=7     ,     a_=True     ,     a_=True     ,     a_=True     ,     a_=True     ,     a_=True     ,     a_=False     ,     a_=False     ,     a_=False     ,     a_=2     ,     a_=9_9     ,     a_=0     ,     a_=3_2     ,     a_=5     ,     a_=4     ,     a_=0.1     ,     a_=0.1     ,     a_=5_1_2     ,     a_=2     ,     a_=0.02     ,     a_=2     ,     a_=4     ,     a_="last"     ,     a_=True     ,     a_=None     ,     a_=0     ,     )	->Dict:







        '''simple docstring'''


        _a							=	parent
        _a							=	batch_size
        _a							=	seq_length
        _a							=	is_training
        _a							=	use_input_lengths
        _a							=	use_token_type_ids
        _a							=	use_labels
        _a							=	gelu_activation
        _a							=	sinusoidal_embeddings
        _a							=	causal
        _a							=	asm
        _a							=	n_langs
        _a							=	vocab_size
        _a							=	n_special
        _a							=	hidden_size
        _a							=	num_hidden_layers
        _a							=	num_attention_heads
        _a							=	hidden_dropout_prob
        _a							=	attention_probs_dropout_prob
        _a							=	max_position_embeddings
        _a							=	type_sequence_label_size
        _a							=	initializer_range
        _a							=	num_labels
        _a							=	num_choices
        _a							=	summary_type
        _a							=	use_proj
        _a							=	scope
        _a							=	bos_token_id






      def 			lowerCamelCase__    (    self	)	->Dict:







        '''simple docstring'''


        _a							=	ids_tensor([self.batch_size, self.seq_length]     ,     self.vocab_size	)
        _a							=	random_attention_mask([self.batch_size, self.seq_length]	)

        _a							=	None
        if self.use_input_lengths:
          _a							=	(
              ids_tensor([self.batch_size]     ,     vocab_size=2	) + self.seq_length - 2
          )  # small variation of seq_length

        _a							=	None
        if self.use_token_type_ids:
          _a							=	ids_tensor([self.batch_size, self.seq_length]     ,     self.n_langs	)

        _a							=	None
        _a							=	None
        _a							=	None
        if self.use_labels:
          _a							=	ids_tensor([self.batch_size]     ,     self.type_sequence_label_size	)
          _a							=	ids_tensor([self.batch_size, self.seq_length]     ,     self.num_labels	)
          _a							=	ids_tensor([self.batch_size]     ,     2	).float()
          _a							=	ids_tensor([self.batch_size]     ,     self.num_choices	)

        _a							=	self.get_config()

        return (
            config,
            input_ids,
            token_type_ids,
            input_lengths,
            sequence_labels,
            token_labels,
            is_impossible_labels,
            choice_labels,
            input_mask,
        )






      def 			lowerCamelCase__    (    self	)	->Optional[Any]:







        '''simple docstring'''


        return XLMConfig(
            vocab_size=self.vocab_size     ,     n_special=self.n_special     ,     emb_dim=self.hidden_size     ,     n_layers=self.num_hidden_layers     ,     n_heads=self.num_attention_heads     ,     dropout=self.hidden_dropout_prob     ,     attention_dropout=self.attention_probs_dropout_prob     ,     gelu_activation=self.gelu_activation     ,     sinusoidal_embeddings=self.sinusoidal_embeddings     ,     asm=self.asm     ,     causal=self.causal     ,     n_langs=self.n_langs     ,     max_position_embeddings=self.max_position_embeddings     ,     initializer_range=self.initializer_range     ,     summary_type=self.summary_type     ,     use_proj=self.use_proj     ,     num_labels=self.num_labels     ,     bos_token_id=self.bos_token_id     ,     )






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     )	->Optional[int]:







        '''simple docstring'''


        _a							=	XLMModel(config=__lowerCamelCase	)
        model.to(__lowerCamelCase	)
        model.eval()
        _a							=	model(__lowerCamelCase     ,     lengths=__lowerCamelCase     ,     langs=__lowerCamelCase	)
        _a							=	model(__lowerCamelCase     ,     langs=__lowerCamelCase	)
        _a							=	model(__lowerCamelCase	)
        self.parent.assertEqual(result.last_hidden_state.shape     ,     (self.batch_size, self.seq_length, self.hidden_size)	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     )	->int:







        '''simple docstring'''


        _a							=	XLMWithLMHeadModel(__lowerCamelCase	)
        model.to(__lowerCamelCase	)
        model.eval()

        _a							=	model(__lowerCamelCase     ,     token_type_ids=__lowerCamelCase     ,     labels=__lowerCamelCase	)
        self.parent.assertEqual(result.loss.shape     ,     ()	)
        self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.seq_length, self.vocab_size)	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     )	->Optional[int]:







        '''simple docstring'''


        _a							=	XLMForQuestionAnsweringSimple(__lowerCamelCase	)
        model.to(__lowerCamelCase	)
        model.eval()

        _a							=	model(__lowerCamelCase	)

        _a							=	model(__lowerCamelCase     ,     start_positions=__lowerCamelCase     ,     end_positions=__lowerCamelCase	)
        _a							=	outputs
        self.parent.assertEqual(result.start_logits.shape     ,     (self.batch_size, self.seq_length)	)
        self.parent.assertEqual(result.end_logits.shape     ,     (self.batch_size, self.seq_length)	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     )	->int:







        '''simple docstring'''


        _a							=	XLMForQuestionAnswering(__lowerCamelCase	)
        model.to(__lowerCamelCase	)
        model.eval()

        _a							=	model(__lowerCamelCase	)

        _a							=	model(
            __lowerCamelCase     ,     start_positions=__lowerCamelCase     ,     end_positions=__lowerCamelCase     ,     cls_index=__lowerCamelCase     ,     is_impossible=__lowerCamelCase     ,     p_mask=__lowerCamelCase     ,     )

        _a							=	model(
            __lowerCamelCase     ,     start_positions=__lowerCamelCase     ,     end_positions=__lowerCamelCase     ,     cls_index=__lowerCamelCase     ,     is_impossible=__lowerCamelCase     ,     )

        (_a	)							=	result_with_labels.to_tuple()

        _a							=	model(__lowerCamelCase     ,     start_positions=__lowerCamelCase     ,     end_positions=__lowerCamelCase	)

        (_a	)							=	result_with_labels.to_tuple()

        self.parent.assertEqual(result_with_labels.loss.shape     ,     ()	)
        self.parent.assertEqual(result.start_top_log_probs.shape     ,     (self.batch_size, model.config.start_n_top)	)
        self.parent.assertEqual(result.start_top_index.shape     ,     (self.batch_size, model.config.start_n_top)	)
        self.parent.assertEqual(
            result.end_top_log_probs.shape     ,     (self.batch_size, model.config.start_n_top * model.config.end_n_top)	)
        self.parent.assertEqual(
            result.end_top_index.shape     ,     (self.batch_size, model.config.start_n_top * model.config.end_n_top)	)
        self.parent.assertEqual(result.cls_logits.shape     ,     (self.batch_size,)	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     )	->str:







        '''simple docstring'''


        _a							=	XLMForSequenceClassification(__lowerCamelCase	)
        model.to(__lowerCamelCase	)
        model.eval()

        _a							=	model(__lowerCamelCase	)
        _a							=	model(__lowerCamelCase     ,     labels=__lowerCamelCase	)
        self.parent.assertEqual(result.loss.shape     ,     ()	)
        self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.type_sequence_label_size)	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     )	->str:







        '''simple docstring'''


        _a							=	self.num_labels
        _a							=	XLMForTokenClassification(__lowerCamelCase	)
        model.to(__lowerCamelCase	)
        model.eval()

        _a							=	model(__lowerCamelCase     ,     attention_mask=__lowerCamelCase     ,     labels=__lowerCamelCase	)
        self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.seq_length, self.num_labels)	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     )	->Any:







        '''simple docstring'''


        _a							=	self.num_choices
        _a							=	XLMForMultipleChoice(config=__lowerCamelCase	)
        model.to(__lowerCamelCase	)
        model.eval()
        _a							=	input_ids.unsqueeze(1	).expand(-1     ,     self.num_choices     ,     -1	).contiguous()
        _a							=	token_type_ids.unsqueeze(1	).expand(-1     ,     self.num_choices     ,     -1	).contiguous()
        _a							=	input_mask.unsqueeze(1	).expand(-1     ,     self.num_choices     ,     -1	).contiguous()
        _a							=	model(
            __lowerCamelCase     ,     attention_mask=__lowerCamelCase     ,     token_type_ids=__lowerCamelCase     ,     labels=__lowerCamelCase     ,     )
        self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.num_choices)	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        _a							=	self.prepare_config_and_inputs()
        (
            _a	
        )							=	config_and_inputs
        _a							=	{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths}
        return config, inputs_dict







@require_torch
class    lowercase_    (lowerCamelCase__,    lowerCamelCase__,    lowerCamelCase__,    unittest.TestCase     ):
      A__	:		Union[str, Any]       			=				(
          (
              XLMModel,
              XLMWithLMHeadModel,
              XLMForQuestionAnswering,
              XLMForSequenceClassification,
              XLMForQuestionAnsweringSimple,
              XLMForTokenClassification,
              XLMForMultipleChoice,
          )
          if is_torch_available()
          else ()
      )
      A__	:		List[Any]       			=				(
          (XLMWithLMHeadModel,) if is_torch_available() else ()
      )  # TODO (PVP): Check other models whether language generation is also applicable
      A__	:		Union[str, Any]       			=				(
          {
              '''feature-extraction''': XLMModel,
              '''fill-mask''': XLMWithLMHeadModel,
              '''question-answering''': XLMForQuestionAnsweringSimple,
              '''text-classification''': XLMForSequenceClassification,
              '''text-generation''': XLMWithLMHeadModel,
              '''token-classification''': XLMForTokenClassification,
              '''zero-shot''': XLMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Optional[Any]:







        '''simple docstring'''


        if (
            pipeline_test_casse_name == "QAPipelineTests"
            and tokenizer_name is not None
            and not tokenizer_name.endswith("Fast"	)
        ):
          # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
          # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
          # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
          return True

        return False






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_=False	)	->List[Any]:







        '''simple docstring'''


        _a							=	super()._prepare_for_class(__lowerCamelCase     ,     __lowerCamelCase     ,     return_labels=__lowerCamelCase	)

        if return_labels:
          if model_class.__name__ == "XLMForQuestionAnswering":
            _a							=	torch.zeros(
                self.model_tester.batch_size     ,     dtype=torch.long     ,     device=__lowerCamelCase	)
            _a							=	torch.zeros(
                self.model_tester.batch_size     ,     dtype=torch.long     ,     device=__lowerCamelCase	)

        return inputs_dict






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


        _a							=	XLMModelTester(self	)
        _a							=	ConfigTester(self     ,     config_class=__lowerCamelCase     ,     emb_dim=3_7	)






      def 			lowerCamelCase__    (    self	)	->Union[str, Any]:







        '''simple docstring'''


        self.config_tester.run_common_tests()






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_model(*__lowerCamelCase	)






      def 			lowerCamelCase__    (    self	)	->List[str]:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_lm_head(*__lowerCamelCase	)






      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_simple_qa(*__lowerCamelCase	)






      def 			lowerCamelCase__    (    self	)	->Optional[Any]:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_qa(*__lowerCamelCase	)






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_sequence_classif(*__lowerCamelCase	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_token_classif(*__lowerCamelCase	)






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_xlm_for_multiple_choice(*__lowerCamelCase	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_=False     ,     a_=1	)	->Dict:







        '''simple docstring'''


        self.assertIsInstance(__lowerCamelCase     ,     __lowerCamelCase	)
        self.assertListEqual(
            [isinstance(__lowerCamelCase     ,     __lowerCamelCase	) for iter_attentions in attentions]     ,     [True] * len(__lowerCamelCase	)	)
        self.assertEqual(len(__lowerCamelCase	)     ,     (max_length - min_length) * num_beam_groups	)

        for idx, iter_attentions in enumerate(__lowerCamelCase	):
          # adds PAD dummy token
          _a							=	min_length + idx + 1
          _a							=	min_length + idx + 1

          _a							=	(
              batch_size * num_beam_groups,
              config.num_attention_heads,
              tgt_len,
              src_len,
          )
          # check attn size
          self.assertListEqual(
              [layer_attention.shape for layer_attention in iter_attentions]     ,     [expected_shape] * len(__lowerCamelCase	)	)






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_=False     ,     a_=1	)	->Union[str, Any]:







        '''simple docstring'''


        self.assertIsInstance(__lowerCamelCase     ,     __lowerCamelCase	)
        self.assertListEqual(
            [isinstance(__lowerCamelCase     ,     __lowerCamelCase	) for iter_hidden_states in hidden_states]     ,     [True] * len(__lowerCamelCase	)     ,     )
        self.assertEqual(len(__lowerCamelCase	)     ,     (max_length - min_length) * num_beam_groups	)

        for idx, iter_hidden_states in enumerate(__lowerCamelCase	):
          # adds PAD dummy token
          _a							=	min_length + idx + 1
          _a							=	(batch_size * num_beam_groups, seq_len, config.hidden_size)
          # check hidden size
          self.assertListEqual(
              [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states]     ,     [expected_shape] * len(__lowerCamelCase	)     ,     )
        pass






      @slow
      def 			lowerCamelCase__    (    self	)	->Optional[Any]:







        '''simple docstring'''


        for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          _a							=	XLMModel.from_pretrained(__lowerCamelCase	)
          self.assertIsNotNone(__lowerCamelCase	)







@require_torch
class    lowercase_    (unittest.TestCase     ):






      @slow
      def 			lowerCamelCase__    (    self	)	->Union[str, Any]:







        '''simple docstring'''


        _a							=	XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048"	)
        model.to(__lowerCamelCase	)
        _a							=	torch.tensor([[1_4, 4_4_7]]     ,     dtype=torch.long     ,     device=__lowerCamelCase	)  # the president
        _a							=	[
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
            1_4,
            4_4_7,
        ]  # the president the president the president the president the president the president the president the president the president the president
        # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
        _a							=	model.generate(__lowerCamelCase     ,     do_sample=__lowerCamelCase	)
        self.assertListEqual(output_ids[0].cpu().numpy().tolist()     ,     __lowerCamelCase	)







"""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 (      UpperCamelCase_:							str					)       ->							Union[str, Any]:







  '''simple docstring'''







  for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
    if class_name in extractors:
      _a							=	model_type_to_module_name(UpperCamelCase_					)

      _a							=	importlib.import_module(f'''.{module_name}'''     , "transformers.models"					)
      try:
        return getattr(UpperCamelCase_     , UpperCamelCase_					)
      except AttributeError:
        continue

  for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
    if getattr(UpperCamelCase_     , "__name__"     , UpperCamelCase_					) == 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.
  _a							=	importlib.import_module("transformers"					)
  if hasattr(UpperCamelCase_     , UpperCamelCase_					):
    return getattr(UpperCamelCase_     , UpperCamelCase_					)

  return None






def        lowerCAmelCase (      UpperCamelCase_:							Union[str, os.PathLike]     , UpperCamelCase_:							Optional[Union[str, os.PathLike]] = None     , UpperCamelCase_:							bool = False     , UpperCamelCase_:							bool = False     , UpperCamelCase_:							Optional[Dict[str, str]] = None     , UpperCamelCase_:							Optional[Union[bool, str]] = None     , UpperCamelCase_:							Optional[str] = None     , UpperCamelCase_:							bool = False     , **UpperCamelCase_:							Dict     , )       ->							Optional[int]:







  '''simple docstring'''







  _a							=	get_file_from_repo(
      UpperCamelCase_     , UpperCamelCase_     , cache_dir=UpperCamelCase_     , force_download=UpperCamelCase_     , resume_download=UpperCamelCase_     , proxies=UpperCamelCase_     , use_auth_token=UpperCamelCase_     , revision=UpperCamelCase_     , local_files_only=UpperCamelCase_     , )
  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(UpperCamelCase_     , encoding="utf-8"					) as reader:
    return json.load(UpperCamelCase_					)




class    lowercase_    :






      def __init__(    self	)	->List[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(a_	)
      def 			lowerCamelCase__    (    cls     ,     a_     ,     **a_	)	->Dict:







        '''simple docstring'''


        _a							=	kwargs.pop("config"     ,     a_	)
        _a							=	kwargs.pop("trust_remote_code"     ,     a_	)
        _a							=	True

        _a			,	_a							=	ImageProcessingMixin.get_image_processor_dict(a_     ,     **a_	)
        _a							=	config_dict.get("image_processor_type"     ,     a_	)
        _a							=	None
        if "AutoImageProcessor" in config_dict.get("auto_map"     ,     {}	):
          _a							=	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:
          _a							=	config_dict.pop("feature_extractor_type"     ,     a_	)
          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."	)
            _a							=	feature_extractor_class.replace("FeatureExtractor"     ,     "ImageProcessor"	)
          if "AutoFeatureExtractor" in config_dict.get("auto_map"     ,     {}	):
            _a							=	config_dict["auto_map"]["AutoFeatureExtractor"]
            _a							=	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(a_     ,     a_	):
            _a							=	AutoConfig.from_pretrained(a_     ,     **a_	)
          # It could be in `config.image_processor_type``
          _a							=	getattr(a_     ,     "image_processor_type"     ,     a_	)
          if hasattr(a_     ,     "auto_map"	) and "AutoImageProcessor" in config.auto_map:
            _a							=	config.auto_map["AutoImageProcessor"]

        if image_processor_class is not None:
          _a							=	image_processor_class_from_name(a_	)

        _a							=	image_processor_auto_map is not None
        _a							=	image_processor_class is not None or type(a_	) in IMAGE_PROCESSOR_MAPPING
        _a							=	resolve_trust_remote_code(
            a_     ,     a_     ,     a_     ,     a_	)

        if has_remote_code and trust_remote_code:
          _a							=	get_class_from_dynamic_module(
              a_     ,     a_     ,     **a_	)
          _a							=	kwargs.pop("code_revision"     ,     a_	)
          if os.path.isdir(a_	):
            image_processor_class.register_for_auto_class()
          return image_processor_class.from_dict(a_     ,     **a_	)
        elif image_processor_class is not None:
          return image_processor_class.from_dict(a_     ,     **a_	)
        # Last try: we use the IMAGE_PROCESSOR_MAPPING.
        elif type(a_	) in IMAGE_PROCESSOR_MAPPING:
          _a							=	IMAGE_PROCESSOR_MAPPING[type(a_	)]
          return image_processor_class.from_dict(a_     ,     **a_	)

        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__    (    a_     ,     a_	)	->Optional[int]:







        '''simple docstring'''


        IMAGE_PROCESSOR_MAPPING.register(a_     ,     a_	)


