


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


_UpperCamelCase 							=  random.Random()

if is_torch_available():
      import torch


def 		_lowercase (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE=1.0       ,					SCREAMING_SNAKE_CASE=None       ,					SCREAMING_SNAKE_CASE=None							):




     '''simple docstring'''





     if rng is None:
          __A	:       Tuple      =							global_rng

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

     return values







class 							__magic_name__	(       unittest.TestCase ):

     """simple docstring"""






     def __init__(   self			,     lowerCamelCase			,     lowerCamelCase=7			,     lowerCamelCase=400			,     lowerCamelCase=2000			,     lowerCamelCase=1			,     lowerCamelCase=0.0			,     lowerCamelCase=1_6000			,     lowerCamelCase=True			,     lowerCamelCase=True			,     ):


          '''simple docstring'''





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


     def lowerCAmelCase__  (   self		):


          '''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 lowerCAmelCase__  (   self			,     lowerCamelCase=False			,     lowerCamelCase=False		):


          '''simple docstring'''





          def _flatten(lowerCamelCase		):
               return list(itertools.chain(*lowerCamelCase		)		)

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

          return speech_inputs







@require_torch
@require_torchaudio
class 							__magic_name__	(       lowerCAmelCase    ,		unittest.TestCase ):

     """simple docstring"""






     lowerCamelCase__       						=				ASTFeatureExtractor


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       List[str]      =							ASTFeatureExtractionTester(self		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       Optional[int]      =							self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
          # create three inputs of length 800, 1000, and 1200
          __A	:       Tuple      =							[floats_list((1, x)		)[0] for x in range(800			,     1400			,     200		)]
          __A	:       Tuple      =							[np.asarray(lowerCamelCase		) for speech_input in speech_inputs]

          # Test not batched input
          __A	:       str      =							feat_extract(speech_inputs[0]			,     return_tensors="np"		).input_values
          __A	:       Optional[int]      =							feat_extract(np_speech_inputs[0]			,     return_tensors="np"		).input_values
          self.assertTrue(np.allclose(lowerCamelCase			,     lowerCamelCase			,     atol=1E-3		)		)

          # Test batched
          __A	:       Tuple      =							feat_extract(lowerCamelCase			,     padding=lowerCamelCase			,     return_tensors="np"		).input_values
          __A	:       Optional[int]      =							feat_extract(lowerCamelCase			,     padding=lowerCamelCase			,     return_tensors="np"		).input_values
          for enc_seq_a, enc_seq_a in zip(lowerCamelCase			,     lowerCamelCase		):
               self.assertTrue(np.allclose(lowerCamelCase			,     lowerCamelCase			,     atol=1E-3		)		)

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


     @require_torch
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          import torch

          __A	:       Optional[int]      =							self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
          __A	:       Optional[int]      =							np.random.rand(100		).astype(np.floataa		)
          __A	:       Union[str, Any]      =							np_speech_inputs.tolist()

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


     def lowerCAmelCase__  (   self			,     lowerCamelCase		):


          '''simple docstring'''





          from datasets import load_dataset

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

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


     @require_torch
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       Any      =							torch.tensor(
              [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
               -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
               -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
               -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869]		)
          # fmt: on

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





'''simple docstring'''


import functools


def 		_lowercase (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							):




     '''simple docstring'''





     __A	:       int      =							len(SCREAMING_SNAKE_CASE							)
     __A	:       int      =							len(SCREAMING_SNAKE_CASE							)

     @functools.cache
     def min_distance(SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							) -> int:
          # if first word index is overflow - delete all from the second word
          if indexa >= len_worda:
               return len_worda - indexa
          # if second word index is overflow - delete all from the first word
          if indexa >= len_worda:
               return len_worda - indexa
          __A	:       Optional[int]      =							int(worda[indexa] != worda[indexa]							)  # current letters not identical
          return min(
              1 + min_distance(indexa + 1       ,					SCREAMING_SNAKE_CASE							)       ,					1 + min_distance(SCREAMING_SNAKE_CASE       ,					indexa + 1							)       ,					diff + min_distance(indexa + 1       ,					indexa + 1							)       ,					)

     return min_distance(0       ,					0							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()

