



"""simple docstring"""


import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    MODEL_MAPPING,
				    SegformerForImageClassification,
				    SegformerForSemanticSegmentation,
				    SegformerModel,
				)
				from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import SegformerImageProcessor







class 				A_      (					UpperCamelCase__    ):



						"""simple docstring"""






						def      UpperCAmelCase__					( self			:Tuple )    ->      Any:
									UpperCAmelCase					=			self.config_class(**self.inputs_dict )
									self.parent.assertTrue(hasattr(__lowerCamelCase       ,  'hidden_sizes' ) )
									self.parent.assertTrue(hasattr(__lowerCamelCase       ,  'num_attention_heads' ) )
									self.parent.assertTrue(hasattr(__lowerCamelCase       ,  'num_encoder_blocks' ) )







class 				A_      :



						"""simple docstring"""






						def __init__( self			:Any       ,  lowercase_			:int       ,  lowercase_			:Optional[int]=13       ,  lowercase_			:Union[str, Any]=64       ,  lowercase_			:Optional[int]=3       ,  lowercase_			:List[str]=4       ,  lowercase_			:Union[str, Any]=[2, 2, 2, 2]       ,  lowercase_			:List[Any]=[8, 4, 2, 1]       ,  lowercase_			:Optional[Any]=[16, 32, 64, 1_28]       ,  lowercase_			:str=[1, 4, 8, 16]       ,  lowercase_			:Optional[Any]=[1, 2, 4, 8]       ,  lowercase_			:Dict=True       ,  lowercase_			:Union[str, Any]=True       ,  lowercase_			:List[Any]="gelu"       ,  lowercase_			:Dict=0.1       ,  lowercase_			:Optional[Any]=0.1       ,  lowercase_			:str=0.02       ,  lowercase_			:Union[str, Any]=3       ,  lowercase_			:Tuple=None       ,  )    ->      Optional[Any]:
									UpperCAmelCase					=			parent
									UpperCAmelCase					=			batch_size
									UpperCAmelCase					=			image_size
									UpperCAmelCase					=			num_channels
									UpperCAmelCase					=			num_encoder_blocks
									UpperCAmelCase					=			sr_ratios
									UpperCAmelCase					=			depths
									UpperCAmelCase					=			hidden_sizes
									UpperCAmelCase					=			downsampling_rates
									UpperCAmelCase					=			num_attention_heads
									UpperCAmelCase					=			is_training
									UpperCAmelCase					=			use_labels
									UpperCAmelCase					=			hidden_act
									UpperCAmelCase					=			hidden_dropout_prob
									UpperCAmelCase					=			attention_probs_dropout_prob
									UpperCAmelCase					=			initializer_range
									UpperCAmelCase					=			num_labels
									UpperCAmelCase					=			scope






						def      UpperCAmelCase__					( self			:Dict )    ->      List[str]:
									UpperCAmelCase					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

									UpperCAmelCase					=			None
									if self.use_labels:
												UpperCAmelCase					=			ids_tensor([self.batch_size, self.image_size, self.image_size]       ,  self.num_labels )

									UpperCAmelCase					=			self.get_config()
									return config, pixel_values, labels






						def      UpperCAmelCase__					( self			:Dict )    ->      List[Any]:
									return SegformerConfig(
									    image_size=self.image_size       ,  num_channels=self.num_channels       ,  num_encoder_blocks=self.num_encoder_blocks       ,  depths=self.depths       ,  hidden_sizes=self.hidden_sizes       ,  num_attention_heads=self.num_attention_heads       ,  hidden_act=self.hidden_act       ,  hidden_dropout_prob=self.hidden_dropout_prob       ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,  initializer_range=self.initializer_range       ,  )






						def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:str       ,  lowercase_			:Union[str, Any]       ,  lowercase_			:int )    ->      str:
									UpperCAmelCase					=			SegformerModel(config=__lowerCamelCase )
									model.to(__lowerCamelCase )
									model.eval()
									UpperCAmelCase					=			model(__lowerCamelCase )
									UpperCAmelCase					=			UpperCAmelCase					=			self.image_size // (self.downsampling_rates[-1] * 2)
									self.parent.assertEqual(
									    result.last_hidden_state.shape       ,  (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) )






						def      UpperCAmelCase__					( self			:Optional[int]       ,  lowercase_			:str       ,  lowercase_			:List[str]       ,  lowercase_			:Optional[int] )    ->      Dict:
									UpperCAmelCase					=			self.num_labels
									UpperCAmelCase					=			SegformerForSemanticSegmentation(__lowerCamelCase )
									model.to(__lowerCamelCase )
									model.eval()
									UpperCAmelCase					=			model(__lowerCamelCase )
									self.parent.assertEqual(
									    result.logits.shape       ,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
									UpperCAmelCase					=			model(__lowerCamelCase       ,  labels=__lowerCamelCase )
									self.parent.assertEqual(
									    result.logits.shape       ,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
									self.parent.assertGreater(result.loss       ,  0.0 )






						def      UpperCAmelCase__					( self			:Union[str, Any]       ,  lowercase_			:Tuple       ,  lowercase_			:Tuple       ,  lowercase_			:Any )    ->      List[Any]:
									UpperCAmelCase					=			1
									UpperCAmelCase					=			SegformerForSemanticSegmentation(config=__lowerCamelCase )
									model.to(__lowerCamelCase )
									model.eval()
									UpperCAmelCase					=			torch.randint(0       ,  1       ,  (self.batch_size, self.image_size, self.image_size) ).to(__lowerCamelCase )
									UpperCAmelCase					=			model(__lowerCamelCase       ,  labels=__lowerCamelCase )
									self.parent.assertGreater(result.loss       ,  0.0 )






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      Optional[Any]:
									UpperCAmelCase					=			self.prepare_config_and_inputs()
									UpperCAmelCase				,   UpperCAmelCase				,   UpperCAmelCase					=			config_and_inputs
									UpperCAmelCase					=			{'pixel_values': pixel_values}
									return config, inputs_dict







@require_torch
class 				A_      (					UpperCamelCase__     ,       UpperCamelCase__     ,       unittest.TestCase    ):



						"""simple docstring"""
						__UpperCamelCase		    =							(
						    (
						        SegformerModel,
						        SegformerForSemanticSegmentation,
						        SegformerForImageClassification,
						    )
						    if is_torch_available()
						    else ()
						)
						__UpperCamelCase		    =							(
						    {
						        """feature-extraction""": SegformerModel,
						        """image-classification""": SegformerForImageClassification,
						        """image-segmentation""": SegformerForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						__UpperCamelCase		    =							True
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Union[str, Any]:
									UpperCAmelCase					=			SegformerModelTester(self )
									UpperCAmelCase					=			SegformerConfigTester(self       ,  config_class=__lowerCamelCase )






						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      Optional[int]:
									self.config_tester.run_common_tests()






						def      UpperCAmelCase__					( self			:int )    ->      Dict:
									UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__lowerCamelCase )






						def      UpperCAmelCase__					( self			:str )    ->      List[Any]:
									UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_binary_image_segmentation(*__lowerCamelCase )






						def      UpperCAmelCase__					( self			:int )    ->      Union[str, Any]:
									UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_segmentation(*__lowerCamelCase )






						@unittest.skip('SegFormer does not use inputs_embeds' )
						def      UpperCAmelCase__					( self			:List[Any] )    ->      int:
									pass






						@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods' )
						def      UpperCAmelCase__					( self			:Tuple )    ->      List[Any]:
									pass






						def      UpperCAmelCase__					( self			:str )    ->      Dict:
									UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												UpperCAmelCase					=			model_class(__lowerCamelCase )
												UpperCAmelCase					=			inspect.signature(model.forward )
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												UpperCAmelCase					=			[*signature.parameters.keys()]

												UpperCAmelCase					=			['pixel_values']
												self.assertListEqual(arg_names[:1]       ,  __lowerCamelCase )






						def      UpperCAmelCase__					( self			:List[str] )    ->      str:
									UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()
									UpperCAmelCase					=			True

									for model_class in self.all_model_classes:
												UpperCAmelCase					=			True
												UpperCAmelCase					=			False
												UpperCAmelCase					=			True
												UpperCAmelCase					=			model_class(__lowerCamelCase )
												model.to(__lowerCamelCase )
												model.eval()
												with torch.no_grad():
															UpperCAmelCase					=			model(**self._prepare_for_class(__lowerCamelCase       ,  __lowerCamelCase ) )
												UpperCAmelCase					=			outputs.attentions

												UpperCAmelCase					=			sum(self.model_tester.depths )
												self.assertEqual(len(__lowerCamelCase )       ,  __lowerCamelCase )

												# check that output_attentions also work using config
												del inputs_dict["output_attentions"]
												UpperCAmelCase					=			True
												UpperCAmelCase					=			model_class(__lowerCamelCase )
												model.to(__lowerCamelCase )
												model.eval()
												with torch.no_grad():
															UpperCAmelCase					=			model(**self._prepare_for_class(__lowerCamelCase       ,  __lowerCamelCase ) )
												UpperCAmelCase					=			outputs.attentions

												self.assertEqual(len(__lowerCamelCase )       ,  __lowerCamelCase )

												# verify the first attentions (first block, first layer)
												UpperCAmelCase					=			(self.model_tester.image_size // 4) ** 2
												UpperCAmelCase					=			(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
												self.assertListEqual(
												    list(attentions[0].shape[-3:] )       ,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,  )

												# verify the last attentions (last block, last layer)
												UpperCAmelCase					=			(self.model_tester.image_size // 32) ** 2
												UpperCAmelCase					=			(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
												self.assertListEqual(
												    list(attentions[-1].shape[-3:] )       ,  [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]       ,  )
												UpperCAmelCase					=			len(__lowerCamelCase )

												# Check attention is always last and order is fine
												UpperCAmelCase					=			True
												UpperCAmelCase					=			True
												UpperCAmelCase					=			model_class(__lowerCamelCase )
												model.to(__lowerCamelCase )
												model.eval()
												with torch.no_grad():
															UpperCAmelCase					=			model(**self._prepare_for_class(__lowerCamelCase       ,  __lowerCamelCase ) )

												self.assertEqual(out_len + 1       ,  len(__lowerCamelCase ) )

												UpperCAmelCase					=			outputs.attentions

												self.assertEqual(len(__lowerCamelCase )       ,  __lowerCamelCase )
												# verify the first attentions (first block, first layer)
												UpperCAmelCase					=			(self.model_tester.image_size // 4) ** 2
												UpperCAmelCase					=			(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
												self.assertListEqual(
												    list(self_attentions[0].shape[-3:] )       ,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,  )






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      Union[str, Any]:
									def check_hidden_states_output(lowercase_			:Dict       ,  lowercase_			:Tuple       ,  lowercase_			:List[str] ):
												UpperCAmelCase					=			model_class(__lowerCamelCase )
												model.to(__lowerCamelCase )
												model.eval()

												with torch.no_grad():
															UpperCAmelCase					=			model(**self._prepare_for_class(__lowerCamelCase       ,  __lowerCamelCase ) )

												UpperCAmelCase					=			outputs.hidden_states

												UpperCAmelCase					=			self.model_tester.num_encoder_blocks
												self.assertEqual(len(__lowerCamelCase )       ,  __lowerCamelCase )

												# verify the first hidden states (first block)
												self.assertListEqual(
												    list(hidden_states[0].shape[-3:] )       ,  [
												        self.model_tester.hidden_sizes[0],
												        self.model_tester.image_size // 4,
												        self.model_tester.image_size // 4,
												    ]       ,  )

									UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												UpperCAmelCase					=			True
												check_hidden_states_output(__lowerCamelCase       ,  __lowerCamelCase       ,  __lowerCamelCase )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												UpperCAmelCase					=			True

												check_hidden_states_output(__lowerCamelCase       ,  __lowerCamelCase       ,  __lowerCamelCase )






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Dict:
									if not self.model_tester.is_training:
												return

									UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()
									UpperCAmelCase					=			True

									for model_class in self.all_model_classes:
												if model_class in get_values(__lowerCamelCase ):
															continue

												UpperCAmelCase					=			model_class(__lowerCamelCase )
												model.to(__lowerCamelCase )
												model.train()
												UpperCAmelCase					=			self._prepare_for_class(__lowerCamelCase       ,  __lowerCamelCase       ,  return_labels=__lowerCamelCase )
												UpperCAmelCase					=			model(**__lowerCamelCase ).loss
												loss.backward()






						@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
						def      UpperCAmelCase__					( self			:Any )    ->      Optional[Any]:
									pass






						@slow
						def      UpperCAmelCase__					( self			:str )    ->      str:
									for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase					=			SegformerModel.from_pretrained(__lowerCamelCase )
												self.assertIsNotNone(__lowerCamelCase )


def 			_lowerCAmelCase				(       ):
			UpperCAmelCase					=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
			return image







@require_torch
class 				A_      (					unittest.TestCase    ):



						"""simple docstring"""






						@slow
						def      UpperCAmelCase__					( self			:Dict )    ->      Optional[int]:
									# only resize + normalize
									UpperCAmelCase					=			SegformerImageProcessor(
									    image_scale=(5_12, 5_12)       ,  keep_ratio=__lowerCamelCase       ,  align=__lowerCamelCase       ,  do_random_crop=__lowerCamelCase )
									UpperCAmelCase					=			SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512' ).to(
									    __lowerCamelCase )

									UpperCAmelCase					=			prepare_img()
									UpperCAmelCase					=			image_processor(images=__lowerCamelCase       ,  return_tensors='pt' )
									UpperCAmelCase					=			encoded_inputs.pixel_values.to(__lowerCamelCase )

									with torch.no_grad():
												UpperCAmelCase					=			model(__lowerCamelCase )

									UpperCAmelCase					=			torch.Size((1, model.config.num_labels, 1_28, 1_28) )
									self.assertEqual(outputs.logits.shape       ,  __lowerCamelCase )

									UpperCAmelCase					=			torch.tensor(
									    [
									        [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
									        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
									        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
									    ] ).to(__lowerCamelCase )
									self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]       ,  __lowerCamelCase       ,  atol=1E-4 ) )






						@slow
						def      UpperCAmelCase__					( self			:Tuple )    ->      Any:
									# only resize + normalize
									UpperCAmelCase					=			SegformerImageProcessor(
									    image_scale=(5_12, 5_12)       ,  keep_ratio=__lowerCamelCase       ,  align=__lowerCamelCase       ,  do_random_crop=__lowerCamelCase )
									UpperCAmelCase					=			SegformerForSemanticSegmentation.from_pretrained(
									    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024' ).to(__lowerCamelCase )

									UpperCAmelCase					=			prepare_img()
									UpperCAmelCase					=			image_processor(images=__lowerCamelCase       ,  return_tensors='pt' )
									UpperCAmelCase					=			encoded_inputs.pixel_values.to(__lowerCamelCase )

									with torch.no_grad():
												UpperCAmelCase					=			model(__lowerCamelCase )

									UpperCAmelCase					=			torch.Size((1, model.config.num_labels, 1_28, 1_28) )
									self.assertEqual(outputs.logits.shape       ,  __lowerCamelCase )

									UpperCAmelCase					=			torch.tensor(
									    [
									        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
									        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
									        [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
									    ] ).to(__lowerCamelCase )
									self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]       ,  __lowerCamelCase       ,  atol=1E-1 ) )






						@slow
						def      UpperCAmelCase__					( self			:Tuple )    ->      str:
									# only resize + normalize
									UpperCAmelCase					=			SegformerImageProcessor(
									    image_scale=(5_12, 5_12)       ,  keep_ratio=__lowerCamelCase       ,  align=__lowerCamelCase       ,  do_random_crop=__lowerCamelCase )
									UpperCAmelCase					=			SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512' ).to(
									    __lowerCamelCase )

									UpperCAmelCase					=			prepare_img()
									UpperCAmelCase					=			image_processor(images=__lowerCamelCase       ,  return_tensors='pt' )
									UpperCAmelCase					=			encoded_inputs.pixel_values.to(__lowerCamelCase )

									with torch.no_grad():
												UpperCAmelCase					=			model(__lowerCamelCase )

									UpperCAmelCase					=			outputs.logits.detach().cpu()

									UpperCAmelCase					=			image_processor.post_process_semantic_segmentation(outputs=__lowerCamelCase       ,  target_sizes=[(5_00, 3_00)] )
									UpperCAmelCase					=			torch.Size((5_00, 3_00) )
									self.assertEqual(segmentation[0].shape       ,  __lowerCamelCase )

									UpperCAmelCase					=			image_processor.post_process_semantic_segmentation(outputs=__lowerCamelCase )
									UpperCAmelCase					=			torch.Size((1_28, 1_28) )
									self.assertEqual(segmentation[0].shape       ,  __lowerCamelCase )










"""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""")





