





'''simple docstring'''

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






@add_end_docstrings(UpperCamelCase__							)
class   UpperCAmelCase      (			UpperCamelCase__							):
 def __init__(							self :Dict		,			**lowercase_ :Optional[int]				)->				Optional[Any]:
     super().__init__(**lowercase_				)

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

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

     A__							=     self.model(**lowercase_		,			**lowercase_				)

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



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

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










'''simple docstring'''

# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__lowerCAmelCase				:      Optional[int]						      ={
    "configuration_vivit": ["VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "VivitConfig"],
}
try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __lowerCAmelCase				:      int						      =["VivitImageProcessor"]


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __lowerCAmelCase				:      int						      =[
      "VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
      "VivitModel",
      "VivitPreTrainedModel",
      "VivitForVideoClassification",
  ]


if TYPE_CHECKING:
  from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_vivit import VivitImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_vivit import (
        VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
        VivitForVideoClassification,
        VivitModel,
        VivitPreTrainedModel,
    )


else:
  import sys

  __lowerCAmelCase				:      List[Any]						      =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



