
    BVh>                     .   d Z ddl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 ej$                  ZdZdZdZdZdZdZdZdZdZdZdZdZdZ eee gZ!d$dZ"d%dZ#d Z$d Z%	 	 	 	 	 d&dZ&d Z'd'dZ(d Z)d Z*	 d$d!Z+	 d$d"Z,d# Z-y)(z>Shared functions and classes for tfdbg command-line interface.    N)command_parser)debugger_cli_common)tensor_format)common)ops)tensor)	variables)gfilei  blackbluecyangraygreenmagentaredwhiteyellowusmssc                     | t        |       S | dk  rd| z  }n$| dk  r	d| dz  z  }n| dk  r	d| dz  z  }nd	| d
z  z  }|r|dz  }|S )ae  Generate a human-readable string representing number of bytes.

  The units B, kB, MB and GB are used.

  Args:
    num_bytes: (`int` or None) Number of bytes.
    include_b: (`bool`) Include the letter B at the end of the unit.

  Returns:
    (`str`) A string representing the number of bytes in a human-readable way,
      including a unit at the end.
  i   z%di   z%.2fkg      @i   @z%.2fMg      0Az%.2fGg      AB)str)	num_bytes	include_bresults      V/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/debug/cli/cli_shared.pybytes_to_readable_strr   3   st     y>IF7	F*+F:	I-.F	L01F
cMF	-    c           	         | sy|rY|t         vrt        d|z        t         j                  |      }|}dj                  | t	        j
                  dd|z        z  |      S t        t        t               dz
  t        t	        j                  | d      dz              }t         |   }dj                  | t	        j
                  dd|z        z  |      S )	aW  Convert time value to human-readable string.

  Args:
    value_us: time value in microseconds.
    force_time_unit: force the output to use the specified time unit. Must be
      in TIME_UNITS.

  Returns:
    Human-readable string representation of the time value.

  Raises:
    ValueError: if force_time_unit value is not in TIME_UNITS.
  0zInvalid time unit: %sz	{:.10g}{}g      $@      
   z{:.3g}{})

TIME_UNITS
ValueErrorindexformatmathpowminlenintlog)value_usforce_time_unitorder	time_units       r   time_to_readable_strr3   Q   s     
j(.@AA_-EIh$%)@@)LLJ!#S(B)?!)C%DEE5!IXqw(??KKr   c                 p    dfd}| r,t        j                  |       t        j                  ||       S y)av  Process ranges highlight string.

  Args:
    ranges_string: (str) A string representing a numerical range of a list of
      numerical ranges. See the help info of the -r flag of the print_tensor
      command for more details.

  Returns:
    An instance of tensor_format.HighlightOptions, if range_string is a valid
      representation of a range or a list of ranges.
  Nc           	          t        j                  | j                  t              }D ]5  \  }}t        j                  |t        j
                  | |k\  | |k              }7 |S )N)dtype)npzerosshapebool
logical_orlogical_and)xrrange_start	range_endrangess       r   ranges_filterz-parse_ranges_highlight.<locals>.ranges_filter|   sX    
%A"( MY
--2>>!{*:ANK
LaM Hr   )description)r   parse_rangesr   HighlightOptions)ranges_stringrB   rA   s     @r   parse_ranges_highlightrG   m   sA     & ((7F))=2 2 r   c                      | rd| v rd| d   iS i S )Ncols	linewidth )screen_infos    r   #numpy_printoptions_from_screen_inforM      s!    V{*V,--Ir   c           	      L   |rt        j                  | |      }||z   }	n| }|}	d}
|rt        j                  |d      5 }t	        j
                  ||       ddd       t        j                  d      }|t        j                  |d      z  }|dt        t        j                  |      j                        z  z  }t        j                  |t        j                  d      g      }
|r|j                  |d<   n	t        |d<   t        j                  ||	d	||
||
      S # 1 sw Y   xY w)a  Generate formatted str to represent a tensor or its slices.

  Args:
    tensor: (numpy ndarray) The tensor value.
    tensor_name: (str) Name of the tensor, e.g., the tensor's debug watch key.
    np_printoptions: (dict) Numpy tensor formatting options.
    print_all: (bool) Whether the tensor is to be displayed in its entirety,
      instead of printing ellipses, even if its number of elements exceeds
      the default numpy display threshold.
      (Note: Even if this is set to true, the screen output can still be cut
       off by the UI frontend if it consist of more lines than the frontend
       can handle.)
    tensor_slicing: (str or None) Slicing of the tensor, e.g., "[:, 1]". If
      None, no slicing will be performed on the tensor.
    highlight_options: (tensor_format.HighlightOptions) options to highlight
      elements of the tensor. See the doc of tensor_format.format_tensor()
      for more details.
    include_numeric_summary: Whether a text summary of the numeric values (if
      applicable) will be included.
    write_path: A path to save the tensor value (after any slicing) to
      (optional). `numpy.save()` is used to save the value.

  Returns:
    An instance of `debugger_cli_common.RichTextLines` representing the
    (potentially sliced) tensor.
  NwbzSaved value to: bold)	font_attrz (%sB) 	thresholdT)include_metadatainclude_numeric_summaryauxiliary_messagenp_printoptionshighlight_options)r   evaluate_tensor_slicer
   Openr7   saver   RichLiner   Statlength#rich_text_lines_from_rich_line_listsize!DEFAULT_NDARRAY_DISPLAY_THRESHOLDr   format_tensor)r   tensor_namerW   	print_alltensor_slicingrX   rU   
write_pathvaluesliced_namerV   output_filelines                r   rb   rb      s!   F 00HE.KEK	J	% "ggk5!"''(:;D((vFFDH,UZZ
-C-J-JKKKD+OO	"++B/02 #(::OK #DOK 		$	$5)%)
+ +" "s   DD#c                 P    t        j                  t        d| z   t              g      S )zGenerate a RichTextLines output for error.

  Args:
    msg: (str) The error message.

  Returns:
    (debugger_cli_common.RichTextLines) A representation of the error message
      for screen output.
  zERROR: )r   r_   RL	COLOR_RED)msgs    r   errorro      s+     
	@	@S)$B& 
' 'r   c                     d|z  }|rt        j                  d|       dg}nd}t        |      t        | |      z   dz   |dz   |z   g}t        j                  |      S )a  Generate a RichTextLines object that describes a recommended command.

  Args:
    command: (str) The command to recommend.
    description: (str) A description of what the command does.
    indent: (int) How many spaces to indent in the beginning.
    create_link: (bool) Whether a command link is to be applied to the command
      string.

  Returns:
    (RichTextLines) Formatted text (with font attributes) for recommending the
      command.
   rR   rP   :  )r   MenuItemrl   r_   )commandrC   indentcreate_link
indent_strrQ   liness          r   _recommend_commandrz      sk     V|*$--b':FCIIj>Bw	22S8{*,% 
	@	@	GGr   c                  4    g d} t        j                  |       S )z/Make an ASCII representation of the tfdbg logo.)rR   zTTTTTT FFFF DDD  BBBB   GGG z  TT   F    D  D B   B G    z  TT   FFF  D  D BBBB  G  GGz  TT   F    D  D B   B G   Gz  TT   F    DDD  BBBB   GGG rR   )r   RichTextLines)ry   s    r   get_tfdbg_logor}     s    % 
	*	*5	11r   z&======================================c           
      B   t        j                  |      }|st        j                  d      g}ntg }|D ]m  }t        j                  |      }t        j                  d      }	|	t        j                  |t        j
                  dd|z              z  }	|j                  |	       o t        j                  |      }t        j                  t              }
|r|
j                  d       n|
j                  d| z         |
j                  d       |
j                  d       |
j                  t        j                  |D cg c]  }d|z   	 c}             |
j                  d       |
j                  d	       |
j                  |       |
j                  t               |
j                  d       |
j                  d
       |
j                  t        ddd             |
j                  t        ddd             |
j                  t        dd             |
j                  t        dd             dg}|r[g }|D ]S  }|j                  |       t        j
                  dd|z        }|j                  t        d      t        ||      z          U n|j                  d       |
j                  t        j                  |             |
j                  d       |
j                  t        d      t        dt        j
                  dd            z   dz          |
j                  d       t        j                         }|j                  t        j
                  dd             |j                  t        j
                  dd             ||
j                  t        j                   <   |
S c c}w )aG  Generate formatted intro for run-start UI.

  Args:
    run_call_count: (int) Run call counter.
    fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
      for more details.
    feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
      for more details.
    tensor_filters: (dict) A dict from tensor-filter name to tensor-filter
      callable.
    is_callable_runner: (bool) whether a runner returned by
        Session.make_callable is being run.

  Returns:
    (RichTextLines) Formatted intro message about the `Session.run()` call.
  z	  (Empty)rs   Nzpf '%s'z4Running a runner returned by Session.make_callable()zSession.run() call #%d:rR   z
Fetch(es):z
Feed dict:z5Select one of the following commands to proceed ---->runz1Execute the run() call with debug tensor-watchingTrw   zrun -nz4Execute the run() call without debug tensor-watchingz
run -t <T>zyExecute run() calls (T - 1) times without debugging, then execute run() once more with debugging and drop back to the CLIzrun -f <filter_name>zpKeep executing run() calls until a dumped tensor passes a given, registered filter (conditional breakpoint mode)z    Registered filter(s):z	run -f %sz
        * z        (None)zFor more details, see zhelp.help.exit)r   get_flattened_namesr   r\   get_graph_element_namert   appendr_   r|   _HORIZONTAL_BARextendrz   rl   append_rich_lineMenuannotationsMAIN_MENU_KEY)run_call_countfetches	feed_dicttensor_filtersis_callable_runnerfetch_linesfeed_dict_linesfeed_keyfeed_key_namefeed_dict_lineoutrj   
more_linesfilter_namesfilter_namecommand_menu_nodemenus                    r   get_run_start_intror     s@   , **73+	*33K@AOO -33H=m*33D9n+44


&
&tY-F
GI In
 ^,- (KK/ 	))/:#JJEFJJ(>9:JJrNJJ|JJ"00!,--/ 0JJrNJJ|JJ**_**R.**DE**

=
 **

@
 **
LMN
 **
 <=> ,,*L% O+&-66
kK')<(2k;L+MMN	O &'**==jIK **R.r23'#6#?#?F#KLM  **R. 
	!	!	#$++!**5%89++!**66:;7;#//%334	*q 	.s   9Nc                    |ryd| z  }t        |t        j                  t        j                  t
        j                  f      r|dt        j                  |      z  z  }n4t        t        j                  |            }|dkD  r	|d|z  z  }n|d|z  z  }|s|dz  }|S t        |      dk(  r9|D ]2  }|dt        |t              st        |d	      s|n|j                  z  z  }4 |S |d
t        |      z  z  }|S )a  Get a short description of the run() call.

  Args:
    run_call_count: (int) Run call counter.
    fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
      for more details.
    feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
      for more details.
    is_callable_runner: (bool) whether a runner returned by
        Session.make_callable is being run.

  Returns:
    (str) A short description of the run() call, including information about
      the fetche(s) and feed(s).
  zrunner from make_callable()z	run #%d: z1 fetch (%s); r#   z%d fetches; z
%d fetch; z0 feedsz1 feed (%s)namez%d feeds)
isinstance
tensor_libTensorr   	Operationr	   Variabler   r   r,   r   r   hasattrr   )r   r   r   r   rC   num_fetcheskeys          r   get_run_short_descriptionr   ~  s   & (n,+
!!3==)2D2DE #f&C&CG&LLLK f009:KQ^k11k\K//k	9K 
 9~ O#}#s#73+? EHXXO 	OO 
 Z#i.00k	r   c           	         t        | d      r-t        | j                  d      r| j                  j                  }nd}dt        dd      dg}t	        j
                  |      }||j                  t	        j                  dg             |j                  t        d	|z  d
d             |j                  t        d|z  dd             |j                  t        ddd             n%|j                  t	        j                  dg             dd|z  dt        t        |             z   ddt        |       dddg	}|j                  t	        j                  |             |S )a  Generate formatted intro for TensorFlow run-time error.

  Args:
    tf_error: (errors.OpError) TensorFlow run-time error object.

  Returns:
    (RichTextLines) Formatted intro message about the run-time OpError, with
      sample commands for debugging.
  opr   Nz&--------------------------------------z(!!! An error occurred during the run !!!blinkrR   z,You may use the following commands to debug:zni -a -d -t %sz)Inspect information about the failing op.Tr   zli -r %sz+List inputs to the failing op, recursively.ltz6List all tensors dumped during the failing run() call.zCWARNING: Cannot determine the name of the op that caused the error.zOp name:    %szError type: zDetails:)r   r   r   rl   r   r_   r   r|   rz   r   type)tf_errorop_nameintro_linesr   r   s        r   get_error_intror     sf    Xtf!=kkGG /	3W=+ 	??L#JJ"00	78: ;JJ+g5F'+	-. JJ:/H'+	-.
 JJD	 JJ"00M2O P Q 	 s4>**	(m.
* ** ..z:;	*r   )F)N)FNNFN)   F).__doc__r)   numpyr7   tensorflow.python.debug.clir   r   r   tensorflow.python.debug.libr   tensorflow.python.frameworkr   r   r   tensorflow.python.opsr	   tensorflow.python.platformr
   r\   rl   ra   COLOR_BLACK
COLOR_BLUE
COLOR_CYAN
COLOR_GRAYCOLOR_GREENCOLOR_MAGENTArm   COLOR_WHITECOLOR_YELLOWTIME_UNIT_USTIME_UNIT_MSTIME_UNIT_Sr%   r   r3   rG   rM   rb   ro   rz   r}   r   r   r   r   rK   r   r   <module>r      s    E   6 ; 5 . + < + ,!! %) !


	L+6
<L8< "!%$(*/!A+H'H82 ; ,1	h\ 27/d;r   