
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(UpperCamelCase_			)
class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     def __init__(				self    ,    **__SCREAMING_SNAKE_CASE	)	-> Optional[int]:




           """simple docstring"""







           super().__init__(**__SCREAMING_SNAKE_CASE	)

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

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






     def __call__(				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE = None    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> str:




           """simple docstring"""







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

           if isinstance(__SCREAMING_SNAKE_CASE    ,    (str, Image.Image)	):
                 UpperCamelCase__     : Optional[int]											=					{'''image''': image, '''candidate_labels''': candidate_labels}
           else:
                 UpperCamelCase__     : int											=					image
           UpperCamelCase__     : List[str]											=					super().__call__(__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)
           return results






     def  __SCREAMING_SNAKE_CASE      (				self    ,    **__SCREAMING_SNAKE_CASE	)	-> Any:




           """simple docstring"""







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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> Optional[Any]:




           """simple docstring"""







           UpperCamelCase__     : Dict											=					load_image(inputs['''image''']	)
           UpperCamelCase__     : Tuple											=					inputs['''candidate_labels''']
           if isinstance(__SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	):
                 UpperCamelCase__     : int											=					candidate_labels.split(''','''	)

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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> Union[str, Any]:




           """simple docstring"""







           UpperCamelCase__     : Union[str, Any]											=					model_inputs.pop('''target_size'''	)
           UpperCamelCase__     : List[str]											=					model_inputs.pop('''candidate_label'''	)
           UpperCamelCase__     : Dict											=					model_inputs.pop('''is_last'''	)

           UpperCamelCase__     : List[str]											=					self.model(**__SCREAMING_SNAKE_CASE	)

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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=None	)	-> Union[str, Any]:




           """simple docstring"""







           UpperCamelCase__     : str											=					[]
           for model_output in model_outputs:
                 UpperCamelCase__     : Union[str, Any]											=					model_output['''candidate_label''']
                 UpperCamelCase__     : int											=					BaseModelOutput(__SCREAMING_SNAKE_CASE	)
                 UpperCamelCase__     : int											=					self.image_processor.post_process_object_detection(
                     outputs=__SCREAMING_SNAKE_CASE    ,    threshold=__SCREAMING_SNAKE_CASE    ,    target_sizes=model_output['''target_size''']	)[0]

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

                       UpperCamelCase__     : Optional[int]											=					{'''score''': score, '''label''': label, '''box''': box}
                       results.append(__SCREAMING_SNAKE_CASE	)

           UpperCamelCase__     : str											=					sorted(__SCREAMING_SNAKE_CASE    ,    key=lambda __SCREAMING_SNAKE_CASE	: x["score"]    ,    reverse=__SCREAMING_SNAKE_CASE	)
           if top_k:
                 UpperCamelCase__     : Any											=					results[:top_k]

           return results






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> Dict[str, int]:




           """simple docstring"""







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




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase  =logging.get_logger(__name__)

lowerCamelCase  ={
    "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json",
    "distilbert-base-uncased-distilled-squad": (
        "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/config.json",
    "distilbert-base-cased-distilled-squad": (
        "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json",
    "distilbert-base-multilingual-cased": (
        "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json"
    ),
    "distilbert-base-uncased-finetuned-sst-2-english": (
        "https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json"
    ),
}




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	'''distilbert'''
     SCREAMING_SNAKE_CASE_		 =	{
         '''hidden_size''': '''dim''',
         '''num_attention_heads''': '''n_heads''',
         '''num_hidden_layers''': '''n_layers''',
     }






     def __init__(				self    ,    __SCREAMING_SNAKE_CASE=3_0_5_2_2    ,    __SCREAMING_SNAKE_CASE=5_1_2    ,    __SCREAMING_SNAKE_CASE=False    ,    __SCREAMING_SNAKE_CASE=6    ,    __SCREAMING_SNAKE_CASE=1_2    ,    __SCREAMING_SNAKE_CASE=7_6_8    ,    __SCREAMING_SNAKE_CASE=4 * 7_6_8    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE="gelu"    ,    __SCREAMING_SNAKE_CASE=0.02    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.2    ,    __SCREAMING_SNAKE_CASE=0    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> Optional[Any]:




           """simple docstring"""







           UpperCamelCase__     : List[Any]											=					vocab_size
           UpperCamelCase__     : Dict											=					max_position_embeddings
           UpperCamelCase__     : Any											=					sinusoidal_pos_embds
           UpperCamelCase__     : Dict											=					n_layers
           UpperCamelCase__     : List[Any]											=					n_heads
           UpperCamelCase__     : Dict											=					dim
           UpperCamelCase__     : Dict											=					hidden_dim
           UpperCamelCase__     : Optional[int]											=					dropout
           UpperCamelCase__     : Optional[Any]											=					attention_dropout
           UpperCamelCase__     : Tuple											=					activation
           UpperCamelCase__     : Optional[int]											=					initializer_range
           UpperCamelCase__     : Optional[int]											=					qa_dropout
           UpperCamelCase__     : str											=					seq_classif_dropout
           super().__init__(**__SCREAMING_SNAKE_CASE    ,    pad_token_id=__SCREAMING_SNAKE_CASE	)




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     @property
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Mapping[str, Mapping[int, str]]:




           """simple docstring"""







           if self.task == "multiple-choice":
                 UpperCamelCase__     : Union[str, Any]											=					{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
           else:
                 UpperCamelCase__     : int											=					{0: '''batch''', 1: '''sequence'''}
           return OrderedDict(
               [
                   ('''input_ids''', dynamic_axis),
                   ('''attention_mask''', dynamic_axis),
               ]	)


