
'''simple docstring'''




from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
		import tensorflow as tf

		from ..tf_utils import stable_softmax


if is_torch_available():
		import torch


__lowerCamelCase   :					Tuple   							=					logging.get_logger(__name__)







@add_end_docstrings(
    SCREAMING_SNAKE_CASE_						,					r'''\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    '''						,					)
class    A_	(SCREAMING_SNAKE_CASE_							):
							"""simple docstring"""




							def 							_A	(		self			:Dict       ,							lowerCAmelCase__			:Tuple				)				->  Any:


										'''simple docstring'''




										if self.framework == "tf":
													snake_case_				:					List[str]   =       tf.where(input_ids == self.tokenizer.mask_token_id				).numpy()
										elif self.framework == "pt":
													snake_case_				:					Any   =       torch.nonzero(input_ids == self.tokenizer.mask_token_id       ,							as_tuple=UpperCamelCase__				)
										else:
													raise ValueError("Unsupported framework"				)
										return masked_index

							def 							_A	(		self			:str       ,							lowerCAmelCase__			:List[Any]				)				->  Any:


										'''simple docstring'''




										snake_case_				:					Dict   =       self.get_masked_index(UpperCamelCase__				)
										snake_case_				:					str   =       np.prod(masked_index.shape				)
										if numel < 1:
													raise PipelineException(
													    "fill-mask"       ,							self.model.base_model_prefix       ,							F'''No mask_token ({self.tokenizer.mask_token}) found on the input'''       ,							)

							def 							_A	(		self			:List[Any]       ,							lowerCAmelCase__			:List[str]				)				->  Optional[Any]:


										'''simple docstring'''




										if isinstance(UpperCamelCase__       ,							UpperCamelCase__				):
													for model_input in model_inputs:
																self._ensure_exactly_one_mask_token(model_input["input_ids"][0]				)
										else:
													for input_ids in model_inputs["input_ids"]:
																self._ensure_exactly_one_mask_token(UpperCamelCase__				)

							def 							_A	(		self			:List[Any]       ,							lowerCAmelCase__			:Union[str, Any]       ,							lowerCAmelCase__			:int=None       ,							**lowerCAmelCase__			:List[Any]				)				->  int:


										'''simple docstring'''




										if return_tensors is None:
													snake_case_				:					str   =       self.framework
										snake_case_				:					str   =       self.tokenizer(UpperCamelCase__       ,							return_tensors=UpperCamelCase__				)
										self.ensure_exactly_one_mask_token(UpperCamelCase__				)
										return model_inputs

							def 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:int				)				->  Optional[int]:


										'''simple docstring'''




										snake_case_				:					Tuple   =       self.model(**UpperCamelCase__				)
										snake_case_				:					List[str]   =       model_inputs['''input_ids''']
										return model_outputs

							def 							_A	(		self			:Dict       ,							lowerCAmelCase__			:Dict       ,							lowerCAmelCase__			:Tuple=5       ,							lowerCAmelCase__			:List[str]=None				)				->  List[Any]:


										'''simple docstring'''




										if target_ids is not None and target_ids.shape[0] < top_k:
													snake_case_				:					Union[str, Any]   =       target_ids.shape[0]
										snake_case_				:					str   =       model_outputs['''input_ids'''][0]
										snake_case_				:					Tuple   =       model_outputs['''logits''']

										if self.framework == "tf":
													snake_case_				:					Tuple   =       tf.where(input_ids == self.tokenizer.mask_token_id				).numpy()[:, 0]

													snake_case_				:					Dict   =       outputs.numpy()

													snake_case_				:					Tuple   =       outputs[0, masked_index, :]
													snake_case_				:					str   =       stable_softmax(UpperCamelCase__       ,							axis=-1				)
													if target_ids is not None:
																snake_case_				:					int   =       tf.gather_nd(tf.squeeze(UpperCamelCase__       ,							0				)       ,							target_ids.reshape(-1       ,							1				)				)
																snake_case_				:					str   =       tf.expand_dims(UpperCamelCase__       ,							0				)

													snake_case_				:					str   =       tf.math.top_k(UpperCamelCase__       ,							k=UpperCamelCase__				)
													snake_case_				:					List[str]   =       topk.values.numpy(), topk.indices.numpy()
										else:
													snake_case_				:					Optional[Any]   =       torch.nonzero(input_ids == self.tokenizer.mask_token_id       ,							as_tuple=UpperCamelCase__				).squeeze(-1				)
													# Fill mask pipeline supports only one ${mask_token} per sample

													snake_case_				:					List[Any]   =       outputs[0, masked_index, :]
													snake_case_				:					Tuple   =       logits.softmax(dim=-1				)
													if target_ids is not None:
																snake_case_				:					str   =       probs[..., target_ids]

													snake_case_				:					Tuple   =       probs.topk(UpperCamelCase__				)

										snake_case_				:					Union[str, Any]   =       []
										snake_case_				:					str   =       values.shape[0] == 1
										for i, (_values, _predictions) in enumerate(zip(values.tolist()       ,							predictions.tolist()				)				):
													snake_case_				:					Optional[Any]   =       []
													for v, p in zip(_values       ,							_predictions				):
																# Copy is important since we're going to modify this array in place
																snake_case_				:					List[str]   =       input_ids.numpy().copy()
																if target_ids is not None:
																			snake_case_				:					Any   =       target_ids[p].tolist()

																snake_case_				:					List[str]   =       p
																# Filter padding out:
																snake_case_				:					Dict   =       tokens[np.where(tokens != self.tokenizer.pad_token_id				)]
																# Originally we skip special tokens to give readable output.
																# For multi masks though, the other [MASK] would be removed otherwise
																# making the output look odd, so we add them back
																snake_case_				:					Any   =       self.tokenizer.decode(UpperCamelCase__       ,							skip_special_tokens=UpperCamelCase__				)
																snake_case_				:					str   =       {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]				), '''sequence''': sequence}
																row.append(UpperCamelCase__				)
													result.append(UpperCamelCase__				)
										if single_mask:
													return result[0]
										return result

							def 							_A	(		self			:Dict       ,							lowerCAmelCase__			:Any       ,							lowerCAmelCase__			:Dict=None				)				->  List[str]:


										'''simple docstring'''




										if isinstance(UpperCamelCase__       ,							UpperCamelCase__				):
													snake_case_				:					Dict   =       [targets]
										try:
													snake_case_				:					Any   =       self.tokenizer.get_vocab()
										except Exception:
													snake_case_				:					Tuple   =       {}
										snake_case_				:					str   =       []
										for target in targets:
													snake_case_				:					int   =       vocab.get(UpperCamelCase__       ,							UpperCamelCase__				)
													if id_ is None:
																snake_case_				:					Tuple   =       self.tokenizer(
																    UpperCamelCase__       ,							add_special_tokens=UpperCamelCase__       ,							return_attention_mask=UpperCamelCase__       ,							return_token_type_ids=UpperCamelCase__       ,							max_length=1       ,							truncation=UpperCamelCase__       ,							)['''input_ids''']
																if len(UpperCamelCase__				) == 0:
																			logger.warning(
																			    F'''The specified target token `{target}` does not exist in the model vocabulary. '''
																			    "We cannot replace it with anything meaningful, ignoring it"				)
																			continue
																snake_case_				:					int   =       input_ids[0]
																# XXX: If users encounter this pass
																# it becomes pretty slow, so let's make sure
																# The warning enables them to fix the input to
																# get faster performance.
																logger.warning(
																    F'''The specified target token `{target}` does not exist in the model vocabulary. '''
																    F'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_				)}`.'''				)
													target_ids.append(id_				)
										snake_case_				:					str   =       list(set(UpperCamelCase__				)				)
										if len(UpperCamelCase__				) == 0:
													raise ValueError("At least one target must be provided when passed."				)
										snake_case_				:					Optional[int]   =       np.array(UpperCamelCase__				)
										return target_ids

							def 							_A	(		self			:Tuple       ,							lowerCAmelCase__			:str=None       ,							lowerCAmelCase__			:int=None				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					Tuple   =       {}

										if targets is not None:
													snake_case_				:					Any   =       self.get_target_ids(UpperCamelCase__       ,							UpperCamelCase__				)
													snake_case_				:					List[Any]   =       target_ids

										if top_k is not None:
													snake_case_				:					Union[str, Any]   =       top_k

										if self.tokenizer.mask_token_id is None:
													raise PipelineException(
													    "fill-mask"       ,							self.model.base_model_prefix       ,							"The tokenizer does not define a `mask_token`."				)
										return {}, {}, postprocess_params






							def __call__(		self			:Union[str, Any]       ,							lowerCAmelCase__			:Optional[Any]       ,							*lowerCAmelCase__			:Union[str, Any]       ,							**lowerCAmelCase__			:List[str]				)				->  Union[str, Any]:


										'''simple docstring'''




										snake_case_				:					Any   =       super().__call__(UpperCamelCase__       ,							**UpperCamelCase__				)
										if isinstance(UpperCamelCase__       ,							UpperCamelCase__				) and len(UpperCamelCase__				) == 1:
													return outputs[0]
										return outputs












'''simple docstring'''




from scipy.stats import spearmanr

import datasets


__lowerCamelCase   :					str   							=					'''
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.
'''

__lowerCamelCase   :					int   							=					'''
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
'''

__lowerCamelCase   :					List[str]   							=					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    A_	(datasets.Metric							):
							"""simple docstring"""




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


										'''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 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:Optional[Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:Optional[Any]=False				)				->  List[Any]:


										'''simple docstring'''




										snake_case_				:					Optional[Any]   =       spearmanr(lowerCAmelCase__       ,							lowerCAmelCase__				)
										if return_pvalue:
													return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
										else:
													return {"spearmanr": results[0]}




