




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 __snake_case			(			unittest.TestCase		):







   def lowerCamelCase						(      self		:						List[str]):

        """simple docstring"""


        UpperCAmelCase_          =							tempfile.mkdtemp()
        UpperCAmelCase_          =							SamImageProcessor()
        UpperCAmelCase_          =							SamProcessor(_snake_case)
        processor.save_pretrained(self.tmpdirname)







   def lowerCamelCase						(      self		:						List[Any]					,						**_snake_case		:						Optional[int]):

        """simple docstring"""


        return AutoProcessor.from_pretrained(self.tmpdirname					,						**_snake_case).image_processor







   def lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        shutil.rmtree(self.tmpdirname)







   def lowerCamelCase						(      self		:						Optional[int]):

        """simple docstring"""


        UpperCAmelCase_          =							[np.random.randint(255					,						size=(3, 30, 400)					,						dtype=np.uinta)]

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

        return image_inputs







   def lowerCamelCase						(      self		:						List[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							SamProcessor(image_processor=self.get_image_processor())
        processor.save_pretrained(self.tmpdirname)

        UpperCAmelCase_          =							self.get_image_processor(do_normalize=_snake_case					,						padding_value=1.0)

        UpperCAmelCase_          =							SamProcessor.from_pretrained(self.tmpdirname					,						do_normalize=_snake_case					,						padding_value=1.0)

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







   def lowerCamelCase						(      self		:						Optional[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_image_processor()

        UpperCAmelCase_          =							SamProcessor(image_processor=_snake_case)

        UpperCAmelCase_          =							self.prepare_image_inputs()

        UpperCAmelCase_          =							image_processor(_snake_case					,						return_tensors='''np''')
        UpperCAmelCase_          =							processor(images=_snake_case					,						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 lowerCamelCase						(      self		:						Optional[int]):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_image_processor()

        UpperCAmelCase_          =							SamProcessor(image_processor=_snake_case)
        UpperCAmelCase_          =							[torch.ones((1, 3, 5, 5))]

        UpperCAmelCase_          =							[[1764, 2646]]

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

        UpperCAmelCase_          =							processor.post_process_masks(
            _snake_case					,						torch.tensor(_snake_case)					,						torch.tensor(_snake_case))
        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(_snake_case					,						np.array(_snake_case)					,						np.array(_snake_case))

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

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







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







   def lowerCamelCase						(      self		:						List[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							tempfile.mkdtemp()
        UpperCAmelCase_          =							SamImageProcessor()
        UpperCAmelCase_          =							SamProcessor(_snake_case)
        processor.save_pretrained(self.tmpdirname)







   def lowerCamelCase						(      self		:						str					,						**_snake_case		:						Optional[int]):

        """simple docstring"""


        return AutoProcessor.from_pretrained(self.tmpdirname					,						**_snake_case).image_processor







   def lowerCamelCase						(      self		:						Optional[int]):

        """simple docstring"""


        shutil.rmtree(self.tmpdirname)







   def lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        UpperCAmelCase_          =							[np.random.randint(255					,						size=(3, 30, 400)					,						dtype=np.uinta)]

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

        return image_inputs







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							SamProcessor(image_processor=self.get_image_processor())
        processor.save_pretrained(self.tmpdirname)

        UpperCAmelCase_          =							self.get_image_processor(do_normalize=_snake_case					,						padding_value=1.0)

        UpperCAmelCase_          =							SamProcessor.from_pretrained(self.tmpdirname					,						do_normalize=_snake_case					,						padding_value=1.0)

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







   def lowerCamelCase						(      self		:						Dict):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_image_processor()

        UpperCAmelCase_          =							SamProcessor(image_processor=_snake_case)

        UpperCAmelCase_          =							self.prepare_image_inputs()

        UpperCAmelCase_          =							image_processor(_snake_case					,						return_tensors='''np''')
        UpperCAmelCase_          =							processor(images=_snake_case					,						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 lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_image_processor()

        UpperCAmelCase_          =							SamProcessor(image_processor=_snake_case)
        UpperCAmelCase_          =							[tf.ones((1, 3, 5, 5))]

        UpperCAmelCase_          =							[[1764, 2646]]

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

        UpperCAmelCase_          =							processor.post_process_masks(
            _snake_case					,						tf.convert_to_tensor(_snake_case)					,						tf.convert_to_tensor(_snake_case)					,						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(
            _snake_case					,						np.array(_snake_case)					,						np.array(_snake_case)					,						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(
                 _snake_case					,						np.array(_snake_case)					,						np.array(_snake_case)					,						return_tensors='''tf''')







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







   def lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        UpperCAmelCase_          =							tempfile.mkdtemp()
        UpperCAmelCase_          =							SamImageProcessor()
        UpperCAmelCase_          =							SamProcessor(_snake_case)
        processor.save_pretrained(self.tmpdirname)







   def lowerCamelCase						(      self		:						Optional[int]					,						**_snake_case		:						int):

        """simple docstring"""


        return AutoProcessor.from_pretrained(self.tmpdirname					,						**_snake_case).image_processor







   def lowerCamelCase						(      self		:						Dict):

        """simple docstring"""


        shutil.rmtree(self.tmpdirname)







   def lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        UpperCAmelCase_          =							[np.random.randint(255					,						size=(3, 30, 400)					,						dtype=np.uinta)]

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

        return image_inputs







   @is_pt_tf_cross_test
   def lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_image_processor()

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

        UpperCAmelCase_          =							[[1764, 2646]]

        UpperCAmelCase_          =							[[683, 1024]]
        UpperCAmelCase_          =							processor.post_process_masks(
            _snake_case					,						_snake_case					,						_snake_case					,						return_tensors='''tf''')
        UpperCAmelCase_          =							processor.post_process_masks(
            _snake_case					,						_snake_case					,						_snake_case					,						return_tensors='''pt''')

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







   @is_pt_tf_cross_test
   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        UpperCAmelCase_          =							self.get_image_processor()

        UpperCAmelCase_          =							SamProcessor(image_processor=_snake_case)

        UpperCAmelCase_          =							self.prepare_image_inputs()

        UpperCAmelCase_          =							image_processor(_snake_case					,						return_tensors='''pt''')['''pixel_values'''].numpy()
        UpperCAmelCase_          =							processor(images=_snake_case					,						return_tensors='''pt''')['''pixel_values'''].numpy()

        UpperCAmelCase_          =							image_processor(_snake_case					,						return_tensors='''tf''')['''pixel_values'''].numpy()
        UpperCAmelCase_          =							processor(images=_snake_case					,						return_tensors='''tf''')['''pixel_values'''].numpy()

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












snake_case_ : Dict    		=       {
    "Pillow": "Pillow",
    "accelerate": "accelerate>=0.11.0",
    "compel": "compel==0.1.8",
    "black": "black~=23.1",
    "datasets": "datasets",
    "filelock": "filelock",
    "flax": "flax>=0.4.1",
    "hf-doc-builder": "hf-doc-builder>=0.3.0",
    "huggingface-hub": "huggingface-hub>=0.13.2",
    "requests-mock": "requests-mock==1.10.0",
    "importlib_metadata": "importlib_metadata",
    "invisible-watermark": "invisible-watermark",
    "isort": "isort>=5.5.4",
    "jax": "jax>=0.2.8,!=0.3.2",
    "jaxlib": "jaxlib>=0.1.65",
    "Jinja2": "Jinja2",
    "k-diffusion": "k-diffusion>=0.0.12",
    "torchsde": "torchsde",
    "note_seq": "note_seq",
    "librosa": "librosa",
    "numpy": "numpy",
    "omegaconf": "omegaconf",
    "parameterized": "parameterized",
    "protobuf": "protobuf>=3.20.3,<4",
    "pytest": "pytest",
    "pytest-timeout": "pytest-timeout",
    "pytest-xdist": "pytest-xdist",
    "ruff": "ruff>=0.0.241",
    "safetensors": "safetensors",
    "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
    "scipy": "scipy",
    "onnx": "onnx",
    "regex": "regex!=2019.12.17",
    "requests": "requests",
    "tensorboard": "tensorboard",
    "torch": "torch>=1.4",
    "torchvision": "torchvision",
    "transformers": "transformers>=4.25.1",
    "urllib3": "urllib3<=2.0.0",
}






