






import os
from shutil import copyfile
from typing import Optional, Tuple

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
   from .tokenization_reformer import ReformerTokenizer
else:
   snake_case			 =						None


snake_case			 =						logging.get_logger(__name__)


snake_case			 =						"""▁"""

snake_case			 =						{"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""}

snake_case			 =						{
    """vocab_file""": {
        """google/reformer-crime-and-punishment""": (
            """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"""
        )
    },
    """tokenizer_file""": {
        """google/reformer-crime-and-punishment""": (
            """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/tokenizer.json"""
        )
    },
}

snake_case			 =						{
    """google/reformer-crime-and-punishment""": 524_288,
}


class        SCREAMING_SNAKE_CASE	(	lowerCAmelCase    ):
     '''simple docstring'''


     UpperCamelCase_							:						List[str]								=		VOCAB_FILES_NAMES
     UpperCamelCase_							:						List[str]								=		PRETRAINED_VOCAB_FILES_MAP
     UpperCamelCase_							:						Optional[int]								=		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     UpperCamelCase_							:						Tuple								=		['''input_ids''', '''attention_mask''']
     UpperCamelCase_							:						str								=		ReformerTokenizer


     def __init__( self				:		Dict    ,       UpperCAmelCase_				:		Tuple=None    ,       UpperCAmelCase_				:		Tuple=None    ,       UpperCAmelCase_				:		str="</s>"    ,       UpperCAmelCase_				:		List[Any]="<unk>"    ,       UpperCAmelCase_				:		Any=[]    ,       **UpperCAmelCase_				:		Optional[Any]    ,       ):
       super().__init__(
           UpperCAmelCase_    ,       tokenizer_file=UpperCAmelCase_    ,       eos_token=UpperCAmelCase_    ,       unk_token=UpperCAmelCase_    ,       additional_special_tokens=UpperCAmelCase_    ,       **UpperCAmelCase_    ,       )

       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			vocab_file
       SCREAMING_SNAKE_CASE				:					Any		  =			False if not self.vocab_file else True






     def  _A				( self				:		Optional[int]    ,       UpperCAmelCase_				:		str    ,       UpperCAmelCase_				:		Optional[str] = None					):
       if not self.can_save_slow_tokenizer:
         raise ValueError(
             "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
             "tokenizer."					)

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

       if os.path.abspath(self.vocab_file					) != os.path.abspath(UpperCAmelCase_					):
         copyfile(self.vocab_file    ,       UpperCAmelCase_					)

       return (out_vocab_file,)














from typing import List

from packaging import version
from sklearn.metrics import fa_score

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse("""3.8"""):
   import importlib_metadata
else:
   import importlib.metadata as importlib_metadata


# TODO(Patrick/Anton)
snake_case			 =						"""\
"""

snake_case			 =						"""\
    XTREME-S is a benchmark to evaluate universal cross-lingual speech representations in many languages.
    XTREME-S covers four task families: speech recognition, classification, speech-to-text translation and retrieval.
"""

snake_case			 =						"""
Compute XTREME-S evaluation metric associated to each XTREME-S dataset.
Args:
    predictions: list of predictions to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    bleu_kwargs: optional dict of keywords to be passed when computing 'bleu'.
        Keywords include Dict can be one of 'smooth_method', 'smooth_value', 'force', 'lowercase',
        'tokenize', 'use_effective_order'.
    wer_kwargs: optional dict of keywords to be passed when computing 'wer' and 'cer'.
        Keywords include 'concatenate_texts'.
Returns: depending on the XTREME-S task, one or several of:
    \"accuracy\": Accuracy - for 'fleurs-lang_id', 'minds14'
    \"f1\": F1 score - for 'minds14'
    \"wer\": Word error rate - for 'mls', 'fleurs-asr', 'voxpopuli', 'babel'
    \"cer\": Character error rate - for 'mls', 'fleurs-asr', 'voxpopuli', 'babel'
    \"bleu\": BLEU score according to the `sacrebleu` metric - for 'covost2'
Examples:

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'mls')  # 'mls', 'voxpopuli', 'fleurs-asr' or 'babel'
    >>> references = [\"it is sunny here\", \"paper and pen are essentials\"]
    >>> predictions = [\"it's sunny\", \"paper pen are essential\"]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'wer': 0.56, 'cer': 0.27}

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'covost2')
    >>> references = [\"bonjour paris\", \"il est necessaire de faire du sport de temps en temp\"]
    >>> predictions = [\"bonjour paris\", \"il est important de faire du sport souvent\"]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'bleu': 31.65}

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'fleurs-lang_id')
    >>> references = [0, 1, 0, 0, 1]
    >>> predictions = [0, 1, 1, 0, 0]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'accuracy': 0.6}

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'minds14')
    >>> references = [0, 1, 0, 0, 1]
    >>> predictions = [0, 1, 1, 0, 0]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'f1': 0.58, 'accuracy': 0.6}
"""

snake_case			 =						["""fleurs-asr""", """mls""", """voxpopuli""", """babel""", """covost2""", """fleurs-lang_id""", """minds14"""]
snake_case			 =						""""""

try:
   from jiwer import transforms as tr

   snake_case			 =						True
except ImportError:
   snake_case			 =						False

if _jiwer_available and version.parse(importlib_metadata.version("""jiwer""")) < version.parse("""2.3.0"""):


   class        SCREAMING_SNAKE_CASE	(	tr.AbstractTransform    ):
        '''simple docstring'''


        def __init__( self				:		Dict    ,       UpperCAmelCase_				:		str = " "					):
          SCREAMING_SNAKE_CASE				:					List[Any]		  =			sentence_delimiter


        def  _A				( self				:		Optional[int]    ,       UpperCAmelCase_				:		str					):
          return list(UpperCAmelCase_					)






        def  _A				( self				:		str    ,       UpperCAmelCase_				:		List[str]					):
          SCREAMING_SNAKE_CASE				:					Tuple		  =			[]
          for sent_idx, sentence in enumerate(UpperCAmelCase_					):
            chars.extend(self.process_string(UpperCAmelCase_					)					)
            if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(UpperCAmelCase_					) - 1:
              chars.append(self.sentence_delimiter					)
          return chars





   snake_case			 =						tr.Compose(
       [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
   )
elif _jiwer_available:
   snake_case			 =						tr.Compose(
       [
           tr.RemoveMultipleSpaces(),
           tr.Strip(),
           tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
           tr.ReduceToListOfListOfChars(),
       ]
   )
else:
   snake_case			 =						None


def      lowerCamelCase__	(   lowercase  ,   lowercase ):

  """simple docstring"""






  return float((preds == labels).mean() )


def      lowerCamelCase__	(   lowercase  ,   lowercase ):

  """simple docstring"""






  return {
      "f1": float(fa_score(y_true=lowercase  ,   y_pred=lowercase  ,   average="macro" ) ),
      "accuracy": simple_accuracy(lowercase  ,   lowercase ),
  }


def      lowerCamelCase__	(   lowercase  ,   lowercase  ,   lowercase="exp"  ,   lowercase=None  ,   lowercase=False  ,   lowercase=False  ,   lowercase=None  ,   lowercase=False  ,   ):

  """simple docstring"""






  SCREAMING_SNAKE_CASE				:					str		  =			[[label] for label in labels]
  SCREAMING_SNAKE_CASE				:					Tuple		  =			list(lowercase )
  try:
    import sacrebleu as scb
  except ImportError:
    raise ValueError(
        "sacrebleu has to be installed in order to apply the bleu metric for covost2."
        "You can install it via `pip install sacrebleu`." )

  if version.parse(scb.__version__ ) < version.parse("1.4.12" ):
    raise ImportWarning(
        "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
        "You can install it with `pip install \"sacrebleu>=1.4.12\"`." )

  SCREAMING_SNAKE_CASE				:					Tuple		  =			len(labels[0] )
  if any(len(lowercase ) != references_per_prediction for refs in labels ):
    raise ValueError("Sacrebleu requires the same number of references for each prediction" )
  SCREAMING_SNAKE_CASE				:					Dict		  =			[[refs[i] for refs in labels] for i in range(lowercase )]
  SCREAMING_SNAKE_CASE				:					List[str]		  =			scb.corpus_bleu(
      lowercase  ,   lowercase  ,   smooth_method=lowercase  ,   smooth_value=lowercase  ,   force=lowercase  ,   lowercase=lowercase  ,   use_effective_order=lowercase  ,   **({"tokenize": tokenize} if tokenize else {})  ,   )
  return {"bleu": output.score}


def      lowerCamelCase__	(   lowercase  ,   lowercase  ,   lowercase  ,   lowercase ):

  """simple docstring"""






  try:
    from jiwer import compute_measures
  except ImportError:
    raise ValueError(
        F'''jiwer has to be installed in order to apply the wer metric for {config_name}.'''
        "You can install it via `pip install jiwer`." )

  if concatenate_texts:
    SCREAMING_SNAKE_CASE				:					Tuple		  =			compute_measures(lowercase  ,   lowercase )["wer"]

    SCREAMING_SNAKE_CASE				:					int		  =			compute_measures(lowercase  ,   lowercase  ,   truth_transform=lowercase  ,   hypothesis_transform=lowercase )["wer"]
    return {"wer": wer, "cer": cer}
  else:

    def compute_score(lowercase  ,   lowercase  ,   lowercase="wer" ):
      SCREAMING_SNAKE_CASE				:					Tuple		  =			0
      SCREAMING_SNAKE_CASE				:					str		  =			0
      for prediction, reference in zip(lowercase  ,   lowercase ):
        if score_type == "wer":
          SCREAMING_SNAKE_CASE				:					int		  =			compute_measures(lowercase  ,   lowercase )
        elif score_type == "cer":
          SCREAMING_SNAKE_CASE				:					int		  =			compute_measures(
              lowercase  ,   lowercase  ,   truth_transform=lowercase  ,   hypothesis_transform=lowercase )
        incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
        total += measures["substitutions"] + measures["deletions"] + measures["hits"]
      return incorrect / total

    return {"wer": compute_score(lowercase  ,   lowercase  ,   "wer" ), "cer": compute_score(lowercase  ,   lowercase  ,   "cer" )}


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


     def  _A				( self				:		str					):
       if self.config_name not in _CONFIG_NAMES:
         raise KeyError(f'''You should supply a configuration name selected in {_CONFIG_NAMES}'''					)

       SCREAMING_SNAKE_CASE				:					Tuple		  =			"int64" if self.config_name in ["fleurs-lang_id", "minds14"] else "string"

       return datasets.MetricInfo(
           description=_DESCRIPTION    ,       citation=_CITATION    ,       inputs_description=_KWARGS_DESCRIPTION    ,       features=datasets.Features(
               {"predictions": datasets.Value(UpperCAmelCase_					), "references": datasets.Value(UpperCAmelCase_					)}					)    ,       codebase_urls=[]    ,       reference_urls=[]    ,       format="numpy"    ,       )






     def  _A				( self				:		Optional[Any]    ,       UpperCAmelCase_				:		int    ,       UpperCAmelCase_				:		Union[str, Any]    ,       UpperCAmelCase_				:		str=None    ,       UpperCAmelCase_				:		Dict=None					):
       SCREAMING_SNAKE_CASE				:					str		  =			bleu_kwargs if bleu_kwargs is not None else {}
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			wer_kwargs if wer_kwargs is not None else {}

       if self.config_name == "fleurs-lang_id":
         return {"accuracy": simple_accuracy(UpperCAmelCase_    ,       UpperCAmelCase_					)}
       elif self.config_name == "minds14":
         return fa_and_simple_accuracy(UpperCAmelCase_    ,       UpperCAmelCase_					)
       elif self.config_name == "covost2":
         SCREAMING_SNAKE_CASE				:					int		  =			bleu_kwargs.pop("smooth_method"    ,       "exp"					)
         SCREAMING_SNAKE_CASE				:					Dict		  =			bleu_kwargs.pop("smooth_value"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					List[Any]		  =			bleu_kwargs.pop("force"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			bleu_kwargs.pop("lowercase"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			bleu_kwargs.pop("tokenize"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					Dict		  =			bleu_kwargs.pop("use_effective_order"    ,       UpperCAmelCase_					)
         return bleu(
             preds=UpperCAmelCase_    ,       labels=UpperCAmelCase_    ,       smooth_method=UpperCAmelCase_    ,       smooth_value=UpperCAmelCase_    ,       force=UpperCAmelCase_    ,       lowercase=UpperCAmelCase_    ,       tokenize=UpperCAmelCase_    ,       use_effective_order=UpperCAmelCase_    ,       )
       elif self.config_name in ["fleurs-asr", "mls", "voxpopuli", "babel"]:
         SCREAMING_SNAKE_CASE				:					Tuple		  =			wer_kwargs.pop("concatenate_texts"    ,       UpperCAmelCase_					)
         return wer_and_cer(UpperCAmelCase_    ,       UpperCAmelCase_    ,       UpperCAmelCase_    ,       self.config_name					)
       else:
         raise KeyError(f'''You should supply a configuration name selected in {_CONFIG_NAMES}'''					)






