o
    ei6                     @   s  d 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 ddlmZmZ ddlZddlmZ ddlmZ eeZG dd	 d	eZe	d
d	dgZde_ dd e_dd e_G dd deZdejdejdedejfddZdeeef defddZddddddddejf	deeef deeeejf  de de d e d!ee d"e d#ee d$eeeejf  dee fd%d&Z!dS )'zDownloads or otherwise fetches pretrained models

Authors:
 * Aku Rouhe 2021
 * Samuele Cornell 2021
 * Andreas Nautsch 2022, 2023
 * Sylvain de Langen 2024
 * Peter Plantinga 2024
    N)
namedtuple)Enum)OptionalUnion)	HTTPError)
get_loggerc                   @   s   e Zd ZdZdZdZdZdS )	FetchFromzDesignator where to fetch models/audios from.

    Note: HuggingFace repository sources and local folder sources may be confused if their source type is undefined.
             N)__name__
__module____qualname____doc__LOCALHUGGING_FACEURI r   r   X/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/speechbrain/utils/fetching.pyr      s
    r   FetchSourcepathz7NamedTuple describing a source path and how to fetch itc                 C   s
   t | jS )N)hashr   )selfr   r   r   <lambda>-   s   
 r   c                 O   s&   d t| jt| jfj|i |S )N_)joinstrr   r   encode)r   argskwargsr   r   r   r   .   s    c                   @   s&   e Zd ZdZdZ	 dZ	 dZ	 dZdS )LocalStrategyzoDescribes what strategy should be chosen for fetching and linking to
    local files when using :func:`~fetch`.r	   r
   r      N)r   r   r   r   SYMLINKCOPYCOPY_SKIP_CACHENO_LINKr   r   r   r   r    4   s    r    srcdstlocal_strategyreturnc                 C   s   |t jkr| S |  } | }| |kr'|  rtd|  dtd|  |S |t jkrKt	 dkr7t
d td| | |jdd ||  |S |t jt jfv rltd	| | |jdd tt| t| |S td
| d)a?  If using `LocalStrategy.COPY` or `LocalStrategy.COPY_SKIP_CACHE`, destroy
    the file or symlink at `dst` if present and creates a copy from `src` to
    `dst`.

    If using `LocalStrategy.SYMLINK`, destroy the file or symlink at `dst` if
    present and creates a symlink from `src` to `dst`.

    If `LocalStrategy.NO_LINK` is passed, the src path is returned.

    Arguments
    ---------
    src : pathlib.Path
        Path to the source file to link to. Must be a valid path.
    dst : pathlib.Path
        Path of the final destination file. The file might not already exist,
        but the directory leading up to it must exist.
    local_strategy : LocalStrategy
        Strategy to adopt for linking.

    Returns
    -------
    pathlib.Path
        Path to the final file on disk, after linking/copying (if any).
    zFetch: Found local symlink 'z' pointing to itself. This may require manual removal to recover. Did you maybe incorrectly call fetch() with `source==savedir`?zUFetch: Source and destination '%s' are identical, returning assuming this is intendedWindowszUsing SYMLINK strategy on Windows for fetching potentially requires elevated privileges and is not recommended. See `LocalStrategy` documentation.z6Fetch: Local file found, creating symlink '%s' -> '%s'T)
missing_okz-Fetch: Local file found, copying '%s' -> '%s'zIllegal local strategy z passed for linking)r    r%   absolute
is_symlink
ValueErrorloggerdebugr"   platformsystemwarningswarnunlink
symlink_tor#   r$   infoshutilcopyr   )r&   r'   r(   r   r   r   link_with_strategyd   sB   




r:   sourcec                 C   sH   t | tr| S t|  rtj| fS d}| |rtj| fS tj	| fS )aj  From a given `FetchSource` or string source identifier, attempts to guess
    the matching :class:`~FetchFrom` (e.g. local or URI).

    If `source` is already a `FetchSource`, it is returned as-is.

    Arguments
    ---------
    source : str or FetchSource
        Where to look for the file. :func:`~fetch` interprets this path using
        the following logic:

        - First, if the source begins with "http://" or "https://", it is
          interpreted as a web address and the file is downloaded.
        - Second, if the source is a valid directory path, the file is either
          linked, copied or directly returned depending on the local strategy.
        - Otherwise, the source is interpreted as a HuggingFace model hub ID,
          and the file is downloaded from there (potentially with caching).

    Returns
    -------
    tuple of (FetchFrom, str))zhttp:zhttps:)

isinstancer   pathlibPathis_dirr   r   
startswithr   r   )r;   uri_supported_schemesr   r   r   guess_source   s   




rB   FTsavedir	overwriteallow_updatesallow_networksave_filenameuse_auth_tokenrevisionhuggingface_cache_dirc              
   C   s4  |du r| }t |\}}| d|  }|dur*t|}|jddd ||  }nd}tj}
|p7|tjko7|}|durV|	 rV|sV|
 rHdnd}td| |t| |S |tjkrht| }t|||
S |tjkr|du rytd|  d	|std|  d
td| t| z
tj|| W |S  tjjy } z	td| d|d}~ww |tjksJ zD|| ||| d}tdt| t| |
tjkrtjdi ||d|d}t| W S tjdi |d|	i}t| }W n ty } zdt|v rtd| d}~ww t|||
S )ad  Fetches a local path, remote URL or remote HuggingFace file, downloading
    it locally if necessary and returns the local path.

    When a `savedir` is specified, but the file already exists locally
    elsewhere, the specified :class:`~LocalStrategy` chooses whether to copy or
    symlink it.

    If `<savedir>/<save_filename>` exists locally, it is returned as is (unless using `overwrite` or `allow_updates`).

    The `HF_HOME` environment (default: `~/.cache/huggingface`) `selects the cache directory for HF <https://huggingface.co/docs/huggingface_hub/guides/manage-cache#manage-huggingfacehub-cache-system>`__.
    To prefer directly downloading to `savedir`, specify `local_strategy=LocalStrategy.COPY_SKIP_CACHE`.
    **HF cache is always looked up first if possible.**

    Arguments
    ---------
    filename : str
        Name of the file including extensions.
    source : str or FetchSource
        Local or remote root path for the filename. The final path is
        determined by `<source>/<filename>`.
        See :func:`~guess_source` for how the path kind is deduced.
    savedir : str, optional
        If specified, directory under which the files will be available
        (possibly as a copy or symlink depending on `local_strategy`).
        Must be specified when downloading from an URL.
    overwrite : bool, defaults to `False`
        Allows the destination to be recreated by copy/symlink/fetch.
        This does **not** skip the HuggingFace cache (see `allow_updates`).
    allow_updates : bool, defaults to `True`
        If `True`, for a remote file on HF, check for updates and download newer
        revisions if available.
        If `False`, when the requested files are available locally, load them
        without fetching from HF.
    allow_network : bool, defaults to `True`
        If `True`, network accesses are allowed. If `False`, then remote URLs
        or HF won't be fetched, regardless of any other parameter.
    save_filename : str, optional, defaults to `None`
        The filename to use for saving this file. Defaults to the `filename`
        argument if not given or `None`.
    use_auth_token : bool, defaults to  `False`
        If `True`, use HuggingFace's `auth_token` to enable loading private
        models from the Hub.
    revision : str, optional, defaults to  `None`
        HuggingFace Hub model revision (Git branch name/tag/commit hash) to pin
        to a specific version.
        When changing the revision while local files might still exist,
        `allow_updates` must be `True`.
    huggingface_cache_dir: str, optional, defaults to `None`
        Path to HuggingFace cache; if `None`, `assumes the default cache location <https://huggingface.co/docs/huggingface_hub/guides/manage-cache#manage-huggingfacehub-cache-system>`__.
        Ignored if using `LocalStrategy.COPY_SKIP_CACHE`.
        Please prefer to let the user specify the cache directory themselves
        through the environment.
    local_strategy : LocalStrategy, optional
        Which strategy to use for local file storage -- see `LocalStrategy` for options.
        Ignored unless `savedir` is provided, default is `LocalStrategy.SYMLINK` which
        adds a link to the downloaded/cached file in the `savedir`.

    Returns
    -------
    pathlib.Path
        Path to file on local file system.

    Raises
    ------
    ValueError
        If file is not found
    N/T)parentsexist_oksymlinkfilez Fetch %s: Using %s found at '%s'zFetch z-: `savedir` must be specified for URI fetchesz>: File was not found locally and `allow_network` was disabled.zFetch %s: Downloading '%s'zInterpreted 'z)' as web address, but could not download.)repo_idfilenamerH   rI   local_files_onlyz:Fetch %s: Fetching from HuggingFace Hub '%s' if not cachedF)	local_dirlocal_dir_use_symlinksforce_filename	cache_dirz404 Client ErrorzFile not found on HF hubr   )rB   r=   r>   mkdirr,   r    r%   r   r   existsr-   r/   r7   r   r   r:   r   r.   urllibrequesturlretrieveerrorURLErrorr$   huggingface_hubhf_hub_downloadr   )rQ   r;   rC   rD   rE   rF   rG   rH   rI   rJ   r(   
fetch_fromsource_pathdestinationshould_try_update	file_kinder   fetched_filer   r   r   fetch   s   Q








rg   )"r   r=   r1   r8   urllib.errorrY   urllib.requestr3   collectionsr   enumr   typingr   r   r^   requests.exceptionsr   speechbrain.utils.loggerr   r   r/   r   r   __hash__r   r    r>   r:   r   rB   r"   boolrg   r   r   r   r   <module>   sz    


0
M*
	
