


"""simple docstring"""


import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


__UpperCamelCase						:				Optional[int]             =      get_tests_dir("fixtures")



class 			lowerCamelCase__						(   unittest.TestCase			):







						def __a						(							self   :    List[str]		):
								# A mock response for an HTTP head request to emulate server down
								A					       = mock.Mock()
								A					       = 500
								A					       = {}
								A					       = HTTPError
								A					       = {}

								# Download this model to make sure it's in the cache.
								A					       = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'		)
								# Under the mock environment we get a 500 error when trying to reach the model.
								with mock.patch('requests.Session.request'			,			return_value=__UpperCamelCase		) as mock_head:
										A					       = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'		)
										# This check we did call the fake head request
										mock_head.assert_called()







						def __a						(							self   :    List[Any]		):
								# This test is for deprecated behavior and can be removed in v5
								A					       = ViTImageProcessor.from_pretrained(
								    'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'		)







						def __a						(							self   :    Any		):
								with self.assertRaises(__UpperCamelCase		):
										# config is in subfolder, the following should not work without specifying the subfolder
										A					       = AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants'		)

								A					       = AutoImageProcessor.from_pretrained(
								    'hf-internal-testing/stable-diffusion-all-variants'			,			subfolder='feature_extractor'		)

								self.assertIsNotNone(__UpperCamelCase		)



@is_staging_test
class 			lowerCamelCase__						(   unittest.TestCase			):







						@classmethod
						def __a						(							cls   :    Dict		):
								A					       = TOKEN
								HfFolder.save_token(__UpperCamelCase		)







						@classmethod
						def __a						(							cls   :    int		):
								try:
										delete_repo(token=cls._token			,			repo_id='test-image-processor'		)
								except HTTPError:
										pass

								try:
										delete_repo(token=cls._token			,			repo_id='valid_org/test-image-processor-org'		)
								except HTTPError:
										pass

								try:
										delete_repo(token=cls._token			,			repo_id='test-dynamic-image-processor'		)
								except HTTPError:
										pass







						def __a						(							self   :    Tuple		):
								A					       = ViTImageProcessor.from_pretrained(__UpperCamelCase		)
								image_processor.push_to_hub('test-image-processor'			,			use_auth_token=self._token		)

								A					       = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor'		)
								for k, v in image_processor.__dict__.items():
										self.assertEqual(__UpperCamelCase			,			getattr(__UpperCamelCase			,			__UpperCamelCase		)		)

								# Reset repo
								delete_repo(token=self._token			,			repo_id='test-image-processor'		)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
										image_processor.save_pretrained(
										    __UpperCamelCase			,			repo_id='test-image-processor'			,			push_to_hub=__UpperCamelCase			,			use_auth_token=self._token		)

								A					       = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor'		)
								for k, v in image_processor.__dict__.items():
										self.assertEqual(__UpperCamelCase			,			getattr(__UpperCamelCase			,			__UpperCamelCase		)		)







						def __a						(							self   :    Union[str, Any]		):
								A					       = ViTImageProcessor.from_pretrained(__UpperCamelCase		)
								image_processor.push_to_hub('valid_org/test-image-processor'			,			use_auth_token=self._token		)

								A					       = ViTImageProcessor.from_pretrained('valid_org/test-image-processor'		)
								for k, v in image_processor.__dict__.items():
										self.assertEqual(__UpperCamelCase			,			getattr(__UpperCamelCase			,			__UpperCamelCase		)		)

								# Reset repo
								delete_repo(token=self._token			,			repo_id='valid_org/test-image-processor'		)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
										image_processor.save_pretrained(
										    __UpperCamelCase			,			repo_id='valid_org/test-image-processor-org'			,			push_to_hub=__UpperCamelCase			,			use_auth_token=self._token		)

								A					       = ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org'		)
								for k, v in image_processor.__dict__.items():
										self.assertEqual(__UpperCamelCase			,			getattr(__UpperCamelCase			,			__UpperCamelCase		)		)







						def __a						(							self   :    Dict		):
								CustomImageProcessor.register_for_auto_class()
								A					       = CustomImageProcessor.from_pretrained(__UpperCamelCase		)

								image_processor.push_to_hub('test-dynamic-image-processor'			,			use_auth_token=self._token		)

								# This has added the proper auto_map field to the config
								self.assertDictEqual(
								    image_processor.auto_map			,			{'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'}			,			)

								A					       = AutoImageProcessor.from_pretrained(
								    f'{USER}/test-dynamic-image-processor'			,			trust_remote_code=__UpperCamelCase		)
								# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
								self.assertEqual(new_image_processor.__class__.__name__			,			'CustomImageProcessor'		)









"""simple docstring"""


import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
	from PIL import Image
else:



	class 			lowerCamelCase__						:







							@staticmethod
							def __a						(							*_lowercase   :    int			,			**_lowercase   :    Optional[int]		):
									pass



@is_pipeline_test
@require_vision
@require_torch
class 			lowerCamelCase__						(   unittest.TestCase			):
						lowerCAmelCase       =     MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING







						def __a						(							self   :    int			,			_lowercase   :    Optional[Any]			,			_lowercase   :    int			,			_lowercase   :    Union[str, Any]		):
								A					       = pipeline(
								    'zero-shot-object-detection'			,			model='hf-internal-testing/tiny-random-owlvit-object-detection'		)

								A					       = [
								    {
								        'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
								        'candidate_labels': ['cat', 'remote', 'couch'],
								    }
								]
								return object_detector, examples







						def __a						(							self   :    Tuple			,			_lowercase   :    int			,			_lowercase   :    Tuple		):
								A					       = object_detector(examples[0]			,			threshold=0.0		)

								A					       = len(_lowercase		)
								self.assertGreater(_lowercase			,			0		)
								self.assertEqual(
								    _lowercase			,			[
								        {
								            'score': ANY(_lowercase		),
								            'label': ANY(_lowercase		),
								            'box': {'xmin': ANY(_lowercase		), 'ymin': ANY(_lowercase		), 'xmax': ANY(_lowercase		), 'ymax': ANY(_lowercase		)},
								        }
								        for i in range(_lowercase		)
								    ]			,			)







						@require_tf
						@unittest.skip('Zero Shot Object Detection not implemented in TF'		)
						def __a						(							self   :    Optional[int]		):
								pass







						@require_torch
						def __a						(							self   :    Optional[Any]		):
								A					       = pipeline(
								    'zero-shot-object-detection'			,			model='hf-internal-testing/tiny-random-owlvit-object-detection'		)

								A					       = object_detector(
								    './tests/fixtures/tests_samples/COCO/000000039769.png'			,			candidate_labels=['cat', 'remote', 'couch']			,			threshold=0.6_4			,			)

								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[
								        {'score': 0.7_2_3_5, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
								        {'score': 0.7_2_1_8, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
								        {'score': 0.7_1_8_4, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
								        {'score': 0.6_7_4_8, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
								        {'score': 0.6_6_5_6, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
								        {'score': 0.6_6_1_4, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
								        {'score': 0.6_4_5_6, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
								        {'score': 0.6_4_2, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}},
								        {'score': 0.6_4_1_9, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
								    ]			,			)

								A					       = object_detector(
								    [
								        {
								            'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
								            'candidate_labels': ['cat', 'remote', 'couch'],
								        }
								    ]			,			threshold=0.6_4			,			)

								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[
								        [
								            {'score': 0.7_2_3_5, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
								            {'score': 0.7_2_1_8, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
								            {'score': 0.7_1_8_4, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
								            {'score': 0.6_7_4_8, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
								            {'score': 0.6_6_5_6, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
								            {'score': 0.6_6_1_4, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
								            {'score': 0.6_4_5_6, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
								            {'score': 0.6_4_2, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}},
								            {'score': 0.6_4_1_9, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
								        ]
								    ]			,			)







						@require_torch
						@slow
						def __a						(							self   :    List[str]		):
								A					       = pipeline('zero-shot-object-detection'		)

								A					       = object_detector(
								    'http://images.cocodataset.org/val2017/000000039769.jpg'			,			candidate_labels=['cat', 'remote', 'couch']			,			)
								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[
								        {'score': 0.2_8_6_8, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
								        {'score': 0.2_7_7, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
								        {'score': 0.2_5_3_7, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
								        {'score': 0.1_4_7_4, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}},
								        {'score': 0.1_2_0_8, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}},
								    ]			,			)

								A					       = object_detector(
								    [
								        {
								            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
								            'candidate_labels': ['cat', 'remote', 'couch'],
								        },
								        {
								            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
								            'candidate_labels': ['cat', 'remote', 'couch'],
								        },
								    ]			,			)
								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[
								        [
								            {'score': 0.2_8_6_8, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
								            {'score': 0.2_7_7, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
								            {'score': 0.2_5_3_7, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
								            {'score': 0.1_4_7_4, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}},
								            {'score': 0.1_2_0_8, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}},
								        ],
								        [
								            {'score': 0.2_8_6_8, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
								            {'score': 0.2_7_7, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
								            {'score': 0.2_5_3_7, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
								            {'score': 0.1_4_7_4, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}},
								            {'score': 0.1_2_0_8, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}},
								        ],
								    ]			,			)







						@require_tf
						@unittest.skip('Zero Shot Object Detection not implemented in TF'		)
						def __a						(							self   :    Optional[int]		):
								pass







						@require_torch
						@slow
						def __a						(							self   :    Optional[Any]		):
								A					       = 0.2
								A					       = pipeline('zero-shot-object-detection'		)

								A					       = object_detector(
								    'http://images.cocodataset.org/val2017/000000039769.jpg'			,			candidate_labels=['cat', 'remote', 'couch']			,			threshold=_lowercase			,			)
								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[
								        {'score': 0.2_8_6_8, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
								        {'score': 0.2_7_7, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
								        {'score': 0.2_5_3_7, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
								    ]			,			)







						@require_torch
						@slow
						def __a						(							self   :    Optional[int]		):
								A					       = 2
								A					       = pipeline('zero-shot-object-detection'		)

								A					       = object_detector(
								    'http://images.cocodataset.org/val2017/000000039769.jpg'			,			candidate_labels=['cat', 'remote', 'couch']			,			top_k=_lowercase			,			)
								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[
								        {'score': 0.2_8_6_8, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
								        {'score': 0.2_7_7, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
								    ]			,			)





