


'''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__						:   Optional[int]				=    logging.get_logger(__name__)





@add_end_docstrings(_UpperCAmelCase    )
class   UpperCAmelCase_    (_UpperCAmelCase    ):





    """simple docstring"""






    def __init__(				self     ,	**SCREAMING_SNAKE_CASE_      )							->	List[str]:
         super().__init__(**SCREAMING_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(SCREAMING_SNAKE_CASE_      )







    def __call__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None     ,	**SCREAMING_SNAKE_CASE_     ,	)							->	Optional[Any]:
         if "text_queries" in kwargs:
              __lowerCamelCase  :      List[Any]														=						kwargs.pop('text_queries'      )

         if isinstance(SCREAMING_SNAKE_CASE_     ,	(str, Image.Image)      ):
              __lowerCamelCase  :      str														=						{'image': image, 'candidate_labels': candidate_labels}
         else:
              __lowerCamelCase  :      List[str]														=						image
         __lowerCamelCase  :      Optional[int]														=						super().__call__(SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )
         return results







    def  lowercase_							(				self     ,	**SCREAMING_SNAKE_CASE_      )							->	List[Any]:
         __lowerCamelCase  :      Union[str, Any]														=						{}
         if "threshold" in kwargs:
              __lowerCamelCase  :      Any														=						kwargs['threshold']
         if "top_k" in kwargs:
              __lowerCamelCase  :      Tuple														=						kwargs['top_k']
         return {}, {}, postprocess_params







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_      )							->	List[str]:
         __lowerCamelCase  :      Union[str, Any]														=						load_image(inputs['image']      )
         __lowerCamelCase  :      int														=						inputs['candidate_labels']
         if isinstance(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ):
              __lowerCamelCase  :      Optional[int]														=						candidate_labels.split(','      )

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







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_      )							->	Any:
         __lowerCamelCase  :      Optional[Any]														=						model_inputs.pop('target_size'      )
         __lowerCamelCase  :      List[Any]														=						model_inputs.pop('candidate_label'      )
         __lowerCamelCase  :      List[Any]														=						model_inputs.pop('is_last'      )

         __lowerCamelCase  :      str														=						self.model(**SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      str														=						{'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
         return model_outputs







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=None      )							->	Tuple:
         __lowerCamelCase  :      Any														=						[]
         for model_output in model_outputs:
              __lowerCamelCase  :      Tuple														=						model_output['candidate_label']
              __lowerCamelCase  :      str														=						BaseModelOutput(SCREAMING_SNAKE_CASE_      )
              __lowerCamelCase  :      Dict														=						self.image_processor.post_process_object_detection(
                  outputs=SCREAMING_SNAKE_CASE_     ,	threshold=SCREAMING_SNAKE_CASE_     ,	target_sizes=model_output['target_size']      )[0]

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

                   __lowerCamelCase  :      Dict														=						{'score': score, 'label': label, 'box': box}
                   results.append(SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      str														=						sorted(SCREAMING_SNAKE_CASE_     ,	key=lambda SCREAMING_SNAKE_CASE_      : x["score"]     ,	reverse=SCREAMING_SNAKE_CASE_      )
         if top_k:
              __lowerCamelCase  :      List[str]														=						results[:top_k]

         return results







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_      )							->	Dict[str, int]:
         if self.framework != "pt":
              raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.'      )
         __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase  :      Union[str, Any]														=						box.int().tolist()
         __lowerCamelCase  :      Any														=						{
             'xmin': xmin,
             'ymin': ymin,
             'xmax': xmax,
             'ymax': ymax,
         }
         return bbox










'''simple docstring'''



from collections.abc import Generator
from math import sin



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						bytes:
     if len(UpperCAmelCase_				) != 32:
          raise ValueError('Input must be of length 32'				)

     __lowerCamelCase  :      Dict														=						B''
     for i in [3, 2, 1, 0]:
          little_endian += string_aa[8 * i : 8 * i + 8]
     return little_endian



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int				)	->						bytes:
     if i < 0:
          raise ValueError('Input must be non-negative'				)

     __lowerCamelCase  :      Union[str, Any]														=						format(UpperCAmelCase_ ,       '08x'				)[-8:]
     __lowerCamelCase  :      str														=						B''
     for i in [3, 2, 1, 0]:
          little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('utf-8'				)
     return little_endian_hex



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						bytes:
     __lowerCamelCase  :      Optional[Any]														=						B''
     for char in message:
          bit_string += format(UpperCAmelCase_ ,       '08b'				).encode('utf-8'				)
     __lowerCamelCase  :      List[str]														=						format(len(UpperCAmelCase_				) ,       '064b'				).encode('utf-8'				)

     # Pad bit_string to a multiple of 512 chars
     bit_string += b"1"
     while len(UpperCAmelCase_				) % 5_12 != 4_48:
          bit_string += b"0"
     bit_string += to_little_endian(start_len[32:]				) + to_little_endian(start_len[:32]				)

     return bit_string



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						Generator[list[int], None, None]:
     if len(UpperCAmelCase_				) % 5_12 != 0:
          raise ValueError('Input must have length that\'s a multiple of 512'				)

     for pos in range(0 ,       len(UpperCAmelCase_				) ,       5_12				):
          __lowerCamelCase  :      Any														=						bit_string[pos : pos + 5_12]
          __lowerCamelCase  :      Optional[int]														=						[]
          for i in range(0 ,       5_12 ,       32				):
               block_words.append(int(to_little_endian(block[i : i + 32]				) ,       2				)				)
          yield block_words



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int				)	->						int:
     if i < 0:
          raise ValueError('Input must be non-negative'				)

     __lowerCamelCase  :      List[Any]														=						format(UpperCAmelCase_ ,       '032b'				)
     __lowerCamelCase  :      Optional[int]														=						''
     for c in i_str:
          new_str += "1" if c == "0" else "0"
     return int(UpperCAmelCase_ ,       2				)



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							int				)	->						int:
     return (a + b) % 2**32



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							int				)	->						int:
     if i < 0:
          raise ValueError('Input must be non-negative'				)
     if shift < 0:
          raise ValueError('Shift must be non-negative'				)
     return ((i << shift) ^ (i >> (32 - shift))) % 2**32



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						bytes:
     __lowerCamelCase  :      Optional[Any]														=						preprocess(UpperCAmelCase_				)

     __lowerCamelCase  :      Union[str, Any]														=						[int(2**32 * abs(sin(i + 1				)				)				) for i in range(64				)]

     # Starting states
     __lowerCamelCase  :      Dict														=						0x67_45_23_01
     __lowerCamelCase  :      Union[str, Any]														=						0xef_cd_ab_89
     __lowerCamelCase  :      Optional[Any]														=						0x98_ba_dc_fe
     __lowerCamelCase  :      Union[str, Any]														=						0x10_32_54_76

     __lowerCamelCase  :      List[str]														=						[
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
     ]

     # Process bit string in chunks, each with 16 32-char words
     for block_words in get_block_words(UpperCAmelCase_				):
          __lowerCamelCase  :      Dict														=						aa
          __lowerCamelCase  :      Tuple														=						ba
          __lowerCamelCase  :      List[Any]														=						ca
          __lowerCamelCase  :      Dict														=						da

          # Hash current chunk
          for i in range(64				):
               if i <= 15:
                    # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
                    __lowerCamelCase  :      List[str]														=						d ^ (b & (c ^ d))
                    __lowerCamelCase  :      Optional[int]														=						i
               elif i <= 31:
                    # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
                    __lowerCamelCase  :      Optional[int]														=						c ^ (d & (b ^ c))
                    __lowerCamelCase  :      Tuple														=						(5 * i + 1) % 16
               elif i <= 47:
                    __lowerCamelCase  :      str														=						b ^ c ^ d
                    __lowerCamelCase  :      Any														=						(3 * i + 5) % 16
               else:
                    __lowerCamelCase  :      Union[str, Any]														=						c ^ (b | not_aa(UpperCAmelCase_				))
                    __lowerCamelCase  :      int														=						(7 * i) % 16
               __lowerCamelCase  :      Optional[int]														=						(f + a + added_consts[i] + block_words[g]) % 2**32
               __lowerCamelCase  :      Optional[Any]														=						d
               __lowerCamelCase  :      Tuple														=						c
               __lowerCamelCase  :      Optional[int]														=						b
               __lowerCamelCase  :      List[str]														=						sum_aa(UpperCAmelCase_ ,       left_rotate_aa(UpperCAmelCase_ ,       shift_amounts[i]				)				)

          # Add hashed chunk to running total
          __lowerCamelCase  :      int														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)
          __lowerCamelCase  :      str														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)
          __lowerCamelCase  :      List[Any]														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)
          __lowerCamelCase  :      List[str]														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)

     __lowerCamelCase  :      Dict														=						reformat_hex(UpperCAmelCase_				) + reformat_hex(UpperCAmelCase_				) + reformat_hex(UpperCAmelCase_				) + reformat_hex(UpperCAmelCase_				)
     return digest


if __name__ == "__main__":
      import doctest

      doctest.testmod()






