





import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
  import torch

if is_datasets_available():
  from datasets import load_dataset

UpperCAmelCase_     							= random.Random()




def 		lowerCAmelCase_    (  __UpperCAmelCase:			Tuple		,   __UpperCAmelCase:			int=1.0		,   __UpperCAmelCase:			List[str]=None		,   __UpperCAmelCase:			Optional[int]=None      )      ->	List[str]:
    if rng is None:
        UpperCamelCase__							:				Dict          =      global_rng

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

    return values






class     lowercase__       (	unittest.TestCase				):

   '''simple docstring'''


   def __init__(    self,		__magic_name__,		__magic_name__=7,		__magic_name__=400,		__magic_name__=2000,		__magic_name__=2048,		__magic_name__=128,		__magic_name__=1,		__magic_name__=512,		__magic_name__=30,		__magic_name__=44100,		) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				List[Any]          =      parent
       UpperCamelCase__							:				List[str]          =      batch_size
       UpperCamelCase__							:				Optional[int]          =      min_seq_length
       UpperCamelCase__							:				int          =      max_seq_length
       UpperCamelCase__							:				List[Any]          =      (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
       UpperCamelCase__							:				int          =      spectrogram_length
       UpperCamelCase__							:				str          =      feature_size
       UpperCamelCase__							:				List[str]          =      num_audio_channels
       UpperCamelCase__							:				List[Any]          =      hop_length
       UpperCamelCase__							:				Dict          =      chunk_length
       UpperCamelCase__							:				str          =      sampling_rate




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       return {
           "spectrogram_length": self.spectrogram_length,
           "feature_size": self.feature_size,
           "num_audio_channels": self.num_audio_channels,
           "hop_length": self.hop_length,
           "chunk_length": self.chunk_length,
           "sampling_rate": self.sampling_rate,
       }




   def       UpperCamelCase__  (    self,		__magic_name__=False,		__magic_name__=False							) ->      Dict:






       """simple docstring"""
       def _flatten(__magic_name__							):
           return list(itertools.chain(*__magic_name__							)							)

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






@require_torch
@require_torchaudio
class     lowercase__       (	__lowerCamelCase			,				unittest.TestCase				):

   '''simple docstring'''


   a						:							str   		=		TvltFeatureExtractor




   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      TvltFeatureExtractionTester(self							)




   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				Dict          =      self.feature_extraction_class(**self.feat_extract_dict							)
       self.assertTrue(hasattr(__magic_name__,		'''spectrogram_length'''							)							)
       self.assertTrue(hasattr(__magic_name__,		'''feature_size'''							)							)
       self.assertTrue(hasattr(__magic_name__,		'''num_audio_channels'''							)							)
       self.assertTrue(hasattr(__magic_name__,		'''hop_length'''							)							)
       self.assertTrue(hasattr(__magic_name__,		'''chunk_length'''							)							)
       self.assertTrue(hasattr(__magic_name__,		'''sampling_rate'''							)							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      self.feature_extraction_class(**self.feat_extract_dict							)

       with tempfile.TemporaryDirectory() as tmpdirname:
           UpperCamelCase__							:				List[Any]          =      feat_extract_first.save_pretrained(__magic_name__							)[0]
           check_json_file_has_correct_format(__magic_name__							)
           UpperCamelCase__							:				List[Any]          =      self.feature_extraction_class.from_pretrained(__magic_name__							)

       UpperCamelCase__							:				Union[str, Any]          =      feat_extract_first.to_dict()
       UpperCamelCase__							:				List[Any]          =      feat_extract_second.to_dict()
       UpperCamelCase__							:				str          =      dict_first.pop('''mel_filters'''							)
       UpperCamelCase__							:				Dict          =      dict_second.pop('''mel_filters'''							)
       self.assertTrue(np.allclose(__magic_name__,		__magic_name__							)							)
       self.assertEqual(__magic_name__,		__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      self.feature_extraction_class(**self.feat_extract_dict							)

       with tempfile.TemporaryDirectory() as tmpdirname:
           UpperCamelCase__							:				Optional[Any]          =      os.path.join(__magic_name__,		'''feat_extract.json'''							)
           feat_extract_first.to_json_file(__magic_name__							)
           UpperCamelCase__							:				str          =      self.feature_extraction_class.from_json_file(__magic_name__							)

       UpperCamelCase__							:				str          =      feat_extract_first.to_dict()
       UpperCamelCase__							:				Optional[int]          =      feat_extract_second.to_dict()
       UpperCamelCase__							:				Union[str, Any]          =      dict_first.pop('''mel_filters'''							)
       UpperCamelCase__							:				Tuple          =      dict_second.pop('''mel_filters'''							)
       self.assertTrue(np.allclose(__magic_name__,		__magic_name__							)							)
       self.assertEqual(__magic_name__,		__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Tuple:






       """simple docstring"""
       # Initialize feature_extractor
       UpperCamelCase__							:				str          =      self.feature_extraction_class(**self.feat_extract_dict							)

       # create three inputs of length 800, 1000, and 1200
       UpperCamelCase__							:				Optional[Any]          =      [floats_list((1, x)							)[0] for x in range(800,		1400,		200							)]
       UpperCamelCase__							:				Optional[Any]          =      [np.asarray(__magic_name__							) for speech_input in speech_inputs]

       # Test not batched input
       UpperCamelCase__							:				Optional[int]          =      feature_extractor(np_speech_inputs[0],		return_tensors='''np''',		sampling_rate=44100							).audio_values

       self.assertTrue(encoded_audios.ndim == 4							)
       self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
       self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
       self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)

       # Test batched
       UpperCamelCase__							:				Dict          =      feature_extractor(__magic_name__,		return_tensors='''np''',		sampling_rate=44100							).audio_values

       self.assertTrue(encoded_audios.ndim == 4							)
       self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
       self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
       self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)

       # Test audio masking
       UpperCamelCase__							:				Any          =      feature_extractor(
           __magic_name__,		return_tensors='''np''',		sampling_rate=44100,		mask_audio=__magic_name__							).audio_values

       self.assertTrue(encoded_audios.ndim == 4							)
       self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
       self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
       self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)

       # Test 2-D numpy arrays are batched.
       UpperCamelCase__							:				List[str]          =      [floats_list((1, x)							)[0] for x in (800, 800, 800)]
       UpperCamelCase__							:				Dict          =      np.asarray(__magic_name__							)
       UpperCamelCase__							:				Optional[Any]          =      feature_extractor(__magic_name__,		return_tensors='''np''',		sampling_rate=44100							).audio_values
       self.assertTrue(encoded_audios.ndim == 4							)
       self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
       self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
       self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      List[Any]:






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

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




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






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      self._load_datasamples(1							)
       UpperCamelCase__							:				Optional[int]          =      TvltFeatureExtractor()
       UpperCamelCase__							:				List[str]          =      feature_extractor(__magic_name__,		return_tensors='''pt'''							).audio_values

       self.assertEquals(audio_values.shape,		(1, 1, 192, 128)							)

       UpperCamelCase__							:				List[str]          =      torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]]							)
       self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2],		__magic_name__,		atol=1E-4							)							)








from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_     							= logging.get_logger(__name__)

UpperCAmelCase_     							= {
    'huggingface/informer-tourism-monthly': (
        'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json'
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}






class     lowercase__       (	__lowerCamelCase				):

   '''simple docstring'''


   a						:							Optional[int]   		=		"informer"
   a						:							Tuple   		=		{
       "hidden_size": "d_model",
       "num_attention_heads": "encoder_attention_heads",
       "num_hidden_layers": "encoder_layers",
   }




   def __init__(    self,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__ = "student_t",		__magic_name__ = "nll",		__magic_name__ = 1,		__magic_name__ = None,		__magic_name__ = "mean",		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__ = 64,		__magic_name__ = 32,		__magic_name__ = 32,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = True,		__magic_name__ = "gelu",		__magic_name__ = 0.05,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 100,		__magic_name__ = 0.02,		__magic_name__=True,		__magic_name__ = "prob",		__magic_name__ = 5,		__magic_name__ = True,		**__magic_name__,		) ->      Optional[int]:






       """simple docstring"""
       # time series specific configuration
       UpperCamelCase__							:				List[Any]          =      prediction_length
       UpperCamelCase__							:				Any          =      context_length or prediction_length
       UpperCamelCase__							:				Optional[int]          =      distribution_output
       UpperCamelCase__							:				Union[str, Any]          =      loss
       UpperCamelCase__							:				Optional[Any]          =      input_size
       UpperCamelCase__							:				Dict          =      num_time_features
       UpperCamelCase__							:				Dict          =      lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
       UpperCamelCase__							:				Optional[int]          =      scaling
       UpperCamelCase__							:				Any          =      num_dynamic_real_features
       UpperCamelCase__							:				Optional[int]          =      num_static_real_features
       UpperCamelCase__							:				Optional[Any]          =      num_static_categorical_features

       # set cardinality
       if cardinality and num_static_categorical_features > 0:
           if len(__magic_name__							) != num_static_categorical_features:
               raise ValueError(
                   '''The cardinality should be a list of the same length as `num_static_categorical_features`'''							)
           UpperCamelCase__							:				str          =      cardinality
       else:
           UpperCamelCase__							:				int          =      [0]

       # set embedding_dimension
       if embedding_dimension and num_static_categorical_features > 0:
           if len(__magic_name__							) != num_static_categorical_features:
               raise ValueError(
                   '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''							)
           UpperCamelCase__							:				Any          =      embedding_dimension
       else:
           UpperCamelCase__							:				Union[str, Any]          =      [min(50,		(cat + 1) // 2							) for cat in self.cardinality]

       UpperCamelCase__							:				Optional[Any]          =      num_parallel_samples

       # Transformer architecture configuration
       UpperCamelCase__							:				Union[str, Any]          =      input_size * len(self.lags_sequence							) + self._number_of_features
       UpperCamelCase__							:				Optional[Any]          =      d_model
       UpperCamelCase__							:				Tuple          =      encoder_attention_heads
       UpperCamelCase__							:				Any          =      decoder_attention_heads
       UpperCamelCase__							:				Dict          =      encoder_ffn_dim
       UpperCamelCase__							:				Optional[Any]          =      decoder_ffn_dim
       UpperCamelCase__							:				str          =      encoder_layers
       UpperCamelCase__							:				Optional[int]          =      decoder_layers

       UpperCamelCase__							:				Optional[Any]          =      dropout
       UpperCamelCase__							:				List[Any]          =      attention_dropout
       UpperCamelCase__							:				Any          =      activation_dropout
       UpperCamelCase__							:				Optional[int]          =      encoder_layerdrop
       UpperCamelCase__							:				Union[str, Any]          =      decoder_layerdrop

       UpperCamelCase__							:				Tuple          =      activation_function
       UpperCamelCase__							:				List[str]          =      init_std

       UpperCamelCase__							:				int          =      use_cache

       # Informer
       UpperCamelCase__							:				Optional[int]          =      attention_type
       UpperCamelCase__							:				Optional[int]          =      sampling_factor
       UpperCamelCase__							:				Dict          =      distil

       super().__init__(is_encoder_decoder=__magic_name__,		**__magic_name__							)




   @property
   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       return (
           sum(self.embedding_dimension							)
           + self.num_dynamic_real_features
           + self.num_time_features
           + self.num_static_real_features
           + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
       )

