


import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import SegformerImageProcessor


class 	a__						(    unittest.TestCase     ):

       def __init__( self   :  Optional[Any]   ,				lowerCamelCase_   :  Dict   ,				lowerCamelCase_   :  List[Any]=7   ,				lowerCamelCase_   :  int=3   ,				lowerCamelCase_   :  Optional[Any]=3_0   ,				lowerCamelCase_   :  Optional[Any]=4_0_0   ,				lowerCamelCase_   :  Dict=True   ,				lowerCamelCase_   :  Optional[Any]=None   ,				lowerCamelCase_   :  Tuple=True   ,				lowerCamelCase_   :  Dict=[0.5, 0.5, 0.5]   ,				lowerCamelCase_   :  Union[str, Any]=[0.5, 0.5, 0.5]   ,				lowerCamelCase_   :  List[str]=False   ,				):
            a_     :  Optional[Any]				      =     size if size is not None else {"""height""": 3_0, """width""": 3_0}
            a_     :  Optional[Any]				      =     parent
            a_     :  Optional[int]				      =     batch_size
            a_     :  Tuple				      =     num_channels
            a_     :  Tuple				      =     min_resolution
            a_     :  Optional[Any]				      =     max_resolution
            a_     :  Tuple				      =     do_resize
            a_     :  Optional[int]				      =     size
            a_     :  Tuple				      =     do_normalize
            a_     :  Dict				      =     image_mean
            a_     :  Optional[int]				      =     image_std
            a_     :  Optional[int]				      =     do_reduce_labels

       def     UpperCAmelCase( self   :  int     ):
            return {
                "do_resize": self.do_resize,
                "size": self.size,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
                "do_reduce_labels": self.do_reduce_labels,
            }



def 			_a      (    ):
     a_     :  Any				      =     load_dataset("""hf-internal-testing/fixtures_ade20k"""	,	split="""test"""			)

     a_     :  List[Any]				      =     Image.open(dataset[0]["""file"""]			)
     a_     :  List[Any]				      =     Image.open(dataset[1]["""file"""]			)

     return image, map



def 			_a      (    ):
     a_     :  str				      =     load_dataset("""hf-internal-testing/fixtures_ade20k"""	,	split="""test"""			)

     a_     :  str				      =     Image.open(dataset[0]["""file"""]			)
     a_     :  str				      =     Image.open(dataset[1]["""file"""]			)
     a_     :  List[Any]				      =     Image.open(dataset[2]["""file"""]			)
     a_     :  str				      =     Image.open(dataset[3]["""file"""]			)

     return [imagea, imagea], [mapa, mapa]


@require_torch
@require_vision
class 	a__						(    lowerCAmelCase_    ,							unittest.TestCase     ):
       lowerCamelCase__:  Optional[int]				     =  SegformerImageProcessor if is_vision_available() else None

       def     UpperCAmelCase( self   :  Dict     ):
            a_     :  Dict				      =     SegformerImageProcessingTester(self     )

       @property
       def     UpperCAmelCase( self   :  List[str]     ):
            return self.image_processor_tester.prepare_image_processor_dict()

       def     UpperCAmelCase( self   :  Union[str, Any]     ):
            a_     :  str				      =     self.image_processing_class(**self.image_processor_dict     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""do_resize"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""size"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""do_normalize"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""image_mean"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""image_std"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""do_reduce_labels"""     )     )

       def     UpperCAmelCase( self   :  Union[str, Any]     ):
            a_     :  Optional[int]				      =     self.image_processing_class.from_dict(self.image_processor_dict     )
            self.assertEqual(image_processor.size   ,				{"""height""": 3_0, """width""": 3_0}     )
            self.assertEqual(image_processor.do_reduce_labels   ,				lowerCamelCase_     )

            a_     :  Any				      =     self.image_processing_class.from_dict(self.image_processor_dict   ,				size=4_2   ,				reduce_labels=lowerCamelCase_     )
            self.assertEqual(image_processor.size   ,				{"""height""": 4_2, """width""": 4_2}     )
            self.assertEqual(image_processor.do_reduce_labels   ,				lowerCamelCase_     )

       def     UpperCAmelCase( self   :  List[Any]     ):
            pass

       def     UpperCAmelCase( self   :  Any     ):
            # Initialize image_processing
            a_     :  List[Any]				      =     self.image_processing_class(**self.image_processor_dict     )
            # create random PIL images
            a_     :  List[str]				      =     prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowerCamelCase_     )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_   ,				Image.Image     )

            # Test not batched input
            a_     :  Tuple				      =     image_processing(image_inputs[0]   ,				return_tensors="""pt"""     ).pixel_values
            self.assertEqual(
                encoded_images.shape   ,				(
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

            # Test batched
            a_     :  int				      =     image_processing(lowerCamelCase_   ,				return_tensors="""pt"""     ).pixel_values
            self.assertEqual(
                encoded_images.shape   ,				(
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

       def     UpperCAmelCase( self   :  Any     ):
            # Initialize image_processing
            a_     :  Any				      =     self.image_processing_class(**self.image_processor_dict     )
            # create random numpy tensors
            a_     :  Union[str, Any]				      =     prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowerCamelCase_   ,				numpify=lowerCamelCase_     )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_   ,				np.ndarray     )

            # Test not batched input
            a_     :  Dict				      =     image_processing(image_inputs[0]   ,				return_tensors="""pt"""     ).pixel_values
            self.assertEqual(
                encoded_images.shape   ,				(
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

            # Test batched
            a_     :  Tuple				      =     image_processing(lowerCamelCase_   ,				return_tensors="""pt"""     ).pixel_values
            self.assertEqual(
                encoded_images.shape   ,				(
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

       def     UpperCAmelCase( self   :  str     ):
            # Initialize image_processing
            a_     :  Dict				      =     self.image_processing_class(**self.image_processor_dict     )
            # create random PyTorch tensors
            a_     :  List[Any]				      =     prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowerCamelCase_   ,				torchify=lowerCamelCase_     )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_   ,				torch.Tensor     )

            # Test not batched input
            a_     :  List[Any]				      =     image_processing(image_inputs[0]   ,				return_tensors="""pt"""     ).pixel_values
            self.assertEqual(
                encoded_images.shape   ,				(
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

            # Test batched
            a_     :  Dict				      =     image_processing(lowerCamelCase_   ,				return_tensors="""pt"""     ).pixel_values
            self.assertEqual(
                encoded_images.shape   ,				(
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

       def     UpperCAmelCase( self   :  int     ):
            # Initialize image_processing
            a_     :  Dict				      =     self.image_processing_class(**self.image_processor_dict     )
            # create random PyTorch tensors
            a_     :  Union[str, Any]				      =     prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowerCamelCase_   ,				torchify=lowerCamelCase_     )
            a_     :  str				      =     []
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_   ,				torch.Tensor     )
                 maps.append(torch.zeros(image.shape[-2:]     ).long()     )

            # Test not batched input
            a_     :  Optional[Any]				      =     image_processing(image_inputs[0]   ,				maps[0]   ,				return_tensors="""pt"""     )
            self.assertEqual(
                encoding["""pixel_values"""].shape   ,				(
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(
                encoding["""labels"""].shape   ,				(
                    1,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(encoding["""labels"""].dtype   ,				torch.long     )
            self.assertTrue(encoding["""labels"""].min().item() >= 0     )
            self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5     )

            # Test batched
            a_     :  Optional[Any]				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				return_tensors="""pt"""     )
            self.assertEqual(
                encoding["""pixel_values"""].shape   ,				(
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(
                encoding["""labels"""].shape   ,				(
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(encoding["""labels"""].dtype   ,				torch.long     )
            self.assertTrue(encoding["""labels"""].min().item() >= 0     )
            self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5     )

            # Test not batched input (PIL images)
            a_      ,      a_     :  Tuple				      =     prepare_semantic_single_inputs()

            a_     :  Optional[int]				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				return_tensors="""pt"""     )
            self.assertEqual(
                encoding["""pixel_values"""].shape   ,				(
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(
                encoding["""labels"""].shape   ,				(
                    1,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(encoding["""labels"""].dtype   ,				torch.long     )
            self.assertTrue(encoding["""labels"""].min().item() >= 0     )
            self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5     )

            # Test batched input (PIL images)
            a_      ,      a_     :  int				      =     prepare_semantic_batch_inputs()

            a_     :  str				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				return_tensors="""pt"""     )
            self.assertEqual(
                encoding["""pixel_values"""].shape   ,				(
                    2,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(
                encoding["""labels"""].shape   ,				(
                    2,
                    self.image_processor_tester.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)
            self.assertEqual(encoding["""labels"""].dtype   ,				torch.long     )
            self.assertTrue(encoding["""labels"""].min().item() >= 0     )
            self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5     )

       def     UpperCAmelCase( self   :  List[Any]     ):
            # Initialize image_processing
            a_     :  Optional[int]				      =     self.image_processing_class(**self.image_processor_dict     )

            # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
            a_      ,      a_     :  List[Any]				      =     prepare_semantic_single_inputs()
            a_     :  Optional[Any]				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				return_tensors="""pt"""     )
            self.assertTrue(encoding["""labels"""].min().item() >= 0     )
            self.assertTrue(encoding["""labels"""].max().item() <= 1_5_0     )

            a_     :  Tuple				      =     True
            a_     :  Dict				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				return_tensors="""pt"""     )
            self.assertTrue(encoding["""labels"""].min().item() >= 0     )
            self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5     )





"""simple docstring"""




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
					import torch

if is_vision_available():
					from PIL import Image

					from transformers import MobileNetVaImageProcessor
class SCREAMING_SNAKE_CASE       (      unittest.TestCase					):






	'''simple docstring'''







	def __init__(  self :Tuple       ,    __magic_name__ :str       ,    __magic_name__ :Optional[Any]=7       ,    __magic_name__ :int=3       ,    __magic_name__ :Union[str, Any]=18       ,    __magic_name__ :Union[str, Any]=30       ,    __magic_name__ :str=400       ,    __magic_name__ :str=True       ,    __magic_name__ :Any=None       ,    __magic_name__ :Tuple=True       ,    __magic_name__ :List[str]=None       ,    )			->   Optional[int]:

			'''simple docstring'''






			a__   		=     size if size is not None else {'''shortest_edge''': 20}
			a__   		=     crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
			a__   		=     parent
			a__   		=     batch_size
			a__   		=     num_channels
			a__   		=     image_size
			a__   		=     min_resolution
			a__   		=     max_resolution
			a__   		=     do_resize
			a__   		=     size
			a__   		=     do_center_crop
			a__   		=     crop_size






	def    _UpperCamelCase							(  self :Tuple			)			->   Any:

			'''simple docstring'''






			return {
			    "do_resize": self.do_resize,
			    "size": self.size,
			    "do_center_crop": self.do_center_crop,
			    "crop_size": self.crop_size,
			}

@require_torch
@require_vision
class SCREAMING_SNAKE_CASE       (      lowerCAmelCase					,   unittest.TestCase					):






	'''simple docstring'''







	snake_case__							:		str         =		MobileNetVaImageProcessor if is_vision_available() else None


	def    _UpperCamelCase							(  self :Union[str, Any]			)			->   str:

			'''simple docstring'''






			a__   		=     MobileNetVaImageProcessingTester(self			)


	@property
	def    _UpperCamelCase							(  self :List[str]			)			->   Optional[Any]:

			'''simple docstring'''






			return self.image_processor_tester.prepare_image_processor_dict()


	def    _UpperCamelCase							(  self :Tuple			)			->   Tuple:

			'''simple docstring'''






			a__   		=     self.image_processing_class(**self.image_processor_dict			)
			self.assertTrue(hasattr(__magic_name__       ,    '''do_resize'''			)			)
			self.assertTrue(hasattr(__magic_name__       ,    '''size'''			)			)
			self.assertTrue(hasattr(__magic_name__       ,    '''do_center_crop'''			)			)
			self.assertTrue(hasattr(__magic_name__       ,    '''center_crop'''			)			)


	def    _UpperCamelCase							(  self :List[Any]			)			->   int:

			'''simple docstring'''






			a__   		=     self.image_processing_class.from_dict(self.image_processor_dict			)
			self.assertEqual(image_processor.size       ,    {'''shortest_edge''': 20}			)
			self.assertEqual(image_processor.crop_size       ,    {'''height''': 18, '''width''': 18}			)

			a__   		=     self.image_processing_class.from_dict(self.image_processor_dict       ,    size=42       ,    crop_size=84			)
			self.assertEqual(image_processor.size       ,    {'''shortest_edge''': 42}			)
			self.assertEqual(image_processor.crop_size       ,    {'''height''': 84, '''width''': 84}			)


	def    _UpperCamelCase							(  self :Optional[int]			)			->   Any:

			'''simple docstring'''






			pass


	def    _UpperCamelCase							(  self :Dict			)			->   Tuple:

			'''simple docstring'''






			a__   		=     self.image_processing_class(**self.image_processor_dict			)
			# create random PIL images
			a__   		=     prepare_image_inputs(self.image_processor_tester       ,    equal_resolution=__magic_name__			)
			for image in image_inputs:
					self.assertIsInstance(__magic_name__       ,    Image.Image			)

			# Test not batched input
			a__   		=     image_processing(image_inputs[0]       ,    return_tensors='''pt'''			).pixel_values
			self.assertEqual(
			    encoded_images.shape       ,    (
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )       ,    )

			# Test batched
			a__   		=     image_processing(__magic_name__       ,    return_tensors='''pt'''			).pixel_values
			self.assertEqual(
			    encoded_images.shape       ,    (
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )       ,    )


	def    _UpperCamelCase							(  self :Optional[Any]			)			->   Union[str, Any]:

			'''simple docstring'''






			a__   		=     self.image_processing_class(**self.image_processor_dict			)
			# create random numpy tensors
			a__   		=     prepare_image_inputs(self.image_processor_tester       ,    equal_resolution=__magic_name__       ,    numpify=__magic_name__			)
			for image in image_inputs:
					self.assertIsInstance(__magic_name__       ,    np.ndarray			)

			# Test not batched input
			a__   		=     image_processing(image_inputs[0]       ,    return_tensors='''pt'''			).pixel_values
			self.assertEqual(
			    encoded_images.shape       ,    (
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )       ,    )

			# Test batched
			a__   		=     image_processing(__magic_name__       ,    return_tensors='''pt'''			).pixel_values
			self.assertEqual(
			    encoded_images.shape       ,    (
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )       ,    )






	def    _UpperCamelCase							(  self :List[Any]			)			->   str:

			'''simple docstring'''






			a__   		=     self.image_processing_class(**self.image_processor_dict			)
			# create random PyTorch tensors
			a__   		=     prepare_image_inputs(self.image_processor_tester       ,    equal_resolution=__magic_name__       ,    torchify=__magic_name__			)
			for image in image_inputs:
					self.assertIsInstance(__magic_name__       ,    torch.Tensor			)

			# Test not batched input
			a__   		=     image_processing(image_inputs[0]       ,    return_tensors='''pt'''			).pixel_values
			self.assertEqual(
			    encoded_images.shape       ,    (
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )       ,    )

			# Test batched
			a__   		=     image_processing(__magic_name__       ,    return_tensors='''pt'''			).pixel_values
			self.assertEqual(
			    encoded_images.shape       ,    (
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.crop_size['''height'''],
			        self.image_processor_tester.crop_size['''width'''],
			    )       ,    )




