

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

lowerCAmelCase							:  Any            =						logging.get_logger(__name__)



@add_end_docstrings(UpperCAmelCase_     )
class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			def __init__(			self  :					int       ,						**lowerCAmelCase__  :					List[str]):
									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  :					Any       ,						lowerCAmelCase__  :					Union[str, List[str], "Image", List["Image"]]       ,						**lowerCAmelCase__  :					Union[str, Any]):
									return super().__call__(lowerCAmelCase__       ,						**lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						**lowerCAmelCase__  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	{}
									if "candidate_labels" in kwargs:
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	kwargs["candidate_labels"]
									if "hypothesis_template" in kwargs:
															SCREAMING_SNAKE_CASE_:			List[str]  		=	kwargs["hypothesis_template"]

									return preprocess_params, {}, {}



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str       ,						lowerCAmelCase__  :					int       ,						lowerCAmelCase__  :					List[str]=None       ,						lowerCAmelCase__  :					Optional[Any]="This is a photo of {}."):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	load_image(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	self.image_processor(images=[image]       ,						return_tensors=self.framework)
									SCREAMING_SNAKE_CASE_:			Dict  		=	candidate_labels
									SCREAMING_SNAKE_CASE_:			str  		=	[hypothesis_template.format(lowerCAmelCase__) for x in candidate_labels]
									SCREAMING_SNAKE_CASE_:			List[str]  		=	self.tokenizer(lowerCAmelCase__       ,						return_tensors=self.framework       ,						padding=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	[text_inputs]
									return inputs



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						lowerCAmelCase__  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			Any  		=	model_inputs.pop("candidate_labels")
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model_inputs.pop("text_inputs")
									if isinstance(text_inputs[0]       ,						lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	text_inputs[0]
									else:
															# Batching case.
															SCREAMING_SNAKE_CASE_:			Tuple  		=	text_inputs[0][0]

									SCREAMING_SNAKE_CASE_:			str  		=	self.model(**lowerCAmelCase__       ,						**lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Tuple  		=	{
									    "candidate_labels": candidate_labels,
									    "logits": outputs.logits_per_image,
									}
									return model_outputs




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

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









from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
						import PIL


lowerCAmelCase							:  Optional[Any]            =						logging.get_logger(__name__)



class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Any      							=					['''pixel_values''']



			def __init__(			self  :					List[Any]       ,						lowerCAmelCase__  :					bool = True       ,						lowerCAmelCase__  :					Dict[str, int] = None       ,						lowerCAmelCase__  :					PILImageResampling = PILImageResampling.BICUBIC       ,						lowerCAmelCase__  :					bool = True       ,						lowerCAmelCase__  :					Union[int, float] = 1 / 255       ,						lowerCAmelCase__  :					bool = True       ,						lowerCAmelCase__  :					Optional[Union[float, List[float]]] = None       ,						lowerCAmelCase__  :					Optional[Union[float, List[float]]] = None       ,						lowerCAmelCase__  :					bool = True       ,						**lowerCAmelCase__  :					Tuple       ,						):
									super().__init__(**lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[str]  		=	size if size is not None else {"height": 384, "width": 384}
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	get_size_dict(lowerCAmelCase__       ,						default_to_square=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			int  		=	do_resize
									SCREAMING_SNAKE_CASE_:			Dict  		=	size
									SCREAMING_SNAKE_CASE_:			int  		=	resample
									SCREAMING_SNAKE_CASE_:			str  		=	do_rescale
									SCREAMING_SNAKE_CASE_:			str  		=	rescale_factor
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	do_normalize
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	image_mean if image_mean is not None else OPENAI_CLIP_MEAN
									SCREAMING_SNAKE_CASE_:			List[str]  		=	image_std if image_std is not None else OPENAI_CLIP_STD
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	do_convert_rgb



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str       ,						lowerCAmelCase__  :					np.ndarray       ,						lowerCAmelCase__  :					Dict[str, int]       ,						lowerCAmelCase__  :					PILImageResampling = PILImageResampling.BICUBIC       ,						lowerCAmelCase__  :					Optional[Union[str, ChannelDimension]] = None       ,						**lowerCAmelCase__  :					Tuple       ,						):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	get_size_dict(lowerCAmelCase__       ,						default_to_square=lowerCAmelCase__)
									if "height" not in size or "width" not in size:
															raise ValueError(F"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
									SCREAMING_SNAKE_CASE_:			int  		=	(size["height"], size["width"])
									return resize(lowerCAmelCase__       ,						size=lowerCAmelCase__       ,						resample=lowerCAmelCase__       ,						data_format=lowerCAmelCase__       ,						**lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						lowerCAmelCase__  :					np.ndarray       ,						lowerCAmelCase__  :					Union[int, float]       ,						lowerCAmelCase__  :					Optional[Union[str, ChannelDimension]] = None       ,						**lowerCAmelCase__  :					List[Any]       ,						):
									return rescale(lowerCAmelCase__       ,						scale=lowerCAmelCase__       ,						data_format=lowerCAmelCase__       ,						**lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[str]       ,						lowerCAmelCase__  :					np.ndarray       ,						lowerCAmelCase__  :					Union[float, List[float]]       ,						lowerCAmelCase__  :					Union[float, List[float]]       ,						lowerCAmelCase__  :					Optional[Union[str, ChannelDimension]] = None       ,						**lowerCAmelCase__  :					List[Any]       ,						):
									return normalize(lowerCAmelCase__       ,						mean=lowerCAmelCase__       ,						std=lowerCAmelCase__       ,						data_format=lowerCAmelCase__       ,						**lowerCAmelCase__)




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					ImageInput       ,						lowerCAmelCase__  :					Optional[bool] = None       ,						lowerCAmelCase__  :					Optional[Dict[str, int]] = None       ,						lowerCAmelCase__  :					PILImageResampling = None       ,						lowerCAmelCase__  :					Optional[bool] = None       ,						lowerCAmelCase__  :					Optional[float] = None       ,						lowerCAmelCase__  :					Optional[bool] = None       ,						lowerCAmelCase__  :					Optional[Union[float, List[float]]] = None       ,						lowerCAmelCase__  :					Optional[Union[float, List[float]]] = None       ,						lowerCAmelCase__  :					Optional[Union[str, TensorType]] = None       ,						lowerCAmelCase__  :					bool = None       ,						lowerCAmelCase__  :					ChannelDimension = ChannelDimension.FIRST       ,						**lowerCAmelCase__  :					Dict       ,						):
									SCREAMING_SNAKE_CASE_:			Any  		=	do_resize if do_resize is not None else self.do_resize
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	resample if resample is not None else self.resample
									SCREAMING_SNAKE_CASE_:			Dict  		=	do_rescale if do_rescale is not None else self.do_rescale
									SCREAMING_SNAKE_CASE_:			Any  		=	rescale_factor if rescale_factor is not None else self.rescale_factor
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	do_normalize if do_normalize is not None else self.do_normalize
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	image_mean if image_mean is not None else self.image_mean
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	image_std if image_std is not None else self.image_std
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

									SCREAMING_SNAKE_CASE_:			str  		=	size if size is not None else self.size
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	get_size_dict(lowerCAmelCase__       ,						default_to_square=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[Any]  		=	make_list_of_images(lowerCAmelCase__)

									if not valid_images(lowerCAmelCase__):
															raise ValueError(
															    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
															    "torch.Tensor, tf.Tensor or jax.ndarray.")

									if do_resize and size is None or resample is None:
															raise ValueError("Size and resample must be specified if do_resize is True.")

									if do_rescale and rescale_factor is None:
															raise ValueError("Rescale factor must be specified if do_rescale is True.")

									if do_normalize and (image_mean is None or image_std is None):
															raise ValueError("Image mean and std must be specified if do_normalize is True.")

									# PIL RGBA images are converted to RGB
									if do_convert_rgb:
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	[convert_to_rgb(lowerCAmelCase__) for image in images]

									# All transformations expect numpy arrays.
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	[to_numpy_array(lowerCAmelCase__) for image in images]

									if do_resize:
															SCREAMING_SNAKE_CASE_:			int  		=	[self.resize(image=lowerCAmelCase__       ,						size=lowerCAmelCase__       ,						resample=lowerCAmelCase__) for image in images]

									if do_rescale:
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	[self.rescale(image=lowerCAmelCase__       ,						scale=lowerCAmelCase__) for image in images]

									if do_normalize:
															SCREAMING_SNAKE_CASE_:			List[str]  		=	[self.normalize(image=lowerCAmelCase__       ,						mean=lowerCAmelCase__       ,						std=lowerCAmelCase__) for image in images]

									SCREAMING_SNAKE_CASE_:			str  		=	[to_channel_dimension_format(lowerCAmelCase__       ,						lowerCAmelCase__) for image in images]

									SCREAMING_SNAKE_CASE_:			List[str]  		=	BatchFeature(data={"pixel_values": images}       ,						tensor_type=lowerCAmelCase__)

									return encoded_outputs






