

import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowercase			:				List[str]   =     random.Random()

if is_torch_available():
		import torch






def        snake_case__		(    lowerCamelCase_     ,				lowerCamelCase_=1.0     ,				lowerCamelCase_=None     ,				lowerCamelCase_=None		):
							if rng is None:
														A      :					Tuple      		=					global_rng

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

							return values







class 					__lowercase  (						unittest.TestCase				):





							"""simple docstring"""

							def __init__(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase=7    ,						__UpperCAmelCase=4_00    ,						__UpperCAmelCase=20_00    ,						__UpperCAmelCase=1    ,						__UpperCAmelCase=0.0    ,						__UpperCAmelCase=1_60_00    ,						__UpperCAmelCase=True    ,						__UpperCAmelCase=True    ,						)		->       Any:
														A      :					Optional[Any]      		=					parent
														A      :					Any      		=					batch_size
														A      :					Tuple      		=					min_seq_length
														A      :					Any      		=					max_seq_length
														A      :					Optional[Any]      		=					(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
														A      :					str      		=					feature_size
														A      :					str      		=					padding_value
														A      :					Dict      		=					sampling_rate
														A      :					Union[str, Any]      		=					return_attention_mask
														A      :					List[Any]      		=					do_normalize




							def       snake_case			(					self						)		->       Optional[Any]:
														return {
														    "feature_size": self.feature_size,
														    "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    ,						__UpperCAmelCase=False    ,						__UpperCAmelCase=False						)		->       List[str]:
														def _flatten(__UpperCAmelCase						):
																					return list(itertools.chain(*__UpperCAmelCase						)						)

														if equal_length:
																					A      :					List[Any]      		=					floats_list((self.batch_size, self.max_seq_length)						)
														else:
																					# make sure that inputs increase in size
																					A      :					Union[str, Any]      		=					[
																					    _flatten(floats_list((x, self.feature_size)						)						)
																					    for x in range(self.min_seq_length    ,						self.max_seq_length    ,						self.seq_length_diff						)
																					]

														if numpify:
																					A      :					Optional[Any]      		=					[np.asarray(__UpperCAmelCase						) for x in speech_inputs]

														return speech_inputs







@require_torch
@require_torchaudio
class 					__lowercase  (						_SCREAMING_SNAKE_CASE		,       unittest.TestCase				):





							"""simple docstring"""

							UpperCAmelCase_						:		str								=	ASTFeatureExtractor




							def       snake_case			(					self						)		->       int:
														A      :					Tuple      		=					ASTFeatureExtractionTester(self						)




							def       snake_case			(					self						)		->       Any:
														# Tests that all call wrap to encode_plus and batch_encode_plus
														A      :					int      		=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
														# create three inputs of length 800, 1000, and 1200
														A      :					Any      		=					[floats_list((1, x)						)[0] for x in range(8_00    ,						14_00    ,						2_00						)]
														A      :					Tuple      		=					[np.asarray(__UpperCAmelCase						) for speech_input in speech_inputs]

														# Test not batched input
														A      :					Union[str, Any]      		=					feat_extract(speech_inputs[0]    ,						return_tensors='''np'''						).input_values
														A      :					Dict      		=					feat_extract(np_speech_inputs[0]    ,						return_tensors='''np'''						).input_values
														self.assertTrue(np.allclose(__UpperCAmelCase    ,						__UpperCAmelCase    ,						atol=1E-3						)						)

														# Test batched
														A      :					int      		=					feat_extract(__UpperCAmelCase    ,						padding=__UpperCAmelCase    ,						return_tensors='''np'''						).input_values
														A      :					Dict      		=					feat_extract(__UpperCAmelCase    ,						padding=__UpperCAmelCase    ,						return_tensors='''np'''						).input_values
														for enc_seq_a, enc_seq_a in zip(__UpperCAmelCase    ,						__UpperCAmelCase						):
																					self.assertTrue(np.allclose(__UpperCAmelCase    ,						__UpperCAmelCase    ,						atol=1E-3						)						)

														# Test 2-D numpy arrays are batched.
														A      :					Dict      		=					[floats_list((1, x)						)[0] for x in (8_00, 8_00, 8_00)]
														A      :					str      		=					np.asarray(__UpperCAmelCase						)
														A      :					List[str]      		=					feat_extract(__UpperCAmelCase    ,						return_tensors='''np'''						).input_values
														A      :					List[Any]      		=					feat_extract(__UpperCAmelCase    ,						return_tensors='''np'''						).input_values
														for enc_seq_a, enc_seq_a in zip(__UpperCAmelCase    ,						__UpperCAmelCase						):
																					self.assertTrue(np.allclose(__UpperCAmelCase    ,						__UpperCAmelCase    ,						atol=1E-3						)						)




							@require_torch
							def       snake_case			(					self						)		->       int:
														import torch

														A      :					List[Any]      		=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
														A      :					Optional[int]      		=					np.random.rand(1_00						).astype(np.floataa						)
														A      :					str      		=					np_speech_inputs.tolist()

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




							def       snake_case			(					self    ,						__UpperCAmelCase						)		->       Any:
														from datasets import load_dataset

														A      :					List[Any]      		=					load_dataset('''hf-internal-testing/librispeech_asr_dummy'''    ,						'''clean'''    ,						split='''validation'''						)
														# automatic decoding with librispeech
														A      :					Optional[int]      		=					ds.sort('''id'''						).select(range(__UpperCAmelCase						)						)[:num_samples]['''audio''']

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






							@require_torch
							def       snake_case			(					self						)		->       List[str]:
														# fmt: off
														A      :					Any      		=					torch.tensor(
														    [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
														     -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
														     -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
														     -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9]						)
														# fmt: on

														A      :					Optional[int]      		=					self._load_datasamples(1						)
														A      :					Any      		=					ASTFeatureExtractor()
														A      :					List[str]      		=					feature_extractor(__UpperCAmelCase    ,						return_tensors='''pt'''						).input_values
														self.assertEquals(input_values.shape    ,						(1, 10_24, 1_28)						)
														self.assertTrue(torch.allclose(input_values[0, 0, :30]    ,						__UpperCAmelCase    ,						atol=1E-4						)						)









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, 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, is_vision_available, logging


if is_vision_available():
		import PIL


lowercase			:				Tuple   =     logging.get_logger(__name__)







class 					__lowercase  (						_SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		Optional[Any]								=	['''pixel_values''']




							def __init__(					self    ,						__UpperCAmelCase = True    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = PIL.Image.BICUBIC    ,						__UpperCAmelCase = True    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = 1 / 2_55    ,						__UpperCAmelCase = True    ,						__UpperCAmelCase = True    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						**__UpperCAmelCase    ,						)		->       None:
														super().__init__(**__UpperCAmelCase						)
														A      :					Any      		=					size if size is not None else {'''height''': 2_56, '''width''': 2_56}
														A      :					Any      		=					get_size_dict(__UpperCAmelCase						)
														A      :					List[Any]      		=					crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
														A      :					List[Any]      		=					get_size_dict(__UpperCAmelCase    ,						param_name='''crop_size'''						)

														A      :					Dict      		=					do_resize
														A      :					Tuple      		=					size
														A      :					Union[str, Any]      		=					resample
														A      :					Dict      		=					do_center_crop
														A      :					int      		=					crop_size
														A      :					Union[str, Any]      		=					do_rescale
														A      :					str      		=					rescale_factor
														A      :					Optional[Any]      		=					do_normalize
														A      :					Dict      		=					image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
														A      :					Dict      		=					image_std if image_std is not None else IMAGENET_STANDARD_STD




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase = PIL.Image.BICUBIC    ,						__UpperCAmelCase = None    ,						**__UpperCAmelCase    ,						)		->       np.ndarray:
														A      :					int      		=					get_size_dict(__UpperCAmelCase						)
														if "height" not in size or "width" not in size:
																					raise ValueError(f'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'						)
														return resize(
														    __UpperCAmelCase    ,						size=(size['''height'''], size['''width'''])    ,						resample=__UpperCAmelCase    ,						data_format=__UpperCAmelCase    ,						**__UpperCAmelCase						)




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase = None    ,						**__UpperCAmelCase    ,						)		->       np.ndarray:
														A      :					Optional[Any]      		=					get_size_dict(__UpperCAmelCase						)
														if "height" not in size or "width" not in size:
																					raise ValueError(f'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'						)
														return center_crop(__UpperCAmelCase    ,						size=(size['''height'''], size['''width'''])    ,						data_format=__UpperCAmelCase    ,						**__UpperCAmelCase						)




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase = None    ,						**__UpperCAmelCase    ,						)		->       List[str]:
														return rescale(__UpperCAmelCase    ,						scale=__UpperCAmelCase    ,						data_format=__UpperCAmelCase    ,						**__UpperCAmelCase						)




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase = None    ,						**__UpperCAmelCase    ,						)		->       np.ndarray:
														return normalize(__UpperCAmelCase    ,						mean=__UpperCAmelCase    ,						std=__UpperCAmelCase    ,						data_format=__UpperCAmelCase    ,						**__UpperCAmelCase						)






							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = None    ,						__UpperCAmelCase = ChannelDimension.FIRST    ,						**__UpperCAmelCase    ,						)		->       PIL.Image.Image:
														A      :					Optional[int]      		=					do_resize if do_resize is not None else self.do_resize
														A      :					Optional[Any]      		=					resample if resample is not None else self.resample
														A      :					Tuple      		=					do_center_crop if do_center_crop is not None else self.do_center_crop
														A      :					Optional[Any]      		=					do_rescale if do_rescale is not None else self.do_rescale
														A      :					str      		=					rescale_factor if rescale_factor is not None else self.rescale_factor
														A      :					Tuple      		=					do_normalize if do_normalize is not None else self.do_normalize
														A      :					Optional[int]      		=					image_mean if image_mean is not None else self.image_mean
														A      :					Dict      		=					image_std if image_std is not None else self.image_std

														A      :					List[Any]      		=					size if size is not None else self.size
														A      :					List[Any]      		=					get_size_dict(__UpperCAmelCase						)
														A      :					Dict      		=					crop_size if crop_size is not None else self.crop_size
														A      :					Tuple      		=					get_size_dict(__UpperCAmelCase    ,						param_name='''crop_size'''						)

														A      :					Any      		=					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 or resample is None:
																					raise ValueError('''Size and resample 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.
														A      :					List[Any]      		=					[to_numpy_array(__UpperCAmelCase						) for image in images]

														if do_resize:
																					A      :					List[str]      		=					[self.resize(image=__UpperCAmelCase    ,						size=__UpperCAmelCase    ,						resample=__UpperCAmelCase						) for image in images]

														if do_center_crop:
																					A      :					Dict      		=					[self.center_crop(image=__UpperCAmelCase    ,						size=__UpperCAmelCase						) for image in images]

														if do_rescale:
																					A      :					Union[str, Any]      		=					[self.rescale(image=__UpperCAmelCase    ,						scale=__UpperCAmelCase						) for image in images]

														if do_normalize:
																					A      :					Tuple      		=					[self.normalize(image=__UpperCAmelCase    ,						mean=__UpperCAmelCase    ,						std=__UpperCAmelCase						) for image in images]

														A      :					Optional[Any]      		=					[to_channel_dimension_format(__UpperCAmelCase    ,						__UpperCAmelCase						) for image in images]

														A      :					List[Any]      		=					{'''pixel_values''': images}
														return BatchFeature(data=__UpperCAmelCase    ,						tensor_type=__UpperCAmelCase						)






