


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

_A			=						logging.get_logger(__name__)






@add_end_docstrings(A_		)
class    UpperCAmelCase__	( A_		):



    """simple docstring"""






    def __init__(      self ,       **A_   )  ->	Optional[int]:
         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 ,       A_ ,       A_ = None ,       **A_ ,       )  ->	int:
         if "text_queries" in kwargs:
              __UpperCamelCase   							=kwargs.pop('text_queries'   )

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






    def _a (      self ,       **A_   )  ->	int:
         __UpperCamelCase   							={}
         if "threshold" in kwargs:
              __UpperCamelCase   							=kwargs['threshold']
         if "top_k" in kwargs:
              __UpperCamelCase   							=kwargs['top_k']
         return {}, {}, postprocess_params






    def _a (      self ,       A_   )  ->	Tuple:
         __UpperCamelCase   							=load_image(inputs['image']   )
         __UpperCamelCase   							=inputs['candidate_labels']
         if isinstance(A_ ,       A_   ):
              __UpperCamelCase   							=candidate_labels.split(','   )

         __UpperCamelCase   							=torch.tensor([[image.height, image.width]] ,       dtype=torch.intaa   )
         for i, candidate_label in enumerate(A_   ):
              __UpperCamelCase   							=self.tokenizer(A_ ,       return_tensors=self.framework   )
              __UpperCamelCase   							=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 _a (      self ,       A_   )  ->	Optional[Any]:
         __UpperCamelCase   							=model_inputs.pop('target_size'   )
         __UpperCamelCase   							=model_inputs.pop('candidate_label'   )
         __UpperCamelCase   							=model_inputs.pop('is_last'   )

         __UpperCamelCase   							=self.model(**A_   )

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






    def _a (      self ,       A_ ,       A_=0.1 ,       A_=None   )  ->	Dict:
         __UpperCamelCase   							=[]
         for model_output in model_outputs:
              __UpperCamelCase   							=model_output['candidate_label']
              __UpperCamelCase   							=BaseModelOutput(A_   )
              __UpperCamelCase   							=self.image_processor.post_process_object_detection(
                  outputs=A_ ,       threshold=A_ ,       target_sizes=model_output['target_size']   )[0]

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

                   __UpperCamelCase   							={'score': score, 'label': label, 'box': box}
                   results.append(A_   )

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

         return results






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









from ..utils import DummyObject, requires_backends






class    UpperCAmelCase__	( metaclass=A_		):



    """simple docstring"""






    UpperCAmelCase__						:		Any              =  ["speech"]






    def __init__(      self ,       *A_ ,       **A_   )  ->	Any:
         requires_backends(self ,       ['speech']   )






class    UpperCAmelCase__	( metaclass=A_		):



    """simple docstring"""






    UpperCAmelCase__						:		Union[str, Any]              =  ["speech"]






    def __init__(      self ,       *A_ ,       **A_   )  ->	Union[str, Any]:
         requires_backends(self ,       ['speech']   )





