

'''simple docstring'''





import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
				import torch

				from transformers import (
				    MODEL_MAPPING,
				    SegformerForImageClassification,
				    SegformerForSemanticSegmentation,
				    SegformerModel,
				)
				from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import SegformerImageProcessor


class  UpperCAmelCase (							UpperCAmelCase__    ):

		'''simple docstring'''






		def 			UpperCamelCase(					self		)  ->     Dict:






							'''simple docstring'''



							lowerCamelCase_  				=      self.config_class(**self.inputs_dict		)
							self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_   ,			'hidden_sizes'		)		)
							self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_   ,			'num_attention_heads'		)		)
							self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_   ,			'num_encoder_blocks'		)		)


class  UpperCAmelCase :

		'''simple docstring'''






		def __init__(					self   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_=13   ,			SCREAMING_SNAKE_CASE_=64   ,			SCREAMING_SNAKE_CASE_=3   ,			SCREAMING_SNAKE_CASE_=4   ,			SCREAMING_SNAKE_CASE_=[2, 2, 2, 2]   ,			SCREAMING_SNAKE_CASE_=[8, 4, 2, 1]   ,			SCREAMING_SNAKE_CASE_=[16, 32, 64, 128]   ,			SCREAMING_SNAKE_CASE_=[1, 4, 8, 16]   ,			SCREAMING_SNAKE_CASE_=[1, 2, 4, 8]   ,			SCREAMING_SNAKE_CASE_=True   ,			SCREAMING_SNAKE_CASE_=True   ,			SCREAMING_SNAKE_CASE_="gelu"   ,			SCREAMING_SNAKE_CASE_=0.1   ,			SCREAMING_SNAKE_CASE_=0.1   ,			SCREAMING_SNAKE_CASE_=0.02   ,			SCREAMING_SNAKE_CASE_=3   ,			SCREAMING_SNAKE_CASE_=None   ,			)  ->     str:






							'''simple docstring'''



							lowerCamelCase_  				=      parent
							lowerCamelCase_  				=      batch_size
							lowerCamelCase_  				=      image_size
							lowerCamelCase_  				=      num_channels
							lowerCamelCase_  				=      num_encoder_blocks
							lowerCamelCase_  				=      sr_ratios
							lowerCamelCase_  				=      depths
							lowerCamelCase_  				=      hidden_sizes
							lowerCamelCase_  				=      downsampling_rates
							lowerCamelCase_  				=      num_attention_heads
							lowerCamelCase_  				=      is_training
							lowerCamelCase_  				=      use_labels
							lowerCamelCase_  				=      hidden_act
							lowerCamelCase_  				=      hidden_dropout_prob
							lowerCamelCase_  				=      attention_probs_dropout_prob
							lowerCamelCase_  				=      initializer_range
							lowerCamelCase_  				=      num_labels
							lowerCamelCase_  				=      scope
		def 			UpperCamelCase(					self		)  ->     str:






							'''simple docstring'''



							lowerCamelCase_  				=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

							lowerCamelCase_  				=      None
							if self.use_labels:
												lowerCamelCase_  				=      ids_tensor([self.batch_size, self.image_size, self.image_size]   ,			self.num_labels		)

							lowerCamelCase_  				=      self.get_config()
							return config, pixel_values, labels
		def 			UpperCamelCase(					self		)  ->     int:






							'''simple docstring'''



							return SegformerConfig(
							    image_size=self.image_size   ,			num_channels=self.num_channels   ,			num_encoder_blocks=self.num_encoder_blocks   ,			depths=self.depths   ,			hidden_sizes=self.hidden_sizes   ,			num_attention_heads=self.num_attention_heads   ,			hidden_act=self.hidden_act   ,			hidden_dropout_prob=self.hidden_dropout_prob   ,			attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,			initializer_range=self.initializer_range   ,			)
		def 			UpperCamelCase(					self   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)  ->     Any:






							'''simple docstring'''



							lowerCamelCase_  				=      SegformerModel(config=SCREAMING_SNAKE_CASE_		)
							model.to(SCREAMING_SNAKE_CASE_		)
							model.eval()
							lowerCamelCase_  				=      model(SCREAMING_SNAKE_CASE_		)
							lowerCamelCase_  				=      lowerCamelCase_  				=      self.image_size // (self.downsampling_rates[-1] * 2)
							self.parent.assertEqual(
							    result.last_hidden_state.shape   ,			(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)		)
		def 			UpperCamelCase(					self   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)  ->     Dict:






							'''simple docstring'''



							lowerCamelCase_  				=      self.num_labels
							lowerCamelCase_  				=      SegformerForSemanticSegmentation(SCREAMING_SNAKE_CASE_		)
							model.to(SCREAMING_SNAKE_CASE_		)
							model.eval()
							lowerCamelCase_  				=      model(SCREAMING_SNAKE_CASE_		)
							self.parent.assertEqual(
							    result.logits.shape   ,			(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)		)
							lowerCamelCase_  				=      model(SCREAMING_SNAKE_CASE_   ,			labels=SCREAMING_SNAKE_CASE_		)
							self.parent.assertEqual(
							    result.logits.shape   ,			(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)		)
							self.parent.assertGreater(result.loss   ,			0.0		)
		def 			UpperCamelCase(					self   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)  ->     int:






							'''simple docstring'''



							lowerCamelCase_  				=      1
							lowerCamelCase_  				=      SegformerForSemanticSegmentation(config=SCREAMING_SNAKE_CASE_		)
							model.to(SCREAMING_SNAKE_CASE_		)
							model.eval()
							lowerCamelCase_  				=      torch.randint(0   ,			1   ,			(self.batch_size, self.image_size, self.image_size)		).to(SCREAMING_SNAKE_CASE_		)
							lowerCamelCase_  				=      model(SCREAMING_SNAKE_CASE_   ,			labels=SCREAMING_SNAKE_CASE_		)
							self.parent.assertGreater(result.loss   ,			0.0		)






		def 			UpperCamelCase(					self		)  ->     Any:






							'''simple docstring'''



							lowerCamelCase_  				=      self.prepare_config_and_inputs()
							lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_  				=      config_and_inputs
							lowerCamelCase_  				=      {'pixel_values': pixel_values}
							return config, inputs_dict


@require_torch
class  UpperCAmelCase (							UpperCAmelCase__  , UpperCAmelCase__  , unittest.TestCase    ):

		'''simple docstring'''






		SCREAMING_SNAKE_CASE_           =					(
		    (
		        SegformerModel,
		        SegformerForSemanticSegmentation,
		        SegformerForImageClassification,
		    )
		    if is_torch_available()
		    else ()
		)
		SCREAMING_SNAKE_CASE_           =					(
		    {
		        'feature-extraction': SegformerModel,
		        'image-classification': SegformerForImageClassification,
		        'image-segmentation': SegformerForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		SCREAMING_SNAKE_CASE_           =					True
		SCREAMING_SNAKE_CASE_           =					False
		SCREAMING_SNAKE_CASE_           =					False
		SCREAMING_SNAKE_CASE_           =					False
		def 			UpperCamelCase(					self		)  ->     Optional[int]:






							'''simple docstring'''



							lowerCamelCase_  				=      SegformerModelTester(self		)
							lowerCamelCase_  				=      SegformerConfigTester(self   ,			config_class=SCREAMING_SNAKE_CASE_		)
		def 			UpperCamelCase(					self		)  ->     Union[str, Any]:






							'''simple docstring'''



							self.config_tester.run_common_tests()
		def 			UpperCamelCase(					self		)  ->     Optional[int]:






							'''simple docstring'''



							lowerCamelCase_  				=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_		)
		def 			UpperCamelCase(					self		)  ->     Optional[Any]:






							'''simple docstring'''



							lowerCamelCase_  				=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_binary_image_segmentation(*SCREAMING_SNAKE_CASE_		)
		def 			UpperCamelCase(					self		)  ->     List[Any]:






							'''simple docstring'''



							lowerCamelCase_  				=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_segmentation(*SCREAMING_SNAKE_CASE_		)
		@unittest.skip('SegFormer does not use inputs_embeds'		)
		def 			UpperCamelCase(					self		)  ->     Optional[int]:






							'''simple docstring'''



							pass
		@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'		)
		def 			UpperCamelCase(					self		)  ->     List[Any]:






							'''simple docstring'''



							pass
		def 			UpperCamelCase(					self		)  ->     Optional[int]:






							'''simple docstring'''



							lowerCamelCase_				,lowerCamelCase_  				=      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												lowerCamelCase_  				=      model_class(SCREAMING_SNAKE_CASE_		)
												lowerCamelCase_  				=      inspect.signature(model.forward		)
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												lowerCamelCase_  				=      [*signature.parameters.keys()]

												lowerCamelCase_  				=      ['pixel_values']
												self.assertListEqual(arg_names[:1]   ,			SCREAMING_SNAKE_CASE_		)
		def 			UpperCamelCase(					self		)  ->     str:






							'''simple docstring'''



							lowerCamelCase_				,lowerCamelCase_  				=      self.model_tester.prepare_config_and_inputs_for_common()
							lowerCamelCase_  				=      True

							for model_class in self.all_model_classes:
												lowerCamelCase_  				=      True
												lowerCamelCase_  				=      False
												lowerCamelCase_  				=      True
												lowerCamelCase_  				=      model_class(SCREAMING_SNAKE_CASE_		)
												model.to(SCREAMING_SNAKE_CASE_		)
												model.eval()
												with torch.no_grad():
																	lowerCamelCase_  				=      model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)		)
												lowerCamelCase_  				=      outputs.attentions

												lowerCamelCase_  				=      sum(self.model_tester.depths		)
												self.assertEqual(len(SCREAMING_SNAKE_CASE_		)   ,			SCREAMING_SNAKE_CASE_		)

												# check that output_attentions also work using config
												del inputs_dict["output_attentions"]
												lowerCamelCase_  				=      True
												lowerCamelCase_  				=      model_class(SCREAMING_SNAKE_CASE_		)
												model.to(SCREAMING_SNAKE_CASE_		)
												model.eval()
												with torch.no_grad():
																	lowerCamelCase_  				=      model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)		)
												lowerCamelCase_  				=      outputs.attentions

												self.assertEqual(len(SCREAMING_SNAKE_CASE_		)   ,			SCREAMING_SNAKE_CASE_		)

												# verify the first attentions (first block, first layer)
												lowerCamelCase_  				=      (self.model_tester.image_size // 4) ** 2
												lowerCamelCase_  				=      (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
												self.assertListEqual(
												    list(attentions[0].shape[-3:]		)   ,			[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]   ,			)

												# verify the last attentions (last block, last layer)
												lowerCamelCase_  				=      (self.model_tester.image_size // 32) ** 2
												lowerCamelCase_  				=      (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
												self.assertListEqual(
												    list(attentions[-1].shape[-3:]		)   ,			[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]   ,			)
												lowerCamelCase_  				=      len(SCREAMING_SNAKE_CASE_		)

												# Check attention is always last and order is fine
												lowerCamelCase_  				=      True
												lowerCamelCase_  				=      True
												lowerCamelCase_  				=      model_class(SCREAMING_SNAKE_CASE_		)
												model.to(SCREAMING_SNAKE_CASE_		)
												model.eval()
												with torch.no_grad():
																	lowerCamelCase_  				=      model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)		)

												self.assertEqual(out_len + 1   ,			len(SCREAMING_SNAKE_CASE_		)		)

												lowerCamelCase_  				=      outputs.attentions

												self.assertEqual(len(SCREAMING_SNAKE_CASE_		)   ,			SCREAMING_SNAKE_CASE_		)
												# verify the first attentions (first block, first layer)
												lowerCamelCase_  				=      (self.model_tester.image_size // 4) ** 2
												lowerCamelCase_  				=      (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
												self.assertListEqual(
												    list(self_attentions[0].shape[-3:]		)   ,			[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]   ,			)
		def 			UpperCamelCase(					self		)  ->     str:






							'''simple docstring'''



							def check_hidden_states_output(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		):
												lowerCamelCase_  				=      model_class(SCREAMING_SNAKE_CASE_		)
												model.to(SCREAMING_SNAKE_CASE_		)
												model.eval()

												with torch.no_grad():
																	lowerCamelCase_  				=      model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)		)

												lowerCamelCase_  				=      outputs.hidden_states

												lowerCamelCase_  				=      self.model_tester.num_encoder_blocks
												self.assertEqual(len(SCREAMING_SNAKE_CASE_		)   ,			SCREAMING_SNAKE_CASE_		)

												# verify the first hidden states (first block)
												self.assertListEqual(
												    list(hidden_states[0].shape[-3:]		)   ,			[
												        self.model_tester.hidden_sizes[0],
												        self.model_tester.image_size // 4,
												        self.model_tester.image_size // 4,
												    ]   ,			)

							lowerCamelCase_				,lowerCamelCase_  				=      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												lowerCamelCase_  				=      True
												check_hidden_states_output(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												lowerCamelCase_  				=      True

												check_hidden_states_output(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)
		def 			UpperCamelCase(					self		)  ->     Tuple:






							'''simple docstring'''



							if not self.model_tester.is_training:
												return

							lowerCamelCase_				,lowerCamelCase_  				=      self.model_tester.prepare_config_and_inputs_for_common()
							lowerCamelCase_  				=      True

							for model_class in self.all_model_classes:
												if model_class in get_values(SCREAMING_SNAKE_CASE_		):
																	continue

												lowerCamelCase_  				=      model_class(SCREAMING_SNAKE_CASE_		)
												model.to(SCREAMING_SNAKE_CASE_		)
												model.train()
												lowerCamelCase_  				=      self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			return_labels=SCREAMING_SNAKE_CASE_		)
												lowerCamelCase_  				=      model(**SCREAMING_SNAKE_CASE_		).loss
												loss.backward()
		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'		)
		def 			UpperCamelCase(					self		)  ->     str:






							'''simple docstring'''



							pass






		@slow
		def 			UpperCamelCase(					self		)  ->     str:






							'''simple docstring'''



							for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												lowerCamelCase_  				=      SegformerModel.from_pretrained(SCREAMING_SNAKE_CASE_		)
												self.assertIsNotNone(SCREAMING_SNAKE_CASE_		)







def   _UpperCamelCase	(		)       ->			Optional[Any]:
					lowerCamelCase_  				=      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
					return image







@require_torch
class  UpperCAmelCase (							unittest.TestCase    ):

		'''simple docstring'''






		@slow
		def 			UpperCamelCase(					self		)  ->     int:






							'''simple docstring'''



							lowerCamelCase_  				=      SegformerImageProcessor(
							    image_scale=(512, 512)   ,			keep_ratio=SCREAMING_SNAKE_CASE_   ,			align=SCREAMING_SNAKE_CASE_   ,			do_random_crop=SCREAMING_SNAKE_CASE_		)
							lowerCamelCase_  				=      SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'		).to(
							    SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      prepare_img()
							lowerCamelCase_  				=      image_processor(images=SCREAMING_SNAKE_CASE_   ,			return_tensors='pt'		)
							lowerCamelCase_  				=      encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_		)

							with torch.no_grad():
												lowerCamelCase_  				=      model(SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      torch.Size((1, model.config.num_labels, 128, 128)		)
							self.assertEqual(outputs.logits.shape   ,			SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      torch.tensor(
							    [
							        [[-4.6_310, -5.5_232, -6.2_356], [-5.1_921, -6.1_444, -6.5_996], [-5.4_424, -6.2_790, -6.7_574]],
							        [[-12.1_391, -13.3_122, -13.9_554], [-12.8_732, -13.9_352, -14.3_563], [-12.9_438, -13.8_226, -14.2_513]],
							        [[-12.5_134, -13.4_686, -14.4_915], [-12.8_669, -14.4_343, -14.7_758], [-13.2_523, -14.5_819, -15.0_694]],
							    ]		).to(SCREAMING_SNAKE_CASE_		)
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]   ,			SCREAMING_SNAKE_CASE_   ,			atol=1E-4		)		)
		@slow
		def 			UpperCamelCase(					self		)  ->     List[Any]:






							'''simple docstring'''



							lowerCamelCase_  				=      SegformerImageProcessor(
							    image_scale=(512, 512)   ,			keep_ratio=SCREAMING_SNAKE_CASE_   ,			align=SCREAMING_SNAKE_CASE_   ,			do_random_crop=SCREAMING_SNAKE_CASE_		)
							lowerCamelCase_  				=      SegformerForSemanticSegmentation.from_pretrained(
							    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'		).to(SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      prepare_img()
							lowerCamelCase_  				=      image_processor(images=SCREAMING_SNAKE_CASE_   ,			return_tensors='pt'		)
							lowerCamelCase_  				=      encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_		)

							with torch.no_grad():
												lowerCamelCase_  				=      model(SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      torch.Size((1, model.config.num_labels, 128, 128)		)
							self.assertEqual(outputs.logits.shape   ,			SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      torch.tensor(
							    [
							        [[-13.5_748, -13.9_111, -12.6_500], [-14.3_500, -15.3_683, -14.2_328], [-14.7_532, -16.0_424, -15.6_087]],
							        [[-17.1_651, -15.8_725, -12.9_653], [-17.2_580, -17.3_718, -14.8_223], [-16.6_058, -16.8_783, -16.7_452]],
							        [[-3.6_456, -3.0_209, -1.4_203], [-3.0_797, -3.1_959, -2.0_000], [-1.8_757, -1.9_217, -1.6_997]],
							    ]		).to(SCREAMING_SNAKE_CASE_		)
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]   ,			SCREAMING_SNAKE_CASE_   ,			atol=1E-1		)		)






		@slow
		def 			UpperCamelCase(					self		)  ->     Optional[Any]:






							'''simple docstring'''



							lowerCamelCase_  				=      SegformerImageProcessor(
							    image_scale=(512, 512)   ,			keep_ratio=SCREAMING_SNAKE_CASE_   ,			align=SCREAMING_SNAKE_CASE_   ,			do_random_crop=SCREAMING_SNAKE_CASE_		)
							lowerCamelCase_  				=      SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'		).to(
							    SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      prepare_img()
							lowerCamelCase_  				=      image_processor(images=SCREAMING_SNAKE_CASE_   ,			return_tensors='pt'		)
							lowerCamelCase_  				=      encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_		)

							with torch.no_grad():
												lowerCamelCase_  				=      model(SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      outputs.logits.detach().cpu()

							lowerCamelCase_  				=      image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_   ,			target_sizes=[(500, 300)]		)
							lowerCamelCase_  				=      torch.Size((500, 300)		)
							self.assertEqual(segmentation[0].shape   ,			SCREAMING_SNAKE_CASE_		)

							lowerCamelCase_  				=      image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_		)
							lowerCamelCase_  				=      torch.Size((128, 128)		)
							self.assertEqual(segmentation[0].shape   ,			SCREAMING_SNAKE_CASE_		)




"""simple docstring"""




import time
from contextlib import contextmanager
from pathlib import Path

import pytest
import requests
from huggingface_hub.hf_api import HfApi, HfFolder


__lowerCAmelCase     :				str    				=    "__DUMMY_TRANSFORMERS_USER__"
__lowerCAmelCase     :				Dict    				=    "Dummy User"
__lowerCAmelCase     :				Optional[Any]    				=    "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"

__lowerCAmelCase     :				str    				=    "https://hub-ci.huggingface.co"
__lowerCAmelCase     :				int    				=    CI_HUB_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}"
__lowerCAmelCase     :				Dict    				=    CI_HUB_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
__lowerCAmelCase     :				Optional[Any]    				=    Path("~/.huggingface/hub_ci_token").expanduser()







@pytest.fixture
def 				_UpperCAmelCase		(							lowerCamelCase__  ):





		"""simple docstring"""




		monkeypatch.setattr(
		    """huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE"""      ,	lowerCamelCase__  )







@pytest.fixture
def 				_UpperCAmelCase		(							lowerCamelCase__  ):





		"""simple docstring"""




		monkeypatch.setattr("""datasets.config.HF_ENDPOINT"""      ,	lowerCamelCase__  )
		monkeypatch.setattr("""datasets.config.HUB_DATASETS_URL"""      ,	lowerCamelCase__  )







@pytest.fixture
def 				_UpperCAmelCase		(							lowerCamelCase__  ):





		"""simple docstring"""




		monkeypatch.setattr("""huggingface_hub.hf_api.HfFolder.path_token"""      ,	lowerCamelCase__  )







@pytest.fixture
def 				_UpperCAmelCase		(							lowerCamelCase__      ,	lowerCamelCase__  ):





		"""simple docstring"""




		HfFolder.save_token(lowerCamelCase__  )
		yield
		HfFolder.delete_token()







@pytest.fixture(scope="""session"""  )
def 				_UpperCAmelCase		(							):





		"""simple docstring"""




		return HfApi(endpoint=lowerCamelCase__  )







@pytest.fixture(scope="""session"""  )
def 				_UpperCAmelCase		(							lowerCamelCase__  ):





		"""simple docstring"""




		lowerCAmelCase__   = HfFolder.get_token()
		HfFolder.save_token(lowerCamelCase__  )
		yield CI_HUB_USER_TOKEN
		if previous_token is not None:
				HfFolder.save_token(lowerCamelCase__  )







@pytest.fixture
def 				_UpperCAmelCase		(							lowerCamelCase__  ):





		"""simple docstring"""




		def _cleanup_repo(lowerCamelCase__  ):
				hf_api.delete_repo(lowerCamelCase__      ,	token=lowerCamelCase__      ,	repo_type="""dataset"""  )

		return _cleanup_repo







@pytest.fixture
def 				_UpperCAmelCase		(							lowerCamelCase__  ):





		"""simple docstring"""




		@contextmanager
		def _temporary_repo(lowerCamelCase__  ):
				try:
						yield repo_id
				finally:
						cleanup_repo(lowerCamelCase__  )

		return _temporary_repo







@pytest.fixture(scope="""session"""  )
def 				_UpperCAmelCase		(							lowerCamelCase__      ,	lowerCamelCase__      ,	lowerCamelCase__  ):





		"""simple docstring"""




		lowerCAmelCase__   = f"""repo_txt_data-{int(time.time() * 10e3  )}"""
		lowerCAmelCase__   = f"""{CI_HUB_USER}/{repo_name}"""
		hf_api.create_repo(lowerCamelCase__      ,	token=lowerCamelCase__      ,	repo_type="""dataset"""      ,	private=lowerCamelCase__  )
		hf_api.upload_file(
		    token=lowerCamelCase__      ,	path_or_fileobj=str(lowerCamelCase__  )      ,	path_in_repo="""data/text_data.txt"""      ,	repo_id=lowerCamelCase__      ,	repo_type="""dataset"""      ,	)
		yield repo_id
		try:
				hf_api.delete_repo(lowerCamelCase__      ,	token=lowerCamelCase__      ,	repo_type="""dataset"""  )
		except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
				pass







@pytest.fixture()
def 				_UpperCAmelCase		(							lowerCamelCase__      ,	lowerCamelCase__      ,	lowerCamelCase__  ):





		"""simple docstring"""




		return hf_private_dataset_repo_txt_data_







@pytest.fixture(scope="""session"""  )
def 				_UpperCAmelCase		(							lowerCamelCase__      ,	lowerCamelCase__      ,	lowerCamelCase__  ):





		"""simple docstring"""




		lowerCAmelCase__   = f"""repo_zipped_txt_data-{int(time.time() * 10e3  )}"""
		lowerCAmelCase__   = f"""{CI_HUB_USER}/{repo_name}"""
		hf_api.create_repo(lowerCamelCase__      ,	token=lowerCamelCase__      ,	repo_type="""dataset"""      ,	private=lowerCamelCase__  )
		hf_api.upload_file(
		    token=lowerCamelCase__      ,	path_or_fileobj=str(lowerCamelCase__  )      ,	path_in_repo="""data.zip"""      ,	repo_id=lowerCamelCase__      ,	repo_type="""dataset"""      ,	)
		yield repo_id
		try:
				hf_api.delete_repo(lowerCamelCase__      ,	token=lowerCamelCase__      ,	repo_type="""dataset"""  )
		except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
				pass







@pytest.fixture()
def 				_UpperCAmelCase		(							lowerCamelCase__      ,	lowerCamelCase__      ,	lowerCamelCase__  ):





		"""simple docstring"""




		return hf_private_dataset_repo_zipped_txt_data_







@pytest.fixture(scope="""session"""  )
def 				_UpperCAmelCase		(							lowerCamelCase__      ,	lowerCamelCase__      ,	lowerCamelCase__  ):





		"""simple docstring"""




		lowerCAmelCase__   = f"""repo_zipped_img_data-{int(time.time() * 10e3  )}"""
		lowerCAmelCase__   = f"""{CI_HUB_USER}/{repo_name}"""
		hf_api.create_repo(lowerCamelCase__      ,	token=lowerCamelCase__      ,	repo_type="""dataset"""      ,	private=lowerCamelCase__  )
		hf_api.upload_file(
		    token=lowerCamelCase__      ,	path_or_fileobj=str(lowerCamelCase__  )      ,	path_in_repo="""data.zip"""      ,	repo_id=lowerCamelCase__      ,	repo_type="""dataset"""      ,	)
		yield repo_id
		try:
				hf_api.delete_repo(lowerCamelCase__      ,	token=lowerCamelCase__      ,	repo_type="""dataset"""  )
		except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
				pass







@pytest.fixture()
def 				_UpperCAmelCase		(							lowerCamelCase__      ,	lowerCamelCase__      ,	lowerCamelCase__  ):





		"""simple docstring"""




		return hf_private_dataset_repo_zipped_img_data_




