
'''simple docstring'''







from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
  from PIL import Image

  from ..image_utils import load_image

if is_torch_available():
  import torch

  from transformers.modeling_outputs import BaseModelOutput

  from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

__lowerCAmelCase         =    logging.get_logger(__name__)







@add_end_docstrings(_lowerCamelCase	)
class UpperCAmelCase__	( _lowerCamelCase	):





  """simple docstring"""

  def __init__(		self      :     Union[str, Any]							,**_a      :     Dict       ):


     '''simple docstring'''






     super().__init__(**a_       )

     if self.framework == "tf":
        raise ValueError(F"""The {self.__class__} is only available in PyTorch."""       )

     requires_backends(self							,'vision'       )
     self.check_model_type(a_       )


  def __call__(		self      :     Optional[Any]							,_a      :     Dict							,_a      :     Union[str, Any] = None							,**_a      :     str							,):


     '''simple docstring'''






     if "text_queries" in kwargs:
        _a				:	str			=   kwargs.pop('text_queries'       )

     if isinstance(a_							,(str, Image.Image)       ):
        _a				:	Dict			=   {"""image""": image, """candidate_labels""": candidate_labels}
     else:
        _a				:	int			=   image
     _a				:	Optional[Any]			=   super().__call__(a_							,**a_       )
     return results


  def   __lowercase		(		self      :     Optional[Any]							,**_a      :     Union[str, Any]       ):


     '''simple docstring'''






     _a				:	str			=   {}
     if "threshold" in kwargs:
        _a				:	List[Any]			=   kwargs["""threshold"""]
     if "top_k" in kwargs:
        _a				:	Union[str, Any]			=   kwargs["""top_k"""]
     return {}, {}, postprocess_params


  def   __lowercase		(		self      :     Optional[int]							,_a      :     str       ):


     '''simple docstring'''






     _a				:	str			=   load_image(inputs['image']       )
     _a				:	str			=   inputs["""candidate_labels"""]
     if isinstance(a_							,a_       ):
        _a				:	Dict			=   candidate_labels.split(','       )

     _a				:	Optional[int]			=   torch.tensor([[image.height, image.width]]							,dtype=torch.intaa       )
     for i, candidate_label in enumerate(a_       ):
        _a				:	Union[str, Any]			=   self.tokenizer(a_							,return_tensors=self.framework       )
        _a				:	Optional[Any]			=   self.image_processor(a_							,return_tensors=self.framework       )
        yield {
            "is_last": i == len(a_       ) - 1,
            "target_size": target_size,
            "candidate_label": candidate_label,
            **text_inputs,
            **image_features,
        }


  def   __lowercase		(		self      :     List[Any]							,_a      :     Dict       ):


     '''simple docstring'''






     _a				:	Optional[Any]			=   model_inputs.pop('target_size'       )
     _a				:	Optional[int]			=   model_inputs.pop('candidate_label'       )
     _a				:	Tuple			=   model_inputs.pop('is_last'       )

     _a				:	Any			=   self.model(**a_       )

     _a				:	int			=   {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
     return model_outputs


  def   __lowercase		(		self      :     List[str]							,_a      :     Optional[int]							,_a      :     Tuple=0.1							,_a      :     Dict=None       ):


     '''simple docstring'''






     _a				:	Union[str, Any]			=   []
     for model_output in model_outputs:
        _a				:	Union[str, Any]			=   model_output["""candidate_label"""]
        _a				:	Optional[Any]			=   BaseModelOutput(a_       )
        _a				:	List[str]			=   self.image_processor.post_process_object_detection(
            outputs=a_							,threshold=a_							,target_sizes=model_output['target_size']       )[0]

        for index in outputs["scores"].nonzero():
           _a				:	Optional[int]			=   outputs["""scores"""][index].item()
           _a				:	Dict			=   self._get_bounding_box(outputs['boxes'][index][0]       )

           _a				:	Optional[Any]			=   {"""score""": score, """label""": label, """box""": box}
           results.append(a_       )

     _a				:	Union[str, Any]			=   sorted(a_							,key=lambda _a       : x["score"]							,reverse=a_       )
     if top_k:
        _a				:	Dict			=   results[:top_k]

     return results


  def   __lowercase		(		self      :     Any							,_a      :     Union[str, Any]       ):


     '''simple docstring'''






     if self.framework != "pt":
        raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.'       )
     _a				:	int			=   box.int().tolist()
     _a				:	Dict			=   {
         """xmin""": xmin,
         """ymin""": ymin,
         """xmax""": xmax,
         """ymax""": ymax,
     }
     return bbox








'''simple docstring'''






from typing import TYPE_CHECKING

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


A_							: Optional[Any]						 =	{
    """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""],
}

try:
   if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_							: List[str]						 =	["""LlamaTokenizer"""]

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_							: Dict						 =	["""LlamaTokenizerFast"""]

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_							: Optional[int]						 =	[
       """LlamaForCausalLM""",
       """LlamaModel""",
       """LlamaPreTrainedModel""",
       """LlamaForSequenceClassification""",
   ]


if TYPE_CHECKING:
   from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig

   try:
      if not is_sentencepiece_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_llama import LlamaTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_llama_fast import LlamaTokenizerFast

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel


else:
   import sys

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



