




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__       :      Union[str, Any]  =   logging.get_logger(__name__)




@add_end_docstrings(lowerCAmelCase__     )
class 		UpperCamelCase__	(lowerCAmelCase__     ):

    '''simple docstring'''



    def __init__(    self     ,  **UpperCamelCase__     )     ->      Optional[Any]:
           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     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Optional[int]:
           return super().__call__(UpperCamelCase__     ,  **UpperCamelCase__     )







    def     _lowercase     (    self     ,  **UpperCamelCase__     )     ->      List[Any]:
           lowerCamelCase   :      Optional[int]			 =					{}
           if "candidate_labels" in kwargs:
                  lowerCamelCase   :      str			 =					kwargs["candidate_labels"]
           if "hypothesis_template" in kwargs:
                  lowerCamelCase   :      str			 =					kwargs["hypothesis_template"]

           return preprocess_params, {}, {}







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







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      Union[str, Any]:
           lowerCamelCase   :      List[str]			 =					model_inputs.pop("candidate_labels"     )
           lowerCamelCase   :      Dict			 =					model_inputs.pop("text_inputs"     )
           if isinstance(text_inputs[0]     ,  UpperCamelCase__     ):
                  lowerCamelCase   :      Dict			 =					text_inputs[0]
           else:
                  # Batching case.
                  lowerCamelCase   :      int			 =					text_inputs[0][0]

           lowerCamelCase   :      List[Any]			 =					self.model(**UpperCamelCase__     ,  **UpperCamelCase__     )

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







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

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












from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


SCREAMING_SNAKE_CASE__       :      List[Any]  =   {'processing_layoutxlm': ['LayoutXLMProcessor']}

try:
       if not is_sentencepiece_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       SCREAMING_SNAKE_CASE__       :      Optional[Any]  =   ['LayoutXLMTokenizer']

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       SCREAMING_SNAKE_CASE__       :      Dict  =   ['LayoutXLMTokenizerFast']

if TYPE_CHECKING:
       from .processing_layoutxlm import LayoutXLMProcessor

       try:
              if not is_sentencepiece_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_layoutxlm import LayoutXLMTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast

else:
       import sys

       SCREAMING_SNAKE_CASE__       :      str  =   _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)






