




import inspect
import unittest

import numpy as np

from transformers import BeitConfig
from transformers.testing_utils import require_flax, require_vision, slow
from transformers.utils import cached_property, is_flax_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor


if is_flax_available():
     import jax

     from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel

if is_vision_available():
     from PIL import Image

     from transformers import BeitImageProcessor





class 			__lowerCamelCase	(   unittest.TestCase   ):




    """simple docstring"""

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

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


    def        a				(	self					:					List[Any]       )				->	int:
         lowerCAmelCase__          =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

         lowerCAmelCase__          =			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=SCREAMING_SNAKE_CASE__       ,     initializer_range=self.initializer_range       ,     )

         return config, pixel_values, labels


    def        a				(	self					:					List[Any]       ,     SCREAMING_SNAKE_CASE__					:					Any       ,     SCREAMING_SNAKE_CASE__					:					Optional[Any]       ,     SCREAMING_SNAKE_CASE__					:					int       )				->	int:
         lowerCAmelCase__          =			FlaxBeitModel(config=SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			model(SCREAMING_SNAKE_CASE__       )
         self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)       )


    def        a				(	self					:					Tuple       ,     SCREAMING_SNAKE_CASE__					:					List[str]       ,     SCREAMING_SNAKE_CASE__					:					Optional[int]       ,     SCREAMING_SNAKE_CASE__					:					Tuple       )				->	List[Any]:
         lowerCAmelCase__          =			FlaxBeitForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			model(SCREAMING_SNAKE_CASE__       )
         self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length - 1, self.vocab_size)       )


    def        a				(	self					:					List[str]       ,     SCREAMING_SNAKE_CASE__					:					Optional[int]       ,     SCREAMING_SNAKE_CASE__					:					Tuple       ,     SCREAMING_SNAKE_CASE__					:					Optional[Any]       )				->	int:
         lowerCAmelCase__          =			self.type_sequence_label_size
         lowerCAmelCase__          =			FlaxBeitForImageClassification(config=SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			model(SCREAMING_SNAKE_CASE__       )
         self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.type_sequence_label_size)       )

         # test greyscale images
         lowerCAmelCase__          =			1
         lowerCAmelCase__          =			FlaxBeitForImageClassification(SCREAMING_SNAKE_CASE__       )

         lowerCAmelCase__          =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
         lowerCAmelCase__          =			model(SCREAMING_SNAKE_CASE__       )


    def        a				(	self					:					List[Any]       )				->	Optional[int]:
         lowerCAmelCase__          =			self.prepare_config_and_inputs()
         (
             (
             lowerCAmelCase__
         )     ,		(
             lowerCAmelCase__
         )     ,		(
             lowerCAmelCase__
         )     ,		
         )          =			config_and_inputs
         lowerCAmelCase__          =			{"pixel_values": pixel_values}
         return config, inputs_dict






@require_flax
class 			__lowerCamelCase	(   UpperCamelCase__     ,    unittest.TestCase   ):




    """simple docstring"""

    snake_case__ =				(
        (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
    )


    def        a				(	self					:					Optional[int]       )				->	None:
         lowerCAmelCase__          =			FlaxBeitModelTester(self       )
         lowerCAmelCase__          =			ConfigTester(self       ,     config_class=SCREAMING_SNAKE_CASE__       ,     has_text_modality=SCREAMING_SNAKE_CASE__       ,     hidden_size=37       )


    def        a				(	self					:					str       )				->	Optional[Any]:
         self.config_tester.run_common_tests()


    def        a				(	self					:					str       )				->	Any:
         lowerCAmelCase__     ,		lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs_for_common()

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

              lowerCAmelCase__          =			["pixel_values"]
              self.assertListEqual(arg_names[:1]       ,     SCREAMING_SNAKE_CASE__       )


    def        a				(	self					:					Optional[int]       )				->	int:
         lowerCAmelCase__     ,		lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__       ):
                   lowerCAmelCase__          =			self._prepare_for_class(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
                   lowerCAmelCase__          =			model_class(SCREAMING_SNAKE_CASE__       )

                   @jax.jit
                   def model_jitted(SCREAMING_SNAKE_CASE__					:					Tuple       ,     **SCREAMING_SNAKE_CASE__					:					Optional[int]       ):
                        return model(pixel_values=SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

                   with self.subTest("JIT Enabled"       ):
                        lowerCAmelCase__          =			model_jitted(**SCREAMING_SNAKE_CASE__       ).to_tuple()

                   with self.subTest("JIT Disabled"       ):
                        with jax.disable_jit():
                             lowerCAmelCase__          =			model_jitted(**SCREAMING_SNAKE_CASE__       ).to_tuple()

                   self.assertEqual(len(SCREAMING_SNAKE_CASE__       )       ,     len(SCREAMING_SNAKE_CASE__       )       )
                   for jitted_output, output in zip(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ):
                        self.assertEqual(jitted_output.shape       ,     output.shape       )


    def        a				(	self					:					Optional[int]       )				->	str:
         lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__       )


    def        a				(	self					:					Optional[Any]       )				->	Any:
         lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__       )


    def        a				(	self					:					str       )				->	List[Any]:
         lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__       )


    @slow
    def        a				(	self					:					List[str]       )				->	Any:
         for model_class_name in self.all_model_classes:
              lowerCAmelCase__          =			model_class_name.from_pretrained("microsoft/beit-base-patch16-224"       )
              lowerCAmelCase__          =			model(np.ones((1, 3, 224, 224)       )       )
              self.assertIsNotNone(SCREAMING_SNAKE_CASE__       )






def 							_A       (						):
     """simple docstring"""

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






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




    """simple docstring"""

    @cached_property
    def        a				(	self					:					Any       )				->	Union[str, Any]:
         return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224"       ) if is_vision_available() else None


    @slow
    def        a				(	self					:					List[Any]       )				->	Optional[Any]:
         lowerCAmelCase__          =			FlaxBeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k"       )

         lowerCAmelCase__          =			self.default_image_processor
         lowerCAmelCase__          =			prepare_img()
         lowerCAmelCase__          =			image_processor(images=SCREAMING_SNAKE_CASE__       ,     return_tensors="np"       ).pixel_values

         # prepare bool_masked_pos
         lowerCAmelCase__          =			np.ones((1, 196)       ,     dtype=SCREAMING_SNAKE_CASE__       )

         # forward pass
         lowerCAmelCase__          =			model(pixel_values=SCREAMING_SNAKE_CASE__       ,     bool_masked_pos=SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			outputs.logits

         # verify the logits
         lowerCAmelCase__          =			(1, 196, 8_192)
         self.assertEqual(logits.shape       ,     SCREAMING_SNAKE_CASE__       )

         lowerCAmelCase__          =			np.array(
             [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]]       )

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


    @slow
    def        a				(	self					:					int       )				->	List[Any]:
         lowerCAmelCase__          =			FlaxBeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224"       )

         lowerCAmelCase__          =			self.default_image_processor
         lowerCAmelCase__          =			prepare_img()
         lowerCAmelCase__          =			image_processor(images=SCREAMING_SNAKE_CASE__       ,     return_tensors="np"       )

         # forward pass
         lowerCAmelCase__          =			model(**SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			outputs.logits

         # verify the logits
         lowerCAmelCase__          =			(1, 1_000)
         self.assertEqual(logits.shape       ,     SCREAMING_SNAKE_CASE__       )

         lowerCAmelCase__          =			np.array([-1.2_385, -1.0_987, -1.0_108]       )

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

         lowerCAmelCase__          =			281
         self.assertEqual(logits.argmax(-1       ).item()       ,     SCREAMING_SNAKE_CASE__       )


    @slow
    def        a				(	self					:					Optional[int]       )				->	Optional[int]:
         lowerCAmelCase__          =			FlaxBeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k"       )

         lowerCAmelCase__          =			self.default_image_processor
         lowerCAmelCase__          =			prepare_img()
         lowerCAmelCase__          =			image_processor(images=SCREAMING_SNAKE_CASE__       ,     return_tensors="np"       )

         # forward pass
         lowerCAmelCase__          =			model(**SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			outputs.logits

         # verify the logits
         lowerCAmelCase__          =			(1, 21_841)
         self.assertEqual(logits.shape       ,     SCREAMING_SNAKE_CASE__       )

         lowerCAmelCase__          =			np.array([1.6_881, -0.2_787, 0.5_901]       )

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

         lowerCAmelCase__          =			2_396
         self.assertEqual(logits.argmax(-1       ).item()       ,     SCREAMING_SNAKE_CASE__       )






import unittest

from huggingface_hub import hf_hub_download

from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor
from transformers.pipelines import VideoClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_decord,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
)

from .test_pipelines_common import ANY





@is_pipeline_test
@require_torch_or_tf
@require_vision
@require_decord
class 			__lowerCamelCase	(   unittest.TestCase   ):




    """simple docstring"""

    snake_case__ =				MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING


    def        a				(	self					:					str       ,     SCREAMING_SNAKE_CASE__					:					Tuple       ,     SCREAMING_SNAKE_CASE__					:					List[str]       ,     SCREAMING_SNAKE_CASE__					:					Optional[int]       )				->	Any:
         lowerCAmelCase__          =			hf_hub_download(
             repo_id="nateraw/video-demo"       ,     filename="archery.mp4"       ,     repo_type="dataset"       )
         lowerCAmelCase__          =			VideoClassificationPipeline(model=SCREAMING_SNAKE_CASE__       ,     image_processor=SCREAMING_SNAKE_CASE__       ,     top_k=2       )
         lowerCAmelCase__          =			[
             example_video_filepath,
             "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4",
         ]
         return video_classifier, examples


    def        a				(	self					:					Any       ,     SCREAMING_SNAKE_CASE__					:					Dict       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]       )				->	Tuple:
         for example in examples:
              lowerCAmelCase__          =			video_classifier(SCREAMING_SNAKE_CASE__       )

              self.assertEqual(
                  SCREAMING_SNAKE_CASE__       ,     [
                      {"score": ANY(SCREAMING_SNAKE_CASE__       ), "label": ANY(SCREAMING_SNAKE_CASE__       )},
                      {"score": ANY(SCREAMING_SNAKE_CASE__       ), "label": ANY(SCREAMING_SNAKE_CASE__       )},
                  ]       ,     )


    @require_torch
    def        a				(	self					:					Dict       )				->	Optional[Any]:
         lowerCAmelCase__          =			"hf-internal-testing/tiny-random-VideoMAEForVideoClassification"
         lowerCAmelCase__          =			VideoMAEFeatureExtractor(
             size={"shortest_edge": 10}       ,     crop_size={"height": 10, "width": 10}       )
         lowerCAmelCase__          =			pipeline(
             "video-classification"       ,     model=SCREAMING_SNAKE_CASE__       ,     feature_extractor=SCREAMING_SNAKE_CASE__       ,     frame_sampling_rate=4       )

         lowerCAmelCase__          =			hf_hub_download(repo_id="nateraw/video-demo"       ,     filename="archery.mp4"       ,     repo_type="dataset"       )
         lowerCAmelCase__          =			video_classifier(SCREAMING_SNAKE_CASE__       ,     top_k=2       )
         self.assertEqual(
             nested_simplify(SCREAMING_SNAKE_CASE__       ,     decimals=4       )       ,     [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}]       ,     )

         lowerCAmelCase__          =			video_classifier(
             [
                 video_file_path,
                 video_file_path,
             ]       ,     top_k=2       ,     )
         self.assertEqual(
             nested_simplify(SCREAMING_SNAKE_CASE__       ,     decimals=4       )       ,     [
                 [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}],
                 [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}],
             ]       ,     )


    @require_tf
    def        a				(	self					:					Optional[Any]       )				->	Optional[int]:
         pass
