





"""simple docstring"""




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						:       List[str],					lowerCAmelCase__						:       Tuple,					lowerCAmelCase__						:       List[Any]=7,					lowerCAmelCase__						:       Tuple=3,					lowerCAmelCase__						:       List[Any]=3_0,					lowerCAmelCase__						:       str=4_0_0,					lowerCAmelCase__						:       Optional[Any]=True,					lowerCAmelCase__						:       Optional[Any]=None,					lowerCAmelCase__						:       Optional[Any]=True,					lowerCAmelCase__						:       int=[0.5, 0.5, 0.5],					lowerCAmelCase__						:       List[str]=[0.5, 0.5, 0.5],					lowerCAmelCase__						:       Optional[Any]=False,					)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       size if size is not None else {'''height''': 3_0, '''width''': 3_0}
										_UpperCamelCase     :   Any      =       parent
										_UpperCamelCase     :   List[Any]      =       batch_size
										_UpperCamelCase     :   List[Any]      =       num_channels
										_UpperCamelCase     :   Tuple      =       min_resolution
										_UpperCamelCase     :   Union[str, Any]      =       max_resolution
										_UpperCamelCase     :   str      =       do_resize
										_UpperCamelCase     :   Tuple      =       size
										_UpperCamelCase     :   Tuple      =       do_normalize
										_UpperCamelCase     :   List[str]      =       image_mean
										_UpperCamelCase     :   Dict      =       image_std
										_UpperCamelCase     :   int      =       do_reduce_labels






				def 							snake_case      (					self						:       Optional[int]				)      -> Optional[int]:




										'''simple docstring'''



										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_							(				):
						_UpperCamelCase     :   List[str]      =       load_dataset('''hf-internal-testing/fixtures_ade20k'''			,		split='''test'''  )

						_UpperCamelCase     :   Tuple      =       Image.open(dataset[0]['''file''']  )
						_UpperCamelCase     :   int      =       Image.open(dataset[1]['''file''']  )

						return image, map





def 			a_							(				):
						_UpperCamelCase     :   Dict      =       load_dataset('''hf-internal-testing/fixtures_ade20k'''			,		split='''test'''  )

						_UpperCamelCase     :   Tuple      =       Image.open(dataset[0]['''file''']  )
						_UpperCamelCase     :   Any      =       Image.open(dataset[1]['''file''']  )
						_UpperCamelCase     :   Dict      =       Image.open(dataset[2]['''file''']  )
						_UpperCamelCase     :   Union[str, Any]      =       Image.open(dataset[3]['''file''']  )

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






@require_torch
@require_vision
class 					_a		( a_      ,							unittest.TestCase							):
				UpperCamelCase								=       SegformerImageProcessor if is_vision_available() else None






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




										'''simple docstring'''



										_UpperCamelCase     :   str      =       SegformerImageProcessingTester(self				)






				@property
				def 							snake_case      (					self						:       Dict				)      -> Optional[int]:




										'''simple docstring'''



										return self.image_processor_tester.prepare_image_processor_dict()






				def 							snake_case      (					self						:       str				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   str      =       self.image_processing_class(**self.image_processor_dict				)
										self.assertTrue(hasattr(snake_case__,					'''do_resize'''				)				)
										self.assertTrue(hasattr(snake_case__,					'''size'''				)				)
										self.assertTrue(hasattr(snake_case__,					'''do_normalize'''				)				)
										self.assertTrue(hasattr(snake_case__,					'''image_mean'''				)				)
										self.assertTrue(hasattr(snake_case__,					'''image_std'''				)				)
										self.assertTrue(hasattr(snake_case__,					'''do_reduce_labels'''				)				)






				def 							snake_case      (					self						:       List[str]				)      -> Dict:




										'''simple docstring'''



										_UpperCamelCase     :   Tuple      =       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,					snake_case__				)

										_UpperCamelCase     :   str      =       self.image_processing_class.from_dict(self.image_processor_dict,					size=4_2,					reduce_labels=snake_case__				)
										self.assertEqual(image_processor.size,					{'''height''': 4_2, '''width''': 4_2}				)
										self.assertEqual(image_processor.do_reduce_labels,					snake_case__				)






				def 							snake_case      (					self						:       str				)      -> Any:




										'''simple docstring'''



										pass






				def 							snake_case      (					self						:       Any				)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   List[Any]      =       self.image_processing_class(**self.image_processor_dict				)
										# create random PIL images
										_UpperCamelCase     :   List[str]      =       prepare_image_inputs(self.image_processor_tester,					equal_resolution=snake_case__				)
										for image in image_inputs:
																self.assertIsInstance(snake_case__,					Image.Image				)

										# Test not batched input
										_UpperCamelCase     :   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
										_UpperCamelCase     :   Optional[int]      =       image_processing(snake_case__,					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 							snake_case      (					self						:       Union[str, Any]				)      -> Tuple:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.image_processing_class(**self.image_processor_dict				)
										# create random numpy tensors
										_UpperCamelCase     :   int      =       prepare_image_inputs(self.image_processor_tester,					equal_resolution=snake_case__,					numpify=snake_case__				)
										for image in image_inputs:
																self.assertIsInstance(snake_case__,					np.ndarray				)

										# Test not batched input
										_UpperCamelCase     :   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
										_UpperCamelCase     :   Union[str, Any]      =       image_processing(snake_case__,					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 							snake_case      (					self						:       Union[str, Any]				)      -> Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.image_processing_class(**self.image_processor_dict				)
										# create random PyTorch tensors
										_UpperCamelCase     :   Any      =       prepare_image_inputs(self.image_processor_tester,					equal_resolution=snake_case__,					torchify=snake_case__				)
										for image in image_inputs:
																self.assertIsInstance(snake_case__,					torch.Tensor				)

										# Test not batched input
										_UpperCamelCase     :   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
										_UpperCamelCase     :   Any      =       image_processing(snake_case__,					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 							snake_case      (					self						:       Optional[Any]				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   Union[str, Any]      =       self.image_processing_class(**self.image_processor_dict				)
										# create random PyTorch tensors
										_UpperCamelCase     :   List[Any]      =       prepare_image_inputs(self.image_processor_tester,					equal_resolution=snake_case__,					torchify=snake_case__				)
										_UpperCamelCase     :   List[Any]      =       []
										for image in image_inputs:
																self.assertIsInstance(snake_case__,					torch.Tensor				)
																maps.append(torch.zeros(image.shape[-2:]				).long()				)

										# Test not batched input
										_UpperCamelCase     :   List[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
										_UpperCamelCase     :   str      =       image_processing(snake_case__,					snake_case__,					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)
										_UpperCamelCase  ,				_UpperCamelCase     :   Tuple      =       prepare_semantic_single_inputs()

										_UpperCamelCase     :   Union[str, Any]      =       image_processing(snake_case__,					snake_case__,					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)
										_UpperCamelCase  ,				_UpperCamelCase     :   int      =       prepare_semantic_batch_inputs()

										_UpperCamelCase     :   Union[str, Any]      =       image_processing(snake_case__,					snake_case__,					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 							snake_case      (					self						:       List[str]				)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   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
										_UpperCamelCase  ,				_UpperCamelCase     :   Dict      =       prepare_semantic_single_inputs()
										_UpperCamelCase     :   Tuple      =       image_processing(snake_case__,					snake_case__,					return_tensors='''pt'''				)
										self.assertTrue(encoding['''labels'''].min().item() >= 0				)
										self.assertTrue(encoding['''labels'''].max().item() <= 1_5_0				)

										_UpperCamelCase     :   Optional[int]      =       True
										_UpperCamelCase     :   Any      =       image_processing(snake_case__,					snake_case__,					return_tensors='''pt'''				)
										self.assertTrue(encoding['''labels'''].min().item() >= 0				)
										self.assertTrue(encoding['''labels'''].max().item() <= 2_5_5				)








import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


UpperCAmelCase :				Union[str, Any]							=logging.get_logger(__name__)


class    _lowercase (a_   ):
				'''simple docstring'''







				lowercase__     =    """speech-encoder-decoder"""
				lowercase__     =    True

				def __init__(			self  ,			**snake_case__     ):

									'''simple docstring'''


									super().__init__(**snake_case__     )
									if "encoder" not in kwargs or "decoder" not in kwargs:
														raise ValueError(
														    F"""A configuraton of type {self.model_type} cannot be instantiated because not both `encoder` and"""
														    F""" `decoder` sub-configurations are passed, but only {kwargs}"""     )

									UpperCamelCase_			= kwargs.pop("encoder"     )
									UpperCamelCase_			= encoder_config.pop("model_type"     )
									UpperCamelCase_			= kwargs.pop("decoder"     )
									UpperCamelCase_			= decoder_config.pop("model_type"     )

									UpperCamelCase_			= AutoConfig.for_model(snake_case__  ,			**snake_case__     )
									UpperCamelCase_			= AutoConfig.for_model(snake_case__  ,			**snake_case__     )
									UpperCamelCase_			= True

				@classmethod
				def    _lowerCamelCase       (			cls  ,			snake_case__  ,			snake_case__  ,			**snake_case__     ):

									'''simple docstring'''


									logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config"     )
									UpperCamelCase_			= True
									UpperCamelCase_			= True

									return cls(encoder=encoder_config.to_dict()  ,			decoder=decoder_config.to_dict()  ,			**snake_case__     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= copy.deepcopy(self.__dict__     )
									UpperCamelCase_			= self.encoder.to_dict()
									UpperCamelCase_			= self.decoder.to_dict()
									UpperCamelCase_			= self.__class__.model_type
									return output
