

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 CLIPImageProcessor



class     lowercase						(       unittest.TestCase					):



 '''simple docstring'''


 def __init__(self       ,       __a       ,       __a=7       ,       __a=3       ,       __a=18       ,       __a=30       ,       __a=400       ,       __a=True       ,       __a=None       ,       __a=True       ,       __a=None       ,       __a=True       ,       __a=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]       ,       __a=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]       ,       __a=True       ,       ) ->					Optional[int]:






  """simple docstring"""





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




 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  return {
      "do_resize": self.do_resize,
      "size": self.size,
      "do_center_crop": self.do_center_crop,
      "crop_size": self.crop_size,
      "do_normalize": self.do_normalize,
      "image_mean": self.image_mean,
      "image_std": self.image_std,
      "do_convert_rgb": self.do_convert_rgb,
  }




 def   UpperCamelCase__							(self       ,       __a=False       ,       __a=False       ,       __a=False ) ->					Union[str, Any]:






  """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(__a       ,       0       ,       -1 ) ) for x in image_inputs]

  if torchify:
   UpperCAmelCase__							=				[torch.from_numpy(__a ) for x in image_inputs]

  return image_inputs







@require_torch
@require_vision
class     lowercase						(       _UpperCamelCase ,				unittest.TestCase					):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE												=				CLIPImageProcessor if is_vision_available() else None




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






  """simple docstring"""





  UpperCAmelCase__							=				CLIPImageProcessingTester(self )




 @property
 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  return self.image_processor_tester.prepare_image_processor_dict()




 def   UpperCamelCase__							(self ) ->					Any:






  """simple docstring"""





  UpperCAmelCase__							=				self.image_processing_class(**self.image_processor_dict )
  self.assertTrue(hasattr(__a       ,       'do_resize' ) )
  self.assertTrue(hasattr(__a       ,       'size' ) )
  self.assertTrue(hasattr(__a       ,       'do_center_crop' ) )
  self.assertTrue(hasattr(__a       ,       'center_crop' ) )
  self.assertTrue(hasattr(__a       ,       'do_normalize' ) )
  self.assertTrue(hasattr(__a       ,       'image_mean' ) )
  self.assertTrue(hasattr(__a       ,       'image_std' ) )
  self.assertTrue(hasattr(__a       ,       'do_convert_rgb' ) )




 def   UpperCamelCase__							(self ) ->					str:






  """simple docstring"""





  UpperCAmelCase__							=				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} )

  UpperCAmelCase__							=				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 ) ->					List[Any]:






  """simple docstring"""





  pass




 def   UpperCamelCase__							(self ) ->					Dict:






  """simple docstring"""





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

  # Test not batched input
  UpperCAmelCase__							=				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
  UpperCAmelCase__							=				image_processing(__a       ,       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]:






  """simple docstring"""





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

  # Test not batched input
  UpperCAmelCase__							=				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
  UpperCAmelCase__							=				image_processing(__a       ,       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 ) ->					Tuple:






  """simple docstring"""





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

  # Test not batched input
  UpperCAmelCase__							=				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
  UpperCAmelCase__							=				image_processing(__a       ,       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'],
      )       ,       )







@require_torch
@require_vision
class     lowercase						(       _UpperCamelCase ,				unittest.TestCase					):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE												=				CLIPImageProcessor if is_vision_available() else None




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






  """simple docstring"""





  UpperCAmelCase__							=				CLIPImageProcessingTester(self       ,       num_channels=4 )
  UpperCAmelCase__							=				3




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






  """simple docstring"""





  return self.image_processor_tester.prepare_image_processor_dict()




 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__							=				self.image_processing_class(**self.image_processor_dict )
  self.assertTrue(hasattr(__a       ,       'do_resize' ) )
  self.assertTrue(hasattr(__a       ,       'size' ) )
  self.assertTrue(hasattr(__a       ,       'do_center_crop' ) )
  self.assertTrue(hasattr(__a       ,       'center_crop' ) )
  self.assertTrue(hasattr(__a       ,       'do_normalize' ) )
  self.assertTrue(hasattr(__a       ,       'image_mean' ) )
  self.assertTrue(hasattr(__a       ,       'image_std' ) )
  self.assertTrue(hasattr(__a       ,       'do_convert_rgb' ) )




 def   UpperCamelCase__							(self ) ->					Tuple:






  """simple docstring"""





  pass




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






  """simple docstring"""





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

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

  # Test batched
  UpperCAmelCase__							=				image_processing(__a       ,       return_tensors='pt' ).pixel_values
  self.assertEqual(
      encoded_images.shape       ,       (
          self.image_processor_tester.batch_size,
          self.expected_encoded_image_num_channels,
          self.image_processor_tester.crop_size['height'],
          self.image_processor_tester.crop_size['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					:     Union[str, Any]					  =  True
	_lowerCamelCase					:     Optional[Any]					  =  ""
except Exception as e:
	_lowerCamelCase					:     int					  =  False
	_lowerCamelCase					:     List[str]					  =  (
	    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 				__snake_case     (_a  ,		_a						):
				lowerCAmelCase__			=   "mel_config.json"



				@register_to_config
				def __init__(					self					:						Dict						,		_UpperCAmelCase					:						int = 256						,		_UpperCAmelCase					:						int = 256						,		_UpperCAmelCase					:						int = 2_2050						,		_UpperCAmelCase					:						int = 2048						,		_UpperCAmelCase					:						int = 512						,		_UpperCAmelCase					:						int = 80						,		_UpperCAmelCase					:						int = 32						,		)     ->			List[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			List[str]        =					hop_length
								_lowerCAmelCase			:			Optional[Any]        =					sample_rate
								_lowerCAmelCase			:			Optional[Any]        =					n_fft
								_lowerCAmelCase			:			Dict        =					top_db
								_lowerCAmelCase			:			List[Any]        =					n_iter
								self.set_resolution(_UpperCAmelCase						,		_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					None

								if not _librosa_can_be_imported:
												raise ValueError(_import_error					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]						,		_UpperCAmelCase					:						int						,		_UpperCAmelCase					:						int					)     ->			List[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			Dict        =					x_res
								_lowerCAmelCase			:			Union[str, Any]        =					y_res
								_lowerCAmelCase			:			Any        =					self.y_res
								_lowerCAmelCase			:			Optional[Any]        =					self.x_res * self.hop_length - 1



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						str = None						,		_UpperCAmelCase					:						np.ndarray = None					)     ->			List[str]:





								'''simple docstring'''




								if audio_file is not None:
												_lowerCAmelCase    ,			_lowerCAmelCase			:			Dict        =					librosa.load(_UpperCAmelCase						,		mono=_UpperCAmelCase						,		sr=self.sr					)
								else:
												_lowerCAmelCase			:			Any        =					raw_audio

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



				def 					SCREAMING_SNAKE_CASE				(					self					:						Any					)     ->			int:





								'''simple docstring'''




								return len(self.audio					) // self.slice_size



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[str]						,		_UpperCAmelCase					:						int = 0					)     ->			np.ndarray:





								'''simple docstring'''




								return self.audio[self.slice_size * slice : self.slice_size * (slice + 1)]



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





								'''simple docstring'''




								return self.sr



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						int					)     ->			Image.Image:





								'''simple docstring'''




								_lowerCAmelCase			:			Union[str, Any]        =					librosa.feature.melspectrogram(
								    y=self.get_audio_slice(_UpperCAmelCase					)						,		sr=self.sr						,		n_fft=self.n_fft						,		hop_length=self.hop_length						,		n_mels=self.n_mels					)
								_lowerCAmelCase			:			List[Any]        =					librosa.power_to_db(_UpperCAmelCase						,		ref=np.max						,		top_db=self.top_db					)
								_lowerCAmelCase			:			List[Any]        =					(((log_S + self.top_db) * 255 / self.top_db).clip(0						,		255					) + 0.5).astype(np.uinta					)
								_lowerCAmelCase			:			Optional[Any]        =					Image.fromarray(_UpperCAmelCase					)
								return image



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]						,		_UpperCAmelCase					:						Image.Image					)     ->			np.ndarray:





								'''simple docstring'''




								_lowerCAmelCase			:			Optional[int]        =					np.frombuffer(image.tobytes()						,		dtype="""uint8"""					).reshape((image.height, image.width)					)
								_lowerCAmelCase			:			Optional[int]        =					bytedata.astype("""float"""					) * self.top_db / 255 - self.top_db
								_lowerCAmelCase			:			List[Any]        =					librosa.db_to_power(_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					librosa.feature.inverse.mel_to_audio(
								    _UpperCAmelCase						,		sr=self.sr						,		n_fft=self.n_fft						,		hop_length=self.hop_length						,		n_iter=self.n_iter					)
								return audio

