o
    e!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,d6d,d-Z-d.d/ Z.d0d1 Z/d2d3 Z0G d4d5 d5ej1Z2dS )7z>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r)t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"   XD:\Projects\ConvertPro\env\Lib\site-packages\tensorboard/uploader/uploader_subcommand.py_prompt_for_user_ack;   s   
r$   c              
   C   s\  t t j t| |}t }t|tr%|  t	j
d t	j
  dS | }|sAt| tj| jd}t	j
d || | j \}}zt| }W n tjyg } ztt| W Y d}~nd}~ww t| t d| |jjst d| td t|t |}	tj!|jj|	|d}
|
 |"||
 W d   dS 1 sw   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   sN   	




"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      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   r?   )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"   rA   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      t d)zMust not be called.z(No user ack needed to revoke credentialsAssertionErrorr@   r"   r"   r#   r      s   z&_AuthRevokeIntent.get_ack_message_bodyc                 C   rJ   )zJExecute handled specially by `main`.

        Must not be called.
        z1_AuthRevokeIntent should not be directly executedrK   rB   r"   r"   r#   r6      s   z_AuthRevokeIntent.executeN)rC   rD   rE   rF   r   r6   r"   r"   r"   r#   r)      s    r)   c                   @   2   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   
   || _ d S N)experiment_id_list)rA   rQ   r"   r"   r#   __init__      
z _DeleteExperimentIntent.__init__c                 C   s   | j jt| j| jdS )N)numrQ   )_MESSAGE_TEMPLATEformatlenrQ   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 ]Z}|s#d|f||< qzt|| d| |f||< W q tjyE   d| |f||< Y q tj	yV   d| |f||< Y q t
jyr } zd||f |f||< W Y d }~qd }~ww d	}	d
}
| D ]\}}||krt| ||kr|
|d 7 }
d}	q{|	rt|
 d S 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   TensorBoardWriterServiceStubrQ   r   
FlagsErrorsetuploader_libZdelete_experimentExperimentNotFoundErrorPermissionDeniedErrorr5   RpcErrorvaluesprintr.   )rA   r   r<   
api_clientresultsrX   rY   experiment_idr;   Zany_die_actionerr_msgmsgactionr"   r"   r#   r6      sj   	z_DeleteExperimentIntent.executeN
rC   rD   rE   rF   textwrapdedentrU   rR   r   r6   r"   r"   r"   r#   rN      s    rN   c                   @   4   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 rP   )rg   namedescription)rA   rg   rp   rq   r"   r"   r#   rR     s   
z_UpdateMetadataIntent.__init__c                 C      | j j| jdS )N)rg   )rU   rV   rg   r@   r"   r"   r#   r        z*_UpdateMetadataIntent.get_ack_message_bodyc              
   C   s4  t |}| j}t| j t| j |stdzt	j
||| j| jd W nO t	jy6   td|  Y n@ t	jyE   td|  Y n1 t	jy] } ztd|  W Y d }~nd }~w tjyu } ztd|  W Y d }~nd }~ww td| | jd urtd| j | jd urtd	t| j d S d S )
Nz1Must specify a non-empty experiment ID to modify.rp   rq   rZ   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   r\   rg   _die_if_bad_experiment_namerp   "_die_if_bad_experiment_descriptionrq   r   r]   r_   Zupdate_experiment_metadatar`   r.   ra   ZInvalidArgumentErrorr5   rb   r   r1   repr)rA   r   r<   re   rg   r;   r"   r"   r#   r6     sT   




z_UpdateMetadataIntent.execute)NNrk   r"   r"   r"   r#   ro     s    
ro   c                   @   rn   )_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   
   || _ 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)rA   r{   r"   r"   r#   rR   L     
z_ListIntent.__init__c                 C   s   | j S rP   )_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r$t }nt	 }|D ]}|d7 }|j
}	t||	}
t|||
 q*tj  |sPtjd ntjd|  tj  d S )NT)	rp   rq   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_experimentsr{   r   ZJsonFormatterZReadableFormatterrg   r-   experiment_urlrd   Zformat_experimentr   stdoutr+   r   r   )rA   r   r<   re   r~   gencount	formatterZ
experimentrg   urlr"   r"   r#   r6   X  s>   

z_ListIntent.executerP   )
rC   rD   rE   rF   rl   rm   r}   rR   r   r6   r"   r"   r"   r#   rx   A  s    
	rx   c                 C   ,   | rt | tkrtdt| f  d S d S d S )NzFExperiment name is too long.  Limit is %s characters.
%r was provided.)rW   _EXPERIMENT_NAME_MAX_CHARSr.   )rp   r"   r"   r#   ru   }     ru   c                 C   r   )NzMExperiment description is too long.  Limit is %s characters.
%r was provided.)rW   !_EXPERIMENT_DESCRIPTION_MAX_CHARSr.   )rq   r"   r"   r#   rv     r   rv   c                   @   s@   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 rdn|| _|| _d S )NF)logdirrp   rq   	verbositydry_runone_shotr8   )rA   r   rp   rq   r   r   r   r8   r"   r"   r#   rR     s   

zUploadIntent.__init__c                 C   rr   )N)r   )rU   rV   r   r@   r"   r"   r#   r     rs   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rGtjj| jsGtd| j  td d S | }t||}| jd ur[| | | jsbtd | j rjtd ntd|  d}zz|  W nR t	jy   td Y 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   d S  t!y   d}Y nw 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   d S | jr| std	| j|jf  d
}|r$|d7 }n|d7 }| j s7| r7|d| 7 }tj|d  tj   w )N)allowed_pluginsupload_limitsrp   rq   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   r\   ru   rp   rv   rq   r_   ZTensorBoardUploaderr   r-   r   r   r   r   r   ioZgfileisdirrd   Zcreate_experimentr   r8   Zstart_uploadingr`   Zhas_datarg   r   r   r   r+   KeyboardInterrupt)	rA   r   r<   re   r   rg   r   ZinterruptedZend_messager"   r"   r#   r6     s   






	

	

	
zUploadIntent.execute)NNNNNNrk   r"   r"   r"   r#   r     s    
r   c                   @   rM   )
_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   rO   rP   
output_dir)rA   r   r"   r"   r#   rR     rS   z_ExportIntent.__init__c                 C   rr   )Nr   )rU   rV   r   r@   r"   r"   r#   r     rs   z"_ExportIntent.get_ack_message_bodyc           
   
   C   s   t |}| j}zt||}W n tjy!   d| }t|w d}z| D ]}|d7 }t	d|  q)W n tj
yQ }	 zt	d|	j  W Y d }	~	nd }	~	ww t	d||f  d S )Nz#Output directory already exists: %rr   r   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   r   r   r   ZTensorBoardExporterZOutputDirectoryExistsErrorr   r]   Zexportrd   ZGrpcTimeoutExceptionrg   )
rA   r   r<   re   outdirr	   ri   Znum_experimentsrg   r;   r"   r"   r#   r6     s6   

z_ExportIntent.executeNrk   r"   r"   r"   r#   r     s    r   c              	   C   sd  t | tjd}|du rtd|tjkr2| jr-ttj	
| j| j| j| j| j| j|dS td|tjkrX| jrS| jdusD| jdurNt| j| j| jdS tdtd|tjkrj| jret| jS td|tjkrut| jd	S |tjkr| jrt| jS td
|tjkrt | tjd}|du rtd|tjkrt S td|f td|f )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).)rp   rq   r   r   r   r8   z0Must specify directory to upload via `--logdir`.rt   z0Must specify either `--name` or `--description`.z8Must specify experiment to modify via `--experiment_id`.z;Must specify experiment(s) to delete via `--experiment_id`.rz   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   r]   ZSUBCOMMAND_KEY_UPLOADr   r   ospath
expanduserrp   rq   verboser   r   ZSUBCOMMAND_KEY_UPDATE_METADATArg   ro   ZSUBCOMMAND_KEY_DELETErN   ZSUBCOMMAND_KEY_LISTrx   r{   ZSUBCOMMAND_KEY_EXPORTr   r   ZSUBCOMMAND_KEY_AUTHZAUTH_SUBCOMMAND_FLAGZAUTH_SUBCOMMAND_KEY_REVOKEr)   rL   )r7   r8   cmdZauth_cmdr"   r"   r#   r'   /  sj   











r'   c                 C   s\   | j ptj}t| dg }| jr| j st|| j|S t||}| jr,|jj	r,| 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   sz   | j }|jtjkrtjd|j  tj  d S |jtj	kr(t
d|j  d S |jr;tjd|j  tj  d S d S )NzWarning [from server]: %s
zError [from server]: %s%s
)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   r   )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   ry   )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)rA   r8   r"   r"   r#   rR     r|   zUploaderSubcommand.__init__c                 C   r?   )Ndevr"   r@   r"   r"   r#   rp        zUploaderSubcommand.namec                 C   s   t | d S rP   )r
   define_flags)rA   parserr"   r"   r#   r     s   zUploaderSubcommand.define_flagsc                 C   s   t || jS rP   )r=   r   )rA   r7   r"   r"   r#   run  s   zUploaderSubcommand.runc                 C   r?   )Nzupload data to TensorBoard.devr"   r@   r"   r"   r#   help  r   zUploaderSubcommand.helprP   )	rC   rD   rE   rF   rR   rp   r   r   r   r"   r"   r"   r#   r     s    
	r   rP   )3rF   rG   r   r   rl   Zabslr   r5   Ztensorboard.compatr   Ztensorboard.uploader.protor   r   r   Ztensorboard.uploaderr   r   r	   r   r
   r   r   r-   r   r_   r   Ztensorboardr   Ztensorboard.pluginsr   r   r   r   r$   r=   ABCMetar>   r)   rN   ro   rx   ru   rv   r   r   r'   r,   r0   r.   ZTensorBoardSubcommandr   r"   r"   r"   r#   <module>   sP   
7S?<		p
0M