


"""simple docstring"""







from queue import Queue
from typing import TYPE_CHECKING, Optional


if TYPE_CHECKING:
 from ..models.auto import AutoTokenizer






class 						_A  :







    """simple docstring"""




    def      __snake_case							( self    :   int    ,			__UpperCAmelCase    :   Optional[Any]):
      raise NotImplementedError()






    def      __snake_case							( self    :   int):
      raise NotImplementedError()






class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   Any    ,			__UpperCAmelCase    :   "AutoTokenizer"    ,			__UpperCAmelCase    :   bool = False    ,			**__UpperCAmelCase    :   Union[str, Any]):
      a						:		str											=      tokenizer
      a						:		Dict											=      skip_prompt
      a						:		List[Any]											=      decode_kwargs

      # variables used in the streaming process
      a						:		Union[str, Any]											=      []
      a						:		Any											=      0
      a						:		Any											=      True






    def      __snake_case							( self    :   List[str]    ,			__UpperCAmelCase    :   List[str]):
      if len(value.shape) > 1 and value.shape[0] > 1:
        raise ValueError("TextStreamer only supports batch size 1")
      elif len(value.shape) > 1:
        a						:		List[str]											=      value[0]

      if self.skip_prompt and self.next_tokens_are_prompt:
        a						:		str											=      False
        return

      # Add the new token to the cache and decodes the entire thing.
      self.token_cache.extend(value.tolist())
      a						:		int											=      self.tokenizer.decode(self.token_cache    ,			**self.decode_kwargs)

      # After the symbol for a new line, we flush the cache.
      if text.endswith("\n"):
        a						:		str											=      text[self.print_len :]
        a						:		Dict											=      []
        a						:		Tuple											=      0
      # If the last token is a CJK character, we print the characters.
      elif len(__UpperCAmelCase) > 0 and self._is_chinese_char(ord(text[-1])):
        a						:		str											=      text[self.print_len :]
        self.print_len += len(__UpperCAmelCase)
      # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,
      # which may change with the subsequent token -- there are probably smarter ways to do this!)
      else:
        a						:		List[str]											=      text[self.print_len : text.rfind(" ") + 1]
        self.print_len += len(__UpperCAmelCase)

      self.on_finalized_text(__UpperCAmelCase)






    def      __snake_case							( self    :   int):
      # Flush the cache, if it exists
      if len(self.token_cache) > 0:
        a						:		Any											=      self.tokenizer.decode(self.token_cache    ,			**self.decode_kwargs)
        a						:		str											=      text[self.print_len :]
        a						:		Any											=      []
        a						:		Any											=      0
      else:
        a						:		Optional[Any]											=      ""

      a						:		Optional[int]											=      True
      self.on_finalized_text(__UpperCAmelCase    ,			stream_end=__UpperCAmelCase)






    def      __snake_case							( self    :   Dict    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   bool = False):
      print(__UpperCAmelCase    ,			flush=__UpperCAmelCase    ,			end="" if not stream_end else None)






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   List[Any]):
      # This defines a "chinese character" as anything in the CJK Unicode block:
      #   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
      #
      # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
      # despite its name. The modern Korean Hangul alphabet is a different block,
      # as is Japanese Hiragana and Katakana. Those alphabets are used to write
      # space-separated words, so they are not treated specially and handled
      # like the all of the other languages.
      if (
          (cp >= 0x4_E_0_0 and cp <= 0x9_F_F_F)
          or (cp >= 0x3_4_0_0 and cp <= 0x4_D_B_F)  #
          or (cp >= 0x2_0_0_0_0 and cp <= 0x2_A_6_D_F)  #
          or (cp >= 0x2_A_7_0_0 and cp <= 0x2_B_7_3_F)  #
          or (cp >= 0x2_B_7_4_0 and cp <= 0x2_B_8_1_F)  #
          or (cp >= 0x2_B_8_2_0 and cp <= 0x2_C_E_A_F)  #
          or (cp >= 0xF_9_0_0 and cp <= 0xF_A_F_F)
          or (cp >= 0x2_F_8_0_0 and cp <= 0x2_F_A_1_F)  #
      ):  #
        return True

      return False






class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   Dict    ,			__UpperCAmelCase    :   "AutoTokenizer"    ,			__UpperCAmelCase    :   bool = False    ,			__UpperCAmelCase    :   Optional[float] = None    ,			**__UpperCAmelCase    :   int):
      super().__init__(__UpperCAmelCase    ,			__UpperCAmelCase    ,			**__UpperCAmelCase)
      a						:		str											=      Queue()
      a						:		Tuple											=      None
      a						:		str											=      timeout






    def      __snake_case							( self    :   List[str]    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   bool = False):
      self.text_queue.put(__UpperCAmelCase    ,			timeout=self.timeout)
      if stream_end:
        self.text_queue.put(self.stop_signal    ,			timeout=self.timeout)






    def __iter__( self    :   List[str]):
      return self






    def      __snake_case							( self    :   Tuple):
      a						:		Tuple											=      self.text_queue.get(timeout=self.timeout)
      if value == self.stop_signal:
        raise StopIteration()
      else:
        return value










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

__lowercase    =				logging.get_logger(__name__)






@add_end_docstrings(_a  )
class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   List[Any]    ,			**__UpperCAmelCase    :   List[Any]):
      super().__init__(**__UpperCAmelCase)

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

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






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

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






    def      __snake_case							( self    :   Optional[int]    ,			**__UpperCAmelCase    :   List[Any]):
      a						:		str											=      {}
      if "threshold" in kwargs:
        a						:		Dict											=      kwargs["threshold"]
      if "top_k" in kwargs:
        a						:		str											=      kwargs["top_k"]
      return {}, {}, postprocess_params






    def      __snake_case							( self    :   List[Any]    ,			__UpperCAmelCase    :   Optional[Any]):
      a						:		Union[str, Any]											=      load_image(inputs["image"])
      a						:		Any											=      inputs["candidate_labels"]
      if isinstance(__UpperCAmelCase    ,			__UpperCAmelCase):
        a						:		Optional[Any]											=      candidate_labels.split(",")

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






    def      __snake_case							( self    :   Dict    ,			__UpperCAmelCase    :   Optional[int]):
      a						:		List[Any]											=      model_inputs.pop("target_size")
      a						:		Optional[int]											=      model_inputs.pop("candidate_label")
      a						:		List[Any]											=      model_inputs.pop("is_last")

      a						:		List[Any]											=      self.model(**__UpperCAmelCase)

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






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

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

          a						:		Optional[Any]											=      {"score": score, "label": label, "box": box}
          results.append(__UpperCAmelCase)

      a						:		str											=      sorted(__UpperCAmelCase    ,			key=lambda __UpperCAmelCase: x["score"]    ,			reverse=__UpperCAmelCase)
      if top_k:
        a						:		Union[str, Any]											=      results[:top_k]

      return results






    def      __snake_case							( self    :   Union[str, Any]    ,			__UpperCAmelCase    :   "torch.Tensor"):
      if self.framework != "pt":
        raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch.")
      a							,		a							,		a							,		a						:		List[Any]											=      box.int().tolist()
      a						:		str											=      {
          "xmin": xmin,
          "ymin": ymin,
          "xmax": xmax,
          "ymax": ymax,
      }
      return bbox






