





import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
				from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import ViTImageProcessor



class    _a     :






							"""simple docstring"""

							def __init__(      self				:     int							,	a				:     str							,	a				:     str=13							,	a				:     str=30							,	a				:     Tuple=2							,	a				:     List[Any]=3							,	a				:     List[Any]=True							,	a				:     str=True							,	a				:     Optional[int]=32							,	a				:     Optional[int]=5							,	a				:     List[str]=4							,	a				:     Optional[int]=37							,	a				:     Tuple="gelu"							,	a				:     Optional[int]=0.1							,	a				:     str=0.1							,	a				:     Optional[int]=10							,	a				:     Any=0.02							,	a				:     Union[str, Any]=None							,	a				:     Any=2							,	)	->int:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					parent
													SCREAMING_SNAKE_CASE__     :				List[str]   =					batch_size
													SCREAMING_SNAKE_CASE__     :				int   =					image_size
													SCREAMING_SNAKE_CASE__     :				List[str]   =					patch_size
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					num_channels
													SCREAMING_SNAKE_CASE__     :				Dict   =					is_training
													SCREAMING_SNAKE_CASE__     :				Dict   =					use_labels
													SCREAMING_SNAKE_CASE__     :				Any   =					hidden_size
													SCREAMING_SNAKE_CASE__     :				Any   =					num_hidden_layers
													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					num_attention_heads
													SCREAMING_SNAKE_CASE__     :				int   =					intermediate_size
													SCREAMING_SNAKE_CASE__     :				Dict   =					hidden_act
													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					hidden_dropout_prob
													SCREAMING_SNAKE_CASE__     :				int   =					attention_probs_dropout_prob
													SCREAMING_SNAKE_CASE__     :				Tuple   =					type_sequence_label_size
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					initializer_range
													SCREAMING_SNAKE_CASE__     :				Tuple   =					scope
													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					encoder_stride

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

							def      A_  (      self				:     Dict    )	->List[str]:
													SCREAMING_SNAKE_CASE__     :				Any   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

													SCREAMING_SNAKE_CASE__     :				str   =					None
													if self.use_labels:
																			SCREAMING_SNAKE_CASE__     :				Any   =					ids_tensor([self.batch_size]							,	self.type_sequence_label_size    )

													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					self.get_config()

													return config, pixel_values, labels

							def      A_  (      self				:     List[Any]    )	->Tuple:
													return ViTConfig(
													    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=a							,	initializer_range=self.initializer_range							,	encoder_stride=self.encoder_stride							,	)

							def      A_  (      self				:     Tuple							,	a				:     Dict							,	a				:     Optional[int]							,	a				:     str    )	->Optional[Any]:
													SCREAMING_SNAKE_CASE__     :				Any   =					ViTModel(config=a    )
													model.to(a    )
													model.eval()
													SCREAMING_SNAKE_CASE__     :				int   =					model(a    )
													self.parent.assertEqual(result.last_hidden_state.shape							,	(self.batch_size, self.seq_length, self.hidden_size)    )

							def      A_  (      self				:     Optional[int]							,	a				:     Optional[Any]							,	a				:     Optional[int]							,	a				:     Optional[Any]    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				List[str]   =					ViTForMaskedImageModeling(config=a    )
													model.to(a    )
													model.eval()
													SCREAMING_SNAKE_CASE__     :				Any   =					model(a    )
													self.parent.assertEqual(
													    result.reconstruction.shape							,	(self.batch_size, self.num_channels, self.image_size, self.image_size)    )

													# test greyscale images
													SCREAMING_SNAKE_CASE__     :				int   =					1
													SCREAMING_SNAKE_CASE__     :				str   =					ViTForMaskedImageModeling(a    )
													model.to(a    )
													model.eval()

													SCREAMING_SNAKE_CASE__     :				int   =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					model(a    )
													self.parent.assertEqual(result.reconstruction.shape							,	(self.batch_size, 1, self.image_size, self.image_size)    )

							def      A_  (      self				:     Optional[int]							,	a				:     Optional[int]							,	a				:     Optional[int]							,	a				:     Any    )	->Any:
													SCREAMING_SNAKE_CASE__     :				List[str]   =					self.type_sequence_label_size
													SCREAMING_SNAKE_CASE__     :				Any   =					ViTForImageClassification(a    )
													model.to(a    )
													model.eval()
													SCREAMING_SNAKE_CASE__     :				Dict   =					model(a							,	labels=a    )
													self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.type_sequence_label_size)    )

													# test greyscale images
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					1
													SCREAMING_SNAKE_CASE__     :				int   =					ViTForImageClassification(a    )
													model.to(a    )
													model.eval()

													SCREAMING_SNAKE_CASE__     :				List[str]   =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					model(a    )
													self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.type_sequence_label_size)    )






							def      A_  (      self				:     Any    )	->List[str]:
													SCREAMING_SNAKE_CASE__     :				Any   =					self.prepare_config_and_inputs()
													(
													    SCREAMING_SNAKE_CASE__							
													)     :				Any   =					config_and_inputs
													SCREAMING_SNAKE_CASE__     :				Any   =					{"pixel_values": pixel_values}
													return config, inputs_dict







@require_torch
class    _a     (				lowercase__					,							lowercase__					,							unittest.TestCase							):






							"""simple docstring"""

							snake_case_							 =						(
							    (
							        ViTModel,
							        ViTForImageClassification,
							        ViTForMaskedImageModeling,
							    )
							    if is_torch_available()
							    else ()
							)
							snake_case_							 =						(
							    {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification}
							    if is_torch_available()
							    else {}
							)
							snake_case_							 =						True

							snake_case_							 =						False
							snake_case_							 =						False
							snake_case_							 =						False

							def      A_  (      self				:     Tuple    )	->List[Any]:
													SCREAMING_SNAKE_CASE__     :				str   =					ViTModelTester(self    )
													SCREAMING_SNAKE_CASE__     :				List[str]   =					ConfigTester(self							,	config_class=a							,	has_text_modality=a							,	hidden_size=37    )

							def      A_  (      self				:     Tuple    )	->List[str]:
													self.config_tester.run_common_tests()

							@unittest.skip(reason="ViT does not use inputs_embeds"    )
							def      A_  (      self				:     Union[str, Any]    )	->List[Any]:
													pass

							def      A_  (      self				:     List[str]    )	->Optional[Any]:
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			SCREAMING_SNAKE_CASE__     :				List[str]   =					model_class(a    )
																			self.assertIsInstance(model.get_input_embeddings()							,	(nn.Module)    )
																			SCREAMING_SNAKE_CASE__     :				Any   =					model.get_output_embeddings()
																			self.assertTrue(x is None or isinstance(a							,	nn.Linear    )    )

							def      A_  (      self				:     Dict    )	->Optional[Any]:
													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					self.model_tester.prepare_config_and_inputs_for_common()

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

																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					["pixel_values"]
																			self.assertListEqual(arg_names[:1]							,	a    )

							def      A_  (      self				:     Union[str, Any]    )	->Optional[int]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*a    )

							def      A_  (      self				:     Tuple    )	->Any:
													SCREAMING_SNAKE_CASE__     :				Dict   =					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_masked_image_modeling(*a    )

							def      A_  (      self				:     int    )	->str:
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*a    )






							@slow
							def      A_  (      self				:     Tuple    )	->List[Any]:
													for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			SCREAMING_SNAKE_CASE__     :				int   =					ViTModel.from_pretrained(a    )
																			self.assertIsNotNone(a    )







def       UpperCAmelCase							(     ):





						'''simple docstring'''


						SCREAMING_SNAKE_CASE__     :				Optional[int]   =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
						return image



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






							"""simple docstring"""

							@cached_property
							def      A_  (      self				:     Optional[Any]    )	->Tuple:
													return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"    ) if is_vision_available() else None

							@slow
							def      A_  (      self				:     str    )	->List[Any]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					ViTForImageClassification.from_pretrained("google/vit-base-patch16-224"    ).to(a    )

													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					self.default_image_processor
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					prepare_img()
													SCREAMING_SNAKE_CASE__     :				int   =					image_processor(images=a							,	return_tensors="pt"    ).to(a    )

													# forward pass
													with torch.no_grad():
																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					model(**a    )

													# verify the logits
													SCREAMING_SNAKE_CASE__     :				Any   =					torch.Size((1, 10_00)    )
													self.assertEqual(outputs.logits.shape							,	a    )

													SCREAMING_SNAKE_CASE__     :				str   =					torch.tensor([-0.2744, 0.8215, -0.0836]    ).to(a    )

													self.assertTrue(torch.allclose(outputs.logits[0, :3]							,	a							,	atol=1E-4    )    )

							@slow
							def      A_  (      self				:     Tuple    )	->int:
													# ViT models have an `interpolate_pos_encoding` argument in their forward method,
													# allowing to interpolate the pre-trained position embeddings in order to use
													# the model on higher resolutions. The DINO model by Facebook AI leverages this
													# to visualize self-attention on higher resolution images.
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					ViTModel.from_pretrained("facebook/dino-vits8"    ).to(a    )

													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					ViTImageProcessor.from_pretrained("facebook/dino-vits8"							,	size=4_80    )
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					prepare_img()
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					image_processor(images=a							,	return_tensors="pt"    )
													SCREAMING_SNAKE_CASE__     :				List[str]   =					inputs.pixel_values.to(a    )

													# forward pass
													with torch.no_grad():
																			SCREAMING_SNAKE_CASE__     :				List[str]   =					model(a							,	interpolate_pos_encoding=a    )

													# verify the logits
													SCREAMING_SNAKE_CASE__     :				List[str]   =					torch.Size((1, 36_01, 3_84)    )
													self.assertEqual(outputs.last_hidden_state.shape							,	a    )

													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					torch.tensor(
													    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]    ).to(a    )

													self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]							,	a							,	atol=1E-4    )    )






							@slow
							@require_accelerate
							@require_torch_gpu
							def      A_  (      self				:     int    )	->Any:
													SCREAMING_SNAKE_CASE__     :				Tuple   =					ViTModel.from_pretrained("facebook/dino-vits8"							,	torch_dtype=torch.floataa							,	device_map="auto"    )
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					self.default_image_processor

													SCREAMING_SNAKE_CASE__     :				str   =					prepare_img()
													SCREAMING_SNAKE_CASE__     :				str   =					image_processor(images=a							,	return_tensors="pt"    )
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					inputs.pixel_values.to(a    )

													# forward pass to make sure inference works in fp16
													with torch.no_grad():
																			SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					model(a    )






import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

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

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


__lowercase       :List[str]       =  get_tests_dir("fixtures/dummy_feature_extractor_config.json")
__lowercase       :str       =  get_tests_dir("fixtures/vocab.json")
__lowercase       :Optional[int]       =  get_tests_dir("fixtures")



class    _a     (				unittest.TestCase							):






							"""simple docstring"""

							snake_case_							 =						["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]

							def      A_  (      self				:     Optional[Any]    )	->int:
													SCREAMING_SNAKE_CASE__     :				Dict   =					0

							def      A_  (      self				:     Any    )	->Optional[int]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h"    )
													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     Union[str, Any]    )	->List[str]:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				Dict   =					WavaVecaConfig()
																			SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h"    )

																			# save in new folder
																			model_config.save_pretrained(a    )
																			processor.save_pretrained(a    )

																			SCREAMING_SNAKE_CASE__     :				str   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     int    )	->List[str]:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			# copy relevant files
																			copyfile(a							,	os.path.join(a							,	a    )    )
																			copyfile(a							,	os.path.join(a							,	"vocab.json"    )    )

																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     List[Any]    )	->Tuple:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					WavaVecaFeatureExtractor()
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h"    )

																			SCREAMING_SNAKE_CASE__     :				Any   =					WavaVecaProcessor(a							,	a    )

																			# save in new folder
																			processor.save_pretrained(a    )

																			# drop `processor_class` in tokenizer
																			with open(os.path.join(a							,	a    )							,	"r"    ) as f:
																									SCREAMING_SNAKE_CASE__     :				Optional[int]   =					json.load(a    )
																									config_dict.pop("processor_class"    )

																			with open(os.path.join(a							,	a    )							,	"w"    ) as f:
																									f.write(json.dumps(a    )    )

																			SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     List[str]    )	->Optional[Any]:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					WavaVecaFeatureExtractor()
																			SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h"    )

																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					WavaVecaProcessor(a							,	a    )

																			# save in new folder
																			processor.save_pretrained(a    )

																			# drop `processor_class` in feature extractor
																			with open(os.path.join(a							,	a    )							,	"r"    ) as f:
																									SCREAMING_SNAKE_CASE__     :				List[Any]   =					json.load(a    )
																									config_dict.pop("processor_class"    )

																			with open(os.path.join(a							,	a    )							,	"w"    ) as f:
																									f.write(json.dumps(a    )    )

																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     Union[str, Any]    )	->str:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					WavaVecaConfig(processor_class="Wav2Vec2Processor"    )
																			model_config.save_pretrained(a    )
																			# copy relevant files
																			copyfile(a							,	os.path.join(a							,	"vocab.json"    )    )
																			# create emtpy sample processor
																			with open(os.path.join(a							,	a    )							,	"w"    ) as f:
																									f.write("{}"    )

																			SCREAMING_SNAKE_CASE__     :				Tuple   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     Optional[Any]    )	->Optional[int]:
													# If remote code is not set, we will time out when asking whether to load the model.
													with self.assertRaises(a    ):
																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor"    )
													# If remote code is disabled, we can't load this config.
													with self.assertRaises(a    ):
																			SCREAMING_SNAKE_CASE__     :				Any   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )

													SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )
													self.assertTrue(processor.special_attribute_present    )
													self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )

													SCREAMING_SNAKE_CASE__     :				Dict   =					processor.feature_extractor
													self.assertTrue(feature_extractor.special_attribute_present    )
													self.assertEqual(feature_extractor.__class__.__name__							,	"NewFeatureExtractor"    )

													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					processor.tokenizer
													self.assertTrue(tokenizer.special_attribute_present    )
													if is_tokenizers_available():
																			self.assertEqual(tokenizer.__class__.__name__							,	"NewTokenizerFast"    )

																			# Test we can also load the slow version
																			SCREAMING_SNAKE_CASE__     :				int   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a							,	use_fast=a    )
																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					new_processor.tokenizer
																			self.assertTrue(new_tokenizer.special_attribute_present    )
																			self.assertEqual(new_tokenizer.__class__.__name__							,	"NewTokenizer"    )
													else:
																			self.assertEqual(tokenizer.__class__.__name__							,	"NewTokenizer"    )

							def      A_  (      self				:     Tuple    )	->List[Any]:
													try:
																			AutoConfig.register("custom"							,	a    )
																			AutoFeatureExtractor.register(a							,	a    )
																			AutoTokenizer.register(a							,	slow_tokenizer_class=a    )
																			AutoProcessor.register(a							,	a    )
																			# Trying to register something existing in the Transformers library will raise an error
																			with self.assertRaises(a    ):
																									AutoProcessor.register(a							,	a    )

																			# Now that the config is registered, it can be used as any other config with the auto-API
																			SCREAMING_SNAKE_CASE__     :				List[str]   =					CustomFeatureExtractor.from_pretrained(a    )

																			with tempfile.TemporaryDirectory() as tmp_dir:
																									SCREAMING_SNAKE_CASE__     :				int   =					os.path.join(a							,	"vocab.txt"    )
																									with open(a							,	"w"							,	encoding="utf-8"    ) as vocab_writer:
																															vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]    )    )
																									SCREAMING_SNAKE_CASE__     :				Optional[int]   =					CustomTokenizer(a    )

																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					CustomProcessor(a							,	a    )

																			with tempfile.TemporaryDirectory() as tmp_dir:
																									processor.save_pretrained(a    )
																									SCREAMING_SNAKE_CASE__     :				Any   =					AutoProcessor.from_pretrained(a    )
																									self.assertIsInstance(a							,	a    )

													finally:
																			if "custom" in CONFIG_MAPPING._extra_content:
																									del CONFIG_MAPPING._extra_content["custom"]
																			if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																									del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in TOKENIZER_MAPPING._extra_content:
																									del TOKENIZER_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in PROCESSOR_MAPPING._extra_content:
																									del PROCESSOR_MAPPING._extra_content[CustomConfig]

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



													class    _a     (				lowercase__							):






																				"""simple docstring"""

																				snake_case_							 =						False







													class    _a     (				lowercase__							):






																				"""simple docstring"""

																				snake_case_							 =						False







													class    _a     (				lowercase__							):






																				"""simple docstring"""

																				snake_case_							 =						"AutoFeatureExtractor"
																				snake_case_							 =						"AutoTokenizer"
																				snake_case_							 =						False

													try:
																			AutoConfig.register("custom"							,	a    )
																			AutoFeatureExtractor.register(a							,	a    )
																			AutoTokenizer.register(a							,	slow_tokenizer_class=a    )
																			AutoProcessor.register(a							,	a    )
																			# If remote code is not set, the default is to use local classes.
																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor"    )
																			self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )
																			self.assertFalse(processor.special_attribute_present    )
																			self.assertFalse(processor.feature_extractor.special_attribute_present    )
																			self.assertFalse(processor.tokenizer.special_attribute_present    )

																			# If remote code is disabled, we load the local ones.
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )
																			self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )
																			self.assertFalse(processor.special_attribute_present    )
																			self.assertFalse(processor.feature_extractor.special_attribute_present    )
																			self.assertFalse(processor.tokenizer.special_attribute_present    )

																			# If remote is enabled, we load from the Hub.
																			SCREAMING_SNAKE_CASE__     :				Any   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )
																			self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )
																			self.assertTrue(processor.special_attribute_present    )
																			self.assertTrue(processor.feature_extractor.special_attribute_present    )
																			self.assertTrue(processor.tokenizer.special_attribute_present    )

													finally:
																			if "custom" in CONFIG_MAPPING._extra_content:
																									del CONFIG_MAPPING._extra_content["custom"]
																			if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																									del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in TOKENIZER_MAPPING._extra_content:
																									del TOKENIZER_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in PROCESSOR_MAPPING._extra_content:
																									del PROCESSOR_MAPPING._extra_content[CustomConfig]

							def      A_  (      self				:     Optional[Any]    )	->Dict:
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert"    )
													self.assertEqual(processor.__class__.__name__							,	"BertTokenizerFast"    )






							def      A_  (      self				:     Dict    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				Dict   =					AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext"    )
													self.assertEqual(processor.__class__.__name__							,	"ConvNextImageProcessor"    )







@is_staging_test
class    _a     (				unittest.TestCase							):






							"""simple docstring"""

							snake_case_							 =						["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]

							@classmethod
							def      A_  (      cls				:     List[str]    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				int   =					TOKEN
													HfFolder.save_token(a    )

							@classmethod
							def      A_  (      cls				:     List[str]    )	->Optional[int]:
													try:
																			delete_repo(token=cls._token							,	repo_id="test-processor"    )
													except HTTPError:
																			pass

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

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

							def      A_  (      self				:     Dict    )	->Dict:
													SCREAMING_SNAKE_CASE__     :				Tuple   =					WavaVecaProcessor.from_pretrained(a    )
													with tempfile.TemporaryDirectory() as tmp_dir:
																			processor.save_pretrained(
																			    os.path.join(a							,	"test-processor"    )							,	push_to_hub=a							,	use_auth_token=self._token    )

																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					WavaVecaProcessor.from_pretrained(f"""{USER}/test-processor"""    )
																			for k, v in processor.feature_extractor.__dict__.items():
																									self.assertEqual(a							,	getattr(new_processor.feature_extractor							,	a    )    )
																			self.assertDictEqual(new_processor.tokenizer.get_vocab()							,	processor.tokenizer.get_vocab()    )

							def      A_  (      self				:     List[str]    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					WavaVecaProcessor.from_pretrained(a    )

													with tempfile.TemporaryDirectory() as tmp_dir:
																			processor.save_pretrained(
																			    os.path.join(a							,	"test-processor-org"    )							,	push_to_hub=a							,	use_auth_token=self._token							,	organization="valid_org"							,	)

																			SCREAMING_SNAKE_CASE__     :				Dict   =					WavaVecaProcessor.from_pretrained("valid_org/test-processor-org"    )
																			for k, v in processor.feature_extractor.__dict__.items():
																									self.assertEqual(a							,	getattr(new_processor.feature_extractor							,	a    )    )
																			self.assertDictEqual(new_processor.tokenizer.get_vocab()							,	processor.tokenizer.get_vocab()    )






							def      A_  (      self				:     Any    )	->int:
													CustomFeatureExtractor.register_for_auto_class()
													CustomTokenizer.register_for_auto_class()
													CustomProcessor.register_for_auto_class()

													SCREAMING_SNAKE_CASE__     :				Any   =					CustomFeatureExtractor.from_pretrained(a    )

													with tempfile.TemporaryDirectory() as tmp_dir:
																			SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					os.path.join(a							,	"vocab.txt"    )
																			with open(a							,	"w"							,	encoding="utf-8"    ) as vocab_writer:
																									vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]    )    )
																			SCREAMING_SNAKE_CASE__     :				str   =					CustomTokenizer(a    )

													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					CustomProcessor(a							,	a    )

													with tempfile.TemporaryDirectory() as tmp_dir:
																			create_repo(f"""{USER}/test-dynamic-processor"""							,	token=self._token    )
																			SCREAMING_SNAKE_CASE__     :				str   =					Repository(a							,	clone_from=f"""{USER}/test-dynamic-processor"""							,	token=self._token    )
																			processor.save_pretrained(a    )

																			# This has added the proper auto_map field to the feature extractor config
																			self.assertDictEqual(
																			    processor.feature_extractor.auto_map							,	{
																			        "AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor",
																			        "AutoProcessor": "custom_processing.CustomProcessor",
																			    }							,	)

																			# This has added the proper auto_map field to the tokenizer config
																			with open(os.path.join(a							,	"tokenizer_config.json"    )    ) as f:
																									SCREAMING_SNAKE_CASE__     :				str   =					json.load(a    )
																			self.assertDictEqual(
																			    tokenizer_config["auto_map"]							,	{
																			        "AutoTokenizer": ["custom_tokenization.CustomTokenizer", None],
																			        "AutoProcessor": "custom_processing.CustomProcessor",
																			    }							,	)

																			# The code has been copied from fixtures
																			self.assertTrue(os.path.isfile(os.path.join(a							,	"custom_feature_extraction.py"    )    )    )
																			self.assertTrue(os.path.isfile(os.path.join(a							,	"custom_tokenization.py"    )    )    )
																			self.assertTrue(os.path.isfile(os.path.join(a							,	"custom_processing.py"    )    )    )

																			repo.push_to_hub()

													SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained(f"""{USER}/test-dynamic-processor"""							,	trust_remote_code=a    )
													# Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
													self.assertEqual(new_processor.__class__.__name__							,	"CustomProcessor"    )