


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_		:

 '''simple docstring'''

 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=5_12	,   _UpperCAmelCase=0.02	,   _UpperCAmelCase=0	,   _UpperCAmelCase=None	,   ):
       snake_case_ =   parent
       snake_case_ =   batch_size
       snake_case_ =   seq_length
       snake_case_ =   is_training
       snake_case_ =   use_input_mask
       snake_case_ =   use_labels
       snake_case_ =   vocab_size
       snake_case_ =   hidden_size
       snake_case_ =   projection_dim
       snake_case_ =   num_hidden_layers
       snake_case_ =   num_attention_heads
       snake_case_ =   intermediate_size
       snake_case_ =   dropout
       snake_case_ =   attention_dropout
       snake_case_ =   max_position_embeddings
       snake_case_ =   initializer_range
       snake_case_ =   scope
       snake_case_ =   bos_token_id



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   ids_tensor([self.batch_size, self.seq_length]	,   self.vocab_size      )

       snake_case_ =   None
       if self.use_input_mask:
             snake_case_ =   random_attention_mask([self.batch_size, self.seq_length]      )

       if input_mask is not None:
             snake_case_ =   input_mask.numpy()
             snake_case_ ,					snake_case_ =   input_mask.shape
             snake_case_ =   np.random.randint(1	,   seq_length - 1	,   size=(batch_size,)      )
             for batch_idx, start_index in enumerate(_UpperCAmelCase      ):
                   snake_case_ =   1
                   snake_case_ =   0

       snake_case_ =   self.get_config()

       return config, input_ids, tf.convert_to_tensor(_UpperCAmelCase      )



 def 		UpperCamelCase__  (			self      ):
       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 		UpperCamelCase__  (			self	,   _UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase      ):
       snake_case_ =   TFBlipTextModel(config=_UpperCAmelCase      )
       snake_case_ =   model(_UpperCAmelCase	,   attention_mask=_UpperCAmelCase	,   training=_UpperCAmelCase      )
       snake_case_ =   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 		UpperCamelCase__  (			self      ):
       snake_case_ =   self.prepare_config_and_inputs()
       snake_case_ ,					snake_case_ ,					snake_case_ =   config_and_inputs
       snake_case_ =   {'''input_ids''': input_ids, '''attention_mask''': input_mask}
       return config, inputs_dict







@require_tf
class      lowerCAmelCase_		(				lowerCamelCase__      ,		unittest.TestCase ):

 '''simple docstring'''

 __snake_case				=						(TFBlipTextModel,) if is_tf_available() else ()
 __snake_case				=						False
 __snake_case				=						False
 __snake_case				=						False



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   BlipTextModelTester(self      )
       snake_case_ =   ConfigTester(self	,   config_class=_UpperCAmelCase	,   hidden_size=37      )



 def 		UpperCamelCase__  (			self      ):
       self.config_tester.run_common_tests()



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase      )



 def 		UpperCamelCase__  (			self      ):
       pass



 def 		UpperCamelCase__  (			self      ):
       pass



 @unittest.skip(reason='''Blip does not use inputs_embeds'''      )
 def 		UpperCamelCase__  (			self      ):
       pass



 @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''      )
 def 		UpperCamelCase__  (			self      ):
       pass



 @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''      )
 def 		UpperCamelCase__  (			self      ):
       pass



 @slow
 def 		UpperCamelCase__  (			self      ):
       for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             snake_case_ =   TFBlipTextModel.from_pretrained(_UpperCAmelCase      )
             self.assertIsNotNone(_UpperCAmelCase      )





 def 		UpperCamelCase__  (			self	,   _UpperCAmelCase=True      ):
       super().test_pt_tf_model_equivalence(allow_missing_keys=_UpperCAmelCase      )



import numpy as np

import datasets


UpperCAmelCase    =					"""
Compute the Mahalanobis Distance

Mahalonobis distance is the distance between a point and a distribution.
And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.
It was introduced by Prof. P. C. Mahalanobis in 1936
and has been used in various statistical applications ever since
[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]
"""

UpperCAmelCase    =					"""\
@article{de2000mahalanobis,
  title={The mahalanobis distance},
  author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},
  journal={Chemometrics and intelligent laboratory systems},
  volume={50},
  number={1},
  pages={1--18},
  year={2000},
  publisher={Elsevier}
}
"""

UpperCAmelCase    =					"""
Args:
    X: List of datapoints to be compared with the `reference_distribution`.
    reference_distribution: List of datapoints from the reference distribution we want to compare to.
Returns:
    mahalanobis: The Mahalonobis distance for each datapoint in `X`.
Examples:

    >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\")
    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])
    >>> print(results)
    {'mahalanobis': array([0.5])}
"""







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,		_KWARGS_DESCRIPTION )
class lowerCAmelCase_		(				datasets.Metric ):

 '''simple docstring'''

 def 		UpperCamelCase__  (			self      ):
       return datasets.MetricInfo(
           description=_DESCRIPTION	,   citation=_CITATION	,   inputs_description=_KWARGS_DESCRIPTION	,   features=datasets.Features(
               {
                   '''X''': datasets.Sequence(datasets.Value('''float'''	,   id='''sequence'''      )	,   id='''X'''      ),
               }      )	,   )





 def 		UpperCamelCase__  (			self	,   _UpperCAmelCase	,   _UpperCAmelCase      ):
       # convert to numpy arrays
       snake_case_ =   np.array(_UpperCAmelCase      )
       snake_case_ =   np.array(_UpperCAmelCase      )

       # Assert that arrays are 2D
       if len(X.shape      ) != 2:
             raise ValueError('''Expected `X` to be a 2D vector'''      )
       if len(reference_distribution.shape      ) != 2:
             raise ValueError('''Expected `reference_distribution` to be a 2D vector'''      )
       if reference_distribution.shape[0] < 2:
             raise ValueError(
                 '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension'''      )

       # Get mahalanobis distance for each prediction
       snake_case_ =   X - np.mean(_UpperCAmelCase      )
       snake_case_ =   np.cov(reference_distribution.T      )
       try:
             snake_case_ =   np.linalg.inv(_UpperCAmelCase      )
       except np.linalg.LinAlgError:
             snake_case_ =   np.linalg.pinv(_UpperCAmelCase      )
       snake_case_ =   np.dot(_UpperCAmelCase	,   _UpperCAmelCase      )
       snake_case_ =   np.dot(_UpperCAmelCase	,   X_minus_mu.T      ).diagonal()

       return {"mahalanobis": mahal_dist}