o
    mizC                     @   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mZ d dlm	Z	 d dl
Z
d dlmZ d dlZd dlZd dlmZ zd dlZd dlmZmZmZ d dlmZmZmZ W n% ey{   ed G d	d
 d
Zdd Zdd Zdd Zdd ZY nw eeZdZdd Z dd Z!G dd dZ"eG dd deZ#dd Z$de%de	e&e&f fdd Z'd!d" Z(d#d$ Z)d%d& Z*d'd( Z+G d)d* d*Z,dS )+    N)	b64encode)Dict)urljoin)
filesystem)Magicsline_cell_magicmagics_class)argumentmagic_argumentsparse_argstringz6ipython is not supported in python 2.7, upgrade to 3.xc                   @   s   e Zd ZdS )r   N)__name__
__module____qualname__ r   r   K/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/jupyter.pyr      s    r   c                  O      dd S )Nc                  _      d S Nr   argskwargsr   r   r   <lambda>       zmagics_class.<locals>.<lambda>r   r   r   r   r   r         r   c                  O   r   )Nc                  _   r   r   r   r   r   r   r   r      r   z!magic_arguments.<locals>.<lambda>r   r   r   r   r   r
      r   r
   c                  O   r   )Nc                  _   r   r   r   r   r   r   r   r   "   r   zargument.<locals>.<lambda>r   r   r   r   r   r	   !   r   r	   c                  O   r   )Nc                  _   r   r   r   r   r   r   r   r   %   r   z!line_cell_magic.<locals>.<lambda>r   r   r   r   r   r   $   r   r   c                   C   s   t durt  S dS )z;Display a run if the user added cell magic and we have run.NF)__IFramemaybe_displayr   r   r   r   r   -   s   r   c                   C   s   t d ur
t jdS dS )NquietF)r   optsgetr   r   r   r   r   4   s   r   c                   @   s,   e Zd Zd	ddZdefddZdd ZdS )
IFrameNc                 C   s4   || _ t | _|pi | _d| _| jdd| _d S )NFheight  )pathwandbApiapir   	displayedr   r    )selfr"   r   r   r   r   __init__;   s
   

zIFrame.__init__returnc                 C   s$   | j s| js	tjrtj|  | j S r   )r&   r"   r#   runIPythondisplay)r'   r   r   r   r   B   s   zIFrame.maybe_displayc              
   C   s   zQd| _ | jddr| jd u rtjrtjj| _t| jtr&| j	| j}ntj}|d u rIt
 jd u r7W dS | jdt
 jtjd g}|j| jddW S  tjyi } zd| W  Y d }~S d }~ww )NT	workspaceFzEYou must be logged in to render wandb in jupyter, run `wandb.login()`/)hiddenz"Can't display wandb interface<br/>)r&   r   r   r"   r#   r*   
isinstancestrr%   	from_pathr$   api_keyprojectjoindefault_entityutilauto_project_nameto_htmlr    Error)r'   objecter   r   r   _repr_html_G   s.   

zIFrame._repr_html_)NN)r   r   r   r(   boolr   r=   r   r   r   r   r   :   s    
r   c                       sx   e Zd Zd fdd	Ze eddddded	d
ddddeddddddedddeddedddZ  Z	S )WandBMagicsFc                    s   t  | i | _d S r   )superr(   options)r'   shellrequire_interaction	__class__r   r   r(   d   s   
zWandBMagics.__init__r"   N?zDA path to a resource you want to display, defaults to wandb.run.path)defaultnargshelpz-wz--workspace
store_truez(Display the entire run project workspace)rG   actionrI   z-qz--quietz$Display the minimal amount of outputz-hz--heightr!   z"The height of the iframe in pixels)rG   typerI   c                 C   s   t | j|}|j| jd< |j| jd< |j| jd< t|j| jd}| }|dur>|s5d| j d| d }t	
 | dS dS )	zDisplay wandb resources in jupyter.  This can be used as cell or line magic.

        %wandb USERNAME/PROJECT/runs/RUN_ID
        ---
        %%wandb -h 1024
        with wandb.init() as run:
            run.log({"loss": 1})
        r    r-   r   )r   Nz3wandb.jupyter.__IFrame = wandb.jupyter.IFrame(opts=z)
z
wandb.jupyter.__IFrame = None)r   r#   r    rA   r-   r   r   r"   r   r+   get_ipythonrun_cell)r'   linecellr   iframer&   r   r   r   r#   h   s    'zWandBMagics.wandb)Fr   )
r   r   r   r(   r
   r	   intr   r#   __classcell__r   r   rD   r   r?   b   s@    r?   c               
   C   s$  t  \} }| D ]V}|drtdtjt|d dd|ddid }|D ]4}t|tr\|dr\d	|v r\|d d
 |kr\|d|dt	 |d	 d |d	 d d    S q(q|sbd S z%ddl
m} | }|jjjd}|rtj||tj|dW S W d S  ty   Y d S w )Npasswordz%Can't query password protected kernelurlzapi/sessionstoken )paramskernelnotebookidroot_dirnotebook_dirr"   namerootr"   r^   r   )rM   __vsc_ipynb_file__)jupyter_servers_and_kernel_idr   
ValueErrorrequestsr   jsonr0   dictosgetcwdr+   rM   rY   rB   user_nsr"   dirnamebasename	Exception)servers	kernel_idsresnnrM   ipythonnotebook_pathr   r   r   4notebook_metadata_from_jupyter_servers_and_kernel_id   sB   



	

rt   silentr)   c                 C   s   d}zAt  }t }|dur|durd|d |d dW S tj r5t }|r5d|d d |d d dW S |r:|W S | sAt| i W S  tyU   | sQt| i  Y S w )	zAttempt to query jupyter for the path and name of the notebook file.

    This can handle different jupyter environments, specifically:

    1. Colab
    2. Kaggle
    3. JupyterLab
    4. Notebooks
    5. Other?
    zFailed to detect the name of this notebook, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable to enable code saving.Nz/contentr"   r^   r_   z/kaggle/workingmetadata)	rt   attempt_colab_load_ipynbr#   r7   
_is_kaggleattempt_kaggle_load_ipynbloggererrorrl   )ru   error_messagejupyter_metadataipynbr   r   r   notebook_metadata   s6   




r   c               
   C   s   z=ddl } td| j d}tjd}tjd}g }|dur,|	t
|  |dur9|	t
|  ||fW S  tttfyM   g df Y S w )ziReturn a list of servers and the current kernel_id.

    Used to query for the name of the notebook.
    r   Nzkernel-(.*).json   zjupyter_server.serverappznotebook.notebookapp)	ipykernelresearchconnectget_connection_filegroupr#   r7   
get_moduleextendlistlist_running_serversAttributeErrorrc   ImportError)r   rn   	serverappnotebookapprm   r   r   r   rb      s$   

rb   c                  C   s4   t jd} | r| jjddd}|r|d S d S d S )Nzgoogle.colab	get_ipynb   )timeout_secr~   )r#   r7   r   _messageblocking_request)colabresponser   r   r   rw     s   rw   c                  C   s`   t jd} | r.z|  }t| d }d|d d< |W S  ty-   t	d Y d S w d S )Nkaggle_sessionsourcezkaggle.ipynbrv   r^   zUnable to load kaggle notebook)
r#   r7   r   UserSessionClientre   loadsget_exportable_ipynbrl   rz   	exception)kaggleclientparsedr   r   r   ry     s   
ry   c              
   C   sd   ddl m} ddlm} ddlm} ||d| dd z|	dW S  |y1   Y d	S w )
zFThis renders an iframe to wandb in the hopes it posts back an api key.r   output)MessageError)r,   a  
        window._wandbApiKey = new Promise((resolve, reject) => {{
            function loadScript(url) {{
            return new Promise(function(resolve, reject) {{
                let newScript = document.createElement("script");
                newScript.onerror = reject;
                newScript.onload = resolve;
                document.body.appendChild(newScript);
                newScript.src = url;
            }});
            }}
            loadScript("https://cdn.jsdelivr.net/npm/postmate/build/postmate.min.js").then(() => {{
            const iframe = document.createElement('iframe')
            iframe.style.cssText = "width:0;height:0;border:none"
            document.body.appendChild(iframe)
            const handshake = new Postmate({{
                container: iframe,
                url: '{}/authorize'
            }});
            const timeout = setTimeout(() => reject("Couldn't auto authenticate"), 5000)
            handshake.then(function(child) {{
                child.on('authorize', data => {{
                    clearTimeout(timeout)
                    resolve(data)
                }});
            }});
            }})
        }});
    zhttp:zhttps:_wandbApiKeyN)
google.colabr   google.colab._messager   r+   r,   
Javascriptformatreplaceeval_js)app_urlr   r   r,   r   r   r   attempt_colab_login(  s   !r   c                   @   sH   e Zd Zdd Zdd Zdd Zdefdd	Zdefd
dZdd Z	dS )Notebookc                 C   s   i | _ || _t | _d S r   )outputssettingsr+   rM   rB   )r'   r   r   r   r   r(   V  s   zNotebook.__init__c                 C   sv   | j |g | j |< |d }i }|D ]}|| }t|tr't|d||< q|||< q| j | ||d d d S )Ndatautf-8rv   )r   rv   )r   r   r0   bytesr   decodeappend)r'   	exc_countdata_with_metadatar   b64_datakeyvalr   r   r   save_display[  s   


zNotebook.save_displayc                 C   s~   | j j}|r'tj|r't|}t|}|W  d   S 1 s"w   Y  t }|r.|S t	 }|r=t
|d dkr=|S dS )z Return notebook as dict or None.Ncellsr   )r   x_jupyter_pathrg   r"   existsopenre   loadrw   ry   len)r'   relpath	json_filer   colab_ipynbkaggle_ipynbr   r   r   probe_ipynbm  s   

 zNotebook.probe_ipynbr)   c              
   C   sd   | j jstd dS d}z|  }W |S  ty1 } ztdt|  W Y d }~|S d }~ww )Nznot saving jupyter notebookFzProblem saving notebook: )r   	save_coderz   info_save_ipynbrl   repr)r'   retr<   r   r   r   
save_ipynb  s   

zNotebook.save_ipynbc              	   C   sZ  | j j}td| |r%tj|r%t|tj	| j j
tj| dS t }|rqz	t }|d }W n ty>   d}Y nw |dsH|d7 }ttj	| j j
|ddd}|t| W d    dS 1 sjw   Y  dS t }|rt|d	 d
krttj	| j j
|d d ddd}|t| W d    dS 1 sw   Y  dS dS )Nzlooking for notebook: %sTr^   zcolab.ipynbz.ipynbwr   encodingr   r   rv   F)r   r   rz   r   rg   r"   r   shutilcopyr5   _tmp_code_dirrk   rw   rt   rl   endswithr   writere   dumpsry   r   )r'   r   r   r}   nb_namefr   r   r   r   r     sh   

		
zNotebook._save_ipynbc              
   C   s  zddl m}m}m} W n ty   td Y dS w | jdu r#dS g }t| jj	j
dd}t|dks9| jjs@td dS z|D ]C\}}}|d rX|jd	d
|d dg}	ng }	| j|ry| j| D ]}
|	|jd|
d |
d pti d qe||j||d |	d qCt| jdr| jjj}ndtjd}tdt| |j|dtjd  dtjd  dd|dd}tjdd}tj d| t!"tjtjj#d t$tj| jj%dddd}|||dd  W d   n1 sw   Y  t$tjtjj#|ddd}|||dd  W d   W dS 1 sw   Y  W dS  t&|j'fyA } ztd!| W Y d}~dS d}~ww )"zHThis saves all cell executions in the current session as a new notebook.r   )v4	validatorr   z1Run pip install nbformat to save notebook historyNTr   r   znot saving jupyter historystreamstdout)output_typer^   textdisplay_datar   rv   )r   r   rv   )execution_countr   r   rY   python)r^   versionz)saving %i cells to _session_history.ipynbzPython )display_namer^   language)
kernelspeclanguage_info)r   rv   codez_session_history.ipynbsession_historyr   r   r      )r   z*Unable to save ipython session history:
%s)(nbformatr   r   r   r   rz   r{   rB   r   history_manager	get_ranger   r   r   r   
new_outputr   r   r   new_code_cellhasattrrY   r   sysr   new_notebookversion_inforg   r"   r5   r#   r*   _set_config_wandbr   mkdir_exists_okdirr   r   OSErrorNotebookValidationError)r'   r   r   r   r   hist_r   excr   outr   nb
state_pathr   r<   r   r   r   save_history  s   




(zNotebook.save_historyN)
r   r   r   r(   r   r   r>   r   r   r   r   r   r   r   r   U  s    2r   )-re   loggingrg   r   r   r   base64r   typingr   rd   requests.compatr   r#   
wandb.utilwandb.sdk.libr   r+   IPython.core.magicr   r   r   IPython.core.magic_argumentsr	   r
   r   r   termwarn	getLoggerr   rz   r   r   r   r   r?   rt   r>   r1   r   rb   rw   ry   r   r   r   r   r   r   <module>   sN    

(=$5	-