


"""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__      				=   pytest.mark.integration


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

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

lowerCAmelCase__      				=   {'''bertscore''', '''frugalscore''', '''perplexity'''}
lowerCAmelCase__      				=   importlib.util.find_spec('''transformers''') is not None
def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				):


  '''simple docstring'''







  @wraps(SCREAMING_SNAKE_CASE				)
  def wrapper(self    :    Any				,      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 					a__			(				SCREAMING_SNAKE_CASE    :    str				):


  '''simple docstring'''







  @wraps(SCREAMING_SNAKE_CASE				)
  def wrapper(self    :    List[Any]				,      SCREAMING_SNAKE_CASE    :    Optional[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 					a__			(				SCREAMING_SNAKE_CASE    :    int				):


  '''simple docstring'''







  @wraps(SCREAMING_SNAKE_CASE				)
  def wrapper(self    :    Tuple				,      SCREAMING_SNAKE_CASE    :    str				):
    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 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     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(
    lowercase   ,    lowercase   ,    lowercase				)
@local
class       SCREAMING_SNAKE_CASE__				(		parameterized.TestCase				):
       """simple docstring"""


       a  :				int   ={}
       a  :				List[str]   =None

       @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"						)
       @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"						)
       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     List[Any]								=							"[...]"
         lowerCAmelCase     :     str								=							importlib.import_module(
             datasets.load.metric_module_factory(os.path.join("metrics"		,     snake_case__						)						).module_path						)
         lowerCAmelCase     :     List[Any]								=							datasets.load.import_main_class(metric_module.__name__		,     dataset=snake_case__						)
         # check parameters
         lowerCAmelCase     :     Optional[Any]								=							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(snake_case__		,     metric_module.__name__						):
           with self.use_local_metrics():
             try:
               lowerCAmelCase     :     Optional[Any]								=							doctest.testmod(snake_case__		,     verbose=snake_case__		,     raise_on_error=snake_case__						)
             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        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     List[Any]								=							"[...]"
         lowerCAmelCase     :     Dict								=							importlib.import_module(
             datasets.load.metric_module_factory(os.path.join("metrics"		,     snake_case__						)						).module_path						)
         # run doctest
         with self.use_local_metrics():
           lowerCAmelCase     :     List[Any]								=							doctest.testmod(snake_case__		,     verbose=snake_case__		,     raise_on_error=snake_case__						)
         self.assertEqual(results.failed		,     0						)
         self.assertGreater(results.attempted		,     1						)

       @contextmanager
       def        lowercase__							(						self		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         if metric_name in self.INTENSIVE_CALLS_PATCHER:
           with self.INTENSIVE_CALLS_PATCHER[metric_name](snake_case__						):
             yield
         else:
           yield

       @contextmanager
       def        lowercase__							(						self						):






         """simple docstring"""





         def load_local_metric(snake_case__		,     *snake_case__		,     **snake_case__						):
           return load_metric(os.path.join("metrics"		,     snake_case__						)		,     *snake_case__		,     **snake_case__						)

         with patch("datasets.load_metric"						) as mock_load_metric:
           lowerCAmelCase     :     Dict								=							load_local_metric
           yield







       @classmethod
       def        lowercase__							(						cls		,     snake_case__						):






         """simple docstring"""





         def wrapper(snake_case__						):
           lowerCAmelCase     :     Dict								=							contextmanager(snake_case__						)
           lowerCAmelCase     :     List[str]								=							patcher
           return patcher

         return wrapper

@LocalMetricTest.register_intensive_calls_patcher("bleurt"				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Union[str, Any]				):


  '''simple docstring'''







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

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


  class       SCREAMING_SNAKE_CASE__				(		lowercase				):
         """simple docstring"""


         def        lowercase__							(						self		,     snake_case__						):






           """simple docstring"""





           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:
    lowerCAmelCase     :     Optional[Any]								=							MockedPredictor()
    yield
@LocalMetricTest.register_intensive_calls_patcher("bertscore"				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[int]				):


  '''simple docstring'''







  import torch

  def bert_cos_score_idf(SCREAMING_SNAKE_CASE    :    Any				,      SCREAMING_SNAKE_CASE    :    Any				,      *SCREAMING_SNAKE_CASE    :    Tuple				,      **SCREAMING_SNAKE_CASE    :    Optional[int]				):
    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:
    lowerCAmelCase     :     Tuple								=							bert_cos_score_idf
    yield
@LocalMetricTest.register_intensive_calls_patcher("comet"				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[Any]				):


  '''simple docstring'''







  def load_from_checkpoint(SCREAMING_SNAKE_CASE    :    Optional[Any]				):


    class       SCREAMING_SNAKE_CASE__				:
           """simple docstring"""


           def        lowercase__							(						self		,     snake_case__		,     *snake_case__		,     **snake_case__						):






             """simple docstring"""





             assert len(snake_case__						) == 2
             lowerCAmelCase     :     Union[str, Any]								=							[0.19, 0.92]
             return scores, sum(snake_case__						) / len(snake_case__						)

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





def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     int								=							load_metric(os.path.join("metrics"				,      "seqeval"				)				)
  lowerCAmelCase     :     List[Any]								=							"ERROR"
  lowerCAmelCase     :     Optional[int]								=							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"""







from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__      				=   logging.get_logger(__name__)

lowerCAmelCase__      				=   {
    '''facebook/dpr-ctx_encoder-single-nq-base''': (
        '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json'''
    ),
    '''facebook/dpr-question_encoder-single-nq-base''': (
        '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json'''
    ),
    '''facebook/dpr-reader-single-nq-base''': (
        '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json'''
    ),
    '''facebook/dpr-ctx_encoder-multiset-base''': (
        '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json'''
    ),
    '''facebook/dpr-question_encoder-multiset-base''': (
        '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json'''
    ),
    '''facebook/dpr-reader-multiset-base''': (
        '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json'''
    ),
}


class       SCREAMING_SNAKE_CASE__				(		lowercase				):
       """simple docstring"""


       a  :				int   ="dpr"

       def __init__(						self		,     snake_case__=30_522		,     snake_case__=768		,     snake_case__=12		,     snake_case__=12		,     snake_case__=3_072		,     snake_case__="gelu"		,     snake_case__=0.1		,     snake_case__=0.1		,     snake_case__=512		,     snake_case__=2		,     snake_case__=0.02		,     snake_case__=1e-12		,     snake_case__=0		,     snake_case__="absolute"		,     snake_case__ = 0		,     **snake_case__		,     ):






         """simple docstring"""





         super().__init__(pad_token_id=snake_case__		,     **snake_case__						)

         lowerCAmelCase     :     Union[str, Any]								=							vocab_size
         lowerCAmelCase     :     str								=							hidden_size
         lowerCAmelCase     :     Any								=							num_hidden_layers
         lowerCAmelCase     :     Optional[int]								=							num_attention_heads
         lowerCAmelCase     :     Union[str, Any]								=							hidden_act
         lowerCAmelCase     :     Dict								=							intermediate_size
         lowerCAmelCase     :     Union[str, Any]								=							hidden_dropout_prob
         lowerCAmelCase     :     Dict								=							attention_probs_dropout_prob
         lowerCAmelCase     :     Dict								=							max_position_embeddings
         lowerCAmelCase     :     Tuple								=							type_vocab_size
         lowerCAmelCase     :     Any								=							initializer_range
         lowerCAmelCase     :     Any								=							layer_norm_eps
         lowerCAmelCase     :     Dict								=							projection_dim
         lowerCAmelCase     :     Dict								=							position_embedding_type





