


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					:		Union[str, Any]      =    logging.get_logger(__name__)

@add_end_docstrings(_lowerCAmelCase				)
class     a		(_lowerCAmelCase				):




							"""simple docstring"""


							def __init__(							self	:  List[Any]   ,     **lowerCamelCase	:  Tuple    )     ->   Optional[Any]:
														super().__init__(**lowerCamelCase    )

														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	:  Dict   ,     lowerCamelCase	:  Union[str, List[str], "Image", List["Image"]]   ,     **lowerCamelCase	:  Optional[int]    )     ->   List[str]:
														return super().__call__(lowerCamelCase   ,     **lowerCamelCase    )

							def    __snake_case (							self	:  str   ,     **lowerCamelCase	:  Dict    )     ->   Dict:
														__snake_case		:      Any										=       {}
														if "candidate_labels" in kwargs:
																					__snake_case		:      Dict										=       kwargs["candidate_labels"]
														if "hypothesis_template" in kwargs:
																					__snake_case		:      Any										=       kwargs["hypothesis_template"]

														return preprocess_params, {}, {}

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

							def    __snake_case (							self	:  int   ,     lowerCamelCase	:  Union[str, Any]    )     ->   str:
														__snake_case		:      Tuple										=       model_inputs.pop("candidate_labels"    )
														__snake_case		:      Union[str, Any]										=       model_inputs.pop("text_inputs"    )
														if isinstance(text_inputs[0]   ,     lowerCamelCase    ):
																					__snake_case		:      Dict										=       text_inputs[0]
														else:
																					# Batching case.
																					__snake_case		:      List[Any]										=       text_inputs[0][0]

														__snake_case		:      Dict										=       self.model(**lowerCamelCase   ,     **lowerCamelCase    )

														__snake_case		:      Optional[int]										=       {
														    "candidate_labels": candidate_labels,
														    "logits": outputs.logits_per_image,
														}
														return model_outputs






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

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





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_tf_available():
			import tensorflow as tf

			from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
			from ..tf_utils import stable_softmax

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

_snake_case					:		Optional[int]      =    logging.get_logger(__name__)

@add_end_docstrings(_lowerCAmelCase				)
class     a		(_lowerCAmelCase				):




							"""simple docstring"""


							def __init__(							self	:  Tuple   ,     *lowerCamelCase	:  Any   ,     **lowerCamelCase	:  Tuple    )     ->   int:
														super().__init__(*lowerCamelCase   ,     **lowerCamelCase    )
														requires_backends(self   ,     "vision"    )
														self.check_model_type(
														    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
														    if self.framework == "tf"
														    else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING    )

							def    __snake_case (							self	:  List[str]   ,     lowerCamelCase	:  Optional[Any]=None    )     ->   Optional[int]:
														__snake_case		:      Optional[Any]										=       {}
														if top_k is not None:
																					__snake_case		:      List[Any]										=       top_k
														return {}, {}, postprocess_params

							def __call__(							self	:  List[Any]   ,     lowerCamelCase	:  Union[str, List[str], "Image.Image", List["Image.Image"]]   ,     **lowerCamelCase	:  Dict    )     ->   Optional[int]:
														return super().__call__(lowerCamelCase   ,     **lowerCamelCase    )

							def    __snake_case (							self	:  Optional[Any]   ,     lowerCamelCase	:  List[Any]    )     ->   int:
														__snake_case		:      Any										=       load_image(lowerCamelCase    )
														__snake_case		:      str										=       self.image_processor(images=lowerCamelCase   ,     return_tensors=self.framework    )
														return model_inputs

							def    __snake_case (							self	:  int   ,     lowerCamelCase	:  List[str]    )     ->   Tuple:
														__snake_case		:      List[Any]										=       self.model(**lowerCamelCase    )
														return model_outputs






							def    __snake_case (							self	:  List[Any]   ,     lowerCamelCase	:  Any   ,     lowerCamelCase	:  Optional[Any]=5    )     ->   List[str]:
														if top_k > self.model.config.num_labels:
																					__snake_case		:      int										=       self.model.config.num_labels

														if self.framework == "pt":
																					__snake_case		:      Optional[Any]										=       model_outputs.logits.softmax(-1    )[0]
																					__snake_case			,      __snake_case		:      List[str]										=       probs.topk(lowerCamelCase    )
														elif self.framework == "tf":
																					__snake_case		:      Tuple										=       stable_softmax(model_outputs.logits   ,     axis=-1    )[0]
																					__snake_case		:      Optional[Any]										=       tf.math.top_k(lowerCamelCase   ,     k=lowerCamelCase    )
																					__snake_case			,      __snake_case		:      List[Any]										=       topk.values.numpy(), topk.indices.numpy()
														else:
																					raise ValueError(F'Unsupported framework: {self.framework}'    )

														__snake_case		:      Any										=       scores.tolist()
														__snake_case		:      Optional[int]										=       ids.tolist()
														return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase   ,     lowerCamelCase    )]

