






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


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

if is_torch_available():
	import torch



def     A__						(	A_    ,      A_=1.0    ,      A_=None    ,      A_=None		)     ->				List[Any]:
					if rng is None:
										_lowercase			= global_rng

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

					return values







class 	UpperCamelCase__					(     unittest.TestCase			):

		"""simple docstring"""




		def __init__( self						:						int							,    __A						:						List[str]							,    __A						:						str=7							,    __A						:						Tuple=4_0_0							,    __A						:						Union[str, Any]=2_0_0_0							,    __A						:						Dict=1							,    __A						:						Any=0.0							,    __A						:						Any=1_6_0_0_0							,    __A						:						List[Any]=True							,    __A						:						List[str]=True							,    ):







							"""simple docstring"""
							_lowercase			= parent
							_lowercase			= batch_size
							_lowercase			= min_seq_length
							_lowercase			= max_seq_length
							_lowercase			= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
							_lowercase			= feature_size
							_lowercase			= padding_value
							_lowercase			= sampling_rate
							_lowercase			= return_attention_mask
							_lowercase			= do_normalize




		def       snake_case     ( self						:						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       snake_case     ( self						:						List[str]							,    __A						:						List[Any]=False							,    __A						:						Union[str, Any]=False    ):







							"""simple docstring"""
							def _flatten(__A						:						Dict    ):
												return list(itertools.chain(*_a    )    )

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

							return speech_inputs







@require_torch
@require_torchaudio
class 	UpperCamelCase__					(     a_      ,     unittest.TestCase			):

		"""simple docstring"""
		UpperCAmelCase__     			=						ASTFeatureExtractor




		def       snake_case     ( self						:						int    ):







							"""simple docstring"""
							_lowercase			= ASTFeatureExtractionTester(self    )




		def       snake_case     ( self						:						Tuple    ):







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

							# Test not batched input
							_lowercase			= feat_extract(speech_inputs[0]							,    return_tensors="np"    ).input_values
							_lowercase			= feat_extract(np_speech_inputs[0]							,    return_tensors="np"    ).input_values
							self.assertTrue(np.allclose(_a							,    _a							,    atol=1e-3    )    )

							# Test batched
							_lowercase			= feat_extract(_a							,    padding=_a							,    return_tensors="np"    ).input_values
							_lowercase			= feat_extract(_a							,    padding=_a							,    return_tensors="np"    ).input_values
							for enc_seq_a, enc_seq_a in zip(_a							,    _a    ):
												self.assertTrue(np.allclose(_a							,    _a							,    atol=1e-3    )    )

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




		@require_torch
		def       snake_case     ( self						:						List[str]    ):







							"""simple docstring"""
							import torch

							_lowercase			= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
							_lowercase			= np.random.rand(1_0_0    ).astype(np.floataa    )
							_lowercase			= np_speech_inputs.tolist()

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




		def       snake_case     ( self						:						Union[str, Any]							,    __A						:						Tuple    ):







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

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

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




		@require_torch
		def       snake_case     ( self						:						List[str]    ):







							"""simple docstring"""
							# fmt: off
							_lowercase			= 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

							_lowercase			= self._load_datasamples(1    )
							_lowercase			= ASTFeatureExtractor()
							_lowercase			= feature_extractor(_a							,    return_tensors="pt"    ).input_values
							self.assertEquals(input_values.shape							,    (1, 1_0_2_4, 1_2_8)    )
							self.assertTrue(torch.allclose(input_values[0, 0, :3_0]							,    _a							,    atol=1e-4    )    )



"""simple docstring"""




import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


_A     :			str  						=			False
try:
   _A     :			Dict  						=			_is_package_available("""google.colab""")
except ModuleNotFoundError:
   pass

@input.register
class 						a__		:
   def __init__(     self      ,       _a = None      ,       _a = []							):
          lowercase       :							Union[str, Any]									=				0
          lowercase       :							str									=				choices
          lowercase       :							List[Any]									=				prompt
          if sys.platform == "win32":
                 lowercase       :							Union[str, Any]									=				"*"
          else:
                 lowercase       :							int									=				"➔ "
   def      __magic_name__     (     self      ,       _a      ,       _a = ""							):
          if sys.platform != "win32":
                 writeColor(self.choices[index]      ,       32      ,       _a							)
          else:
                 forceWrite(self.choices[index]      ,       _a							)
   def      __magic_name__     (     self      ,       _a							):
          if index == self.position:
                 forceWrite(f""" {self.arrow_char} """							)
                 self.write_choice(_a							)
          else:
                 forceWrite(f"""    {self.choices[index]}"""							)
          reset_cursor()
   def      __magic_name__     (     self      ,       _a      ,       _a = 1							):
          lowercase       :							Optional[int]									=				self.position
          if direction == Direction.DOWN:
                 if self.position + 1 >= len(self.choices							):
                        return
                 self.position += num_spaces
          else:
                 if self.position - 1 < 0:
                        return
                 self.position -= num_spaces
          clear_line()
          self.print_choice(_a							)
          move_cursor(_a      ,       direction.name							)
          self.print_choice(self.position							)
   @input.mark(KEYMAP["up"]							)
   def      __magic_name__     (     self							):
          self.move_direction(Direction.UP							)
   @input.mark(KEYMAP["down"]							)
   def      __magic_name__     (     self							):
          self.move_direction(Direction.DOWN							)
   @input.mark(KEYMAP["newline"]							)
   def      __magic_name__     (     self							):
          move_cursor(len(self.choices							) - self.position      ,       "DOWN"							)
          return self.position
   @input.mark(KEYMAP["interrupt"]							)
   def      __magic_name__     (     self							):
          move_cursor(len(self.choices							) - self.position      ,       "DOWN"							)
          raise KeyboardInterrupt
   @input.mark_multiple(*[KEYMAP[str(_a							)] for number in range(10							)]							)
   def      __magic_name__     (     self							):
          lowercase       :							List[str]									=				int(chr(self.current_selection							)							)
          lowercase       :							Union[str, Any]									=				index - self.position
          if index == self.position:
                 return
          if index < len(self.choices							):
                 if self.position > index:
                        self.move_direction(Direction.UP      ,       -movement							)
                 elif self.position < index:
                        self.move_direction(Direction.DOWN      ,       _a							)
                 else:
                        return
          else:
                 return

   def      __magic_name__     (     self      ,       _a = 0							):
          if self.prompt:
                 linebreak()
                 forceWrite(self.prompt      ,       "\n"							)
                 if in_colab:
                        forceWrite("Please input a choice index (starting from 0), and press enter"      ,       "\n"							)
                 else:
                        forceWrite("Please select a choice using the arrow or number keys, and selecting with enter"      ,       "\n"							)
          lowercase       :							Tuple									=				default_choice
          for i in range(len(self.choices							)							):
                 self.print_choice(_a							)
                 forceWrite("\n"							)
          move_cursor(len(self.choices							) - self.position      ,       "UP"							)
          with cursor.hide():
                 while True:
                        if in_colab:
                               try:
                                      lowercase       :							Tuple									=				int(builtins.input()							)
                               except ValueError:
                                      lowercase       :							Optional[int]									=				default_choice
                        else:
                               lowercase       :							int									=				self.handle_input()
                        if choice is not None:
                               reset_cursor()
                               for _ in range(len(self.choices							) + 1							):
                                      move_cursor(1      ,       "UP"							)
                                      clear_line()
                               self.write_choice(_a      ,       "\n"							)
                               return choice


