





import unittest

from transformers import (
    MODEL_FOR_OBJECT_DETECTION_MAPPING,
    AutoFeatureExtractor,
    AutoModelForObjectDetection,
    ObjectDetectionPipeline,
    is_vision_available,
    pipeline,
)
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_pytesseract,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
    from PIL import Image
else:







    class __a :





       @staticmethod
       def      UpperCAmelCase__     (					*lowerCamelCase				:			int				,**lowerCamelCase				:			List[str]    ):

          '''simple docstring'''

          pass







@is_pipeline_test
@require_vision
@require_timm
@require_torch
class __a (   unittest.TestCase			):
   __UpperCamelCase   : Tuple	      =	MODEL_FOR_OBJECT_DETECTION_MAPPING





   def      UpperCAmelCase__     (					self				:			Optional[int]				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			int    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       ObjectDetectionPipeline(model=_A				,image_processor=_A    )
      return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]





   def      UpperCAmelCase__     (					self				:			List[str]				,lowerCamelCase				:			List[Any]				,lowerCamelCase				:			str    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png"""				,threshold=0.0    )

      self.assertGreater(len(_A    )				,0    )
      for detected_object in outputs:
         self.assertEqual(
             _A				,{
                 """score""": ANY(_A    ),
                 """label""": ANY(_A    ),
                 """box""": {"""xmin""": ANY(_A    ), """ymin""": ANY(_A    ), """xmax""": ANY(_A    ), """ymax""": ANY(_A    )},
             }				,)

      import datasets

      __SCREAMING_SNAKE_CASE      							=       datasets.load_dataset("""hf-internal-testing/fixtures_image_utils"""				,"""image"""				,split="""test"""    )

      __SCREAMING_SNAKE_CASE      							=       [
          Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    ),
          'http://images.cocodataset.org/val2017/000000039769.jpg',
          # RGBA
          dataset[0]['file'],
          # LA
          dataset[1]['file'],
          # L
          dataset[2]['file'],
      ]
      __SCREAMING_SNAKE_CASE      							=       object_detector(_A				,threshold=0.0    )

      self.assertEqual(len(_A    )				,len(_A    )    )
      for outputs in batch_outputs:
         self.assertGreater(len(_A    )				,0    )
         for detected_object in outputs:
            self.assertEqual(
                _A				,{
                    """score""": ANY(_A    ),
                    """label""": ANY(_A    ),
                    """box""": {"""xmin""": ANY(_A    ), """ymin""": ANY(_A    ), """xmax""": ANY(_A    ), """ymax""": ANY(_A    )},
                }				,)





   @require_tf
   @unittest.skip("""Object detection not implemented in TF"""    )
   def      UpperCAmelCase__     (					self				:			List[Any]    ):

      '''simple docstring'''

      pass





   @require_torch
   def      UpperCAmelCase__     (					self				:			int    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       'hf-internal-testing/tiny-detr-mobilenetsv3'

      __SCREAMING_SNAKE_CASE      							=       AutoModelForObjectDetection.from_pretrained(_A    )
      __SCREAMING_SNAKE_CASE      							=       AutoFeatureExtractor.from_pretrained(_A    )
      __SCREAMING_SNAKE_CASE      							=       ObjectDetectionPipeline(model=_A				,feature_extractor=_A    )

      __SCREAMING_SNAKE_CASE      							=       object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg"""				,threshold=0.0    )

      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
              {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
          ]				,)

      __SCREAMING_SNAKE_CASE      							=       object_detector(
          [
              """http://images.cocodataset.org/val2017/000000039769.jpg""",
              """http://images.cocodataset.org/val2017/000000039769.jpg""",
          ]				,threshold=0.0				,)

      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              [
                  {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
                  {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
              ],
              [
                  {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
                  {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
              ],
          ]				,)





   @require_torch
   @slow
   def      UpperCAmelCase__     (					self				:			Optional[int]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       'facebook/detr-resnet-50'

      __SCREAMING_SNAKE_CASE      							=       AutoModelForObjectDetection.from_pretrained(_A    )
      __SCREAMING_SNAKE_CASE      							=       AutoFeatureExtractor.from_pretrained(_A    )
      __SCREAMING_SNAKE_CASE      							=       ObjectDetectionPipeline(model=_A				,feature_extractor=_A    )

      __SCREAMING_SNAKE_CASE      							=       object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
              {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
              {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
              {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
              {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
          ]				,)

      __SCREAMING_SNAKE_CASE      							=       object_detector(
          [
              """http://images.cocodataset.org/val2017/000000039769.jpg""",
              """http://images.cocodataset.org/val2017/000000039769.jpg""",
          ]    )
      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              [
                  {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
                  {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
                  {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
                  {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
                  {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
              ],
              [
                  {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
                  {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
                  {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
                  {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
                  {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
              ],
          ]				,)





   @require_torch
   @slow
   def      UpperCAmelCase__     (					self				:			int    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       'facebook/detr-resnet-50'

      __SCREAMING_SNAKE_CASE      							=       pipeline("""object-detection"""				,model=_A    )

      __SCREAMING_SNAKE_CASE      							=       object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
              {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
              {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
              {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
              {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
          ]				,)

      __SCREAMING_SNAKE_CASE      							=       object_detector(
          [
              """http://images.cocodataset.org/val2017/000000039769.jpg""",
              """http://images.cocodataset.org/val2017/000000039769.jpg""",
          ]    )
      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              [
                  {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
                  {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
                  {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
                  {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
                  {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
              ],
              [
                  {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
                  {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
                  {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
                  {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
                  {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
              ],
          ]				,)





   @require_torch
   @slow
   def      UpperCAmelCase__     (					self				:			Optional[int]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       0.9_985
      __SCREAMING_SNAKE_CASE      							=       'facebook/detr-resnet-50'

      __SCREAMING_SNAKE_CASE      							=       pipeline("""object-detection"""				,model=_A    )

      __SCREAMING_SNAKE_CASE      							=       object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg"""				,threshold=_A    )
      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
              {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
          ]				,)





   @require_torch
   @require_pytesseract
   @slow
   def      UpperCAmelCase__     (					self				:			Any    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       'Narsil/layoutlmv3-finetuned-funsd'
      __SCREAMING_SNAKE_CASE      							=       0.9_993

      __SCREAMING_SNAKE_CASE      							=       pipeline("""object-detection"""				,model=_A				,threshold=_A    )

      __SCREAMING_SNAKE_CASE      							=       object_detector(
          """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png"""    )
      self.assertEqual(
          nested_simplify(_A				,decimals=4    )				,[
              {"""score""": 0.9_993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}},
              {"""score""": 0.9_993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}},
          ]				,)












'''simple docstring'''

import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

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


if is_flax_available():
    import jax

    from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel







class __a (   unittest.TestCase			):





   def __init__(					self				:			Optional[int]				,lowerCamelCase				:			str				,lowerCamelCase				:			List[str]=13				,lowerCamelCase				:			Optional[Any]=30				,lowerCamelCase				:			Dict=2				,lowerCamelCase				:			List[Any]=3				,lowerCamelCase				:			List[str]=True				,lowerCamelCase				:			str=True				,lowerCamelCase				:			Optional[int]=32				,lowerCamelCase				:			Dict=5				,lowerCamelCase				:			Optional[int]=4				,lowerCamelCase				:			List[Any]=37				,lowerCamelCase				:			Union[str, Any]="gelu"				,lowerCamelCase				:			List[Any]=0.1				,lowerCamelCase				:			Any=0.1				,lowerCamelCase				:			str=10				,lowerCamelCase				:			Dict=0.02				,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       parent
      __SCREAMING_SNAKE_CASE      							=       batch_size
      __SCREAMING_SNAKE_CASE      							=       image_size
      __SCREAMING_SNAKE_CASE      							=       patch_size
      __SCREAMING_SNAKE_CASE      							=       num_channels
      __SCREAMING_SNAKE_CASE      							=       is_training
      __SCREAMING_SNAKE_CASE      							=       use_labels
      __SCREAMING_SNAKE_CASE      							=       hidden_size
      __SCREAMING_SNAKE_CASE      							=       num_hidden_layers
      __SCREAMING_SNAKE_CASE      							=       num_attention_heads
      __SCREAMING_SNAKE_CASE      							=       intermediate_size
      __SCREAMING_SNAKE_CASE      							=       hidden_act
      __SCREAMING_SNAKE_CASE      							=       hidden_dropout_prob
      __SCREAMING_SNAKE_CASE      							=       attention_probs_dropout_prob
      __SCREAMING_SNAKE_CASE      							=       type_sequence_label_size
      __SCREAMING_SNAKE_CASE      							=       initializer_range

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





   def      UpperCAmelCase__     (					self				:			List[Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

      __SCREAMING_SNAKE_CASE      							=       ViTConfig(
          image_size=self.image_size				,patch_size=self.patch_size				,num_channels=self.num_channels				,hidden_size=self.hidden_size				,num_hidden_layers=self.num_hidden_layers				,num_attention_heads=self.num_attention_heads				,intermediate_size=self.intermediate_size				,hidden_act=self.hidden_act				,hidden_dropout_prob=self.hidden_dropout_prob				,attention_probs_dropout_prob=self.attention_probs_dropout_prob				,is_decoder=lowerCamelCase				,initializer_range=self.initializer_range				,)

      return config, pixel_values





   def      UpperCAmelCase__     (					self				:			Tuple				,lowerCamelCase				:			int				,lowerCamelCase				:			Optional[Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       FlaxViTModel(config=lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       model(lowerCamelCase    )
      # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
      __SCREAMING_SNAKE_CASE      							=       (self.image_size, self.image_size)
      __SCREAMING_SNAKE_CASE      							=       (self.patch_size, self.patch_size)
      __SCREAMING_SNAKE_CASE      							=       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
      self.parent.assertEqual(result.last_hidden_state.shape				,(self.batch_size, num_patches + 1, self.hidden_size)    )





   def      UpperCAmelCase__     (					self				:			Union[str, Any]				,lowerCamelCase				:			Optional[int]				,lowerCamelCase				:			Dict    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.type_sequence_label_size
      __SCREAMING_SNAKE_CASE      							=       FlaxViTForImageClassification(config=lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       model(lowerCamelCase    )
      self.parent.assertEqual(result.logits.shape				,(self.batch_size, self.type_sequence_label_size)    )

      # test greyscale images
      __SCREAMING_SNAKE_CASE      							=       1
      __SCREAMING_SNAKE_CASE      							=       FlaxViTForImageClassification(lowerCamelCase    )

      __SCREAMING_SNAKE_CASE      							=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
      __SCREAMING_SNAKE_CASE      							=       model(lowerCamelCase    )





   def      UpperCAmelCase__     (					self				:			int    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.prepare_config_and_inputs()
      (
          (
          __SCREAMING_SNAKE_CASE
      )							,     (
          __SCREAMING_SNAKE_CASE
      )							,     
      )      							=       config_and_inputs
      __SCREAMING_SNAKE_CASE      							=       {"""pixel_values""": pixel_values}
      return config, inputs_dict







@require_flax
class __a (   _snake_case,   unittest.TestCase			):
   __UpperCamelCase   : Any	      =	(FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()





   def      UpperCAmelCase__     (					self				:			Union[str, Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       FlaxViTModelTester(self    )
      __SCREAMING_SNAKE_CASE      							=       ConfigTester(self				,config_class=lowerCamelCase				,has_text_modality=lowerCamelCase				,hidden_size=37    )





   def      UpperCAmelCase__     (					self				:			Tuple    ):

      '''simple docstring'''

      self.config_tester.run_common_tests()





   def      UpperCAmelCase__     (					self				:			List[str]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase    )





   def      UpperCAmelCase__     (					self				:			List[Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowerCamelCase    )





   def      UpperCAmelCase__     (					self				:			List[Any]    ):

      '''simple docstring'''

      __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(lowerCamelCase    )
         __SCREAMING_SNAKE_CASE      							=       inspect.signature(model.__call__    )
         # 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]				,lowerCamelCase    )





   def      UpperCAmelCase__     (					self				:			Optional[int]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         with self.subTest(model_class.__name__    ):
            __SCREAMING_SNAKE_CASE      							=       self._prepare_for_class(lowerCamelCase				,lowerCamelCase    )
            __SCREAMING_SNAKE_CASE      							=       model_class(lowerCamelCase    )

            @jax.jit
            def model_jitted(lowerCamelCase				:			int				,**lowerCamelCase				:			Union[str, Any]    ):
               return model(pixel_values=lowerCamelCase				,**lowerCamelCase    )

            with self.subTest("""JIT Enabled"""    ):
               __SCREAMING_SNAKE_CASE      							=       model_jitted(**lowerCamelCase    ).to_tuple()

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

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





   @slow
   def      UpperCAmelCase__     (					self				:			Optional[Any]    ):

      '''simple docstring'''

      for model_class_name in self.all_model_classes:
         __SCREAMING_SNAKE_CASE      							=       model_class_name.from_pretrained("""google/vit-base-patch16-224"""    )
         __SCREAMING_SNAKE_CASE      							=       model(np.ones((1, 3, 224, 224)    )    )
         self.assertIsNotNone(lowerCamelCase    )





