



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







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

														'''simple docstring'''

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







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Union[str, Any]				     =					ids_tensor([self.batch_size, self.seq_length],    self.vocab_size)

														_lowerCAmelCase  :							Optional[int]				     =					None
														if self.use_input_mask:
																					_lowerCAmelCase  :							Union[str, Any]				     =					random_attention_mask([self.batch_size, self.seq_length])

														if input_mask is not None:
																					_lowerCAmelCase  :							Any				     =					input_mask.numpy()
																					_lowerCAmelCase  :							Optional[Any]				     =					input_mask.shape
																					_lowerCAmelCase  :							Union[str, Any]				     =					np.random.randint(1,    seq_length - 1,    size=(batch_size,))
																					for batch_idx, start_index in enumerate(__a):
																												_lowerCAmelCase  :							Union[str, Any]				     =					1
																												_lowerCAmelCase  :							List[Any]				     =					0

														_lowerCAmelCase  :							str				     =					self.get_config()

														return config, input_ids, tf.convert_to_tensor(__a)







							def      snake_case__   (     self):

														'''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      snake_case__   (     self,    __a,    __a,    __a):

														'''simple docstring'''

														_lowerCAmelCase  :							Any				     =					TFBlipTextModel(config=__a)
														_lowerCAmelCase  :							Union[str, Any]				     =					model(__a,    attention_mask=__a,    training=__a)
														_lowerCAmelCase  :							str				     =					model(__a,    training=__a)
														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      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Tuple				     =					self.prepare_config_and_inputs()
														_lowerCAmelCase  :							int				     =					config_and_inputs
														_lowerCAmelCase  :							str				     =					{'input_ids': input_ids, 'attention_mask': input_mask}
														return config, inputs_dict



@require_tf
class 						UpperCAmelCase_					( a     ,      unittest.TestCase):
							lowerCamelCase__         =	(TFBlipTextModel,) if is_tf_available() else ()
							lowerCamelCase__         =	False
							lowerCamelCase__         =	False
							lowerCamelCase__         =	False







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Dict				     =					BlipTextModelTester(self)
														_lowerCAmelCase  :							Tuple				     =					ConfigTester(self,    config_class=__a,    hidden_size=37)







							def      snake_case__   (     self):

														'''simple docstring'''

														self.config_tester.run_common_tests()







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							int				     =					self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*__a)







							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							@unittest.skip(reason="Blip does not use inputs_embeds")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







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

														'''simple docstring'''

														pass







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

														'''simple docstring'''

														pass







							@slow
							def      snake_case__   (     self):

														'''simple docstring'''

														for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_lowerCAmelCase  :							Union[str, Any]				     =					TFBlipTextModel.from_pretrained(__a)
																					self.assertIsNotNone(__a)







							def      snake_case__   (     self,    __a=True):

														'''simple docstring'''

														super().test_pt_tf_model_equivalence(allow_missing_keys=__a)





import logging

import numpy as np
import pytest
from scipy.linalg import eigh

logging.basicConfig(level=logging.INFO, format="%(message)s")






def        A       (      _lowerCamelCase						):





							'''simple docstring'''




							return input_array.reshape((input_array.size, 1)						)






def        A       (      _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						):





							'''simple docstring'''




							_lowerCAmelCase  :							Any				     =					np.nan
							for i in range(_lowerCamelCase						):
														_lowerCAmelCase  :							Tuple				     =					features[:, labels == i]
														_lowerCAmelCase  :							Dict				     =					data.mean(1						)
														# Centralize the data of class i
														_lowerCAmelCase  :							Union[str, Any]				     =					data - column_reshape(_lowerCamelCase						)
														if i > 0:
																					# If covariance_sum is not None
																					covariance_sum += np.dot(_lowerCamelCase       ,				centered_data.T						)
														else:
																					# If covariance_sum is np.nan (i.e. first loop)
																					_lowerCAmelCase  :							int				     =					np.dot(_lowerCamelCase       ,				centered_data.T						)

							return covariance_sum / features.shape[1]






def        A       (      _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						):





							'''simple docstring'''




							_lowerCAmelCase  :							Optional[Any]				     =					features.mean(1						)
							_lowerCAmelCase  :							List[str]				     =					np.nan
							for i in range(_lowerCamelCase						):
														_lowerCAmelCase  :							str				     =					features[:, labels == i]
														_lowerCAmelCase  :							Optional[Any]				     =					data.shape[1]
														_lowerCAmelCase  :							Optional[Any]				     =					data.mean(1						)
														if i > 0:
																					# If covariance_sum is not None
																					covariance_sum += device_data * np.dot(
																					    column_reshape(_lowerCamelCase						) - column_reshape(_lowerCamelCase						)       ,				(column_reshape(_lowerCamelCase						) - column_reshape(_lowerCamelCase						)).T       ,				)
														else:
																					# If covariance_sum is np.nan (i.e. first loop)
																					_lowerCAmelCase  :							Optional[Any]				     =					device_data * np.dot(
																					    column_reshape(_lowerCamelCase						) - column_reshape(_lowerCamelCase						)       ,				(column_reshape(_lowerCamelCase						) - column_reshape(_lowerCamelCase						)).T       ,				)

							return covariance_sum / features.shape[1]






def        A       (      _lowerCamelCase       ,				_lowerCamelCase						):





							'''simple docstring'''




							if features.any():
														_lowerCAmelCase  :							List[Any]				     =					features.mean(1						)
														# Center the dataset
														_lowerCAmelCase  :							List[Any]				     =					features - np.reshape(_lowerCamelCase       ,				(data_mean.size, 1)						)
														_lowerCAmelCase  :							Optional[Any]				     =					np.dot(_lowerCamelCase       ,				centered_data.T						) / features.shape[1]
														_lowerCAmelCase     ,					_lowerCAmelCase  :							List[Any]				     =					np.linalg.eigh(_lowerCamelCase						)
														# Take all the columns in the reverse order (-1), and then takes only the first
														_lowerCAmelCase  :							Union[str, Any]				     =					eigenvectors[:, ::-1][:, 0:dimensions]
														# Project the database on the new space
														_lowerCAmelCase  :							List[Any]				     =					np.dot(filtered_eigenvectors.T       ,				_lowerCamelCase						)
														logging.info("Principal Component Analysis computed"						)

														return projected_data
							else:
														logging.basicConfig(level=logging.ERROR       ,				format="%(message)s"       ,				force=_lowerCamelCase						)
														logging.error("Dataset empty"						)
														raise AssertionError






def        A       (      _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						):





							'''simple docstring'''




							assert classes > dimensions

							# Check if features have been already loaded
							if features.any:
														_lowerCAmelCase     ,					_lowerCAmelCase  :							List[str]				     =					eigh(
														    covariance_between_classes(_lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						)       ,				covariance_within_classes(_lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						)       ,				)
														_lowerCAmelCase  :							List[str]				     =					eigenvectors[:, ::-1][:, :dimensions]
														_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase  :							Any				     =					np.linalg.svd(_lowerCamelCase						)
														_lowerCAmelCase  :							Optional[Any]				     =					svd_matrix[:, 0:dimensions]
														_lowerCAmelCase  :							str				     =					np.dot(filtered_svd_matrix.T       ,				_lowerCamelCase						)
														logging.info("Linear Discriminant Analysis computed"						)

														return projected_data
							else:
														logging.basicConfig(level=logging.ERROR       ,				format="%(message)s"       ,				force=_lowerCamelCase						)
														logging.error("Dataset empty"						)
														raise AssertionError






def        A       (      ):





							'''simple docstring'''




							_lowerCAmelCase  :							Optional[int]				     =					np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]						)
							_lowerCAmelCase  :							List[Any]				     =					np.array([0, 0, 0, 1, 1]						)
							_lowerCAmelCase  :							List[Any]				     =					2
							_lowerCAmelCase  :							Union[str, Any]				     =					2

							# Assert that the function raises an AssertionError if dimensions > classes
							with pytest.raises(_lowerCamelCase						) as error_info:
														_lowerCAmelCase  :							Union[str, Any]				     =					linear_discriminant_analysis(
														    _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						)
														if isinstance(_lowerCamelCase       ,				np.ndarray						):
																					raise AssertionError(
																					    "Did not raise AssertionError for dimensions > classes"						)
														assert error_info.type is AssertionError






def        A       (      ):





							'''simple docstring'''




							_lowerCAmelCase  :							Optional[Any]				     =					np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]						)
							_lowerCAmelCase  :							List[str]				     =					2
							_lowerCAmelCase  :							List[Any]				     =					np.array([[6.92_82_03_23, 8.66_02_54_04, 10.39_23_04_85], [3.0, 3.0, 3.0]]						)

							with pytest.raises(_lowerCamelCase						) as error_info:
														_lowerCAmelCase  :							Tuple				     =					principal_component_analysis(_lowerCamelCase       ,				_lowerCamelCase						)
														if not np.allclose(_lowerCamelCase       ,				_lowerCamelCase						):
																					raise AssertionError
														assert error_info.type is AssertionError


if __name__ == "__main__":
						import doctest

						doctest.testmod()
