






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


   '''simple docstring'''

   def __init__(      self					:	Dict,			_lowerCamelCase					:	Dict,			_lowerCamelCase					:	List[str]=7,			_lowerCamelCase					:	Tuple=3,			_lowerCamelCase					:	Union[str, Any]=30,			_lowerCamelCase					:	Optional[int]=4_00,			_lowerCamelCase					:	Optional[Any]=True,			_lowerCamelCase					:	Optional[Any]=None,			_lowerCamelCase					:	List[Any]=True,			_lowerCamelCase					:	Dict=[0.5, 0.5, 0.5],			_lowerCamelCase					:	Dict=[0.5, 0.5, 0.5],			_lowerCamelCase					:	Optional[int]=False,			):

     '''simple docstring'''
     __A		     =					size if size is not None else {'''height''': 30, '''width''': 30}
     __A		     =					parent
     __A		     =					batch_size
     __A		     =					num_channels
     __A		     =					min_resolution
     __A		     =					max_resolution
     __A		     =					do_resize
     __A		     =					size
     __A		     =					do_normalize
     __A		     =					image_mean
     __A		     =					image_std
     __A		     =					do_reduce_labels






   def 							_SCREAMING_SNAKE_CASE							(      self					:	str    ):

     '''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    lowerCAmelCase							(       ):




  """simple docstring"""







  __A		     =					load_dataset('''hf-internal-testing/fixtures_ade20k'''						,			split='''test'''					)

  __A		     =					Image.open(dataset[0]['''file''']					)
  __A		     =					Image.open(dataset[1]['''file''']					)

  return image, map



def    lowerCAmelCase							(       ):




  """simple docstring"""







  __A		     =					load_dataset('''hf-internal-testing/fixtures_ade20k'''						,			split='''test'''					)

  __A		     =					Image.open(dataset[0]['''file''']					)
  __A		     =					Image.open(dataset[1]['''file''']					)
  __A		     =					Image.open(dataset[2]['''file''']					)
  __A		     =					Image.open(dataset[3]['''file''']					)

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





@require_torch
@require_vision
class    snake_case						(				_lowerCAmelCase  ,      unittest.TestCase		):


   '''simple docstring'''

   A_		:      Optional[Any]							=					SegformerImageProcessor if is_vision_available() else None


   def 							_SCREAMING_SNAKE_CASE							(      self					:	str    ):

     '''simple docstring'''
     __A		     =					SegformerImageProcessingTester(self    )


   @property
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Dict    ):

     '''simple docstring'''
     return self.image_processor_tester.prepare_image_processor_dict()


   def 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     __A		     =					self.image_processing_class(**self.image_processor_dict    )
     self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'''do_resize'''    )    )
     self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'''size'''    )    )
     self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'''do_normalize'''    )    )
     self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'''image_mean'''    )    )
     self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'''image_std'''    )    )
     self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'''do_reduce_labels'''    )    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	List[Any]    ):

     '''simple docstring'''
     __A		     =					self.image_processing_class.from_dict(self.image_processor_dict    )
     self.assertEqual(image_processor.size,			{'''height''': 30, '''width''': 30}    )
     self.assertEqual(image_processor.do_reduce_labels,			SCREAMING_SNAKE_CASE_    )

     __A		     =					self.image_processing_class.from_dict(self.image_processor_dict,			size=42,			reduce_labels=SCREAMING_SNAKE_CASE_    )
     self.assertEqual(image_processor.size,			{'''height''': 42, '''width''': 42}    )
     self.assertEqual(image_processor.do_reduce_labels,			SCREAMING_SNAKE_CASE_    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Any    ):

     '''simple docstring'''
     pass


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Tuple    ):

     '''simple docstring'''
     # Initialize image_processing
     __A		     =					self.image_processing_class(**self.image_processor_dict    )
     # create random PIL images
     __A		     =					prepare_image_inputs(self.image_processor_tester,			equal_resolution=SCREAMING_SNAKE_CASE_    )
     for image in image_inputs:
       self.assertIsInstance(SCREAMING_SNAKE_CASE_,			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.size['''height'''],
             self.image_processor_tester.size['''width'''],
         ),			)

     # Test batched
     __A		     =					image_processing(SCREAMING_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 							_SCREAMING_SNAKE_CASE							(      self					:	Tuple    ):

     '''simple docstring'''
     # Initialize image_processing
     __A		     =					self.image_processing_class(**self.image_processor_dict    )
     # create random numpy tensors
     __A		     =					prepare_image_inputs(self.image_processor_tester,			equal_resolution=SCREAMING_SNAKE_CASE_,			numpify=SCREAMING_SNAKE_CASE_    )
     for image in image_inputs:
       self.assertIsInstance(SCREAMING_SNAKE_CASE_,			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.size['''height'''],
             self.image_processor_tester.size['''width'''],
         ),			)

     # Test batched
     __A		     =					image_processing(SCREAMING_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 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     # Initialize image_processing
     __A		     =					self.image_processing_class(**self.image_processor_dict    )
     # create random PyTorch tensors
     __A		     =					prepare_image_inputs(self.image_processor_tester,			equal_resolution=SCREAMING_SNAKE_CASE_,			torchify=SCREAMING_SNAKE_CASE_    )
     for image in image_inputs:
       self.assertIsInstance(SCREAMING_SNAKE_CASE_,			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.size['''height'''],
             self.image_processor_tester.size['''width'''],
         ),			)

     # Test batched
     __A		     =					image_processing(SCREAMING_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 							_SCREAMING_SNAKE_CASE							(      self					:	List[str]    ):

     '''simple docstring'''
     # Initialize image_processing
     __A		     =					self.image_processing_class(**self.image_processor_dict    )
     # create random PyTorch tensors
     __A		     =					prepare_image_inputs(self.image_processor_tester,			equal_resolution=SCREAMING_SNAKE_CASE_,			torchify=SCREAMING_SNAKE_CASE_    )
     __A		     =					[]
     for image in image_inputs:
       self.assertIsInstance(SCREAMING_SNAKE_CASE_,			torch.Tensor    )
       maps.append(torch.zeros(image.shape[-2:]    ).long()    )

     # Test not batched input
     __A		     =					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_55    )

     # Test batched
     __A		     =					image_processing(SCREAMING_SNAKE_CASE_,			SCREAMING_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_55    )

     # Test not batched input (PIL images)
     __A		     =					prepare_semantic_single_inputs()

     __A		     =					image_processing(SCREAMING_SNAKE_CASE_,			SCREAMING_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_55    )

     # Test batched input (PIL images)
     __A		     =					prepare_semantic_batch_inputs()

     __A		     =					image_processing(SCREAMING_SNAKE_CASE_,			SCREAMING_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_55    )






   def 							_SCREAMING_SNAKE_CASE							(      self					:	Tuple    ):

     '''simple docstring'''
     # Initialize image_processing
     __A		     =					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		     =					prepare_semantic_single_inputs()
     __A		     =					image_processing(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			return_tensors='''pt'''    )
     self.assertTrue(encoding['''labels'''].min().item() >= 0    )
     self.assertTrue(encoding['''labels'''].max().item() <= 1_50    )

     __A		     =					True
     __A		     =					image_processing(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			return_tensors='''pt'''    )
     self.assertTrue(encoding['''labels'''].min().item() >= 0    )
     self.assertTrue(encoding['''labels'''].max().item() <= 2_55    )






'''simple docstring'''





import copy

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


UpperCAmelCase            = logging.get_logger(__name__)

UpperCAmelCase            = {
    "facebook/musicgen-small": "https://huggingface.co/facebook/musicgen-small/resolve/main/config.json",
    # See all Musicgen models at https://huggingface.co/models?filter=musicgen
}

class     a (					__magic_name__     ):
				_snake_case		     =			'''musicgen_decoder'''
				_snake_case		     =			['''past_key_values''']




				def __init__(				self						:					Optional[int],     SCREAMING_SNAKE_CASE_						:					Dict=20_48,     SCREAMING_SNAKE_CASE_						:					List[str]=20_48,     SCREAMING_SNAKE_CASE_						:					int=24,     SCREAMING_SNAKE_CASE_						:					Dict=40_96,     SCREAMING_SNAKE_CASE_						:					str=16,     SCREAMING_SNAKE_CASE_						:					int=0.0,     SCREAMING_SNAKE_CASE_						:					Optional[Any]=True,     SCREAMING_SNAKE_CASE_						:					str="gelu",     SCREAMING_SNAKE_CASE_						:					List[Any]=10_24,     SCREAMING_SNAKE_CASE_						:					int=0.1,     SCREAMING_SNAKE_CASE_						:					List[Any]=0.0,     SCREAMING_SNAKE_CASE_						:					int=0.0,     SCREAMING_SNAKE_CASE_						:					str=0.02,     SCREAMING_SNAKE_CASE_						:					Any=False,     SCREAMING_SNAKE_CASE_						:					List[str]=4,     SCREAMING_SNAKE_CASE_						:					str=20_48,     SCREAMING_SNAKE_CASE_						:					int=20_48,     SCREAMING_SNAKE_CASE_						:					Union[str, Any]=None,     SCREAMING_SNAKE_CASE_						:					Union[str, Any]=False,     **SCREAMING_SNAKE_CASE_						:					Tuple,     ):
										snake_case							:  Optional[int]			=     vocab_size
										snake_case							:  Optional[int]			=     max_position_embeddings
										snake_case							:  Dict			=     hidden_size
										snake_case							:  Any			=     ffn_dim
										snake_case							:  Optional[Any]			=     num_hidden_layers
										snake_case							:  Tuple			=     num_attention_heads
										snake_case							:  int			=     dropout
										snake_case							:  Union[str, Any]			=     attention_dropout
										snake_case							:  Optional[int]			=     activation_dropout
										snake_case							:  Union[str, Any]			=     activation_function
										snake_case							:  Tuple			=     initializer_factor
										snake_case							:  List[Any]			=     layerdrop
										snake_case							:  Optional[int]			=     use_cache
										snake_case							:  Dict			=     scale_embedding  # scale factor will be sqrt(d_model) if True
										snake_case							:  Tuple			=     num_codebooks
										super().__init__(
										    pad_token_id=SCREAMING_SNAKE_CASE_,     bos_token_id=SCREAMING_SNAKE_CASE_,     eos_token_id=SCREAMING_SNAKE_CASE_,     tie_word_embeddings=SCREAMING_SNAKE_CASE_,     **SCREAMING_SNAKE_CASE_,     )




class     a (					__magic_name__     ):
				_snake_case		     =			'''musicgen'''
				_snake_case		     =			True




				def __init__(				self						:					Dict,     **SCREAMING_SNAKE_CASE_						:					Optional[int]   ):
										super().__init__(**SCREAMING_SNAKE_CASE_   )
										if "text_encoder" not in kwargs or "audio_encoder" not in kwargs or "decoder" not in kwargs:
																raise ValueError('''Config has to be initialized with text_encoder, audio_encoder and decoder config'''   )

										snake_case							:  Any			=     kwargs.pop('''text_encoder'''   )
										snake_case							:  List[Any]			=     text_encoder_config.pop('''model_type'''   )

										snake_case							:  Union[str, Any]			=     kwargs.pop('''audio_encoder'''   )
										snake_case							:  Tuple			=     audio_encoder_config.pop('''model_type'''   )

										snake_case							:  List[str]			=     kwargs.pop('''decoder'''   )

										snake_case							:  List[str]			=     AutoConfig.for_model(SCREAMING_SNAKE_CASE_,     **SCREAMING_SNAKE_CASE_   )
										snake_case							:  List[Any]			=     AutoConfig.for_model(SCREAMING_SNAKE_CASE_,     **SCREAMING_SNAKE_CASE_   )
										snake_case							:  Optional[Any]			=     MusicgenDecoderConfig(**SCREAMING_SNAKE_CASE_   )
										snake_case							:  Any			=     True




				@classmethod
				def 						__snake_case				(				cls						:					Tuple,     SCREAMING_SNAKE_CASE_						:					PretrainedConfig,     SCREAMING_SNAKE_CASE_						:					PretrainedConfig,     SCREAMING_SNAKE_CASE_						:					MusicgenDecoderConfig,     **SCREAMING_SNAKE_CASE_						:					Optional[Any],     ):
										return cls(
										    text_encoder=text_encoder_config.to_dict(),     audio_encoder=audio_encoder_config.to_dict(),     decoder=decoder_config.to_dict(),     **SCREAMING_SNAKE_CASE_,     )




				def 						__snake_case				(				self						:					Optional[Any]   ):
										snake_case							:  Dict			=     copy.deepcopy(self.__dict__   )
										snake_case							:  Tuple			=     self.text_encoder.to_dict()
										snake_case							:  str			=     self.audio_encoder.to_dict()
										snake_case							:  Dict			=     self.decoder.to_dict()
										snake_case							:  Optional[int]			=     self.__class__.model_type
										return output

