






import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


__UpperCamelCase      :      List[str]     						=						get_logger(__name__)


class        __UpperCamelCase    :







	def __init__(  self      :							List[str]       ,				_lowerCAmelCase      :							Optional[str] = None			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  (
		    os.path.join(_lowerCAmelCase       ,				config.EXTRACTED_DATASETS_DIR			) if cache_dir else config.EXTRACTED_DATASETS_PATH
		)
		__lowercase             =  Extractor







	def  _a   (  self      :							str       ,				_lowerCAmelCase      :							str			)		-> 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      :							Optional[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							bool			)		-> 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      :							List[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							bool = 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        __UpperCamelCase    (     _lowerCAmelCase   ):







	@classmethod
	@abstractmethod
	def  _a   (  cls      :							List[str]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				**_lowerCAmelCase      :							str			)		-> bool:
		"""simple docstring"""







		...







	@staticmethod
	@abstractmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







		...


class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ):
	__snake_case	:List[bytes]   =       []







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							int			)		-> List[Any]:
		"""simple docstring"""







		with open(_lowerCAmelCase       ,				"""rb"""			) as f:
			return f.read(_lowerCAmelCase			)







	@classmethod
	def  _a   (  cls      :							Any       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							bytes = 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        __UpperCamelCase    (     _lowerCAmelCase   ):







	@classmethod
	def  _a   (  cls      :							Dict       ,				_lowerCAmelCase      :							Union[Path, str]       ,				**_lowerCAmelCase      :							str			)		-> bool:
		"""simple docstring"""







		return tarfile.is_tarfile(_lowerCAmelCase			)







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Optional[Any]			)		-> List[str]:
		"""simple docstring"""







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

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

		def badlink(_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							str			) -> 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      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:List[Any]   =       [B'\x1F\x8B']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







		with gzip.open(_lowerCAmelCase       ,				"""rb"""			) as gzip_file:
			with open(_lowerCAmelCase       ,				"""wb"""			) as extracted_file:
				shutil.copyfileobj(_lowerCAmelCase       ,				_lowerCAmelCase			)


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Dict   =       [
	    B'PK\x03\x04',
	    B'PK\x05\x06',  # empty archive
	    B'PK\x07\x08',  # spanned archive
	]







	@classmethod
	def  _a   (  cls      :							Optional[Any]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							bytes = 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      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Tuple   =       [B'\xFD\x37\x7A\x58\x5A\x00']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







		with lzma.open(_lowerCAmelCase			) as compressed_file:
			with open(_lowerCAmelCase       ,				"""wb"""			) as extracted_file:
				shutil.copyfileobj(_lowerCAmelCase       ,				_lowerCAmelCase			)


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Union[str, Any]   =       [B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Dict   =       [B'\x28\xb5\x2F\xFD']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:List[Any]   =       [B'\x42\x5A\x68']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







		with bza.open(_lowerCAmelCase       ,				"""rb"""			) as compressed_file:
			with open(_lowerCAmelCase       ,				"""wb"""			) as extracted_file:
				shutil.copyfileobj(_lowerCAmelCase       ,				_lowerCAmelCase			)


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Any   =       [B'\x37\x7A\xBC\xAF\x27\x1C']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Tuple   =       [B'\x04\x22\x4D\x18']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    :
	#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
	__snake_case	:Dict[str, Type[BaseExtractor]]   =       {
	    "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      :							Union[str, Any]			)		-> Union[str, Any]:
		"""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      :							Union[Path, str]       ,				_lowerCAmelCase      :							int			)		-> Dict:
		"""simple docstring"""







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







	@classmethod
	def  _a   (  cls      :							str       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							bool = 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      :							Optional[int]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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      :							List[str]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Optional[str] = None       ,				_lowerCAmelCase      :							Optional[BaseExtractor] = "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			)









import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import (
						    TFEfficientFormerForImageClassification,
						    TFEfficientFormerForImageClassificationWithTeacher,
						    TFEfficientFormerModel,
						)
						from transformers.models.efficientformer.modeling_tf_efficientformer import (
						    TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
						)


if is_vision_available():
						from PIL import Image

						from transformers import EfficientFormerImageProcessor


class        __UpperCamelCase    :







	def __init__(  self      :							int       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							int = 13       ,				_lowerCAmelCase      :							int = 64       ,				_lowerCAmelCase      :							int = 2       ,				_lowerCAmelCase      :							int = 3       ,				_lowerCAmelCase      :							int = 3       ,				_lowerCAmelCase      :							bool = True       ,				_lowerCAmelCase      :							bool = True       ,				_lowerCAmelCase      :							int = 128       ,				_lowerCAmelCase      :							Optional[int]=[16, 32, 64, 128]       ,				_lowerCAmelCase      :							int = 7       ,				_lowerCAmelCase      :							int = 4       ,				_lowerCAmelCase      :							int = 37       ,				_lowerCAmelCase      :							str = "gelu"       ,				_lowerCAmelCase      :							float = 0.1       ,				_lowerCAmelCase      :							float = 0.1       ,				_lowerCAmelCase      :							int = 10       ,				_lowerCAmelCase      :							float = 0.02       ,				_lowerCAmelCase      :							int = 2       ,				_lowerCAmelCase      :							int = 1       ,				_lowerCAmelCase      :							int = 128       ,				_lowerCAmelCase      :							List[int] = [2, 2, 2, 2]       ,				_lowerCAmelCase      :							int = 2       ,				_lowerCAmelCase      :							int = 2       ,				)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  parent
		__lowercase             =  batch_size
		__lowercase             =  image_size
		__lowercase             =  patch_size
		__lowercase             =  num_channels
		__lowercase             =  is_training
		__lowercase             =  use_labels
		__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             =  type_sequence_label_size
		__lowercase             =  initializer_range
		__lowercase             =  encoder_stride
		__lowercase             =  num_attention_outputs
		__lowercase             =  embed_dim
		__lowercase             =  embed_dim + 1
		__lowercase             =  resolution
		__lowercase             =  depths
		__lowercase             =  hidden_sizes
		__lowercase             =  dim
		__lowercase             =  mlp_expansion_ratio







	def  _a   (  self      :							List[Any]			)		-> Optional[int]:
		"""simple docstring"""







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

		__lowercase             =  None
		if self.use_labels:
			__lowercase             =  ids_tensor([self.batch_size]       ,				self.type_sequence_label_size			)

		__lowercase             =  self.get_config()

		return config, pixel_values, labels







	def  _a   (  self      :							Optional[Any]			)		-> str:
		"""simple docstring"""







		return EfficientFormerConfig(
		    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=_lowerCAmelCase       ,				initializer_range=self.initializer_range       ,				encoder_stride=self.encoder_stride       ,				resolution=self.resolution       ,				depths=self.depths       ,				hidden_sizes=self.hidden_sizes       ,				dim=self.dim       ,				mlp_expansion_ratio=self.mlp_expansion_ratio       ,				)







	def  _a   (  self      :							Union[str, Any]       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Optional[int]			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  TFEfficientFormerModel(config=_lowerCAmelCase			)
		__lowercase             =  model(_lowerCAmelCase       ,				training=_lowerCAmelCase			)
		self.parent.assertEqual(result.last_hidden_state.shape       ,				(self.batch_size, self.seq_length, self.hidden_size)			)







	def  _a   (  self      :							Union[str, Any]       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Dict			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  self.type_sequence_label_size
		__lowercase             =  TFEfficientFormerForImageClassification(_lowerCAmelCase			)
		__lowercase             =  model(_lowerCAmelCase       ,				labels=_lowerCAmelCase       ,				training=_lowerCAmelCase			)
		self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.type_sequence_label_size)			)

		# test greyscale images
		__lowercase             =  1
		__lowercase             =  TFEfficientFormerForImageClassification(_lowerCAmelCase			)

		__lowercase             =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
		__lowercase             =  model(_lowerCAmelCase       ,				labels=_lowerCAmelCase			)
		self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.type_sequence_label_size)			)







	def  _a   (  self      :							Optional[Any]			)		-> Any:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		__lowercase       ,						__lowercase       ,						__lowercase             =  config_and_inputs
		__lowercase             =  {"""pixel_values""": pixel_values}
		return config, inputs_dict


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:Any   =       (
	    (
	        TFEfficientFormerModel,
	        TFEfficientFormerForImageClassificationWithTeacher,
	        TFEfficientFormerForImageClassification,
	    )
	    if is_tf_available()
	    else ()
	)
	__snake_case	:Any   =       (
	    {
	        'feature-extraction': TFEfficientFormerModel,
	        'image-classification': (
	            TFEfficientFormerForImageClassification,
	            TFEfficientFormerForImageClassificationWithTeacher,
	        ),
	    }
	    if is_tf_available()
	    else {}
	)

	__snake_case	:int   =       False

	__snake_case	:Optional[int]   =       False
	__snake_case	:int   =       False
	__snake_case	:Any   =       False
	__snake_case	:Any   =       False







	def  _a   (  self      :							Tuple			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  TFEfficientFormerModelTester(self			)
		__lowercase             =  ConfigTester(
		    self       ,				config_class=_lowerCAmelCase       ,				has_text_modality=_lowerCAmelCase       ,				hidden_size=37			)







	def  _a   (  self      :							Optional[int]			)		-> int:
		"""simple docstring"""







		self.config_tester.run_common_tests()







	@unittest.skip(reason="""EfficientFormer does not use inputs_embeds"""			)
	def  _a   (  self      :							Optional[int]			)		-> Any:
		"""simple docstring"""







		pass







	@unittest.skip(reason="""EfficientFormer does not support input and output embeddings"""			)
	def  _a   (  self      :							int			)		-> str:
		"""simple docstring"""







		pass







	def  _a   (  self      :							Union[str, Any]			)		-> List[str]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

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

			__lowercase             =  ["""pixel_values"""]
			self.assertListEqual(arg_names[:1]       ,				_lowerCAmelCase			)







	def  _a   (  self      :							Union[str, Any]			)		-> Dict:
		"""simple docstring"""







		def check_hidden_states_output(_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							List[Any]			):
			__lowercase             =  model_class(_lowerCAmelCase			)

			__lowercase             =  model(**self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)       ,				training=_lowerCAmelCase			)
			__lowercase             =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

			__lowercase             =  getattr(
			    self.model_tester       ,				"""expected_num_hidden_layers"""       ,				self.model_tester.num_hidden_layers + 1			)
			self.assertEqual(len(_lowerCAmelCase			)       ,				_lowerCAmelCase			)

			if hasattr(self.model_tester       ,				"""encoder_seq_length"""			):
				__lowercase             =  self.model_tester.encoder_seq_length
				if hasattr(self.model_tester       ,				"""chunk_length"""			) and self.model_tester.chunk_length > 1:
					__lowercase             =  seq_length * self.model_tester.chunk_length
			else:
				__lowercase             =  self.model_tester.seq_length

			self.assertListEqual(
			    list(hidden_states[-1].shape[-2:]			)       ,				[seq_length, self.model_tester.hidden_size]       ,				)

			if config.is_encoder_decoder:
				__lowercase             =  outputs.decoder_hidden_states

				self.asseretIsInstance(_lowerCAmelCase       ,				(list, tuple)			)
				self.assertEqual(len(_lowerCAmelCase			)       ,				_lowerCAmelCase			)
				__lowercase             =  getattr(self.model_tester       ,				"""seq_length"""       ,				_lowerCAmelCase			)
				__lowercase             =  getattr(self.model_tester       ,				"""decoder_seq_length"""       ,				_lowerCAmelCase			)

				self.assertListEqual(
				    list(hidden_states[-1].shape[-2:]			)       ,				[decoder_seq_length, self.model_tester.hidden_size]       ,				)

		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			__lowercase             =  True
			check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)

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

			check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)







	def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Optional[Any]=False			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  super()._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase       ,				return_labels=_lowerCAmelCase			)

		if return_labels:
			if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
				del inputs_dict["labels"]

		return inputs_dict







	def  _a   (  self      :							int			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*_lowerCAmelCase			)







	@unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet"""			)
	def  _a   (  self      :							Union[str, Any]			)		-> str:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase			)







	def  _a   (  self      :							Optional[int]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase			)







	@slow
	def  _a   (  self      :							List[str]			)		-> List[Any]:
		"""simple docstring"""







		for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			__lowercase             =  TFEfficientFormerModel.from_pretrained(_lowerCAmelCase			)
			self.assertIsNotNone(_lowerCAmelCase			)







	def  _a   (  self      :							Any			)		-> List[str]:
		"""simple docstring"""







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

		__lowercase             =  getattr(self.model_tester       ,				"""seq_length"""       ,				_lowerCAmelCase			)
		__lowercase             =  getattr(self.model_tester       ,				"""encoder_seq_length"""       ,				_lowerCAmelCase			)
		__lowercase             =  getattr(self.model_tester       ,				"""key_length"""       ,				_lowerCAmelCase			)
		__lowercase             =  getattr(self.model_tester       ,				"""chunk_length"""       ,				_lowerCAmelCase			)

		if chunk_length is not None and hasattr(self.model_tester       ,				"""num_hashes"""			):
			__lowercase             =  encoder_seq_length * self.model_tester.num_hashes

		for model_class in self.all_model_classes:
			__lowercase             =  True
			__lowercase             =  False
			__lowercase             =  True
			__lowercase             =  model_class(_lowerCAmelCase			)

			__lowercase             =  model(**self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)       ,				training=_lowerCAmelCase			)
			__lowercase             =  outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
			self.assertEqual(len(_lowerCAmelCase			)       ,				self.model_tester.num_attention_outputs			)

			# check that output_attentions also work using config
			del inputs_dict["output_attentions"]
			__lowercase             =  True
			__lowercase             =  model_class(_lowerCAmelCase			)
			__lowercase             =  model(**self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)       ,				training=_lowerCAmelCase			)

			__lowercase             =  outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
			self.assertEqual(len(_lowerCAmelCase			)       ,				self.model_tester.num_attention_outputs			)

			if chunk_length is not None:
				self.assertListEqual(
				    list(attentions[0].shape[-4:]			)       ,				[self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]       ,				)
			else:
				self.assertListEqual(
				    list(attentions[0].shape[-3:]			)       ,				[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]       ,				)







	def  _a   (  self      :							Dict			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			# Prepare our model
			__lowercase             =  model_class(_lowerCAmelCase			)
			# These are maximally general inputs for the model, with multiple None dimensions
			# Hopefully this will catch any conditionals that fail for flexible shapes
			__lowercase             =  {
			    key: tf.keras.Input(shape=val.shape[1:]       ,				dtype=val.dtype       ,				name=_lowerCAmelCase			)
			    for key, val in model.input_signature.items()
			    if key in model.dummy_inputs
			}
			__lowercase             =  model(_lowerCAmelCase			)
			self.assertTrue(outputs_dict is not None			)





def 				snake_case  (     ):




	'''simple docstring'''







	__lowercase             =  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
	return image




@require_tf
@require_vision
class        __UpperCamelCase    (     unittest.TestCase   ):







	@cached_property
	def  _a   (  self      :							Optional[Any]			)		-> Any:
		"""simple docstring"""







		return (
		    EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300"""			)
		    if is_vision_available()
		    else None
		)







	@slow
	def  _a   (  self      :							Optional[Any]			)		-> Any:
		"""simple docstring"""







		__lowercase             =  TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300"""			)
		__lowercase             =  self.default_image_processor
		__lowercase             =  prepare_img()
		__lowercase             =  image_processor(images=_lowerCAmelCase       ,				return_tensors="""tf"""			)
		# forward pass
		__lowercase             =  model(**_lowerCAmelCase       ,				training=_lowerCAmelCase			)
		# verify the logits
		__lowercase             =  tf.TensorShape((1, 1000)			)
		self.assertEqual(outputs.logits.shape       ,				_lowerCAmelCase			)
		__lowercase             =  tf.constant([-0.0_555, 0.4_825, -0.0_852]			)
		self.assertTrue(np.allclose(outputs.logits[0, :3]       ,				_lowerCAmelCase       ,				atol=1e-4			)			)







	@slow
	def  _a   (  self      :							Optional[Any]			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
		    """snap-research/efficientformer-l1-300"""			)
		__lowercase             =  self.default_image_processor
		__lowercase             =  prepare_img()
		__lowercase             =  image_processor(images=_lowerCAmelCase       ,				return_tensors="""tf"""			)
		# forward pass
		__lowercase             =  model(**_lowerCAmelCase       ,				training=_lowerCAmelCase			)
		# verify the logits
		__lowercase             =  tf.TensorShape((1, 1000)			)
		self.assertEqual(outputs.logits.shape       ,				_lowerCAmelCase			)
		__lowercase             =  tf.constant([-0.1_312, 0.4_353, -1.0_499]			)
		self.assertTrue(np.allclose(outputs.logits[0, :3]       ,				_lowerCAmelCase       ,				atol=1e-4			)			)

