



"""simple docstring"""







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(SCREAMING_SNAKE_CASE__)
class       _a  ( SCREAMING_SNAKE_CASE__):



			def __init__(			self							:				Tuple   ,	**_lowercase							:				List[str]		)							->					int:
									super().__init__(**_lowercase		)

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

									requires_backends(self   ,	"vision"		)
									self.check_model_type(_lowercase		)



			def __call__(			self							:				Any   ,	_lowercase							:				Union[str, "Image.Image", List[Dict[str, Any]]]   ,	_lowercase							:				Union[str, List[str]] = None   ,	**_lowercase							:				Any   ,	)							->					Union[str, Any]:
									if "text_queries" in kwargs:
															snake_case   :			Union[str, Any]						    = kwargs.pop("text_queries"		)

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



			def 				__lowercase					(			self							:				Optional[Any]   ,	**_lowercase							:				int		)							->					List[Any]:
									snake_case   :			int						    = {}
									if "threshold" in kwargs:
															snake_case   :			Union[str, Any]						    = kwargs["threshold"]
									if "top_k" in kwargs:
															snake_case   :			Optional[Any]						    = kwargs["top_k"]
									return {}, {}, postprocess_params



			def 				__lowercase					(			self							:				List[str]   ,	_lowercase							:				str		)							->					Optional[int]:
									snake_case   :			Tuple						    = load_image(inputs["image"]		)
									snake_case   :			int						    = inputs["candidate_labels"]
									if isinstance(_lowercase   ,	_lowercase		):
															snake_case   :			Dict						    = candidate_labels.split(","		)

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



			def 				__lowercase					(			self							:				int   ,	_lowercase							:				Optional[Any]		)							->					Tuple:
									snake_case   :			List[str]						    = model_inputs.pop("target_size"		)
									snake_case   :			Dict						    = model_inputs.pop("candidate_label"		)
									snake_case   :			str						    = model_inputs.pop("is_last"		)

									snake_case   :			Optional[Any]						    = self.model(**_lowercase		)

									snake_case   :			Optional[Any]						    = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
									return model_outputs



			def 				__lowercase					(			self							:				Union[str, Any]   ,	_lowercase							:				Optional[int]   ,	_lowercase							:				Optional[Any]=0.1   ,	_lowercase							:				Any=None		)							->					List[str]:
									snake_case   :			int						    = []
									for model_output in model_outputs:
															snake_case   :			Tuple						    = model_output["candidate_label"]
															snake_case   :			int						    = BaseModelOutput(_lowercase		)
															snake_case   :			str						    = self.image_processor.post_process_object_detection(
															    outputs=_lowercase   ,	threshold=_lowercase   ,	target_sizes=model_output["target_size"]		)[0]

															for index in outputs["scores"].nonzero():
																					snake_case   :			Union[str, Any]						    = outputs["scores"][index].item()
																					snake_case   :			str						    = self._get_bounding_box(outputs["boxes"][index][0]		)

																					snake_case   :			int						    = {"score": score, "label": label, "box": box}
																					results.append(_lowercase		)

									snake_case   :			int						    = sorted(_lowercase   ,	key=lambda _lowercase		: x["score"]   ,	reverse=_lowercase		)
									if top_k:
															snake_case   :			Any						    = results[:top_k]

									return results



			def 				__lowercase					(			self							:				List[Any]   ,	_lowercase							:				"torch.Tensor"		)							->					Dict[str, int]:
									if self.framework != "pt":
															raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch."		)
									snake_case    ,			snake_case    ,			snake_case    ,			snake_case   :			Optional[int]						    = box.int().tolist()
									snake_case   :			Dict						    = {
									    "xmin": xmin,
									    "ymin": ymin,
									    "xmax": xmax,
									    "ymax": ymax,
									}
									return bbox








"""simple docstring"""







import importlib
import inspect
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
A		=						'src/transformers'


# This is to make sure the transformers module imported is the one in the repo.
A		=						importlib.util.spec_from_file_location(
    'transformers',
    os.path.join(PATH_TO_TRANSFORMERS, '__init__.py'),
    submodule_search_locations=[PATH_TO_TRANSFORMERS],
)
A		=						spec.loader.load_module()

A		=						transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
A		=						re.compile('\[(.+?)\]\((https://huggingface\.co/.+?)\)')


A		=						{
    'CLIPConfigMixin',
    'DecisionTransformerConfigMixin',
    'EncoderDecoderConfigMixin',
    'RagConfigMixin',
    'SpeechEncoderDecoderConfigMixin',
    'VisionEncoderDecoderConfigMixin',
    'VisionTextDualEncoderConfigMixin',
}

def  __SCREAMING_SNAKE_CASE		(			):
						"""simple docstring"""






						snake_case   :			Union[str, Any]						    = []

						for config_class in list(CONFIG_MAPPING.values() ):
												snake_case   :			List[str]						    = False

												# source code of `config_class`
												snake_case   :			Optional[int]						    = inspect.getsource(lowerCamelCase_ )
												snake_case   :			Optional[int]						    = _re_checkpoint.findall(lowerCamelCase_ )

												for checkpoint in checkpoints:
																		# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
																		# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
																		snake_case    ,			snake_case   :			Tuple						    = checkpoint

																		# verify the checkpoint name corresponds to the checkpoint link
																		snake_case   :			Any						    = f'''https://huggingface.co/{ckpt_name}'''
																		if ckpt_link == ckpt_link_from_name:
																								snake_case   :			List[str]						    = True
																								break

												snake_case   :			Any						    = config_class.__name__
												if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
																		configs_without_checkpoint.append(lowerCamelCase_ )

						if len(lowerCamelCase_ ) > 0:
												snake_case   :			List[str]						    = "\n".join(sorted(lowerCamelCase_ ) )
												raise ValueError(f'''The following configurations don\'t contain any valid checkpoint:\n{message}''' )


if __name__ == "__main__":
			check_config_docstrings_have_checkpoints()



