




"""simple docstring"""







import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
SCREAMING_SNAKE_CASE_	     =       pytest.mark.integration


SCREAMING_SNAKE_CASE_	     =       {'comet'}
SCREAMING_SNAKE_CASE_	     =       importlib.util.find_spec('fairseq') is not None

SCREAMING_SNAKE_CASE_	     =       {'code_eval'}
SCREAMING_SNAKE_CASE_	     =       os.name == 'nt'

SCREAMING_SNAKE_CASE_	     =       {'bertscore', 'frugalscore', 'perplexity'}
SCREAMING_SNAKE_CASE_	     =       importlib.util.find_spec('transformers') is not None





def      __snake_case (				_lowercase    ):


    """simple docstring"""







    @wraps(_lowercase    )
    def wrapper(self			,_lowercase    ):
        if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
            self.skipTest('''"test requires Fairseq"'''    )
        else:
            test_case(self			,_lowercase    )

    return wrapper





def      __snake_case (				_lowercase    ):


    """simple docstring"""







    @wraps(_lowercase    )
    def wrapper(self			,_lowercase    ):
        if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
            self.skipTest('''"test requires transformers"'''    )
        else:
            test_case(self			,_lowercase    )

    return wrapper





def      __snake_case (				_lowercase    ):


    """simple docstring"""







    @wraps(_lowercase    )
    def wrapper(self			,_lowercase    ):
        if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
            self.skipTest('''"test not supported on Windows"'''    )
        else:
            test_case(self			,_lowercase    )

    return wrapper





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	[metric_dir.split(os.sep    )[-2] for metric_dir in glob.glob('''./metrics/*/'''    )]
    return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished

@parameterized.named_parameters(get_local_metric_names()			)
@for_all_test_methods(
    lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_			)
@local
class 				snake_case_			(					parameterized.TestCase			):







   """simple docstring"""




   A_				      =       {}
   A_				      =       None







   @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''')
   @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''')
   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   int:
       UpperCamelCase              =	'''[...]'''
       UpperCamelCase              =	importlib.import_module(
           datasets.load.metric_module_factory(os.path.join('''metrics'''       ,					lowerCamelCase_)).module_path)
       UpperCamelCase              =	datasets.load.import_main_class(metric_module.__name__       ,					dataset=lowerCamelCase_)
       # check parameters
       UpperCamelCase              =	inspect.signature(metric._compute).parameters
       self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()))  # no **kwargs
       # run doctest
       with self.patch_intensive_calls(lowerCamelCase_       ,					metric_module.__name__):
           with self.use_local_metrics():
               try:
                   UpperCamelCase              =	doctest.testmod(lowerCamelCase_       ,					verbose=lowerCamelCase_       ,					raise_on_error=lowerCamelCase_)
               except doctest.UnexpectedException as e:
                   raise e.exc_info[1]  # raise the exception that doctest caught
       self.assertEqual(results.failed       ,					0)
       self.assertGreater(results.attempted       ,					1)







   @slow
   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Optional[int]:
       UpperCamelCase              =	'''[...]'''
       UpperCamelCase              =	importlib.import_module(
           datasets.load.metric_module_factory(os.path.join('''metrics'''       ,					lowerCamelCase_)).module_path)
       # run doctest
       with self.use_local_metrics():
           UpperCamelCase              =	doctest.testmod(lowerCamelCase_       ,					verbose=lowerCamelCase_       ,					raise_on_error=lowerCamelCase_)
       self.assertEqual(results.failed       ,					0)
       self.assertGreater(results.attempted       ,					1)







   @contextmanager
   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_       ,					lowerCamelCase_)				->   Optional[int]:
       if metric_name in self.INTENSIVE_CALLS_PATCHER:
           with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCamelCase_):
               yield
       else:
           yield







   @contextmanager
   def   UpperCAmelCase__			(		self)				->   Dict:
       def load_local_metric(lowerCamelCase_       ,					*lowerCamelCase_       ,					**lowerCamelCase_):
           return load_metric(os.path.join('''metrics'''       ,					lowerCamelCase_)       ,					*lowerCamelCase_       ,					**lowerCamelCase_)

       with patch('''datasets.load_metric''') as mock_load_metric:
           UpperCamelCase              =	load_local_metric
           yield







   @classmethod
   def   UpperCAmelCase__			(		cls       ,					lowerCamelCase_)				->   Tuple:
       def wrapper(lowerCamelCase_):
           UpperCamelCase              =	contextmanager(lowerCamelCase_)
           UpperCamelCase              =	patcher
           return patcher

       return wrapper





@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''    )
def      __snake_case (				_lowercase    ):


    """simple docstring"""







    import tensorflow.compat.va as tf
    from bleurt.score import Predictor

    tf.flags.DEFINE_string('''sv'''			,''''''			,''''''    )  # handle pytest cli flags

    class 				snake_case_			(					lowerCamelCase_			):







       """simple docstring"""




       def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Optional[int]:
           assert len(input_dict['''input_ids''']) == 2
           return np.array([1.03, 1.04])

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
    with patch('''bleurt.score._create_predictor'''    ) as mock_create_predictor:
        UpperCamelCase              =	MockedPredictor()
        yield





@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''    )
def      __snake_case (				_lowercase    ):


    """simple docstring"""







    import torch

    def bert_cos_score_idf(_lowercase			,_lowercase			,*_lowercase			,**_lowercase    ):
        return torch.tensor([[1.0, 1.0, 1.0]] * len(_lowercase    )    )

    # mock get_model which is supposed to do download a bert model
    # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
    with patch('''bert_score.scorer.get_model'''    ), patch(
        '''bert_score.scorer.bert_cos_score_idf'''    ) as mock_bert_cos_score_idf:
        UpperCamelCase              =	bert_cos_score_idf
        yield





@LocalMetricTest.register_intensive_calls_patcher('''comet'''    )
def      __snake_case (				_lowercase    ):


    """simple docstring"""







    def load_from_checkpoint(_lowercase    ):

        class 				snake_case_			:







           """simple docstring"""




           def   UpperCAmelCase__			(		self       ,					lowerCamelCase_       ,					*lowerCamelCase_       ,					**lowerCamelCase_)				->   List[str]:
               assert len(lowerCamelCase_) == 2
               UpperCamelCase              =	[0.19, 0.92]
               return scores, sum(lowerCamelCase_) / len(lowerCamelCase_)
        return Model()

    # mock load_from_checkpoint which is supposed to do download a bert model
    # mock load_from_checkpoint which is supposed to do download a bert model
    with patch('''comet.download_model'''    ) as mock_download_model:
        UpperCamelCase              =	None
        with patch('''comet.load_from_checkpoint'''    ) as mock_load_from_checkpoint:
            UpperCamelCase              =	load_from_checkpoint
            yield





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	load_metric(os.path.join('''metrics'''			,'''seqeval'''    )    )
    UpperCamelCase              =	'''ERROR'''
    UpperCamelCase              =	f'Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'
    with pytest.raises(_lowercase			,match=re.escape(_lowercase    )    ):
        metric.compute(predictions=[]			,references=[]			,scheme=_lowercase    )

"""simple docstring"""






from typing import Dict, List, Optional

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


__SCREAMING_SNAKE_CASE							=     logging.get_logger(__name__)


__SCREAMING_SNAKE_CASE							=     {
    'nielsr/canine-s': 2_048,
}

# Unicode defines 1,114,112 total “codepoints”
__SCREAMING_SNAKE_CASE							=     1_114_112

# Below: Constants defining canonical codepoints for special, pseudo-characters.
# Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py
__SCREAMING_SNAKE_CASE							=     0

__SCREAMING_SNAKE_CASE							=     0XE_0_0_0
__SCREAMING_SNAKE_CASE							=     0XE_0_0_1
__SCREAMING_SNAKE_CASE							=     0XE_0_0_2
__SCREAMING_SNAKE_CASE							=     0XE_0_0_3
__SCREAMING_SNAKE_CASE							=     0XE_0_0_4

# Maps special codepoints to human-readable names.
__SCREAMING_SNAKE_CASE							=     {
    # Special symbols are represented using codepoints values that are valid,
    # but designated as "Private Use", meaning that they will never be assigned
    # characters by the Unicode Consortium, and are thus safe for use here.
    #
    # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly
    # excluded and should fail with a hard error.
    CLS: "[CLS]",
    SEP: "[SEP]",
    BOS: "[BOS]",
    MASK: "[MASK]",
    PAD: "[PAD]",
    RESERVED: "[RESERVED]",
}

# Maps special codepoint human-readable names to their codepoint values.
__SCREAMING_SNAKE_CASE							=     {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()}





class 				a__					(						A__       ):
     UpperCAmelCase__         =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES



     def __init__(							self :List[str]      ,  _lowerCamelCase :Optional[Any]=chr(_lowerCamelCase   )      ,  _lowerCamelCase :List[str]=chr(_lowerCamelCase   )      ,  _lowerCamelCase :Any=chr(_lowerCamelCase   )      ,  _lowerCamelCase :Optional[int]=chr(_lowerCamelCase   )      ,  _lowerCamelCase :Tuple=chr(_lowerCamelCase   )      ,  _lowerCamelCase :Union[str, Any]=chr(_lowerCamelCase   )      ,  _lowerCamelCase :str=False      ,  _lowerCamelCase :Union[str, Any]=2_048      ,  **_lowerCamelCase :Tuple      ,  ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=AddedToken(_lowerCamelCase      ,  lstrip=_lowerCamelCase      ,  rstrip=_lowerCamelCase   ) if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ) else bos_token
      UpperCamelCase_     :					List[str]   	=AddedToken(_lowerCamelCase      ,  lstrip=_lowerCamelCase      ,  rstrip=_lowerCamelCase   ) if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ) else eos_token
      UpperCamelCase_     :					List[str]   	=AddedToken(_lowerCamelCase      ,  lstrip=_lowerCamelCase      ,  rstrip=_lowerCamelCase   ) if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ) else sep_token
      UpperCamelCase_     :					Tuple   	=AddedToken(_lowerCamelCase      ,  lstrip=_lowerCamelCase      ,  rstrip=_lowerCamelCase   ) if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ) else cls_token
      UpperCamelCase_     :					Optional[int]   	=AddedToken(_lowerCamelCase      ,  lstrip=_lowerCamelCase      ,  rstrip=_lowerCamelCase   ) if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ) else pad_token

      # Mask token behave like a normal word, i.e. include the space before it
      UpperCamelCase_     :					Dict   	=AddedToken(_lowerCamelCase      ,  lstrip=_lowerCamelCase      ,  rstrip=_lowerCamelCase   ) if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ) else mask_token

      super().__init__(
          bos_token=_lowerCamelCase      ,  eos_token=_lowerCamelCase      ,  sep_token=_lowerCamelCase      ,  cls_token=_lowerCamelCase      ,  pad_token=_lowerCamelCase      ,  mask_token=_lowerCamelCase      ,  add_prefix_space=_lowerCamelCase      ,  model_max_length=_lowerCamelCase      ,  **_lowerCamelCase      ,  )

      # Creates a mapping for looking up the IDs of special symbols.
      UpperCamelCase_     :					Dict[str, int]   	={}
      for codepoint, name in SPECIAL_CODEPOINTS.items():
       UpperCamelCase_     :					List[str]   	=codepoint

      # Creates a mapping for looking up the string forms of special symbol IDs.
      UpperCamelCase_     :					Dict[int, str]   	={
          codepoint: name for name, codepoint in self._special_codepoints.items()
      }

      UpperCamelCase_     :					str   	=UNICODE_VOCAB_SIZE
      UpperCamelCase_     :					Any   	=len(self._special_codepoints   )



     @property
     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      return self._unicode_vocab_size



     def  lowerCamelCase_						(							self :str      ,  _lowerCamelCase :str   ):







      '''simple docstring'''



      return list(_lowerCamelCase   )



     def  lowerCamelCase_						(							self :str      ,  _lowerCamelCase :str   ):







      '''simple docstring'''



      try:
       return ord(_lowerCamelCase   )
      except TypeError:
       raise ValueError(f'''invalid token: \'{token}\''''   )



     def  lowerCamelCase_						(							self :str      ,  _lowerCamelCase :int   ):







      '''simple docstring'''



      try:
       if index in SPECIAL_CODEPOINTS:
        return SPECIAL_CODEPOINTS[index]
       return chr(_lowerCamelCase   )
      except TypeError:
       raise ValueError(f'''invalid id: {index}'''   )



     def  lowerCamelCase_						(							self :List[Any]      ,  _lowerCamelCase :str   ):







      '''simple docstring'''



      return "".join(_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Tuple      ,  _lowerCamelCase :List[int]      ,  _lowerCamelCase :Optional[List[int]] = None   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=[self.sep_token_id]
      UpperCamelCase_     :					Tuple   	=[self.cls_token_id]

      UpperCamelCase_     :					List[str]   	=cls + token_ids_a + sep
      if token_ids_a is not None:
       result += token_ids_a + sep
      return result



     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :List[int]      ,  _lowerCamelCase :Optional[List[int]] = None      ,  _lowerCamelCase :bool = False   ):







      '''simple docstring'''



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

      UpperCamelCase_     :					int   	=[1] + ([0] * len(_lowerCamelCase   )) + [1]
      if token_ids_a is not None:
       result += ([0] * len(_lowerCamelCase   )) + [1]
      return result



     def  lowerCamelCase_						(							self :List[str]      ,  _lowerCamelCase :List[int]      ,  _lowerCamelCase :Optional[List[int]] = None   ):







      '''simple docstring'''



      UpperCamelCase_     :					Dict   	=[self.sep_token_id]
      UpperCamelCase_     :					Optional[int]   	=[self.cls_token_id]

      UpperCamelCase_     :					Dict   	=len(cls + token_ids_a + sep   ) * [0]
      if token_ids_a is not None:
       result += len(token_ids_a + sep   ) * [1]
      return result




     def  lowerCamelCase_						(							self :Tuple      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Optional[str] = None   ):







      '''simple docstring'''



      return ()
