B
    )²ô`D>  ã               @   sD  d Z ddlmZ ddlmZ ddlm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	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$d3dd„Z%d4dd„Z&dd „ Z'd!d"„ Z(d5d#d$„Z)d%d&„ Z*d6d(d)„Z+d*d+„ Z,d,Z-d7d-d.„Z.d8d/d0„Z/d1d2„ Z0dS )9z>Shared functions and classes for tfdbg command-line interface.é    )Úabsolute_import)Údivision)Úprint_functionN)Úcommand_parser)Údebugger_cli_common)Útensor_format)Úcommon)Úops)Ú	variables)ÚgfileiÐ  ZblackZblueZcyanZgrayZgreenZmagentaZredZwhiteZyellowÚusÚmsÚsFc             C   sj   | dkrt | ƒS | dk r"d|  }n8| dk r8d| d  }n"| dk rNd| d	  }nd
| d  }|rf|d7 }|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.
  Ni   z%di   z%.2fkg      @i   @z%.2fMg      0Az%.2fGg      ÐAÚB)Ústr)Ú	num_bytesZ	include_bÚresult© r   úU/home/dcms/DCMS/lib/python3.7/site-packages/tensorflow/python/debug/cli/cli_shared.pyÚbytes_to_readable_str7   s    
r   c             C   s”   | sdS |rJ|t kr td| ƒ‚t  |¡}|}d | t dd| ¡ |¡S ttt ƒd tt 	| d¡d ƒƒ}t | }d | t dd| ¡ |¡S d	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}{}N)
Ú
TIME_UNITSÚ
ValueErrorÚindexÚformatÚmathÚpowÚminÚlenÚintÚlog)Zvalue_usZforce_time_unitÚorderZ	time_unitr   r   r   Útime_to_readable_strU   s    
"r%   c                s4   d‰ ‡ fdd„}| r,t  | ¡‰ tj|| dS dS dS )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          	      sB   t j| jtd}x,ˆ D ]$\}}t  |t  | |k| |k¡¡}qW |S )N)Zdtype)ÚnpÚzerosÚshapeÚboolÚ
logical_orÚlogical_and)ÚxÚrZrange_startZ	range_end)Úrangesr   r   Úranges_filter€   s     z-parse_ranges_highlight.<locals>.ranges_filter)Údescription)r   Zparse_rangesr   ZHighlightOptions)Zranges_stringr/   r   )r.   r   Úparse_ranges_highlightq   s    

r1   c             C   s    | rd| krd| d iS i S d S )NÚcolsZ	linewidthr   )Zscreen_infor   r   r   Ú#numpy_printoptions_from_screen_info   s    r3   c          	   C   sÆ   |rt  | |¡}|| }	n| }|}	d}
|r–t |d¡}t ||¡ W dQ R X t d¡}|tj|dd7 }|dtt 	|¡j
ƒ 7 }t |t d¡g¡}
|r¦|j|d< nt|d< tj||	d	||
||d
S )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)Zinclude_metadataÚinclude_numeric_summaryÚauxiliary_messageÚnp_printoptionsÚhighlight_options)r   Zevaluate_tensor_slicer   ZOpenr&   Úsaver   ÚRichLiner   ZStatÚlengthÚ#rich_text_lines_from_rich_line_listÚsizeÚ!DEFAULT_NDARRAY_DISPLAY_THRESHOLDr   Úformat_tensor)ZtensorZtensor_namer;   Z	print_allZtensor_slicingr<   r9   Z
write_pathÚvalueZsliced_namer:   Zoutput_fileÚliner   r   r   rC   –   s2    #

rC   c             C   s   t  td|  tƒg¡S )zËGenerate 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)Úmsgr   r   r   ÚerrorÚ   s    rI   é   c             C   sN   d| }|rt  d| ¡dg}nd}t|ƒt| |ƒ d |d | g}t  |¡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.
  ú r7   r5   ú:z  )r   ÚMenuItemrF   r@   )Úcommandr0   ÚindentÚcreate_linkZ
indent_strr6   Úlinesr   r   r   Ú_recommend_commandé   s    rR   c              C   s   dddddddg} t  | ¡S )z/Make an ASCII representation of the tfdbg logo.r7   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 )r   ÚRichTextLines)rQ   r   r   r   Úget_tfdbg_logo  s    rT   z&======================================c          
   C   s.  t  |¡}|st d¡g}nLg }xF|D ]>}t  |¡}t d¡}	|	t |t dd| ¡¡7 }	| |	¡ q&W t |¡}t t	¡}
|rŒ|
 d¡ nZ|
 d|  ¡ |
 d¡ |
 d¡ |
 
t d	d
„ |D ƒ¡¡ |
 d¡ |
 d¡ |
 
|¡ |
 t	¡ |
 d¡ |
 d¡ |
 
tdddd¡ |
 
tdddd¡ |
 
tddƒ¡ |
 
tddƒ¡ dg}|r g }xL|D ]8}| |¡ t dd| ¡}| tdƒt||ƒ ¡ qbW n
| d¡ |
 
t |¡¡ |
 d¡ |
 tdƒtdt dd¡ƒ d ¡ |
 d¡ t ¡ }| t dd¡¡ | t dd¡¡ ||
jtj< |
S ) 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)z  Nzpf '%s'z4Running a runner returned by Session.make_callable()zSession.run() call #%d:r7   z
Fetch(es):c             S   s   g | ]}d | ‘qS )z  r   )Ú.0rE   r   r   r   ú
<listcomp>G  s    z'get_run_start_intro.<locals>.<listcomp>z
Feed dict:z5Select one of the following commands to proceed ---->Úrunz1Execute the run() call with debug tensor-watchingT)rP   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_namerM   Úappendr@   rS   Ú_HORIZONTAL_BARÚextendrR   rF   Zappend_rich_lineZMenuÚannotationsZMAIN_MENU_KEY)Úrun_call_countÚfetchesÚ	feed_dictZtensor_filtersÚis_callable_runnerZfetch_linesZfeed_dict_linesZfeed_keyZfeed_key_nameZfeed_dict_lineÚoutÚ
more_linesZfilter_namesZfilter_nameZcommand_menu_nodeÚmenur   r   r   Úget_run_start_intro  s„    
















 


rh   c             C   sÐ   |rdS d|  }t |tjtjtjfƒr:|dt |¡ 7 }n0tt 	|¡ƒ}|dkr^|d| 7 }n|d| 7 }|sx|d7 }nTt|ƒdkr¼xF|D ],}|dt |t
jƒs¨t|d	ƒs¬|n|j 7 }qŠW n|d
t|ƒ 7 }|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)Ú
isinstancer	   ZTensorZ	Operationr
   ÚVariabler   r\   r!   r[   ÚsixÚstring_typesÚhasattrri   )ra   rb   rc   rd   r0   Znum_fetchesÚkeyr   r   r   Úget_run_short_description‚  s$    

rp   c          	   C   sî   t | dƒr t | jdƒr | jj}nd}dtddƒdg}t |¡}|dk	rž| t dg¡¡ | td	| d
dd¡ | td| ddd¡ | tdddd¡ n| t dg¡¡ dd| dt	t
| ƒƒ ddt	| ƒdddg	}| t |¡¡ |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.
  Úopri   Nz&--------------------------------------z(!!! An error occurred during the run !!!Zblinkr7   z,You may use the following commands to debug:zni -a -d -t %sz)Inspect information about the failing op.T)rP   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:)rn   rq   ri   rF   r   r@   r_   rS   rR   r   Útype)Ztf_errorZop_nameZintro_linesre   rf   r   r   r   Úget_error_intro²  sH    





rt   )F)N)FNNFN)rJ   F)F)F)1Ú__doc__Ú
__future__r   r   r   r   Únumpyr&   rl   Ztensorflow.python.debug.clir   r   r   Ztensorflow.python.debug.libr   Ztensorflow.python.frameworkr	   Ztensorflow.python.opsr
   Ztensorflow.python.platformr   r>   rF   rB   ZCOLOR_BLACKZ
COLOR_BLUEZ
COLOR_CYANZ
COLOR_GRAYZCOLOR_GREENZCOLOR_MAGENTArG   ZCOLOR_WHITEZCOLOR_YELLOWZTIME_UNIT_USZTIME_UNIT_MSZTIME_UNIT_Sr   r   r%   r1   r3   rC   rI   rR   rT   r^   rh   rp   rt   r   r   r   r   Ú<module>   sX   



    
=

j
-