

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


lowerCAmelCase__       = random.Random()

if is_torch_available():
      import torch
def      _lowerCAmelCase(	__A   ,       __A=1.0   ,       __A=None   ,       __A=None			):
  if rng is None:
    UpperCAmelCase					      =  global_rng

  UpperCAmelCase					      =  []
  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    ):


 def __init__(						self		: Dict			,						lowerCAmelCase__		: List[str]			,						lowerCAmelCase__		: Union[str, Any]=7			,						lowerCAmelCase__		: Union[str, Any]=4_0_0			,						lowerCAmelCase__		: List[Any]=2_0_0_0			,						lowerCAmelCase__		: Any=1			,						lowerCAmelCase__		: Dict=0.0			,						lowerCAmelCase__		: Optional[int]=1_6_0_0_0			,						lowerCAmelCase__		: int=True			,						lowerCAmelCase__		: List[str]=True			,						)    ->      Union[str, Any]:
   UpperCAmelCase					      =  parent
   UpperCAmelCase					      =  batch_size
   UpperCAmelCase					      =  min_seq_length
   UpperCAmelCase					      =  max_seq_length
   UpperCAmelCase					      =  (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
   UpperCAmelCase					      =  feature_size
   UpperCAmelCase					      =  padding_value
   UpperCAmelCase					      =  sampling_rate
   UpperCAmelCase					      =  return_attention_mask
   UpperCAmelCase					      =  do_normalize


 def _UpperCamelCase	(						self		: Dict    )    ->      Optional[int]:
   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		: List[Any]			,						lowerCAmelCase__		: Any=False			,						lowerCAmelCase__		: Optional[int]=False    )    ->      Optional[Any]:
   def _flatten(lowerCAmelCase__		: Optional[int]    ):
     return list(itertools.chain(*lowerCAmelCase__    )    )

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

   return speech_inputs






@require_torch
@require_torchaudio
class 						__magic_name__    (       _snake_case	,						unittest.TestCase    ):
 UpperCAmelCase							    =						ASTFeatureExtractor


 def _UpperCamelCase	(						self		: Dict    )    ->      str:
   UpperCAmelCase					      =  ASTFeatureExtractionTester(self    )


 def _UpperCamelCase	(						self		: Any    )    ->      List[str]:
   # Tests that all call wrap to encode_plus and batch_encode_plus
   UpperCAmelCase					      =  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
   # create three inputs of length 800, 1000, and 1200
   UpperCAmelCase					      =  [floats_list((1, x)    )[0] for x in range(8_0_0			,						1_4_0_0			,						2_0_0    )]
   UpperCAmelCase					      =  [np.asarray(lowerCAmelCase__    ) for speech_input in speech_inputs]

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

   # Test batched
   UpperCAmelCase					      =  feat_extract(lowerCAmelCase__			,						padding=lowerCAmelCase__			,						return_tensors="np"    ).input_values
   UpperCAmelCase					      =  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.
   UpperCAmelCase					      =  [floats_list((1, x)    )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
   UpperCAmelCase					      =  np.asarray(lowerCAmelCase__    )
   UpperCAmelCase					      =  feat_extract(lowerCAmelCase__			,						return_tensors="np"    ).input_values
   UpperCAmelCase					      =  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 _UpperCamelCase	(						self		: int    )    ->      Optional[int]:
   import torch

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

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


 def _UpperCamelCase	(						self		: Tuple			,						lowerCAmelCase__		: List[Any]    )    ->      Dict:
   from datasets import load_dataset

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

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


 @require_torch
 def _UpperCamelCase	(						self		: Any    )    ->      int:
   # fmt: off
   UpperCAmelCase					      =  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

   UpperCAmelCase					      =  self._load_datasamples(1    )
   UpperCAmelCase					      =  ASTFeatureExtractor()
   UpperCAmelCase					      =  feature_extractor(lowerCAmelCase__			,						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]			,						lowerCAmelCase__			,						atol=1e-4    )    )






from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)



