a
    –¥»aK[  ã                   @   sÖ  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlmZ d dlmZmZ d dlmZ zd dlmZ W nF eyÖ   zd dlmZ W n" eyÐ   G dd„ deƒZY n0 Y n0 e d¡Zd	Zd
ZdZdZdZdZdZdadd„ Z dd„ Z!dd„ Z"dd„ Z#dd„ Z$dd„ Z%dd„ Z&dd„ Z'dBd"d#„Z(d$d%„ Z)d&d'„ Z*d(d)„ Z+d*d+„ Z,d,d-„ Z-dCd.d/„Z.dDd0d1„Z/d2d!d d!d3œd4d5„Z0d6d7„ Z1dEd8d9„Z2dFd:d;„Z3d<d=„ Z4d>d?„ Z5dGd@dA„Z6dS )Hé    N)Ú	HTTPError)ÚurlopenÚRequest)Úurlparse)Útqdmc                   @   s6   e Zd Zddd„Zdd„ Zdd„ Zd	d
„ Zdd„ ZdS )r   NFc                 C   s   || _ || _d| _d S ©Nr   )ÚtotalÚdisableÚn)Úselfr   r	   ÚunitÚ
unit_scaleÚunit_divisor© r   úC/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/hub.pyÚ__init__   s    ztqdm.__init__c                 C   sh   | j r
d S |  j|7  _| jd u r8tj d | j¡¡ n"tj d d| j t| jƒ ¡¡ tj ¡  d S )Nz{0:.1f} bytesz	{0:.1f}%éd   )	r	   r
   r   ÚsysÚstderrÚwriteÚformatÚfloatÚflush)r   r
   r   r   r   Úupdate!   s    
"ztqdm.updatec                 C   s
   d| _ d S )NT)r	   ©r   r   r   r   Úclose,   s    z
tqdm.closec                 C   s   | S ©Nr   r   r   r   r   Ú	__enter__/   s    ztqdm.__enter__c                 C   s   | j r
d S tj d¡ d S )NÚ
)r	   r   r   r   )r   Úexc_typeÚexc_valÚexc_tbr   r   r   Ú__exit__2   s    ztqdm.__exit__)NFNNN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r"   r   r   r   r   r      s     ÿ
r   z-([a-f0-9]*)\.ZGITHUB_TOKENZ
TORCH_HOMEÚXDG_CACHE_HOMEz~/.cacheÚdependenciesz
hubconf.pyé    c                 C   sN   dd l }ddlm} |j | |¡}|j |¡}t|j|ƒs>J ‚|j |¡ |S )Nr   )ÚLoader)	Úimportlib.utilÚimportlib.abcr)   ÚutilÚspec_from_file_locationÚmodule_from_specÚ
isinstanceÚloaderÚexec_module)ÚnameÚpathÚ	importlibr)   ÚspecÚmoduler   r   r   Úimport_moduleF   s    r7   c                 C   s2   t j | ¡r.t j | ¡r$t  | ¡ n
t | ¡ d S r   )Úosr3   ÚexistsÚisfileÚremoveÚshutilÚrmtree)r3   r   r   r   Ú_remove_if_existsP   s    r>   c                 C   s   d  | ||¡S )Nz'https://github.com/{}/{}/archive/{}.zip)r   )Ú
repo_ownerÚ	repo_nameÚbranchr   r   r   Ú_git_archive_linkX   s    rB   c                 C   s   |t | ƒvrd S t| |ƒS r   )ÚdirÚgetattr)r6   Ú	func_namer   r   r   Ú_load_attr_from_module\   s    rF   c                  C   s*   t j t  tt j t  tt¡d¡¡¡} | S )NÚtorch)r8   r3   Ú
expanduserÚgetenvÚENV_TORCH_HOMEÚjoinÚENV_XDG_CACHE_HOMEÚDEFAULT_CACHE_DIR)Z
torch_homer   r   r   Ú_get_torch_homec   s    ÿÿÿÿrN   c              
   C   s¸   d| v r|   d¡\}}n
| d  }}|  d¡\}}|d u r®z>td|› d|› d�ƒ� d}W d   ƒ n1 sj0    Y  W n6 ty¬ } z|jdkr–d}n‚ W Y d }~n
d }~0 0 |||fS )Nú:ú/zhttps://github.com/z/tree/main/Úmaini”  Zmaster)Úsplitr   r   Úcode)ÚgithubZ	repo_inforA   r?   r@   Úer   r   r   Ú_parse_repo_infok   s    
&
rV   c                 C   sB   t | ƒ�&}| ¡  |j d¡¡W  d   ƒ S 1 s40    Y  d S )Nzutf-8)r   ÚreadÚdecodeÚheadersÚget_content_charset)ÚurlÚrr   r   r   Ú	_read_url�   s    
r]   c           
      C   sÜ   ddi}t j t¡}|d ur*d|› �|d< d| › d|› d�d| › d|› d�fD ]l}d	}|d
7 }|› d|› �}t tt||d�ƒ¡}|sˆqN|D ]*}	|	d |ks®|	d d  |¡rŒ  d S qŒqVqNt	d|› d| › d|› d�ƒ‚d S )NÚAcceptzapplication/vnd.github.v3+jsonztoken ÚAuthorizationzhttps://api.github.com/repos/rP   z	/branchesz/tagsr   é   z?per_page=100&page=©rY   r2   ÚcommitÚshazCannot find z in https://github.com/zX. If it's a commit from a forked repo, please call hub.load() with forked repo directly.)
r8   ÚenvironÚgetÚENV_GITHUB_TOKENÚjsonÚloadsr]   r   Ú
startswithÚ
ValueError)
r?   r@   rA   rY   ÚtokenZ
url_prefixÚpager[   ÚresponseÚbrr   r   r   Ú_validate_not_a_forked_repo†   s"    þro   TFc                 C   sP  t ƒ }tj |¡st |¡ t| ƒ\}}}| dd¡}tj |d |||g¡¡}	| o`tj |	¡}
|
r~|r|tj	 
d |	¡¡ nÎ|sŽt|||ƒ tj ||d ¡}t|ƒ t|||ƒ}tj	 
d ||¡¡ t||dd� t |¡�>}| ¡ d j}tj ||¡}t|ƒ | |¡ W d   ƒ n1 �s&0    Y  t|ƒ t|	ƒ t ||	¡ |	S )	NrP   Ú_zUsing cache found in {}
z.zipúDownloading: "{}" to {}
F©Úprogressr   )Úget_dirr8   r3   r9   ÚmakedirsrV   ÚreplacerK   r   r   r   r   ro   r>   rB   Údownload_url_to_fileÚzipfileÚZipFileÚinfolistÚfilenameÚ
extractallr<   Úmove)rT   Úforce_reloadÚverboseÚskip_validationÚhub_dirr?   r@   rA   Znormalized_brÚrepo_dirZ	use_cacheÚcached_filer[   Zcached_zipfileZextraced_repo_nameZextracted_repor   r   r   Ú_get_cache_or_reloadŸ   s4    
*r„   c                 C   s   dd l }|j | ¡d uS r   )r*   r,   Ú	find_spec)r2   r4   r   r   r   Ú_check_module_existsÐ   s    r†   c                 C   s@   t | tƒ}|d ur<dd„ |D ƒ}t|ƒr<td d |¡¡ƒ‚d S )Nc                 S   s   g | ]}t |ƒs|‘qS r   )r†   )Ú.0Úpkgr   r   r   Ú
<listcomp>Ù   ó    z'_check_dependencies.<locals>.<listcomp>zMissing dependencies: {}z, )rF   ÚVAR_DEPENDENCYÚlenÚRuntimeErrorr   rK   )Úmr'   Úmissing_depsr   r   r   Ú_check_dependenciesÕ   s
    
r�   c                 C   sF   t |tƒstdƒ‚t| ƒ t| |ƒ}|d u s4t|ƒsBtd |¡ƒ‚|S )Nz8Invalid input: model should be a string of function namez"Cannot find callable {} in hubconf)r/   Ústrrj   r�   rF   Úcallabler�   r   )rŽ   ÚmodelÚfuncr   r   r   Ú_load_entry_from_hubconfÞ   s    

r•   c                   C   s0   t  d¡rt d¡ tdur tS t j tƒ d¡S )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.
    Z	TORCH_HUBz:TORCH_HUB is deprecated, please use env TORCH_HOME insteadNZhub)r8   rI   ÚwarningsÚwarnÚ_hub_dirr3   rK   rN   r   r   r   r   rt   ð   s
    

rt   c                 C   s   | a dS )zµ
    Optionally set the Torch Hub directory used to save downloaded models & weights.

    Args:
        d (string): path to a local folder to save downloaded models & weights.
    N)r˜   )Údr   r   r   Úset_dir  s    rš   c                    s\   t | |d|d�}tj d|¡ tj |t¡}tt|ƒ‰ tj |¡ ‡ fdd„t	ˆ ƒD ƒ}|S )a"  
    List all callable entrypoints available in the repo specified by ``github``.

    Args:
        github (string): a string with format "repo_owner/repo_name[:tag_name]" with an optional
            tag/branch. If ``tag_name`` 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``.
    Returns:
        list: The available callables entrypoint

    Example:
        >>> entrypoints = torch.hub.list('pytorch/vision', force_reload=True)
    T©r   r€   r   c                    s(   g | ] }t tˆ |ƒƒr| d ¡s|‘qS )rp   )r’   rD   ri   )r‡   Úf©Ú
hub_moduler   r   r‰   -  rŠ   zlist.<locals>.<listcomp>)
r„   r   r3   Úinsertr8   rK   ÚMODULE_HUBCONFr7   r;   rC   )rT   r~   r€   r‚   Úhubconf_pathZentrypointsr   r�   r   Úlist  s    
r¢   c                 C   sR   t | |d|d�}tj d|¡ tj |t¡}tt|ƒ}tj |¡ t	||ƒ}|j
S )a  
    Show the docstring of entrypoint ``model``.

    Args:
        github (string): a string with format <repo_owner/repo_name[:tag_name]> with an optional
            tag/branch. If ``tag_name`` is not specified, the default branch is assumed to be ``main`` if
            it exists, and otherwise ``master``.
            Example: 'pytorch/vision:0.10'
        model (string): 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 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``.
    Example:
        >>> print(torch.hub.help('pytorch/vision', 'resnet18', force_reload=True))
    Tr›   r   )r„   r   r3   rŸ   r8   rK   r    r7   r;   r•   Ú__doc__)rT   r“   r~   r€   r‚   r¡   rž   Úentryr   r   r   Úhelp2  s    

r¥   rT   )Úsourcer~   r   r€   c                O   sR   |  ¡ }|dvr td|› d�ƒ‚|dkr6t| |||ƒ} t| |g|¢R 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[:tag_name]`` with an optional
    tag/branch.

    If ``source`` is 'local', ``repo_or_dir`` is expected to be a
    path to a local directory.

    Args:
        repo_or_dir (string): If ``source`` is 'github',
            this should correspond to a github repo with format ``repo_owner/repo_name[:tag_name]`` with
            an optional tag/branch, for example 'pytorch/vision:0.10'. If ``tag_name`` 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 (string): the name of a callable (entrypoint) defined in the
            repo/dir's ``hubconf.py``.
        *args (optional): the corresponding args for callable ``model``.
        source (string, optional): 'github' or 'local'. Specifies how
            ``repo_or_dir`` is to be interpreted. Default is 'github'.
        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:
        >>> # from a github repo
        >>> repo = 'pytorch/vision'
        >>> model = torch.hub.load(repo, 'resnet50', pretrained=True)
        >>> # from a local directory
        >>> path = '/some/local/path/pytorch/vision'
        >>> model = torch.hub.load(path, 'resnet50', pretrained=True)
    )rT   ÚlocalzUnknown source: "z&". Allowed values: "github" | "local".rT   )Úlowerrj   r„   Ú_load_local)Zrepo_or_dirr“   r¦   r~   r   r€   ÚargsÚkwargsr   r   r   ÚloadS  s    3
ÿr¬   c                 O   sN   t j d| ¡ tj | t¡}tt|ƒ}t||ƒ}||i |¤Ž}t j | ¡ |S )a�  
    Load a model from a local directory with a ``hubconf.py``.

    Args:
        hubconf_dir (string): path to a local directory that contains a
            ``hubconf.py``.
        model (string): name of an entrypoint defined in the directory's
            ``hubconf.py``.
        *args (optional): the corresponding args for callable ``model``.
        **kwargs (optional): the corresponding kwargs for callable ``model``.

    Returns:
        a single model with corresponding pretrained weights.

    Example:
        >>> path = '/some/local/path/pytorch/vision'
        >>> model = _load_local(path, 'resnet50', pretrained=True)
    r   )	r   r3   rŸ   r8   rK   r    r7   r•   r;   )Zhubconf_dirr“   rª   r«   r¡   rž   r¤   r   r   r   r©   “  s    

r©   c              	   C   s¸  d}t | ddid�}t|ƒ}| ¡ }t|dƒr:| d¡}n
| d¡}|durdt|ƒdkrdt|d ƒ}tj	 
|¡}tj	 |¡}	tjd|	d	�}
�z |duržt ¡ }t|| d
ddd��T}| d¡}t|ƒdkrÌqø|
 |¡ |durè| |¡ | t|ƒ¡ q´W d  ƒ n1 �s0    Y  |
 ¡  |du�rX| ¡ }|dt|ƒ… |k�rXtd ||¡ƒ‚t |
j|¡ W |
 ¡  tj	 |
j¡�r´t |
j¡ n&|
 ¡  tj	 |
j¡�r²t |
j¡ 0 dS )a]  Download object at the given URL to a local path.

    Args:
        url (string): URL of the object to download
        dst (string): Full path where object will be saved, e.g. ``/tmp/temporary_file``
        hash_prefix (string, 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:
        >>> torch.hub.download_url_to_file('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth', '/tmp/temporary_file')

    Nz
User-Agentz	torch.hubra   Ú
getheaderszContent-Lengthr   F)ÚdeleterC   ÚBTi   )r   r	   r   r   r   r(   z,invalid hash value (expected "{}", got "{}"))r   r   ÚinfoÚhasattrr­   Úget_allrŒ   Úintr8   r3   rH   ÚdirnameÚtempfileÚNamedTemporaryFileÚhashlibÚsha256r   rW   r   r   r   Ú	hexdigestr�   r   r<   r}   r2   r9   r;   )r[   ÚdstÚhash_prefixrs   Ú	file_sizeÚreqÚuÚmetaÚcontent_lengthZdst_dirrœ   r¸   ZpbarÚbufferÚdigestr   r   r   rw   ³  sP    

ÿ


0
ÿþrw   c                 C   s   t  d¡ t| |||ƒ d S )Nz·torch.hub._download_url_to_file has been renamed to            torch.hub.download_url_to_file to be a public API,            _download_url_to_file will be removed in after 1.3 release)r–   r—   rw   )r[   rº   r»   rs   r   r   r   Ú_download_url_to_fileï  s    
rÃ   c                 C   s6   t  | ¡r2t  | ¡ ¡ }t|ƒdko0|d  ¡  S dS )Nr`   r   F)rx   Ú
is_zipfilery   rz   rŒ   Úis_dir)r{   rz   r   r   r   Ú_is_legacy_zip_formatù  s    
rÆ   c                 C   s€   t  d¡ t | ¡�N}| ¡ }t|ƒdkr2tdƒ‚| |¡ |d j}t	j
 ||¡}W d   ƒ n1 sh0    Y  tj||d�S )NzºFalling 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.r`   z0Only one file(not dir) is allowed in the zipfiler   ©Úmap_location)r–   r—   rx   ry   rz   rŒ   r�   r|   r{   r8   r3   rK   rG   r¬   )r{   Ú	model_dirrÈ   rœ   ÚmembersZextraced_nameZextracted_filer   r   r   Ú_legacy_zip_load   s    


,rË   c              
   C   s  t  d¡rt d¡ |du r0tƒ }t j |d¡}zt  |¡ W n4 tyr } z|j	t	j
kr\n‚ W Y d}~n
d}~0 0 t| ƒ}t j |j¡}	|dur–|}	t j ||	¡}
t j |
¡søtj d | |
¡¡ d}|rèt |	¡}|rä| d¡nd}t| |
||d� t|
ƒ�rt|
||ƒS tj|
|d�S )	a_  Loads 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 ``<hub_dir>/checkpoints`` where
    ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`.

    Args:
        url (string): URL of the object to download
        model_dir (string, 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-<sha256>.ext`` where ``<sha256>`` 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 (string, optional): name for the downloaded file. Filename from ``url`` will be used if not set.

    Example:
        >>> state_dict = torch.hub.load_state_dict_from_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth')

    ZTORCH_MODEL_ZOOz@TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME insteadNZcheckpointsrq   r`   rr   rÇ   )r8   rI   r–   r—   rt   r3   rK   ru   ÚOSErrorÚerrnoÚEEXISTr   Úbasenamer9   r   r   r   r   Ú
HASH_REGEXÚsearchÚgrouprw   rÆ   rË   rG   r¬   )r[   rÉ   rÈ   rs   Z
check_hashÚ	file_namer�   rU   Úpartsr{   rƒ   r»   r\   r   r   r   Úload_state_dict_from_url  s4    



rÕ   )TF)FF)FF)NT)NT)NNTFN)7rÍ   r·   rg   r8   Úrer<   r   rµ   rG   r–   rx   Úurllib.errorr   Úurllib.requestr   r   Úurllib.parser   Z	tqdm.autor   ÚImportErrorÚobjectÚcompilerÐ   rf   rJ   rL   rM   r‹   r    ZREAD_DATA_CHUNKr˜   r7   r>   rB   rF   rN   rV   r]   ro   r„   r†   r�   r•   rt   rš   r¢   r¥   r¬   r©   rw   rÃ   rÆ   rË   rÕ   r   r   r   r   Ú<module>   sh   !


1	
$
!@ 
<

