




'''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 							_a				(			unittest.TestCase ):





       '''simple docstring'''






       def __init__(      self,							A,							A=7,							A=3,							A=18,							A=30,							A=400,							A=True,							A=None,							A=True,							A=None,							A=True,							A=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],							A=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],							A=True,							):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self  ):







             '''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,							A=False,							A=False,							A=False  ):







             '''simple docstring'''







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

             if equal_resolution:
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						[]
                   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:
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						[]
                   for i in range(self.batch_size  ):
                         SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[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
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						[Image.fromarray(np.moveaxis(A,							0,							-1  )  ) for x in image_inputs]

             if torchify:
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						[torch.from_numpy(A  ) for x in image_inputs]

             return image_inputs






@require_torch
@require_vision
class 							_a				(			SCREAMING_SNAKE_CASE ,      unittest.TestCase ):





       '''simple docstring'''






       A						:				Tuple        =						ChineseCLIPImageProcessor if is_vision_available() else None







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						ChineseCLIPImageProcessingTester(self,							do_center_crop=A  )







       @property
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return self.image_processor_tester.prepare_image_processor_dict()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.image_processing_class(**self.image_processor_dict  )
             self.assertTrue(hasattr(A,							'do_resize'  )  )
             self.assertTrue(hasattr(A,							'size'  )  )
             self.assertTrue(hasattr(A,							'do_center_crop'  )  )
             self.assertTrue(hasattr(A,							'center_crop'  )  )
             self.assertTrue(hasattr(A,							'do_normalize'  )  )
             self.assertTrue(hasattr(A,							'image_mean'  )  )
             self.assertTrue(hasattr(A,							'image_std'  )  )
             self.assertTrue(hasattr(A,							'do_convert_rgb'  )  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.image_processing_class.from_dict(self.image_processor_dict  )
             self.assertEqual(image_processor.size,							{'height': 224, 'width': 224}  )
             self.assertEqual(image_processor.crop_size,							{'height': 18, 'width': 18}  )

             SCREAMING_SNAKE_CASE   :      int    					=						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  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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

             # Test not batched input
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						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
             SCREAMING_SNAKE_CASE   :      Tuple    					=						image_processing(A,							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'''







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

             # Test not batched input
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						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
             SCREAMING_SNAKE_CASE   :      str    					=						image_processing(A,							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'''







             SCREAMING_SNAKE_CASE   :      int    					=						self.image_processing_class(**self.image_processor_dict  )
             # create random PyTorch tensors
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.image_processor_tester.prepare_inputs(equal_resolution=A,							torchify=A  )
             for image in image_inputs:
                   self.assertIsInstance(A,							torch.Tensor  )

             # Test not batched input
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						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
             SCREAMING_SNAKE_CASE   :      List[str]    					=						image_processing(A,							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 							_a				(			SCREAMING_SNAKE_CASE ,      unittest.TestCase ):





       '''simple docstring'''






       A						:				int        =						ChineseCLIPImageProcessor if is_vision_available() else None







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						ChineseCLIPImageProcessingTester(self,							num_channels=4,							do_center_crop=A  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						3







       @property
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return self.image_processor_tester.prepare_image_processor_dict()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.image_processing_class(**self.image_processor_dict  )
             self.assertTrue(hasattr(A,							'do_resize'  )  )
             self.assertTrue(hasattr(A,							'size'  )  )
             self.assertTrue(hasattr(A,							'do_center_crop'  )  )
             self.assertTrue(hasattr(A,							'center_crop'  )  )
             self.assertTrue(hasattr(A,							'do_normalize'  )  )
             self.assertTrue(hasattr(A,							'image_mean'  )  )
             self.assertTrue(hasattr(A,							'image_std'  )  )
             self.assertTrue(hasattr(A,							'do_convert_rgb'  )  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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

             # Test not batched input
             SCREAMING_SNAKE_CASE   :      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
             SCREAMING_SNAKE_CASE   :      Tuple    					=						image_processing(A,							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'''
from dataclasses import dataclass
from typing import Optional

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin

@dataclass
class     _lowerCamelCase       (     snake_case_					):




 '''simple docstring'''
 __lowercase					:		torch.FloatTensor


class     _lowerCamelCase       (     snake_case_     ,		snake_case_					):




 '''simple docstring'''


 @register_to_config
 def __init__(   self   ,   __lowercase = 16   ,   __lowercase = 88   ,   __lowercase = None   ,   __lowercase = None   ,   __lowercase = 1   ,   __lowercase = 0.0   ,   __lowercase = 32   ,   __lowercase = None   ,   __lowercase = False   ,   __lowercase = None   ,   __lowercase = "geglu"   ,   __lowercase = True   ,   __lowercase = True   ,   ):

  """simple docstring"""







  super().__init__()
  __A	:		Optional[int]	  =      num_attention_heads
  __A	:		Dict	  =      attention_head_dim
  __A	:		Optional[int]	  =      num_attention_heads * attention_head_dim

  __A	:		Optional[Any]	  =      in_channels

  __A	:		Optional[int]	  =      torch.nn.GroupNorm(num_groups=__lowercase   ,   num_channels=__lowercase   ,   eps=1E-6   ,   affine=__lowercase    )
  __A	:		Optional[Any]	  =      nn.Linear(__lowercase   ,   __lowercase    )

  # 3. Define transformers blocks
  __A	:		List[Any]	  =      nn.ModuleList(
      [
          BasicTransformerBlock(
              __lowercase   ,   __lowercase   ,   __lowercase   ,   dropout=__lowercase   ,   cross_attention_dim=__lowercase   ,   activation_fn=__lowercase   ,   attention_bias=__lowercase   ,   double_self_attention=__lowercase   ,   norm_elementwise_affine=__lowercase   ,   )
          for d in range(__lowercase    )
      ]    )

  __A	:		Union[str, Any]	  =      nn.Linear(__lowercase   ,   __lowercase    )







 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase=None   ,   __lowercase=None   ,   __lowercase=None   ,   __lowercase=1   ,   __lowercase=None   ,   __lowercase = True   ,   ):

  """simple docstring"""







  __A  ,__A  ,__A  ,__A	:		int	  =      hidden_states.shape
  __A	:		Union[str, Any]	  =      batch_frames // num_frames

  __A	:		Union[str, Any]	  =      hidden_states

  __A	:		List[str]	  =      hidden_states[None, :].reshape(__lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase    )
  __A	:		List[Any]	  =      hidden_states.permute(0   ,   2   ,   1   ,   3   ,   4    )

  __A	:		Dict	  =      self.norm(__lowercase    )
  __A	:		List[Any]	  =      hidden_states.permute(0   ,   3   ,   4   ,   2   ,   1    ).reshape(batch_size * height * width   ,   __lowercase   ,   __lowercase    )

  __A	:		Optional[Any]	  =      self.proj_in(__lowercase    )

  # 2. Blocks
  for block in self.transformer_blocks:
   __A	:		List[Any]	  =      block(
       __lowercase   ,   encoder_hidden_states=__lowercase   ,   timestep=__lowercase   ,   cross_attention_kwargs=__lowercase   ,   class_labels=__lowercase   ,   )

  # 3. Output
  __A	:		Optional[int]	  =      self.proj_out(__lowercase    )
  __A	:		int	  =      (
      hidden_states[None, None, :]
      .reshape(__lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase    )
      .permute(0   ,   3   ,   4   ,   1   ,   2    )
      .contiguous()
  )
  __A	:		List[str]	  =      hidden_states.reshape(__lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase    )

  __A	:		str	  =      hidden_states + residual

  if not return_dict:
   return (output,)

  return TransformerTemporalModelOutput(sample=__lowercase    )






