




import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import (
     MODEL_MAPPING,
     BeitForImageClassification,
     BeitForMaskedImageModeling,
     BeitForSemanticSegmentation,
     BeitModel,
 )
 from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 import PIL
 from PIL import Image

 from transformers import BeitImageProcessor
class 						_A :






  def __init__(  self		:     List[str]				,						_A		:     str				,						_A		:     str=100				,						_A		:     Optional[int]=13				,						_A		:     Optional[Any]=30				,						_A		:     Optional[int]=2				,						_A		:     Tuple=3				,						_A		:     Tuple=True				,						_A		:     Optional[int]=True				,						_A		:     List[Any]=32				,						_A		:     Dict=4				,						_A		:     Tuple=4				,						_A		:     Optional[Any]=37				,						_A		:     str="gelu"				,						_A		:     Optional[int]=0.1				,						_A		:     List[str]=0.1				,						_A		:     Any=10				,						_A		:     List[str]=0.02				,						_A		:     str=3				,						_A		:     Union[str, Any]=None				,						_A		:     str=[0, 1, 2, 3]				,						)		->   Optional[Any]:






       """simple docstring"""







       lowercase :       Optional[Any]       =			parent
       lowercase :       Optional[Any]       =			100
       lowercase :       int       =			batch_size
       lowercase :       List[str]       =			image_size
       lowercase :       str       =			patch_size
       lowercase :       Tuple       =			num_channels
       lowercase :       Tuple       =			is_training
       lowercase :       Union[str, Any]       =			use_labels
       lowercase :       int       =			hidden_size
       lowercase :       Any       =			num_hidden_layers
       lowercase :       str       =			num_attention_heads
       lowercase :       List[str]       =			intermediate_size
       lowercase :       Union[str, Any]       =			hidden_act
       lowercase :       Optional[int]       =			hidden_dropout_prob
       lowercase :       int       =			attention_probs_dropout_prob
       lowercase :       List[str]       =			type_sequence_label_size
       lowercase :       int       =			initializer_range
       lowercase :       List[Any]       =			scope
       lowercase :       str       =			out_indices
       lowercase :       Optional[Any]       =			num_labels

       # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
       lowercase :       List[str]       =			(image_size // patch_size) ** 2
       lowercase :       List[str]       =			num_patches + 1






  def  __a      (  self		:     int				)		->   Dict:






       """simple docstring"""







       lowercase :       List[str]       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

       lowercase :       Dict       =			None
       lowercase :       Any       =			None
       if self.use_labels:
            lowercase :       Tuple       =			ids_tensor([self.batch_size]				,						self.type_sequence_label_size				)
            lowercase :       str       =			ids_tensor([self.batch_size, self.image_size, self.image_size]				,						self.num_labels				)

       lowercase :       Optional[int]       =			self.get_config()

       return config, pixel_values, labels, pixel_labels






  def  __a      (  self		:     Optional[int]				)		->   List[str]:






       """simple docstring"""







       return BeitConfig(
           vocab_size=self.vocab_size				,						image_size=self.image_size				,						patch_size=self.patch_size				,						num_channels=self.num_channels				,						hidden_size=self.hidden_size				,						num_hidden_layers=self.num_hidden_layers				,						num_attention_heads=self.num_attention_heads				,						intermediate_size=self.intermediate_size				,						hidden_act=self.hidden_act				,						hidden_dropout_prob=self.hidden_dropout_prob				,						attention_probs_dropout_prob=self.attention_probs_dropout_prob				,						is_decoder=_A				,						initializer_range=self.initializer_range				,						out_indices=self.out_indices				,						)






  def  __a      (  self		:     Optional[Any]				,						_A		:     Tuple				,						_A		:     Optional[Any]				,						_A		:     int				,						_A		:     Any				)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       List[str]       =			BeitModel(config=_A				)
       model.to(_A				)
       model.eval()
       lowercase :       int       =			model(_A				)
       self.parent.assertEqual(result.last_hidden_state.shape				,						(self.batch_size, self.seq_length, self.hidden_size)				)






  def  __a      (  self		:     str				,						_A		:     Optional[Any]				,						_A		:     Union[str, Any]				,						_A		:     List[str]				,						_A		:     Dict				)		->   Dict:






       """simple docstring"""







       lowercase :       str       =			BeitForMaskedImageModeling(config=_A				)
       model.to(_A				)
       model.eval()
       lowercase :       int       =			model(_A				)
       self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.seq_length - 1, self.vocab_size)				)






  def  __a      (  self		:     Any				,						_A		:     Dict				,						_A		:     Any				,						_A		:     Any				,						_A		:     List[Any]				)		->   str:






       """simple docstring"""







       lowercase :       List[str]       =			self.type_sequence_label_size
       lowercase :       Tuple       =			BeitForImageClassification(_A				)
       model.to(_A				)
       model.eval()
       lowercase :       Any       =			model(_A				,						labels=_A				)
       self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.type_sequence_label_size)				)

       # test greyscale images
       lowercase :       List[str]       =			1
       lowercase :       int       =			BeitForImageClassification(_A				)
       model.to(_A				)
       model.eval()

       lowercase :       Optional[int]       =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
       lowercase :       Union[str, Any]       =			model(_A				,						labels=_A				)
       self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.type_sequence_label_size)				)






  def  __a      (  self		:     Optional[Any]				,						_A		:     Tuple				,						_A		:     Tuple				,						_A		:     List[Any]				,						_A		:     Union[str, Any]				)		->   List[Any]:






       """simple docstring"""







       lowercase :       str       =			self.num_labels
       lowercase :       Tuple       =			BeitForSemanticSegmentation(_A				)
       model.to(_A				)
       model.eval()
       lowercase :       List[Any]       =			model(_A				)
       self.parent.assertEqual(
           result.logits.shape				,						(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)				)
       lowercase :       Union[str, Any]       =			model(_A				,						labels=_A				)
       self.parent.assertEqual(
           result.logits.shape				,						(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)				)






  def  __a      (  self		:     Optional[Any]				)		->   int:






       """simple docstring"""







       lowercase :       int       =			self.prepare_config_and_inputs()
       lowercase      ,	lowercase      ,	lowercase      ,	lowercase :       List[Any]       =			config_and_inputs
       lowercase :       List[Any]       =			{'''pixel_values''': pixel_values}
       return config, inputs_dict


@require_torch
class 						_A (  _lowerCamelCase      ,       _lowerCamelCase      ,       unittest.TestCase				):
  _UpperCamelCase       :      str			=      (
      (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
      if is_torch_available()
      else ()
  )
  _UpperCamelCase       :      str			=      (
      {
          '''feature-extraction''': BeitModel,
          '''image-classification''': BeitForImageClassification,
          '''image-segmentation''': BeitForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  _UpperCamelCase       :      Union[str, Any]			=      False
  _UpperCamelCase       :      List[Any]			=      False
  _UpperCamelCase       :      Dict			=      False






  def  __a      (  self		:     Optional[int]				)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       List[str]       =			BeitModelTester(self				)
       lowercase :       str       =			ConfigTester(self				,						config_class=_A				,						has_text_modality=_A				,						hidden_size=37				)






  def  __a      (  self		:     Optional[Any]				)		->   List[str]:






       """simple docstring"""







       self.config_tester.run_common_tests()






  @unittest.skip(reason='''BEiT does not use inputs_embeds'''				)
  def  __a      (  self		:     Optional[Any]				)		->   List[str]:






       """simple docstring"""







       pass






  @require_torch_multi_gpu
  @unittest.skip(reason='''BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''				)
  def  __a      (  self		:     Union[str, Any]				)		->   Optional[int]:






       """simple docstring"""







       pass






  def  __a      (  self		:     Optional[Any]				)		->   Dict:






       """simple docstring"""







       lowercase      ,	lowercase :       Dict       =			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowercase :       List[str]       =			model_class(_A				)
            self.assertIsInstance(model.get_input_embeddings()				,						(nn.Module)				)
            lowercase :       List[str]       =			model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(_A				,						nn.Linear				)				)






  def  __a      (  self		:     List[Any]				)		->   List[Any]:






       """simple docstring"""







       lowercase      ,	lowercase :       Any       =			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowercase :       Union[str, Any]       =			model_class(_A				)
            lowercase :       List[str]       =			inspect.signature(model.forward				)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            lowercase :       List[str]       =			[*signature.parameters.keys()]

            lowercase :       Optional[int]       =			['''pixel_values''']
            self.assertListEqual(arg_names[:1]				,						_A				)






  def  __a      (  self		:     List[Any]				)		->   List[str]:






       """simple docstring"""







       lowercase :       Optional[int]       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_A				)






  def  __a      (  self		:     Union[str, Any]				)		->   Dict:






       """simple docstring"""







       lowercase :       Any       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*_A				)






  def  __a      (  self		:     Tuple				)		->   Tuple:






       """simple docstring"""







       lowercase :       int       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_A				)






  def  __a      (  self		:     Any				)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       List[Any]       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*_A				)






  def  __a      (  self		:     Optional[int]				)		->   Optional[int]:






       """simple docstring"""







       if not self.model_tester.is_training:
            return

       lowercase      ,	lowercase :       List[str]       =			self.model_tester.prepare_config_and_inputs_for_common()
       lowercase :       Tuple       =			True

       for model_class in self.all_model_classes:
            # we don't test BeitForMaskedImageModeling
            if model_class in [*get_values(_A				), BeitForMaskedImageModeling]:
                 continue

            lowercase :       List[Any]       =			model_class(_A				)
            model.to(_A				)
            model.train()
            lowercase :       Optional[Any]       =			self._prepare_for_class(_A				,						_A				,						return_labels=_A				)
            lowercase :       Any       =			model(**_A				).loss
            loss.backward()






  def  __a      (  self		:     List[str]				)		->   Any:






       """simple docstring"""







       lowercase      ,	lowercase :       Dict       =			self.model_tester.prepare_config_and_inputs_for_common()
       if not self.model_tester.is_training:
            return

       lowercase :       List[Any]       =			False
       lowercase :       Optional[int]       =			True

       for model_class in self.all_model_classes:
            # we don't test BeitForMaskedImageModeling
            if (
                model_class in [*get_values(_A				), BeitForMaskedImageModeling]
                or not model_class.supports_gradient_checkpointing
            ):
                 continue

            lowercase :       List[str]       =			model_class(_A				)
            model.gradient_checkpointing_enable()
            model.to(_A				)
            model.train()
            lowercase :       Dict       =			self._prepare_for_class(_A				,						_A				,						return_labels=_A				)
            lowercase :       Any       =			model(**_A				).loss
            loss.backward()






  def  __a      (  self		:     Union[str, Any]				)		->   Tuple:






       """simple docstring"""







       lowercase      ,	lowercase :       List[str]       =			self.model_tester.prepare_config_and_inputs_for_common()

       lowercase :       Tuple       =			_config_zero_init(_A				)
       for model_class in self.all_model_classes:
            lowercase :       int       =			model_class(config=_A				)
            for name, param in model.named_parameters():
                 # we skip lambda parameters as these require special initial values
                 # determined by config.layer_scale_init_value
                 if "lambda" in name:
                      continue
                 if param.requires_grad:
                      self.assertIn(
                          ((param.data.mean() * 1E9).round() / 1E9).item()				,						[0.0, 1.0]				,						msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""				,						)






  @slow
  def  __a      (  self		:     str				)		->   int:






       """simple docstring"""







       for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            lowercase :       Union[str, Any]       =			BeitModel.from_pretrained(_A				)
            self.assertIsNotNone(_A				)






def  snake_case(    )			->							int:





     '''simple docstring'''


     lowercase :       Dict       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
     return image



@require_torch
@require_vision
class 						_A (  unittest.TestCase				):






  @cached_property
  def  __a      (  self		:     Tuple				)		->   str:






       """simple docstring"""







       return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224'''				) if is_vision_available() else None






  @slow
  def  __a      (  self		:     Tuple				)		->   int:






       """simple docstring"""







       lowercase :       List[str]       =			BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k'''				).to(_A				)

       lowercase :       Any       =			self.default_image_processor
       lowercase :       Union[str, Any]       =			prepare_img()
       lowercase :       Optional[Any]       =			image_processor(images=_A				,						return_tensors='''pt'''				).pixel_values.to(_A				)

       # prepare bool_masked_pos
       lowercase :       List[Any]       =			torch.ones((1, 196)				,						dtype=torch.bool				).to(_A				)

       # forward pass
       with torch.no_grad():
            lowercase :       Union[str, Any]       =			model(pixel_values=_A				,						bool_masked_pos=_A				)
       lowercase :       List[Any]       =			outputs.logits

       # verify the logits
       lowercase :       Union[str, Any]       =			torch.Size((1, 196, 8_192)				)
       self.assertEqual(logits.shape				,						_A				)

       lowercase :       str       =			torch.tensor(
           [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]]				).to(_A				)

       self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]				,						_A				,						atol=1E-2				)				)






  @slow
  def  __a      (  self		:     Dict				)		->   Any:






       """simple docstring"""







       lowercase :       Any       =			BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224'''				).to(_A				)

       lowercase :       List[Any]       =			self.default_image_processor
       lowercase :       List[str]       =			prepare_img()
       lowercase :       List[Any]       =			image_processor(images=_A				,						return_tensors='''pt'''				).to(_A				)

       # forward pass
       with torch.no_grad():
            lowercase :       List[Any]       =			model(**_A				)
       lowercase :       Tuple       =			outputs.logits

       # verify the logits
       lowercase :       List[Any]       =			torch.Size((1, 1_000)				)
       self.assertEqual(logits.shape				,						_A				)

       lowercase :       str       =			torch.tensor([-1.2_385, -1.0_987, -1.0_108]				).to(_A				)

       self.assertTrue(torch.allclose(logits[0, :3]				,						_A				,						atol=1E-4				)				)

       lowercase :       List[Any]       =			281
       self.assertEqual(logits.argmax(-1				).item()				,						_A				)






  @slow
  def  __a      (  self		:     Tuple				)		->   Any:






       """simple docstring"""







       lowercase :       Optional[Any]       =			BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k'''				).to(
           _A				)

       lowercase :       str       =			self.default_image_processor
       lowercase :       List[str]       =			prepare_img()
       lowercase :       Tuple       =			image_processor(images=_A				,						return_tensors='''pt'''				).to(_A				)

       # forward pass
       with torch.no_grad():
            lowercase :       List[Any]       =			model(**_A				)
       lowercase :       Any       =			outputs.logits

       # verify the logits
       lowercase :       Optional[int]       =			torch.Size((1, 21_841)				)
       self.assertEqual(logits.shape				,						_A				)

       lowercase :       Any       =			torch.tensor([1.6_881, -0.2_787, 0.5_901]				).to(_A				)

       self.assertTrue(torch.allclose(logits[0, :3]				,						_A				,						atol=1E-4				)				)

       lowercase :       Dict       =			2_396
       self.assertEqual(logits.argmax(-1				).item()				,						_A				)






  @slow
  def  __a      (  self		:     List[Any]				)		->   int:






       """simple docstring"""







       lowercase :       Union[str, Any]       =			BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''				)
       lowercase :       Any       =			model.to(_A				)

       lowercase :       Tuple       =			BeitImageProcessor(do_resize=_A				,						size=640				,						do_center_crop=_A				)

       lowercase :       Union[str, Any]       =			load_dataset('''hf-internal-testing/fixtures_ade20k'''				,						split='''test'''				)
       lowercase :       List[str]       =			Image.open(ds[0]['''file''']				)
       lowercase :       Optional[int]       =			image_processor(images=_A				,						return_tensors='''pt'''				).to(_A				)

       # forward pass
       with torch.no_grad():
            lowercase :       Any       =			model(**_A				)
       lowercase :       Tuple       =			outputs.logits

       # verify the logits
       lowercase :       str       =			torch.Size((1, 150, 160, 160)				)
       self.assertEqual(logits.shape				,						_A				)

       lowercase :       Optional[Any]       =			version.parse(PIL.__version__				) < version.parse('''9.0.0'''				)

       if is_pillow_less_than_a:
            lowercase :       int       =			torch.tensor(
                [
                    [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]],
                    [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]],
                    [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]],
                ]				,						device=_A				,						)
       else:
            lowercase :       Dict       =			torch.tensor(
                [
                    [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]],
                    [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]],
                    [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]],
                ]				,						device=_A				,						)

       self.assertTrue(torch.allclose(logits[0, :3, :3, :3]				,						_A				,						atol=1E-4				)				)






  @slow
  def  __a      (  self		:     Dict				)		->   List[Any]:






       """simple docstring"""







       lowercase :       List[str]       =			BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''				)
       lowercase :       Any       =			model.to(_A				)

       lowercase :       Optional[Any]       =			BeitImageProcessor(do_resize=_A				,						size=640				,						do_center_crop=_A				)

       lowercase :       Any       =			load_dataset('''hf-internal-testing/fixtures_ade20k'''				,						split='''test'''				)
       lowercase :       Dict       =			Image.open(ds[0]['''file''']				)
       lowercase :       List[str]       =			image_processor(images=_A				,						return_tensors='''pt'''				).to(_A				)

       # forward pass
       with torch.no_grad():
            lowercase :       Optional[int]       =			model(**_A				)

       lowercase :       List[Any]       =			outputs.logits.detach().cpu()

       lowercase :       Optional[int]       =			image_processor.post_process_semantic_segmentation(outputs=_A				,						target_sizes=[(500, 300)]				)
       lowercase :       Union[str, Any]       =			torch.Size((500, 300)				)
       self.assertEqual(segmentation[0].shape				,						_A				)

       lowercase :       Optional[int]       =			image_processor.post_process_semantic_segmentation(outputs=_A				)
       lowercase :       Any       =			torch.Size((160, 160)				)
       self.assertEqual(segmentation[0].shape				,						_A				)





import os
from pathlib import Path
from unittest.mock import patch

import pytest
import zstandard as zstd

from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
    OfflineModeIsEnabled,
    cached_path,
    fsspec_get,
    fsspec_head,
    ftp_get,
    ftp_head,
    get_from_cache,
    http_get,
    http_head,
)


lowerCAmelCase_						=			'\\n    Text data.\n    Second line of data.'

lowerCAmelCase_						=			'file'






@pytest.fixture(scope='''session'''   )
def  snake_case(    __magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       Any       =			tmp_path_factory.mktemp('''data'''   ) / (FILE_PATH + '''.zstd''')
     lowercase :       List[Any]       =			bytes(__magic_name__			,		'''utf-8'''   )
     with zstd.open(__magic_name__			,		'''wb'''   ) as f:
          f.write(__magic_name__   )
     return path






@pytest.fixture
def  snake_case(    __magic_name__   )			->							List[Any]:





     '''simple docstring'''


     with open(os.path.join(tmpfs.local_root_dir			,		__magic_name__   )			,		'''w'''   ) as f:
          f.write(__magic_name__   )
     return FILE_PATH






@pytest.mark.parametrize('''compression_format'''			,		['''gzip''', '''xz''', '''zstd''']   )
def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       Optional[int]       =			{'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
     lowercase :       int       =			input_paths[compression_format]
     lowercase :       Any       =			tmp_path / '''cache'''
     lowercase :       int       =			DownloadConfig(cache_dir=__magic_name__			,		extract_compressed_file=__magic_name__   )
     lowercase :       Optional[Any]       =			cached_path(__magic_name__			,		download_config=__magic_name__   )
     with open(__magic_name__   ) as f:
          lowercase :       Optional[int]       =			f.read()
     with open(__magic_name__   ) as f:
          lowercase :       str       =			f.read()
     assert extracted_file_content == expected_file_content






@pytest.mark.parametrize('''default_extracted'''			,		[True, False]   )
@pytest.mark.parametrize('''default_cache_dir'''			,		[True, False]   )
def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       Dict       =			'''custom_cache'''
     lowercase :       Union[str, Any]       =			'''custom_extracted_dir'''
     lowercase :       str       =			tmp_path / '''custom_extracted_path'''
     if default_extracted:
          lowercase :       Tuple       =			('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
     else:
          monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR'''			,		__magic_name__   )
          monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH'''			,		str(__magic_name__   )   )
          lowercase :       int       =			custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)

     lowercase :       List[str]       =			xz_file
     lowercase :       Any       =			(
         DownloadConfig(extract_compressed_file=__magic_name__   )
         if default_cache_dir
         else DownloadConfig(cache_dir=tmp_path / custom_cache_dir			,		extract_compressed_file=__magic_name__   )
     )
     lowercase :       Optional[int]       =			cached_path(__magic_name__			,		download_config=__magic_name__   )
     assert Path(__magic_name__   ).parent.parts[-2:] == expected






def  snake_case(    __magic_name__   )			->							List[Any]:





     '''simple docstring'''


     lowercase :       Any       =			str(Path(__magic_name__   ).resolve()   )
     assert cached_path(__magic_name__   ) == text_file
     # relative path
     lowercase :       Union[str, Any]       =			str(Path(__magic_name__   ).resolve().relative_to(Path(os.getcwd()   )   )   )
     assert cached_path(__magic_name__   ) == text_file






def  snake_case(    __magic_name__   )			->							Union[str, Any]:





     '''simple docstring'''


     lowercase :       List[Any]       =			str(tmp_path.resolve() / '''__missing_file__.txt'''   )
     with pytest.raises(__magic_name__   ):
          cached_path(__magic_name__   )
     # relative path
     lowercase :       Optional[int]       =			'''./__missing_file__.txt'''
     with pytest.raises(__magic_name__   ):
          cached_path(__magic_name__   )






def  snake_case(    __magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       List[str]       =			get_from_cache(F"""tmp://{tmpfs_file}"""   )
     with open(__magic_name__   ) as f:
          lowercase :       List[Any]       =			f.read()
     assert output_file_content == FILE_CONTENT






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    )			->							List[Any]:





     '''simple docstring'''


     with pytest.raises(__magic_name__   ):
          cached_path('''https://huggingface.co'''   )






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    __magic_name__   )			->							Tuple:





     '''simple docstring'''


     lowercase :       Any       =			tmp_path_factory.mktemp('''data'''   ) / '''file.html'''
     with pytest.raises(__magic_name__   ):
          http_get('''https://huggingface.co'''			,		temp_file=__magic_name__   )
     with pytest.raises(__magic_name__   ):
          http_head('''https://huggingface.co'''   )






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    __magic_name__   )			->							Optional[Any]:





     '''simple docstring'''


     lowercase :       Optional[Any]       =			tmp_path_factory.mktemp('''data'''   ) / '''file.html'''
     with pytest.raises(__magic_name__   ):
          ftp_get('''ftp://huggingface.co'''			,		temp_file=__magic_name__   )
     with pytest.raises(__magic_name__   ):
          ftp_head('''ftp://huggingface.co'''   )






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    __magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       str       =			tmp_path_factory.mktemp('''data'''   ) / '''file.html'''
     with pytest.raises(__magic_name__   ):
          fsspec_get('''s3://huggingface.co'''			,		temp_file=__magic_name__   )
     with pytest.raises(__magic_name__   ):
          fsspec_head('''s3://huggingface.co'''   )