

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

SCREAMING_SNAKE_CASE_        =      logging.get_logger(__name__)

@add_end_docstrings(lowercase__				)
class 				a  (	lowercase__				):


      def __init__(       self						,					**A_	):







          '''simple docstring'''


          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						,					A_						,					**A_	):







          '''simple docstring'''


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


      def        _UpperCAmelCase				(       self						,					**A_	):







          '''simple docstring'''


          _UpperCAmelCase       :		Union[str, Any] 		=    {}
          if "candidate_labels" in kwargs:
              _UpperCAmelCase       :		Optional[Any] 		=    kwargs["candidate_labels"]
          if "hypothesis_template" in kwargs:
              _UpperCAmelCase       :		str 		=    kwargs["hypothesis_template"]

          return preprocess_params, {}, {}


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







          '''simple docstring'''


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


      def        _UpperCAmelCase				(       self						,					A_	):







          '''simple docstring'''


          _UpperCAmelCase       :		Optional[Any] 		=    model_inputs.pop("candidate_labels"	)
          _UpperCAmelCase       :		List[str] 		=    model_inputs.pop("text_inputs"	)
          if isinstance(text_inputs[0]						,					__lowerCamelCase	):
              _UpperCAmelCase       :		Optional[Any] 		=    text_inputs[0]
          else:
              # Batching case.
              _UpperCAmelCase       :		Union[str, Any] 		=    text_inputs[0][0]

          _UpperCAmelCase       :		Optional[int] 		=    self.model(**__lowerCamelCase						,					**__lowerCamelCase	)

          _UpperCAmelCase       :		List[Any] 		=    {
              "candidate_labels": candidate_labels,
              "logits": outputs.logits_per_image,
          }
          return model_outputs





      def        _UpperCAmelCase				(       self						,					A_	):







          '''simple docstring'''


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

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





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


SCREAMING_SNAKE_CASE_        =      {
    'configuration_nllb_moe': [
        'NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'NllbMoeConfig',
    ]
}

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE_        =      [
					    'NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'NllbMoeForConditionalGeneration',
					    'NllbMoeModel',
					    'NllbMoePreTrainedModel',
					    'NllbMoeTop2Router',
					    'NllbMoeSparseMLP',
					]


if TYPE_CHECKING:
					from .configuration_nllb_moe import (
					    NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP,
					    NllbMoeConfig,
					)

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_nllb_moe import (
										    NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST,
										    NllbMoeForConditionalGeneration,
										    NllbMoeModel,
										    NllbMoePreTrainedModel,
										    NllbMoeSparseMLP,
										    NllbMoeTopaRouter,
										)


else:
					import sys

					SCREAMING_SNAKE_CASE_        =      _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


