





"""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

SCREAMING_SNAKE_CASE__   =  logging.get_logger(__name__)

@add_end_docstrings(_UpperCAmelCase   )
class 						lowercase   (   _UpperCAmelCase   ):





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





      def        _snake_case     (			self ,		**lowercase					)						->	List[Any]:
            lowerCAmelCase    		=			{}
            if "candidate_labels" in kwargs:
                  lowerCAmelCase    		=			kwargs["""candidate_labels"""]
            if "hypothesis_template" in kwargs:
                  lowerCAmelCase    		=			kwargs["""hypothesis_template"""]

            return preprocess_params, {}, {}





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





      def        _snake_case     (			self ,		lowercase					)						->	Optional[Any]:
            lowerCAmelCase    		=			model_inputs.pop("""candidate_labels"""					)
            lowerCAmelCase    		=			model_inputs.pop("""text_inputs"""					)
            if isinstance(text_inputs[0] ,		lowercase					):
                  lowerCAmelCase    		=			text_inputs[0]
            else:
                  # Batching case.
                  lowerCAmelCase    		=			text_inputs[0][0]

            lowerCAmelCase    		=			self.model(**lowercase ,		**lowercase					)

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





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

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













"""simple docstring"""





def      UpperCAmelCase__				(    SCREAMING_SNAKE_CASE	:		int				,		SCREAMING_SNAKE_CASE	:		int     ):







      '''simple docstring'''




      if a < 0 or b < 0:
            raise ValueError("""the value of both inputs must be positive"""     )
      lowerCAmelCase    		=			str(bin(SCREAMING_SNAKE_CASE     )     )[2:]  # remove the leading "0b"
      lowerCAmelCase    		=			str(bin(SCREAMING_SNAKE_CASE     )     )[2:]
      lowerCAmelCase    		=			max(len(SCREAMING_SNAKE_CASE     )				,		len(SCREAMING_SNAKE_CASE     )     )
      return "0b" + "".join(
          str(int("""1""" in (char_a, char_b)     )     )
          for char_a, char_b in zip(a_binary.zfill(SCREAMING_SNAKE_CASE     )				,		b_binary.zfill(SCREAMING_SNAKE_CASE     )     )     )


if __name__ == "__main__":
       import doctest

       doctest.testmod()






