




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	:						List[str]			=     logging.get_logger(__name__)




@add_end_docstrings(lowerCAmelCase)
class    __lowerCAmelCase       (							lowerCAmelCase):






       def __init__(   self:					Tuple       ,					**_lowerCAmelCase:					List[str]				):
         super().__init__(**_lowerCAmelCase				)

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

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






       def __call__(   self:					Tuple       ,					_lowerCAmelCase:					Union[str, "Image.Image", List[Dict[str, Any]]]       ,					_lowerCAmelCase:					Union[str, List[str]] = None       ,					**_lowerCAmelCase:					int       ,					):
         if "text_queries" in kwargs:
           lowercase    :Optional[Any]      	=						kwargs.pop("text_queries"				)

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Any       ,					**_lowerCAmelCase:					int				):
         lowercase    :Any      	=						{}
         if "threshold" in kwargs:
           lowercase    :List[Any]      	=						kwargs["threshold"]
         if "top_k" in kwargs:
           lowercase    :Dict      	=						kwargs["top_k"]
         return {}, {}, postprocess_params






       def 					SCREAMING_SNAKE_CASE    (   self:					str       ,					_lowerCAmelCase:					Optional[int]				):
         lowercase    :Union[str, Any]      	=						load_image(inputs["image"]				)
         lowercase    :List[str]      	=						inputs["candidate_labels"]
         if isinstance(_lowerCAmelCase       ,					_lowerCAmelCase				):
           lowercase    :Dict      	=						candidate_labels.split(","				)

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]       ,					_lowerCAmelCase:					Dict				):
         lowercase    :Any      	=						model_inputs.pop("target_size"				)
         lowercase    :Tuple      	=						model_inputs.pop("candidate_label"				)
         lowercase    :List[Any]      	=						model_inputs.pop("is_last"				)

         lowercase    :str      	=						self.model(**_lowerCAmelCase				)

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






       def 					SCREAMING_SNAKE_CASE    (   self:					str       ,					_lowerCAmelCase:					List[Any]       ,					_lowerCAmelCase:					Dict=0.1       ,					_lowerCAmelCase:					Dict=None				):
         lowercase    :Dict      	=						[]
         for model_output in model_outputs:
           lowercase    :Any      	=						model_output["candidate_label"]
           lowercase    :List[str]      	=						BaseModelOutput(_lowerCAmelCase				)
           lowercase    :int      	=						self.image_processor.post_process_object_detection(
               outputs=_lowerCAmelCase       ,					threshold=_lowerCAmelCase       ,					target_sizes=model_output["target_size"]				)[0]

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

             lowercase    :Any      	=						{"score": score, "label": label, "box": box}
             results.append(_lowerCAmelCase				)

         lowercase    :Optional[Any]      	=						sorted(_lowerCAmelCase       ,					key=lambda _lowerCAmelCase				: x["score"]       ,					reverse=_lowerCAmelCase				)
         if top_k:
           lowercase    :List[Any]      	=						results[:top_k]

         return results






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple       ,					_lowerCAmelCase:					"torch.Tensor"				):
         if self.framework != "pt":
           raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch."				)
         lowercase	,    lowercase	,    lowercase	,    lowercase    :Optional[int]      	=						box.int().tolist()
         lowercase    :Dict      	=						{
             "xmin": xmin,
             "ymin": ymin,
             "xmax": xmax,
             "ymax": ymax,
         }
         return bbox









from collections.abc import Generator
from math import sin



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if len(lowerCamelCase   ) != 32:
    raise ValueError("Input must be of length 32"   )

  lowercase    :Any      	=						B""
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )

  lowercase    :List[Any]      	=						format(lowerCamelCase,			"08x"   )[-8:]
  lowercase    :Tuple      	=						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__  (     lowerCamelCase   ):
  lowercase    :Union[str, Any]      	=						B""
  for char in message:
    bit_string += format(lowerCamelCase,			"08b"   ).encode("utf-8"   )
  lowercase    :str      	=						format(len(lowerCamelCase   ),			"064b"   ).encode("utf-8"   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(lowerCamelCase   ) % 512 != 448:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if len(lowerCamelCase   ) % 512 != 0:
    raise ValueError("Input must have length that's a multiple of 512"   )

  for pos in range(0,			len(lowerCamelCase   ),			512   ):
    lowercase    :List[str]      	=						bit_string[pos : pos + 512]
    lowercase    :int      	=						[]
    for i in range(0,			512,			32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   ),			2   )   )
    yield block_words



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )

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



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  return (a + b) % 2**32



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  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__  (     lowerCamelCase   ):
  lowercase    :Tuple      	=						preprocess(lowerCamelCase   )

  lowercase    :Tuple      	=						[int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  lowercase    :Optional[Any]      	=						0X6745_2301
  lowercase    :Union[str, Any]      	=						0XEFCD_AB89
  lowercase    :Optional[int]      	=						0X98BA_DCFE
  lowercase    :str      	=						0X1032_5476

  lowercase    :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(lowerCamelCase   ):
    lowercase    :str      	=						aa
    lowercase    :int      	=						ba
    lowercase    :int      	=						ca
    lowercase    :List[str]      	=						da

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

    # Add hashed chunk to running total
    lowercase    :Optional[Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :List[Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :List[str]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :Union[str, Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )

  lowercase    :int      	=						reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   )
  return digest


if __name__ == "__main__":
     import doctest

     doctest.testmod()



