

'''simple docstring'''







import logging

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

logging.basicConfig(level=logging.INFO, format='''%(message)s''')
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      np.ndarray:
       return input_array.reshape((input_array.size, 1)					)
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__					)      ->      np.ndarray:
       A_						       =   np.nan
       for i in range(UpperCAmelCase__					):
              A_						       =   features[:, labels == i]
              A_						       =   data.mean(1					)
              # Centralize the data of class i
              A_						       =   data - column_reshape(UpperCAmelCase__					)
              if i > 0:
                     # If covariance_sum is not None
                     covariance_sum += np.dot(UpperCAmelCase__,							centered_data.T					)
              else:
                     # If covariance_sum is np.nan (i.e. first loop)
                     A_						       =   np.dot(UpperCAmelCase__,							centered_data.T					)

       return covariance_sum / features.shape[1]
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__					)      ->      np.ndarray:
       A_						       =   features.mean(1					)
       A_						       =   np.nan
       for i in range(UpperCAmelCase__					):
              A_						       =   features[:, labels == i]
              A_						       =   data.shape[1]
              A_						       =   data.mean(1					)
              if i > 0:
                     # If covariance_sum is not None
                     covariance_sum += device_data * np.dot(
                         column_reshape(UpperCAmelCase__					) - column_reshape(UpperCAmelCase__					),							(column_reshape(UpperCAmelCase__					) - column_reshape(UpperCAmelCase__					)).T,							)
              else:
                     # If covariance_sum is np.nan (i.e. first loop)
                     A_						       =   device_data * np.dot(
                         column_reshape(UpperCAmelCase__					) - column_reshape(UpperCAmelCase__					),							(column_reshape(UpperCAmelCase__					) - column_reshape(UpperCAmelCase__					)).T,							)

       return covariance_sum / features.shape[1]
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      np.ndarray:

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

              return projected_data
       else:
              logging.basicConfig(level=logging.ERROR,							format="""%(message)s""",							force=UpperCAmelCase__					)
              logging.error("""Dataset empty"""					)
              raise AssertionError
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__					)      ->      np.ndarray:
       assert classes > dimensions

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

              return projected_data
       else:
              logging.basicConfig(level=logging.ERROR,							format="""%(message)s""",							force=UpperCAmelCase__					)
              logging.error("""Dataset empty"""					)
              raise AssertionError
def    UpperCAmelCase__     (   )      ->      None:
       # Create dummy dataset with 2 classes and 3 features
       A_						       =   np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]					)
       A_						       =   np.array([0, 0, 0, 1, 1]					)
       A_						       =   2
       A_						       =   2

       # Assert that the function raises an AssertionError if dimensions > classes
       with pytest.raises(UpperCAmelCase__					) as error_info:
              A_						       =   linear_discriminant_analysis(
                  UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__					)
              if isinstance(UpperCAmelCase__,							np.ndarray					):
                     raise AssertionError(
                         """Did not raise AssertionError for dimensions > classes"""					)
              assert error_info.type is AssertionError
def    UpperCAmelCase__     (   )      ->      None:
       A_						       =   np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]					)
       A_						       =   2
       A_						       =   np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]]					)

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


if __name__ == "__main__":
      import doctest

      doctest.testmod()



'''simple docstring'''







import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available


class        A__   (   _snake_case      ):
    lowercase						       =		["image_processor", "tokenizer"]
    lowercase						       =		"OwlViTImageProcessor"
    lowercase						       =		("CLIPTokenizer", "CLIPTokenizerFast")



    def __init__(       self		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					**UpperCamelCase__							)    ->   str:





           '''simple docstring'''
           A_						       =   None
           if "feature_extractor" in kwargs:
                  warnings.warn(
                      """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
                      """ instead."""		,					UpperCamelCase__		,					)
                  A_						       =   kwargs.pop("""feature_extractor"""							)

           A_						       =   image_processor if image_processor is not None else feature_extractor
           if image_processor is None:
                  raise ValueError("""You need to specify an `image_processor`."""							)
           if tokenizer is None:
                  raise ValueError("""You need to specify a `tokenizer`."""							)

           super().__init__(UpperCamelCase__		,					UpperCamelCase__							)



    def __call__(       self		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					UpperCamelCase__="max_length"		,					UpperCamelCase__="np"		,					**UpperCamelCase__							)    ->   int:





           '''simple docstring'''

           if text is None and query_images is None and images is None:
                  raise ValueError(
                      """You have to specify at least one text or query image or image. All three cannot be none."""							)

           if text is not None:
                  if isinstance(UpperCamelCase__		,					UpperCamelCase__							) or (isinstance(UpperCamelCase__		,					UpperCamelCase__							) and not isinstance(text[0]		,					UpperCamelCase__							)):
                         A_						       =   [self.tokenizer(UpperCamelCase__		,					padding=UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							)]

                  elif isinstance(UpperCamelCase__		,					UpperCamelCase__							) and isinstance(text[0]		,					UpperCamelCase__							):
                         A_						       =   []

                         # Maximum number of queries across batch
                         A_						       =   max([len(UpperCamelCase__							) for t in text]							)

                         # Pad all batch samples to max number of text queries
                         for t in text:
                                if len(UpperCamelCase__							) != max_num_queries:
                                       A_						       =   t + [""" """] * (max_num_queries - len(UpperCamelCase__							))

                                A_						       =   self.tokenizer(UpperCamelCase__		,					padding=UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							)
                                encodings.append(UpperCamelCase__							)
                  else:
                         raise TypeError("""Input text should be a string, a list of strings or a nested list of strings"""							)

                  if return_tensors == "np":
                         A_						       =   np.concatenate([encoding["""input_ids"""] for encoding in encodings]		,					axis=0							)
                         A_						       =   np.concatenate([encoding["""attention_mask"""] for encoding in encodings]		,					axis=0							)

                  elif return_tensors == "jax" and is_flax_available():
                         import jax.numpy as jnp

                         A_						       =   jnp.concatenate([encoding["""input_ids"""] for encoding in encodings]		,					axis=0							)
                         A_						       =   jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings]		,					axis=0							)

                  elif return_tensors == "pt" and is_torch_available():
                         import torch

                         A_						       =   torch.cat([encoding["""input_ids"""] for encoding in encodings]		,					dim=0							)
                         A_						       =   torch.cat([encoding["""attention_mask"""] for encoding in encodings]		,					dim=0							)

                  elif return_tensors == "tf" and is_tf_available():
                         import tensorflow as tf

                         A_						       =   tf.stack([encoding["""input_ids"""] for encoding in encodings]		,					axis=0							)
                         A_						       =   tf.stack([encoding["""attention_mask"""] for encoding in encodings]		,					axis=0							)

                  else:
                         raise ValueError("""Target return tensor type could not be returned"""							)

                  A_						       =   BatchEncoding()
                  A_						       =   input_ids
                  A_						       =   attention_mask

           if query_images is not None:
                  A_						       =   BatchEncoding()
                  A_						       =   self.image_processor(
                      UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							).pixel_values
                  A_						       =   query_pixel_values

           if images is not None:
                  A_						       =   self.image_processor(UpperCamelCase__		,					return_tensors=UpperCamelCase__		,					**UpperCamelCase__							)

           if text is not None and images is not None:
                  A_						       =   image_features.pixel_values
                  return encoding
           elif query_images is not None and images is not None:
                  A_						       =   image_features.pixel_values
                  return encoding
           elif text is not None or query_images is not None:
                  return encoding
           else:
                  return BatchEncoding(data=dict(**UpperCamelCase__							)		,					tensor_type=UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   int:





           '''simple docstring'''
           return self.image_processor.post_process(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   List[Any]:





           '''simple docstring'''
           return self.image_processor.post_process_object_detection(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   Tuple:





           '''simple docstring'''
           return self.image_processor.post_process_image_guided_detection(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   Any:





           '''simple docstring'''
           return self.tokenizer.batch_decode(*UpperCamelCase__		,					**UpperCamelCase__							)



    def        snake_case_      (       self		,					*UpperCamelCase__		,					**UpperCamelCase__							)    ->   List[str]:





           '''simple docstring'''
           return self.tokenizer.decode(*UpperCamelCase__		,					**UpperCamelCase__							)



    @property
    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           warnings.warn(
               """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""		,					UpperCamelCase__		,					)
           return self.image_processor_class







    @property
    def        snake_case_      (       self							)    ->   List[str]:





           '''simple docstring'''
           warnings.warn(
               """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""		,					UpperCamelCase__		,					)
           return self.image_processor
