U
    h6-                     @  s   d Z ddlm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 ddlmZ z(ddlmZmZ dd	lmZmZ d
ZW n ek
r   dZY nX eeZdddddZG dd dZdS )zThis module provides mixin functionality for the Albumentations library.
It includes utility functions and classes to enhance the core capabilities.
    )annotationsN)Path)AnyCallable)load)save)HfApihf_hub_download)HfHubHTTPErrorSoftTemporaryDirectoryTFzCallable[..., Any])funcreturnc                   s$   t  dddd fdd}|S )Nr   )argskwargsr   c                    s    t std j d | |S )Nz-You need to install `huggingface_hub` to use zJ. Run `pip install huggingface_hub`, or `pip install albumentations[hub]`.)is_huggingface_hub_availableImportError__name__)r   r   r    A/tmp/pip-unpacked-wheel-e8onvpoz/albumentations/core/hub_mixin.pywrapper   s
    z(require_huggingface_hub.<locals>.wrapper)	functoolswraps)r   r   r   r   r   require_huggingface_hub   s    r   c                   @  s   e Zd ZdZdZddddddZeddd	dd
dZdddddddddddddddZedddddddddddddddddd	d
ddZ	e
dddddddddddddddddd 	d!d"ZdS )#HubMixin)Ztrainevalzalbumentations_config_{}.jsonz
str | Pathstrr   )save_directoryfilenamer   c                 C  s0   t |}|jddd || }t| |dd |S )aJ  Save the transform to a specified directory.

        Args:
            save_directory (Union[str, Path]):
                Directory where the transform will be saved.
            filename (str):
                Name of the file to save the transform.

        Returns:
            Path: Path to the saved transform file.
        T)parentsexist_okjsonZdata_format)r   mkdirsave_transform)selfr   r   	save_pathr   r   r   _save_pretrained,   s
    zHubMixin._save_pretrainedobjectc                 C  s   t || }t|ddS )aJ  Load a transform from a specified directory.

        Args:
            save_directory (Union[str, Path]):
                Directory from where the transform will be loaded.
            filename (str):
                Name of the file to load the transform from.

        Returns:
            A.Compose: Loaded transform.
        r!   r"   )r   load_transform)clsr   r   r&   r   r   r   _from_pretrainedB   s    zHubMixin._from_pretrainedr   FN)keyallow_custom_keysrepo_idpush_to_hubboolz
str | Noner   )r   r,   r-   r.   r/   push_to_hub_kwargsr   c          	      K  sv   |s&|| j kr&td| d| j  d| j|}| || |rr| }|dkr\t|j}| jf ||d|S dS )a5  Save the transform and optionally push it to the Huggingface Hub.

        Args:
            save_directory (`str` or `Path`):
                Path to directory in which the transform configuration will be saved.
            key (`str`, *optional*):
                Key to identify the configuration type, one of ["train", "eval"]. Defaults to "eval".
            allow_custom_keys (`bool`, *optional*):
                Allow custom keys for the configuration. Defaults to False.
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your transform to the Huggingface Hub after saving it.
            repo_id (`str`, *optional*):
                ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
                not provided.
            push_to_hub_kwargs:
                Additional key word arguments passed along to the [`push_to_hub`] method.

        Returns:
            `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
        Invalid key: ``. Please use key from zP keys for upload. If you want to use a custom key, set `allow_custom_keys=True`.N)r.   r,   )	_CONFIG_KEYS
ValueError_CONFIG_FILE_NAME_TEMPLATEformatr'   copyr   namer/   )	r%   r   r,   r-   r.   r/   r1   r   r   r   r   r   save_pretrainedR   s    
zHubMixin.save_pretrained)r,   force_downloadproxiestoken	cache_dirlocal_files_onlyrevisionzdict[str, str] | Nonezstr | bool | Nonezstr | Path | None)
r*   directory_or_repo_idr,   r;   r<   r=   r>   r?   r@   r   c             
   C  s  | j |}	t|}d}
| r~|	t|kr>| j||	d}
n@trbt	|	 dt|
  d nt|	 dt|
  d|
dk	r|
S z>t||	||||||d}t|jt|j }}	| j||	dW S  tk
 r } zt|	 d|W 5 d}~X Y nX dS )a  Load a transform from the Huggingface Hub or a local directory.

        Args:
            directory_or_repo_id (`str`, `Path`):
                - Either the `repo_id` (string) of a repo with hosted transform on the Hub, e.g. `qubvel-hf/albu`.
                - Or a path to a `directory` containing transform config saved using
                    [`~albumentations.Compose.save_pretrained`], e.g., `../path/to/my_directory/`.
            key (`str`, *optional*):
                Key to identify the configuration type, one of ["train", "eval"]. Defaults to "eval".
            revision (`str`, *optional*):
                Revision of the repo on the Hub. Can be a branch name, a git tag or any commit id.
                Defaults to the latest commit on `main` branch.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether to force (re-)downloading the transform configuration files from the Hub, overriding
                the existing cache.
            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on every request.
            token (`str` or `bool`, *optional*):
                The token to use as HTTP bearer authorization for remote files. By default, it will use the token
                cached when running `huggingface-cli login`.
            cache_dir (`str`, `Path`, *optional*):
                Path to the folder where cached files are stored.
            local_files_only (`bool`, *optional*, defaults to `False`):
                If `True`, avoid downloading the file and return the path to the local cached file if it exists.
        N)r   r   z not found in z, trying to load from the Hub.z8. Please install `huggingface_hub` to load from the Hub.)r.   r   r@   r>   r;   r<   r=   r?   z! not found on the HuggingFace Hub)r6   r7   r   is_diroslistdirr+   r   logginginforesolveFileNotFoundErrorr	   parentr9   r
   )r*   rA   r,   r;   r<   r=   r>   r?   r@   r   Z	transformconfig_file	directoryer   r   r   from_pretrained   s<    '
zHubMixin.from_pretrainedz%Push transform using huggingface_hub.)r,   r-   commit_messageprivater=   branch	create_przbool | None)	r.   r,   r-   rN   rO   r=   rP   rQ   r   c             
   C  s   |s&|| j kr&td| d| j  dt|d}	|	j||ddj}t J}
t|
| }| j|}| j	||d}|	j
||||||dW  5 Q R  S Q R X d	S )
a  Push the transform to the Huggingface Hub.

        Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
        `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
        details.

        Args:
            repo_id (`str`):
                ID of the repository to push to (example: `"username/my-model"`).
            key (`str`, *optional*):
                Key to identify the configuration type, one of ["train", "eval"]. Defaults to "eval".
            allow_custom_keys (`bool`, *optional*):
                Allow custom keys for the configuration. Defaults to False.
            commit_message (`str`, *optional*):
                Message to commit while pushing.
            private (`bool`, *optional*, defaults to `False`):
                Whether the repository created should be private.
            token (`str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. By default, it will use the token
                cached when running `huggingface-cli login`.
            branch (`str`, *optional*):
                The git branch on which to push the transform. This defaults to `"main"`.
            create_pr (`boolean`, *optional*):
                Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.

        Returns:
            The url of the commit of your transform in the given repository.
        r2   r3   zV keys for upload. If you still want to use a custom key, set `allow_custom_keys=True`.)r=   T)r.   rO   r    )r   )Zpath_or_fileobjZpath_in_repor.   rN   r@   rQ   N)r4   r5   r   Zcreate_repor.   r   r   r6   r7   r'   Zupload_file)r%   r.   r,   r-   rN   rO   r=   rP   rQ   apitmpr   r   r&   r   r   r   r/      s$    )
zHubMixin.push_to_hub)r   
__module____qualname__r4   r6   r'   classmethodr+   r:   rM   r   r/   r   r   r   r   r   (   s8   0&Lr   )__doc__
__future__r   r   rE   rC   pathlibr   typingr   r   Z!albumentations.core.serializationr   r)   r   r$   Zhuggingface_hubr   r	   Zhuggingface_hub.utilsr
   r   r   r   	getLoggerr   loggerr   r   r   r   r   r   <module>   s"   

