

'''simple docstring'''



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
  import PIL


UpperCAmelCase :       Optional[Any]			   =     logging.get_logger(__name__)







class 						lowerCAmelCase__   (      a					):



 """simple docstring"""



 lowerCAmelCase__  					=      ["pixel_values"]
 def __init__(		self					:       Any					,							__SCREAMING_SNAKE_CASE					:       bool = True					,							__SCREAMING_SNAKE_CASE					:       Dict[str, int] = None					,							__SCREAMING_SNAKE_CASE					:       PILImageResampling = PILImageResampling.BICUBIC					,							__SCREAMING_SNAKE_CASE					:       bool = True					,							__SCREAMING_SNAKE_CASE					:       Union[int, float] = 1 / 255					,							__SCREAMING_SNAKE_CASE					:       bool = True					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[float, List[float]]] = None					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[float, List[float]]] = None					,							__SCREAMING_SNAKE_CASE					:       bool = True					,							**__SCREAMING_SNAKE_CASE					:       Optional[Any]					,							)  -> None:


      """simple docstring"""




      super().__init__(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      size if size is not None else {"""height""": 384, """width""": 384}
      __SCREAMING_SNAKE_CASE     =      get_size_dict(__SCREAMING_SNAKE_CASE					,							default_to_square=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      do_resize
      __SCREAMING_SNAKE_CASE     =      size
      __SCREAMING_SNAKE_CASE     =      resample
      __SCREAMING_SNAKE_CASE     =      do_rescale
      __SCREAMING_SNAKE_CASE     =      rescale_factor
      __SCREAMING_SNAKE_CASE     =      do_normalize
      __SCREAMING_SNAKE_CASE     =      image_mean if image_mean is not None else OPENAI_CLIP_MEAN
      __SCREAMING_SNAKE_CASE     =      image_std if image_std is not None else OPENAI_CLIP_STD
      __SCREAMING_SNAKE_CASE     =      do_convert_rgb
 def       UpperCAmelCase__		(		self					:       str					,							__SCREAMING_SNAKE_CASE					:       np.ndarray					,							__SCREAMING_SNAKE_CASE					:       Dict[str, int]					,							__SCREAMING_SNAKE_CASE					:       PILImageResampling = PILImageResampling.BICUBIC					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[str, ChannelDimension]] = None					,							**__SCREAMING_SNAKE_CASE					:       Union[str, Any]					,							)  -> np.ndarray:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      get_size_dict(__SCREAMING_SNAKE_CASE					,							default_to_square=__SCREAMING_SNAKE_CASE			)
      if "height" not in size or "width" not in size:
           raise ValueError(f'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'			)
      __SCREAMING_SNAKE_CASE     =      (size["""height"""], size["""width"""])
      return resize(__SCREAMING_SNAKE_CASE					,							size=__SCREAMING_SNAKE_CASE					,							resample=__SCREAMING_SNAKE_CASE					,							data_format=__SCREAMING_SNAKE_CASE					,							**__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Optional[int]					,							__SCREAMING_SNAKE_CASE					:       np.ndarray					,							__SCREAMING_SNAKE_CASE					:       Union[int, float]					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[str, ChannelDimension]] = None					,							**__SCREAMING_SNAKE_CASE					:       Any					,							)  -> int:


      """simple docstring"""




      return rescale(__SCREAMING_SNAKE_CASE					,							scale=__SCREAMING_SNAKE_CASE					,							data_format=__SCREAMING_SNAKE_CASE					,							**__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       List[Any]					,							__SCREAMING_SNAKE_CASE					:       np.ndarray					,							__SCREAMING_SNAKE_CASE					:       Union[float, List[float]]					,							__SCREAMING_SNAKE_CASE					:       Union[float, List[float]]					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[str, ChannelDimension]] = None					,							**__SCREAMING_SNAKE_CASE					:       Dict					,							)  -> np.ndarray:


      """simple docstring"""




      return normalize(__SCREAMING_SNAKE_CASE					,							mean=__SCREAMING_SNAKE_CASE					,							std=__SCREAMING_SNAKE_CASE					,							data_format=__SCREAMING_SNAKE_CASE					,							**__SCREAMING_SNAKE_CASE			)


 def       UpperCAmelCase__		(		self					:       Optional[Any]					,							__SCREAMING_SNAKE_CASE					:       ImageInput					,							__SCREAMING_SNAKE_CASE					:       Optional[bool] = None					,							__SCREAMING_SNAKE_CASE					:       Optional[Dict[str, int]] = None					,							__SCREAMING_SNAKE_CASE					:       PILImageResampling = None					,							__SCREAMING_SNAKE_CASE					:       Optional[bool] = None					,							__SCREAMING_SNAKE_CASE					:       Optional[float] = None					,							__SCREAMING_SNAKE_CASE					:       Optional[bool] = None					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[float, List[float]]] = None					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[float, List[float]]] = None					,							__SCREAMING_SNAKE_CASE					:       Optional[Union[str, TensorType]] = None					,							__SCREAMING_SNAKE_CASE					:       bool = None					,							__SCREAMING_SNAKE_CASE					:       ChannelDimension = ChannelDimension.FIRST					,							**__SCREAMING_SNAKE_CASE					:       str					,							)  -> PIL.Image.Image:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      do_resize if do_resize is not None else self.do_resize
      __SCREAMING_SNAKE_CASE     =      resample if resample is not None else self.resample
      __SCREAMING_SNAKE_CASE     =      do_rescale if do_rescale is not None else self.do_rescale
      __SCREAMING_SNAKE_CASE     =      rescale_factor if rescale_factor is not None else self.rescale_factor
      __SCREAMING_SNAKE_CASE     =      do_normalize if do_normalize is not None else self.do_normalize
      __SCREAMING_SNAKE_CASE     =      image_mean if image_mean is not None else self.image_mean
      __SCREAMING_SNAKE_CASE     =      image_std if image_std is not None else self.image_std
      __SCREAMING_SNAKE_CASE     =      do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

      __SCREAMING_SNAKE_CASE     =      size if size is not None else self.size
      __SCREAMING_SNAKE_CASE     =      get_size_dict(__SCREAMING_SNAKE_CASE					,							default_to_square=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      make_list_of_images(__SCREAMING_SNAKE_CASE			)

      if not valid_images(__SCREAMING_SNAKE_CASE			):
           raise ValueError(
               """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
               """torch.Tensor, tf.Tensor or jax.ndarray."""			)

      if do_resize and size is None or resample is None:
           raise ValueError("""Size and resample must be specified if do_resize is True."""			)

      if do_rescale and rescale_factor is None:
           raise ValueError("""Rescale factor must be specified if do_rescale is True."""			)

      if do_normalize and (image_mean is None or image_std is None):
           raise ValueError("""Image mean and std must be specified if do_normalize is True."""			)

      # PIL RGBA images are converted to RGB
      if do_convert_rgb:
           __SCREAMING_SNAKE_CASE     =      [convert_to_rgb(__SCREAMING_SNAKE_CASE			) for image in images]

      # All transformations expect numpy arrays.
      __SCREAMING_SNAKE_CASE     =      [to_numpy_array(__SCREAMING_SNAKE_CASE			) for image in images]

      if do_resize:
           __SCREAMING_SNAKE_CASE     =      [self.resize(image=__SCREAMING_SNAKE_CASE					,							size=__SCREAMING_SNAKE_CASE					,							resample=__SCREAMING_SNAKE_CASE			) for image in images]

      if do_rescale:
           __SCREAMING_SNAKE_CASE     =      [self.rescale(image=__SCREAMING_SNAKE_CASE					,							scale=__SCREAMING_SNAKE_CASE			) for image in images]

      if do_normalize:
           __SCREAMING_SNAKE_CASE     =      [self.normalize(image=__SCREAMING_SNAKE_CASE					,							mean=__SCREAMING_SNAKE_CASE					,							std=__SCREAMING_SNAKE_CASE			) for image in images]

      __SCREAMING_SNAKE_CASE     =      [to_channel_dimension_format(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			) for image in images]

      __SCREAMING_SNAKE_CASE     =      BatchFeature(data={"""pixel_values""": images}					,							tensor_type=__SCREAMING_SNAKE_CASE			)

      return encoded_outputs









'''simple docstring'''



import logging
import os
import threading
import time


try:
  import warnings
except ImportError:
  UpperCAmelCase :       Optional[Any]			   =     None

try:
  import msvcrt
except ImportError:
  UpperCAmelCase :       List[Any]			   =     None

try:
  import fcntl
except ImportError:
  UpperCAmelCase :       int			   =     None


# Backward compatibility
# ------------------------------------------------
try:
  TimeoutError
except NameError:
  UpperCAmelCase :       Union[str, Any]			   =     OSError


# Data
# ------------------------------------------------
UpperCAmelCase :       List[Any]			   =     [
    'Timeout',
    'BaseFileLock',
    'WindowsFileLock',
    'UnixFileLock',
    'SoftFileLock',
    'FileLock',
]

UpperCAmelCase :       Tuple			   =     '3.0.12'


UpperCAmelCase :       str			   =     None







def    a__       (  ):




     """simple docstring"""


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







class 						lowerCAmelCase__   (      a					):



 """simple docstring"""



 def __init__(		self					:       Any					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      lock_file
      return None


 def __str__(		self					:       str			)  -> Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      f'The file lock \'{self.lock_file}\' could not be acquired.'
      return temp







class 						lowerCAmelCase__   :



 """simple docstring"""



 def __init__(		self					:       Tuple					,							__SCREAMING_SNAKE_CASE					:       List[Any]			)  -> Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      lock
      return None
 def __enter__(		self					:       List[str]			)  -> List[Any]:


      """simple docstring"""




      return self.lock


 def __exit__(		self					:       Tuple					,							__SCREAMING_SNAKE_CASE					:       List[str]					,							__SCREAMING_SNAKE_CASE					:       Dict					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]			)  -> List[str]:


      """simple docstring"""




      self.lock.release()
      return None







class 						lowerCAmelCase__   :



 """simple docstring"""



 def __init__(		self					:       List[Any]					,							__SCREAMING_SNAKE_CASE					:       List[Any]					,							__SCREAMING_SNAKE_CASE					:       str=-1					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]=None			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      max_filename_length if max_filename_length is not None else 255
      # Hash the filename if it's too long
      __SCREAMING_SNAKE_CASE     =      self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)
      # The path to the lock file.
      __SCREAMING_SNAKE_CASE     =      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.
      __SCREAMING_SNAKE_CASE     =      None

      # The default timeout value.
      __SCREAMING_SNAKE_CASE     =      timeout

      # We use this lock primarily for the lock counter.
      __SCREAMING_SNAKE_CASE     =      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.
      __SCREAMING_SNAKE_CASE     =      0
      return None
 @property
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> List[str]:


      """simple docstring"""




      return self._lock_file
 @property
 def       UpperCAmelCase__		(		self					:       Optional[Any]			)  -> Optional[int]:


      """simple docstring"""




      return self._timeout
 @timeout.setter
 def       UpperCAmelCase__		(		self					:       List[str]					,							__SCREAMING_SNAKE_CASE					:       Dict			)  -> Optional[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      float(__SCREAMING_SNAKE_CASE			)
      return None
 def       UpperCAmelCase__		(		self					:       Optional[Any]			)  -> List[Any]:


      """simple docstring"""




      raise NotImplementedError()
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> Any:


      """simple docstring"""




      raise NotImplementedError()
 @property
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> int:


      """simple docstring"""




      return self._lock_file_fd is not None
 def       UpperCAmelCase__		(		self					:       Optional[Any]					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]=None					,							__SCREAMING_SNAKE_CASE					:       Optional[int]=0.05			)  -> Optional[Any]:


      """simple docstring"""




      if timeout is None:
           __SCREAMING_SNAKE_CASE     =      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

      __SCREAMING_SNAKE_CASE     =      id(self			)
      __SCREAMING_SNAKE_CASE     =      self._lock_file
      __SCREAMING_SNAKE_CASE     =      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(__SCREAMING_SNAKE_CASE			)
      except:  # noqa
           # Something did go wrong, so decrement the counter.
           with self._thread_lock:
                __SCREAMING_SNAKE_CASE     =      max(0					,							self._lock_counter - 1			)

           raise
      return _Acquire_ReturnProxy(lock=self			)
 def       UpperCAmelCase__		(		self					:       Optional[Any]					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]=False			)  -> Dict:


      """simple docstring"""




      with self._thread_lock:
           if self.is_locked:
                self._lock_counter -= 1

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

                     logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}'			)
                     self._release()
                     __SCREAMING_SNAKE_CASE     =      0
                     logger().debug(f'Lock {lock_id} released on {lock_filename}'			)

      return None
 def __enter__(		self					:       Union[str, Any]			)  -> Optional[int]:


      """simple docstring"""




      self.acquire()
      return self
 def __exit__(		self					:       Optional[Any]					,							__SCREAMING_SNAKE_CASE					:       Tuple					,							__SCREAMING_SNAKE_CASE					:       Union[str, Any]					,							__SCREAMING_SNAKE_CASE					:       Any			)  -> Tuple:


      """simple docstring"""




      self.release()
      return None
 def __del__(		self					:       str			)  -> Union[str, Any]:


      """simple docstring"""




      self.release(force=__SCREAMING_SNAKE_CASE			)
      return None


 def       UpperCAmelCase__		(		self					:       Optional[int]					,							__SCREAMING_SNAKE_CASE					:       str					,							__SCREAMING_SNAKE_CASE					:       int			)  -> str:


      """simple docstring"""




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







class 						lowerCAmelCase__   (      a					):



 """simple docstring"""



 def __init__(		self					:       Tuple					,							__SCREAMING_SNAKE_CASE					:       Tuple					,							__SCREAMING_SNAKE_CASE					:       Dict=-1					,							__SCREAMING_SNAKE_CASE					:       Dict=None			)  -> List[Any]:


      """simple docstring"""




      from .file_utils import relative_to_absolute_path

      super().__init__(__SCREAMING_SNAKE_CASE					,							timeout=__SCREAMING_SNAKE_CASE					,							max_filename_length=__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      """\\\\?\\""" + relative_to_absolute_path(self.lock_file			)
 def       UpperCAmelCase__		(		self					:       Dict			)  -> Optional[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      os.O_RDWR | os.O_CREAT | os.O_TRUNC

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


 def       UpperCAmelCase__		(		self					:       Tuple			)  -> List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self._lock_file_fd
      __SCREAMING_SNAKE_CASE     =      None
      msvcrt.locking(__SCREAMING_SNAKE_CASE					,							msvcrt.LK_UNLCK					,							1			)
      os.close(__SCREAMING_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 						lowerCAmelCase__   (      a					):



 """simple docstring"""



 def __init__(		self					:       Union[str, Any]					,							__SCREAMING_SNAKE_CASE					:       int					,							__SCREAMING_SNAKE_CASE					:       Union[str, Any]=-1					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]=None			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE			)			).f_namemax
      super().__init__(__SCREAMING_SNAKE_CASE					,							timeout=__SCREAMING_SNAKE_CASE					,							max_filename_length=__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      os.O_RDWR | os.O_CREAT | os.O_TRUNC
      __SCREAMING_SNAKE_CASE     =      os.open(self._lock_file					,							__SCREAMING_SNAKE_CASE			)

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


 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self._lock_file_fd
      __SCREAMING_SNAKE_CASE     =      None
      fcntl.flock(__SCREAMING_SNAKE_CASE					,							fcntl.LOCK_UN			)
      os.close(__SCREAMING_SNAKE_CASE			)
      return None







class 						lowerCAmelCase__   (      a					):



 """simple docstring"""



 def       UpperCAmelCase__		(		self					:       List[str]			)  -> List[Any]:


      """simple docstring"""




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


 def       UpperCAmelCase__		(		self					:       int			)  -> Optional[int]:


      """simple docstring"""




      os.close(self._lock_file_fd			)
      __SCREAMING_SNAKE_CASE     =      None

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


UpperCAmelCase :       Dict			   =     None

if msvcrt:
  UpperCAmelCase :       Optional[int]			   =     WindowsFileLock
elif fcntl:
  UpperCAmelCase :       Optional[Any]			   =     UnixFileLock
else:
  UpperCAmelCase :       int			   =     SoftFileLock

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






