
'''simple docstring'''



import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

     if is_vision_available():
          from transformers import MaskaFormerImageProcessor

if is_vision_available():
     from PIL import Image

class  _a					:





       """simple docstring"""




       def __init__(				self							,				A__							,				A__=2							,				A__=True							,				A__=False							,				A__=10							,				A__=3							,				A__=32 * 8							,				A__=32 * 8							,				A__=4							,				A__=64							,				)     ->      List[Any]:
          _SCREAMING_SNAKE_CASE  			=					parent
          _SCREAMING_SNAKE_CASE  			=					batch_size
          _SCREAMING_SNAKE_CASE  			=					is_training
          _SCREAMING_SNAKE_CASE  			=					use_auxiliary_loss
          _SCREAMING_SNAKE_CASE  			=					num_queries
          _SCREAMING_SNAKE_CASE  			=					num_channels
          _SCREAMING_SNAKE_CASE  			=					min_size
          _SCREAMING_SNAKE_CASE  			=					max_size
          _SCREAMING_SNAKE_CASE  			=					num_labels
          _SCREAMING_SNAKE_CASE  			=					hidden_dim
          _SCREAMING_SNAKE_CASE  			=					hidden_dim






       def 							UpperCamelCase					(				self   )     ->      Optional[Any]:
          _SCREAMING_SNAKE_CASE  			=					floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]   ).to(
              _lowercase   )

          _SCREAMING_SNAKE_CASE  			=					torch.ones([self.batch_size, self.min_size, self.max_size]							,				device=_lowercase   )

          _SCREAMING_SNAKE_CASE  			=					(
              torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]							,				device=_lowercase   ) > 0.5
          ).float()
          _SCREAMING_SNAKE_CASE  			=					(torch.rand((self.batch_size, self.num_labels)							,				device=_lowercase   ) > 0.5).long()

          _SCREAMING_SNAKE_CASE  			=					self.get_config()
          return config, pixel_values, pixel_mask, mask_labels, class_labels






       def 							UpperCamelCase					(				self   )     ->      Dict:
          _SCREAMING_SNAKE_CASE  			=					MaskaFormerConfig(
              hidden_size=self.hidden_dim							,				)
          _SCREAMING_SNAKE_CASE  			=					self.num_queries
          _SCREAMING_SNAKE_CASE  			=					self.num_labels

          _SCREAMING_SNAKE_CASE  			=					[1, 1, 1, 1]
          _SCREAMING_SNAKE_CASE  			=					self.num_channels

          _SCREAMING_SNAKE_CASE  			=					64
          _SCREAMING_SNAKE_CASE  			=					1_28
          _SCREAMING_SNAKE_CASE  			=					self.hidden_dim
          _SCREAMING_SNAKE_CASE  			=					self.hidden_dim
          _SCREAMING_SNAKE_CASE  			=					self.hidden_dim
          return config






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.prepare_config_and_inputs()
          _SCREAMING_SNAKE_CASE  			=					{"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
          return config, inputs_dict






       def 							UpperCamelCase					(				self							,				A__							,				A__   )     ->      List[Any]:
          _SCREAMING_SNAKE_CASE  			=					output.encoder_hidden_states
          _SCREAMING_SNAKE_CASE  			=					output.pixel_decoder_hidden_states
          _SCREAMING_SNAKE_CASE  			=					output.transformer_decoder_hidden_states

          self.parent.assertTrue(len(_lowercase   )							,				len(config.backbone_config.depths   )   )
          self.parent.assertTrue(len(_lowercase   )							,				len(config.backbone_config.depths   )   )
          self.parent.assertTrue(len(_lowercase   )							,				config.decoder_layers   )






       def 							UpperCamelCase					(				self							,				A__							,				A__							,				A__							,				A__=False   )     ->      int:
          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					MaskaFormerModel(config=_lowercase   )
             model.to(_lowercase   )
             model.eval()

             _SCREAMING_SNAKE_CASE  			=					model(pixel_values=_lowercase							,				pixel_mask=_lowercase   )
             _SCREAMING_SNAKE_CASE  			=					model(_lowercase							,				output_hidden_states=_lowercase   )

          self.parent.assertEqual(
              output.transformer_decoder_last_hidden_state.shape							,				(self.batch_size, self.num_queries, self.hidden_dim)							,				)
          # let's ensure the other two hidden state exists
          self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None   )
          self.parent.assertTrue(output.encoder_last_hidden_state is not None   )

          if output_hidden_states:
             self.check_output_hidden_state(_lowercase							,				_lowercase   )






       def 							UpperCamelCase					(				self							,				A__							,				A__							,				A__							,				A__							,				A__   )     ->      Optional[Any]:
          _SCREAMING_SNAKE_CASE  			=					MaskaFormerForUniversalSegmentation(config=_lowercase   )
          model.to(_lowercase   )
          model.eval()

          def comm_check_on_output(A__   ):
             # let's still check that all the required stuff is there
             self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None   )
             self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None   )
             self.parent.assertTrue(result.encoder_last_hidden_state is not None   )
             # okay, now we need to check the logits shape
             # due to the encoder compression, masks have a //4 spatial size
             self.parent.assertEqual(
                 result.masks_queries_logits.shape							,				(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)							,				)
             # + 1 for null class
             self.parent.assertEqual(
                 result.class_queries_logits.shape							,				(self.batch_size, self.num_queries, self.num_labels + 1)   )

          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(pixel_values=_lowercase							,				pixel_mask=_lowercase   )
             _SCREAMING_SNAKE_CASE  			=					model(_lowercase   )

             comm_check_on_output(_lowercase   )

             _SCREAMING_SNAKE_CASE  			=					model(
                 pixel_values=_lowercase							,				pixel_mask=_lowercase							,				mask_labels=_lowercase							,				class_labels=_lowercase   )

          comm_check_on_output(_lowercase   )

          self.parent.assertTrue(result.loss is not None   )
          self.parent.assertEqual(result.loss.shape							,				torch.Size([1]   )   )






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





       """simple docstring"""




       SCREAMING_SNAKE_CASE   =	(MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
       SCREAMING_SNAKE_CASE   =	{'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

       SCREAMING_SNAKE_CASE   =	False
       SCREAMING_SNAKE_CASE   =	False
       SCREAMING_SNAKE_CASE   =	False
       SCREAMING_SNAKE_CASE   =	False






       def 							UpperCamelCase					(				self   )     ->      List[Any]:
          _SCREAMING_SNAKE_CASE  			=					MaskaFormerModelTester(self   )
          _SCREAMING_SNAKE_CASE  			=					ConfigTester(self							,				config_class=_lowercase							,				has_text_modality=_lowercase   )






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          self.config_tester.run_common_tests()






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()
          self.model_tester.create_and_check_maskaformer_model(_lowercase							,				**_lowercase							,				output_hidden_states=_lowercase   )






       def 							UpperCamelCase					(				self   )     ->      Tuple:
          _SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_lowercase   )






       @unittest.skip(reason="""Mask2Former does not use inputs_embeds"""   )
       def 							UpperCamelCase					(				self   )     ->      Dict:
          pass






       @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""   )
       def 							UpperCamelCase					(				self   )     ->      List[str]:
          pass






       @unittest.skip(reason="""Mask2Former is not a generative model"""   )
       def 							UpperCamelCase					(				self   )     ->      Optional[Any]:
          pass






       @unittest.skip(reason="""Mask2Former does not use token embeddings"""   )
       def 							UpperCamelCase					(				self   )     ->      int:
          pass






       @require_torch_multi_gpu
       @unittest.skip(
           reason="""Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`"""   )
       def 							UpperCamelCase					(				self   )     ->      List[str]:
          pass






       @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""   )
       def 							UpperCamelCase					(				self   )     ->      Optional[Any]:
          pass






       def 							UpperCamelCase					(				self   )     ->      str:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()

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

             _SCREAMING_SNAKE_CASE  			=					["""pixel_values"""]
             self.assertListEqual(arg_names[:1]							,				_lowercase   )






       @slow
       def 							UpperCamelCase					(				self   )     ->      List[Any]:
          for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
             _SCREAMING_SNAKE_CASE  			=					MaskaFormerModel.from_pretrained(_lowercase   )
             self.assertIsNotNone(_lowercase   )






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE  			=					(self.model_tester.min_size,) * 2
          _SCREAMING_SNAKE_CASE  			=					{
              """pixel_values""": torch.randn((2, 3, *size)							,				device=_lowercase   ),
              """mask_labels""": torch.randn((2, 10, *size)							,				device=_lowercase   ),
              """class_labels""": torch.zeros(2							,				10							,				device=_lowercase   ).long(),
          }
          _SCREAMING_SNAKE_CASE  			=					self.model_tester.get_config()

          _SCREAMING_SNAKE_CASE  			=					MaskaFormerForUniversalSegmentation(_lowercase   ).to(_lowercase   )
          _SCREAMING_SNAKE_CASE  			=					model(**_lowercase   )
          self.assertTrue(outputs.loss is not None   )






       def 							UpperCamelCase					(				self   )     ->      List[str]:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()
          self.model_tester.create_and_check_maskaformer_model(_lowercase							,				**_lowercase							,				output_hidden_states=_lowercase   )






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
             _SCREAMING_SNAKE_CASE  			=					model_class(_lowercase   ).to(_lowercase   )
             _SCREAMING_SNAKE_CASE  			=					model(**_lowercase							,				output_attentions=_lowercase   )
             self.assertTrue(outputs.attentions is not None   )






       def 							UpperCamelCase					(				self   )     ->      int:
          if not self.model_tester.is_training:
             return

          _SCREAMING_SNAKE_CASE  			=					self.all_model_classes[1]
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs()

          _SCREAMING_SNAKE_CASE  			=					model_class(_lowercase   )
          model.to(_lowercase   )
          model.train()

          _SCREAMING_SNAKE_CASE  			=					model(_lowercase							,				mask_labels=_lowercase							,				class_labels=_lowercase   ).loss
          loss.backward()






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE  			=					self.all_model_classes[1]
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs()
          _SCREAMING_SNAKE_CASE  			=					True
          _SCREAMING_SNAKE_CASE  			=					True

          _SCREAMING_SNAKE_CASE  			=					model_class(_lowercase   ).to(_lowercase   )
          model.train()

          _SCREAMING_SNAKE_CASE  			=					model(_lowercase							,				mask_labels=_lowercase							,				class_labels=_lowercase   )

          _SCREAMING_SNAKE_CASE  			=					outputs.encoder_hidden_states[0]
          encoder_hidden_states.retain_grad()

          _SCREAMING_SNAKE_CASE  			=					outputs.pixel_decoder_hidden_states[0]
          pixel_decoder_hidden_states.retain_grad()

          _SCREAMING_SNAKE_CASE  			=					outputs.transformer_decoder_hidden_states[0]
          transformer_decoder_hidden_states.retain_grad()

          _SCREAMING_SNAKE_CASE  			=					outputs.attentions[0]
          attentions.retain_grad()

          outputs.loss.backward(retain_graph=_lowercase   )

          self.assertIsNotNone(encoder_hidden_states.grad   )
          self.assertIsNotNone(pixel_decoder_hidden_states.grad   )
          self.assertIsNotNone(transformer_decoder_hidden_states.grad   )
          self.assertIsNotNone(attentions.grad   )






UpperCamelCase__   :		Dict											=	1E-4
def  lowerCAmelCase_						(					)  ->  Any:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE  			=					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
   return image







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





       """simple docstring"""




       @cached_property
       def 							UpperCamelCase					(				self   )     ->      List[Any]:
          return "facebook/mask2former-swin-small-coco-instance"






       @cached_property
       def 							UpperCamelCase					(				self   )     ->      str:
          return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints   ) if is_vision_available() else None






       def 							UpperCamelCase					(				self   )     ->      List[Any]:
          _SCREAMING_SNAKE_CASE  			=					MaskaFormerModel.from_pretrained(self.model_checkpoints   ).to(_lowercase   )
          _SCREAMING_SNAKE_CASE  			=					self.default_image_processor
          _SCREAMING_SNAKE_CASE  			=					prepare_img()
          _SCREAMING_SNAKE_CASE  			=					image_processor(_lowercase							,				return_tensors="""pt"""   ).to(_lowercase   )
          _SCREAMING_SNAKE_CASE  			=					inputs["""pixel_values"""].shape
          # check size is divisible by 32
          self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
          # check size
          self.assertEqual(_lowercase							,				(1, 3, 3_84, 3_84)   )

          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(**_lowercase   )

          _SCREAMING_SNAKE_CASE  			=					torch.tensor(
              [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]   ).to(_lowercase   )
          self.assertTrue(
              torch.allclose(
                  outputs.encoder_last_hidden_state[0, 0, :3, :3]							,				_lowercase							,				atol=_lowercase   )   )

          _SCREAMING_SNAKE_CASE  			=					torch.tensor(
              [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]   ).to(_lowercase   )
          self.assertTrue(
              torch.allclose(
                  outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]							,				_lowercase							,				atol=_lowercase   )   )

          _SCREAMING_SNAKE_CASE  			=					torch.tensor(
              [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]   ).to(_lowercase   )
          self.assertTrue(
              torch.allclose(
                  outputs.transformer_decoder_last_hidden_state[0, :3, :3]							,				_lowercase							,				atol=_lowercase   )   )






       def 							UpperCamelCase					(				self   )     ->      Any:
          _SCREAMING_SNAKE_CASE  			=					MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints   ).to(_lowercase   ).eval()
          _SCREAMING_SNAKE_CASE  			=					self.default_image_processor
          _SCREAMING_SNAKE_CASE  			=					prepare_img()
          _SCREAMING_SNAKE_CASE  			=					image_processor(_lowercase							,				return_tensors="""pt"""   ).to(_lowercase   )
          _SCREAMING_SNAKE_CASE  			=					inputs["""pixel_values"""].shape
          # check size is divisible by 32
          self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
          # check size
          self.assertEqual(_lowercase							,				(1, 3, 3_84, 3_84)   )

          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(**_lowercase   )
          # masks_queries_logits
          _SCREAMING_SNAKE_CASE  			=					outputs.masks_queries_logits
          self.assertEqual(
              masks_queries_logits.shape							,				(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)   )
          _SCREAMING_SNAKE_CASE  			=					[
              [-8.7839, -9.0056, -8.8121],
              [-7.4104, -7.0313, -6.5401],
              [-6.6105, -6.3427, -6.4675],
          ]
          _SCREAMING_SNAKE_CASE  			=					torch.tensor(_lowercase   ).to(_lowercase   )
          self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]							,				_lowercase							,				atol=_lowercase   )   )
          # class_queries_logits
          _SCREAMING_SNAKE_CASE  			=					outputs.class_queries_logits
          self.assertEqual(class_queries_logits.shape							,				(1, model.config.num_queries, model.config.num_labels + 1)   )
          _SCREAMING_SNAKE_CASE  			=					torch.tensor(
              [
                  [1.8324, -8.0835, -4.1922],
                  [0.8450, -9.0050, -3.6053],
                  [0.3045, -7.7293, -3.0275],
              ]   ).to(_lowercase   )
          self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]							,				_lowercase							,				atol=_lowercase   )   )






       def 							UpperCamelCase					(				self   )     ->      Any:
          _SCREAMING_SNAKE_CASE  			=					MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints   ).to(_lowercase   ).eval()
          _SCREAMING_SNAKE_CASE  			=					self.default_image_processor

          _SCREAMING_SNAKE_CASE  			=					image_processor(
              [np.zeros((3, 8_00, 13_33)   ), np.zeros((3, 8_00, 13_33)   )]							,				segmentation_maps=[np.zeros((3_84, 3_84)   ).astype(np.floataa   ), np.zeros((3_84, 3_84)   ).astype(np.floataa   )]							,				return_tensors="""pt"""							,				)

          _SCREAMING_SNAKE_CASE  			=					inputs["""pixel_values"""].to(_lowercase   )
          _SCREAMING_SNAKE_CASE  			=					[el.to(_lowercase   ) for el in inputs["""mask_labels"""]]
          _SCREAMING_SNAKE_CASE  			=					[el.to(_lowercase   ) for el in inputs["""class_labels"""]]

          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(**_lowercase   )

          self.assertTrue(outputs.loss is not None   )









'''simple docstring'''

import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


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


SCREAMING_SNAKE_CASE							:				int     	=			get_tests_dir("fixtures")
SCREAMING_SNAKE_CASE							:				str     	=			get_tests_dir("fixtures/dummy_feature_extractor_config.json")
SCREAMING_SNAKE_CASE							:				str     	=			get_tests_dir("fixtures/dummy-config.json")






class    snake_case     (      unittest.TestCase		):






				"""simple docstring"""



				def   a__					(    self       )     ->							str:
											SCREAMING_SNAKE_CASE_				=				0



				def   a__					(    self       )     ->							Tuple:
											SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h'       )
											self.assertIsInstance(_lowercase,     _lowercase       )



				def   a__					(    self       )     ->							List[str]:
											SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(_lowercase       )
											self.assertIsInstance(_lowercase,     _lowercase       )



				def   a__					(    self       )     ->							str:
											with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE_				=				WavaVecaConfig()

																		# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(_lowercase       ).to_dict()

																		config_dict.pop('feature_extractor_type'       )
																		SCREAMING_SNAKE_CASE_				=				WavaVecaFeatureExtractor(**_lowercase       )

																		# save in new folder
																		model_config.save_pretrained(_lowercase       )
																		config.save_pretrained(_lowercase       )

																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(_lowercase       )

																		# make sure private variable is not incorrectly saved
																		SCREAMING_SNAKE_CASE_				=				json.loads(config.to_json_string()       )
																		self.assertTrue('_processor_class' not in dict_as_saved       )

											self.assertIsInstance(_lowercase,     _lowercase       )



				def   a__					(    self       )     ->							int:
											SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(_lowercase       )
											self.assertIsInstance(_lowercase,     _lowercase       )



				def   a__					(    self       )     ->							Any:
											with self.assertRaisesRegex(
											    _lowercase,     'bert-base is not a local folder and is not a valid model identifier'       ):
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained('bert-base'       )



				def   a__					(    self       )     ->							List[Any]:
											with self.assertRaisesRegex(
											    _lowercase,     R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'       ):
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(_lowercase,     revision='aaaaaa'       )



				def   a__					(    self       )     ->							List[Any]:
											with self.assertRaisesRegex(
											    _lowercase,     'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.',     ):
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model'       )



				def   a__					(    self       )     ->							List[str]:
											# If remote code is not set, we will time out when asking whether to load the model.
											with self.assertRaises(_lowercase       ):
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(
																		    'hf-internal-testing/test_dynamic_feature_extractor'       )
											# If remote code is disabled, we can't load this config.
											with self.assertRaises(_lowercase       ):
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(
																		    'hf-internal-testing/test_dynamic_feature_extractor',     trust_remote_code=_lowercase       )

											SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(
											    'hf-internal-testing/test_dynamic_feature_extractor',     trust_remote_code=_lowercase       )
											self.assertEqual(feature_extractor.__class__.__name__,     'NewFeatureExtractor'       )

											# Test feature extractor can be reloaded.
											with tempfile.TemporaryDirectory() as tmp_dir:
																		feature_extractor.save_pretrained(_lowercase       )
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(_lowercase,     trust_remote_code=_lowercase       )
											self.assertEqual(reloaded_feature_extractor.__class__.__name__,     'NewFeatureExtractor'       )



				def   a__					(    self       )     ->							int:
											try:
																		AutoConfig.register('custom',     _lowercase       )
																		AutoFeatureExtractor.register(_lowercase,     _lowercase       )
																		# Trying to register something existing in the Transformers library will raise an error
																		with self.assertRaises(_lowercase       ):
																									AutoFeatureExtractor.register(_lowercase,     _lowercase       )

																		# Now that the config is registered, it can be used as any other config with the auto-API
																		SCREAMING_SNAKE_CASE_				=				CustomFeatureExtractor.from_pretrained(_lowercase       )
																		with tempfile.TemporaryDirectory() as tmp_dir:
																									feature_extractor.save_pretrained(_lowercase       )
																									SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(_lowercase       )
																									self.assertIsInstance(_lowercase,     _lowercase       )

											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]





				def   a__					(    self       )     ->							str:






											class    snake_case     (      lowercase_		):






															"""simple docstring"""
															_a    	=     True

											try:
																		AutoConfig.register('custom',     _lowercase       )
																		AutoFeatureExtractor.register(_lowercase,     _lowercase       )
																		# If remote code is not set, the default is to use local
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(
																		    'hf-internal-testing/test_dynamic_feature_extractor'       )
																		self.assertEqual(feature_extractor.__class__.__name__,     'NewFeatureExtractor'       )
																		self.assertTrue(feature_extractor.is_local       )

																		# If remote code is disabled, we load the local one.
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(
																		    'hf-internal-testing/test_dynamic_feature_extractor',     trust_remote_code=_lowercase       )
																		self.assertEqual(feature_extractor.__class__.__name__,     'NewFeatureExtractor'       )
																		self.assertTrue(feature_extractor.is_local       )

																		# If remote is enabled, we load from the Hub
																		SCREAMING_SNAKE_CASE_				=				AutoFeatureExtractor.from_pretrained(
																		    'hf-internal-testing/test_dynamic_feature_extractor',     trust_remote_code=_lowercase       )
																		self.assertEqual(feature_extractor.__class__.__name__,     'NewFeatureExtractor'       )
																		self.assertTrue(not hasattr(_lowercase,     'is_local'       )       )

											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]





