

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     __snake_case    (				unittest.TestCase  ):
       """simple docstring"""







       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              __snake_case       	=							mock.Mock()
              __snake_case       	=							5_00
              __snake_case       	=							{}
              __snake_case       	=							HTTPError
              __snake_case       	=							{}

              # Download this model to make sure it's in the cache.
              __snake_case       	=							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:
                     __snake_case       	=							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   )      ->							Tuple:






              """simple docstring"""


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






       def 			a		(		self   )      ->							int:






              """simple docstring"""


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

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

              self.assertIsNotNone(_UpperCamelCase   )






@is_staging_test
class     __snake_case    (				unittest.TestCase  ):
       """simple docstring"""







       @classmethod
       def 			a		(		cls   )      ->							Dict:






              """simple docstring"""


              __snake_case       	=							TOKEN
              HfFolder.save_token(_UpperCamelCase   )


       @classmethod
       def 			a		(		cls   )      ->							List[Any]:






              """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 			a		(		self   )      ->							List[str]:






              """simple docstring"""


              __snake_case       	=							ViTImageProcessor.from_pretrained(_UpperCamelCase   )
              image_processor.push_to_hub("""test-image-processor"""      , use_auth_token=self._token   )

              __snake_case       	=							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   )

              __snake_case       	=							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   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							ViTImageProcessor.from_pretrained(_UpperCamelCase   )
              image_processor.push_to_hub("""valid_org/test-image-processor"""      , use_auth_token=self._token   )

              __snake_case       	=							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   )

              __snake_case       	=							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   )      ->							Optional[Any]:






              """simple docstring"""


              CustomImageProcessor.register_for_auto_class()
              __snake_case       	=							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"""}      , )

              __snake_case       	=							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"""   )




import unittest

import numpy as np

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

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import VivitImageProcessor

class     __snake_case    (				unittest.TestCase  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase=7      , _UpperCamelCase=3      , _UpperCamelCase=10      , _UpperCamelCase=18      , _UpperCamelCase=30      , _UpperCamelCase=4_00      , _UpperCamelCase=True      , _UpperCamelCase=None      , _UpperCamelCase=True      , _UpperCamelCase=[0.5, 0.5, 0.5]      , _UpperCamelCase=[0.5, 0.5, 0.5]      , _UpperCamelCase=None      , )      ->							str:






              """simple docstring"""


              __snake_case       	=							size if size is not None else {"""shortest_edge""": 18}
              __snake_case       	=							crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

              __snake_case       	=							parent
              __snake_case       	=							batch_size
              __snake_case       	=							num_channels
              __snake_case       	=							num_frames
              __snake_case       	=							image_size
              __snake_case       	=							min_resolution
              __snake_case       	=							max_resolution
              __snake_case       	=							do_resize
              __snake_case       	=							size
              __snake_case       	=							do_normalize
              __snake_case       	=							image_mean
              __snake_case       	=							image_std
              __snake_case       	=							crop_size






       def 			a		(		self   )      ->							Optional[Any]:






              """simple docstring"""


              return {
                  "image_mean": self.image_mean,
                  "image_std": self.image_std,
                  "do_normalize": self.do_normalize,
                  "do_resize": self.do_resize,
                  "size": self.size,
                  "crop_size": self.crop_size,
              }






@require_torch
@require_vision
class     __snake_case    (				snake_case__			,	unittest.TestCase  ):
       """simple docstring"""







       __SCREAMING_SNAKE_CASE				    =							VivitImageProcessor if is_vision_available() else None


       def 			a		(		self   )      ->							int:






              """simple docstring"""


              __snake_case       	=							VivitImageProcessingTester(self   )


       @property
       def 			a		(		self   )      ->							str:






              """simple docstring"""


              return self.image_processor_tester.prepare_image_processor_dict()


       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              __snake_case       	=							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      , """do_center_crop"""   )   )
              self.assertTrue(hasattr(_UpperCamelCase      , """size"""   )   )


       def 			a		(		self   )      ->							str:






              """simple docstring"""


              __snake_case       	=							self.image_processing_class.from_dict(self.image_processor_dict   )
              self.assertEqual(image_processor.size      , {"""shortest_edge""": 18}   )
              self.assertEqual(image_processor.crop_size      , {"""height""": 18, """width""": 18}   )

              __snake_case       	=							self.image_processing_class.from_dict(self.image_processor_dict      , size=42      , crop_size=84   )
              self.assertEqual(image_processor.size      , {"""shortest_edge""": 42}   )
              self.assertEqual(image_processor.crop_size      , {"""height""": 84, """width""": 84}   )


       def 			a		(		self   )      ->							List[str]:






              """simple docstring"""


              __snake_case       	=							self.image_processing_class(**self.image_processor_dict   )
              # create random PIL videos
              __snake_case       	=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=_UpperCamelCase   )
              for video in video_inputs:
                     self.assertIsInstance(_UpperCamelCase      , _UpperCamelCase   )
                     self.assertIsInstance(video[0]      , Image.Image   )

              # Test not batched input
              __snake_case       	=							image_processing(video_inputs[0]      , return_tensors="""pt"""   ).pixel_values
              self.assertEqual(
                  encoded_videos.shape      , (
                      1,
                      self.image_processor_tester.num_frames,
                      self.image_processor_tester.num_channels,
                      self.image_processor_tester.crop_size["""height"""],
                      self.image_processor_tester.crop_size["""width"""],
                  )      , )

              # Test batched
              __snake_case       	=							image_processing(_UpperCamelCase      , return_tensors="""pt"""   ).pixel_values
              self.assertEqual(
                  encoded_videos.shape      , (
                      self.image_processor_tester.batch_size,
                      self.image_processor_tester.num_frames,
                      self.image_processor_tester.num_channels,
                      self.image_processor_tester.crop_size["""height"""],
                      self.image_processor_tester.crop_size["""width"""],
                  )      , )


       def 			a		(		self   )      ->							Union[str, Any]:






              """simple docstring"""


              __snake_case       	=							self.image_processing_class(**self.image_processor_dict   )
              # create random numpy tensors
              __snake_case       	=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=_UpperCamelCase      , numpify=_UpperCamelCase   )
              for video in video_inputs:
                     self.assertIsInstance(_UpperCamelCase      , _UpperCamelCase   )
                     self.assertIsInstance(video[0]      , np.ndarray   )

              # Test not batched input
              __snake_case       	=							image_processing(video_inputs[0]      , return_tensors="""pt"""   ).pixel_values
              self.assertEqual(
                  encoded_videos.shape      , (
                      1,
                      self.image_processor_tester.num_frames,
                      self.image_processor_tester.num_channels,
                      self.image_processor_tester.crop_size["""height"""],
                      self.image_processor_tester.crop_size["""width"""],
                  )      , )

              # Test batched
              __snake_case       	=							image_processing(_UpperCamelCase      , return_tensors="""pt"""   ).pixel_values
              self.assertEqual(
                  encoded_videos.shape      , (
                      self.image_processor_tester.batch_size,
                      self.image_processor_tester.num_frames,
                      self.image_processor_tester.num_channels,
                      self.image_processor_tester.crop_size["""height"""],
                      self.image_processor_tester.crop_size["""width"""],
                  )      , )






       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              __snake_case       	=							self.image_processing_class(**self.image_processor_dict   )
              # create random PyTorch tensors
              __snake_case       	=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=_UpperCamelCase      , torchify=_UpperCamelCase   )
              for video in video_inputs:
                     self.assertIsInstance(_UpperCamelCase      , _UpperCamelCase   )
                     self.assertIsInstance(video[0]      , torch.Tensor   )

              # Test not batched input
              __snake_case       	=							image_processing(video_inputs[0]      , return_tensors="""pt"""   ).pixel_values
              self.assertEqual(
                  encoded_videos.shape      , (
                      1,
                      self.image_processor_tester.num_frames,
                      self.image_processor_tester.num_channels,
                      self.image_processor_tester.crop_size["""height"""],
                      self.image_processor_tester.crop_size["""width"""],
                  )      , )

              # Test batched
              __snake_case       	=							image_processing(_UpperCamelCase      , return_tensors="""pt"""   ).pixel_values
              self.assertEqual(
                  encoded_videos.shape      , (
                      self.image_processor_tester.batch_size,
                      self.image_processor_tester.num_frames,
                      self.image_processor_tester.num_channels,
                      self.image_processor_tester.crop_size["""height"""],
                      self.image_processor_tester.crop_size["""width"""],
                  )      , )

