





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        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):
   _UpperCamelCase					:	List[str]				      = ['image_processor', 'tokenizer']
   _UpperCamelCase					:	Union[str, Any]				      = 'OwlViTImageProcessor'
   _UpperCamelCase					:	Dict				      = ('CLIPTokenizer', 'CLIPTokenizerFast')


   def __init__(					self    :       Optional[int]    ,  a    :       Union[str, Any]=None    ,  a    :       Dict=None    ,  **a    :       Union[str, Any] )->     int:





     """simple docstring"""







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

     lowercase__			    =						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__(a    ,  a )


   def __call__(					self    :       Tuple    ,  a    :       Tuple=None    ,  a    :       Any=None    ,  a    :       Tuple=None    ,  a    :       Union[str, Any]="max_length"    ,  a    :       int="np"    ,  **a    :       Tuple )->     Union[str, Any]:





     """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(a    ,  a ) or (isinstance(a    ,  a ) and not isinstance(text[0]    ,  a )):
         lowercase__			    =						[self.tokenizer(a    ,  padding=a    ,  return_tensors=a    ,  **a )]

       elif isinstance(a    ,  a ) and isinstance(text[0]    ,  a ):
         lowercase__			    =						[]

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

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

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

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

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

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

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

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

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

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

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

       lowercase__			    =						BatchEncoding()
       lowercase__			    =						input_ids
       lowercase__			    =						attention_mask

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

     if images is not None:
       lowercase__			    =						self.image_processor(a    ,  return_tensors=a    ,  **a )

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       Any    ,  *a    :       Optional[int]    ,  **a    :       List[Any] )->     List[str]:





     """simple docstring"""







     return self.image_processor.post_process(*a    ,  **a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Any    ,  *a    :       Optional[Any]    ,  **a    :       Tuple )->     Optional[Any]:





     """simple docstring"""







     return self.image_processor.post_process_object_detection(*a    ,  **a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Any    ,  *a    :       List[str]    ,  **a    :       Any )->     int:





     """simple docstring"""







     return self.image_processor.post_process_image_guided_detection(*a    ,  **a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict    ,  *a    :       List[Any]    ,  **a    :       Union[str, Any] )->     Union[str, Any]:





     """simple docstring"""







     return self.tokenizer.batch_decode(*a    ,  **a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int]    ,  *a    :       Optional[int]    ,  **a    :       Tuple )->     Optional[Any]:





     """simple docstring"""







     return self.tokenizer.decode(*a    ,  **a )


   @property
   def  SCREAMING_SNAKE_CASE_							(					self    :       Any )->     str:





     """simple docstring"""







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


   @property
   def  SCREAMING_SNAKE_CASE_							(					self    :       Union[str, Any] )->     Tuple:





     """simple docstring"""







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









from scipy.stats import spearmanr

import datasets


lowercase_					     =	"""
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

lowercase_					     =	"""
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {'spearmanr': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

lowercase_					     =	R"""\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,			_KWARGS_DESCRIPTION   )
class        SCREAMING_SNAKE_CASE     (datasets.Metric   ):


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





     """simple docstring"""







     return datasets.MetricInfo(
         description=_DESCRIPTION    ,  citation=_CITATION    ,  inputs_description=_KWARGS_DESCRIPTION    ,  features=datasets.Features(
             {
                 'predictions': datasets.Value('float' ),
                 'references': datasets.Value('float' ),
             } )    ,  reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html']    ,  )


   def  SCREAMING_SNAKE_CASE_							(					self    :       int    ,  a    :       str    ,  a    :       Any    ,  a    :       str=False )->     Optional[int]:





     """simple docstring"""







     lowercase__			    =						spearmanr(a    ,  a )
     if return_pvalue:
       return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
     else:
       return {"spearmanr": results[0]}


