





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


_UpperCAmelCase             =							random.Random()

if is_torch_available():
      import torch






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Union[str, Any]   ,   SCREAMING_SNAKE_CASE		:Any=1.0   ,   SCREAMING_SNAKE_CASE		:Optional[Any]=None   ,   SCREAMING_SNAKE_CASE		:Tuple=None   )      ->   str:
 if rng is None:
  __lowerCAmelCase					:	Optional[Any]      =       global_rng

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

 return values






class        snake_case_    (		unittest.TestCase						):






  def __init__(							self			:					str       ,  _snake_case			:					Any       ,  _snake_case			:					List[str]=7       ,  _snake_case			:					Optional[Any]=400       ,  _snake_case			:					Optional[Any]=2000       ,  _snake_case			:					Dict=1       ,  _snake_case			:					Dict=0.0       ,  _snake_case			:					Optional[int]=16000       ,  _snake_case			:					List[str]=True       ,  _snake_case			:					Optional[Any]=True       ,  )->Tuple:






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       parent
   __lowerCAmelCase					:	Union[str, Any]      =       batch_size
   __lowerCAmelCase					:	Optional[Any]      =       min_seq_length
   __lowerCAmelCase					:	List[Any]      =       max_seq_length
   __lowerCAmelCase					:	Optional[int]      =       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
   __lowerCAmelCase					:	Dict      =       feature_size
   __lowerCAmelCase					:	Union[str, Any]      =       padding_value
   __lowerCAmelCase					:	Any      =       sampling_rate
   __lowerCAmelCase					:	Union[str, Any]      =       return_attention_mask
   __lowerCAmelCase					:	int      =       do_normalize






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






   '''simple docstring'''

   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 				UpperCAmelCase__						(							self			:					Optional[Any]       ,  _snake_case			:					List[str]=False       ,  _snake_case			:					Union[str, Any]=False      )->List[str]:






   '''simple docstring'''

   def _flatten(_snake_case			:					Optional[Any]      ):
    return list(itertools.chain(*_snake_case      )      )

   if equal_length:
    __lowerCAmelCase					:	Dict      =       floats_list((self.batch_size, self.max_seq_length)      )
   else:
    # make sure that inputs increase in size
    __lowerCAmelCase					:	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:
    __lowerCAmelCase					:	Optional[Any]      =       [np.asarray(_snake_case      ) for x in speech_inputs]

   return speech_inputs






@require_torch
@require_torchaudio
class        snake_case_    (		__lowercase					,unittest.TestCase						):
  A_      							=   ASTFeatureExtractor






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






   '''simple docstring'''

   __lowerCAmelCase					:	int      =       ASTFeatureExtractionTester(self      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
   # create three inputs of length 800, 1000, and 1200
   __lowerCAmelCase					:	Union[str, Any]      =       [floats_list((1, x)      )[0] for x in range(800       ,  1400       ,  200      )]
   __lowerCAmelCase					:	List[Any]      =       [np.asarray(_snake_case      ) for speech_input in speech_inputs]

   # Test not batched input
   __lowerCAmelCase					:	Any      =       feat_extract(speech_inputs[0]       ,  return_tensors="""np"""      ).input_values
   __lowerCAmelCase					:	List[str]      =       feat_extract(np_speech_inputs[0]       ,  return_tensors="""np"""      ).input_values
   self.assertTrue(np.allclose(_snake_case       ,  _snake_case       ,  atol=1E-3      )      )

   # Test batched
   __lowerCAmelCase					:	Dict      =       feat_extract(_snake_case       ,  padding=_snake_case       ,  return_tensors="""np"""      ).input_values
   __lowerCAmelCase					:	str      =       feat_extract(_snake_case       ,  padding=_snake_case       ,  return_tensors="""np"""      ).input_values
   for enc_seq_a, enc_seq_a in zip(_snake_case       ,  _snake_case      ):
    self.assertTrue(np.allclose(_snake_case       ,  _snake_case       ,  atol=1E-3      )      )

   # Test 2-D numpy arrays are batched.
   __lowerCAmelCase					:	Optional[int]      =       [floats_list((1, x)      )[0] for x in (800, 800, 800)]
   __lowerCAmelCase					:	Tuple      =       np.asarray(_snake_case      )
   __lowerCAmelCase					:	Dict      =       feat_extract(_snake_case       ,  return_tensors="""np"""      ).input_values
   __lowerCAmelCase					:	int      =       feat_extract(_snake_case       ,  return_tensors="""np"""      ).input_values
   for enc_seq_a, enc_seq_a in zip(_snake_case       ,  _snake_case      ):
    self.assertTrue(np.allclose(_snake_case       ,  _snake_case       ,  atol=1E-3      )      )






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






   '''simple docstring'''

   import torch

   __lowerCAmelCase					:	List[Any]      =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
   __lowerCAmelCase					:	Optional[Any]      =       np.random.rand(100      ).astype(np.floataa      )
   __lowerCAmelCase					:	Any      =       np_speech_inputs.tolist()

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






  def 				UpperCAmelCase__						(							self			:					Optional[Any]       ,  _snake_case			:					List[Any]      )->Dict:






   '''simple docstring'''

   from datasets import load_dataset

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

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






  @require_torch
  def 				UpperCAmelCase__						(							self			:					Any      )->Dict:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       torch.tensor(
       [-0.9_894, -1.2_776, -0.9_066, -1.2_776, -0.9_349, -1.2_609, -1.0_386, -1.2_776,
        -1.1_561, -1.2_776, -1.2_052, -1.2_723, -1.2_190, -1.2_132, -1.2_776, -1.1_133,
        -1.1_953, -1.1_343, -1.1_584, -1.2_203, -1.1_770, -1.2_474, -1.2_381, -1.1_936,
        -0.9_270, -0.8_317, -0.8_049, -0.7_706, -0.7_565, -0.7_869]      )
   # fmt: on

   __lowerCAmelCase					:	Union[str, Any]      =       self._load_datasamples(1      )
   __lowerCAmelCase					:	Optional[Any]      =       ASTFeatureExtractor()
   __lowerCAmelCase					:	Optional[int]      =       feature_extractor(_snake_case       ,  return_tensors="""pt"""      ).input_values
   self.assertEquals(input_values.shape       ,  (1, 1024, 128)      )
   self.assertTrue(torch.allclose(input_values[0, 0, :30]       ,  _snake_case       ,  atol=1E-4      )      )






_UpperCAmelCase             =							{0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}

_UpperCAmelCase             =							{0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:dict[int, list[int]]   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list[bool]   )      ->   list[int]:
 __lowerCAmelCase					:	str      =       True
 __lowerCAmelCase					:	str      =       []

 for neighbour in graph[vert]:
  if not visited[neighbour]:
   order += topology_sort(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

 order.append(SCREAMING_SNAKE_CASE   )

 return order






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:dict[int, list[int]]   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list[bool]   )      ->   list[int]:
 __lowerCAmelCase					:	Optional[Any]      =       True
 __lowerCAmelCase					:	Union[str, Any]      =       [vert]

 for neighbour in reversed_graph[vert]:
  if not visited[neighbour]:
   component += find_components(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

 return component







def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:dict[int, list[int]]   )      ->   list[list[int]]:
 __lowerCAmelCase					:	Optional[Any]      =       len(SCREAMING_SNAKE_CASE   ) * [False]
 __lowerCAmelCase					:	dict[int, list[int]]      =       {vert: [] for vert in range(len(SCREAMING_SNAKE_CASE   )   )}

 for vert, neighbours in graph.items():
  for neighbour in neighbours:
   reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE   )

 __lowerCAmelCase					:	Tuple      =       []
 for i, was_visited in enumerate(SCREAMING_SNAKE_CASE   ):
  if not was_visited:
   order += topology_sort(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

 __lowerCAmelCase					:	Optional[Any]      =       []
 __lowerCAmelCase					:	Any      =       len(SCREAMING_SNAKE_CASE   ) * [False]

 for i in range(len(SCREAMING_SNAKE_CASE   )   ):
  __lowerCAmelCase					:	Optional[int]      =       order[len(SCREAMING_SNAKE_CASE   ) - i - 1]
  if not visited[vert]:
   __lowerCAmelCase					:	Any      =       find_components(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
   components_list.append(SCREAMING_SNAKE_CASE   )

 return components_list