

# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile




def 			UpperCAmelCase__				(			_A      : Union[str, Any]	,      _A      : List[str]	,      _A      : List[Any]	,      _A      : int							):





  '''simple docstring'''







  a__  =multiprocessing.Manager()
  a__  =manager.list()

  a__  =multiprocessing.Process(target=_A	,      args=(check_program, result, timeout)							)
  p.start()
  p.join(timeout=timeout + 1							)
  if p.is_alive():
    p.kill()

  if not result:
    result.append('''timed out'''							)

  return {
      "task_id": task_id,
      "passed": result[0] == "passed",
      "result": result[0],
      "completion_id": completion_id,
  }




def 			UpperCAmelCase__				(			_A      : str	,      _A      : Any	,      _A      : Dict							):





  '''simple docstring'''







  with create_tempdir():
    # These system calls are needed when cleaning up tempdir.
    import os
    import shutil

    a__  =shutil.rmtree
    a__  =os.rmdir
    a__  =os.chdir

    # Disable functionalities that can make destructive changes to the test.
    reliability_guard()

    # Run program.
    try:
      a__  ={}
      with swallow_io():
        with time_limit(_A							):
          exec(_A	,      _A							)
      result.append('''passed'''							)
    except TimeoutException:
      result.append('''timed out'''							)
    except BaseException as e:
      result.append(F"""failed: {e}"""							)

    # Needed for cleaning up.
    a__  =rmtree
    a__  =rmdir
    a__  =chdir




@contextlib.contextmanager
def 			UpperCAmelCase__				(			_A      : Any							):





  '''simple docstring'''







  def signal_handler(_A      : List[str]	,      _A      : Tuple							):
    raise TimeoutException('''Timed out!'''							)

  signal.setitimer(signal.ITIMER_REAL	,      _A							)
  signal.signal(signal.SIGALRM	,      _A							)
  try:
    yield
  finally:
    signal.setitimer(signal.ITIMER_REAL	,      0							)




@contextlib.contextmanager
def 			UpperCAmelCase__				(			):





  '''simple docstring'''







  a__  =WriteOnlyStringIO()
  with contextlib.redirect_stdout(_A							):
    with contextlib.redirect_stderr(_A							):
      with redirect_stdin(_A							):
        yield




@contextlib.contextmanager
def 			UpperCAmelCase__				(			):





  '''simple docstring'''







  with tempfile.TemporaryDirectory() as dirname:
    with chdir(_A							):
      yield dirname







class 						__magic_name__			(							lowerCamelCase__							):

   '''simple docstring'''




   pass







class 						__magic_name__			(							io.StringIO							):

   '''simple docstring'''




   def  _UpperCAmelCase (				self,    *lowercase_,    **lowercase_       )							->    Tuple:






     """simple docstring"""






     raise OSError



   def  _UpperCAmelCase (				self,    *lowercase_,    **lowercase_       )							->    List[str]:






     """simple docstring"""






     raise OSError



   def  _UpperCAmelCase (				self,    *lowercase_,    **lowercase_       )							->    str:






     """simple docstring"""






     raise OSError



   def  _UpperCAmelCase (				self,    *lowercase_,    **lowercase_       )							->    Tuple:






     """simple docstring"""






     return False







class 						__magic_name__			(							contextlib._RedirectStream							):  # type: ignore

   '''simple docstring'''




   lowerCamelCase__ :	List[str]    =   'stdin'





@contextlib.contextmanager
def 			UpperCAmelCase__				(			_A      : List[str]							):





  '''simple docstring'''







  if root == ".":
    yield
    return
  a__  =os.getcwd()
  os.chdir(_A							)
  try:
    yield
  except BaseException as exc:
    raise exc
  finally:
    os.chdir(_A							)




def 			UpperCAmelCase__				(			_A      : str=None							):





  '''simple docstring'''







  if maximum_memory_bytes is not None:
    import resource

    resource.setrlimit(resource.RLIMIT_AS	,      (maximum_memory_bytes, maximum_memory_bytes)							)
    resource.setrlimit(resource.RLIMIT_DATA	,      (maximum_memory_bytes, maximum_memory_bytes)							)
    if not platform.uname().system == "Darwin":
      resource.setrlimit(resource.RLIMIT_STACK	,      (maximum_memory_bytes, maximum_memory_bytes)							)

  faulthandler.disable()

  import builtins

  a__  =None
  a__  =None

  import os

  a__  ='''1'''

  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None

  import shutil

  a__  =None
  a__  =None
  a__  =None

  import subprocess

  a__  =None  # type: ignore

  a__  =None

  import sys

  a__  =None
  a__  =None
  a__  =None
  a__  =None
  a__  =None



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(lowerCamelCase__							)
class 						__magic_name__			(							lowerCamelCase__							):

   '''simple docstring'''




   def __init__(				self,    **lowercase_       )							->    Optional[int]:






     """simple docstring"""






     super().__init__(**lowercase_       )
     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(lowercase_       )



   def  _UpperCAmelCase (				self,    **lowercase_       )							->    Optional[Any]:






     """simple docstring"""






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



   def __call__(				self,    lowercase_,    *lowercase_,    lowercase_=None,    lowercase_=None,    **lowercase_       )							->    List[Any]:






     """simple docstring"""






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



   def  _UpperCAmelCase (				self,    lowercase_,    lowercase_=64,    lowercase_ = 0,    lowercase_ = 512 / 1500,    lowercase_ = 32,    lowercase_ = 1,    )							->    Any:






     """simple docstring"""






     a__  =load_image(lowercase_       )
     a__  =self.image_processor.size['''longest_edge''']
     a__,      a__,      a__,      a__  =self.image_processor.generate_crop_boxes(
         lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_       )
     a__  =self.image_processor(images=lowercase_,    return_tensors='''pt'''       )

     with self.device_placement():
       if self.framework == "pt":
         a__  =self.get_inference_context()
         with inference_context():
           a__  =self._ensure_tensor_on_device(lowercase_,    device=self.device       )
           a__  =self.model.get_image_embeddings(model_inputs.pop('''pixel_values'''       )       )
           a__  =image_embeddings

     a__  =grid_points.shape[1]
     a__  =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,    lowercase_,    lowercase_       ):
       a__  =grid_points[:, i : i + points_per_batch, :, :]
       a__  =input_labels[:, i : i + points_per_batch]
       a__  =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,    lowercase_,    lowercase_=0.88,    lowercase_=0.95,    lowercase_=0,    lowercase_=1,    )							->    int:






     """simple docstring"""






     a__  =model_inputs.pop('''input_boxes'''       )
     a__  =model_inputs.pop('''is_last'''       )
     a__  =model_inputs.pop('''original_sizes'''       ).tolist()
     a__  =model_inputs.pop('''reshaped_input_sizes'''       ).tolist()

     a__  =self.model(**lowercase_       )

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



   def  _UpperCAmelCase (				self,    lowercase_,    lowercase_=False,    lowercase_=False,    lowercase_=0.7,    )							->    Any:






     """simple docstring"""






     a__  =[]
     a__  =[]
     a__  =[]
     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'''       )       )

     a__  =torch.cat(lowercase_       )
     a__  =torch.cat(lowercase_       )
     a__,      a__,      a__,      a__  =self.image_processor.post_process_for_mask_generation(
         lowercase_,    lowercase_,    lowercase_,    lowercase_       )

     a__  =defaultdict(lowercase_       )
     for output in model_outputs:
       for k, v in output.items():
         extra[k].append(lowercase_       )

     a__  ={}
     if output_rle_mask:
       a__  =rle_mask

     if output_bboxes_mask:
       a__  =bounding_boxes

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