'''simple docstring'''





from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block




@dataclass
class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							42





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[Any]       ,		lowercase__					:						List[str]=3       ,		lowercase__					:						Tuple=3       ,		lowercase__					:						List[str]=("DownEncoderBlock2D",)       ,		lowercase__					:						Optional[int]=(64,)       ,		lowercase__					:						List[Any]=2       ,		lowercase__					:						int=32       ,		lowercase__					:						Optional[int]="silu"       ,		lowercase__					:						List[Any]=True       ,		)							->Optional[Any]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			Union[str, Any]   			=						layers_per_block

										_UpperCamelCase			:			Union[str, Any]   			=						torch.nn.Convad(
										    lowercase__       ,		block_out_channels[0]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

										_UpperCamelCase			:			int   			=						None
										_UpperCamelCase			:			Optional[Any]   			=						nn.ModuleList([]					)

										# down
										_UpperCamelCase			:			Optional[int]   			=						block_out_channels[0]
										for i, down_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			int   			=						output_channel
																_UpperCamelCase			:			int   			=						block_out_channels[i]
																_UpperCamelCase			:			Tuple   			=						i == len(lowercase__					) - 1

																_UpperCamelCase			:			List[Any]   			=						get_down_block(
																    lowercase__       ,		num_layers=self.layers_per_block       ,		in_channels=lowercase__       ,		out_channels=lowercase__       ,		add_downsample=not is_final_block       ,		resnet_eps=1e-6       ,		downsample_padding=0       ,		resnet_act_fn=lowercase__       ,		resnet_groups=lowercase__       ,		attention_head_dim=lowercase__       ,		temb_channels=lowercase__       ,		)
																self.down_blocks.append(lowercase__					)

										# mid
										_UpperCamelCase			:			Dict   			=						UNetMidBlockaD(
										    in_channels=block_out_channels[-1]       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		output_scale_factor=1       ,		resnet_time_scale_shift="default"       ,		attention_head_dim=block_out_channels[-1]       ,		resnet_groups=lowercase__       ,		temb_channels=lowercase__       ,		)

										# out
										_UpperCamelCase			:			List[str]   			=						nn.GroupNorm(num_channels=block_out_channels[-1]       ,		num_groups=lowercase__       ,		eps=1e-6					)
										_UpperCamelCase			:			Union[str, Any]   			=						nn.SiLU()

										_UpperCamelCase			:			Tuple   			=						2 * out_channels if double_z else out_channels
										_UpperCamelCase			:			List[Any]   			=						nn.Convad(block_out_channels[-1]       ,		lowercase__       ,		3       ,		padding=1					)

										_UpperCamelCase			:			Tuple   			=						False







				def  snake_case__				(						self					:						str       ,		lowercase__					:						Any					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						x
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

										if self.training and self.gradient_checkpointing:

																def create_custom_forward(lowercase__					:						Any					):
																						def custom_forward(*lowercase__					:						List[Any]					):
																												return module(*lowercase__					)

																						return custom_forward

																# down
																if is_torch_version(">="       ,		"1.11.0"					):
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			Optional[Any]   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						# middle
																						_UpperCamelCase			:			List[Any]   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			List[str]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__					)
																						# middle
																						_UpperCamelCase			:			Union[str, Any]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block					)       ,		lowercase__					)

										else:
																# down
																for down_block in self.down_blocks:
																						_UpperCamelCase			:			Tuple   			=						down_block(lowercase__					)

																# middle
																_UpperCamelCase			:			Optional[int]   			=						self.mid_block(lowercase__					)

										# post-process
										_UpperCamelCase			:			List[Any]   			=						self.conv_norm_out(lowercase__					)
										_UpperCamelCase			:			Tuple   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			int   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						str=3       ,		lowercase__					:						List[Any]=3       ,		lowercase__					:						Optional[int]=("UpDecoderBlock2D",)       ,		lowercase__					:						Any=(64,)       ,		lowercase__					:						str=2       ,		lowercase__					:						List[Any]=32       ,		lowercase__					:						Optional[int]="silu"       ,		lowercase__					:						List[str]="group"       ,		)							->Any:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						layers_per_block

										_UpperCamelCase			:			Any   			=						nn.Convad(
										    lowercase__       ,		block_out_channels[-1]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

										_UpperCamelCase			:			List[str]   			=						None
										_UpperCamelCase			:			Dict   			=						nn.ModuleList([]					)

										_UpperCamelCase			:			Optional[int]   			=						in_channels if norm_type == "spatial" else None

										# mid
										_UpperCamelCase			:			int   			=						UNetMidBlockaD(
										    in_channels=block_out_channels[-1]       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		output_scale_factor=1       ,		resnet_time_scale_shift="default" if norm_type == "group" else norm_type       ,		attention_head_dim=block_out_channels[-1]       ,		resnet_groups=lowercase__       ,		temb_channels=lowercase__       ,		)

										# up
										_UpperCamelCase			:			Dict   			=						list(reversed(lowercase__					)					)
										_UpperCamelCase			:			Tuple   			=						reversed_block_out_channels[0]
										for i, up_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			Union[str, Any]   			=						output_channel
																_UpperCamelCase			:			Dict   			=						reversed_block_out_channels[i]

																_UpperCamelCase			:			List[str]   			=						i == len(lowercase__					) - 1

																_UpperCamelCase			:			Tuple   			=						get_up_block(
																    lowercase__       ,		num_layers=self.layers_per_block + 1       ,		in_channels=lowercase__       ,		out_channels=lowercase__       ,		prev_output_channel=lowercase__       ,		add_upsample=not is_final_block       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		resnet_groups=lowercase__       ,		attention_head_dim=lowercase__       ,		temb_channels=lowercase__       ,		resnet_time_scale_shift=lowercase__       ,		)
																self.up_blocks.append(lowercase__					)
																_UpperCamelCase			:			Any   			=						output_channel

										# out
										if norm_type == "spatial":
																_UpperCamelCase			:			Any   			=						SpatialNorm(block_out_channels[0]       ,		lowercase__					)
										else:
																_UpperCamelCase			:			int   			=						nn.GroupNorm(num_channels=block_out_channels[0]       ,		num_groups=lowercase__       ,		eps=1e-6					)
										_UpperCamelCase			:			Tuple   			=						nn.SiLU()
										_UpperCamelCase			:			Tuple   			=						nn.Convad(block_out_channels[0]       ,		lowercase__       ,		3       ,		padding=1					)

										_UpperCamelCase			:			Optional[Any]   			=						False







				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						Union[str, Any]       ,		lowercase__					:						Optional[Any]=None					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						z
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

										_UpperCamelCase			:			Any   			=						next(iter(self.up_blocks.parameters()					)					).dtype
										if self.training and self.gradient_checkpointing:

																def create_custom_forward(lowercase__					:						Optional[int]					):
																						def custom_forward(*lowercase__					:						List[str]					):
																												return module(*lowercase__					)

																						return custom_forward

																if is_torch_version(">="       ,		"1.11.0"					):
																						# middle
																						_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						_UpperCamelCase			:			Union[str, Any]   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						# middle
																						_UpperCamelCase			:			Any   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__					)
																						_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__					)
										else:
																# middle
																_UpperCamelCase			:			str   			=						self.mid_block(lowercase__       ,		lowercase__					)
																_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																# up
																for up_block in self.up_blocks:
																						_UpperCamelCase			:			str   			=						up_block(lowercase__       ,		lowercase__					)

        # post-process
										if latent_embeds is None:
																_UpperCamelCase			:			Union[str, Any]   			=						self.conv_norm_out(lowercase__					)
										else:
																_UpperCamelCase			:			Any   			=						self.conv_norm_out(lowercase__       ,		lowercase__					)
										_UpperCamelCase			:			List[str]   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			Dict   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[int]       ,		lowercase__					:						str       ,		lowercase__					:						Tuple       ,		lowercase__					:						Optional[Any]       ,		lowercase__					:						Tuple=None       ,		lowercase__					:						Dict="random"       ,		lowercase__					:						List[Any]=False       ,		lowercase__					:						List[Any]=True					)							->Optional[int]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						n_e
										_UpperCamelCase			:			List[str]   			=						vq_embed_dim
										_UpperCamelCase			:			List[str]   			=						beta
										_UpperCamelCase			:			Any   			=						legacy

										_UpperCamelCase			:			Optional[int]   			=						nn.Embedding(self.n_e       ,		self.vq_embed_dim					)
										self.embedding.weight.data.uniform_(-1.0 / self.n_e       ,		1.0 / self.n_e					)

										_UpperCamelCase			:			str   			=						remap
										if self.remap is not None:
																self.register_buffer("used"       ,		torch.tensor(np.load(self.remap					)					)					)
																_UpperCamelCase			:			List[Any]   			=						self.used.shape[0]
																_UpperCamelCase			:			Optional[int]   			=						unknown_index  # "random" or "extra" or integer
																if self.unknown_index == "extra":
																						_UpperCamelCase			:			Any   			=						self.re_embed
																						_UpperCamelCase			:			Any   			=						self.re_embed + 1
																print(
																    f'''Remapping {self.n_e} indices to {self.re_embed} indices. '''
																    f'''Using {self.unknown_index} for unknown indices.'''					)
										else:
																_UpperCamelCase			:			Optional[Any]   			=						n_e

										_UpperCamelCase			:			Optional[Any]   			=						sane_index_shape





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Dict					)							->Optional[int]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						inds.shape
										assert len(lowercase__					) > 1
										_UpperCamelCase			:			List[Any]   			=						inds.reshape(ishape[0]       ,		-1					)
										_UpperCamelCase			:			Tuple   			=						self.used.to(lowercase__					)
										_UpperCamelCase			:			List[str]   			=						(inds[:, :, None] == used[None, None, ...]).long()
										_UpperCamelCase			:			Optional[Any]   			=						match.argmax(-1					)
										_UpperCamelCase			:			int   			=						match.sum(2					) < 1
										if self.unknown_index == "random":
																_UpperCamelCase			:			int   			=						torch.randint(0       ,		self.re_embed       ,		size=new[unknown].shape					).to(device=new.device					)
										else:
																_UpperCamelCase			:			Optional[int]   			=						self.unknown_index
										return new.reshape(lowercase__					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[Any]					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						inds.shape
										assert len(lowercase__					) > 1
										_UpperCamelCase			:			Dict   			=						inds.reshape(ishape[0]       ,		-1					)
										_UpperCamelCase			:			Optional[Any]   			=						self.used.to(lowercase__					)
										if self.re_embed > self.used.shape[0]:  # extra token
																_UpperCamelCase			:			int   			=						0  # simply set to zero
										_UpperCamelCase			:			Tuple   			=						torch.gather(used[None, :][inds.shape[0] * [0], :]       ,		1       ,		lowercase__					)
										return back.reshape(lowercase__					)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						Union[str, Any]					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						z.permute(0       ,		2       ,		3       ,		1					).contiguous()
										_UpperCamelCase			:			Optional[Any]   			=						z.view(-1       ,		self.vq_embed_dim					)

										# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
										_UpperCamelCase			:			Optional[Any]   			=						torch.argmin(torch.cdist(lowercase__       ,		self.embedding.weight					)       ,		dim=1					)

										_UpperCamelCase			:			List[str]   			=						self.embedding(lowercase__					).view(z.shape					)
										_UpperCamelCase			:			Optional[int]   			=						None
										_UpperCamelCase			:			Tuple   			=						None

										# compute loss for embedding
										if not self.legacy:
																_UpperCamelCase			:			Any   			=						self.beta * torch.mean((z_q.detach() - z) ** 2					) + torch.mean((z_q - z.detach()) ** 2					)
										else:
																_UpperCamelCase			:			str   			=						torch.mean((z_q.detach() - z) ** 2					) + self.beta * torch.mean((z_q - z.detach()) ** 2					)

										# preserve gradients
										_UpperCamelCase			:			List[Any]   			=						z + (z_q - z).detach()

										# reshape back to match original input shape
										_UpperCamelCase			:			List[Any]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										if self.remap is not None:
																_UpperCamelCase			:			str   			=						min_encoding_indices.reshape(z.shape[0]       ,		-1					)  # add batch axis
																_UpperCamelCase			:			int   			=						self.remap_to_used(lowercase__					)
																_UpperCamelCase			:			List[str]   			=						min_encoding_indices.reshape(-1       ,		1					)  # flatten

										if self.sane_index_shape:
																_UpperCamelCase			:			Tuple   			=						min_encoding_indices.reshape(z_q.shape[0]       ,		z_q.shape[2]       ,		z_q.shape[3]					)

										return z_q, loss, (perplexity, min_encodings, min_encoding_indices)







				def  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						List[str]       ,		lowercase__					:						List[str]					)							->Dict:


										'''simple docstring'''




										if self.remap is not None:
																_UpperCamelCase			:			Tuple   			=						indices.reshape(shape[0]       ,		-1					)  # add batch axis
																_UpperCamelCase			:			str   			=						self.unmap_to_all(lowercase__					)
																_UpperCamelCase			:			str   			=						indices.reshape(-1					)  # flatten again

										# get quantized latent vectors
										_UpperCamelCase			:			Dict   			=						self.embedding(lowercase__					)

										if shape is not None:
																_UpperCamelCase			:			List[Any]   			=						z_q.view(lowercase__					)
																# reshape back to match original input shape
																_UpperCamelCase			:			Optional[int]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										return z_q





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=False					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						parameters
										_UpperCamelCase			,       _UpperCamelCase			:			Tuple   			=						torch.chunk(lowercase__       ,		2       ,		dim=1					)
										_UpperCamelCase			:			str   			=						torch.clamp(self.logvar       ,		-3_0.0       ,		2_0.0					)
										_UpperCamelCase			:			str   			=						deterministic
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(0.5 * self.logvar					)
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(self.logvar					)
										if self.deterministic:
																_UpperCamelCase			:			Optional[Any]   			=						torch.zeros_like(
																    self.mean       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[torch.Generator] = None					)							->torch.FloatTensor:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						randn_tensor(
										    self.mean.shape       ,		generator=lowercase__       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)
										_UpperCamelCase			:			Optional[int]   			=						self.mean + self.std * sample
										return x





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Optional[int]=None					)							->List[str]:


										'''simple docstring'''




										if self.deterministic:
																return torch.Tensor([0.0]					)
										else:
																if other is None:
																						return 0.5 * torch.sum(torch.pow(self.mean       ,		2					) + self.var - 1.0 - self.logvar       ,		dim=[1, 2, 3]					)
																else:
																						return 0.5 * torch.sum(
																						    torch.pow(self.mean - other.mean       ,		2					) / other.var
																						    + self.var / other.var
																						    - 1.0
																						    - self.logvar
																						    + other.logvar       ,		dim=[1, 2, 3]       ,		)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=[1, 2, 3]					)							->Dict:


										'''simple docstring'''




										if self.deterministic:
																return torch.Tensor([0.0]					)
										_UpperCamelCase			:			Optional[Any]   			=						np.log(2.0 * np.pi					)
										return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean       ,		2					) / self.var       ,		dim=lowercase__					)







				def  snake_case__				(						self					:						List[Any]					)							->str:


										'''simple docstring'''




										return self.mean



'''simple docstring'''





import logging
import os
import threading
import time


try:
			import warnings
except ImportError:
			lowerCAmelCase_	:		Any			=     None

try:
			import msvcrt
except ImportError:
			lowerCAmelCase_	:		Union[str, Any]			=     None

try:
			import fcntl
except ImportError:
			lowerCAmelCase_	:		List[Any]			=     None


# Backward compatibility
# ------------------------------------------------
try:
			TimeoutError
except NameError:
			lowerCAmelCase_	:		Optional[int]			=     OSError


# Data
# ------------------------------------------------
lowerCAmelCase_	:		Optional[int]			=     [
    """Timeout""",
    """BaseFileLock""",
    """WindowsFileLock""",
    """UnixFileLock""",
    """SoftFileLock""",
    """FileLock""",
]

lowerCAmelCase_	:		List[Any]			=     """3.0.12"""


lowerCAmelCase_	:		Optional[int]			=     None
def 						__A							(     )     ->			Optional[Any]:




						'''simple docstring'''
						global _logger
						_UpperCamelCase			:			Union[str, Any]   			=						_logger or logging.getLogger(__name__					)
						return _logger




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						List[str]					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						lock_file
										return None







				def __str__(						self					:						List[str]					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[int]   			=						f'''The file lock \'{self.lock_file}\' could not be acquired.'''
										return temp





class 		SCREAMING_SNAKE_CASE     :







				'''simple docstring'''





				def __init__(						self					:						List[Any]       ,		lowercase__					:						List[str]					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			List[str]   			=						lock
										return None





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


										'''simple docstring'''




										return self.lock







				def __exit__(						self					:						Union[str, Any]       ,		lowercase__					:						Tuple       ,		lowercase__					:						List[str]       ,		lowercase__					:						int					)							->str:


										'''simple docstring'''




										self.lock.release()
										return None





class 		SCREAMING_SNAKE_CASE     :







				'''simple docstring'''





				def __init__(						self					:						Any       ,		lowercase__					:						Tuple       ,		lowercase__					:						Any=-1       ,		lowercase__					:						int=None					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			int   			=						max_filename_length if max_filename_length is not None else 255
										# Hash the filename if it's too long
										_UpperCamelCase			:			str   			=						self.hash_filename_if_too_long(lowercase__       ,		lowercase__					)
										# The path to the lock file.
										_UpperCamelCase			:			Optional[int]   			=						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			:			Optional[int]   			=						None

										# The default timeout value.
										_UpperCamelCase			:			Any   			=						timeout

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





				@property
				def  snake_case__				(						self					:						Optional[Any]					)							->str:


										'''simple docstring'''




										return self._lock_file





				@property
				def  snake_case__				(						self					:						int					)							->str:


										'''simple docstring'''




										return self._timeout





				@timeout.setter
				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						Tuple					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						float(lowercase__					)
										return None





				def  snake_case__				(						self					:						Optional[Any]					)							->Tuple:


										'''simple docstring'''




										raise NotImplementedError()





				def  snake_case__				(						self					:						str					)							->Optional[Any]:


										'''simple docstring'''




										raise NotImplementedError()





				@property
				def  snake_case__				(						self					:						str					)							->Tuple:


										'''simple docstring'''




										return self._lock_file_fd is not None





				def  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						Optional[int]=None       ,		lowercase__					:						str=0.0_5					)							->str:


										'''simple docstring'''




										if timeout is None:
																_UpperCamelCase			:			Tuple   			=						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			:			List[str]   			=						id(self					)
										_UpperCamelCase			:			List[str]   			=						self._lock_file
										_UpperCamelCase			:			List[str]   			=						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			:			List[Any]   			=						max(0       ,		self._lock_counter - 1					)

																raise
										return _Acquire_ReturnProxy(lock=self					)





				def  snake_case__				(						self					:						Dict       ,		lowercase__					:						str=False					)							->Tuple:


										'''simple docstring'''




										with self._thread_lock:
																if self.is_locked:
																						self._lock_counter -= 1

																						if self._lock_counter == 0 or force:
																												_UpperCamelCase			:			Tuple   			=						id(self					)
																												_UpperCamelCase			:			str   			=						self._lock_file

																												logger().debug(f'''Attempting to release lock {lock_id} on {lock_filename}'''					)
																												self._release()
																												_UpperCamelCase			:			List[str]   			=						0
																												logger().debug(f'''Lock {lock_id} released on {lock_filename}'''					)

										return None





				def __enter__(						self					:						Optional[int]					)							->str:


										'''simple docstring'''




										self.acquire()
										return self





				def __exit__(						self					:						List[Any]       ,		lowercase__					:						int       ,		lowercase__					:						Dict       ,		lowercase__					:						Union[str, Any]					)							->Tuple:


										'''simple docstring'''




										self.release()
										return None





				def __del__(						self					:						Dict					)							->int:


										'''simple docstring'''




										self.release(force=lowercase__					)
										return None







				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						str       ,		lowercase__					:						int					)							->str:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						os.path.basename(lowercase__					)
										if len(lowercase__					) > max_length and max_length > 0:
																_UpperCamelCase			:			Optional[Any]   			=						os.path.dirname(lowercase__					)
																_UpperCamelCase			:			Tuple   			=						str(hash(lowercase__					)					)
																_UpperCamelCase			:			Dict   			=						filename[: max_length - len(lowercase__					) - 8] + "..." + hashed_filename + ".lock"
																return os.path.join(lowercase__       ,		lowercase__					)
										else:
																return path





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





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


										'''simple docstring'''




										from .file_utils import relative_to_absolute_path

										super().__init__(lowercase__       ,		timeout=lowercase__       ,		max_filename_length=lowercase__					)
										_UpperCamelCase			:			int   			=						"\\\\?\\" + relative_to_absolute_path(self.lock_file					)





				def  snake_case__				(						self					:						int					)							->Dict:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[Any]   			=						os.O_RDWR | os.O_CREAT | os.O_TRUNC

										try:
																_UpperCamelCase			:			str   			=						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			:			Union[str, Any]   			=						fd
										return None







				def  snake_case__				(						self					:						List[Any]					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[int]   			=						self._lock_file_fd
										_UpperCamelCase			:			Optional[int]   			=						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 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						List[Any]       ,		lowercase__					:						Any       ,		lowercase__					:						Union[str, Any]=-1       ,		lowercase__					:						Dict=None					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[Any]   			=						os.statvfs(os.path.dirname(lowercase__					)					).f_namemax
										super().__init__(lowercase__       ,		timeout=lowercase__       ,		max_filename_length=lowercase__					)





				def  snake_case__				(						self					:						List[Any]					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[Any]   			=						os.O_RDWR | os.O_CREAT | os.O_TRUNC
										_UpperCamelCase			:			str   			=						os.open(self._lock_file       ,		lowercase__					)

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







				def  snake_case__				(						self					:						Optional[Any]					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			List[str]   			=						self._lock_file_fd
										_UpperCamelCase			:			List[Any]   			=						None
										fcntl.flock(lowercase__       ,		fcntl.LOCK_UN					)
										os.close(lowercase__					)
										return None





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def  snake_case__				(						self					:						List[Any]					)							->List[str]:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
										try:
																_UpperCamelCase			:			Any   			=						os.open(self._lock_file       ,		lowercase__					)
										except OSError:
																pass
										else:
																_UpperCamelCase			:			str   			=						fd
										return None







				def  snake_case__				(						self					:						Dict					)							->int:


										'''simple docstring'''




										os.close(self._lock_file_fd					)
										_UpperCamelCase			:			Dict   			=						None

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





lowerCAmelCase_	:		List[Any]			=     None

if msvcrt:
			lowerCAmelCase_	:		Dict			=     WindowsFileLock
elif fcntl:
			lowerCAmelCase_	:		int			=     UnixFileLock
else:
			lowerCAmelCase_	:		Tuple			=     SoftFileLock

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


