
"""simple docstring"""


import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import YolosImageProcessor




class  __lowerCamelCase  ( unittest.TestCase			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase=7							,						UpperCAmelCase=3							,						UpperCAmelCase=30							,						UpperCAmelCase=400							,						UpperCAmelCase=True							,						UpperCAmelCase=None							,						UpperCAmelCase=True							,						UpperCAmelCase=[0.5, 0.5, 0.5]							,						UpperCAmelCase=[0.5, 0.5, 0.5]							,						UpperCAmelCase=True							,						UpperCAmelCase=1 / 255							,						UpperCAmelCase=True							,						):
							lowerCamelCase_					=  size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333}
							lowerCamelCase_					=  parent
							lowerCamelCase_					=  batch_size
							lowerCamelCase_					=  num_channels
							lowerCamelCase_					=  min_resolution
							lowerCamelCase_					=  max_resolution
							lowerCamelCase_					=  do_resize
							lowerCamelCase_					=  size
							lowerCamelCase_					=  do_normalize
							lowerCamelCase_					=  image_mean
							lowerCamelCase_					=  image_std
							lowerCamelCase_					=  do_rescale
							lowerCamelCase_					=  rescale_factor
							lowerCamelCase_					=  do_pad




				def        UpperCAmelCase__						(				self   ):
							return {
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "do_normalize": self.do_normalize,
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							    "do_rescale": self.do_rescale,
							    "rescale_factor": self.rescale_factor,
							    "do_pad": self.do_pad,
							}





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase=False   ):







							if not batched:
										lowerCamelCase_					=  image_inputs[0]
										if isinstance(UpperCAmelCase							,						Image.Image   ):
													lowerCamelCase_					=  image.size
										else:
													lowerCamelCase_					=  image.shape[1], image.shape[2]
										if w < h:
													lowerCamelCase_					=  int(self.size['''shortest_edge'''] * h / w   )
													lowerCamelCase_					=  self.size['shortest_edge']
										elif w > h:
													lowerCamelCase_					=  self.size['shortest_edge']
													lowerCamelCase_					=  int(self.size['''shortest_edge'''] * w / h   )
										else:
													lowerCamelCase_					=  self.size['shortest_edge']
													lowerCamelCase_					=  self.size['shortest_edge']

							else:
										lowerCamelCase_					=  []
										for image in image_inputs:
													lowerCamelCase_					=  self.get_expected_values([image]   )
													expected_values.append((expected_height, expected_width)   )
										lowerCamelCase_					=  max(UpperCAmelCase							,						key=lambda UpperCAmelCase   : item[0]   )[0]
										lowerCamelCase_					=  max(UpperCAmelCase							,						key=lambda UpperCAmelCase   : item[1]   )[1]

							return expected_height, expected_width




@require_torch
@require_vision
class  __lowerCamelCase  ( lowerCAmelCase						,	unittest.TestCase			):
				a__:      List[Any]          =    YolosImageProcessor if is_vision_available() else None




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  YolosImageProcessingTester(self   )




				@property
				def        UpperCAmelCase__						(				self   ):
							return self.image_processor_tester.prepare_image_processor_dict()




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.image_processing_class(**self.image_processor_dict   )
							self.assertTrue(hasattr(UpperCAmelCase							,						'''image_mean'''   )   )
							self.assertTrue(hasattr(UpperCAmelCase							,						'''image_std'''   )   )
							self.assertTrue(hasattr(UpperCAmelCase							,						'''do_normalize'''   )   )
							self.assertTrue(hasattr(UpperCAmelCase							,						'''do_resize'''   )   )
							self.assertTrue(hasattr(UpperCAmelCase							,						'''size'''   )   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.image_processing_class.from_dict(self.image_processor_dict   )
							self.assertEqual(image_processor.size							,						{'''shortest_edge''': 18, '''longest_edge''': 1333}   )
							self.assertEqual(image_processor.do_pad							,						UpperCAmelCase   )

							lowerCamelCase_					=  self.image_processing_class.from_dict(
							    self.image_processor_dict							,						size=42							,						max_size=84							,						pad_and_return_pixel_mask=UpperCAmelCase   )
							self.assertEqual(image_processor.size							,						{'''shortest_edge''': 42, '''longest_edge''': 84}   )
							self.assertEqual(image_processor.do_pad							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							pass




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.image_processing_class(**self.image_processor_dict   )
							# create random PIL images
							lowerCamelCase_					=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=UpperCAmelCase   )
							for image in image_inputs:
										self.assertIsInstance(UpperCAmelCase							,						Image.Image   )

							# Test not batched input
							lowerCamelCase_					=  image_processing(image_inputs[0]							,						return_tensors='''pt'''   ).pixel_values

							lowerCamelCase_					=  self.image_processor_tester.get_expected_values(UpperCAmelCase   )

							self.assertEqual(
							    encoded_images.shape							,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,						)

							# Test batched
							lowerCamelCase_					=  self.image_processor_tester.get_expected_values(UpperCAmelCase							,						batched=UpperCAmelCase   )

							lowerCamelCase_					=  image_processing(UpperCAmelCase							,						return_tensors='''pt'''   ).pixel_values
							self.assertEqual(
							    encoded_images.shape							,						(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )							,						)




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.image_processing_class(**self.image_processor_dict   )
							# create random numpy tensors
							lowerCamelCase_					=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=UpperCAmelCase							,						numpify=UpperCAmelCase   )
							for image in image_inputs:
										self.assertIsInstance(UpperCAmelCase							,						np.ndarray   )

							# Test not batched input
							lowerCamelCase_					=  image_processing(image_inputs[0]							,						return_tensors='''pt'''   ).pixel_values

							lowerCamelCase_					=  self.image_processor_tester.get_expected_values(UpperCAmelCase   )

							self.assertEqual(
							    encoded_images.shape							,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,						)

							# Test batched
							lowerCamelCase_					=  image_processing(UpperCAmelCase							,						return_tensors='''pt'''   ).pixel_values

							lowerCamelCase_					=  self.image_processor_tester.get_expected_values(UpperCAmelCase							,						batched=UpperCAmelCase   )

							self.assertEqual(
							    encoded_images.shape							,						(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )							,						)




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.image_processing_class(**self.image_processor_dict   )
							# create random PyTorch tensors
							lowerCamelCase_					=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=UpperCAmelCase							,						torchify=UpperCAmelCase   )
							for image in image_inputs:
										self.assertIsInstance(UpperCAmelCase							,						torch.Tensor   )

							# Test not batched input
							lowerCamelCase_					=  image_processing(image_inputs[0]							,						return_tensors='''pt'''   ).pixel_values

							lowerCamelCase_					=  self.image_processor_tester.get_expected_values(UpperCAmelCase   )

							self.assertEqual(
							    encoded_images.shape							,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,						)

							# Test batched
							lowerCamelCase_					=  image_processing(UpperCAmelCase							,						return_tensors='''pt'''   ).pixel_values

							lowerCamelCase_					=  self.image_processor_tester.get_expected_values(UpperCAmelCase							,						batched=UpperCAmelCase   )

							self.assertEqual(
							    encoded_images.shape							,						(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )							,						)




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.image_processing_class(**self.image_processor_dict   )
							lowerCamelCase_					=  self.image_processing_class(do_resize=UpperCAmelCase							,						do_normalize=UpperCAmelCase							,						do_rescale=UpperCAmelCase   )
							# create random PyTorch tensors
							lowerCamelCase_					=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=UpperCAmelCase							,						torchify=UpperCAmelCase   )
							for image in image_inputs:
										self.assertIsInstance(UpperCAmelCase							,						torch.Tensor   )

							# Test whether the method "pad" and calling the image processor return the same tensors
							lowerCamelCase_					=  image_processing_a.pad(UpperCAmelCase							,						return_tensors='''pt'''   )
							lowerCamelCase_					=  image_processing_a(UpperCAmelCase							,						return_tensors='''pt'''   )

							self.assertTrue(
							    torch.allclose(encoded_images_with_method['''pixel_values''']							,						encoded_images['''pixel_values''']							,						atol=1e-4   )   )




				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
							with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt'''							,						'''r'''   ) as f:
										lowerCamelCase_					=  json.loads(f.read()   )

							lowerCamelCase_					=  {'image_id': 3_9769, 'annotations': target}

							# encode them
							lowerCamelCase_					=  YolosImageProcessor.from_pretrained('''hustvl/yolos-small'''   )
							lowerCamelCase_					=  image_processing(images=UpperCAmelCase							,						annotations=UpperCAmelCase							,						return_tensors='''pt'''   )

							# verify pixel values
							lowerCamelCase_					=  torch.Size([1, 3, 800, 1066]   )
							self.assertEqual(encoding['''pixel_values'''].shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]   )
							self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3]							,						UpperCAmelCase							,						atol=1e-4   )   )

							# verify area
							lowerCamelCase_					=  torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area''']							,						UpperCAmelCase   )   )
							# verify boxes
							lowerCamelCase_					=  torch.Size([6, 4]   )
							self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape							,						UpperCAmelCase   )
							lowerCamelCase_					=  torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0]							,						UpperCAmelCase							,						atol=1e-3   )   )
							# verify image_id
							lowerCamelCase_					=  torch.tensor([3_9769]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id''']							,						UpperCAmelCase   )   )
							# verify is_crowd
							lowerCamelCase_					=  torch.tensor([0, 0, 0, 0, 0, 0]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd''']							,						UpperCAmelCase   )   )
							# verify class_labels
							lowerCamelCase_					=  torch.tensor([75, 75, 63, 65, 17, 17]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels''']							,						UpperCAmelCase   )   )
							# verify orig_size
							lowerCamelCase_					=  torch.tensor([480, 640]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size''']							,						UpperCAmelCase   )   )
							# verify size
							lowerCamelCase_					=  torch.tensor([800, 1066]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size''']							,						UpperCAmelCase   )   )





				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
							with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'''							,						'''r'''   ) as f:
										lowerCamelCase_					=  json.loads(f.read()   )

							lowerCamelCase_					=  {'file_name': '000000039769.png', 'image_id': 3_9769, 'segments_info': target}

							lowerCamelCase_					=  pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic'''   )

							# encode them
							lowerCamelCase_					=  YolosImageProcessor(format='''coco_panoptic'''   )
							lowerCamelCase_					=  image_processing(images=UpperCAmelCase							,						annotations=UpperCAmelCase							,						masks_path=UpperCAmelCase							,						return_tensors='''pt'''   )

							# verify pixel values
							lowerCamelCase_					=  torch.Size([1, 3, 800, 1066]   )
							self.assertEqual(encoding['''pixel_values'''].shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]   )
							self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3]							,						UpperCAmelCase							,						atol=1e-4   )   )

							# verify area
							lowerCamelCase_					=  torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area''']							,						UpperCAmelCase   )   )
							# verify boxes
							lowerCamelCase_					=  torch.Size([6, 4]   )
							self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape							,						UpperCAmelCase   )
							lowerCamelCase_					=  torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0]							,						UpperCAmelCase							,						atol=1e-3   )   )
							# verify image_id
							lowerCamelCase_					=  torch.tensor([3_9769]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id''']							,						UpperCAmelCase   )   )
							# verify is_crowd
							lowerCamelCase_					=  torch.tensor([0, 0, 0, 0, 0, 0]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd''']							,						UpperCAmelCase   )   )
							# verify class_labels
							lowerCamelCase_					=  torch.tensor([17, 17, 63, 75, 75, 93]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels''']							,						UpperCAmelCase   )   )
							# verify masks
							lowerCamelCase_					=  82_2873
							self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item()							,						UpperCAmelCase   )
							# verify orig_size
							lowerCamelCase_					=  torch.tensor([480, 640]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size''']							,						UpperCAmelCase   )   )
							# verify size
							lowerCamelCase_					=  torch.tensor([800, 1066]   )
							self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size''']							,						UpperCAmelCase   )   )









'''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_    	=				get_tests_dir("fixtures")






class 							_a				(			unittest.TestCase ):





       '''simple docstring'''






       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						mock.Mock()
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						500
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						{}
             SCREAMING_SNAKE_CASE   :      Any    					=						HTTPError
             SCREAMING_SNAKE_CASE   :      Any    					=						{}

             # Download this model to make sure it's in the cache.
             SCREAMING_SNAKE_CASE   :      str    					=						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=A  ) as mock_head:
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'  )
                   # This check we did call the fake head request
                   mock_head.assert_called()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						ViTImageProcessor.from_pretrained(
                 'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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

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

             self.assertIsNotNone(A  )






@is_staging_test
class 							_a				(			unittest.TestCase ):





       '''simple docstring'''






       @classmethod
       def        UpperCamelCase_							(      cls  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						TOKEN
             HfFolder.save_token(A  )







       @classmethod
       def        UpperCamelCase_							(      cls  ):







             '''simple docstring'''







             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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						ViTImageProcessor.from_pretrained(A  )
             image_processor.push_to_hub('test-image-processor',							use_auth_token=self._token  )

             SCREAMING_SNAKE_CASE   :      int    					=						ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor"  )
             for k, v in image_processor.__dict__.items():
                   self.assertEqual(A,							getattr(A,							A  )  )

             # 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(
                       A,							repo_id='test-image-processor',							push_to_hub=A,							use_auth_token=self._token  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor"  )
             for k, v in image_processor.__dict__.items():
                   self.assertEqual(A,							getattr(A,							A  )  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						ViTImageProcessor.from_pretrained(A  )
             image_processor.push_to_hub('valid_org/test-image-processor',							use_auth_token=self._token  )

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

             # 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(
                       A,							repo_id='valid_org/test-image-processor-org',							push_to_hub=A,							use_auth_token=self._token  )

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             CustomImageProcessor.register_for_auto_class()
             SCREAMING_SNAKE_CASE   :      Tuple    					=						CustomImageProcessor.from_pretrained(A  )

             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'},							)

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						AutoImageProcessor.from_pretrained(
                 F"{USER}/test-dynamic-image-processor",							trust_remote_code=A  )
             # 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'  )


