





'''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				:      List[str]						      =True
except ImportError:
  __lowerCAmelCase				:      str						      =False


try:
  from torch.hub import _get_torch_home

  __lowerCAmelCase				:      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				:      Tuple						      =os.path.join(torch_cache_home, "transformers")

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





def 		UpperCamelCase							(				_lowerCamelCase   :   Optional[int]=OBJECTS		,			_lowerCamelCase   :   Optional[int]=ATTRIBUTES			):
    A__							=     []
    with open(_lowerCamelCase			) as f:
        for object in f.readlines():
            vg_classes.append(object.split(","			)[0].lower().strip()			)

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





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






class   UpperCAmelCase      :
 __lowercase  						=							{}
 def __init__(							self :List[Any]		,			lowercase_ :dict		,			lowercase_ :str = "root"		,			lowercase_ :Union[str, Any]=0				)->				Tuple:
     A__							=     name
     A__							=     level
     A__							=     {}
     for k, v in dictionary.items():
         if v is None:
             raise ValueError()
         A__							=     copy.deepcopy(lowercase_				)
         A__							=     copy.deepcopy(lowercase_				)
         if isinstance(lowercase_		,			lowercase_				):
             A__							=     Config(lowercase_		,			name=lowercase_		,			level=level + 1				)
         A__							=     v
         setattr(self		,			lowercase_		,			lowercase_				)

     A__							=     d
 def __repr__(							self :List[Any]				)->				List[Any]:
     return str(list((self._pointer.keys())				)				)
 def __setattr__(							self :List[str]		,			lowercase_ :Dict		,			lowercase_ :List[Any]				)->				int:
     A__							=     val
     A__							=     val
     A__							=     key.split("."				)
     A__							=     len(lowercase_				) - 1
     A__							=     self._pointer
     if len(lowercase_				) > 1:
         for i, l in enumerate(lowercase_				):
             if hasattr(self		,			lowercase_				) and isinstance(getattr(self		,			lowercase_				)		,			lowercase_				):
                 setattr(getattr(self		,			lowercase_				)		,			".".join(levels[i:]				)		,			lowercase_				)
             if l == last_level:
                 A__							=     val
             else:
                 A__							=     pointer[l]
 def 	UpperCAmelCase_				(							self :Dict				)->				Any:
     return self._pointer
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :Optional[int]		,			lowercase_ :List[Any]				)->				Dict:
     with open(F"{file_name}"		,			"w"				) as stream:
         dump(lowercase_		,			lowercase_				)
 def 	UpperCAmelCase_				(							self :List[str]		,			lowercase_ :Union[str, Any]		,			lowercase_ :Optional[int]				)->				Union[str, Any]:
     with open(F"{file_name}"		,			"w"				) as stream:
         json.dump(lowercase_		,			lowercase_				)
 @staticmethod
 def 	UpperCAmelCase_				(							lowercase_ :List[Any]				)->				str:
     with open(lowercase_				) as stream:
         A__							=     load(lowercase_		,			Loader=lowercase_				)
     return data
 def __str__(							self :List[Any]				)->				Dict:
     A__							=     "    "
     if self._name != "root":
         A__							=     F"{t * (self._level-1)}{self._name}:\n"
     else:
         A__							=     ""
     A__							=     self._level
     for i, (k, v) in enumerate(self._pointer.items()				):
         if isinstance(lowercase_		,			lowercase_				):
             r += F"{t * (self._level)}{v}\n"
             self._level += 1
         else:
             r += F"{t * (self._level)}{k}: {v} ({type(lowercase_				).__name__})\n"
         A__							=     level
     return r[:-1]
 @classmethod
 def 	UpperCAmelCase_				(							cls :List[str]		,			lowercase_ :str		,			**lowercase_ :List[str]				)->				List[str]:
     A__,      A__							=     cls.get_config_dict(lowercase_		,			**lowercase_				)
     return cls(lowercase_				)



 @classmethod
 def 	UpperCAmelCase_				(							cls :Optional[Any]		,			lowercase_ :str		,			**lowercase_ :Optional[int]				)->				Optional[int]:
     A__							=     kwargs.pop("cache_dir"		,			lowercase_				)
     A__							=     kwargs.pop("force_download"		,			lowercase_				)
     A__							=     kwargs.pop("resume_download"		,			lowercase_				)
     A__							=     kwargs.pop("proxies"		,			lowercase_				)
     A__							=     kwargs.pop("local_files_only"		,			lowercase_				)

     if os.path.isdir(lowercase_				):
         A__							=     os.path.join(lowercase_		,			lowercase_				)
     elif os.path.isfile(lowercase_				) or is_remote_url(lowercase_				):
         A__							=     pretrained_model_name_or_path
     else:
         A__							=     hf_bucket_url(lowercase_		,			filename=lowercase_		,			use_cdn=lowercase_				)

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

         A__							=     Config.load_yaml(lowercase_				)

     except EnvironmentError:
         A__							=     "Can't load config for"
         raise EnvironmentError(lowercase_				)

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

     return Config.load_yaml(lowercase_				), kwargs





def 		UpperCamelCase							(				_lowerCamelCase   :   Dict			):
    A__							=     torch.load("dump.pt"		,			map_location=in_tensor.device			)
    A__							=     in_tensor.numpy()
    A__							=     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.0_1		,			atol=0.1			), (
        F"{sum([1 for x in np.isclose(_lowerCamelCase		,			_lowerCamelCase		,			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 		UpperCamelCase							(				_lowerCamelCase   :   Dict			):
    A__							=     urlparse(_lowerCamelCase			)
    return parsed.scheme in ("http", "https")





def 		UpperCamelCase							(				_lowerCamelCase   :   str		,			_lowerCamelCase   :   str		,			_lowerCamelCase   :   int=True			):
    A__							=     CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
    A__							=     "/" not in model_id
    if legacy_format:
        return F"{endpoint}/{model_id}-{filename}"
    else:
        return F"{endpoint}/{model_id}/{filename}"





def 		UpperCamelCase							(				_lowerCamelCase   :   int		,			_lowerCamelCase   :   Optional[int]		,			_lowerCamelCase   :   str=None		,			_lowerCamelCase   :   Any=0		,			_lowerCamelCase   :   Dict=None		,			):
    A__							=     "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
    A__							=     {"user-agent": ua}
    if resume_size > 0:
        A__							=     "bytes=%d-" % (resume_size,)
    A__							=     requests.get(_lowerCamelCase		,			stream=_lowerCamelCase		,			proxies=_lowerCamelCase		,			headers=_lowerCamelCase			)
    if response.status_code == 4_16:  # Range not satisfiable
        return
    A__							=     response.headers.get("Content-Length"			)
    A__							=     resume_size + int(_lowerCamelCase			) if content_length is not None else None
    A__							=     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 		UpperCamelCase							(				_lowerCamelCase   :   Dict		,			_lowerCamelCase   :   List[str]=None		,			_lowerCamelCase   :   int=False		,			_lowerCamelCase   :   Any=None		,			_lowerCamelCase   :   Union[str, Any]=10		,			_lowerCamelCase   :   Tuple=False		,			_lowerCamelCase   :   Dict=None		,			_lowerCamelCase   :   Any=False		,			):
    if cache_dir is None:
        A__							=     TRANSFORMERS_CACHE
    if isinstance(_lowerCamelCase		,			_lowerCamelCase			):
        A__							=     str(_lowerCamelCase			)

    os.makedirs(_lowerCamelCase		,			exist_ok=_lowerCamelCase			)

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

    A__							=     url_to_filename(_lowerCamelCase		,			_lowerCamelCase			)

    # get cache path to put the file
    A__							=     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:
            A__							=     [
                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.
    A__							=     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:
            A__							=     cache_path + ".incomplete"

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

            A__							=     _resumable_file_manager
            if os.path.exists(_lowerCamelCase			):
                A__							=     os.stat(_lowerCamelCase			).st_size
            else:
                A__							=     0
        else:
            A__							=     partial(tempfile.NamedTemporaryFile		,			dir=_lowerCamelCase		,			delete=_lowerCamelCase			)
            A__							=     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			)

        A__							=     {"url": url, "etag": etag}
        A__							=     cache_path + ".json"
        with open(_lowerCamelCase		,			"w"			) as meta_file:
            json.dump(_lowerCamelCase		,			_lowerCamelCase			)

    return cache_path





def 		UpperCamelCase							(				_lowerCamelCase   :   Optional[Any]		,			_lowerCamelCase   :   Optional[int]=None			):
    A__							=     url.encode("utf-8"			)
    A__							=     shaaaa(_lowerCamelCase			)
    A__							=     url_hash.hexdigest()

    if etag:
        A__							=     etag.encode("utf-8"			)
        A__							=     shaaaa(_lowerCamelCase			)
        filename += "." + etag_hash.hexdigest()

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

    return filename





def 		UpperCamelCase							(				_lowerCamelCase   :   List[Any]		,			_lowerCamelCase   :   Any=None		,			_lowerCamelCase   :   Optional[int]=False		,			_lowerCamelCase   :   int=None		,			_lowerCamelCase   :   Optional[Any]=False		,			_lowerCamelCase   :   Dict=None		,			_lowerCamelCase   :   List[str]=False		,			_lowerCamelCase   :   Optional[Any]=False		,			_lowerCamelCase   :   Tuple=False		,			):
    if cache_dir is None:
        A__							=     TRANSFORMERS_CACHE
    if isinstance(_lowerCamelCase		,			_lowerCamelCase			):
        A__							=     str(_lowerCamelCase			)
    if isinstance(_lowerCamelCase		,			_lowerCamelCase			):
        A__							=     str(_lowerCamelCase			)

    if is_remote_url(_lowerCamelCase			):
        # URL, so get it from the cache (downloading if necessary)
        A__							=     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.
        A__							=     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/"
        A__,      A__							=     os.path.split(_lowerCamelCase			)
        A__							=     output_file.replace("."		,			"-"			) + "-extracted"
        A__							=     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
        A__							=     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			):
                A__							=     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 		UpperCamelCase							(				_lowerCamelCase   :   Optional[Any]		,			_lowerCamelCase   :   str=","			):
    assert isinstance(_lowerCamelCase		,			_lowerCamelCase			)
    if os.path.isfile(_lowerCamelCase			):
        with open(_lowerCamelCase			) as f:
            A__							=     eval(f.read()			)
    else:
        A__							=     requests.get(_lowerCamelCase			)
        try:
            A__							=     requests.json()
        except Exception:
            A__							=     req.content.decode()
            assert data is not None, "could not connect"
            try:
                A__							=     eval(_lowerCamelCase			)
            except Exception:
                A__							=     data.split("\n"			)
        req.close()
    return data





def 		UpperCamelCase							(				_lowerCamelCase   :   str			):
    A__							=     requests.get(_lowerCamelCase			)
    A__							=     np.array(Image.open(BytesIO(response.content			)			)			)
    return img





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





def 		UpperCamelCase							(				):
    print(F"{os.path.abspath(os.path.join(_lowerCamelCase		,			os.pardir			)			)}/demo.ipynb"			)





def 		UpperCamelCase							(				_lowerCamelCase   :   List[str]		,			_lowerCamelCase   :   Tuple="RGB"			):
    assert isinstance(_lowerCamelCase		,			_lowerCamelCase			)
    if os.path.isfile(_lowerCamelCase			):
        A__							=     cva.imread(_lowerCamelCase			)
    else:
        A__							=     get_image_from_url(_lowerCamelCase			)
        assert img is not None, F"could not connect to: {im}"
    A__							=     cva.cvtColor(_lowerCamelCase		,			cva.COLOR_BGR2RGB			)
    if input_format == "RGB":
        A__							=     img[:, :, ::-1]
    return img





def 		UpperCamelCase							(				_lowerCamelCase   :   Any		,			_lowerCamelCase   :   Any=1			):
    return (images[i : i + batch] for i in range(0		,			len(_lowerCamelCase			)		,			_lowerCamelCase			))










'''simple docstring'''

from string import ascii_uppercase

__lowerCAmelCase				:      Union[str, Any]						      ={str(ord(c) - 55): c for c in ascii_uppercase}





def 		UpperCamelCase							(				_lowerCamelCase   :   int		,			_lowerCamelCase   :   int			):
    if isinstance(_lowerCamelCase		,			_lowerCamelCase			):
        raise TypeError("int() can't convert non-string with explicit base"			)
    if num < 0:
        raise ValueError("parameter must be positive int"			)
    if isinstance(_lowerCamelCase		,			_lowerCamelCase			):
        raise TypeError("'str' object cannot be interpreted as an integer"			)
    if isinstance(_lowerCamelCase		,			_lowerCamelCase			):
        raise TypeError("'float' object cannot be interpreted as an integer"			)
    if base in (0, 1):
        raise ValueError("base must be >= 2"			)
    if base > 36:
        raise ValueError("base must be <= 36"			)
    A__							=     ""
    A__							=     0
    A__							=     0
    while div != 1:
        A__,      A__							=     divmod(_lowerCamelCase		,			_lowerCamelCase			)
        if base >= 11 and 9 < mod < 36:
            A__							=     ALPHABET_VALUES[str(_lowerCamelCase			)]
        else:
            A__							=     str(_lowerCamelCase			)
        new_value += actual_value
        A__							=     num // base
        A__							=     div
        if div == 0:
            return str(new_value[::-1]			)
        elif div == 1:
            new_value += str(_lowerCamelCase			)
            return str(new_value[::-1]			)

    return new_value[::-1]


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  for base in range(2, 37):
    for num in range(1000):
      assert int(decimal_to_any(num, base), base) == num, (
          num,
          base,
          decimal_to_any(num, base),
          int(decimal_to_any(num, base), base),
      )



