o
    xiHB                     @  sv  U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZmZ ddlZer=ddlZejdddd	ZdZejd
dddZejdddZdaded< 	 daded< 	 daded< 	 daded< 	 daded< 	 e Zded< 	 e	 Z	 g Z ded< 	 G dd de!Z"G dd  d eZ#did&d'Z$ej%djd)d*Z&dkd+d,Z'dkd-d.Z(dld1d2Z)dkd3d4Z*	5			dmdnd;d<Z+			dodnd=d>Z,			dodnd?d@Z-dkdAdBZ.dkdCdDZ/dddEdpdJdKZ0dqdLdMZ1dddEdrdOdPZ2G dQdR dRZ3dsdTdUZ4e5dVZ6dtdYdZZ7dtd[d\Z8d5ddddej9fdud_d`Z:dvdadbZ;ej%dcdd Z<dvdedfZ=dvdgdhZ>dS )wax  Global functions for interacting with the terminal for wandb.

The functions termlog, termwarn and termerror print to stderr.

The function terminput prints to stderr and reads from stdin.

We print to stderr because wandb does not output any messages that are useful
to pipe to another program. Using stderr allows using wandb in a program that
*does* output pipe-able text.
    )annotationsN)Iterator)TYPE_CHECKINGProtocolwandbblueT)fgboldERRORredgreen)bgr   WARNINGyellow)r   Fbool_silentSupportsLeveledLogging | None_logger
_show_info_show_warnings_show_errorszset[str]_printed_messageszlist[DynamicBlock]_dynamic_blocksc                   @  s   e Zd ZdZdS )NotATerminalErrorz@The output device is not sufficiently capable for the operation.N)__name__
__module____qualname____doc__ r   r   E/home/ubuntu/.local/lib/python3.10/site-packages/wandb/errors/term.pyr   @   s    r   c                   @  s.   e Zd ZdZdddZddd	Zdd
dZdS )SupportsLeveledLoggingz;Portion of the standard logging.Logger used in this module.msgstrreturnNonec                 C     d S Nr   selfr!   r   r   r   infoG       zSupportsLeveledLogging.infoc                 C  r%   r&   r   r'   r   r   r   warningH   r*   zSupportsLeveledLogging.warningc                 C  r%   r&   r   r'   r   r   r   errorI   r*   zSupportsLeveledLogging.errorN)r!   r"   r#   r$   )r   r   r   r   r)   r+   r,   r   r   r   r   r    D   s
    

r    settingswandb.Settingsloggerr#   r$   c                 C  s    | j a| ja| ja| ja|adS )a  Configure the global logging functions.

    Args:
        settings: The settings object passed to wandb.setup() or wandb.init().
        logger: A fallback logger to use for "silent" mode. In this mode,
            the logger is used instead of printing to stderr.
    N)	silentr   	show_infor   show_warningsr   show_errorsr   r   )r-   r/   r   r   r   	termsetupL   s
   r4   Iterator[DynamicBlock | None]c                  c  s    t sts
dV  dS t rt rdV  dS t } t t|  W d   n1 s*w   Y  z$| V  W t g | _t	  t
|  W d   dS 1 sMw   Y  dS t g | _t	  t
|  W d   w 1 slw   Y  w )a^  A context manager that provides a handle to a new dynamic text area.

    The text goes to stderr. Returns None if dynamic text is not supported.

    Dynamic text must only be used while `wandb` has control of the terminal,
    or else text written by other programs will be overwritten. It's
    appropriate to use during a blocking operation.

    ```
    with term.dynamic_text() as text_area:
        if text_area:
            text_area.set_text("Writing to a terminal.")
            for i in range(2000):
                text_area.set_text(f"Still going... ({i}/2000)")
                time.sleep(0.001)
        else:
            wandb.termlog("Writing to a file or dumb terminal.")
            time.sleep(1)
            wandb.termlog("Finished 1000/2000 tasks, still working...")
            time.sleep(1)
    wandb.termlog("Done!", err=True)
    ```
    N)r   r   _sys_stderr_isatty_is_term_dumbDynamicBlock_dynamic_text_lockr   append_lines_to_print_l_rerender_dynamic_blocksremoveblockr   r   r   dynamic_text_   s,   	(r@   c                   C  
   t tjS )zJReturns sys.stderr.isatty().

    Defined here for patching in tests.
    )_isattysysstderrr   r   r   r   r6         
r6   c                   C  rA   )zIReturns sys.stdin.isatty().

    Defined here for patching in tests.
    )rB   rC   stdinr   r   r   r   _sys_stdin_isatty   rE   rG   streamobjectc                 C  s>   t | dd}|rt|sdS zt| W S  ty   Y dS w )zReturns true if the stream defines isatty and returns true for it.

    This is needed because some people patch `sys.stderr` / `sys.stdin`
    with incompatible objects, e.g. a Logger.

    Args:
        stream: An IO object like stdin or stderr.
    isattyNF)getattrcallabler   	TypeError)rH   rJ   r   r   r   rB      s   	rB   c                   C  s   t ddkS )zReturns whether the TERM environment variable is set to 'dumb'.

    This is a convention to indicate that the terminal doesn't support
    ANSI sequences like colors, clearing the screen and positioning the cursor.
    TERMdumb)osgetenvr   r   r   r   r7      s   r7    stringr"   newlinerepeatprefixc                 C  s   t | |||t d dS )a  Log an informational message to stderr.

    The message may contain ANSI color sequences and the \n character.
    Colors are stripped if stderr is not a TTY.

    Args:
        string: The message to display.
        newline: Whether to add a newline to the end of the string.
        repeat: If false, then the string is not printed if an exact match has
            already been printed through any of the other logging functions
            in this file.
        prefix: Whether to include the 'wandb:' prefix.
    )rT   rU   rV   r0   N)_logr   rS   rT   rU   rV   r   r   r   termlog   s   
rY   c                 C  6   d dd | dD } t| |||t tjd dS )zQLog a warning to stderr.

    The arguments are the same as for `termlog()`.
    
c                 S     g | ]	}t  d | qS  )WARN_STRING.0sr   r   r   
<listcomp>       ztermwarn.<locals>.<listcomp>rT   rU   rV   r0   levelN)joinsplitrW   r   loggingr   rX   r   r   r   termwarn      

rj   c                 C  rZ   )zPLog an error to stderr.

    The arguments are the same as for `termlog()`.
    r[   c                 S  r\   r]   )ERROR_STRINGr`   r   r   r   rc     rd   ztermerror.<locals>.<listcomp>re   N)rg   rh   rW   r   ri   r
   rX   r   r   r   	termerror   rk   rm   c                  C  s   ddl m}  |  S )z,Returns True if we're in a Jupyter notebook.r   ipython)wandb.sdk.libro   
in_jupyterrn   r   r   r   _in_jupyter  s   rr   c                  C  s<   t strt r	dS ddlm}  |  rdS t pt ot S )z:Returns True if terminput won't raise a NotATerminalError.Fr   util)	r   r   r7   r   rt   _is_databricksrr   r6   rG   rs   r   r   r   can_use_terminput  s   rv   timeouthidepromptrx   float | Nonery   c                C  s   t  d|  }t|||dS )a  Prompt the user for input.

    Args:
        prompt: The prompt to display. The prompt is printed without a newline
            and the cursor is positioned after the prompt's last character.
            The prompt should end with whitespace.
        timeout: A timeout after which to raise a TimeoutError.
            Cannot be set if hide is True.
        hide: If true, does not echo the characters typed by the user.
            This is useful for passwords.

    Returns:
        The text typed by the user before pressing the 'return' key.

    Raises:
        TimeoutError: If a timeout was specified and expired.
        NotATerminalError: If the output device is not capable, like if stderr
            is redirected to a file, stdin is a pipe or closed, TERM=dumb is
            set, or wandb is configured in 'silent' mode.
        KeyboardInterrupt: If the user pressed Ctrl+C during the prompt.
    : rw   )
LOG_STRING
_terminput)rz   rx   ry   prefixed_promptr   r   r   	terminput%  s   r   c                 C  s6   |  d} 	 t |   }|dv rdS |dv rdS q)zPrompt the user with a yes/no question.

    Args:
        prompt: A prompt ending with a question mark (not whitespace),
            like "Are you sure?".

    Returns:
        The user's choice.
    z [y/n] T)nnoF)yyes)r   striplower)rz   answerr   r   r   confirmD  s   

r   r   c                C  s   t  st|r|durt|dur0ddlm} z
|| |dt dW S  ty/   tj	d  w z
t
j| d|ddW S  t
jyK   tj	d tdw )	z3Implements terminput() and can be patched by tests.Nr   )timed_inputT)rx   errjupyterr[   rR   )prompt_suffix
hide_inputr   )rv   r   NotImplementedErrorwandb.sdk.lib.timed_inputr   rr   KeyboardInterruptrC   rD   writeclickrz   Abort)r   rx   ry   r   r   r   r   r~   X  s8   r~   c                   @  s:   e Zd ZdZdddZddddZdddZdddZdS )r8   z3A handle to a changeable text area in the terminal.r#   r$   c                 C  s   g | _ d| _d S )Nr   )r;   _num_lines_printedr(   r   r   r   __init__  s   
zDynamicBlock.__init__Ttextr"   rV   r   c                 C  sP   t  | | _|rdd | jD | _t  W d   dS 1 s!w   Y  dS )a@  Replace the text in this block.

        Args:
            text: The text to put in the block, with lines separated
                by \n characters. The text should not end in \n unless
                a blank line at the end of the block is desired.
            prefix: Whether to include the "wandb:" prefix.
        c                 S  r\   r|   r}   ra   liner   r   r   rc     s    z)DynamicBlock.set_text.<locals>.<listcomp>N)r9   
splitlinesr;   r<   )r(   r   rV   r   r   r   set_text  s   	
"zDynamicBlock.set_textc                 C  s&   d}t j|| j tjdd d| _dS )zSend terminal commands to clear all previously printed lines.

        The lock must be held, and the cursor must be on the line after this
        block of text.
        z
[Am[2KFfilenlr   N)r   echor   rC   rD   )r(   move_up_and_delete_liner   r   r   _l_clear  s   
zDynamicBlock._l_clearc                   sJ   | j rt  tjd fdd| j D tjd |  jt| j 7  _dS )zFPrint out this block of text.

        The lock must be held.
        r[   c                 3  s    | ]}t | V  qd S r&   )_ansi_shortenr   
term_widthr   r   	<genexpr>  s
    
z(DynamicBlock._l_print.<locals>.<genexpr>)r   N)	r;   _shutil_get_terminal_widthr   r   rg   rC   rD   r   lenr   r   r   r   _l_print  s   	zDynamicBlock._l_printNr#   r$   )T)r   r"   rV   r   r#   r$   )r   r   r   r   r   r   r   r   r   r   r   r   r8     s    

r8   intc                  C  s   t  \} }| S )zPReturns the width of the terminal.

    Defined here for patching in tests.
    )shutilget_terminal_size)columns_r   r   r   r     s   r   z\[(K|.*?m)r   widthc                 C  sl   t | }|st| |S | |d krt| d|  |S | d|  t| | d ||   S )zBShorten text potentially containing ANSI sequences to fit a width.   N)_ANSI_REsearch_raw_shortenstartendr   )r   r   
first_ansir   r   r   r     s   


r   c                 C  s$   t | |kr| S | d|d  d S )zShorten text to fit a width, replacing the end with "...".

    Unlike textwrap.shorten(), this does not drop whitespace or do anything
    smart.
    Nr   z...)r   )r   r   r   r   r   r     s   r   r0   rf   c              	   C  s,  t  t n |s'| tv r	 W d    W d    d S ttdk r't|  |r6ddd | dD } |p9t}|sFtj	| t
j|d n'tsIn$|tjkrWtt|  n|tjkrett|  ntt|  W d    n1 sww   Y  W d    d S W d    d S 1 sw   Y  d S )Ni  r[   c                 S  r\   r   r   r`   r   r   r   rc     rd   z_log.<locals>.<listcomp>r   )r9   _l_above_dynamic_textr   r   addrg   rh   r   r   r   rC   rD   r   ri   r
   r,   unstyler   r+   r)   )rS   rT   rU   rV   r0   rf   r   r   r   rW     s*   


PrW   c                   C  s,   t  	 W d   dS 1 sw   Y  dS )zClear and re-print all dynamic text.

    The lock must be held. The cursor must be positioned at the start of
    the first line after the dynamic text area.
    N)r   r   r   r   r   r<     s   "r<   c                   c  s$    t   z	dV  W t  dS t  w )zA context manager for inserting static text above any dynamic text.

    The lock must be held. The cursor must be positioned at the start of the
    first line after the dynamic text area.

    The dynamic text is re-rendered.
    N)_l_clear_dynamic_blocks_l_print_dynamic_blocksr   r   r   r   r     s
   	r   c                  C  s   t tD ]} |   qdS )zDelete all dynamic text.

    The lock must be held, and the cursor must be positioned at the start
    of the first line after the dynamic text area. After this, the cursor
    is positioned at the start of the first line after all static text.
    N)reversedr   r   r>   r   r   r   r   /  s   
r   c                  C  s   t D ]} |   qdS )zOutput all dynamic text.

    The lock must be held. After this, the cursor is positioned at the start
    of the first line after the dynamic text area.
    N)r   r   r>   r   r   r   r   :  s   
r   )r-   r.   r/   r   r#   r$   )r#   r5   )r#   r   )rH   rI   r#   r   )rR   TTT)
rS   r"   rT   r   rU   r   rV   r   r#   r$   )TTT)rz   r"   rx   r{   ry   r   r#   r"   )rz   r"   r#   r   )r   r"   rx   r{   ry   r   r#   r"   )r#   r   )r   r"   r   r   r#   r"   )rS   r"   rT   r   rU   r   rV   r   r0   r   rf   r   r#   r$   r   )?r   
__future__r   
contextlibri   rP   rer   rC   	threadingcollections.abcr   typingr   r   r   r   styler}   LOG_STRING_NOCOLORrl   r_   r   __annotations__r   r   r   r   setr   Lockr9   r   	Exceptionr   r    r4   contextmanagerr@   r6   rG   rB   r7   rY   rj   rm   rr   rv   r   r   r~   r8   r   compiler   r   r   INFOrW   r<   r   r   r   r   r   r   r   <module>   s    

9






)
I
	


 

