


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


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import OwlViTImageProcessor







class 			UpperCAmelCase			(							unittest.TestCase):

 def __init__(			self			:						Optional[Any],       a_			:						Optional[int],       a_			:						Dict=7,       a_			:						List[str]=3,       a_			:						int=18,       a_			:						Tuple=30,       a_			:						Any=400,       a_			:						Optional[int]=True,       a_			:						Optional[int]=None,       a_			:						Any=True,       a_			:						Optional[int]=None,       a_			:						int=True,       a_			:						Optional[int]=[0.48_145_466, 0.4_578_275, 0.40_821_073],       a_			:						Optional[Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711],       a_			:						Optional[int]=True,       ):





    """simple docstring"""



    UpperCamelCase__			    =    parent
    UpperCamelCase__			    =    batch_size
    UpperCamelCase__			    =    num_channels
    UpperCamelCase__			    =    image_size
    UpperCamelCase__			    =    min_resolution
    UpperCamelCase__			    =    max_resolution
    UpperCamelCase__			    =    do_resize
    UpperCamelCase__			    =    size if size is not None else {"height": 18, "width": 18}
    UpperCamelCase__			    =    do_center_crop
    UpperCamelCase__			    =    crop_size if crop_size is not None else {"height": 18, "width": 18}
    UpperCamelCase__			    =    do_normalize
    UpperCamelCase__			    =    image_mean
    UpperCamelCase__			    =    image_std
    UpperCamelCase__			    =    do_convert_rgb

 def 		lowercase_    (			self			:						List[str]       ):





    """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,
    }







@require_torch
@require_vision
class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__		,      unittest.TestCase):
 _lowerCamelCase			:       Tuple            =       OwlViTImageProcessor if is_vision_available() else None

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    OwlViTImageProcessingTester(self       )

 @property
 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    return self.image_processor_tester.prepare_image_processor_dict()

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



    UpperCamelCase__			    =    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 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class.from_dict(self.image_processor_dict       )
    self.assertEqual(image_processor.size,       {"height": 18, "width": 18}       )
    self.assertEqual(image_processor.crop_size,       {"height": 18, "width": 18}       )

    UpperCamelCase__			    =    self.image_processing_class.from_dict(self.image_processor_dict,       size=42,       crop_size=84       )
    self.assertEqual(image_processor.size,       {"height": 42, "width": 42}       )
    self.assertEqual(image_processor.crop_size,       {"height": 84, "width": 84}       )

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random PIL images
    UpperCamelCase__			    =    prepare_image_inputs(self.image_processor_tester,       equal_resolution=a_       )

    for image in image_inputs:
       self.assertIsInstance(a_,       Image.Image       )

    # Test not batched input
    UpperCamelCase__			    =    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__			    =    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 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random numpy tensors
    UpperCamelCase__			    =    prepare_image_inputs(self.image_processor_tester,       equal_resolution=a_,       numpify=a_       )
    for image in image_inputs:
       self.assertIsInstance(a_,       np.ndarray       )

    # Test not batched input
    UpperCamelCase__			    =    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__			    =    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 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random PyTorch tensors
    UpperCamelCase__			    =    prepare_image_inputs(self.image_processor_tester,       equal_resolution=a_,       torchify=a_       )
    for image in image_inputs:
       self.assertIsInstance(a_,       torch.Tensor       )

    # Test not batched input
    UpperCamelCase__			    =    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__			    =    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"],
        ),       )



'''simple docstring'''

import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					int     ,		_UpperCamelCase   :					List[str]     ,		_UpperCamelCase   :					List[str] )		->       List[str]:





   '''simple docstring'''







   UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__			    =    pt_weights[F'{prefix}.in_proj_weight'].chunk(3     ,		dim=0 )
   UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__			    =    pt_weights[F'{prefix}.in_proj_bias'].chunk(3     ,		dim=0 )

   UpperCamelCase__			    =    pt_weights[F'{prefix}.out_proj.weight']
   UpperCamelCase__			    =    pt_weights[F'{prefix}.out_proj.bias']

   UpperCamelCase__			    =    q_proj
   UpperCamelCase__			    =    q_proj_bias

   UpperCamelCase__			    =    k_proj
   UpperCamelCase__			    =    k_proj_bias

   UpperCamelCase__			    =    v_proj
   UpperCamelCase__			    =    v_proj_bias

   UpperCamelCase__			    =    out_proj_weights
   UpperCamelCase__			    =    out_proj_bias



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					Union[str, Any]     ,		_UpperCamelCase   :					List[str]     ,		_UpperCamelCase   :					Dict )		->       Tuple:





   '''simple docstring'''







   copy_linear(hf_mlp.fca     ,		_UpperCamelCase     ,		F'{prefix}.c_fc' )
   copy_linear(hf_mlp.fca     ,		_UpperCamelCase     ,		F'{prefix}.c_proj' )



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					Tuple     ,		_UpperCamelCase   :					str     ,		_UpperCamelCase   :					Optional[int] )		->       Any:





   '''simple docstring'''







   UpperCamelCase__			    =    pt_weights[F'{prefix}.weight'].data
   UpperCamelCase__			    =    pt_weights[F'{prefix}.bias'].data



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					int     ,		_UpperCamelCase   :					List[Any]     ,		_UpperCamelCase   :					Any )		->       Union[str, Any]:





   '''simple docstring'''







   copy_linear(hf_layer.layer_norma     ,		_UpperCamelCase     ,		F'{prefix}.ln_1' )
   copy_linear(hf_layer.layer_norma     ,		_UpperCamelCase     ,		F'{prefix}.ln_2' )

   # copy MLP
   copy_mlp(hf_layer.mlp     ,		_UpperCamelCase     ,		F'{prefix}.mlp' )

   # copy attn
   copy_attn_layer(hf_layer.self_attn     ,		_UpperCamelCase     ,		F'{prefix}.attn' )



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					Tuple     ,		_UpperCamelCase   :					Optional[int]     ,		_UpperCamelCase   :					Optional[int] )		->       List[Any]:





   '''simple docstring'''







   for layer_id, hf_layer in enumerate(_UpperCamelCase ):
      copy_layer(_UpperCamelCase     ,		_UpperCamelCase     ,		F'{prefix}.{layer_id}' )



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					Tuple     ,		_UpperCamelCase   :					Dict )		->       Tuple:





   '''simple docstring'''







   UpperCamelCase__			    =    pt_weights["text_projection"].data.T

   # copy text encoder
   for name, param in hf_model.text_model.named_parameters():
      UpperCamelCase__			    =    pt_weights[F'bert.{name}'].data



def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					List[str]     ,		_UpperCamelCase   :					Dict )		->       List[Any]:





   '''simple docstring'''







   UpperCamelCase__			    =    pt_weights["visual.proj"].data.T

   # copy layer norms
   copy_linear(hf_model.vision_model.pre_layrnorm     ,		_UpperCamelCase     ,		"visual.ln_pre" )
   copy_linear(hf_model.vision_model.post_layernorm     ,		_UpperCamelCase     ,		"visual.ln_post" )

   # copy embeddings
   UpperCamelCase__			    =    pt_weights["visual.conv1.weight"].data
   UpperCamelCase__			    =    pt_weights["visual.class_embedding"].data
   UpperCamelCase__			    =    pt_weights["visual.positional_embedding"].data

   # copy encoder
   copy_layers(hf_model.vision_model.encoder.layers     ,		_UpperCamelCase     ,		"visual.transformer.resblocks" )



@torch.no_grad()
def 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					int     ,		_UpperCamelCase   :					Union[str, Any]     ,		_UpperCamelCase   :					Any=None )		->       List[str]:





   '''simple docstring'''







   assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
   UpperCamelCase__			    =    ChineseCLIPConfig.from_pretrained(_UpperCamelCase )

   UpperCamelCase__			    =    ChineseCLIPModel(_UpperCamelCase ).eval()

   UpperCamelCase__			    =    torch.load(_UpperCamelCase     ,		map_location="cpu" )["state_dict"]
   UpperCamelCase__			    =    {(name[7:] if name.startswith("module." ) else name): value for name, value in pt_weights.items()}

   copy_text_model_and_projection(_UpperCamelCase     ,		_UpperCamelCase )
   copy_vision_model_and_projection(_UpperCamelCase     ,		_UpperCamelCase )
   UpperCamelCase__			    =    pt_weights["logit_scale"].data

   hf_model.save_pretrained(_UpperCamelCase )


if __name__ == "__main__":
       __lowercase:		Tuple    						=  argparse.ArgumentParser()
       parser.add_argument(
           "--pytorch_dump_folder_path",
           default=None,
           type=str,
           help="Path to the output folder storing converted hf PyTorch model.",
       )
       parser.add_argument(
           "--checkpoint_path", default=None, type=str, help="Path to original github format ChineseCLIP checkpoint."
       )
       parser.add_argument(
           "--config_path", default=None, required=True, type=str, help="Path to hf config.json of model to convert."
       )
       __lowercase:		Optional[int]    						=  parser.parse_args()

       convert_chinese_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
       print("The conversion is finished!")