





'''simple docstring'''



from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import numpy as np
	import tensorflow as tf

	from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
	from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import MobileViTImageProcessor






class 							__lowercase				(					lowerCAmelCase__  ):







	'''simple docstring'''

	def   _UpperCAmelCase   (self       )							->							Tuple:







				'''simple docstring'''





				__lowercase   =							self.config_class(**self.inputs_dict       )
				self.parent.assertTrue(hasattr(_lowerCamelCase   ,'''hidden_sizes'''       )       )
				self.parent.assertTrue(hasattr(_lowerCamelCase   ,'''neck_hidden_sizes'''       )       )
				self.parent.assertTrue(hasattr(_lowerCamelCase   ,'''num_attention_heads'''       )       )






class 							__lowercase				:







	'''simple docstring'''

	def __init__(self   ,_lowerCamelCase   ,_lowerCamelCase=13   ,_lowerCamelCase=32   ,_lowerCamelCase=2   ,_lowerCamelCase=3   ,_lowerCamelCase=640   ,_lowerCamelCase=4   ,_lowerCamelCase="silu"   ,_lowerCamelCase=3   ,_lowerCamelCase=32   ,_lowerCamelCase=0.1   ,_lowerCamelCase=0.1   ,_lowerCamelCase=0.1   ,_lowerCamelCase=0.0_2   ,_lowerCamelCase=True   ,_lowerCamelCase=True   ,_lowerCamelCase=10   ,_lowerCamelCase=None   ,)							->							Dict:







				'''simple docstring'''





				__lowercase   =							parent
				__lowercase   =							batch_size
				__lowercase   =							image_size
				__lowercase   =							patch_size
				__lowercase   =							num_channels
				__lowercase   =							last_hidden_size
				__lowercase   =							num_attention_heads
				__lowercase   =							hidden_act
				__lowercase   =							conv_kernel_size
				__lowercase   =							output_stride
				__lowercase   =							hidden_dropout_prob
				__lowercase   =							attention_probs_dropout_prob
				__lowercase   =							classifier_dropout_prob
				__lowercase   =							use_labels
				__lowercase   =							is_training
				__lowercase   =							num_labels
				__lowercase   =							initializer_range
				__lowercase   =							scope


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







				'''simple docstring'''





				__lowercase   =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

				__lowercase   =							None
				__lowercase   =							None
				if self.use_labels:
							__lowercase   =							ids_tensor([self.batch_size]   ,self.num_labels       )
							__lowercase   =							ids_tensor([self.batch_size, self.image_size, self.image_size]   ,self.num_labels       )

				__lowercase   =							self.get_config()

				return config, pixel_values, labels, pixel_labels


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







				'''simple docstring'''





				return MobileViTConfig(
				    image_size=self.image_size   ,patch_size=self.patch_size   ,num_channels=self.num_channels   ,num_attention_heads=self.num_attention_heads   ,hidden_act=self.hidden_act   ,conv_kernel_size=self.conv_kernel_size   ,output_stride=self.output_stride   ,hidden_dropout_prob=self.hidden_dropout_prob   ,attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,classifier_dropout_prob=self.classifier_dropout_prob   ,initializer_range=self.initializer_range   ,)


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase       )							->							Dict:







				'''simple docstring'''





				__lowercase   =							TFMobileViTModel(config=_lowerCamelCase       )
				__lowercase   =							model(_lowerCamelCase   ,training=_lowerCamelCase       )
				__lowercase   =							__lowercase   =							self.image_size // self.output_stride
				self.parent.assertEqual(
				    result.last_hidden_state.shape   ,(self.batch_size, self.last_hidden_size, expected_height, expected_width)       )


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase       )							->							List[str]:







				'''simple docstring'''





				__lowercase   =							self.num_labels
				__lowercase   =							TFMobileViTForImageClassification(_lowerCamelCase       )
				__lowercase   =							model(_lowerCamelCase   ,labels=_lowerCamelCase   ,training=_lowerCamelCase       )
				self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.num_labels)       )


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase       )							->							Any:







				'''simple docstring'''





				__lowercase   =							self.num_labels
				__lowercase   =							TFMobileViTForSemanticSegmentation(_lowerCamelCase       )
				__lowercase   =							__lowercase   =							self.image_size // self.output_stride

				__lowercase   =							model(_lowerCamelCase   ,training=_lowerCamelCase       )
				self.parent.assertEqual(
				    result.logits.shape   ,(self.batch_size, self.num_labels, expected_height, expected_width)       )

				__lowercase   =							model(_lowerCamelCase   ,labels=_lowerCamelCase   ,training=_lowerCamelCase       )
				self.parent.assertEqual(
				    result.logits.shape   ,(self.batch_size, self.num_labels, expected_height, expected_width)       )


	def   _UpperCAmelCase   (self       )							->							Dict:







				'''simple docstring'''





				__lowercase   =							self.prepare_config_and_inputs()
				__lowercase  ,						__lowercase  ,						__lowercase  ,						__lowercase   =							config_and_inputs
				__lowercase   =							{'''pixel_values''': pixel_values}
				return config, inputs_dict






@require_tf
class 							__lowercase				(					lowerCAmelCase__       ,					lowerCAmelCase__       ,					unittest.TestCase  ):







	'''simple docstring'''

	a			: Optional[int]      =				(
	    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
	    if is_tf_available()
	    else ()
	)
	a			: Optional[int]      =				(
	    {"feature-extraction": TFMobileViTModel, "image-classification": TFMobileViTForImageClassification}
	    if is_tf_available()
	    else {}
	)

	a			: Dict      =				False
	a			: Union[str, Any]      =				False
	a			: Optional[Any]      =				False
	a			: int      =				False
	a			: List[Any]      =				False


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







				'''simple docstring'''





				__lowercase   =							TFMobileViTModelTester(self       )
				__lowercase   =							TFMobileViTConfigTester(self   ,config_class=_lowerCamelCase   ,has_text_modality=_lowerCamelCase       )


	def   _UpperCAmelCase   (self       )							->							Dict:







				'''simple docstring'''





				self.config_tester.run_common_tests()


	@unittest.skip(reason='''MobileViT does not use inputs_embeds'''       )
	def   _UpperCAmelCase   (self       )							->							int:







				'''simple docstring'''





				pass


	@unittest.skip(reason='''MobileViT does not support input and output embeddings'''       )
	def   _UpperCAmelCase   (self       )							->							Tuple:







				'''simple docstring'''





				pass


	@unittest.skip(reason='''MobileViT does not output attentions'''       )
	def   _UpperCAmelCase   (self       )							->							Dict:







				'''simple docstring'''





				pass


	def   _UpperCAmelCase   (self       )							->							str:







				'''simple docstring'''





				__lowercase  ,						__lowercase   =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							__lowercase   =							model_class(_lowerCamelCase       )
							__lowercase   =							inspect.signature(model.call       )
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							__lowercase   =							[*signature.parameters.keys()]

							__lowercase   =							['''pixel_values''']
							self.assertListEqual(arg_names[:1]   ,_lowerCamelCase       )


	def   _UpperCAmelCase   (self       )							->							Optional[int]:







				'''simple docstring'''





				__lowercase   =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_lowerCamelCase       )


	def   _UpperCAmelCase   (self       )							->							str:







				'''simple docstring'''





				def check_hidden_states_output(_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase       ):
							__lowercase   =							model_class(_lowerCamelCase       )

							__lowercase   =							model(**self._prepare_for_class(_lowerCamelCase   ,_lowerCamelCase       )       )

							__lowercase   =							outputs.hidden_states

							__lowercase   =							5
							self.assertEqual(len(_lowerCamelCase       )   ,_lowerCamelCase       )

							# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
							# with the width and height being successively divided by 2.
							__lowercase   =							2
							for i in range(len(_lowerCamelCase       )       ):
										self.assertListEqual(
										    list(hidden_states[i].shape[-2:]       )   ,[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]   ,)
										divisor *= 2

							self.assertEqual(self.model_tester.output_stride   ,divisor // 2       )

				__lowercase  ,						__lowercase   =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							__lowercase   =							True
							check_hidden_states_output(_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase       )

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							__lowercase   =							True

							check_hidden_states_output(_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase       )


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







				'''simple docstring'''





				__lowercase   =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase       )


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







				'''simple docstring'''





				__lowercase   =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase       )


	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''       )       ) == 0   ,reason='''TF does not support backprop for grouped convolutions on CPU.'''   ,)
	def   _UpperCAmelCase   (self       )							->							List[Any]:







				'''simple docstring'''





				super().test_dataset_conversion()


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase=2E-1   ,_lowerCamelCase=2E-1       )							->							Optional[int]:







				'''simple docstring'''





				self.assertTrue(np.allclose(_lowerCamelCase   ,_lowerCamelCase   ,atol=_lowerCamelCase   ,rtol=_lowerCamelCase       )       )


	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''       )       ) == 0   ,reason='''TF does not support backprop for grouped convolutions on CPU.'''   ,)
	@slow
	def   _UpperCAmelCase   (self       )							->							Tuple:







				'''simple docstring'''





				__lowercase  ,						__lowercase   =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							# Since `TFMobileViTModel` cannot operate with the default `fit()` method.
							if model_class.__name__ != "TFMobileViTModel":
										__lowercase   =							model_class(_lowerCamelCase       )
										if getattr(_lowerCamelCase   ,'''hf_compute_loss'''   ,_lowerCamelCase       ):
													super().test_keras_fit()


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







				'''simple docstring'''





				__lowercase  ,						__lowercase   =							self.model_tester.prepare_config_and_inputs_for_common()
				for model_class in self.all_model_classes:
							# set an ignore index to correctly test the masked loss used in
							# `TFMobileViTForSemanticSegmentation`.
							if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
										__lowercase   =							5

							__lowercase   =							model_class(_lowerCamelCase       )
							if getattr(_lowerCamelCase   ,'''hf_compute_loss'''   ,_lowerCamelCase       ):
										# The number of elements in the loss should be the same as the number of elements in the label
										__lowercase   =							self._prepare_for_class(inputs_dict.copy()   ,_lowerCamelCase   ,return_labels=_lowerCamelCase       )
										__lowercase   =							prepared_for_class[
										    sorted(prepared_for_class.keys() - inputs_dict.keys()   ,reverse=_lowerCamelCase       )[0]
										]
										__lowercase   =							added_label.shape.as_list()[:1]

										# Test that model correctly compute the loss with kwargs
										__lowercase   =							self._prepare_for_class(inputs_dict.copy()   ,_lowerCamelCase   ,return_labels=_lowerCamelCase       )
										__lowercase   =							{'''input_ids''', '''pixel_values''', '''input_features'''}
										__lowercase   =							possible_input_names.intersection(set(_lowerCamelCase       )       ).pop()
										__lowercase   =							prepared_for_class.pop(_lowerCamelCase       )

										__lowercase   =							model(_lowerCamelCase   ,**_lowerCamelCase       )[0]
										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]       )

										# Test that model correctly compute the loss when we mask some positions
										__lowercase   =							self._prepare_for_class(inputs_dict.copy()   ,_lowerCamelCase   ,return_labels=_lowerCamelCase       )
										__lowercase   =							{'''input_ids''', '''pixel_values''', '''input_features'''}
										__lowercase   =							possible_input_names.intersection(set(_lowerCamelCase       )       ).pop()
										__lowercase   =							prepared_for_class.pop(_lowerCamelCase       )
										if "labels" in prepared_for_class:
													__lowercase   =							prepared_for_class['''labels'''].numpy()
													if len(labels.shape       ) > 1 and labels.shape[1] != 1:
																# labels[0] = -100
																__lowercase   =							tf.convert_to_tensor(_lowerCamelCase       )
																__lowercase   =							model(_lowerCamelCase   ,**_lowerCamelCase       )[0]
																self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]       )
																self.assertTrue(not np.any(np.isnan(loss.numpy()       )       )       )

                # Test that model correctly compute the loss with a dict
										__lowercase   =							self._prepare_for_class(inputs_dict.copy()   ,_lowerCamelCase   ,return_labels=_lowerCamelCase       )
										__lowercase   =							model(_lowerCamelCase       )[0]
										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]       )

										# Test that model correctly compute the loss with a tuple
										__lowercase   =							self._prepare_for_class(inputs_dict.copy()   ,_lowerCamelCase   ,return_labels=_lowerCamelCase       )

										# Get keys that were added with the _prepare_for_class function
										__lowercase   =							prepared_for_class.keys() - inputs_dict.keys()
										__lowercase   =							inspect.signature(model.call       ).parameters
										__lowercase   =							list(signature.keys()       )

										# Create a dictionary holding the location of the tensors in the tuple
										__lowercase   =							{0: input_name}
										for label_key in label_keys:
													__lowercase   =							signature_names.index(_lowerCamelCase       )
													__lowercase   =							label_key
										__lowercase   =							sorted(tuple_index_mapping.items()       )
										# Initialize a list with their default values, update the values and convert to a tuple
										__lowercase   =							[]

										for name in signature_names:
													if name != "kwargs":
																list_input.append(signature[name].default       )

										for index, value in sorted_tuple_index_mapping:
													__lowercase   =							prepared_for_class[value]

										__lowercase   =							tuple(_lowerCamelCase       )

										# Send to model
										__lowercase   =							model(tuple_input[:-1]       )[0]

										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]       )


	@slow
	def   _UpperCAmelCase   (self       )							->							Any:







				'''simple docstring'''





				for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__lowercase   =							TFMobileViTModel.from_pretrained(_lowerCamelCase       )
							self.assertIsNotNone(_lowerCamelCase       )





def       _lowerCAmelCase  ( ):
			__lowercase   =							Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
			return image






@require_tf
class 							__lowercase				(					unittest.TestCase  ):







	'''simple docstring'''

	@slow
	def   _UpperCAmelCase   (self       )							->							Dict:







				'''simple docstring'''





				__lowercase   =							TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''       )

				__lowercase   =							MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''       )
				__lowercase   =							prepare_img()
				__lowercase   =							image_processor(images=_lowerCamelCase   ,return_tensors='''tf'''       )

				# forward pass
				__lowercase   =							model(**_lowerCamelCase   ,training=_lowerCamelCase       )

				# verify the logits
				__lowercase   =							tf.TensorShape((1, 1000)       )
				self.assertEqual(outputs.logits.shape   ,_lowerCamelCase       )

				__lowercase   =							tf.constant([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]       )

				tf.debugging.assert_near(outputs.logits[0, :3]   ,_lowerCamelCase   ,atol=1E-4   ,rtol=1E-0_4       )


	@slow
	def   _UpperCAmelCase   (self       )							->							Optional[int]:







				'''simple docstring'''





				__lowercase   =							TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''       )

				__lowercase   =							MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''       )

				__lowercase   =							prepare_img()
				__lowercase   =							image_processor(images=_lowerCamelCase   ,return_tensors='''tf'''       )

				# forward pass
				__lowercase   =							model(inputs.pixel_values   ,training=_lowerCamelCase       )
				__lowercase   =							outputs.logits

				# verify the logits
				__lowercase   =							tf.TensorShape((1, 21, 32, 32)       )
				self.assertEqual(logits.shape   ,_lowerCamelCase       )

				__lowercase   =							tf.constant(
				    [
				        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
				        [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
				        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
				    ]       )

				tf.debugging.assert_near(logits[0, :3, :3, :3]   ,_lowerCamelCase   ,rtol=1E-4   ,atol=1E-4       )












'''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


_SCREAMING_SNAKE_CASE    =			logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE    =			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'''),
    ]
)

_SCREAMING_SNAKE_CASE    =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)




def       _lowerCAmelCase  ( lowerCamelCase_	:     str ):
			for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
						if class_name in processors:
									__lowercase   =							model_type_to_module_name(lowerCamelCase_ )

									__lowercase   =							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.
			__lowercase   =							importlib.import_module('''transformers''' )
			if hasattr(lowerCamelCase_						,				lowerCamelCase_ ):
						return getattr(lowerCamelCase_						,				lowerCamelCase_ )

			return None






class 							__lowercase				:







	'''simple docstring'''

	def __init__(self       )							->							List[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(_lowerCamelCase       )
	def   _UpperCAmelCase   (cls   ,_lowerCamelCase   ,**_lowerCamelCase       )							->							Optional[Any]:







				'''simple docstring'''





				__lowercase   =							kwargs.pop('''config'''   ,_lowerCamelCase       )
				__lowercase   =							kwargs.pop('''trust_remote_code'''   ,_lowerCamelCase       )
				__lowercase   =							True

				__lowercase   =							None
				__lowercase   =							None

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

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

										__lowercase   =							config_dict.get('''processor_class'''   ,_lowerCamelCase       )
										if "AutoProcessor" in config_dict.get('''auto_map'''   ,{}       ):
													__lowercase   =							config_dict['''auto_map''']['''AutoProcessor''']

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

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

				if processor_class is not None:
							__lowercase   =							processor_class_from_name(_lowerCamelCase       )

				__lowercase   =							processor_auto_map is not None
				__lowercase   =							processor_class is not None or type(_lowerCamelCase       ) in PROCESSOR_MAPPING
				__lowercase   =							resolve_trust_remote_code(
				    _lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase   ,_lowerCamelCase       )

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

				# 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(
							    _lowerCamelCase   ,trust_remote_code=_lowerCamelCase   ,**_lowerCamelCase       )
				except Exception:
							try:
										return AutoImageProcessor.from_pretrained(
										    _lowerCamelCase   ,trust_remote_code=_lowerCamelCase   ,**_lowerCamelCase       )
							except Exception:
										pass

							try:
										return AutoFeatureExtractor.from_pretrained(
										    _lowerCamelCase   ,trust_remote_code=_lowerCamelCase   ,**_lowerCamelCase       )
							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   (_lowerCamelCase   ,_lowerCamelCase       )							->							int:







				'''simple docstring'''





				PROCESSOR_MAPPING.register(_lowerCamelCase   ,_lowerCamelCase       )





