



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 						snake_case  :



     '''simple docstring'''






     @staticmethod
     def    UpperCamelCase_     (    *lowerCAmelCase							:	Dict ,						**lowerCAmelCase							:	List[str]) -> List[Any]:

      """simple docstring"""







      pass







@is_pipeline_test
@require_vision
@require_timm
@require_torch
class 						snake_case  (		unittest.TestCase     ):



   '''simple docstring'''






   snake_case_    :       List[Any]								=						MODEL_FOR_OBJECT_DETECTION_MAPPING

   def    UpperCamelCase_     (    self							:	Tuple ,						lowerCAmelCase							:	Optional[int] ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	Dict) -> int:

    """simple docstring"""







    _snake_case			:     Dict 		=    ObjectDetectionPipeline(model=_UpperCAmelCase ,						image_processor=_UpperCAmelCase)
    return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]

   def    UpperCamelCase_     (    self							:	Tuple ,						lowerCAmelCase							:	Optional[int] ,						lowerCAmelCase							:	Any) -> Dict:

    """simple docstring"""







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

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

    import datasets

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

    _snake_case			:     List[str] 		=    [
        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'],
    ]
    _snake_case			:     Union[str, Any] 		=    object_detector(_UpperCAmelCase ,						threshold=0.0)

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

   @require_tf
   @unittest.skip("""Object detection not implemented in TF""")
   def    UpperCamelCase_     (    self							:	Union[str, Any]) -> Tuple:

    """simple docstring"""







    pass

   @require_torch
   def    UpperCamelCase_     (    self							:	Optional[Any]) -> str:

    """simple docstring"""







    _snake_case			:     List[str] 		=    'hf-internal-testing/tiny-detr-mobilenetsv3'

    _snake_case			:     Any 		=    AutoModelForObjectDetection.from_pretrained(_UpperCAmelCase)
    _snake_case			:     int 		=    AutoFeatureExtractor.from_pretrained(_UpperCAmelCase)
    _snake_case			:     Any 		=    ObjectDetectionPipeline(model=_UpperCAmelCase ,						feature_extractor=_UpperCAmelCase)

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

    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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}},
        ] ,						)

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

    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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							:	int) -> Tuple:

    """simple docstring"""







    _snake_case			:     Optional[Any] 		=    'facebook/detr-resnet-50'

    _snake_case			:     Union[str, Any] 		=    AutoModelForObjectDetection.from_pretrained(_UpperCAmelCase)
    _snake_case			:     Tuple 		=    AutoFeatureExtractor.from_pretrained(_UpperCAmelCase)
    _snake_case			:     List[Any] 		=    ObjectDetectionPipeline(model=_UpperCAmelCase ,						feature_extractor=_UpperCAmelCase)

    _snake_case			:     Union[str, Any] 		=    object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""")
    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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}},
        ] ,						)

    _snake_case			:     Tuple 		=    object_detector(
        [
            """http://images.cocodataset.org/val2017/000000039769.jpg""",
            """http://images.cocodataset.org/val2017/000000039769.jpg""",
        ])
    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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[Any]) -> Union[str, Any]:

    """simple docstring"""







    _snake_case			:     List[Any] 		=    'facebook/detr-resnet-50'

    _snake_case			:     str 		=    pipeline("""object-detection""" ,						model=_UpperCAmelCase)

    _snake_case			:     Any 		=    object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""")
    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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}},
        ] ,						)

    _snake_case			:     str 		=    object_detector(
        [
            """http://images.cocodataset.org/val2017/000000039769.jpg""",
            """http://images.cocodataset.org/val2017/000000039769.jpg""",
        ])
    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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							:	Any) -> Any:

    """simple docstring"""







    _snake_case			:     List[Any] 		=    0.9_985
    _snake_case			:     List[Any] 		=    'facebook/detr-resnet-50'

    _snake_case			:     List[str] 		=    pipeline("""object-detection""" ,						model=_UpperCAmelCase)

    _snake_case			:     List[Any] 		=    object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ,						threshold=_UpperCAmelCase)
    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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							:	Optional[Any]) -> Tuple:

    """simple docstring"""







    _snake_case			:     Optional[int] 		=    'Narsil/layoutlmv3-finetuned-funsd'
    _snake_case			:     Tuple 		=    0.9_993

    _snake_case			:     str 		=    pipeline("""object-detection""" ,						model=_UpperCAmelCase ,						threshold=_UpperCAmelCase)

    _snake_case			:     Optional[int] 		=    object_detector(
        """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""")
    self.assertEqual(
        nested_simplify(_UpperCAmelCase ,						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 hashlib
import unittest
from typing import Dict

import numpy as np

from transformers import (
    MODEL_FOR_MASK_GENERATION_MAPPING,
    TF_MODEL_FOR_MASK_GENERATION_MAPPING,
    is_vision_available,
    pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)


if is_vision_available():
  from PIL import Image
else:


  class  SCREAMING_SNAKE_CASE    :


       @staticmethod
       def 							SCREAMING_SNAKE_CASE  (						*_UpperCAmelCase						,	**_UpperCAmelCase):

            '''simple docstring'''






            pass






def        _lowerCAmelCase			(  __snake_case  : Image			)     ->     str:
     __A						: Dict      =       hashlib.mda(image.tobytes()			)
     return m.hexdigest()[:10]






def        _lowerCAmelCase			(  __snake_case  : Image			)     ->     Dict:
     __A						: Dict      =       np.array(__snake_case			)
     __A						: List[Any]      =       npimg.shape
     return {"hash": hashimage(__snake_case			), "shape": shape}







@is_pipeline_test
@require_vision
@require_torch
class  SCREAMING_SNAKE_CASE    (unittest.TestCase							):
     lowerCAmelCase					=       dict(
         (list(MODEL_FOR_MASK_GENERATION_MAPPING.items()							) if MODEL_FOR_MASK_GENERATION_MAPPING else [])							)
     lowerCAmelCase					=       dict(
         (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items()							) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else [])							)


     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          __A						: Any      =       MaskGenerationPipeline(model=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)
          return image_segmenter, [
              "./tests/fixtures/tests_samples/COCO/000000039769.png",
              "./tests/fixtures/tests_samples/COCO/000000039769.png",
          ]


     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          pass


     @require_tf
     @unittest.skip('Image segmentation not implemented in TF')
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          pass


     @slow
     @require_torch
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[int]      =       pipeline('mask-generation'						,	model='facebook/sam-vit-huge')

          __A						: Tuple      =       image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg'						,	points_per_batch=256)

          # Shortening by hashing
          __A						: int      =       []
          for i, o in enumerate(outputs['masks']):
               new_outupt += [{"mask": mask_to_test_readable(_UpperCAmelCase), "scores": outputs["scores"][i]}]

          # fmt: off
          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0444},
                  {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.021},
                  {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0167},
                  {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0132},
                  {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0053},
                  {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9967},
                  {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.993},
                  {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9909},
                  {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9879},
                  {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9834},
                  {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9716},
                  {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9612},
                  {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9599},
                  {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9552},
                  {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9532},
                  {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9516},
                  {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9499},
                  {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9483},
                  {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9464},
                  {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.943},
                  {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.943},
                  {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9408},
                  {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9335},
                  {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9326},
                  {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9262},
                  {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8999},
                  {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8986},
                  {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8984},
                  {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8873},
                  {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8871}
              ]						,	)
          # fmt: on


     @require_torch
     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: int      =       'facebook/sam-vit-huge'
          __A						: Optional[Any]      =       pipeline('mask-generation'						,	model=_UpperCAmelCase)

          __A						: int      =       image_segmenter(
              'http://images.cocodataset.org/val2017/000000039769.jpg'						,	pred_iou_thresh=1						,	points_per_batch=256)

          # Shortening by hashing
          __A						: int      =       []
          for i, o in enumerate(outputs['masks']):
               new_outupt += [{"mask": mask_to_test_readable(_UpperCAmelCase), "scores": outputs["scores"][i]}]

          self.assertEqual(
              nested_simplify(_UpperCAmelCase						,	decimals=4)						,	[
                  {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0444},
                  {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0210},
                  {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0167},
                  {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0132},
                  {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0053},
              ]						,	)