

'''simple docstring'''



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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase				: Union[str, Any]         =  logging.get_logger(__name__)
UpperCAmelCase				: List[Any]         =  {'vocab_file': 'spiece.model'}

UpperCAmelCase				: Any         =  {
    'vocab_file': {
        'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model',
        'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model',
    },
}

UpperCAmelCase				: Tuple         =  {
    'google/fnet-base': 5_1_2,
    'google/fnet-large': 5_1_2,
}

UpperCAmelCase				: Union[str, Any]         =  '▁'







class 		lowerCAmelCase__     (   a      ):



 """simple docstring"""



 lowerCAmelCase__						      =   VOCAB_FILES_NAMES
 lowerCAmelCase__						      =   PRETRAINED_VOCAB_FILES_MAP
 lowerCAmelCase__						      =   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowerCAmelCase__						      =   ["input_ids", "token_type_ids"]
 def __init__(	self      : List[str]      ,							__SCREAMING_SNAKE_CASE      : Optional[Any]      ,							__SCREAMING_SNAKE_CASE      : str=False      ,							__SCREAMING_SNAKE_CASE      : Optional[int]=True      ,							__SCREAMING_SNAKE_CASE      : List[Any]=True      ,							__SCREAMING_SNAKE_CASE      : int="<unk>"      ,							__SCREAMING_SNAKE_CASE      : List[str]="[SEP]"      ,							__SCREAMING_SNAKE_CASE      : List[str]="<pad>"      ,							__SCREAMING_SNAKE_CASE      : List[Any]="[CLS]"      ,							__SCREAMING_SNAKE_CASE      : Dict="[MASK]"      ,							__SCREAMING_SNAKE_CASE      : Optional[Dict[str, Any]] = None      ,							**__SCREAMING_SNAKE_CASE      : Dict      ,							)						->				None:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   (
          AddedToken(__SCREAMING_SNAKE_CASE      ,							lstrip=__SCREAMING_SNAKE_CASE      ,							rstrip=__SCREAMING_SNAKE_CASE      ,							normalized=__SCREAMING_SNAKE_CASE    )
          if isinstance(__SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE    )
          else mask_token
      )

      __SCREAMING_SNAKE_CASE						     =   {} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          do_lower_case=__SCREAMING_SNAKE_CASE      ,							remove_space=__SCREAMING_SNAKE_CASE      ,							keep_accents=__SCREAMING_SNAKE_CASE      ,							unk_token=__SCREAMING_SNAKE_CASE      ,							sep_token=__SCREAMING_SNAKE_CASE      ,							pad_token=__SCREAMING_SNAKE_CASE      ,							cls_token=__SCREAMING_SNAKE_CASE      ,							mask_token=__SCREAMING_SNAKE_CASE      ,							sp_model_kwargs=self.sp_model_kwargs      ,							**__SCREAMING_SNAKE_CASE      ,							)

      __SCREAMING_SNAKE_CASE						     =   do_lower_case
      __SCREAMING_SNAKE_CASE						     =   remove_space
      __SCREAMING_SNAKE_CASE						     =   keep_accents
      __SCREAMING_SNAKE_CASE						     =   vocab_file

      __SCREAMING_SNAKE_CASE						     =   spm.SentencePieceProcessor(**self.sp_model_kwargs    )
      self.sp_model.Load(__SCREAMING_SNAKE_CASE    )
 @property
 def    UpperCAmelCase__	(	self      : int    )						->				Optional[Any]:


      """simple docstring"""




      return len(self.sp_model    )
 def    UpperCAmelCase__	(	self      : Dict    )						->				Tuple:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE    ): i for i in range(self.vocab_size    )}
      vocab.update(self.added_tokens_encoder    )
      return vocab
 def __getstate__(	self      : Any    )						->				str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   self.__dict__.copy()
      __SCREAMING_SNAKE_CASE						     =   None
      return state
 def __setstate__(	self      : List[str]      ,							__SCREAMING_SNAKE_CASE      : Dict    )						->				Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   d

      # for backward compatibility
      if not hasattr(self      ,							"""sp_model_kwargs"""    ):
           __SCREAMING_SNAKE_CASE						     =   {}

      __SCREAMING_SNAKE_CASE						     =   spm.SentencePieceProcessor(**self.sp_model_kwargs    )
      self.sp_model.Load(self.vocab_file    )
 def    UpperCAmelCase__	(	self      : Tuple      ,							__SCREAMING_SNAKE_CASE      : Optional[int]    )						->				Optional[int]:


      """simple docstring"""




      if self.remove_space:
           __SCREAMING_SNAKE_CASE						     =   """ """.join(inputs.strip().split()    )
      else:
           __SCREAMING_SNAKE_CASE						     =   inputs
      __SCREAMING_SNAKE_CASE						     =   outputs.replace("""``"""      ,							"""\""""    ).replace("""''"""      ,							"""\""""    )

      if not self.keep_accents:
           __SCREAMING_SNAKE_CASE						     =   unicodedata.normalize("""NFKD"""      ,							__SCREAMING_SNAKE_CASE    )
           __SCREAMING_SNAKE_CASE						     =   """""".join([c for c in outputs if not unicodedata.combining(__SCREAMING_SNAKE_CASE    )]    )
      if self.do_lower_case:
           __SCREAMING_SNAKE_CASE						     =   outputs.lower()

      return outputs
 def    UpperCAmelCase__	(	self      : str      ,							__SCREAMING_SNAKE_CASE      : str    )						->				List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   self.preprocess_text(__SCREAMING_SNAKE_CASE    )
      __SCREAMING_SNAKE_CASE						     =   self.sp_model.encode(__SCREAMING_SNAKE_CASE      ,							out_type=__SCREAMING_SNAKE_CASE    )
      __SCREAMING_SNAKE_CASE						     =   []
      for piece in pieces:
           if len(__SCREAMING_SNAKE_CASE    ) > 1 and piece[-1] == str(""","""    ) and piece[-2].isdigit():
                __SCREAMING_SNAKE_CASE						     =   self.sp_model.EncodeAsPieces(piece[:-1].replace(__SCREAMING_SNAKE_CASE      ,							""""""    )    )
                if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                     if len(cur_pieces[0]    ) == 1:
                          __SCREAMING_SNAKE_CASE						     =   cur_pieces[1:]
                     else:
                          __SCREAMING_SNAKE_CASE						     =   cur_pieces[0][1:]
                cur_pieces.append(piece[-1]    )
                new_pieces.extend(__SCREAMING_SNAKE_CASE    )
           else:
                new_pieces.append(__SCREAMING_SNAKE_CASE    )

      return new_pieces
 def    UpperCAmelCase__	(	self      : Any      ,							__SCREAMING_SNAKE_CASE      : str    )						->				Optional[Any]:


      """simple docstring"""




      return self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE    )
 def    UpperCAmelCase__	(	self      : Optional[Any]      ,							__SCREAMING_SNAKE_CASE      : Union[str, Any]    )						->				Optional[Any]:


      """simple docstring"""




      return self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE    )
 def    UpperCAmelCase__	(	self      : Dict      ,							__SCREAMING_SNAKE_CASE      : List[str]    )						->				Optional[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   []
      __SCREAMING_SNAKE_CASE						     =   """"""
      __SCREAMING_SNAKE_CASE						     =   False
      for token in tokens:
           # make sure that special tokens are not decoded using sentencepiece model
           if token in self.all_special_tokens:
                if not prev_is_special:
                     out_string += " "
                out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE    ) + token
                __SCREAMING_SNAKE_CASE						     =   True
                __SCREAMING_SNAKE_CASE						     =   []
           else:
                current_sub_tokens.append(__SCREAMING_SNAKE_CASE    )
                __SCREAMING_SNAKE_CASE						     =   False
      out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE    )
      return out_string.strip()
 def    UpperCAmelCase__	(	self      : List[Any]      ,							__SCREAMING_SNAKE_CASE      : List[int]      ,							__SCREAMING_SNAKE_CASE      : bool = False      ,							__SCREAMING_SNAKE_CASE      : bool = None      ,							__SCREAMING_SNAKE_CASE      : bool = True      ,							**__SCREAMING_SNAKE_CASE      : List[str]      ,							)						->				str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   kwargs.pop("""use_source_tokenizer"""      ,							__SCREAMING_SNAKE_CASE    )

      __SCREAMING_SNAKE_CASE						     =   self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE      ,							skip_special_tokens=__SCREAMING_SNAKE_CASE    )

      # To avoid mixing byte-level and unicode for byte-level BPT
      # we need to build string separately for added tokens and byte-level tokens
      # cf. https://github.com/huggingface/transformers/issues/1133
      __SCREAMING_SNAKE_CASE						     =   []
      __SCREAMING_SNAKE_CASE						     =   []
      for token in filtered_tokens:
           if skip_special_tokens and token in self.all_special_ids:
                continue
           if token in self.added_tokens_encoder:
                if current_sub_text:
                     sub_texts.append(self.convert_tokens_to_string(__SCREAMING_SNAKE_CASE    )    )
                     __SCREAMING_SNAKE_CASE						     =   []
                sub_texts.append(__SCREAMING_SNAKE_CASE    )
           else:
                current_sub_text.append(__SCREAMING_SNAKE_CASE    )
      if current_sub_text:
           sub_texts.append(self.convert_tokens_to_string(__SCREAMING_SNAKE_CASE    )    )

      # Mimic the behavior of the Rust tokenizer:
      # No space after <unk>
      if spaces_between_special_tokens:
           __SCREAMING_SNAKE_CASE						     =   re.sub(r"""(<unk>) """      ,							r"""\1"""      ,							""" """.join(__SCREAMING_SNAKE_CASE    )    )
      else:
           __SCREAMING_SNAKE_CASE						     =   """""".join(__SCREAMING_SNAKE_CASE    )

      __SCREAMING_SNAKE_CASE						     =   (
          clean_up_tokenization_spaces
          if clean_up_tokenization_spaces is not None
          else self.clean_up_tokenization_spaces
      )
      if clean_up_tokenization_spaces:
           __SCREAMING_SNAKE_CASE						     =   self.clean_up_tokenization(__SCREAMING_SNAKE_CASE    )
           return clean_text
      else:
           return text
 def    UpperCAmelCase__	(	self      : str      ,							__SCREAMING_SNAKE_CASE      : List[int]      ,							__SCREAMING_SNAKE_CASE      : Optional[List[int]] = None    )						->				List[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   [self.sep_token_id]
      __SCREAMING_SNAKE_CASE						     =   [self.cls_token_id]
      if token_ids_a is None:
           return cls + token_ids_a + sep
      return cls + token_ids_a + sep + token_ids_a + sep
 def    UpperCAmelCase__	(	self      : Dict      ,							__SCREAMING_SNAKE_CASE      : List[int]      ,							__SCREAMING_SNAKE_CASE      : Optional[List[int]] = None      ,							__SCREAMING_SNAKE_CASE      : bool = False    )						->				List[int]:


      """simple docstring"""




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

      if token_ids_a is not None:
           return [1] + ([0] * len(__SCREAMING_SNAKE_CASE    )) + [1] + ([0] * len(__SCREAMING_SNAKE_CASE    )) + [1]
      return [1] + ([0] * len(__SCREAMING_SNAKE_CASE    )) + [1]
 def    UpperCAmelCase__	(	self      : List[Any]      ,							__SCREAMING_SNAKE_CASE      : List[int]      ,							__SCREAMING_SNAKE_CASE      : Optional[List[int]] = None    )						->				List[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   [self.sep_token_id]
      __SCREAMING_SNAKE_CASE						     =   [self.cls_token_id]

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


 def    UpperCAmelCase__	(	self      : List[str]      ,							__SCREAMING_SNAKE_CASE      : str      ,							__SCREAMING_SNAKE_CASE      : Optional[str] = None    )						->				Tuple[str]:


      """simple docstring"""




      if not os.path.isdir(__SCREAMING_SNAKE_CASE    ):
           logger.error(f'Vocabulary path ({save_directory}) should be a directory'    )
           return
      __SCREAMING_SNAKE_CASE						     =   os.path.join(
          __SCREAMING_SNAKE_CASE      ,							(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]    )

      if os.path.abspath(self.vocab_file    ) != os.path.abspath(__SCREAMING_SNAKE_CASE    ) and os.path.isfile(self.vocab_file    ):
           copyfile(self.vocab_file      ,							__SCREAMING_SNAKE_CASE    )
      elif not os.path.isfile(self.vocab_file    ):
           with open(__SCREAMING_SNAKE_CASE      ,							"""wb"""    ) as fi:
                __SCREAMING_SNAKE_CASE						     =   self.sp_model.serialized_model_proto()
                fi.write(__SCREAMING_SNAKE_CASE    )

      return (out_vocab_file,)









'''simple docstring'''



from sklearn.metrics import precision_score

import datasets


UpperCAmelCase				: Optional[int]         =  '\nPrecision is the fraction of correctly labeled positive examples out of all of the examples that were labeled as positive. It is computed via the equation:\nPrecision = TP / (TP + FP)\nwhere TP is the True positives (i.e. the examples correctly labeled as positive) and FP is the False positive examples (i.e. the examples incorrectly labeled as positive).\n'


UpperCAmelCase				: Optional[int]         =  '\nArgs:\n    predictions (`list` of `int`): Predicted class labels.\n    references (`list` of `int`): Actual class labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`. If `average` is `None`, it should be the label order. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. 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 `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` 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. This option 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 (`int` or `string`): Sets the value to return when there is a zero division. Defaults to \'warn\'.\n\n        - 0: Returns 0 when there is a zero division.\n        - 1: Returns 1 when there is a zero division.\n        - \'warn\': Raises warnings and then returns 0 when there is a zero division.\n\nReturns:\n    precision (`float` or `array` of `float`): Precision score or list of precision scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate that fewer negative examples were incorrectly labeled as positive, which means that, generally, higher scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {\'precision\': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results[\'precision\'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(results)\n        {\'precision\': 0.23529411764705882}\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'macro\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'micro\')\n        >>> print(results)\n        {\'precision\': 0.3333333333333333}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'weighted\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print([round(res, 2) for res in results[\'precision\']])\n        [0.67, 0.0, 0.0]\n'


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







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,      _KWARGS_DESCRIPTION      )
class 		lowerCAmelCase__     (   datasets.Metric      ):



 """simple docstring"""



 def    UpperCAmelCase__	(	self      : List[str]    )						->				Dict:


      """simple docstring"""




      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.precision_score.html"""]      ,							)


 def    UpperCAmelCase__	(	self      : List[Any]      ,							__SCREAMING_SNAKE_CASE      : List[str]      ,							__SCREAMING_SNAKE_CASE      : Dict      ,							__SCREAMING_SNAKE_CASE      : Union[str, Any]=None      ,							__SCREAMING_SNAKE_CASE      : List[Any]=1      ,							__SCREAMING_SNAKE_CASE      : Tuple="binary"      ,							__SCREAMING_SNAKE_CASE      : Any=None      ,							__SCREAMING_SNAKE_CASE      : Tuple="warn"      ,							)						->				List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   precision_score(
          __SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE      ,							labels=__SCREAMING_SNAKE_CASE      ,							pos_label=__SCREAMING_SNAKE_CASE      ,							average=__SCREAMING_SNAKE_CASE      ,							sample_weight=__SCREAMING_SNAKE_CASE      ,							zero_division=__SCREAMING_SNAKE_CASE      ,							)
      return {"precision": float(__SCREAMING_SNAKE_CASE    ) if score.size == 1 else score}






