





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  __lowerCAmelCase	:






    @staticmethod
    def       lowerCamelCase  (*__magic_name__ ,							**__magic_name__   )					->       Tuple:


        '''simple docstring'''



        pass



@is_pipeline_test
@require_vision
@require_timm
@require_torch
class  __lowerCAmelCase	(      unittest.TestCase					):
   lowerCamelCase_					:					Union[str, Any]	      =				MODEL_FOR_OBJECT_DETECTION_MAPPING






   def       lowerCamelCase  (self ,							__magic_name__ ,							__magic_name__ ,							__magic_name__   )					->       Optional[Any]:


       '''simple docstring'''



       snake_case_						:   str           =  ObjectDetectionPipeline(model=__magic_name__ ,							image_processor=__magic_name__   )
       return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]






   def       lowerCamelCase  (self ,							__magic_name__ ,							__magic_name__   )					->       str:


       '''simple docstring'''



       snake_case_						:   Tuple           =  object_detector('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ,							threshold=0.0   )

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

       import datasets

       snake_case_						:   int           =  datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' ,							'''image''' ,							split='''test'''   )

       snake_case_						:   Dict           =  [
           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'''],
       ]
       snake_case_						:   List[Any]           =  object_detector(__magic_name__ ,							threshold=0.0   )

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






   @require_tf
   @unittest.skip('''Object detection not implemented in TF'''   )
   def       lowerCamelCase  (self   )					->       Dict:


       '''simple docstring'''



       pass






   @require_torch
   def       lowerCamelCase  (self   )					->       str:


       '''simple docstring'''



       snake_case_						:   Tuple           =  '''hf-internal-testing/tiny-detr-mobilenetsv3'''

       snake_case_						:   Tuple           =  AutoModelForObjectDetection.from_pretrained(__magic_name__   )
       snake_case_						:   str           =  AutoFeatureExtractor.from_pretrained(__magic_name__   )
       snake_case_						:   Optional[Any]           =  ObjectDetectionPipeline(model=__magic_name__ ,							feature_extractor=__magic_name__   )

       snake_case_						:   Dict           =  object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ,							threshold=0.0   )

       self.assertEqual(
           nested_simplify(__magic_name__ ,							decimals=4   ) ,							[
               {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}},
               {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}},
           ] ,							)

       snake_case_						:   Optional[int]           =  object_detector(
           [
               '''http://images.cocodataset.org/val2017/000000039769.jpg''',
               '''http://images.cocodataset.org/val2017/000000039769.jpg''',
           ] ,							threshold=0.0 ,							)

       self.assertEqual(
           nested_simplify(__magic_name__ ,							decimals=4   ) ,							[
               [
                   {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}},
                   {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}},
               ],
               [
                   {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}},
                   {'''score''': 0.3_376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}},
               ],
           ] ,							)






   @require_torch
   @slow
   def       lowerCamelCase  (self   )					->       List[str]:


       '''simple docstring'''



       snake_case_						:   Dict           =  '''facebook/detr-resnet-50'''

       snake_case_						:   int           =  AutoModelForObjectDetection.from_pretrained(__magic_name__   )
       snake_case_						:   Union[str, Any]           =  AutoFeatureExtractor.from_pretrained(__magic_name__   )
       snake_case_						:   List[Any]           =  ObjectDetectionPipeline(model=__magic_name__ ,							feature_extractor=__magic_name__   )

       snake_case_						:   Optional[Any]           =  object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg'''   )
       self.assertEqual(
           nested_simplify(__magic_name__ ,							decimals=4   ) ,							[
               {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}},
               {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}},
               {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}},
               {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}},
               {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}},
           ] ,							)

       snake_case_						:   Tuple           =  object_detector(
           [
               '''http://images.cocodataset.org/val2017/000000039769.jpg''',
               '''http://images.cocodataset.org/val2017/000000039769.jpg''',
           ]   )
       self.assertEqual(
           nested_simplify(__magic_name__ ,							decimals=4   ) ,							[
               [
                   {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}},
                   {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}},
                   {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}},
                   {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}},
                   {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}},
               ],
               [
                   {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}},
                   {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}},
                   {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}},
                   {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}},
                   {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}},
               ],
           ] ,							)






   @require_torch
   @slow
   def       lowerCamelCase  (self   )					->       Union[str, Any]:


       '''simple docstring'''



       snake_case_						:   List[str]           =  '''facebook/detr-resnet-50'''

       snake_case_						:   Optional[Any]           =  pipeline('''object-detection''' ,							model=__magic_name__   )

       snake_case_						:   Tuple           =  object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg'''   )
       self.assertEqual(
           nested_simplify(__magic_name__ ,							decimals=4   ) ,							[
               {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}},
               {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}},
               {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}},
               {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}},
               {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}},
           ] ,							)

       snake_case_						:   Union[str, Any]           =  object_detector(
           [
               '''http://images.cocodataset.org/val2017/000000039769.jpg''',
               '''http://images.cocodataset.org/val2017/000000039769.jpg''',
           ]   )
       self.assertEqual(
           nested_simplify(__magic_name__ ,							decimals=4   ) ,							[
               [
                   {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}},
                   {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}},
                   {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}},
                   {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}},
                   {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}},
               ],
               [
                   {'''score''': 0.9_982, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}},
                   {'''score''': 0.9_960, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}},
                   {'''score''': 0.9_955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}},
                   {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}},
                   {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}},
               ],
           ] ,							)






   @require_torch
   @slow
   def       lowerCamelCase  (self   )					->       str:


       '''simple docstring'''



       snake_case_						:   Optional[Any]           =  0.9_985
       snake_case_						:   Any           =  '''facebook/detr-resnet-50'''

       snake_case_						:   List[str]           =  pipeline('''object-detection''' ,							model=__magic_name__   )

       snake_case_						:   int           =  object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ,							threshold=__magic_name__   )
       self.assertEqual(
           nested_simplify(__magic_name__ ,							decimals=4   ) ,							[
               {'''score''': 0.9_988, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}},
               {'''score''': 0.9_987, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}},
           ] ,							)






   @require_torch
   @require_pytesseract
   @slow
   def       lowerCamelCase  (self   )					->       Dict:


       '''simple docstring'''



       snake_case_						:   Optional[int]           =  '''Narsil/layoutlmv3-finetuned-funsd'''
       snake_case_						:   Optional[Any]           =  0.9_993

       snake_case_						:   Any           =  pipeline('''object-detection''' ,							model=__magic_name__ ,							threshold=__magic_name__   )

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







import time
from contextlib import contextmanager
from pathlib import Path

import pytest
import requests
from huggingface_hub.hf_api import HfApi, HfFolder


lowerCAmelCase_    =    '''__DUMMY_TRANSFORMERS_USER__'''
lowerCAmelCase_    =    '''Dummy User'''
lowerCAmelCase_    =    '''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'''

lowerCAmelCase_    =    '''https://hub-ci.huggingface.co'''
lowerCAmelCase_    =    CI_HUB_ENDPOINT + '''/datasets/{repo_id}/resolve/{revision}/{path}'''
lowerCAmelCase_    =    CI_HUB_ENDPOINT + '''/{repo_id}/resolve/{revision}/{filename}'''
lowerCAmelCase_    =    Path('''~/.huggingface/hub_ci_token''').expanduser()






@pytest.fixture
def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Optional[int]:






				"""simple docstring"""


				monkeypatch.setattr(
				    '''huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE'''			,    _UpperCamelCase			)






@pytest.fixture
def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Optional[int]:






				"""simple docstring"""


				monkeypatch.setattr('''datasets.config.HF_ENDPOINT'''			,    _UpperCamelCase			)
				monkeypatch.setattr('''datasets.config.HUB_DATASETS_URL'''			,    _UpperCamelCase			)






@pytest.fixture
def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Any:






				"""simple docstring"""


				monkeypatch.setattr('''huggingface_hub.hf_api.HfFolder.path_token'''			,    _UpperCamelCase			)






@pytest.fixture
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			)		->						Optional[Any]:






				"""simple docstring"""


				HfFolder.save_token(_UpperCamelCase			)
				yield
				HfFolder.delete_token()






@pytest.fixture(scope='''session'''			)
def 					lowerCamelCase_						(    )		->						List[str]:






				"""simple docstring"""


				return HfApi(endpoint=_UpperCamelCase			)






@pytest.fixture(scope='''session'''			)
def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Dict:






				"""simple docstring"""


				snake_case_						:   Union[str, Any]           =  HfFolder.get_token()
				HfFolder.save_token(_UpperCamelCase			)
				yield CI_HUB_USER_TOKEN
				if previous_token is not None:
								HfFolder.save_token(_UpperCamelCase			)






@pytest.fixture
def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[str]:






				"""simple docstring"""


				def _cleanup_repo(_UpperCamelCase			):
								hf_api.delete_repo(_UpperCamelCase			,    token=_UpperCamelCase			,    repo_type='''dataset'''			)

				return _cleanup_repo






@pytest.fixture
def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[str]:






				"""simple docstring"""


				@contextmanager
				def _temporary_repo(_UpperCamelCase			):
								try:
												yield repo_id
								finally:
												cleanup_repo(_UpperCamelCase			)

				return _temporary_repo






@pytest.fixture(scope='''session'''			)
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)		->						Dict:






				"""simple docstring"""


				snake_case_						:   Optional[int]           =  f'''repo_txt_data-{int(time.time() * 10E3			)}'''
				snake_case_						:   Any           =  f'''{CI_HUB_USER}/{repo_name}'''
				hf_api.create_repo(_UpperCamelCase			,    token=_UpperCamelCase			,    repo_type='''dataset'''			,    private=_UpperCamelCase			)
				hf_api.upload_file(
				    token=_UpperCamelCase			,    path_or_fileobj=str(_UpperCamelCase			)			,    path_in_repo='''data/text_data.txt'''			,    repo_id=_UpperCamelCase			,    repo_type='''dataset'''			,    )
				yield repo_id
				try:
								hf_api.delete_repo(_UpperCamelCase			,    token=_UpperCamelCase			,    repo_type='''dataset'''			)
				except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
								pass






@pytest.fixture()
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)		->						Dict:






				"""simple docstring"""


				return hf_private_dataset_repo_txt_data_






@pytest.fixture(scope='''session'''			)
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)		->						Optional[Any]:






				"""simple docstring"""


				snake_case_						:   int           =  f'''repo_zipped_txt_data-{int(time.time() * 10E3			)}'''
				snake_case_						:   Tuple           =  f'''{CI_HUB_USER}/{repo_name}'''
				hf_api.create_repo(_UpperCamelCase			,    token=_UpperCamelCase			,    repo_type='''dataset'''			,    private=_UpperCamelCase			)
				hf_api.upload_file(
				    token=_UpperCamelCase			,    path_or_fileobj=str(_UpperCamelCase			)			,    path_in_repo='''data.zip'''			,    repo_id=_UpperCamelCase			,    repo_type='''dataset'''			,    )
				yield repo_id
				try:
								hf_api.delete_repo(_UpperCamelCase			,    token=_UpperCamelCase			,    repo_type='''dataset'''			)
				except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
								pass






@pytest.fixture()
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)		->						Dict:






				"""simple docstring"""


				return hf_private_dataset_repo_zipped_txt_data_






@pytest.fixture(scope='''session'''			)
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)		->						Optional[Any]:






				"""simple docstring"""


				snake_case_						:   List[str]           =  f'''repo_zipped_img_data-{int(time.time() * 10E3			)}'''
				snake_case_						:   str           =  f'''{CI_HUB_USER}/{repo_name}'''
				hf_api.create_repo(_UpperCamelCase			,    token=_UpperCamelCase			,    repo_type='''dataset'''			,    private=_UpperCamelCase			)
				hf_api.upload_file(
				    token=_UpperCamelCase			,    path_or_fileobj=str(_UpperCamelCase			)			,    path_in_repo='''data.zip'''			,    repo_id=_UpperCamelCase			,    repo_type='''dataset'''			,    )
				yield repo_id
				try:
								hf_api.delete_repo(_UpperCamelCase			,    token=_UpperCamelCase			,    repo_type='''dataset'''			)
				except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
								pass






@pytest.fixture()
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				return hf_private_dataset_repo_zipped_img_data_
