


'''simple docstring'''

import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer





class 						__SCREAMING_SNAKE_CASE					(      __A ):






     def  a_					(			self		)       ->    str:
          _a						=		tempfile.mkdtemp()
          _a						=		5

          # Realm tok
          _a						=		[
              '''[UNK]''',
              '''[CLS]''',
              '''[SEP]''',
              '''[PAD]''',
              '''[MASK]''',
              '''test''',
              '''question''',
              '''this''',
              '''is''',
              '''the''',
              '''first''',
              '''second''',
              '''third''',
              '''fourth''',
              '''fifth''',
              '''record''',
              '''want''',
              '''##want''',
              '''##ed''',
              '''wa''',
              '''un''',
              '''runn''',
              '''##ing''',
              ''',''',
              '''low''',
              '''lowest''',
          ]
          _a						=		os.path.join(self.tmpdirname     ,							"realm_tokenizer"		)
          os.makedirs(__UpperCamelCase     ,							exist_ok=__UpperCamelCase		)
          _a						=		os.path.join(__UpperCamelCase     ,							VOCAB_FILES_NAMES["vocab_file"]		)
          with open(self.vocab_file     ,							"w"     ,							encoding="utf-8"		) as vocab_writer:
               vocab_writer.write("".join([x + "\n" for x in vocab_tokens]		)		)

          _a						=		os.path.join(self.tmpdirname     ,							"realm_block_records"		)
          os.makedirs(__UpperCamelCase     ,							exist_ok=__UpperCamelCase		)






     def  a_					(			self		)       ->    RealmTokenizer:
          return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname     ,							"realm_tokenizer"		)		)






     def  a_					(			self		)       ->    Tuple:
          shutil.rmtree(self.tmpdirname		)






     def  a_					(			self		)       ->    Union[str, Any]:
          _a						=		RealmConfig(num_block_records=self.num_block_records		)
          return config






     def  a_					(			self		)       ->    Optional[Any]:
          _a						=		Dataset.from_dict(
              {
                  "id": ["0", "1"],
                  "question": ["foo", "bar"],
                  "answers": [["Foo", "Bar"], ["Bar"]],
              }		)
          return dataset






     def  a_					(			self		)       ->    str:
          _a						=		np.array(
              [
                  B"This is the first record",
                  B"This is the second record",
                  B"This is the third record",
                  B"This is the fourth record",
                  B"This is the fifth record",
                  B"This is a longer longer longer record",
              ]     ,							dtype=__UpperCamelCase     ,							)
          return block_records






     def  a_					(			self		)       ->    Dict:
          _a						=		RealmRetriever(
              block_records=self.get_dummy_block_records()     ,							tokenizer=self.get_tokenizer()     ,							)
          return retriever






     def  a_					(			self		)       ->    Tuple:
          _a						=		self.get_config()
          _a						=		self.get_dummy_retriever()
          _a						=		retriever.tokenizer

          _a						=		np.array([0, 3]     ,							dtype="long"		)
          _a						=		tokenizer(["Test question"]		).input_ids
          _a						=		tokenizer(
              ["the fourth"]     ,							add_special_tokens=__UpperCamelCase     ,							return_token_type_ids=__UpperCamelCase     ,							return_attention_mask=__UpperCamelCase     ,							).input_ids
          _a						=		config.reader_seq_len

          _a						=		retriever(
              __UpperCamelCase     ,							__UpperCamelCase     ,							answer_ids=__UpperCamelCase     ,							max_length=__UpperCamelCase     ,							return_tensors="np"		)

          self.assertEqual(len(__UpperCamelCase		)     ,							2		)
          self.assertEqual(len(__UpperCamelCase		)     ,							2		)
          self.assertEqual(len(__UpperCamelCase		)     ,							2		)
          self.assertEqual(concat_inputs.input_ids.shape     ,							(2, 10)		)
          self.assertEqual(concat_inputs.attention_mask.shape     ,							(2, 10)		)
          self.assertEqual(concat_inputs.token_type_ids.shape     ,							(2, 10)		)
          self.assertEqual(concat_inputs.special_tokens_mask.shape     ,							(2, 10)		)
          self.assertEqual(
              tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]		)     ,							["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"]     ,							)
          self.assertEqual(
              tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]		)     ,							["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"]     ,							)






     def  a_					(			self		)       ->    int:
          _a						=		self.get_config()
          _a						=		self.get_dummy_retriever()
          _a						=		retriever.tokenizer

          _a						=		np.array([0, 3, 5]     ,							dtype="long"		)
          _a						=		tokenizer(["Test question"]		).input_ids
          _a						=		tokenizer(
              ["the fourth", "longer longer"]     ,							add_special_tokens=__UpperCamelCase     ,							return_token_type_ids=__UpperCamelCase     ,							return_attention_mask=__UpperCamelCase     ,							).input_ids
          _a						=		config.reader_seq_len

          _a						=		retriever(
              __UpperCamelCase     ,							__UpperCamelCase     ,							answer_ids=__UpperCamelCase     ,							max_length=__UpperCamelCase     ,							return_tensors="np"		)

          self.assertEqual([False, True, True]     ,							__UpperCamelCase		)
          self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]     ,							__UpperCamelCase		)
          self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]     ,							__UpperCamelCase		)






     def  a_					(			self		)       ->    Optional[int]:
          _a						=		self.get_dummy_retriever()
          retriever.save_pretrained(os.path.join(self.tmpdirname     ,							"realm_block_records"		)		)

          # Test local path
          _a						=		retriever.from_pretrained(os.path.join(self.tmpdirname     ,							"realm_block_records"		)		)
          self.assertEqual(retriever.block_records[0]     ,							B"This is the first record"		)

          # Test mocked remote path
          with patch("transformers.models.realm.retrieval_realm.hf_hub_download"		) as mock_hf_hub_download:
               _a						=		os.path.join(
                   os.path.join(self.tmpdirname     ,							"realm_block_records"		)     ,							_REALM_BLOCK_RECORDS_FILENAME		)
               _a						=		RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa"		)

          self.assertEqual(retriever.block_records[0]     ,							B"This is the first record"		)





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


lowercase__				     =		get_logger(__name__)





class 						__SCREAMING_SNAKE_CASE					:






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






     def  a_					(			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"
          _a						=		os.path.abspath(__UpperCamelCase		)
          return os.path.join(self.extract_dir     ,							hash_url_to_filename(__UpperCamelCase		)		)






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






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase = False		)       ->    str:
          _a						=		self.extractor.infer_extractor_format(__UpperCamelCase		)
          if not extractor_format:
               return input_path
          _a						=		self._get_output_path(__UpperCamelCase		)
          if self._do_extract(__UpperCamelCase     ,							__UpperCamelCase		):
               self.extractor.extract(__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)
          return output_path







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):






     @classmethod
     @abstractmethod
     def  a_					(			cls     ,							__UpperCamelCase     ,							**__UpperCamelCase		)       ->    bool:
          ...






     @staticmethod
     @abstractmethod
     def  a_					(			__UpperCamelCase     ,							__UpperCamelCase		)       ->    None:
          ...







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ,			lowerCamelCase__ ):
     UpperCAmelCase 					=				[]






     @staticmethod
     def  a_					(			__UpperCamelCase     ,							__UpperCamelCase		)       ->    Dict:
          with open(__UpperCamelCase     ,							"rb"		) as f:
               return f.read(__UpperCamelCase		)






     @classmethod
     def  a_					(			cls     ,							__UpperCamelCase     ,							__UpperCamelCase = b""		)       ->    bool:
          if not magic_number:
               _a						=		max(len(__UpperCamelCase		) for cls_magic_number in cls.magic_numbers		)
               try:
                    _a						=		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 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):






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






     @staticmethod
     def  a_					(			__UpperCamelCase     ,							__UpperCamelCase		)       ->    str:

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

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







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[b'''\x1F\x8B''']






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







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[
         b'''PK\x03\x04''',
         b'''PK\x05\x06''',  # empty archive
         b'''PK\x07\x08''',  # spanned archive
     ]






     @classmethod
     def  a_					(			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:
                    _a						=		_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:
                                   _a						=		fp.read(__UpperCamelCase		)  # CD is where we expect it to be
                                   if len(__UpperCamelCase		) == sizeCentralDir:
                                        _a						=		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  a_					(			__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 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[b'''\xFD\x37\x7A\x58\x5A\x00''']






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







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID






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

          os.makedirs(__UpperCamelCase     ,							exist_ok=__UpperCamelCase		)
          _a						=		rarfile.RarFile(__UpperCamelCase		)
          rf.extractall(__UpperCamelCase		)
          rf.close()







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[b'''\x28\xb5\x2F\xFD''']






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

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







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[b'''\x42\x5A\x68''']






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







class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[b'''\x37\x7A\xBC\xAF\x27\x1C''']






     @staticmethod
     def  a_					(			__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 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ):
     UpperCAmelCase 					=				[b'''\x04\x22\x4D\x18''']






     @staticmethod
     def  a_					(			__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 						__SCREAMING_SNAKE_CASE					:
     #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
     UpperCAmelCase 					=				{
         "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		)       ->    str:
          return max(
              len(__UpperCamelCase		)
              for extractor in cls.extractors.values()
              if issubclass(__UpperCamelCase     ,							__UpperCamelCase		)
              for extractor_magic_number in extractor.magic_numbers		)






     @staticmethod
     def  a_					(			__UpperCamelCase     ,							__UpperCamelCase		)       ->    List[Any]:
          try:
               return MagicNumberBaseExtractor.read_magic_number(__UpperCamelCase     ,							magic_number_length=__UpperCamelCase		)
          except OSError:
               return b""






     @classmethod
     def  a_					(			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     ,							)
          _a						=		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  a_					(			cls     ,							__UpperCamelCase		)       ->    str:  # <Added version="2.4.0"/>
          _a						=		cls._get_magic_number_max_length()
          _a						=		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  a_					(			cls     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase = None     ,							__UpperCamelCase = "deprecated"     ,							)       ->    None:
          os.makedirs(os.path.dirname(__UpperCamelCase		)     ,							exist_ok=__UpperCamelCase		)
          # Prevent parallel extractions
          _a						=		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     ,							)
                         _a						=		extractor if extractor != "deprecated" else extractor_format
                    else:
                         _a						=		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		)

