



'''simple docstring'''




from dataclasses import asdict, dataclass
from typing import Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging


a   :			List[Any]					  =    logging.get_logger(__name__)

# TODO Update this
a   :			Tuple					  =    {
    """facebook/esm-1b""": """https://huggingface.co/facebook/esm-1b/resolve/main/config.json""",
    # See all ESM models at https://huggingface.co/models?filter=esm
}

class 			UpperCamelCase_ (							__magic_name__			):
	lowercase          = 'esm'





	def __init__(  self		,		A=None		,		A=None		,		A=None		,		A=768		,		A=12		,		A=12		,		A=3072		,		A=0.1		,		A=0.1		,		A=1026		,		A=0.0_2		,		A=1e-12		,		A="absolute"		,		A=True		,		A=None		,		A=False		,		A=False		,		A=None		,		A=None		,		**A		,		)			->			str:
								super().__init__(pad_token_id=A		,		mask_token_id=A		,		**A    )

								UpperCAmelCase     :		Any							     =		vocab_size
								UpperCAmelCase     :		Optional[Any]							     =		hidden_size
								UpperCAmelCase     :		Tuple							     =		num_hidden_layers
								UpperCAmelCase     :		str							     =		num_attention_heads
								UpperCAmelCase     :		Dict							     =		intermediate_size
								UpperCAmelCase     :		str							     =		hidden_dropout_prob
								UpperCAmelCase     :		Any							     =		attention_probs_dropout_prob
								UpperCAmelCase     :		Optional[Any]							     =		max_position_embeddings
								UpperCAmelCase     :		Optional[int]							     =		initializer_range
								UpperCAmelCase     :		Optional[int]							     =		layer_norm_eps
								UpperCAmelCase     :		Dict							     =		position_embedding_type
								UpperCAmelCase     :		Any							     =		use_cache
								UpperCAmelCase     :		Dict							     =		emb_layer_norm_before
								UpperCAmelCase     :		Any							     =		token_dropout
								UpperCAmelCase     :		Dict							     =		is_folding_model
								if is_folding_model:
															if esmfold_config is None:
																						logger.info("""No esmfold_config supplied for folding model, using default values."""    )
																						UpperCAmelCase     :		Tuple							     =		EsmFoldConfig()
															elif isinstance(A		,		A    ):
																						UpperCAmelCase     :		Dict							     =		EsmFoldConfig(**A    )
															UpperCAmelCase     :		Tuple							     =		esmfold_config
															if vocab_list is None:
																						logger.warning("""No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!"""    )
																						UpperCAmelCase     :		Optional[int]							     =		get_default_vocab_list()
															else:
																						UpperCAmelCase     :		Optional[Any]							     =		vocab_list
								else:
															UpperCAmelCase     :		Any							     =		None
															UpperCAmelCase     :		List[Any]							     =		None
								if self.esmfold_config is not None and getattr(self.esmfold_config		,		"""use_esm_attn_map"""		,		A    ):
															raise ValueError("""The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!"""    )






	def  _lowercase(  self    )			->			str:
								UpperCAmelCase     :		Any							     =		super().to_dict()
								if isinstance(self.esmfold_config		,		A    ):
															UpperCAmelCase     :		Tuple							     =		self.esmfold_config.to_dict()
								return output




@dataclass
class 			UpperCamelCase_ :
	lowercase          = None
	lowercase          = True
	lowercase          = False
	lowercase          = False
	lowercase          = False
	lowercase          = 0

	lowercase          = True
	lowercase          = False

	lowercase          = 128
	lowercase          = None





	def  _lowercase(  self    )			->			Dict:
								if self.trunk is None:
															UpperCAmelCase     :		Optional[Any]							     =		TrunkConfig()
								elif isinstance(self.trunk		,		A    ):
															UpperCAmelCase     :		Dict							     =		TrunkConfig(**self.trunk    )






	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Tuple							     =		asdict(self    )
								UpperCAmelCase     :		int							     =		self.trunk.to_dict()
								return output




@dataclass
class 			UpperCamelCase_ :
	lowercase          = 48
	lowercase          = 1_024
	lowercase          = 128
	lowercase          = 32
	lowercase          = 32
	lowercase          = 32
	lowercase          = 0
	lowercase          = 0
	lowercase          = False
	lowercase          = 4
	lowercase          = 128
	lowercase          = None





	def  _lowercase(  self    )			->			Union[str, Any]:
								if self.structure_module is None:
															UpperCAmelCase     :		int							     =		StructureModuleConfig()
								elif isinstance(self.structure_module		,		A    ):
															UpperCAmelCase     :		Dict							     =		StructureModuleConfig(**self.structure_module    )

								if self.max_recycles <= 0:
															raise ValueError(f'''`max_recycles` should be positive, got {self.max_recycles}.'''    )
								if self.sequence_state_dim % self.sequence_state_dim != 0:
															raise ValueError(
															    """`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"""
															    f''' {self.sequence_state_dim} and {self.sequence_state_dim}.'''    )
								if self.pairwise_state_dim % self.pairwise_state_dim != 0:
															raise ValueError(
															    """`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"""
															    f''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.'''    )

								UpperCAmelCase     :		str							     =		self.sequence_state_dim // self.sequence_head_width
								UpperCAmelCase     :		int							     =		self.pairwise_state_dim // self.pairwise_head_width

								if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
															raise ValueError(
															    """`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"""
															    f''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.'''    )
								if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
															raise ValueError(
															    """`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"""
															    f''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.'''    )
								if self.pairwise_state_dim % 2 != 0:
															raise ValueError(f'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.'''    )

								if self.dropout >= 0.4:
															raise ValueError(f'''`dropout` should not be greater than 0.4, got {self.dropout}.'''    )






	def  _lowercase(  self    )			->			Any:
								UpperCAmelCase     :		Any							     =		asdict(self    )
								UpperCAmelCase     :		Optional[int]							     =		self.structure_module.to_dict()
								return output




@dataclass
class 			UpperCamelCase_ :
	lowercase          = 384
	lowercase          = 128
	lowercase          = 16
	lowercase          = 128
	lowercase          = 12
	lowercase          = 4
	lowercase          = 8
	lowercase          = 0.1
	lowercase          = 8
	lowercase          = 1
	lowercase          = 2
	lowercase          = 7
	lowercase          = 10
	lowercase          = 1e-8
	lowercase          = 1e5





	def  _lowercase(  self    )			->			Optional[Any]:
								return asdict(self    )




def       __lowerCamelCase  (					)      ->			int:
							return (
							    "<cls>",
							    "<pad>",
							    "<eos>",
							    "<unk>",
							    "L",
							    "A",
							    "G",
							    "V",
							    "S",
							    "E",
							    "R",
							    "T",
							    "I",
							    "D",
							    "P",
							    "K",
							    "Q",
							    "N",
							    "F",
							    "Y",
							    "M",
							    "H",
							    "W",
							    "C",
							    "X",
							    "B",
							    "U",
							    "Z",
							    "O",
							    ".",
							    "-",
							    "<null_1>",
							    "<mask>",
							)






'''simple docstring'''




from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
							from PIL import Image

							from ..image_utils import load_image

if is_torch_available():
							from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
							from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
							from ..tf_utils import stable_softmax

a   :			Union[str, Any]					  =    logging.get_logger(__name__)

@add_end_docstrings(__magic_name__			)
class 			UpperCamelCase_ (							__magic_name__			):





	def __init__(  self		,		**A    )			->			List[str]:
								super().__init__(**A    )

								requires_backends(self		,		"""vision"""    )
								self.check_model_type(
								    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
								    if self.framework == """tf"""
								    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING    )





	def __call__(  self		,		A		,		**A    )			->			Optional[Any]:
								return super().__call__(A		,		**A    )





	def  _lowercase(  self		,		**A    )			->			Optional[Any]:
								UpperCAmelCase     :		List[Any]							     =		{}
								if "candidate_labels" in kwargs:
															UpperCAmelCase     :		Dict							     =		kwargs["""candidate_labels"""]
								if "hypothesis_template" in kwargs:
															UpperCAmelCase     :		Optional[Any]							     =		kwargs["""hypothesis_template"""]

								return preprocess_params, {}, {}





	def  _lowercase(  self		,		A		,		A=None		,		A="This is a photo of {}."    )			->			Optional[Any]:
								UpperCAmelCase     :		int							     =		load_image(A    )
								UpperCAmelCase     :		List[str]							     =		self.image_processor(images=[image]		,		return_tensors=self.framework    )
								UpperCAmelCase     :		List[str]							     =		candidate_labels
								UpperCAmelCase     :		Tuple							     =		[hypothesis_template.format(A    ) for x in candidate_labels]
								UpperCAmelCase     :		Union[str, Any]							     =		self.tokenizer(A		,		return_tensors=self.framework		,		padding=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		[text_inputs]
								return inputs





	def  _lowercase(  self		,		A    )			->			Optional[int]:
								UpperCAmelCase     :		List[Any]							     =		model_inputs.pop("""candidate_labels"""    )
								UpperCAmelCase     :		Optional[Any]							     =		model_inputs.pop("""text_inputs"""    )
								if isinstance(text_inputs[0]		,		A    ):
															UpperCAmelCase     :		Optional[Any]							     =		text_inputs[0]
								else:
															# Batching case.
															UpperCAmelCase     :		Any							     =		text_inputs[0][0]

								UpperCAmelCase     :		Dict							     =		self.model(**A		,		**A    )

								UpperCAmelCase     :		List[Any]							     =		{
								    """candidate_labels""": candidate_labels,
								    """logits""": outputs.logits_per_image,
								}
								return model_outputs






	def  _lowercase(  self		,		A    )			->			Union[str, Any]:
								UpperCAmelCase     :		int							     =		model_outputs.pop("""candidate_labels"""    )
								UpperCAmelCase     :		int							     =		model_outputs["""logits"""][0]
								if self.framework == "pt":
															UpperCAmelCase     :		Optional[int]							     =		logits.softmax(dim=-1    ).squeeze(-1    )
															UpperCAmelCase     :		Any							     =		probs.tolist()
															if not isinstance(A		,		A    ):
																						UpperCAmelCase     :		Any							     =		[scores]
								elif self.framework == "tf":
															UpperCAmelCase     :		List[str]							     =		stable_softmax(A		,		axis=-1    )
															UpperCAmelCase     :		Union[str, Any]							     =		probs.numpy().tolist()
								else:
															raise ValueError(f'''Unsupported framework: {self.framework}'''    )

								UpperCAmelCase     :		Any							     =		[
								    {"""score""": score, """label""": candidate_label}
								    for score, candidate_label in sorted(zip(A		,		A    )		,		key=lambda A    : -x[0]    )
								]
								return result

