


"""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_       :       Tuple      						=  pytest.mark.integration


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

lowerCamelCase_       :       Optional[Any]      						=  {"""code_eval"""}
lowerCamelCase_       :       Any      						=  os.name == """nt"""

lowerCamelCase_       :       Optional[int]      						=  {"""bertscore""", """frugalscore""", """perplexity"""}
lowerCamelCase_       :       int      						=  importlib.util.find_spec("""transformers""") is not None
def _A						(						lowercase		):







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

    return wrapper
def _A						(						lowercase		):







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

    return wrapper
def _A						(						lowercase		):







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

    return wrapper
def _A						(						):







    """simple docstring"""
    a					=[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 				__A    (	parameterized.TestCase      ):






 """simple docstring"""




 __lowerCAmelCase			 =  {}
 __lowerCAmelCase			 =  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						) ->					Union[str, Any]:
     a					='''[...]'''
     a					=importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('''metrics'''			,   __A						)						).module_path						)
     a					=datasets.load.import_main_class(metric_module.__name__			,   dataset=__A						)
     # check parameters
     a					=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:
                 a					=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						) ->					Dict:
     a					='''[...]'''
     a					=importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('''metrics'''			,   __A						)						).module_path						)
     # run doctest
     with self.use_local_metrics():
         a					=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						) ->					Tuple:
     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						) ->					Optional[int]:
     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:
         a					=load_local_metric
         yield





 @classmethod
 def 				SCREAMING_SNAKE_CASE							(		cls			,   __A						) ->					Optional[int]:
     def wrapper(__A						):
         a					=contextmanager(__A						)
         a					=patcher
         return patcher

     return wrapper

@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''		)
def _A						(						lowercase		):







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

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






    class 				__A    (	_SCREAMING_SNAKE_CASE      ):






     """simple docstring"""




     def 				SCREAMING_SNAKE_CASE							(		self			,   __A						) ->					str:
         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:
        a					=MockedPredictor()
        yield
@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''		)
def _A						(						lowercase		):







    """simple docstring"""
    import torch

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

    # 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					=bert_cos_score_idf
        yield
@LocalMetricTest.register_intensive_calls_patcher('''comet'''		)
def _A						(						lowercase		):







    """simple docstring"""
    def load_from_checkpoint(lowercase		):






        class 				__A    :






         """simple docstring"""




         def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   *__A			,   **__A						) ->					Optional[Any]:
             assert len(__A						) == 2
             a					=[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:
        a					=None
        with patch('''comet.load_from_checkpoint'''		) as mock_load_from_checkpoint:
            a					=load_from_checkpoint
            yield





def _A						(						):







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



"""simple docstring"""







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

lowerCamelCase_       :       Dict      						=  logging.get_logger(__name__)






@add_end_docstrings(_SCREAMING_SNAKE_CASE      )
class 				__A    (	_SCREAMING_SNAKE_CASE      ):






 """simple docstring"""




 def __init__(		self			,   **__A						) ->					Dict:
     super().__init__(**__A						)

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

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


 def __call__(		self			,   __A			,   __A = None			,   **__A			,   ) ->					List[str]:
     if "text_queries" in kwargs:
         a					=kwargs.pop('''text_queries'''						)

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


 def 				SCREAMING_SNAKE_CASE							(		self			,   **__A						) ->					Optional[Any]:
     a					={}
     if "threshold" in kwargs:
         a					=kwargs['''threshold''']
     if "top_k" in kwargs:
         a					=kwargs['''top_k''']
     return {}, {}, postprocess_params


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A						) ->					str:
     a					=load_image(inputs['''image''']						)
     a					=inputs['''candidate_labels''']
     if isinstance(__A			,   __A						):
         a					=candidate_labels.split(''','''						)

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


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A						) ->					List[Any]:
     a					=model_inputs.pop('''target_size'''						)
     a					=model_inputs.pop('''candidate_label'''						)
     a					=model_inputs.pop('''is_last'''						)

     a					=self.model(**__A						)

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


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A=0.1			,   __A=None						) ->					List[str]:
     a					=[]
     for model_output in model_outputs:
         a					=model_output['''candidate_label''']
         a					=BaseModelOutput(__A						)
         a					=self.image_processor.post_process_object_detection(
             outputs=__A			,   threshold=__A			,   target_sizes=model_output['''target_size''']						)[0]

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

             a					={'''score''': score, '''label''': label, '''box''': box}
             results.append(__A						)

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

     return results





 def 				SCREAMING_SNAKE_CASE							(		self			,   __A						) ->					Dict[str, int]:
     if self.framework != "pt":
         raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.'''						)
     a		,				a		,				a		,				a					=box.int().tolist()
     a					={
         '''xmin''': xmin,
         '''ymin''': ymin,
         '''xmax''': xmax,
         '''ymax''': ymax,
     }
     return bbox