

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(_lowercase							)
class 	lowercase    (				_lowercase							):


		"""simple docstring"""




		def __init__(				self	,       **__snake_case):
			super().__init__(**__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(__snake_case)


		def __call__(				self	,       __snake_case	,       __snake_case = None	,       **__snake_case	,       ):
			if "text_queries" in kwargs:
				_UpperCamelCase   :		List[Any]			=						kwargs.pop('text_queries')

			if isinstance(__snake_case	,       (str, Image.Image)):
				_UpperCamelCase   :		Union[str, Any]			=						{'image': image, 'candidate_labels': candidate_labels}
			else:
				_UpperCamelCase   :		int			=						image
			_UpperCamelCase   :		Tuple			=						super().__call__(__snake_case	,       **__snake_case)
			return results


		def 		A__					(				self	,       **__snake_case):
			_UpperCamelCase   :		int			=						{}
			if "threshold" in kwargs:
				_UpperCamelCase   :		Tuple			=						kwargs['threshold']
			if "top_k" in kwargs:
				_UpperCamelCase   :		Optional[Any]			=						kwargs['top_k']
			return {}, {}, postprocess_params


		def 		A__					(				self	,       __snake_case):
			_UpperCamelCase   :		Dict			=						load_image(inputs['image'])
			_UpperCamelCase   :		Dict			=						inputs['candidate_labels']
			if isinstance(__snake_case	,       __snake_case):
				_UpperCamelCase   :		Tuple			=						candidate_labels.split(',')

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


		def 		A__					(				self	,       __snake_case):
			_UpperCamelCase   :		Any			=						model_inputs.pop('target_size')
			_UpperCamelCase   :		str			=						model_inputs.pop('candidate_label')
			_UpperCamelCase   :		List[str]			=						model_inputs.pop('is_last')

			_UpperCamelCase   :		Any			=						self.model(**__snake_case)

			_UpperCamelCase   :		List[str]			=						{'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
			return model_outputs


		def 		A__					(				self	,       __snake_case	,       __snake_case=0.1	,       __snake_case=None):
			_UpperCamelCase   :		Union[str, Any]			=						[]
			for model_output in model_outputs:
				_UpperCamelCase   :		Union[str, Any]			=						model_output['candidate_label']
				_UpperCamelCase   :		Any			=						BaseModelOutput(__snake_case)
				_UpperCamelCase   :		Union[str, Any]			=						self.image_processor.post_process_object_detection(
				    outputs=__snake_case	,       threshold=__snake_case	,       target_sizes=model_output['target_size'])[0]

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

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

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

			return results






		def 		A__					(				self	,       __snake_case):
			if self.framework != "pt":
				raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.')
			_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase   :		List[Any]			=						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__								=		{
    """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/config.json""",
    """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/config.json""",
    """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/config.json""",
    """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/config.json""",
    """bert-base-multilingual-uncased""": """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json""",
    """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json""",
    """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/config.json""",
    """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/config.json""",
    """bert-large-uncased-whole-word-masking""": (
        """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json"""
    ),
    """bert-large-cased-whole-word-masking""": (
        """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json"""
    ),
    """bert-large-uncased-whole-word-masking-finetuned-squad""": (
        """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json"""
    ),
    """bert-large-cased-whole-word-masking-finetuned-squad""": (
        """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json"""
    ),
    """bert-base-cased-finetuned-mrpc""": """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json""",
    """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json""",
    """bert-base-german-dbmdz-uncased""": """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json""",
    """cl-tohoku/bert-base-japanese""": """https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json""",
    """cl-tohoku/bert-base-japanese-whole-word-masking""": (
        """https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json"""
    ),
    """cl-tohoku/bert-base-japanese-char""": (
        """https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json"""
    ),
    """cl-tohoku/bert-base-japanese-char-whole-word-masking""": (
        """https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json"""
    ),
    """TurkuNLP/bert-base-finnish-cased-v1""": (
        """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json"""
    ),
    """TurkuNLP/bert-base-finnish-uncased-v1""": (
        """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json"""
    ),
    """wietsedv/bert-base-dutch-cased""": """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json""",
    # See all BERT models at https://huggingface.co/models?filter=bert
}







class 	lowercase    (				_lowercase							):


		"""simple docstring"""




		a__					       =  "bert"


		def __init__(				self	,       __snake_case=3_05_22	,       __snake_case=7_68	,       __snake_case=12	,       __snake_case=12	,       __snake_case=30_72	,       __snake_case="gelu"	,       __snake_case=0.1	,       __snake_case=0.1	,       __snake_case=5_12	,       __snake_case=2	,       __snake_case=0.0_2	,       __snake_case=1e-12	,       __snake_case=0	,       __snake_case="absolute"	,       __snake_case=True	,       __snake_case=None	,       **__snake_case	,       ):
			super().__init__(pad_token_id=__snake_case	,       **__snake_case)

			_UpperCamelCase   :		int			=						vocab_size
			_UpperCamelCase   :		Optional[Any]			=						hidden_size
			_UpperCamelCase   :		Optional[Any]			=						num_hidden_layers
			_UpperCamelCase   :		List[str]			=						num_attention_heads
			_UpperCamelCase   :		int			=						hidden_act
			_UpperCamelCase   :		Optional[Any]			=						intermediate_size
			_UpperCamelCase   :		Union[str, Any]			=						hidden_dropout_prob
			_UpperCamelCase   :		Tuple			=						attention_probs_dropout_prob
			_UpperCamelCase   :		Optional[int]			=						max_position_embeddings
			_UpperCamelCase   :		str			=						type_vocab_size
			_UpperCamelCase   :		Optional[Any]			=						initializer_range
			_UpperCamelCase   :		List[str]			=						layer_norm_eps
			_UpperCamelCase   :		Any			=						position_embedding_type
			_UpperCamelCase   :		Any			=						use_cache
			_UpperCamelCase   :		Any			=						classifier_dropout







class 	lowercase    (				_lowercase							):


		"""simple docstring"""




		@property
		def 		A__					(				self):
			if self.task == "multiple-choice":
				_UpperCamelCase   :		Union[str, Any]			=						{0: 'batch', 1: 'choice', 2: 'sequence'}
			else:
				_UpperCamelCase   :		Optional[Any]			=						{0: 'batch', 1: 'sequence'}
			return OrderedDict(
			    [
			        ('input_ids', dynamic_axis),
			        ('attention_mask', dynamic_axis),
			        ('token_type_ids', dynamic_axis),
			    ])




