


"""simple docstring"""




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     lowercase			()   ->						Optional[int]:
						global _logger
						SCREAMING_SNAKE_CASE													=					_logger or logging.getLogger(__name__  )
						return _logger
class 					lowerCAmelCase	(					lowerCamelCase_    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__				)     ->							Any:
								SCREAMING_SNAKE_CASE													=					lock_file
								return None







		def __str__(	self				)     ->							Tuple:
								SCREAMING_SNAKE_CASE													=					F'The file lock \'{self.lock_file}\' could not be acquired.'
								return temp





class 					lowerCAmelCase	:




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__				)     ->							Union[str, Any]:
								SCREAMING_SNAKE_CASE													=					lock
								return None







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







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





class 					lowerCAmelCase	:




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__=-1						,       lowerCAmelCase__=None				)     ->							List[Any]:
								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(lowerCAmelCase__						,       lowerCAmelCase__				)
								# 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 							__A						(	self				)     ->							Union[str, Any]:
								return self._lock_file







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







		@timeout.setter
		def 							__A						(	self						,       lowerCAmelCase__				)     ->							List[Any]:
								SCREAMING_SNAKE_CASE													=					float(lowerCAmelCase__				)
								return None







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







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







		@property
		def 							__A						(	self				)     ->							List[str]:
								return self._lock_file_fd is not None







		def 							__A						(	self						,       lowerCAmelCase__=None						,       lowerCAmelCase__=0.05				)     ->							Tuple:
								# Use the default timeout, if no timeout is provided.
								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(lowerCAmelCase__				)
								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 							__A						(	self						,       lowerCAmelCase__=False				)     ->							Optional[int]:
								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				)     ->							int:
								self.acquire()
								return self







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







		def __del__(	self				)     ->							List[str]:
								self.release(force=lowerCAmelCase__				)
								return None







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





class 					lowerCAmelCase	(					lowerCamelCase_    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__=-1						,       lowerCAmelCase__=None				)     ->							List[Any]:
								from .file_utils import relative_to_absolute_path

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







		def 							__A						(	self				)     ->							str:
								SCREAMING_SNAKE_CASE													=					os.O_RDWR | os.O_CREAT | os.O_TRUNC

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







		def 							__A						(	self				)     ->							Union[str, Any]:
								SCREAMING_SNAKE_CASE													=					self._lock_file_fd
								SCREAMING_SNAKE_CASE													=					None
								msvcrt.locking(lowerCAmelCase__						,       msvcrt.LK_UNLCK						,       1				)
								os.close(lowerCAmelCase__				)

								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_    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__=-1						,       lowerCAmelCase__=None				)     ->							Any:
								SCREAMING_SNAKE_CASE													=					os.statvfs(os.path.dirname(lowerCAmelCase__				)				).f_namemax
								super().__init__(lowerCAmelCase__						,       timeout=lowerCAmelCase__						,       max_filename_length=lowerCAmelCase__				)







		def 							__A						(	self				)     ->							List[str]:
								SCREAMING_SNAKE_CASE													=					os.O_RDWR | os.O_CREAT | os.O_TRUNC
								SCREAMING_SNAKE_CASE													=					os.open(self._lock_file						,       lowerCAmelCase__				)

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







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





class 					lowerCAmelCase	(					lowerCamelCase_    ):




		'''simple docstring'''







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







		def 							__A						(	self				)     ->							List[Any]:
								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						=      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''')






"""simple docstring"""




from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


__UpperCamelCase						=      {
    '''configuration_blip''': [
        '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''BlipConfig''',
        '''BlipTextConfig''',
        '''BlipVisionConfig''',
    ],
    '''processing_blip''': ['''BlipProcessor'''],
}

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__UpperCamelCase						=      ['''BlipImageProcessor''']


try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__UpperCamelCase						=      [
	    '''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''BlipModel''',
	    '''BlipPreTrainedModel''',
	    '''BlipForConditionalGeneration''',
	    '''BlipForQuestionAnswering''',
	    '''BlipVisionModel''',
	    '''BlipTextModel''',
	    '''BlipForImageTextRetrieval''',
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__UpperCamelCase						=      [
	    '''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''TFBlipModel''',
	    '''TFBlipPreTrainedModel''',
	    '''TFBlipForConditionalGeneration''',
	    '''TFBlipForQuestionAnswering''',
	    '''TFBlipVisionModel''',
	    '''TFBlipTextModel''',
	    '''TFBlipForImageTextRetrieval''',
	]

if TYPE_CHECKING:
	from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
	from .processing_blip import BlipProcessor

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .image_processing_blip import BlipImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_blip import (
		    BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    BlipForConditionalGeneration,
		    BlipForImageTextRetrieval,
		    BlipForQuestionAnswering,
		    BlipModel,
		    BlipPreTrainedModel,
		    BlipTextModel,
		    BlipVisionModel,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_blip import (
		    TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFBlipForConditionalGeneration,
		    TFBlipForImageTextRetrieval,
		    TFBlipForQuestionAnswering,
		    TFBlipModel,
		    TFBlipPreTrainedModel,
		    TFBlipTextModel,
		    TFBlipVisionModel,
		)

else:
	import sys

	__UpperCamelCase						=      _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


