






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


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

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

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

def 			lowerCAmelCase__     (     UpperCamelCase__				):



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

  return wrapper

def 			lowerCAmelCase__     (     UpperCamelCase__				):



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

  return wrapper

def 			lowerCAmelCase__     (     UpperCamelCase__				):



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

  return wrapper

def 			lowerCAmelCase__     (     ):



  '''simple docstring'''
  _a  :       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(
    snake_case_		,     snake_case_		,     snake_case_      )
@local
class        UpperCamelCase			(	parameterized.TestCase      ):
 UpperCamelCase					:       Tuple			=					{}
 UpperCamelCase					:       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		:						Union[str, Any]							,						UpperCAmelCase__		:						Any							)					->       Dict:
   _a  :       Optional[Any]             =	"""[...]"""
   _a  :       Optional[Any]             =	importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("""metrics"""							,						UpperCAmelCase__							)							).module_path							)
   _a  :       List[str]             =	datasets.load.import_main_class(metric_module.__name__							,						dataset=UpperCAmelCase__							)
   # check parameters
   _a  :       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(UpperCAmelCase__							,						metric_module.__name__							):
     with self.use_local_metrics():
       try:
         _a  :       Any             =	doctest.testmod(UpperCAmelCase__							,						verbose=UpperCAmelCase__							,						raise_on_error=UpperCAmelCase__							)
       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		:						List[str]							,						UpperCAmelCase__		:						Optional[int]							)					->       int:
   _a  :       Optional[int]             =	"""[...]"""
   _a  :       List[str]             =	importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("""metrics"""							,						UpperCAmelCase__							)							).module_path							)
   # run doctest
   with self.use_local_metrics():
     _a  :       List[str]             =	doctest.testmod(UpperCAmelCase__							,						verbose=UpperCAmelCase__							,						raise_on_error=UpperCAmelCase__							)
   self.assertEqual(results.failed							,						0							)
   self.assertGreater(results.attempted							,						1							)


 @contextmanager
 def _lowercase	(     self		:						List[Any]							,						UpperCAmelCase__		:						List[str]							,						UpperCAmelCase__		:						int							)					->       Union[str, Any]:
   if metric_name in self.INTENSIVE_CALLS_PATCHER:
     with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCAmelCase__							):
       yield
   else:
     yield


 @contextmanager
 def _lowercase	(     self		:						Tuple							)					->       Optional[int]:
   def load_local_metric(UpperCAmelCase__		:						Optional[Any]							,						*UpperCAmelCase__		:						Union[str, Any]							,						**UpperCAmelCase__		:						Tuple							):
     return load_metric(os.path.join("""metrics"""							,						UpperCAmelCase__							)							,						*UpperCAmelCase__							,						**UpperCAmelCase__							)

   with patch("""datasets.load_metric"""							) as mock_load_metric:
     _a  :       Optional[int]             =	load_local_metric
     yield







 @classmethod
 def _lowercase	(     cls		:						Union[str, Any]							,						UpperCAmelCase__		:						Tuple							)					->       List[str]:
   def wrapper(UpperCAmelCase__		:						str							):
     _a  :       int             =	contextmanager(UpperCAmelCase__							)
     _a  :       Tuple             =	patcher
     return patcher

   return wrapper







@LocalMetricTest.register_intensive_calls_patcher("""bleurt"""				)
def 			lowerCAmelCase__     (     UpperCamelCase__				):



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

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






  class        UpperCamelCase			(	snake_case_      ):


   def _lowercase	(     self		:						str							,						UpperCAmelCase__		:						List[str]							)					->       int:
     assert len(input_dict["""input_ids"""]							) == 2
     return np.array([1.0_3, 1.0_4]							)

    # 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:
    _a  :       int             =	MockedPredictor()
    yield

@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""				)
def 			lowerCAmelCase__     (     UpperCamelCase__				):



  '''simple docstring'''
  import torch

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

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

@LocalMetricTest.register_intensive_calls_patcher("""comet"""				)
def 			lowerCAmelCase__     (     UpperCamelCase__				):



  '''simple docstring'''
  def load_from_checkpoint(UpperCamelCase__				):






    class        UpperCamelCase			:


     def _lowercase	(     self		:						Optional[int]							,						UpperCAmelCase__		:						List[str]							,						*UpperCAmelCase__		:						int							,						**UpperCAmelCase__		:						Optional[int]							)					->       int:
       assert len(UpperCAmelCase__							) == 2
       _a  :       str             =	[0.1_9, 0.9_2]
       return scores, sum(UpperCAmelCase__							) / len(UpperCAmelCase__							)







    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:
    _a  :       str             =	None
    with patch("""comet.load_from_checkpoint"""				) as mock_load_from_checkpoint:
      _a  :       str             =	load_from_checkpoint
      yield



def 			lowerCAmelCase__     (     ):



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









"""simple docstring"""




import cva
import numpy as np






class        UpperCamelCase			:


 def __init__(     self		:						Optional[int]							,						UpperCAmelCase__		:						float							,						UpperCAmelCase__		:						int							)					->       Dict:

   if k in (0.0_4, 0.0_6):
     _a  :       List[str]             =	k
     _a  :       List[Any]             =	window_size
   else:
     raise ValueError("""invalid k value"""							)


 def __str__(     self		:						Dict							)					->       str:
   return str(self.k							)







 def _lowercase	(     self		:						int							,						UpperCAmelCase__		:						str							)					->       tuple[cva.Mat, list[list[int]]]:
   _a  :       Dict             =	cva.imread(UpperCAmelCase__							,						0							)
   _a      ,  _a  :       List[Any]             =	img.shape
   _a  :       list[list[int]]             =	[]
   _a  :       List[Any]             =	img.copy()
   _a  :       int             =	cva.cvtColor(UpperCAmelCase__							,						cva.COLOR_GRAY2RGB							)
   _a      ,  _a  :       Any             =	np.gradient(UpperCAmelCase__							)
   _a  :       Tuple             =	dx**2
   _a  :       Union[str, Any]             =	dy**2
   _a  :       Union[str, Any]             =	dx * dy
   _a  :       int             =	0.0_4
   _a  :       List[str]             =	self.window_size // 2
   for y in range(UpperCAmelCase__							,						h - offset							):
     for x in range(UpperCAmelCase__							,						w - offset							):
       _a  :       str             =	ixx[
           y - offset : y + offset + 1, x - offset : x + offset + 1
       ].sum()
       _a  :       List[Any]             =	iyy[
           y - offset : y + offset + 1, x - offset : x + offset + 1
       ].sum()
       _a  :       Tuple             =	ixy[
           y - offset : y + offset + 1, x - offset : x + offset + 1
       ].sum()

       _a  :       Any             =	(wxx * wyy) - (wxy**2)
       _a  :       Tuple             =	wxx + wyy
       _a  :       Any             =	det - k * (trace**2)
       # Can change the value
       if r > 0.5:
         corner_list.append([x, y, r]							)
         color_img.itemset((y, x, 0)							,						0							)
         color_img.itemset((y, x, 1)							,						0							)
         color_img.itemset((y, x, 2)							,						255							)
   return color_img, corner_list


if __name__ == "__main__":
 _snake_case          =   HarrisCorner(0.04, 3)
 _snake_case      , _snake_case          =   edge_detect.detect('path_to_image')
 cva.imwrite('detect.png', color_img)

