o
    si2                     @   s   d dl Z d dlZd dlZd dlmZ dZdZdZdZeddZ	dd	d
Z
							dddZdddZdd ZdddZdddZdd Zdd Zdd ZdS )     N)pprintz
Don't forget to share your pretrained models at https://zenodo.org/communities/asteroid-models/! =)
You can directly use our CLI for that, run this: 
`asteroid-upload {} --uploader "Your name here"`
z<a href="{}">{}</a>z#Attribution-ShareAlike 3.0 Unportedz/https://creativecommons.org/licenses/by-sa/3.0/z)https://github.com/asteroid-team/asteroidAsteroidc                 C   s  d|  v s
J dd|  v sJ dd|  v sJ dd|  v s(J dt|ts1J d	|d
urAt|ts>J d|}ntjtj| dr^tt	tj| d}|
dd nd}||d d< ||d d< ||d d< tj| dd t|tj| d tt|  |S )a  Save models to prepare for publication / model sharing.

    Args:
        publish_dir (str): Path to the publishing directory.
            Usually under exp/exp_name/publish_dir
        model_dict (dict): dict at least with keys `model_args`,
            `state_dict`,`dataset` or `licenses`
        metrics (dict): dict with evaluation metrics.
        train_conf (dict): Training configuration dict (from conf.yml).
        recipe (str): Name of the recipe.

    Returns:
        dict, same as `model_dict` with added fields.

    Raises:
        AssertionError when either `model_args`, `state_dict`,`dataset` or
            `licenses` are not present is `model_dict.keys()`
    
model_argsz%`model_args` not found in model dict.
state_dictz%`state_dict` not found in model dict.datasetz"`dataset` not found in model dict.licensesz#`licenses` not found in model dict.z&Cannot upload a model without metrics.Nz`recipe` should be a string.zrecipe_name.txt
 Unknowninfosrecipe_nametraining_configfinal_metricsT)exist_ok	model.pth)keys
isinstancedictstrospathexistsjoinnextopenreplacemakedirstorchsaveprintPLEASE_PUBLISHformat)publish_dir
model_dictmetrics
train_confreciper    r'   M/home/ubuntu/.local/lib/python3.10/site-packages/asteroid/models/publisher.pysave_publishable   s&   r)   Fc                    sF   fdd |du rt dtj| d}tj| d}	t|}
t|
|||d}
t|
|	 |du r@td}|du r@t d	t	|
||	|d
\}}tj|j
dt|}|rk||}t|  td| |S ||}td| d t|  |r||fS   }|dkr||}td| dS td| d dS )a  Entry point to upload publishable model.

    Args:
        publish_dir (str): Path to the publishing directory.
            Usually under exp/exp_name/publish_dir
        uploader (str): Full name of the uploader (Ex: Manuel Pariente)
        affiliation (str, optional): Affiliation (no accent).
        git_username (str, optional): GitHub username.
        token (str): Access token generated to upload depositions.
        force_publish (bool): Whether to directly publish without
            asking confirmation before. Defaults to False.
        use_sandbox (bool): Whether to use Zenodo's sandbox instead of
            the official Zenodo.
        unit_test (bool): If True, we do not ask user input and do not publish.

    c                     s*   t d} | dvrtd|  d   S | S )NzE

Do you want to publish it now (irreversible)? y/n(Recommended: n).
)ynz&
Expected one of [`y`, `n`], received z, please retry.)inputr   )out
get_answerr'   r(   r/   Z   s
   z&upload_publishable.<locals>.get_answerNzNeed uploader namer   zpublished_model.pth)uploaderaffiliationgit_usernameACCESS_TOKENaa  Need an access token to Zenodo to upload the model. Either set ACCESS_TOKEN environment variable or pass it directly (`asteroid-upload --token ...`).If you do not have a access token, first create a Zenodo account (https://zenodo.org/signup/), create a token https://zenodo.org/account/settings/applications/tokens/new/and you are all set to help us! =))
model_pathuse_sandboxdepositzYou can also visit it at {}z9

 This is the current state of the deposition (see here z): r*   zVisit it at {}z*Did not finalize the upload, please visit z to finalize it.)
ValueErrorr   r   r   r   load_populate_publishabler   getenvzenodo_uploadzenodo_addressr   publish_depositionr   jsonr   r!   get_deposition)r"   r0   r1   r2   tokenforce_publishr5   	unit_testr4   publish_model_pathmodelzendep_idaddress	r_publishcurrentinp_r'   r.   r(   upload_publishable?   sL   





rL   c                 C   s   |du rt  }d| d | d | d ddg}|d | }t|| d |d	}|| d
 d< || d
 d< |r8|nd| d
 d< || d
 d< || d
 d< | S )a  Populate infos in publishable model.

    Args:
        model (dict): Model to publish, with `infos` key, at least.
        uploader (str): Full name of the uploader (Ex: Manuel Pariente)
        affiliation (str, optional): Affiliation (no accent).
        git_username (str, optional): GitHub username.

    Returns:
        dict (model), same as input `model`

    .. note:: If a `git_username` is not specified, we look for it somehow, or take
        the laptop username.
    NrK   
model_namer   taskr	   /r   )r0   r   r0   r2   r
   r1   upload_namelicense_note)get_usernamer   r   make_license_notice)rD   r0   r1   r2   rM   rP   rQ   r'   r'   r(   r9      s   $r9   c                  C   s8   t g d} | ddd } | sddl}| } | S )z"Get git of FS username for upload.)gitconfigz	user.namezutf-8Nr   )
subprocesscheck_outputdecodegetpassgetuser)usernamerZ   r'   r'   r(   rR      s   rR   c           
   	   C   s   |du rt dd| }|D ];}t|d |d }t|d |d }t|d |d	 }|d
 r5dnd}|d| d| d| | 7 }|d7 }q|dd d }ttt}	|d|  d|	 d| d7 }|S )a  Make license notice based on license dicts.

    Args:
        model_name (str): Name of the model.
        licenses (List[dict]): List of dict with
            keys (`title`, `title_link`, `author`, `author_link`,
                  `licence`, `licence_link`).
        uploader (str): Name of the uploader such as "Manuel Pariente".

    Returns:
        str, the license note describing the model, it's attribution,
            the original licenses, what we license it under and the licensor.
    Nz$Cannot share model without uploader.zThis work "{}" is a derivative 
title_linktitleauthor_linkauthorlicense_linklicensenon_commercialz (Research only)r	   zof z by z, used under z; z. "z" is licensed under .)r7   r!   HREF
CC_SA_LINKCC_SA)
rM   r   r0   notel_dictr^   r`   	license_hcommcc_sar'   r'   r(   rS      s   

rS   c                 C   s   d}|du rd}d}t | | ddlm} |||d}t| }|j|d}|jd	kr5t|  t	d
| d }	|j
|	|dd}
|rJt| ||	fS )a  Create deposit and upload metadata + model

    Args:
        model (dict):
        token (str): Access token.
        model_path (str): Saved model path.
        use_sandbox (bool): Whether to use Zenodo's sandbox instead of
            the official Zenodo.

    Returns:
        Zenodo (Zenodo instance with access token)
        int (deposit ID)

    .. note::If `model_path` is not specified, save the model in tmp.pth and
        remove it after upload.
    FNTztmp.pth   )Zenodo)r5   )metadata   z:Could not create the deposition, check the provided token.idr   )name)r   r   zenodorp   make_metadata_from_modelcreate_new_depositionstatus_coder   r>   RuntimeErrorupload_new_file_to_depositionr   remove)rD   r@   r4   r5   model_path_was_nonerp   rE   rq   rrF   rK   r'   r'   r(   r;      s"   

r;   c                 C   s$  | d }d}d}|| |d |d t7 }d}|| | d | d 7 }|d	7 }|d
7 }|t|d 7 }|d	7 }|d7 }dd |d  D }|t|7 }|d	7 }|d7 }|t|d 7 }|d	7 }|d7 }||d 7 }|d d||d |d dgddiddigdd| d | d | d dgdd }|S )!a^  Create Zenodo deposit metadata for a given publishable model.

    Args:
        model (dict): Dictionary with all infos needed to publish.
            More info to come.

    Returns:
        dict, the metadata to create the Zenodo deposit with.

    .. note:: We remove the PESQ from the final results as a license is needed to
        use it.
    r   z%<p><strong>Description: </strong></p>z8This model was trained by {} using the {} recipe in {}. r0   r   zE</a>It was trained on the <code>{}</code> task of the {} dataset.</p>rN   r   z<p>&nbsp;</p>z(<p><strong>Training config:</strong></p>r   z <p><strong>Results:</strong></p>c                 S   s"   i | ]\}}d |  vr||qS )pesq)lower).0kvr'   r'   r(   
<dictcomp>'  s   " z,make_metadata_from_model.<locals>.<dictcomp>r   z!<p><strong>Versions:</strong></p>software_versionsz'<p><strong>License notice:</strong></p>rQ   rP   softwarer1   )rt   r1   
identifierru   zasteroid-modelsr   zaudio source separationrM   zpretrained modelzCC-BY-SA-3.0)r^   upload_typedescriptioncreatorscommunitieskeywordsrb   )r!   ASTEROID_REFtwo_level_dict_htmlitemsdisplay_one_level_dict)rD   r   r   tmpdisplay_resultrq   r'   r'   r(   rv   
  sD   rv   c                 C   sn   d}|   D ]*}|d| d7 }| |   D ]}t| | | }|d| d| d7 }q|d7 }q|d7 }|S )zTwo-level dict to HTML.

    Args:
        dic (dict): two-level dict

    Returns:
        str for HTML-encoded two level dic
    <ul><li>z: <ul>: z</li>z
</il></ul></ul>r   r   )dichtmlr   k2valr'   r'   r(   r   H  s   	
r   c                 C   s@   d}|   D ]}t| | }|d| d| d7 }q|d7 }|S )zySingle level dict to HTML

    Args:
        dic (dict):

    Returns:
        str for HTML-encoded single level dic
    r   r   r   z </li>r   r   )r   r   r   r   r'   r'   r(   r   ^  s   	r   )NNN)NNNNFFF)N)NF)r   r   rW   r   r    rg   ri   rh   r!   r   r)   rL   r9   rR   rS   r;   rv   r   r   r'   r'   r'   r(   <module>   s4    
-

Z!

&>