


"""simple docstring"""


from sklearn.metrics import recall_score

import datasets


__snake_case    					=					'\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n'


__snake_case    					=					'\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the \'positive class\' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n    - `\'binary\'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `\'micro\'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `\'macro\'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `\'weighted\'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `\'samples\'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `\'warn\'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {\'recall\': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {\'recall\': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {\'recall\': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'macro\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'micro\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'weighted\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {\'recall\': array([1., 0., 0.])}\n'


__snake_case    					=					'\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n'

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,   _KWARGS_DESCRIPTION  )
class 				_SCREAMING_SNAKE_CASE				(							datasets.Metric  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    return datasets.MetricInfo(
        description=_DESCRIPTION ,     citation=_CITATION ,     inputs_description=_KWARGS_DESCRIPTION ,     features=datasets.Features(
            {
                """predictions""": datasets.Sequence(datasets.Value("""int32"""						)						),
                """references""": datasets.Sequence(datasets.Value("""int32"""						)						),
            }
            if self.config_name == """multilabel"""
            else {
                """predictions""": datasets.Value("""int32"""						),
                """references""": datasets.Value("""int32"""						),
            }						) ,     reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""] ,     )







   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ ,     lowerCamelCase__=None ,     lowerCamelCase__=1 ,     lowerCamelCase__="binary" ,     lowerCamelCase__=None ,     lowerCamelCase__="warn" ,     )      ->							Tuple:
    lowercase__       :       int				=						recall_score(
        lowerCamelCase__ ,     lowerCamelCase__ ,     labels=lowerCamelCase__ ,     pos_label=lowerCamelCase__ ,     average=lowerCamelCase__ ,     sample_weight=lowerCamelCase__ ,     zero_division=lowerCamelCase__ ,     )
    return {"recall": float(lowerCamelCase__						) if score.size == 1 else score}



"""simple docstring"""


import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__snake_case    					=					logging.get_logger(__name__)

__snake_case    					=					'▁'

__snake_case    					=					{'vocab_file': 'sentencepiece.bpe.model'}

__snake_case    					=					{
    'vocab_file': {
        'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model',
    }
}

__snake_case    					=					{
    'facebook/xglm-564M': 2048,
}

class 				_SCREAMING_SNAKE_CASE				(							__UpperCAmelCase  ):
   """simple docstring"""



   _a   :       Optional[int]									=    VOCAB_FILES_NAMES
   _a   :       Union[str, Any]									=    PRETRAINED_VOCAB_FILES_MAP
   _a   :       Dict									=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   _a   :       Any									=    ['''input_ids''', '''attention_mask''']


   def __init__(						self ,     lowerCamelCase__ ,     lowerCamelCase__="<s>" ,     lowerCamelCase__="</s>" ,     lowerCamelCase__="</s>" ,     lowerCamelCase__="<s>" ,     lowerCamelCase__="<unk>" ,     lowerCamelCase__="<pad>" ,     lowerCamelCase__ = None ,     **lowerCamelCase__ ,     )      ->							None:
    lowercase__       :       List[Any]				=						{} if sp_model_kwargs is None else sp_model_kwargs

    # Compatibility with the original tokenizer
    lowercase__       :       Any				=						7
    lowercase__       :       Dict				=						[F'''<madeupword{i}>''' for i in range(self.num_madeup_words						)]

    lowercase__       :       Tuple				=						kwargs.get("""additional_special_tokens""" ,     []						)
    kwargs["additional_special_tokens"] += [
        word for word in madeup_words if word not in kwargs["additional_special_tokens"]
    ]

    super().__init__(
        bos_token=lowerCamelCase__ ,     eos_token=lowerCamelCase__ ,     unk_token=lowerCamelCase__ ,     sep_token=lowerCamelCase__ ,     cls_token=lowerCamelCase__ ,     pad_token=lowerCamelCase__ ,     sp_model_kwargs=self.sp_model_kwargs ,     **lowerCamelCase__ ,     )

    lowercase__       :       Optional[Any]				=						spm.SentencePieceProcessor(**self.sp_model_kwargs						)
    self.sp_model.Load(str(lowerCamelCase__						)						)
    lowercase__       :       Optional[Any]				=						vocab_file

    # Original fairseq vocab and spm vocab must be "aligned":
    # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
    # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
    # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
    # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

    # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
    lowercase__       :       Optional[Any]				=						1

    # Mimic fairseq token-to-id alignment for the first 4 token
    lowercase__       :       Any				=						{"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

    lowercase__       :       Optional[int]				=						len(self.sp_model						)
    lowercase__       :       Union[str, Any]				=						{F'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words						)}
    self.fairseq_tokens_to_ids.update(lowerCamelCase__						)

    lowercase__       :       List[str]				=						{v: k for k, v in self.fairseq_tokens_to_ids.items()}


   def __getstate__(						self						)      ->							Dict:
    lowercase__       :       Any				=						self.__dict__.copy()
    lowercase__       :       List[str]				=						None
    lowercase__       :       str				=						self.sp_model.serialized_model_proto()
    return state


   def __setstate__(						self ,     lowerCamelCase__						)      ->							Optional[int]:
    lowercase__       :       int				=						d

    # for backward compatibility
    if not hasattr(self ,     """sp_model_kwargs"""						):
     lowercase__       :       Union[str, Any]				=						{}

    lowercase__       :       Optional[int]				=						spm.SentencePieceProcessor(**self.sp_model_kwargs						)
    self.sp_model.LoadFromSerializedProto(self.sp_model_proto						)


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ = None						)      ->							List[int]:

    if token_ids_a is None:
     return [self.sep_token_id] + token_ids_a
    lowercase__       :       List[str]				=						[self.sep_token_id]
    return sep + token_ids_a + sep + sep + token_ids_a


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ = None ,     lowerCamelCase__ = False						)      ->							List[int]:

    if already_has_special_tokens:
     return super().get_special_tokens_mask(
         token_ids_a=lowerCamelCase__ ,     token_ids_a=lowerCamelCase__ ,     already_has_special_tokens=lowerCamelCase__						)

    if token_ids_a is None:
     return [1] + ([0] * len(lowerCamelCase__						))
    return [1] + ([0] * len(lowerCamelCase__						)) + [1, 1] + ([0] * len(lowerCamelCase__						))


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ = None						)      ->							List[int]:
    lowercase__       :       str				=						[self.sep_token_id]

    if token_ids_a is None:
     return len(sep + token_ids_a						) * [0]
    return len(sep + token_ids_a + sep + sep + token_ids_a						) * [0]


   @property
   def 					UpperCAmelCase__(						self						)      ->							Union[str, Any]:
    return len(self.sp_model						) + self.fairseq_offset + self.num_madeup_words


   def 					UpperCAmelCase__(						self						)      ->							int:
    lowercase__       :       Optional[Any]				=						{self.convert_ids_to_tokens(lowerCamelCase__						): i for i in range(self.vocab_size						)}
    vocab.update(self.added_tokens_encoder						)
    return vocab


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__						)      ->							List[str]:
    return self.sp_model.encode(lowerCamelCase__ ,     out_type=lowerCamelCase__						)


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__						)      ->							int:
    if token in self.fairseq_tokens_to_ids:
     return self.fairseq_tokens_to_ids[token]
    lowercase__       :       List[Any]				=						self.sp_model.PieceToId(lowerCamelCase__						)

    # Need to return unknown token if the SP model returned 0
    return spm_id + self.fairseq_offset if spm_id else self.unk_token_id


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__						)      ->							int:
    if index in self.fairseq_ids_to_tokens:
     return self.fairseq_ids_to_tokens[index]
    return self.sp_model.IdToPiece(index - self.fairseq_offset						)


   def 					UpperCAmelCase__(						self ,     lowerCamelCase__						)      ->							int:
    lowercase__       :       Dict				=						"""""".join(lowerCamelCase__						).replace(lowerCamelCase__ ,     """ """						).strip()
    return out_string







   def 					UpperCAmelCase__(						self ,     lowerCamelCase__ ,     lowerCamelCase__ = None						)      ->							Tuple[str]:
    if not os.path.isdir(lowerCamelCase__						):
     logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''						)
     return
    lowercase__       :       int				=						os.path.join(
        lowerCamelCase__ ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]						)

    if os.path.abspath(self.vocab_file						) != os.path.abspath(lowerCamelCase__						) and os.path.isfile(self.vocab_file						):
     copyfile(self.vocab_file ,     lowerCamelCase__						)
    elif not os.path.isfile(self.vocab_file						):
     with open(lowerCamelCase__ ,     """wb"""						) as fi:
      lowercase__       :       Union[str, Any]				=						self.sp_model.serialized_model_proto()
      fi.write(lowerCamelCase__						)

    return (out_vocab_file,)