


"""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   			=    random.Random()

if is_torch_available():
  import torch







def   __lowerCAmelCase						(						lowercase  :  Optional[int]						,							lowercase  :  str=1.0						,							lowercase  :  Any=None						,							lowercase  :  str=None )	->						Union[str, Any]:


    """simple docstring"""





    if rng is None:
        snake_case    :      Any      					=    global_rng

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

    return values







class _lowerCAmelCase				(      unittest.TestCase	):







   def __init__(	self						,	UpperCamelCase__						,	UpperCamelCase__=7						,	UpperCamelCase__=400						,	UpperCamelCase__=2000						,	UpperCamelCase__=1						,	UpperCamelCase__=0.0						,	UpperCamelCase__=1_6000						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	)	->		Dict:

       '''simple docstring'''




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







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''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  lowerCamelCase		(	self						,	UpperCamelCase__=False						,	UpperCamelCase__=False						)	->		Any:

       '''simple docstring'''




       def _flatten(UpperCamelCase__						):
           return list(itertools.chain(*UpperCamelCase__						)						)

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

       return speech_inputs







@require_torch
@require_torchaudio
class _lowerCAmelCase				(      snake_case_    ,							unittest.TestCase	):
   __UpperCAmelCase :       Tuple							  =  ASTFeatureExtractor







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      Tuple      					=    ASTFeatureExtractionTester(self						)







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




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

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

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

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







   @require_torch
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       import torch

       snake_case    :      List[Any]      					=    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
       snake_case    :      Optional[int]      					=    np.random.rand(100						).astype(np.floataa						)
       snake_case    :      Dict      					=    np_speech_inputs.tolist()

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







   def  lowerCamelCase		(	self						,	UpperCamelCase__						)	->		Optional[Any]:

       '''simple docstring'''




       from datasets import load_dataset

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

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







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

       '''simple docstring'''




       snake_case    :      List[str]      					=    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

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









"""simple docstring"""



from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
  import tensorflow as tf

  from transformers import TFBlipTextModel
  from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST







class _lowerCAmelCase				:







   def __init__(	self						,	UpperCamelCase__						,	UpperCamelCase__=12						,	UpperCamelCase__=7						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=99						,	UpperCamelCase__=32						,	UpperCamelCase__=32						,	UpperCamelCase__=2						,	UpperCamelCase__=4						,	UpperCamelCase__=37						,	UpperCamelCase__=0.1						,	UpperCamelCase__=0.1						,	UpperCamelCase__=512						,	UpperCamelCase__=0.02						,	UpperCamelCase__=0						,	UpperCamelCase__=None						,	)	->		Dict:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    parent
       snake_case    :      Dict      					=    batch_size
       snake_case    :      List[str]      					=    seq_length
       snake_case    :      Dict      					=    is_training
       snake_case    :      Optional[Any]      					=    use_input_mask
       snake_case    :      Optional[int]      					=    use_labels
       snake_case    :      Tuple      					=    vocab_size
       snake_case    :      Optional[Any]      					=    hidden_size
       snake_case    :      Optional[Any]      					=    projection_dim
       snake_case    :      List[Any]      					=    num_hidden_layers
       snake_case    :      List[Any]      					=    num_attention_heads
       snake_case    :      int      					=    intermediate_size
       snake_case    :      str      					=    dropout
       snake_case    :      List[Any]      					=    attention_dropout
       snake_case    :      Any      					=    max_position_embeddings
       snake_case    :      List[Any]      					=    initializer_range
       snake_case    :      Any      					=    scope
       snake_case    :      Union[str, Any]      					=    bos_token_id







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      str      					=    ids_tensor([self.batch_size, self.seq_length]						,	self.vocab_size						)

       snake_case    :      int      					=    None
       if self.use_input_mask:
           snake_case    :      Optional[int]      					=    random_attention_mask([self.batch_size, self.seq_length]						)

       if input_mask is not None:
           snake_case    :      Tuple      					=    input_mask.numpy()
           snake_case					,snake_case    :      str      					=    input_mask.shape
           snake_case    :      Tuple      					=    np.random.randint(1						,	seq_length - 1						,	size=(batch_size,)						)
           for batch_idx, start_index in enumerate(UpperCamelCase__						):
               snake_case    :      int      					=    1
               snake_case    :      Tuple      					=    0

       snake_case    :      Union[str, Any]      					=    self.get_config()

       return config, input_ids, tf.convert_to_tensor(UpperCamelCase__						)







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

       '''simple docstring'''




       return BlipTextConfig(
           vocab_size=self.vocab_size						,	hidden_size=self.hidden_size						,	projection_dim=self.projection_dim						,	num_hidden_layers=self.num_hidden_layers						,	num_attention_heads=self.num_attention_heads						,	intermediate_size=self.intermediate_size						,	dropout=self.dropout						,	attention_dropout=self.attention_dropout						,	max_position_embeddings=self.max_position_embeddings						,	initializer_range=self.initializer_range						,	bos_token_id=self.bos_token_id						,	)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      str      					=    TFBlipTextModel(config=UpperCamelCase__						)
       snake_case    :      Any      					=    model(UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	training=UpperCamelCase__						)
       snake_case    :      Optional[int]      					=    model(UpperCamelCase__						,	training=UpperCamelCase__						)
       self.parent.assertEqual(result.last_hidden_state.shape						,	(self.batch_size, self.seq_length, self.hidden_size)						)
       self.parent.assertEqual(result.pooler_output.shape						,	(self.batch_size, self.hidden_size)						)







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    self.prepare_config_and_inputs()
       snake_case					,snake_case					,snake_case    :      Tuple      					=    config_and_inputs
       snake_case    :      str      					=    {"input_ids": input_ids, "attention_mask": input_mask}
       return config, inputs_dict







@require_tf
class _lowerCAmelCase				(      snake_case_    ,							unittest.TestCase	):
   __UpperCAmelCase :       Any							  =  (TFBlipTextModel,) if is_tf_available() else ()
   __UpperCAmelCase :       Any							  =  False
   __UpperCAmelCase :       Dict							  =  False
   __UpperCAmelCase :       List[Any]							  =  False







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    BlipTextModelTester(self						)
       snake_case    :      Optional[int]      					=    ConfigTester(self						,	config_class=UpperCamelCase__						,	hidden_size=37						)







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      List[str]      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







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

       '''simple docstring'''




       pass







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







   @unittest.skip(reason="Blip does not use inputs_embeds"						)
   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       pass







   @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"						)
   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       pass







   @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"						)
   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       pass







   @slow
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case    :      List[str]      					=    TFBlipTextModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__=True						)	->		Optional[int]:

       '''simple docstring'''




       super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase__						)





