
"""simple docstring"""


import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import (
						    MODEL_MAPPING,
						    BeitForImageClassification,
						    BeitForMaskedImageModeling,
						    BeitForSemanticSegmentation,
						    BeitModel,
						)
						from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						import PIL
						from PIL import Image

						from transformers import BeitImageProcessor




class  __lowerCamelCase  :




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase=100							,						UpperCAmelCase=13							,						UpperCAmelCase=30							,						UpperCAmelCase=2							,						UpperCAmelCase=3							,						UpperCAmelCase=True							,						UpperCAmelCase=True							,						UpperCAmelCase=32							,						UpperCAmelCase=4							,						UpperCAmelCase=4							,						UpperCAmelCase=37							,						UpperCAmelCase="gelu"							,						UpperCAmelCase=0.1							,						UpperCAmelCase=0.1							,						UpperCAmelCase=10							,						UpperCAmelCase=0.0_2							,						UpperCAmelCase=3							,						UpperCAmelCase=None							,						UpperCAmelCase=[0, 1, 2, 3]							,						):
							lowerCamelCase_					=  parent
							lowerCamelCase_					=  100
							lowerCamelCase_					=  batch_size
							lowerCamelCase_					=  image_size
							lowerCamelCase_					=  patch_size
							lowerCamelCase_					=  num_channels
							lowerCamelCase_					=  is_training
							lowerCamelCase_					=  use_labels
							lowerCamelCase_					=  hidden_size
							lowerCamelCase_					=  num_hidden_layers
							lowerCamelCase_					=  num_attention_heads
							lowerCamelCase_					=  intermediate_size
							lowerCamelCase_					=  hidden_act
							lowerCamelCase_					=  hidden_dropout_prob
							lowerCamelCase_					=  attention_probs_dropout_prob
							lowerCamelCase_					=  type_sequence_label_size
							lowerCamelCase_					=  initializer_range
							lowerCamelCase_					=  scope
							lowerCamelCase_					=  out_indices
							lowerCamelCase_					=  num_labels

							# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
							lowerCamelCase_					=  (image_size // patch_size) ** 2
							lowerCamelCase_					=  num_patches + 1




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

							lowerCamelCase_					=  self.get_config()

							return config, pixel_values, labels, pixel_labels




				def        UpperCAmelCase__						(				self   ):
							return BeitConfig(
							    vocab_size=self.vocab_size							,						image_size=self.image_size							,						patch_size=self.patch_size							,						num_channels=self.num_channels							,						hidden_size=self.hidden_size							,						num_hidden_layers=self.num_hidden_layers							,						num_attention_heads=self.num_attention_heads							,						intermediate_size=self.intermediate_size							,						hidden_act=self.hidden_act							,						hidden_dropout_prob=self.hidden_dropout_prob							,						attention_probs_dropout_prob=self.attention_probs_dropout_prob							,						is_decoder=UpperCAmelCase							,						initializer_range=self.initializer_range							,						out_indices=self.out_indices							,						)




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
							lowerCamelCase_					=  BeitModel(config=UpperCAmelCase   )
							model.to(UpperCAmelCase   )
							model.eval()
							lowerCamelCase_					=  model(UpperCAmelCase   )
							self.parent.assertEqual(result.last_hidden_state.shape							,						(self.batch_size, self.seq_length, self.hidden_size)   )




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
							lowerCamelCase_					=  BeitForMaskedImageModeling(config=UpperCAmelCase   )
							model.to(UpperCAmelCase   )
							model.eval()
							lowerCamelCase_					=  model(UpperCAmelCase   )
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.seq_length - 1, self.vocab_size)   )




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
							lowerCamelCase_					=  self.type_sequence_label_size
							lowerCamelCase_					=  BeitForImageClassification(UpperCAmelCase   )
							model.to(UpperCAmelCase   )
							model.eval()
							lowerCamelCase_					=  model(UpperCAmelCase							,						labels=UpperCAmelCase   )
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.type_sequence_label_size)   )

							# test greyscale images
							lowerCamelCase_					=  1
							lowerCamelCase_					=  BeitForImageClassification(UpperCAmelCase   )
							model.to(UpperCAmelCase   )
							model.eval()

							lowerCamelCase_					=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
							lowerCamelCase_					=  model(UpperCAmelCase							,						labels=UpperCAmelCase   )
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.type_sequence_label_size)   )




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
							lowerCamelCase_					=  self.num_labels
							lowerCamelCase_					=  BeitForSemanticSegmentation(UpperCAmelCase   )
							model.to(UpperCAmelCase   )
							model.eval()
							lowerCamelCase_					=  model(UpperCAmelCase   )
							self.parent.assertEqual(
							    result.logits.shape							,						(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )
							lowerCamelCase_					=  model(UpperCAmelCase							,						labels=UpperCAmelCase   )
							self.parent.assertEqual(
							    result.logits.shape							,						(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )





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




@require_torch
class  __lowerCamelCase  ( lowerCAmelCase						,	lowerCAmelCase						,	unittest.TestCase			):
				a__:      Tuple          =    (
				    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)
				a__:      Tuple          =    (
				    {
				        '''feature-extraction''': BeitModel,
				        '''image-classification''': BeitForImageClassification,
				        '''image-segmentation''': BeitForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				a__:      Optional[Any]          =    False
				a__:      Any          =    False
				a__:      List[str]          =    False




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  BeitModelTester(self   )
							lowerCamelCase_					=  ConfigTester(self							,						config_class=UpperCAmelCase							,						has_text_modality=UpperCAmelCase							,						hidden_size=37   )




				def        UpperCAmelCase__						(				self   ):
							self.config_tester.run_common_tests()




				@unittest.skip(reason='''BEiT does not use inputs_embeds'''   )
				def        UpperCAmelCase__						(				self   ):
							pass




				@require_torch_multi_gpu
				@unittest.skip(reason='''BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''   )
				def        UpperCAmelCase__						(				self   ):
							pass




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										lowerCamelCase_					=  model_class(UpperCAmelCase   )
										self.assertIsInstance(model.get_input_embeddings()							,						(nn.Module)   )
										lowerCamelCase_					=  model.get_output_embeddings()
										self.assertTrue(x is None or isinstance(UpperCAmelCase							,						nn.Linear   )   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()

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

										lowerCamelCase_					=  ['pixel_values']
										self.assertListEqual(arg_names[:1]							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):







							if not self.model_tester.is_training:
										return

							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()
							lowerCamelCase_					=  True

							for model_class in self.all_model_classes:
										# we don't test BeitForMaskedImageModeling
										if model_class in [*get_values(UpperCAmelCase   ), BeitForMaskedImageModeling]:
													continue

										lowerCamelCase_					=  model_class(UpperCAmelCase   )
										model.to(UpperCAmelCase   )
										model.train()
										lowerCamelCase_					=  self._prepare_for_class(UpperCAmelCase							,						UpperCAmelCase							,						return_labels=UpperCAmelCase   )
										lowerCamelCase_					=  model(**UpperCAmelCase   ).loss
										loss.backward()




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()
							if not self.model_tester.is_training:
										return

							lowerCamelCase_					=  False
							lowerCamelCase_					=  True

							for model_class in self.all_model_classes:
										# we don't test BeitForMaskedImageModeling
										if (
										    model_class in [*get_values(UpperCAmelCase   ), BeitForMaskedImageModeling]
										    or not model_class.supports_gradient_checkpointing
										):
													continue

										lowerCamelCase_					=  model_class(UpperCAmelCase   )
										model.gradient_checkpointing_enable()
										model.to(UpperCAmelCase   )
										model.train()
										lowerCamelCase_					=  self._prepare_for_class(UpperCAmelCase							,						UpperCAmelCase							,						return_labels=UpperCAmelCase   )
										lowerCamelCase_					=  model(**UpperCAmelCase   ).loss
										loss.backward()




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()

							lowerCamelCase_					=  _config_zero_init(UpperCAmelCase   )
							for model_class in self.all_model_classes:
										lowerCamelCase_					=  model_class(config=UpperCAmelCase   )
										for name, param in model.named_parameters():
													# we skip lambda parameters as these require special initial values
													# determined by config.layer_scale_init_value
													if "lambda" in name:
																continue
													if param.requires_grad:
																self.assertIn(
																    ((param.data.mean() * 1e9).round() / 1e9).item()							,						[0.0, 1.0]							,						msg=f"Parameter {name} of model {model_class} seems not properly initialized"							,						)





				@slow
				def        UpperCAmelCase__						(				self   ):







							for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowerCamelCase_					=  BeitModel.from_pretrained(UpperCAmelCase   )
										self.assertIsNotNone(UpperCAmelCase   )






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




@require_torch
@require_vision
class  __lowerCamelCase  ( unittest.TestCase			):




				@cached_property
				def        UpperCAmelCase__						(				self   ):
							return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224'''   ) if is_vision_available() else None




				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k'''   ).to(UpperCAmelCase   )

							lowerCamelCase_					=  self.default_image_processor
							lowerCamelCase_					=  prepare_img()
							lowerCamelCase_					=  image_processor(images=UpperCAmelCase							,						return_tensors='''pt'''   ).pixel_values.to(UpperCAmelCase   )

							# prepare bool_masked_pos
							lowerCamelCase_					=  torch.ones((1, 196)							,						dtype=torch.bool   ).to(UpperCAmelCase   )

							# forward pass
							with torch.no_grad():
										lowerCamelCase_					=  model(pixel_values=UpperCAmelCase							,						bool_masked_pos=UpperCAmelCase   )
							lowerCamelCase_					=  outputs.logits

							# verify the logits
							lowerCamelCase_					=  torch.Size((1, 196, 8192)   )
							self.assertEqual(logits.shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  torch.tensor(
							    [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]]   ).to(UpperCAmelCase   )

							self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]							,						UpperCAmelCase							,						atol=1e-2   )   )




				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224'''   ).to(UpperCAmelCase   )

							lowerCamelCase_					=  self.default_image_processor
							lowerCamelCase_					=  prepare_img()
							lowerCamelCase_					=  image_processor(images=UpperCAmelCase							,						return_tensors='''pt'''   ).to(UpperCAmelCase   )

							# forward pass
							with torch.no_grad():
										lowerCamelCase_					=  model(**UpperCAmelCase   )
							lowerCamelCase_					=  outputs.logits

							# verify the logits
							lowerCamelCase_					=  torch.Size((1, 1000)   )
							self.assertEqual(logits.shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]   ).to(UpperCAmelCase   )

							self.assertTrue(torch.allclose(logits[0, :3]							,						UpperCAmelCase							,						atol=1e-4   )   )

							lowerCamelCase_					=  281
							self.assertEqual(logits.argmax(-1   ).item()							,						UpperCAmelCase   )




				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k'''   ).to(
							    UpperCAmelCase   )

							lowerCamelCase_					=  self.default_image_processor
							lowerCamelCase_					=  prepare_img()
							lowerCamelCase_					=  image_processor(images=UpperCAmelCase							,						return_tensors='''pt'''   ).to(UpperCAmelCase   )

							# forward pass
							with torch.no_grad():
										lowerCamelCase_					=  model(**UpperCAmelCase   )
							lowerCamelCase_					=  outputs.logits

							# verify the logits
							lowerCamelCase_					=  torch.Size((1, 2_1841)   )
							self.assertEqual(logits.shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]   ).to(UpperCAmelCase   )

							self.assertTrue(torch.allclose(logits[0, :3]							,						UpperCAmelCase							,						atol=1e-4   )   )

							lowerCamelCase_					=  2396
							self.assertEqual(logits.argmax(-1   ).item()							,						UpperCAmelCase   )




				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''   )
							lowerCamelCase_					=  model.to(UpperCAmelCase   )

							lowerCamelCase_					=  BeitImageProcessor(do_resize=UpperCAmelCase							,						size=640							,						do_center_crop=UpperCAmelCase   )

							lowerCamelCase_					=  load_dataset('''hf-internal-testing/fixtures_ade20k'''							,						split='''test'''   )
							lowerCamelCase_					=  Image.open(ds[0]['''file''']   )
							lowerCamelCase_					=  image_processor(images=UpperCAmelCase							,						return_tensors='''pt'''   ).to(UpperCAmelCase   )

							# forward pass
							with torch.no_grad():
										lowerCamelCase_					=  model(**UpperCAmelCase   )
							lowerCamelCase_					=  outputs.logits

							# verify the logits
							lowerCamelCase_					=  torch.Size((1, 150, 160, 160)   )
							self.assertEqual(logits.shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  version.parse(PIL.__version__   ) < version.parse('''9.0.0'''   )

							if is_pillow_less_than_a:
										lowerCamelCase_					=  torch.tensor(
										    [
										        [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]],
										        [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]],
										        [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]],
										    ]							,						device=UpperCAmelCase							,						)
							else:
										lowerCamelCase_					=  torch.tensor(
										    [
										        [[-4.8_9_6_0, -2.3_6_8_8, -3.0_3_5_5], [-2.8_4_7_8, -0.9_8_3_6, -1.7_4_1_8], [-2.9_4_4_9, -1.3_3_3_2, -2.1_4_5_6]],
										        [[-5.8_0_8_1, -3.4_1_2_4, -4.1_0_0_6], [-3.8_5_6_1, -2.2_0_8_1, -3.0_3_2_3], [-3.8_3_6_5, -2.4_6_0_1, -3.3_6_6_9]],
										        [[-0.0_3_0_9, 3.9_8_6_8, 4.0_5_4_0], [2.9_6_4_0, 4.6_8_7_7, 4.9_9_7_6], [3.2_0_8_1, 4.7_6_9_0, 4.9_9_4_2]],
										    ]							,						device=UpperCAmelCase							,						)

							self.assertTrue(torch.allclose(logits[0, :3, :3, :3]							,						UpperCAmelCase							,						atol=1e-4   )   )





				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''   )
							lowerCamelCase_					=  model.to(UpperCAmelCase   )

							lowerCamelCase_					=  BeitImageProcessor(do_resize=UpperCAmelCase							,						size=640							,						do_center_crop=UpperCAmelCase   )

							lowerCamelCase_					=  load_dataset('''hf-internal-testing/fixtures_ade20k'''							,						split='''test'''   )
							lowerCamelCase_					=  Image.open(ds[0]['''file''']   )
							lowerCamelCase_					=  image_processor(images=UpperCAmelCase							,						return_tensors='''pt'''   ).to(UpperCAmelCase   )

							# forward pass
							with torch.no_grad():
										lowerCamelCase_					=  model(**UpperCAmelCase   )

							lowerCamelCase_					=  outputs.logits.detach().cpu()

							lowerCamelCase_					=  image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase							,						target_sizes=[(500, 300)]   )
							lowerCamelCase_					=  torch.Size((500, 300)   )
							self.assertEqual(segmentation[0].shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase   )
							lowerCamelCase_					=  torch.Size((160, 160)   )
							self.assertEqual(segmentation[0].shape							,						UpperCAmelCase   )









'''simple docstring'''



import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


UpperCamelCase_    	=				get_tests_dir("fixtures")






class 							_a				(			unittest.TestCase ):





       '''simple docstring'''






       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						mock.Mock()
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						500
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						{}
             SCREAMING_SNAKE_CASE   :      Any    					=						HTTPError
             SCREAMING_SNAKE_CASE   :      Any    					=						{}

             # Download this model to make sure it's in the cache.
             SCREAMING_SNAKE_CASE   :      str    					=						ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'  )
             # Under the mock environment we get a 500 error when trying to reach the model.
             with mock.patch('requests.Session.request',							return_value=A  ) as mock_head:
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'  )
                   # This check we did call the fake head request
                   mock_head.assert_called()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						ViTImageProcessor.from_pretrained(
                 'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             with self.assertRaises(A  ):
                   # config is in subfolder, the following should not work without specifying the subfolder
                   SCREAMING_SNAKE_CASE   :      str    					=						AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants'  )

             SCREAMING_SNAKE_CASE   :      Dict    					=						AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/stable-diffusion-all-variants',							subfolder='feature_extractor'  )

             self.assertIsNotNone(A  )






@is_staging_test
class 							_a				(			unittest.TestCase ):





       '''simple docstring'''






       @classmethod
       def        UpperCamelCase_							(      cls  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						TOKEN
             HfFolder.save_token(A  )







       @classmethod
       def        UpperCamelCase_							(      cls  ):







             '''simple docstring'''







             try:
                   delete_repo(token=cls._token,							repo_id='test-image-processor'  )
             except HTTPError:
                   pass

             try:
                   delete_repo(token=cls._token,							repo_id='valid_org/test-image-processor-org'  )
             except HTTPError:
                   pass

             try:
                   delete_repo(token=cls._token,							repo_id='test-dynamic-image-processor'  )
             except HTTPError:
                   pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						ViTImageProcessor.from_pretrained(A  )
             image_processor.push_to_hub('test-image-processor',							use_auth_token=self._token  )

             SCREAMING_SNAKE_CASE   :      int    					=						ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor"  )
             for k, v in image_processor.__dict__.items():
                   self.assertEqual(A,							getattr(A,							A  )  )

             # Reset repo
             delete_repo(token=self._token,							repo_id='test-image-processor'  )

             # Push to hub via save_pretrained
             with tempfile.TemporaryDirectory() as tmp_dir:
                   image_processor.save_pretrained(
                       A,							repo_id='test-image-processor',							push_to_hub=A,							use_auth_token=self._token  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor"  )
             for k, v in image_processor.__dict__.items():
                   self.assertEqual(A,							getattr(A,							A  )  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						ViTImageProcessor.from_pretrained(A  )
             image_processor.push_to_hub('valid_org/test-image-processor',							use_auth_token=self._token  )

             SCREAMING_SNAKE_CASE   :      str    					=						ViTImageProcessor.from_pretrained('valid_org/test-image-processor'  )
             for k, v in image_processor.__dict__.items():
                   self.assertEqual(A,							getattr(A,							A  )  )

             # Reset repo
             delete_repo(token=self._token,							repo_id='valid_org/test-image-processor'  )

             # Push to hub via save_pretrained
             with tempfile.TemporaryDirectory() as tmp_dir:
                   image_processor.save_pretrained(
                       A,							repo_id='valid_org/test-image-processor-org',							push_to_hub=A,							use_auth_token=self._token  )

             SCREAMING_SNAKE_CASE   :      Dict    					=						ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org'  )
             for k, v in image_processor.__dict__.items():
                   self.assertEqual(A,							getattr(A,							A  )  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             CustomImageProcessor.register_for_auto_class()
             SCREAMING_SNAKE_CASE   :      Tuple    					=						CustomImageProcessor.from_pretrained(A  )

             image_processor.push_to_hub('test-dynamic-image-processor',							use_auth_token=self._token  )

             # This has added the proper auto_map field to the config
             self.assertDictEqual(
                 image_processor.auto_map,							{'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'},							)

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						AutoImageProcessor.from_pretrained(
                 F"{USER}/test-dynamic-image-processor",							trust_remote_code=A  )
             # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
             self.assertEqual(new_image_processor.__class__.__name__,							'CustomImageProcessor'  )


