


import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel




def       a__						(		snake_case__				:       str	,      snake_case__				:       str	,      snake_case__				:       Optional[int]    ):
  _UpperCAmelCase		:       Optional[int]       =    pt_weights[f'''{prefix}.in_proj_weight'''].chunk(3	,      dim=0    )
  _UpperCAmelCase		:       List[str]       =    pt_weights[f'''{prefix}.in_proj_bias'''].chunk(3	,      dim=0    )

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

  _UpperCAmelCase		:       Dict       =    q_proj
  _UpperCAmelCase		:       Optional[int]       =    q_proj_bias

  _UpperCAmelCase		:       List[Any]       =    k_proj
  _UpperCAmelCase		:       Union[str, Any]       =    k_proj_bias

  _UpperCAmelCase		:       Union[str, Any]       =    v_proj
  _UpperCAmelCase		:       Optional[Any]       =    v_proj_bias

  _UpperCAmelCase		:       Optional[int]       =    out_proj_weights
  _UpperCAmelCase		:       Tuple       =    out_proj_bias




def       a__						(		snake_case__				:       Tuple	,      snake_case__				:       Tuple	,      snake_case__				:       Any    ):
  copy_linear(hf_mlp.fca	,      _SCREAMING_SNAKE_CASE	,      f'''{prefix}.c_fc'''    )
  copy_linear(hf_mlp.fca	,      _SCREAMING_SNAKE_CASE	,      f'''{prefix}.c_proj'''    )




def       a__						(		snake_case__				:       Tuple	,      snake_case__				:       List[str]	,      snake_case__				:       Any    ):
  _UpperCAmelCase		:       Tuple       =    pt_weights[f'''{prefix}.weight'''].data
  _UpperCAmelCase		:       int       =    pt_weights[f'''{prefix}.bias'''].data




def       a__						(		snake_case__				:       Union[str, Any]	,      snake_case__				:       List[str]	,      snake_case__				:       Union[str, Any]    ):
  # copy layer norms
  copy_linear(hf_layer.layer_norma	,      _SCREAMING_SNAKE_CASE	,      f'''{prefix}.ln_1'''    )
  copy_linear(hf_layer.layer_norma	,      _SCREAMING_SNAKE_CASE	,      f'''{prefix}.ln_2'''    )

  # copy MLP
  copy_mlp(hf_layer.mlp	,      _SCREAMING_SNAKE_CASE	,      f'''{prefix}.mlp'''    )

  # copy attn
  copy_attn_layer(hf_layer.self_attn	,      _SCREAMING_SNAKE_CASE	,      f'''{prefix}.attn'''    )




def       a__						(		snake_case__				:       Dict	,      snake_case__				:       Dict	,      snake_case__				:       Optional[int]    ):
  for layer_id, hf_layer in enumerate(_SCREAMING_SNAKE_CASE    ):
    copy_layer(_SCREAMING_SNAKE_CASE	,      _SCREAMING_SNAKE_CASE	,      f'''{prefix}.{layer_id}'''    )




def       a__						(		snake_case__				:       Union[str, Any]	,      snake_case__				:       List[str]    ):
  # copy projection
  _UpperCAmelCase		:       Optional[Any]       =    pt_weights['text_projection'].data.T

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




def       a__						(		snake_case__				:       Any	,      snake_case__				:       Optional[Any]    ):
  # copy projection
  _UpperCAmelCase		:       Any       =    pt_weights['visual.proj'].data.T

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

  # copy embeddings
  _UpperCAmelCase		:       int       =    pt_weights['visual.conv1.weight'].data
  _UpperCAmelCase		:       Dict       =    pt_weights['visual.class_embedding'].data
  _UpperCAmelCase		:       List[Any]       =    pt_weights['visual.positional_embedding'].data

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




@torch.no_grad()
def       a__						(		snake_case__				:       Union[str, Any]	,      snake_case__				:       Tuple	,      snake_case__				:       List[Any]=None    ):
  assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
  _UpperCAmelCase		:       int       =    ChineseCLIPConfig.from_pretrained(_SCREAMING_SNAKE_CASE    )

  _UpperCAmelCase		:       int       =    ChineseCLIPModel(_SCREAMING_SNAKE_CASE    ).eval()

  _UpperCAmelCase		:       Any       =    torch.load(_SCREAMING_SNAKE_CASE	,      map_location="""cpu"""    )['state_dict']
  _UpperCAmelCase		:       Union[str, Any]       =    {(name[7:] if name.startswith("""module."""    ) else name): value for name, value in pt_weights.items()}

  copy_text_model_and_projection(_SCREAMING_SNAKE_CASE	,      _SCREAMING_SNAKE_CASE    )
  copy_vision_model_and_projection(_SCREAMING_SNAKE_CASE	,      _SCREAMING_SNAKE_CASE    )
  _UpperCAmelCase		:       Any       =    pt_weights['logit_scale'].data

  hf_model.save_pretrained(_SCREAMING_SNAKE_CASE    )


if __name__ == "__main__":
   SCREAMING_SNAKE_CASE__				:    Optional[int]         =    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.'
   )
   SCREAMING_SNAKE_CASE__				:    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!')









import os

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

SCREAMING_SNAKE_CASE__				:    int         =    {'UserAgent': UserAgent().random}
SCREAMING_SNAKE_CASE__				:    Tuple         =    'https://www.mywaifulist.moe/random'




def       a__						(		snake_case__				:       str	,      snake_case__				:       str    ):
  _UpperCAmelCase		:       Any       =    requests.get(snake_case__	,      headers=snake_case__    )
  with open(snake_case__	,      """wb"""    ) as file:
    file.write(image.content    )




def       a__						(		):
  _UpperCAmelCase		:       List[Any]       =    BeautifulSoup(requests.get(snake_case__	,      headers=snake_case__    ).text	,      """html.parser"""    )
  _UpperCAmelCase		:       Optional[int]       =    soup.find("""meta"""	,      attrs={"""property""": """og:title"""}    ).attrs["""content"""]
  _UpperCAmelCase		:       int       =    soup.find("""meta"""	,      attrs={"""property""": """og:image"""}    ).attrs["""content"""]
  _UpperCAmelCase		:       Any       =    soup.find("""p"""	,      id="""description"""    ).get_text()
  _UpperCAmelCase,_UpperCAmelCase		:       Dict       =    os.path.splitext(os.path.basename(snake_case__    )    )
  _UpperCAmelCase		:       Tuple       =    title.strip().replace(""" """	,      """_"""    )
  _UpperCAmelCase		:       Optional[Any]       =    f'''{image_title}{image_extension}'''
  save_image(snake_case__	,      snake_case__    )
  return (title, description, image_title)


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE__     ,				SCREAMING_SNAKE_CASE__     ,				SCREAMING_SNAKE_CASE__				:    Optional[int]         =    random_anime_character()
 print(F'{title}\n\n{desc}\n\nImage saved : {image_title}')





