





"""simple docstring"""
from collections import defaultdict
from typing import Optional

from ..image_utils import load_image
from ..utils import (
    add_end_docstrings,
    is_torch_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_torch_available():
  import torch

  from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING

lowerCamelCase_								=		logging.get_logger(__name__)






@add_end_docstrings(A  )
class 					_SCREAMING_SNAKE_CASE(   A  ):




       def __init__(						self		,**SCREAMING_SNAKE_CASE__							)			->      Any:





             """simple docstring"""






             super().__init__(**SCREAMING_SNAKE_CASE__							)
             requires_backends(self		,'''vision'''							)
             requires_backends(self		,'''torch'''							)

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

             self.check_model_type(SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self		,**SCREAMING_SNAKE_CASE__							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  {}
             __SCREAMING_SNAKE_CASE   :Tuple						=  {}
             __SCREAMING_SNAKE_CASE   :Any						=  {}
             # preprocess args
             if "points_per_batch" in kwargs:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  kwargs['''points_per_batch''']
             if "points_per_crop" in kwargs:
                   __SCREAMING_SNAKE_CASE   :Any						=  kwargs['''points_per_crop''']
             if "crops_n_layers" in kwargs:
                   __SCREAMING_SNAKE_CASE   :str						=  kwargs['''crops_n_layers''']
             if "crop_overlap_ratio" in kwargs:
                   __SCREAMING_SNAKE_CASE   :str						=  kwargs['''crop_overlap_ratio''']
             if "crop_n_points_downscale_factor" in kwargs:
                   __SCREAMING_SNAKE_CASE   :Tuple						=  kwargs['''crop_n_points_downscale_factor''']
             # postprocess args
             if "pred_iou_thresh" in kwargs:
                   __SCREAMING_SNAKE_CASE   :Tuple						=  kwargs['''pred_iou_thresh''']
             if "stability_score_offset" in kwargs:
                   __SCREAMING_SNAKE_CASE   :Any						=  kwargs['''stability_score_offset''']
             if "mask_threshold" in kwargs:
                   __SCREAMING_SNAKE_CASE   :str						=  kwargs['''mask_threshold''']
             if "stability_score_thresh" in kwargs:
                   __SCREAMING_SNAKE_CASE   :List[Any]						=  kwargs['''stability_score_thresh''']
             if "crops_nms_thresh" in kwargs:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  kwargs['''crops_nms_thresh''']
             if "output_rle_mask" in kwargs:
                   __SCREAMING_SNAKE_CASE   :Any						=  kwargs['''output_rle_mask''']
             if "output_bboxes_mask" in kwargs:
                   __SCREAMING_SNAKE_CASE   :int						=  kwargs['''output_bboxes_mask''']
             return preprocess_kwargs, forward_params, postprocess_kwargs




       def __call__(						self		,SCREAMING_SNAKE_CASE__		,*SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=None		,SCREAMING_SNAKE_CASE__=None		,**SCREAMING_SNAKE_CASE__							)			->      Tuple:





             """simple docstring"""






             return super().__call__(SCREAMING_SNAKE_CASE__		,*SCREAMING_SNAKE_CASE__		,num_workers=SCREAMING_SNAKE_CASE__		,batch_size=SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=64		,SCREAMING_SNAKE_CASE__ = 0		,SCREAMING_SNAKE_CASE__ = 5_12 / 15_00		,SCREAMING_SNAKE_CASE__ = 32		,SCREAMING_SNAKE_CASE__ = 1		,)			->      Union[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[str]						=  load_image(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :List[Any]						=  self.image_processor.size['''longest_edge''']
             __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[Any]						=  self.image_processor.generate_crop_boxes(
                 SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  self.image_processor(images=SCREAMING_SNAKE_CASE__		,return_tensors='''pt'''							)

             with self.device_placement():
                   if self.framework == "pt":
                         __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  self.get_inference_context()
                         with inference_context():
                               __SCREAMING_SNAKE_CASE   :int						=  self._ensure_tensor_on_device(SCREAMING_SNAKE_CASE__		,device=self.device							)
                               __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  self.model.get_image_embeddings(model_inputs.pop('''pixel_values'''							)							)
                               __SCREAMING_SNAKE_CASE   :Optional[int]						=  image_embeddings

             __SCREAMING_SNAKE_CASE   :str						=  grid_points.shape[1]
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  points_per_batch if points_per_batch is not None else n_points

             if points_per_batch <= 0:
                   raise ValueError(
                       '''Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. '''
                       '''To return all points at once, set points_per_batch to None'''							)

             for i in range(0		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :List[Any]						=  grid_points[:, i : i + points_per_batch, :, :]
                   __SCREAMING_SNAKE_CASE   :Tuple						=  input_labels[:, i : i + points_per_batch]
                   __SCREAMING_SNAKE_CASE   :Any						=  i == n_points - points_per_batch
                   yield {
                       "input_points": batched_points,
                       "input_labels": labels,
                       "input_boxes": crop_boxes,
                       "is_last": is_last,
                       **model_inputs,
                   }




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=0.8_8		,SCREAMING_SNAKE_CASE__=0.9_5		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__=1		,)			->      Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :int						=  model_inputs.pop('''input_boxes'''							)
             __SCREAMING_SNAKE_CASE   :List[Any]						=  model_inputs.pop('''is_last'''							)
             __SCREAMING_SNAKE_CASE   :Dict						=  model_inputs.pop('''original_sizes'''							).tolist()
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  model_inputs.pop('''reshaped_input_sizes'''							).tolist()

             __SCREAMING_SNAKE_CASE   :str						=  self.model(**SCREAMING_SNAKE_CASE__							)

             # post processing happens here in order to avoid CPU GPU copies of ALL the masks
             __SCREAMING_SNAKE_CASE   :Tuple						=  model_outputs['''pred_masks''']
             __SCREAMING_SNAKE_CASE   :int						=  self.image_processor.post_process_masks(
                 SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,binarize=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Dict						=  model_outputs['''iou_scores''']
             __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :List[Any]						=  self.image_processor.filter_masks(
                 masks[0]		,iou_scores[0]		,original_sizes[0]		,input_boxes[0]		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,)
             return {
                 "masks": masks,
                 "is_last": is_last,
                 "boxes": boxes,
                 "iou_scores": iou_scores,
             }




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=0.7		,)			->      Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  []
             __SCREAMING_SNAKE_CASE   :Any						=  []
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  []
             for model_output in model_outputs:
                   all_scores.append(model_output.pop('''iou_scores'''							)							)
                   all_masks.extend(model_output.pop('''masks'''							)							)
                   all_boxes.append(model_output.pop('''boxes'''							)							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  torch.cat(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :List[Any]						=  torch.cat(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Tuple						=  self.image_processor.post_process_for_mask_generation(
                 SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  defaultdict(SCREAMING_SNAKE_CASE__							)
             for output in model_outputs:
                   for k, v in output.items():
                         extra[k].append(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Dict						=  {}
             if output_rle_mask:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  rle_mask

             if output_bboxes_mask:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  bounding_boxes

             return {"masks": output_masks, "scores": iou_scores, **optional, **extra}






"""simple docstring"""
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_								=		logging.get_logger(__name__)

lowerCamelCase_								=		{
    "microsoft/beit-base-patch16-224-pt22k": (
        "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json"
    ),
    # See all BEiT models at https://huggingface.co/models?filter=beit
}






class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      str							=  '''beit'''




       def __init__(						self		,SCREAMING_SNAKE_CASE__=81_92		,SCREAMING_SNAKE_CASE__=7_68		,SCREAMING_SNAKE_CASE__=12		,SCREAMING_SNAKE_CASE__=12		,SCREAMING_SNAKE_CASE__=30_72		,SCREAMING_SNAKE_CASE__="gelu"		,SCREAMING_SNAKE_CASE__=0.0		,SCREAMING_SNAKE_CASE__=0.0		,SCREAMING_SNAKE_CASE__=0.0_2		,SCREAMING_SNAKE_CASE__=1E-12		,SCREAMING_SNAKE_CASE__=2_24		,SCREAMING_SNAKE_CASE__=16		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=0.1		,SCREAMING_SNAKE_CASE__=0.1		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=[3, 5, 7, 11]		,SCREAMING_SNAKE_CASE__=[1, 2, 3, 6]		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=0.4		,SCREAMING_SNAKE_CASE__=2_56		,SCREAMING_SNAKE_CASE__=1		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=2_55		,**SCREAMING_SNAKE_CASE__		,)			->      Optional[Any]:





             """simple docstring"""






             super().__init__(**SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Any						=  vocab_size
             __SCREAMING_SNAKE_CASE   :Dict						=  hidden_size
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  num_hidden_layers
             __SCREAMING_SNAKE_CASE   :List[str]						=  num_attention_heads
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  intermediate_size
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  hidden_act
             __SCREAMING_SNAKE_CASE   :Tuple						=  hidden_dropout_prob
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  attention_probs_dropout_prob
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  initializer_range
             __SCREAMING_SNAKE_CASE   :str						=  layer_norm_eps

             __SCREAMING_SNAKE_CASE   :int						=  image_size
             __SCREAMING_SNAKE_CASE   :Tuple						=  patch_size
             __SCREAMING_SNAKE_CASE   :Any						=  num_channels
             __SCREAMING_SNAKE_CASE   :Any						=  use_mask_token
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  use_absolute_position_embeddings
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  use_relative_position_bias
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  use_shared_relative_position_bias
             __SCREAMING_SNAKE_CASE   :List[str]						=  layer_scale_init_value
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  drop_path_rate
             __SCREAMING_SNAKE_CASE   :str						=  use_mean_pooling
             # decode head attributes (semantic segmentation)
             __SCREAMING_SNAKE_CASE   :Dict						=  out_indices
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  pool_scales
             # auxiliary head attributes (semantic segmentation)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  use_auxiliary_head
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  auxiliary_loss_weight
             __SCREAMING_SNAKE_CASE   :Dict						=  auxiliary_channels
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  auxiliary_num_convs
             __SCREAMING_SNAKE_CASE   :List[str]						=  auxiliary_concat_input
             __SCREAMING_SNAKE_CASE   :List[Any]						=  semantic_loss_ignore_index






class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      List[Any]							=  version.parse('''1.11'''  )




       @property
       def     _UpperCamelCase     (						self							)			->      Mapping[str, Mapping[int, str]]:





             """simple docstring"""






             return OrderedDict(
                 [
                     ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                 ]							)




       @property
       def     _UpperCamelCase     (						self							)			->      float:





             """simple docstring"""






             return 1E-4