o
    -wiC                     @  sv  U d dl m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Zd dl	m
Z
 d dlmZ d dlZd dlZd dlZd dlmZmZmZ d dlmZmZmZ d dlmZ d dlZd dlZd dlmZmZ d d	lm Z  e!e"Z#d2ddZ$G dd dZ%da&de'd< d3ddZ(d4ddZ)eG dd deZ*dd  Z+d5d#d$Z,d%d& Z-d'd( Z.d)d* Z/	d6d7d.d/Z0G d0d1 d1Z1dS )8    )annotationsN)	b64encode)Any)Magicsline_cell_magicmagics_class)argumentmagic_argumentsparse_argstring)urljoin)	wandb_runwandb_setup)
filesystemrunwandb_run.Runreturnboolc                 C  s   t sdS t |  dS )zDisplay a run's page if the cell has the %%wandb cell magic.

    Args:
        run: The run to display.

    Returns:
        Whether the %%wandb cell magic was present.
    FT)_current_cell_wandb_magicdisplay_if_allowed)r    r   J/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/jupyter.pydisplay_if_magic_is_used   s   	
r   c                   @  s$   e Zd ZdZdddZdd
dZdS )_WandbCellMagicStatez-State for a cell with the %%wandb cell magic.heightintr   Nonec                C  s   || _ d| _dS )zInitializes the %%wandb cell magic state.

        Args:
            height: The desired height for displayed iframes.
        FN)_height_already_displayed)selfr   r   r   r   __init__/   s   
z_WandbCellMagicState.__init__r   r   c                 C  s"   | j rdS d| _ t|| jd dS )ztDisplay a run's iframe if one is not already displayed.

        Args:
            run: The run to display.
        NTr   )r   _display_wandb_runr   )r   r   r   r   r   r   8   s   z'_WandbCellMagicState.display_if_allowedN)r   r   r   r   )r   r   r   r   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   ,   s    
	r   z_WandbCellMagicState | Noner   pathstrr   r   r   c                C  sh   t  }z|| }tjj|j|ddd W dS  t jy3   t	  tjjd| ddd Y dS w )zDisplay a wandb object (usually in an iframe) given its URI.

    Args:
        path: A path to a run, sweep, project, report, etc.
        height: Height of the iframe in pixels.
    r    TrawzPath z/ does not refer to a W&B object you can access.N)
wandbApi	from_pathIPythondisplaydisplay_htmlto_htmlError	traceback	print_exc)r&   r   apiobjr   r   r   _display_by_wandb_pathH   s   


r6   c                C  s   t jj| j|ddd dS )zDisplay a run (usually in an iframe).

    Args:
        run: The run to display.
        height: Height of the iframe in pixels.
    r    Tr(   N)r-   r.   r/   r0   )r   r   r   r   r   r!   `   s   

r!   c                	      sT   e Zd Z fddZe edddddedd	d
eddeddddZ  Z	S )WandBMagicsc                   s   t  | d S N)superr   )r   shell	__class__r   r   r   o   s   zWandBMagics.__init__r&   N?z+The path to a resource you want to display.)defaultnargshelpz-hz--heighti  z#The height of the iframe in pixels.)r>   typer@   liner'   cell
str | Noner   r   c                 C  s   t | j|}|j}|j}|rt||d d}nt j }r't||d d}nd}|du r/dS |s6t	|da
zt | W da
dS da
w )a  Display wandb resources in Jupyter.

        This can be used as a line magic:

            %wandb USERNAME/PROJECT/runs/RUN_ID

        Or as a cell magic:

            %%wandb -h 1024
            with wandb.init() as run:
                run.log({"loss": 1})
        r    TFN)r
   r*   r&   r   r6   r   	singletonmost_recent_active_runr!   r   r   r-   get_ipythonrun_cell)r   rB   rC   argsr&   r   	displayedr   r   r   r   r*   r   s"   
zWandBMagics.wandbr8   )rB   r'   rC   rD   r   r   )
r"   r#   r$   r   r	   r   r   r   r*   __classcell__r   r   r;   r   r7   m   s$    r7   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&   rV   r   )rG   __vsc_ipynb_file__)jupyter_servers_and_kernel_idget
ValueErrorrequestsr   json
isinstancedictosgetcwdr-   rG   rQ   r:   user_nsr&   dirnamebasename	Exception)servers	kernel_idsresnnrG   ipythonnotebook_pathr   r   r   4notebook_metadata_from_jupyter_servers_and_kernel_id   sB   



	

rn   silentdict[str, str]c                 C  s   d}z9t  }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 W n tyI   t| Y nw t	| i S )	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&   rV   rW   z/kaggle/workingmetadata)
rn   attempt_colab_load_ipynbr*   util
_is_kaggleattempt_kaggle_load_ipynbrf   logger	exception	termerror)ro   error_messagejupyter_metadataipynbr   r   r   notebook_metadata   s2   



r|   c               
   C  s   zBddl } td| j d}tjd}tjd}g }|dur,|	t
|  |dur>|	t
|  W ||fS W ||fS  tttfyR   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*   rs   
get_moduleextendlistlist_running_serversAttributeErrorr\   ImportError)r~   rh   	serverappnotebookapprg   r   r   r   rZ      s(   
rZ   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*   rs   r   _messageblocking_request)colabresponser   r   r   rr     s   rr   c                  C  sj   t jd} | s
d S z|  }t| d }d|d d< W |S  ty4   t d t	
d Y d S w )Nkaggle_sessionsourcezkaggle.ipynbrq   rV   zUnable to load kaggle notebook.)r*   rs   r   UserSessionClientr^   loadsget_exportable_ipynbrf   rx   rv   rw   )kaggleclientparsedr   r   r   ru   "  s   

ru   app_urlreferrerrD   c              
   C  st   ddl m} ddlm} ddlm} ||d| dd|r$d| nd	 z|	d
W S  |y9   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:z?ref=rO   _wandbApiKeyN)
google.colabr   google.colab._messager   r-   r.   
Javascriptformatreplaceeval_js)r   r   r   r   r.   r   r   r   attempt_colab_login4  s"   
$r   c                   @  sD   e Zd ZdddZdd Zd	d
 ZdddZdddZdddZdS )Notebooksettingswandb.Settingsr   r   c                 C  s   i | _ || _t | _d S r8   )outputsr   r-   rG   r:   )r   r   r   r   r   r   h  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-8rq   )r   rq   )r   r[   r_   bytesr   decodeappend)r   	exc_countdata_with_metadatar   b64_datakeyvalr   r   r   save_displaym  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_pathra   r&   existsopenr^   loadrr   ru   len)r   relpath	json_filer   colab_ipynbkaggle_ipynbr   r   r   probe_ipynb  s   

 zNotebook.probe_ipynbr   c                 C  sR   | j jstd dS d}z|  }W |S  ty(   td td Y |S w )Nznot saving jupyter notebookFzFailed to save notebook.zProblem saving notebook.)	r   	save_coderv   info_save_ipynbrf   r*   rx   rw   )r   retr   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: %sTrV   zcolab.ipynbz.ipynbwr   encodingr   r   rq   F)r   r   rv   r   ra   r&   r   shutilcopyjoin_tmp_code_dirre   rr   rn   rf   endswithr   writer^   dumpsru   r   )r   r   r   rz   nb_namefr   r   r   r   r     sh   

		
zNotebook._save_ipynbr   r   c              	   C  sx  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}|d| t !tj| jj"d t#tj| jj$dddd}|||dd  W d   n1 sw   Y  t#tj| jj"|ddd}|||dd  W d   W dS 1 sw   Y  W dS  t%|j&fy;   td! t'd! Y dS w )"zHThis saves all cell executions in the current session as a new notebook.r   )v4	validatorr   zLThe nbformat package was not found. It is required to save notebook history.NTr   r}   znot saving jupyter historystreamstdout)output_typerV   textdisplay_datar   rq   )r   r   rq   )execution_countr   r   rQ   python)rV   versionz)saving %i cells to _session_history.ipynbzPython )display_namerV   language)
kernelspeclanguage_info)r   rq   codez_session_history.ipynbsession_historyr   r   r      )r   z(Unable to save notebook session history.)(nbformatr   r   r   r   r*   rx   r:   r   history_manager	get_ranger   r   r   rv   r   
new_outputr   r[   r   new_code_cellhasattrrQ   r   sysr   new_notebookversion_infora   r&   r   _set_config_wandbr   mkdir_exists_ok	files_dirr   r   OSErrorNotebookValidationErrorrw   )r   r   r   r   r   r   hist_r   excr   outr   nb
state_pathr   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   r   r   r   r   r   r   r   g  s    


2r   )r   r   r   r   )r&   r'   r   r   r   r   )r   r   r   r   r   r   )ro   r   r   rp   r8   )r   r'   r   rD   )2
__future__r   r^   loggingra   r   r   r   r2   base64r   typingr   r-   IPython.displayr]   IPython.core.magicr   r   r   IPython.core.magic_argumentsr   r	   r
   requests.compatr   r*   
wandb.util	wandb.sdkr   r   wandb.sdk.libr   	getLoggerr"   rv   r   r   r   __annotations__r6   r!   r7   rn   r|   rZ   rr   ru   r   r   r   r   r   r   <module>   sH    



=
$1	3