
import logging
import os
import threading
import time


try:
    import warnings
except ImportError:
    lowerCamelCase_						     =		None

try:
    import msvcrt
except ImportError:
    lowerCamelCase_						     =		None

try:
    import fcntl
except ImportError:
    lowerCamelCase_						     =		None


# Backward compatibility
# ------------------------------------------------
try:
    TimeoutError
except NameError:
    lowerCamelCase_						     =		OSError


# Data
# ------------------------------------------------
lowerCamelCase_						     =		[
    '''Timeout''',
    '''BaseFileLock''',
    '''WindowsFileLock''',
    '''UnixFileLock''',
    '''SoftFileLock''',
    '''FileLock''',
]

lowerCamelCase_						     =		'''3.0.12'''


lowerCamelCase_						     =		None






def 						__magic_name__			(   ):



     '''simple docstring'''




     global _logger
     UpperCamelCase__				=    _logger or logging.getLogger(__name__						)
     return _logger




class      __A(    A__			):

  """simple docstring"""







  def __init__(self	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    lock_file
       return None







  def __str__(self						):
       UpperCamelCase__				=    F"The file lock \'{self.lock_file}\' could not be acquired."
       return temp






class      __A:

  """simple docstring"""







  def __init__(self	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    lock
       return None







  def __enter__(self						):
       return self.lock







  def __exit__(self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       self.lock.release()
       return None






class      __A:

  """simple docstring"""







  def __init__(self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_=-1	,      SCREAMING_SNAKE_CASE_=None						):
       UpperCamelCase__				=    max_filename_length if max_filename_length is not None else 2_55
       # Hash the filename if it's too long
       UpperCamelCase__				=    self.hash_filename_if_too_long(__snake_case	,      __snake_case						)
       # The path to the lock file.
       UpperCamelCase__				=    lock_file

       # The file descriptor for the *_lock_file* as it is returned by the
       # os.open() function.
       # This file lock is only NOT None, if the object currently holds the
       # lock.
       UpperCamelCase__				=    None

       # The default timeout value.
       UpperCamelCase__				=    timeout

       # We use this lock primarily for the lock counter.
       UpperCamelCase__				=    threading.Lock()

       # The lock counter is used for implementing the nested locking
       # mechanism. Whenever the lock is acquired, the counter is increased and
       # the lock is only released, when this value is 0 again.
       UpperCamelCase__				=    0
       return None







  @property
  def 	UpperCAmelCase_ (self						):
       return self._lock_file







  @property
  def 	UpperCAmelCase_ (self						):
       return self._timeout







  @timeout.setter
  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    float(__snake_case						)
       return None







  def 	UpperCAmelCase_ (self						):
       raise NotImplementedError()







  def 	UpperCAmelCase_ (self						):
       raise NotImplementedError()







  @property
  def 	UpperCAmelCase_ (self						):
       return self._lock_file_fd is not None







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_=None	,      SCREAMING_SNAKE_CASE_=0.05						):
       # Use the default timeout, if no timeout is provided.
       if timeout is None:
            UpperCamelCase__				=    self.timeout

       # Increment the number right at the beginning.
       # We can still undo it, if something fails.
       with self._thread_lock:
            self._lock_counter += 1

       UpperCamelCase__				=    id(self						)
       UpperCamelCase__				=    self._lock_file
       UpperCamelCase__				=    time.time()
       try:
            while True:
                 with self._thread_lock:
                      if not self.is_locked:
                           logger().debug(F"Attempting to acquire lock {lock_id} on {lock_filename}"						)
                           self._acquire()

                 if self.is_locked:
                      logger().debug(F"Lock {lock_id} acquired on {lock_filename}"						)
                      break
                 elif timeout >= 0 and time.time() - start_time > timeout:
                      logger().debug(F"Timeout on acquiring lock {lock_id} on {lock_filename}"						)
                      raise Timeout(self._lock_file						)
                 else:
                      logger().debug(
                          F"Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ..."						)
                      time.sleep(__snake_case						)
       except:  # noqa
            # Something did go wrong, so decrement the counter.
            with self._thread_lock:
                 UpperCamelCase__				=    max(0	,      self._lock_counter - 1						)

            raise
       return _Acquire_ReturnProxy(lock=self						)







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_=False						):
       with self._thread_lock:
            if self.is_locked:
                 self._lock_counter -= 1

                 if self._lock_counter == 0 or force:
                      UpperCamelCase__				=    id(self						)
                      UpperCamelCase__				=    self._lock_file

                      logger().debug(F"Attempting to release lock {lock_id} on {lock_filename}"						)
                      self._release()
                      UpperCamelCase__				=    0
                      logger().debug(F"Lock {lock_id} released on {lock_filename}"						)

       return None







  def __enter__(self						):
       self.acquire()
       return self







  def __exit__(self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       self.release()
       return None







  def __del__(self						):
       self.release(force=__snake_case						)
       return None







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    os.path.basename(__snake_case						)
       if len(__snake_case						) > max_length and max_length > 0:
            UpperCamelCase__				=    os.path.dirname(__snake_case						)
            UpperCamelCase__				=    str(hash(__snake_case						)						)
            UpperCamelCase__				=    filename[: max_length - len(__snake_case						) - 8] + """...""" + hashed_filename + """.lock"""
            return os.path.join(__snake_case	,      __snake_case						)
       else:
            return path






class      __A(    A__			):

  """simple docstring"""







  def __init__(self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_=-1	,      SCREAMING_SNAKE_CASE_=None						):
       from .file_utils import relative_to_absolute_path

       super().__init__(__snake_case	,      timeout=__snake_case	,      max_filename_length=__snake_case						)
       UpperCamelCase__				=    """\\\\?\\""" + relative_to_absolute_path(self.lock_file						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    os.O_RDWR | os.O_CREAT | os.O_TRUNC

       try:
            UpperCamelCase__				=    os.open(self._lock_file	,      __snake_case						)
       except OSError:
            pass
       else:
            try:
                 msvcrt.locking(__snake_case	,      msvcrt.LK_NBLCK	,      1						)
            except OSError:
                 os.close(__snake_case						)
            else:
                 UpperCamelCase__				=    fd
       return None







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self._lock_file_fd
       UpperCamelCase__				=    None
       msvcrt.locking(__snake_case	,      msvcrt.LK_UNLCK	,      1						)
       os.close(__snake_case						)

       try:
            os.remove(self._lock_file						)
       # Probably another instance of the application
       # that acquired the file lock.
       except OSError:
            pass
       return None






class      __A(    A__			):

  """simple docstring"""







  def __init__(self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_=-1	,      SCREAMING_SNAKE_CASE_=None						):
       UpperCamelCase__				=    os.statvfs(os.path.dirname(__snake_case						)						).f_namemax
       super().__init__(__snake_case	,      timeout=__snake_case	,      max_filename_length=__snake_case						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    os.O_RDWR | os.O_CREAT | os.O_TRUNC
       UpperCamelCase__				=    os.open(self._lock_file	,      __snake_case						)

       try:
            fcntl.flock(__snake_case	,      fcntl.LOCK_EX | fcntl.LOCK_NB						)
       except OSError:
            os.close(__snake_case						)
       else:
            UpperCamelCase__				=    fd
       return None







  def 	UpperCAmelCase_ (self						):
       # Do not remove the lockfile:
       #
       #   https://github.com/benediktschmitt/py-filelock/issues/31
       #   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
       UpperCamelCase__				=    self._lock_file_fd
       UpperCamelCase__				=    None
       fcntl.flock(__snake_case	,      fcntl.LOCK_UN						)
       os.close(__snake_case						)
       return None






class      __A(    A__			):

  """simple docstring"""







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
       try:
            UpperCamelCase__				=    os.open(self._lock_file	,      __snake_case						)
       except OSError:
            pass
       else:
            UpperCamelCase__				=    fd
       return None







  def 	UpperCAmelCase_ (self						):
       os.close(self._lock_file_fd						)
       UpperCamelCase__				=    None

       try:
            os.remove(self._lock_file						)
       # The file is already deleted and that's what we want.
       except OSError:
            pass
       return None






lowerCamelCase_						     =		None

if msvcrt:
    lowerCamelCase_						     =		WindowsFileLock
elif fcntl:
    lowerCamelCase_						     =		UnixFileLock
else:
    lowerCamelCase_						     =		SoftFileLock

    if warnings is not None:
        warnings.warn('''only soft file lock is available''')







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      __A(    __lowerCamelCase			):

  """simple docstring"""







  def __init__(self	,      **SCREAMING_SNAKE_CASE_						):
       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_						):
       UpperCamelCase__				=    {}
       UpperCamelCase__				=    {}
       UpperCamelCase__				=    {}
       # preprocess args
       if "points_per_batch" in kwargs:
            UpperCamelCase__				=    kwargs["""points_per_batch"""]
       if "points_per_crop" in kwargs:
            UpperCamelCase__				=    kwargs["""points_per_crop"""]
       if "crops_n_layers" in kwargs:
            UpperCamelCase__				=    kwargs["""crops_n_layers"""]
       if "crop_overlap_ratio" in kwargs:
            UpperCamelCase__				=    kwargs["""crop_overlap_ratio"""]
       if "crop_n_points_downscale_factor" in kwargs:
            UpperCamelCase__				=    kwargs["""crop_n_points_downscale_factor"""]
       # postprocess args
       if "pred_iou_thresh" in kwargs:
            UpperCamelCase__				=    kwargs["""pred_iou_thresh"""]
       if "stability_score_offset" in kwargs:
            UpperCamelCase__				=    kwargs["""stability_score_offset"""]
       if "mask_threshold" in kwargs:
            UpperCamelCase__				=    kwargs["""mask_threshold"""]
       if "stability_score_thresh" in kwargs:
            UpperCamelCase__				=    kwargs["""stability_score_thresh"""]
       if "crops_nms_thresh" in kwargs:
            UpperCamelCase__				=    kwargs["""crops_nms_thresh"""]
       if "output_rle_mask" in kwargs:
            UpperCamelCase__				=    kwargs["""output_rle_mask"""]
       if "output_bboxes_mask" in kwargs:
            UpperCamelCase__				=    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_						):
       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	,      ):
       UpperCamelCase__				=    load_image(SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    self.image_processor.size["""longest_edge"""]
       UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__				=    self.image_processor.generate_crop_boxes(
           SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    self.image_processor(images=SCREAMING_SNAKE_CASE_	,      return_tensors="""pt"""						)

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

       UpperCamelCase__				=    grid_points.shape[1]
       UpperCamelCase__				=    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_						):
            UpperCamelCase__				=    grid_points[:, i : i + points_per_batch, :, :]
            UpperCamelCase__				=    input_labels[:, i : i + points_per_batch]
            UpperCamelCase__				=    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.88	,      SCREAMING_SNAKE_CASE_=0.95	,      SCREAMING_SNAKE_CASE_=0	,      SCREAMING_SNAKE_CASE_=1	,      ):
       UpperCamelCase__				=    model_inputs.pop("""input_boxes"""						)
       UpperCamelCase__				=    model_inputs.pop("""is_last"""						)
       UpperCamelCase__				=    model_inputs.pop("""original_sizes"""						).tolist()
       UpperCamelCase__				=    model_inputs.pop("""reshaped_input_sizes"""						).tolist()

       UpperCamelCase__				=    self.model(**SCREAMING_SNAKE_CASE_						)

       # post processing happens here in order to avoid CPU GPU copies of ALL the masks
       UpperCamelCase__				=    model_outputs["""pred_masks"""]
       UpperCamelCase__				=    self.image_processor.post_process_masks(
           SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      binarize=SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    model_outputs["""iou_scores"""]
       UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__				=    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	,      ):
       UpperCamelCase__				=    []
       UpperCamelCase__				=    []
       UpperCamelCase__				=    []
       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"""						)						)

       UpperCamelCase__				=    torch.cat(SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    torch.cat(SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__				=    self.image_processor.post_process_for_mask_generation(
           SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)

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

       UpperCamelCase__				=    {}
       if output_rle_mask:
            UpperCamelCase__				=    rle_mask

       if output_bboxes_mask:
            UpperCamelCase__				=    bounding_boxes

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





