



"""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
_lowerCAmelCase    : List[Any]							=							pytest.mark.integration


_lowerCAmelCase    : str							=							{"comet"}
_lowerCAmelCase    : Union[str, Any]							=							importlib.util.find_spec("fairseq") is not None

_lowerCAmelCase    : str							=							{"code_eval"}
_lowerCAmelCase    : Dict							=							os.name == "nt"

_lowerCAmelCase    : Any							=							{"bertscore", "frugalscore", "perplexity"}
_lowerCAmelCase    : List[str]							=							importlib.util.find_spec("transformers") is not None

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						str    )  ->       Tuple:





     '''simple docstring'''

     @wraps(SCREAMING_SNAKE_CASE__    )
     def wrapper(self     :						Dict						,  SCREAMING_SNAKE_CASE__     :						Optional[Any]    ):
          if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
               self.skipTest("\"test requires Fairseq\""    )
          else:
               test_case(self						,  SCREAMING_SNAKE_CASE__    )

     return wrapper

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						int    )  ->       Tuple:





     '''simple docstring'''

     @wraps(SCREAMING_SNAKE_CASE__    )
     def wrapper(self     :						Optional[Any]						,  SCREAMING_SNAKE_CASE__     :						List[Any]    ):
          if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
               self.skipTest("\"test requires transformers\""    )
          else:
               test_case(self						,  SCREAMING_SNAKE_CASE__    )

     return wrapper

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						List[Any]    )  ->       Optional[int]:





     '''simple docstring'''

     @wraps(SCREAMING_SNAKE_CASE__    )
     def wrapper(self     :						Optional[int]						,  SCREAMING_SNAKE_CASE__     :						Dict    ):
          if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
               self.skipTest("\"test not supported on Windows\""    )
          else:
               test_case(self						,  SCREAMING_SNAKE_CASE__    )

     return wrapper

def 						__snake_case						(				)  ->       Any:





     '''simple docstring'''

     _UpperCAmelCase      :     Optional[Any]        =   [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(
    _UpperCamelCase	,      _UpperCamelCase	,      _UpperCamelCase						)
@local
class      UpperCAmelCase_  (    parameterized.TestCase						):
      __SCREAMING_SNAKE_CASE						:       str								=			{}
      __SCREAMING_SNAKE_CASE						:       List[Any]								=			None



      @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"						)
      @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"						)
      def 						snake_case_ (					self					:     str					,     A					:     Union[str, Any]						):
           _UpperCAmelCase      :     Optional[int]        =   "[...]"
           _UpperCAmelCase      :     List[str]        =   importlib.import_module(
               datasets.load.metric_module_factory(os.path.join("metrics"					,     A						)						).module_path						)
           _UpperCAmelCase      :     int        =   datasets.load.import_main_class(metric_module.__name__					,     dataset=A						)
           # check parameters
           _UpperCAmelCase      :     Optional[int]        =   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(A					,     metric_module.__name__						):
                with self.use_local_metrics():
                     try:
                          _UpperCAmelCase      :     str        =   doctest.testmod(A					,     verbose=A					,     raise_on_error=A						)
                     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 						snake_case_ (					self					:     Tuple					,     A					:     List[Any]						):
           _UpperCAmelCase      :     int        =   "[...]"
           _UpperCAmelCase      :     List[Any]        =   importlib.import_module(
               datasets.load.metric_module_factory(os.path.join("metrics"					,     A						)						).module_path						)
           # run doctest
           with self.use_local_metrics():
                _UpperCAmelCase      :     int        =   doctest.testmod(A					,     verbose=A					,     raise_on_error=A						)
           self.assertEqual(results.failed					,     0						)
           self.assertGreater(results.attempted					,     1						)



      @contextmanager
      def 						snake_case_ (					self					:     Optional[int]					,     A					:     List[Any]					,     A					:     int						):
           if metric_name in self.INTENSIVE_CALLS_PATCHER:
                with self.INTENSIVE_CALLS_PATCHER[metric_name](A						):
                     yield
           else:
                yield



      @contextmanager
      def 						snake_case_ (					self					:     Tuple						):
           def load_local_metric(A					:     List[Any]					,     *A					:     str					,     **A					:     Any						):
                return load_metric(os.path.join("metrics"					,     A						)					,     *A					,     **A						)

           with patch("datasets.load_metric"						) as mock_load_metric:
                _UpperCAmelCase      :     Union[str, Any]        =   load_local_metric
                yield



      @classmethod
      def 						snake_case_ (					cls					:     List[Any]					,     A					:     Dict						):
           def wrapper(A					:     int						):
                _UpperCAmelCase      :     Tuple        =   contextmanager(A						)
                _UpperCAmelCase      :     int        =   patcher
                return patcher

           return wrapper







@LocalMetricTest.register_intensive_calls_patcher("bleurt"    )
def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						str    )  ->       List[str]:





     '''simple docstring'''

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

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






     class      UpperCAmelCase_  (    _UpperCamelCase						):



           def 						snake_case_ (					self					:     Tuple					,     A					:     Tuple						):
                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      :     Tuple        =   MockedPredictor()
          yield

@LocalMetricTest.register_intensive_calls_patcher("bertscore"    )
def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						int    )  ->       int:





     '''simple docstring'''

     import torch

     def bert_cos_score_idf(SCREAMING_SNAKE_CASE__     :						int						,  SCREAMING_SNAKE_CASE__     :						Optional[Any]						,  *SCREAMING_SNAKE_CASE__     :						Union[str, Any]						,  **SCREAMING_SNAKE_CASE__     :						Union[str, Any]    ):
          return torch.tensor([[1.0, 1.0, 1.0]] * len(SCREAMING_SNAKE_CASE__    )    )

     # 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      :     List[Any]        =   bert_cos_score_idf
          yield

@LocalMetricTest.register_intensive_calls_patcher("comet"    )
def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Any    )  ->       Tuple:





     '''simple docstring'''

     def load_from_checkpoint(SCREAMING_SNAKE_CASE__     :						Union[str, Any]    ):






          class      UpperCAmelCase_  :



                def 						snake_case_ (					self					:     Optional[Any]					,     A					:     Dict					,     *A					:     int					,     **A					:     Optional[int]						):
                     assert len(A						) == 2
                     _UpperCAmelCase      :     str        =   [0.19, 0.92]
                     return scores, sum(A						) / len(A						)







          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      :     Optional[Any]        =   None
          with patch("comet.load_from_checkpoint"    ) as mock_load_from_checkpoint:
               _UpperCAmelCase      :     List[Any]        =   load_from_checkpoint
               yield

def 						__snake_case						(				)  ->       Tuple:





     '''simple docstring'''

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





"""simple docstring"""




import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


_lowerCAmelCase    : Any							=							logging.getLogger(__name__)






@dataclass
class      UpperCAmelCase_  :
      __SCREAMING_SNAKE_CASE						:       str
      __SCREAMING_SNAKE_CASE						:       List[str]
      __SCREAMING_SNAKE_CASE						:       Optional[List[str]]







@dataclass
class      UpperCAmelCase_  :
      __SCREAMING_SNAKE_CASE						:       List[int]
      __SCREAMING_SNAKE_CASE						:       List[int]
      __SCREAMING_SNAKE_CASE						:       Optional[List[int]]								=			None
      __SCREAMING_SNAKE_CASE						:       Optional[List[int]]								=			None







class      UpperCAmelCase_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       Union[str, Any]								=			'train'
      __SCREAMING_SNAKE_CASE						:       Tuple								=			'dev'
      __SCREAMING_SNAKE_CASE						:       Optional[int]								=			'test'







class      UpperCAmelCase_  :



      @staticmethod
      def 						snake_case_ (					A					:     Union[str, Any]					,     A					:     Union[Split, str]						):
           raise NotImplementedError



      @staticmethod
      def 						snake_case_ (					A					:     str						):
           raise NotImplementedError



      @staticmethod
      def 						snake_case_ (					A					:     List[InputExample]					,     A					:     List[str]					,     A					:     int					,     A					:     PreTrainedTokenizer					,     A					:     Optional[int]=False					,     A					:     List[str]="[CLS]"					,     A					:     List[Any]=1					,     A					:     str="[SEP]"					,     A					:     int=False					,     A					:     int=False					,     A					:     Any=0					,     A					:     List[str]=0					,     A					:     Dict=-1_0_0					,     A					:     str=0					,     A					:     Optional[Any]=True					,     ):
           _UpperCAmelCase      :     Dict        =   {label: i for i, label in enumerate(A						)}

           _UpperCAmelCase      :     str        =   []
           for ex_index, example in enumerate(A						):
                if ex_index % 1_0_0_0_0 == 0:
                     logger.info("Writing example %d of %d"					,     A					,     len(A						)						)

                _UpperCAmelCase      :     int        =   []
                _UpperCAmelCase      :     List[str]        =   []
                for word, label in zip(example.words					,     example.labels						):
                     _UpperCAmelCase      :     str        =   tokenizer.tokenize(A						)

                     # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
                     if len(A						) > 0:
                          tokens.extend(A						)
                          # Use the real label id for the first token of the word, and padding ids for the remaining tokens
                          label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(A						) - 1)						)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
                _UpperCAmelCase      :     List[str]        =   tokenizer.num_special_tokens_to_add()
                if len(A						) > max_seq_length - special_tokens_count:
                     _UpperCAmelCase      :     List[Any]        =   tokens[: (max_seq_length - special_tokens_count)]
                     _UpperCAmelCase      :     List[Any]        =   label_ids[: (max_seq_length - special_tokens_count)]

                # The convention in BERT is:
                # (a) For sequence pairs:
                #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
                #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
                # (b) For single sequences:
                #  tokens:   [CLS] the dog is hairy . [SEP]
                #  type_ids:   0   0   0   0  0     0   0
                #
                # Where "type_ids" are used to indicate whether this is the first
                # sequence or the second sequence. The embedding vectors for `type=0` and
                # `type=1` were learned during pre-training and are added to the wordpiece
                # embedding vector (and position vector). This is not *strictly* necessary
                # since the [SEP] token unambiguously separates the sequences, but it makes
                # it easier for the model to learn the concept of sequences.
                #
                # For classification tasks, the first vector (corresponding to [CLS]) is
                # used as the "sentence vector". Note that this only makes sense because
                # the entire model is fine-tuned.
                tokens += [sep_token]
                label_ids += [pad_token_label_id]
                if sep_token_extra:
                     # roberta uses an extra separator b/w pairs of sentences
                     tokens += [sep_token]
                     label_ids += [pad_token_label_id]
                _UpperCAmelCase      :     Dict        =   [sequence_a_segment_id] * len(A						)

                if cls_token_at_end:
                     tokens += [cls_token]
                     label_ids += [pad_token_label_id]
                     segment_ids += [cls_token_segment_id]
                else:
                     _UpperCAmelCase      :     str        =   [cls_token] + tokens
                     _UpperCAmelCase      :     Dict        =   [pad_token_label_id] + label_ids
                     _UpperCAmelCase      :     Any        =   [cls_token_segment_id] + segment_ids

                _UpperCAmelCase      :     int        =   tokenizer.convert_tokens_to_ids(A						)

                # The mask has 1 for real tokens and 0 for padding tokens. Only real
                # tokens are attended to.
                _UpperCAmelCase      :     List[Any]        =   [1 if mask_padding_with_zero else 0] * len(A						)

                # Zero-pad up to the sequence length.
                _UpperCAmelCase      :     List[str]        =   max_seq_length - len(A						)
                if pad_on_left:
                     _UpperCAmelCase      :     str        =   ([pad_token] * padding_length) + input_ids
                     _UpperCAmelCase      :     str        =   ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
                     _UpperCAmelCase      :     Any        =   ([pad_token_segment_id] * padding_length) + segment_ids
                     _UpperCAmelCase      :     Dict        =   ([pad_token_label_id] * padding_length) + label_ids
                else:
                     input_ids += [pad_token] * padding_length
                     input_mask += [0 if mask_padding_with_zero else 1] * padding_length
                     segment_ids += [pad_token_segment_id] * padding_length
                     label_ids += [pad_token_label_id] * padding_length

                assert len(A						) == max_seq_length
                assert len(A						) == max_seq_length
                assert len(A						) == max_seq_length
                assert len(A						) == max_seq_length

                if ex_index < 5:
                     logger.info("*** Example ***"						)
                     logger.info("guid: %s"					,     example.guid						)
                     logger.info("tokens: %s"					,     " ".join([str(A						) for x in tokens]						)						)
                     logger.info("input_ids: %s"					,     " ".join([str(A						) for x in input_ids]						)						)
                     logger.info("input_mask: %s"					,     " ".join([str(A						) for x in input_mask]						)						)
                     logger.info("segment_ids: %s"					,     " ".join([str(A						) for x in segment_ids]						)						)
                     logger.info("label_ids: %s"					,     " ".join([str(A						) for x in label_ids]						)						)

                if "token_type_ids" not in tokenizer.model_input_names:
                     _UpperCAmelCase      :     Dict        =   None

                features.append(
                    InputFeatures(
                        input_ids=A					,     attention_mask=A					,     token_type_ids=A					,     label_ids=A						)						)
           return features


if is_torch_available():
 import torch
 from torch import nn
 from torch.utils.data import Dataset






 class      UpperCAmelCase_  (    _UpperCamelCase						):
       __SCREAMING_SNAKE_CASE						:       List[InputFeatures]
       __SCREAMING_SNAKE_CASE						:       int								=			nn.CrossEntropyLoss().ignore_index



       def __init__(					self					:     Dict					,     A					:     TokenClassificationTask					,     A					:     str					,     A					:     PreTrainedTokenizer					,     A					:     List[str]					,     A					:     str					,     A					:     Optional[int] = None					,     A					:     List[str]=False					,     A					:     Split = Split.train					,     ):
            # Load data features from cache or dataset file
            _UpperCAmelCase      :     int        =   os.path.join(
                A					,     "cached_{}_{}_{}".format(mode.value					,     tokenizer.__class__.__name__					,     str(A						)						)					,     )

            # Make sure only the first process in distributed training processes the dataset,
            # and the others will use the cache.
            _UpperCAmelCase      :     List[str]        =   cached_features_file + ".lock"
            with FileLock(A						):
                 if os.path.exists(A						) and not overwrite_cache:
                      logger.info(f'Loading features from cached file {cached_features_file}'						)
                      _UpperCAmelCase      :     Tuple        =   torch.load(A						)
                 else:
                      logger.info(f'Creating features from dataset file at {data_dir}'						)
                      _UpperCAmelCase      :     List[str]        =   token_classification_task.read_examples_from_file(A					,     A						)
                      # TODO clean up all this to leverage built-in features of tokenizers
                      _UpperCAmelCase      :     List[Any]        =   token_classification_task.convert_examples_to_features(
                          A					,     A					,     A					,     A					,     cls_token_at_end=bool(model_type in ["xlnet"]						)					,     cls_token=tokenizer.cls_token					,     cls_token_segment_id=2 if model_type in ["xlnet"] else 0					,     sep_token=tokenizer.sep_token					,     sep_token_extra=A					,     pad_on_left=bool(tokenizer.padding_side == "left"						)					,     pad_token=tokenizer.pad_token_id					,     pad_token_segment_id=tokenizer.pad_token_type_id					,     pad_token_label_id=self.pad_token_label_id					,     )
                      logger.info(f'Saving features into cached file {cached_features_file}'						)
                      torch.save(self.features					,     A						)



       def __len__(					self					:     Dict						):
            return len(self.features						)



       def __getitem__(					self					:     List[str]					,     A					:     Optional[Any]						):
            return self.features[i]


if is_tf_available():
 import tensorflow as tf






 class      UpperCAmelCase_  :
       __SCREAMING_SNAKE_CASE						:       List[InputFeatures]
       __SCREAMING_SNAKE_CASE						:       int								=			-1_0_0



       def __init__(					self					:     Tuple					,     A					:     TokenClassificationTask					,     A					:     str					,     A					:     PreTrainedTokenizer					,     A					:     List[str]					,     A					:     str					,     A					:     Optional[int] = None					,     A					:     Optional[Any]=False					,     A					:     Split = Split.train					,     ):
            _UpperCAmelCase      :     Union[str, Any]        =   token_classification_task.read_examples_from_file(A					,     A						)
            # TODO clean up all this to leverage built-in features of tokenizers
            _UpperCAmelCase      :     List[str]        =   token_classification_task.convert_examples_to_features(
                A					,     A					,     A					,     A					,     cls_token_at_end=bool(model_type in ["xlnet"]						)					,     cls_token=tokenizer.cls_token					,     cls_token_segment_id=2 if model_type in ["xlnet"] else 0					,     sep_token=tokenizer.sep_token					,     sep_token_extra=A					,     pad_on_left=bool(tokenizer.padding_side == "left"						)					,     pad_token=tokenizer.pad_token_id					,     pad_token_segment_id=tokenizer.pad_token_type_id					,     pad_token_label_id=self.pad_token_label_id					,     )

            def gen():
                 for ex in self.features:
                      if ex.token_type_ids is None:
                           yield (
                               {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
                               ex.label_ids,
                           )
                      else:
                           yield (
                               {
                                   "input_ids": ex.input_ids,
                                   "attention_mask": ex.attention_mask,
                                   "token_type_ids": ex.token_type_ids,
                               },
                               ex.label_ids,
                           )

            if "token_type_ids" not in tokenizer.model_input_names:
                 _UpperCAmelCase      :     List[str]        =   tf.data.Dataset.from_generator(
                     A					,     ({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa)					,     (
                         {"input_ids": tf.TensorShape([None]						), "attention_mask": tf.TensorShape([None]						)},
                         tf.TensorShape([None]						),
                     )					,     )
            else:
                 _UpperCAmelCase      :     List[Any]        =   tf.data.Dataset.from_generator(
                     A					,     ({"input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa}, tf.intaa)					,     (
                         {
                             "input_ids": tf.TensorShape([None]						),
                             "attention_mask": tf.TensorShape([None]						),
                             "token_type_ids": tf.TensorShape([None]						),
                         },
                         tf.TensorShape([None]						),
                     )					,     )



       def 						snake_case_ (					self					:     str						):
            _UpperCAmelCase      :     Dict        =   self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features						)						)						)

            return self.dataset



       def __len__(					self					:     List[Any]						):
            return len(self.features						)



       def __getitem__(					self					:     int					,     A					:     int						):
            return self.features[i]
