'''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

      UpperCamelCase       :     Tuple			=    True
except ImportError:
      UpperCamelCase       :     Optional[int]			=    False


try:
      from torch.hub import _get_torch_home

      UpperCamelCase       :     List[Any]			=    _get_torch_home()
except ImportError:
      UpperCamelCase       :     Union[str, Any]			=    os.path.expanduser(
          os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
      )

UpperCamelCase       :     Tuple			=    os.path.join(torch_cache_home, """transformers""")

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






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Tuple=OBJECTS				,	snake_case       :				Optional[Any]=ATTRIBUTES  )   ->				Optional[int]:







     """simple docstring"""
     a					:							Dict							= []
     with open(_lowercase  ) as f:
          for object in f.readlines():
               vg_classes.append(object.split(','  )[0].lower().strip()  )

     a					:							Optional[int]							= []
     with open(_lowercase  ) as f:
          for object in f.readlines():
               vg_attrs.append(object.split(','  )[0].lower().strip()  )
     return vg_classes, vg_attrs






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Dict  )   ->				Dict:







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



class   UpperCamelCase					:







    """simple docstring"""





    A     :    Tuple				=			{}





    def __init__(					self     :						Any							,							UpperCAmelCase_     :						dict							,							UpperCAmelCase_     :						str = "root"							,							UpperCAmelCase_     :						str=0):


         """simple docstring"""







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

         a					:							str							= d





    def __repr__(					self     :						Union[str, Any]):


         """simple docstring"""







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





    def __setattr__(					self     :						Any							,							UpperCAmelCase_     :						Any							,							UpperCAmelCase_     :						Union[str, Any]):


         """simple docstring"""







         a					:							int							= val
         a					:							Any							= val
         a					:							List[Any]							= key.split('.')
         a					:							Any							= len(UpperCamelCase_) - 1
         a					:							Optional[Any]							= 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:
                        a					:							str							= val
                   else:
                        a					:							Optional[Any]							= pointer[l]





    def    SCREAMING_SNAKE_CASE_     (					self     :						Optional[int]):


         """simple docstring"""







         return self._pointer





    def    SCREAMING_SNAKE_CASE_     (					self     :						Optional[Any]							,							UpperCAmelCase_     :						Optional[Any]							,							UpperCAmelCase_     :						Any):


         """simple docstring"""







         with open(f"""{file_name}"""							,							'w') as stream:
              dump(UpperCamelCase_							,							UpperCamelCase_)





    def    SCREAMING_SNAKE_CASE_     (					self     :						Union[str, Any]							,							UpperCAmelCase_     :						List[Any]							,							UpperCAmelCase_     :						Dict):


         """simple docstring"""







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





    @staticmethod
    def    SCREAMING_SNAKE_CASE_     (					UpperCAmelCase_     :						Any):


         """simple docstring"""







         with open(UpperCamelCase_) as stream:
              a					:							Tuple							= load(UpperCamelCase_							,							Loader=UpperCamelCase_)
         return data





    def __str__(					self     :						Dict):


         """simple docstring"""







         a					:							Optional[Any]							= '    '
         if self._name != "root":
              a					:							Any							= f"""{t * (self._level-1)}{self._name}:\n"""
         else:
              a					:							Optional[int]							= ''
         a					:							int							= 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"""
              a					:							Optional[Any]							= level
         return r[:-1]





    @classmethod
    def    SCREAMING_SNAKE_CASE_     (					cls     :						Optional[Any]							,							UpperCAmelCase_     :						str							,							**UpperCAmelCase_     :						Optional[int]):


         """simple docstring"""







         a					:							Optional[int]							= cls.get_config_dict(UpperCamelCase_							,							**UpperCamelCase_)
         return cls(UpperCamelCase_)







    @classmethod
    def    SCREAMING_SNAKE_CASE_     (					cls     :						Optional[Any]							,							UpperCAmelCase_     :						str							,							**UpperCAmelCase_     :						Dict):


         """simple docstring"""







         a					:							Union[str, Any]							= kwargs.pop('cache_dir'							,							UpperCamelCase_)
         a					:							Optional[Any]							= kwargs.pop('force_download'							,							UpperCamelCase_)
         a					:							Any							= kwargs.pop('resume_download'							,							UpperCamelCase_)
         a					:							int							= kwargs.pop('proxies'							,							UpperCamelCase_)
         a					:							int							= kwargs.pop('local_files_only'							,							UpperCamelCase_)

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

         try:
              # Load from URL or cache if already cached
              a					:							List[str]							= 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

              a					:							Dict							= Config.load_yaml(UpperCamelCase_)

         except EnvironmentError:
              a					:							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 SCREAMING_SNAKE_CASE__  (				snake_case       :				Union[str, Any]  )   ->				Optional[Any]:







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

     # Hugging face functions below






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Optional[int]  )   ->				str:







     """simple docstring"""
     a					:							Optional[Any]							= urlparse(_lowercase  )
     return parsed.scheme in ("http", "https")






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Optional[Any]				,	snake_case       :				int				,	snake_case       :				Dict=True  )   ->				str:







     """simple docstring"""
     a					:							List[str]							= CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
     a					:							List[str]							= '/' not in model_id
     if legacy_format:
          return F"""{endpoint}/{model_id}-{filename}"""
     else:
          return F"""{endpoint}/{model_id}/{filename}"""






def SCREAMING_SNAKE_CASE__  (				snake_case       :				List[str]				,	snake_case       :				Optional[int]				,	snake_case       :				Optional[Any]=None				,	snake_case       :				Any=0				,	snake_case       :				Optional[Any]=None				,	)   ->				Dict:







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






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Optional[Any]				,	snake_case       :				Dict=None				,	snake_case       :				Optional[Any]=False				,	snake_case       :				str=None				,	snake_case       :				List[Any]=10				,	snake_case       :				str=False				,	snake_case       :				Union[str, Any]=None				,	snake_case       :				List[str]=False				,	)   ->				Tuple:







     """simple docstring"""
     if cache_dir is None:
          a					:							List[str]							= TRANSFORMERS_CACHE
     if isinstance(_lowercase				,	_lowercase  ):
          a					:							Dict							= str(_lowercase  )

     os.makedirs(_lowercase				,	exist_ok=_lowercase  )

     a					:							Any							= None
     if not local_files_only:
          try:
               a					:							Optional[int]							= requests.head(_lowercase				,	allow_redirects=_lowercase				,	proxies=_lowercase				,	timeout=_lowercase  )
               if response.status_code == 200:
                    a					:							List[str]							= response.headers.get('ETag'  )
          except (EnvironmentError, requests.exceptions.Timeout):
               # etag is already None
               pass

     a					:							Dict							= url_to_filename(_lowercase				,	_lowercase  )

     # get cache path to put the file
     a					:							Optional[Any]							= os.path.join(_lowercase				,	_lowercase  )

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

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

          if resume_download:
               a					:							Optional[Any]							= cache_path + '.incomplete'

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

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

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

          os.replace(temp_file.name				,	_lowercase  )

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

     return cache_path






def SCREAMING_SNAKE_CASE__  (				snake_case       :				str				,	snake_case       :				str=None  )   ->				List[Any]:







     """simple docstring"""
     a					:							Optional[Any]							= url.encode('utf-8'  )
     a					:							Optional[int]							= shaaaa(_lowercase  )
     a					:							Dict							= url_hash.hexdigest()

     if etag:
          a					:							Tuple							= etag.encode('utf-8'  )
          a					:							Optional[int]							= shaaaa(_lowercase  )
          filename += "." + etag_hash.hexdigest()

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

     return filename






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







     """simple docstring"""
     if cache_dir is None:
          a					:							List[str]							= TRANSFORMERS_CACHE
     if isinstance(_lowercase				,	_lowercase  ):
          a					:							List[str]							= str(_lowercase  )
     if isinstance(_lowercase				,	_lowercase  ):
          a					:							Optional[int]							= str(_lowercase  )

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

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

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

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

          return output_path_extracted

     return output_path






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Optional[int]				,	snake_case       :				Optional[int]=","  )   ->				str:







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






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







     """simple docstring"""
     a					:							Dict							= requests.get(_lowercase  )
     a					:							Optional[int]							= np.array(Image.open(BytesIO(response.content  )  )  )
     return img






def SCREAMING_SNAKE_CASE__  (				snake_case       :				Tuple  )   ->				List[Any]:







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






def SCREAMING_SNAKE_CASE__  (				)   ->				Dict:







     """simple docstring"""
     print(F"""{os.path.abspath(os.path.join(_lowercase				,	os.pardir  )  )}/demo.ipynb"""  )






def SCREAMING_SNAKE_CASE__  (				snake_case       :				List[str]				,	snake_case       :				str="RGB"  )   ->				Optional[Any]:







     """simple docstring"""
     assert isinstance(_lowercase				,	_lowercase  )
     if os.path.isfile(_lowercase  ):
          a					:							int							= cva.imread(_lowercase  )
     else:
          a					:							Optional[int]							= get_image_from_url(_lowercase  )
          assert img is not None, F"""could not connect to: {im}"""
     a					:							Tuple							= cva.cvtColor(_lowercase				,	cva.COLOR_BGR2RGB  )
     if input_format == "RGB":
          a					:							Optional[Any]							= img[:, :, ::-1]
     return img






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







     """simple docstring"""
     return (images[i : i + batch] for i in range(0				,	len(_lowercase  )				,	_lowercase  ))






'''simple docstring'''

def     __UpperCamelCase					(				_lowercase = 1000       )			->      int:
	_lowercase       :							Dict  	=		0
	_lowercase       :							int  	=		0
	while 1:
		num += 3
		if num >= n:
			break
		total += num
		num += 2
		if num >= n:
			break
		total += num
		num += 1
		if num >= n:
			break
		total += num
		num += 3
		if num >= n:
			break
		total += num
		num += 1
		if num >= n:
			break
		total += num
		num += 2
		if num >= n:
			break
		total += num
		num += 3
		if num >= n:
			break
		total += num
	return total


if __name__ == "__main__":
		print(F'''{solution() = }''')
