



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


lowerCAmelCase	:		List[Any]				=   get_logger(__name__)






class 					UpperCAmelCase__	:



					def __init__(    self			,				UpperCamelCase = None     )     ->			Union[str, Any]:
						__lowerCAmelCase												=  (
						    os.path.join(UpperCamelCase			,				config.EXTRACTED_DATASETS_DIR     ) if cache_dir else config.EXTRACTED_DATASETS_PATH
						)
						__lowerCAmelCase												=  Extractor



					def        UpperCAmelCase_ (    self			,				UpperCamelCase     )     ->			str:
						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												=  os.path.abspath(UpperCamelCase     )
						return os.path.join(self.extract_dir			,				hash_url_to_filename(UpperCamelCase     )     )



					def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase     )     ->			bool:
						return force_extract or (
						    not os.path.isfile(UpperCamelCase     ) and not (os.path.isdir(UpperCamelCase     ) and os.listdir(UpperCamelCase     ))
						)



					def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase = False     )     ->			str:
						__lowerCAmelCase												=  self.extractor.infer_extractor_format(UpperCamelCase     )
						if not extractor_format:
							return input_path
						__lowerCAmelCase												=  self._get_output_path(UpperCamelCase     )
						if self._do_extract(UpperCamelCase			,				UpperCamelCase     ):
							self.extractor.extract(UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     )
						return output_path






class 					UpperCAmelCase__	(		UpperCamelCase__ ):



					@classmethod
					@abstractmethod
					def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				**UpperCamelCase     )     ->			bool:
						...



					@staticmethod
					@abstractmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						...






class 					UpperCAmelCase__	(		UpperCamelCase__							,       UpperCamelCase__ ):
					a      :     List[bytes]        =							[]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			List[Any]:
						with open(UpperCamelCase			,				"rb"     ) as f:
							return f.read(UpperCamelCase     )



					@classmethod
					def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase = b""     )     ->			bool:
						if not magic_number:
							__lowerCAmelCase												=  max(len(UpperCamelCase     ) for cls_magic_number in cls.magic_numbers     )
							try:
								__lowerCAmelCase												=  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 					UpperCAmelCase__	(		UpperCamelCase__ ):



					@classmethod
					def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				**UpperCamelCase     )     ->			bool:
						return tarfile.is_tarfile(UpperCamelCase     )



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			Dict:

						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
							__lowerCAmelCase												=  resolved(os.path.join(UpperCamelCase			,				os.path.dirname(info.name     )     )     )
							return badpath(info.linkname			,				base=UpperCamelCase     )

						__lowerCAmelCase												=  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        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
						__lowerCAmelCase												=  tarfile.open(UpperCamelCase     )
						tar_file.extractall(UpperCamelCase			,				members=TarExtractor.safemembers(UpperCamelCase			,				UpperCamelCase     )     )
						tar_file.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x1F\x8B"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						with gzip.open(UpperCamelCase			,				"rb"     ) as gzip_file:
							with open(UpperCamelCase			,				"wb"     ) as extracted_file:
								shutil.copyfileobj(UpperCamelCase			,				UpperCamelCase     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     List[Any]        =							[
					    B"""PK\x03\x04""",
					    B"""PK\x05\x06""",  # empty archive
					    B"""PK\x07\x08""",  # spanned archive
					]



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

							with open(UpperCamelCase			,				"rb"     ) as fp:
								__lowerCAmelCase												=  _EndRecData(UpperCamelCase     )
								if endrec:
									if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
										return True  # Empty zipfiles are still zipfiles
									elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
										fp.seek(endrec[_ECD_OFFSET]     )  # Central directory is on the same disk
										if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
											__lowerCAmelCase												=  fp.read(UpperCamelCase     )  # CD is where we expect it to be
											if len(UpperCamelCase     ) == sizeCentralDir:
												__lowerCAmelCase												=  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        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
						with zipfile.ZipFile(UpperCamelCase			,				"r"     ) as zip_file:
							zip_file.extractall(UpperCamelCase     )
							zip_file.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Tuple        =							[B"""\xFD\x37\x7A\x58\x5A\x00"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						with lzma.open(UpperCamelCase     ) as compressed_file:
							with open(UpperCamelCase			,				"wb"     ) as extracted_file:
								shutil.copyfileobj(UpperCamelCase			,				UpperCamelCase     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     str        =							[B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						if not config.RARFILE_AVAILABLE:
							raise ImportError("Please pip install rarfile"     )
						import rarfile

						os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
						__lowerCAmelCase												=  rarfile.RarFile(UpperCamelCase     )
						rf.extractall(UpperCamelCase     )
						rf.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     int        =							[B"""\x28\xb5\x2F\xFD"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						if not config.ZSTANDARD_AVAILABLE:
							raise ImportError("Please pip install zstandard"     )
						import zstandard as zstd

						__lowerCAmelCase												=  zstd.ZstdDecompressor()
						with open(UpperCamelCase			,				"rb"     ) as ifh, open(UpperCamelCase			,				"wb"     ) as ofh:
							dctx.copy_stream(UpperCamelCase			,				UpperCamelCase     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x42\x5A\x68"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						with bza.open(UpperCamelCase			,				"rb"     ) as compressed_file:
							with open(UpperCamelCase			,				"wb"     ) as extracted_file:
								shutil.copyfileobj(UpperCamelCase			,				UpperCamelCase     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x37\x7A\xBC\xAF\x27\x1C"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						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 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x04\x22\x4D\x18"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						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 					UpperCAmelCase__	:
					#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
					a      :     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        UpperCAmelCase_ (    cls     )     ->			Optional[Any]:
						return max(
						    len(UpperCamelCase     )
						    for extractor in cls.extractors.values()
						    if issubclass(UpperCamelCase			,				UpperCamelCase     )
						    for extractor_magic_number in extractor.magic_numbers     )



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			Dict:
						try:
							return MagicNumberBaseExtractor.read_magic_number(UpperCamelCase			,				magic_number_length=UpperCamelCase     )
						except OSError:
							return b""



					@classmethod
					def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase = False     )     ->			bool:
						warnings.warn(
						    "Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
						    "Use 'infer_extractor_format' instead."			,				category=UpperCamelCase			,				)
						__lowerCAmelCase												=  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        UpperCAmelCase_ (    cls			,				UpperCamelCase     )     ->			str:  # <Added version="2.4.0"/>
						__lowerCAmelCase												=  cls._get_magic_number_max_length()
						__lowerCAmelCase												=  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        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase = None			,				UpperCamelCase = "deprecated"			,				)     ->			None:
						os.makedirs(os.path.dirname(UpperCamelCase     )			,				exist_ok=UpperCamelCase     )
						# Prevent parallel extractions
						__lowerCAmelCase												=  str(Path(UpperCamelCase     ).with_suffix(".lock"     )     )
						with FileLock(UpperCamelCase     ):
							shutil.rmtree(UpperCamelCase			,				ignore_errors=UpperCamelCase     )
							if extractor_format or extractor != "deprecated":
								if extractor != "deprecated" or not isinstance(UpperCamelCase			,				UpperCamelCase     ):  # passed as positional arg
									warnings.warn(
									    "Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
									    "Use 'extractor_format' instead."			,				category=UpperCamelCase			,				)
									__lowerCAmelCase												=  extractor if extractor != "deprecated" else extractor_format
								else:
									__lowerCAmelCase												=  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'''



from __future__ import annotations

import math



def   __lowerCAmelCase					(							lowerCamelCase   :						list				,		lowerCamelCase   :						list					):






	'''simple docstring'''




	if len(lowerCamelCase					) != 2 or len(a[0]					) != 2 or len(lowerCamelCase					) != 2 or len(b[0]					) != 2:
		raise Exception("Matrices are not 2x2"					)
	__lowerCAmelCase												=  [
	    [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],
	    [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]],
	]
	return new_matrix



def   __lowerCAmelCase					(							lowerCamelCase   :						list				,		lowerCamelCase   :						list					):






	'''simple docstring'''




	return [
	    [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]					)					)]
	    for row in range(len(lowerCamelCase					)					)
	]



def   __lowerCAmelCase					(							lowerCamelCase   :						list				,		lowerCamelCase   :						list					):






	'''simple docstring'''




	return [
	    [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]					)					)]
	    for row in range(len(lowerCamelCase					)					)
	]



def   __lowerCAmelCase					(							lowerCamelCase   :						list					):






	'''simple docstring'''




	if len(lowerCamelCase					) % 2 != 0 or len(a[0]					) % 2 != 0:
		raise Exception("Odd matrices are not supported!"					)

	__lowerCAmelCase												=  len(lowerCamelCase					)
	__lowerCAmelCase												=  matrix_length // 2

	__lowerCAmelCase												=  [[a[i][j] for j in range(lowerCamelCase				,		lowerCamelCase					)] for i in range(lowerCamelCase					)]
	__lowerCAmelCase												=  [
	    [a[i][j] for j in range(lowerCamelCase				,		lowerCamelCase					)] for i in range(lowerCamelCase				,		lowerCamelCase					)
	]

	__lowerCAmelCase												=  [[a[i][j] for j in range(lowerCamelCase					)] for i in range(lowerCamelCase					)]
	__lowerCAmelCase												=  [[a[i][j] for j in range(lowerCamelCase					)] for i in range(lowerCamelCase				,		lowerCamelCase					)]

	return top_left, top_right, bot_left, bot_right



def   __lowerCAmelCase					(							lowerCamelCase   :						list					):






	'''simple docstring'''




	return len(lowerCamelCase					), len(matrix[0]					)



def   __lowerCAmelCase					(							lowerCamelCase   :						list					):






	'''simple docstring'''




	print("\n".join(str(lowerCamelCase					) for line in matrix					)					)



def   __lowerCAmelCase					(							lowerCamelCase   :						list				,		lowerCamelCase   :						list					):






	'''simple docstring'''




	if matrix_dimensions(lowerCamelCase					) == (2, 2):
		return default_matrix_multiplication(lowerCamelCase				,		lowerCamelCase					)

	__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase												=  split_matrix(lowerCamelCase					)
	__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase												=  split_matrix(lowerCamelCase					)

	__lowerCAmelCase												=  actual_strassen(lowerCamelCase				,		matrix_subtraction(lowerCamelCase				,		lowerCamelCase					)					)
	__lowerCAmelCase												=  actual_strassen(matrix_addition(lowerCamelCase				,		lowerCamelCase					)				,		lowerCamelCase					)
	__lowerCAmelCase												=  actual_strassen(matrix_addition(lowerCamelCase				,		lowerCamelCase					)				,		lowerCamelCase					)
	__lowerCAmelCase												=  actual_strassen(lowerCamelCase				,		matrix_subtraction(lowerCamelCase				,		lowerCamelCase					)					)
	__lowerCAmelCase												=  actual_strassen(matrix_addition(lowerCamelCase				,		lowerCamelCase					)				,		matrix_addition(lowerCamelCase				,		lowerCamelCase					)					)
	__lowerCAmelCase												=  actual_strassen(matrix_subtraction(lowerCamelCase				,		lowerCamelCase					)				,		matrix_addition(lowerCamelCase				,		lowerCamelCase					)					)
	__lowerCAmelCase												=  actual_strassen(matrix_subtraction(lowerCamelCase				,		lowerCamelCase					)				,		matrix_addition(lowerCamelCase				,		lowerCamelCase					)					)

	__lowerCAmelCase												=  matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase				,		lowerCamelCase					)				,		lowerCamelCase					)				,		lowerCamelCase					)
	__lowerCAmelCase												=  matrix_addition(lowerCamelCase				,		lowerCamelCase					)
	__lowerCAmelCase												=  matrix_addition(lowerCamelCase				,		lowerCamelCase					)
	__lowerCAmelCase												=  matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase				,		lowerCamelCase					)				,		lowerCamelCase					)				,		lowerCamelCase					)

	# construct the new matrix from our 4 quadrants
	__lowerCAmelCase												=  []
	for i in range(len(lowerCamelCase					)					):
		new_matrix.append(top_left[i] + top_right[i]					)
	for i in range(len(lowerCamelCase					)					):
		new_matrix.append(bot_left[i] + bot_right[i]					)
	return new_matrix



def   __lowerCAmelCase					(							lowerCamelCase   :						list				,		lowerCamelCase   :						list					):






	'''simple docstring'''




	if matrix_dimensions(lowerCamelCase					)[1] != matrix_dimensions(lowerCamelCase					)[0]:
		__lowerCAmelCase												=  (
		    "Unable to multiply these matrices, please check the dimensions.\n"
		    f'''Matrix A: {matrixa}\n'''
		    f'''Matrix B: {matrixa}'''
		)
		raise Exception(lowerCamelCase					)
	__lowerCAmelCase												=  matrix_dimensions(lowerCamelCase					)
	__lowerCAmelCase												=  matrix_dimensions(lowerCamelCase					)

	if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]:
		return [matrixa, matrixa]

	__lowerCAmelCase												=  max(*lowerCamelCase				,		*lowerCamelCase					)
	__lowerCAmelCase												=  int(math.pow(2				,		math.ceil(math.loga(lowerCamelCase					)					)					)					)
	__lowerCAmelCase												=  matrixa
	__lowerCAmelCase												=  matrixa

	# Adding zeros to the matrices so that the arrays dimensions are the same and also
	# power of 2
	for i in range(0				,		lowerCamelCase					):
		if i < dimensiona[0]:
			for _ in range(dimensiona[1]				,		lowerCamelCase					):
				new_matrixa[i].append(0					)
		else:
			new_matrixa.append([0] * maxim					)
		if i < dimensiona[0]:
			for _ in range(dimensiona[1]				,		lowerCamelCase					):
				new_matrixa[i].append(0					)
		else:
			new_matrixa.append([0] * maxim					)

	__lowerCAmelCase												=  actual_strassen(lowerCamelCase				,		lowerCamelCase					)

	# Removing the additional zeros
	for i in range(0				,		lowerCamelCase					):
		if i < dimensiona[0]:
			for _ in range(dimensiona[1]				,		lowerCamelCase					):
				final_matrix[i].pop()
		else:
			final_matrix.pop()
	return final_matrix


if __name__ == "__main__":
	lowerCAmelCase	:		Tuple				=   [
	    [2, 3, 4, 5],
	    [6, 4, 3, 1],
	    [2, 3, 6, 7],
	    [3, 1, 2, 4],
	    [2, 3, 4, 5],
	    [6, 4, 3, 1],
	    [2, 3, 6, 7],
	    [3, 1, 2, 4],
	    [2, 3, 4, 5],
	    [6, 2, 3, 1],
	]
	lowerCAmelCase	:		Any				=   [[0, 2, 1, 1], [1_6, 2, 3, 3], [2, 2, 7, 7], [1_3, 1_1, 2_2, 4]]
	print(strassen(matrixa, matrixa))