





import itertools
import random
import unittest

import numpy as np

from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
  import torch


UpperCAmelCase_     							= random.Random()




def 		lowerCAmelCase_    (  __UpperCAmelCase:			Dict		,   __UpperCAmelCase:			Union[str, Any]=1.0		,   __UpperCAmelCase:			int=None		,   __UpperCAmelCase:			int=None      )      ->	List[str]:
    if rng is None:
        UpperCamelCase__							:				List[str]          =      global_rng

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

    return values






@require_torch
class     lowercase__       (	unittest.TestCase				):

   '''simple docstring'''


   def __init__(    self,		__magic_name__,		__magic_name__=7,		__magic_name__=400,		__magic_name__=2000,		__magic_name__=1,		__magic_name__=0.0,		__magic_name__=16000,		__magic_name__=True,		__magic_name__=80,		__magic_name__=16,		__magic_name__=64,		__magic_name__="hann_window",		__magic_name__=80,		__magic_name__=7600,		__magic_name__=1E-10,		__magic_name__=True,		) ->      List[str]:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      parent
       UpperCamelCase__							:				List[str]          =      batch_size
       UpperCamelCase__							:				Optional[int]          =      min_seq_length
       UpperCamelCase__							:				Tuple          =      max_seq_length
       UpperCamelCase__							:				Optional[int]          =      (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
       UpperCamelCase__							:				Optional[int]          =      feature_size
       UpperCamelCase__							:				str          =      padding_value
       UpperCamelCase__							:				Tuple          =      sampling_rate
       UpperCamelCase__							:				Any          =      do_normalize
       UpperCamelCase__							:				int          =      num_mel_bins
       UpperCamelCase__							:				Dict          =      hop_length
       UpperCamelCase__							:				List[Any]          =      win_length
       UpperCamelCase__							:				List[Any]          =      win_function
       UpperCamelCase__							:				List[str]          =      fmin
       UpperCamelCase__							:				Any          =      fmax
       UpperCamelCase__							:				Dict          =      mel_floor
       UpperCamelCase__							:				Tuple          =      return_attention_mask




   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       return {
           "feature_size": self.feature_size,
           "padding_value": self.padding_value,
           "sampling_rate": self.sampling_rate,
           "do_normalize": self.do_normalize,
           "num_mel_bins": self.num_mel_bins,
           "hop_length": self.hop_length,
           "win_length": self.win_length,
           "win_function": self.win_function,
           "fmin": self.fmin,
           "fmax": self.fmax,
           "mel_floor": self.mel_floor,
           "return_attention_mask": self.return_attention_mask,
       }




   def       UpperCamelCase__  (    self,		__magic_name__=False,		__magic_name__=False							) ->      str:






       """simple docstring"""
       def _flatten(__magic_name__							):
           return list(itertools.chain(*__magic_name__							)							)

       if equal_length:
           UpperCamelCase__							:				str          =      floats_list((self.batch_size, self.max_seq_length)							)
       else:
           # make sure that inputs increase in size
           UpperCamelCase__							:				List[str]          =      [
               _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:
           UpperCamelCase__							:				Optional[int]          =      [np.asarray(__magic_name__							) for x in speech_inputs]

       return speech_inputs




   def       UpperCamelCase__  (    self,		__magic_name__=False,		__magic_name__=False							) ->      List[Any]:






       """simple docstring"""
       if equal_length:
           UpperCamelCase__							:				Dict          =      [floats_list((self.max_seq_length, self.num_mel_bins)							) for _ in range(self.batch_size							)]
       else:
           # make sure that inputs increase in size
           UpperCamelCase__							:				List[Any]          =      [
               floats_list((x, self.num_mel_bins)							)
               for x in range(self.min_seq_length,		self.max_seq_length,		self.seq_length_diff							)
           ]

       if numpify:
           UpperCamelCase__							:				Any          =      [np.asarray(__magic_name__							) for x in speech_inputs]

       return speech_inputs






@require_torch
class     lowercase__       (	__lowerCamelCase			,				unittest.TestCase				):

   '''simple docstring'''


   a						:							Dict   		=		SpeechTaFeatureExtractor




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      SpeechTaFeatureExtractionTester(self							)




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      Tuple:






       """simple docstring"""
       self.assertTrue(np.all(np.mean(__magic_name__,		axis=0							) < 1E-3							)							)
       self.assertTrue(np.all(np.abs(np.var(__magic_name__,		axis=0							) - 1							) < 1E-3							)							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       # Tests that all call wrap to encode_plus and batch_encode_plus
       UpperCamelCase__							:				Optional[Any]          =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
       # create three inputs of length 800, 1000, and 1200
       UpperCamelCase__							:				List[Any]          =      [floats_list((1, x)							)[0] for x in range(800,		1400,		200							)]
       UpperCamelCase__							:				List[str]          =      [np.asarray(__magic_name__							) for speech_input in speech_inputs]

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

       # Test batched
       UpperCamelCase__							:				Optional[int]          =      feat_extract(__magic_name__,		return_tensors='''np'''							).input_values
       UpperCamelCase__							:				str          =      feat_extract(__magic_name__,		return_tensors='''np'''							).input_values
       for enc_seq_a, enc_seq_a in zip(__magic_name__,		__magic_name__							):
           self.assertTrue(np.allclose(__magic_name__,		__magic_name__,		atol=1E-3							)							)




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






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
       UpperCamelCase__							:				str          =      [floats_list((1, x)							)[0] for x in range(800,		1400,		200							)]

       UpperCamelCase__							:				Any          =      ['''longest''', '''max_length''', '''do_not_pad''']
       UpperCamelCase__							:				Union[str, Any]          =      [None, 1600, None]
       for max_length, padding in zip(__magic_name__,		__magic_name__							):
           UpperCamelCase__							:				List[Any]          =      feat_extract(__magic_name__,		padding=__magic_name__,		max_length=__magic_name__,		return_tensors='''np'''							)
           UpperCamelCase__							:				Any          =      processed.input_values

           self._check_zero_mean_unit_variance(input_values[0][:800]							)
           self.assertTrue(input_values[0][800:].sum() < 1E-6							)
           self._check_zero_mean_unit_variance(input_values[1][:1000]							)
           self.assertTrue(input_values[0][1000:].sum() < 1E-6							)
           self._check_zero_mean_unit_variance(input_values[2][:1200]							)




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






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
       UpperCamelCase__							:				Dict          =      range(800,		1400,		200							)
       UpperCamelCase__							:				Optional[Any]          =      [floats_list((1, x)							)[0] for x in lengths]

       UpperCamelCase__							:				List[str]          =      ['''longest''', '''max_length''', '''do_not_pad''']
       UpperCamelCase__							:				Optional[Any]          =      [None, 1600, None]

       for max_length, padding in zip(__magic_name__,		__magic_name__							):
           UpperCamelCase__							:				Tuple          =      feat_extract(__magic_name__,		max_length=__magic_name__,		padding=__magic_name__							)
           UpperCamelCase__							:				Tuple          =      processed.input_values

           self._check_zero_mean_unit_variance(input_values[0][:800]							)
           self._check_zero_mean_unit_variance(input_values[1][:1000]							)
           self._check_zero_mean_unit_variance(input_values[2][:1200]							)




   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
       UpperCamelCase__							:				Tuple          =      [floats_list((1, x)							)[0] for x in range(800,		1400,		200							)]
       UpperCamelCase__							:				str          =      feat_extract(
           __magic_name__,		truncation=__magic_name__,		max_length=1000,		padding='''max_length''',		return_tensors='''np'''							)
       UpperCamelCase__							:				Dict          =      processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]							)
       self._check_zero_mean_unit_variance(input_values[1]							)
       self._check_zero_mean_unit_variance(input_values[2]							)




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






       """simple docstring"""
       UpperCamelCase__							:				int          =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
       UpperCamelCase__							:				Optional[int]          =      [floats_list((1, x)							)[0] for x in range(800,		1400,		200							)]
       UpperCamelCase__							:				Union[str, Any]          =      feat_extract(
           __magic_name__,		truncation=__magic_name__,		max_length=1000,		padding='''longest''',		return_tensors='''np'''							)
       UpperCamelCase__							:				List[Any]          =      processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]							)
       self._check_zero_mean_unit_variance(input_values[1, :1000]							)
       self._check_zero_mean_unit_variance(input_values[2]							)

       # make sure that if max_length < longest -> then pad to max_length
       self.assertTrue(input_values.shape == (3, 1000)							)

       UpperCamelCase__							:				List[Any]          =      [floats_list((1, x)							)[0] for x in range(800,		1400,		200							)]
       UpperCamelCase__							:				Dict          =      feat_extract(
           __magic_name__,		truncation=__magic_name__,		max_length=2000,		padding='''longest''',		return_tensors='''np'''							)
       UpperCamelCase__							:				Optional[int]          =      processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]							)
       self._check_zero_mean_unit_variance(input_values[1, :1000]							)
       self._check_zero_mean_unit_variance(input_values[2]							)

       # make sure that if max_length > longest -> then pad to longest
       self.assertTrue(input_values.shape == (3, 1200)							)




   def       UpperCamelCase__  (    self							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
       UpperCamelCase__							:				int          =      np.random.rand(100							).astype(np.floataa							)
       UpperCamelCase__							:				Union[str, Any]          =      np_speech_inputs.tolist()

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




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       # Tests that all call wrap to encode_plus and batch_encode_plus
       UpperCamelCase__							:				Any          =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
       # create three inputs of length 800, 1000, and 1200
       UpperCamelCase__							:				Dict          =      [floats_list((1, x)							)[0] for x in range(800,		1400,		200							)]
       UpperCamelCase__							:				List[Any]          =      [np.asarray(__magic_name__							) for speech_input in speech_inputs]

       # Test feature size
       UpperCamelCase__							:				Optional[Any]          =      feature_extractor(audio_target=__magic_name__,		padding=__magic_name__,		return_tensors='''np'''							).input_values
       self.assertTrue(input_values.ndim == 3							)
       self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins							)

       # Test not batched input
       UpperCamelCase__							:				Optional[Any]          =      feature_extractor(speech_inputs[0],		return_tensors='''np'''							).input_values
       UpperCamelCase__							:				Optional[Any]          =      feature_extractor(np_speech_inputs[0],		return_tensors='''np'''							).input_values
       self.assertTrue(np.allclose(__magic_name__,		__magic_name__,		atol=1E-3							)							)

       # Test batched
       UpperCamelCase__							:				List[str]          =      feature_extractor(__magic_name__,		return_tensors='''np'''							).input_values
       UpperCamelCase__							:				List[Any]          =      feature_extractor(__magic_name__,		return_tensors='''np'''							).input_values
       for enc_seq_a, enc_seq_a in zip(__magic_name__,		__magic_name__							):
           self.assertTrue(np.allclose(__magic_name__,		__magic_name__,		atol=1E-3							)							)

       # Test 2-D numpy arrays are batched.
       UpperCamelCase__							:				Tuple          =      [floats_list((1, x)							)[0] for x in (800, 800, 800)]
       UpperCamelCase__							:				str          =      np.asarray(__magic_name__							)
       UpperCamelCase__							:				Tuple          =      feature_extractor(__magic_name__,		return_tensors='''np'''							).input_values
       UpperCamelCase__							:				str          =      feature_extractor(__magic_name__,		return_tensors='''np'''							).input_values
       for enc_seq_a, enc_seq_a in zip(__magic_name__,		__magic_name__							):
           self.assertTrue(np.allclose(__magic_name__,		__magic_name__,		atol=1E-3							)							)




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






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      self.feat_extract_tester.prepare_inputs_for_target()
       UpperCamelCase__							:				Dict          =      self.feature_extraction_class(**self.feat_extract_dict							)
       UpperCamelCase__							:				Any          =      feat_extract.model_input_names[0]

       UpperCamelCase__							:				Optional[Any]          =      BatchFeature({input_name: speech_inputs}							)

       self.assertTrue(all(len(__magic_name__							) == len(__magic_name__							) for x, y in zip(__magic_name__,		processed_features[input_name]							)							)							)

       UpperCamelCase__							:				Tuple          =      self.feat_extract_tester.prepare_inputs_for_target(equal_length=__magic_name__							)
       UpperCamelCase__							:				Optional[Any]          =      BatchFeature({input_name: speech_inputs},		tensor_type='''np'''							)

       UpperCamelCase__							:				Any          =      processed_features[input_name]

       if len(batch_features_input.shape							) < 3:
           UpperCamelCase__							:				List[str]          =      batch_features_input[:, :, None]

       self.assertTrue(
           batch_features_input.shape
           == (self.feat_extract_tester.batch_size, len(speech_inputs[0]							), self.feat_extract_tester.num_mel_bins)							)




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






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      self.feat_extract_tester.prepare_inputs_for_target(equal_length=__magic_name__							)
       UpperCamelCase__							:				Union[str, Any]          =      self.feature_extraction_class(**self.feat_extract_dict							)
       UpperCamelCase__							:				Any          =      feat_extract.model_input_names[0]

       UpperCamelCase__							:				List[str]          =      BatchFeature({input_name: speech_inputs},		tensor_type='''pt'''							)

       UpperCamelCase__							:				Tuple          =      processed_features[input_name]

       if len(batch_features_input.shape							) < 3:
           UpperCamelCase__							:				Optional[Any]          =      batch_features_input[:, :, None]

       self.assertTrue(
           batch_features_input.shape
           == (self.feat_extract_tester.batch_size, len(speech_inputs[0]							), self.feat_extract_tester.num_mel_bins)							)




   @require_torch
   def       UpperCamelCase__  (    self							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.feature_extraction_class(**self.feat_extract_dict							)
       UpperCamelCase__							:				Union[str, Any]          =      self.feat_extract_tester.prepare_inputs_for_target()
       UpperCamelCase__							:				List[str]          =      feat_extract.model_input_names[0]

       UpperCamelCase__							:				Dict          =      BatchFeature({input_name: speech_inputs}							)

       UpperCamelCase__							:				Union[str, Any]          =      feat_extract.num_mel_bins  # hack!

       UpperCamelCase__							:				str          =      feat_extract.pad(__magic_name__,		padding='''longest''',		return_tensors='''np'''							)[input_name]
       UpperCamelCase__							:				Optional[Any]          =      feat_extract.pad(__magic_name__,		padding='''longest''',		return_tensors='''pt'''							)[input_name]

       self.assertTrue(abs(input_np.astype(np.floataa							).sum() - input_pt.numpy().astype(np.floataa							).sum()							) < 1E-2							)




   def       UpperCamelCase__  (    self							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      self.feat_extract_dict
       UpperCamelCase__							:				Union[str, Any]          =      True
       UpperCamelCase__							:				Optional[int]          =      self.feature_extraction_class(**__magic_name__							)
       UpperCamelCase__							:				int          =      self.feat_extract_tester.prepare_inputs_for_target()
       UpperCamelCase__							:				List[Any]          =      [len(__magic_name__							) for x in speech_inputs]
       UpperCamelCase__							:				List[Any]          =      feat_extract.model_input_names[0]

       UpperCamelCase__							:				int          =      BatchFeature({input_name: speech_inputs}							)

       UpperCamelCase__							:				Optional[Any]          =      feat_extract.num_mel_bins  # hack!

       UpperCamelCase__							:				Union[str, Any]          =      feat_extract.pad(__magic_name__,		padding='''longest''',		return_tensors='''np'''							)
       self.assertIn('''attention_mask''',		__magic_name__							)
       self.assertListEqual(list(processed.attention_mask.shape							),		list(processed[input_name].shape[:2]							)							)
       self.assertListEqual(processed.attention_mask.sum(-1							).tolist(),		__magic_name__							)




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






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      self.feat_extract_dict
       UpperCamelCase__							:				List[Any]          =      True
       UpperCamelCase__							:				Any          =      self.feature_extraction_class(**__magic_name__							)
       UpperCamelCase__							:				List[Any]          =      self.feat_extract_tester.prepare_inputs_for_target()
       UpperCamelCase__							:				List[Any]          =      [len(__magic_name__							) for x in speech_inputs]
       UpperCamelCase__							:				Optional[Any]          =      feat_extract.model_input_names[0]

       UpperCamelCase__							:				Optional[int]          =      BatchFeature({input_name: speech_inputs}							)
       UpperCamelCase__							:				Optional[int]          =      min(__magic_name__							)

       UpperCamelCase__							:				Optional[int]          =      feat_extract.num_mel_bins  # hack!

       UpperCamelCase__							:				List[Any]          =      feat_extract.pad(
           __magic_name__,		padding='''max_length''',		max_length=__magic_name__,		truncation=__magic_name__,		return_tensors='''np'''							)
       self.assertIn('''attention_mask''',		__magic_name__							)
       self.assertListEqual(
           list(processed_pad.attention_mask.shape							),		[processed_pad[input_name].shape[0], max_length]							)
       self.assertListEqual(
           processed_pad.attention_mask[:, :max_length].sum(-1							).tolist(),		[max_length for x in speech_inputs]							)




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      Any:






       """simple docstring"""
       from datasets import load_dataset

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

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




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






       """simple docstring"""
       # fmt: off
       UpperCamelCase__							:				str          =      torch.tensor(
           [2.38_04E-03, 2.07_52E-03, 1.98_36E-03, 2.10_57E-03, 1.61_74E-03,
            3.05_18E-04, 9.15_53E-05, 3.35_69E-04, 9.76_56E-04, 1.83_11E-03,
            2.01_42E-03, 2.10_57E-03, 1.73_95E-03, 4.57_76E-04, -3.96_73E-04,
            4.57_76E-04, 1.00_71E-03, 9.15_53E-05, 4.88_28E-04, 1.15_97E-03,
            7.32_42E-04, 9.46_04E-04, 1.80_05E-03, 1.83_11E-03, 8.85_01E-04,
            4.27_25E-04, 4.88_28E-04, 7.32_42E-04, 1.09_86E-03, 2.10_57E-03]							)
       # fmt: on

       UpperCamelCase__							:				Tuple          =      self._load_datasamples(1							)
       UpperCamelCase__							:				Tuple          =      SpeechTaFeatureExtractor()
       UpperCamelCase__							:				str          =      feature_extractor(__magic_name__,		return_tensors='''pt'''							).input_values
       self.assertEquals(input_values.shape,		(1, 93680)							)
       self.assertTrue(torch.allclose(input_values[0, :30],		__magic_name__,		atol=1E-6							)							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       # fmt: off
       UpperCamelCase__							:				Any          =      torch.tensor(
           [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777,
            -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386,
            -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571,
            -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998]							)
       # fmt: on

       UpperCamelCase__							:				Union[str, Any]          =      self._load_datasamples(1							)
       UpperCamelCase__							:				List[str]          =      SpeechTaFeatureExtractor()
       UpperCamelCase__							:				str          =      feature_extractor(audio_target=__magic_name__,		return_tensors='''pt'''							).input_values
       self.assertEquals(input_values.shape,		(1, 366, 80)							)
       self.assertTrue(torch.allclose(input_values[0, 0, :30],		__magic_name__,		atol=1E-4							)							)








from __future__ import annotations




def 		lowerCAmelCase_    (  __UpperCAmelCase:			list[int]		,   __UpperCAmelCase:			int      )      ->	list[int]:
    UpperCamelCase__							:				Optional[int]          =      0
    UpperCamelCase__							:				Tuple          =      len(__UpperCAmelCase      ) - 1

    while i < j:
        if nums[i] + nums[j] == target:
            return [i, j]
        elif nums[i] + nums[j] < target:
            UpperCamelCase__							:				Tuple          =      i + 1
        else:
            UpperCamelCase__							:				str          =      j - 1

    return []


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  print(F'''{two_pointer([2, 7, 11, 15], 9) = }''')

