





'''simple docstring'''






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

A__							:  Dict    =random.Random()
def   UpperCamelCase__ (						lowerCAmelCase				,      lowerCAmelCase=1.0				,      lowerCAmelCase=None				,      lowerCAmelCase=None    ):





      """simple docstring"""


      if rng is None:
            _lowerCAmelCase					=				global_rng

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




      def __init__(     self     :					Any     ,     __snake_case     :					Optional[int]     ,     __snake_case     :					str=7     ,     __snake_case     :					Dict=4_00     ,     __snake_case     :					Union[str, Any]=20_00     ,     __snake_case     :					Union[str, Any]=20_48     ,     __snake_case     :					List[str]=1_28     ,     __snake_case     :					List[Any]=1     ,     __snake_case     :					List[Any]=5_12     ,     __snake_case     :					Optional[int]=30     ,     __snake_case     :					Union[str, Any]=4_41_00     ,     )							-> str:
            _lowerCAmelCase					=				parent
            _lowerCAmelCase					=				batch_size
            _lowerCAmelCase					=				min_seq_length
            _lowerCAmelCase					=				max_seq_length
            _lowerCAmelCase					=				(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
            _lowerCAmelCase					=				spectrogram_length
            _lowerCAmelCase					=				feature_size
            _lowerCAmelCase					=				num_audio_channels
            _lowerCAmelCase					=				hop_length
            _lowerCAmelCase					=				chunk_length
            _lowerCAmelCase					=				sampling_rate




      def 							lowercase__       (     self     :					Tuple    )							-> Tuple:
            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 							lowercase__       (     self     :					List[str]     ,     __snake_case     :					Union[str, Any]=False     ,     __snake_case     :					str=False    )							-> List[str]:
            def _flatten(__snake_case     :					Optional[Any]    ):
                  return list(itertools.chain(*__snake_case    )    )

            if equal_length:
                  _lowerCAmelCase					=				[floats_list((self.max_seq_length, self.feature_size)    ) for _ in range(self.batch_size    )]
            else:
                  # make sure that inputs increase in size
                  _lowerCAmelCase					=				[
                      floats_list((x, self.feature_size)    )
                      for x in range(self.min_seq_length     ,     self.max_seq_length     ,     self.seq_length_diff    )
                  ]
            if numpify:
                  _lowerCAmelCase					=				[np.asarray(__snake_case    ) for x in speech_inputs]
            return speech_inputs




@require_torch
@require_torchaudio
class 					UpperCAmelCase	(     snake_case_				,						unittest.TestCase  ):
      _lowercase:     Union[str, Any]			=  TvltFeatureExtractor




      def 							lowercase__       (     self     :					List[str]    )							-> List[str]:
            _lowerCAmelCase					=				TvltFeatureExtractionTester(self    )




      def 							lowercase__       (     self     :					Any    )							-> Tuple:
            _lowerCAmelCase					=				self.feature_extraction_class(**self.feat_extract_dict    )
            self.assertTrue(hasattr(__snake_case     ,     """spectrogram_length"""    )    )
            self.assertTrue(hasattr(__snake_case     ,     """feature_size"""    )    )
            self.assertTrue(hasattr(__snake_case     ,     """num_audio_channels"""    )    )
            self.assertTrue(hasattr(__snake_case     ,     """hop_length"""    )    )
            self.assertTrue(hasattr(__snake_case     ,     """chunk_length"""    )    )
            self.assertTrue(hasattr(__snake_case     ,     """sampling_rate"""    )    )




      def 							lowercase__       (     self     :					Optional[int]    )							-> Union[str, Any]:
            _lowerCAmelCase					=				self.feature_extraction_class(**self.feat_extract_dict    )

            with tempfile.TemporaryDirectory() as tmpdirname:
                  _lowerCAmelCase					=				feat_extract_first.save_pretrained(__snake_case    )[0]
                  check_json_file_has_correct_format(__snake_case    )
                  _lowerCAmelCase					=				self.feature_extraction_class.from_pretrained(__snake_case    )

            _lowerCAmelCase					=				feat_extract_first.to_dict()
            _lowerCAmelCase					=				feat_extract_second.to_dict()
            _lowerCAmelCase					=				dict_first.pop("""mel_filters"""    )
            _lowerCAmelCase					=				dict_second.pop("""mel_filters"""    )
            self.assertTrue(np.allclose(__snake_case     ,     __snake_case    )    )
            self.assertEqual(__snake_case     ,     __snake_case    )




      def 							lowercase__       (     self     :					List[str]    )							-> Optional[Any]:
            _lowerCAmelCase					=				self.feature_extraction_class(**self.feat_extract_dict    )

            with tempfile.TemporaryDirectory() as tmpdirname:
                  _lowerCAmelCase					=				os.path.join(__snake_case     ,     """feat_extract.json"""    )
                  feat_extract_first.to_json_file(__snake_case    )
                  _lowerCAmelCase					=				self.feature_extraction_class.from_json_file(__snake_case    )

            _lowerCAmelCase					=				feat_extract_first.to_dict()
            _lowerCAmelCase					=				feat_extract_second.to_dict()
            _lowerCAmelCase					=				dict_first.pop("""mel_filters"""    )
            _lowerCAmelCase					=				dict_second.pop("""mel_filters"""    )
            self.assertTrue(np.allclose(__snake_case     ,     __snake_case    )    )
            self.assertEqual(__snake_case     ,     __snake_case    )




      def 							lowercase__       (     self     :					int    )							-> List[Any]:
            # Initialize feature_extractor
            _lowerCAmelCase					=				self.feature_extraction_class(**self.feat_extract_dict    )

            # create three inputs of length 800, 1000, and 1200
            _lowerCAmelCase					=				[floats_list((1, x)    )[0] for x in range(8_00     ,     14_00     ,     2_00    )]
            _lowerCAmelCase					=				[np.asarray(__snake_case    ) for speech_input in speech_inputs]

            # Test not batched input
            _lowerCAmelCase					=				feature_extractor(np_speech_inputs[0]     ,     return_tensors="""np"""     ,     sampling_rate=4_41_00    ).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
            _lowerCAmelCase					=				feature_extractor(__snake_case     ,     return_tensors="""np"""     ,     sampling_rate=4_41_00    ).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
            _lowerCAmelCase					=				feature_extractor(
                __snake_case     ,     return_tensors="""np"""     ,     sampling_rate=4_41_00     ,     mask_audio=__snake_case    ).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.
            _lowerCAmelCase					=				[floats_list((1, x)    )[0] for x in (8_00, 8_00, 8_00)]
            _lowerCAmelCase					=				np.asarray(__snake_case    )
            _lowerCAmelCase					=				feature_extractor(__snake_case     ,     return_tensors="""np"""     ,     sampling_rate=4_41_00    ).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 							lowercase__       (     self     :					int     ,     __snake_case     :					Union[str, Any]    )							-> int:
            _lowerCAmelCase					=				load_dataset("""hf-internal-testing/librispeech_asr_dummy"""     ,     """clean"""     ,     split="""validation"""    )
            # automatic decoding with librispeech
            _lowerCAmelCase					=				ds.sort("""id"""    ).select(range(__snake_case    )    )[:num_samples]["""audio"""]

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




      def 							lowercase__       (     self     :					Optional[Any]    )							-> List[Any]:
            _lowerCAmelCase					=				self._load_datasamples(1    )
            _lowerCAmelCase					=				TvltFeatureExtractor()
            _lowerCAmelCase					=				feature_extractor(__snake_case     ,     return_tensors="""pt"""    ).audio_values

            self.assertEquals(audio_values.shape     ,     (1, 1, 1_92, 1_28)    )

            _lowerCAmelCase					=				torch.tensor([[-0.30_32, -0.27_08], [-0.44_34, -0.40_07]]    )
            self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]     ,     __snake_case     ,     atol=1E-4    )    )













'''simple docstring'''






from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

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


if TYPE_CHECKING:
      from ... import FeatureExtractionMixin, TensorType

A__							:  Tuple    =logging.get_logger(__name__)

A__							:  Any    ={
    '''openai/imagegpt-small''': '''''',
    '''openai/imagegpt-medium''': '''''',
    '''openai/imagegpt-large''': '''''',
}




class 					UpperCAmelCase	(     snake_case_  ):
      _lowercase:     Tuple			=  '''imagegpt'''
      _lowercase:     Optional[int]			=  ['''past_key_values''']
      _lowercase:     str			=  {
          '''hidden_size''': '''n_embd''',
          '''max_position_embeddings''': '''n_positions''',
          '''num_attention_heads''': '''n_head''',
          '''num_hidden_layers''': '''n_layer''',
      }




      def __init__(     self     :					Optional[int]     ,     __snake_case     :					Optional[Any]=5_12 + 1     ,     __snake_case     :					Union[str, Any]=32 * 32     ,     __snake_case     :					List[Any]=5_12     ,     __snake_case     :					Any=24     ,     __snake_case     :					Optional[Any]=8     ,     __snake_case     :					List[Any]=None     ,     __snake_case     :					str="quick_gelu"     ,     __snake_case     :					List[Any]=0.1     ,     __snake_case     :					str=0.1     ,     __snake_case     :					Optional[int]=0.1     ,     __snake_case     :					Tuple=1E-5     ,     __snake_case     :					Optional[int]=0.02     ,     __snake_case     :					str=True     ,     __snake_case     :					Dict=True     ,     __snake_case     :					Union[str, Any]=False     ,     __snake_case     :					Dict=False     ,     __snake_case     :					Union[str, Any]=False     ,     **__snake_case     :					Union[str, Any]     ,     )							-> List[Any]:
            _lowerCAmelCase					=				vocab_size
            _lowerCAmelCase					=				n_positions
            _lowerCAmelCase					=				n_embd
            _lowerCAmelCase					=				n_layer
            _lowerCAmelCase					=				n_head
            _lowerCAmelCase					=				n_inner
            _lowerCAmelCase					=				activation_function
            _lowerCAmelCase					=				resid_pdrop
            _lowerCAmelCase					=				embd_pdrop
            _lowerCAmelCase					=				attn_pdrop
            _lowerCAmelCase					=				layer_norm_epsilon
            _lowerCAmelCase					=				initializer_range
            _lowerCAmelCase					=				scale_attn_weights
            _lowerCAmelCase					=				use_cache
            _lowerCAmelCase					=				scale_attn_by_inverse_layer_idx
            _lowerCAmelCase					=				reorder_and_upcast_attn
            _lowerCAmelCase					=				tie_word_embeddings

            super().__init__(tie_word_embeddings=__snake_case     ,     **__snake_case    )




class 					UpperCAmelCase	(     snake_case_  ):




      @property
      def 							lowercase__       (     self     :					Optional[Any]    )							-> Mapping[str, Mapping[int, str]]:
            return OrderedDict(
                [
                    ("""input_ids""", {0: """batch""", 1: """sequence"""}),
                ]    )




      def 							lowercase__       (     self     :					Union[str, Any]     ,     __snake_case     :					"FeatureExtractionMixin"     ,     __snake_case     :					int = 1     ,     __snake_case     :					int = -1     ,     __snake_case     :					bool = False     ,     __snake_case     :					Optional["TensorType"] = None     ,     __snake_case     :					int = 3     ,     __snake_case     :					int = 32     ,     __snake_case     :					int = 32     ,     )							-> Mapping[str, Any]:
            _lowerCAmelCase					=				self._generate_dummy_images(__snake_case     ,     __snake_case     ,     __snake_case     ,     __snake_case    )
            _lowerCAmelCase					=				dict(preprocessor(images=__snake_case     ,     return_tensors=__snake_case    )    )

            return inputs






