o
    xi.                    @  s  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	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mZ d dlZd dlZd dlm  m  mZ d dlmZm Z m!Z!m"Z"m#Z# d dl$m%Z% d dl&m'Z'm(Z( d d	l)m*Z* d d
l+m,Z, d dl-m.Z/ d dl0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z9 d dl:m;Z< d dl=m>Z> d dl?m@Z@mAZA d dlBmCZC d dlBm;ZD d dlEmFZF d dlGmHZHmIZI d dlJmKZKmLZLmMZM ddlNmNZN e/Oe!P ZQejRSeQreTeQejUseV ZQzeW ZXW n eYy&   eZe[ ZXY nw ejR\eQdeX dZ]e^dZ_dddZ`eae
bd Zceae
bd!Zdd"i iZei d#d#d$Zfd%d& ZgG d'd( d(eZhdd0d1Zid2d3 Zjdakdd4d5Zld6d7 ZmG d8d9 d9ejnZoejpeod#d:ejqejrd;ejsd<d= Ztetjpeed>d#d?ejud@dAde!jvdBdCejddDdEZwetjpeedFejxdGdHdIejudJd#dKdLejudMdNddOdPejudQdd#dRdSejudTdUd#d#dVdWejudXdUd#dYdSejddZd[Zyetjpeed\d]ejud^d_d`daejud@dAdbdaejudcd#dddLejudedfdgdaejsejdhdi ZzetjpeedFejsejxdjdHej{d#dkdlejudmd#dUdnd#doejudpd#dUdqd#doejudrdsdtdaejud^d_dudaejud@dAdvdaejudwdxdydaejudzd#dd{d|ejud}d~daejudddaejudd#ddd|ejudd#ddd|ejudd#ddd|ejudd#d#dd|ejudd#dUdd|ejudd#dUdd|ejuddde|dejudd#dUdd|ejudd#dejuddddPejudd#dUdd|ejudd#dUdd|ejudddaej																							dddZ}dddZ~etjpeedd]ejud^d_dddPejud@dAdddPejudd#dUdd|ejudpd#dUdd|ejuddddPejuddddPejudddd#dejuddddPejudd#dUdd|ejudd#dUdd|ejudd#dUdd|ejudd#dUdd|ejudddd#dddexdejsejddÄ Zetjpeed#ddōejudddddPejud^d_dddPejud@dAdddPejudddddPejudddd#dddejxddUej{d#dkdύejsejddф Zetjpde,dӡ daejudddddd؍ejudddddd؍ejudddddd؍ejudddd#ddejuddddejuddddd#ddejuddddejud@dAdddd؍ejud^d_dddd؍ejudddddd؍ejuddddddejuddddddejudddd dejuddddd#ddejudddUddddejud	d
d#ddLejudddddejuddd#d#ddejudddUdd#ddejudddd#ddejudddddPejudddeg dd d!ejd"d# Zetjpeed$d]ejsejuddǐd%dd#d&dejud@dAdddPejud'd(dd)dPejud*ddd+dPejudddd,dPejud-ddd#d.dejudpdd#dd/ej							 dd0d1Zetjpeed2d]ejsejud^d_dd3dPejud@dAdddPejud4de|d5d!ejud6d7d#dUd8d|exd9ejd:d; Zetjpefd<d]ejsexd9ejd=d> Zetjd?dadd@dAZejpdBdCdaejud^d_e!jdDdejud@dAdEe!jvdFdCdGdH ZejpdIdaexdAdJdK Zejpd#dLejud^d_e!jdDdejud@dAe!jvdFdejuddMdNdaejudOddPdaejudQdRdSdTd#e dUejuddݐdVdWdaejudXddYeZdZd[ejud\deZd]d[ejuddeZd^d[ejuddeZd_d[ejuddeZd`d[ejxdxedadbejudcddded#eidfd#dgejudheZdid#djexdjdkdl Zetjpeedmd]ejudpd#dUdd|exd9ejdndo ZetjpefdpdqejsejxdrdHdIdsdt ZetjpefdFejsejxdrdHdIejxdudUdvejudweddxdPejudyd#dUdzd|ejud{dUd|dPejud}d~ddPejudd#ddLejuddddPejuddddPejudddaejudd#dUdd|ejdd  Zetjpefdd#d?ejsejudd_dddPejuddAg d#ddejudd#ddPejudd#dUdd|ejudd#dUdd#doejdd Zetjddadd Zejpefdd]ejsejudd_dddPejuddAg d#ddejudd#ddPejudd#dUdd#doejudd#dUdd#doejdd Zejpefdd]dd Zetjddadd Zejpeedd]exdjejuddMddaejudOdddaejudddddPejudQdRdgd#ddejudrdsdtdaejudd#ddd|ejudd#dUdd|ejuddeddgdd!ejdd Zejpeedd]exdjejudddaejudddaejdd Zejpeedd]exdjejuddddaejdd ZejddadĐdń Zejpeedd]exdǡejuddUddPejdʐd˄ Zetjpeedd]ejxde!jd΍ejud^d_e!jddejud@dAdEe!jvdBdCejdАdф Zetjpeedd]ejsejxde!jd΍ejudd#dUdd|ejudd#ddPejud^d_e!jddejud@dAe!jvdBdejdؐdل Zetpdڡejdېdڄ Zetpdܡejdݐd܄ Zetjpdd#dejsejdߐdބ Zetjpdd#dejsejdd Zetjpdddaejuddd#ddd Zetjpdddaejudcd#d#d#dddd Zetjpdddaejudcd#d#d#dddd Zetjpeedd]ejudMdddPdd ZetjpdddaejuddddPejudd#dUdd|d	dd ZeteN dS (
      )annotationsNwraps)Any)ClickException)ConfigErrorenvutilwandb_agent)
get_sentry)InternalApi	PublicApi)RunQueue)url_registry)core)wandb_setupwandb_sweep)is_artifact_registry_project)get_artifact_file_cache)Api)utils)_launch_add)ExecutionErrorLaunchError)SweepNotFoundError)	Scheduler)
filesystemsettings_file)SyncManagerget_run_from_pathget_runs   )betaz
debug-cli.z.logwandbreturnNonec                  C  sD   t t} | t j | t jddd t|  t j	|  dS )z4Set up logging to the wandb/debug-cli.user.log file.z%%(asctime)s %(levelname)s %(message)sz%Y-%m-%d %H:%M:%S)fmtdatefmtN)
loggingFileHandler_wandb_log_pathsetLevelINFOsetFormatter	Formatterlogger
addHandlerroot)logger_handler r4   A/home/ubuntu/.local/lib/python3.10/site-packages/wandb/cli/cli.py_setup_loggerA   s   

r6   dockerznvidia-dockerdefault_mapT)r8   allow_extra_argsignore_unknown_optionsc                 C  s    t d|  d td d S )NzUnsupported argument ``r"   )r$   	termerrorsysexit)argumentr4   r4   r5   cli_unsupported]   s   r@   c                   @  s   e Zd Zdd ZdS )ClickWandbExceptionc                 C  sN   | j j d| j j }t| j trtjt| jddS dt	 d| d| j S )N.redfgzAn Exception was raised, see z for full traceback.
: )
	orig_type
__module____name__
issubclassr   clickstylestrmessager+   )selfrG   r4   r4   r5   format_messagec   s   z"ClickWandbException.format_messageN)rI   rH   __qualname__rP   r4   r4   r4   r5   rA   b   s    rA   ctxclick.Context | Noneparamclick.Parameter | Nonevaluetuple[str, ...] | Nonedict[str, str]c                 C  s   |si S i }|D ]7}d|vrt d| d|dd\}}| }| }|s.t d|dvr;t d| d|||< q|S )z:Parse service configurations in format serviceName=policy.=z5Service must be in format 'serviceName=policy', got ''r"   zService name cannot be empty)alwaysneverz)Policy must be 'always' or 'never', got ')rK   BadParametersplitstrip)rR   rT   rV   resultconfigservice_namepolicyr4   r4   r5   parse_service_configo   s&   



rd   c                   s   t   fdd}|S )zLFunction decorator for catching common errors and re-raising as wandb.Error.c               
     s   z | i |W S  t jyC } z.t \}}}t|||}td| t 	dt
  t|}||_|t d d }~ww )N zFind detailed error logs at:    )r$   r   r=   exc_info	tracebackformat_exceptionr0   	exceptionjoinr<   r+   rA   rG   with_traceback)argskwargseexc_type	exc_valueexc_tracebacklines	click_excfuncr4   r5   wrapper   s   zdisplay_error.<locals>.wrapperr   )rv   rw   r4   ru   r5   display_error   s   rx   c                 C  s.   | rda t  t du rdt j_t a t S )z8Get a reference to the internal api with cling settings.NT)_apir$   teardownr   	singletonsettingsx_cli_only_moder   resetr4   r4   r5   _get_cling_api   s   r   c              
   C  s   | j t|dd}t }zMt|dkr#td}|j||dd }W |S dd |D d	g }td
 t	
|}|r<|}nd	}|d	krVtjd|jd}|j||dd }W |S W |S  tjjyl } ztt|d}~ww )z6Ask the user for a project, creating one if necessary.F)entitydisplayr   z#Enter a name for your first projectr   namec                 S     g | ]}|d  qS r   r4   ).0projectr4   r4   r5   
<listcomp>       z&prompt_for_project.<locals>.<listcomp>z
Create NewzWhich project should we use?z!Enter a name for your new project)
value_procN)invokeprojectsr   lenrK   promptupsert_projectr$   termlogr
   prompt_choicesformat_projecterrors	CommErrorr   rM   )rR   r   r`   apir   project_namesro   r4   r4   r5   prompt_for_project   s2   



r   c                   @  s   e Zd Zedd ZdS )RunGroupc                 C  s    t j| ||}|d ur|S d S N)rK   Groupget_command)rO   rR   cmd_namervr4   r4   r5   r      s   zRunGroup.get_commandN)rI   rH   rQ   rx   r   r4   r4   r4   r5   r      s    r   )clsinvoke_without_command)versionc                 C  s&   t   | jd u rt|   d S d S r   )r6   invoked_subcommandrK   echoget_helprR   r4   r4   r5   cli   s   
r   zList projects)context_settingshelphiddenz--entity-ez#The entity to scope the listing to.)defaultenvvarr   c              
   C  s   t  }|j| d}t|dkrd|  }nd|  d}|rJttj|dd |D ] }tdtj|d	 d
dddt|d p?ddd f q)|S )Nr   r   zNo projects found for zLatest projects for ""Tboldre   r   bluerE   r   z - description
)	r   list_projectsr   rK   r   rL   rk   rM   r^   )r   r   r   r   rN   r   r4   r4   r5   r      s"   
	r   )r   key)nargsz--cloudz#Login to the cloud instead of local)is_flagr   z--hostz
--base-urlz#Login to a specific instance of W&B)r   r   z	--reloginz#Force relogin if already logged in.)r   r   r   z--anonymouslyFzLog in anonymously)r   r   r   r   z--verify/--no-verifyzVerify login credentialsc                 C  s   |r	t jddd |r|rt d td |rd}| dur)t| dkr)| d nd} | s/|r1d	nd}t j}d	|_	|o?| |_
t jd	|| ||d
d dS )a  Verify and store your API key for authentication with W&B services.

    By default, only store credentials locally without verifying them with W&B.
    To verify credentials, set `--verify=True`.

    For server deployments (dedicated cloud or customer-managed instances),
    specify the host URL using the `--host` flag. You can also set environment
    variables `WANDB_BASE_URL` and `WANDB_API_KEY` instead of running
    the `login` command with host parameters.
    zRThe --anonymously parameter has no effect and will be removed in a future version.Frepeatz'Cannot use --host and --cloud together.r"   zhttps://api.wandb.aiNr   Tmodels)forcehostr   reloginverifyreferrer)r$   termwarnr<   r=   r>   r   r   r{   r|   r}   x_disable_viewerlogin)r   r   cloudr   anonymouslyr   
no_offlineglobal_settingsr4   r4   r5   r     s.   #

 

r   z+Configure a directory with Weights & Biases)r   r   z	--project-pzThe project to use.)r   z#The entity to scope the project to.z--resetzReset settingsz--modez-mz> Can be "online", "offline" or "disabled". Defaults to online.c              
   C  s  t  j}|s|s|s|r@| }|r"|d |d |d |r*|d| |r2|d| |r:|d| |  d S tj	|j
rTtjtjddddd nttjdd	dd
 t }|jd u rq| t tdd}| }|sttjdddd
 | t tdd}| }|sttjdddd
 td t|d d dkrdd |d d D dg }	td t|	}
|
r|
}nd}|dkrtd}n
|dptd}zt| |}W n ty   td| w | }|d| |d| |  t !|j" t#tj$|j"dd}|%d W d    n	1 s+w   Y  ttjdd	dt&'dj(tjd ddtjd!| d"ddtjd#ddd$  d S )%Nr   r   modezIThis directory has been configured previously, should we re-configure it?Tr   abortz#Let's setup this directory for W&B!greenr   r~   zHYour login information seems to be invalid: can you log in again please?rC   zzWe're sorry, there was a problem logging you in. Please send us a note at support@wandb.com and tell us how this happened.r"   teamsedgesc                 S  s   g | ]}|d  d qS )noder   r4   )r   ro   r4   r4   r5   r         zinit.<locals>.<listcomp>zManual entryzWhich team should we use?zManual Entryz*Enter the name of the team you want to usez$What username or team should we use?zCould not find team: z
.gitignorewz*
!settingsz2This directory is configured!  Next, track a run:
rD   zk        * In your training script:
            {code1}
            {code2}
        * then `{run}`.
        zimport wandbzwandb.init(project="z")zpython <train.py>)code1code2run))r   r{   r|   read_system_settingsclearsetsaveospathexistssettings_workspacerK   confirmrL   r   r   api_keyr   r   viewerr=   r>   r   r$   r   r
   r   r   getr   rA   r   r   mkdir_exists_ok	wandb_diropenrk   writetextwrapdedentformat)rR   r   r   r   r   r   system_settingsr   r   
team_namesr`   filer4   r4   r5   initI  s   











r   r   )r   )r   typez--viewz	View runs)r   r   r   r   z	--verboseVerbosez--idrun_idzThe run you want to upload to.z"The project you want to upload to.zThe entity to scope to.z
--job_typejob_typez=Specifies the type of run for grouping related runs together.z(--sync-tensorboard/--no-sync-tensorboardzStream tfevent files to wandb.)r   r   r   z--include-globsz)Comma separated list of globs to include.z--exclude-globsz)Comma separated list of globs to exclude.z$--include-online/--no-include-onlinezInclude online runsz&--include-offline/--no-include-offlinezInclude offline runsz$--include-synced/--no-include-syncedzInclude synced runsz--mark-synced/--no-mark-syncedzMark runs as syncedz
--sync-allzSync all runsz--cleanzDelete synced runsz--clean-old-hours   zNDelete runs created before this many hours. To be used alongside --clean flag.)r   r   r   z--clean-forcez"Clean without confirmation prompt.z--ignore)r   z--show   zNumber of runs to showz--appendz
Append runz--skip-consolezSkip console logsz--replace-tagsz@Replace tags in the format 'old_tag1=new_tag1,old_tag2=new_tag2'c                   s  t  jstd | jtdd t dd|r|r"dr)dt||r5du r5dS 	
fdd}fd	d
  	
fdd}	
fdd}|rp|  dS |rw|  dS rdurnd} | dS |  dS )a  Synchronize W&B run data to the cloud.

    If PATH is provided, sync runs found at the given path. If a path
    is not specified, search for `./wandb` first, then search for a
    `wandb/` subdirectory.

    To sync a specific run:

        wandb sync ./wandb/run-20250813_124246-n67z9ude

    Or equivalently:

        wandb sync ./wandb/run-20250813_124246-n67z9ude/run-n67z9ude.wandb
    zLogin to W&B to sync runsTr   r~   ,Nc                    sB  t ddddd} t d urndd urndd urndd d}g }g }| D ]}|jr1|n|| q*|rjtdt|  rTt|k rTtd d |d p[t| D ]
}td|  q^ntd	 |rtjd
dd}td| dt| d |rtjddd}td| dt| d d S d S )NT)include_onlineinclude_offlineinclude_syncedinclude_unsyncedFr   r   r   r   exclude_globsinclude_globszNumber of runs to be synced: zShowing z runs to be synced:z  zNo runs to be synced.zwandb sync --cleanyellowrD   z
NOTE: use z to delete z" synced runs from local directory.zwandb sync --sync-allz	 to sync z$ unsynced runs from local directory.)r!   syncedappendr$   r   r   rK   rL   )	all_items
sync_itemsr   unsynceditem	clean_cmdsync_cmd)r   r   r   r   r   showr4   r5   _summaryN  sJ   
zsync.<locals>._summaryc                   s   rt | dkrtd td t j
	|td}| D ]}|| q&|	  |
 s@| }|
 r6d S d S )Nr"   z$id can only be set for a single run.)r   r   r   r   mark_syncedapp_urlviewverbosesync_tensorboardlog_pathr   skip_consolereplace_tags)r   r$   r<   r=   r>   r   r  r+   addstartis_donepoll)_path_sync_tensorboardsmp_)r   r   r   r   r  r   replace_tags_dictr   r  r	  r  r4   r5   
_sync_patht  s0   

zsync.<locals>._sync_pathc                    sh   t d urndd urndd urnddd} | s%td d S d ur+nd} | | d S )NTFr   zNothing to sync.)r!   r$   r<   )r   sync_tb)r  r   r   r   r   r   r
  r4   r5   	_sync_all  s   zsync.<locals>._sync_allc               	     s  r4t tt} stjtjdt|  ddddd | D ]}t|j	 qt
tjddd d S td ur;ndd urBndd urIndd	d
} tj tjd   fdd| D }|jdd d |rt
dt|  dt| d d |D ]}t
|j	 qstjtjdt| ddddd |D ]}t|j	 qt
tjddd d S t
tjd ddd d S )Nz Are you sure you want to remove z runs?Tr   r   zSuccess!r   rD   Fr   )hoursc                   s   g | ]	}|j  k r|qS r4   datetime)r   r   sincer4   r5   r         z(sync.<locals>._clean.<locals>.<listcomp>c                 S  s   | j S r   r  )_runr4   r4   r5   <lambda>  s    z&sync.<locals>._clean.<locals>.<lambda>)r   zFound z runs, z are older than z hourszNo runs older than z hours foundrC   )listmapr    rK   r   rL   r   shutilrmtreer   r   r!   r  now	timedeltasort)runsr   old_runs)clean_forceclean_old_hoursr   r   r   r   r   r   r  r5   _clean  s^   zsync.<locals>._clean)r   is_authenticatedr$   r   r   r   r^   _parse_sync_replace_tags)rR   r   r  r	  r   r   r   r   r
  r   r   r   r   r   r  sync_allignorer  cleanr-  r,  r   r  r  r  r  r.  r  r4   )r  r   r   r,  r-  r   r   r   r   r   r   r   r  r   r   r  r   r  r  r
  r	  r  r5   sync  s4   l



 &2


r4  r  rM   dict[str, str] | Nonec                 C  s`   | si S i }|  dD ]"}d|vrtd| d  dS | dd\}}| || < q|S )zParse replace_tags string into a dictionary.

    Args:
        replace_tags: String in format 'old_tag1=new_tag1,old_tag2=new_tag2'

    Returns:
        Mapping of old tags to new tags, or None if format is invalid
    r   rY   zInvalid replace-tags format: z. Use 'old_tag=new_tag' format.Nr"   )r^   r$   r<   r_   )r  r  pairold_tagnew_tagr4   r4   r5   r0    s   	
r0  zInitialize a hyperparameter sweep. Search for hyperparameters that optimizes a cost function of a machine learning model by testing various combinations.zThe name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled Uncategorized.zThe username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.z--controllerzRun local controllerzDisplay verbose output--namezDThe name of the sweep. The sweep ID is used if no name is specified.z	--programzSet sweep programz
--settingszSet sweep settings)r   r   r   z--updatezUpdate pending sweepz--stopzNFinish a sweep to stop running new runs and let currently running runs finish.z--cancelzBCancel a sweep to kill all running runs and stop running new runs.z--pausez3Pause a sweep to temporarily stop running new runs.z--resumez,Resume a sweep to continue running new runs.z--prior_runz-R
prior_runsz*ID of an existing run to add to this sweep)multipler   r   config_yaml_or_sweep_idc           *   	     s  d}t   t fdd|D }|dkrtd|dkr|}t }|js5td | jtdd tdd	}t	|||d
}t
|}|rJt| d S |dpP|}|dpW|}|dp^|} fdd|D d }ddddd}t||  d| d| d|  t|| d|||d td d S |}dd }t }|jstd | jtdd tdd	}d }|r/t	|||d
}t
|}|rt| d S |dp|}|dp|}|dp|}|p|dd u}|p|dd u}d}|st|d  d S |st|d  d S |j|d||d}|s+td | d| d|  d S |d! }|r4d"nd#}t| d$|  t
|}|rL||d< |rS||d%< |rj||}|rj|d&i  |d& | |ry|d'i  d(|d' d)< |d'i d)d(k} | rdd*lm}! |! }"|"|}|rtd+|  d S tj}#|p|#d,p|dp|d}|p|#d-p|dp|dpt|d%}|j|||||d.\}}$t
|$ tj|d/d0}%t| d1|%  t||}&|&rtj|&dd2d3}'td4|'  |p|#d,}|p |#d-}|r2|r2| d| d| }(n|r=| d| }(n|}(|( d5dkrJ|(}(tjd6|( d/d0})td7|)  |rvtd8 dd*lm}! |!|}"|"j!|d9 d S d S ):N)stopcancelpauseresumec                 3  s    | ]} | V  qd S r   r4   )r   klclsr4   r5   	<genexpr>D  s    zsweep.<locals>.<genexpr>r"   z:Only one state flag (stop/cancel/pause/resume) is allowed.%Login to W&B to use the sweep featureTr   r~   )r   r   r   r   r   r   c                   s   g | ]} | r|qS r4   r4   )r   srB  r4   r5   r   V  r   zsweep.<locals>.<listcomp>r   Stopping
CancellingPausingResumingz sweep /_sweepr   r   zDone.c                 S  sl   i }|  ddkr-| dD ]}|d}t|dkr"tjddd |t|g q|S tjddd |S )	z8Parse settings from json or comma separated assignments.rY   r   r   rf   z-Unable to parse sweep settings key value pairFr   z"Unable to parse settings parameter)findr^   r   r$   r   updatedict)r|   retr  kvr4   r4   r5   _parse_settingsd  s   
zsweep.<locals>._parse_settingszSweep lookup requires a valid %s, and none was specified. 
Either set a default %s in wandb/settings, or, if invoking 
`wandb sweep` from the command line, specify the full sweep path via: 

    wandb sweep {username}/{projectname}/{sweepid}

)r   r   )r   r   {}Could not find sweep idUpdatingCreatingz sweep from: programr|   
controllerlocalr   rZ  zError in sweep file: WANDB_ENTITYWANDB_PROJECT)r   r   obj_idr:  r   rD    sweep with ID: r   	underlinerE   View sweep at:  zwandb agent zRun sweep agent with: Starting wandb controller...r	  )"localssum	Exceptionr   r/  r$   r   r   r   rP  sweep_utilsparse_sweep_idr<   r   getattrr|   sweepload_sweep_config
setdefaultrO  rZ  	_validater   environr
   auto_project_nameupsert_sweephandle_sweep_config_violationsrK   rL   r   _get_sweep_urlrN  r   )*rR   r   r   rZ  r	  r   rY  r|   rO  r=  r>  r?  r@  r:  r<  
state_argsis_state_change_commandsweep_idr   partserrstateingsconfig_yamlrS  sweep_obj_idhas_project
has_entitytermerror_msgfoundactionra   is_localwandb_controllertunerr	   warnings	styled_id	sweep_url
styled_url
sweep_pathstyled_pathr4   rB  r5   rm    s
  N



$









rm  z&Run a W&B launch sweep (Experimental).)r   no_args_is_helpr   z--queue-qz(The name of a queue to push the sweep toz{Name of the project which the agent will watch. If passed in, will override the project value passed in using a config filez5The entity to use. Defaults to current logged-in userz--resume_idz-rzCResume a launch sweep by passing an 8-char sweep id. Queue requiredra   )requiredr   c           "      C  s  t  }tj}|jstd | jtdd t dd}|p%|dp%|	d}|d u r1t
d d S |p<|dp<|	d	}|d u rHt
d
 d S | dpP|}	|s\|s\t
d d S t|}
|
di }|
di }|di }|d}|rtd |p|d}d\}}|s|
}|d}|r|sd|d< n|r|dkrtd ||d< |dr|d |d< n|j|d||d}|st
d| d| d|  d S |ddkrt
d| d| d| d d S |d }t|d  }td!| d| d|  t|
 d"krtd# t|dpd}t|d$d}|rF|drF|d|krFt
d%|d d&|  d S t|\}}|| || |sat
d' d S |sgtjnd }tj|d u||||	d(}|szd S tt |dsd)S tt |sd)S d*i i}|r||d* d< |r||d* d< |r||d* d< |r||d* d+< n||d,< |d-}|r|d.kr|rt
d/ d S |d.kr|d0rt
d1 d S n|sd.nd2}tjtj |d3|||d0|||d4i |d5i d6d |d d7|id8d d9}t!|tj"t!|d:}|j#|||||d;||d<d=\}}t$| t%j&|d>d?}t|rGd@ndA dB|  t'(||} | rht%j&| ddCdD}!tdE|!  tdF| dG d S )HNrE  Tr   r~   r]  r   z%Must specify entity when using launchr^  r   z.A project must be configured when using launchusernamez$'config' and/or 'resume_id' requiredlaunch	schedulerr|   jobzXUsing a scheduler job for launch sweeps is *experimental* and may change without warningqueue)NNmethodcustomzUse 'method': 'custom' in the sweep config when using scheduler jobs, or omit it entirely. For jobs using the wandb optimization engine (WandbScheduler), set the method in the sweep config under scheduler.settings.method rT  rM  rU  rK  r{  RUNNINGzCannot resume sweep z, it is already runningrV  ra   zResuming from existing sweep r   zDSweep parameters loaded from resumed sweep, ignoring provided configrun_specz`Resuming a launch sweep with a different scheduler job is not supported. Job loaded from sweep: z, job in config: zrLaunch-sweeps require setting a 'queue', use --queue option or a 'queue' key in the 'launch' section in the config)
return_jobsweep_configr  r   authorF
run_config
sweep_argsrm   resourcezlocal-processz>Scheduler jobs cannot be run with the 'local-process' resourcedocker_imagezQScheduler jobs cannot be run with the 'local-process' resource and a docker imagezlocal-containerzScheduler.WANDB_SWEEP_IDresource_argsregistryurl	overridesWANDB_SWEEP_ID)urir   r   r   r   r  r  entry_pointr  
repositoryr  r   launch_configr   r  )r  run_queue_projectr  PENDINGtemplate_variables)r   r   r_  launch_schedulerr{  r:  template_variable_valuesr   rD   ResumedCreatedr`  r   ra  rc  z!Scheduler added to launch queue ()))r   r   rq  r/  r$   r   r   r   r   r|   r<   r   rj  load_launch_sweep_configpopr   rm  yaml	safe_loadr   keysjsonloadsget_previous_argsrO  r   
ENTRYPOINTconstruct_scheduler_argscheck_job_existsr   launch_utilsconstruct_launch_specPLACEHOLDER_URIdumpsLAUNCH_DEFAULT_PROJECTrs  rt  rK   rL   r   ru  )"rR   r   r   r  ra   	resume_idr:  r   r	   r  parsed_user_configlaunch_argsscheduler_argsr|   scheduler_jobr  r~  r  r  prev_schedulerr  prev_scheduler_argsprev_settings
entrypointrm   r  r  launch_scheduler_speclaunch_scheduler_with_queuerx  r  r  r  r  r4   r4   r5   launch_sweep  s8  2
















r  zLaunch or queue a W&B Job. See zwandb-launchz--uriz-uz(str)zhLocal path or git repo uri to launch. If provided this command will create a job from the specified uri.)metavarr   r   z--jobz-jzGName of the job to launch. If passed in, launch does not require a uri.z--entry-pointz-ENAMEab  Entry point within project. [default: main]. If the entry point is not found,
    attempts to run the project file with the specified name as a script,
    using 'python' to run .py files and the default shell (specified by
    environment variable $SHELL) to run .sh files. If passed in, will override the entrypoint value passed in using a config file.z--git-versionz-gzGIT-VERSIONzJVersion of the project to run, as a Git commit reference for Git projects.)r  r   r   z--build-contextzsPath to the build context within the source code. Defaults to the root of the source code. Compatible only with -u.)r  r   z
--job-namez-Jz;Name for the job created if the -u,--uri flag is passed in.)r  r   r   r   
WANDB_NAMEzName of the run under which to launch the run. If not
    specified, a random run name will be used to launch run. If passed in, will override the name passed in using a config file.)r   r   zName of the target entity which the new run will be sent to. Defaults to using the entity set by local wandb/settings folder.
    If passed in, will override the entity value passed in using a config file.zName of the target project which the new run will be sent to. Defaults to using the project name given by the source uri
    or for github runs, the git repo name. If passed in, will override the project value passed in using a config file.z
--resourceBACKENDa.  Execution resource to use for run. Supported values: 'local-process', 'local-container', 'kubernetes', 'sagemaker', 'gcp-vertex'.
    This is now a required parameter if pushing to a queue with no resource configuration.
    If passed in, will override the resource value passed in using a config file.z--docker-image-dzDOCKER IMAGEzSpecific docker image you'd like to use. In the form name:tag.
    If passed in, will override the docker image value passed in using a config file.)r   r  r   z--base-imagez-Bz
BASE IMAGEzBDocker image to run job code in. Incompatible with --docker-image.z--config-cFILEzPath to JSON file (must end in '.json') or JSON string which will be passed
    as a launch config. Dictation how the launched run will be configured.z	--set-var-vcli_template_varszSet template variable values for queues with allow listing enabled,
    as key-value pairs e.g. `--set-var key1=value1 --set-var key2=value2`)r   r;  r   r   zName of run queue to push to. If none, launches single run directly. If supplied without
    an argument (`--queue`), defaults to queue 'default'. Else, if name supplied, specified run queue must exist under the
    project and entity supplied.)r   
flag_valuer   r   z--async	run_asynca  Flag to run the job asynchronously. Defaults to false, i.e. unless --async is set, wandb launch will wait for
    the job to finish. This option is incompatible with --queue; asynchronous options when running with an agent should be
    set on wandb launch-agent.z--resource-argszPath to JSON file (must end in '.json') or JSON string which will be passed
    as resource args to the compute resource. The exact content which should be
    provided is different for each execution backend. See documentation for layout of this file.z--buildz-bzBFlag to build an associated job and push to queue as an image job.)r   r   r   z--repositoryz-rgzCName of a remote repository. Will be used to push a built image to.)r   r   r   r   z--project-queuez-pqz^Name of the project containing the queue to push to. If none, defaults to entity level queues.)r   r   r   z--dockerfilez-DzHPath to the Dockerfile used to build the job, relative to the job's rootz
--priorityz-PcriticalhighmediumlowzWhen --queue is passed, set the priority of the job. Launch jobs with higher priority
    are served first.  The order, from highest to lowest priority, is: critical, high, medium, low)r   r   r   c           $      C  s  t dt  dtj d ddlm} ddlm} ddl	m
} t }t jdd	 |r4|d
ur4td|r>|	r>|s>td|d
urJ|d
u rJtd|d
ur\t|}|d
u r[tdni }|d
urgt|}|d
uryt|}|d
u rxtdni }|p|d}|r|d
u rtdzt| W n ty   tdt   Y nw |d}| r|d
u rtd|d
urtd|| rdnd}|d
u rt||}|||| d|||||
|||d\}}}|d
u rtd|  | d| d|j }|rd|v r
||d d< nd|i|d< |d
ur"dddd d!}||  }d
}|rL|d
u r0td"|d
u r;t||}t } t| j ||d#}!t!|!|}|d
u rz1t"#||||||	||||||| ||d$}"t"#|"$ j%d%v rtd& t&'d W d
S W d
S  ty }# zt (d' t (|# t&'|# W Y d
}#~#d
S d
}#~#w t)y }# zt (d' t (|# t&'|# W Y d
}#~#d
S d
}#~#w t"j*y   t&'d Y d
S w zt+||||||||||||	||||||d( W d
S  ty }# zt (|#  d
}#~#ww ))a  Start a W&B run from the given URI.

    The URI can bea wandb URI, a GitHub repo uri, or a local path). In the case of a
    wandb URI the arguments used in the original run will be used by default. These
    arguments can be overridden using the args option, or specifying those arguments in
    the config's 'overrides' key, 'args' field as a list of strings.

    Running `wandb launch [URI]` will launch the run directly. To add the run to a
    queue, run `wandb launch [URI] --queue [optional queuename]`.
    z=== Launch called with kwargs z CLI Version: z===r   )_launch_create_job)_is_git_uri
launch_cliprocess_contextNzLCannot use both --async and --queue with wandb launch, see help for details.zjCannot use --queue and --docker together without a project. Please specify a project with --project or -p.z*--priority flag requires --queue to be setz Invalid format for resource-argszInvalid format for configr  z%Build flag requires a queue to be setzError running job: r   zdCannot provide a uri without an entry point. Please provide an entry point with --entry-point or -E.z)Cannot provide both a uri and a job name.gitcoderd  )r  git_hashr   r   
base_imagebuild_context
dockerfiler   zFailed to create job from uri: rK  r  r  r"   rf      r  z)'--set-var' flag requires queue to be set)clientr   r   )r   r   r  r   r  r   r  r  r  synchronousr   r  )failedstopped	preemptedz(Launched run exited with non-zero statuszAn error occurred.)buildr   r  priority),r0   inforg  r$   __version__wandb.sdk.launch._launchr  wandb.sdk.launch.create_jobr  wandb.sdk.launch.utilsr  r   r   configure_scoper   r
   load_json_yaml_dictshlexr^   r   r  check_logged_inri  r<   rh   
format_excget_default_entityrk   r   lowerr   r   r  %fetch_and_validate_template_variablesasyncior   
get_statusr{  r=   r>   rj   r   CancelledErrorr   )$r  r  r  git_versionr  r   r  r   r   r  r  ra   r  r  r  r  r  r  project_queuer  r  job_namer  r  r  r   r   r   artifactr  priority_mapr  
public_apirunqueuer   ro   r4   r4   r5   r    s4   P











r  zRun a W&B launch agent.queueszHThe name of a queue for the agent to watch. Multiple -q flags supported.z
--log-filez-lzDestination for internal agent logs. Use - for stdout. By default all agents logs will go to debug.log in your wandb/ subdirectory or WANDB_DIR if set.z
--max-jobszmThe maximum number of launch jobs this agent can run in parallel. Defaults to 1. Set to -1 for no upper limitz$path to the agent config yaml to usez--urlz<a wandb client registration URL, this is generated in the UI)countr   c              
   C  s   t dt  dtj d |d urtddd lm  m  m	} |d ur+|
| t }	t jdd ||||||\}
}	t|
ddkrMtd	t|	 td
 z	||	|
 W d S  tys } zt |  d }~ww )Nz$=== Launch-agent called with kwargs z  CLI Version: z ===zJ--url is not supported in this version, upgrade with: pip install -u wandbr   launch_agentr  r	  z_To launch an agent please specify a queue or a list of queues in the configuration file or cli.u   Starting launch agent ✨)r0   r  rg  r$   r  r   r  sdkr  r  set_launch_logfiler   r   r  resolve_agent_configr   r   r  r  r   create_and_run_agentri  rj   )rR   r   r	  max_jobsra   r  log_filer	  r  r   agent_configro   r4   r4   r5   r  h  s8   9



r  zRun the W&B agentzThe name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'.z--countz&The max number of runs for this agent.z--forward-signals-fzmForward signals delivered to the agent (e.g. SIGINT/SIGTERM) to its child runs so they can shut down cleanly.rx  c                 C  s|   t  }|jstd | jtdd t dd}td ztj|||||d W d S  ty=   t	d t
d Y d S w )	Nz+Login to W&B to use the sweep agent featureTr   r~   u   Starting wandb agent 🕵️)r   r   r
  forward_signalsz9Sweep was deleted or agent was not found. Stopping agent.r"   )r   r/  r$   r   r   r   r   agentr   r<   r=   r>   )rR   r   r   r
  r  rx  r   r4   r4   r5   r    s$   



r  z/Run a W&B launch sweep scheduler (Experimental)c              
   C  s  t  }|jstd | jtdd t dd}t jdd td dd	lm	} i }t
| jD ],\}}t|tr\|d
r\|dd  dd}| j|d  }t|rXt|}|||< q0z|dd}	||	d|fd|i|}
|
  W d S  ty } zt |  d }~ww )Nz/Login to W&B to use the sweep scheduler featureTr   r~   sweep_schedulerr  u    Starting a Launch Scheduler 🚀r   )load_schedulerz--rf   -r  r"   
sweep_typer$   )scheduler_typerx  )r   r/  r$   r   r   r   r   r  wandb.sdk.launch.sweepsr  	enumeraterm   
isinstancerM   
startswithreplaceisdigitintr   r  ri  rj   )rR   rx  r   r  rn   i_arg_key_argsr  
_schedulerro   r4   r4   r5   r    s@   




r  z*Commands for managing and viewing W&B jobsc                   C     d S r   r4   r4   r4   r4   r5   r  #     r  r#  zList jobs in a projectz'The project you want to list jobs from.r   zThe entity the jobs belong toc           
   
   C  s  t d| d|   t }z	|j|| d}W n t jjy2 } zt |  W Y d }~d S d }~ww t|dkr@t d d S |D ]F}g }t|d dkrOqB|d d d d d	 }|d D ]}|d
d |d d D 7 }q_d|d d d }	t | dt| d|	  qBd S )NzListing jobs in rK  rM  r   zNo jobs foundr   r   artifactSequencer   c                 S  r   )aliasr4   )r   xr4   r4   r5   r   K  r   z_list.<locals>.<listcomp>aliasesr   r   z -- versions (z): )	r$   r   r   	list_jobsr   r   r<   r   rk   )
r   r   r  jobsro   r  r,  r   r   aliases_strr4   r4   r5   _list(  s,   
 r0  zfDescribe a launch job. Provide the launch job in the form of: entity/project/job-name:alias-or-versionc              
   C  s   t  }z|j| d} W n tjjy& } zt|  W Y d }~d S d }~ww | jD ]}|dr2q*t| d| j|   q*d S )Nr   r  rF   )	r   r  r$   r   r   r<   	_job_infor  r   )r  r  ro   r   r4   r4   r5   describeR  s   

r2  )r  z-nzName for the jobz--descriptionzDescription for the jobz--aliasz-ar,  zAlias for the job)r   r;  r   r  zEntrypoint to the script, including an executable and an entrypoint file. Required for code or repo jobs. If --build-context is provided, paths in the entrypoint command will be relative to the build context.z
--git-hashr  z2Commit reference to use as the source for git jobs)r   r   	--runtimez!Python runtime to execute the jobzPath to the build context from the root of the job source code. If provided, this is used as the base path for the Dockerfile and entrypoint.z<Base image to use for the job. Incompatible with image jobs.z~Path to the Dockerfile for the job. If --build-context is provided, the Dockerfile path will be relative to the build context.)r  r  imager   z	--servicez-sserviceszRService configurations in format serviceName=policy. Valid policies: always, never)r;  callbackr   r   z--schemaz$Path to the schema file for the job.)r   r   r   c                 C  sB  ddl m} t }t jdd |ptdp|j}|s#t	d dS |p)td}|s3t	d	 dS |du rF|d
v rFt
d| d d}|dkrS|rSt	d dS |rht|}|du rht	d|  dS |d1i d|d| d|d|d|d|d|dt|d|d|d|	d|
d|d|d|d |r|nd\}}}|st	d! dS | d"| d"|j }| d#tj|d$d% }t|d&krtj|d d$d%}|d'| 7 }nt|d&krtjd(|d$d%}|d)| 7 }t| t| d*}tj| d"| d"| d+d,d-}td.| d/| d0 dS )2a>  Create a job from a source, without a wandb run.

    Jobs can be of three types, git, code, or image.

    git: A git source, with an entrypoint either in the path or provided explicitly pointing to the main python executable.
    code: A code path, containing a requirements.txt file.
    image: A docker image.
    r   r  
job_creater  r]  z4No entity provided, use --entity or set WANDB_ENTITYNr^  z7No project provided, use --project or set WANDB_PROJECT)r  r  zNo entrypoint provided for z job, defaulting to main.pyzmain.pyr4  z1Cannot provide --base-image/-B for an `image` jobz Invalid format for schema file: r   r   r   r   r   r   r   r,  r  r  runtimer  r  r  r6  schemazJob creation failedrK  z job: r   rD   r"   z, with alias: z, z, with aliases: base_urlz/jobsT)rb  zView all jobs in project 'z' here: r   r4   )r  r  r   r   r  r   getenvdefault_entityr$   r<   r   r
   r  r#  r   rK   rL   r   rk   r   r  r|   r   )r   r   r   r   r   r   r,  r  r  r9  r  r  r  r6  r:  r  r   schema_dictr  r  artifact_pathmsg	alias_strweb_urlr  r4   r4   r5   created  s   w




	




 rC  z"Run the W&B local sweep controllerc                 C  s.   t d ddlm} ||}|j| d d S )Nre  r   r\  rf  )rK   r   r$   rZ  r   )r	  rx  r  r  r4   r4   r5   rZ    s   
rZ  z
docker-run)r   r   docker_run_argsc                 C  s   ddl }t }t|}t|dkr|d dkr|d tdd |D dkr/tr/ddg| }t|}d}|r>|j	|}|rJdd	| g| }n|
d
 |jr]dd|j g| }n|
d tddg|  dS )a	  Wrap `docker run` and adds WANDB_API_KEY and WANDB_DOCKER environment variables.

    This will also set the runtime to nvidia if the nvidia-docker executable is present
    on the system and --runtime wasn't set.

    See `docker run --help` for more details.
    r   Nr   c                 S  s   g | ]	}| d r|qS )r3  )r  )r   ar4   r4   r5   r   <  r   zdocker_run.<locals>.<listcomp>r3  nvidiar   WANDB_DOCKER=zUCouldn't detect image argument, running command without the WANDB_DOCKER env variableWANDB_API_KEY=zONot logged in, run `wandb login` from the host machine to enable result loggingr7   )wandb.dockerr   r#  r   r  _HAS_NVIDIA_DOCKERr
   image_from_docker_argsr7   image_idr   r   
subprocesscall)rR   rD  r$   r   rm   r4  resolved_imager4   r4   r5   
docker_run+  s,   

rP  r  )r  z--nvidia/--no-nvidiazFUse the nvidia runtime, defaults to nvidia if nvidia-docker is presentz--digestz Output the image digest and exitz--jupyter/--no-jupyterz Run jupyter lab in the containerz--dirz/appz2Which directory to mount the code in the containerz--no-dirz!Don't mount the current directoryz--shellz	/bin/bashz%The shell to start the container withz--port8888z The host port to bind jupyter onz--cmdz#The command to run in the containerz--no-ttyzRun the command without a ttyc                 C  sX  t  }ts	tdddl}t|}|pd}t|dkr&|d dkr&|d |dkr5t|dkr5|d}t|	dd sU|rF||g }|j
j|d}tdd	|g |j
|\}}}|j
|}|du rptd
| d|r|tj| td |j
ddd| dg}|rtdrtdd|	dd g td t }dddddd| dd|j
jd ddg}|r|ddg |s|d|d | d|g |jr|dd|j g n|d  |r|dd!d"|	d# g d$}d%| }
|| |r|||d&|
g n|
r|dd'|
 g |d(||g |d) t| dS )*aR  Run your code in a docker container.

    W&B docker lets you run your code in a docker image ensuring wandb is configured. It
    adds the WANDB_DOCKER and WANDB_API_KEY environment variables to your container and
    mounts the current directory in /app by default.  You can pass additional args which
    will be added to `docker run` before the image name is declared, we'll choose a
    default image for you if one isn't passed:

    ```sh
    wandb docker -v /mnt/dataset:/app/data
    wandb docker gcr.io/kubeflow-images-public/tensorflow-1.12.0-notebook-cpu:v0.4.0 --jupyter
    wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py --epochs=5"
    ```

    By default, we override the entrypoint to check for the existence of wandb and
    install it if not present.  If you pass the --jupyter flag we will ensure jupyter is
    installed and start jupyter lab on port 8888.  If we detect nvidia-docker on your
    system we will use the nvidia runtime.  If you just want wandb to set environment
    variable to an existing docker run command, see the wandb docker-run command.
    8Docker not installed, install it from https://docker.comr   Nre   r   @)gpur7   pullzGCouldn't find image locally or in a registry, try running `docker pull r;   psr  z	ancestor=r  zCFound running container with the same image, do you want to attach?attachr   r   zLANG=C.UTF-8rG  z
--ipc=hostr  z:/wandb-entrypoint.shz--entrypointz/wandb-entrypoint.shr3  rF  :z-wrH  zJCouldn't find WANDB_API_KEY, run `wandb login` to enable streaming metricszWANDB_ENSURE_JUPYTER=1r   z:8888TzWjupyter lab --no-browser --ip=0.0.0.0 --allow-root --NotebookApp.token= --notebook-dir r  zWANDB_COMMAND=z-itu   Launching docker container 🚢)r   _HAS_DOCKERr   rI  r#  r   r  r
   docker_image_regexr^   r7   default_imagerM  rN  parserL  r=   stdoutr   r>   shellrK   r   r   getcwdr  extendr   r   )rR   rD  r  rF  digestjupyterdirno_dirr^  portcmdno_ttyr   r$   rm   r4  r  	repo_nametagrO  existingcwdcommandr4   r4   r5   r7   S  s   >







zAStart a local W&B container (deprecated, see wandb server --help)8080z"The host port to bind W&B local onz--envzEnv vars to pass to wandb/localz--daemon/--no-daemonzRun or don't run in daemon modez	--upgradez"Upgrade to the most recent versionz--edgezRun the bleeding edgec                 O  s&   t d | jtg|R i | d S )Nz:`wandb local` has been replaced with `wandb server start`.)r$   r   r   r  )rR   rm   rn   r4   r4   r5   r[    s   
r[  z)Commands for operating a local W&B serverc                   C  r'  r   r4   r4   r4   r4   r5   server  r(  rn  zStart a local W&B serverz#The host port to bind W&B server onc              
   C  sF  t  }ts	tddd l}|jddd }|jddd }	||	kr6|r1t	g d n|
d tg d}
|
dkrT|rKt	g d	 n	|d
 td |rXdnd}t }dd| g}|D ]}|d || qgdddddd|d ddg	| }d| }t j }|jd|dd z|  W n$ tjy } zd}t| || d|  W Y d }~nd }~ww |r|dg7 }||g7 }zddlm} W n ty   ttjd }Y nw tj	||d!}|r|dkr|d" td d S |
d#| d$ |
d% |j s!t!"d& | j#t$|d' d S d S d S )(NrR  r   wandb/localr   )r7   rU  ro  z_A new version of the W&B server is available, upgrade by calling `wandb server start --upgrade`)r7   rV  z--filterzname=^wandb-local$z--formatz{{.ID}}    r7   r=  wandb-localzsA container named wandb-local is already running, run `docker stop wandb-local` if you want to start a new instancer"   z&docker.pkg.github.com/wandb/core/localr   zLOCAL_USERNAME=r7   r   z--rmr  z
wandb:/volr   z:8080r9  rr  zhttp://localhost:r;  T)globallyz!Failed to update base_url settingrF   r  )DEVNULLwb)r]  z?Failed to launch the W&B server container, see the above error.z'W&B server started at http://localhost:u    🚀z6You can stop the server by running `wandb server stop`rf   r   )%r   rY  r   rI  r7   rL  r^   image_id_from_registryrM  rN  r   check_outputr<   r>   getpassgetuserr   r   r{   r|   r   r   r   r   SaveSettingsErrorr0   rj   rt  ImportErrorr   r   devnullr   timesleepr   r   )rR   re  r	   daemonupgradeedger   r$   local_image_sharegistry_image_sharunningr4  r  env_varsro   rl  r   r   r@  rt  r  r4   r4   r5   r    s   



 



	r  zStop a local W&B serverc                   C  s   t stdtg d d S )NrR  rq  )rY  r   rM  rN  r4   r4   r4   r5   r=  d	  s   r=  z'Commands for interacting with artifactsc                   C  r'  r   r4   r4   r4   r4   r5   r  k	  r(  r  zUpload an artifact to wandbz7The name of the artifact to push: project/artifact_namezA description of this artifactz--typez-tdatasetzThe type of the artifactlatestz"An alias to apply to this artifactz0Resume the last run from your current directory.z--skip_cachez,Skip caching while uploading artifact files.z--policymutable	immutablez6Set the storage policy while uploading artifact files.c	              	   C  s  |d u r
t j| }t }	|	|\}
}}|d u rtd}tj|||d}|
 d| d| d|d  }t j	| rSt
d|  d| d| d	 |j| ||d
 n;t j| rqt
d|  d| d| d	 |j| ||d
 nd| v rt
d|  d| d| d	 ||  ntdtj|
|d| id||d}|j||d W d    n1 sw   Y  |  tj
ddd tj
d|j ddd d S )N-Enter the name of the project you want to use)r   r   r   rK  rX  r   zUploading directory z to: "z" (r  )
skip_cacherc   zUploading file z://z Logging reference artifact from z)Path argument must be a file or directoryr   cli_put)r   r   ra   r   rV  r@  )r,  z9Artifact uploaded, use this artifact in a run by adding:
F)prefixz!    artifact = run.use_artifact("z")
)r   r   basenamer   _parse_artifact_pathrK   r   r$   Artifactisdirr   add_dirisfileadd_fileadd_referencer   r   log_artifactwaitsource_qualified_name)r   r   r   r   r*  r   r@  r  rc   r  r   r   artifact_namer  r?  r   r4   r4   r5   putp	  sN   -
	
r  zDownload an artifact from wandbz--rootz2The directory you want to download the artifact toz(The type of artifact you are downloadingc                 C  s  t  }|| \}}}|d u rtd}zk|d}t|dkr)|d }|d }nd}t|rO| ddkr=| dd nd}	|jd	 pF|j	}
t
 j|
|	d
}| d| d| d| }tdj|pcd|d |j||d}|j|d} td|   W d S  ty   tdw )Nr  rX  r"   r   r  rK  rf   re   r   )r   organizationz'Downloading {type} artifact {full_path}r  )r   	full_pathr5  )r2   zArtifact downloaded to zUnable to download artifact)r   r  rK   r   r^   r   r   r
  r|   r=  SDKInternalApi_resolve_org_entity_namer$   r   r   r  download
ValueErrorr   )r   r2   r   r  r   r   r  artifact_partsr   r  settings_entityr  r  r4   r4   r5   r   	  s8   


 r   z%List all artifacts in a wandb projectzThe type of artifacts to listc              
   C  s   t  }|d ur||| g}n|| }|D ]S}| D ]L}|j|jd|j|j|j	gdd}t
|d  }d urSt|jd|jdt|jdd|j	d qt|jdddd	dd|j	dd
 qqd S )NrK  r"   )per_pagez<15sz>15srd  z<20szN/Az0 Bz (no versions))r   artifact_typeartifact_typescollectionsartifact_versionsr   rk   r   r   r   nextr$   r   
updated_atr
   to_human_sizesize)r   r   r  typeskind
collectionversionsr  r4   r4   r5   ls	  s(   
*"r  z0Commands for interacting with the artifact cachec                   C  r'  r   r4   r4   r4   r4   r5   cache
  r(  r  z<Clean up less frequently used files from the artifacts cachetarget_sizez--remove-temp/--no-remove-tempzRemove temp filesc                 C  s8   t | } t }|| |}tdt | d d S )Nz
Reclaimed z	 of space)r
   from_human_sizer   cleanupr$   r   r  )r  remove_tempr  reclaimed_bytesr4   r4   r5   r  
  s   
r  z Pull files from Weights & Biasesr   )r   z!The project you want to download.c              
   C  sn  t  }|j| |d\}} |j|| |d}t|dkrtdtdtj|dd d|   |D ]}|||| d	 rFtd
| d q0|	|| d \}}t
jd
| d tj|}|dkrjt| tj|d
| tjdddd2}	t|d}
|jddD ]}|
| |	t| qW d    n1 sw   Y  W d    n1 sw   Y  q0d S )Nr   r   r   r   zRun has no fileszDownloading: Tr   rK  md5zFile z is up to dater  re   &r   rD   )lengthlabel	fill_charru  i   )
chunk_size)r   
parse_slugdownload_urlsr   r   rK   r   rL   file_currentdownload_filer=   r]  r   r   r   dirnamer   r   progressbarr   iter_contentrO  )r   r   r   r   urlsr   r  responser  barfdatar4   r4   r5   rU  $
  s<    

rU  zRestore code, config and docker state for a run. Retrieves code from latest commit if code was not saved with `wandb.save()` or `wandb.init(save_code=True)`.z--no-gitzDon't restore git statez--branch/--no-branchz/Whether to create a branch or checkout detachedz"The project you wish to upload to.c           #      C  s  ddl m} ddlm} t }d|v r+d|v r |dd\}}	n|}	|	dd\}}n|ddkr:|dd\}}|j||d\}}|j|||d\}
}}}|	d	i 	d
}|	d}d| d}||
dd}|rpd }
n|js|ryt||rtd |
r|jrtd|
  tg d z|j|
 W nd ty   td|
  d }
|j|||d}|D ]-}|dr|dr|tdtd  }
z|j|
 W n ty   d }
Y qw  nq|
rtd|
  ||| \}}nt|Y n*w |r*tj| d}t|d}|| W d    n	1 s$w   Y  nd }d| }|rR||jjvrR|jjj |
|d tdt!j"|dd  n$|rftd| d |jj | ntd |
 d! |jj |
 |r|j#}tjj$||d"}tj%d	d#d$|g|d%}|dkrtd& nt&d' t'(|  tj| d(}t) }|* D ]\}}|d)vr|||< qd*}|d+t+j,|- t+j.d,dd-d. 7 }|/d-}t|d}|| W d    n	1 sw   Y  td/|  |rB|d0 d1s-|	d2d ur-t01|d0 pd3g} | |d0 g |d2  }!d4|!}"ntd5 d }"td6 | j2t3|g|"d7 |
||||fS )8Nr   )r   )GitReporX  rK  r"   r  r  r  repor7   za`wandb restore` needs to be run from the same git repository as the original run.
Run `git clone z3` and restore from there or pass the --no-git flag.
git_remote)remotezBOriginal run has no git history.  Just restoring config and dockerz$Fetching origin and finding commit: )r  fetchz--allzCouldn't find original commit: upstream_diff_z.patchz!Falling back to upstream commit: z
diff.patchr   zwandb/)bzCreated branch Tr   z*Using existing branch, run `git branch -D z"` from master for a clean checkoutzChecking out z in detached mode)r  applyz--reject)rk  zApplied patchz>Failed to apply patch, try un-staging any un-committed changeszconfig.yaml)_wandbwandb_versions   wandb_version: 1s   

Fzutf-8)Dumperdefault_flow_styleallow_unicodeencodingzRestored config variables to rY  <rm   pythonrd  z:Couldn't find original command, just restoring environmentz'Docker image found, attempting to start)rD  rf  )4wandb.old.corer   wandb.sdk.lib.gitlibr  r   r^   r
  r  r  r   r|   enabledr   r$   r   rM  
check_callr  commitr  r  r  endswithr   download_write_filer   r   rk   r   r   branchesr  checkoutrK   rL   r2   relpathrN  r<   r   r   r   itemsr  dump_as_dict
SafeDumperdecoder
   find_runnerr   r7   )#rR   r   no_gitbranchr   r   r   r  r   restr  json_configpatch_contentmetadatar  r4  restore_messager  filesfilename
patch_pathr  r  branch_namer2   patch_rel_path	exit_codeconfig_pathra   rA  vrF  runnerrl  rf  r4   r4   r5   restoreN
  s   






 

r  onlinec                  C  s.   t  j } | d |   td dS )zUndo `wandb offline`.r   zOW&B online. Running your script from this directory will now sync to the cloud.N)r   r{   r|   r   r   r   rK   r   r   r4   r4   r5   r  
  s   
offlinec                  C  s0   t  j } | dd |   td dS )zSave data logged to W&B locally without uploading it to the cloud.

    Use `wandb online` or `wandb sync` to upload offline runs.
    r   r   zW&B offline. Running your script from this directory will only write metadata locally. Use `wandb disabled` to completely turn off W&B.Nr   r{   r|   r   r   r   rK   r   r  r4   r4   r5   r   
  s   onc                 C     |  t d S r   )r   r  r   r4   r4   r5   r       offc                 C  r  r   )r   r   r   r4   r4   r5   r    r  statuszShow configuration settingsz--settings/--no-settingszShow the current settings)r   r   c                 C  sF   t  }| r!ttjddd | } ttj| dddd d S d S )NzCurrent SettingsTr   rf   )r   rF   )	sort_keysindent
separators)r   rK   r   rL   r|   r  r  )r|   r   r4   r4   r5   r    s   disabledzDisable W&B.zDisable W&B service)r   show_defaultr   r   c                 C  0   t  j }|dd |  td d S )Nr   r
  zW&B disabled.r  servicer   r4   r4   r5   r
        	r  zEnable W&B.zEnable W&B servicec                 C  r  )Nr   r  zW&B enabled.r  r  r4   r4   r5   r  0  r  aH  Checks and verifies local instance of W&B. W&B checks for:

    Checks that the host is not `api.wandb.ai` (host check).

    Verifies if the user is logged in correctly using the provided API key (login check).

    Checks that requests are made over HTTPS (secure requests).

    Validates the CORS (Cross-Origin Resource Sharing) configuration of the
    object store (CORS configuration).

    Logs metrics, saves, and downloads files to check if runs are correctly
    recorded and accessible (run check).

    Saves and downloads artifacts to verify that the artifact storage and
    retrieval system is working as expected (artifact check).

    Tests the GraphQL endpoint by uploading a file to ensure it can handle
    signed URL uploads (GraphQL PUT check).

    Checks the ability to send large payloads through the proxy (large payload check).

    Verifies that the installed version of the W&B package is up-to-date and
    compatible with the server (W&B version check).

    Creates and executes a sweep to ensure that sweep functionality is
    working correctly (sweeps check).
zTest a specific instance of W&Bc           
      C  sd  dt jd< dt jd< t }d}| d u r!|d} td|   n	| |dkr*d}t }td	t j	
|d
 t | | t jd< tj| d |rRtdd}t| s\td t|| sgtd t|| \}}t }t|ddd |rt|dd t||  t| t|}t }t|}	|r|r|r|r|	std d S d S )NtrueWANDB_SILENTr   r^  Fr;  zDefault host selected: Tz'Find detailed logs for this test at: {}r$   WANDB_BASE_URLrv  r~   r"   zChecking requests to base urlzLConnections are not made over https. SSL required for secure communications.z'Checking requests made over signed URLszSSigned URL requests not made over https. SSL is required for secure communications.)r   rq  r   r|   r$   r   tempfilemkdtempr   r   rk   chdirr   wandb_verify
check_hostr=   r>   r  check_graphql_putcheck_large_postcheck_secure_requestscheck_cors_configurationcheck_wandb_version	check_runcheck_artifactscheck_sweeps)
r   r   reinittmp_dirurl_successr  large_post_successcheck_run_successcheck_artifacts_successcheck_sweeps_successr4   r4   r5   r   @  sh   
"










r   zpurge-cachezHPurges cached logs, run history, and artifacts from the local W&B cache.z--age0dz^Removes items older than the specified time period (e.g., '10s', '5m', '8h', '7d', '6M', '1y')z--forcez3Do not prompt for confirmation when deleting files.ager   boolc              
   C  s&  zt | }W n ty% } ztt| td W Y d }~nd }~ww t	t
 }| s;td|  d S t | }d}d}|d}|D ]5}	|	 j|ksY|	 rZqL|sptd|	 d}
|
sptd|	  qL||	 j7 }|	jdd	 |d7 }qLtd
| dt | d d S )Nr"   z Cache directory does not exist: r   z**/*z+Are you sure you want to delete cache file ?zSkipping cache file: T)
missing_okzDeleted z
 file(s) (r  )r
   time_string_to_secondsr  r$   r<   rM   r=   r>   pathlibPathr	   get_cache_dirr   r   r~  globstatst_mtimeis_dirrK   r   st_sizeunlinkr  )r(  r   age_secondsro   	cache_dircutoff_timepurged_countdata_deletedr  r   r   r4   r4   r5   purge_cache  s>   


r;  )r%   r&   )rR   rS   rT   rU   rV   rW   r%   rX   r   )T)F)NNNNNNNNNNNNNNNNNNr   NNNN)r  rM   r%   r5  )NNNNNNr   )r(  rM   r   r)  )
__future__r   r  r  ry  r  r)   r   r-  r  r%  rM  r=   r  r   r~  rh   	functoolsr   typingr   rK   r  click.exceptionsr   r$   wandb.errorswandb.sdk.verify.verifyr  r   r  r   r   r	   r
   r   wandb.analyticsr   
wandb.apisr   r   wandb.apis.publicr   wandb.errors.linksr   	wandb.oldr   old_core	wandb.sdkr   r   wandb.sdk.artifacts._validatorsr   'wandb.sdk.artifacts.artifact_file_cacher   wandb.sdk.internal.internal_apir   r  wandb.sdk.launchr   r  wandb.sdk.launch._launch_addr   wandb.sdk.launch.errorsr   r   r  r   rj  !wandb.sdk.launch.sweeps.schedulerr   wandb.sdk.libr   r   
wandb.syncr   r    r!   r#   r   get_dir
_wandb_dirr   r   accessW_OK
gettempdirrz  	_usernameKeyErrorrM   getuidrk   r+   	getLoggerr0   r6   r)  whichrY  rJ  CONTEXTRUN_CONTEXTr@   rA   rd   rx   ry   r   r   r   r   rl  version_optionr  pass_contextr   optionENTITYr   r?   r   r   r.  r!  r4  r0  rm  r  r  Choicer  r  r  r  groupr  PROJECTr0  r2  tuplerC  rZ  rP  r7   r[  rn  r  r=  r  r  r   r  r  r  RUN_IDrU  r  r  r   r  r  r  r
  r  r;  add_commandr4   r4   r4   r5   <module>   s"   
!

,
x@ G* B O
		
	< S

$,

&

	,]

%
&n

S
"6#

 



6)