'''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__  :						str					=      get_tests_dir('fixtures')


class 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      def 		lowerCAmelCase__       (					self				)      ->      int:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[int] 					=	mock.Mock()
         UpperCAmelCase__				:					Dict 					=	500
         UpperCAmelCase__				:					Optional[int] 					=	{}
         UpperCAmelCase__				:					List[str] 					=	HTTPError
         UpperCAmelCase__				:					Tuple 					=	{}

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




      def 		lowerCAmelCase__       (					self				)      ->      Tuple:



         '''simple docstring'''



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




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



         '''simple docstring'''



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

         UpperCAmelCase__				:					Optional[Any] 					=	AutoImageProcessor.from_pretrained(
             '''hf-internal-testing/stable-diffusion-all-variants'''       ,subfolder='''feature_extractor'''				)

         self.assertIsNotNone(lowerCamelCase_				)




@is_staging_test
class 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      @classmethod
      def 		lowerCAmelCase__       (					cls				)      ->      Optional[Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[int] 					=	TOKEN
         HfFolder.save_token(lowerCamelCase_				)




      @classmethod
      def 		lowerCAmelCase__       (					cls				)      ->      List[str]:



         '''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 		lowerCAmelCase__       (					self				)      ->      Union[str, Any]:



         '''simple docstring'''



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

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

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

         UpperCAmelCase__				:					List[Any] 					=	ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)




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



         '''simple docstring'''



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

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

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

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




      def 		lowerCAmelCase__       (					self				)      ->      str:



         '''simple docstring'''



         CustomImageProcessor.register_for_auto_class()
         UpperCAmelCase__				:					List[str] 					=	CustomImageProcessor.from_pretrained(lowerCamelCase_				)

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

         UpperCAmelCase__				:					Any 					=	AutoImageProcessor.from_pretrained(
             f'''{USER}/test-dynamic-image-processor'''       ,trust_remote_code=lowerCamelCase_				)
         # 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 numpy as np







def __UpperCamelCase( _A       :					np.ndarray	,      _A       :					np.ndarray	,      _A       :					float = 1e-12	,      _A       :					int = 1_00	,      ):
   '''simple docstring'''
   assert np.shape(_A     )[0] == np.shape(_A     )[1]
   # Ensure proper dimensionality.
   assert np.shape(_A     )[0] == np.shape(_A     )[0]
   # Ensure inputs are either both complex or both real
   assert np.iscomplexobj(_A     ) == np.iscomplexobj(_A     )
   UpperCAmelCase__				:					int 					=	np.iscomplexobj(_A     )
   if is_complex:
      # Ensure complex input_matrix is Hermitian
      assert np.array_equal(_A	,      input_matrix.conj().T     )

   # Set convergence to False. Will define convergence when we exceed max_iterations
   # or when we have small changes from one iteration to next.

   UpperCAmelCase__				:					Any 					=	False
   UpperCAmelCase__				:					str 					=	0
   UpperCAmelCase__				:					Optional[int] 					=	0
   UpperCAmelCase__				:					Optional[int] 					=	1e12

   while not convergence:
      # Multiple matrix by the vector.
      UpperCAmelCase__				:					str 					=	np.dot(_A	,      _A     )
      # Normalize the resulting output vector.
      UpperCAmelCase__				:					int 					=	w / np.linalg.norm(_A     )
      # Find rayleigh quotient
      # (faster than usual b/c we know vector is normalized already)
      UpperCAmelCase__				:					int 					=	vector.conj().T if is_complex else vector.T
      UpperCAmelCase__				:					Any 					=	np.dot(_A	,      np.dot(_A	,      _A     )     )

      # Check convergence.
      UpperCAmelCase__				:					List[Any] 					=	np.abs(lambda_ - lambda_previous     ) / lambda_
      iterations += 1

      if error <= error_tol or iterations >= max_iterations:
         UpperCAmelCase__				:					Optional[Any] 					=	True

      UpperCAmelCase__				:					Optional[int] 					=	lambda_

   if is_complex:
      UpperCAmelCase__				:					Tuple 					=	np.real(lambda_     )

   return lambda_, vector







def __UpperCamelCase( ):
   '''simple docstring'''
   UpperCAmelCase__				:					Optional[int] 					=	np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]     )
   UpperCAmelCase__				:					int 					=	np.array([41, 4, 20]     )
   UpperCAmelCase__				:					str 					=	real_input_matrix.astype(np.complexaaa     )
   UpperCAmelCase__				:					Union[str, Any] 					=	np.triu(1J * complex_input_matrix	,      1     )
   complex_input_matrix += imag_matrix
   complex_input_matrix += -1 * imag_matrix.T
   UpperCAmelCase__				:					Tuple 					=	np.array([41, 4, 20]     ).astype(np.complexaaa     )

   for problem_type in ["real", "complex"]:
      if problem_type == "real":
         UpperCAmelCase__				:					Optional[int] 					=	real_input_matrix
         UpperCAmelCase__				:					int 					=	real_vector
      elif problem_type == "complex":
         UpperCAmelCase__				:					int 					=	complex_input_matrix
         UpperCAmelCase__				:					Tuple 					=	complex_vector

      # Our implementation.
      UpperCAmelCase__					,   UpperCAmelCase__				:					str 					=	power_iteration(_A	,      _A     )

      # Numpy implementation.

      # Get eigenvalues and eigenvectors using built-in numpy
      # eigh (eigh used for symmetric or hermetian matrices).
      UpperCAmelCase__					,   UpperCAmelCase__				:					Tuple 					=	np.linalg.eigh(_A     )
      # Last eigenvalue is the maximum one.
      UpperCAmelCase__				:					Dict 					=	eigen_values[-1]
      # Last column in this matrix is eigenvector corresponding to largest eigenvalue.
      UpperCAmelCase__				:					Union[str, Any] 					=	eigen_vectors[:, -1]

      # Check our implementation and numpy gives close answers.
      assert np.abs(eigen_value - eigen_value_max     ) <= 1e-6
      # Take absolute values element wise of each eigenvector.
      # as they are only unique to a minus sign.
      assert np.linalg.norm(np.abs(_A     ) - np.abs(_A     )     ) <= 1e-6


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  test_power_iteration()




