a
    
d!a                     @   s  d 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Zddlm	Z	 ddl
mZ ddl
mZ ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl
mZ ddlmZ ddlmZ dZdZdZ dd Z!d6ddZ"G dd dej#dZ$G dd de$Z%G dd de$Z&G d d! d!e$Z'G d"d# d#e$Z(d$d% Z)d&d' Z*G d(d) d)e$Z+G d*d+ d+e$Z,d7d,d-Z-d.d/ Z.d0d1 Z/d2d3 Z0G d4d5 d5ej1Z2dS )8z>Entry point and high-level logic for TensorBoard.dev uploader.    N)logging)tf)experiment_pb2)export_service_pb2_grpc)write_service_pb2_grpc)auth)dry_run_stubs)exporter)flags_parser)
formatters)server_info)uploader)server_info_pb2)program)base_pluginak  Your use of this service is subject to Google's Terms of Service
<https://policies.google.com/terms> and Privacy Policy
<https://policies.google.com/privacy>, and TensorBoard.dev's Terms of Service
<https://tensorboard.dev/policy/terms/>.

This notice will not be shown again while you are logged into the uploader.
To log out, run `tensorboard dev auth revoke`.
d   iX  c                 C   sb   |   }d}d||tf}tj| tjd td}| dvrRtd tjd dS )z>Prompts for user consent, exiting the program if they decline.z"
***** TensorBoard Uploader *****

zContinue? (yes/NO) )yyesr   N)	get_ack_message_bodyjoin_MESSAGE_TOSsysstderrwriteinputlowerexit)intentbodyheaderZuser_ack_messageresponse r"   q/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/tensorboard/uploader/uploader_subcommand.py_prompt_for_user_ack;   s    
r$   c              
   C   s^  t t j t| |}t }t|trJ|  t	j
d t	j
  dS | }|st| tj| jd}t	j
d || | j \}}zt| }W n2 tjy } ztt| W Y d}~n
d}~0 0 t| t d| |jjst d| td t|t |}	tj!|jj|	|d}
|
 |"||
 W d   n1 sP0    Y  dS )	zRuns the main uploader program given parsed flags.

    Args:
      flags: An `argparse.Namespace`.
      experiment_url_callback: A function accepting a single string argument
        containing the full TB.dev URL of the uploaded experiment.
    zLogged out of uploader.
N)Zforce_consoler   zReceived server info: <%r>zServer info response: %sz6Internal error: frontend did not specify an API server)options)#r   Zset_stderrthresholdWARNING_get_intentr   ZCredentialsStore
isinstance_AuthRevokeIntentclearr   r   r   flushZread_credentialsr$   Zauthenticate_userZauth_force_consoleZwrite_credentialsZgrpc_creds_typeZchannel_config_get_server_infoserver_info_libZCommunicationError_diestr_handle_server_infoinfo
api_serverendpointerrorgrpcZcomposite_channel_credentialsZid_token_call_credentialsZsecure_channelexecute)flagsexperiment_url_callbackr   storecredentialsZchannel_credsZchannel_optionsr   eZcomposite_channel_credschannelr"   r"   r#   _runH   sH    	



"

r=   c                   @   s,   e Zd ZdZejdd Zejdd ZdS )_IntentzA description of the user's intent in invoking this program.

    Each valid set of CLI flags corresponds to one intent: e.g., "upload
    data from this logdir", or "delete the experiment with that ID".
    c                 C   s   dS )zGets the message to show when executing this intent at first login.

        This need not include the header (program name) or Terms of Service
        notice.

        Returns:
          A Unicode string, potentially spanning multiple lines.
        Nr"   selfr"   r"   r#   r      s    
z_Intent.get_ack_message_bodyc                 C   s   dS )a  Carries out this intent with the specified gRPC channel.

        Args:
          server_info: A `server_info_pb2.ServerInfoResponse` value.
          channel: A connected gRPC channel whose server provides the TensorBoard
            reader and writer services.
        Nr"   r@   r   r<   r"   r"   r#   r6      s    	z_Intent.executeN)__name__
__module____qualname____doc__abcabstractmethodr   r6   r"   r"   r"   r#   r>      s
   
r>   )	metaclassc                   @   s    e Zd ZdZdd Zdd ZdS )r)   z'The user intends to revoke credentials.c                 C   s   t ddS )zMust not be called.z(No user ack needed to revoke credentialsNAssertionErrorr?   r"   r"   r#   r      s    z&_AuthRevokeIntent.get_ack_message_bodyc                 C   s   t ddS )zJExecute handled specially by `main`.

        Must not be called.
        z1_AuthRevokeIntent should not be directly executedNrI   rA   r"   r"   r#   r6      s    z_AuthRevokeIntent.executeN)rB   rC   rD   rE   r   r6   r"   r"   r"   r#   r)      s   r)   c                   @   s2   e Zd ZdZedZdd Zdd Zdd Z	d	S )
_DeleteExperimentIntentz)The user intends to delete an experiment.aA          This will delete the {num} experiment(s) on
        https://tensorboard.dev with the following experiment ID(s):

        {experiment_id_list}

        You have chosen to delete an experiment. All experiments uploaded
        to TensorBoard.dev are publicly visible. Do not upload sensitive
        data.
        c                 C   s
   || _ d S N)experiment_id_list)r@   rM   r"   r"   r#   __init__   s    z _DeleteExperimentIntent.__init__c                 C   s   | j jt| j| jdS )N)numrM   )_MESSAGE_TEMPLATEformatlenrM   r?   r"   r"   r#   r      s    z,_DeleteExperimentIntent.get_ack_message_bodyc                 C   s>  t |}| jstdi }d}d}t| jD ]}|sFd|f||< q0z t|| d| |f||< W q0 tjy   d| |f||< Y q0 tj	y   d| |f||< Y q0 t
jy } z d||f |f||< W Y d }~q0d }~0 0 q0d	}	d
}
| D ]2\}}||krt| ||kr|
|d 7 }
d}	q|	r:t|
 d S )Nz2Must specify at least one experiment ID to delete.	NO_ACTION
DIE_ACTIONzSkipping empty experiment_id.zDeleted experiment %s.NNo such experiment %s. Either it never existed or it has already been deleted.zDCannot delete experiment %s because it is owned by a different user.z*Internal error deleting experiment %s: %s.F r   T)r   TensorBoardWriterServiceStubrM   r   
FlagsErrorsetuploader_libZdelete_experimentExperimentNotFoundErrorPermissionDeniedErrorr5   RpcErrorvaluesprintr.   )r@   r   r<   
api_clientresultsrS   rT   experiment_idr;   Zany_die_actionerr_msgmsgactionr"   r"   r#   r6      sb     
z_DeleteExperimentIntent.executeN
rB   rC   rD   rE   textwrapdedentrP   rN   r   r6   r"   r"   r"   r#   rK      s   rK   c                   @   s4   e Zd ZdZedZd
ddZdd Zdd	 Z	dS )_UpdateMetadataIntentz:The user intends to update the metadata for an experiment.aM          This will modify the metadata associated with the experiment on
        https://tensorboard.dev with the following experiment ID:

        {experiment_id}

        You have chosen to modify an experiment. All experiments uploaded
        to TensorBoard.dev are publicly visible. Do not upload sensitive
        data.
        Nc                 C   s   || _ || _|| _d S rL   )rb   namedescription)r@   rb   rj   rk   r"   r"   r#   rN     s    z_UpdateMetadataIntent.__init__c                 C   s   | j j| jdS )N)rb   )rP   rQ   rb   r?   r"   r"   r#   r     s    z*_UpdateMetadataIntent.get_ack_message_bodyc              
   C   s4  t |}| j}t| j t| j |s2tdzt	j
||| j| jd W n t	jyl   td|  Y n t	jy   td|  Y nb t	jy } ztd|  W Y d }~n:d }~0  tjy } ztd|  W Y d }~n
d }~0 0 td| | jd urtd| j | jd ur0td	t| j d S )
Nz1Must specify a non-empty experiment ID to modify.rj   rk   rU   zDCannot modify experiment %s because it is owned by a different user.z0Server cannot modify experiment as requested: %sz'Internal error modifying experiment: %szModified experiment %s.zSet name to %rzSet description to %r)r   rW   rb   _die_if_bad_experiment_namerj   "_die_if_bad_experiment_descriptionrk   r   rX   rZ   Zupdate_experiment_metadatar[   r.   r\   ZInvalidArgumentErrorr5   r]   r   r1   repr)r@   r   r<   r`   rb   r;   r"   r"   r#   r6     sL    


 "z_UpdateMetadataIntent.execute)NNrf   r"   r"   r"   r#   ri     s   
ri   c                   @   s4   e Zd ZdZedZd
ddZdd Zdd	 Z	dS )_ListIntentz/The user intends to list all their experiments.z        This will list all experiments that you've uploaded to
        https://tensorboard.dev. TensorBoard.dev experiments are visible
        to everyone. Do not upload sensitive data.
        Nc                 C   s
   || _ dS )zConstructor of _ListIntent.

        Args:
          json: If and only if `True`, will print the list as pretty-formatted
            JSON objects, one object for each experiment.
        Njson)r@   rr   r"   r"   r#   rN   L  s    z_ListIntent.__init__c                 C   s   | j S rL   )_MESSAGEr?   r"   r"   r#   r   U  s    z _ListIntent.get_ack_message_bodyc                 C   s   t |}tjdddddddddd	}tj||d}d}| jrHt }nt	 }|D ].}|d7 }|j
}	t||	}
t|||
 qTtj  |stjd ntjd|  tj  d S )NT)	rj   rk   Zcreate_timeZupdate_timeZnum_runsZnum_tagsZnum_scalarsZtotal_tensor_bytesZtotal_blob_bytes)	fieldmaskr      z=No experiments. Use `tensorboard dev upload` to get started.
zTotal: %d experiment(s)
)r   TensorBoardExporterServiceStubr   ZExperimentMaskexporter_libZlist_experimentsrr   r   ZJsonFormatterZReadableFormatterrb   r-   experiment_urlr_   Zformat_experimentr   stdoutr+   r   r   )r@   r   r<   r`   rt   gencount	formatterZ
experimentrb   urlr"   r"   r#   r6   X  s>    

z_ListIntent.execute)N)
rB   rC   rD   rE   rg   rh   rs   rN   r   r6   r"   r"   r"   r#   rp   A  s   
	rp   c                 C   s$   | r t | tkr tdt| f  d S )NzFExperiment name is too long.  Limit is %s characters.
%r was provided.)rR   _EXPERIMENT_NAME_MAX_CHARSr.   )rj   r"   r"   r#   rm   }  s    rm   c                 C   s$   | r t | tkr tdt| f  d S )NzMExperiment description is too long.  Limit is %s characters.
%r was provided.)rR   !_EXPERIMENT_DESCRIPTION_MAX_CHARSr.   )rk   r"   r"   r#   rn     s    rn   c                   @   s4   e Zd ZdZedZd
ddZdd Zdd	 Z	dS )UploadIntentz?The user intends to upload an experiment from the given logdir.z        This will upload your TensorBoard logs to https://tensorboard.dev/ from
        the following directory:

        {logdir}

        This TensorBoard will be visible to everyone. Do not upload sensitive
        data.
        Nc                 C   sF   || _ || _|| _|| _|d u r$dn|| _|d u r6dn|| _|| _d S )NF)logdirrj   rk   	verbositydry_runone_shotr8   )r@   r   rj   rk   r   r   r   r8   r"   r"   r#   rN     s    
zUploadIntent.__init__c                 C   s   | j j| jdS )N)r   )rP   rQ   r   r?   r"   r"   r#   r     s    z!UploadIntent.get_ack_message_bodyc           	   
   C   s  | j rt }n
t|}t| j t| j t	j
|| jt|t|| j| j| j| jd}| jrtjj| jstd| j  td d S | }t||}| jd ur| | | jstd | j rtd ntd|  d}z>z|  W n t	jy   td Y W | jr8| s8td	| j|jf  d
}|rL|d7 }n|d7 }| j sr| rr|d| 7 }tj|d  tj   d S  t!y   d}Y n0 W | jr| std	| j|jf  d
}|r|d7 }n|d7 }| j s
| r
|d| 7 }tj|d  tj   n|| jrL| sLtd	| j|jf  d
}|r`|d7 }n|d7 }| j s| r|d| 7 }tj|d  tj   0 d S )N)allowed_pluginsupload_limitsrj   rk   r   r   z%s: No such directory.zbUser specified `one_shot` mode with an unavailable logdir. Exiting without creating an experiment.ztUpload started and will continue reading any new data as it's added to the logdir.

To stop uploading, press Ctrl-C.zC
** This is a dry run. No data will be sent to tensorboard.dev. **
z6
New experiment created. View your TensorBoard at: %s
Fz4Experiment was deleted; uploading has been cancelledzTensorBoard was run in `one_shot` mode, but did not find any uploadable data in the specified logdir: %s
An empty experiment was created. To delete the empty experiment you can execute the following

    tensorboard dev delete --experiment_id=%sz

zInterrupted.zDone.z View your TensorBoard at %sr   T)"r   r   ZDryRunTensorBoardWriterStubr   rW   rm   rj   rn   rk   rZ   ZTensorBoardUploaderr   r-   r   r   r   r   r   ioZgfileisdirr_   Zcreate_experimentrx   r8   Zstart_uploadingr[   has_datarb   r   ry   r   r+   KeyboardInterrupt)	r@   r   r<   r`   r   rb   r}   interruptedZend_messager"   r"   r#   r6     s    






	


	

	
zUploadIntent.execute)NNNNNNrf   r"   r"   r"   r#   r     s         
r   c                   @   s2   e Zd ZdZedZdd Zdd Zdd Z	d	S )
_ExportIntentz7The user intends to download all their experiment data.a^          This will download all your experiment data from https://tensorboard.dev
        and save it to the following directory:

        {output_dir}

        Downloading your experiment data does not delete it from the
        service. All experiments uploaded to TensorBoard.dev are publicly
        visible. Do not upload sensitive data.
        c                 C   s
   || _ d S rL   
output_dir)r@   r   r"   r"   r#   rN     s    z_ExportIntent.__init__c                 C   s   | j j| jdS )Nr   )rP   rQ   r   r?   r"   r"   r#   r     s    z"_ExportIntent.get_ack_message_bodyc           
   
   C   s   t |}| j}zt||}W n& tjyF   d| }t|Y n0 d}z&| D ]}|d7 }t	d|  qVW n4 tj
y }	 zt	d|	j  W Y d }	~	n
d }	~	0 0 t	d||f  d S )Nz#Output directory already exists: %rr   ru   zDownloaded experiment %sz
Uploader has failed because of a timeout error.  Please reach out via e-mail to tensorboard.dev-support@google.com to get help completing your export of experiment %s.z&Done. Downloaded %d experiments to: %s)r   rv   r   rw   ZTensorBoardExporterZOutputDirectoryExistsErrorr   rX   exportr_   ZGrpcTimeoutExceptionrb   )
r@   r   r<   r`   outdirr	   rd   Znum_experimentsrb   r;   r"   r"   r#   r6     s.    
z_ExportIntent.executeNrf   r"   r"   r"   r#   r     s   r   c              	   C   s|  t | tjd}|du r td|tjkrd| jrZttj	
| j| j| j| j| j| j|dS td|tjkr| jr| jdus| jdurt| j| j| jdS tdn
tdn|tjkr| jrt| jS tdn|tjkrt| jd	S |tjkr| jrt| jS td
n^|tjkrjt | tjd}|du rHtd|tjkrZt S td|f ntd|f dS )a  Determines what the program should do (upload, delete, ...).

    Args:
      flags: An `argparse.Namespace` with the parsed flags.
      experiment_url_callback: A function accepting a single string argument
        containing the full TB.dev URL of the uploaded experiment.

    Returns:
      An `_Intent` instance.

    Raises:
      base_plugin.FlagsError: If the command-line `flags` do not correctly
        specify an intent.
    Nz%Must specify subcommand (try --help).)rj   rk   r   r   r   r8   z0Must specify directory to upload via `--logdir`.rl   z0Must specify either `--name` or `--description`.z8Must specify experiment to modify via `--experiment_id`.z;Must specify experiment(s) to delete via `--experiment_id`.rq   z-Must specify output directory via `--outdir`.z$Must specify a subcommand to `auth`.zUnknown auth subcommand %rzUnknown subcommand %r) getattrr
   ZSUBCOMMAND_FLAGr   rX   ZSUBCOMMAND_KEY_UPLOADr   r   ospath
expanduserrj   rk   verboser   r   ZSUBCOMMAND_KEY_UPDATE_METADATArb   ri   ZSUBCOMMAND_KEY_DELETErK   ZSUBCOMMAND_KEY_LISTrp   rr   ZSUBCOMMAND_KEY_EXPORTr   r   ZSUBCOMMAND_KEY_AUTHZAUTH_SUBCOMMAND_FLAGZAUTH_SUBCOMMAND_KEY_REVOKEr)   rJ   )r7   r8   cmdZauth_cmdr"   r"   r#   r'   /  sj    









r'   c                 C   s\   | j p
tj}t| dg }| jr4| j s4t|| j|S t||}| jrX|jj	rX| j|j_	|S )Nplugins)
originr
   ZDEFAULT_ORIGINr   Zapi_endpointr-   Zcreate_server_infoZfetch_server_infor2   r3   )r7   r   r   r   r"   r"   r#   r,   |  s    
r,   c                 C   sr   | j }|jtjkr0tjd|j  tj  n>|jtj	krLt
d|j  n"|jrntjd|j  tj  d S )NzWarning [from server]: %s
zError [from server]: %s%s
)ZcompatibilityZverdictr   ZVERDICT_WARNr   r   r   detailsr+   ZVERDICT_ERRORr.   )r1   compatr"   r"   r#   r0     s    r0   c                 C   s*   t jd| f  t j  t d d S )Nr   ru   )r   r   r   r+   r   )messager"   r"   r#   r.     s    
r.   c                   @   s:   e Zd ZdZdddZdd Zdd Zd	d
 Zdd ZdS )UploaderSubcommandz)Integration point with `tensorboard` CLI.Nc                 C   s
   || _ dS )zConstructor of UploaderSubcommand.

        Args:
          experiment_url_callback: A function accepting a single string argument
            containing the full TB.dev URL of the uploaded experiment.
        N)_experiment_url_callback)r@   r8   r"   r"   r#   rN     s    zUploaderSubcommand.__init__c                 C   s   dS )Ndevr"   r?   r"   r"   r#   rj     s    zUploaderSubcommand.namec                 C   s   t | d S rL   )r
   define_flags)r@   parserr"   r"   r#   r     s    zUploaderSubcommand.define_flagsc                 C   s   t || jS rL   )r=   r   )r@   r7   r"   r"   r#   run  s    zUploaderSubcommand.runc                 C   s   dS )Nzupload data to TensorBoard.devr"   r?   r"   r"   r#   help  s    zUploaderSubcommand.help)N)	rB   rC   rD   rE   rN   rj   r   r   r   r"   r"   r"   r#   r     s   
	r   )N)N)3rE   rF   r   r   rg   Zabslr   r5   Ztensorboard.compatr   Ztensorboard.uploader.protor   r   r   Ztensorboard.uploaderr   r   r	   rw   r
   r   r   r-   r   rZ   r   Ztensorboardr   Ztensorboard.pluginsr   r   r~   r   r$   r=   ABCMetar>   r)   rK   ri   rp   rm   rn   r   r   r'   r,   r0   r.   ZTensorBoardSubcommandr   r"   r"   r"   r#   <module>   sN   
7S?<		p0
M