






import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel



def        _lowerCamelCase(      lowerCAmelCase__					:		int     ,     lowerCAmelCase__					:		List[str]     ,     lowerCAmelCase__					:		List[str]   ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Dict    				= pt_weights[F'''{prefix}.in_proj_weight'''].chunk(3     ,     dim=0   )
				SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= pt_weights[F'''{prefix}.in_proj_bias'''].chunk(3     ,     dim=0   )

				SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= pt_weights[F'''{prefix}.out_proj.weight''']
				SCREAMING_SNAKE_CASE_ :						str    				= pt_weights[F'''{prefix}.out_proj.bias''']

				SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= q_proj
				SCREAMING_SNAKE_CASE_ :						int    				= q_proj_bias

				SCREAMING_SNAKE_CASE_ :						Any    				= k_proj
				SCREAMING_SNAKE_CASE_ :						str    				= k_proj_bias

				SCREAMING_SNAKE_CASE_ :						Dict    				= v_proj
				SCREAMING_SNAKE_CASE_ :						List[Any]    				= v_proj_bias

				SCREAMING_SNAKE_CASE_ :						Optional[int]    				= out_proj_weights
				SCREAMING_SNAKE_CASE_ :						Dict    				= out_proj_bias



def        _lowerCamelCase(      lowerCAmelCase__					:		Union[str, Any]     ,     lowerCAmelCase__					:		List[str]     ,     lowerCAmelCase__					:		Dict   ):





				'''simple docstring'''







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



def        _lowerCamelCase(      lowerCAmelCase__					:		Tuple     ,     lowerCAmelCase__					:		str     ,     lowerCAmelCase__					:		Optional[int]   ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= pt_weights[F'''{prefix}.weight'''].data
				SCREAMING_SNAKE_CASE_ :						Any    				= pt_weights[F'''{prefix}.bias'''].data



def        _lowerCamelCase(      lowerCAmelCase__					:		int     ,     lowerCAmelCase__					:		List[Any]     ,     lowerCAmelCase__					:		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        _lowerCamelCase(      lowerCAmelCase__					:		Tuple     ,     lowerCAmelCase__					:		Optional[int]     ,     lowerCAmelCase__					:		Optional[int]   ):





				'''simple docstring'''







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



def        _lowerCamelCase(      lowerCAmelCase__					:		Tuple     ,     lowerCAmelCase__					:		Dict   ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_ :						Tuple    				= pt_weights['text_projection'].data.T

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



def        _lowerCamelCase(      lowerCAmelCase__					:		List[str]     ,     lowerCAmelCase__					:		Dict   ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_ :						Tuple    				= 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
				SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= pt_weights['visual.conv1.weight'].data
				SCREAMING_SNAKE_CASE_ :						Optional[int]    				= pt_weights['visual.class_embedding'].data
				SCREAMING_SNAKE_CASE_ :						List[Any]    				= pt_weights['visual.positional_embedding'].data

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



@torch.no_grad()
def        _lowerCamelCase(      lowerCAmelCase__					:		int     ,     lowerCAmelCase__					:		Union[str, Any]     ,     lowerCAmelCase__					:		Any=None   ):





				'''simple docstring'''







				assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
				SCREAMING_SNAKE_CASE_ :						List[str]    				= ChineseCLIPConfig.from_pretrained(_UpperCamelCase   )

				SCREAMING_SNAKE_CASE_ :						str    				= ChineseCLIPModel(_UpperCamelCase   ).eval()

				SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= torch.load(_UpperCamelCase     ,     map_location='cpu'   )['state_dict']
				SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= {(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   )
				SCREAMING_SNAKE_CASE_ :						Dict    				= pt_weights['logit_scale'].data

				hf_model.save_pretrained(_UpperCamelCase   )


if __name__ == "__main__":
				A										=      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.'
				)
				A										=      parser.parse_args()

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



'''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"],
        ),       )