





from __future__ import annotations


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Dict:
    SCREAMING_SNAKE_CASE__       							= "", "", ""
    SCREAMING_SNAKE_CASE__       							= []

    for character in message_part:
        tmp.append(character_to_number[character]  )

    for each in tmp:
        one += each[0]
        two += each[1]
        three += each[2]

    return one + two + three


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_  )							->	List[str]:
    SCREAMING_SNAKE_CASE__       							= "", ""
    SCREAMING_SNAKE_CASE__       							= []

    for character in message_part:
        this_part += character_to_number[character]

    for digit in this_part:
        tmp += digit
        if len(lowerCAmelCase_  ) == len(lowerCAmelCase_  ):
            result.append(lowerCAmelCase_  )
            SCREAMING_SNAKE_CASE__       							= ""

    return result[0], result[1], result[2]


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Optional[int]:
    SCREAMING_SNAKE_CASE__       							= alphabet.replace(''' '''   ,       ''''''  ).upper()
    SCREAMING_SNAKE_CASE__       							= message.replace(''' '''   ,       ''''''  ).upper()

    # Check length and characters
    if len(lowerCAmelCase_  ) != 2_7:
        raise KeyError('''Length of alphabet has to be 27.'''  )
    for each in message:
        if each not in alphabet:
            raise ValueError('''Each message character has to be included in alphabet!'''  )

        # Generate dictionares
    SCREAMING_SNAKE_CASE__       							= (
        "111",
        "112",
        "113",
        "121",
        "122",
        "123",
        "131",
        "132",
        "133",
        "211",
        "212",
        "213",
        "221",
        "222",
        "223",
        "231",
        "232",
        "233",
        "311",
        "312",
        "313",
        "321",
        "322",
        "323",
        "331",
        "332",
        "333",
    )
    SCREAMING_SNAKE_CASE__       							= {}
    SCREAMING_SNAKE_CASE__       							= {}
    for letter, number in zip(lowerCAmelCase_   ,       lowerCAmelCase_  ):
        SCREAMING_SNAKE_CASE__       							= number
        SCREAMING_SNAKE_CASE__       							= letter

    return message, alphabet, character_to_number, number_to_character


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ."   ,       lowerCAmelCase_ = 5  )							->	Dict:
    SCREAMING_SNAKE_CASE__       							= __prepare(
        lowerCAmelCase_   ,       lowerCAmelCase_  )
    SCREAMING_SNAKE_CASE__       							= "", ""

    for i in range(0   ,       len(lowerCAmelCase_  ) + 1   ,       lowerCAmelCase_  ):
        encrypted_numeric += __encrypt_part(
            message[i : i + period]   ,       lowerCAmelCase_  )

    for i in range(0   ,       len(lowerCAmelCase_  )   ,       3  ):
        encrypted += number_to_character[encrypted_numeric[i : i + 3]]

    return encrypted


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ."   ,       lowerCAmelCase_ = 5  )							->	str:
    SCREAMING_SNAKE_CASE__       							= __prepare(
        lowerCAmelCase_   ,       lowerCAmelCase_  )
    SCREAMING_SNAKE_CASE__       							= []
    SCREAMING_SNAKE_CASE__       							= ""

    for i in range(0   ,       len(lowerCAmelCase_  ) + 1   ,       lowerCAmelCase_  ):
        SCREAMING_SNAKE_CASE__       							= __decrypt_part(message[i : i + period]   ,       lowerCAmelCase_  )

        for j in range(0   ,       len(lowerCAmelCase_  )  ):
            decrypted_numeric.append(a[j] + b[j] + c[j]  )

    for each in decrypted_numeric:
        decrypted += number_to_character[each]

    return decrypted


if __name__ == "__main__":
  _A							= """DEFEND THE EAST WALL OF THE CASTLE."""
  _A							= encrypt_message(msg, """EPSDUCVWYM.ZLKXNBTFGORIJHAQ""")
  _A							= decrypt_message(encrypted, """EPSDUCVWYM.ZLKXNBTFGORIJHAQ""")
  print(F'Encrypted: {encrypted}\nDecrypted: {decrypted}')







import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	str:
    SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.in_proj_weight'''].chunk(3   ,       dim=0  )
    SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.in_proj_bias'''].chunk(3   ,       dim=0  )

    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.out_proj.weight''']
    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.out_proj.bias''']

    SCREAMING_SNAKE_CASE__       							= q_proj
    SCREAMING_SNAKE_CASE__       							= q_proj_bias

    SCREAMING_SNAKE_CASE__       							= k_proj
    SCREAMING_SNAKE_CASE__       							= k_proj_bias

    SCREAMING_SNAKE_CASE__       							= v_proj
    SCREAMING_SNAKE_CASE__       							= v_proj_bias

    SCREAMING_SNAKE_CASE__       							= out_proj_weights
    SCREAMING_SNAKE_CASE__       							= out_proj_bias


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Dict:
    copy_linear(hf_mlp.fca   ,       lowerCAmelCase_   ,       f'''{prefix}.c_fc'''  )
    copy_linear(hf_mlp.fca   ,       lowerCAmelCase_   ,       f'''{prefix}.c_proj'''  )


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	str:
    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.weight'''].data
    SCREAMING_SNAKE_CASE__       							= pt_weights[f'''{prefix}.bias'''].data


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Dict:
    # copy layer norms
    copy_linear(hf_layer.layer_norma   ,       lowerCAmelCase_   ,       f'''{prefix}.ln_1'''  )
    copy_linear(hf_layer.layer_norma   ,       lowerCAmelCase_   ,       f'''{prefix}.ln_2'''  )

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

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


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Optional[int]:
    for layer_id, hf_layer in enumerate(lowerCAmelCase_  ):
        copy_layer(lowerCAmelCase_   ,       lowerCAmelCase_   ,       f'''{prefix}.{layer_id}'''  )


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_  )							->	Any:
    # copy projection
    SCREAMING_SNAKE_CASE__       							= pt_weights['''text_projection'''].data.T

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


def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_  )							->	List[str]:
    # copy projection
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.proj'''].data.T

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

    # copy embeddings
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.conv1.weight'''].data
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.class_embedding'''].data
    SCREAMING_SNAKE_CASE__       							= pt_weights['''visual.positional_embedding'''].data

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


@torch.no_grad()
def        __snake_case       (						lowerCAmelCase_   ,       lowerCAmelCase_   ,       lowerCAmelCase_=None  )							->	str:
    assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
    SCREAMING_SNAKE_CASE__       							= ChineseCLIPConfig.from_pretrained(lowerCAmelCase_  )

    SCREAMING_SNAKE_CASE__       							= ChineseCLIPModel(lowerCAmelCase_  ).eval()

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

    copy_text_model_and_projection(lowerCAmelCase_   ,       lowerCAmelCase_  )
    copy_vision_model_and_projection(lowerCAmelCase_   ,       lowerCAmelCase_  )
    SCREAMING_SNAKE_CASE__       							= pt_weights['''logit_scale'''].data

    hf_model.save_pretrained(lowerCAmelCase_  )


if __name__ == "__main__":
  _A				:							Union[str, Any]							= 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				:							Union[str, Any]							= parser.parse_args()

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