


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


snake_case__						 =						get_logger(__name__)


class 					lowerCAmelCase_ :




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






									"""simple docstring"""






									a__ :Any						  =    (
									    os.path.join(__A   ,     config.EXTRACTED_DATASETS_DIR						) if cache_dir else config.EXTRACTED_DATASETS_PATH
									)
									a__ :str						  =    Extractor




						def  _snake_case					(	self						:   int   ,     __A						:   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"
									a__ :Optional[Any]						  =    os.path.abspath(__A						)
									return os.path.join(self.extract_dir   ,     hash_url_to_filename(__A						)						)




						def  _snake_case					(	self						:   Optional[Any]   ,     __A						:   str   ,     __A						:   bool						)      ->bool:






									"""simple docstring"""






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






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






									"""simple docstring"""






									a__ :List[Any]						  =    self.extractor.infer_extractor_format(__A						)
									if not extractor_format:
												return input_path
									a__ :Optional[int]						  =    self._get_output_path(__A						)
									if self._do_extract(__A   ,     __A						):
												self.extractor.extract(__A   ,     __A   ,     __A						)
									return output_path






class 					lowerCAmelCase_ (       _a):




						@classmethod
						@abstractmethod
						def  _snake_case					(	cls						:   int   ,     __A						:   Union[Path, str]   ,     **__A						:   List[str]						)      ->bool:






									"""simple docstring"""






									...






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






									"""simple docstring"""






									...






class 					lowerCAmelCase_ (       _a			,_a):
						lowerCamelCase_         =     []




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






									"""simple docstring"""






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






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






									"""simple docstring"""






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






class 					lowerCAmelCase_ (       _a):




						@classmethod
						def  _snake_case					(	cls						:   Tuple   ,     __A						:   Union[Path, str]   ,     **__A						:   Any						)      ->bool:






									"""simple docstring"""






									return tarfile.is_tarfile(__A						)




						@staticmethod
						def  _snake_case					(	__A						:   Tuple   ,     __A						:   str						)      ->List[Any]:






									"""simple docstring"""






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

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

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

									a__ :Any						  =    resolved(__A						)

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






						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






									os.makedirs(__A   ,     exist_ok=__A						)
									a__ :List[str]						  =    tarfile.open(__A						)
									tar_file.extractall(__A   ,     members=TarExtractor.safemembers(__A   ,     __A						)						)
									tar_file.close()






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [B'\x1F\x8B']




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






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






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [
						    B'PK\x03\x04',
						    B'PK\x05\x06',  # empty archive
						    B'PK\x07\x08',  # spanned archive
						]




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






									"""simple docstring"""






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






									"""simple docstring"""






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






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [B'\xFD\x37\x7A\x58\x5A\x00']




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






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






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






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

									os.makedirs(__A   ,     exist_ok=__A						)
									a__ :Dict						  =    rarfile.RarFile(__A						)
									rf.extractall(__A						)
									rf.close()






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [B'\x28\xb5\x2F\xFD']




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






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

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






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [B'\x42\x5A\x68']




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






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






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [B'\x37\x7A\xBC\xAF\x27\x1C']




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






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

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






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     [B'\x04\x22\x4D\x18']




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   Union[Path, str]						)      ->None:






									"""simple docstring"""






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

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






class 					lowerCAmelCase_ :
						#  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  _snake_case					(	cls						:   int						)      ->Optional[int]:






									"""simple docstring"""






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




						@staticmethod
						def  _snake_case					(	__A						:   Union[Path, str]   ,     __A						:   int						)      ->str:






									"""simple docstring"""






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




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






									"""simple docstring"""






									a__ :Optional[Any]						  =    cls._get_magic_number_max_length()
									a__ :Union[str, Any]						  =    cls._read_magic_number(__A   ,     __A						)
									for extractor_format, extractor in cls.extractors.items():
												if extractor.is_extractable(__A   ,     magic_number=__A						):
															return extractor_format






						@classmethod
						def  _snake_case					(	cls						:   int   ,     __A						:   Union[Path, str]   ,     __A						:   Union[Path, str]   ,     __A						:   Optional[str] = None   ,     __A						:   Optional[BaseExtractor] = "deprecated"   ,     )      ->None:






									"""simple docstring"""






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






from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case__			 =						logging.get_logger(__name__)

snake_case__			 =						{
    '''facebook/s2t-wav2vec2-large-en-de''': (
        '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json'''
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2
}


class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     'speech_to_text_2'
						lowerCamelCase_         =     ['past_key_values']
						lowerCamelCase_         =     {'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model'}




						def __init__(	self						:   Dict   ,     __A						:   Union[str, Any]=10000   ,     __A						:   Tuple=6   ,     __A						:   Tuple=2048   ,     __A						:   Any=4   ,     __A						:   str=0.0   ,     __A						:   Tuple=True   ,     __A						:   List[Any]="relu"   ,     __A						:   Union[str, Any]=256   ,     __A						:   str=0.1   ,     __A						:   Optional[Any]=0.0   ,     __A						:   Tuple=0.0   ,     __A						:   Any=0.02   ,     __A						:   int=2   ,     __A						:   Union[str, Any]=True   ,     __A						:   Tuple=1   ,     __A						:   List[str]=0   ,     __A						:   List[str]=2   ,     __A						:   Union[str, Any]=1024   ,     **__A						:   Tuple   ,     )      ->List[str]:






									"""simple docstring"""






									a__ :Tuple						  =    vocab_size
									a__ :Dict						  =    d_model
									a__ :Optional[int]						  =    decoder_ffn_dim
									a__ :Optional[int]						  =    decoder_layers
									a__ :Optional[int]						  =    decoder_attention_heads
									a__ :Dict						  =    dropout
									a__ :Optional[Any]						  =    attention_dropout
									a__ :Any						  =    activation_dropout
									a__ :int						  =    activation_function
									a__ :Optional[int]						  =    init_std
									a__ :List[Any]						  =    decoder_layerdrop
									a__ :Optional[Any]						  =    use_cache
									a__ :List[str]						  =    decoder_layers
									a__ :int						  =    scale_embedding  # scale factor will be sqrt(d_model) if True
									a__ :Optional[int]						  =    max_target_positions

									super().__init__(
									    pad_token_id=__A   ,     bos_token_id=__A   ,     eos_token_id=__A   ,     decoder_start_token_id=__A   ,     **__A   ,     )


