




'''simple docstring'''



import inspect
import unittest

from datasets import load_dataset
from packaging import version

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

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


if is_torch_available():
      import torch
      from torch import nn

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


if is_vision_available():
      import PIL
      from PIL import Image

      from transformers import BeitImageProcessor






class 							_a				:





       '''simple docstring'''






       def __init__(      self,							A,							A=100,							A=13,							A=30,							A=2,							A=3,							A=True,							A=True,							A=32,							A=4,							A=4,							A=37,							A="gelu",							A=0.1,							A=0.1,							A=10,							A=0.02,							A=3,							A=None,							A=[0, 1, 2, 3],							):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Dict    					=						parent
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						100
             SCREAMING_SNAKE_CASE   :      int    					=						batch_size
             SCREAMING_SNAKE_CASE   :      str    					=						image_size
             SCREAMING_SNAKE_CASE   :      List[str]    					=						patch_size
             SCREAMING_SNAKE_CASE   :      Dict    					=						num_channels
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						is_training
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						use_labels
             SCREAMING_SNAKE_CASE   :      List[str]    					=						hidden_size
             SCREAMING_SNAKE_CASE   :      Tuple    					=						num_hidden_layers
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						num_attention_heads
             SCREAMING_SNAKE_CASE   :      Any    					=						intermediate_size
             SCREAMING_SNAKE_CASE   :      str    					=						hidden_act
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						hidden_dropout_prob
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						attention_probs_dropout_prob
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						type_sequence_label_size
             SCREAMING_SNAKE_CASE   :      int    					=						initializer_range
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						scope
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						out_indices
             SCREAMING_SNAKE_CASE   :      Tuple    					=						num_labels

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             if self.use_labels:
                   SCREAMING_SNAKE_CASE   :      str    					=						ids_tensor([self.batch_size],							self.type_sequence_label_size  )
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						ids_tensor([self.batch_size, self.image_size, self.image_size],							self.num_labels  )

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

             return config, pixel_values, labels, pixel_labels







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						BeitModel(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						model(A  )
             self.parent.assertEqual(result.last_hidden_state.shape,							(self.batch_size, self.seq_length, self.hidden_size)  )







       def        UpperCamelCase_							(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						BeitForMaskedImageModeling(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      str    					=						model(A  )
             self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.seq_length - 1, self.vocab_size)  )







       def        UpperCamelCase_							(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.type_sequence_label_size
             SCREAMING_SNAKE_CASE   :      str    					=						BeitForImageClassification(A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						model(A,							labels=A  )
             self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.type_sequence_label_size)  )

             # test greyscale images
             SCREAMING_SNAKE_CASE   :      Dict    					=						1
             SCREAMING_SNAKE_CASE   :      Any    					=						BeitForImageClassification(A  )
             model.to(A  )
             model.eval()

             SCREAMING_SNAKE_CASE   :      str    					=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
             SCREAMING_SNAKE_CASE   :      str    					=						model(A,							labels=A  )
             self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.type_sequence_label_size)  )







       def        UpperCamelCase_							(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.num_labels
             SCREAMING_SNAKE_CASE   :      List[str]    					=						BeitForSemanticSegmentation(A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						model(A  )
             self.parent.assertEqual(
                 result.logits.shape,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						model(A,							labels=A  )
             self.parent.assertEqual(
                 result.logits.shape,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.prepare_config_and_inputs()
             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      List[str]    					=						config_and_inputs
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						{'pixel_values': pixel_values}
             return config, inputs_dict






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





       '''simple docstring'''






       A						:				Tuple        =						(
           (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       A						:				Tuple        =						(
           {
               '''feature-extraction''': BeitModel,
               '''image-classification''': BeitForImageClassification,
               '''image-segmentation''': BeitForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						BeitModelTester(self  )
             SCREAMING_SNAKE_CASE   :      str    					=						ConfigTester(self,							config_class=A,							has_text_modality=A,							hidden_size=37  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             self.config_tester.run_common_tests()







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







             '''simple docstring'''







             pass







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







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    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   :      Optional[int]    					=						model.get_output_embeddings()
                   self.assertTrue(x is None or isinstance(A,							nn.Linear  )  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      str    					=						self.model_tester.prepare_config_and_inputs_for_common()

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

                   SCREAMING_SNAKE_CASE   :      Dict    					=						['pixel_values']
                   self.assertListEqual(arg_names[:1],							A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_masked_lm(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Dict    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             if not self.model_tester.is_training:
                   return

             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.model_tester.prepare_config_and_inputs_for_common()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						True

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

                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model_class(A  )
                   model.to(A  )
                   model.train()
                   SCREAMING_SNAKE_CASE   :      Any    					=						self._prepare_for_class(A,							A,							return_labels=A  )
                   SCREAMING_SNAKE_CASE   :      int    					=						model(**A  ).loss
                   loss.backward()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      str    					=						self.model_tester.prepare_config_and_inputs_for_common()
             if not self.model_tester.is_training:
                   return

             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						False
             SCREAMING_SNAKE_CASE   :      str    					=						True

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

                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						model_class(A  )
                   model.gradient_checkpointing_enable()
                   model.to(A  )
                   model.train()
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						self._prepare_for_class(A,							A,							return_labels=A  )
                   SCREAMING_SNAKE_CASE   :      Dict    					=						model(**A  ).loss
                   loss.backward()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      List[str]    					=						self.model_tester.prepare_config_and_inputs_for_common()

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







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   SCREAMING_SNAKE_CASE   :      str    					=						BeitModel.from_pretrained(A  )
                   self.assertIsNotNone(A  )




def   lowercase__(			):

      """simple docstring"""






      SCREAMING_SNAKE_CASE   :      List[Any]    					=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
      return image






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





       '''simple docstring'''






       @cached_property
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224'  ) if is_vision_available() else None







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k'  ).to(A  )

             SCREAMING_SNAKE_CASE   :      Any    					=						self.default_image_processor
             SCREAMING_SNAKE_CASE   :      Tuple    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						image_processor(images=A,							return_tensors='pt'  ).pixel_values.to(A  )

             # prepare bool_masked_pos
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						torch.ones((1, 196),							dtype=torch.bool  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						model(pixel_values=A,							bool_masked_pos=A  )
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						outputs.logits

             # verify the logits
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						torch.Size((1, 196, 8_192)  )
             self.assertEqual(logits.shape,							A  )

             SCREAMING_SNAKE_CASE   :      Any    					=						torch.tensor(
                 [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]]  ).to(A  )

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







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224'  ).to(A  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.default_image_processor
             SCREAMING_SNAKE_CASE   :      Any    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						image_processor(images=A,							return_tensors='pt'  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model(**A  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						outputs.logits

             # verify the logits
             SCREAMING_SNAKE_CASE   :      str    					=						torch.Size((1, 1_000)  )
             self.assertEqual(logits.shape,							A  )

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						torch.tensor([-1.23_85, -1.09_87, -1.01_08]  ).to(A  )

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

             SCREAMING_SNAKE_CASE   :      int    					=						281
             self.assertEqual(logits.argmax(-1  ).item(),							A  )







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k'  ).to(
                 A  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.default_image_processor
             SCREAMING_SNAKE_CASE   :      str    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      str    					=						image_processor(images=A,							return_tensors='pt'  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      Any    					=						model(**A  )
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						outputs.logits

             # verify the logits
             SCREAMING_SNAKE_CASE   :      Tuple    					=						torch.Size((1, 21_841)  )
             self.assertEqual(logits.shape,							A  )

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						torch.tensor([1.68_81, -0.27_87, 0.59_01]  ).to(A  )

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

             SCREAMING_SNAKE_CASE   :      Dict    					=						2_396
             self.assertEqual(logits.argmax(-1  ).item(),							A  )







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640'  )
             SCREAMING_SNAKE_CASE   :      Tuple    					=						model.to(A  )

             SCREAMING_SNAKE_CASE   :      int    					=						BeitImageProcessor(do_resize=A,							size=640,							do_center_crop=A  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						load_dataset('hf-internal-testing/fixtures_ade20k',							split='test'  )
             SCREAMING_SNAKE_CASE   :      str    					=						Image.open(ds[0]['file']  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						image_processor(images=A,							return_tensors='pt'  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						model(**A  )
             SCREAMING_SNAKE_CASE   :      str    					=						outputs.logits

             # verify the logits
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						torch.Size((1, 150, 160, 160)  )
             self.assertEqual(logits.shape,							A  )

             SCREAMING_SNAKE_CASE   :      str    					=						version.parse(PIL.__version__  ) < version.parse('9.0.0'  )

             if is_pillow_less_than_a:
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						torch.tensor(
                       [
                           [[-4.92_25, -2.39_54, -3.05_22], [-2.88_22, -1.00_46, -1.75_61], [-2.95_49, -1.32_28, -2.13_47]],
                           [[-5.81_68, -3.41_29, -4.07_78], [-3.86_51, -2.22_14, -3.02_77], [-3.83_56, -2.46_43, -3.35_35]],
                           [[-0.00_78, 3.99_52, 4.07_54], [2.98_56, 4.69_44, 5.00_35], [3.24_13, 4.78_13, 4.99_69]],
                       ],							device=A,							)
             else:
                   SCREAMING_SNAKE_CASE   :      int    					=						torch.tensor(
                       [
                           [[-4.89_60, -2.36_88, -3.03_55], [-2.84_78, -0.98_36, -1.74_18], [-2.94_49, -1.33_32, -2.14_56]],
                           [[-5.80_81, -3.41_24, -4.10_06], [-3.85_61, -2.20_81, -3.03_23], [-3.83_65, -2.46_01, -3.36_69]],
                           [[-0.03_09, 3.98_68, 4.05_40], [2.96_40, 4.68_77, 4.99_76], [3.20_81, 4.76_90, 4.99_42]],
                       ],							device=A,							)

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







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640'  )
             SCREAMING_SNAKE_CASE   :      Tuple    					=						model.to(A  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						BeitImageProcessor(do_resize=A,							size=640,							do_center_crop=A  )

             SCREAMING_SNAKE_CASE   :      Any    					=						load_dataset('hf-internal-testing/fixtures_ade20k',							split='test'  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						Image.open(ds[0]['file']  )
             SCREAMING_SNAKE_CASE   :      Any    					=						image_processor(images=A,							return_tensors='pt'  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      Any    					=						model(**A  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						outputs.logits.detach().cpu()

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						image_processor.post_process_semantic_segmentation(outputs=A,							target_sizes=[(500, 300)]  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						torch.Size((500, 300)  )
             self.assertEqual(segmentation[0].shape,							A  )

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						image_processor.post_process_semantic_segmentation(outputs=A  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						torch.Size((160, 160)  )
             self.assertEqual(segmentation[0].shape,							A  )









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


a_					=     get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
a_					=     get_tests_dir("""fixtures/vocab.json""")
a_					=     get_tests_dir("""fixtures""")






class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


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

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[Any]							=	0

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		str							=	AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )
     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		str							=	WavaVecaConfig()
         __A       :		Dict							=	AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )

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

         __A       :		List[str]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         # copy relevant files
         copyfile(__lowerCamelCase   ,		os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )    )
         copyfile(__lowerCamelCase   ,		os.path.join(__lowerCamelCase   ,		'''vocab.json'''    )    )

         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Union[str, Any]							=	WavaVecaFeatureExtractor()
         __A       :		Optional[Any]							=	AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''    )

         __A       :		Union[str, Any]							=	WavaVecaProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

         # save in new folder
         processor.save_pretrained(__lowerCamelCase    )

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

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

         __A       :		Tuple							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Optional[int]							=	WavaVecaFeatureExtractor()
         __A       :		List[str]							=	AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''    )

         __A       :		List[Any]							=	WavaVecaProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

         # save in new folder
         processor.save_pretrained(__lowerCamelCase    )

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

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

         __A       :		Optional[int]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Optional[Any]							=	WavaVecaConfig(processor_class='''Wav2Vec2Processor'''    )
         model_config.save_pretrained(__lowerCamelCase    )
         # copy relevant files
         copyfile(__lowerCamelCase   ,		os.path.join(__lowerCamelCase   ,		'''vocab.json'''    )    )
         # create emtpy sample processor
         with open(os.path.join(__lowerCamelCase   ,		__lowerCamelCase    )   ,		'''w'''    ) as f:
             f.write('''{}'''    )

         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with self.assertRaises(__lowerCamelCase    ):
         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''    )
     # If remote code is disabled, we can't load this config.
     with self.assertRaises(__lowerCamelCase    ):
         __A       :		Dict							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )

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

     __A       :		Union[str, Any]							=	processor.feature_extractor
     self.assertTrue(feature_extractor.special_attribute_present    )
     self.assertEqual(feature_extractor.__class__.__name__   ,		'''NewFeatureExtractor'''    )

     __A       :		Optional[int]							=	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
         __A       :		int							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase   ,		use_fast=__lowerCamelCase    )
         __A       :		Optional[int]							=	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    UpperCamelCase__(       self    ):



     '''simple docstring'''




     try:
         AutoConfig.register('''custom'''   ,		__lowerCamelCase    )
         AutoFeatureExtractor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         AutoTokenizer.register(__lowerCamelCase   ,		slow_tokenizer_class=__lowerCamelCase    )
         AutoProcessor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         # Trying to register something existing in the Transformers library will raise an error
         with self.assertRaises(__lowerCamelCase    ):
             AutoProcessor.register(__lowerCamelCase   ,		__lowerCamelCase    )

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

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

         __A       :		Optional[Any]							=	CustomProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(__lowerCamelCase    )
             __A       :		List[str]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )
             self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

     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    UpperCamelCase__(       self    ):



     '''simple docstring'''




     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	False






     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	False






     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	"""AutoFeatureExtractor"""
      _lowerCamelCase								=	"""AutoTokenizer"""
      _lowerCamelCase								=	False

     try:
         AutoConfig.register('''custom'''   ,		__lowerCamelCase    )
         AutoFeatureExtractor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         AutoTokenizer.register(__lowerCamelCase   ,		slow_tokenizer_class=__lowerCamelCase    )
         AutoProcessor.register(__lowerCamelCase   ,		__lowerCamelCase    )
         # If remote code is not set, the default is to use local classes.
         __A       :		Union[str, Any]							=	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.
         __A       :		int							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )
         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.
         __A       :		str							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )
         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    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		int							=	AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert'''    )
     self.assertEqual(processor.__class__.__name__   ,		'''BertTokenizerFast'''    )







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		int							=	AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext'''    )
     self.assertEqual(processor.__class__.__name__   ,		'''ConvNextImageProcessor'''    )






@is_staging_test
class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


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

 @classmethod
 def    UpperCamelCase__(       cls    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	TOKEN
     HfFolder.save_token(__lowerCamelCase    )

 @classmethod
 def    UpperCamelCase__(       cls    ):



     '''simple docstring'''




     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    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Tuple							=	WavaVecaProcessor.from_pretrained(__lowerCamelCase    )
     with tempfile.TemporaryDirectory() as tmp_dir:
         processor.save_pretrained(
             os.path.join(__lowerCamelCase   ,		'''test-processor'''    )   ,		push_to_hub=__lowerCamelCase   ,		use_auth_token=self._token    )

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

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	WavaVecaProcessor.from_pretrained(__lowerCamelCase    )

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

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







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     CustomFeatureExtractor.register_for_auto_class()
     CustomTokenizer.register_for_auto_class()
     CustomProcessor.register_for_auto_class()

     __A       :		Any							=	CustomFeatureExtractor.from_pretrained(__lowerCamelCase    )

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

     __A       :		Any							=	CustomProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

     with tempfile.TemporaryDirectory() as tmp_dir:
         create_repo(F"""{USER}/test-dynamic-processor"""   ,		token=self._token    )
         __A       :		Tuple							=	Repository(__lowerCamelCase   ,		clone_from=F"""{USER}/test-dynamic-processor"""   ,		token=self._token    )
         processor.save_pretrained(__lowerCamelCase    )

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

         repo.push_to_hub()

     __A       :		Any							=	AutoProcessor.from_pretrained(F"""{USER}/test-dynamic-processor"""   ,		trust_remote_code=__lowerCamelCase    )
     # 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'''    )




