

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		=logging.get_logger(__name__)






@add_end_docstrings(snake_case__    )
class 	A_		(	snake_case__    ):
							def __init__(		self		:      List[Any]       ,**SCREAMING_SNAKE_CASE__		:      Dict):
								super().__init__(**UpperCAmelCase_)

								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		:      List[str]       ,SCREAMING_SNAKE_CASE__		:      Union[str, List[str], "Image", List["Image"]]       ,**SCREAMING_SNAKE_CASE__		:      Tuple):
								return super().__call__(UpperCAmelCase_       ,**UpperCAmelCase_)
							def    lowerCAmelCase					(		self		:      Union[str, Any]       ,**SCREAMING_SNAKE_CASE__		:      Optional[Any]):
								__lowerCamelCase    :    List[Any] 	=			{}
								if "candidate_labels" in kwargs:
									__lowerCamelCase    :    Union[str, Any] 	=			kwargs["candidate_labels"]
								if "hypothesis_template" in kwargs:
									__lowerCamelCase    :    int 	=			kwargs["hypothesis_template"]

								return preprocess_params, {}, {}
							def    lowerCAmelCase					(		self		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      int       ,SCREAMING_SNAKE_CASE__		:      List[str]=None       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]="This is a photo of {}."):
								__lowerCamelCase    :    Tuple 	=			load_image(UpperCAmelCase_)
								__lowerCamelCase    :    List[Any] 	=			self.image_processor(images=[image]       ,return_tensors=self.framework)
								__lowerCamelCase    :    Dict 	=			candidate_labels
								__lowerCamelCase    :    Any 	=			[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels]
								__lowerCamelCase    :    Optional[int] 	=			self.tokenizer(UpperCAmelCase_       ,return_tensors=self.framework       ,padding=UpperCAmelCase_)
								__lowerCamelCase    :    List[Any] 	=			[text_inputs]
								return inputs
							def    lowerCAmelCase					(		self		:      Tuple       ,SCREAMING_SNAKE_CASE__		:      Tuple):
								__lowerCamelCase    :    Union[str, Any] 	=			model_inputs.pop('candidate_labels')
								__lowerCamelCase    :    str 	=			model_inputs.pop('text_inputs')
								if isinstance(text_inputs[0]       ,UpperCAmelCase_):
									__lowerCamelCase    :    Tuple 	=			text_inputs[0]
								else:
									# Batching case.
									__lowerCamelCase    :    Optional[int] 	=			text_inputs[0][0]

								__lowerCamelCase    :    Any 	=			self.model(**UpperCAmelCase_       ,**UpperCAmelCase_)

								__lowerCamelCase    :    Dict 	=			{
								    "candidate_labels": candidate_labels,
								    "logits": outputs.logits_per_image,
								}
								return model_outputs


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

								__lowerCamelCase    :    Dict 	=			[
								    {"score": score, "label": candidate_label}
								    for score, candidate_label in sorted(zip(UpperCAmelCase_       ,UpperCAmelCase_)       ,key=lambda SCREAMING_SNAKE_CASE__: -x[0])
								]
								return result







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


a		={
    """configuration_pix2struct""": [
        """PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """Pix2StructConfig""",
        """Pix2StructTextConfig""",
        """Pix2StructVisionConfig""",
    ],
    """processing_pix2struct""": ["""Pix2StructProcessor"""],
}

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					a		=["""Pix2StructImageProcessor"""]


try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					a		=[
					    """PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST""",
					    """Pix2StructPreTrainedModel""",
					    """Pix2StructForConditionalGeneration""",
					    """Pix2StructVisionModel""",
					    """Pix2StructTextModel""",
					]

if TYPE_CHECKING:
					from .configuration_pixastruct import (
					    PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
					    PixaStructConfig,
					    PixaStructTextConfig,
					    PixaStructVisionConfig,
					)
					from .processing_pixastruct import PixaStructProcessor

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .image_processing_pixastruct import PixaStructImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_pixastruct import (
										    PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
										    PixaStructForConditionalGeneration,
										    PixaStructPreTrainedModel,
										    PixaStructTextModel,
										    PixaStructVisionModel,
										)

else:
					import sys

					a		=_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




