~L iUddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZmZmZddlmZddlmZmZddlmZddlmZmZddlZddlmZGd d Z dd l m Z gd Z"ejFd Z$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,da-ee.e/d<ej`dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9 dAd"Z: dBd#Z;d$Zd'e.fd(Z?d)ee.ejfd'dfd*ZA dCd+ZBdDd,ZCd-dd!d d!d.d/ZDd0ZE dEd1e.d2e.d3ee.d4eFd'df d5ZGd6e.d'eFfd7ZHed8eI9d6e.d:e.d;edeFd?ee.d> 1 1$ =D    ^^ , ,T 2F dkk6 ** *KKF# Mrctjj|rKtjj|rtj|yt j |yyr')osrNexistsisfilerPshutilrmtreerQs r_remove_if_existsrhws> ww~~d 77>>$  IIdO MM$  rcd|d|d|S)Nhttps://github.com//z /zipball/r() repo_owner repo_namerefs r_git_archive_linkros  Ai[ # GGrc6|t|vryt||Sr')dirgetattr)r` func_names r_load_attr_from_modulertsF # 69 %%rc tjjtjttjj tjt td}|S)Ntorch)rcrN expandusergetenvENV_TORCH_HOMEjoinENV_XDG_CACHE_HOMEDEFAULT_CACHE_DIR) torch_homes r_get_torch_homer~sL##  GGLL#57HI7 S J rc d|vr|jd\}}n|d}}|jd\}}| td|d|d5d}ddd|||fS#1swYxYw#t$r}|jdk(rd}nYd}~2d}~wt$ra}dD]8}t j jtd|d |d |s6|}n|td td |Yd}~d}~wwxYw) N:rkrjz /tree/main/mainimaster)rr_z\It looks like there is no internet connection and the repo could not be found in the cache ()) splitr rcoder rcrNrdr> RuntimeError)github repo_infornrlrme possible_refs r_parse_repo_infors+ f}c* 33 %OOC0J  { .zl!I;kRS  ( y# %%)   vv}  2  77>>yk:,a {!L>J'C   {"==DYKqJ sAA#A A#A A## C1,B C17C,C,,C1ct|5}|jj|jj dcdddS#1swYyxYw)Nzutf-8)r readdecodeheadersget_content_charset)urlrs r _read_urlrsE Gvvxqyy<rcmakedirsrreplacerzrN_check_repo_is_trustedrdr r!r"rrhrostdoutr=rrwarningswarnzipfileZipFileinfolistfilename extractallrfmove)r force_reloadrrverboseskip_validationhub_dirrlrmrn normalized_browner_name_branchrepo_dir use_cache cached_filererrdisambiguated_branch_refcached_zipfileextraced_repo_nameextracted_repos r_get_cache_or_reloadrs>iGKK$'!1&!9J 3 KKS)M *i!GHww||G%67H "!?rww~~h'?I  JJ  4XJbA BX OS ' Is Cggll7MF,BC +& #J 3?C JJ  ~cU% }BG H kE B*__[ ) /^!/!8!8!:1!=!F!F WW\\'3EFN n -  % %g .  / +&(# NH- O? xx3  se$dd .9+>(' /G%S+FG! ( / /s'AG8(AI8 IA III"c<t}tjj|d}tjj |st |j t|5}td|D}dddttj|d} dj||g} | vxs|| vxs|tv} || stjd|d|dy|dus|d k(r]| s[td | d } | jd vr| r8t!d n,| jdvr t#dt%d| d| s*t|d5}|j'| dzdddyy#1swYxYw#1swYyxYw)N trusted_listc3<K|]}|jywr')strip).0lines r z)_check_repo_is_trusted..?srcrNrzrdrtouchopentuplenextwalk_TRUSTED_REPO_OWNERSrrinputlowerprint Exceptionrr") rlrmrrrrfilepathfile trusted_repostrusted_repos_legacy owner_name is_trustedrs rrr2siGww||G^4H 77>>( # X h=4> | +:; ^^  034 45hZqAB B  (C  *D JJzD( ) * * S==T * *s.F&FFFcDddl}|jj|duSr)rUrW find_spec)r]r^s r_check_module_existsrls >> # #D ) 55rct|t}|D|Dcgc]}t|r|}}t|rt ddj |yycc}w)NzMissing dependencies: z, )rtVAR_DEPENDENCYrlenrrz)mrKpkg missing_depss r_check_dependenciesrrsb)!^25'EFF KrreturnctjdrtjdttStj j tdS)a Get the Torch Hub cache directory used for storing downloaded models & weights. If :func:`~torch.hub.set_dir` is not called, default path is ``$TORCH_HOME/hub`` where environment variable ``$TORCH_HOME`` defaults to ``$XDG_CACHE_HOME/torch``. ``$XDG_CACHE_HOME`` follows the X Design Group specification of the Linux filesystem layout, with a default value ``~/.cache`` if the environment variable is not set. TORCH_HUBz:TORCH_HUB is deprecated, please use env TORCH_HOME insteadhub)rcrxrrrLrNrzr~r(rrr>r>s@ yy RS 77<<)5 11rdcBtjj|ay)z Optionally set the Torch Hub directory used to save downloaded models & weights. Args: d (str): path to a local folder to save downloaded models & weights. N)rcrNrwrL)rs rrCrCsww!!!$Hrc Vt|||d||}t|5tjj |t }t t |}dddtDcgc]*}tt||r|jds|,} }| S#1swYIxYwcc}w)a* List all callable entrypoints available in the repo specified by ``github``. Args: github (str): a string with format "repo_owner/repo_name[:ref]" with an optional ref (tag or branch). If ``ref`` is not specified, the default branch is assumed to be ``main`` if it exists, and otherwise ``master``. Example: 'pytorch/vision:0.10' force_reload (bool, optional): whether to discard the existing cache and force a fresh download. Default is ``False``. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit specified by the ``github`` argument properly belongs to the repo owner. This will make requests to the GitHub API; you can specify a non-default GitHub token by setting the ``GITHUB_TOKEN`` environment variable. Default is ``False``. trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``. This parameter was introduced in v1.12 and helps ensuring that users only run code from repos that they trust. - If ``False``, a prompt will ask the user whether the repo should be trusted. - If ``True``, the repo will be added to the trusted list and loaded without requiring explicit confirmation. - If ``"check"``, the repo will be checked against the list of trusted repos in the cache. If it is not present in that list, the behaviour will fall back onto the ``trust_repo=False`` option. - If ``None``: this will raise a warning, inviting the user to set ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This is only present for backward compatibility and will be removed in v2.0. Default is ``None`` and will eventually change to ``"check"`` in v2.0. verbose (bool, optional): If ``False``, mute messages about hitting local caches. Note that the message about first download cannot be muted. Default is ``True``. Returns: list: The available callables entrypoint Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) >>> entrypoints = torch.hub.list("pytorch/vision", force_reload=True) r@rrNr) rrRrcrNrzMODULE_HUBCONFrarqrrrr) rrrrrr hubconf_path hub_modulef entrypointss rr@r@sb$' H ( #Bww||Hn= #NLA BZ GJ* +ALL4E K BB s5B'/B&B#ct|||dd|}t|5tjj |t }t t |}dddt|}|jS#1swY!xYw)aT Show the docstring of entrypoint ``model``. Args: github (str): a string with format with an optional ref (a tag or a branch). If ``ref`` is not specified, the default branch is assumed to be ``main`` if it exists, and otherwise ``master``. Example: 'pytorch/vision:0.10' model (str): a string of entrypoint name defined in repo's ``hubconf.py`` force_reload (bool, optional): whether to discard the existing cache and force a fresh download. Default is ``False``. skip_validation (bool, optional): if ``False``, torchhub will check that the ref specified by the ``github`` argument properly belongs to the repo owner. This will make requests to the GitHub API; you can specify a non-default GitHub token by setting the ``GITHUB_TOKEN`` environment variable. Default is ``False``. trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``. This parameter was introduced in v1.12 and helps ensuring that users only run code from repos that they trust. - If ``False``, a prompt will ask the user whether the repo should be trusted. - If ``True``, the repo will be added to the trusted list and loaded without requiring explicit confirmation. - If ``"check"``, the repo will be checked against the list of trusted repos in the cache. If it is not present in that list, the behaviour will fall back onto the ``trust_repo=False`` option. - If ``None``: this will raise a warning, inviting the user to set ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This is only present for backward compatibility and will be removed in v2.0. Default is ``None`` and will eventually change to ``"check"`` in v2.0. Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) >>> print(torch.hub.help("pytorch/vision", "resnet18", force_reload=True)) r?TrN) rrRrcrNrzrrar__doc__) rrrrrrrrentrys rr?r?s|J$' H ( #Bww||Hn= #NLA B %Z 7E == BBs 5A22A;r)sourcerrrrc|j}|dvrtd|d|dk(rt|||d||}t||g|i|}|S)a Load a model from a github repo or a local directory. Note: Loading a model is the typical use case, but this can also be used to for loading other objects such as tokenizers, loss functions, etc. If ``source`` is 'github', ``repo_or_dir`` is expected to be of the form ``repo_owner/repo_name[:ref]`` with an optional ref (a tag or a branch). If ``source`` is 'local', ``repo_or_dir`` is expected to be a path to a local directory. Args: repo_or_dir (str): If ``source`` is 'github', this should correspond to a github repo with format ``repo_owner/repo_name[:ref]`` with an optional ref (tag or branch), for example 'pytorch/vision:0.10'. If ``ref`` is not specified, the default branch is assumed to be ``main`` if it exists, and otherwise ``master``. If ``source`` is 'local' then it should be a path to a local directory. model (str): the name of a callable (entrypoint) defined in the repo/dir's ``hubconf.py``. *args (optional): the corresponding args for callable ``model``. source (str, optional): 'github' or 'local'. Specifies how ``repo_or_dir`` is to be interpreted. Default is 'github'. trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``. This parameter was introduced in v1.12 and helps ensuring that users only run code from repos that they trust. - If ``False``, a prompt will ask the user whether the repo should be trusted. - If ``True``, the repo will be added to the trusted list and loaded without requiring explicit confirmation. - If ``"check"``, the repo will be checked against the list of trusted repos in the cache. If it is not present in that list, the behaviour will fall back onto the ``trust_repo=False`` option. - If ``None``: this will raise a warning, inviting the user to set ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This is only present for backward compatibility and will be removed in v2.0. Default is ``None`` and will eventually change to ``"check"`` in v2.0. force_reload (bool, optional): whether to force a fresh download of the github repo unconditionally. Does not have any effect if ``source = 'local'``. Default is ``False``. verbose (bool, optional): If ``False``, mute messages about hitting local caches. Note that the message about first download cannot be muted. Does not have any effect if ``source = 'local'``. Default is ``True``. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit specified by the ``github`` argument properly belongs to the repo owner. This will make requests to the GitHub API; you can specify a non-default GitHub token by setting the ``GITHUB_TOKEN`` environment variable. Default is ``False``. **kwargs (optional): the corresponding kwargs for callable ``model``. Returns: The output of the ``model`` callable when called with the given ``*args`` and ``**kwargs``. Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) >>> # from a github repo >>> repo = "pytorch/vision" >>> model = torch.hub.load( ... repo, "resnet50", weights="ResNet50_Weights.IMAGENET1K_V1" ... ) >>> # from a local directory >>> path = "/some/local/path/pytorch/vision" >>> # xdoctest: +SKIP >>> model = torch.hub.load(path, "resnet50", weights="ResNet50_Weights.DEFAULT") )rlocalzUnknown source: "z&". Allowed values: "github" | "local".rrAr)rrr _load_local) repo_or_dirrr rrrrrrs rrArA*svb\\^F ((x'M N  *    +    U >> # xdoctest: +SKIP("stub local path") >>> path = "/some/local/path/pytorch/vision" >>> model = _load_local( ... path, ... "resnet50", ... weights="ResNet50_Weights.IMAGENET1K_V1", ... ) N)rRrcrNrzrrar) hubconf_dirrrrrrr s rrrse0 + &'ww||K@ #NLA (U;t&v& ' L' Ls A AA)rdst hash_prefixrcd}t|ddi}t|}|j}t|dr|j d}n|j d}|t |dkDrt|d}tjj|}ttjD]7} |dztjj zd z} t#| d } nt%t&j(d  |t+j,} t/|| d d d5} |j1t2}t |dk(rn?| j5|| j7|| j7t |c ddd| j9|3 j;}|dt ||k7rt=d|d|dt?j@| jB|| j9tjjE| jBr tjF| jByy#t$$rYwxYw#1swYxYw#| j9tjjE| jBr tjF| jBwwxYw)aDownload object at the given URL to a local path. Args: url (str): URL of the object to download dst (str): Full path where object will be saved, e.g. ``/tmp/temporary_file`` hash_prefix (str, optional): If not None, the SHA256 downloaded file should start with ``hash_prefix``. Default: None progress (bool, optional): whether or not to display a progress bar to stderr Default: True Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) >>> # xdoctest: +REQUIRES(POSIX) >>> torch.hub.download_url_to_file( ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth", ... "/tmp/temporary_file", ... ) Nz User-Agentz torch.hubr getheaderszContent-Lengthrrz.partialzw+bz#No usable temporary file name foundBTi)rrr unit_scale unit_divisorzinvalid hash value (expected "z", got "z"))$r r infohasattrrget_allrintrcrNrwrangetempfileTMP_MAXuuiduuid4hexrFileExistsErrorerrnoEEXISThashlibsha256r<rREAD_DATA_CHUNKr"r%r1 hexdigestrrfrr]rdrP)rrrr file_sizerequmetacontent_lengthrtmp_dstrr'pbarbufferdigests rr=r=sw2I # k: ;C A 668Dt\")9:&67!c.&9A&=q)*  ''  S !C 8## $S)djjl...; We$A  Sell,QRR  "^^%F  L   ) 0v;!#*MM&) CK( )   "%%'F(K()[8"4[M&QST  AFFC   77>>!&& ! IIaff  "G    ) )2  77>>!&& ! IIaff  "s9 I'I7.A%I+A-I7 I('I(+I40I77AKrctj|rGtj|j}t |dk(xr|dj Sy)NrrF)r is_zipfilerrris_dir)rrs r_is_legacy_zip_formatr6 sN(#??8,5578}!>(1+*<*<*>&>> rzFalling back to the old format < 1.6. This support will be deprecated in favor of default zipfile format introduced in 1.6. Please redo torch.save() to save it in the new zipfile format.)category model_dir map_location weights_onlycXtj|5}|j}t|dk7r t d|j ||dj }tjj||}dddtj||S#1swY!xYw)Nrz0Only one file(not dir) is allowed in the zipfilerr9r:) rrrrrrrrcrNrzrvrA)rr8r9r:rmembers extraced_nameextracted_files r_legacy_zip_loadr@s  "@a**, w<1 QR R Y ++ i? @ ::\  @@s A*B  B) check_hash file_namectjdrtjd|*t }tj j |d}tj|dt|}tj j|j } ||} tj j || } tj j| sctjjd|d| d d} |r*tj| } | r| j!d nd} t#|| | | t%| rt'| |||St)j*| || S) aqLoads the Torch serialized object at the given URL. If downloaded file is a zip file, it will be automatically decompressed. If the object is already present in `model_dir`, it's deserialized and returned. The default value of ``model_dir`` is ``/checkpoints`` where ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`. Args: url (str): URL of the object to download model_dir (str, optional): directory in which to save the object map_location (optional): a function or a dict specifying how to remap storage locations (see torch.load) progress (bool, optional): whether or not to display a progress bar to stderr. Default: True check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention ``filename-.ext`` where ```` is the first eight or more digits of the SHA256 hash of the contents of the file. The hash is used to ensure unique names and to verify the contents of the file. Default: False file_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set. weights_only(bool, optional): If True, only weights will be loaded and no complex pickled objects. Recommended for untrusted sources. See :func:`~torch.load` for more details. Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) >>> state_dict = torch.hub.load_state_dict_from_url( ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth" ... ) TORCH_MODEL_ZOOz@TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME insteadN checkpointsTrrrr,rrr<)rcrxrrr>rNrzrr basenamerdr rr" HASH_REGEXsearchgroupr=r6r@rvrA) rr8r9rrArBr:rpartsrrrrs rrBrB,s&T yy"# N )GGLL-8 KK D) SMEww +H'',,y(3K 77>>+ & >#eK=CD !!(+A()!''!*tKS+{XN[) Y lSS ::k < XXr)TF)rA)FFNT)FFNr/)NNTFNF)M contextlibr$r&rrcrerfr rr rrpathlibrtypingrrrtyping_extensionsr urllib.errorrr urllib.parser urllib.requestr r rvtorch.serializationr rr< ImportError__all__compilerGrrryr{r|rrr(rLr__annotations__contextmanagerrRrarhrortr~rrrrrrrrr>PathLikerCr@r?rArboolr=r6 FutureWarningdictr@rBr(rrr]s   ''(,!+ ,##L RZZ) *  "%(3-   H & &FG L  Qr 7*t6 S$22&%uS"++%&%4%  EP4v  cLJ"& R R R#R R  RpCD E     #s(^   . $!%#DY DY}DYDY DY  DY } DYDY #s(^DYW Ds3FF  F