





'''simple docstring'''


import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
    from PIL import Image

    from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
    import torch

if is_tf_available():
    import tensorflow as tf






@require_vision
@require_torchvision
class     lowerCAmelCase__ (				unittest.TestCase    ):

       '''simple docstring'''

       def 			__snake_case      ( self					:				int						):
              UpperCAmelCase  =						tempfile.mkdtemp()
              UpperCAmelCase  =						SamImageProcessor()
              UpperCAmelCase  =						SamProcessor(a__						)
              processor.save_pretrained(self.tmpdirname						)

       def 			__snake_case      ( self					:				str       ,     **a__					:				Any						):
              return AutoProcessor.from_pretrained(self.tmpdirname       ,     **a__						).image_processor

       def 			__snake_case      ( self					:				Tuple						):
              shutil.rmtree(self.tmpdirname						)

       def 			__snake_case      ( self					:				Any						):
              UpperCAmelCase  =						[np.random.randint(255       ,     size=(3, 30, 400)       ,     dtype=np.uinta						)]

              UpperCAmelCase  =						[Image.fromarray(np.moveaxis(a__       ,     0       ,     -1						)						) for x in image_inputs]

              return image_inputs

       def 			__snake_case      ( self					:				Tuple						):
              UpperCAmelCase  =						SamProcessor(image_processor=self.get_image_processor()						)
              processor.save_pretrained(self.tmpdirname						)

              UpperCAmelCase  =						self.get_image_processor(do_normalize=a__       ,     padding_value=1.0						)

              UpperCAmelCase  =						SamProcessor.from_pretrained(self.tmpdirname       ,     do_normalize=a__       ,     padding_value=1.0						)

              self.assertEqual(processor.image_processor.to_json_string()       ,     image_processor_add_kwargs.to_json_string()						)
              self.assertIsInstance(processor.image_processor       ,     a__						)

       def 			__snake_case      ( self					:				List[str]						):
              UpperCAmelCase  =						self.get_image_processor()

              UpperCAmelCase  =						SamProcessor(image_processor=a__						)

              UpperCAmelCase  =						self.prepare_image_inputs()

              UpperCAmelCase  =						image_processor(a__       ,     return_tensors='''np'''						)
              UpperCAmelCase  =						processor(images=a__       ,     return_tensors='''np'''						)

              input_feat_extract.pop('''original_sizes'''						)  # pop original_sizes as it is popped in the processor
              input_feat_extract.pop('''reshaped_input_sizes'''						)  # pop original_sizes as it is popped in the processor

              for key in input_feat_extract.keys():
                     self.assertAlmostEqual(input_feat_extract[key].sum()       ,     input_processor[key].sum()       ,     delta=1e-2						)



       @require_torch
       def 			__snake_case      ( self					:				Any						):
              UpperCAmelCase  =						self.get_image_processor()

              UpperCAmelCase  =						SamProcessor(image_processor=a__						)
              UpperCAmelCase  =						[torch.ones((1, 3, 5, 5)						)]

              UpperCAmelCase  =						[[1764, 2646]]

              UpperCAmelCase  =						[[683, 1024]]
              UpperCAmelCase  =						processor.post_process_masks(a__       ,     a__       ,     a__						)
              self.assertEqual(masks[0].shape       ,     (1, 3, 1764, 2646)						)

              UpperCAmelCase  =						processor.post_process_masks(
                  a__       ,     torch.tensor(a__						)       ,     torch.tensor(a__						)						)
              self.assertEqual(masks[0].shape       ,     (1, 3, 1764, 2646)						)

              # should also work with np
              UpperCAmelCase  =						[np.ones((1, 3, 5, 5)						)]
              UpperCAmelCase  =						processor.post_process_masks(a__       ,     np.array(a__						)       ,     np.array(a__						)						)

              self.assertEqual(masks[0].shape       ,     (1, 3, 1764, 2646)						)

              UpperCAmelCase  =						[[1, 0], [0, 1]]
              with self.assertRaises(a__						):
                     UpperCAmelCase  =						processor.post_process_masks(a__       ,     np.array(a__						)       ,     np.array(a__						)						)






@require_vision
@require_tf
class     lowerCAmelCase__ (				unittest.TestCase    ):

       '''simple docstring'''

       def 			__snake_case      ( self					:				List[str]						):
              UpperCAmelCase  =						tempfile.mkdtemp()
              UpperCAmelCase  =						SamImageProcessor()
              UpperCAmelCase  =						SamProcessor(a__						)
              processor.save_pretrained(self.tmpdirname						)

       def 			__snake_case      ( self					:				Optional[int]       ,     **a__					:				Any						):
              return AutoProcessor.from_pretrained(self.tmpdirname       ,     **a__						).image_processor

       def 			__snake_case      ( self					:				int						):
              shutil.rmtree(self.tmpdirname						)

       def 			__snake_case      ( self					:				int						):
              UpperCAmelCase  =						[np.random.randint(255       ,     size=(3, 30, 400)       ,     dtype=np.uinta						)]

              UpperCAmelCase  =						[Image.fromarray(np.moveaxis(a__       ,     0       ,     -1						)						) for x in image_inputs]

              return image_inputs

       def 			__snake_case      ( self					:				str						):
              UpperCAmelCase  =						SamProcessor(image_processor=self.get_image_processor()						)
              processor.save_pretrained(self.tmpdirname						)

              UpperCAmelCase  =						self.get_image_processor(do_normalize=a__       ,     padding_value=1.0						)

              UpperCAmelCase  =						SamProcessor.from_pretrained(self.tmpdirname       ,     do_normalize=a__       ,     padding_value=1.0						)

              self.assertEqual(processor.image_processor.to_json_string()       ,     image_processor_add_kwargs.to_json_string()						)
              self.assertIsInstance(processor.image_processor       ,     a__						)

       def 			__snake_case      ( self					:				Optional[int]						):
              UpperCAmelCase  =						self.get_image_processor()

              UpperCAmelCase  =						SamProcessor(image_processor=a__						)

              UpperCAmelCase  =						self.prepare_image_inputs()

              UpperCAmelCase  =						image_processor(a__       ,     return_tensors='''np'''						)
              UpperCAmelCase  =						processor(images=a__       ,     return_tensors='''np'''						)

              input_feat_extract.pop('''original_sizes'''						)  # pop original_sizes as it is popped in the processor
              input_feat_extract.pop('''reshaped_input_sizes'''						)  # pop reshaped_input_sizes as it is popped in the processor

              for key in input_feat_extract.keys():
                     self.assertAlmostEqual(input_feat_extract[key].sum()       ,     input_processor[key].sum()       ,     delta=1e-2						)



       @require_tf
       def 			__snake_case      ( self					:				Union[str, Any]						):
              UpperCAmelCase  =						self.get_image_processor()

              UpperCAmelCase  =						SamProcessor(image_processor=a__						)
              UpperCAmelCase  =						[tf.ones((1, 3, 5, 5)						)]

              UpperCAmelCase  =						[[1764, 2646]]

              UpperCAmelCase  =						[[683, 1024]]
              UpperCAmelCase  =						processor.post_process_masks(a__       ,     a__       ,     a__       ,     return_tensors='''tf'''						)
              self.assertEqual(masks[0].shape       ,     (1, 3, 1764, 2646)						)

              UpperCAmelCase  =						processor.post_process_masks(
                  a__       ,     tf.convert_to_tensor(a__						)       ,     tf.convert_to_tensor(a__						)       ,     return_tensors='''tf'''       ,     )
              self.assertEqual(masks[0].shape       ,     (1, 3, 1764, 2646)						)

              # should also work with np
              UpperCAmelCase  =						[np.ones((1, 3, 5, 5)						)]
              UpperCAmelCase  =						processor.post_process_masks(
                  a__       ,     np.array(a__						)       ,     np.array(a__						)       ,     return_tensors='''tf'''						)

              self.assertEqual(masks[0].shape       ,     (1, 3, 1764, 2646)						)

              UpperCAmelCase  =						[[1, 0], [0, 1]]
              with self.assertRaises(tf.errors.InvalidArgumentError						):
                     UpperCAmelCase  =						processor.post_process_masks(
                         a__       ,     np.array(a__						)       ,     np.array(a__						)       ,     return_tensors='''tf'''						)






@require_vision
@require_torchvision
class     lowerCAmelCase__ (				unittest.TestCase    ):

       '''simple docstring'''

       def 			__snake_case      ( self					:				List[str]						):
              UpperCAmelCase  =						tempfile.mkdtemp()
              UpperCAmelCase  =						SamImageProcessor()
              UpperCAmelCase  =						SamProcessor(a__						)
              processor.save_pretrained(self.tmpdirname						)

       def 			__snake_case      ( self					:				Union[str, Any]       ,     **a__					:				Tuple						):
              return AutoProcessor.from_pretrained(self.tmpdirname       ,     **a__						).image_processor

       def 			__snake_case      ( self					:				List[Any]						):
              shutil.rmtree(self.tmpdirname						)

       def 			__snake_case      ( self					:				Union[str, Any]						):
              UpperCAmelCase  =						[np.random.randint(255       ,     size=(3, 30, 400)       ,     dtype=np.uinta						)]

              UpperCAmelCase  =						[Image.fromarray(np.moveaxis(a__       ,     0       ,     -1						)						) for x in image_inputs]

              return image_inputs

       @is_pt_tf_cross_test
       def 			__snake_case      ( self					:				List[Any]						):
              UpperCAmelCase  =						self.get_image_processor()

              UpperCAmelCase  =						SamProcessor(image_processor=a__						)
              UpperCAmelCase  =						np.random.randint(0       ,     2       ,     size=(1, 3, 5, 5)						).astype(np.floataa						)
              UpperCAmelCase  =						[tf.convert_to_tensor(a__						)]
              UpperCAmelCase  =						[torch.tensor(a__						)]

              UpperCAmelCase  =						[[1764, 2646]]

              UpperCAmelCase  =						[[683, 1024]]
              UpperCAmelCase  =						processor.post_process_masks(
                  a__       ,     a__       ,     a__       ,     return_tensors='''tf'''						)
              UpperCAmelCase  =						processor.post_process_masks(
                  a__       ,     a__       ,     a__       ,     return_tensors='''pt'''						)

              self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()						)						)



       @is_pt_tf_cross_test
       def 			__snake_case      ( self					:				List[Any]						):
              UpperCAmelCase  =						self.get_image_processor()

              UpperCAmelCase  =						SamProcessor(image_processor=a__						)

              UpperCAmelCase  =						self.prepare_image_inputs()

              UpperCAmelCase  =						image_processor(a__       ,     return_tensors='''pt'''						)['''pixel_values'''].numpy()
              UpperCAmelCase  =						processor(images=a__       ,     return_tensors='''pt'''						)['''pixel_values'''].numpy()

              UpperCAmelCase  =						image_processor(a__       ,     return_tensors='''tf'''						)['''pixel_values'''].numpy()
              UpperCAmelCase  =						processor(images=a__       ,     return_tensors='''tf'''						)['''pixel_values'''].numpy()

              self.assertTrue(np.allclose(a__       ,     a__						)						)
              self.assertTrue(np.allclose(a__       ,     a__						)						)
              self.assertTrue(np.allclose(a__       ,     a__						)						)








from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_lowerCamelCase      :						Optional[Any]							=  logging.get_logger(__name__)

_lowerCamelCase      :						Union[str, Any]							=  {
    """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
    """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = '''mobilenet_v1'''


    def __init__(     self :      Optional[int]   ,					UpperCAmelCase__ :      Optional[int]=3   ,					UpperCAmelCase__ :      Optional[Any]=224   ,					UpperCAmelCase__ :      Optional[int]=1.0   ,					UpperCAmelCase__ :      Optional[int]=8   ,					UpperCAmelCase__ :      Tuple="relu6"   ,					UpperCAmelCase__ :      List[Any]=True   ,					UpperCAmelCase__ :      Dict=0.999   ,					UpperCAmelCase__ :      str=0.02   ,					UpperCAmelCase__ :      Optional[int]=0.001   ,					**UpperCAmelCase__ :      Dict   ,					)		->List[str]:





           '''simple docstring'''

           super().__init__(**UpperCAmelCase__)

           if depth_multiplier <= 0:
                  raise ValueError('''depth_multiplier must be greater than zero.''')

           A__ 					=       num_channels
           A__ 					=       image_size
           A__ 					=       depth_multiplier
           A__ 					=       min_depth
           A__ 					=       hidden_act
           A__ 					=       tf_padding
           A__ 					=       classifier_dropout_prob
           A__ 					=       initializer_range
           A__ 					=       layer_norm_eps


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = version.parse('''1.11'''	)


    @property
    def 			SCREAMING_SNAKE_CASE				(     self :      Any)		->Mapping[str, Mapping[int, str]]:





           '''simple docstring'''

           return OrderedDict([('''pixel_values''', {0: '''batch'''})])


    @property
    def 			SCREAMING_SNAKE_CASE				(     self :      List[str])		->Mapping[str, Mapping[int, str]]:





           '''simple docstring'''

           if self.task == "image-classification":
                  return OrderedDict([('''logits''', {0: '''batch'''})])
           else:
                  return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})])





    @property
    def 			SCREAMING_SNAKE_CASE				(     self :      int)		->float:





           '''simple docstring'''

           return 1e-4


