
'''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 AutoFeatureExtractor, WavaVecaFeatureExtractor
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_feature_extraction import CustomFeatureExtractor  # noqa E402


snake_case_ :  str     =					get_tests_dir('fixtures')


class 						lowercase__	(  unittest.TestCase   ):






			'''simple docstring'''







			def       UpperCAmelCase				(			self   ):

						'''simple docstring'''







						UpperCamelCase       =  mock.Mock()
						UpperCamelCase       =  5_0_0
						UpperCamelCase       =  {}
						UpperCamelCase       =  HTTPError
						UpperCamelCase       =  {}

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







			def       UpperCAmelCase				(			self   ):

						'''simple docstring'''







						UpperCamelCase       =  WavaVecaFeatureExtractor.from_pretrained(
						    '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json'''   )




@is_staging_test
class 						lowercase__	(  unittest.TestCase   ):






			'''simple docstring'''







			@classmethod
			def       UpperCAmelCase				(			cls   ):

						'''simple docstring'''







						UpperCamelCase       =  TOKEN
						HfFolder.save_token(lowerCamelCase__   )







			@classmethod
			def       UpperCAmelCase				(			cls   ):

						'''simple docstring'''







						try:
									delete_repo(token=cls._token ,   repo_id='''test-feature-extractor'''   )
						except HTTPError:
									pass

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

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







			def       UpperCAmelCase				(			self   ):

						'''simple docstring'''







						UpperCamelCase       =  WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase__   )
						feature_extractor.push_to_hub('''test-feature-extractor''' ,   use_auth_token=self._token   )

						UpperCamelCase       =  WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor'   )
						for k, v in feature_extractor.__dict__.items():
									self.assertEqual(lowerCamelCase__ ,   getattr(lowerCamelCase__ ,   lowerCamelCase__   )   )

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

						# Push to hub via save_pretrained
						with tempfile.TemporaryDirectory() as tmp_dir:
									feature_extractor.save_pretrained(
									    lowerCamelCase__ ,   repo_id='''test-feature-extractor''' ,   push_to_hub=lowerCamelCase__ ,   use_auth_token=self._token   )

						UpperCamelCase       =  WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor'   )
						for k, v in feature_extractor.__dict__.items():
									self.assertEqual(lowerCamelCase__ ,   getattr(lowerCamelCase__ ,   lowerCamelCase__   )   )







			def       UpperCAmelCase				(			self   ):

						'''simple docstring'''







						UpperCamelCase       =  WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase__   )
						feature_extractor.push_to_hub('''valid_org/test-feature-extractor''' ,   use_auth_token=self._token   )

						UpperCamelCase       =  WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor'''   )
						for k, v in feature_extractor.__dict__.items():
									self.assertEqual(lowerCamelCase__ ,   getattr(lowerCamelCase__ ,   lowerCamelCase__   )   )

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

						# Push to hub via save_pretrained
						with tempfile.TemporaryDirectory() as tmp_dir:
									feature_extractor.save_pretrained(
									    lowerCamelCase__ ,   repo_id='''valid_org/test-feature-extractor-org''' ,   push_to_hub=lowerCamelCase__ ,   use_auth_token=self._token   )

						UpperCamelCase       =  WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org'''   )
						for k, v in feature_extractor.__dict__.items():
									self.assertEqual(lowerCamelCase__ ,   getattr(lowerCamelCase__ ,   lowerCamelCase__   )   )







			def       UpperCAmelCase				(			self   ):

						'''simple docstring'''







						CustomFeatureExtractor.register_for_auto_class()
						UpperCamelCase       =  CustomFeatureExtractor.from_pretrained(lowerCamelCase__   )

						feature_extractor.push_to_hub('''test-dynamic-feature-extractor''' ,   use_auth_token=self._token   )

						# This has added the proper auto_map field to the config
						self.assertDictEqual(
						    feature_extractor.auto_map ,   {'''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor'''} ,   )

						UpperCamelCase       =  AutoFeatureExtractor.from_pretrained(
						    f'{USER}/test-dynamic-feature-extractor' ,   trust_remote_code=lowerCamelCase__   )
						# Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
						self.assertEqual(new_feature_extractor.__class__.__name__ ,   '''CustomFeatureExtractor'''   )







'''simple docstring'''


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_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import LevitImageProcessor


class 						lowercase__	(  unittest.TestCase   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__=7 ,   lowerCamelCase__=3 ,   lowerCamelCase__=1_8 ,   lowerCamelCase__=3_0 ,   lowerCamelCase__=4_0_0 ,   lowerCamelCase__=True ,   lowerCamelCase__=None ,   lowerCamelCase__=True ,   lowerCamelCase__=None ,   lowerCamelCase__=True ,   lowerCamelCase__=[0.5, 0.5, 0.5] ,   lowerCamelCase__=[0.5, 0.5, 0.5] ,   ):

      '''simple docstring'''







      UpperCamelCase       =  size if size is not None else {'''shortest_edge''': 1_8}
      UpperCamelCase       =  crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8}
      UpperCamelCase       =  parent
      UpperCamelCase       =  batch_size
      UpperCamelCase       =  num_channels
      UpperCamelCase       =  image_size
      UpperCamelCase       =  min_resolution
      UpperCamelCase       =  max_resolution
      UpperCamelCase       =  do_resize
      UpperCamelCase       =  size
      UpperCamelCase       =  do_center_crop
      UpperCamelCase       =  crop_size
      UpperCamelCase       =  do_normalize
      UpperCamelCase       =  image_mean
      UpperCamelCase       =  image_std







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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




@require_torch
@require_vision
class 						lowercase__	(  snake_case_,					unittest.TestCase   ):






   '''simple docstring'''







   _snake_case		   =							LevitImageProcessor if is_vision_available() else None







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  LevitImageProcessingTester(self   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      return self.image_processor_tester.prepare_image_processor_dict()







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  self.image_processing_class(**self.image_processor_dict   )
      self.assertTrue(hasattr(lowerCamelCase__ ,   '''image_mean'''   )   )
      self.assertTrue(hasattr(lowerCamelCase__ ,   '''image_std'''   )   )
      self.assertTrue(hasattr(lowerCamelCase__ ,   '''do_normalize'''   )   )
      self.assertTrue(hasattr(lowerCamelCase__ ,   '''do_resize'''   )   )
      self.assertTrue(hasattr(lowerCamelCase__ ,   '''do_center_crop'''   )   )
      self.assertTrue(hasattr(lowerCamelCase__ ,   '''size'''   )   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  self.image_processing_class.from_dict(self.image_processor_dict   )
      self.assertEqual(image_processor.size ,   {'''shortest_edge''': 1_8}   )
      self.assertEqual(image_processor.crop_size ,   {'''height''': 1_8, '''width''': 1_8}   )

      UpperCamelCase       =  self.image_processing_class.from_dict(self.image_processor_dict ,   size=4_2 ,   crop_size=8_4   )
      self.assertEqual(image_processor.size ,   {'''shortest_edge''': 4_2}   )
      self.assertEqual(image_processor.crop_size ,   {'''height''': 8_4, '''width''': 8_4}   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      pass







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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

      # Test not batched input
      UpperCamelCase       =  image_processing(image_inputs[0] ,   return_tensors='''pt'''   ).pixel_values
      self.assertEqual(
          encoded_images.shape ,   (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          ) ,   )

      # Test batched
      UpperCamelCase       =  image_processing(lowerCamelCase__ ,   return_tensors='''pt'''   ).pixel_values
      self.assertEqual(
          encoded_images.shape ,   (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          ) ,   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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

      # Test not batched input
      UpperCamelCase       =  image_processing(image_inputs[0] ,   return_tensors='''pt'''   ).pixel_values
      self.assertEqual(
          encoded_images.shape ,   (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          ) ,   )

      # Test batched
      UpperCamelCase       =  image_processing(lowerCamelCase__ ,   return_tensors='''pt'''   ).pixel_values
      self.assertEqual(
          encoded_images.shape ,   (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          ) ,   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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

      # Test not batched input
      UpperCamelCase       =  image_processing(image_inputs[0] ,   return_tensors='''pt'''   ).pixel_values
      self.assertEqual(
          encoded_images.shape ,   (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          ) ,   )

      # Test batched
      UpperCamelCase       =  image_processing(lowerCamelCase__ ,   return_tensors='''pt'''   ).pixel_values
      self.assertEqual(
          encoded_images.shape ,   (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          ) ,   )





