






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(__lowerCamelCase   )
class 				__UpperCAmelCase		(__lowerCamelCase   ):







			def __init__(     self:  str				,     **UpperCAmelCase_:  int					):







									'''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:  Union[str, Any]				,     UpperCAmelCase_:  Union[str, "Image.Image", List[Dict[str, Any]]]				,     UpperCAmelCase_:  Union[str, List[str]] = None				,     **UpperCAmelCase_:  List[str]				,     ):







									'''simple docstring'''




									if "text_queries" in kwargs:
															_SCREAMING_SNAKE_CASE     				=  kwargs.pop("""text_queries"""					)

									if isinstance(UpperCamelCase_				,     (str, Image.Image)					):
															_SCREAMING_SNAKE_CASE     				=  {"""image""": image, """candidate_labels""": candidate_labels}
									else:
															_SCREAMING_SNAKE_CASE     				=  image
									_SCREAMING_SNAKE_CASE     				=  super().__call__(UpperCamelCase_				,     **UpperCamelCase_					)
									return results







			def 							UpperCamelCase				(     self:  List[str]				,     **UpperCAmelCase_:  Dict					):







									'''simple docstring'''




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







			def 							UpperCamelCase				(     self:  Any				,     UpperCAmelCase_:  Optional[Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  load_image(inputs["""image"""]					)
									_SCREAMING_SNAKE_CASE     				=  inputs["""candidate_labels"""]
									if isinstance(UpperCamelCase_				,     UpperCamelCase_					):
															_SCREAMING_SNAKE_CASE     				=  candidate_labels.split(""","""					)

									_SCREAMING_SNAKE_CASE     				=  torch.tensor([[image.height, image.width]]				,     dtype=torch.intaa					)
									for i, candidate_label in enumerate(UpperCamelCase_					):
															_SCREAMING_SNAKE_CASE     				=  self.tokenizer(UpperCamelCase_				,     return_tensors=self.framework					)
															_SCREAMING_SNAKE_CASE     				=  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 							UpperCamelCase				(     self:  List[Any]				,     UpperCAmelCase_:  Tuple					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  model_inputs.pop("""target_size"""					)
									_SCREAMING_SNAKE_CASE     				=  model_inputs.pop("""candidate_label"""					)
									_SCREAMING_SNAKE_CASE     				=  model_inputs.pop("""is_last"""					)

									_SCREAMING_SNAKE_CASE     				=  self.model(**UpperCamelCase_					)

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







			def 							UpperCamelCase				(     self:  List[Any]				,     UpperCAmelCase_:  Any				,     UpperCAmelCase_:  Dict=0.1				,     UpperCAmelCase_:  Union[str, Any]=None					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  []
									for model_output in model_outputs:
															_SCREAMING_SNAKE_CASE     				=  model_output["""candidate_label"""]
															_SCREAMING_SNAKE_CASE     				=  BaseModelOutput(UpperCamelCase_					)
															_SCREAMING_SNAKE_CASE     				=  self.image_processor.post_process_object_detection(
															    outputs=UpperCamelCase_				,     threshold=UpperCamelCase_				,     target_sizes=model_output["""target_size"""]					)[0]

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

																					_SCREAMING_SNAKE_CASE     				=  {"""score""": score, """label""": label, """box""": box}
																					results.append(UpperCamelCase_					)

									_SCREAMING_SNAKE_CASE     				=  sorted(UpperCamelCase_				,     key=lambda UpperCAmelCase_					: x["score"]				,     reverse=UpperCamelCase_					)
									if top_k:
															_SCREAMING_SNAKE_CASE     				=  results[:top_k]

									return results







			def 							UpperCamelCase				(     self:  Optional[Any]				,     UpperCAmelCase_:  "torch.Tensor"					):







									'''simple docstring'''




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









from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


UpperCamelCase			    =     {
    '''configuration_layoutlmv3''': [
        '''LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''LayoutLMv3Config''',
        '''LayoutLMv3OnnxConfig''',
    ],
    '''processing_layoutlmv3''': ['''LayoutLMv3Processor'''],
    '''tokenization_layoutlmv3''': ['''LayoutLMv3Tokenizer'''],
}

try:
		if not is_tokenizers_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCamelCase			    =     ['''LayoutLMv3TokenizerFast''']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCamelCase			    =     [
		    '''LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''LayoutLMv3ForQuestionAnswering''',
		    '''LayoutLMv3ForSequenceClassification''',
		    '''LayoutLMv3ForTokenClassification''',
		    '''LayoutLMv3Model''',
		    '''LayoutLMv3PreTrainedModel''',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCamelCase			    =     [
		    '''TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''TFLayoutLMv3ForQuestionAnswering''',
		    '''TFLayoutLMv3ForSequenceClassification''',
		    '''TFLayoutLMv3ForTokenClassification''',
		    '''TFLayoutLMv3Model''',
		    '''TFLayoutLMv3PreTrainedModel''',
		]

try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCamelCase			    =     ['''LayoutLMv3FeatureExtractor''']
		UpperCamelCase			    =     ['''LayoutLMv3ImageProcessor''']


if TYPE_CHECKING:
		from .configuration_layoutlmva import (
		    LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    LayoutLMvaConfig,
		    LayoutLMvaOnnxConfig,
		)
		from .processing_layoutlmva import LayoutLMvaProcessor
		from .tokenization_layoutlmva import LayoutLMvaTokenizer

		try:
				if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_layoutlmva import (
				    LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
				    LayoutLMvaForQuestionAnswering,
				    LayoutLMvaForSequenceClassification,
				    LayoutLMvaForTokenClassification,
				    LayoutLMvaModel,
				    LayoutLMvaPreTrainedModel,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_layoutlmva import (
				    TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFLayoutLMvaForQuestionAnswering,
				    TFLayoutLMvaForSequenceClassification,
				    TFLayoutLMvaForTokenClassification,
				    TFLayoutLMvaModel,
				    TFLayoutLMvaPreTrainedModel,
				)

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
				from .image_processing_layoutlmva import LayoutLMvaImageProcessor

else:
		import sys

		UpperCamelCase			    =     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

