


'''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


__snake_case							   =  get_logger(__name__)
class      lowercase			:

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_ = None							):

							'''simple docstring'''


							UpperCamelCase__     :Any							      =				(
							    os.path.join(UpperCamelCase_					,     config.EXTRACTED_DATASETS_DIR							) if cache_dir else config.EXTRACTED_DATASETS_PATH
							)
							UpperCamelCase__     :Any							      =				Extractor




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''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"
							UpperCamelCase__     :Union[str, Any]							      =				os.path.abspath(UpperCamelCase_							)
							return os.path.join(self.extract_dir					,     hash_url_to_filename(UpperCamelCase_							)							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_ = False							):

							'''simple docstring'''


							UpperCamelCase__     :Any							      =				self.extractor.infer_extractor_format(UpperCamelCase_							)
							if not extractor_format:
												return input_path
							UpperCamelCase__     :Any							      =				self._get_output_path(UpperCamelCase_							)
							if self._do_extract(UpperCamelCase_					,     UpperCamelCase_							):
												self.extractor.extract(UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_							)
							return output_path



class      lowercase			(							A__      ):

		"""simple docstring"""

		@classmethod
		@abstractmethod
		def 					lowerCAmelCase__       (	cls					,     UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							...




		@staticmethod
		@abstractmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


							...



class      lowercase			(							A__			,	A__      ):

		"""simple docstring"""

		_a									=       []




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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




		@classmethod
		def 					lowerCAmelCase__       (	cls					,     UpperCamelCase_					,     UpperCamelCase_ = b""							):

							'''simple docstring'''


							if not magic_number:
												UpperCamelCase__     :Optional[Any]							      =				max(len(UpperCamelCase_							) for cls_magic_number in cls.magic_numbers							)
												try:
																	UpperCamelCase__     :Dict							      =				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      lowercase			(							A__      ):

		"""simple docstring"""

		@classmethod
		def 					lowerCAmelCase__       (	cls					,     UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							return tarfile.is_tarfile(UpperCamelCase_							)




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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

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

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

							UpperCamelCase__     :List[str]							      =				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 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [b'\x1F\x8B']




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [
		    b'PK\x03\x04',
		    b'PK\x05\x06',  # empty archive
		    b'PK\x07\x08',  # spanned archive
		]




		@classmethod
		def 					lowerCAmelCase__       (	cls					,     UpperCamelCase_					,     UpperCamelCase_ = b""							):

							'''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:
																	UpperCamelCase__     :List[str]							      =				_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:
																																UpperCamelCase__     :Optional[Any]							      =				fp.read(UpperCamelCase_							)  # CD is where we expect it to be
																																if len(UpperCamelCase_							) == sizeCentralDir:
																																					UpperCamelCase__     :Any							      =				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 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [b'\xFD\x37\x7A\x58\x5A\x00']




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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

							os.makedirs(UpperCamelCase_					,     exist_ok=UpperCamelCase_							)
							UpperCamelCase__     :Optional[int]							      =				rarfile.RarFile(UpperCamelCase_							)
							rf.extractall(UpperCamelCase_							)
							rf.close()



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [b'\x28\xb5\x2F\xFD']




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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

							UpperCamelCase__     :Union[str, Any]							      =				zstd.ZstdDecompressor()
							with open(UpperCamelCase_					,     '''rb'''							) as ifh, open(UpperCamelCase_					,     '''wb'''							) as ofh:
												dctx.copy_stream(UpperCamelCase_					,     UpperCamelCase_							)



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [b'\x42\x5A\x68']




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [b'\x37\x7A\xBC\xAF\x27\x1C']




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''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      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       [b'\x04\x22\x4D\x18']




		@staticmethod
		def 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''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      lowercase			:

		"""simple docstring"""

		_a									=       {
		    '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							):

							'''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 					lowerCAmelCase__       (	UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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




		@classmethod
		def 					lowerCAmelCase__       (	cls					,     UpperCamelCase_					,     UpperCamelCase_ = False							):

							'''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_					,     )
							UpperCamelCase__     :Optional[Any]							      =				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 					lowerCAmelCase__       (	cls					,     UpperCamelCase_							):  # <Added version="2.4.0"/>

							'''simple docstring'''


							UpperCamelCase__     :str							      =				cls._get_magic_number_max_length()
							UpperCamelCase__     :List[str]							      =				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 					lowerCAmelCase__       (	cls					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_ = None					,     UpperCamelCase_ = "deprecated"					,     ):

							'''simple docstring'''


							os.makedirs(os.path.dirname(UpperCamelCase_							)					,     exist_ok=UpperCamelCase_							)
							# Prevent parallel extractions
							UpperCamelCase__     :Dict							      =				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_					,     )
																						UpperCamelCase__     :List[str]							      =				extractor if extractor != '''deprecated''' else extractor_format
																	else:
																						UpperCamelCase__     :List[str]							      =				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_							)



'''simple docstring'''
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       'Speech2TextFeatureExtractor'
		_a									=       'Speech2TextTokenizer'




		def __init__(	self					,     UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


							super().__init__(UpperCamelCase_					,     UpperCamelCase_							)
							UpperCamelCase__     :List[str]							      =				self.feature_extractor
							UpperCamelCase__     :Optional[Any]							      =				False




		def __call__(	self					,     *UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							if self._in_target_context_manager:
												return self.current_processor(*UpperCamelCase_					,     **UpperCamelCase_							)

							if "raw_speech" in kwargs:
												warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'''							)
												UpperCamelCase__     :Optional[Any]							      =				kwargs.pop('''raw_speech'''							)
							else:
												UpperCamelCase__     :List[Any]							      =				kwargs.pop('''audio'''					,     UpperCamelCase_							)
							UpperCamelCase__     :List[Any]							      =				kwargs.pop('''sampling_rate'''					,     UpperCamelCase_							)
							UpperCamelCase__     :Dict							      =				kwargs.pop('''text'''					,     UpperCamelCase_							)
							if len(UpperCamelCase_							) > 0:
												UpperCamelCase__     :Tuple							      =				args[0]
												UpperCamelCase__     :Optional[int]							      =				args[1:]

							if audio is None and text is None:
												raise ValueError('''You need to specify either an `audio` or `text` input to process.'''							)

							if audio is not None:
												UpperCamelCase__     :Any							      =				self.feature_extractor(UpperCamelCase_					,     *UpperCamelCase_					,     sampling_rate=UpperCamelCase_					,     **UpperCamelCase_							)
							if text is not None:
												UpperCamelCase__     :Dict							      =				self.tokenizer(UpperCamelCase_					,     **UpperCamelCase_							)

							if text is None:
												return inputs
							elif audio is None:
												return encodings
							else:
												UpperCamelCase__     :Dict							      =				encodings['''input_ids''']
												return inputs




		def 					lowerCAmelCase__       (	self					,     *UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							return self.tokenizer.batch_decode(*UpperCamelCase_					,     **UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self					,     *UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							return self.tokenizer.decode(*UpperCamelCase_					,     **UpperCamelCase_							)




		@contextmanager
		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							warnings.warn(
							    '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
							    '''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
							    '''your audio inputs, or in a separate call.'''							)
							UpperCamelCase__     :Optional[Any]							      =				True
							UpperCamelCase__     :Any							      =				self.tokenizer
							yield
							UpperCamelCase__     :Any							      =				self.feature_extractor
							UpperCamelCase__     :Any							      =				False