'''simple docstring'''







from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


UpperCamelCase_      	=	logging.get_logger(__name__)

# General docstring
UpperCamelCase_      	=	'RegNetConfig'

# Base docstring
UpperCamelCase_      	=	'facebook/regnet-y-040'
UpperCamelCase_      	=	[1, 10_88, 7, 7]

# Image classification docstring
UpperCamelCase_      	=	'facebook/regnet-y-040'
UpperCamelCase_      	=	'tabby, tabby cat'

UpperCamelCase_      	=	[
    'facebook/regnet-y-040',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       int							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int = 3							,							UpperCamelCase_ :       int = 1							,							UpperCamelCase_ :       int = 1							,							UpperCamelCase_ :       Optional[str] = "relu"							,							)     ->				Dict:
													super().__init__()
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = nn.Convad(
													    _SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=_SCREAMING_SNAKE_CASE							,							stride=_SCREAMING_SNAKE_CASE							,							padding=kernel_size // 2							,							groups=_SCREAMING_SNAKE_CASE							,							bias=_SCREAMING_SNAKE_CASE							,							)
													SCREAMING_SNAKE_CASE__     :int						    = nn.BatchNormad(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = ACTaFN[activation] if activation is not None else nn.Identity()




						def      __lowerCamelCase       (    self :       str							,							UpperCamelCase_ :       Any      )     ->				List[Any]:
													SCREAMING_SNAKE_CASE__     :List[str]						    = self.convolution(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Dict						    = self.normalization(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Any						    = self.activation(_SCREAMING_SNAKE_CASE      )
													return hidden_state




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       List[Any]							,							UpperCamelCase_ :       RegNetConfig      )     ->				Any:
													super().__init__()
													SCREAMING_SNAKE_CASE__     :Dict						    = RegNetConvLayer(
													    config.num_channels							,							config.embedding_size							,							kernel_size=3							,							stride=2							,							activation=config.hidden_act      )
													SCREAMING_SNAKE_CASE__     :List[Any]						    = config.num_channels




						def      __lowerCamelCase       (    self :       int							,							UpperCamelCase_ :       Tuple      )     ->				Tuple:
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = pixel_values.shape[1]
													if num_channels != self.num_channels:
																				raise ValueError(
																				    'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'      )
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = self.embedder(_SCREAMING_SNAKE_CASE      )
													return hidden_state




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       Dict							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int = 2      )     ->				int:
													super().__init__()
													SCREAMING_SNAKE_CASE__     :List[Any]						    = nn.Convad(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=1							,							stride=_SCREAMING_SNAKE_CASE							,							bias=_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = nn.BatchNormad(_SCREAMING_SNAKE_CASE      )




						def      __lowerCamelCase       (    self :       str							,							UpperCamelCase_ :       Tensor      )     ->				Tensor:
													SCREAMING_SNAKE_CASE__     :int						    = self.convolution(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = self.normalization(_SCREAMING_SNAKE_CASE      )
													return hidden_state




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       str							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int      )     ->				Union[str, Any]:
													super().__init__()

													SCREAMING_SNAKE_CASE__     :Dict						    = nn.AdaptiveAvgPoolad((1, 1)      )
													SCREAMING_SNAKE_CASE__     :Any						    = nn.Sequential(
													    nn.Convad(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=1      )							,							nn.ReLU()							,							nn.Convad(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=1      )							,							nn.Sigmoid()							,							)




						def      __lowerCamelCase       (    self :       Optional[int]							,							UpperCamelCase_ :       str      )     ->				Optional[Any]:
													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.pooler(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = self.attention(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Any						    = hidden_state * attention
													return hidden_state




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       List[Any]							,							UpperCamelCase_ :       RegNetConfig							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int = 1      )     ->				int:
													super().__init__()
													SCREAMING_SNAKE_CASE__     :Tuple						    = in_channels != out_channels or stride != 1
													SCREAMING_SNAKE_CASE__     :int						    = max(1							,							out_channels // config.groups_width      )
													SCREAMING_SNAKE_CASE__     :Tuple						    = (
													    RegNetShortCut(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							stride=_SCREAMING_SNAKE_CASE      ) if should_apply_shortcut else nn.Identity()
													)
													SCREAMING_SNAKE_CASE__     :Dict						    = nn.Sequential(
													    RegNetConvLayer(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=1							,							activation=config.hidden_act      )							,							RegNetConvLayer(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							stride=_SCREAMING_SNAKE_CASE							,							groups=_SCREAMING_SNAKE_CASE							,							activation=config.hidden_act      )							,							RegNetConvLayer(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=1							,							activation=_SCREAMING_SNAKE_CASE      )							,							)
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = ACTaFN[config.hidden_act]




						def      __lowerCamelCase       (    self :       Dict							,							UpperCamelCase_ :       Union[str, Any]      )     ->				Dict:
													SCREAMING_SNAKE_CASE__     :Dict						    = hidden_state
													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.layer(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.shortcut(_SCREAMING_SNAKE_CASE      )
													hidden_state += residual
													SCREAMING_SNAKE_CASE__     :Any						    = self.activation(_SCREAMING_SNAKE_CASE      )
													return hidden_state




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       Tuple							,							UpperCamelCase_ :       RegNetConfig							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int = 1      )     ->				str:
													super().__init__()
													SCREAMING_SNAKE_CASE__     :Dict						    = in_channels != out_channels or stride != 1
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = max(1							,							out_channels // config.groups_width      )
													SCREAMING_SNAKE_CASE__     :Tuple						    = (
													    RegNetShortCut(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							stride=_SCREAMING_SNAKE_CASE      ) if should_apply_shortcut else nn.Identity()
													)
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = nn.Sequential(
													    RegNetConvLayer(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=1							,							activation=config.hidden_act      )							,							RegNetConvLayer(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							stride=_SCREAMING_SNAKE_CASE							,							groups=_SCREAMING_SNAKE_CASE							,							activation=config.hidden_act      )							,							RegNetSELayer(_SCREAMING_SNAKE_CASE							,							reduced_channels=int(round(in_channels / 4      )      )      )							,							RegNetConvLayer(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							kernel_size=1							,							activation=_SCREAMING_SNAKE_CASE      )							,							)
													SCREAMING_SNAKE_CASE__     :int						    = ACTaFN[config.hidden_act]




						def      __lowerCamelCase       (    self :       str							,							UpperCamelCase_ :       Any      )     ->				List[str]:
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = hidden_state
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = self.layer(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :List[str]						    = self.shortcut(_SCREAMING_SNAKE_CASE      )
													hidden_state += residual
													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.activation(_SCREAMING_SNAKE_CASE      )
													return hidden_state




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       Tuple							,							UpperCamelCase_ :       RegNetConfig							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       int = 2							,							UpperCamelCase_ :       int = 2							,							)     ->				Optional[int]:
													super().__init__()

													SCREAMING_SNAKE_CASE__     :Optional[int]						    = RegNetXLayer if config.layer_type == 'x' else RegNetYLayer

													SCREAMING_SNAKE_CASE__     :int						    = nn.Sequential(
													    # downsampling is done in the first layer with stride of 2
													    layer(
													        _SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							stride=_SCREAMING_SNAKE_CASE							,							)							,							*[layer(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE      ) for _ in range(depth - 1      )]							,							)




						def      __lowerCamelCase       (    self :       Optional[int]							,							UpperCamelCase_ :       Union[str, Any]      )     ->				Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.layers(_SCREAMING_SNAKE_CASE      )
													return hidden_state




class _SCREAMING_SNAKE_CASE(							nn.Module					):




						def __init__(    self :       List[str]							,							UpperCamelCase_ :       RegNetConfig      )     ->				Union[str, Any]:
													super().__init__()
													SCREAMING_SNAKE_CASE__     :Tuple						    = nn.ModuleList([]      )
													# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
													self.stages.append(
													    RegNetStage(
													        _SCREAMING_SNAKE_CASE							,							config.embedding_size							,							config.hidden_sizes[0]							,							stride=2 if config.downsample_in_first_stage else 1							,							depth=config.depths[0]							,							)      )
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = zip(config.hidden_sizes							,							config.hidden_sizes[1:]      )
													for (in_channels, out_channels), depth in zip(_SCREAMING_SNAKE_CASE							,							config.depths[1:]      ):
																				self.stages.append(RegNetStage(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							depth=_SCREAMING_SNAKE_CASE      )      )




						def      __lowerCamelCase       (    self :       Union[str, Any]							,							UpperCamelCase_ :       Tensor							,							UpperCamelCase_ :       bool = False							,							UpperCamelCase_ :       bool = True      )     ->				BaseModelOutputWithNoAttention:
													SCREAMING_SNAKE_CASE__     :List[Any]						    = () if output_hidden_states else None

													for stage_module in self.stages:
																				if output_hidden_states:
																											SCREAMING_SNAKE_CASE__     :Any						    = hidden_states + (hidden_state,)

																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = stage_module(_SCREAMING_SNAKE_CASE      )

													if output_hidden_states:
																				SCREAMING_SNAKE_CASE__     :List[str]						    = hidden_states + (hidden_state,)

													if not return_dict:
																				return tuple(v for v in [hidden_state, hidden_states] if v is not None      )

													return BaseModelOutputWithNoAttention(last_hidden_state=_SCREAMING_SNAKE_CASE							,							hidden_states=_SCREAMING_SNAKE_CASE      )




class _SCREAMING_SNAKE_CASE(							_lowerCamelCase					):
						A_			:							Optional[Any]     		= RegNetConfig
						A_			:							str     		= '''regnet'''
						A_			:							Dict     		= '''pixel_values'''
						A_			:							Tuple     		= True




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


													if isinstance(_SCREAMING_SNAKE_CASE							,							nn.Convad      ):
																				nn.init.kaiming_normal_(module.weight							,							mode='fan_out'							,							nonlinearity='relu'      )
													elif isinstance(_SCREAMING_SNAKE_CASE							,							(nn.BatchNormad, nn.GroupNorm)      ):
																				nn.init.constant_(module.weight							,							1      )
																				nn.init.constant_(module.bias							,							0      )




						def      __lowerCamelCase       (    self :       Tuple							,							UpperCamelCase_ :       str							,							UpperCamelCase_ :       Any=False      )     ->				Any:


													if isinstance(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE      ):
																				SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = value
UpperCamelCase_      	=	R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

UpperCamelCase_      	=	R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n'




@add_start_docstrings(
    'The bare RegNet model outputting raw features without any specific head on top.'						,						_lowerCamelCase						,						)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class _SCREAMING_SNAKE_CASE(							_lowerCamelCase					):




						def __init__(    self :       Union[str, Any]							,							UpperCamelCase_ :       str      )     ->				List[str]:
													super().__init__(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :List[str]						    = config
													SCREAMING_SNAKE_CASE__     :Tuple						    = RegNetEmbeddings(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = RegNetEncoder(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :str						    = nn.AdaptiveAvgPoolad((1, 1)      )
													# Initialize weights and apply final processing
													self.post_init()




						@add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE      )
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC							,							output_type=_SCREAMING_SNAKE_CASE							,							config_class=_CONFIG_FOR_DOC							,							modality='vision'							,							expected_output=_EXPECTED_OUTPUT_SHAPE							,							)
						def      __lowerCamelCase       (    self :       List[Any]							,							UpperCamelCase_ :       Tensor							,							UpperCamelCase_ :       Optional[bool] = None							,							UpperCamelCase_ :       Optional[bool] = None      )     ->				BaseModelOutputWithPoolingAndNoAttention:
													SCREAMING_SNAKE_CASE__     :List[Any]						    = (
													    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
													)
													SCREAMING_SNAKE_CASE__     :Dict						    = return_dict if return_dict is not None else self.config.use_return_dict

													SCREAMING_SNAKE_CASE__     :Dict						    = self.embedder(_SCREAMING_SNAKE_CASE      )

													SCREAMING_SNAKE_CASE__     :str						    = self.encoder(
													    _SCREAMING_SNAKE_CASE							,							output_hidden_states=_SCREAMING_SNAKE_CASE							,							return_dict=_SCREAMING_SNAKE_CASE      )

													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = encoder_outputs[0]

													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.pooler(_SCREAMING_SNAKE_CASE      )

													if not return_dict:
																				return (last_hidden_state, pooled_output) + encoder_outputs[1:]

													return BaseModelOutputWithPoolingAndNoAttention(
													    last_hidden_state=_SCREAMING_SNAKE_CASE							,							pooler_output=_SCREAMING_SNAKE_CASE							,							hidden_states=encoder_outputs.hidden_states							,							)




@add_start_docstrings(
    '\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '						,						_lowerCamelCase						,						)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class _SCREAMING_SNAKE_CASE(							_lowerCamelCase					):




						def __init__(    self :       Optional[int]							,							UpperCamelCase_ :       Any      )     ->				Optional[int]:
													super().__init__(_SCREAMING_SNAKE_CASE      )
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = config.num_labels
													SCREAMING_SNAKE_CASE__     :Dict						    = RegNetModel(_SCREAMING_SNAKE_CASE      )
													# classification head
													SCREAMING_SNAKE_CASE__     :Any						    = nn.Sequential(
													    nn.Flatten()							,							nn.Linear(config.hidden_sizes[-1]							,							config.num_labels      ) if config.num_labels > 0 else nn.Identity()							,							)
													# initialize weights and apply final processing
													self.post_init()




						@add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE      )
						@add_code_sample_docstrings(
						    checkpoint=_IMAGE_CLASS_CHECKPOINT							,							output_type=_SCREAMING_SNAKE_CASE							,							config_class=_CONFIG_FOR_DOC							,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT							,							)
						def      __lowerCamelCase       (    self :       List[Any]							,							UpperCamelCase_ :       Optional[torch.FloatTensor] = None							,							UpperCamelCase_ :       Optional[torch.LongTensor] = None							,							UpperCamelCase_ :       Optional[bool] = None							,							UpperCamelCase_ :       Optional[bool] = None							,							)     ->				ImageClassifierOutputWithNoAttention:
													SCREAMING_SNAKE_CASE__     :str						    = return_dict if return_dict is not None else self.config.use_return_dict

													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.regnet(_SCREAMING_SNAKE_CASE							,							output_hidden_states=_SCREAMING_SNAKE_CASE							,							return_dict=_SCREAMING_SNAKE_CASE      )

													SCREAMING_SNAKE_CASE__     :int						    = outputs.pooler_output if return_dict else outputs[1]

													SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.classifier(_SCREAMING_SNAKE_CASE      )

													SCREAMING_SNAKE_CASE__     :Optional[int]						    = None

													if labels is not None:
																				if self.config.problem_type is None:
																											if self.num_labels == 1:
																																		SCREAMING_SNAKE_CASE__     :List[Any]						    = 'regression'
																											elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																																		SCREAMING_SNAKE_CASE__     :str						    = 'single_label_classification'
																											else:
																																		SCREAMING_SNAKE_CASE__     :Optional[int]						    = 'multi_label_classification'
																				if self.config.problem_type == "regression":
																											SCREAMING_SNAKE_CASE__     :List[str]						    = MSELoss()
																											if self.num_labels == 1:
																																		SCREAMING_SNAKE_CASE__     :List[Any]						    = loss_fct(logits.squeeze()							,							labels.squeeze()      )
																											else:
																																		SCREAMING_SNAKE_CASE__     :Dict						    = loss_fct(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE      )
																				elif self.config.problem_type == "single_label_classification":
																											SCREAMING_SNAKE_CASE__     :Optional[int]						    = CrossEntropyLoss()
																											SCREAMING_SNAKE_CASE__     :Dict						    = loss_fct(logits.view(-1							,							self.num_labels      )							,							labels.view(-1      )      )
																				elif self.config.problem_type == "multi_label_classification":
																											SCREAMING_SNAKE_CASE__     :List[str]						    = BCEWithLogitsLoss()
																											SCREAMING_SNAKE_CASE__     :List[Any]						    = loss_fct(_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE      )

													if not return_dict:
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = (logits,) + outputs[2:]
																				return (loss,) + output if loss is not None else output

													return ImageClassifierOutputWithNoAttention(loss=_SCREAMING_SNAKE_CASE							,							logits=_SCREAMING_SNAKE_CASE							,							hidden_states=outputs.hidden_states      )











"""simple docstring"""

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


A_						:    Optional[int]				=      get_logger(__name__)
class     lowerCAmelCase__						:


	'''simple docstring'''







	def __init__(      self				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       Optional[str] = None    )						->	str:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							List[str]							=     (
					    os.path.join(_SCREAMING_SNAKE_CASE     ,       config.EXTRACTED_DATASETS_DIR    ) if cache_dir else config.EXTRACTED_DATASETS_PATH
					)
					SCREAMING_SNAKE_CASE						:							Dict							=     Extractor





	def 			_lowerCAmelCase     (      self				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       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"
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     os.path.abspath(_SCREAMING_SNAKE_CASE    )
					return os.path.join(self.extract_dir     ,       hash_url_to_filename(_SCREAMING_SNAKE_CASE    )    )





	def 			_lowerCAmelCase     (      self				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       str     ,       _SCREAMING_SNAKE_CASE				:       bool    )						->	bool:





					"""simple docstring"""


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







	def 			_lowerCAmelCase     (      self				:       str     ,       _SCREAMING_SNAKE_CASE				:       str     ,       _SCREAMING_SNAKE_CASE				:       bool = False    )						->	str:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							int							=     self.extractor.infer_extractor_format(_SCREAMING_SNAKE_CASE    )
					if not extractor_format:
									return input_path
					SCREAMING_SNAKE_CASE						:							List[str]							=     self._get_output_path(_SCREAMING_SNAKE_CASE    )
					if self._do_extract(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    ):
									self.extractor.extract(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
					return output_path




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	@classmethod
	@abstractmethod
	def 			_lowerCAmelCase     (      cls				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       **_SCREAMING_SNAKE_CASE				:       Tuple    )						->	bool:





					"""simple docstring"""


					...







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





					"""simple docstring"""


					...




class     lowerCAmelCase__						(	_lowerCamelCase							,							_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		List[bytes]  						= []





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





					"""simple docstring"""


					with open(_SCREAMING_SNAKE_CASE     ,       'rb'    ) as f:
									return f.read(_SCREAMING_SNAKE_CASE    )







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





					"""simple docstring"""


					if not magic_number:
									SCREAMING_SNAKE_CASE						:							Any							=     max(len(_SCREAMING_SNAKE_CASE    ) for cls_magic_number in cls.magic_numbers    )
									try:
													SCREAMING_SNAKE_CASE						:							int							=     cls.read_magic_number(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
									except OSError:
													return False
					return any(magic_number.startswith(_SCREAMING_SNAKE_CASE    ) for cls_magic_number in cls.magic_numbers    )




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	@classmethod
	def 			_lowerCAmelCase     (      cls				:       List[str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       **_SCREAMING_SNAKE_CASE				:       List[Any]    )						->	bool:





					"""simple docstring"""


					return tarfile.is_tarfile(_SCREAMING_SNAKE_CASE    )





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Dict    )						->	Dict:





					"""simple docstring"""


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

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

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

					SCREAMING_SNAKE_CASE						:							str							=     resolved(_SCREAMING_SNAKE_CASE    )

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







	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


					os.makedirs(_SCREAMING_SNAKE_CASE     ,       exist_ok=_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     tarfile.open(_SCREAMING_SNAKE_CASE    )
					tar_file.extractall(_SCREAMING_SNAKE_CASE     ,       members=TarExtractor.safemembers(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )    )
					tar_file.close()




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		Optional[int]  						= [B'''\x1F\x8B''']





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


					with gzip.open(_SCREAMING_SNAKE_CASE     ,       'rb'    ) as gzip_file:
									with open(_SCREAMING_SNAKE_CASE     ,       'wb'    ) as extracted_file:
													shutil.copyfileobj(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		Optional[Any]  						= [
	    B'''PK\x03\x04''',
	    B'''PK\x05\x06''',  # empty archive
	    B'''PK\x07\x08''',  # spanned archive
	]





	@classmethod
	def 			_lowerCAmelCase     (      cls				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       bytes = b""    )						->	bool:





					"""simple docstring"""


					if super().is_extractable(_SCREAMING_SNAKE_CASE     ,       magic_number=_SCREAMING_SNAKE_CASE    ):
									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(_SCREAMING_SNAKE_CASE     ,       'rb'    ) as fp:
													SCREAMING_SNAKE_CASE						:							List[str]							=     _EndRecData(_SCREAMING_SNAKE_CASE    )
													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:
																									SCREAMING_SNAKE_CASE						:							str							=     fp.read(_SCREAMING_SNAKE_CASE    )  # CD is where we expect it to be
																									if len(_SCREAMING_SNAKE_CASE    ) == sizeCentralDir:
																													SCREAMING_SNAKE_CASE						:							Optional[Any]							=     struct.unpack(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )  # 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 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


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




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		Union[str, Any]  						= [B'''\xFD\x37\x7A\x58\x5A\x00''']





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


					with lzma.open(_SCREAMING_SNAKE_CASE    ) as compressed_file:
									with open(_SCREAMING_SNAKE_CASE     ,       'wb'    ) as extracted_file:
													shutil.copyfileobj(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		Dict  						= [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


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

					os.makedirs(_SCREAMING_SNAKE_CASE     ,       exist_ok=_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							str							=     rarfile.RarFile(_SCREAMING_SNAKE_CASE    )
					rf.extractall(_SCREAMING_SNAKE_CASE    )
					rf.close()




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		Optional[int]  						= [B'''\x28\xb5\x2F\xFD''']





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


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

					SCREAMING_SNAKE_CASE						:							Any							=     zstd.ZstdDecompressor()
					with open(_SCREAMING_SNAKE_CASE     ,       'rb'    ) as ifh, open(_SCREAMING_SNAKE_CASE     ,       'wb'    ) as ofh:
									dctx.copy_stream(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		Union[str, Any]  						= [B'''\x42\x5A\x68''']





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


					with bza.open(_SCREAMING_SNAKE_CASE     ,       'rb'    ) as compressed_file:
									with open(_SCREAMING_SNAKE_CASE     ,       'wb'    ) as extracted_file:
													shutil.copyfileobj(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		str  						= [B'''\x37\x7A\xBC\xAF\x27\x1C''']





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


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

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




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		List[str]  						= [B'''\x04\x22\x4D\x18''']





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	None:





					"""simple docstring"""


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

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




class     lowerCAmelCase__						:


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		Dict[str, Type[BaseExtractor]]  						= {
	    "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 			_lowerCAmelCase     (      cls				:       List[str]    )						->	Tuple:





					"""simple docstring"""


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





	@staticmethod
	def 			_lowerCAmelCase     (      _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       int    )						->	List[str]:





					"""simple docstring"""


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





	@classmethod
	def 			_lowerCAmelCase     (      cls				:       Any     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       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=_SCREAMING_SNAKE_CASE     ,       )
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     cls.infer_extractor_format(_SCREAMING_SNAKE_CASE    )
					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 			_lowerCAmelCase     (      cls				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]    )						->	str:  # <Added version="2.4.0"/>





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							List[Any]							=     cls._get_magic_number_max_length()
					SCREAMING_SNAKE_CASE						:							str							=     cls._read_magic_number(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
					for extractor_format, extractor in cls.extractors.items():
									if extractor.is_extractable(_SCREAMING_SNAKE_CASE     ,       magic_number=_SCREAMING_SNAKE_CASE    ):
													return extractor_format







	@classmethod
	def 			_lowerCAmelCase     (      cls				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Union[Path, str]     ,       _SCREAMING_SNAKE_CASE				:       Optional[str] = None     ,       _SCREAMING_SNAKE_CASE				:       Optional[BaseExtractor] = "deprecated"     ,       )						->	None:





					"""simple docstring"""


					os.makedirs(os.path.dirname(_SCREAMING_SNAKE_CASE    )     ,       exist_ok=_SCREAMING_SNAKE_CASE    )
					# Prevent parallel extractions
					SCREAMING_SNAKE_CASE						:							List[str]							=     str(Path(_SCREAMING_SNAKE_CASE    ).with_suffix('.lock'    )    )
					with FileLock(_SCREAMING_SNAKE_CASE    ):
									shutil.rmtree(_SCREAMING_SNAKE_CASE     ,       ignore_errors=_SCREAMING_SNAKE_CASE    )
									if extractor_format or extractor != "deprecated":
													if extractor != "deprecated" or not isinstance(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    ):  # 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=_SCREAMING_SNAKE_CASE     ,       )
																	SCREAMING_SNAKE_CASE						:							int							=     extractor if extractor != 'deprecated' else extractor_format
													else:
																	SCREAMING_SNAKE_CASE						:							int							=     cls.extractors[extractor_format]
													return extractor.extract(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
									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=_SCREAMING_SNAKE_CASE     ,       )
													for extractor in cls.extractors.values():
																	if extractor.is_extractable(_SCREAMING_SNAKE_CASE    ):
																					return extractor.extract(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )





