



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

_snake_case		=  logging.get_logger(__name__)



@add_end_docstrings(UpperCAmelCase_)
class   UpperCAmelCase_    (       UpperCAmelCase_):







							def __init__(   self,			**__a):

														'''simple docstring'''

														super().__init__(**__lowercase)

														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):

														'''simple docstring'''

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







							def    snake_case__      (   self,			**__a):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    {}
														if "candidate_labels" in kwargs:
																					_lowerCAmelCase     :							Union[str, Any]    =    kwargs['''candidate_labels''']
														if "hypothesis_template" in kwargs:
																					_lowerCAmelCase     :							List[str]    =    kwargs['''hypothesis_template''']

														return preprocess_params, {}, {}







							def    snake_case__      (   self,			__a,			__a=None,			__a="This is a photo of {}."):

														'''simple docstring'''

														_lowerCAmelCase     :							Dict    =    load_image(__lowercase)
														_lowerCAmelCase     :							Dict    =    self.image_processor(images=[image],			return_tensors=self.framework)
														_lowerCAmelCase     :							Optional[int]    =    candidate_labels
														_lowerCAmelCase     :							int    =    [hypothesis_template.format(__lowercase) for x in candidate_labels]
														_lowerCAmelCase     :							Optional[Any]    =    self.tokenizer(__lowercase,			return_tensors=self.framework,			padding=__lowercase)
														_lowerCAmelCase     :							List[str]    =    [text_inputs]
														return inputs







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							List[str]    =    model_inputs.pop("candidate_labels")
														_lowerCAmelCase     :							List[str]    =    model_inputs.pop("text_inputs")
														if isinstance(text_inputs[0],			__lowercase):
																					_lowerCAmelCase     :							int    =    text_inputs[0]
														else:
																					# Batching case.
																					_lowerCAmelCase     :							str    =    text_inputs[0][0]

														_lowerCAmelCase     :							Dict    =    self.model(**__lowercase,			**__lowercase)

														_lowerCAmelCase     :							str    =    {
														    '''candidate_labels''': candidate_labels,
														    '''logits''': outputs.logits_per_image,
														}
														return model_outputs







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

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

														_lowerCAmelCase     :							Optional[int]    =    [
														    {'''score''': score, '''label''': candidate_label}
														    for score, candidate_label in sorted(zip(__lowercase,			__lowercase),			key=lambda __a: -x[0])
														]
														return result

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


__lowercase							 =					logging.get_logger(__name__)

__lowercase							 =					{'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''}


class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    a__	:						str						=      """ctrl"""
    a__	:						Dict						=      ["""past_key_values"""]
    a__	:						Tuple						=      {
        """max_position_embeddings""": """n_positions""",
        """hidden_size""": """n_embd""",
        """num_attention_heads""": """n_head""",
        """num_hidden_layers""": """n_layer""",
    }







    def __init__(	self , __lowercase=246_534 , __lowercase=256 , __lowercase=1_280 , __lowercase=8_192 , __lowercase=48 , __lowercase=16 , __lowercase=0.1 , __lowercase=0.1 , __lowercase=1E-6 , __lowercase=0.02 , __lowercase=True , **__lowercase , )       ->	List[Any]:
        __UpperCamelCase     :List[str]			  =		vocab_size
        __UpperCamelCase     :Optional[Any]			  =		n_positions
        __UpperCamelCase     :Dict			  =		n_embd
        __UpperCamelCase     :Dict			  =		n_layer
        __UpperCamelCase     :List[Any]			  =		n_head
        __UpperCamelCase     :int			  =		dff
        __UpperCamelCase     :Union[str, Any]			  =		resid_pdrop
        __UpperCamelCase     :Optional[int]			  =		embd_pdrop
        __UpperCamelCase     :List[Any]			  =		layer_norm_epsilon
        __UpperCamelCase     :Dict			  =		initializer_range

        __UpperCamelCase     :Any			  =		use_cache

        super().__init__(**__lowercase)





