




import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
	import torch
	from torch import nn

	from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
	from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import DPTImageProcessor
class        __snake_case  :



				def __init__(      self      :		List[str]		,	_UpperCAmelCase      :		Dict		,	_UpperCAmelCase      :		Any=2		,	_UpperCAmelCase      :		Tuple=32		,	_UpperCAmelCase      :		Union[str, Any]=16		,	_UpperCAmelCase      :		List[Any]=3		,	_UpperCAmelCase      :		List[Any]=True		,	_UpperCAmelCase      :		Optional[int]=True		,	_UpperCAmelCase      :		Optional[int]=32		,	_UpperCAmelCase      :		Any=4		,	_UpperCAmelCase      :		Tuple=[0, 1, 2, 3]		,	_UpperCAmelCase      :		Optional[int]=4		,	_UpperCAmelCase      :		int=37		,	_UpperCAmelCase      :		str="gelu"		,	_UpperCAmelCase      :		Union[str, Any]=0.1		,	_UpperCAmelCase      :		Tuple=0.1		,	_UpperCAmelCase      :		List[str]=0.02		,	_UpperCAmelCase      :		Any=3		,	_UpperCAmelCase      :		List[str]=[1, 384, 24, 24]		,	_UpperCAmelCase      :		Optional[int]=True		,	_UpperCAmelCase      :		Union[str, Any]=None		,	)  ->    int:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[Any]										=      parent
								_lowerCAmelCase    :    Optional[int]										=      batch_size
								_lowerCAmelCase    :    List[Any]										=      image_size
								_lowerCAmelCase    :    List[str]										=      patch_size
								_lowerCAmelCase    :    Any										=      num_channels
								_lowerCAmelCase    :    List[str]										=      is_training
								_lowerCAmelCase    :    int										=      use_labels
								_lowerCAmelCase    :    Optional[int]										=      hidden_size
								_lowerCAmelCase    :    str										=      num_hidden_layers
								_lowerCAmelCase    :    Optional[Any]										=      backbone_out_indices
								_lowerCAmelCase    :    List[str]										=      num_attention_heads
								_lowerCAmelCase    :    Optional[int]										=      intermediate_size
								_lowerCAmelCase    :    int										=      hidden_act
								_lowerCAmelCase    :    int										=      hidden_dropout_prob
								_lowerCAmelCase    :    int										=      attention_probs_dropout_prob
								_lowerCAmelCase    :    Optional[int]										=      initializer_range
								_lowerCAmelCase    :    List[str]										=      num_labels
								_lowerCAmelCase    :    Optional[Any]										=      backbone_featmap_shape
								_lowerCAmelCase    :    List[Any]										=      scope
								_lowerCAmelCase    :    Any										=      is_hybrid
								# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
								_lowerCAmelCase    :    int										=      (image_size // patch_size) ** 2
								_lowerCAmelCase    :    List[Any]										=      num_patches + 1



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict      )  ->    Tuple:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[int]										=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

								_lowerCAmelCase    :    Union[str, Any]										=      None
								if self.use_labels:
												_lowerCAmelCase    :    Union[str, Any]										=      ids_tensor([self.batch_size, self.image_size, self.image_size]		,	self.num_labels      )

								_lowerCAmelCase    :    List[Any]										=      self.get_config()

								return config, pixel_values, labels



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





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[int]										=      {
								    """global_padding""": """same""",
								    """layer_type""": """bottleneck""",
								    """depths""": [3, 4, 9],
								    """out_features""": ["""stage1""", """stage2""", """stage3"""],
								    """embedding_dynamic_padding""": True,
								    """hidden_sizes""": [96, 192, 384, 768],
								    """num_groups""": 2,
								}

								return DPTConfig(
								    image_size=self.image_size		,	patch_size=self.patch_size		,	num_channels=self.num_channels		,	hidden_size=self.hidden_size		,	num_hidden_layers=self.num_hidden_layers		,	backbone_out_indices=self.backbone_out_indices		,	num_attention_heads=self.num_attention_heads		,	intermediate_size=self.intermediate_size		,	hidden_act=self.hidden_act		,	hidden_dropout_prob=self.hidden_dropout_prob		,	attention_probs_dropout_prob=self.attention_probs_dropout_prob		,	is_decoder=_SCREAMING_SNAKE_CASE		,	initializer_range=self.initializer_range		,	is_hybrid=self.is_hybrid		,	backbone_config=_SCREAMING_SNAKE_CASE		,	backbone_featmap_shape=self.backbone_featmap_shape		,	)



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]		,	_UpperCAmelCase      :		List[str]		,	_UpperCAmelCase      :		Any		,	_UpperCAmelCase      :		Dict      )  ->    Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    str										=      DPTModel(config=_SCREAMING_SNAKE_CASE      )
								model.to(_SCREAMING_SNAKE_CASE      )
								model.eval()
								_lowerCAmelCase    :    List[Any]										=      model(_SCREAMING_SNAKE_CASE      )
								self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, self.seq_length, self.hidden_size)      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict		,	_UpperCAmelCase      :		Tuple		,	_UpperCAmelCase      :		Dict		,	_UpperCAmelCase      :		int      )  ->    List[Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    int										=      self.num_labels
								_lowerCAmelCase    :    Any										=      DPTForDepthEstimation(_SCREAMING_SNAKE_CASE      )
								model.to(_SCREAMING_SNAKE_CASE      )
								model.eval()
								_lowerCAmelCase    :    List[str]										=      model(_SCREAMING_SNAKE_CASE      )
								self.parent.assertEqual(result.predicted_depth.shape		,	(self.batch_size, self.image_size, self.image_size)      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]		,	_UpperCAmelCase      :		Union[str, Any]		,	_UpperCAmelCase      :		Optional[Any]		,	_UpperCAmelCase      :		Union[str, Any]      )  ->    Optional[int]:





								'''simple docstring'''




								_lowerCAmelCase    :    int										=      self.num_labels
								_lowerCAmelCase    :    Any										=      DPTForSemanticSegmentation(_SCREAMING_SNAKE_CASE      )
								model.to(_SCREAMING_SNAKE_CASE      )
								model.eval()
								_lowerCAmelCase    :    Any										=      model(_SCREAMING_SNAKE_CASE		,	labels=_SCREAMING_SNAKE_CASE      )
								self.parent.assertEqual(
								    result.logits.shape		,	(self.batch_size, self.num_labels, self.image_size, self.image_size)      )



				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]      )  ->    str:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[int]										=      self.prepare_config_and_inputs()
								_lowerCAmelCase					,    _lowerCAmelCase					,    _lowerCAmelCase    :    Optional[Any]										=      config_and_inputs
								_lowerCAmelCase    :    Optional[Any]										=      {"""pixel_values""": pixel_values}
								return config, inputs_dict






@require_torch
class        __snake_case  (_a						,	_a						,	unittest.TestCase		):
				lowerCAmelCase__				=     (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
				lowerCAmelCase__				=     (
				    {
				        "depth-estimation": DPTForDepthEstimation,
				        "feature-extraction": DPTModel,
				        "image-segmentation": DPTForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				lowerCAmelCase__				=     False
				lowerCAmelCase__				=     False
				lowerCAmelCase__				=     False



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]      )  ->    Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    int										=      DPTModelTester(self      )
								_lowerCAmelCase    :    Optional[int]										=      ConfigTester(self		,	config_class=_SCREAMING_SNAKE_CASE		,	has_text_modality=_SCREAMING_SNAKE_CASE		,	hidden_size=37      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]      )  ->    int:





								'''simple docstring'''




								self.config_tester.run_common_tests()



				@unittest.skip(reason="""DPT does not use inputs_embeds"""      )
				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]      )  ->    Any:





								'''simple docstring'''




								pass



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]      )  ->    int:





								'''simple docstring'''




								_lowerCAmelCase					,    _lowerCAmelCase    :    Dict										=      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												_lowerCAmelCase    :    Any										=      model_class(_SCREAMING_SNAKE_CASE      )
												self.assertIsInstance(model.get_input_embeddings()		,	(nn.Module)      )
												_lowerCAmelCase    :    Tuple										=      model.get_output_embeddings()
												self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE		,	nn.Linear      )      )



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





								'''simple docstring'''




								_lowerCAmelCase					,    _lowerCAmelCase    :    List[Any]										=      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												_lowerCAmelCase    :    Any										=      model_class(_SCREAMING_SNAKE_CASE      )
												_lowerCAmelCase    :    Dict										=      inspect.signature(model.forward      )
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												_lowerCAmelCase    :    List[str]										=      [*signature.parameters.keys()]

												_lowerCAmelCase    :    List[Any]										=      ["""pixel_values"""]
												self.assertListEqual(arg_names[:1]		,	_SCREAMING_SNAKE_CASE      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict      )  ->    List[Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    int										=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]      )  ->    Dict:





								'''simple docstring'''




								_lowerCAmelCase    :    Tuple										=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_depth_estimation(*_SCREAMING_SNAKE_CASE      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Tuple      )  ->    int:





								'''simple docstring'''




								_lowerCAmelCase    :    Any										=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE      )



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





								'''simple docstring'''




								for model_class in self.all_model_classes:
												if model_class.__name__ == "DPTForDepthEstimation":
																continue

												_lowerCAmelCase					,    _lowerCAmelCase    :    List[Any]										=      self.model_tester.prepare_config_and_inputs_for_common()
												_lowerCAmelCase    :    str										=      True

												if model_class in get_values(_SCREAMING_SNAKE_CASE      ):
																continue

												_lowerCAmelCase    :    str										=      model_class(_SCREAMING_SNAKE_CASE      )
												model.to(_SCREAMING_SNAKE_CASE      )
												model.train()
												_lowerCAmelCase    :    Optional[Any]										=      self._prepare_for_class(_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE		,	return_labels=_SCREAMING_SNAKE_CASE      )
												_lowerCAmelCase    :    Union[str, Any]										=      model(**_SCREAMING_SNAKE_CASE      ).loss
												loss.backward()



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]      )  ->    Union[str, Any]:





								'''simple docstring'''




								for model_class in self.all_model_classes:
												if model_class.__name__ == "DPTForDepthEstimation":
																continue

												_lowerCAmelCase					,    _lowerCAmelCase    :    Optional[Any]										=      self.model_tester.prepare_config_and_inputs_for_common()
												_lowerCAmelCase    :    Any										=      False
												_lowerCAmelCase    :    int										=      True

												if model_class in get_values(_SCREAMING_SNAKE_CASE      ) or not model_class.supports_gradient_checkpointing:
																continue
												_lowerCAmelCase    :    Union[str, Any]										=      model_class(_SCREAMING_SNAKE_CASE      )
												model.to(_SCREAMING_SNAKE_CASE      )
												model.gradient_checkpointing_enable()
												model.train()
												_lowerCAmelCase    :    List[str]										=      self._prepare_for_class(_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE		,	return_labels=_SCREAMING_SNAKE_CASE      )
												_lowerCAmelCase    :    Tuple										=      model(**_SCREAMING_SNAKE_CASE      ).loss
												loss.backward()



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





								'''simple docstring'''




								_lowerCAmelCase					,    _lowerCAmelCase    :    List[str]										=      self.model_tester.prepare_config_and_inputs_for_common()

								_lowerCAmelCase    :    Optional[Any]										=      _config_zero_init(_SCREAMING_SNAKE_CASE      )
								for model_class in self.all_model_classes:
												_lowerCAmelCase    :    List[str]										=      model_class(config=_SCREAMING_SNAKE_CASE      )
												# Skip the check for the backbone
												_lowerCAmelCase    :    int										=      []
												for name, module in model.named_modules():
																if module.__class__.__name__ == "DPTViTHybridEmbeddings":
																				_lowerCAmelCase    :    Optional[Any]										=      [f"{name}.{key}" for key in module.state_dict().keys()]
																				break

												for name, param in model.named_parameters():
																if param.requires_grad:
																				if name in backbone_params:
																								continue
																				self.assertIn(
																				    ((param.data.mean() * 1E9).round() / 1E9).item()		,	[0.0, 1.0]		,	msg=f"Parameter {name} of model {model_class} seems not properly initialized"		,	)



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





								'''simple docstring'''




								pass



				@slow
				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]      )  ->    Dict:





								'''simple docstring'''




								for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
												_lowerCAmelCase    :    Union[str, Any]										=      DPTModel.from_pretrained(_SCREAMING_SNAKE_CASE      )
												self.assertIsNotNone(_SCREAMING_SNAKE_CASE      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Any      )  ->    int:





								'''simple docstring'''




								_lowerCAmelCase					,    _lowerCAmelCase    :    Union[str, Any]										=      self.model_tester.prepare_config_and_inputs_for_common()
								_lowerCAmelCase    :    Any										=      """add"""
								with self.assertRaises(_SCREAMING_SNAKE_CASE      ):
												_lowerCAmelCase    :    Tuple										=      DPTForDepthEstimation(_SCREAMING_SNAKE_CASE      )






def 							_UpperCAmelCase  ():
				'''simple docstring'''
				_lowerCAmelCase    :    List[Any]										=      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
				return image





@require_torch
@require_vision
@slow
class        __snake_case  (unittest.TestCase		):



				def       SCREAMING_SNAKE_CASE       (      self      :		Any      )  ->    int:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[Any]										=      DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas"""      )
								_lowerCAmelCase    :    Optional[int]										=      DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas"""      ).to(_SCREAMING_SNAKE_CASE      )

								_lowerCAmelCase    :    int										=      prepare_img()
								_lowerCAmelCase    :    Tuple										=      image_processor(images=_SCREAMING_SNAKE_CASE		,	return_tensors="""pt"""      ).to(_SCREAMING_SNAKE_CASE      )

								# forward pass
								with torch.no_grad():
												_lowerCAmelCase    :    Optional[int]										=      model(**_SCREAMING_SNAKE_CASE      )
												_lowerCAmelCase    :    Tuple										=      outputs.predicted_depth

								# verify the predicted depth
								_lowerCAmelCase    :    Dict										=      torch.Size((1, 384, 384)      )
								self.assertEqual(predicted_depth.shape		,	_SCREAMING_SNAKE_CASE      )

								_lowerCAmelCase    :    Any										=      torch.tensor(
								    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]      ).to(_SCREAMING_SNAKE_CASE      )

								self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100		,	_SCREAMING_SNAKE_CASE		,	atol=1E-4      )      )












import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


_lowerCamelCase      :  str      						=						get_logger(__name__)
class        __snake_case  :



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





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[Any]										=      (
								    os.path.join(_UpperCAmelCase		,	config.EXTRACTED_DATASETS_DIR      ) if cache_dir else config.EXTRACTED_DATASETS_PATH
								)
								_lowerCAmelCase    :    Optional[int]										=      Extractor



				def       SCREAMING_SNAKE_CASE       (      self      :		Tuple		,	_UpperCAmelCase      :		str      )  ->    str:





								'''simple docstring'''




								from .file_utils import hash_url_to_filename

								# Path where we extract compressed archives
								# We extract in the cache dir, and get the extracted path name by hashing the original path"
								_lowerCAmelCase    :    List[Any]										=      os.path.abspath(_UpperCAmelCase      )
								return os.path.join(self.extract_dir		,	hash_url_to_filename(_UpperCAmelCase      )      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		bool      )  ->    bool:





								'''simple docstring'''




								return force_extract or (
								    not os.path.isfile(_UpperCAmelCase      ) and not (os.path.isdir(_UpperCAmelCase      ) and os.listdir(_UpperCAmelCase      ))
								)



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		bool = False      )  ->    str:





								'''simple docstring'''




								_lowerCAmelCase    :    str										=      self.extractor.infer_extractor_format(_UpperCAmelCase      )
								if not extractor_format:
												return input_path
								_lowerCAmelCase    :    int										=      self._get_output_path(_UpperCAmelCase      )
								if self._do_extract(_UpperCAmelCase		,	_UpperCAmelCase      ):
												self.extractor.extract(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase      )
								return output_path






class        __snake_case  (_a		):



				@classmethod
				@abstractmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		Tuple		,	_UpperCAmelCase      :		Union[Path, str]		,	**_UpperCAmelCase      :		Optional[int]      )  ->    bool:





								'''simple docstring'''




								...



				@staticmethod
				@abstractmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								...






class        __snake_case  (_a						,	_a		):
				lowerCAmelCase__				=     []



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		int      )  ->    Dict:





								'''simple docstring'''




								with open(_UpperCAmelCase		,	"""rb"""      ) as f:
												return f.read(_UpperCAmelCase      )



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		Any		,	_UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		bytes = b""      )  ->    bool:





								'''simple docstring'''




								if not magic_number:
												_lowerCAmelCase    :    Optional[int]										=      max(len(_UpperCAmelCase      ) for cls_magic_number in cls.magic_numbers      )
												try:
																_lowerCAmelCase    :    Union[str, Any]										=      cls.read_magic_number(_UpperCAmelCase		,	_UpperCAmelCase      )
												except OSError:
																return False
								return any(magic_number.startswith(_UpperCAmelCase      ) for cls_magic_number in cls.magic_numbers      )






class        __snake_case  (_a		):



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		str		,	_UpperCAmelCase      :		Union[Path, str]		,	**_UpperCAmelCase      :		Dict      )  ->    bool:





								'''simple docstring'''




								return tarfile.is_tarfile(_UpperCAmelCase      )



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Optional[int]		,	_UpperCAmelCase      :		Tuple      )  ->    Tuple:





								'''simple docstring'''




								def resolved(_UpperCAmelCase      :		str      ) -> str:
												return os.path.realpath(os.path.abspath(_UpperCAmelCase      )      )

								def badpath(_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		str      ) -> bool:
												# joinpath will ignore base if path is absolute
												return not resolved(os.path.join(_UpperCAmelCase		,	_UpperCAmelCase      )      ).startswith(_UpperCAmelCase      )

								def badlink(_UpperCAmelCase      :		Optional[int]		,	_UpperCAmelCase      :		str      ) -> bool:
												# Links are interpreted relative to the directory containing the link
												_lowerCAmelCase    :    Tuple										=      resolved(os.path.join(_UpperCAmelCase		,	os.path.dirname(info.name      )      )      )
												return badpath(info.linkname		,	base=_UpperCAmelCase      )

								_lowerCAmelCase    :    List[Any]										=      resolved(_UpperCAmelCase      )

								for finfo in members:
												if badpath(finfo.name		,	_UpperCAmelCase      ):
																logger.error(f"Extraction of {finfo.name} is blocked (illegal path)"      )
												elif finfo.issym() and badlink(_UpperCAmelCase		,	_UpperCAmelCase      ):
																logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}"      )
												elif finfo.islnk() and badlink(_UpperCAmelCase		,	_UpperCAmelCase      ):
																logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}"      )
												else:
																yield finfo



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								os.makedirs(_UpperCAmelCase		,	exist_ok=_UpperCAmelCase      )
								_lowerCAmelCase    :    str										=      tarfile.open(_UpperCAmelCase      )
								tar_file.extractall(_UpperCAmelCase		,	members=TarExtractor.safemembers(_UpperCAmelCase		,	_UpperCAmelCase      )      )
								tar_file.close()






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [b"\x1F\x8B"]



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								with gzip.open(_UpperCAmelCase		,	"""rb"""      ) as gzip_file:
												with open(_UpperCAmelCase		,	"""wb"""      ) as extracted_file:
																shutil.copyfileobj(_UpperCAmelCase		,	_UpperCAmelCase      )






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [
				    b"PK\x03\x04",
				    b"PK\x05\x06",  # empty archive
				    b"PK\x07\x08",  # spanned archive
				]



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		Dict		,	_UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		bytes = b""      )  ->    bool:





								'''simple docstring'''




								if super().is_extractable(_UpperCAmelCase		,	magic_number=_UpperCAmelCase      ):
												return True
								try:
												# Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
												# From: https://github.com/python/cpython/pull/5053
												from zipfile import (
												    _CD_SIGNATURE,
												    _ECD_DISK_NUMBER,
												    _ECD_DISK_START,
												    _ECD_ENTRIES_TOTAL,
												    _ECD_OFFSET,
												    _ECD_SIZE,
												    _EndRecData,
												    sizeCentralDir,
												    stringCentralDir,
												    structCentralDir,
												)

												with open(_UpperCAmelCase		,	"""rb"""      ) as fp:
																_lowerCAmelCase    :    Union[str, Any]										=      _EndRecData(_UpperCAmelCase      )
																if endrec:
																				if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
																								return True  # Empty zipfiles are still zipfiles
																				elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
																								fp.seek(endrec[_ECD_OFFSET]      )  # Central directory is on the same disk
																								if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
																												_lowerCAmelCase    :    List[Any]										=      fp.read(_UpperCAmelCase      )  # CD is where we expect it to be
																												if len(_UpperCAmelCase      ) == sizeCentralDir:
																																_lowerCAmelCase    :    int										=      struct.unpack(_UpperCAmelCase		,	_UpperCAmelCase      )  # CD is the right size
																																if centdir[_CD_SIGNATURE] == stringCentralDir:
																																				return True  # First central directory entry  has correct magic number
												return False
								except Exception:  # catch all errors in case future python versions change the zipfile internals
												return False



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								os.makedirs(_UpperCAmelCase		,	exist_ok=_UpperCAmelCase      )
								with zipfile.ZipFile(_UpperCAmelCase		,	"""r"""      ) as zip_file:
												zip_file.extractall(_UpperCAmelCase      )
												zip_file.close()






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [b"\xFD\x37\x7A\x58\x5A\x00"]



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								with lzma.open(_UpperCAmelCase      ) as compressed_file:
												with open(_UpperCAmelCase		,	"""wb"""      ) as extracted_file:
																shutil.copyfileobj(_UpperCAmelCase		,	_UpperCAmelCase      )






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"]  # RAR_ID  # RAR5_ID



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								if not config.RARFILE_AVAILABLE:
												raise ImportError("""Please pip install rarfile"""      )
								import rarfile

								os.makedirs(_UpperCAmelCase		,	exist_ok=_UpperCAmelCase      )
								_lowerCAmelCase    :    str										=      rarfile.RarFile(_UpperCAmelCase      )
								rf.extractall(_UpperCAmelCase      )
								rf.close()






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [b"\x28\xb5\x2F\xFD"]



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								if not config.ZSTANDARD_AVAILABLE:
												raise ImportError("""Please pip install zstandard"""      )
								import zstandard as zstd

								_lowerCAmelCase    :    Any										=      zstd.ZstdDecompressor()
								with open(_UpperCAmelCase		,	"""rb"""      ) as ifh, open(_UpperCAmelCase		,	"""wb"""      ) as ofh:
												dctx.copy_stream(_UpperCAmelCase		,	_UpperCAmelCase      )






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [b"\x42\x5A\x68"]



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								with bza.open(_UpperCAmelCase		,	"""rb"""      ) as compressed_file:
												with open(_UpperCAmelCase		,	"""wb"""      ) as extracted_file:
																shutil.copyfileobj(_UpperCAmelCase		,	_UpperCAmelCase      )






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [b"\x37\x7A\xBC\xAF\x27\x1C"]



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								if not config.PY7ZR_AVAILABLE:
												raise ImportError("""Please pip install py7zr"""      )
								import pyazr

								os.makedirs(_UpperCAmelCase		,	exist_ok=_UpperCAmelCase      )
								with pyazr.SevenZipFile(_UpperCAmelCase		,	"""r"""      ) as archive:
												archive.extractall(_UpperCAmelCase      )






class        __snake_case  (_a		):
				lowerCAmelCase__				=     [b"\x04\x22\x4D\x18"]



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    None:





								'''simple docstring'''




								if not config.LZ4_AVAILABLE:
												raise ImportError("""Please pip install lz4"""      )
								import lza.frame

								with lza.frame.open(_UpperCAmelCase		,	"""rb"""      ) as compressed_file:
												with open(_UpperCAmelCase		,	"""wb"""      ) as extracted_file:
																shutil.copyfileobj(_UpperCAmelCase		,	_UpperCAmelCase      )






class        __snake_case  :
				#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
				lowerCAmelCase__				=     {
				    "tar": TarExtractor,
				    "gzip": GzipExtractor,
				    "zip": ZipExtractor,
				    "xz": XzExtractor,
				    "rar": RarExtractor,
				    "zstd": ZstdExtractor,
				    "bz2": BzipaExtractor,
				    "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
				    "lz4": LzaExtractor,  # <Added version="2.4.0"/>
				}



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		str      )  ->    Optional[int]:





								'''simple docstring'''




								return max(
								    len(_UpperCAmelCase      )
								    for extractor in cls.extractors.values()
								    if issubclass(_UpperCAmelCase		,	_UpperCAmelCase      )
								    for extractor_magic_number in extractor.magic_numbers      )



				@staticmethod
				def       SCREAMING_SNAKE_CASE       (      _UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		int      )  ->    Any:





								'''simple docstring'''




								try:
												return MagicNumberBaseExtractor.read_magic_number(_UpperCAmelCase		,	magic_number_length=_UpperCAmelCase      )
								except OSError:
												return b""



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		int		,	_UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		bool = False      )  ->    bool:





								'''simple docstring'''




								warnings.warn(
								    """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
								    """Use 'infer_extractor_format' instead."""		,	category=_UpperCAmelCase		,	)
								_lowerCAmelCase    :    str										=      cls.infer_extractor_format(_UpperCAmelCase      )
								if extractor_format:
												return True if not return_extractor else (True, cls.extractors[extractor_format])
								return False if not return_extractor else (False, None)



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		Optional[Any]		,	_UpperCAmelCase      :		Union[Path, str]      )  ->    str:  # <Added version="2.4.0"/>





								'''simple docstring'''




								_lowerCAmelCase    :    str										=      cls._get_magic_number_max_length()
								_lowerCAmelCase    :    Dict										=      cls._read_magic_number(_UpperCAmelCase		,	_UpperCAmelCase      )
								for extractor_format, extractor in cls.extractors.items():
												if extractor.is_extractable(_UpperCAmelCase		,	magic_number=_UpperCAmelCase      ):
																return extractor_format



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		Optional[Any]		,	_UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Union[Path, str]		,	_UpperCAmelCase      :		Optional[str] = None		,	_UpperCAmelCase      :		Optional[BaseExtractor] = "deprecated"		,	)  ->    None:





								'''simple docstring'''




								os.makedirs(os.path.dirname(_UpperCAmelCase      )		,	exist_ok=_UpperCAmelCase      )
								# Prevent parallel extractions
								_lowerCAmelCase    :    Tuple										=      str(Path(_UpperCAmelCase      ).with_suffix(""".lock"""      )      )
								with FileLock(_UpperCAmelCase      ):
												shutil.rmtree(_UpperCAmelCase		,	ignore_errors=_UpperCAmelCase      )
												if extractor_format or extractor != "deprecated":
																if extractor != "deprecated" or not isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ):  # passed as positional arg
																				warnings.warn(
																				    """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
																				    """Use 'extractor_format' instead."""		,	category=_UpperCAmelCase		,	)
																				_lowerCAmelCase    :    List[str]										=      extractor if extractor != """deprecated""" else extractor_format
																else:
																				_lowerCAmelCase    :    List[Any]										=      cls.extractors[extractor_format]
																return extractor.extract(_UpperCAmelCase		,	_UpperCAmelCase      )
												else:
																warnings.warn(
																    """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """
																    """exception in 3.0.0."""		,	category=_UpperCAmelCase		,	)
																for extractor in cls.extractors.values():
																				if extractor.is_extractable(_UpperCAmelCase      ):
																								return extractor.extract(_UpperCAmelCase		,	_UpperCAmelCase      )

