



"""simple docstring"""


import itertools
import json
import os
import unittest

from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class 				A_      (					SCREAMING_SNAKE_CASE_     ,       unittest.TestCase    ):



						"""simple docstring"""
						__UpperCamelCase		    =							RobertaTokenizer
						__UpperCamelCase		    =							RobertaTokenizerFast
						__UpperCamelCase		    =							True
						__UpperCamelCase		    =							{"""cls_token""": """<s>"""}






						def      UpperCAmelCase__					( self			:List[Any] )    ->      Optional[Any]:
												super().setUp()

												# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
												UpperCAmelCase					=			[
												    'l',
												    'o',
												    'w',
												    'e',
												    'r',
												    's',
												    't',
												    'i',
												    'd',
												    'n',
												    '\u0120',
												    '\u0120l',
												    '\u0120n',
												    '\u0120lo',
												    '\u0120low',
												    'er',
												    '\u0120lowest',
												    '\u0120newer',
												    '\u0120wider',
												    '<unk>',
												]
												UpperCAmelCase					=			dict(zip(lowercase_       ,  range(len(lowercase_ ) ) ) )
												UpperCAmelCase					=			['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
												UpperCAmelCase					=			{'unk_token': '<unk>'}

												UpperCAmelCase					=			os.path.join(self.tmpdirname       ,  VOCAB_FILES_NAMES['vocab_file'] )
												UpperCAmelCase					=			os.path.join(self.tmpdirname       ,  VOCAB_FILES_NAMES['merges_file'] )
												with open(self.vocab_file       ,  'w'       ,  encoding='utf-8' ) as fp:
																		fp.write(json.dumps(lowercase_ ) + '\n' )
												with open(self.merges_file       ,  'w'       ,  encoding='utf-8' ) as fp:
																		fp.write('\n'.join(lowercase_ ) )






						def      UpperCAmelCase__					( self			:List[str]       ,  **lowercase_			:Optional[int] )    ->      str:
												kwargs.update(self.special_tokens_map )
												return self.tokenizer_class.from_pretrained(self.tmpdirname       ,  **lowercase_ )






						def      UpperCAmelCase__					( self			:int       ,  **lowercase_			:Any )    ->      Union[str, Any]:
												kwargs.update(self.special_tokens_map )
												return RobertaTokenizerFast.from_pretrained(self.tmpdirname       ,  **lowercase_ )






						def      UpperCAmelCase__					( self			:str       ,  lowercase_			:Optional[int] )    ->      Tuple:
												UpperCAmelCase					=			'lower newer'
												UpperCAmelCase					=			'lower newer'
												return input_text, output_text






						def      UpperCAmelCase__					( self			:List[Any] )    ->      Optional[int]:
												UpperCAmelCase					=			self.tokenizer_class(self.vocab_file       ,  self.merges_file       ,  **self.special_tokens_map )
												UpperCAmelCase					=			'lower newer'
												UpperCAmelCase					=			['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er']
												UpperCAmelCase					=			tokenizer.tokenize(lowercase_ )  # , add_prefix_space=True)
												self.assertListEqual(lowercase_       ,  lowercase_ )

												UpperCAmelCase					=			tokens + [tokenizer.unk_token]
												UpperCAmelCase					=			[0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
												self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_ )       ,  lowercase_ )






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Any:
												UpperCAmelCase					=			self.get_tokenizer()

												self.assertListEqual(tokenizer.encode('Hello world!'       ,  add_special_tokens=lowercase_ )       ,  [0, 3_14_14, 2_32, 3_28, 2] )
												self.assertListEqual(
												    tokenizer.encode('Hello world! cécé herlolip 418'       ,  add_special_tokens=lowercase_ )       ,  [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]       ,  )






						@slow
						def      UpperCAmelCase__					( self			:List[Any] )    ->      Dict:
												UpperCAmelCase					=			self.tokenizer_class.from_pretrained('roberta-base' )

												UpperCAmelCase					=			tokenizer.encode('sequence builders'       ,  add_special_tokens=lowercase_ )
												UpperCAmelCase					=			tokenizer.encode('multi-sequence build'       ,  add_special_tokens=lowercase_ )

												UpperCAmelCase					=			tokenizer.encode(
												    'sequence builders'       ,  add_special_tokens=lowercase_       ,  add_prefix_space=lowercase_ )
												UpperCAmelCase					=			tokenizer.encode(
												    'sequence builders'       ,  'multi-sequence build'       ,  add_special_tokens=lowercase_       ,  add_prefix_space=lowercase_ )

												UpperCAmelCase					=			tokenizer.build_inputs_with_special_tokens(lowercase_ )
												UpperCAmelCase					=			tokenizer.build_inputs_with_special_tokens(lowercase_       ,  lowercase_ )

												assert encoded_sentence == encoded_text_from_decode
												assert encoded_pair == encoded_pair_from_decode






						def      UpperCAmelCase__					( self			:Dict )    ->      Dict:
												UpperCAmelCase					=			self.get_tokenizer()

												UpperCAmelCase					=			'Encode this sequence.'
												UpperCAmelCase					=			tokenizer.byte_encoder[' '.encode('utf-8' )[0]]

												# Testing encoder arguments
												UpperCAmelCase					=			tokenizer.encode(lowercase_       ,  add_special_tokens=lowercase_       ,  add_prefix_space=lowercase_ )
												UpperCAmelCase					=			tokenizer.convert_ids_to_tokens(encoded[0] )[0]
												self.assertNotEqual(lowercase_       ,  lowercase_ )

												UpperCAmelCase					=			tokenizer.encode(lowercase_       ,  add_special_tokens=lowercase_       ,  add_prefix_space=lowercase_ )
												UpperCAmelCase					=			tokenizer.convert_ids_to_tokens(encoded[0] )[0]
												self.assertEqual(lowercase_       ,  lowercase_ )

												tokenizer.add_special_tokens({'bos_token': '<s>'} )
												UpperCAmelCase					=			tokenizer.encode(lowercase_       ,  add_special_tokens=lowercase_ )
												UpperCAmelCase					=			tokenizer.convert_ids_to_tokens(encoded[1] )[0]
												self.assertNotEqual(lowercase_       ,  lowercase_ )

												# Testing spaces after special tokens
												UpperCAmelCase					=			'<mask>'
												tokenizer.add_special_tokens(
												    {'mask_token': AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ )} )  # mask token has a left space
												UpperCAmelCase					=			tokenizer.convert_tokens_to_ids(lowercase_ )

												UpperCAmelCase					=			'Encode <mask> sequence'
												UpperCAmelCase					=			'Encode <mask>sequence'

												UpperCAmelCase					=			tokenizer.encode(lowercase_ )
												UpperCAmelCase					=			encoded.index(lowercase_ )
												UpperCAmelCase					=			tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
												self.assertEqual(lowercase_       ,  lowercase_ )

												UpperCAmelCase					=			tokenizer.encode(lowercase_ )
												UpperCAmelCase					=			encoded.index(lowercase_ )
												UpperCAmelCase					=			tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
												self.assertNotEqual(lowercase_       ,  lowercase_ )






						def      UpperCAmelCase__					( self			:Tuple )    ->      Tuple:
												pass






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Any:
												for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																		with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(lowercase_       ,  **lowercase_ )
																								UpperCAmelCase					=			self.tokenizer_class.from_pretrained(lowercase_       ,  **lowercase_ )
																								UpperCAmelCase					=			'A, <mask> AllenNLP sentence.'
																								UpperCAmelCase					=			tokenizer_r.encode_plus(lowercase_       ,  add_special_tokens=lowercase_       ,  return_token_type_ids=lowercase_ )
																								UpperCAmelCase					=			tokenizer_p.encode_plus(lowercase_       ,  add_special_tokens=lowercase_       ,  return_token_type_ids=lowercase_ )

																								# token_type_ids should put 0 everywhere
																								self.assertEqual(sum(tokens_r['token_type_ids'] )       ,  sum(tokens_p['token_type_ids'] ) )

																								# attention_mask should put 1 everywhere, so sum over length should be 1
																								self.assertEqual(
																								    sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] )       ,  sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] )       ,  )

																								UpperCAmelCase					=			tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] )
																								UpperCAmelCase					=			tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] )

																								# Rust correctly handles the space before the mask while python doesnt
																								self.assertSequenceEqual(tokens_p['input_ids']       ,  [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] )
																								self.assertSequenceEqual(tokens_r['input_ids']       ,  [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] )

																								self.assertSequenceEqual(
																								    lowercase_       ,  ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
																								self.assertSequenceEqual(
																								    lowercase_       ,  ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      List[Any]:
												for trim_offsets, add_prefix_space in itertools.product([True, False]       ,  repeat=2 ):
																		UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																		    self.tmpdirname       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )

																		UpperCAmelCase					=			json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() )
																		UpperCAmelCase					=			json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() )

																		self.assertEqual(pre_tokenizer_state['add_prefix_space']       ,  lowercase_ )

																		self.assertEqual(post_processor_state['add_prefix_space']       ,  lowercase_ )
																		self.assertEqual(post_processor_state['trim_offsets']       ,  lowercase_ )






						def      UpperCAmelCase__					( self			:Tuple )    ->      Tuple:
												# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and
												# `trim_offsets`
												for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																		with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
																								UpperCAmelCase					=			'hello'  # `hello` is a token in the vocabulary of `pretrained_name`
																								UpperCAmelCase					=			f"""{text_of_1_token} {text_of_1_token}"""

																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																								    lowercase_       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )
																								UpperCAmelCase					=			tokenizer_r(lowercase_       ,  return_offsets_mapping=lowercase_       ,  add_special_tokens=lowercase_ )
																								self.assertEqual(encoding.offset_mapping[0]       ,  (0, len(lowercase_ )) )
																								self.assertEqual(
																								    encoding.offset_mapping[1]       ,  (len(lowercase_ ) + 1, len(lowercase_ ) + 1 + len(lowercase_ ))       ,  )

																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																								    lowercase_       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )
																								UpperCAmelCase					=			tokenizer_r(lowercase_       ,  return_offsets_mapping=lowercase_       ,  add_special_tokens=lowercase_ )
																								self.assertEqual(encoding.offset_mapping[0]       ,  (0, len(lowercase_ )) )
																								self.assertEqual(
																								    encoding.offset_mapping[1]       ,  (len(lowercase_ ) + 1, len(lowercase_ ) + 1 + len(lowercase_ ))       ,  )

																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																								    lowercase_       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )
																								UpperCAmelCase					=			tokenizer_r(lowercase_       ,  return_offsets_mapping=lowercase_       ,  add_special_tokens=lowercase_ )
																								self.assertEqual(encoding.offset_mapping[0]       ,  (0, len(lowercase_ )) )
																								self.assertEqual(
																								    encoding.offset_mapping[1]       ,  (len(lowercase_ ), len(lowercase_ ) + 1 + len(lowercase_ ))       ,  )

																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																								    lowercase_       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )
																								UpperCAmelCase					=			tokenizer_r(lowercase_       ,  return_offsets_mapping=lowercase_       ,  add_special_tokens=lowercase_ )
																								self.assertEqual(encoding.offset_mapping[0]       ,  (0, len(lowercase_ )) )
																								self.assertEqual(
																								    encoding.offset_mapping[1]       ,  (len(lowercase_ ), len(lowercase_ ) + 1 + len(lowercase_ ))       ,  )

																								UpperCAmelCase					=			f""" {text}"""

																								# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
																								#     pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
																								# )
																								# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
																								# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
																								# self.assertEqual(
																								#     encoding.offset_mapping[1],
																								#     (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
																								# )

																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																								    lowercase_       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )
																								UpperCAmelCase					=			tokenizer_r(lowercase_       ,  return_offsets_mapping=lowercase_       ,  add_special_tokens=lowercase_ )
																								self.assertEqual(encoding.offset_mapping[0]       ,  (1, 1 + len(lowercase_ )) )
																								self.assertEqual(
																								    encoding.offset_mapping[1]       ,  (1 + len(lowercase_ ) + 1, 1 + len(lowercase_ ) + 1 + len(lowercase_ ))       ,  )

																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																								    lowercase_       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )
																								UpperCAmelCase					=			tokenizer_r(lowercase_       ,  return_offsets_mapping=lowercase_       ,  add_special_tokens=lowercase_ )
																								self.assertEqual(encoding.offset_mapping[0]       ,  (0, 1 + len(lowercase_ )) )
																								self.assertEqual(
																								    encoding.offset_mapping[1]       ,  (1 + len(lowercase_ ), 1 + len(lowercase_ ) + 1 + len(lowercase_ ))       ,  )

																								UpperCAmelCase					=			self.rust_tokenizer_class.from_pretrained(
																								    lowercase_       ,  use_fast=lowercase_       ,  add_prefix_space=lowercase_       ,  trim_offsets=lowercase_ )
																								UpperCAmelCase					=			tokenizer_r(lowercase_       ,  return_offsets_mapping=lowercase_       ,  add_special_tokens=lowercase_ )
																								self.assertEqual(encoding.offset_mapping[0]       ,  (0, 1 + len(lowercase_ )) )
																								self.assertEqual(
																								    encoding.offset_mapping[1]       ,  (1 + len(lowercase_ ), 1 + len(lowercase_ ) + 1 + len(lowercase_ ))       ,  )










"""simple docstring"""


import logging
import os
import threading
import time


try:
				import warnings
except ImportError:
				snake_case_    					=	None

try:
				import msvcrt
except ImportError:
				snake_case_    					=	None

try:
				import fcntl
except ImportError:
				snake_case_    					=	None


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


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

snake_case_    					=	"""3.0.12"""


snake_case_    					=	None

def 			_lowerCAmelCase				(       ):
						global _logger
						UpperCAmelCase					=			_logger or logging.getLogger(__name__						)
						return _logger







class 				A_      (					SCREAMING_SNAKE_CASE_    ):



						"""simple docstring"""






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






						def __str__( self			:Dict )    ->      Optional[int]:
												UpperCAmelCase					=			f"""The file lock '{self.lock_file}' could not be acquired."""
												return temp







class 				A_      :



						"""simple docstring"""






						def __init__( self			:List[Any]       ,  lowercase_			:Dict )    ->      Dict:
												UpperCAmelCase					=			lock
												return None






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






						def __exit__( self			:Optional[int]       ,  lowercase_			:Tuple       ,  lowercase_			:Any       ,  lowercase_			:Union[str, Any] )    ->      List[Any]:
												self.lock.release()
												return None







class 				A_      :



						"""simple docstring"""






						def __init__( self			:List[str]       ,  lowercase_			:str       ,  lowercase_			:str=-1       ,  lowercase_			:List[Any]=None )    ->      Dict:
												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(lowercase_       ,  lowercase_ )
												# 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			:Optional[Any] )    ->      int:
												return self._lock_file






						@property
						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Any:
												return self._timeout






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






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






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






						@property
						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      Union[str, Any]:
												return self._lock_file_fd is not None






						def      UpperCAmelCase__					( self			:Union[str, Any]       ,  lowercase_			:Dict=None       ,  lowercase_			:int=0.05 )    ->      Union[str, Any]:
												# 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(lowercase_ )
												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			:Optional[int]       ,  lowercase_			:List[str]=False )    ->      int:
												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			:Any )    ->      Tuple:
												self.acquire()
												return self






						def __exit__( self			:Dict       ,  lowercase_			:Optional[int]       ,  lowercase_			:Union[str, Any]       ,  lowercase_			:Union[str, Any] )    ->      Any:
												self.release()
												return None






						def __del__( self			:Any )    ->      int:
												self.release(force=lowercase_ )
												return None






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







class 				A_      (					SCREAMING_SNAKE_CASE_    ):



						"""simple docstring"""






						def __init__( self			:Tuple       ,  lowercase_			:Tuple       ,  lowercase_			:List[Any]=-1       ,  lowercase_			:Union[str, Any]=None )    ->      Optional[Any]:
												from .file_utils import relative_to_absolute_path

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






						def      UpperCAmelCase__					( self			:List[str] )    ->      str:
												UpperCAmelCase					=			os.O_RDWR | os.O_CREAT | os.O_TRUNC

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






						def      UpperCAmelCase__					( self			:int )    ->      Union[str, Any]:
												UpperCAmelCase					=			self._lock_file_fd
												UpperCAmelCase					=			None
												msvcrt.locking(lowercase_       ,  msvcrt.LK_UNLCK       ,  1 )
												os.close(lowercase_ )

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







class 				A_      (					SCREAMING_SNAKE_CASE_    ):



						"""simple docstring"""






						def __init__( self			:Optional[Any]       ,  lowercase_			:str       ,  lowercase_			:List[str]=-1       ,  lowercase_			:str=None )    ->      str:
												UpperCAmelCase					=			os.statvfs(os.path.dirname(lowercase_ ) ).f_namemax
												super().__init__(lowercase_       ,  timeout=lowercase_       ,  max_filename_length=lowercase_ )






						def      UpperCAmelCase__					( self			:str )    ->      Dict:
												UpperCAmelCase					=			os.O_RDWR | os.O_CREAT | os.O_TRUNC
												UpperCAmelCase					=			os.open(self._lock_file       ,  lowercase_ )

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






						def      UpperCAmelCase__					( self			:List[Any] )    ->      List[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
												UpperCAmelCase					=			self._lock_file_fd
												UpperCAmelCase					=			None
												fcntl.flock(lowercase_       ,  fcntl.LOCK_UN )
												os.close(lowercase_ )
												return None







class 				A_      (					SCREAMING_SNAKE_CASE_    ):



						"""simple docstring"""






						def      UpperCAmelCase__					( self			:List[Any] )    ->      List[str]:
												UpperCAmelCase					=			os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
												try:
																		UpperCAmelCase					=			os.open(self._lock_file       ,  lowercase_ )
												except OSError:
																		pass
												else:
																		UpperCAmelCase					=			fd
												return None






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      List[Any]:
												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_    					=	None

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

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





