





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


A__:  Tuple        =     random.Random()

if is_torch_available():
   import torch



def 							lowerCAmelCase_      (				A_  ,A_=1.0  ,A_=None  ,A_=None):
    if rng is None:
        UpperCamelCase__:     Optional[Any]     							=			global_rng

    UpperCamelCase__:     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     _a  (  unittest.TestCase):

      """simple docstring"""


      def __init__(						self:       Any     ,  __lowerCamelCase:       Optional[int]     ,  __lowerCamelCase:       Tuple=7     ,  __lowerCamelCase:       str=400     ,  __lowerCamelCase:       int=2000     ,  __lowerCamelCase:       Tuple=1     ,  __lowerCamelCase:       int=0.0     ,  __lowerCamelCase:       List[Any]=1_6000     ,  __lowerCamelCase:       List[str]=True     ,  __lowerCamelCase:       List[str]=True     ,  ):
          '''simple docstring'''


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






      def        UpperCAmelCase_    (						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        UpperCAmelCase_    (						self:       Any     ,  __lowerCamelCase:       Union[str, Any]=False     ,  __lowerCamelCase:       List[Any]=False ):
          '''simple docstring'''


          def _flatten(__lowerCamelCase:       int ):
              return list(itertools.chain(*SCREAMING_SNAKE_CASE__ ) )

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

          return speech_inputs




@require_torch
@require_torchaudio
class     _a  (  a__		,       unittest.TestCase):

      """simple docstring"""


      UpperCamelCase__   						=    ASTFeatureExtractor






      def        UpperCAmelCase_    (						self:       Any ):
          '''simple docstring'''


          UpperCamelCase__:     Union[str, Any]     							=			ASTFeatureExtractionTester(self )






      def        UpperCAmelCase_    (						self:       str ):
          '''simple docstring'''


          UpperCamelCase__:     List[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__:     Dict     							=			[np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs]

          # Test not batched input
          UpperCamelCase__:     int     							=			feat_extract(speech_inputs[0]     ,  return_tensors="np" ).input_values
          UpperCamelCase__:     Union[str, Any]     							=			feat_extract(np_speech_inputs[0]     ,  return_tensors="np" ).input_values
          self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  atol=1e-3 ) )

          # Test batched
          UpperCamelCase__:     List[str]     							=			feat_extract(SCREAMING_SNAKE_CASE__     ,  padding=SCREAMING_SNAKE_CASE__     ,  return_tensors="np" ).input_values
          UpperCamelCase__:     str     							=			feat_extract(SCREAMING_SNAKE_CASE__     ,  padding=SCREAMING_SNAKE_CASE__     ,  return_tensors="np" ).input_values
          for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__ ):
              self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  atol=1e-3 ) )

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






      @require_torch
      def        UpperCAmelCase_    (						self:       List[Any] ):
          '''simple docstring'''


          import torch

          UpperCamelCase__:     Optional[Any]     							=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
          UpperCamelCase__:     Any     							=			np.random.rand(100 ).astype(np.floataa )
          UpperCamelCase__:     List[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__:     Dict     							=			feature_extractor.pad([{"input_values": inputs}]     ,  return_tensors="pt" )
              self.assertTrue(pt_processed.input_values.dtype == torch.floataa )






      def        UpperCAmelCase_    (						self:       List[Any]     ,  __lowerCamelCase:       str ):
          '''simple docstring'''


          from datasets import load_dataset

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

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






      @require_torch
      def        UpperCAmelCase_    (						self:       Optional[int] ):
          '''simple docstring'''


          UpperCamelCase__:     List[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

          UpperCamelCase__:     Optional[int]     							=			self._load_datasamples(1 )
          UpperCamelCase__:     int     							=			ASTFeatureExtractor()
          UpperCamelCase__:     Dict     							=			feature_extractor(SCREAMING_SNAKE_CASE__     ,  return_tensors="pt" ).input_values
          self.assertEquals(input_values.shape     ,  (1, 1024, 128) )
          self.assertTrue(torch.allclose(input_values[0, 0, :30]     ,  SCREAMING_SNAKE_CASE__     ,  atol=1e-4 ) )



"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCAmelCase__      :    str    							= logging.get_logger(__name__)

UpperCAmelCase__      :    Optional[int]    							= {
    'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json',
    # See all YOLOS models at https://huggingface.co/models?filter=yolos
}



class 	lowerCAmelCase_						(a__  ):


				"""simple docstring"""



				__UpperCamelCase      :						int					       =   '''yolos'''



				def __init__(self   ,       SCREAMING_SNAKE_CASE__=7_68   ,       SCREAMING_SNAKE_CASE__=12   ,       SCREAMING_SNAKE_CASE__=12   ,       SCREAMING_SNAKE_CASE__=30_72   ,       SCREAMING_SNAKE_CASE__="gelu"   ,       SCREAMING_SNAKE_CASE__=0.0   ,       SCREAMING_SNAKE_CASE__=0.0   ,       SCREAMING_SNAKE_CASE__=0.02   ,       SCREAMING_SNAKE_CASE__=1E-12   ,       SCREAMING_SNAKE_CASE__=[5_12, 8_64]   ,       SCREAMING_SNAKE_CASE__=16   ,       SCREAMING_SNAKE_CASE__=3   ,       SCREAMING_SNAKE_CASE__=True   ,       SCREAMING_SNAKE_CASE__=1_00   ,       SCREAMING_SNAKE_CASE__=True   ,       SCREAMING_SNAKE_CASE__=False   ,       SCREAMING_SNAKE_CASE__=1   ,       SCREAMING_SNAKE_CASE__=5   ,       SCREAMING_SNAKE_CASE__=2   ,       SCREAMING_SNAKE_CASE__=5   ,       SCREAMING_SNAKE_CASE__=2   ,       SCREAMING_SNAKE_CASE__=0.1   ,       **SCREAMING_SNAKE_CASE__   ,       )					->		Optional[Any]:



											"""simple docstring"""




											super().__init__(**SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   hidden_size
											SCREAMING_SNAKE_CASE__						:       int           =   num_hidden_layers
											SCREAMING_SNAKE_CASE__						:       str           =   num_attention_heads
											SCREAMING_SNAKE_CASE__						:       List[str]           =   intermediate_size
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   hidden_act
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   hidden_dropout_prob
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   attention_probs_dropout_prob
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   initializer_range
											SCREAMING_SNAKE_CASE__						:       Dict           =   layer_norm_eps
											SCREAMING_SNAKE_CASE__						:       List[str]           =   image_size
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   patch_size
											SCREAMING_SNAKE_CASE__						:       List[str]           =   num_channels
											SCREAMING_SNAKE_CASE__						:       List[str]           =   qkv_bias
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   num_detection_tokens
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   use_mid_position_embeddings
											SCREAMING_SNAKE_CASE__						:       List[str]           =   auxiliary_loss
											# Hungarian matcher
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   class_cost
											SCREAMING_SNAKE_CASE__						:       List[str]           =   bbox_cost
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   giou_cost
											# Loss coefficients
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   bbox_loss_coefficient
											SCREAMING_SNAKE_CASE__						:       List[str]           =   giou_loss_coefficient
											SCREAMING_SNAKE_CASE__						:       int           =   eos_coefficient






class 	lowerCAmelCase_						(a__  ):


				"""simple docstring"""



				__UpperCamelCase      :						Dict					       =   version.parse('''1.11'''  )



				@property
				def 	__magic_name__    (self    )					->		Mapping[str, Mapping[int, str]]:



											"""simple docstring"""




											return OrderedDict(
											    [
											        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
											    ]    )



				@property
				def 	__magic_name__    (self    )					->		float:



											"""simple docstring"""




											return 1E-4



				@property
				def 	__magic_name__    (self    )					->		int:



											"""simple docstring"""




											return 12




