



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


__snake_case				:  List[Any] =       random.Random()

if is_torch_available():
	import torch


def      _lowercase							(    __snake_case   ,__snake_case=1.0   ,__snake_case=None   ,__snake_case=None      )		->  Union[str, Any]:
			if rng is None:
						__lowerCAmelCase :    Optional[int]				=			global_rng

			__lowerCAmelCase :    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:						Union[str, Any]			,     _SCREAMING_SNAKE_CASE:						List[Any]			,     _SCREAMING_SNAKE_CASE:						Optional[int]=7			,     _SCREAMING_SNAKE_CASE:						int=400			,     _SCREAMING_SNAKE_CASE:						List[Any]=2000			,     _SCREAMING_SNAKE_CASE:						List[Any]=1			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=0.0			,     _SCREAMING_SNAKE_CASE:						Dict=1_6000			,     _SCREAMING_SNAKE_CASE:						List[Any]=True			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=True			,     )							->			Any:

				"""simple docstring"""

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						Any)							->			List[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 				_SCREAMING_SNAKE_CASE  (	self:						Dict			,     _SCREAMING_SNAKE_CASE:						Optional[int]=False			,     _SCREAMING_SNAKE_CASE:						List[Any]=False)							->			int:

				"""simple docstring"""

				def _flatten(_SCREAMING_SNAKE_CASE:						Optional[int]):
							return list(itertools.chain(*_SCREAMING_SNAKE_CASE))

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

				return speech_inputs






@require_torch
@require_torchaudio
class      A__  (    __SCREAMING_SNAKE_CASE    ,						unittest.TestCase				):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE        =      ASTFeatureExtractor

	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any])							->			Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase :    Tuple				=			ASTFeatureExtractionTester(self)

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

				"""simple docstring"""

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

				# Test not batched input
				__lowerCAmelCase :    List[Any]				=			feat_extract(speech_inputs[0]			,     return_tensors="np").input_values
				__lowerCAmelCase :    Optional[int]				=			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
				__lowerCAmelCase :    Dict				=			feat_extract(_SCREAMING_SNAKE_CASE			,     padding=_SCREAMING_SNAKE_CASE			,     return_tensors="np").input_values
				__lowerCAmelCase :    Any				=			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.
				__lowerCAmelCase :    Optional[Any]				=			[floats_list((1, x))[0] for x in (800, 800, 800)]
				__lowerCAmelCase :    Dict				=			np.asarray(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    str				=			feat_extract(_SCREAMING_SNAKE_CASE			,     return_tensors="np").input_values
				__lowerCAmelCase :    str				=			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 				_SCREAMING_SNAKE_CASE  (	self:						Union[str, Any])							->			Optional[Any]:

				"""simple docstring"""

				import torch

				__lowerCAmelCase :    str				=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
				__lowerCAmelCase :    Any				=			np.random.rand(100).astype(np.floataa)
				__lowerCAmelCase :    int				=			np_speech_inputs.tolist()

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict			,     _SCREAMING_SNAKE_CASE:						Tuple)							->			Optional[int]:

				"""simple docstring"""

				from datasets import load_dataset

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

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







	@require_torch
	def 				_SCREAMING_SNAKE_CASE  (	self:						Tuple)							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[int]				=			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

				__lowerCAmelCase :    Optional[int]				=			self._load_datasamples(1)
				__lowerCAmelCase :    Any				=			ASTFeatureExtractor()
				__lowerCAmelCase :    Any				=			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"""






import copy
import os
from typing import Union

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


__snake_case				:  str =       logging.get_logger(__name__)

__snake_case				:  Union[str, Any] =       {
    'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json',
}



class      A__  (    __SCREAMING_SNAKE_CASE				):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE        =      'git_vision_model'

	def __init__(	self:						Optional[int]			,     _SCREAMING_SNAKE_CASE:						List[Any]=768			,     _SCREAMING_SNAKE_CASE:						Optional[Any]=3072			,     _SCREAMING_SNAKE_CASE:						str=12			,     _SCREAMING_SNAKE_CASE:						Any=12			,     _SCREAMING_SNAKE_CASE:						Dict=3			,     _SCREAMING_SNAKE_CASE:						List[Any]=224			,     _SCREAMING_SNAKE_CASE:						List[str]=16			,     _SCREAMING_SNAKE_CASE:						str="quick_gelu"			,     _SCREAMING_SNAKE_CASE:						Any=1e-5			,     _SCREAMING_SNAKE_CASE:						List[str]=0.0			,     _SCREAMING_SNAKE_CASE:						Dict=0.02			,     **_SCREAMING_SNAKE_CASE:						str			,     )							->			Optional[Any]:

				"""simple docstring"""

				super().__init__(**_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase :    Union[str, Any]				=			hidden_size
				__lowerCAmelCase :    List[str]				=			intermediate_size
				__lowerCAmelCase :    List[str]				=			num_hidden_layers
				__lowerCAmelCase :    Tuple				=			num_attention_heads
				__lowerCAmelCase :    List[Any]				=			num_channels
				__lowerCAmelCase :    Dict				=			patch_size
				__lowerCAmelCase :    Optional[int]				=			image_size
				__lowerCAmelCase :    Optional[Any]				=			initializer_range
				__lowerCAmelCase :    str				=			attention_dropout
				__lowerCAmelCase :    Optional[Any]				=			layer_norm_eps
				__lowerCAmelCase :    Tuple				=			hidden_act







	@classmethod
	def 				_SCREAMING_SNAKE_CASE  (	cls:						Dict			,     _SCREAMING_SNAKE_CASE:						Union[str, os.PathLike]			,     **_SCREAMING_SNAKE_CASE:						Dict)							->			"PretrainedConfig":

				"""simple docstring"""

				cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase		,      __lowerCAmelCase :    List[Any]				=			cls.get_config_dict(_SCREAMING_SNAKE_CASE			,     **_SCREAMING_SNAKE_CASE)

				# get the vision config dict if we are loading from GITConfig
				if config_dict.get("model_type") == "git":
							__lowerCAmelCase :    str				=			config_dict["vision_config"]

				if "model_type" in config_dict and hasattr(cls			,     "model_type") and config_dict["model_type"] != cls.model_type:
							logger.warning(
							    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
							    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")

				return cls.from_dict(_SCREAMING_SNAKE_CASE			,     **_SCREAMING_SNAKE_CASE)






class      A__  (    __SCREAMING_SNAKE_CASE				):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE        =      'git'

	def __init__(	self:						Union[str, Any]			,     _SCREAMING_SNAKE_CASE:						Tuple=None			,     _SCREAMING_SNAKE_CASE:						Dict=3_0522			,     _SCREAMING_SNAKE_CASE:						Any=768			,     _SCREAMING_SNAKE_CASE:						str=6			,     _SCREAMING_SNAKE_CASE:						int=12			,     _SCREAMING_SNAKE_CASE:						Dict=3072			,     _SCREAMING_SNAKE_CASE:						Optional[Any]="gelu"			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=0.1			,     _SCREAMING_SNAKE_CASE:						Any=0.1			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=1024			,     _SCREAMING_SNAKE_CASE:						str=0.02			,     _SCREAMING_SNAKE_CASE:						Tuple=1e-12			,     _SCREAMING_SNAKE_CASE:						List[str]=0			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]="absolute"			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=True			,     _SCREAMING_SNAKE_CASE:						Tuple=False			,     _SCREAMING_SNAKE_CASE:						Dict=101			,     _SCREAMING_SNAKE_CASE:						Tuple=102			,     _SCREAMING_SNAKE_CASE:						Any=None			,     **_SCREAMING_SNAKE_CASE:						List[Any]			,     )							->			List[Any]:

				"""simple docstring"""

				super().__init__(bos_token_id=_SCREAMING_SNAKE_CASE			,     eos_token_id=_SCREAMING_SNAKE_CASE			,     pad_token_id=_SCREAMING_SNAKE_CASE			,     **_SCREAMING_SNAKE_CASE)

				if vision_config is None:
							__lowerCAmelCase :    int				=			{}
							logger.info("vision_config is None. initializing the GitVisionConfig with default values.")

				__lowerCAmelCase :    List[str]				=			GitVisionConfig(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase :    List[Any]				=			vocab_size
				__lowerCAmelCase :    int				=			hidden_size
				__lowerCAmelCase :    Dict				=			num_hidden_layers
				__lowerCAmelCase :    Tuple				=			num_attention_heads
				__lowerCAmelCase :    Union[str, Any]				=			hidden_act
				__lowerCAmelCase :    Dict				=			intermediate_size
				__lowerCAmelCase :    List[str]				=			hidden_dropout_prob
				__lowerCAmelCase :    Union[str, Any]				=			attention_probs_dropout_prob
				__lowerCAmelCase :    Union[str, Any]				=			max_position_embeddings
				__lowerCAmelCase :    Optional[int]				=			initializer_range
				__lowerCAmelCase :    str				=			layer_norm_eps
				__lowerCAmelCase :    Optional[Any]				=			position_embedding_type
				__lowerCAmelCase :    str				=			use_cache
				__lowerCAmelCase :    str				=			tie_word_embeddings
				__lowerCAmelCase :    Optional[int]				=			num_image_with_embedding

				__lowerCAmelCase :    Optional[Any]				=			bos_token_id
				__lowerCAmelCase :    Any				=			eos_token_id







	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict)							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[int]				=			copy.deepcopy(self.__dict__)
				__lowerCAmelCase :    List[Any]				=			self.vision_config.to_dict()
				__lowerCAmelCase :    Tuple				=			self.__class__.model_type
				return output