




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






						def __init__(     self	,    **_A    ):




											"""simple docstring"""



											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	,    ):




											"""simple docstring"""



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

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






						def        __SCREAMING_SNAKE_CASE(     self	,    **_A    ):




											"""simple docstring"""



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






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



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

											__lowerCAmelCase            = torch.tensor([[image.height, image.width]]	,    dtype=torch.intaa    )
											for i, candidate_label in enumerate(_a    ):
																__lowerCAmelCase            = self.tokenizer(_a	,    return_tensors=self.framework    )
																__lowerCAmelCase            = 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        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



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

											__lowerCAmelCase            = self.model(**_a    )

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






						def        __SCREAMING_SNAKE_CASE(     self	,    _A	,    _A=0.1	,    _A=None    ):




											"""simple docstring"""



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

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

																					__lowerCAmelCase            = {"""score""": score, """label""": label, """box""": box}
																					results.append(_a    )

											__lowerCAmelCase            = sorted(_a	,    key=lambda _A    : x["score"]	,    reverse=_a    )
											if top_k:
																__lowerCAmelCase            = results[:top_k]

											return results






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



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










import os


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
UpperCamelCase__					    =    """."""


if __name__ == "__main__":
					UpperCamelCase__					    =    os.path.join(REPO_PATH, """utils/documentation_tests.txt""")
					UpperCamelCase__					    =    []
					UpperCamelCase__					    =    []
					with open(doctest_file_path) as fp:
										for line in fp:
															UpperCamelCase__					    =    line.strip()
															UpperCamelCase__					    =    os.path.join(REPO_PATH, line)
															if not (os.path.isfile(path) or os.path.isdir(path)):
																				non_existent_paths.append(line)
															all_paths.append(path)
					if len(non_existent_paths) > 0:
										UpperCamelCase__					    =    """\n""".join(non_existent_paths)
										raise ValueError(f'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''')
					if all_paths != sorted(all_paths):
										raise ValueError("""Files in `utils/documentation_tests.txt` are not in alphabetical order.""")




