






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 ):






      def __init__(self					:    str		,		_snake_case					:    Any		,		_snake_case					:    List[str]=7		,		_snake_case					:    Dict=3		,		_snake_case					:    Optional[int]=18		,		_snake_case					:    int=30		,		_snake_case					:    Union[str, Any]=400		,		_snake_case					:    Any=True		,		_snake_case					:    List[Any]=None		,		_snake_case					:    Optional[int]=True		,		_snake_case					:    Optional[int]=None		,		_snake_case					:    List[str]=True		,		_snake_case					:    Dict=[0.4814_5466, 0.457_8275, 0.4082_1073]		,		_snake_case					:    Union[str, Any]=[0.2686_2954, 0.2613_0258, 0.2757_7711]		,		_snake_case					:    Any=True		,		)       ->   Dict:


       """simple docstring"""






       lowerCamelCase_							:    Union[str, Any]							=     size if size is not None else {'shortest_edge': 20}
       lowerCamelCase_							:    Optional[Any]							=     crop_size if crop_size is not None else {'height': 18, 'width': 18}
       lowerCamelCase_							:    int							=     parent
       lowerCamelCase_							:    Optional[Any]							=     batch_size
       lowerCamelCase_							:    List[Any]							=     num_channels
       lowerCamelCase_							:    Any							=     image_size
       lowerCamelCase_							:    Union[str, Any]							=     min_resolution
       lowerCamelCase_							:    str							=     max_resolution
       lowerCamelCase_							:    str							=     do_resize
       lowerCamelCase_							:    Optional[Any]							=     size
       lowerCamelCase_							:    int							=     do_center_crop
       lowerCamelCase_							:    str							=     crop_size
       lowerCamelCase_							:    Optional[int]							=     do_normalize
       lowerCamelCase_							:    List[Any]							=     image_mean
       lowerCamelCase_							:    Tuple							=     image_std
       lowerCamelCase_							:    Optional[int]							=     do_convert_rgb






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


       """simple docstring"""






       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      UpperCAmelCase_     (self					:    Dict		,		_snake_case					:    List[Any]=False		,		_snake_case					:    Optional[Any]=False		,		_snake_case					:    Union[str, Any]=False		)       ->   Optional[int]:


       """simple docstring"""






       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

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

       if torchify:
        lowerCamelCase_							:    List[str]							=     [torch.from_numpy(_snake_case		) for x in image_inputs]

       return image_inputs




@require_torch
@require_vision
class 	lowerCamelCase__				(							UpperCAmelCase,   unittest.TestCase ):
      lowerCamelCase_							:   List[Any]											=	CLIPImageProcessor if is_vision_available() else None






      def      UpperCAmelCase_     (self					:    Dict		)       ->   Dict:


       """simple docstring"""






       lowerCamelCase_							:    Optional[int]							=     CLIPImageProcessingTester(self		)






      @property
      def      UpperCAmelCase_     (self					:    Dict		)       ->   Any:


       """simple docstring"""






       return self.image_processor_tester.prepare_image_processor_dict()






      def      UpperCAmelCase_     (self					:    Optional[Any]		)       ->   List[str]:


       """simple docstring"""






       lowerCamelCase_							:    Any							=     self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(_snake_case		,		'do_resize'		)		)
       self.assertTrue(hasattr(_snake_case		,		'size'		)		)
       self.assertTrue(hasattr(_snake_case		,		'do_center_crop'		)		)
       self.assertTrue(hasattr(_snake_case		,		'center_crop'		)		)
       self.assertTrue(hasattr(_snake_case		,		'do_normalize'		)		)
       self.assertTrue(hasattr(_snake_case		,		'image_mean'		)		)
       self.assertTrue(hasattr(_snake_case		,		'image_std'		)		)
       self.assertTrue(hasattr(_snake_case		,		'do_convert_rgb'		)		)






      def      UpperCAmelCase_     (self					:    Tuple		)       ->   Optional[int]:


       """simple docstring"""






       lowerCamelCase_							:    Union[str, Any]							=     self.image_processing_class.from_dict(self.image_processor_dict		)
       self.assertEqual(image_processor.size		,		{'shortest_edge': 20}		)
       self.assertEqual(image_processor.crop_size		,		{'height': 18, 'width': 18}		)

       lowerCamelCase_							:    Union[str, Any]							=     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      UpperCAmelCase_     (self					:    int		)       ->   int:


       """simple docstring"""






       pass






      def      UpperCAmelCase_     (self					:    Optional[int]		)       ->   Tuple:


       """simple docstring"""






       lowerCamelCase_							:    Optional[int]							=     self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       lowerCamelCase_							:    Any							=     self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case		)
       for image in image_inputs:
        self.assertIsInstance(_snake_case		,		Image.Image		)

       # Test not batched input
       lowerCamelCase_							:    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
       lowerCamelCase_							:    Optional[int]							=     image_processing(_snake_case		,		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					:    Dict		)       ->   str:


       """simple docstring"""






       lowerCamelCase_							:    Any							=     self.image_processing_class(**self.image_processor_dict		)
       # create random numpy tensors
       lowerCamelCase_							:    Optional[int]							=     self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case		,		numpify=_snake_case		)
       for image in image_inputs:
        self.assertIsInstance(_snake_case		,		np.ndarray		)

       # Test not batched input
       lowerCamelCase_							:    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
       lowerCamelCase_							:    int							=     image_processing(_snake_case		,		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					:    str		)       ->   int:


       """simple docstring"""






       lowerCamelCase_							:    str							=     self.image_processing_class(**self.image_processor_dict		)
       # create random PyTorch tensors
       lowerCamelCase_							:    str							=     self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case		,		torchify=_snake_case		)
       for image in image_inputs:
        self.assertIsInstance(_snake_case		,		torch.Tensor		)

       # Test not batched input
       lowerCamelCase_							:    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
       lowerCamelCase_							:    str							=     image_processing(_snake_case		,		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__				(							UpperCAmelCase,   unittest.TestCase ):
      lowerCamelCase_							:   List[str]											=	CLIPImageProcessor if is_vision_available() else None






      def      UpperCAmelCase_     (self					:    int		)       ->   Optional[Any]:


       """simple docstring"""






       lowerCamelCase_							:    Optional[Any]							=     CLIPImageProcessingTester(self		,		num_channels=4		)
       lowerCamelCase_							:    Optional[Any]							=     3






      @property
      def      UpperCAmelCase_     (self					:    Union[str, Any]		)       ->   Tuple:


       """simple docstring"""






       return self.image_processor_tester.prepare_image_processor_dict()






      def      UpperCAmelCase_     (self					:    int		)       ->   int:


       """simple docstring"""






       lowerCamelCase_							:    Any							=     self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(_snake_case		,		'do_resize'		)		)
       self.assertTrue(hasattr(_snake_case		,		'size'		)		)
       self.assertTrue(hasattr(_snake_case		,		'do_center_crop'		)		)
       self.assertTrue(hasattr(_snake_case		,		'center_crop'		)		)
       self.assertTrue(hasattr(_snake_case		,		'do_normalize'		)		)
       self.assertTrue(hasattr(_snake_case		,		'image_mean'		)		)
       self.assertTrue(hasattr(_snake_case		,		'image_std'		)		)
       self.assertTrue(hasattr(_snake_case		,		'do_convert_rgb'		)		)






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


       """simple docstring"""






       pass






      def      UpperCAmelCase_     (self					:    int		)       ->   Any:


       """simple docstring"""






       lowerCamelCase_							:    List[str]							=     self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       lowerCamelCase_							:    Union[str, Any]							=     self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case		)
       for image in image_inputs:
        self.assertIsInstance(_snake_case		,		Image.Image		)

       # Test not batched input
       lowerCamelCase_							:    Optional[Any]							=     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
       lowerCamelCase_							:    List[str]							=     image_processing(_snake_case		,		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 collections import namedtuple

UpperCamelCase											=      namedtuple('''from_to''', '''from_ to''')

UpperCamelCase											=      {
    '''millimeter''': '''mm''',
    '''centimeter''': '''cm''',
    '''meter''': '''m''',
    '''kilometer''': '''km''',
    '''inch''': '''in''',
    '''inche''': '''in''',  # Trailing 's' has been stripped off
    '''feet''': '''ft''',
    '''foot''': '''ft''',
    '''yard''': '''yd''',
    '''mile''': '''mi''',
}

UpperCamelCase											=      {
    '''mm''': from_to(0.001, 1_0_0_0),
    '''cm''': from_to(0.01, 1_0_0),
    '''m''': from_to(1, 1),
    '''km''': from_to(1_0_0_0, 0.001),
    '''in''': from_to(0.0254, 39.3701),
    '''ft''': from_to(0.3048, 3.2_8084),
    '''yd''': from_to(0.9144, 1.0_9361),
    '''mi''': from_to(1609.34, 0.0_0062_1371),
}




def       _a   (							lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				)  ->      float:
 lowerCamelCase_							:    List[Any]							=     from_type.lower().rstrip('s'				)
 lowerCamelCase_							:    Optional[Any]							=     TYPE_CONVERSION.get(lowerCamelCase__ ,			lowerCamelCase__				)
 lowerCamelCase_							:    List[Any]							=     to_type.lower().rstrip('s'				)
 lowerCamelCase_							:    Optional[int]							=     TYPE_CONVERSION.get(lowerCamelCase__ ,			lowerCamelCase__				)
 if new_from not in METRIC_CONVERSION:
  lowerCamelCase_							:    List[Any]							=     (
      F'Invalid \'from_type\' value: {from_type!r}.\n'
      F'Conversion abbreviations are: {", ".join(lowerCamelCase__				)}'
  )
  raise ValueError(lowerCamelCase__				)
 if new_to not in METRIC_CONVERSION:
  lowerCamelCase_							:    List[str]							=     (
      F'Invalid \'to_type\' value: {to_type!r}.\n'
      F'Conversion abbreviations are: {", ".join(lowerCamelCase__				)}'
  )
  raise ValueError(lowerCamelCase__				)
 return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to


if __name__ == "__main__":
       import doctest

       doctest.testmod()
