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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import CLIPImageProcessor




class       __lowerCAmelCase     (				unittest.TestCase  ):



 '''simple docstring'''

 def __init__(	self				:						Dict				,	lowerCamelCase				:						List[Any]				,	lowerCamelCase				:						Any=7				,	lowerCamelCase				:						List[str]=3				,	lowerCamelCase				:						Union[str, Any]=1_8				,	lowerCamelCase				:						Tuple=3_0				,	lowerCamelCase				:						Union[str, Any]=4_0_0				,	lowerCamelCase				:						Optional[int]=True				,	lowerCamelCase				:						str=None				,	lowerCamelCase				:						Optional[int]=True				,	lowerCamelCase				:						Optional[Any]=None				,	lowerCamelCase				:						int=True				,	lowerCamelCase				:						str=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]				,	lowerCamelCase				:						Dict=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]				,	lowerCamelCase				:						Optional[int]=True				,	)       ->							int:
        _UpperCamelCase   :				str       =     size if size is not None else {'shortest_edge': 2_0}
        _UpperCamelCase   :				Tuple       =     crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
        _UpperCamelCase   :				str       =     parent
        _UpperCamelCase   :				Dict       =     batch_size
        _UpperCamelCase   :				Dict       =     num_channels
        _UpperCamelCase   :				Dict       =     image_size
        _UpperCamelCase   :				Tuple       =     min_resolution
        _UpperCamelCase   :				Optional[int]       =     max_resolution
        _UpperCamelCase   :				Union[str, Any]       =     do_resize
        _UpperCamelCase   :				Optional[Any]       =     size
        _UpperCamelCase   :				str       =     do_center_crop
        _UpperCamelCase   :				List[str]       =     crop_size
        _UpperCamelCase   :				str       =     do_normalize
        _UpperCamelCase   :				Any       =     image_mean
        _UpperCamelCase   :				Optional[Any]       =     image_std
        _UpperCamelCase   :				Optional[Any]       =     do_convert_rgb

 def     __snake_case    (	self				:						Dict     )       ->							Optional[Any]:
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_convert_rgb": self.do_convert_rgb,
        }

 def     __snake_case    (	self				:						Tuple				,	lowerCamelCase				:						List[Any]=False				,	lowerCamelCase				:						Union[str, Any]=False				,	lowerCamelCase				:						Any=False     )       ->							Tuple:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
               _UpperCamelCase   :				int       =     []
               for i in range(self.batch_size     ):
                      image_inputs.append(
                          np.random.randint(
                              2_5_5				,	size=(self.num_channels, self.max_resolution, self.max_resolution)				,	dtype=np.uinta     )     )
        else:
               _UpperCamelCase   :				int       =     []
               for i in range(self.batch_size     ):
                      _UpperCamelCase  ,					_UpperCamelCase   :				Optional[Any]       =     np.random.choice(np.arange(self.min_resolution				,	self.max_resolution     )				,	2     )
                      image_inputs.append(np.random.randint(2_5_5				,	size=(self.num_channels, width, height)				,	dtype=np.uinta     )     )

        if not numpify and not torchify:
               # PIL expects the channel dimension as last dimension
               _UpperCamelCase   :				List[Any]       =     [Image.fromarray(np.moveaxis(lowerCamelCase				,	0				,	-1     )     ) for x in image_inputs]

        if torchify:
               _UpperCamelCase   :				str       =     [torch.from_numpy(lowerCamelCase     ) for x in image_inputs]

        return image_inputs







@require_torch
@require_vision
class       __lowerCAmelCase     (				a_,		unittest.TestCase  ):



 '''simple docstring'''
 _lowerCamelCase  :		Optional[Any] 			=       CLIPImageProcessor if is_vision_available() else None

 def     __snake_case    (	self				:						Any     )       ->							int:
        _UpperCamelCase   :				Optional[Any]       =     CLIPImageProcessingTester(self     )

 @property
 def     __snake_case    (	self				:						Union[str, Any]     )       ->							List[str]:
        return self.image_processor_tester.prepare_image_processor_dict()

 def     __snake_case    (	self				:						int     )       ->							str:
        _UpperCamelCase   :				Union[str, Any]       =     self.image_processing_class(**self.image_processor_dict     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_resize'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'size'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_center_crop'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'center_crop'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_normalize'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'image_mean'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'image_std'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_convert_rgb'     )     )

 def     __snake_case    (	self				:						Any     )       ->							Union[str, Any]:
        _UpperCamelCase   :				Tuple       =     self.image_processing_class.from_dict(self.image_processor_dict     )
        self.assertEqual(image_processor.size				,	{'shortest_edge': 2_0}     )
        self.assertEqual(image_processor.crop_size				,	{'height': 1_8, 'width': 1_8}     )

        _UpperCamelCase   :				Any       =     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     __snake_case    (	self				:						int     )       ->							str:
        pass

 def     __snake_case    (	self				:						int     )       ->							Optional[int]:
        # Initialize image_processing
        _UpperCamelCase   :				Union[str, Any]       =     self.image_processing_class(**self.image_processor_dict     )
        # create random PIL images
        _UpperCamelCase   :				Dict       =     self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase     )
        for image in image_inputs:
               self.assertIsInstance(lowerCamelCase				,	Image.Image     )

        # Test not batched input
        _UpperCamelCase   :				Dict       =     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   :				Optional[Any]       =     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     __snake_case    (	self				:						Tuple     )       ->							List[str]:
        # Initialize image_processing
        _UpperCamelCase   :				int       =     self.image_processing_class(**self.image_processor_dict     )
        # create random numpy tensors
        _UpperCamelCase   :				Any       =     self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase				,	numpify=lowerCamelCase     )
        for image in image_inputs:
               self.assertIsInstance(lowerCamelCase				,	np.ndarray     )

        # Test not batched input
        _UpperCamelCase   :				Dict       =     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   :				Any       =     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     __snake_case    (	self				:						Dict     )       ->							Any:
        # Initialize image_processing
        _UpperCamelCase   :				Optional[int]       =     self.image_processing_class(**self.image_processor_dict     )
        # create random PyTorch tensors
        _UpperCamelCase   :				Dict       =     self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase				,	torchify=lowerCamelCase     )
        for image in image_inputs:
               self.assertIsInstance(lowerCamelCase				,	torch.Tensor     )

        # Test not batched input
        _UpperCamelCase   :				List[str]       =     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   :				Optional[Any]       =     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'],
            )				,	)







@require_torch
@require_vision
class       __lowerCAmelCase     (				a_,		unittest.TestCase  ):



 '''simple docstring'''
 _lowerCamelCase  :		List[Any] 			=       CLIPImageProcessor if is_vision_available() else None

 def     __snake_case    (	self				:						List[str]     )       ->							str:
        _UpperCamelCase   :				Dict       =     CLIPImageProcessingTester(self				,	num_channels=4     )
        _UpperCamelCase   :				List[str]       =     3

 @property
 def     __snake_case    (	self				:						Any     )       ->							List[str]:
        return self.image_processor_tester.prepare_image_processor_dict()

 def     __snake_case    (	self				:						Any     )       ->							int:
        _UpperCamelCase   :				Dict       =     self.image_processing_class(**self.image_processor_dict     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_resize'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'size'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_center_crop'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'center_crop'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_normalize'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'image_mean'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'image_std'     )     )
        self.assertTrue(hasattr(lowerCamelCase				,	'do_convert_rgb'     )     )

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

 def     __snake_case    (	self				:						Dict     )       ->							Any:
        # Initialize image_processing
        _UpperCamelCase   :				int       =     self.image_processing_class(**self.image_processor_dict     )
        # create random PIL images
        _UpperCamelCase   :				Dict       =     self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase     )
        for image in image_inputs:
               self.assertIsInstance(lowerCamelCase				,	Image.Image     )

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

        # Test batched
        _UpperCamelCase   :				Union[str, Any]       =     image_processing(lowerCamelCase				,	return_tensors='pt'     ).pixel_values
        self.assertEqual(
            encoded_images.shape				,	(
                self.image_processor_tester.batch_size,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )				,	)




from __future__ import annotations


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int						,  lowercase_:		int ):
       assert n > 1 and a > 0 and greatest_common_divisor(lowercase_						,  lowercase_ ) == 1
       ((_UpperCamelCase)  ,					(_UpperCamelCase)  ,					(_UpperCamelCase))   :				Optional[int]       =     extended_gcd(lowercase_						,  lowercase_ )  # Implemented below
       _UpperCamelCase   :				str       =     (b * s) % n
       return x


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       ((_UpperCamelCase)  ,					(_UpperCamelCase))   :				Union[str, Any]       =     extended_euclid(lowercase_						,  lowercase_ )  # Implemented below
       if b < 0:
              _UpperCamelCase   :				Union[str, Any]       =     (b % n + n) % n
       return b


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int						,  lowercase_:		int ):
       _UpperCamelCase   :				Union[str, Any]       =     invert_modulo(lowercase_						,  lowercase_ )
       _UpperCamelCase   :				str       =     (b * s) % n
       return x


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       assert a >= 0 and b >= 0

       if b == 0:
              _UpperCamelCase  ,					_UpperCamelCase  ,					_UpperCamelCase   :				Any       =     a, 1, 0
       else:
              ((_UpperCamelCase)  ,					(_UpperCamelCase)  ,					(_UpperCamelCase))   :				Dict       =     extended_gcd(lowercase_						,  a % b )
              _UpperCamelCase   :				List[str]       =     q
              _UpperCamelCase   :				Any       =     p - q * (a // b)

       assert a % d == 0 and b % d == 0
       assert d == a * x + b * y

       return (d, x, y)


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       if b == 0:
              return (1, 0)
       ((_UpperCamelCase)  ,					(_UpperCamelCase))   :				Optional[Any]       =     extended_euclid(lowercase_						,  a % b )
       _UpperCamelCase   :				List[Any]       =     a // b
       return (y, x - k * y)


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       if a < b:
              _UpperCamelCase  ,					_UpperCamelCase   :				Optional[int]       =     b, a

       while a % b != 0:
              _UpperCamelCase  ,					_UpperCamelCase   :				Union[str, Any]       =     b, a % b

       return b


if __name__ == "__main__":
 from doctest import testmod

 testmod(name='''modular_division''', verbose=True)
 testmod(name='''modular_division2''', verbose=True)
 testmod(name='''invert_modulo''', verbose=True)
 testmod(name='''extended_gcd''', verbose=True)
 testmod(name='''extended_euclid''', verbose=True)
 testmod(name='''greatest_common_divisor''', verbose=True)



