





"""simple docstring"""



from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

a_			=      TypeVar("""T""")
a_			=      TypeVar("""U""")






class 		__snake_case (		Generic[T, U]					):





 """simple docstring"""


 def __init__(   self ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Optional[Any]									=					key
     __A   :						Tuple									=					val
     __A   :						DoubleLinkedListNode[T, U] | None									=					None
     __A   :						DoubleLinkedListNode[T, U] | None									=					None







 def __repr__(   self  ):



     '''simple docstring'''




     return (
         F"""Node: key: {self.key}, val: {self.val}, """
         F"""has next: {bool(self.next  )}, has prev: {bool(self.prev  )}"""
     )






class 		__snake_case (		Generic[T, U]					):





 """simple docstring"""


 def __init__(   self  ):



     '''simple docstring'''




     __A   :						DoubleLinkedListNode[T, U]									=					DoubleLinkedListNode(__lowerCamelCase ,						__lowerCamelCase  )
     __A   :						DoubleLinkedListNode[T, U]									=					DoubleLinkedListNode(__lowerCamelCase ,						__lowerCamelCase  )
     __A			,	__A   :						int									=					self.rear, self.head

 def __repr__(   self  ):



     '''simple docstring'''




     __A   :						Dict									=					['''DoubleLinkedList''']
     __A   :						str									=					self.head
     while node.next is not None:
         rep.append(str(__lowerCamelCase  )  )
         __A   :						List[str]									=					node.next
     rep.append(str(self.rear  )  )
     return ",\n    ".join(__lowerCamelCase  )

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					self.rear.prev

     # All nodes other than self.head are guaranteed to have non-None previous
     assert previous is not None

     __A   :						Union[str, Any]									=					node
     __A   :						int									=					previous
     __A   :						int									=					node
     __A   :						Tuple									=					self.rear







 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     if node.prev is None or node.next is None:
         return None

     __A   :						Dict									=					node.next
     __A   :						str									=					node.prev
     __A   :						List[str]									=					None
     __A   :						List[str]									=					None
     return node






class 		__snake_case (		Generic[T, U]					):





 """simple docstring"""


 _lowerCamelCase				=					{}

 def __init__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						DoubleLinkedList[T, U]									=					DoubleLinkedList()
     __A   :						List[Any]									=					capacity
     __A   :						Optional[Any]									=					0
     __A   :						Any									=					0
     __A   :						str									=					0
     __A   :						dict[T, DoubleLinkedListNode[T, U]]									=					{}

 def __repr__(   self  ):



     '''simple docstring'''




     return (
         F"""CacheInfo(hits={self.hits}, misses={self.miss}, """
         F"""capacity={self.capacity}, current size={self.num_keys})"""
     )

 def __contains__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     return key in self.cache

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     if key in self.cache:
         self.hits += 1
         __A   :						DoubleLinkedListNode[T, U]									=					self.cache[key]
         __A   :						Optional[Any]									=					self.list.remove(self.cache[key]  )
         assert node == value_node

         # node is guaranteed not None because it is in self.cache
         assert node is not None
         self.list.add(__lowerCamelCase  )
         return node.val
     self.miss += 1
     return None

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     if key not in self.cache:
         if self.num_keys >= self.capacity:
             # delete first node (oldest) when over capacity
             __A   :						Dict									=					self.list.head.next

             # guaranteed to have a non-None first node when num_keys > 0
             # explain to type checker via assertions
             assert first_node is not None
             assert first_node.key is not None
             assert (
                 self.list.remove(__lowerCamelCase  ) is not None
             )  # node guaranteed to be in list assert node.key is not None

             del self.cache[first_node.key]
             self.num_keys -= 1
         __A   :						Any									=					DoubleLinkedListNode(__lowerCamelCase ,						__lowerCamelCase  )
         self.list.add(self.cache[key]  )
         self.num_keys += 1

     else:
         # bump node to the end of the list, update value
         __A   :						Tuple									=					self.list.remove(self.cache[key]  )
         assert node is not None  # node guaranteed to be in list
         __A   :						Optional[Any]									=					value
         self.list.add(__lowerCamelCase  )







 @classmethod
 def  UpperCamelCase__(   cls ,						__lowerCamelCase = 128  ):



     '''simple docstring'''




     def cache_decorator_inner(__lowerCamelCase  ) -> Callable[..., U]:
         def cache_decorator_wrapper(*__lowerCamelCase  ) -> U:
             if func not in cls.decorator_function_to_instance_map:
                 __A   :						List[str]									=					LRUCache(__lowerCamelCase  )

             __A   :						Optional[Any]									=					cls.decorator_function_to_instance_map[func].get(args[0]  )
             if result is None:
                 __A   :						List[Any]									=					func(*__lowerCamelCase  )
                 cls.decorator_function_to_instance_map[func].put(args[0] ,						__lowerCamelCase  )
             return result

         def cache_info() -> LRUCache[T, U]:
             return cls.decorator_function_to_instance_map[func]

         setattr(__lowerCamelCase ,						'''cache_info''' ,						__lowerCamelCase  )  # noqa: B010

         return cache_decorator_wrapper

     return cache_decorator_inner


if __name__ == "__main__":
       import doctest

       doctest.testmod()











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

a_			=      logging.get_logger(__name__)






@add_end_docstrings(SCREAMING_SNAKE_CASE__					)
class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 def __init__(   self ,						**__lowerCamelCase  ):



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



     '''simple docstring'''




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

 def  UpperCamelCase__(   self ,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Union[str, Any]									=					{}
     if "candidate_labels" in kwargs:
         __A   :						Tuple									=					kwargs['''candidate_labels''']
     if "hypothesis_template" in kwargs:
         __A   :						List[str]									=					kwargs['''hypothesis_template''']

     return preprocess_params, {}, {}

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



     '''simple docstring'''




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

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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

     __A   :						List[str]									=					self.model(**__lowerCamelCase ,						**__lowerCamelCase  )

     __A   :						Dict									=					{
         '''candidate_labels''': candidate_labels,
         '''logits''': outputs.logits_per_image,
     }
     return model_outputs







 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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

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




