



"""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

__lowerCAmelCase							:       List[str]          =       logging.get_logger(__name__)



@add_end_docstrings(SCREAMING_SNAKE_CASE__		)
class  _lowerCAmelCase     (					SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		def __init__(       self				,     **_lowercase )			->    List[Any]:







								'''simple docstring'''

								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				,     _lowercase				,     _lowercase = None				,     **_lowercase				,     )			->    Any:







								'''simple docstring'''

								if "text_queries" in kwargs:
														snake_case_ :			Optional[Any]            =      kwargs.pop("""text_queries""" )

								if isinstance(_lowercase				,     (str, Image.Image) ):
														snake_case_ :			int            =      {"""image""": image, """candidate_labels""": candidate_labels}
								else:
														snake_case_ :			Optional[int]            =      image
								snake_case_ :			Any            =      super().__call__(_lowercase				,     **_lowercase )
								return results





		def  UpperCAmelCase__				(       self				,     **_lowercase )			->    Dict:







								'''simple docstring'''

								snake_case_ :			Optional[int]            =      {}
								if "threshold" in kwargs:
														snake_case_ :			str            =      kwargs["""threshold"""]
								if "top_k" in kwargs:
														snake_case_ :			Tuple            =      kwargs["""top_k"""]
								return {}, {}, postprocess_params





		def  UpperCAmelCase__				(       self				,     _lowercase )			->    Optional[int]:







								'''simple docstring'''

								snake_case_ :			List[str]            =      load_image(inputs["""image"""] )
								snake_case_ :			Tuple            =      inputs["""candidate_labels"""]
								if isinstance(_lowercase				,     _lowercase ):
														snake_case_ :			Dict            =      candidate_labels.split(""",""" )

								snake_case_ :			int            =      torch.tensor([[image.height, image.width]]				,     dtype=torch.intaa )
								for i, candidate_label in enumerate(_lowercase ):
														snake_case_ :			Dict            =      self.tokenizer(_lowercase				,     return_tensors=self.framework )
														snake_case_ :			Union[str, Any]            =      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  UpperCAmelCase__				(       self				,     _lowercase )			->    Tuple:







								'''simple docstring'''

								snake_case_ :			int            =      model_inputs.pop("""target_size""" )
								snake_case_ :			int            =      model_inputs.pop("""candidate_label""" )
								snake_case_ :			Optional[Any]            =      model_inputs.pop("""is_last""" )

								snake_case_ :			Dict            =      self.model(**_lowercase )

								snake_case_ :			Union[str, Any]            =      {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
								return model_outputs





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase=0.1				,     _lowercase=None )			->    Any:







								'''simple docstring'''

								snake_case_ :			Any            =      []
								for model_output in model_outputs:
														snake_case_ :			List[str]            =      model_output["""candidate_label"""]
														snake_case_ :			Union[str, Any]            =      BaseModelOutput(_lowercase )
														snake_case_ :			Dict            =      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_ :			List[Any]            =      outputs["""scores"""][index].item()
																				snake_case_ :			List[str]            =      self._get_bounding_box(outputs["""boxes"""][index][0] )

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

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

								return results





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







								'''simple docstring'''

								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_ :			str            =      {
								    """xmin""": xmin,
								    """ymin""": ymin,
								    """xmax""": xmax,
								    """ymax""": ymax,
								}
								return bbox







'''simple docstring'''



def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> int:




     '''simple docstring'''





     __snake_case            =	abs(_lowerCamelCase						)
     __snake_case            =	0
     while n > 0:
          res += n % 10
          n //= 10
     return res







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> int:




     '''simple docstring'''





     __snake_case            =	abs(_lowerCamelCase						)
     return n if n < 10 else n % 10 + sum_of_digits(n // 10						)







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> int:




     '''simple docstring'''





     return sum(int(_lowerCamelCase						) for c in str(abs(_lowerCamelCase						)						)						)







def       _UpperCamelCase			()-> None:




     '''simple docstring'''





     from collections.abc import Callable
     from timeit import timeit

     def benchmark_a_function(_lowerCamelCase				:  Callable ,						_lowerCamelCase				:  int						) -> None:
          __snake_case            =	f'''{func.__name__}({value})'''
          __snake_case            =	timeit(f'''__main__.{call}''' ,						setup='''import __main__'''						)
          print(f'''{call:56} = {func(_lowerCamelCase						)} -- {timing:.4f} seconds'''						)

     for value in (26_21_44, 11_25_89_99_06_84_26_24, 1_26_76_50_60_02_28_22_94_01_49_67_03_20_53_76):
          for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
               benchmark_a_function(_lowerCamelCase ,						_lowerCamelCase						)
          print()


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     benchmark()






