






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

UpperCAmelCase__				   =		logging.get_logger(__name__)






@add_end_docstrings(lowercase   )
class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      def __init__(      self      :						str ,					**__UpperCAmelCase      :						Optional[int]  )    ->Dict:




       """simple docstring"""


       super().__init__(**__UpperCAmelCase  )

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

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







      def __call__(      self      :						Optional[Any] ,					__UpperCAmelCase      :						Union[str, "Image.Image", List[Dict[str, Any]]] ,					__UpperCAmelCase      :						Union[str, List[str]] = None ,					**__UpperCAmelCase      :						Dict ,					)    ->Optional[int]:




       """simple docstring"""


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

       if isinstance(__UpperCAmelCase ,					(str, Image.Image)  ):
        a		  =      {'''image''': image, '''candidate_labels''': candidate_labels}
       else:
        a		  =      image
       a		  =      super().__call__(__UpperCAmelCase ,					**__UpperCAmelCase  )
       return results







      def       __lowerCAmelCase					(      self      :						Union[str, Any] ,					**__UpperCAmelCase      :						Optional[int]  )    ->Dict:




       """simple docstring"""


       a		  =      {}
       if "threshold" in kwargs:
        a		  =      kwargs['''threshold''']
       if "top_k" in kwargs:
        a		  =      kwargs['''top_k''']
       return {}, {}, postprocess_params







      def       __lowerCAmelCase					(      self      :						str ,					__UpperCAmelCase      :						int  )    ->Optional[Any]:




       """simple docstring"""


       a		  =      load_image(inputs['''image''']  )
       a		  =      inputs['''candidate_labels''']
       if isinstance(__UpperCAmelCase ,					__UpperCAmelCase  ):
        a		  =      candidate_labels.split(''','''  )

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







      def       __lowerCAmelCase					(      self      :						Optional[int] ,					__UpperCAmelCase      :						int  )    ->str:




       """simple docstring"""


       a		  =      model_inputs.pop('''target_size'''  )
       a		  =      model_inputs.pop('''candidate_label'''  )
       a		  =      model_inputs.pop('''is_last'''  )

       a		  =      self.model(**__UpperCAmelCase  )

       a		  =      {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
       return model_outputs







      def       __lowerCAmelCase					(      self      :						int ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						List[str]=0.1 ,					__UpperCAmelCase      :						List[str]=None  )    ->List[Any]:




       """simple docstring"""


       a		  =      []
       for model_output in model_outputs:
        a		  =      model_output['''candidate_label''']
        a		  =      BaseModelOutput(__UpperCAmelCase  )
        a		  =      self.image_processor.post_process_object_detection(
            outputs=__UpperCAmelCase ,					threshold=__UpperCAmelCase ,					target_sizes=model_output['''target_size''']  )[0]

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

         a		  =      {'''score''': score, '''label''': label, '''box''': box}
         results.append(__UpperCAmelCase  )

       a		  =      sorted(__UpperCAmelCase ,					key=lambda __UpperCAmelCase  : x["score"] ,					reverse=__UpperCAmelCase  )
       if top_k:
        a		  =      results[:top_k]

       return results







      def       __lowerCAmelCase					(      self      :						Any ,					__UpperCAmelCase      :						"torch.Tensor"  )    ->Dict[str, int]:




       """simple docstring"""


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










from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase__				   =		logging.get_logger(__name__)

UpperCAmelCase__				   =		{}






class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      __snake_case       =  '''llama'''
      __snake_case       =  ['''past_key_values''']







      def __init__(      self      :						Optional[Any] ,					__UpperCAmelCase      :						Union[str, Any]=32_000 ,					__UpperCAmelCase      :						str=4_096 ,					__UpperCAmelCase      :						int=11_008 ,					__UpperCAmelCase      :						Tuple=32 ,					__UpperCAmelCase      :						Optional[int]=32 ,					__UpperCAmelCase      :						List[str]=None ,					__UpperCAmelCase      :						Union[str, Any]="silu" ,					__UpperCAmelCase      :						Tuple=2_048 ,					__UpperCAmelCase      :						Optional[Any]=0.02 ,					__UpperCAmelCase      :						Any=1e-6 ,					__UpperCAmelCase      :						Union[str, Any]=True ,					__UpperCAmelCase      :						Optional[int]=0 ,					__UpperCAmelCase      :						Optional[int]=1 ,					__UpperCAmelCase      :						Optional[int]=2 ,					__UpperCAmelCase      :						Tuple=1 ,					__UpperCAmelCase      :						List[str]=False ,					__UpperCAmelCase      :						Tuple=None ,					**__UpperCAmelCase      :						Tuple ,					)    ->str:




       """simple docstring"""


       a		  =      vocab_size
       a		  =      max_position_embeddings
       a		  =      hidden_size
       a		  =      intermediate_size
       a		  =      num_hidden_layers
       a		  =      num_attention_heads

       # for backward compatibility
       if num_key_value_heads is None:
        a		  =      num_attention_heads

       a		  =      num_key_value_heads
       a		  =      hidden_act
       a		  =      initializer_range
       a		  =      rms_norm_eps
       a		  =      pretraining_tp
       a		  =      use_cache
       a		  =      rope_scaling
       self._rope_scaling_validation()

       super().__init__(
           pad_token_id=__UpperCAmelCase ,					bos_token_id=__UpperCAmelCase ,					eos_token_id=__UpperCAmelCase ,					tie_word_embeddings=__UpperCAmelCase ,					**__UpperCAmelCase ,					)







      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Tuple:




       """simple docstring"""


       if self.rope_scaling is None:
        return

       if not isinstance(self.rope_scaling ,					__UpperCAmelCase  ) or len(self.rope_scaling  ) != 2:
        raise ValueError(
            '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
            F"""got {self.rope_scaling}"""  )
       a		  =      self.rope_scaling.get('''type''' ,					__UpperCAmelCase  )
       a		  =      self.rope_scaling.get('''factor''' ,					__UpperCAmelCase  )
       if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
        raise ValueError(
            F"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"""  )
       if rope_scaling_factor is None or not isinstance(__UpperCAmelCase ,					__UpperCAmelCase  ) or rope_scaling_factor <= 1.0:
        raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}"""  )


