






'''simple docstring'''




import unittest

from transformers import (
    MODEL_FOR_OBJECT_DETECTION_MAPPING,
    AutoFeatureExtractor,
    AutoModelForObjectDetection,
    ObjectDetectionPipeline,
    is_vision_available,
    pipeline,
)
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_pytesseract,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
    from PIL import Image
else:

    class   _UpperCAmelCase     :




       """simple docstring"""

       @staticmethod
       def 		lowerCAmelCase					(						*__UpperCAmelCase					:      int , **__UpperCAmelCase					:      List[Any]						):





             '''simple docstring'''





             pass

@is_pipeline_test
@require_vision
@require_timm
@require_torch
class   _UpperCAmelCase     (	unittest.TestCase		):




   """simple docstring"""

   snake_case       							=		MODEL_FOR_OBJECT_DETECTION_MAPPING

   def 		lowerCAmelCase					(						self					:      str , __UpperCAmelCase					:      Tuple , __UpperCAmelCase					:      Tuple , __UpperCAmelCase					:      str						):





         '''simple docstring'''





         _A     	=      ObjectDetectionPipeline(model=__UpperCAmelCase , image_processor=__UpperCAmelCase						)
         return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]

   def 		lowerCAmelCase					(						self					:      int , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      int						):





         '''simple docstring'''





         _A     	=      object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0						)

         self.assertGreater(len(__UpperCAmelCase						) , 0						)
         for detected_object in outputs:
               self.assertEqual(
                   __UpperCAmelCase , {
                       "score": ANY(__UpperCAmelCase						),
                       "label": ANY(__UpperCAmelCase						),
                       "box": {"xmin": ANY(__UpperCAmelCase						), "ymin": ANY(__UpperCAmelCase						), "xmax": ANY(__UpperCAmelCase						), "ymax": ANY(__UpperCAmelCase						)},
                   } , )

         import datasets

         _A     	=      datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test"						)

         _A     	=      [
             Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						),
             "http://images.cocodataset.org/val2017/000000039769.jpg",
             # RGBA
             dataset[0]["file"],
             # LA
             dataset[1]["file"],
             # L
             dataset[2]["file"],
         ]
         _A     	=      object_detector(__UpperCAmelCase , threshold=0.0						)

         self.assertEqual(len(__UpperCAmelCase						) , len(__UpperCAmelCase						)						)
         for outputs in batch_outputs:
               self.assertGreater(len(__UpperCAmelCase						) , 0						)
               for detected_object in outputs:
                     self.assertEqual(
                         __UpperCAmelCase , {
                             "score": ANY(__UpperCAmelCase						),
                             "label": ANY(__UpperCAmelCase						),
                             "box": {"xmin": ANY(__UpperCAmelCase						), "ymin": ANY(__UpperCAmelCase						), "xmax": ANY(__UpperCAmelCase						), "ymax": ANY(__UpperCAmelCase						)},
                         } , )

   @require_tf
   @unittest.skip("Object detection not implemented in TF"						)
   def 		lowerCAmelCase					(						self					:      List[str]						):





         '''simple docstring'''





         pass

   @require_torch
   def 		lowerCAmelCase					(						self					:      Union[str, Any]						):





         '''simple docstring'''





         _A     	=      "hf-internal-testing/tiny-detr-mobilenetsv3"

         _A     	=      AutoModelForObjectDetection.from_pretrained(__UpperCAmelCase						)
         _A     	=      AutoFeatureExtractor.from_pretrained(__UpperCAmelCase						)
         _A     	=      ObjectDetectionPipeline(model=__UpperCAmelCase , feature_extractor=__UpperCAmelCase						)

         _A     	=      object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0						)

         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
                 {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
             ] , )

         _A     	=      object_detector(
             [
                 "http://images.cocodataset.org/val2017/000000039769.jpg",
                 "http://images.cocodataset.org/val2017/000000039769.jpg",
             ] , threshold=0.0 , )

         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 [
                     {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
                     {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
                 ],
                 [
                     {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
                     {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
                 ],
             ] , )

   @require_torch
   @slow
   def 		lowerCAmelCase					(						self					:      Union[str, Any]						):





         '''simple docstring'''





         _A     	=      "facebook/detr-resnet-50"

         _A     	=      AutoModelForObjectDetection.from_pretrained(__UpperCAmelCase						)
         _A     	=      AutoFeatureExtractor.from_pretrained(__UpperCAmelCase						)
         _A     	=      ObjectDetectionPipeline(model=__UpperCAmelCase , feature_extractor=__UpperCAmelCase						)

         _A     	=      object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"						)
         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
                 {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
                 {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
                 {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
                 {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
             ] , )

         _A     	=      object_detector(
             [
                 "http://images.cocodataset.org/val2017/000000039769.jpg",
                 "http://images.cocodataset.org/val2017/000000039769.jpg",
             ]						)
         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 [
                     {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
                     {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
                     {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
                     {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
                     {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
                 ],
                 [
                     {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
                     {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
                     {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
                     {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
                     {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
                 ],
             ] , )

   @require_torch
   @slow
   def 		lowerCAmelCase					(						self					:      Union[str, Any]						):





         '''simple docstring'''





         _A     	=      "facebook/detr-resnet-50"

         _A     	=      pipeline("object-detection" , model=__UpperCAmelCase						)

         _A     	=      object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"						)
         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
                 {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
                 {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
                 {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
                 {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
             ] , )

         _A     	=      object_detector(
             [
                 "http://images.cocodataset.org/val2017/000000039769.jpg",
                 "http://images.cocodataset.org/val2017/000000039769.jpg",
             ]						)
         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 [
                     {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
                     {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
                     {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
                     {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
                     {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
                 ],
                 [
                     {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
                     {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
                     {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
                     {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
                     {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
                 ],
             ] , )

   @require_torch
   @slow
   def 		lowerCAmelCase					(						self					:      str						):





         '''simple docstring'''





         _A     	=      0.9985
         _A     	=      "facebook/detr-resnet-50"

         _A     	=      pipeline("object-detection" , model=__UpperCAmelCase						)

         _A     	=      object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=__UpperCAmelCase						)
         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
                 {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
             ] , )

   @require_torch
   @require_pytesseract
   @slow
   def 		lowerCAmelCase					(						self					:      Optional[Any]						):





         '''simple docstring'''





         _A     	=      "Narsil/layoutlmv3-finetuned-funsd"
         _A     	=      0.9993

         _A     	=      pipeline("object-detection" , model=__UpperCAmelCase , threshold=__UpperCAmelCase						)

         _A     	=      object_detector(
             "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png"						)
         self.assertEqual(
             nested_simplify(__UpperCAmelCase , decimals=4						) , [
                 {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
                 {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
             ] , )






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


__UpperCAmelCase					={"comet"}
__UpperCAmelCase					=importlib.util.find_spec("fairseq") is not None

__UpperCAmelCase					={"code_eval"}
__UpperCAmelCase					=os.name == "nt"

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






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Any:
    @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__							)      ->       Any:
    @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__							)      ->       List[Any]:
    @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					(				)      ->       Any:
    __lowerCamelCase            =    [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					):
     lowerCamelCase    :	str				={}
     lowerCamelCase    :	Union[str, Any]				=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						:						Tuple    ,							a						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    '''[...]'''
         __lowerCamelCase            =    importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('''metrics'''    ,							a       )       ).module_path       )
         __lowerCamelCase            =    datasets.load.import_main_class(metric_module.__name__    ,							dataset=a       )
         # check parameters
         __lowerCamelCase            =    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:
                     __lowerCamelCase            =    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						:						Optional[Any]    ,							a						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    '''[...]'''
         __lowerCamelCase            =    importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('''metrics'''    ,							a       )       ).module_path       )
         # run doctest
         with self.use_local_metrics():
             __lowerCamelCase            =    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						:						Any    ,							a						:						Optional[Any]    ,							a						:						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						:						List[str]    ,							*a						:						Optional[int]    ,							**a						:						Tuple       ):
             return load_metric(os.path.join('''metrics'''    ,							a       )    ,							*a    ,							**a       )

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






     @classmethod
     def   SCREAMING_SNAKE_CASE__  (					cls						:						List[str]    ,							a						:						Tuple       ):





         """simple docstring"""



         def wrapper(a						:						List[Any]       ):
             __lowerCamelCase            =    contextmanager(a       )
             __lowerCamelCase            =    patcher
             return patcher

         return wrapper






@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''							)
def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Union[str, Any]:
    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						:						Tuple    ,							a						:						Dict       ):





             """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            =    MockedPredictor()
        yield






@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''							)
def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Tuple:
    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:
        __lowerCamelCase            =    bert_cos_score_idf
        yield






@LocalMetricTest.register_intensive_calls_patcher('''comet'''							)
def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[str]:
    def load_from_checkpoint(UpperCamelCase__							):




        class        a__ :






             def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]    ,							a						:						str    ,							*a						:						int    ,							**a						:						Tuple       ):





                 """simple docstring"""



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






def __lowerCAmelCase					(				)      ->       List[Any]:
    __lowerCamelCase            =    load_metric(os.path.join('''metrics'''							,    '''seqeval'''							)							)
    __lowerCamelCase            =    '''ERROR'''
    __lowerCamelCase            =    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__							)
