





"""simple docstring"""




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

		_lowerCamelCase :    Any  							= True
except ImportError:
		_lowerCamelCase :    Optional[int]  							= False


try:
		from torch.hub import _get_torch_home

		_lowerCamelCase :    Optional[int]  							= _get_torch_home()
except ImportError:
		_lowerCamelCase :    List[str]  							= os.path.expanduser(
		    os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
		)

_lowerCamelCase :    List[Any]  							= os.path.join(torch_cache_home, '''transformers''')

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




def _a (  SCREAMING_SNAKE_CASE__      :  str=OBJECTS			,				SCREAMING_SNAKE_CASE__      :  List[Any]=ATTRIBUTES       )	->    Dict:

							'''simple docstring'''






							SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						[]
							with open(SCREAMING_SNAKE_CASE__       ) as f:
														for object in f.readlines():
																					vg_classes.append(object.split(","       )[0].lower().strip()       )

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




def _a (  SCREAMING_SNAKE_CASE__      :  str       )	->    int:

							'''simple docstring'''






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


class 						lowerCamelCase       :







							"""simple docstring"""




							UpperCAmelCase_      						=   {}






							def __init__( self     :					Any,			_UpperCAmelCase     :					dict,			_UpperCAmelCase     :					str = "root",			_UpperCAmelCase     :					Optional[Any]=0						)				->			Tuple:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Any     =						name
														SCREAMING_SNAKE_CASE__       :      int     =						level
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						{}
														for k, v in dictionary.items():
																					if v is None:
																												raise ValueError()
																					SCREAMING_SNAKE_CASE__       :      int     =						copy.deepcopy(_UpperCAmelCase						)
																					SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						copy.deepcopy(_UpperCAmelCase						)
																					if isinstance(_UpperCAmelCase,			_UpperCAmelCase						):
																												SCREAMING_SNAKE_CASE__       :      Dict     =						Config(_UpperCAmelCase,			name=_UpperCAmelCase,			level=level + 1						)
																					SCREAMING_SNAKE_CASE__       :      Tuple     =						v
																					setattr(self,			_UpperCAmelCase,			_UpperCAmelCase						)

														SCREAMING_SNAKE_CASE__       :      Dict     =						d






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





														"""simple docstring"""
														return str(list((self._pointer.keys())						)						)






							def __setattr__( self     :					int,			_UpperCAmelCase     :					str,			_UpperCAmelCase     :					Tuple						)				->			Optional[Any]:





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






							def  A_     ( self     :					List[Any]						)				->			Dict:





														"""simple docstring"""
														return self._pointer






							def  A_     ( self     :					Tuple,			_UpperCAmelCase     :					str,			_UpperCAmelCase     :					Optional[Any]						)				->			Optional[Any]:





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






							def  A_     ( self     :					List[str],			_UpperCAmelCase     :					int,			_UpperCAmelCase     :					Any						)				->			Tuple:





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






							@staticmethod
							def  A_     ( _UpperCAmelCase     :					int						)				->			List[Any]:





														"""simple docstring"""
														with open(_UpperCAmelCase						) as stream:
																					SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						load(_UpperCAmelCase,			Loader=_UpperCAmelCase						)
														return data






							def __str__( self     :					Dict						)				->			Dict:





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






							@classmethod
							def  A_     ( cls     :					Optional[Any],			_UpperCAmelCase     :					str,			**_UpperCAmelCase     :					Optional[Any]						)				->			Optional[int]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						cls.get_config_dict(_UpperCAmelCase,			**_UpperCAmelCase						)
														return cls(_UpperCAmelCase						)






							@classmethod
							def  A_     ( cls     :					Union[str, Any],			_UpperCAmelCase     :					str,			**_UpperCAmelCase     :					Tuple						)				->			Tuple:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Dict     =						kwargs.pop("cache_dir",			_UpperCAmelCase						)
														SCREAMING_SNAKE_CASE__       :      Tuple     =						kwargs.pop("force_download",			_UpperCAmelCase						)
														SCREAMING_SNAKE_CASE__       :      List[str]     =						kwargs.pop("resume_download",			_UpperCAmelCase						)
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						kwargs.pop("proxies",			_UpperCAmelCase						)
														SCREAMING_SNAKE_CASE__       :      Tuple     =						kwargs.pop("local_files_only",			_UpperCAmelCase						)

														if os.path.isdir(_UpperCAmelCase						):
																					SCREAMING_SNAKE_CASE__       :      Dict     =						os.path.join(_UpperCAmelCase,			_UpperCAmelCase						)
														elif os.path.isfile(_UpperCAmelCase						) or is_remote_url(_UpperCAmelCase						):
																					SCREAMING_SNAKE_CASE__       :      Dict     =						pretrained_model_name_or_path
														else:
																					SCREAMING_SNAKE_CASE__       :      int     =						hf_bucket_url(_UpperCAmelCase,			filename=_UpperCAmelCase,			use_cdn=_UpperCAmelCase						)

														try:
																					# Load from URL or cache if already cached
																					SCREAMING_SNAKE_CASE__       :      Tuple     =						cached_path(
																					    _UpperCAmelCase,			cache_dir=_UpperCAmelCase,			force_download=_UpperCAmelCase,			proxies=_UpperCAmelCase,			resume_download=_UpperCAmelCase,			local_files_only=_UpperCAmelCase,			)
																					# Load config dict
																					if resolved_config_file is None:
																												raise EnvironmentError

																					SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						Config.load_yaml(_UpperCAmelCase						)

														except EnvironmentError:
																					SCREAMING_SNAKE_CASE__       :      List[str]     =						"Can't load config for"
																					raise EnvironmentError(_UpperCAmelCase						)

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

														return Config.load_yaml(_UpperCAmelCase						), kwargs




def _a (  SCREAMING_SNAKE_CASE__      :  str       )	->    Union[str, Any]:

							'''simple docstring'''






							SCREAMING_SNAKE_CASE__       :      Any     =						torch.load("dump.pt"			,				map_location=in_tensor.device       )
							SCREAMING_SNAKE_CASE__       :      Dict     =						in_tensor.numpy()
							SCREAMING_SNAKE_CASE__       :      Dict     =						out_tensor.numpy()[0]
							print(na.shape			,				na[0, 0, :5]       )
							print(na.shape			,				na[0, 0, :5]       )
							assert np.allclose(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__			,				rtol=0.0_1			,				atol=0.1       ), (
							    f'''{sum([1 for x in np.isclose(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__			,				rtol=0.0_1			,				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 (  SCREAMING_SNAKE_CASE__      :  Optional[Any]       )	->    Tuple:

							'''simple docstring'''






							SCREAMING_SNAKE_CASE__       :      List[str]     =						urlparse(SCREAMING_SNAKE_CASE__       )
							return parsed.scheme in ("http", "https")




def _a (  SCREAMING_SNAKE_CASE__      :  str			,				SCREAMING_SNAKE_CASE__      :  str			,				SCREAMING_SNAKE_CASE__      :  Optional[Any]=True       )	->    str:

							'''simple docstring'''






							SCREAMING_SNAKE_CASE__       :      List[Any]     =						CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
							SCREAMING_SNAKE_CASE__       :      int     =						"/" not in model_id
							if legacy_format:
														return f'''{endpoint}/{model_id}-{filename}'''
							else:
														return f'''{endpoint}/{model_id}/{filename}'''




def _a (  SCREAMING_SNAKE_CASE__      :  Optional[int]			,				SCREAMING_SNAKE_CASE__      :  Optional[int]			,				SCREAMING_SNAKE_CASE__      :  Any=None			,				SCREAMING_SNAKE_CASE__      :  Tuple=0			,				SCREAMING_SNAKE_CASE__      :  Any=None			,				)	->    Tuple:

							'''simple docstring'''






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




def _a (  SCREAMING_SNAKE_CASE__      :  Any			,				SCREAMING_SNAKE_CASE__      :  List[str]=None			,				SCREAMING_SNAKE_CASE__      :  Tuple=False			,				SCREAMING_SNAKE_CASE__      :  int=None			,				SCREAMING_SNAKE_CASE__      :  List[str]=10			,				SCREAMING_SNAKE_CASE__      :  Optional[int]=False			,				SCREAMING_SNAKE_CASE__      :  List[Any]=None			,				SCREAMING_SNAKE_CASE__      :  List[Any]=False			,				)	->    Optional[Any]:

							'''simple docstring'''






							if cache_dir is None:
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						TRANSFORMERS_CACHE
							if isinstance(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__       ):
														SCREAMING_SNAKE_CASE__       :      Dict     =						str(SCREAMING_SNAKE_CASE__       )

							os.makedirs(SCREAMING_SNAKE_CASE__			,				exist_ok=SCREAMING_SNAKE_CASE__       )

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

							SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						url_to_filename(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__       )

							# get cache path to put the file
							SCREAMING_SNAKE_CASE__       :      List[Any]     =						os.path.join(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__       )

							# 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(SCREAMING_SNAKE_CASE__       ):
																					return cache_path
														else:
																					SCREAMING_SNAKE_CASE__       :      int     =						[
																					    file
																					    for file in fnmatch.filter(os.listdir(SCREAMING_SNAKE_CASE__       )			,				filename + ".*"       )
																					    if not file.endswith(".json"       ) and not file.endswith(".lock"       )
																					]
																					if len(SCREAMING_SNAKE_CASE__       ) > 0:
																												return os.path.join(SCREAMING_SNAKE_CASE__			,				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(SCREAMING_SNAKE_CASE__       ) and not force_download:
														return cache_path

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

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

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

																					SCREAMING_SNAKE_CASE__       :      Optional[int]     =						_resumable_file_manager
																					if os.path.exists(SCREAMING_SNAKE_CASE__       ):
																												SCREAMING_SNAKE_CASE__       :      Dict     =						os.stat(SCREAMING_SNAKE_CASE__       ).st_size
																					else:
																												SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						0
														else:
																					SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						partial(tempfile.NamedTemporaryFile			,				dir=SCREAMING_SNAKE_CASE__			,				delete=SCREAMING_SNAKE_CASE__       )
																					SCREAMING_SNAKE_CASE__       :      List[str]     =						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"			,				SCREAMING_SNAKE_CASE__			,				temp_file.name			,				)

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

														os.replace(temp_file.name			,				SCREAMING_SNAKE_CASE__       )

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

							return cache_path




def _a (  SCREAMING_SNAKE_CASE__      :  Tuple			,				SCREAMING_SNAKE_CASE__      :  Union[str, Any]=None       )	->    Optional[Any]:

							'''simple docstring'''






							SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						url.encode("utf-8"       )
							SCREAMING_SNAKE_CASE__       :      List[str]     =						shaaaa(SCREAMING_SNAKE_CASE__       )
							SCREAMING_SNAKE_CASE__       :      List[str]     =						url_hash.hexdigest()

							if etag:
														SCREAMING_SNAKE_CASE__       :      str     =						etag.encode("utf-8"       )
														SCREAMING_SNAKE_CASE__       :      List[str]     =						shaaaa(SCREAMING_SNAKE_CASE__       )
														filename += "." + etag_hash.hexdigest()

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

							return filename




def _a (  SCREAMING_SNAKE_CASE__      :  int			,				SCREAMING_SNAKE_CASE__      :  Optional[Any]=None			,				SCREAMING_SNAKE_CASE__      :  Tuple=False			,				SCREAMING_SNAKE_CASE__      :  Any=None			,				SCREAMING_SNAKE_CASE__      :  List[str]=False			,				SCREAMING_SNAKE_CASE__      :  List[str]=None			,				SCREAMING_SNAKE_CASE__      :  Optional[int]=False			,				SCREAMING_SNAKE_CASE__      :  int=False			,				SCREAMING_SNAKE_CASE__      :  List[str]=False			,				)	->    int:

							'''simple docstring'''






							if cache_dir is None:
														SCREAMING_SNAKE_CASE__       :      Any     =						TRANSFORMERS_CACHE
							if isinstance(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__       ):
														SCREAMING_SNAKE_CASE__       :      List[str]     =						str(SCREAMING_SNAKE_CASE__       )
							if isinstance(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__       ):
														SCREAMING_SNAKE_CASE__       :      List[str]     =						str(SCREAMING_SNAKE_CASE__       )

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

							if extract_compressed_file:
														if not is_zipfile(SCREAMING_SNAKE_CASE__       ) and not tarfile.is_tarfile(SCREAMING_SNAKE_CASE__       ):
																					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/"
														SCREAMING_SNAKE_CASE__       :      int     =						os.path.split(SCREAMING_SNAKE_CASE__       )
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						output_file.replace("."			,				"-"       ) + "-extracted"
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						os.path.join(SCREAMING_SNAKE_CASE__			,				SCREAMING_SNAKE_CASE__       )

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

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

														return output_path_extracted

							return output_path




def _a (  SCREAMING_SNAKE_CASE__      :  int			,				SCREAMING_SNAKE_CASE__      :  Tuple=","       )	->    Tuple:

							'''simple docstring'''






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




def _a (  SCREAMING_SNAKE_CASE__      :  Union[str, Any]       )	->    Tuple:

							'''simple docstring'''






							SCREAMING_SNAKE_CASE__       :      Tuple     =						requests.get(SCREAMING_SNAKE_CASE__       )
							SCREAMING_SNAKE_CASE__       :      List[str]     =						np.array(Image.open(BytesIO(response.content       )       )       )
							return img




def _a (  SCREAMING_SNAKE_CASE__      :  Dict       )	->    Optional[int]:

							'''simple docstring'''






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




def _a (  )	->    Optional[Any]:

							'''simple docstring'''






							print(f'''{os.path.abspath(os.path.join(SCREAMING_SNAKE_CASE__			,				os.pardir       )       )}/demo.ipynb'''       )




def _a (  SCREAMING_SNAKE_CASE__      :  Dict			,				SCREAMING_SNAKE_CASE__      :  Any="RGB"       )	->    Union[str, Any]:

							'''simple docstring'''






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







def _a (  SCREAMING_SNAKE_CASE__      :  Any			,				SCREAMING_SNAKE_CASE__      :  List[Any]=1       )	->    List[str]:

							'''simple docstring'''






							return (images[i : i + batch] for i in range(0			,				len(SCREAMING_SNAKE_CASE__       )			,				SCREAMING_SNAKE_CASE__       ))













from __future__ import annotations




def _a (  SCREAMING_SNAKE_CASE__      :  list[float]			,				SCREAMING_SNAKE_CASE__      :  list[float]       )	->    float:

							'''simple docstring'''






							SCREAMING_SNAKE_CASE__       :      List[Any]     =						sorted(numsa + numsa       )
							SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      Dict     =						divmod(len(SCREAMING_SNAKE_CASE__       )			,				2       )
							if mod == 1:
														return all_numbers[div]
							else:
														return (all_numbers[div] + all_numbers[div - 1]) / 2


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		_lowerCamelCase :    List[str]  							= [float(x) for x in input('''Enter the elements of first array: ''').split()]
		_lowerCamelCase :    Any  							= [float(x) for x in input('''Enter the elements of second array: ''').split()]
		print(f"The median of two arrays is: {median_of_two_arrays(array_a, array_a)}")






