


import logging
import os
import threading
import time


try:
  import warnings
except ImportError:
  UpperCAmelCase__   	=							None

try:
  import msvcrt
except ImportError:
  UpperCAmelCase__   	=							None

try:
  import fcntl
except ImportError:
  UpperCAmelCase__   	=							None


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


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

UpperCAmelCase__   	=							'''3.0.12'''


UpperCAmelCase__   	=							None
def 				UpperCAmelCase_					(							)     ->			Optional[int]:







 """simple docstring"""


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







class       lowerCamelCase__   (       lowerCAmelCase):





     def __init__(self		,     UpperCAmelCase       )     ->   Optional[Any]:
      _lowercase							      =lock_file
      return None





     def __str__(self       )     ->   str:
      _lowercase							      =f"The file lock '{self.lock_file}' could not be acquired."
      return temp







class       lowerCamelCase__   :





     def __init__(self		,     UpperCAmelCase       )     ->   Dict:
      _lowercase							      =lock
      return None





     def __enter__(self       )     ->   Optional[Any]:
      return self.lock





     def __exit__(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   List[Any]:
      self.lock.release()
      return None







class       lowerCamelCase__   :





     def __init__(self		,     UpperCAmelCase		,     UpperCAmelCase=-1		,     UpperCAmelCase=None       )     ->   Dict:
      _lowercase							      =max_filename_length if max_filename_length is not None else 2_5_5
      # Hash the filename if it's too long
      _lowercase							      =self.hash_filename_if_too_long(UpperCAmelCase		,     UpperCAmelCase       )
      # The path to the lock file.
      _lowercase							      =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.
      _lowercase							      =None

      # The default timeout value.
      _lowercase							      =timeout

      # We use this lock primarily for the lock counter.
      _lowercase							      =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.
      _lowercase							      =0
      return None





     @property
     def      __A					(self       )     ->   int:
      return self._lock_file





     @property
     def      __A					(self       )     ->   Optional[Any]:
      return self._timeout





     @timeout.setter
     def      __A					(self		,     UpperCAmelCase       )     ->   Union[str, Any]:
      _lowercase							      =float(UpperCAmelCase       )
      return None





     def      __A					(self       )     ->   Any:
      raise NotImplementedError()





     def      __A					(self       )     ->   List[Any]:
      raise NotImplementedError()





     @property
     def      __A					(self       )     ->   Tuple:
      return self._lock_file_fd is not None





     def      __A					(self		,     UpperCAmelCase=None		,     UpperCAmelCase=0.05       )     ->   Union[str, Any]:
      # Use the default timeout, if no timeout is provided.
      if timeout is None:
       _lowercase							      =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

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

       raise
      return _Acquire_ReturnProxy(lock=self       )





     def      __A					(self		,     UpperCAmelCase=False       )     ->   Union[str, Any]:
      with self._thread_lock:
       if self.is_locked:
        self._lock_counter -= 1

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

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

      return None





     def __enter__(self       )     ->   List[Any]:
      self.acquire()
      return self





     def __exit__(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   Dict:
      self.release()
      return None





     def __del__(self       )     ->   Optional[Any]:
      self.release(force=UpperCAmelCase       )
      return None





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   str:
      _lowercase							      =os.path.basename(UpperCAmelCase       )
      if len(UpperCAmelCase       ) > max_length and max_length > 0:
       _lowercase							      =os.path.dirname(UpperCAmelCase       )
       _lowercase							      =str(hash(UpperCAmelCase       )       )
       _lowercase							      =filename[: max_length - len(UpperCAmelCase       ) - 8] + '''...''' + hashed_filename + '''.lock'''
       return os.path.join(UpperCAmelCase		,     UpperCAmelCase       )
      else:
       return path







class       lowerCamelCase__   (       lowerCAmelCase):





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

      super().__init__(UpperCAmelCase		,     timeout=UpperCAmelCase		,     max_filename_length=UpperCAmelCase       )
      _lowercase							      ='''\\\\?\\''' + relative_to_absolute_path(self.lock_file       )





     def      __A					(self       )     ->   Any:
      _lowercase							      =os.O_RDWR | os.O_CREAT | os.O_TRUNC

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





     def      __A					(self       )     ->   Optional[int]:
      _lowercase							      =self._lock_file_fd
      _lowercase							      =None
      msvcrt.locking(UpperCAmelCase		,     msvcrt.LK_UNLCK		,     1       )
      os.close(UpperCAmelCase       )

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







class       lowerCamelCase__   (       lowerCAmelCase):





     def __init__(self		,     UpperCAmelCase		,     UpperCAmelCase=-1		,     UpperCAmelCase=None       )     ->   Tuple:
      _lowercase							      =os.statvfs(os.path.dirname(UpperCAmelCase       )       ).f_namemax
      super().__init__(UpperCAmelCase		,     timeout=UpperCAmelCase		,     max_filename_length=UpperCAmelCase       )





     def      __A					(self       )     ->   int:
      _lowercase							      =os.O_RDWR | os.O_CREAT | os.O_TRUNC
      _lowercase							      =os.open(self._lock_file		,     UpperCAmelCase       )

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





     def      __A					(self       )     ->   Any:
      # 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
      _lowercase							      =self._lock_file_fd
      _lowercase							      =None
      fcntl.flock(UpperCAmelCase		,     fcntl.LOCK_UN       )
      os.close(UpperCAmelCase       )
      return None







class       lowerCamelCase__   (       lowerCAmelCase):





     def      __A					(self       )     ->   Dict:
      _lowercase							      =os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
      try:
       _lowercase							      =os.open(self._lock_file		,     UpperCAmelCase       )
      except OSError:
       pass
      else:
       _lowercase							      =fd
      return None





     def      __A					(self       )     ->   Any:
      os.close(self._lock_file_fd       )
      _lowercase							      =None

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



UpperCAmelCase__   	=							None

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

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








import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


a__:      List[str]									=		False




class     SCREAMING_SNAKE_CASE__ (						unittest.TestCase      ):
 pass




@nightly
@require_torch_gpu
class     SCREAMING_SNAKE_CASE__ (						unittest.TestCase      ):



 def 				UpperCamelCase			(							self ):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()



 def 				UpperCamelCase			(							self ):
        A__											=						VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' )
        # remove text_unet
        pipe.remove_unused_weights()
        pipe.to(__lowerCamelCase )
        pipe.set_progress_bar_config(disable=__lowerCamelCase )

        A__											=						'''A painting of a squirrel eating a burger '''
        A__											=						torch.manual_seed(0 )
        A__											=						pipe(
            prompt=__lowerCamelCase,generator=__lowerCamelCase,guidance_scale=7.5,num_inference_steps=2,output_type='''numpy''' ).images

        with tempfile.TemporaryDirectory() as tmpdirname:
               pipe.save_pretrained(__lowerCamelCase )
               A__											=						VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCamelCase )
        pipe.to(__lowerCamelCase )
        pipe.set_progress_bar_config(disable=__lowerCamelCase )

        A__											=						generator.manual_seed(0 )
        A__											=						pipe(
            prompt=__lowerCamelCase,generator=__lowerCamelCase,guidance_scale=7.5,num_inference_steps=2,output_type='''numpy''' ).images

        assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"




 def 				UpperCamelCase			(							self ):
        A__											=						VersatileDiffusionTextToImagePipeline.from_pretrained(
            '''shi-labs/versatile-diffusion''',torch_dtype=torch.floataa )
        pipe.to(__lowerCamelCase )
        pipe.set_progress_bar_config(disable=__lowerCamelCase )

        A__											=						'''A painting of a squirrel eating a burger '''
        A__											=						torch.manual_seed(0 )
        A__											=						pipe(
            prompt=__lowerCamelCase,generator=__lowerCamelCase,guidance_scale=7.5,num_inference_steps=50,output_type='''numpy''' ).images

        A__											=						image[0, 253:256, 253:256, -1]

        assert image.shape == (1, 512, 512, 3)
        A__											=						np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )

        assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2





