
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_    :			Optional[Any]    =	logging.get_logger(__name__)

@add_end_docstrings(_A	)
class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			def __init__(							self			:							Optional[Any]    ,						**snake_case_			:							Union[str, Any]   ):
							super().__init__(**snake_case_   )

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

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

							return preprocess_params, {}, {}

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

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

							UpperCamelCase_:				Optional[int]						=    self.model(**snake_case_    ,						**snake_case_   )

							UpperCamelCase_:				Union[str, Any]						=    {
							    """candidate_labels""": candidate_labels,
							    """logits""": outputs.logits_per_image,
							}
							return model_outputs




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

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








import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
							import torch

							from transformers.generation import DisjunctiveConstraint

@require_torch
class 							_UpperCamelCase					(       unittest.TestCase	):






			'''simple docstring'''

			def    lowerCAmelCase__						(							self			:							Dict   ):
							# For consistency across different places the DisjunctiveConstraint is called,
							# dc.token_ids is a list of integers. It is also initialized only by integers.

							UpperCamelCase_:				Optional[int]						=    [[1, 2, 4], [1, 2, 3, 4]]
							UpperCamelCase_:				List[str]						=    DisjunctiveConstraint(snake_case_   )
							self.assertTrue(isinstance(dc.token_ids    ,						snake_case_   )   )

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]   )   )

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint([torch.LongTensor([1, 2, 4]   ), torch.LongTensor([1, 2, 3, 4, 5]   )]   )

			def    lowerCAmelCase__						(							self			:							Optional[Any]   ):
							# We can't have constraints that are complete subsets of another. This leads to a preverse
							# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
							# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
							# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
							# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
							UpperCamelCase_:				Dict						=    [[1, 2], [1, 2, 3, 4]]

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint(snake_case_   )  # fails here

			def    lowerCAmelCase__						(							self			:							int   ):
							UpperCamelCase_:				Dict						=    [[1, 2, 3], [1, 2, 4]]

							UpperCamelCase_:				Dict						=    DisjunctiveConstraint(snake_case_   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				str						=    dc.update(1   )
							UpperCamelCase_:				Union[str, Any]						=    stepped is True and completed is False and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Optional[int]						=    dc.update(2   )
							UpperCamelCase_:				Tuple						=    stepped is True and completed is False and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Optional[int]						=    dc.update(3   )
							UpperCamelCase_:				Union[str, Any]						=    stepped is True and completed is True and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.current_seq == [1, 2, 3]   )




			def    lowerCAmelCase__						(							self			:							List[str]   ):
							UpperCamelCase_:				Optional[int]						=    [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]

							UpperCamelCase_:				Tuple						=    DisjunctiveConstraint(snake_case_   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Dict						=    dc.update(1   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Union[str, Any]						=    dc.update(2   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Any						=    dc.update(4   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2, 4]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				int						=    dc.update(5   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.current_seq == [1, 2, 4, 5]   )

							dc.reset()

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				int						=    dc.update(1   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.remaining() == 3   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Tuple						=    dc.update(2   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.remaining() == 2   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				List[str]						=    dc.update(5   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.remaining() == 0   )
							self.assertTrue(dc.current_seq == [1, 2, 5]   )






