
'''simple docstring'''



import unittest
from typing import Dict, List, Optional, Union

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, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import BridgeTowerImageProcessor




class     UpperCAmelCase_	(						unittest.TestCase					):






						'''simple docstring'''






						def __init__(   self       ,  _lowercase       ,  _lowercase = True       ,  _lowercase = None       ,  _lowercase = 32       ,  _lowercase = True       ,  _lowercase = 1 / 255       ,  _lowercase = True       ,  _lowercase = True       ,  _lowercase = [0.4814_5466, 0.457_8275, 0.4082_1073]       ,  _lowercase = [0.2686_2954, 0.2613_0258, 0.2757_7711]       ,  _lowercase = True       ,  _lowercase=7       ,  _lowercase=30       ,  _lowercase=400       ,  _lowercase=3       ,  ):

												"""simple docstring"""



												_lowerCAmelCase    		=					parent
												_lowerCAmelCase    		=					do_resize
												_lowerCAmelCase    		=					size if size is not None else {"""shortest_edge""": 288}
												_lowerCAmelCase    		=					size_divisor
												_lowerCAmelCase    		=					do_rescale
												_lowerCAmelCase    		=					rescale_factor
												_lowerCAmelCase    		=					do_normalize
												_lowerCAmelCase    		=					do_center_crop
												_lowerCAmelCase    		=					image_mean
												_lowerCAmelCase    		=					image_std
												_lowerCAmelCase    		=					do_pad
												_lowerCAmelCase    		=					batch_size
												_lowerCAmelCase    		=					num_channels
												_lowerCAmelCase    		=					min_resolution
												_lowerCAmelCase    		=					max_resolution




						def    _lowercase      (   self ):

												"""simple docstring"""



												return {
												    "image_mean": self.image_mean,
												    "image_std": self.image_std,
												    "do_normalize": self.do_normalize,
												    "do_resize": self.do_resize,
												    "size": self.size,
												    "size_divisor": self.size_divisor,
												}




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase=False ):

												"""simple docstring"""



												if not batched:
																		_lowerCAmelCase    		=					self.size["""shortest_edge"""]
																		_lowerCAmelCase    		=					image_inputs[0]
																		if isinstance(_lowercase       ,  Image.Image ):
																								_lowerCAmelCase		,       _lowerCAmelCase    		=					image.size
																		else:
																								_lowerCAmelCase		,       _lowerCAmelCase    		=					image.shape[1], image.shape[2]
																		_lowerCAmelCase    		=					size / min(_lowercase       ,  _lowercase )
																		if h < w:
																								_lowerCAmelCase		,       _lowerCAmelCase    		=					size, scale * w
																		else:
																								_lowerCAmelCase		,       _lowerCAmelCase    		=					scale * h, size

																		_lowerCAmelCase    		=					int((1_333 / 800) * size )
																		if max(_lowercase       ,  _lowercase ) > max_size:
																								_lowerCAmelCase    		=					max_size / max(_lowercase       ,  _lowercase )
																								_lowerCAmelCase    		=					newh * scale
																								_lowerCAmelCase    		=					neww * scale

																		_lowerCAmelCase		,       _lowerCAmelCase    		=					int(newh + 0.5 ), int(neww + 0.5 )
																		_lowerCAmelCase		,       _lowerCAmelCase    		=					(
																		    newh // self.size_divisor * self.size_divisor,
																		    neww // self.size_divisor * self.size_divisor,
																		)

												else:
																		_lowerCAmelCase    		=					[]
																		for image in image_inputs:
																								_lowerCAmelCase		,       _lowerCAmelCase    		=					self.get_expected_values([image] )
																								expected_values.append((expected_height, expected_width) )
																		_lowerCAmelCase    		=					max(_lowercase       ,  key=lambda _lowercase : item[0] )[0]
																		_lowerCAmelCase    		=					max(_lowercase       ,  key=lambda _lowercase : item[1] )[1]

												return expected_height, expected_width






@require_torch
@require_vision
class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE			,				unittest.TestCase					):






						'''simple docstring'''






						_lowercase						: Optional[int]										=  BridgeTowerImageProcessor if is_vision_available() else None




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					BridgeTowerImageProcessingTester(self )




						@property
						def    _lowercase      (   self ):

												"""simple docstring"""



												return self.image_processor_tester.prepare_image_processor_dict()




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.image_processing_class(**self.image_processor_dict )
												self.assertTrue(hasattr(_lowercase       ,  """image_mean""" ) )
												self.assertTrue(hasattr(_lowercase       ,  """image_std""" ) )
												self.assertTrue(hasattr(_lowercase       ,  """do_normalize""" ) )
												self.assertTrue(hasattr(_lowercase       ,  """do_resize""" ) )
												self.assertTrue(hasattr(_lowercase       ,  """size""" ) )
												self.assertTrue(hasattr(_lowercase       ,  """size_divisor""" ) )




						def    _lowercase      (   self ):

												"""simple docstring"""



												pass




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.image_processing_class(**self.image_processor_dict )
												# create random PIL images
												_lowerCAmelCase    		=					prepare_image_inputs(self.image_processor_tester       ,  equal_resolution=_lowercase )
												for image in image_inputs:
																		self.assertIsInstance(_lowercase       ,  Image.Image )

												# Test not batched input
												_lowerCAmelCase    		=					image_processing(image_inputs[0]       ,  return_tensors="""pt""" ).pixel_values

												_lowerCAmelCase		,       _lowerCAmelCase    		=					self.image_processor_tester.get_expected_values(_lowercase )
												self.assertEqual(
												    encoded_images.shape       ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,  )

												# Test batched
												_lowerCAmelCase    		=					image_processing(_lowercase       ,  return_tensors="""pt""" ).pixel_values

												_lowerCAmelCase		,       _lowerCAmelCase    		=					self.image_processor_tester.get_expected_values(_lowercase       ,  batched=_lowercase )
												self.assertEqual(
												    encoded_images.shape       ,  (
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        expected_height,
												        expected_width,
												    )       ,  )




						def    _lowercase      (   self ):

												"""simple docstring"""



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

												# Test not batched input
												_lowerCAmelCase    		=					image_processing(image_inputs[0]       ,  return_tensors="""pt""" ).pixel_values

												_lowerCAmelCase		,       _lowerCAmelCase    		=					self.image_processor_tester.get_expected_values(_lowercase )
												self.assertEqual(
												    encoded_images.shape       ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,  )

												# Test batched
												_lowerCAmelCase    		=					image_processing(_lowercase       ,  return_tensors="""pt""" ).pixel_values

												_lowerCAmelCase		,       _lowerCAmelCase    		=					self.image_processor_tester.get_expected_values(_lowercase       ,  batched=_lowercase )
												self.assertEqual(
												    encoded_images.shape       ,  (
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        expected_height,
												        expected_width,
												    )       ,  )




						def    _lowercase      (   self ):

												"""simple docstring"""



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

												# Test not batched input
												_lowerCAmelCase    		=					image_processing(image_inputs[0]       ,  return_tensors="""pt""" ).pixel_values

												_lowerCAmelCase		,       _lowerCAmelCase    		=					self.image_processor_tester.get_expected_values(_lowercase )
												self.assertEqual(
												    encoded_images.shape       ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,  )

												# Test batched
												_lowerCAmelCase    		=					image_processing(_lowercase       ,  return_tensors="""pt""" ).pixel_values

												_lowerCAmelCase		,       _lowerCAmelCase    		=					self.image_processor_tester.get_expected_values(_lowercase       ,  batched=_lowercase )
												self.assertEqual(
												    encoded_images.shape       ,  (
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        expected_height,
												        expected_width,
												    )       ,  )


'''simple docstring'''



from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


_lowercase          =						logging.get_logger(__name__)




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: List[str]										=  ['''input_values''', '''padding_mask''']




						def __init__(   self       ,  _lowercase = 1       ,  _lowercase = 24_000       ,  _lowercase = 0.0       ,  _lowercase = None       ,  _lowercase = None       ,  **_lowercase       ,  ):

												"""simple docstring"""



												super().__init__(feature_size=_lowercase       ,  sampling_rate=_lowercase       ,  padding_value=_lowercase       ,  **_lowercase )
												_lowerCAmelCase    		=					chunk_length_s
												_lowerCAmelCase    		=					overlap




						@property
						def    _lowercase      (   self ):

												"""simple docstring"""



												if self.chunk_length_s is None:
																		return None
												else:
																		return int(self.chunk_length_s * self.sampling_rate )




						@property
						def    _lowercase      (   self ):

												"""simple docstring"""



												if self.chunk_length_s is None or self.overlap is None:
																		return None
												else:
																		return max(1       ,  int((1.0 - self.overlap) * self.chunk_length ) )




						def __call__(   self       ,  _lowercase       ,  _lowercase = None       ,  _lowercase = False       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  ):

												"""simple docstring"""



												if sampling_rate is not None:
																		if sampling_rate != self.sampling_rate:
																								raise ValueError(
																								    F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
																								    F' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'
																								    F' {self.sampling_rate} and not {sampling_rate}.' )
												else:
																		logger.warning(
																		    """It is strongly recommended to pass the `sampling_rate` argument to this function. """
																		    """Failing to do so can result in silent errors that might be hard to debug.""" )

												if padding and truncation:
																		raise ValueError("""Both padding and truncation were set. Make sure you only set one.""" )
												elif padding is None:
																		# by default let's pad the inputs
																		_lowerCAmelCase    		=					True

												_lowerCAmelCase    		=					bool(
												    isinstance(_lowercase       ,  (list, tuple) ) and (isinstance(raw_audio[0]       ,  (np.ndarray, tuple, list) )) )

												if is_batched:
																		_lowerCAmelCase    		=					[np.asarray(_lowercase       ,  dtype=np.floataa ).T for audio in raw_audio]
												elif not is_batched and not isinstance(_lowercase       ,  np.ndarray ):
																		_lowerCAmelCase    		=					np.asarray(_lowercase       ,  dtype=np.floataa )
												elif isinstance(_lowercase       ,  np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ):
																		_lowerCAmelCase    		=					raw_audio.astype(np.floataa )

												# always return batch
												if not is_batched:
																		_lowerCAmelCase    		=					[np.asarray(_lowercase ).T]

												# verify inputs are valid
												for idx, example in enumerate(_lowercase ):
																		if example.ndim > 2:
																								raise ValueError(F'Expected input shape (channels, length) but got shape {example.shape}' )
																		if self.feature_size == 1 and example.ndim != 1:
																								raise ValueError(F'Expected mono audio but example has {example.shape[-1]} channels' )
																		if self.feature_size == 2 and example.shape[-1] != 2:
																								raise ValueError(F'Expected stereo audio but example has {example.shape[-1]} channels' )

												_lowerCAmelCase    		=					None
												_lowerCAmelCase    		=					BatchFeature({"""input_values""": raw_audio} )
												if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
																		if truncation:
																								_lowerCAmelCase    		=					min(array.shape[0] for array in raw_audio )
																								_lowerCAmelCase    		=					int(np.floor(max_length / self.chunk_stride ) )
																								_lowerCAmelCase    		=					(nb_step - 1) * self.chunk_stride + self.chunk_length
																		elif padding:
																								_lowerCAmelCase    		=					max(array.shape[0] for array in raw_audio )
																								_lowerCAmelCase    		=					int(np.ceil(max_length / self.chunk_stride ) )
																								_lowerCAmelCase    		=					(nb_step - 1) * self.chunk_stride + self.chunk_length
																								_lowerCAmelCase    		=					"""max_length"""
																		else:
																								_lowerCAmelCase    		=					input_values

        # normal padding on batch
												if padded_inputs is None:
																		_lowerCAmelCase    		=					self.pad(
																		    _lowercase       ,  max_length=_lowercase       ,  truncation=_lowercase       ,  padding=_lowercase       ,  return_attention_mask=_lowercase       ,  )
																		if padding:
																								_lowerCAmelCase    		=					padded_inputs.pop("""attention_mask""" )

												_lowerCAmelCase    		=					[]
												for example in padded_inputs.pop("""input_values""" ):
																		if self.feature_size == 1:
																								_lowerCAmelCase    		=					example[..., None]
																		input_values.append(example.T )

												_lowerCAmelCase    		=					input_values
												if return_tensors is not None:
																		_lowerCAmelCase    		=					padded_inputs.convert_to_tensors(_lowercase )

												return padded_inputs
