





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_    :						Optional[int]    		=      pytest.mark.integration


a_    :						Optional[int]    		=      {"comet"}
a_    :						List[str]    		=      importlib.util.find_spec("fairseq") is not None

a_    :						Tuple    		=      {"code_eval"}
a_    :						List[Any]    		=      os.name == "nt"

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


def        __lowerCAmelCase    (       _UpperCamelCase		:  Any	)		->							Optional[Any]:
 '''simple docstring'''


 @wraps(_UpperCamelCase	)
 def wrapper(self		:  List[str]		,							_UpperCamelCase		:  int	):
  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		:  List[str]	)		->							List[str]:
 '''simple docstring'''


 @wraps(_UpperCamelCase	)
 def wrapper(self		:  str		,							_UpperCamelCase		:  List[str]	):
  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		:  int	)		->							str:
 '''simple docstring'''


 @wraps(_UpperCamelCase	)
 def wrapper(self		:  Union[str, Any]		,							_UpperCamelCase		:  Any	):
  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    (       )		->							Dict:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE								=			[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(
    SCREAMING_SNAKE_CASE	,			SCREAMING_SNAKE_CASE	,			SCREAMING_SNAKE_CASE   )
@local
class      UpperCamelCase (     parameterized.TestCase   ):
    __UpperCamelCase         ={}
    __UpperCamelCase         =None

    @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'    )
    @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'    )
    def UpperCamelCase			(			self :      Optional[int]							,    snake_case__ :      List[Any]    ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE								=			'[...]'
     SCREAMING_SNAKE_CASE								=			importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('metrics'							,    snake_case__    )    ).module_path    )
     SCREAMING_SNAKE_CASE								=			datasets.load.import_main_class(metric_module.__name__							,    dataset=snake_case__    )
     # check parameters
     SCREAMING_SNAKE_CASE								=			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:
        SCREAMING_SNAKE_CASE								=			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 UpperCamelCase			(			self :      str							,    snake_case__ :      Union[str, Any]    ):

     """simple docstring"""






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

    @contextmanager
    def UpperCamelCase			(			self :      int							,    snake_case__ :      Optional[Any]							,    snake_case__ :      str    ):

     """simple docstring"""






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

    @contextmanager
    def UpperCamelCase			(			self :      Any    ):

     """simple docstring"""






     def load_local_metric(snake_case__ :      Tuple							,    *snake_case__ :      int							,    **snake_case__ :      List[str]    ):
      return load_metric(os.path.join('metrics'							,    snake_case__    )							,    *snake_case__							,    **snake_case__    )

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




    @classmethod
    def UpperCamelCase			(			cls :      Any							,    snake_case__ :      Any    ):

     """simple docstring"""






     def wrapper(snake_case__ :      Any    ):
      SCREAMING_SNAKE_CASE								=			contextmanager(snake_case__    )
      SCREAMING_SNAKE_CASE								=			patcher
      return patcher

     return wrapper


@LocalMetricTest.register_intensive_calls_patcher('bleurt'	)
def        __lowerCAmelCase    (       _UpperCamelCase		:  Any	)		->							Dict:
 '''simple docstring'''


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

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




 class      UpperCamelCase (     SCREAMING_SNAKE_CASE   ):

     def UpperCamelCase			(			self :      str							,    snake_case__ :      Optional[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:
  SCREAMING_SNAKE_CASE								=			MockedPredictor()
  yield


@LocalMetricTest.register_intensive_calls_patcher('bertscore'	)
def        __lowerCAmelCase    (       _UpperCamelCase		:  Optional[Any]	)		->							str:
 '''simple docstring'''


 import torch

 def bert_cos_score_idf(_UpperCamelCase		:  List[Any]		,							_UpperCamelCase		:  Any		,							*_UpperCamelCase		:  Dict		,							**_UpperCamelCase		:  str	):
  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:
  SCREAMING_SNAKE_CASE								=			bert_cos_score_idf
  yield


@LocalMetricTest.register_intensive_calls_patcher('comet'	)
def        __lowerCAmelCase    (       _UpperCamelCase		:  Dict	)		->							List[Any]:
 '''simple docstring'''


 def load_from_checkpoint(_UpperCamelCase		:  Any	):




  class      UpperCamelCase :

      def UpperCamelCase			(			self :      str							,    snake_case__ :      Any							,    *snake_case__ :      List[Any]							,    **snake_case__ :      Dict    ):

       """simple docstring"""






       assert len(snake_case__    ) == 2
       SCREAMING_SNAKE_CASE								=			[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:
  SCREAMING_SNAKE_CASE								=			None
  with patch('comet.load_from_checkpoint'	) as mock_load_from_checkpoint:
   SCREAMING_SNAKE_CASE								=			load_from_checkpoint
   yield




def        __lowerCAmelCase    (       )		->							List[Any]:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE								=			load_metric(os.path.join('metrics'		,							'seqeval'	)	)
 SCREAMING_SNAKE_CASE								=			'ERROR'
 SCREAMING_SNAKE_CASE								=			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	)




from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
      from PIL import Image

      from ..image_utils import load_image

if is_torch_available():
      import torch

      from transformers.modeling_outputs import BaseModelOutput

      from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

a_    :						Dict    		=      logging.get_logger(__name__)




@add_end_docstrings(SCREAMING_SNAKE_CASE   )
class      UpperCamelCase (     SCREAMING_SNAKE_CASE   ):

    def __init__(			self :      Any							,    **snake_case__ :      Optional[int]    ):

     """simple docstring"""






     super().__init__(**snake_case__    )

     if self.framework == "tf":
      raise ValueError(F"""The {self.__class__} is only available in PyTorch."""    )

     requires_backends(self							,    'vision'    )
     self.check_model_type(snake_case__    )

    def __call__(			self :      List[Any]							,    snake_case__ :      Union[str, "Image.Image", List[Dict[str, Any]]]							,    snake_case__ :      Union[str, List[str]] = None							,    **snake_case__ :      Union[str, Any]							,    ):

     """simple docstring"""






     if "text_queries" in kwargs:
      SCREAMING_SNAKE_CASE								=			kwargs.pop('text_queries'    )

     if isinstance(snake_case__							,    (str, Image.Image)    ):
      SCREAMING_SNAKE_CASE								=			{'image': image, 'candidate_labels': candidate_labels}
     else:
      SCREAMING_SNAKE_CASE								=			image
     SCREAMING_SNAKE_CASE								=			super().__call__(snake_case__							,    **snake_case__    )
     return results

    def UpperCamelCase			(			self :      Union[str, Any]							,    **snake_case__ :      Optional[Any]    ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE								=			{}
     if "threshold" in kwargs:
      SCREAMING_SNAKE_CASE								=			kwargs['threshold']
     if "top_k" in kwargs:
      SCREAMING_SNAKE_CASE								=			kwargs['top_k']
     return {}, {}, postprocess_params

    def UpperCamelCase			(			self :      List[Any]							,    snake_case__ :      Optional[int]    ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE								=			load_image(inputs['image']    )
     SCREAMING_SNAKE_CASE								=			inputs['candidate_labels']
     if isinstance(snake_case__							,    snake_case__    ):
      SCREAMING_SNAKE_CASE								=			candidate_labels.split(','    )

     SCREAMING_SNAKE_CASE								=			torch.tensor([[image.height, image.width]]							,    dtype=torch.intaa    )
     for i, candidate_label in enumerate(snake_case__    ):
      SCREAMING_SNAKE_CASE								=			self.tokenizer(snake_case__							,    return_tensors=self.framework    )
      SCREAMING_SNAKE_CASE								=			self.image_processor(snake_case__							,    return_tensors=self.framework    )
      yield {
          "is_last": i == len(snake_case__    ) - 1,
          "target_size": target_size,
          "candidate_label": candidate_label,
          **text_inputs,
          **image_features,
      }

    def UpperCamelCase			(			self :      Any							,    snake_case__ :      Dict    ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE								=			model_inputs.pop('target_size'    )
     SCREAMING_SNAKE_CASE								=			model_inputs.pop('candidate_label'    )
     SCREAMING_SNAKE_CASE								=			model_inputs.pop('is_last'    )

     SCREAMING_SNAKE_CASE								=			self.model(**snake_case__    )

     SCREAMING_SNAKE_CASE								=			{'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
     return model_outputs

    def UpperCamelCase			(			self :      Union[str, Any]							,    snake_case__ :      Tuple							,    snake_case__ :      str=0.1							,    snake_case__ :      Union[str, Any]=None    ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE								=			[]
     for model_output in model_outputs:
      SCREAMING_SNAKE_CASE								=			model_output['candidate_label']
      SCREAMING_SNAKE_CASE								=			BaseModelOutput(snake_case__    )
      SCREAMING_SNAKE_CASE								=			self.image_processor.post_process_object_detection(
          outputs=snake_case__							,    threshold=snake_case__							,    target_sizes=model_output['target_size']    )[0]

      for index in outputs["scores"].nonzero():
       SCREAMING_SNAKE_CASE								=			outputs['scores'][index].item()
       SCREAMING_SNAKE_CASE								=			self._get_bounding_box(outputs['boxes'][index][0]    )

       SCREAMING_SNAKE_CASE								=			{'score': score, 'label': label, 'box': box}
       results.append(snake_case__    )

     SCREAMING_SNAKE_CASE								=			sorted(snake_case__							,    key=lambda snake_case__    : x["score"]							,    reverse=snake_case__    )
     if top_k:
      SCREAMING_SNAKE_CASE								=			results[:top_k]

     return results




    def UpperCamelCase			(			self :      List[Any]							,    snake_case__ :      "torch.Tensor"    ):

     """simple docstring"""






     if self.framework != "pt":
      raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.'    )
     SCREAMING_SNAKE_CASE						,	SCREAMING_SNAKE_CASE						,	SCREAMING_SNAKE_CASE						,	SCREAMING_SNAKE_CASE								=			box.int().tolist()
     SCREAMING_SNAKE_CASE								=			{
         'xmin': xmin,
         'ymin': ymin,
         'xmax': xmax,
         'ymax': ymax,
     }
     return bbox

