



'''simple docstring'''

import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 (
			    FocalNetBackbone,
			    FocalNetForImageClassification,
			    FocalNetForMaskedImageModeling,
			    FocalNetModel,
			)
			from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor

class 							a__:






			def __init__(     self					,   _UpperCAmelCase					,   _UpperCAmelCase=13					,   _UpperCAmelCase=32					,   _UpperCAmelCase=2					,   _UpperCAmelCase=3					,   _UpperCAmelCase=16					,   _UpperCAmelCase=[32, 64, 128]					,   _UpperCAmelCase=[1, 2, 1]					,   _UpperCAmelCase=[2, 2, 4]					,   _UpperCAmelCase=2					,   _UpperCAmelCase=2.0					,   _UpperCAmelCase=True					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.1					,   _UpperCAmelCase="gelu"					,   _UpperCAmelCase=False					,   _UpperCAmelCase=True					,   _UpperCAmelCase=0.02					,   _UpperCAmelCase=1E-5					,   _UpperCAmelCase=True					,   _UpperCAmelCase=None					,   _UpperCAmelCase=True					,   _UpperCAmelCase=10					,   _UpperCAmelCase=8					,   _UpperCAmelCase=["stage1", "stage2"]					,   _UpperCAmelCase=[1, 2]					,   )							->							int:
					snake_case__	     =parent
					snake_case__	     =batch_size
					snake_case__	     =image_size
					snake_case__	     =patch_size
					snake_case__	     =num_channels
					snake_case__	     =embed_dim
					snake_case__	     =hidden_sizes
					snake_case__	     =depths
					snake_case__	     =num_heads
					snake_case__	     =window_size
					snake_case__	     =mlp_ratio
					snake_case__	     =qkv_bias
					snake_case__	     =hidden_dropout_prob
					snake_case__	     =attention_probs_dropout_prob
					snake_case__	     =drop_path_rate
					snake_case__	     =hidden_act
					snake_case__	     =use_absolute_embeddings
					snake_case__	     =patch_norm
					snake_case__	     =layer_norm_eps
					snake_case__	     =initializer_range
					snake_case__	     =is_training
					snake_case__	     =scope
					snake_case__	     =use_labels
					snake_case__	     =type_sequence_label_size
					snake_case__	     =encoder_stride
					snake_case__	     =out_features
					snake_case__	     =out_indices






			def 						_lowercase  (     self						)							->							Dict:
					snake_case__	     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

					snake_case__	     =None
					if self.use_labels:
							snake_case__	     =ids_tensor([self.batch_size]					,   self.type_sequence_label_size						)

					snake_case__	     =self.get_config()

					return config, pixel_values, labels






			def 						_lowercase  (     self						)							->							Any:
					return FocalNetConfig(
					    image_size=self.image_size					,   patch_size=self.patch_size					,   num_channels=self.num_channels					,   embed_dim=self.embed_dim					,   hidden_sizes=self.hidden_sizes					,   depths=self.depths					,   num_heads=self.num_heads					,   window_size=self.window_size					,   mlp_ratio=self.mlp_ratio					,   qkv_bias=self.qkv_bias					,   hidden_dropout_prob=self.hidden_dropout_prob					,   attention_probs_dropout_prob=self.attention_probs_dropout_prob					,   drop_path_rate=self.drop_path_rate					,   hidden_act=self.hidden_act					,   use_absolute_embeddings=self.use_absolute_embeddings					,   path_norm=self.patch_norm					,   layer_norm_eps=self.layer_norm_eps					,   initializer_range=self.initializer_range					,   encoder_stride=self.encoder_stride					,   out_features=self.out_features					,   out_indices=self.out_indices					,   )






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =FocalNetModel(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					snake_case__	     =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
					snake_case__	     =int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

					self.parent.assertEqual(result.last_hidden_state.shape					,   (self.batch_size, expected_seq_len, expected_dim)						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Optional[int]:
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					# verify feature maps
					self.parent.assertEqual(len(result.feature_maps						)					,   len(config.out_features						)						)
					self.parent.assertListEqual(list(result.feature_maps[0].shape						)					,   [self.batch_size, self.image_size, 8, 8]						)

					# verify channels
					self.parent.assertEqual(len(model.channels						)					,   len(config.out_features						)						)
					self.parent.assertListEqual(model.channels					,   config.hidden_sizes[:-1]						)

					# verify backbone works with out_features=None
					snake_case__	     =None
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					# verify feature maps
					self.parent.assertEqual(len(result.feature_maps						)					,   1						)
					self.parent.assertListEqual(list(result.feature_maps[0].shape						)					,   [self.batch_size, self.image_size * 2, 4, 4]						)

					# verify channels
					self.parent.assertEqual(len(model.channels						)					,   1						)
					self.parent.assertListEqual(model.channels					,   [config.hidden_sizes[-1]]						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Any:
					snake_case__	     =FocalNetForMaskedImageModeling(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(
					    result.reconstruction.shape					,   (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForMaskedImageModeling(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					snake_case__	     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(result.reconstruction.shape					,   (self.batch_size, 1, self.image_size, self.image_size)						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Tuple:
					snake_case__	     =self.type_sequence_label_size
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase					,   labels=_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					snake_case__	     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__	     =self.prepare_config_and_inputs()

					snake_case__     ,	snake_case__     ,	snake_case__	     =config_and_inputs
					snake_case__	     ={'pixel_values': pixel_values}
					return config, inputs_dict





@require_torch
class 							a__( snake_case__   ,      snake_case__   ,      unittest.TestCase     ):
			a_	: str									=      (
			    (
			        FocalNetModel,
			        FocalNetForImageClassification,
			        FocalNetForMaskedImageModeling,
			        FocalNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			a_	: Union[str, Any]									=      (
			    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
			    if is_torch_available()
			    else {}
			)
			a_	: Dict									=      False

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






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)
					snake_case__	     =ConfigTester(self					,   config_class=_UpperCAmelCase					,   embed_dim=37					,   has_text_modality=_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					self.create_and_test_config_common_properties()
					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()






			def 						_lowercase  (     self						)							->							str:
					return






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Union[str, Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase						)






			@unittest.skip(reason='FocalNet does not use inputs_embeds'						)
			def 						_lowercase  (     self						)							->							str:
					pass






			@unittest.skip(reason='FocalNet does not use feedforward chunking'						)
			def 						_lowercase  (     self						)							->							int:
					pass






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes[:-1]:
							snake_case__	     =model_class(_UpperCAmelCase						)
							self.assertIsInstance(model.get_input_embeddings()					,   (nn.Module)						)
							snake_case__	     =model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(_UpperCAmelCase					,   nn.Linear						)						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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

							snake_case__	     =['pixel_values']
							self.assertListEqual(arg_names[:1]					,   _UpperCAmelCase						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =model_class(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					with torch.no_grad():
							snake_case__	     =model(**self._prepare_for_class(_UpperCAmelCase					,   _UpperCAmelCase						)						)

					snake_case__	     =outputs.hidden_states

					snake_case__	     =getattr(
					    self.model_tester					,   'expected_num_hidden_layers'					,   len(self.model_tester.depths						) + 1						)
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

					# FocalNet has a different seq_length
					snake_case__	     =(
					    config.patch_size
					    if isinstance(config.patch_size					,   collections.abc.Iterable						)
					    else (config.patch_size, config.patch_size)
					)

					snake_case__	     =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

					self.assertListEqual(
					    list(hidden_states[0].shape[-2:]						)					,   [num_patches, self.model_tester.embed_dim]					,   )

					snake_case__	     =outputs.reshaped_hidden_states
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

					snake_case__     ,	snake_case__     ,	snake_case__     ,	snake_case__	     =reshaped_hidden_states[0].shape
					snake_case__	     =(
					    reshaped_hidden_states[0].view(_UpperCAmelCase					,   _UpperCAmelCase					,   height * width						).permute(0					,   2					,   1						)
					)
					self.assertListEqual(
					    list(reshaped_hidden_states.shape[-2:]						)					,   [num_patches, self.model_tester.embed_dim]					,   )






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =(
					    self.model_tester.image_size
					    if isinstance(self.model_tester.image_size					,   collections.abc.Iterable						)
					    else (self.model_tester.image_size, self.model_tester.image_size)
					)

					for model_class in self.all_model_classes[:-1]:
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)

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

							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()
					snake_case__	     =3

					snake_case__	     =(
					    self.model_tester.image_size
					    if isinstance(self.model_tester.image_size					,   collections.abc.Iterable						)
					    else (self.model_tester.image_size, self.model_tester.image_size)
					)
					snake_case__	     =(
					    config.patch_size
					    if isinstance(config.patch_size					,   collections.abc.Iterable						)
					    else (config.patch_size, config.patch_size)
					)

					snake_case__	     =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
					snake_case__	     =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

					for model_class in self.all_model_classes[:-1]:
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   (padded_height, padded_width)						)

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   (padded_height, padded_width)						)






			@slow
			def 						_lowercase  (     self						)							->							Optional[Any]:
					for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__	     =FocalNetModel.from_pretrained(_UpperCAmelCase						)
							self.assertIsNotNone(_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							int:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =_config_zero_init(_UpperCAmelCase						)
					for model_class in self.all_model_classes:
							snake_case__	     =model_class(config=_UpperCAmelCase						)
							for name, param in model.named_parameters():
									if "embeddings" not in name and 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"""					,   )





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






			@cached_property
			def 						_lowercase  (     self						)							->							Any:
					# TODO update organization
					return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'						) if is_vision_available() else None






			@slow
			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'						).to(_UpperCAmelCase						)
					snake_case__	     =self.default_image_processor

					snake_case__	     =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
					snake_case__	     =image_processor(images=_UpperCAmelCase					,   return_tensors='pt'						).to(_UpperCAmelCase						)

					# forward pass
					with torch.no_grad():
							snake_case__	     =model(**_UpperCAmelCase						)

					# verify the logits
					snake_case__	     =torch.Size((1, 1000)						)
					self.assertEqual(outputs.logits.shape					,   _UpperCAmelCase						)
					snake_case__	     =torch.tensor([0.2_166, -0.4_368, 0.2_191]						).to(_UpperCAmelCase						)
					self.assertTrue(torch.allclose(outputs.logits[0, :3]					,   _UpperCAmelCase					,   atol=1E-4						)						)
					self.assertTrue(outputs.logits.argmax(dim=-1						).item()					,   281						)





@require_torch
class 							a__( snake_case__   ,      unittest.TestCase     ):
			a_	: int									=      (FocalNetBackbone,) if is_torch_available() else ()
			a_	: Any									=      FocalNetConfig

			a_	: int									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)









'''simple docstring'''

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


SCREAMING_SNAKE_CASE__     :						Optional[int]	=  get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
SCREAMING_SNAKE_CASE__     :						Any	=  get_tests_dir('''fixtures/vocab.json''')
SCREAMING_SNAKE_CASE__     :						Optional[Any]	=  get_tests_dir('''fixtures''')

class 							a__( unittest.TestCase     ):
			a_	: Union[str, Any]									=      ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']






			def 						_lowercase  (     self						)							->							Dict:
					snake_case__	     =0






			def 						_lowercase  (     self						)							->							List[Any]:
					snake_case__	     =AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h'						)
					self.assertIsInstance(_UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Dict:
					with tempfile.TemporaryDirectory() as tmpdirname:
							snake_case__	     =WavaVecaConfig()
							snake_case__	     =AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h'						)

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

							snake_case__	     =AutoProcessor.from_pretrained(_UpperCAmelCase						)

					self.assertIsInstance(_UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Tuple:
					with tempfile.TemporaryDirectory() as tmpdirname:
							# copy relevant files
							copyfile(_UpperCAmelCase					,   os.path.join(_UpperCAmelCase					,   _UpperCAmelCase						)						)
							copyfile(_UpperCAmelCase					,   os.path.join(_UpperCAmelCase					,   'vocab.json'						)						)

							snake_case__	     =AutoProcessor.from_pretrained(_UpperCAmelCase						)

					self.assertIsInstance(_UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Dict:
					with tempfile.TemporaryDirectory() as tmpdirname:
							snake_case__	     =WavaVecaFeatureExtractor()
							snake_case__	     =AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h'						)

							snake_case__	     =WavaVecaProcessor(_UpperCAmelCase					,   _UpperCAmelCase						)

							# save in new folder
							processor.save_pretrained(_UpperCAmelCase						)

							# drop `processor_class` in tokenizer
							with open(os.path.join(_UpperCAmelCase					,   _UpperCAmelCase						)					,   'r'						) as f:
									snake_case__	     =json.load(_UpperCAmelCase						)
									config_dict.pop('processor_class'						)

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

							snake_case__	     =AutoProcessor.from_pretrained(_UpperCAmelCase						)

					self.assertIsInstance(_UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[int]:
					with tempfile.TemporaryDirectory() as tmpdirname:
							snake_case__	     =WavaVecaFeatureExtractor()
							snake_case__	     =AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h'						)

							snake_case__	     =WavaVecaProcessor(_UpperCAmelCase					,   _UpperCAmelCase						)

							# save in new folder
							processor.save_pretrained(_UpperCAmelCase						)

							# drop `processor_class` in feature extractor
							with open(os.path.join(_UpperCAmelCase					,   _UpperCAmelCase						)					,   'r'						) as f:
									snake_case__	     =json.load(_UpperCAmelCase						)
									config_dict.pop('processor_class'						)

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

							snake_case__	     =AutoProcessor.from_pretrained(_UpperCAmelCase						)

					self.assertIsInstance(_UpperCAmelCase					,   _UpperCAmelCase						)






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

							snake_case__	     =AutoProcessor.from_pretrained(_UpperCAmelCase						)

					self.assertIsInstance(_UpperCAmelCase					,   _UpperCAmelCase						)






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

					snake_case__	     =AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor'					,   trust_remote_code=_UpperCAmelCase						)
					self.assertTrue(processor.special_attribute_present						)
					self.assertEqual(processor.__class__.__name__					,   'NewProcessor'						)

					snake_case__	     =processor.feature_extractor
					self.assertTrue(feature_extractor.special_attribute_present						)
					self.assertEqual(feature_extractor.__class__.__name__					,   'NewFeatureExtractor'						)

					snake_case__	     =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
							snake_case__	     =AutoProcessor.from_pretrained(
							    'hf-internal-testing/test_dynamic_processor'					,   trust_remote_code=_UpperCAmelCase					,   use_fast=_UpperCAmelCase						)
							snake_case__	     =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 						_lowercase  (     self						)							->							Optional[Any]:
					try:
							AutoConfig.register('custom'					,   _UpperCAmelCase						)
							AutoFeatureExtractor.register(_UpperCAmelCase					,   _UpperCAmelCase						)
							AutoTokenizer.register(_UpperCAmelCase					,   slow_tokenizer_class=_UpperCAmelCase						)
							AutoProcessor.register(_UpperCAmelCase					,   _UpperCAmelCase						)
							# Trying to register something existing in the Transformers library will raise an error
							with self.assertRaises(_UpperCAmelCase						):
									AutoProcessor.register(_UpperCAmelCase					,   _UpperCAmelCase						)

							# Now that the config is registered, it can be used as any other config with the auto-API
							snake_case__	     =CustomFeatureExtractor.from_pretrained(_UpperCAmelCase						)

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

							snake_case__	     =CustomProcessor(_UpperCAmelCase					,   _UpperCAmelCase						)

							with tempfile.TemporaryDirectory() as tmp_dir:
									processor.save_pretrained(_UpperCAmelCase						)
									snake_case__	     =AutoProcessor.from_pretrained(_UpperCAmelCase						)
									self.assertIsInstance(_UpperCAmelCase					,   _UpperCAmelCase						)

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

					class 							a__( snake_case__     ):
								a_	: Optional[int]									=      False





					class 							a__( snake_case__     ):
								a_	: List[Any]									=      False





					class 							a__( snake_case__     ):
								a_	: int									=      '''AutoFeatureExtractor'''
								a_	: int									=      '''AutoTokenizer'''
								a_	: List[str]									=      False

					try:
							AutoConfig.register('custom'					,   _UpperCAmelCase						)
							AutoFeatureExtractor.register(_UpperCAmelCase					,   _UpperCAmelCase						)
							AutoTokenizer.register(_UpperCAmelCase					,   slow_tokenizer_class=_UpperCAmelCase						)
							AutoProcessor.register(_UpperCAmelCase					,   _UpperCAmelCase						)
							# If remote code is not set, the default is to use local classes.
							snake_case__	     =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.
							snake_case__	     =AutoProcessor.from_pretrained(
							    'hf-internal-testing/test_dynamic_processor'					,   trust_remote_code=_UpperCAmelCase						)
							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.
							snake_case__	     =AutoProcessor.from_pretrained(
							    'hf-internal-testing/test_dynamic_processor'					,   trust_remote_code=_UpperCAmelCase						)
							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 						_lowercase  (     self						)							->							Union[str, Any]:
					snake_case__	     =AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-bert'						)
					self.assertEqual(processor.__class__.__name__					,   'BertTokenizerFast'						)






			def 						_lowercase  (     self						)							->							List[Any]:
					snake_case__	     =AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-convnext'						)
					self.assertEqual(processor.__class__.__name__					,   'ConvNextImageProcessor'						)





@is_staging_test
class 							a__( unittest.TestCase     ):
			a_	: Dict									=      ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']






			@classmethod
			def 						_lowercase  (     cls						)							->							str:
					snake_case__	     =TOKEN
					HfFolder.save_token(_UpperCAmelCase						)






			@classmethod
			def 						_lowercase  (     cls						)							->							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 						_lowercase  (     self						)							->							int:
					snake_case__	     =WavaVecaProcessor.from_pretrained(_UpperCAmelCase						)
					with tempfile.TemporaryDirectory() as tmp_dir:
							processor.save_pretrained(
							    os.path.join(_UpperCAmelCase					,   'test-processor'						)					,   push_to_hub=_UpperCAmelCase					,   use_auth_token=self._token						)

							snake_case__	     =WavaVecaProcessor.from_pretrained(f"""{USER}/test-processor"""						)
							for k, v in processor.feature_extractor.__dict__.items():
									self.assertEqual(_UpperCAmelCase					,   getattr(new_processor.feature_extractor					,   _UpperCAmelCase						)						)
							self.assertDictEqual(new_processor.tokenizer.get_vocab()					,   processor.tokenizer.get_vocab()						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__	     =WavaVecaProcessor.from_pretrained(_UpperCAmelCase						)

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

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






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

					snake_case__	     =CustomFeatureExtractor.from_pretrained(_UpperCAmelCase						)

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

					snake_case__	     =CustomProcessor(_UpperCAmelCase					,   _UpperCAmelCase						)

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

							# 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(_UpperCAmelCase					,   'tokenizer_config.json'						)						) as f:
									snake_case__	     =json.load(_UpperCAmelCase						)
							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(_UpperCAmelCase					,   'custom_feature_extraction.py'						)						)						)
							self.assertTrue(os.path.isfile(os.path.join(_UpperCAmelCase					,   'custom_tokenization.py'						)						)						)
							self.assertTrue(os.path.isfile(os.path.join(_UpperCAmelCase					,   'custom_processing.py'						)						)						)

							repo.push_to_hub()

					snake_case__	     =AutoProcessor.from_pretrained(f"""{USER}/test-dynamic-processor"""					,   trust_remote_code=_UpperCAmelCase						)
					# 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'						)




