





import argparse

import torch
from clip import load

from transformers import CLIPConfig, CLIPModel


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Optional[int]     ,							__lowercase:		Optional[int]):



  '''simple docstring'''






  __lowerCAmelCase	,						__lowerCAmelCase	,						__lowerCAmelCase			=				pt_attn_layer.in_proj_weight.chunk(3     ,							dim=0)
  __lowerCAmelCase	,						__lowerCAmelCase	,						__lowerCAmelCase			=				pt_attn_layer.in_proj_bias.chunk(3     ,							dim=0)

  __lowerCAmelCase			=				pt_attn_layer.out_proj.weight
  __lowerCAmelCase			=				pt_attn_layer.out_proj.bias

  __lowerCAmelCase			=				q_proj
  __lowerCAmelCase			=				q_proj_bias

  __lowerCAmelCase			=				k_proj
  __lowerCAmelCase			=				k_proj_bias

  __lowerCAmelCase			=				v_proj
  __lowerCAmelCase			=				v_proj_bias

  __lowerCAmelCase			=				out_proj_weights
  __lowerCAmelCase			=				out_proj_bias


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Any     ,							__lowercase:		Optional[int]):



  '''simple docstring'''






  copy_linear(hf_mlp.fca     ,							pt_mlp.c_fc)
  copy_linear(hf_mlp.fca     ,							pt_mlp.c_proj)


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Optional[int]     ,							__lowercase:		Dict):



  '''simple docstring'''






  __lowerCAmelCase			=				pt_linear.weight
  __lowerCAmelCase			=				pt_linear.bias


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Optional[Any]     ,							__lowercase:		Any):



  '''simple docstring'''






  copy_linear(hf_layer.layer_norma     ,							pt_layer.ln_a)
  copy_linear(hf_layer.layer_norma     ,							pt_layer.ln_a)

  # copy MLP
  copy_mlp(hf_layer.mlp     ,							pt_layer.mlp)

  # copy attn
  copy_attn_layer(hf_layer.self_attn     ,							pt_layer.attn)


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Optional[int]     ,							__lowercase:		List[Any]):



  '''simple docstring'''






  for hf_layer, pt_layer in zip(__lowercase     ,							__lowercase):
    copy_layer(__lowercase     ,							__lowercase)


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Any     ,							__lowercase:		Tuple):



  '''simple docstring'''






  __lowerCAmelCase			=				pt_model.token_embedding.weight
  __lowerCAmelCase			=				pt_model.positional_embedding

  # copy layer norm
  copy_linear(hf_encoder.final_layer_norm     ,							pt_model.ln_final)

  # copy hidden layers
  copy_layers(hf_encoder.encoder.layers     ,							pt_model.transformer.resblocks)


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Tuple     ,							__lowercase:		Any):



  '''simple docstring'''






  __lowerCAmelCase			=				pt_model.text_projection.data.T

  # copy text encoder
  copy_encoder(hf_model.text_model     ,							__lowercase)


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Optional[Any]     ,							__lowercase:		Optional[Any]):



  '''simple docstring'''






  __lowerCAmelCase			=				pt_model.visual.proj.data.T

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

  # copy embeds
  __lowerCAmelCase			=				pt_model.visual.conva.weight.data
  __lowerCAmelCase			=				pt_model.visual.class_embedding
  __lowerCAmelCase			=				pt_model.visual.positional_embedding.data

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


@torch.no_grad()
def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		Union[str, Any]     ,							__lowercase:		Tuple     ,							__lowercase:		List[Any]=None):



  '''simple docstring'''






  if config_path is not None:
    __lowerCAmelCase			=				CLIPConfig.from_pretrained(__lowercase)
  else:
    __lowerCAmelCase			=				CLIPConfig(projection_dim=5_12     ,							text_config={}     ,							vision_config={})

  __lowerCAmelCase			=				CLIPModel(__lowercase).eval()

  __lowerCAmelCase	,						__lowerCAmelCase			=				load(__lowercase     ,							device='''cpu'''     ,							jit=__lowercase)
  __lowerCAmelCase			=				pt_model.eval()

  copy_text_model_and_projection(__lowercase     ,							__lowercase)
  copy_vison_model_and_projection(__lowercase     ,							__lowercase)
  __lowerCAmelCase			=				pt_model.logit_scale

  __lowerCAmelCase			=				torch.arange(0     ,							77).unsqueeze(0)
  __lowerCAmelCase			=				torch.randn(1     ,							3     ,							2_24     ,							2_24)

  __lowerCAmelCase			=				hf_model(input_ids=__lowercase     ,							pixel_values=__lowercase     ,							return_dict=__lowercase)
  __lowerCAmelCase			=				hf_outputs.logits_per_image
  __lowerCAmelCase			=				hf_outputs.logits_per_text
  __lowerCAmelCase	,						__lowerCAmelCase			=				pt_model(__lowercase     ,							__lowercase)

  assert torch.allclose(__lowercase     ,							__lowercase     ,							atol=1E-3)
  assert torch.allclose(__lowercase     ,							__lowercase     ,							atol=1E-3)

  hf_model.save_pretrained(__lowercase)


if __name__ == "__main__":
      __lowercase													=			argparse.ArgumentParser()
      parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
      parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
      parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
      __lowercase													=			parser.parse_args()

      convert_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)







import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand

class   __snake_case				(			_a   ):






    '''simple docstring'''





    @staticmethod
    def 	A		(   snake_case						:		ArgumentParser							):

      """simple docstring"""





      __lowerCAmelCase			=				parser.add_parser('''login'''			,						help='''Log in using the same credentials as on huggingface.co'''							)
      login_parser.set_defaults(func=lambda snake_case							: LoginCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''whoami'''			,						help='''Find out which huggingface.co account you are logged in as.'''							)
      whoami_parser.set_defaults(func=lambda snake_case							: WhoamiCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''logout'''			,						help='''Log out'''							)
      logout_parser.set_defaults(func=lambda snake_case							: LogoutCommand(snake_case							)							)

      # new system: git-based repo system
      __lowerCAmelCase			=				parser.add_parser(
          '''repo'''			,						help='''Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.'''			,						)
      __lowerCAmelCase			=				repo_parser.add_subparsers(
          help='''Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands'''							)
      __lowerCAmelCase			=				repo_subparsers.add_parser(
          '''create'''			,						help='''Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co'''							)
      repo_create_parser.add_argument(
          '''name'''			,						type=snake_case			,						help='''Name for your model\'s repo. Will be namespaced under your username to build the model id.'''			,						)
      repo_create_parser.add_argument('''--organization'''			,						type=snake_case			,						help='''Optional: organization namespace.'''							)
      repo_create_parser.add_argument('''-y'''			,						'''--yes'''			,						action='''store_true'''			,						help='''Optional: answer Yes to the prompt'''							)
      repo_create_parser.set_defaults(func=lambda snake_case							: RepoCreateCommand(snake_case							)							)


class   __snake_case				:






    '''simple docstring'''
    _lowerCAmelCase     =	"""\u001b[1m"""
    _lowerCAmelCase     =	"""\u001b[31m"""
    _lowerCAmelCase     =	"""\u001b[90m"""
    _lowerCAmelCase     =	"""\u001b[0m"""





    @classmethod
    def 	A		(   cls						:		str			,						snake_case						:		Optional[int]							):

      """simple docstring"""





      return f'''{cls._bold}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Optional[Any]			,						snake_case						:		str							):

      """simple docstring"""





      return f'''{cls._bold}{cls._red}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Dict			,						snake_case						:		List[Any]							):

      """simple docstring"""





      return f'''{cls._gray}{s}{cls._reset}'''


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		List[List[Union[str, int]]]     ,							__lowercase:		List[str]):



  '''simple docstring'''






  __lowerCAmelCase			=				[max(len(str(__lowercase)) for x in col) for col in zip(*__lowercase     ,							__lowercase)]
  __lowerCAmelCase			=				('''{{:{}}} ''' * len(__lowercase)).format(*__lowercase)
  __lowerCAmelCase			=				[]
  lines.append(row_format.format(*__lowercase))
  lines.append(row_format.format(*['''-''' * w for w in col_widths]))
  for row in rows:
    lines.append(row_format.format(*__lowercase))
  return "\n".join(__lowercase)

class   __snake_case				:






    '''simple docstring'''





    def __init__(   self						:		List[str]			,						snake_case						:		List[str]							):

      """simple docstring"""





      __lowerCAmelCase			=				args


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		List[Any]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `huggingface-cli login` uses an outdated login mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli login instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		int							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use '''
              '''`huggingface-cli whoami` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit()
      try:
        __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
        print(snake_case							)
        if orgs:
          print(ANSI.bold('''orgs: '''							)			,						''','''.join(snake_case							)							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Any							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `transformers-cli logout` uses an outdated logout mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli logout instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Optional[int]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! Managing repositories through transformers-cli is deprecated. '''
              '''Please use `huggingface-cli` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit(1							)
      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print('''Looks like you do not have git installed, please install.'''							)

      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git-lfs''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print(
            ANSI.red(
                '''Looks like you do not have git-lfs installed, please install.'''
                ''' You can install from https://git-lfs.github.com/.'''
                ''' Then run `git lfs install` (you only have to do this once).'''							)							)
      print(''''''							)

      __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
      __lowerCAmelCase			=				self.args.organization if self.args.organization is not None else user
      __lowerCAmelCase			=				f'''{namespace}/{self.args.name}'''
      print(f'''You are about to create {ANSI.bold(snake_case							)}'''							)

      if not self.args.yes:
        __lowerCAmelCase			=				input('''Proceed? [Y/n] '''							).lower()
        if not (choice == "" or choice == "y" or choice == "yes"):
          print('''Abort'''							)
          exit()
      try:
        __lowerCAmelCase			=				create_repo(snake_case			,						name=self.args.name			,						organization=self.args.organization							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)
      print('''\nYour repo now lives at:'''							)
      print(f'''  {ANSI.bold(snake_case							)}'''							)
      print('''\nYou can clone it locally with the command below, and commit/push as usual.'''							)
      print(f'''\n  git clone {url}'''							)
      print(''''''							)
