



"""simple docstring"""
from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__SCREAMING_SNAKE_CASE  :						List[str]    							=      logging.get_logger(__name__)


class 							lowerCamelCase_(   __A    ):





     '''simple docstring'''



     lowercase__   :       Optional[Any]										= ["""pixel_values"""]

     def __init__(    self				,       lowerCamelCase__ = True				,       lowerCamelCase__ = None				,       lowerCamelCase__ = PILImageResampling.BILINEAR				,       lowerCamelCase__ = True				,       lowerCamelCase__ = None				,       lowerCamelCase__ = True				,       lowerCamelCase__ = 1 / 2_5_5				,       lowerCamelCase__ = True				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       **lowerCamelCase__				,       ):
         super().__init__(**UpperCamelCase__   )
         _lowerCamelCase        =				size if size is not None else {'shortest_edge': 2_5_6}
         _lowerCamelCase        =				get_size_dict(UpperCamelCase__				,       default_to_square=UpperCamelCase__   )
         _lowerCamelCase        =				crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
         _lowerCamelCase        =				get_size_dict(UpperCamelCase__   )
         _lowerCamelCase        =				do_resize
         _lowerCamelCase        =				size
         _lowerCamelCase        =				resample
         _lowerCamelCase        =				do_center_crop
         _lowerCamelCase        =				crop_size
         _lowerCamelCase        =				do_rescale
         _lowerCamelCase        =				rescale_factor
         _lowerCamelCase        =				do_normalize
         _lowerCamelCase        =				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         _lowerCamelCase        =				image_std if image_std is not None else IMAGENET_STANDARD_STD

     def 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__ = PILImageResampling.BICUBIC				,       lowerCamelCase__ = None				,       **lowerCamelCase__				,       ):
         _lowerCamelCase        =				get_size_dict(UpperCamelCase__				,       default_to_square=UpperCamelCase__   )
         if "shortest_edge" not in size:
             raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""   )
         _lowerCamelCase        =				get_resize_output_image_size(UpperCamelCase__				,       size=size['''shortest_edge''']				,       default_to_square=UpperCamelCase__   )
         return resize(UpperCamelCase__				,       size=UpperCamelCase__				,       resample=UpperCamelCase__				,       data_format=UpperCamelCase__				,       **UpperCamelCase__   )

     def 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__ = None				,       **lowerCamelCase__				,       ):
         _lowerCamelCase        =				get_size_dict(UpperCamelCase__   )
         return center_crop(UpperCamelCase__				,       size=(size['''height'''], size['''width'''])				,       data_format=UpperCamelCase__				,       **UpperCamelCase__   )

     def 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__ = None				,       **lowerCamelCase__   ):
         return rescale(UpperCamelCase__				,       scale=UpperCamelCase__				,       data_format=UpperCamelCase__				,       **UpperCamelCase__   )

     def 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__ = None				,       **lowerCamelCase__				,       ):
         return normalize(UpperCamelCase__				,       mean=UpperCamelCase__				,       std=UpperCamelCase__				,       data_format=UpperCamelCase__				,       **UpperCamelCase__   )





     def 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = ChannelDimension.FIRST				,       **lowerCamelCase__				,       ):
         _lowerCamelCase        =				do_resize if do_resize is not None else self.do_resize
         _lowerCamelCase        =				size if size is not None else self.size
         _lowerCamelCase        =				get_size_dict(UpperCamelCase__				,       default_to_square=UpperCamelCase__   )
         _lowerCamelCase        =				resample if resample is not None else self.resample
         _lowerCamelCase        =				do_center_crop if do_center_crop is not None else self.do_center_crop
         _lowerCamelCase        =				crop_size if crop_size is not None else self.crop_size
         _lowerCamelCase        =				get_size_dict(UpperCamelCase__   )
         _lowerCamelCase        =				do_rescale if do_rescale is not None else self.do_rescale
         _lowerCamelCase        =				rescale_factor if rescale_factor is not None else self.rescale_factor
         _lowerCamelCase        =				do_normalize if do_normalize is not None else self.do_normalize
         _lowerCamelCase        =				image_mean if image_mean is not None else self.image_mean
         _lowerCamelCase        =				image_std if image_std is not None else self.image_std

         _lowerCamelCase        =				make_list_of_images(UpperCamelCase__   )

         if not valid_images(UpperCamelCase__   ):
             raise ValueError(
                 '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                 '''torch.Tensor, tf.Tensor or jax.ndarray.'''   )

         if do_resize and size is None:
             raise ValueError('''Size must be specified if do_resize is True.'''   )

         if do_center_crop and crop_size is None:
             raise ValueError('''Crop size must be specified if do_center_crop is True.'''   )

         if do_rescale and rescale_factor is None:
             raise ValueError('''Rescale factor must be specified if do_rescale is True.'''   )

         if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('''Image mean and std must be specified if do_normalize is True.'''   )

         # All transformations expect numpy arrays.
         _lowerCamelCase        =				[to_numpy_array(UpperCamelCase__   ) for image in images]

         if do_resize:
             _lowerCamelCase        =				[self.resize(image=UpperCamelCase__				,       size=UpperCamelCase__				,       resample=UpperCamelCase__   ) for image in images]

         if do_center_crop:
             _lowerCamelCase        =				[self.center_crop(image=UpperCamelCase__				,       size=UpperCamelCase__   ) for image in images]

         if do_rescale:
             _lowerCamelCase        =				[self.rescale(image=UpperCamelCase__				,       scale=UpperCamelCase__   ) for image in images]

         if do_normalize:
             _lowerCamelCase        =				[self.normalize(image=UpperCamelCase__				,       mean=UpperCamelCase__				,       std=UpperCamelCase__   ) for image in images]

         _lowerCamelCase        =				[to_channel_dimension_format(UpperCamelCase__				,       UpperCamelCase__   ) for image in images]

         _lowerCamelCase        =				{'pixel_values': images}
         return BatchFeature(data=UpperCamelCase__				,       tensor_type=UpperCamelCase__   )





"""simple docstring"""
import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
			from transformers import WhisperFeatureExtractor

if is_torch_available():
			import torch

__SCREAMING_SNAKE_CASE  :						Dict    							=      random.Random()



def        lowerCAmelCase_(   lowercase_     :							Dict						,   lowercase_     :							int=1.0						,   lowercase_     :							str=None						,   lowercase_     :							Optional[int]=None							)	->       Any:
				if rng is None:
								_lowerCamelCase        =				global_rng

				_lowerCamelCase        =				[]
				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_torchaudio
class 							lowerCamelCase_(   unittest.TestCase    ):





					'''simple docstring'''



					def __init__(    self				,       lowerCamelCase__				,       lowerCamelCase__=7				,       lowerCamelCase__=4_0_0				,       lowerCamelCase__=2_0_0_0				,       lowerCamelCase__=1_0				,       lowerCamelCase__=1_6_0				,       lowerCamelCase__=8				,       lowerCamelCase__=0.0				,       lowerCamelCase__=4_0_0_0				,       lowerCamelCase__=False				,       lowerCamelCase__=True				,       ):
									_lowerCamelCase        =				parent
									_lowerCamelCase        =				batch_size
									_lowerCamelCase        =				min_seq_length
									_lowerCamelCase        =				max_seq_length
									_lowerCamelCase        =				(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									_lowerCamelCase        =				padding_value
									_lowerCamelCase        =				sampling_rate
									_lowerCamelCase        =				return_attention_mask
									_lowerCamelCase        =				do_normalize
									_lowerCamelCase        =				feature_size
									_lowerCamelCase        =				chunk_length
									_lowerCamelCase        =				hop_length

					def 			snake_case__      (    self   ):
									return {
									    "feature_size": self.feature_size,
									    "hop_length": self.hop_length,
									    "chunk_length": self.chunk_length,
									    "padding_value": self.padding_value,
									    "sampling_rate": self.sampling_rate,
									    "return_attention_mask": self.return_attention_mask,
									    "do_normalize": self.do_normalize,
									}





					def 			snake_case__      (    self				,       lowerCamelCase__=False				,       lowerCamelCase__=False   ):
									def _flatten(lowerCamelCase__   ):
													return list(itertools.chain(*lowerCamelCase__   )   )

									if equal_length:
													_lowerCamelCase        =				[floats_list((self.max_seq_length, self.feature_size)   ) for _ in range(self.batch_size   )]
									else:
													# make sure that inputs increase in size
													_lowerCamelCase        =				[
													    floats_list((x, self.feature_size)   )
													    for x in range(self.min_seq_length				,       self.max_seq_length				,       self.seq_length_diff   )
													]
									if numpify:
													_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for x in speech_inputs]
									return speech_inputs


@require_torch
@require_torchaudio
class 							lowerCamelCase_(   A__,				unittest.TestCase    ):





					'''simple docstring'''



					lowercase__   :       Optional[int]										= WhisperFeatureExtractor if is_speech_available() else None

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				WhisperFeatureExtractionTester(self   )

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_dict   )

									with tempfile.TemporaryDirectory() as tmpdirname:
													_lowerCamelCase        =				feat_extract_first.save_pretrained(lowerCamelCase__   )[0]
													check_json_file_has_correct_format(lowerCamelCase__   )
													_lowerCamelCase        =				self.feature_extraction_class.from_pretrained(lowerCamelCase__   )

									_lowerCamelCase        =				feat_extract_first.to_dict()
									_lowerCamelCase        =				feat_extract_second.to_dict()
									_lowerCamelCase        =				feat_extract_first.mel_filters
									_lowerCamelCase        =				feat_extract_second.mel_filters
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__   )   )
									self.assertEqual(lowerCamelCase__				,       lowerCamelCase__   )

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_dict   )

									with tempfile.TemporaryDirectory() as tmpdirname:
													_lowerCamelCase        =				os.path.join(lowerCamelCase__				,       '''feat_extract.json'''   )
													feat_extract_first.to_json_file(lowerCamelCase__   )
													_lowerCamelCase        =				self.feature_extraction_class.from_json_file(lowerCamelCase__   )

									_lowerCamelCase        =				feat_extract_first.to_dict()
									_lowerCamelCase        =				feat_extract_second.to_dict()
									_lowerCamelCase        =				feat_extract_first.mel_filters
									_lowerCamelCase        =				feat_extract_second.mel_filters
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__   )   )
									self.assertEqual(lowerCamelCase__				,       lowerCamelCase__   )

					def 			snake_case__      (    self   ):
									# Tests that all call wrap to encode_plus and batch_encode_plus
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									# create three inputs of length 800, 1000, and 1200
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in range(8_0_0				,       1_4_0_0				,       2_0_0   )]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs]

									# Test feature size
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       padding='''max_length'''				,       return_tensors='''np'''   ).input_features
									self.assertTrue(input_features.ndim == 3   )
									self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames   )
									self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size   )

									# Test not batched input
									_lowerCamelCase        =				feature_extractor(speech_inputs[0]				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(np_speech_inputs[0]				,       return_tensors='''np'''   ).input_features
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

									# Test batched
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									for enc_seq_a, enc_seq_a in zip(lowerCamelCase__				,       lowerCamelCase__   ):
													self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

									# Test 2-D numpy arrays are batched.
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
									_lowerCamelCase        =				np.asarray(lowerCamelCase__   )
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									for enc_seq_a, enc_seq_a in zip(lowerCamelCase__				,       lowerCamelCase__   ):
													self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

									# Test truncation required
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in range(2_0_0				,       (feature_extractor.n_samples + 5_0_0)				,       2_0_0   )]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs]

									_lowerCamelCase        =				[x[: feature_extractor.n_samples] for x in speech_inputs]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs_truncated]

									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									for enc_seq_a, enc_seq_a in zip(lowerCamelCase__				,       lowerCamelCase__   ):
													self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

					def 			snake_case__      (    self   ):
									import torch

									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									_lowerCamelCase        =				np.random.rand(1_0_0				,       3_2   ).astype(np.floataa   )
									_lowerCamelCase        =				np_speech_inputs.tolist()

									for inputs in [py_speech_inputs, np_speech_inputs]:
													_lowerCamelCase        =				feature_extractor.pad([{'''input_features''': inputs}]				,       return_tensors='''np'''   )
													self.assertTrue(np_processed.input_features.dtype == np.floataa   )
													_lowerCamelCase        =				feature_extractor.pad([{'''input_features''': inputs}]				,       return_tensors='''pt'''   )
													self.assertTrue(pt_processed.input_features.dtype == torch.floataa   )

					def 			snake_case__      (    self				,       lowerCamelCase__   ):
									_lowerCamelCase        =				load_dataset('''hf-internal-testing/librispeech_asr_dummy'''				,       '''clean'''				,       split='''validation'''   )
									# automatic decoding with librispeech
									_lowerCamelCase        =				ds.sort('''id'''   ).select(range(lowerCamelCase__   )   )[:num_samples]['''audio''']

									return [x["array"] for x in speech_samples]

					def 			snake_case__      (    self   ):
									# fmt: off
									_lowerCamelCase        =				torch.tensor(
									    [
									        0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
									        0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
									        0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
									        -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
									    ]   )
									# fmt: on

									_lowerCamelCase        =				self._load_datasamples(1   )
									_lowerCamelCase        =				WhisperFeatureExtractor()
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''pt'''   ).input_features
									self.assertEqual(input_features.shape				,       (1, 8_0, 3_0_0_0)   )
									self.assertTrue(torch.allclose(input_features[0, 0, :3_0]				,       lowerCamelCase__				,       atol=1e-4   )   )





					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									_lowerCamelCase        =				self._load_datasamples(1   )[0]
									_lowerCamelCase        =				((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5  # Rescale to [0, 65535] to show issue
									_lowerCamelCase        =				feat_extract.zero_mean_unit_var_norm([audio]				,       attention_mask=lowerCamelCase__   )[0]

									self.assertTrue(np.all(np.mean(lowerCamelCase__   ) < 1e-3   )   )
									self.assertTrue(np.all(np.abs(np.var(lowerCamelCase__   ) - 1   ) < 1e-3   )   )
