




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


lowercase__  		=		get_logger(__name__)






class lowerCAmelCase__			:






			'''simple docstring'''



			def __init__(						self						,   lowercase = None						):
							_lowerCamelCase  :    Optional[Any]					=					(
							    os.path.join(lowercase						,   config.EXTRACTED_DATASETS_DIR						) if cache_dir else config.EXTRACTED_DATASETS_PATH
							)
							_lowerCamelCase  :    str					=					Extractor
			def       A_					(						self						,   lowercase						):
							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  :    Any					=					os.path.abspath(lowercase						)
							return os.path.join(self.extract_dir						,   hash_url_to_filename(lowercase						)						)
			def       A_					(						self						,   lowercase						,   lowercase						):
							return force_extract or (
							    not os.path.isfile(lowercase						) and not (os.path.isdir(lowercase						) and os.listdir(lowercase						))
							)






			def       A_					(						self						,   lowercase						,   lowercase = False						):
							_lowerCamelCase  :    Optional[Any]					=					self.extractor.infer_extractor_format(lowercase						)
							if not extractor_format:
											return input_path
							_lowerCamelCase  :    List[str]					=					self._get_output_path(lowercase						)
							if self._do_extract(lowercase						,   lowercase						):
											self.extractor.extract(lowercase						,   lowercase						,   lowercase						)
							return output_path






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			@classmethod
			@abstractmethod
			def       A_					(						cls						,   lowercase						,   **lowercase						):
							...






			@staticmethod
			@abstractmethod
			def       A_					(						lowercase						,   lowercase						):
							...






class lowerCAmelCase__			(  lowercase,			lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    []
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							with open(lowercase						,   'rb'						) as f:
											return f.read(lowercase						)






			@classmethod
			def       A_					(						cls						,   lowercase						,   lowercase = b""						):
							if not magic_number:
											_lowerCamelCase  :    List[str]					=					max(len(lowercase						) for cls_magic_number in cls.magic_numbers						)
											try:
															_lowerCamelCase  :    List[Any]					=					cls.read_magic_number(lowercase						,   lowercase						)
											except OSError:
															return False
							return any(magic_number.startswith(lowercase						) for cls_magic_number in cls.magic_numbers						)






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			@classmethod
			def       A_					(						cls						,   lowercase						,   **lowercase						):
							return tarfile.is_tarfile(lowercase						)
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):

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

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

							def badlink(lowercase						,   lowercase						) -> bool:
											# Links are interpreted relative to the directory containing the link
											_lowerCamelCase  :    Tuple					=					resolved(os.path.join(lowercase						,   os.path.dirname(info.name						)						)						)
											return badpath(info.linkname						,   base=lowercase						)

							_lowerCamelCase  :    str					=					resolved(lowercase						)

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






			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							os.makedirs(lowercase						,   exist_ok=lowercase						)
							_lowerCamelCase  :    str					=					tarfile.open(lowercase						)
							tar_file.extractall(lowercase						,   members=TarExtractor.safemembers(lowercase						,   lowercase						)						)
							tar_file.close()






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [B"""\x1F\x8B"""]
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							with gzip.open(lowercase						,   'rb'						) as gzip_file:
											with open(lowercase						,   'wb'						) as extracted_file:
															shutil.copyfileobj(lowercase						,   lowercase						)






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [
			    B"""PK\x03\x04""",
			    B"""PK\x05\x06""",  # empty archive
			    B"""PK\x07\x08""",  # spanned archive
			]
			@classmethod
			def       A_					(						cls						,   lowercase						,   lowercase = b""						):
							if super().is_extractable(lowercase						,   magic_number=lowercase						):
											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(lowercase						,   'rb'						) as fp:
															_lowerCamelCase  :    List[Any]					=					_EndRecData(lowercase						)
															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  :    Union[str, Any]					=					fp.read(lowercase						)  # CD is where we expect it to be
																											if len(lowercase						) == sizeCentralDir:
																															_lowerCamelCase  :    Dict					=					struct.unpack(lowercase						,   lowercase						)  # 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       A_					(						lowercase						,   lowercase						):
							os.makedirs(lowercase						,   exist_ok=lowercase						)
							with zipfile.ZipFile(lowercase						,   'r'						) as zip_file:
											zip_file.extractall(lowercase						)
											zip_file.close()






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [B"""\xFD\x37\x7A\x58\x5A\x00"""]
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							with lzma.open(lowercase						) as compressed_file:
											with open(lowercase						,   'wb'						) as extracted_file:
															shutil.copyfileobj(lowercase						,   lowercase						)






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							if not config.RARFILE_AVAILABLE:
											raise ImportError('Please pip install rarfile'						)
							import rarfile

							os.makedirs(lowercase						,   exist_ok=lowercase						)
							_lowerCamelCase  :    int					=					rarfile.RarFile(lowercase						)
							rf.extractall(lowercase						)
							rf.close()






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [B"""\x28\xb5\x2F\xFD"""]
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							if not config.ZSTANDARD_AVAILABLE:
											raise ImportError('Please pip install zstandard'						)
							import zstandard as zstd

							_lowerCamelCase  :    List[Any]					=					zstd.ZstdDecompressor()
							with open(lowercase						,   'rb'						) as ifh, open(lowercase						,   'wb'						) as ofh:
											dctx.copy_stream(lowercase						,   lowercase						)






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [B"""\x42\x5A\x68"""]
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							with bza.open(lowercase						,   'rb'						) as compressed_file:
											with open(lowercase						,   'wb'						) as extracted_file:
															shutil.copyfileobj(lowercase						,   lowercase						)






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [B"""\x37\x7A\xBC\xAF\x27\x1C"""]
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							if not config.PY7ZR_AVAILABLE:
											raise ImportError('Please pip install py7zr'						)
							import pyazr

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






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    [B"""\x04\x22\x4D\x18"""]
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							if not config.LZ4_AVAILABLE:
											raise ImportError('Please pip install lz4'						)
							import lza.frame

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






class lowerCAmelCase__			:






			'''simple docstring'''



			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       A_					(						cls						):
							return max(
							    len(lowercase						)
							    for extractor in cls.extractors.values()
							    if issubclass(lowercase						,   lowercase						)
							    for extractor_magic_number in extractor.magic_numbers						)
			@staticmethod
			def       A_					(						lowercase						,   lowercase						):
							try:
											return MagicNumberBaseExtractor.read_magic_number(lowercase						,   magic_number_length=lowercase						)
							except OSError:
											return b""
			@classmethod
			def       A_					(						cls						,   lowercase						,   lowercase = False						):
							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=lowercase						,   )
							_lowerCamelCase  :    List[str]					=					cls.infer_extractor_format(lowercase						)
							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       A_					(						cls						,   lowercase						):  # <Added version="2.4.0"/>
							_lowerCamelCase  :    Tuple					=					cls._get_magic_number_max_length()
							_lowerCamelCase  :    List[str]					=					cls._read_magic_number(lowercase						,   lowercase						)
							for extractor_format, extractor in cls.extractors.items():
											if extractor.is_extractable(lowercase						,   magic_number=lowercase						):
															return extractor_format






			@classmethod
			def       A_					(						cls						,   lowercase						,   lowercase						,   lowercase = None						,   lowercase = "deprecated"						,   ):
							os.makedirs(os.path.dirname(lowercase						)						,   exist_ok=lowercase						)
							# Prevent parallel extractions
							_lowerCamelCase  :    str					=					str(Path(lowercase						).with_suffix('.lock'						)						)
							with FileLock(lowercase						):
											shutil.rmtree(lowercase						,   ignore_errors=lowercase						)
											if extractor_format or extractor != "deprecated":
															if extractor != "deprecated" or not isinstance(lowercase						,   lowercase						):  # 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=lowercase						,   )
																			_lowerCamelCase  :    Tuple					=					extractor if extractor != 'deprecated' else extractor_format
															else:
																			_lowerCamelCase  :    Optional[Any]					=					cls.extractors[extractor_format]
															return extractor.extract(lowercase						,   lowercase						)
											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=lowercase						,   )
															for extractor in cls.extractors.values():
																			if extractor.is_extractable(lowercase						):
																							return extractor.extract(lowercase						,   lowercase						)





"""simple docstring"""






from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


lowercase__  		=		logging.get_logger(__name__)

lowercase__  		=		{
    """google/umt5-small""": """https://huggingface.co/google/umt5-small/resolve/main/config.json""",
    # See all umt5 models at https://huggingface.co/models?filter=umt5
}






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    """umt5"""
			lowerCamelCase__   =    ["""past_key_values"""]
			def __init__(						self						,   lowercase=250112						,   lowercase=512						,   lowercase=64						,   lowercase=1024						,   lowercase=8						,   lowercase=None						,   lowercase=6						,   lowercase=32						,   lowercase=128						,   lowercase=0.1						,   lowercase=1E-6						,   lowercase=1.0						,   lowercase="gated-gelu"						,   lowercase=True						,   lowercase=True						,   lowercase="T5Tokenizer"						,   lowercase=True						,   lowercase=0						,   lowercase=1						,   lowercase=0						,   **lowercase						,   ):
							super().__init__(
							    is_encoder_decoder=lowercase						,   tokenizer_class=lowercase						,   tie_word_embeddings=lowercase						,   pad_token_id=lowercase						,   eos_token_id=lowercase						,   decoder_start_token_id=lowercase						,   **lowercase						,   )
							_lowerCamelCase  :    Union[str, Any]					=					vocab_size
							_lowerCamelCase  :    Optional[Any]					=					d_model
							_lowerCamelCase  :    Optional[Any]					=					d_kv
							_lowerCamelCase  :    Optional[int]					=					d_ff
							_lowerCamelCase  :    List[str]					=					num_layers
							_lowerCamelCase  :    Union[str, Any]					=					(
							    num_decoder_layers if num_decoder_layers is not None else self.num_layers
							)  # default = symmetry
							_lowerCamelCase  :    List[str]					=					num_heads
							_lowerCamelCase  :    int					=					relative_attention_num_buckets
							_lowerCamelCase  :    Union[str, Any]					=					relative_attention_max_distance
							_lowerCamelCase  :    int					=					dropout_rate
							_lowerCamelCase  :    List[Any]					=					layer_norm_epsilon
							_lowerCamelCase  :    Union[str, Any]					=					initializer_factor
							_lowerCamelCase  :    List[Any]					=					feed_forward_proj
							_lowerCamelCase  :    Dict					=					use_cache

							_lowerCamelCase  :    Dict					=					self.feed_forward_proj.split('-'						)
							_lowerCamelCase  :    List[str]					=					act_info[-1]
							_lowerCamelCase  :    int					=					act_info[0] == 'gated'

							if len(lowercase						) > 1 and act_info[0] != "gated" or len(lowercase						) > 2:
											raise ValueError(
											    F'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
											    'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
											    '\'gated-gelu\' or \'relu\''						)

							if feed_forward_proj == "gated-gelu":
											_lowerCamelCase  :    Optional[int]					=					'gelu_new'
			@property
			def       A_					(						self						):
							return self.d_model
			@property
			def       A_					(						self						):
							return self.num_heads






			@property
			def       A_					(						self						):
							return self.num_layers






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			@property
			# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
			def       A_					(						self						):
							_lowerCamelCase  :    Tuple					=					{
							    'input_ids': {0: 'batch', 1: 'encoder_sequence'},
							    'attention_mask': {0: 'batch', 1: 'encoder_sequence'},
							}
							if self.use_past:
											_lowerCamelCase  :    Optional[int]					=					'past_encoder_sequence + sequence'
											_lowerCamelCase  :    int					=					{0: 'batch'}
											_lowerCamelCase  :    List[str]					=					{0: 'batch', 1: 'past_decoder_sequence + sequence'}
							else:
											_lowerCamelCase  :    Dict					=					{0: 'batch', 1: 'decoder_sequence'}
											_lowerCamelCase  :    str					=					{0: 'batch', 1: 'decoder_sequence'}

							if self.use_past:
											self.fill_with_past_key_values_(lowercase						,   direction='inputs'						)

							return common_inputs
			@property
			# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
			def       A_					(						self						):
							return 13






			@property
			def       A_					(						self						):
							return 5E-4