




import logging
import os
import threading
import time


try:
    import warnings
except ImportError:
    snake_case_ : Dict    		=       None

try:
    import msvcrt
except ImportError:
    snake_case_ : Optional[Any]    		=       None

try:
    import fcntl
except ImportError:
    snake_case_ : List[str]    		=       None


# Backward compatibility
# ------------------------------------------------
try:
    TimeoutError
except NameError:
    snake_case_ : Tuple    		=       OSError


# Data
# ------------------------------------------------
snake_case_ : str    		=       [
    "Timeout",
    "BaseFileLock",
    "WindowsFileLock",
    "UnixFileLock",
    "SoftFileLock",
    "FileLock",
]

snake_case_ : Optional[int]    		=       "3.0.12"


snake_case_ : Union[str, Any]    		=       None


def    A						()   ->      Tuple:







     """simple docstring"""


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







class __snake_case			(			UpperCamelCase__		):







   def __init__(      self		:						List[Any]					,						_snake_case		:						Optional[int]):

        """simple docstring"""


        UpperCAmelCase_          =							lock_file
        return None







   def __str__(      self		:						List[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							F"""The file lock \'{self.lock_file}\' could not be acquired."""
        return temp







class __snake_case			:







   def __init__(      self		:						List[Any]					,						_snake_case		:						Any):

        """simple docstring"""


        UpperCAmelCase_          =							lock
        return None







   def __enter__(      self		:						List[Any]):

        """simple docstring"""


        return self.lock







   def __exit__(      self		:						Optional[int]					,						_snake_case		:						Any					,						_snake_case		:						int					,						_snake_case		:						Optional[int]):

        """simple docstring"""


        self.lock.release()
        return None







class __snake_case			:







   def __init__(      self		:						Optional[Any]					,						_snake_case		:						str					,						_snake_case		:						Tuple=-1					,						_snake_case		:						List[Any]=None):

        """simple docstring"""


        UpperCAmelCase_          =							max_filename_length if max_filename_length is not None else 255
        # Hash the filename if it's too long
        UpperCAmelCase_          =							self.hash_filename_if_too_long(UpperCamelCase_					,						UpperCamelCase_)
        # 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 lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        return self._lock_file







   @property
   def lowerCamelCase						(      self		:						int):

        """simple docstring"""


        return self._timeout







   @timeout.setter
   def lowerCamelCase						(      self		:						Optional[Any]					,						_snake_case		:						Dict):

        """simple docstring"""


        UpperCAmelCase_          =							float(UpperCamelCase_)
        return None







   def lowerCamelCase						(      self		:						List[str]):

        """simple docstring"""


        raise NotImplementedError()







   def lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        raise NotImplementedError()







   @property
   def lowerCamelCase						(      self		:						Dict):

        """simple docstring"""


        return self._lock_file_fd is not None







   def lowerCamelCase						(      self		:						List[Any]					,						_snake_case		:						Union[str, Any]=None					,						_snake_case		:						Optional[Any]=0.0_5):

        """simple docstring"""


        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(UpperCamelCase_)
        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 lowerCamelCase						(      self		:						Any					,						_snake_case		:						int=False):

        """simple docstring"""


        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		:						Optional[int]):

        """simple docstring"""


        self.acquire()
        return self







   def __exit__(      self		:						str					,						_snake_case		:						int					,						_snake_case		:						Optional[Any]					,						_snake_case		:						Optional[Any]):

        """simple docstring"""


        self.release()
        return None







   def __del__(      self		:						Any):

        """simple docstring"""


        self.release(force=UpperCamelCase_)
        return None







   def lowerCamelCase						(      self		:						Dict					,						_snake_case		:						str					,						_snake_case		:						int):

        """simple docstring"""


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







class __snake_case			(			UpperCamelCase__		):







   def __init__(      self		:						Union[str, Any]					,						_snake_case		:						Optional[int]					,						_snake_case		:						Tuple=-1					,						_snake_case		:						List[Any]=None):

        """simple docstring"""


        from .file_utils import relative_to_absolute_path

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







   def lowerCamelCase						(      self		:						Dict):

        """simple docstring"""


        UpperCAmelCase_          =							os.O_RDWR | os.O_CREAT | os.O_TRUNC

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







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							self._lock_file_fd
        UpperCAmelCase_          =							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 __snake_case			(			UpperCamelCase__		):







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

        """simple docstring"""


        UpperCAmelCase_          =							os.statvfs(os.path.dirname(UpperCamelCase_)).f_namemax
        super().__init__(UpperCamelCase_					,						timeout=UpperCamelCase_					,						max_filename_length=UpperCamelCase_)







   def lowerCamelCase						(      self		:						Optional[Any]):

        """simple docstring"""


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

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







   def lowerCamelCase						(      self		:						Optional[Any]):

        """simple docstring"""


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







class __snake_case			(			UpperCamelCase__		):







   def lowerCamelCase						(      self		:						Union[str, Any]):

        """simple docstring"""


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







   def lowerCamelCase						(      self		:						List[Any]):

        """simple docstring"""


        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







snake_case_ : Dict    		=       None

if msvcrt:
    snake_case_ : str    		=       WindowsFileLock
elif fcntl:
    snake_case_ : Optional[Any]    		=       UnixFileLock
else:
    snake_case_ : Tuple    		=       SoftFileLock

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










from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


lowerCAmelCase       =							{
    'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'],
    'tokenization_tapas': ['TapasTokenizer'],
}

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCAmelCase       =							[
			    'TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST',
			    'TapasForMaskedLM',
			    'TapasForQuestionAnswering',
			    'TapasForSequenceClassification',
			    'TapasModel',
			    'TapasPreTrainedModel',
			    'load_tf_weights_in_tapas',
			]
try:
			if not is_tf_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCAmelCase       =							[
			    'TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST',
			    'TFTapasForMaskedLM',
			    'TFTapasForQuestionAnswering',
			    'TFTapasForSequenceClassification',
			    'TFTapasModel',
			    'TFTapasPreTrainedModel',
			]


if TYPE_CHECKING:
			from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig
			from .tokenization_tapas import TapasTokenizer

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tapas import (
						    TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TapasForMaskedLM,
						    TapasForQuestionAnswering,
						    TapasForSequenceClassification,
						    TapasModel,
						    TapasPreTrainedModel,
						    load_tf_weights_in_tapas,
						)

			try:
						if not is_tf_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tf_tapas import (
						    TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TFTapasForMaskedLM,
						    TFTapasForQuestionAnswering,
						    TFTapasForSequenceClassification,
						    TFTapasModel,
						    TFTapasPreTrainedModel,
						)


else:
			import sys

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


