





'''simple docstring'''




from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
      TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
      TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
      TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
      LayoutLMvaConfig,
      TFLayoutLMvaForQuestionAnswering,
      TFLayoutLMvaForSequenceClassification,
      TFLayoutLMvaForTokenClassification,
      TFLayoutLMvaModel,
  )

if is_vision_available():
  from PIL import Image

  from transformers import LayoutLMvaImageProcessor


class  SCREAMING_SNAKE_CASE    :


     def __init__(						self						,	_UpperCAmelCase						,	_UpperCAmelCase=2						,	_UpperCAmelCase=3						,	_UpperCAmelCase=4						,	_UpperCAmelCase=2						,	_UpperCAmelCase=7						,	_UpperCAmelCase=True						,	_UpperCAmelCase=True						,	_UpperCAmelCase=True						,	_UpperCAmelCase=True						,	_UpperCAmelCase=99						,	_UpperCAmelCase=36						,	_UpperCAmelCase=2						,	_UpperCAmelCase=4						,	_UpperCAmelCase=37						,	_UpperCAmelCase="gelu"						,	_UpperCAmelCase=0.1						,	_UpperCAmelCase=0.1						,	_UpperCAmelCase=512						,	_UpperCAmelCase=16						,	_UpperCAmelCase=2						,	_UpperCAmelCase=0.02						,	_UpperCAmelCase=6						,	_UpperCAmelCase=6						,	_UpperCAmelCase=3						,	_UpperCAmelCase=4						,	_UpperCAmelCase=None						,	_UpperCAmelCase=1000						,	):

          '''simple docstring'''






          __A						: List[Any]      =       parent
          __A						: Optional[Any]      =       batch_size
          __A						: Tuple      =       num_channels
          __A						: Union[str, Any]      =       image_size
          __A						: Optional[Any]      =       patch_size
          __A						: Optional[Any]      =       is_training
          __A						: Optional[int]      =       use_input_mask
          __A						: Tuple      =       use_token_type_ids
          __A						: str      =       use_labels
          __A						: str      =       vocab_size
          __A						: Optional[int]      =       hidden_size
          __A						: List[Any]      =       num_hidden_layers
          __A						: Dict      =       num_attention_heads
          __A						: List[Any]      =       intermediate_size
          __A						: Optional[int]      =       hidden_act
          __A						: List[Any]      =       hidden_dropout_prob
          __A						: Union[str, Any]      =       attention_probs_dropout_prob
          __A						: Optional[Any]      =       max_position_embeddings
          __A						: Any      =       type_vocab_size
          __A						: Any      =       type_sequence_label_size
          __A						: Any      =       initializer_range
          __A						: Tuple      =       coordinate_size
          __A						: List[str]      =       shape_size
          __A						: Dict      =       num_labels
          __A						: Tuple      =       num_choices
          __A						: List[Any]      =       scope
          __A						: Dict      =       range_bbox

          # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
          __A						: Optional[int]      =       text_seq_length
          __A						: str      =       (image_size // patch_size) ** 2 + 1
          __A						: Dict      =       self.text_seq_length + self.image_seq_length


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[int]      =       ids_tensor([self.batch_size, self.text_seq_length]						,	self.vocab_size)

          __A						: str      =       ids_tensor([self.batch_size, self.text_seq_length, 4]						,	self.range_bbox)
          __A						: Optional[int]      =       bbox.numpy()
          # Ensure that bbox is legal
          for i in range(bbox.shape[0]):
               for j in range(bbox.shape[1]):
                    if bbox[i, j, 3] < bbox[i, j, 1]:
                         __A						: int      =       bbox[i, j, 3]
                         __A						: List[Any]      =       bbox[i, j, 1]
                         __A						: List[str]      =       tmp_coordinate
                    if bbox[i, j, 2] < bbox[i, j, 0]:
                         __A						: str      =       bbox[i, j, 2]
                         __A						: Dict      =       bbox[i, j, 0]
                         __A						: List[Any]      =       tmp_coordinate
          __A						: str      =       tf.constant(_UpperCAmelCase)

          __A						: Dict      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          __A						: Union[str, Any]      =       None
          if self.use_input_mask:
               __A						: Optional[Any]      =       random_attention_mask([self.batch_size, self.text_seq_length])

          __A						: int      =       None
          if self.use_token_type_ids:
               __A						: List[str]      =       ids_tensor([self.batch_size, self.text_seq_length]						,	self.type_vocab_size)

          __A						: Optional[int]      =       None
          __A						: Optional[int]      =       None
          if self.use_labels:
               __A						: str      =       ids_tensor([self.batch_size]						,	self.type_sequence_label_size)
               __A						: Tuple      =       ids_tensor([self.batch_size, self.text_seq_length]						,	self.num_labels)

          __A						: Any      =       LayoutLMvaConfig(
              vocab_size=self.vocab_size						,	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						,	max_position_embeddings=self.max_position_embeddings						,	type_vocab_size=self.type_vocab_size						,	initializer_range=self.initializer_range						,	coordinate_size=self.coordinate_size						,	shape_size=self.shape_size						,	input_size=self.image_size						,	patch_size=self.patch_size						,	)

          return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels


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

          '''simple docstring'''






          __A						: int      =       TFLayoutLMvaModel(config=_UpperCAmelCase)

          # text + image
          __A						: Dict      =       model(_UpperCAmelCase						,	pixel_values=_UpperCAmelCase						,	training=_UpperCAmelCase)
          __A						: List[Any]      =       model(
              _UpperCAmelCase						,	bbox=_UpperCAmelCase						,	pixel_values=_UpperCAmelCase						,	attention_mask=_UpperCAmelCase						,	token_type_ids=_UpperCAmelCase						,	training=_UpperCAmelCase						,	)
          __A						: Optional[int]      =       model(_UpperCAmelCase						,	bbox=_UpperCAmelCase						,	pixel_values=_UpperCAmelCase						,	training=_UpperCAmelCase)

          self.parent.assertEqual(result.last_hidden_state.shape						,	(self.batch_size, self.seq_length, self.hidden_size))

          # text only
          __A						: Optional[Any]      =       model(_UpperCAmelCase						,	training=_UpperCAmelCase)
          self.parent.assertEqual(
              result.last_hidden_state.shape						,	(self.batch_size, self.text_seq_length, self.hidden_size))

          # image only
          __A						: int      =       model({'pixel_values': pixel_values}						,	training=_UpperCAmelCase)
          self.parent.assertEqual(
              result.last_hidden_state.shape						,	(self.batch_size, self.image_seq_length, self.hidden_size))


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

          '''simple docstring'''






          __A						: List[Any]      =       self.num_labels
          __A						: int      =       TFLayoutLMvaForSequenceClassification(config=_UpperCAmelCase)
          __A						: Any      =       model(
              _UpperCAmelCase						,	bbox=_UpperCAmelCase						,	pixel_values=_UpperCAmelCase						,	attention_mask=_UpperCAmelCase						,	token_type_ids=_UpperCAmelCase						,	labels=_UpperCAmelCase						,	training=_UpperCAmelCase						,	)
          self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.num_labels))


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

          '''simple docstring'''






          __A						: List[str]      =       self.num_labels
          __A						: List[str]      =       TFLayoutLMvaForTokenClassification(config=_UpperCAmelCase)
          __A						: str      =       model(
              _UpperCAmelCase						,	bbox=_UpperCAmelCase						,	pixel_values=_UpperCAmelCase						,	attention_mask=_UpperCAmelCase						,	token_type_ids=_UpperCAmelCase						,	labels=_UpperCAmelCase						,	training=_UpperCAmelCase						,	)
          self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.text_seq_length, self.num_labels))


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

          '''simple docstring'''






          __A						: Optional[Any]      =       2
          __A						: Optional[Any]      =       TFLayoutLMvaForQuestionAnswering(config=_UpperCAmelCase)
          __A						: List[str]      =       model(
              _UpperCAmelCase						,	bbox=_UpperCAmelCase						,	pixel_values=_UpperCAmelCase						,	attention_mask=_UpperCAmelCase						,	token_type_ids=_UpperCAmelCase						,	start_positions=_UpperCAmelCase						,	end_positions=_UpperCAmelCase						,	training=_UpperCAmelCase						,	)
          self.parent.assertEqual(result.start_logits.shape						,	(self.batch_size, self.seq_length))
          self.parent.assertEqual(result.end_logits.shape						,	(self.batch_size, self.seq_length))


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[Any]      =       self.prepare_config_and_inputs()
          ((__A) ,(__A) ,(__A) ,(__A) ,(__A) ,(__A) ,(__A) ,(__A))						: int      =       config_and_inputs
          __A						: str      =       {
              'input_ids': input_ids,
              'bbox': bbox,
              'pixel_values': pixel_values,
              'token_type_ids': token_type_ids,
              'attention_mask': input_mask,
          }
          return config, inputs_dict




@require_tf
class  SCREAMING_SNAKE_CASE    (a__					,		a__					,		unittest.TestCase							):
     lowerCAmelCase					=       (
         (
             TFLayoutLMvaModel,
             TFLayoutLMvaForQuestionAnswering,
             TFLayoutLMvaForSequenceClassification,
             TFLayoutLMvaForTokenClassification,
         )
         if is_tf_available()
         else ()
     )
     lowerCAmelCase					=       (
         {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel}
         if is_tf_available()
         else {}
     )

     lowerCAmelCase					=       False
     lowerCAmelCase					=       False
     lowerCAmelCase					=       False


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

          '''simple docstring'''






          return True


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

          '''simple docstring'''






          __A						: int      =       copy.deepcopy(_UpperCAmelCase)

          if model_class in get_values(_UpperCAmelCase):
               __A						: Dict      =       {
                   k: tf.tile(tf.expand_dims(_UpperCAmelCase						,	1)						,	(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1))
                   if isinstance(_UpperCAmelCase						,	tf.Tensor) and v.ndim > 0
                   else v
                   for k, v in inputs_dict.items()
               }

          if return_labels:
               if model_class in get_values(_UpperCAmelCase):
                    __A						: Tuple      =       tf.ones(self.model_tester.batch_size						,	dtype=tf.intaa)
               elif model_class in get_values(_UpperCAmelCase):
                    __A						: List[str]      =       tf.zeros(self.model_tester.batch_size						,	dtype=tf.intaa)
                    __A						: Optional[Any]      =       tf.zeros(self.model_tester.batch_size						,	dtype=tf.intaa)
               elif model_class in get_values(_UpperCAmelCase):
                    __A						: Optional[int]      =       tf.zeros(self.model_tester.batch_size						,	dtype=tf.intaa)
               elif model_class in get_values(_UpperCAmelCase):
                    __A						: Any      =       tf.zeros(
                        (self.model_tester.batch_size, self.model_tester.text_seq_length)						,	dtype=tf.intaa)

          return inputs_dict


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[Any]      =       TFLayoutLMvaModelTester(self)
          __A						: Optional[int]      =       ConfigTester(self						,	config_class=_UpperCAmelCase						,	hidden_size=37)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          self.config_tester.run_common_tests()


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A ,__A						: Dict      =       self.model_tester.prepare_config_and_inputs_for_common()
          for model_class in self.all_model_classes:
               __A						: Union[str, Any]      =       model_class(_UpperCAmelCase)
               if getattr(_UpperCAmelCase						,	'hf_compute_loss'						,	_UpperCAmelCase):
                    # The number of elements in the loss should be the same as the number of elements in the label
                    __A						: Any      =       self._prepare_for_class(inputs_dict.copy()						,	_UpperCAmelCase						,	return_labels=_UpperCAmelCase)
                    __A						: str      =       prepared_for_class[
                        sorted(prepared_for_class.keys() - inputs_dict.keys()						,	reverse=_UpperCAmelCase)[0]
                    ]
                    __A						: Any      =       added_label.shape.as_list()[:1]

                    # Test that model correctly compute the loss with kwargs
                    __A						: int      =       self._prepare_for_class(inputs_dict.copy()						,	_UpperCAmelCase						,	return_labels=_UpperCAmelCase)
                    __A						: Tuple      =       prepared_for_class.pop('input_ids')

                    __A						: Optional[int]      =       model(_UpperCAmelCase						,	**_UpperCAmelCase)[0]
                    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

                    # Test that model correctly compute the loss when we mask some positions
                    __A						: Union[str, Any]      =       self._prepare_for_class(inputs_dict.copy()						,	_UpperCAmelCase						,	return_labels=_UpperCAmelCase)
                    __A						: List[str]      =       prepared_for_class.pop('input_ids')
                    if "labels" in prepared_for_class:
                         __A						: List[Any]      =       prepared_for_class['labels'].numpy()
                         if len(labels.shape) > 1 and labels.shape[1] != 1:
                              __A						: int      =       -100
                              __A						: Optional[Any]      =       tf.convert_to_tensor(_UpperCAmelCase)
                              __A						: Dict      =       model(_UpperCAmelCase						,	**_UpperCAmelCase)[0]
                              self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
                              self.assertTrue(not np.any(np.isnan(loss.numpy())))

                # Test that model correctly compute the loss with a dict
                    __A						: List[str]      =       self._prepare_for_class(inputs_dict.copy()						,	_UpperCAmelCase						,	return_labels=_UpperCAmelCase)
                    __A						: Union[str, Any]      =       model(_UpperCAmelCase)[0]
                    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

                    # Test that model correctly compute the loss with a tuple
                    __A						: Dict      =       self._prepare_for_class(inputs_dict.copy()						,	_UpperCAmelCase						,	return_labels=_UpperCAmelCase)

                    # Get keys that were added with the _prepare_for_class function
                    __A						: Optional[Any]      =       prepared_for_class.keys() - inputs_dict.keys()
                    __A						: Any      =       inspect.signature(model.call).parameters
                    __A						: int      =       list(signature.keys())

                    # Create a dictionary holding the location of the tensors in the tuple
                    __A						: str      =       {0: 'input_ids'}
                    for label_key in label_keys:
                         __A						: Optional[Any]      =       signature_names.index(_UpperCAmelCase)
                         __A						: List[str]      =       label_key
                    __A						: int      =       sorted(tuple_index_mapping.items())
                    # Initialize a list with their default values, update the values and convert to a tuple
                    __A						: List[str]      =       []

                    for name in signature_names:
                         if name != "kwargs":
                              list_input.append(signature[name].default)

                    for index, value in sorted_tuple_index_mapping:
                         __A						: Optional[int]      =       prepared_for_class[value]

                    __A						: Optional[Any]      =       tuple(_UpperCAmelCase)

                    # Send to model
                    __A						: Dict      =       model(tuple_input[:-1])[0]

                    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          (
              (
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,
          )						: List[str]      =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          (
              (
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,
          )						: Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
          for type in ["absolute", "relative_key", "relative_key_query"]:
               __A						: Tuple      =       type
               self.model_tester.create_and_check_model(_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          (
              (
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,
          )						: str      =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_sequence_classification(
              _UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          (
              (
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,
          )						: Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(
              _UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          (
              (
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,(
              __A
          ) ,
          )						: Optional[int]      =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_question_answering(
              _UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase)


     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __A						: str      =       TFLayoutLMvaModel.from_pretrained(_UpperCAmelCase)
               self.assertIsNotNone(_UpperCAmelCase)






def        _lowerCAmelCase			(  )     ->     Dict:
     __A						: Tuple      =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     return image







@require_tf
class  SCREAMING_SNAKE_CASE    (unittest.TestCase							):


     @cached_property
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          return LayoutLMvaImageProcessor(apply_ocr=_UpperCAmelCase) if is_vision_available() else None


     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Dict      =       TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base')

          __A						: str      =       self.default_image_processor
          __A						: Tuple      =       prepare_img()
          __A						: Dict      =       image_processor(images=_UpperCAmelCase						,	return_tensors='tf').pixel_values

          __A						: str      =       tf.constant([[1, 2]])
          __A						: Dict      =       tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]])						,	axis=0)

          # forward pass
          __A						: Union[str, Any]      =       model(input_ids=_UpperCAmelCase						,	bbox=_UpperCAmelCase						,	pixel_values=_UpperCAmelCase						,	training=_UpperCAmelCase)

          # verify the logits
          __A						: Optional[Any]      =       (1, 199, 768)
          self.assertEqual(outputs.last_hidden_state.shape						,	_UpperCAmelCase)

          __A						: Union[str, Any]      =       tf.constant(
              [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]])

          self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]						,	_UpperCAmelCase						,	atol=1e-4))






'''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},
              ]						,	)