

import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
  from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder
def   a   (    A__			:     List[Any]   ,     A__			:     List[str]   ,     A__			:     List[Any]   ,     A__			:     Tuple=None   ,     A__			:     Dict=None   ,     A__			:     int=None   ,     A__			:     List[Any]=None   ,     A__			:     int=None   ,     )					->   List[Any]:





      """simple docstring"""



      if attention_mask is None:
            _lowercase			 =input_ids.ne(config.pad_token_id  )
      if decoder_attention_mask is None:
            _lowercase			 =decoder_input_ids.ne(config.pad_token_id  )
      if head_mask is None:
            _lowercase			 =torch.ones(config.encoder_layers   ,     config.encoder_attention_heads   ,     device=A__  )
      if decoder_head_mask is None:
            _lowercase			 =torch.ones(config.decoder_layers   ,     config.decoder_attention_heads   ,     device=A__  )
      if cross_attn_head_mask is None:
            _lowercase			 =torch.ones(config.decoder_layers   ,     config.decoder_attention_heads   ,     device=A__  )
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": attention_mask,
          "head_mask": head_mask,
          "decoder_head_mask": decoder_head_mask,
          "cross_attn_head_mask": cross_attn_head_mask,
      }





class 				__lowerCAmelCase  :




  def __init__(       self							,     lowerCAmelCase							,     lowerCAmelCase=13							,     lowerCAmelCase=7							,     lowerCAmelCase=True							,     lowerCAmelCase=False							,     lowerCAmelCase=99							,     lowerCAmelCase=16							,     lowerCAmelCase=2							,     lowerCAmelCase=4							,     lowerCAmelCase=4							,     lowerCAmelCase="relu"							,     lowerCAmelCase=0.1							,     lowerCAmelCase=0.1							,     lowerCAmelCase=0.0							,     lowerCAmelCase=0.0							,     lowerCAmelCase=20							,     lowerCAmelCase=2							,     lowerCAmelCase=1							,     lowerCAmelCase=0							,     )						->				int:
        '''simple docstring'''






        _lowercase			 =parent
        _lowercase			 =batch_size
        _lowercase			 =seq_length
        _lowercase			 =is_training
        _lowercase			 =use_labels
        _lowercase			 =vocab_size
        _lowercase			 =hidden_size
        _lowercase			 =num_hidden_layers
        _lowercase			 =num_attention_heads
        _lowercase			 =intermediate_size
        _lowercase			 =hidden_act
        _lowercase			 =hidden_dropout_prob
        _lowercase			 =attention_probs_dropout_prob
        _lowercase			 =encoder_layerdrop
        _lowercase			 =decoder_layerdrop
        _lowercase			 =max_position_embeddings
        _lowercase			 =eos_token_id
        _lowercase			 =pad_token_id
        _lowercase			 =bos_token_id




  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        _lowercase			 =ids_tensor([self.batch_size, self.seq_length]							,     self.vocab_size      )
        _lowercase			 =self.eos_token_id  # Eos Token
        _lowercase			 =ids_tensor([self.batch_size, self.seq_length]							,     self.vocab_size      )

        # we need to clamp the input ids here to avoid having pad token in between
        # this is because for M2M100 the position_ids are prepared such that
        # all pad tokens have pos id = 2 and rest are between 2..seq_length
        # and the seq_length here is seq_length - num_pad_tokens
        # but when using past, there is no way of knowing if the past input ids had
        # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
        # position_ids being off by num_pad_tokens in past input
        _lowercase			 =input_ids.clamp(self.pad_token_id + 1      )
        _lowercase			 =decoder_input_ids.clamp(self.pad_token_id + 1      )

        _lowercase			 =self.get_config()
        _lowercase			 =prepare_mam_aaa_inputs_dict(lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )
        return config, inputs_dict




  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        return MaMaaaConfig(
            vocab_size=self.vocab_size							,     d_model=self.hidden_size							,     encoder_layers=self.num_hidden_layers							,     decoder_layers=self.num_hidden_layers							,     encoder_attention_heads=self.num_attention_heads							,     decoder_attention_heads=self.num_attention_heads							,     encoder_ffn_dim=self.intermediate_size							,     decoder_ffn_dim=self.intermediate_size							,     dropout=self.hidden_dropout_prob							,     attention_dropout=self.attention_probs_dropout_prob							,     encoder_layerdrop=self.encoder_layerdrop							,     decoder_layerdrop=self.decoder_layerdrop							,     max_position_embeddings=self.max_position_embeddings							,     eos_token_id=self.eos_token_id							,     bos_token_id=self.bos_token_id							,     pad_token_id=self.pad_token_id							,     )




  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        _lowercase , _lowercase			 =self.prepare_config_and_inputs()
        return config, inputs_dict




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase      )						->				Any:
        '''simple docstring'''






        _lowercase			 =MaMaaaModel(config=lowerCAmelCase      ).get_decoder().to(lowerCAmelCase      ).eval()
        _lowercase			 =inputs_dict['input_ids']
        _lowercase			 =inputs_dict['attention_mask']
        _lowercase			 =inputs_dict['head_mask']

        # first forward pass
        _lowercase			 =model(lowerCAmelCase							,     attention_mask=lowerCAmelCase							,     head_mask=lowerCAmelCase							,     use_cache=lowerCAmelCase      )

        _lowercase , _lowercase			 =outputs.to_tuple()

        # create hypothetical multiple next token and extent to next_input_ids
        _lowercase			 =ids_tensor((self.batch_size, 3)							,     config.vocab_size      )
        _lowercase			 =ids_tensor((self.batch_size, 3)							,     2      )

        # append to next input_ids and
        _lowercase			 =torch.cat([input_ids, next_tokens]							,     dim=-1      )
        _lowercase			 =torch.cat([attention_mask, next_attn_mask]							,     dim=-1      )

        _lowercase			 =model(lowerCAmelCase							,     attention_mask=lowerCAmelCase      )['last_hidden_state']
        _lowercase			 =model(lowerCAmelCase							,     attention_mask=lowerCAmelCase							,     past_key_values=lowerCAmelCase      )[
            'last_hidden_state'
        ]

        # select random slice
        _lowercase			 =ids_tensor((1,)							,     output_from_past.shape[-1]      ).item()
        _lowercase			 =output_from_no_past[:, -3:, random_slice_idx].detach()
        _lowercase			 =output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]      )

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(lowerCAmelCase							,     lowerCAmelCase							,     atol=1e-2      )      )




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase      )						->				Union[str, Any]:
        '''simple docstring'''






        _lowercase			 =MaMaaaModel(config=lowerCAmelCase      ).to(lowerCAmelCase      ).eval()
        _lowercase			 =model(**lowerCAmelCase      )

        _lowercase			 =outputs.encoder_last_hidden_state
        _lowercase			 =outputs.last_hidden_state

        with tempfile.TemporaryDirectory() as tmpdirname:
              _lowercase			 =model.get_encoder()
              encoder.save_pretrained(lowerCAmelCase      )
              _lowercase			 =MaMaaaEncoder.from_pretrained(lowerCAmelCase      ).to(lowerCAmelCase      )

        _lowercase			 =encoder(inputs_dict['input_ids']							,     attention_mask=inputs_dict['attention_mask']      )[
            0
        ]

        self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3      )

        with tempfile.TemporaryDirectory() as tmpdirname:
              _lowercase			 =model.get_decoder()
              decoder.save_pretrained(lowerCAmelCase      )
              _lowercase			 =MaMaaaDecoder.from_pretrained(lowerCAmelCase      ).to(lowerCAmelCase      )

        _lowercase			 =decoder(
            input_ids=inputs_dict['decoder_input_ids']							,     attention_mask=inputs_dict['decoder_attention_mask']							,     encoder_hidden_states=lowerCAmelCase							,     encoder_attention_mask=inputs_dict['attention_mask']							,     )[0]

        self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3      )





@require_torch
class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE    ,    SCREAMING_SNAKE_CASE    ,    SCREAMING_SNAKE_CASE    ,    unittest.TestCase							):
  _a		    =						(
      (
          MaMaaaModel,
          MaMaaaForConditionalGeneration,
      )
      if is_torch_available()
      else ()
  )
  _a		    =						(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
  _a		    =						(
      {
          """conversational""": MaMaaaForConditionalGeneration,
          """feature-extraction""": MaMaaaModel,
          """summarization""": MaMaaaForConditionalGeneration,
          """text2text-generation""": MaMaaaForConditionalGeneration,
          """translation""": MaMaaaForConditionalGeneration,
      }
      if is_torch_available()
      else {}
  )
  _a		    =						True
  _a		    =						True
  _a		    =						False
  _a		    =						False




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )						->				Any:
        '''simple docstring'''






        if pipeline_test_casse_name == "TranslationPipelineTests":
              # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
              # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
              return True

        return False




  def 						A__  (       self      )						->				int:
        '''simple docstring'''






        _lowercase			 =MaMaaaModelTester(self      )
        _lowercase			 =ConfigTester(self							,     config_class=lowerCAmelCase      )




  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        self.config_tester.run_common_tests()




  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        _lowercase , _lowercase			 =self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
              _lowercase			 =model_class(lowerCAmelCase      )

              with tempfile.TemporaryDirectory() as tmpdirname:
                    model.save_pretrained(lowerCAmelCase      )
                    _lowercase , _lowercase			 =model_class.from_pretrained(lowerCAmelCase							,     output_loading_info=lowerCAmelCase      )
              self.assertEqual(info['missing_keys']							,     []      )




  def 						A__  (       self      )						->				Tuple:
        '''simple docstring'''






        _lowercase			 =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCAmelCase      )




  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        _lowercase			 =self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.check_encoder_decoder_model_standalone(*lowerCAmelCase      )




  def 						A__  (       self      )						->				Tuple:
        '''simple docstring'''






        _lowercase , _lowercase			 =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
              _lowercase			 =model_class(lowerCAmelCase      )
              model.to(lowerCAmelCase      )
              model.eval()

              _lowercase			 =copy.deepcopy(self._prepare_for_class(lowerCAmelCase							,     lowerCAmelCase      )      )

              if not self.is_encoder_decoder:
                    _lowercase			 =inputs['input_ids']
                    del inputs["input_ids"]
              else:
                    _lowercase			 =inputs['input_ids']
                    _lowercase			 =inputs.get('decoder_input_ids'							,     lowerCAmelCase      )
                    del inputs["input_ids"]
                    inputs.pop('decoder_input_ids'							,     lowerCAmelCase      )

              _lowercase			 =model.get_input_embeddings()
              if not self.is_encoder_decoder:
                    _lowercase			 =wte(lowerCAmelCase      )
              else:
                    _lowercase			 =wte(lowerCAmelCase      )
                    _lowercase			 =wte(lowerCAmelCase      )

              with torch.no_grad():
                    model(**lowerCAmelCase      )[0]




  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        _lowercase , _lowercase			 =self.model_tester.prepare_config_and_inputs()
        _lowercase			 =input_dict['input_ids']
        _lowercase			 =input_ids.ne(1      ).to(lowerCAmelCase      )
        _lowercase			 =MaMaaaForConditionalGeneration(lowerCAmelCase      ).eval().to(lowerCAmelCase      )
        if torch_device == "cuda":
              model.half()
        model.generate(lowerCAmelCase							,     attention_mask=lowerCAmelCase      )
        model.generate(num_beams=4							,     do_sample=lowerCAmelCase							,     early_stopping=lowerCAmelCase							,     num_return_sequences=3      )
def   a   (    A__			:     List[Any]  )					->   int:





      """simple docstring"""



      return torch.tensor(A__   ,     dtype=torch.long   ,     device=A__  )


lowercase_             =     1e-4







@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 				__lowerCAmelCase  (      unittest.TestCase							):




  @cached_property
  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'      )




  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        _lowercase			 =MaMaaaModel.from_pretrained('facebook/m2m100_418M'      ).to(lowerCAmelCase      )
        _lowercase			 =_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]      )
        _lowercase			 =_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]      )
        _lowercase			 =prepare_mam_aaa_inputs_dict(model.config							,     lowerCAmelCase							,     lowerCAmelCase      )
        with torch.no_grad():
              _lowercase			 =model(**lowerCAmelCase      )[0]
        _lowercase			 =torch.Size((1, 11, 1_024)      )
        self.assertEqual(output.shape							,     lowerCAmelCase      )
        # change to expected output here
        _lowercase			 =torch.tensor(
            [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]							,     device=lowerCAmelCase      )
        self.assertTrue(torch.allclose(output[:, :3, :3]							,     lowerCAmelCase							,     atol=lowerCAmelCase      )      )




  def 						A__  (       self      )						->				List[Any]:
        '''simple docstring'''






        _lowercase			 =MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'      ).to(lowerCAmelCase      )

        # change to intended input
        _lowercase			 =_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]      )
        _lowercase			 =_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]      )
        _lowercase			 =prepare_mam_aaa_inputs_dict(model.config							,     lowerCAmelCase							,     lowerCAmelCase      )
        with torch.no_grad():
              _lowercase			 =model(**lowerCAmelCase      )[0]
        _lowercase			 =torch.Size((1, 11, model.config.vocab_size)      )
        self.assertEqual(output.shape							,     lowerCAmelCase      )
        # change to expected output here
        _lowercase			 =torch.tensor(
            [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]							,     device=lowerCAmelCase      )
        self.assertTrue(torch.allclose(output[:, :3, :3]							,     lowerCAmelCase							,     atol=lowerCAmelCase      )      )




  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        _lowercase			 =MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'      ).to(lowerCAmelCase      )
        _lowercase			 =MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'							,     src_lang='fr'							,     tgt_lang='en'      )

        _lowercase			 =[
            'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
            'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
            'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
            ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
            ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
        ]

        # The below article tests that we don't add any hypotheses outside of the top n_beams
        _lowercase			 =tokenizer(lowerCAmelCase							,     padding=lowerCAmelCase							,     return_tensors='pt'      )

        _lowercase			 =model.generate(
            input_ids=dct['input_ids'].to(lowerCAmelCase      )							,     attention_mask=dct['attention_mask'].to(lowerCAmelCase      )							,     num_beams=5							,     forced_bos_token_id=tokenizer.get_lang_id('en'      )							,     )

        _lowercase			 =[
            'The NSA case highlights the total absence of intelligence debate',
            'I think there are two levels of response from the French government.',
            'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
            ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
            ' communications in France.',
        ]

        _lowercase			 =tokenizer.batch_decode(
            hypotheses_batch.tolist()							,     clean_up_tokenization_spaces=lowerCAmelCase							,     skip_special_tokens=lowerCAmelCase      )
        assert generated == expected_en





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 				__lowerCAmelCase  :




  def __init__(       self							,     lowerCAmelCase = None      )						->				str:
        '''simple docstring'''






        _lowercase			 =(
            os.path.join(lowerCAmelCase							,     config.EXTRACTED_DATASETS_DIR      ) if cache_dir else config.EXTRACTED_DATASETS_PATH
        )
        _lowercase			 =Extractor




  def 						A__  (       self							,     lowerCAmelCase      )						->				str:
        '''simple docstring'''






        from .file_utils import hash_url_to_filename

        # Path where we extract compressed archives
        # We extract in the cache dir, and get the extracted path name by hashing the original path"
        _lowercase			 =os.path.abspath(lowerCAmelCase      )
        return os.path.join(self.extract_dir							,     hash_url_to_filename(lowerCAmelCase      )      )




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase      )						->				bool:
        '''simple docstring'''






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




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase = False      )						->				str:
        '''simple docstring'''






        _lowercase			 =self.extractor.infer_extractor_format(lowerCAmelCase      )
        if not extractor_format:
              return input_path
        _lowercase			 =self._get_output_path(lowerCAmelCase      )
        if self._do_extract(lowerCAmelCase							,     lowerCAmelCase      ):
              self.extractor.extract(lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase      )
        return output_path





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):




  @classmethod
  @abstractmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     **lowerCAmelCase      )						->				bool:
        '''simple docstring'''






        ...




  @staticmethod
  @abstractmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






        ...





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE    ,    SCREAMING_SNAKE_CASE							):
  _a		    =						[]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				List[Any]:
        '''simple docstring'''






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




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase = b""      )						->				bool:
        '''simple docstring'''






        if not magic_number:
              _lowercase			 =max(len(lowerCAmelCase      ) for cls_magic_number in cls.magic_numbers      )
              try:
                    _lowercase			 =cls.read_magic_number(lowerCAmelCase							,     lowerCAmelCase      )
              except OSError:
                    return False
        return any(magic_number.startswith(lowerCAmelCase      ) for cls_magic_number in cls.magic_numbers      )





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     **lowerCAmelCase      )						->				bool:
        '''simple docstring'''






        return tarfile.is_tarfile(lowerCAmelCase      )




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				List[Any]:
        '''simple docstring'''






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

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

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

        _lowercase			 =resolved(lowerCAmelCase      )

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




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






        os.makedirs(lowerCAmelCase							,     exist_ok=lowerCAmelCase      )
        _lowercase			 =tarfile.open(lowerCAmelCase      )
        tar_file.extractall(lowerCAmelCase							,     members=TarExtractor.safemembers(lowerCAmelCase							,     lowerCAmelCase      )      )
        tar_file.close()





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x1F\x8B"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[
      b"""PK\x03\x04""",
      b"""PK\x05\x06""",  # empty archive
      b"""PK\x07\x08""",  # spanned archive
  ]




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase = b""      )						->				bool:
        '''simple docstring'''






        if super().is_extractable(lowerCAmelCase							,     magic_number=lowerCAmelCase      ):
              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(lowerCAmelCase							,     'rb'      ) as fp:
                    _lowercase			 =_EndRecData(lowerCAmelCase      )
                    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:
                                      _lowercase			 =fp.read(lowerCAmelCase      )  # CD is where we expect it to be
                                      if len(lowerCAmelCase      ) == sizeCentralDir:
                                            _lowercase			 =struct.unpack(lowerCAmelCase							,     lowerCAmelCase      )  # 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__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\xFD\x37\x7A\x58\x5A\x00"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""Rar!\x1a\x07\x00""", b"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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

        os.makedirs(lowerCAmelCase							,     exist_ok=lowerCAmelCase      )
        _lowercase			 =rarfile.RarFile(lowerCAmelCase      )
        rf.extractall(lowerCAmelCase      )
        rf.close()





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x28\xb5\x2F\xFD"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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

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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x42\x5A\x68"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x37\x7A\xBC\xAF\x27\x1C"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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

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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x04\x22\x4D\x18"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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

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





class 				__lowerCAmelCase  :
  #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
  _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 						A__  (       cls      )						->				str:
        '''simple docstring'''






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




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				Optional[Any]:
        '''simple docstring'''






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




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase = False      )						->				bool:
        '''simple docstring'''






        warnings.warn(
            'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '
            'Use \'infer_extractor_format\' instead.'							,     category=lowerCAmelCase							,     )
        _lowercase			 =cls.infer_extractor_format(lowerCAmelCase      )
        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							,     lowerCAmelCase      )						->				str:  # <Added version="2.4.0"/>
        '''simple docstring'''






        _lowercase			 =cls._get_magic_number_max_length()
        _lowercase			 =cls._read_magic_number(lowerCAmelCase							,     lowerCAmelCase      )
        for extractor_format, extractor in cls.extractors.items():
              if extractor.is_extractable(lowerCAmelCase							,     magic_number=lowerCAmelCase      ):
                    return extractor_format




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase = None							,     lowerCAmelCase = "deprecated"							,     )						->				None:
        '''simple docstring'''






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


