



'''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

lowercase							       =			random.Random()






def  UpperCAmelCase_       (		lowercase__       ,	lowercase__=1.0       ,	lowercase__=None       ,	lowercase__=None       ):


					'''simple docstring'''







					if rng is None:
										a_       		=global_rng

					a_       		=[]
					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 	UpperCAmelCase	(		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							,  ) ->      str:



						"""simple docstring"""







						a_       		=parent
						a_       		=batch_size
						a_       		=min_seq_length
						a_       		=max_seq_length
						a_       		=(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
						a_       		=padding_value
						a_       		=sampling_rate
						a_       		=return_attention_mask
						a_       		=do_normalize
						a_       		=feature_size
						a_       		=chunk_length
						a_       		=hop_length




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



						"""simple docstring"""







						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       lowercase_  (   self							,  lowerCAmelCase_=False							,  lowerCAmelCase_=False) ->      Dict:



						"""simple docstring"""







						def _flatten(lowerCAmelCase_):
											return list(itertools.chain(*lowercase_))

						if equal_length:
											a_       		=[floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
						else:
											# make sure that inputs increase in size
											a_       		=[
											    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_       		=[np.asarray(lowercase_) for x in speech_inputs]
						return speech_inputs







@require_torch
@require_torchaudio
class 	UpperCAmelCase	(		snake_case__					,	unittest.TestCase):


	'''simple docstring'''




	__magic_name__					: Dict  =      WhisperFeatureExtractor if is_speech_available() else None




	def       lowercase_  (   self) ->      List[Any]:



						"""simple docstring"""







						a_       		=WhisperFeatureExtractionTester(self)




	def       lowercase_  (   self) ->      Any:



						"""simple docstring"""







						a_       		=self.feature_extraction_class(**self.feat_extract_dict)

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

						a_       		=feat_extract_first.to_dict()
						a_       		=feat_extract_second.to_dict()
						a_       		=feat_extract_first.mel_filters
						a_       		=feat_extract_second.mel_filters
						self.assertTrue(np.allclose(lowercase_							,  lowercase_))
						self.assertEqual(lowercase_							,  lowercase_)




	def       lowercase_  (   self) ->      Dict:



						"""simple docstring"""







						a_       		=self.feature_extraction_class(**self.feat_extract_dict)

						with tempfile.TemporaryDirectory() as tmpdirname:
											a_       		=os.path.join(lowercase_							,  "feat_extract.json")
											feat_extract_first.to_json_file(lowercase_)
											a_       		=self.feature_extraction_class.from_json_file(lowercase_)

						a_       		=feat_extract_first.to_dict()
						a_       		=feat_extract_second.to_dict()
						a_       		=feat_extract_first.mel_filters
						a_       		=feat_extract_second.mel_filters
						self.assertTrue(np.allclose(lowercase_							,  lowercase_))
						self.assertEqual(lowercase_							,  lowercase_)




	def       lowercase_  (   self) ->      Optional[Any]:



						"""simple docstring"""







						a_       		=self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
						# create three inputs of length 800, 1000, and 1200
						a_       		=[floats_list((1, x))[0] for x in range(8_0_0							,  1_4_0_0							,  2_0_0)]
						a_       		=[np.asarray(lowercase_) for speech_input in speech_inputs]

						# Test feature size
						a_       		=feature_extractor(lowercase_							,  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
						a_       		=feature_extractor(speech_inputs[0]							,  return_tensors="np").input_features
						a_       		=feature_extractor(np_speech_inputs[0]							,  return_tensors="np").input_features
						self.assertTrue(np.allclose(lowercase_							,  lowercase_							,  atol=1e-3))

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

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

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

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

						a_       		=feature_extractor(lowercase_							,  return_tensors="np").input_features
						a_       		=feature_extractor(lowercase_							,  return_tensors="np").input_features
						for enc_seq_a, enc_seq_a in zip(lowercase_							,  lowercase_):
											self.assertTrue(np.allclose(lowercase_							,  lowercase_							,  atol=1e-3))




	def       lowercase_  (   self) ->      Optional[Any]:



						"""simple docstring"""







						import torch

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

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




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



						"""simple docstring"""







						a_       		=load_dataset("hf-internal-testing/librispeech_asr_dummy"							,  "clean"							,  split="validation")
						# automatic decoding with librispeech
						a_       		=ds.sort("id").select(range(lowercase_))[:num_samples]["audio"]

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




	def       lowercase_  (   self) ->      Tuple:



						"""simple docstring"""







						a_       		=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

						a_       		=self._load_datasamples(1)
						a_       		=WhisperFeatureExtractor()
						a_       		=feature_extractor(lowercase_							,  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]							,  lowercase_							,  atol=1e-4))




	def       lowercase_  (   self) ->      Tuple:



						"""simple docstring"""







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

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







'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


lowercase							       =			{
    '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig''']
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase							       =			['''VisionEncoderDecoderModel''']

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase							       =			['''TFVisionEncoderDecoderModel''']

try:
  if not is_flax_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase							       =			['''FlaxVisionEncoderDecoderModel''']

if TYPE_CHECKING:
  from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel

  try:
    if not is_flax_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel

else:
  import sys

  lowercase							       =			_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


