

'''simple docstring'''

import json
import os
import re
import unicodedata
from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowercase__            =     logging.get_logger(__name__)

lowercase__            =     {
    "src_vocab_file": "vocab-src.json",
    "tgt_vocab_file": "vocab-tgt.json",
    "merges_file": "merges.txt",
}

lowercase__            =     {
    "src_vocab_file": {
        "stas/tiny-wmt19-en-de": "https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-src.json"
    },
    "tgt_vocab_file": {
        "stas/tiny-wmt19-en-de": "https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-tgt.json"
    },
    "merges_file": {"stas/tiny-wmt19-en-de": "https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/merges.txt"},
}

lowercase__            =     {"stas/tiny-wmt19-en-de": 1024}
lowercase__            =     {
    "stas/tiny-wmt19-en-de": {
        "langs": ["en", "de"],
        "model_max_length": 1024,
        "special_tokens_map_file": None,
        "full_tokenizer_file": None,
    }
}




def  UpperCamelCase(	UpperCAmelCase_      ):
 UpperCAmelCase			:      int		   =					set()
 UpperCAmelCase			:      Any		   =					word[0]
 for char in word[1:]:
  pairs.add((prev_char, char)      )
  UpperCAmelCase			:      str		   =					char
 return pairs




def  UpperCamelCase(	UpperCAmelCase_      ):
 UpperCAmelCase			:      Union[str, Any]		   =					text.replace('，'    ,			','      )
 UpperCAmelCase			:      int		   =					re.sub(R'。\s*'    ,			'. '    ,			UpperCAmelCase_      )
 UpperCAmelCase			:      List[str]		   =					text.replace('、'    ,			','      )
 UpperCAmelCase			:      int		   =					text.replace('”'    ,			'"'      )
 UpperCAmelCase			:      str		   =					text.replace('“'    ,			'"'      )
 UpperCAmelCase			:      Optional[int]		   =					text.replace('∶'    ,			':'      )
 UpperCAmelCase			:      Optional[int]		   =					text.replace('：'    ,			':'      )
 UpperCAmelCase			:      List[str]		   =					text.replace('？'    ,			'?'      )
 UpperCAmelCase			:      Tuple		   =					text.replace('《'    ,			'"'      )
 UpperCAmelCase			:      Any		   =					text.replace('》'    ,			'"'      )
 UpperCAmelCase			:      Optional[Any]		   =					text.replace('）'    ,			')'      )
 UpperCAmelCase			:      List[str]		   =					text.replace('！'    ,			'!'      )
 UpperCAmelCase			:      List[str]		   =					text.replace('（'    ,			'('      )
 UpperCAmelCase			:      str		   =					text.replace('；'    ,			';'      )
 UpperCAmelCase			:      List[Any]		   =					text.replace('１'    ,			'1'      )
 UpperCAmelCase			:      Optional[int]		   =					text.replace('」'    ,			'"'      )
 UpperCAmelCase			:      str		   =					text.replace('「'    ,			'"'      )
 UpperCAmelCase			:      Any		   =					text.replace('０'    ,			'0'      )
 UpperCAmelCase			:      Any		   =					text.replace('３'    ,			'3'      )
 UpperCAmelCase			:      List[Any]		   =					text.replace('２'    ,			'2'      )
 UpperCAmelCase			:      int		   =					text.replace('５'    ,			'5'      )
 UpperCAmelCase			:      Dict		   =					text.replace('６'    ,			'6'      )
 UpperCAmelCase			:      Optional[int]		   =					text.replace('９'    ,			'9'      )
 UpperCAmelCase			:      Dict		   =					text.replace('７'    ,			'7'      )
 UpperCAmelCase			:      Optional[int]		   =					text.replace('８'    ,			'8'      )
 UpperCAmelCase			:      Tuple		   =					text.replace('４'    ,			'4'      )
 UpperCAmelCase			:      Union[str, Any]		   =					re.sub(R'．\s*'    ,			'. '    ,			UpperCAmelCase_      )
 UpperCAmelCase			:      Optional[int]		   =					text.replace('～'    ,			'~'      )
 UpperCAmelCase			:      Tuple		   =					text.replace('’'    ,			'\''      )
 UpperCAmelCase			:      Union[str, Any]		   =					text.replace('…'    ,			'...'      )
 UpperCAmelCase			:      Dict		   =					text.replace('━'    ,			'-'      )
 UpperCAmelCase			:      Union[str, Any]		   =					text.replace('〈'    ,			'<'      )
 UpperCAmelCase			:      Dict		   =					text.replace('〉'    ,			'>'      )
 UpperCAmelCase			:      Union[str, Any]		   =					text.replace('【'    ,			'['      )
 UpperCAmelCase			:      Union[str, Any]		   =					text.replace('】'    ,			']'      )
 UpperCAmelCase			:      List[str]		   =					text.replace('％'    ,			'%'      )
 return text




def  UpperCamelCase(	UpperCAmelCase_      ):
 UpperCAmelCase			:      Union[str, Any]		   =					[]
 for char in text:
  UpperCAmelCase			:      int		   =					unicodedata.category(UpperCAmelCase_      )
  if cat.startswith('C'      ):
   continue
  output.append(UpperCAmelCase_      )
 return "".join(UpperCAmelCase_      )




class 			A_					(							_snake_case				):






     '''simple docstring'''



     UpperCAmelCase_		:      List[Any]    						=    VOCAB_FILES_NAMES
     UpperCAmelCase_		:      Optional[int]    						=    PRETRAINED_VOCAB_FILES_MAP
     UpperCAmelCase_		:      Dict    						=    PRETRAINED_INIT_CONFIGURATION
     UpperCAmelCase_		:      int    						=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     UpperCAmelCase_		:      Union[str, Any]    						=    ["""input_ids""", """attention_mask"""]


     def __init__(						self					:	List[Any]	,     lowercase_					:	Any=None	,     lowercase_					:	List[str]=None	,     lowercase_					:	int=None	,     lowercase_					:	Optional[int]=None	,     lowercase_					:	Tuple=False	,     lowercase_					:	Any="<unk>"	,     lowercase_					:	Optional[Any]="<s>"	,     lowercase_					:	Union[str, Any]="</s>"	,     lowercase_					:	List[Any]="<pad>"	,     **lowercase_					:	Any	,     )		->      List[Any]:
      super().__init__(
          langs=lowercase_	,     src_vocab_file=lowercase_	,     tgt_vocab_file=lowercase_	,     merges_file=lowercase_	,     do_lower_case=lowercase_	,     unk_token=lowercase_	,     bos_token=lowercase_	,     sep_token=lowercase_	,     pad_token=lowercase_	,     **lowercase_	,     )

      try:
       import sacremoses
      except ImportError:
       raise ImportError(
           'You need to install sacremoses to use XLMTokenizer. '
           'See https://pypi.org/project/sacremoses/ for installation.'			)

      UpperCAmelCase			:      Optional[Any]		   =					sacremoses

      UpperCAmelCase			:      Dict		   =					src_vocab_file
      UpperCAmelCase			:      int		   =					tgt_vocab_file
      UpperCAmelCase			:      int		   =					merges_file
      UpperCAmelCase			:      List[str]		   =					do_lower_case

      # cache of sm.MosesPunctNormalizer instance
      UpperCAmelCase			:      Optional[Any]		   =					{}
      # cache of sm.MosesTokenizer instance
      UpperCAmelCase			:      Optional[Any]		   =					{}
      UpperCAmelCase			:      Union[str, Any]		   =					{}

      if langs and len(lowercase_			) == 2:
       UpperCAmelCase   ,					UpperCAmelCase			:      str		   =					langs
      else:
       raise ValueError(
           f"""arg `langs` needs to be a list of 2 langs, e.g. ['en', 'ru'], but got {langs}. """
           'Usually that means that tokenizer can\'t find a mapping for the given model path '
           'in PRETRAINED_VOCAB_FILES_MAP, and other maps of this tokenizer.'			)

      with open(lowercase_	,     encoding='utf-8'			) as src_vocab_handle:
       UpperCAmelCase			:      Union[str, Any]		   =					json.load(lowercase_			)
      with open(lowercase_	,     encoding='utf-8'			) as tgt_vocab_handle:
       UpperCAmelCase			:      Tuple		   =					json.load(lowercase_			)
       UpperCAmelCase			:      List[Any]		   =					{v: k for k, v in tgt_vocab.items()}
      with open(lowercase_	,     encoding='utf-8'			) as merges_handle:
       UpperCAmelCase			:      str		   =					merges_handle.read().split('\n'			)[:-1]
      UpperCAmelCase			:      Tuple		   =					[tuple(merge.split()[:2]			) for merge in merges]
      UpperCAmelCase			:      Any		   =					dict(zip(lowercase_	,     range(len(lowercase_			)			)			)			)
      UpperCAmelCase			:      Dict		   =					{}


     def   UpperCAmelCase_			(						self					:	Any			)		->      Dict[str, int]:
      return self.get_src_vocab()


     @property
     def   UpperCAmelCase_			(						self					:	List[str]			)		->      int:
      return self.src_vocab_size


     def   UpperCAmelCase_			(						self					:	str	,     lowercase_					:	str	,     lowercase_					:	Union[str, Any]			)		->      Tuple:
      if lang not in self.cache_moses_punct_normalizer:
       UpperCAmelCase			:      Tuple		   =					self.sm.MosesPunctNormalizer(lang=lowercase_			)
       UpperCAmelCase			:      Dict		   =					punct_normalizer
      return self.cache_moses_punct_normalizer[lang].normalize(lowercase_			)


     def   UpperCAmelCase_			(						self					:	str	,     lowercase_					:	int	,     lowercase_					:	int			)		->      Optional[int]:
      if lang not in self.cache_moses_tokenizer:
       UpperCAmelCase			:      Optional[Any]		   =					self.sm.MosesTokenizer(lang=lowercase_			)
       UpperCAmelCase			:      Tuple		   =					moses_tokenizer
      return self.cache_moses_tokenizer[lang].tokenize(
          lowercase_	,     aggressive_dash_splits=lowercase_	,     return_str=lowercase_	,     escape=lowercase_			)


     def   UpperCAmelCase_			(						self					:	List[str]	,     lowercase_					:	Optional[int]	,     lowercase_					:	str			)		->      Tuple:
      if lang not in self.cache_moses_detokenizer:
       UpperCAmelCase			:      List[str]		   =					self.sm.MosesDetokenizer(lang=lowercase_			)
       UpperCAmelCase			:      Tuple		   =					moses_detokenizer
      return self.cache_moses_detokenizer[lang].detokenize(lowercase_			)


     def   UpperCAmelCase_			(						self					:	Dict	,     lowercase_					:	str	,     lowercase_					:	Tuple			)		->      Optional[Any]:
      UpperCAmelCase			:      int		   =					replace_unicode_punct(lowercase_			)
      UpperCAmelCase			:      int		   =					self.moses_punct_norm(lowercase_	,     lowercase_			)
      UpperCAmelCase			:      List[str]		   =					remove_non_printing_char(lowercase_			)
      return text


     @property
     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      List[str]:
      return len(self.encoder			)


     @property
     def   UpperCAmelCase_			(						self					:	Any			)		->      str:
      return len(self.decoder			)


     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      str:
      return dict(self.encoder	,     **self.added_tokens_encoder			)


     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      str:
      return dict(self.decoder	,     **self.added_tokens_decoder			)


     def   UpperCAmelCase_			(						self					:	Optional[Any]	,     lowercase_					:	Optional[int]			)		->      Optional[Any]:
      UpperCAmelCase			:      List[str]		   =					tuple(token[:-1]			) + (token[-1] + '</w>',)
      if token in self.cache:
       return self.cache[token]
      UpperCAmelCase			:      Dict		   =					get_pairs(lowercase_			)

      if not pairs:
       return token + "</w>"

      while True:
       UpperCAmelCase			:      Union[str, Any]		   =					min(lowercase_	,     key=lambda lowercase_			: self.bpe_ranks.get(lowercase_	,     float('inf'			)			)			)
       if bigram not in self.bpe_ranks:
        break
       UpperCAmelCase   ,					UpperCAmelCase			:      List[Any]		   =					bigram
       UpperCAmelCase			:      Optional[Any]		   =					[]
       UpperCAmelCase			:      str		   =					0
       while i < len(lowercase_			):
        try:
         UpperCAmelCase			:      Union[str, Any]		   =					word.index(lowercase_	,     lowercase_			)
        except ValueError:
         new_word.extend(word[i:]			)
         break
        else:
         new_word.extend(word[i:j]			)
         UpperCAmelCase			:      Union[str, Any]		   =					j

        if word[i] == first and i < len(lowercase_			) - 1 and word[i + 1] == second:
         new_word.append(first + second			)
         i += 2
        else:
         new_word.append(word[i]			)
         i += 1
       UpperCAmelCase			:      Optional[Any]		   =					tuple(lowercase_			)
       UpperCAmelCase			:      int		   =					new_word
       if len(lowercase_			) == 1:
        break
       else:
        UpperCAmelCase			:      Any		   =					get_pairs(lowercase_			)
      UpperCAmelCase			:      Optional[int]		   =					' '.join(lowercase_			)
      if word == "\n  </w>":
       UpperCAmelCase			:      List[Any]		   =					'\n</w>'
      UpperCAmelCase			:      Tuple		   =					word
      return word


     def   UpperCAmelCase_			(						self					:	Tuple	,     lowercase_					:	List[Any]	,     lowercase_					:	Tuple="en"	,     lowercase_					:	int=False			)		->      str:
      UpperCAmelCase			:      Optional[Any]		   =					self.src_lang

      if self.do_lower_case:
       UpperCAmelCase			:      Dict		   =					text.lower()

      if bypass_tokenizer:
       UpperCAmelCase			:      List[str]		   =					text.split()
      else:
       UpperCAmelCase			:      Tuple		   =					self.moses_pipeline(lowercase_	,     lang=lowercase_			)
       UpperCAmelCase			:      int		   =					self.moses_tokenize(lowercase_	,     lang=lowercase_			)

      UpperCAmelCase			:      Tuple		   =					[]
      for token in text:
       if token:
        split_tokens.extend(list(self.bpe(lowercase_			).split(' '			)			)			)

      return split_tokens


     def   UpperCAmelCase_			(						self					:	Optional[int]	,     lowercase_					:	Any			)		->      List[Any]:
      return self.encoder.get(lowercase_	,     self.encoder.get(self.unk_token			)			)


     def   UpperCAmelCase_			(						self					:	Dict	,     lowercase_					:	Tuple			)		->      Any:
      return self.decoder.get(lowercase_	,     self.unk_token			)


     def   UpperCAmelCase_			(						self					:	Tuple	,     lowercase_					:	str			)		->      Optional[Any]:
      UpperCAmelCase			:      List[str]		   =					[t.replace(' '	,     ''			).replace('</w>'	,     ' '			) for t in tokens]
      UpperCAmelCase			:      Any		   =					''.join(lowercase_			).split()
      # detokenize
      UpperCAmelCase			:      Union[str, Any]		   =					self.moses_detokenize(lowercase_	,     self.tgt_lang			)
      return text


     def   UpperCAmelCase_			(						self					:	Union[str, Any]	,     lowercase_					:	List[int]	,     lowercase_					:	Optional[List[int]] = None			)		->      List[int]:
      UpperCAmelCase			:      Dict		   =					[self.sep_token_id]

      # no bos used in fairseq
      if token_ids_a is None:
       return token_ids_a + sep
      return token_ids_a + sep + token_ids_a + sep


     def   UpperCAmelCase_			(						self					:	List[Any]	,     lowercase_					:	List[int]	,     lowercase_					:	Optional[List[int]] = None	,     lowercase_					:	bool = False			)		->      List[int]:

      if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=lowercase_	,     token_ids_a=lowercase_	,     already_has_special_tokens=lowercase_			)
      # no bos used in fairseq
      if token_ids_a is not None:
       return ([0] * len(lowercase_			)) + [1] + ([0] * len(lowercase_			)) + [1]
      return ([0] * len(lowercase_			)) + [1]


     def   UpperCAmelCase_			(						self					:	Optional[Any]	,     lowercase_					:	List[int]	,     lowercase_					:	Optional[List[int]] = None			)		->      List[int]:
      UpperCAmelCase			:      str		   =					[self.sep_token_id]

      # no bos used in fairseq
      if token_ids_a is None:
       return len(token_ids_a + sep			) * [0]
      return len(token_ids_a + sep			) * [0] + len(token_ids_a + sep			) * [1]


     def   UpperCAmelCase_			(						self					:	List[str]	,     lowercase_					:	str	,     lowercase_					:	Optional[str] = None			)		->      Tuple[str]:
      if not os.path.isdir(lowercase_			):
       logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""			)
       return

      UpperCAmelCase			:      int		   =					os.path.join(
          lowercase_	,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['src_vocab_file']			)
      UpperCAmelCase			:      List[str]		   =					os.path.join(
          lowercase_	,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['tgt_vocab_file']			)
      UpperCAmelCase			:      Optional[Any]		   =					os.path.join(
          lowercase_	,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']			)

      with open(lowercase_	,     'w'	,     encoding='utf-8'			) as f:
       f.write(json.dumps(self.encoder	,     indent=2	,     sort_keys=lowercase_	,     ensure_ascii=lowercase_			) + '\n'			)

      with open(lowercase_	,     'w'	,     encoding='utf-8'			) as f:
       UpperCAmelCase			:      Dict		   =					{v: k for k, v in self.decoder.items()}
       f.write(json.dumps(lowercase_	,     indent=2	,     sort_keys=lowercase_	,     ensure_ascii=lowercase_			) + '\n'			)

      UpperCAmelCase			:      List[str]		   =					0
      with open(lowercase_	,     'w'	,     encoding='utf-8'			) as writer:
       for bpe_tokens, token_index in sorted(self.bpe_ranks.items()	,     key=lambda lowercase_			: kv[1]			):
        if index != token_index:
         logger.warning(
             f"""Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."""
             ' Please check that the tokenizer is not corrupted!'			)
         UpperCAmelCase			:      Any		   =					token_index
        writer.write(' '.join(lowercase_			) + '\n'			)
        index += 1

      return src_vocab_file, tgt_vocab_file, merges_file


     def __getstate__(						self					:	int			)		->      List[str]:
      UpperCAmelCase			:      List[Any]		   =					self.__dict__.copy()
      UpperCAmelCase			:      int		   =					None
      return state




     def __setstate__(						self					:	Optional[Any]	,     lowercase_					:	str			)		->      str:
      UpperCAmelCase			:      int		   =					d

      try:
       import sacremoses
      except ImportError:
       raise ImportError(
           'You need to install sacremoses to use XLMTokenizer. '
           'See https://pypi.org/project/sacremoses/ for installation.'			)

      UpperCAmelCase			:      Union[str, Any]		   =					sacremoses







'''simple docstring'''

import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_      ):
 UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase			:      Optional[Any]		   =					pt_weights[F"""{prefix}.in_proj_weight"""].chunk(3    ,			dim=0      )
 UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase			:      str		   =					pt_weights[F"""{prefix}.in_proj_bias"""].chunk(3    ,			dim=0      )

 UpperCAmelCase			:      Dict		   =					pt_weights[F"""{prefix}.out_proj.weight"""]
 UpperCAmelCase			:      Tuple		   =					pt_weights[F"""{prefix}.out_proj.bias"""]

 UpperCAmelCase			:      Dict		   =					q_proj
 UpperCAmelCase			:      Optional[Any]		   =					q_proj_bias

 UpperCAmelCase			:      Union[str, Any]		   =					k_proj
 UpperCAmelCase			:      Optional[Any]		   =					k_proj_bias

 UpperCAmelCase			:      Dict		   =					v_proj
 UpperCAmelCase			:      Tuple		   =					v_proj_bias

 UpperCAmelCase			:      List[Any]		   =					out_proj_weights
 UpperCAmelCase			:      Any		   =					out_proj_bias




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_      ):
 copy_linear(hf_mlp.fca    ,			UpperCAmelCase_    ,			F"""{prefix}.c_fc"""      )
 copy_linear(hf_mlp.fca    ,			UpperCAmelCase_    ,			F"""{prefix}.c_proj"""      )




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_      ):
 UpperCAmelCase			:      Tuple		   =					pt_weights[F"""{prefix}.weight"""].data
 UpperCAmelCase			:      Dict		   =					pt_weights[F"""{prefix}.bias"""].data




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_      ):
 # copy layer norms
 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  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_      ):
 for layer_id, hf_layer in enumerate(UpperCAmelCase_      ):
  copy_layer(UpperCAmelCase_    ,			UpperCAmelCase_    ,			F"""{prefix}.{layer_id}"""      )




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_      ):
 # copy projection
 UpperCAmelCase			:      Optional[int]		   =					pt_weights['text_projection'].data.T

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




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_      ):
 # copy projection
 UpperCAmelCase			:      Optional[int]		   =					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			:      List[str]		   =					pt_weights['visual.conv1.weight'].data
 UpperCAmelCase			:      Tuple		   =					pt_weights['visual.class_embedding'].data
 UpperCAmelCase			:      str		   =					pt_weights['visual.positional_embedding'].data

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




@torch.no_grad()
def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_=None      ):
 assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
 UpperCAmelCase			:      str		   =					ChineseCLIPConfig.from_pretrained(UpperCAmelCase_      )

 UpperCAmelCase			:      List[Any]		   =					ChineseCLIPModel(UpperCAmelCase_      ).eval()

 UpperCAmelCase			:      Optional[Any]		   =					torch.load(UpperCAmelCase_    ,			map_location='cpu'      )['state_dict']
 UpperCAmelCase			:      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_      )
 UpperCAmelCase			:      Optional[int]		   =					pt_weights['logit_scale'].data

 hf_model.save_pretrained(UpperCAmelCase_      )


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

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




