






'''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
__A    	=   pytest.mark.integration


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

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

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




def        _SCREAMING_SNAKE_CASE  (				A  :       Dict  )    -> int:







   """simple docstring"""
   @wraps(A  )
   def wrapper(self  :       Union[str, Any]  ,		A  :       int  ):
      if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
         self.skipTest('"test requires Fairseq"'  )
      else:
         test_case(self  ,		A  )

   return wrapper




def        _SCREAMING_SNAKE_CASE  (				A  :       Tuple  )    -> Optional[Any]:







   """simple docstring"""
   @wraps(A  )
   def wrapper(self  :       Union[str, Any]  ,		A  :       int  ):
      if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
         self.skipTest('"test requires transformers"'  )
      else:
         test_case(self  ,		A  )

   return wrapper




def        _SCREAMING_SNAKE_CASE  (				A  :       List[str]  )    -> str:







   """simple docstring"""
   @wraps(A  )
   def wrapper(self  :       List[str]  ,		A  :       Optional[Any]  ):
      if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
         self.skipTest('"test not supported on Windows"'  )
      else:
         test_case(self  ,		A  )

   return wrapper




def        _SCREAMING_SNAKE_CASE  (				)    -> str:







   """simple docstring"""
   __snake_case				:      str     							= [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 a_    (    parameterized.TestCase							):
   _snake_case        =							{}
   _snake_case        =							None







   @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning')
   @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning')
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      int:
      """simple docstring"""






      __snake_case				:      int     							= '[...]'
      __snake_case				:      Union[str, Any]     							= importlib.import_module(
          datasets.load.metric_module_factory(os.path.join('metrics'					,   __a)).module_path)
      __snake_case				:      List[Any]     							= datasets.load.import_main_class(metric_module.__name__					,   dataset=__a)
      # check parameters
      __snake_case				:      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:
               __snake_case				:      Optional[Any]     							= 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     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      List[str]:
      """simple docstring"""






      __snake_case				:      Dict     							= '[...]'
      __snake_case				:      str     							= importlib.import_module(
          datasets.load.metric_module_factory(os.path.join('metrics'					,   __a)).module_path)
      # run doctest
      with self.use_local_metrics():
         __snake_case				:      Tuple     							= doctest.testmod(__a					,   verbose=__a					,   raise_on_error=__a)
      self.assertEqual(results.failed					,   0)
      self.assertGreater(results.attempted					,   1)







   @contextmanager
   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a)			->      List[Any]:
      """simple docstring"""






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







   @contextmanager
   def     SCREAMING_SNAKE_CASE__					(self)			->      Dict:
      """simple docstring"""






      def load_local_metric(__a					,   *__a					,   **__a):
         return load_metric(os.path.join('metrics'					,   __a)					,   *__a					,   **__a)

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







   @classmethod
   def     SCREAMING_SNAKE_CASE__					(cls					,   __a)			->      Any:
      """simple docstring"""






      def wrapper(__a):
         __snake_case				:      Optional[Any]     							= contextmanager(__a)
         __snake_case				:      Tuple     							= patcher
         return patcher

      return wrapper




@LocalMetricTest.register_intensive_calls_patcher('bleurt'  )
def        _SCREAMING_SNAKE_CASE  (				A  :       Tuple  )    -> str:







   """simple docstring"""
   import tensorflow.compat.va as tf
   from bleurt.score import Predictor

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




   class a_    (    UpperCamelCase_							):







      def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      List[Any]:
         """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:
      __snake_case				:      Tuple     							= MockedPredictor()
      yield




@LocalMetricTest.register_intensive_calls_patcher('bertscore'  )
def        _SCREAMING_SNAKE_CASE  (				A  :       List[Any]  )    -> List[Any]:







   """simple docstring"""
   import torch

   def bert_cos_score_idf(A  :       Any  ,		A  :       Any  ,		*A  :       Optional[Any]  ,		**A  :       Tuple  ):
      return torch.tensor([[1.0, 1.0, 1.0]] * len(A  )  )

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




@LocalMetricTest.register_intensive_calls_patcher('comet'  )
def        _SCREAMING_SNAKE_CASE  (				A  :       Tuple  )    -> List[Any]:







   """simple docstring"""
   def load_from_checkpoint(A  :       str  ):




      class a_    :







         def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   *__a					,   **__a)			->      Any:
            """simple docstring"""






            assert len(__a) == 2
            __snake_case				:      Optional[Any]     							= [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:
      __snake_case				:      Optional[Any]     							= None
      with patch('comet.load_from_checkpoint'  ) as mock_load_from_checkpoint:
         __snake_case				:      List[Any]     							= load_from_checkpoint
         yield





def        _SCREAMING_SNAKE_CASE  (				)    -> Tuple:







   """simple docstring"""
   __snake_case				:      Optional[int]     							= load_metric(os.path.join('metrics'  ,		'seqeval'  )  )
   __snake_case				:      Optional[int]     							= 'ERROR'
   __snake_case				:      Any     							= F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
   with pytest.raises(A  ,		match=re.escape(A  )  ):
      metric.compute(predictions=[]  ,		references=[]  ,		scheme=A  )







'''simple docstring'''






import math




class a_    :







   def __init__(self					,   __a=0)			->      Any:  # a graph with Node 0,1,...,N-1
      """simple docstring"""






      __snake_case				:      List[str]     							= n
      __snake_case				:      Tuple     							= [
          [math.inf for j in range(0					,   __a)] for i in range(0					,   __a)
      ]  # adjacency matrix for weight
      __snake_case				:      Union[str, Any]     							= [
          [math.inf for j in range(0					,   __a)] for i in range(0					,   __a)
      ]  # dp[i][j] stores minimum distance from i to j







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a					,   __a)			->      Tuple:
      """simple docstring"""






      __snake_case				:      Union[str, Any]     							= w







   def     SCREAMING_SNAKE_CASE__					(self)			->      Tuple:
      """simple docstring"""






      for k in range(0					,   self.n):
         for i in range(0					,   self.n):
            for j in range(0					,   self.n):
               __snake_case				:      List[Any]     							= min(self.dp[i][j]					,   self.dp[i][k] + self.dp[k][j])







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a)			->      Optional[int]:
      """simple docstring"""






      return self.dp[u][v]


if __name__ == "__main__":
      __A    	=   Graph(5)
      graph.add_edge(0, 2, 9)
      graph.add_edge(0, 4, 1_0)
      graph.add_edge(1, 3, 5)
      graph.add_edge(2, 3, 7)
      graph.add_edge(3, 0, 1_0)
      graph.add_edge(3, 1, 2)
      graph.add_edge(3, 2, 1)
      graph.add_edge(3, 4, 6)
      graph.add_edge(4, 1, 3)
      graph.add_edge(4, 2, 4)
      graph.add_edge(4, 3, 9)
      graph.floyd_warshall()
      graph.show_min(1, 4)
      graph.show_min(0, 3)