"""simple docstring"""




from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


_a :						Any			       =  logging.get_logger(__name__)
class 		__A				(					lowerCamelCase__						):






     def        __A    (						self							,	a__    ):





       if isinstance(a__							,	a__    ):
         _lowerCAmelCase		:			Tuple         =	[label.strip() for label in labels.split(""","""    ) if label.strip()]
       return labels






     def __call__(						self							,	a__							,	a__							,	a__    ):





       if len(a__    ) == 0 or len(a__    ) == 0:
         raise ValueError("""You must include at least one label and at least one sequence."""    )
       if hypothesis_template.format(labels[0]    ) == hypothesis_template:
         raise ValueError(
             (
                 """The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. """
                 """Make sure the passed template includes formatting syntax such as {{}} where the label should go."""
             ).format(a__    )    )

       if isinstance(a__							,	a__    ):
         _lowerCAmelCase		:			List[Any]         =	[sequences]

       _lowerCAmelCase		:			List[Any]         =	[]
       for sequence in sequences:
         sequence_pairs.extend([[sequence, hypothesis_template.format(a__    )] for label in labels]    )

       return sequence_pairs, sequences







@add_end_docstrings(lowerCamelCase__						)
class 		__A				(					lowerCamelCase__						):






     def __init__(						self							,	a__=ZeroShotClassificationArgumentHandler()							,	*a__							,	**a__    ):
       _lowerCAmelCase		:			int         =	args_parser
       super().__init__(*a__							,	**a__    )
       if self.entailment_id == -1:
         logger.warning(
             """Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to """
             """-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."""    )






     @property
     def        __A    (						self    ):





       for label, ind in self.model.config.labelaid.items():
         if label.lower().startswith("""entail"""    ):
           return ind
       return -1






     def        __A    (						self							,	a__							,	a__=True							,	a__=True							,	a__=TruncationStrategy.ONLY_FIRST							,	**a__    ):
       _lowerCAmelCase		:			Optional[Any]         =	self.framework
       if self.tokenizer.pad_token is None:
         # Override for tokenizers not supporting padding
         logger.error(
             """Tokenizer was not supporting padding necessary for zero-shot, attempting to use """
             """ `pad_token=eos_token`"""    )
         _lowerCAmelCase		:			Optional[Any]         =	self.tokenizer.eos_token
       try:
         _lowerCAmelCase		:			Any         =	self.tokenizer(
             a__							,	add_special_tokens=a__							,	return_tensors=a__							,	padding=a__							,	truncation=a__							,	)
       except Exception as e:
         if "too short" in str(a__    ):
           # tokenizers might yell that we want to truncate
           # to a value that is not even reached by the input.
           # In that case we don't want to truncate.
           # It seems there's not a really better way to catch that
           # exception.

           _lowerCAmelCase		:			Optional[int]         =	self.tokenizer(
               a__							,	add_special_tokens=a__							,	return_tensors=a__							,	padding=a__							,	truncation=TruncationStrategy.DO_NOT_TRUNCATE							,	)
         else:
           raise e

       return inputs






     def        __A    (						self							,	**a__    ):





       if kwargs.get("""multi_class"""							,	a__    ) is not None:
         _lowerCAmelCase		:			Union[str, Any]         =	kwargs['''multi_class''']
         logger.warning(
             """The `multi_class` argument has been deprecated and renamed to `multi_label`. """
             """`multi_class` will be removed in a future version of Transformers."""    )
       _lowerCAmelCase		:			Union[str, Any]         =	{}
       if "candidate_labels" in kwargs:
         _lowerCAmelCase		:			List[Any]         =	self._args_parser._parse_labels(kwargs["""candidate_labels"""]    )
       if "hypothesis_template" in kwargs:
         _lowerCAmelCase		:			List[Any]         =	kwargs['''hypothesis_template''']

       _lowerCAmelCase		:			Tuple         =	{}
       if "multi_label" in kwargs:
         _lowerCAmelCase		:			Union[str, Any]         =	kwargs['''multi_label''']
       return preprocess_params, {}, postprocess_params






     def __call__(						self							,	a__							,	*a__							,	**a__							,	):





       if len(a__    ) == 0:
         pass
       elif len(a__    ) == 1 and "candidate_labels" not in kwargs:
         _lowerCAmelCase		:			Union[str, Any]         =	args[0]
       else:
         raise ValueError(F"Unable to understand extra arguments {args}"    )

       return super().__call__(a__							,	**a__    )






     def        __A    (						self							,	a__							,	a__=None							,	a__="This example is {}."    ):
       _lowerCAmelCase		:			Union[str, Any]         =	self._args_parser(a__							,	a__							,	a__    )

       for i, (candidate_label, sequence_pair) in enumerate(zip(a__							,	a__    )    ):
         _lowerCAmelCase		:			str         =	self._parse_and_tokenize([sequence_pair]    )

         yield {
             "candidate_label": candidate_label,
             "sequence": sequences[0],
             "is_last": i == len(a__    ) - 1,
             **model_input,
         }






     def        __A    (						self							,	a__    ):
       _lowerCAmelCase		:			List[str]         =	inputs['''candidate_label''']
       _lowerCAmelCase		:			Tuple         =	inputs['''sequence''']
       _lowerCAmelCase		:			Union[str, Any]         =	{k: inputs[k] for k in self.tokenizer.model_input_names}
       _lowerCAmelCase		:			List[str]         =	self.model(**a__    )

       _lowerCAmelCase		:			Dict         =	{
           '''candidate_label''': candidate_label,
           '''sequence''': sequence,
           '''is_last''': inputs['''is_last'''],
           **outputs,
       }
       return model_outputs






     def        __A    (						self							,	a__							,	a__=False    ):
       _lowerCAmelCase		:			List[str]         =	[outputs['''candidate_label'''] for outputs in model_outputs]
       _lowerCAmelCase		:			Any         =	[outputs['''sequence'''] for outputs in model_outputs]
       _lowerCAmelCase		:			str         =	np.concatenate([output["""logits"""].numpy() for output in model_outputs]    )
       _lowerCAmelCase		:			Optional[Any]         =	logits.shape[0]
       _lowerCAmelCase		:			int         =	len(a__    )
       _lowerCAmelCase		:			List[Any]         =	N // n
       _lowerCAmelCase		:			Tuple         =	logits.reshape((num_sequences, n, -1)    )

       if multi_label or len(a__    ) == 1:
         # softmax over the entailment vs. contradiction dim for each label independently
         _lowerCAmelCase		:			Optional[int]         =	self.entailment_id
         _lowerCAmelCase		:			Optional[int]         =	-1 if entailment_id == 0 else 0
         _lowerCAmelCase		:			int         =	reshaped_outputs[..., [contradiction_id, entailment_id]]
         _lowerCAmelCase		:			Union[str, Any]         =	np.exp(a__    ) / np.exp(a__    ).sum(-1							,	keepdims=a__    )
         _lowerCAmelCase		:			List[Any]         =	scores[..., 1]
       else:
         # softmax the "entailment" logits over all candidate labels
         _lowerCAmelCase		:			Tuple         =	reshaped_outputs[..., self.entailment_id]
         _lowerCAmelCase		:			Tuple         =	np.exp(a__    ) / np.exp(a__    ).sum(-1							,	keepdims=a__    )

       _lowerCAmelCase		:			List[str]         =	list(reversed(scores[0].argsort()    )    )
       return {
           "sequence": sequences[0],
           "labels": [candidate_labels[i] for i in top_inds],
           "scores": scores[0, top_inds].tolist(),
       }











import argparse

import requests
import torch
from PIL import Image

from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel




def  __UpperCAmelCase(   lowercase_   ):
       # vision encoder
       if "img_encoder.pos_embed" in name:
              _lowerCamelCase				:  Tuple						=		name.replace('''img_encoder.pos_embed'''			,     '''vision_model.embeddings.position_embeddings'''   )
       if "img_encoder.patch_embed.proj" in name:
              _lowerCamelCase				:  List[str]						=		name.replace('''img_encoder.patch_embed.proj'''			,     '''vision_model.embeddings.patch_embeddings.projection'''   )
       if "img_encoder.patch_embed.norm" in name:
              _lowerCamelCase				:  Dict						=		name.replace('''img_encoder.patch_embed.norm'''			,     '''vision_model.embeddings.layernorm'''   )
       if "img_encoder.layers" in name:
              _lowerCamelCase				:  Dict						=		name.replace('''img_encoder.layers'''			,     '''vision_model.encoder.stages'''   )
       if "blocks" in name and "res" not in name:
              _lowerCamelCase				:  Optional[Any]						=		name.replace('''blocks'''			,     '''layers'''   )
       if "attn" in name and "pre_assign" not in name:
              _lowerCamelCase				:  Tuple						=		name.replace('''attn'''			,     '''self_attn'''   )
       if "proj" in name and "self_attn" in name and "text" not in name:
              _lowerCamelCase				:  Optional[int]						=		name.replace('''proj'''			,     '''out_proj'''   )
       if "pre_assign_attn.attn.proj" in name:
              _lowerCamelCase				:  List[Any]						=		name.replace('''pre_assign_attn.attn.proj'''			,     '''pre_assign_attn.attn.out_proj'''   )
       if "norm1" in name:
              _lowerCamelCase				:  int						=		name.replace('''norm1'''			,     '''layer_norm1'''   )
       if "norm2" in name and "pre_assign" not in name:
              _lowerCamelCase				:  Optional[int]						=		name.replace('''norm2'''			,     '''layer_norm2'''   )
       if "img_encoder.norm" in name:
              _lowerCamelCase				:  Dict						=		name.replace('''img_encoder.norm'''			,     '''vision_model.layernorm'''   )
       # text encoder
       if "text_encoder.token_embedding" in name:
              _lowerCamelCase				:  List[Any]						=		name.replace('''text_encoder.token_embedding'''			,     '''text_model.embeddings.token_embedding'''   )
       if "text_encoder.positional_embedding" in name:
              _lowerCamelCase				:  Optional[Any]						=		name.replace('''text_encoder.positional_embedding'''			,     '''text_model.embeddings.position_embedding.weight'''   )
       if "text_encoder.transformer.resblocks." in name:
              _lowerCamelCase				:  Dict						=		name.replace('''text_encoder.transformer.resblocks.'''			,     '''text_model.encoder.layers.'''   )
       if "ln_1" in name:
              _lowerCamelCase				:  Tuple						=		name.replace('''ln_1'''			,     '''layer_norm1'''   )
       if "ln_2" in name:
              _lowerCamelCase				:  List[str]						=		name.replace('''ln_2'''			,     '''layer_norm2'''   )
       if "c_fc" in name:
              _lowerCamelCase				:  List[str]						=		name.replace('''c_fc'''			,     '''fc1'''   )
       if "c_proj" in name:
              _lowerCamelCase				:  str						=		name.replace('''c_proj'''			,     '''fc2'''   )
       if "text_encoder" in name:
              _lowerCamelCase				:  Tuple						=		name.replace('''text_encoder'''			,     '''text_model'''   )
       if "ln_final" in name:
              _lowerCamelCase				:  str						=		name.replace('''ln_final'''			,     '''final_layer_norm'''   )
       # projection layers
       if "img_projector.linear_hidden." in name:
              _lowerCamelCase				:  str						=		name.replace('''img_projector.linear_hidden.'''			,     '''visual_projection.'''   )
       if "img_projector.linear_out." in name:
              _lowerCamelCase				:  Union[str, Any]						=		name.replace('''img_projector.linear_out.'''			,     '''visual_projection.3.'''   )
       if "text_projector.linear_hidden" in name:
              _lowerCamelCase				:  List[str]						=		name.replace('''text_projector.linear_hidden'''			,     '''text_projection'''   )
       if "text_projector.linear_out" in name:
              _lowerCamelCase				:  Any						=		name.replace('''text_projector.linear_out'''			,     '''text_projection.3'''   )

       return name




def  __UpperCAmelCase(   lowercase_			,     lowercase_   ):
       for key in orig_state_dict.copy().keys():
              _lowerCamelCase				:  Optional[int]						=		orig_state_dict.pop(lowercase_   )

              if "qkv" in key:
                     # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment:
                     # we need to split them up into separate matrices/vectors
                     _lowerCamelCase				:  Tuple						=		key.split('''.'''   )
                     _lowerCamelCase,	_lowerCamelCase				:  Dict						=		int(key_split[2]   ), int(key_split[4]   )
                     _lowerCamelCase				:  Optional[int]						=		config.vision_config.hidden_size
                     if "weight" in key:
                            _lowerCamelCase				:  List[Any]						=		val[:dim, :]
                            _lowerCamelCase				:  List[Any]						=		val[dim : dim * 2, :]
                            _lowerCamelCase				:  Optional[Any]						=		val[-dim:, :]
                     else:
                            _lowerCamelCase				:  Union[str, Any]						=		val[:dim]
                            _lowerCamelCase				:  Optional[Any]						=		val[dim : dim * 2]
                            _lowerCamelCase				:  Any						=		val[-dim:]
              elif "in_proj" in key:
                     # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment:
                     # we need to split them up into separate matrices/vectors
                     _lowerCamelCase				:  Optional[int]						=		key.split('''.'''   )
                     _lowerCamelCase				:  Optional[Any]						=		int(key_split[3]   )
                     _lowerCamelCase				:  Union[str, Any]						=		config.text_config.hidden_size
                     if "weight" in key:
                            _lowerCamelCase				:  Any						=		val[:dim, :]
                            _lowerCamelCase				:  Optional[Any]						=		val[
                                dim : dim * 2, :
                            ]
                            _lowerCamelCase				:  Dict						=		val[-dim:, :]
                     else:
                            _lowerCamelCase				:  List[Any]						=		val[:dim]
                            _lowerCamelCase				:  Tuple						=		val[dim : dim * 2]
                            _lowerCamelCase				:  str						=		val[-dim:]
              else:
                     _lowerCamelCase				:  Optional[Any]						=		rename_key(lowercase_   )
                     # squeeze if necessary
                     if (
                         "text_projection.0" in new_name
                         or "text_projection.3" in new_name
                         or "visual_projection.0" in new_name
                         or "visual_projection.3" in new_name
                     ):
                            _lowerCamelCase				:  List[str]						=		val.squeeze_()
                     else:
                            _lowerCamelCase				:  Tuple						=		val

       return orig_state_dict




def  __UpperCAmelCase(   ):
       _lowerCamelCase				:  Union[str, Any]						=		'''http://images.cocodataset.org/val2017/000000039769.jpg'''
       _lowerCamelCase				:  Any						=		Image.open(requests.get(lowercase_			,     stream=lowercase_   ).raw   )
       return im




@torch.no_grad()
def  __UpperCAmelCase(   lowercase_			,     lowercase_			,     lowercase_="groupvit-gcc-yfcc"			,     lowercase_=False   ):
       _lowerCamelCase				:  Optional[Any]						=		GroupViTConfig()
       _lowerCamelCase				:  Any						=		GroupViTModel(lowercase_   ).eval()

       _lowerCamelCase				:  Optional[Any]						=		torch.load(lowercase_			,     map_location='''cpu'''   )['''model''']
       _lowerCamelCase				:  List[str]						=		convert_state_dict(lowercase_			,     lowercase_   )
       _lowerCamelCase,	_lowerCamelCase				:  List[str]						=		model.load_state_dict(lowercase_			,     strict=lowercase_   )
       assert missing_keys == ["text_model.embeddings.position_ids"]
       assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowercase_   ) == 0)

       # verify result
       _lowerCamelCase				:  Optional[Any]						=		CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32'''   )
       _lowerCamelCase				:  Dict						=		prepare_img()
       _lowerCamelCase				:  str						=		processor(text=['''a photo of a cat''', '''a photo of a dog''']			,     images=lowercase_			,     padding=lowercase_			,     return_tensors='''pt'''   )

       with torch.no_grad():
              _lowerCamelCase				:  Optional[int]						=		model(**lowercase_   )

       if model_name == "groupvit-gcc-yfcc":
              _lowerCamelCase				:  Dict						=		torch.tensor([[1_3.3_5_2_3, 6.3_6_2_9]]   )
       elif model_name == "groupvit-gcc-redcaps":
              _lowerCamelCase				:  Tuple						=		torch.tensor([[1_6.1_8_7_3, 8.6_2_3_0]]   )
       else:
              raise ValueError(F"""Model name {model_name} not supported."""   )
       assert torch.allclose(outputs.logits_per_image			,     lowercase_			,     atol=1e-3   )

       processor.save_pretrained(lowercase_   )
       model.save_pretrained(lowercase_   )
       print('''Successfully saved processor and model to'''			,     lowercase_   )

       if push_to_hub:
              print('''Pushing to the hub...'''   )
              processor.push_to_hub(lowercase_			,     organization='''nielsr'''   )
              model.push_to_hub(lowercase_			,     organization='''nielsr'''   )


if __name__ == "__main__":
       _lowerCamelCase      							=   argparse.ArgumentParser()
       parser.add_argument(
           '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.'
       )
       parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint')
       parser.add_argument(
           '--model_name',
           default='groupvit-gccy-fcc',
           type=str,
           help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'',
       )
       parser.add_argument(
           '--push_to_hub',
           action='store_true',
           help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.',
       )
       _lowerCamelCase      							=   parser.parse_args()

       convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)

