





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


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import SwinaSRImageProcessor
     from transformers.image_transforms import get_image_size



class 				_UpperCamelCase       (						unittest.TestCase  ):

       def __init__(		self:			List[Any]       , _SCREAMING_SNAKE_CASE:			Tuple       , _SCREAMING_SNAKE_CASE:			Optional[Any]=7       , _SCREAMING_SNAKE_CASE:			Any=3       , _SCREAMING_SNAKE_CASE:			List[Any]=18       , _SCREAMING_SNAKE_CASE:			Tuple=30       , _SCREAMING_SNAKE_CASE:			List[str]=400       , _SCREAMING_SNAKE_CASE:			Tuple=True       , _SCREAMING_SNAKE_CASE:			List[str]=1 / 255       , _SCREAMING_SNAKE_CASE:			List[Any]=True       , _SCREAMING_SNAKE_CASE:			Tuple=8       , )							->			Optional[int]:




              """simple docstring"""


              UpperCamelCase_ 							=	parent
              UpperCamelCase_ 							=	batch_size
              UpperCamelCase_ 							=	num_channels
              UpperCamelCase_ 							=	image_size
              UpperCamelCase_ 							=	min_resolution
              UpperCamelCase_ 							=	max_resolution
              UpperCamelCase_ 							=	do_rescale
              UpperCamelCase_ 							=	rescale_factor
              UpperCamelCase_ 							=	do_pad
              UpperCamelCase_ 							=	pad_size

       def lowercase			(		self:			Tuple		)							->			Optional[Any]:




              """simple docstring"""


              return {
                  "do_rescale": self.do_rescale,
                  "rescale_factor": self.rescale_factor,
                  "do_pad": self.do_pad,
                  "pad_size": self.pad_size,
              }



       def lowercase			(		self:			Tuple       , _SCREAMING_SNAKE_CASE:			List[Any]=False       , _SCREAMING_SNAKE_CASE:			List[str]=False       , _SCREAMING_SNAKE_CASE:			Any=False		)							->			List[str]:




              """simple docstring"""


              assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

              if equal_resolution:
                     UpperCamelCase_ 							=	[]
                     for i in range(self.batch_size		):
                            image_inputs.append(
                                np.random.randint(
                                    255       , size=(self.num_channels, self.max_resolution, self.max_resolution)       , dtype=np.uinta		)		)
              else:
                     UpperCamelCase_ 							=	[]
                     for i in range(self.batch_size		):
                            UpperCamelCase_							,			UpperCamelCase_ 							=	np.random.choice(np.arange(self.min_resolution       , self.max_resolution		)       , 2		)
                            image_inputs.append(np.random.randint(255       , size=(self.num_channels, width, height)       , dtype=np.uinta		)		)

              if not numpify and not torchify:
                     # PIL expects the channel dimension as last dimension
                     UpperCamelCase_ 							=	[Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE       , 0       , -1		)		) for x in image_inputs]

              if torchify:
                     UpperCamelCase_ 							=	[torch.from_numpy(_SCREAMING_SNAKE_CASE		) for x in image_inputs]

              return image_inputs



@require_torch
@require_vision
class 				_UpperCamelCase       (						lowerCAmelCase_	,    unittest.TestCase  ):
       _UpperCamelCase					:       Union[str, Any]       = SwinaSRImageProcessor if is_vision_available() else None

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




              """simple docstring"""


              UpperCamelCase_ 							=	SwinaSRImageProcessingTester(self		)

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




              """simple docstring"""


              return self.image_processor_tester.prepare_image_processor_dict()

       def lowercase			(		self:			Tuple		)							->			Optional[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "do_rescale"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "rescale_factor"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "do_pad"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "pad_size"		)		)

       def lowercase			(		self:			List[Any]		)							->			Tuple:




              """simple docstring"""


              pass

       def lowercase			(		self:			int       , _SCREAMING_SNAKE_CASE:			Optional[Any]		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_							,			UpperCamelCase_ 							=	get_image_size(_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_ 							=	self.image_processor_tester.pad_size

              UpperCamelCase_ 							=	(old_height // size + 1) * size - old_height
              UpperCamelCase_ 							=	(old_width // size + 1) * size - old_width
              return old_height + pad_height, old_width + pad_width

       def lowercase			(		self:			Dict		)							->			Any:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              # create random PIL images
              UpperCamelCase_ 							=	self.image_processor_tester.prepare_inputs(equal_resolution=_SCREAMING_SNAKE_CASE		)
              for image in image_inputs:
                     self.assertIsInstance(_SCREAMING_SNAKE_CASE       , Image.Image		)

              # Test not batched input
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(np.array(image_inputs[0]		)		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )

       def lowercase			(		self:			Any		)							->			Any:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              # create random numpy tensors
              UpperCamelCase_ 							=	self.image_processor_tester.prepare_inputs(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
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(image_inputs[0]		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )



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




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              # create random PyTorch tensors
              UpperCamelCase_ 							=	self.image_processor_tester.prepare_inputs(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
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(image_inputs[0]		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )





import random
import shutil
import tempfile
import unittest

import numpy as np

from transformers import TaTokenizer, TaTokenizerFast
from transformers.testing_utils import require_sentencepiece, require_torch
from transformers.utils.import_utils import is_speech_available, is_torch_available


if is_torch_available():
			pass

if is_speech_available():
			from transformers import EncodecFeatureExtractor, MusicgenProcessor


_A							     =       random.Random()

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      List[Any]     ,					UpperCamelCase		:      Any=1.0     ,					UpperCamelCase		:      Union[str, Any]=None     ,					UpperCamelCase		:      Union[str, Any]=None	)     ->	List[Any]:



	"""simple docstring"""






	if rng is None:
		a_     			=   global_rng

	a_     			=   []
	for batch_idx in range(shape[0]	):
		values.append([]	)
		for _ in range(shape[1]	):
			values[-1].append(rng.random() * scale	)

	return values

@require_torch
@require_sentencepiece
class 			lowerCamelCase_					(    unittest.TestCase    ):





							def   __magic_name__      (							self    ):
								a_     			=   """facebook/musicgen-small"""
								a_     			=   tempfile.mkdtemp()





							def   __magic_name__      (							self			,       **_SCREAMING_SNAKE_CASE    ):
								return TaTokenizer.from_pretrained(self.checkpoint			,       **_SCREAMING_SNAKE_CASE    )





							def   __magic_name__      (							self			,       **_SCREAMING_SNAKE_CASE    ):
								return EncodecFeatureExtractor.from_pretrained(self.checkpoint			,       **_SCREAMING_SNAKE_CASE    )





							def   __magic_name__      (							self    ):
								shutil.rmtree(self.tmpdirname    )





							def   __magic_name__      (							self    ):
								a_     			=   self.get_tokenizer()
								a_     			=   self.get_feature_extractor()

								a_     			=   MusicgenProcessor(tokenizer=_SCREAMING_SNAKE_CASE			,       feature_extractor=_SCREAMING_SNAKE_CASE    )

								processor.save_pretrained(self.tmpdirname    )
								a_     			=   MusicgenProcessor.from_pretrained(self.tmpdirname    )

								self.assertEqual(processor.tokenizer.get_vocab()			,       tokenizer.get_vocab()    )
								self.assertIsInstance(processor.tokenizer			,       _SCREAMING_SNAKE_CASE    )

								self.assertEqual(processor.feature_extractor.to_json_string()			,       feature_extractor.to_json_string()    )
								self.assertIsInstance(processor.feature_extractor			,       _SCREAMING_SNAKE_CASE    )





							def   __magic_name__      (							self    ):
								a_     			=   MusicgenProcessor(tokenizer=self.get_tokenizer()			,       feature_extractor=self.get_feature_extractor()    )
								processor.save_pretrained(self.tmpdirname    )

								a_     			=   self.get_tokenizer(bos_token="""(BOS)"""			,       eos_token="""(EOS)"""    )
								a_     			=   self.get_feature_extractor(do_normalize=_SCREAMING_SNAKE_CASE			,       padding_value=1.0    )

								a_     			=   MusicgenProcessor.from_pretrained(
								    self.tmpdirname			,       bos_token="""(BOS)"""			,       eos_token="""(EOS)"""			,       do_normalize=_SCREAMING_SNAKE_CASE			,       padding_value=1.0    )

								self.assertEqual(processor.tokenizer.get_vocab()			,       tokenizer_add_kwargs.get_vocab()    )
								self.assertIsInstance(processor.tokenizer			,       _SCREAMING_SNAKE_CASE    )

								self.assertEqual(processor.feature_extractor.to_json_string()			,       feature_extractor_add_kwargs.to_json_string()    )
								self.assertIsInstance(processor.feature_extractor			,       _SCREAMING_SNAKE_CASE    )





							def   __magic_name__      (							self    ):
								a_     			=   self.get_feature_extractor()
								a_     			=   self.get_tokenizer()

								a_     			=   MusicgenProcessor(tokenizer=_SCREAMING_SNAKE_CASE			,       feature_extractor=_SCREAMING_SNAKE_CASE    )

								a_     			=   floats_list((3, 1000)    )

								a_     			=   feature_extractor(_SCREAMING_SNAKE_CASE			,       return_tensors="""np"""    )
								a_     			=   processor(_SCREAMING_SNAKE_CASE			,       return_tensors="""np"""    )

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





							def   __magic_name__      (							self    ):
								a_     			=   self.get_feature_extractor()
								a_     			=   self.get_tokenizer()

								a_     			=   MusicgenProcessor(tokenizer=_SCREAMING_SNAKE_CASE			,       feature_extractor=_SCREAMING_SNAKE_CASE    )

								a_     			=   """This is a test string"""

								a_     			=   processor(text=_SCREAMING_SNAKE_CASE    )

								a_     			=   tokenizer(_SCREAMING_SNAKE_CASE    )

								for key in encoded_tok.keys():
									self.assertListEqual(encoded_tok[key]			,       encoded_processor[key]    )





							def   __magic_name__      (							self    ):
								a_     			=   self.get_feature_extractor()
								a_     			=   self.get_tokenizer()

								a_     			=   MusicgenProcessor(tokenizer=_SCREAMING_SNAKE_CASE			,       feature_extractor=_SCREAMING_SNAKE_CASE    )

								a_     			=   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

								a_     			=   processor.batch_decode(sequences=_SCREAMING_SNAKE_CASE    )
								a_     			=   tokenizer.batch_decode(_SCREAMING_SNAKE_CASE    )

								self.assertListEqual(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE    )





							def   __magic_name__      (							self    ):
								a_     			=   self.get_feature_extractor()
								a_     			=   self.get_tokenizer()

								a_     			=   MusicgenProcessor(tokenizer=_SCREAMING_SNAKE_CASE			,       feature_extractor=_SCREAMING_SNAKE_CASE    )

								self.assertListEqual(
								    processor.model_input_names			,       feature_extractor.model_input_names			,       msg="""`processor` and `feature_extractor` model input names do not match"""			,       )





							def   __magic_name__      (							self    ):
								a_     			=   self.get_feature_extractor(padding_side="""left"""    )
								a_     			=   self.get_tokenizer()

								a_     			=   MusicgenProcessor(tokenizer=_SCREAMING_SNAKE_CASE			,       feature_extractor=_SCREAMING_SNAKE_CASE    )

								a_     			=   [floats_list((1, x)    )[0] for x in range(5			,       20			,       5    )]
								a_     			=   processor(_SCREAMING_SNAKE_CASE    ).padding_mask

								a_     			=   np.asarray(floats_list((3, 20)    )    )[:, None, :]
								a_     			=   processor.batch_decode(_SCREAMING_SNAKE_CASE			,       padding_mask=_SCREAMING_SNAKE_CASE    )

								self.assertIsInstance(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE    )

								for audio in decoded_audios:
									self.assertIsInstance(_SCREAMING_SNAKE_CASE			,       np.ndarray    )

								self.assertTrue(decoded_audios[0].shape == (1, 10)    )
								self.assertTrue(decoded_audios[1].shape == (1, 15)    )
								self.assertTrue(decoded_audios[2].shape == (1, 20)    )