


'''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


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import ChineseCLIPImageProcessor





class   UpperCAmelCase_    (unittest.TestCase    ):





    """simple docstring"""






    def __init__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=7     ,	SCREAMING_SNAKE_CASE_=3     ,	SCREAMING_SNAKE_CASE_=18     ,	SCREAMING_SNAKE_CASE_=30     ,	SCREAMING_SNAKE_CASE_=4_00     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=[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]     ,	SCREAMING_SNAKE_CASE_=[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]     ,	SCREAMING_SNAKE_CASE_=True     ,	)							->	Optional[Any]:
         __lowerCamelCase  :      int														=						size if size is not None else {'height': 2_24, 'width': 2_24}
         __lowerCamelCase  :      Optional[Any]														=						crop_size if crop_size is not None else {'height': 18, 'width': 18}
         __lowerCamelCase  :      Tuple														=						parent
         __lowerCamelCase  :      int														=						batch_size
         __lowerCamelCase  :      Dict														=						num_channels
         __lowerCamelCase  :      Any														=						image_size
         __lowerCamelCase  :      Dict														=						min_resolution
         __lowerCamelCase  :      List[Any]														=						max_resolution
         __lowerCamelCase  :      str														=						do_resize
         __lowerCamelCase  :      Union[str, Any]														=						size
         __lowerCamelCase  :      Any														=						do_center_crop
         __lowerCamelCase  :      List[str]														=						crop_size
         __lowerCamelCase  :      Union[str, Any]														=						do_normalize
         __lowerCamelCase  :      Optional[int]														=						image_mean
         __lowerCamelCase  :      int														=						image_std
         __lowerCamelCase  :      List[str]														=						do_convert_rgb







    def  lowercase_							(				self      )							->	List[str]:
         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  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_=False     ,	SCREAMING_SNAKE_CASE_=False     ,	SCREAMING_SNAKE_CASE_=False      )							->	Dict:
         assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

         if equal_resolution:
              __lowerCamelCase  :      Dict														=						[]
              for i in range(self.batch_size      ):
                   image_inputs.append(
                       np.random.randint(
                           2_55     ,	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  :      Tuple														=						np.random.choice(np.arange(self.min_resolution     ,	self.max_resolution      )     ,	2      )
                   image_inputs.append(np.random.randint(2_55     ,	size=(self.num_channels, width, height)     ,	dtype=np.uinta      )      )

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

         if torchify:
              __lowerCamelCase  :      Dict														=						[torch.from_numpy(SCREAMING_SNAKE_CASE_      ) for x in image_inputs]

         return image_inputs







@require_torch
@require_vision
class   UpperCAmelCase_    (_UpperCAmelCase   ,						unittest.TestCase    ):





    """simple docstring"""






    lowerCamelCase    :   Dict					=     ChineseCLIPImageProcessor if is_vision_available() else None







    def  lowercase_							(				self      )							->	int:
         __lowerCamelCase  :      Any														=						ChineseCLIPImageProcessingTester(self     ,	do_center_crop=SCREAMING_SNAKE_CASE_      )







    @property
    def  lowercase_							(				self      )							->	Tuple:
         return self.image_processor_tester.prepare_image_processor_dict()







    def  lowercase_							(				self      )							->	List[str]:
         __lowerCamelCase  :      int														=						self.image_processing_class(**self.image_processor_dict      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_resize'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'size'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_center_crop'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'center_crop'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_normalize'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'image_mean'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'image_std'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_convert_rgb'      )      )







    def  lowercase_							(				self      )							->	List[str]:
         __lowerCamelCase  :      List[str]														=						self.image_processing_class.from_dict(self.image_processor_dict      )
         self.assertEqual(image_processor.size     ,	{'height': 2_24, 'width': 2_24}      )
         self.assertEqual(image_processor.crop_size     ,	{'height': 18, 'width': 18}      )

         __lowerCamelCase  :      str														=						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  lowercase_							(				self      )							->	str:
         pass







    def  lowercase_							(				self      )							->	str:
         # Initialize image_processing
         __lowerCamelCase  :      int														=						self.image_processing_class(**self.image_processor_dict      )
         # create random PIL images
         __lowerCamelCase  :      Any														=						self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_      )
         for image in image_inputs:
              self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,	Image.Image      )

         # 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  :      Tuple														=						image_processing(SCREAMING_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  lowercase_							(				self      )							->	Tuple:
         # Initialize image_processing
         __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=SCREAMING_SNAKE_CASE_     ,	numpify=SCREAMING_SNAKE_CASE_      )
         for image in image_inputs:
              self.assertIsInstance(SCREAMING_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(SCREAMING_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  lowercase_							(				self      )							->	int:
         # Initialize image_processing
         __lowerCamelCase  :      Optional[int]														=						self.image_processing_class(**self.image_processor_dict      )
         # create random PyTorch tensors
         __lowerCamelCase  :      Optional[int]														=						self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_     ,	torchify=SCREAMING_SNAKE_CASE_      )
         for image in image_inputs:
              self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,	torch.Tensor      )

         # Test not batched input
         __lowerCamelCase  :      Optional[int]														=						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  :      List[str]														=						image_processing(SCREAMING_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   UpperCAmelCase_    (_UpperCAmelCase   ,						unittest.TestCase    ):





    """simple docstring"""






    lowerCamelCase    :   int					=     ChineseCLIPImageProcessor if is_vision_available() else None







    def  lowercase_							(				self      )							->	List[Any]:
         __lowerCamelCase  :      str														=						ChineseCLIPImageProcessingTester(self     ,	num_channels=4     ,	do_center_crop=SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      List[str]														=						3







    @property
    def  lowercase_							(				self      )							->	str:
         return self.image_processor_tester.prepare_image_processor_dict()







    def  lowercase_							(				self      )							->	Optional[Any]:
         __lowerCamelCase  :      List[str]														=						self.image_processing_class(**self.image_processor_dict      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_resize'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'size'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_center_crop'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'center_crop'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_normalize'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'image_mean'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'image_std'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_convert_rgb'      )      )







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







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

         # Test not batched input
         __lowerCamelCase  :      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[Any]														=						image_processing(SCREAMING_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'],
             )     ,	)








'''simple docstring'''

import torch
from torch import nn
from transformers import CLIPPreTrainedModel, CLIPVisionModel

from ...models.attention import BasicTransformerBlock
from ...utils import logging


snake_case									=    logging.get_logger(__name__)  # pylint: disable=invalid-name




class    lowerCAmelCase       (     UpperCamelCase_  ):


 def __init__(    self  : Union[str, Any]			,							a__  : int			,							a__  : List[Any]=768    ):
  '''simple docstring'''

  super().__init__(a__    )
  lowerCAmelCase__     :   int     		=	proj_size

  lowerCAmelCase__     :   str     		=	CLIPVisionModel(a__    )
  lowerCAmelCase__     :   int     		=	PaintByExampleMapper(a__    )
  lowerCAmelCase__     :   Optional[int]     		=	nn.LayerNorm(config.hidden_size    )
  lowerCAmelCase__     :   Optional[Any]     		=	nn.Linear(config.hidden_size			,							self.proj_size    )

  # uncondition for scaling
  lowerCAmelCase__     :   Dict     		=	nn.Parameter(torch.randn((1, 1, self.proj_size)    )    )


 def    _A	(    self  : Tuple			,							a__  : int			,							a__  : Optional[Any]=False    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[Any]     		=	self.model(pixel_values=a__    )
  lowerCAmelCase__     :   Any     		=	clip_output.pooler_output
  lowerCAmelCase__     :   Union[str, Any]     		=	self.mapper(latent_states[:, None]    )
  lowerCAmelCase__     :   List[Any]     		=	self.final_layer_norm(a__    )
  lowerCAmelCase__     :   Optional[int]     		=	self.proj_out(a__    )
  if return_uncond_vector:
   return latent_states, self.uncond_vector

  return latent_states




class    lowerCAmelCase       (     nn.Module  ):


 def __init__(    self  : Optional[Any]			,							a__  : Optional[Any]    ):
  '''simple docstring'''

  super().__init__()
  lowerCAmelCase__     :   Optional[Any]     		=	(config.num_hidden_layers + 1) // 5
  lowerCAmelCase__     :   str     		=	config.hidden_size
  lowerCAmelCase__     :   Dict     		=	1
  lowerCAmelCase__     :   int     		=	nn.ModuleList(
      [
          BasicTransformerBlock(a__			,							a__			,							a__			,							activation_fn="gelu"			,							attention_bias=a__    )
          for _ in range(a__    )
      ]    )


 def    _A	(    self  : int			,							a__  : Union[str, Any]    ):
  '''simple docstring'''

  for block in self.blocks:
   lowerCAmelCase__     :   List[Any]     		=	block(a__    )

  return hidden_states





