






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		,	lowercase		,	lowercase=7		,	lowercase=3		,	lowercase=18		,	lowercase=30		,	lowercase=400		,	lowercase=True		,	lowercase=1 / 255		,	lowercase=True		,	lowercase=8		,	)			->						List[str]:
													_a  :    Union[str, Any]			=						parent
													_a  :    Optional[Any]			=						batch_size
													_a  :    Dict			=						num_channels
													_a  :    Optional[int]			=						image_size
													_a  :    int			=						min_resolution
													_a  :    Optional[int]			=						max_resolution
													_a  :    int			=						do_rescale
													_a  :    int			=						rescale_factor
													_a  :    List[str]			=						do_pad
													_a  :    str			=						pad_size




						def      snake_case__(    self       )			->						Optional[Any]:
													return {
													    "do_rescale": self.do_rescale,
													    "rescale_factor": self.rescale_factor,
													    "do_pad": self.do_pad,
													    "pad_size": self.pad_size,
													}







						def      snake_case__(    self		,	lowercase=False		,	lowercase=False		,	lowercase=False       )			->						Union[str, Any]:
													assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

													if equal_resolution:
																				_a  :    Optional[Any]			=						[]
																				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:
																				_a  :    List[str]			=						[]
																				for i in range(self.batch_size       ):
																											_a		,					_a  :    Dict			=						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
																				_a  :    Any			=						[Image.fromarray(np.moveaxis(lowercase		,	0		,	-1       )       ) for x in image_inputs]

													if torchify:
																				_a  :    Tuple			=						[torch.from_numpy(lowercase       ) for x in image_inputs]

													return image_inputs

@require_torch
@require_vision
class      UpperCamelCase_							(				UpperCamelCase ,       unittest.TestCase       ):
						lowercase									=  SwinaSRImageProcessor if is_vision_available() else None




						def      snake_case__(    self       )			->						List[str]:
													_a  :    Tuple			=						SwinaSRImageProcessingTester(self       )




						@property
						def      snake_case__(    self       )			->						Any:
													return self.image_processor_tester.prepare_image_processor_dict()




						def      snake_case__(    self       )			->						List[str]:
													_a  :    Tuple			=						self.image_processing_class(**self.image_processor_dict       )
													self.assertTrue(hasattr(lowercase		,	'''do_rescale'''       )       )
													self.assertTrue(hasattr(lowercase		,	'''rescale_factor'''       )       )
													self.assertTrue(hasattr(lowercase		,	'''do_pad'''       )       )
													self.assertTrue(hasattr(lowercase		,	'''pad_size'''       )       )




						def      snake_case__(    self       )			->						Optional[Any]:
													pass




						def      snake_case__(    self		,	lowercase       )			->						Union[str, Any]:
													_a		,					_a  :    Optional[int]			=						get_image_size(lowercase       )
													_a  :    Any			=						self.image_processor_tester.pad_size

													_a  :    Optional[Any]			=						(old_height // size + 1) * size - old_height
													_a  :    Tuple			=						(old_width // size + 1) * size - old_width
													return old_height + pad_height, old_width + pad_width




						def      snake_case__(    self       )			->						Union[str, Any]:
													# Initialize image_processor
													_a  :    Tuple			=						self.image_processing_class(**self.image_processor_dict       )
													# create random PIL images
													_a  :    Optional[int]			=						self.image_processor_tester.prepare_inputs(equal_resolution=lowercase       )
													for image in image_inputs:
																				self.assertIsInstance(lowercase		,	Image.Image       )

													# Test not batched input
													_a  :    Dict			=						image_processor(image_inputs[0]		,	return_tensors='''pt'''       ).pixel_values
													_a		,					_a  :    str			=						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      snake_case__(    self       )			->						List[Any]:
													# Initialize image_processor
													_a  :    Dict			=						self.image_processing_class(**self.image_processor_dict       )
													# create random numpy tensors
													_a  :    Union[str, Any]			=						self.image_processor_tester.prepare_inputs(equal_resolution=lowercase		,	numpify=lowercase       )
													for image in image_inputs:
																				self.assertIsInstance(lowercase		,	np.ndarray       )

													# Test not batched input
													_a  :    Union[str, Any]			=						image_processor(image_inputs[0]		,	return_tensors='''pt'''       ).pixel_values
													_a		,					_a  :    Optional[int]			=						self.calculate_expected_size(image_inputs[0]       )
													self.assertEqual(
													    encoded_images.shape		,	(
													        1,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )		,	)







						def      snake_case__(    self       )			->						Union[str, Any]:
													# Initialize image_processor
													_a  :    Tuple			=						self.image_processing_class(**self.image_processor_dict       )
													# create random PyTorch tensors
													_a  :    Optional[int]			=						self.image_processor_tester.prepare_inputs(equal_resolution=lowercase		,	torchify=lowercase       )
													for image in image_inputs:
																				self.assertIsInstance(lowercase		,	torch.Tensor       )

													# Test not batched input
													_a  :    Union[str, Any]			=						image_processor(image_inputs[0]		,	return_tensors='''pt'''       ).pixel_values
													_a		,					_a  :    Optional[Any]			=						self.calculate_expected_size(image_inputs[0]       )
													self.assertEqual(
													    encoded_images.shape		,	(
													        1,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )		,	)







import numpy as np  # noqa: E402

from ...configuration_utils import ConfigMixin, register_to_config
from ...schedulers.scheduling_utils import SchedulerMixin


try:
						import librosa  # noqa: E402

						__lowerCamelCase						= True
						__lowerCamelCase						= ''
except Exception as e:
						__lowerCamelCase						= False
						__lowerCamelCase						= (
						    F'''Cannot import librosa because {e}. Make sure to correctly install librosa to be able to install it.'''
						)


from PIL import Image  # noqa: E402

class      UpperCamelCase_							(				UpperCamelCase ,       UpperCamelCase       ):
						lowercase									=  '''mel_config.json'''




						@register_to_config
						def __init__(    self		,	lowercase = 256		,	lowercase = 256		,	lowercase = 22_050		,	lowercase = 2_048		,	lowercase = 512		,	lowercase = 80		,	lowercase = 32		,	)			->						Optional[Any]:
													_a  :    Tuple			=						hop_length
													_a  :    Dict			=						sample_rate
													_a  :    Dict			=						n_fft
													_a  :    List[str]			=						top_db
													_a  :    Optional[int]			=						n_iter
													self.set_resolution(lowercase		,	lowercase       )
													_a  :    Optional[int]			=						None

													if not _librosa_can_be_imported:
																				raise ValueError(_import_error       )




						def      snake_case__(    self		,	lowercase		,	lowercase       )			->						Any:
													_a  :    Any			=						x_res
													_a  :    Optional[Any]			=						y_res
													_a  :    List[Any]			=						self.y_res
													_a  :    Tuple			=						self.x_res * self.hop_length - 1




						def      snake_case__(    self		,	lowercase = None		,	lowercase = None       )			->						Union[str, Any]:
													if audio_file is not None:
																				_a		,					_a  :    str			=						librosa.load(lowercase		,	mono=lowercase		,	sr=self.sr       )
													else:
																				_a  :    Any			=						raw_audio

													# Pad with silence if necessary.
													if len(self.audio       ) < self.x_res * self.hop_length:
																				_a  :    str			=						np.concatenate([self.audio, np.zeros((self.x_res * self.hop_length - len(self.audio       ),)       )]       )




						def      snake_case__(    self       )			->						int:
													return len(self.audio       ) // self.slice_size




						def      snake_case__(    self		,	lowercase = 0       )			->						np.ndarray:
													return self.audio[self.slice_size * slice : self.slice_size * (slice + 1)]




						def      snake_case__(    self       )			->						int:
													return self.sr




						def      snake_case__(    self		,	lowercase       )			->						Image.Image:
													_a  :    int			=						librosa.feature.melspectrogram(
													    y=self.get_audio_slice(lowercase       )		,	sr=self.sr		,	n_fft=self.n_fft		,	hop_length=self.hop_length		,	n_mels=self.n_mels       )
													_a  :    List[str]			=						librosa.power_to_db(lowercase		,	ref=np.max		,	top_db=self.top_db       )
													_a  :    List[str]			=						(((log_S + self.top_db) * 255 / self.top_db).clip(0		,	255       ) + 0.5).astype(np.uinta       )
													_a  :    Any			=						Image.fromarray(lowercase       )
													return image







						def      snake_case__(    self		,	lowercase       )			->						np.ndarray:
													_a  :    Any			=						np.frombuffer(image.tobytes()		,	dtype='''uint8'''       ).reshape((image.height, image.width)       )
													_a  :    Any			=						bytedata.astype('''float'''       ) * self.top_db / 255 - self.top_db
													_a  :    Dict			=						librosa.db_to_power(lowercase       )
													_a  :    List[str]			=						librosa.feature.inverse.mel_to_audio(
													    lowercase		,	sr=self.sr		,	n_fft=self.n_fft		,	hop_length=self.hop_length		,	n_iter=self.n_iter       )
													return audio