
    BVh^                         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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 G d dej*                        Zy)z@Debugger Wrapper Session Consisting of a Local Curses-based CLI.    N)analyzer_cli)
cli_config)
cli_shared)command_parser)debugger_cli_common)profile_analyzer_cli)
ui_factory)common)
debug_data)	framework)file_iotfdbg_c                       e Zd ZdZ	 	 	 	 d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ddZddZddZd Zd Z	 ddZy)LocalCLIDebugWrapperSessiona   Concrete subclass of BaseDebugWrapperSession implementing a local CLI.

  This class has all the methods that a `session.Session` object has, in order
  to support debugging with minimal code changes. Invoking its `run()` method
  will launch the command-line interface (CLI) of tfdbg.
  Nc                    t         j                  j                  | ||       |s t        j                  t
              | _        nt        j                  j                  |      }t        j                  j                  |      rt        d|z        t        j                  j                  |      r#t        j                  |      rt        d|z        || _        | j                          i | _        | j!                  dt"        j$                         d| _        d| _        d| _        d| _        d| _        d| _        d	| _        || _        d| _        |rt9        j:                  |
      | _        yy)a  Constructor of LocalCLIDebugWrapperSession.

    Args:
      sess: The TensorFlow `Session` object being wrapped.
      dump_root: (`str`) optional path to the dump root directory. Must be a
        directory that does not exist or an empty directory. If the directory
        does not exist, it will be created by the debugger core during debug
        `run()` calls and removed afterwards. If `None`, the debug dumps will
        be at tfdbg_<random_string> under the system temp directory.
      ui_type: (`str`) requested UI type. Currently supported:
        (readline)
      thread_name_filter: Regular-expression white list for thread name. See
        the doc of `BaseDebugWrapperSession` for details.
      config_file_path: Optional override to the default configuration file
        path, which is at `${HOME}/.tfdbg_config`.

    Raises:
      ValueError: If dump_root is an existing and non-empty directory or if
        dump_root is a file.
    )thread_name_filter)prefixz#dump_root path points to a file: %sz2dump_root path points to a non-empty directory: %shas_inf_or_nanN   FT)config_file_path)r   BaseDebugWrapperSession__init__tempfilemkdtemp_DUMP_ROOT_PREFIX
_dump_rootospath
expanduserisfile
ValueErrorisdirlistdir_initialize_argparsers_tensor_filtersadd_tensor_filterr   r   _active_tensor_filter!_active_filter_exclude_node_names(_active_tensor_filter_run_start_response_run_through_times_skip_debug_run_start_response_is_run_start_ui_type_configr   	CLIConfig)selfsess	dump_rootui_typer   r   s         b/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/debug/wrappers/local_cli_wrapper.pyr   z$LocalCLIDebugWrapperSession.__init__.   s>   4 %%..d'9 / ;  ((0ABdo''$$Y/i			">JKK77==#

9(=M"# $ 	$ "do! D+Z-F-FG$ "&D-1D*48D1DD#DDDMDL));KLdl     c                      y)NT r1   s    r5   _is_disk_usage_reset_each_runz9LocalCLIDebugWrapperSession._is_disk_usage_reset_each_runz   s     r6   c                    i | _         t        j                  dt        j                        }|j	                  dddt
        dd       |j	                  d	d
ddd       |j	                  dddt        dd       |j	                  dddt        dd       |j	                  ddt        dd       |j	                  ddt        dd       |j	                  ddt        dd        |j	                  d!d"d#dd$       || j                   d%<   t        j                  d&t        j                        }|| j                   d'<   t        j                  d(      | j                   d)<   y )*Nz3Run through, with or without debug tensor watching.)descriptionusagez-tz--timestimesr   z-How many Session.run() calls to proceed with.)desttypedefaulthelpz-nz
--no_debugno_debug
store_truez*Run through without debug tensor watching.)r?   actionrB   z-fz--till_filter_passtill_filter_pass z<Run until a tensor in the graph passes the specified filter.z-fennz--filter_exclude_node_namesfilter_exclude_node_nameszWhen applying the tensor filter, exclude node with names matching the regular expression. Applicable only if --tensor_filter or -f is used.z--node_name_filternode_name_filterzXRegular-expression filter for node names to be watched in the run, e.g., loss, reshape.*z--op_type_filterop_type_filterz^Regular-expression filter for op type to be watched in the run, e.g., (MatMul|Add), Variable.*z--tensor_dtype_filtertensor_dtype_filterzcRegular-expression filter for tensor dtype to be watched in the run, e.g., (float32|float64), int.*z-pz	--profileprofilez+Run and profile TensorFlow graph execution.runz2Display information about this Session.run() call.run_infoz'Print the value of a feed in feed_dict.
print_feed)	_argparsersargparseArgumentParserSUPPRESSadd_argumentintstrr   get_print_tensor_argparser)r1   aps     r5   r$   z2LocalCLIDebugWrapperSession._initialize_argparsers   s   D		 	 I
!B OO<  > OO9  ; OOK  M OO%(   OO%  & OO)  * OO".  / OO:  < !DU		 	 H
!B $&DZ %3%N%N1&3D\"r6   c                 "    || j                   |<   y)zAdd a tensor filter.

    Args:
      filter_name: (`str`) name of the filter.
      tensor_filter: (`callable`) the filter callable. See the doc string of
        `DebugDumpDir.find()` for more details about its signature.
    N)r%   )r1   filter_nametensor_filters      r5   r&   z-LocalCLIDebugWrapperSession.add_tensor_filter   s     )6D%r6   c                 \    t        j                  t         j                  j                        S )zOverrides on-session-init callback.

    Args:
      request: An instance of `OnSessionInitRequest`.

    Returns:
      An instance of `OnSessionInitResponse`.
    )r   OnSessionInitResponseOnSessionInitActionPROCEEDr1   requests     r5   on_session_initz+LocalCLIDebugWrapperSession.on_session_init   s&     **%%--/ /r6   c                 X   d| _         | j                  |j                  |j                  |j                  |j
                         | j                  r| j                  S | j                          | j                  dkD  r| j                  s| j                  dkD  r.t        j                  t        j                  j                  g       S | j                  dk(  rJ| j                   xs< t        j                  t        j                  j"                  | j%                               S | j                   f| j'                          | j)                         | _        | j                  r| j                   | _        | j                  dkD  r| xj                  dz  c_        | j                          | j                   S )zOverrides on-run-start callback.

    Args:
      request: An instance of `OnRunStartRequest`.

    Returns:
      An instance of `OnRunStartResponse`.
    Tis_callable_runnerr   r   )r-   _update_run_calls_staterun_call_countfetches	feed_dictre   r'   r)   _exit_if_requested_by_user_run_call_countr+   r*   r   OnRunStartResponseOnRunStartActionNON_DEBUG_RUNr,   	DEBUG_RUN_get_run_debug_urls_prep_cli_for_run_start_launch_clir`   s     r5   on_run_startz(LocalCLIDebugWrapperSession.on_run_start   sq    D  1B1B"55 ! 7 !! :::##%a(8(8		 	 1	$++&&44b: 	:""a' (( 0,,..88,,.0	1
 '
""$!%!1!1!3d		#	#8<8P8P5		 	 1	$1$##%###r6   c                     | j                   t        j                  k(  r1t        dt        j
                         t	        j                  d       y y )Nz9Note: user exited from debugger CLI: Calling sys.exit(1).)filer   )r,   r   EXPLICIT_USER_EXITprintsysstderrexitr9   s    r5   rj   z6LocalCLIDebugWrapperSession._exit_if_requested_by_user  s<    #6#I#II
Ezz 
hhqk Jr6   c                 0   t        j                  | j                  | j                        | _        t        j                  g       }| j                  dk(  rF|j                  t        j                                |j                  t        j                                |j                  t        j                  d             |j                  | j                         | j                  j                  |       d| j                  z   | _        d| _        d| _        y)z/Prepare (but not launch) the CLI for run-start.)configr   zUpcoming run:zrun-start: rN   blue_on_whiteN)r	   get_uir.   r/   _run_clir   RichTextLinesrk   extendr   get_tfdbg_logoget_tensorflow_version_lines	_run_infoset_help_intro_run_description_title_init_command_title_color)r1   
help_intros     r5   rq   z3LocalCLIDebugWrapperSession._prep_cli_for_run_start  s    %%dmmDLLIDM$2226Jq 
1134+HHJK)77HIdnn%MM  ,  $"7"77DK#D'Dr6   c                    d| _         |j                  t        j                  j                  k(  rd}|j
                  r-|j
                  j                  r|j
                  j                  }n|j                  r|j                  g}|j                  r5t        j                  j                  | j                        s|j                  t        j                  | j                  |      }|j                  | j                   j"                         d}d}| j$                  r|j'                  | j(                  | j$                     d| j*                        s$| j-                          t        j.                         S | j$                  }| j*                  }d| _        d| _        | j1                  ||j                  ||       | j3                         | _        | j-                          t        j.                         S |j                  t        j                  j6                  k(  rY| j9                  | j                   j"                  |j
                         | j3                         | _        t        j.                         S d| _        t        j.                         S )zOverrides on-run-end callback.

    Actions taken:
      1) Load the debug dump.
      2) Bring up the Analyzer CLI.

    Args:
      request: An instance of OnSessionInitRequest.

    Returns:
      An instance of OnSessionInitResponse.
    FN)partition_graphsr   )first_nexclude_node_names)r-   performed_actionr   rm   ro   run_metadatar   client_graph_deftf_errorr   r   r"   r   r   DebugDumpDirset_python_graph_sessgraphr'   findr%   r(   _remove_dump_rootOnRunEndResponse_prep_debug_cli_for_run_endrr   r,   PROFILE_RUN_prep_profile_cli_for_run_end)r1   ra   r   
debug_dumppassed_filter passed_filter_exclude_node_namess         r5   
on_run_endz&LocalCLIDebugWrapperSession.on_run_end'  s    D9#=#=#G#GG			'"6"6"G"G"//@@###445			"''--"@
 **
//,<>j!!$**"2"23m)-&		#	#  !;!;<a#EE  G
 
 
 
"++-
- 44-44 +'+$
$37$
0
&&
g&&
*, "&!1!1!3d  %%'' 
	!	!Y%?%?%K%K	K
(()9)97;O;OP!%!1!1!3d %%''	 "&d %%''r6   c                     t         j                  j                  | j                        r t	        j
                  | j                         y y N)r   r   r"   r   r   delete_recursivelyr9   s    r5   r   z-LocalCLIDebugWrapperSession._remove_dump_rootm  s-    	ww}}T__%  1 &r6   c           	         |r$t        j                  |      }d| _        d| _        n=d}d| _        d| _        |+d|z  | _        |r| xj                  d|z  z  c_        d| _        t	        j
                  || j                  | j                  | j                  | j                        | _
        g }|j                  D ],  }|j                  d	|j                  |j                  fz         . | j                  j                  d
dg|       | j                  j                  g d|j!                         D cg c]  }t#        |       c}       d| j$                  z   | _        |r| j                  j)                  |       yyc c}w )aR  Prepare (but not launch) CLI for run-end, with debug dump from the run.

    Args:
      debug_dump: (debug_data.DebugDumpDir) The debug dump directory from this
        run.
      tf_error: (None or OpError) OpError that happened during the run() call
        (if any).
      passed_filter: (None or str) Name of the tensor filter that just passed
        and caused the preparation of this run-end CLI (if any).
      passed_filter_exclude_node_names: (None or str) Regular expression used
        with the tensor filter to exclude ops with names matching the regular
        expression.
    rB   red_on_whiteNltblack_on_whitezlt -f %sz --filter_exclude_node_names %s)r4   
on_ui_exitr|   z%s:%dprint_tensorpt)	node_infonilist_inputslilist_outputsloz	run-end: )r   get_error_intror   r   r   create_analyzer_uir%   r.   r   r/   r   dumped_tensor_dataappend	node_nameoutput_slotregister_tab_comp_contextnodesrV   r   r   r   )	r1   r   r   r   r   r   dumped_tensor_namesdatumr   s	            r5   r   z7LocalCLIDebugWrapperSession._prep_debug_cli_for_run_endq  sy   & --h7j!d(djd*d		"'-7+


!B!A"B C
* 33))||DM .. G  "'//53D3D!E"F GG
 	MM++^T,B,?A 	MM++F)3)9)9);<IY<>  5 55DK
mm"":.  	=s   0E<
c                     d| _         t        j                  ||| j                  | j                  j
                        | _        d| j                  z   | _        y )Nlp)r4   r|   zrun-end (profiler mode): )r   r   create_profiler_uir.   r   r|   r   r   )r1   py_graphr   s      r5   r   z9LocalCLIDebugWrapperSession._prep_profile_cli_for_run_end  sH    D(;;,}}##%DM .0E0EEDKr6   c                     | j                  | j                         | j                  j                  | j                  | j                  | j
                        }|S )zLaunch the interactive command-line interface.

    Returns:
      The OnRunStartResponse specified by the user using the "run" command.
    )init_commandtitletitle_color)_register_this_run_infor   run_uir   r   r   )r1   responses     r5   rr   z'LocalCLIDebugWrapperSession._launch_cli  sO     	  /}}##''kk%% $ 'H
 Or6   c                 
   t        j                  g       }| j                  dk(  rF|j                  t	        j
                                |j                  t        j                                |j                  | j                         | j                  sqt         j                  |j                  v rU|j                  t         j                     }d|j                         vr&|j                  dt        j                  dd             |S )Nr   list_tensorsr   )r   r   rk   r   r   r   r   r   r-   MAIN_MENU_KEYannotationscaptionsinsertMenuItem)r1   argsscreen_infooutputmenus        r5   _run_info_handlerz-LocalCLIDebugWrapperSession._run_info_handler  s     ..r2Fq mmJ--/0mm'DDFG
MM$..!))V-?-?? 3 A ABd	t}}	."++NNK	M Mr6   c           
      F   t        j                  |      }| j                  st        j                  d      S | j                  d   j                  |      }t        j                  |j                        \  }}d }d }| j                  D ]/  }	t        j                  |	      }
|
|k(  s|
}| j                  |	   } n |t        j                  d|z        S t        j                  ||dz   ||j                  |t        j                  |j                        |j                        S )Nz2The feed_dict of the current run is None or empty.rO   z<The feed_dict of the current run does not contain the key %sz (feed))	print_alltensor_slicinghighlight_optionsinclude_numeric_summary)r   #numpy_printoptions_from_screen_info
_feed_dicterrorrP   
parse_argsr   parse_tensor_name_with_slicingtensor_namer
   get_graph_element_nameformat_tensorr   parse_ranges_highlightrangesnumeric_summary)r1   r   r   np_printoptionsparsedr   r   feed_key
feed_valuekeykey_names              r5   _print_feed_handlerz/LocalCLIDebugWrapperSession._print_feed_handler  s-    DDO ??
>@ @ l+66t<F55f6H6HI  K HJ ..s3h	[	 __S)
 
H
  %%

Y

$$'&==fmmL"("8"8: :r6   c                 Z   ~| j                   d   j                  |      }|j                  xs d|_        |j                  xs d|_        |j                  xs d|_        |j
                  r|j                  st        d      |j                  rBt        j                  t        j                  t        j                  j                  g             |j                  | _        |j"                  | _        |j"                  dkD  s|j                  rt        j                  j&                  }g }n*t        j                  j(                  }| j+                         }t        j                  |||j                  |j                  |j                        }|j                  r|j                  | j,                  v rDt        j                  j(                  }|j                  | _        |j
                  | _        || _        n#t        j4                  d|j                  z  g      S t        j                  |      )z6Command handler for "run" command during on-run-start.rM   NzmThe --filter_exclude_node_names (or -feon) flag is valid only if the --till_filter_pass (or -f) flag is used.)
exit_tokenr   )node_name_regex_allowlistop_type_regex_allowlisttensor_dtype_regex_allowlistz)ERROR: tensor filter "%s" does not exist.)rP   r   rI   rJ   rK   rH   rF   r!   rL   r   CommandLineExitr   rl   rm   r   rC   r+   r>   r*   rn   ro   rp   r%   r'   r(   r)   r   )r1   r   r   r   rE   
debug_urlsrun_start_responses          r5   _run_handlerz(LocalCLIDebugWrapperSession._run_handler  s    	e$//5F$55=F"119TF!'!;!;!CtF''0G0G9: : ~~//11((44b:; ; D$llD||a6??))77fj))33f++-j"55"("9"9 & 5 5%+%?%?A  
	 	 D$8$8	8++55%+%<%<",, 	.8J5 #00:$$% &' 	'
 
-
-9K
LLr6   c                    |j                  d| j                  | j                  d   j                         dg       |j                  d| j                  | j                  d   j                         dg       |j                  d| j
                  | j                  d   j                         dg       | j                  r5|j                  ddgt        | j                  j                                      | j                  rft        | j                  d      rO| j                  j                         D cg c]  }t        j                  |       }}|j                  ddg|       y y y c c}w )	NrM   r)prefix_aliasesrN   rirO   pfkeys)register_command_handlerr   rP   format_helpr   r   r%   r   listr   r   hasattrr
   r   )r1   
curses_clir   	feed_keyss       r5   r   z3LocalCLIDebugWrapperSession._register_this_run_info7  sZ   ''++-u	 ( 
 ''$002v	 ( 
 ''  &224v	 (  **E3<+/0D0D0I0I0K+LN74??F; #oo2246 005 6i 6**L$+?K	 <6s   1E&c                 "    d| j                   z   gS )zGet the debug_urls value for the current run() call.

    Returns:
      debug_urls: (list of str) Debug URLs for the current run() call.
        Currently, the list consists of only one URL that is a file:// URL.
    zfile://)r   r9   s    r5   rp   z/LocalCLIDebugWrapperSession._get_run_debug_urlsR  s     '((r6   c                     || _         || _        t        j                  ||||      | _        | xj
                  dz  c_        t        j                  |||| j                  |      | _        y)a  Update the internal state with regard to run() call history.

    Args:
      run_call_count: (int) Number of run() calls that have occurred.
      fetches: a node/tensor or a list of node/tensor that are the fetches of
        the run() call. This is the same as the fetches argument to the run()
        call.
      feed_dict: None of a dict. This is the feed_dict argument to the run()
        call.
      is_callable_runner: (bool) whether a runner returned by
        Session.make_callable is being run.
    rd   r   N)	rk   r   r   get_run_short_descriptionr   r*   get_run_start_intror%   r   )r1   rg   rh   ri   re   s        r5   rf   z3LocalCLIDebugWrapperSession._update_run_calls_state\  sl    $ *DDO&@@-	/D
 	q 33-/DNr6   )NreadlineNFr   )F)__name__
__module____qualname____doc__r   r:   r$   r&   rb   rs   rj   rq   r   r   r   r   rr   r   r   r   r   rp   rf   r8   r6   r5   r   r   &   s     !"& %JMX
E3N	6/,$\(&D(L2B/HF"!:F6MpL6) 27	 /r6   r   )r  rQ   r   rx   r   tensorflow.python.debug.clir   r   r   r   r   r   r	   tensorflow.python.debug.libr
   r    tensorflow.python.debug.wrappersr   tensorflow.python.lib.ior   r   r   r   r8   r6   r5   <module>r     sT    G  	 
  4 2 2 6 ; < 2 . 2 6 ,  V	/)"C"C V	/r6   