


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


__UpperCAmelCase					       =							get_logger(__name__)




class 	a__       :





       '''simple docstring'''






       def __init__(	self      ,					lowerCamelCase_ = None     ) ->							List[str]:
              lowerCAmelCase__      =			(
                  os.path.join(__A      ,					config.EXTRACTED_DATASETS_DIR     ) if cache_dir else config.EXTRACTED_DATASETS_PATH
              )
              lowerCAmelCase__      =			Extractor







       def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							Any:
              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(__A     )
              return os.path.join(self.extract_dir      ,					hash_url_to_filename(__A     )     )







       def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_     ) ->							int:
              return force_extract or (
                  not os.path.isfile(__A     ) and not (os.path.isdir(__A     ) and os.listdir(__A     ))
              )







       def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_ = False     ) ->							Tuple:
              lowerCAmelCase__      =			self.extractor.infer_extractor_format(__A     )
              if not extractor_format:
                     return input_path
              lowerCAmelCase__      =			self._get_output_path(__A     )
              if self._do_extract(__A      ,					__A     ):
                     self.extractor.extract(__A      ,					__A      ,					__A     )
              return output_path




class 	a__       (							a__						):





       '''simple docstring'''






       @classmethod
       @abstractmethod
       def 						__SCREAMING_SNAKE_CASE							(	cls      ,					lowerCamelCase_      ,					**lowerCamelCase_     ) ->							str:
              ...







       @staticmethod
       @abstractmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Any:
              ...




class 	a__       (							a__       ,       a__						):





       '''simple docstring'''






       lowercase__    :     Optional[Any]					=   []







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Any:
              with open(__A      ,					'''rb'''     ) as f:
                     return f.read(__A     )







       @classmethod
       def 						__SCREAMING_SNAKE_CASE							(	cls      ,					lowerCamelCase_      ,					lowerCamelCase_ = b""     ) ->							Optional[Any]:
              if not magic_number:
                     lowerCAmelCase__      =			max(len(__A     ) for cls_magic_number in cls.magic_numbers     )
                     try:
                            lowerCAmelCase__      =			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 	a__       (							a__						):





       '''simple docstring'''






       @classmethod
       def 						__SCREAMING_SNAKE_CASE							(	cls      ,					lowerCamelCase_      ,					**lowerCamelCase_     ) ->							Optional[int]:
              return tarfile.is_tarfile(__A     )







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							List[Any]:

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

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

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

              lowerCAmelCase__      =			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 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Tuple:
              os.makedirs(__A      ,					exist_ok=__A     )
              lowerCAmelCase__      =			tarfile.open(__A     )
              tar_file.extractall(__A      ,					members=TarExtractor.safemembers(__A      ,					__A     )     )
              tar_file.close()




class 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     Dict					=   [b"\x1F\x8B"]







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							List[Any]:
              with gzip.open(__A      ,					'''rb'''     ) as gzip_file:
                     with open(__A      ,					'''wb'''     ) as extracted_file:
                            shutil.copyfileobj(__A      ,					__A     )




class 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     Any					=   [
           b"PK\x03\x04",
           b"PK\x05\x06",  # empty archive
           b"PK\x07\x08",  # spanned archive
       ]







       @classmethod
       def 						__SCREAMING_SNAKE_CASE							(	cls      ,					lowerCamelCase_      ,					lowerCamelCase_ = b""     ) ->							Any:
              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:
                            lowerCAmelCase__      =			_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:
                                                 lowerCAmelCase__      =			fp.read(__A     )  # CD is where we expect it to be
                                                 if len(__A     ) == sizeCentralDir:
                                                        lowerCAmelCase__      =			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 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Optional[int]:
              os.makedirs(__A      ,					exist_ok=__A     )
              with zipfile.ZipFile(__A      ,					'''r'''     ) as zip_file:
                     zip_file.extractall(__A     )
                     zip_file.close()




class 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     Dict					=   [b"\xFD\x37\x7A\x58\x5A\x00"]







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Union[str, Any]:
              with lzma.open(__A     ) as compressed_file:
                     with open(__A      ,					'''wb'''     ) as extracted_file:
                            shutil.copyfileobj(__A      ,					__A     )




class 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     Optional[Any]					=   [b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"]  # RAR_ID  # RAR5_ID







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Optional[int]:
              if not config.RARFILE_AVAILABLE:
                     raise ImportError('''Please pip install rarfile'''     )
              import rarfile

              os.makedirs(__A      ,					exist_ok=__A     )
              lowerCAmelCase__      =			rarfile.RarFile(__A     )
              rf.extractall(__A     )
              rf.close()




class 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     Any					=   [b"\x28\xb5\x2F\xFD"]







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Optional[Any]:
              if not config.ZSTANDARD_AVAILABLE:
                     raise ImportError('''Please pip install zstandard'''     )
              import zstandard as zstd

              lowerCAmelCase__      =			zstd.ZstdDecompressor()
              with open(__A      ,					'''rb'''     ) as ifh, open(__A      ,					'''wb'''     ) as ofh:
                     dctx.copy_stream(__A      ,					__A     )




class 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     int					=   [b"\x42\x5A\x68"]







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Union[str, Any]:
              with bza.open(__A      ,					'''rb'''     ) as compressed_file:
                     with open(__A      ,					'''wb'''     ) as extracted_file:
                            shutil.copyfileobj(__A      ,					__A     )




class 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     List[str]					=   [b"\x37\x7A\xBC\xAF\x27\x1C"]







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Union[str, Any]:
              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 	a__       (							a__						):





       '''simple docstring'''






       lowercase__    :     int					=   [b"\x04\x22\x4D\x18"]







       @staticmethod
       def 						__SCREAMING_SNAKE_CASE							(	lowerCamelCase_      ,					lowerCamelCase_     ) ->							Union[str, Any]:
              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 	a__       :





       '''simple docstring'''






       lowercase__    :     Dict					=   {
           "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 						__SCREAMING_SNAKE_CASE							(	cls     ) ->							int:
              return max(
                  len(__A     )
                  for extractor in cls.extractors.values()
                  if issubclass(__A      ,					__A     )
                  for extractor_magic_number in extractor.magic_numbers     )







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







       @classmethod
       def 						__SCREAMING_SNAKE_CASE							(	cls      ,					lowerCamelCase_      ,					lowerCamelCase_ = False     ) ->							Union[str, Any]:
              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      ,					)
              lowerCAmelCase__      =			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 						__SCREAMING_SNAKE_CASE							(	cls      ,					lowerCamelCase_     ) ->							List[Any]:  # <Added version="2.4.0"/>
              lowerCAmelCase__      =			cls._get_magic_number_max_length()
              lowerCAmelCase__      =			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 						__SCREAMING_SNAKE_CASE							(	cls      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_ = None      ,					lowerCamelCase_ = "deprecated"      ,					) ->							List[Any]:
              os.makedirs(os.path.dirname(__A     )      ,					exist_ok=__A     )
              # Prevent parallel extractions
              lowerCAmelCase__      =			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      ,					)
                                   lowerCAmelCase__      =			extractor if extractor != "deprecated" else extractor_format
                            else:
                                   lowerCAmelCase__      =			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     )



'''simple docstring'''






import tempfile
import unittest

import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax


if is_flax_available():
		import os

		from flax.core.frozen_dict import unfreeze
		from flax.traverse_util import flatten_dict

		from transformers import FlaxBertModel

		__UpperCAmelCase					       =							'''0.12'''  # assumed parallelism: 8




@require_flax
@is_staging_test
class 	a__       (							unittest.TestCase						):





							'''simple docstring'''






							@classmethod
							def 						__SCREAMING_SNAKE_CASE							(	cls     ) ->							Any:
														lowerCAmelCase__      =			TOKEN
														HfFolder.save_token(lowerCamelCase_     )







							@classmethod
							def 						__SCREAMING_SNAKE_CASE							(	cls     ) ->							Tuple:
														try:
																					delete_repo(token=cls._token      ,					repo_id='''test-model-flax'''     )
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token      ,					repo_id='''valid_org/test-model-flax-org'''     )
														except HTTPError:
																					pass







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[Any]:
														lowerCAmelCase__      =			BertConfig(
														    vocab_size=99      ,					hidden_size=32      ,					num_hidden_layers=5      ,					num_attention_heads=4      ,					intermediate_size=37     )
														lowerCAmelCase__      =			FlaxBertModel(lowerCamelCase_     )
														model.push_to_hub('''test-model-flax'''      ,					use_auth_token=self._token     )

														lowerCAmelCase__      =			FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""     )

														lowerCAmelCase__      =			flatten_dict(unfreeze(model.params     )     )
														lowerCAmelCase__      =			flatten_dict(unfreeze(new_model.params     )     )

														for key in base_params.keys():
																					lowerCAmelCase__      =			(base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCamelCase_      ,					1e-3      ,					msg=F"""{key} not identical"""     )

														# Reset repo
														delete_repo(token=self._token      ,					repo_id='''test-model-flax'''     )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(lowerCamelCase_      ,					repo_id='''test-model-flax'''      ,					push_to_hub=lowerCamelCase_      ,					use_auth_token=self._token     )

														lowerCAmelCase__      =			FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""     )

														lowerCAmelCase__      =			flatten_dict(unfreeze(model.params     )     )
														lowerCAmelCase__      =			flatten_dict(unfreeze(new_model.params     )     )

														for key in base_params.keys():
																					lowerCAmelCase__      =			(base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCamelCase_      ,					1e-3      ,					msg=F"""{key} not identical"""     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Union[str, Any]:
														lowerCAmelCase__      =			BertConfig(
														    vocab_size=99      ,					hidden_size=32      ,					num_hidden_layers=5      ,					num_attention_heads=4      ,					intermediate_size=37     )
														lowerCAmelCase__      =			FlaxBertModel(lowerCamelCase_     )
														model.push_to_hub('''valid_org/test-model-flax-org'''      ,					use_auth_token=self._token     )

														lowerCAmelCase__      =			FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''     )

														lowerCAmelCase__      =			flatten_dict(unfreeze(model.params     )     )
														lowerCAmelCase__      =			flatten_dict(unfreeze(new_model.params     )     )

														for key in base_params.keys():
																					lowerCAmelCase__      =			(base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCamelCase_      ,					1e-3      ,					msg=F"""{key} not identical"""     )

														# Reset repo
														delete_repo(token=self._token      ,					repo_id='''valid_org/test-model-flax-org'''     )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(
																					    lowerCamelCase_      ,					repo_id='''valid_org/test-model-flax-org'''      ,					push_to_hub=lowerCamelCase_      ,					use_auth_token=self._token     )

														lowerCAmelCase__      =			FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''     )

														lowerCAmelCase__      =			flatten_dict(unfreeze(model.params     )     )
														lowerCAmelCase__      =			flatten_dict(unfreeze(new_model.params     )     )

														for key in base_params.keys():
																					lowerCAmelCase__      =			(base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCamelCase_      ,					1e-3      ,					msg=F"""{key} not identical"""     )


def       _snake_case     (  A				,					A )		->					Optional[int]:
							lowerCAmelCase__      =			True
							lowerCAmelCase__      =			flatten_dict(modela.params )
							lowerCAmelCase__      =			flatten_dict(modela.params )
							for key in flat_params_a.keys():
														if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4:
																					lowerCAmelCase__      =			False

							return models_are_equal






@require_flax
class 	a__       (							unittest.TestCase						):





							'''simple docstring'''






							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Optional[Any]:
														lowerCAmelCase__      =			BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''     )
														lowerCAmelCase__      =			FlaxBertModel(lowerCamelCase_     )

														lowerCAmelCase__      =			'''bert'''
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(os.path.join(lowerCamelCase_      ,					lowerCamelCase_     )     )

																					with self.assertRaises(lowerCamelCase_     ):
																												lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_     )

																					lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_      ,					subfolder=lowerCamelCase_     )

														self.assertTrue(check_models_equal(lowerCamelCase_      ,					lowerCamelCase_     )     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[Any]:
														lowerCAmelCase__      =			BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''     )
														lowerCAmelCase__      =			FlaxBertModel(lowerCamelCase_     )

														lowerCAmelCase__      =			'''bert'''
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(os.path.join(lowerCamelCase_      ,					lowerCamelCase_     )      ,					max_shard_size='''10KB'''     )

																					with self.assertRaises(lowerCamelCase_     ):
																												lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_     )

																					lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_      ,					subfolder=lowerCamelCase_     )

														self.assertTrue(check_models_equal(lowerCamelCase_      ,					lowerCamelCase_     )     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Optional[Any]:
														lowerCAmelCase__      =			'''bert'''
														lowerCAmelCase__      =			'''hf-internal-testing/tiny-random-bert-subfolder'''

														with self.assertRaises(lowerCamelCase_     ):
																					lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_     )

														lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_      ,					subfolder=lowerCamelCase_     )

														self.assertIsNotNone(lowerCamelCase_     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[Any]:
														lowerCAmelCase__      =			'''bert'''
														lowerCAmelCase__      =			'''hf-internal-testing/tiny-random-bert-sharded-subfolder'''
														with self.assertRaises(lowerCamelCase_     ):
																					lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_     )

														lowerCAmelCase__      =			FlaxBertModel.from_pretrained(lowerCamelCase_      ,					subfolder=lowerCamelCase_     )

														self.assertIsNotNone(lowerCamelCase_     )