U
    ”Ê¹jä   ã                   @   sÒ   d Z ddlmZ ddlmZmZmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ zdd	lmZ d
ZW nT ek
r¼   zdd	lmZ d
ZW n* ek
r¶   G dd„ dƒZeZdZY nX Y nX G dd„ deƒZdS )zFContains a logger to push training logs to the Hub, using Tensorboard.é    )ÚPath)ÚListÚOptionalÚUnioné   )ÚCommitScheduler)ÚEntryNotFoundError)Ú	ModelCard)Úexperimental)ÚSummaryWriterTc                   @   s   e Zd ZdS )Ú_DummySummaryWriterN)Ú__name__Ú
__module__Ú__qualname__© r   r   úb/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/_tensorboard_logger.pyr   '   s   r   Fc                       s´   e Zd ZdZed dœ‡ fdd„ƒZdddddddd	ddd
œ
eee ee	e
f eee ee ee ee eeee ef  eeee ef  ee dœ‡ fdd„Z‡ fdd„Z‡  ZS )ÚHFSummaryWritera�  
    Wrapper around the tensorboard's `SummaryWriter` to push training logs to the Hub.

    Data is logged locally and then pushed to the Hub asynchronously. Pushing data to the Hub is done in a separate
    thread to avoid blocking the training script. In particular, if the upload fails for any reason (e.g. a connection
    issue), the main script will not be interrupted. Data is automatically pushed to the Hub every `commit_every`
    minutes (default to every 5 minutes).

    > [!WARNING]
    > `HFSummaryWriter` is experimental. Its API is subject to change in the future without prior notice.

    Args:
        repo_id (`str`):
            The id of the repo to which the logs will be pushed.
        logdir (`str`, *optional*):
            The directory where the logs will be written. If not specified, a local directory will be created by the
            underlying `SummaryWriter` object.
        commit_every (`int` or `float`, *optional*):
            The frequency (in minutes) at which the logs will be pushed to the Hub. Defaults to 5 minutes.
        squash_history (`bool`, *optional*):
            Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
            useful to avoid degraded performances on the repo when it grows too large.
        repo_type (`str`, *optional*):
            The type of the repo to which the logs will be pushed. Defaults to "model".
        repo_revision (`str`, *optional*):
            The revision of the repo to which the logs will be pushed. Defaults to "main".
        repo_private (`bool`, *optional*):
            Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
        path_in_repo (`str`, *optional*):
            The path to the folder in the repo where the logs will be pushed. Defaults to "tensorboard/".
        repo_allow_patterns (`List[str]` or `str`, *optional*):
            A list of patterns to include in the upload. Defaults to `"*.tfevents.*"`. Check out the
            [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
        repo_ignore_patterns (`List[str]` or `str`, *optional*):
            A list of patterns to exclude in the upload. Check out the
            [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
        token (`str`, *optional*):
            Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more
            details
        kwargs:
            Additional keyword arguments passed to `SummaryWriter`.

    Examples:
    ```diff
    # Taken from https://pytorch.org/docs/stable/tensorboard.html
    - from torch.utils.tensorboard import SummaryWriter
    + from huggingface_hub import HFSummaryWriter

    import numpy as np

    - writer = SummaryWriter()
    + writer = HFSummaryWriter(repo_id="username/my-trained-model")

    for n_iter in range(100):
        writer.add_scalar('Loss/train', np.random.random(), n_iter)
        writer.add_scalar('Loss/test', np.random.random(), n_iter)
        writer.add_scalar('Accuracy/train', np.random.random(), n_iter)
        writer.add_scalar('Accuracy/test', np.random.random(), n_iter)
    ```

    ```py
    >>> from huggingface_hub import HFSummaryWriter

    # Logs are automatically pushed every 15 minutes (5 by default) + when exiting the context manager
    >>> with HFSummaryWriter(repo_id="test_hf_logger", commit_every=15) as logger:
    ...     logger.add_scalar("a", 1)
    ...     logger.add_scalar("b", 2)
    ```
    )Úreturnc                    s   t stdƒ‚tƒ  | ¡S )NzvYou must have `tensorboard` installed to use `HFSummaryWriter`. Please run `pip install --upgrade tensorboardX` first.)Úis_summary_writer_availableÚImportErrorÚsuperÚ__new__)ÚclsÚargsÚkwargs©Ú	__class__r   r   r   u   s
    ÿzHFSummaryWriter.__new__Né   FZtensorboardz*.tfevents.*)
ÚlogdirÚcommit_everyÚsquash_historyÚ	repo_typeÚrepo_revisionÚrepo_privateÚpath_in_repoÚrepo_allow_patternsÚrepo_ignore_patternsÚtoken)Úrepo_idr   r   r    r!   r"   r#   r$   r%   r&   r'   c       
            s.  t ƒ jf d|i|—Ž t| jtƒs@td| j› dt| jƒ› d�ƒ‚|d ksP|dkr^t| jƒj}n| 	d¡d t| jƒj }t
| j|||||||	|
||d�| _| jj| _| jj| _| jj| _ztj| j| jd�}W n tk
rê   tdƒ}Y nX |j d	g ¡}d
|k�r*| d
¡ ||jd	< |j| j| jd� d S )Nr   z%`self.logdir` must be a string. Got 'z
' of type Ú.Ú ú/)Zfolder_pathr$   r(   r!   ÚrevisionÚprivater'   Zallow_patternsÚignore_patternsZeveryr    )Zrepo_id_or_pathr!   Útagszhf-summary-writer)r(   r!   )r   Ú__init__Ú
isinstancer   ÚstrÚ
ValueErrorÚtyper   ÚnameÚstripr   Ú	schedulerr(   r!   r,   r"   r	   Úloadr   ÚdataÚgetÚappendZpush_to_hub)Úselfr(   r   r   r    r!   r"   r#   r$   r%   r&   r'   r   Zcardr/   r   r   r   r0   ~   s>    õ





zHFSummaryWriter.__init__c                    s&   t ƒ  |||¡ | j ¡ }| ¡  dS )zLPush to hub in a non-blocking way when exiting the logger's context manager.N)r   Ú__exit__r7   ÚtriggerÚresult)r<   Úexc_typeÚexc_valÚexc_tbÚfuturer   r   r   r=   º   s    
zHFSummaryWriter.__exit__)r   r   r   Ú__doc__r
   r   r2   r   r   ÚintÚfloatÚboolr   r0   r=   Ú__classcell__r   r   r   r   r   .   s6   Fó
ó<r   N)rD   Úpathlibr   Útypingr   r   r   Z_commit_schedulerr   Úerrorsr   Zrepocardr	   Úutilsr
   ZtensorboardXr   Z_RuntimeSummaryWriterr   r   Ztorch.utils.tensorboardr   r   r   r   r   r   Ú<module>   s$   