





import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
	import torch

	a__		    =    True
except ImportError:
	a__		    =    False


try:
	from torch.hub import _get_torch_home

	a__		    =    _get_torch_home()
except ImportError:
	a__		    =    os.path.expanduser(
	    os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
	)

a__		    =    os.path.join(torch_cache_home, '''transformers''')

a__		    =    '''https://cdn.huggingface.co'''
a__		    =    '''https://s3.amazonaws.com/models.huggingface.co/bert'''
a__		    =    '''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1])
a__		    =    os.path.join(PATH, '''config.yaml''')
a__		    =    os.path.join(PATH, '''attributes.txt''')
a__		    =    os.path.join(PATH, '''objects.txt''')
a__		    =    os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path)
a__		    =    os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE)
a__		    =    os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE)
a__		    =    '''pytorch_model.bin'''
a__		    =    '''config.yaml'''





def 							A__   (snake_case      :		str=OBJECTS		,  snake_case      :		Dict=ATTRIBUTES							)    ->	str:
					__UpperCamelCase				:  Optional[Any]								=			[]
					with open(__lowerCamelCase							) as f:
										for object in f.readlines():
															vg_classes.append(object.split(""","""							)[0].lower().strip()							)

					__UpperCamelCase				:  List[str]								=			[]
					with open(__lowerCamelCase							) as f:
										for object in f.readlines():
															vg_attrs.append(object.split(""","""							)[0].lower().strip()							)
					return vg_classes, vg_attrs





def 							A__   (snake_case      :		Optional[int]							)    ->	Optional[Any]:
					__UpperCamelCase				:  Any								=			OrderedDict()
					with open(__lowerCamelCase		,  """rb"""							) as f:
										__UpperCamelCase				:  Any								=			pkl.load(__lowerCamelCase							)["""model"""]
					for k in copy.deepcopy(list(ckp.keys()							)							):
										__UpperCamelCase				:  List[str]								=			ckp.pop(__lowerCamelCase							)
										if isinstance(__lowerCamelCase		,  np.ndarray							):
															__UpperCamelCase				:  List[Any]								=			torch.tensor(__lowerCamelCase							)
										else:
															assert isinstance(__lowerCamelCase		,  torch.tensor							), type(__lowerCamelCase							)
										__UpperCamelCase				:  Union[str, Any]								=			v
					return r


class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


	__magic_name__      :					int			  =		{}






	def __init__(				self		:	Dict				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	List[Any] = "root"				,    lowerCAmelCase		:	Optional[Any]=0  )  ->					int:







						"""simple docstring"""







						__UpperCamelCase				:  str								=			name
						__UpperCamelCase				:  List[Any]								=			level
						__UpperCamelCase				:  Optional[Any]								=			{}
						for k, v in dictionary.items():
											if v is None:
																raise ValueError()
											__UpperCamelCase				:  Union[str, Any]								=			copy.deepcopy(lowerCAmelCase  )
											__UpperCamelCase				:  Union[str, Any]								=			copy.deepcopy(lowerCAmelCase  )
											if isinstance(lowerCAmelCase				,    lowerCAmelCase  ):
																__UpperCamelCase				:  str								=			Config(lowerCAmelCase				,    name=lowerCAmelCase				,    level=level + 1  )
											__UpperCamelCase				:  int								=			v
											setattr(self				,    lowerCAmelCase				,    lowerCAmelCase  )

						__UpperCamelCase				:  Tuple								=			d






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







						"""simple docstring"""







						return str(list((self._pointer.keys())  )  )






	def __setattr__(				self		:	Optional[int]				,    lowerCAmelCase		:	List[str]				,    lowerCAmelCase		:	Union[str, Any]  )  ->					int:







						"""simple docstring"""







						__UpperCamelCase				:  Any								=			val
						__UpperCamelCase				:  List[Any]								=			val
						__UpperCamelCase				:  Optional[int]								=			key.split("""."""  )
						__UpperCamelCase				:  Any								=			len(lowerCAmelCase  ) - 1
						__UpperCamelCase				:  Dict								=			self._pointer
						if len(lowerCAmelCase  ) > 1:
											for i, l in enumerate(lowerCAmelCase  ):
																if hasattr(self				,    lowerCAmelCase  ) and isinstance(getattr(self				,    lowerCAmelCase  )				,    lowerCAmelCase  ):
																					setattr(getattr(self				,    lowerCAmelCase  )				,    """.""".join(levels[i:]  )				,    lowerCAmelCase  )
																if l == last_level:
																					__UpperCamelCase				:  Tuple								=			val
																else:
																					__UpperCamelCase				:  List[Any]								=			pointer[l]






	def 				lowerCamelCase__    (				self		:	str  )  ->					str:







						"""simple docstring"""







						return self._pointer






	def 				lowerCamelCase__    (				self		:	Dict				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	Optional[int]  )  ->					Any:







						"""simple docstring"""







						with open(F'''{file_name}'''				,    """w"""  ) as stream:
											dump(lowerCAmelCase				,    lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	int				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	Union[str, Any]  )  ->					str:







						"""simple docstring"""







						with open(F'''{file_name}'''				,    """w"""  ) as stream:
											json.dump(lowerCAmelCase				,    lowerCAmelCase  )






	@staticmethod
	def 				lowerCamelCase__    (				lowerCAmelCase		:	Any  )  ->					List[str]:







						"""simple docstring"""







						with open(lowerCAmelCase  ) as stream:
											__UpperCamelCase				:  Dict								=			load(lowerCAmelCase				,    Loader=lowerCAmelCase  )
						return data






	def __str__(				self		:	Tuple  )  ->					List[str]:







						"""simple docstring"""







						__UpperCamelCase				:  Any								=			"""    """
						if self._name != "root":
											__UpperCamelCase				:  Any								=			F'''{t * (self._level-1)}{self._name}:\n'''
						else:
											__UpperCamelCase				:  Optional[int]								=			""""""
						__UpperCamelCase				:  Union[str, Any]								=			self._level
						for i, (k, v) in enumerate(self._pointer.items()  ):
											if isinstance(lowerCAmelCase				,    lowerCAmelCase  ):
																r += F'''{t * (self._level)}{v}\n'''
																self._level += 1
											else:
																r += F'''{t * (self._level)}{k}: {v} ({type(lowerCAmelCase  ).__name__})\n'''
											__UpperCamelCase				:  Dict								=			level
						return r[:-1]






	@classmethod
	def 				lowerCamelCase__    (				cls		:	Dict				,    lowerCAmelCase		:	List[str]				,    **lowerCAmelCase		:	Tuple  )  ->					str:







						"""simple docstring"""







						__UpperCamelCase			, __UpperCamelCase				:  Optional[Any]								=			cls.get_config_dict(lowerCAmelCase				,    **lowerCAmelCase  )
						return cls(lowerCAmelCase  )






	@classmethod
	def 				lowerCamelCase__    (				cls		:	Optional[int]				,    lowerCAmelCase		:	List[Any]				,    **lowerCAmelCase		:	Any  )  ->					Any:







						"""simple docstring"""







						__UpperCamelCase				:  str								=			kwargs.pop("""cache_dir"""				,    lowerCAmelCase  )
						__UpperCamelCase				:  Optional[Any]								=			kwargs.pop("""force_download"""				,    lowerCAmelCase  )
						__UpperCamelCase				:  List[Any]								=			kwargs.pop("""resume_download"""				,    lowerCAmelCase  )
						__UpperCamelCase				:  str								=			kwargs.pop("""proxies"""				,    lowerCAmelCase  )
						__UpperCamelCase				:  Optional[Any]								=			kwargs.pop("""local_files_only"""				,    lowerCAmelCase  )

						if os.path.isdir(lowerCAmelCase  ):
											__UpperCamelCase				:  List[Any]								=			os.path.join(lowerCAmelCase				,    lowerCAmelCase  )
						elif os.path.isfile(lowerCAmelCase  ) or is_remote_url(lowerCAmelCase  ):
											__UpperCamelCase				:  Union[str, Any]								=			pretrained_model_name_or_path
						else:
											__UpperCamelCase				:  Union[str, Any]								=			hf_bucket_url(lowerCAmelCase				,    filename=lowerCAmelCase				,    use_cdn=lowerCAmelCase  )

						try:
											# Load from URL or cache if already cached
											__UpperCamelCase				:  Union[str, Any]								=			cached_path(
											    lowerCAmelCase				,    cache_dir=lowerCAmelCase				,    force_download=lowerCAmelCase				,    proxies=lowerCAmelCase				,    resume_download=lowerCAmelCase				,    local_files_only=lowerCAmelCase				,    )
											# Load config dict
											if resolved_config_file is None:
																raise EnvironmentError

											__UpperCamelCase				:  Dict								=			Config.load_yaml(lowerCAmelCase  )

						except EnvironmentError:
											__UpperCamelCase				:  int								=			"""Can't load config for"""
											raise EnvironmentError(lowerCAmelCase  )

						if resolved_config_file == config_file:
											print("""loading configuration file from path"""  )
						else:
											print("""loading configuration file cache"""  )

						return Config.load_yaml(lowerCAmelCase  ), kwargs






def 							A__   (snake_case      :		Any							)    ->	List[str]:
					__UpperCamelCase				:  List[Any]								=			torch.load("""dump.pt"""		,  map_location=in_tensor.device							)
					__UpperCamelCase				:  Optional[Any]								=			in_tensor.numpy()
					__UpperCamelCase				:  Dict								=			out_tensor.numpy()[0]
					print(na.shape		,  na[0, 0, :5]							)
					print(na.shape		,  na[0, 0, :5]							)
					assert np.allclose(__lowerCamelCase		,  __lowerCamelCase		,  rtol=0.01		,  atol=0.1							), (
					    F'''{sum([1 for x in np.isclose(__lowerCamelCase		,  __lowerCamelCase		,  rtol=0.01		,  atol=0.1							).flatten() if x is False]							)/len(na.flatten()							)*1_00:.4f} %'''
					    " element-wise mismatch"
					)
					raise Exception("""tensors are all good"""							)

					# Hugging face functions below





def 							A__   (snake_case      :		Optional[Any]							)    ->	List[str]:
					__UpperCamelCase				:  Optional[Any]								=			urlparse(__lowerCamelCase							)
					return parsed.scheme in ("http", "https")





def 							A__   (snake_case      :		str		,  snake_case      :		str		,  snake_case      :		Dict=True							)    ->	str:
					__UpperCamelCase				:  Optional[Any]								=			CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
					__UpperCamelCase				:  List[Any]								=			"""/""" not in model_id
					if legacy_format:
										return F'''{endpoint}/{model_id}-{filename}'''
					else:
										return F'''{endpoint}/{model_id}/{filename}'''





def 							A__   (snake_case      :		str		,  snake_case      :		List[str]		,  snake_case      :		Any=None		,  snake_case      :		List[str]=0		,  snake_case      :		List[str]=None		,  )    ->	Any:
					__UpperCamelCase				:  Optional[Any]								=			"""python/{}""".format(sys.version.split()[0]							)
					if _torch_available:
										ua += "; torch/{}".format(torch.__version__							)
					if isinstance(__lowerCamelCase		,  __lowerCamelCase							):
										ua += "; " + "; ".join("""{}/{}""".format(__lowerCamelCase		,  __lowerCamelCase							) for k, v in user_agent.items()							)
					elif isinstance(__lowerCamelCase		,  __lowerCamelCase							):
										ua += "; " + user_agent
					__UpperCamelCase				:  str								=			{"""user-agent""": ua}
					if resume_size > 0:
										__UpperCamelCase				:  Optional[int]								=			"""bytes=%d-""" % (resume_size,)
					__UpperCamelCase				:  int								=			requests.get(__lowerCamelCase		,  stream=__lowerCamelCase		,  proxies=__lowerCamelCase		,  headers=__lowerCamelCase							)
					if response.status_code == 4_16:  # Range not satisfiable
										return
					__UpperCamelCase				:  Tuple								=			response.headers.get("""Content-Length"""							)
					__UpperCamelCase				:  List[Any]								=			resume_size + int(__lowerCamelCase							) if content_length is not None else None
					__UpperCamelCase				:  int								=			tqdm(
					    unit="""B"""		,  unit_scale=__lowerCamelCase		,  total=__lowerCamelCase		,  initial=__lowerCamelCase		,  desc="""Downloading"""		,  )
					for chunk in response.iter_content(chunk_size=10_24							):
										if chunk:  # filter out keep-alive new chunks
															progress.update(len(__lowerCamelCase							)							)
															temp_file.write(__lowerCamelCase							)
					progress.close()





def 							A__   (snake_case      :		int		,  snake_case      :		Any=None		,  snake_case      :		List[str]=False		,  snake_case      :		Tuple=None		,  snake_case      :		Dict=10		,  snake_case      :		List[Any]=False		,  snake_case      :		str=None		,  snake_case      :		List[Any]=False		,  )    ->	List[str]:
					if cache_dir is None:
										__UpperCamelCase				:  Union[str, Any]								=			TRANSFORMERS_CACHE
					if isinstance(__lowerCamelCase		,  __lowerCamelCase							):
										__UpperCamelCase				:  str								=			str(__lowerCamelCase							)

					os.makedirs(__lowerCamelCase		,  exist_ok=__lowerCamelCase							)

					__UpperCamelCase				:  str								=			None
					if not local_files_only:
										try:
															__UpperCamelCase				:  Any								=			requests.head(__lowerCamelCase		,  allow_redirects=__lowerCamelCase		,  proxies=__lowerCamelCase		,  timeout=__lowerCamelCase							)
															if response.status_code == 2_00:
																				__UpperCamelCase				:  str								=			response.headers.get("""ETag"""							)
										except (EnvironmentError, requests.exceptions.Timeout):
															# etag is already None
															pass

					__UpperCamelCase				:  Optional[Any]								=			url_to_filename(__lowerCamelCase		,  __lowerCamelCase							)

					# get cache path to put the file
					__UpperCamelCase				:  Union[str, Any]								=			os.path.join(__lowerCamelCase		,  __lowerCamelCase							)

					# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
					# try to get the last downloaded one
					if etag is None:
										if os.path.exists(__lowerCamelCase							):
															return cache_path
										else:
															__UpperCamelCase				:  List[Any]								=			[
															    file
															    for file in fnmatch.filter(os.listdir(__lowerCamelCase							)		,  filename + """.*"""							)
															    if not file.endswith(""".json"""							) and not file.endswith(""".lock"""							)
															]
															if len(__lowerCamelCase							) > 0:
																				return os.path.join(__lowerCamelCase		,  matching_files[-1]							)
															else:
																				# If files cannot be found and local_files_only=True,
																				# the models might've been found if local_files_only=False
																				# Notify the user about that
																				if local_files_only:
																									raise ValueError(
																									    """Cannot find the requested files in the cached path and outgoing traffic has been"""
																									    """ disabled. To enable model look-ups and downloads online, set 'local_files_only'"""
																									    """ to False."""							)
																				return None

    # From now on, etag is not None.
					if os.path.exists(__lowerCamelCase							) and not force_download:
										return cache_path

					# Prevent parallel downloads of the same file with a lock.
					__UpperCamelCase				:  Dict								=			cache_path + """.lock"""
					with FileLock(__lowerCamelCase							):
										# If the download just completed while the lock was activated.
										if os.path.exists(__lowerCamelCase							) and not force_download:
															# Even if returning early like here, the lock will be released.
															return cache_path

										if resume_download:
															__UpperCamelCase				:  Dict								=			cache_path + """.incomplete"""

															@contextmanager
															def _resumable_file_manager():
																				with open(__lowerCamelCase		,  """a+b"""							) as f:
																									yield f

															__UpperCamelCase				:  str								=			_resumable_file_manager
															if os.path.exists(__lowerCamelCase							):
																				__UpperCamelCase				:  Optional[int]								=			os.stat(__lowerCamelCase							).st_size
															else:
																				__UpperCamelCase				:  List[str]								=			0
										else:
															__UpperCamelCase				:  List[str]								=			partial(tempfile.NamedTemporaryFile		,  dir=__lowerCamelCase		,  delete=__lowerCamelCase							)
															__UpperCamelCase				:  List[Any]								=			0

										# Download to temporary file, then copy to cache dir once finished.
										# Otherwise you get corrupt cache entries if the download gets interrupted.
										with temp_file_manager() as temp_file:
															print(
															    """%s not found in cache or force_download set to True, downloading to %s"""		,  __lowerCamelCase		,  temp_file.name		,  )

															http_get(
															    __lowerCamelCase		,  __lowerCamelCase		,  proxies=__lowerCamelCase		,  resume_size=__lowerCamelCase		,  user_agent=__lowerCamelCase		,  )

										os.replace(temp_file.name		,  __lowerCamelCase							)

										__UpperCamelCase				:  Dict								=			{"""url""": url, """etag""": etag}
										__UpperCamelCase				:  Optional[Any]								=			cache_path + """.json"""
										with open(__lowerCamelCase		,  """w"""							) as meta_file:
															json.dump(__lowerCamelCase		,  __lowerCamelCase							)

					return cache_path





def 							A__   (snake_case      :		str		,  snake_case      :		Optional[int]=None							)    ->	Union[str, Any]:
					__UpperCamelCase				:  Any								=			url.encode("""utf-8"""							)
					__UpperCamelCase				:  Tuple								=			shaaaa(__lowerCamelCase							)
					__UpperCamelCase				:  Optional[int]								=			url_hash.hexdigest()

					if etag:
										__UpperCamelCase				:  str								=			etag.encode("""utf-8"""							)
										__UpperCamelCase				:  Tuple								=			shaaaa(__lowerCamelCase							)
										filename += "." + etag_hash.hexdigest()

					if url.endswith(""".h5"""							):
										filename += ".h5"

					return filename





def 							A__   (snake_case      :		Union[str, Any]		,  snake_case      :		List[str]=None		,  snake_case      :		Dict=False		,  snake_case      :		Any=None		,  snake_case      :		List[str]=False		,  snake_case      :		Any=None		,  snake_case      :		Dict=False		,  snake_case      :		Optional[int]=False		,  snake_case      :		List[Any]=False		,  )    ->	Any:
					if cache_dir is None:
										__UpperCamelCase				:  Union[str, Any]								=			TRANSFORMERS_CACHE
					if isinstance(__lowerCamelCase		,  __lowerCamelCase							):
										__UpperCamelCase				:  Tuple								=			str(__lowerCamelCase							)
					if isinstance(__lowerCamelCase		,  __lowerCamelCase							):
										__UpperCamelCase				:  Tuple								=			str(__lowerCamelCase							)

					if is_remote_url(__lowerCamelCase							):
										# URL, so get it from the cache (downloading if necessary)
										__UpperCamelCase				:  Optional[int]								=			get_from_cache(
										    __lowerCamelCase		,  cache_dir=__lowerCamelCase		,  force_download=__lowerCamelCase		,  proxies=__lowerCamelCase		,  resume_download=__lowerCamelCase		,  user_agent=__lowerCamelCase		,  local_files_only=__lowerCamelCase		,  )
					elif os.path.exists(__lowerCamelCase							):
										# File, and it exists.
										__UpperCamelCase				:  List[str]								=			url_or_filename
					elif urlparse(__lowerCamelCase							).scheme == "":
										# File, but it doesn't exist.
										raise EnvironmentError("""file {} not found""".format(__lowerCamelCase							)							)
					else:
										# Something unknown
										raise ValueError("""unable to parse {} as a URL or as a local path""".format(__lowerCamelCase							)							)

					if extract_compressed_file:
										if not is_zipfile(__lowerCamelCase							) and not tarfile.is_tarfile(__lowerCamelCase							):
															return output_path

										# Path where we extract compressed archives
										# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
										__UpperCamelCase			, __UpperCamelCase				:  List[Any]								=			os.path.split(__lowerCamelCase							)
										__UpperCamelCase				:  Union[str, Any]								=			output_file.replace("""."""		,  """-"""							) + """-extracted"""
										__UpperCamelCase				:  Optional[int]								=			os.path.join(__lowerCamelCase		,  __lowerCamelCase							)

										if os.path.isdir(__lowerCamelCase							) and os.listdir(__lowerCamelCase							) and not force_extract:
															return output_path_extracted

										# Prevent parallel extractions
										__UpperCamelCase				:  Optional[Any]								=			output_path + """.lock"""
										with FileLock(__lowerCamelCase							):
															shutil.rmtree(__lowerCamelCase		,  ignore_errors=__lowerCamelCase							)
															os.makedirs(__lowerCamelCase							)
															if is_zipfile(__lowerCamelCase							):
																				with ZipFile(__lowerCamelCase		,  """r"""							) as zip_file:
																									zip_file.extractall(__lowerCamelCase							)
																									zip_file.close()
															elif tarfile.is_tarfile(__lowerCamelCase							):
																				__UpperCamelCase				:  Optional[Any]								=			tarfile.open(__lowerCamelCase							)
																				tar_file.extractall(__lowerCamelCase							)
																				tar_file.close()
															else:
																				raise EnvironmentError("""Archive format of {} could not be identified""".format(__lowerCamelCase							)							)

										return output_path_extracted

					return output_path





def 							A__   (snake_case      :		Optional[int]		,  snake_case      :		List[str]=","							)    ->	Optional[int]:
					assert isinstance(__lowerCamelCase		,  __lowerCamelCase							)
					if os.path.isfile(__lowerCamelCase							):
										with open(__lowerCamelCase							) as f:
															__UpperCamelCase				:  Any								=			eval(f.read()							)
					else:
										__UpperCamelCase				:  Any								=			requests.get(__lowerCamelCase							)
										try:
															__UpperCamelCase				:  Any								=			requests.json()
										except Exception:
															__UpperCamelCase				:  Union[str, Any]								=			req.content.decode()
															assert data is not None, "could not connect"
															try:
																				__UpperCamelCase				:  List[Any]								=			eval(__lowerCamelCase							)
															except Exception:
																				__UpperCamelCase				:  Tuple								=			data.split("""\n"""							)
										req.close()
					return data





def 							A__   (snake_case      :		int							)    ->	Any:
					__UpperCamelCase				:  Union[str, Any]								=			requests.get(__lowerCamelCase							)
					__UpperCamelCase				:  Dict								=			np.array(Image.open(BytesIO(response.content							)							)							)
					return img





def 							A__   (snake_case      :		Tuple							)    ->	int:
					__UpperCamelCase				:  Any								=			url.split("""/"""							)[-1]
					if fn not in os.listdir(os.getcwd()							):
										wget.download(__lowerCamelCase							)
					with open(__lowerCamelCase		,  """rb"""							) as stream:
										__UpperCamelCase				:  Any								=			pkl.load(__lowerCamelCase							)
					__UpperCamelCase				:  Union[str, Any]								=			weights.pop("""model"""							)
					__UpperCamelCase				:  int								=			{}
					for k, v in model.items():
										__UpperCamelCase				:  Any								=			torch.from_numpy(__lowerCamelCase							)
										if "running_var" in k:
															__UpperCamelCase				:  Tuple								=			torch.tensor([0]							)
															__UpperCamelCase				:  Dict								=			k.replace("""running_var"""		,  """num_batches_tracked"""							)
															__UpperCamelCase				:  Dict								=			zero
					return new





def 							A__   ()    ->	Dict:
					print(F'''{os.path.abspath(os.path.join(__lowerCamelCase		,  os.pardir							)							)}/demo.ipynb'''							)





def 							A__   (snake_case      :		Any		,  snake_case      :		Optional[int]="RGB"							)    ->	Optional[Any]:
					assert isinstance(__lowerCamelCase		,  __lowerCamelCase							)
					if os.path.isfile(__lowerCamelCase							):
										__UpperCamelCase				:  List[str]								=			cva.imread(__lowerCamelCase							)
					else:
										__UpperCamelCase				:  List[str]								=			get_image_from_url(__lowerCamelCase							)
										assert img is not None, F'''could not connect to: {im}'''
					__UpperCamelCase				:  Any								=			cva.cvtColor(__lowerCamelCase		,  cva.COLOR_BGR2RGB							)
					if input_format == "RGB":
										__UpperCamelCase				:  List[Any]								=			img[:, :, ::-1]
					return img







def 							A__   (snake_case      :		str		,  snake_case      :		int=1							)    ->	int:
					return (images[i : i + batch] for i in range(0		,  len(__lowerCamelCase							)		,  __lowerCamelCase							))












import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, 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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import EfficientNetForImageClassification, EfficientNetModel
	from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor


class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


	def __init__(				self		:	Optional[int]				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	int=13				,    lowerCAmelCase		:	Union[str, Any]=32				,    lowerCAmelCase		:	List[Any]=3				,    lowerCAmelCase		:	Tuple=[3, 3, 5]				,    lowerCAmelCase		:	str=[32, 16, 24]				,    lowerCAmelCase		:	Dict=[16, 24, 40]				,    lowerCAmelCase		:	Optional[Any]=[1, 1, 2]				,    lowerCAmelCase		:	int=[1, 1, 2]				,    lowerCAmelCase		:	Any=[1, 6, 6]				,    lowerCAmelCase		:	str=True				,    lowerCAmelCase		:	Tuple=True				,    lowerCAmelCase		:	Dict=37				,    lowerCAmelCase		:	Any="gelu"				,    lowerCAmelCase		:	List[str]=10				,    )  ->					Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  List[Any]								=			parent
						__UpperCamelCase				:  Any								=			batch_size
						__UpperCamelCase				:  List[str]								=			image_size
						__UpperCamelCase				:  int								=			num_channels
						__UpperCamelCase				:  Tuple								=			kernel_sizes
						__UpperCamelCase				:  Union[str, Any]								=			in_channels
						__UpperCamelCase				:  int								=			out_channels
						__UpperCamelCase				:  List[str]								=			strides
						__UpperCamelCase				:  Optional[Any]								=			num_block_repeats
						__UpperCamelCase				:  Tuple								=			expand_ratios
						__UpperCamelCase				:  Optional[int]								=			is_training
						__UpperCamelCase				:  Dict								=			hidden_act
						__UpperCamelCase				:  Optional[int]								=			num_labels
						__UpperCamelCase				:  List[Any]								=			use_labels






	def 				lowerCamelCase__    (				self		:	Optional[Any]  )  ->					Tuple:







						"""simple docstring"""







						__UpperCamelCase				:  Tuple								=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

						__UpperCamelCase				:  int								=			None
						if self.use_labels:
											__UpperCamelCase				:  str								=			ids_tensor([self.batch_size]				,    self.num_labels  )

						__UpperCamelCase				:  int								=			self.get_config()
						return config, pixel_values, labels






	def 				lowerCamelCase__    (				self		:	Tuple  )  ->					Any:







						"""simple docstring"""







						return EfficientNetConfig(
						    num_channels=self.num_channels				,    kernel_sizes=self.kernel_sizes				,    in_channels=self.in_channels				,    out_channels=self.out_channels				,    strides=self.strides				,    num_block_repeats=self.num_block_repeats				,    expand_ratios=self.expand_ratios				,    hidden_act=self.hidden_act				,    num_labels=self.num_labels				,    )






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







						"""simple docstring"""







						__UpperCamelCase				:  int								=			EfficientNetModel(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  Union[str, Any]								=			model(lowerCAmelCase  )
						# expected last hidden states: B, C, H // 4, W // 4
						self.parent.assertEqual(
						    result.last_hidden_state.shape				,    (self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)				,    )






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







						"""simple docstring"""







						__UpperCamelCase				:  List[Any]								=			EfficientNetForImageClassification(lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  Optional[int]								=			model(lowerCAmelCase				,    labels=lowerCAmelCase  )
						self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.num_labels)  )






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







						"""simple docstring"""







						__UpperCamelCase				:  Optional[int]								=			self.prepare_config_and_inputs()
						__UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase				:  str								=			config_and_inputs
						__UpperCamelCase				:  Optional[Any]								=			{"""pixel_values""": pixel_values}
						return config, inputs_dict






@require_torch
class       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase  ,     _UpperCamelCase  ,     unittest.TestCase      ):



	"""simple docstring"""


	__magic_name__      :					List[Any]			  =		(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
	__magic_name__      :					Tuple			  =		(
	    {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
	    if is_torch_available()
	    else {}
	)

	__magic_name__      :					Union[str, Any]			  =		False
	__magic_name__      :					Dict			  =		False
	__magic_name__      :					str			  =		False
	__magic_name__      :					Union[str, Any]			  =		False
	__magic_name__      :					int			  =		False






	def 				lowerCamelCase__    (				self		:	Dict  )  ->					Optional[int]:







						"""simple docstring"""







						__UpperCamelCase				:  List[str]								=			EfficientNetModelTester(self  )
						__UpperCamelCase				:  Optional[Any]								=			ConfigTester(
						    self				,    config_class=lowerCAmelCase				,    has_text_modality=lowerCAmelCase				,    hidden_size=37  )






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







						"""simple docstring"""







						self.create_and_test_config_common_properties()
						self.config_tester.create_and_test_config_to_json_string()
						self.config_tester.create_and_test_config_to_json_file()
						self.config_tester.create_and_test_config_from_and_save_pretrained()
						self.config_tester.create_and_test_config_with_num_labels()
						self.config_tester.check_config_can_be_init_without_params()
						self.config_tester.check_config_arguments_init()






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







						"""simple docstring"""







						return






	@unittest.skip(reason="""EfficientNet does not use inputs_embeds"""  )
	def 				lowerCamelCase__    (				self		:	str  )  ->					List[str]:







						"""simple docstring"""







						pass






	@unittest.skip(reason="""EfficientNet does not support input and output embeddings"""  )
	def 				lowerCamelCase__    (				self		:	Optional[Any]  )  ->					Any:







						"""simple docstring"""







						pass






	@unittest.skip(reason="""EfficientNet does not use feedforward chunking"""  )
	def 				lowerCamelCase__    (				self		:	Tuple  )  ->					Optional[int]:







						"""simple docstring"""







						pass






	def 				lowerCamelCase__    (				self		:	Tuple  )  ->					List[str]:







						"""simple docstring"""







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

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

											__UpperCamelCase				:  Union[str, Any]								=			["""pixel_values"""]
											self.assertListEqual(arg_names[:1]				,    lowerCAmelCase  )






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







						"""simple docstring"""







						__UpperCamelCase				:  Optional[int]								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Tuple  )  ->					List[Any]:







						"""simple docstring"""







						def check_hidden_states_output(lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Any  ):
											__UpperCamelCase				:  int								=			model_class(lowerCAmelCase  )
											model.to(lowerCAmelCase  )
											model.eval()

											with torch.no_grad():
																__UpperCamelCase				:  Tuple								=			model(**self._prepare_for_class(lowerCAmelCase				,    lowerCAmelCase  )  )

											__UpperCamelCase				:  Any								=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
											__UpperCamelCase				:  Union[str, Any]								=			sum(config.num_block_repeats  ) * 4
											self.assertEqual(len(lowerCAmelCase  )				,    lowerCAmelCase  )

											# EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
											self.assertListEqual(
											    list(hidden_states[0].shape[-2:]  )				,    [self.model_tester.image_size // 2, self.model_tester.image_size // 2]				,    )

						__UpperCamelCase			, __UpperCamelCase				:  Union[str, Any]								=			self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											__UpperCamelCase				:  Union[str, Any]								=			True
											check_hidden_states_output(lowerCAmelCase				,    lowerCAmelCase				,    lowerCAmelCase  )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											__UpperCamelCase				:  Optional[Any]								=			True

											check_hidden_states_output(lowerCAmelCase				,    lowerCAmelCase				,    lowerCAmelCase  )






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







						"""simple docstring"""







						__UpperCamelCase				:  Optional[Any]								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase  )






	@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""  )
	def 				lowerCamelCase__    (				self		:	Optional[int]  )  ->					Dict:







						"""simple docstring"""







						pass






	@slow
	def 				lowerCamelCase__    (				self		:	str  )  ->					Any:







						"""simple docstring"""







						for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__UpperCamelCase				:  Union[str, Any]								=			EfficientNetModel.from_pretrained(lowerCAmelCase  )
											self.assertIsNotNone(lowerCAmelCase  )






	@is_pipeline_test
	@require_vision
	@slow
	def 				lowerCamelCase__    (				self		:	List[str]  )  ->					Union[str, Any]:







						"""simple docstring"""







						super().test_pipeline_image_classification()






def 							A__   ()    ->	Union[str, Any]:
					__UpperCamelCase				:  List[str]								=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
					return image







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



	"""simple docstring"""


	@cached_property
	def 				lowerCamelCase__    (				self		:	List[str]  )  ->					Union[str, Any]:







						"""simple docstring"""







						return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""  ) if is_vision_available() else None






	@slow
	def 				lowerCamelCase__    (				self		:	List[str]  )  ->					Dict:







						"""simple docstring"""







						__UpperCamelCase				:  Optional[Any]								=			EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""  ).to(lowerCAmelCase  )

						__UpperCamelCase				:  Any								=			self.default_image_processor
						__UpperCamelCase				:  Any								=			prepare_img()
						__UpperCamelCase				:  Optional[Any]								=			image_processor(images=lowerCAmelCase				,    return_tensors="""pt"""  ).to(lowerCAmelCase  )

						# forward pass
						with torch.no_grad():
											__UpperCamelCase				:  Tuple								=			model(**lowerCAmelCase  )

						# verify the logits
						__UpperCamelCase				:  Optional[int]								=			torch.Size((1, 1000)  )
						self.assertEqual(outputs.logits.shape				,    lowerCAmelCase  )

						__UpperCamelCase				:  int								=			torch.tensor([0.00_01, 0.00_02, 0.00_02]  ).to(lowerCAmelCase  )
						self.assertTrue(torch.allclose(outputs.logits[0, :3]				,    lowerCAmelCase				,    atol=1E-4  )  )






