
    2VhW<                         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Zd dlm	Z	 d dlm
Z
 d dlmZ d dlmZ d Z e j                  d      d        Zd	 Zd
 Zd Zd ZddZd Z	 	 	 	 	 	 ddZddZy)    N)backend)tree)dtype_utils)io_utilsc                 t    | D cg c]  }|j                    }}t        t        d |D                    S c c}w )Nc              3   F   K   | ]  }t        j                  |        y wN)mathprod).0ps     M/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/utils/summary_utils.py	<genexpr>zcount_params.<locals>.<genexpr>   s     0A499Q<0s   !)shapeintsum)weightsvshapess      r   count_paramsr      s4    &'!agg'F's00011 (s   5i   c                     t        j                  |       }t        j                  |      }t	        j
                  |      }||z  S r	   )r
   r   r   standardize_dtyper   
dtype_size)r   dtypeweight_countsper_param_sizes       r   _compute_memory_sizer      s;    IIe$M%%e,E ++E2N>))    c                     | D ci c]  }t        |      | c}j                         }d}|D ]%  }|t        |j                  |j                        z  }' |dz  S c c}w )zCompute the memory footprint for weights based on their dtypes.

    Args:
        weights: An iterable contains the weights to compute weight size.

    Returns:
        The total memory size (in Bytes) of the weights.
    r      )idvaluesr   r   r   )r   wunique_weightstotal_memory_sizes       r   weight_memory_sizer&   !   sg     )001beQh0779N D1!''177CCDq  	 1s   Ac                     g d}d}|D ]#  }| |z  dk  rdj                  | |      c S | |z  } % dj                  | |d         S )z<Convert the weight memory size (Bytes) to a readable string.)BKBMBGBTBPBi      z	{:.2f} {})format)r&   unitsscaleunits       r   readable_memory_sizer4   1   sa    /EE (%)%%&8$??%'	(
 0%)<<r   c                     | d|  dS d|  dS )ztThemes numbers in a summary using rich markup.

    We use a separate color for `None`s, e.g. in a layer shape.
    z[color(45)][/]z[color(34)] xs    r   highlight_numberr:   =   s'    
 	yQCs##QCs##r   c                     d|  dS )z4Themes keras symbols in a summary using rich markup.z[color(33)]r6   r7   r8   s    r   highlight_symbolr<   H   s    3r   c                 $    |r	d| d|  dS d|  dS )zBolds text using rich markup.z[bold][color(z)]z[/][/]z[bold]r6   r7   )r9   colors     r   	bold_textr?   M   s(    ugRs&11A3c?r   c                 D   | j                   s| j                  syd t        | j                         dkD  rVt        t        | j                               D ]4  }| j                   |   j                  }t        j                  fd|      }6 nU	 t        | d      r | j                        }n5 | j                  d
i | j                  }t        j                  fd|      }t              dk(  r|d   S t        |      }|j                  dd	      }|S # t        $ r Y yw xY w)N?c                 j    | D cg c]  }t        |       }}ddj                  |      z   dz   S c c}w )N(, ))r:   join)r   r9   highlighteds      r   format_shapez(format_layer_shape.<locals>.format_shapeX   s9    49:q'*::TYY{++c11 ;s   0r   c                 (     | j                         S r	   )r   r9   rH   s    r   <lambda>z$format_layer_shape.<locals>.<lambda>e   s    ,qww/ r   output_shapec                      |       S r	   r7   rJ   s    r   rK   z$format_layer_shape.<locals>.<lambda>n   s    l1o r   r.   ' r7   )_inbound_nodes_build_shapes_dictlenrangeoutput_tensorsr   map_structurehasattrrL   compute_output_shapemap_shape_structureNotImplementedErrorstrreplace)layerioutputsoutput_shapesoutrH   s        @r   format_layer_shapera   T   s   (@(@2 5 1$s5//01 	A**1-<<G ../M			un- ,U-?-? @4%44Pu7O7OP $ 8 8-w!
 =QQ
m
C
++c2
CJ # 		s   AD 	DDc                   ()*+, ddl m} ddl m} |s$t        j                         st        j
                  }t        | |      rd,| j                  }	nt        | |      sd,| j                  }	n| j                  }	d,| j                  j                         }
g }|
D ]U  }t        |      dkD  s<t        |      dk(  r2t        t        j                  |d   j                              dkD  rd, n||z  }W ,r5| j                  D ]&  }d}|j                  D ]  }||v s|rd, nd} ,r& n ,rd}|xs g d}g d	}g d
}n8d}|xs g d}g d}g d}g +| j                  j                         D ]  }+|z  +	 r>|dz  }|D cg c]  }|dz  	 c}dgz   }|j!                  d       |j!                  d       t#        |t%        j&                         j(                  dz
        }|xs |}g }d}|D ]9  }t+        ||z        |z
  }|dk  rt-        d      |j!                  |       ||z  }; g }t/        |      D ]>  \  }}t0        j2                  j5                  |||   ||         }|j!                  |       @ t1        j2                  j6                  ||dd}+fd(d)(,fd	)d*)*fd	*t9        |	|      }|	|d   |d    D ]  } *|      D ]  } |j:                  |     t=        | d      r+t?        | j@                        }tC        | j@                        }n*t?        | jD                        }tC        | jD                        }t?        | jF                        } tC        | jF                        }!| jH                  rc| jJ                  rW| jJ                  jL                  rAt?        | jJ                  jN                        }"tC        | jJ                  jN                        }#d}$nd}"d}#d}$|| z   |"z   }%||!z   |#z   }&|r3t0        jP                  jS                  ddd      }'|'jU                          n t0        jP                  jS                  d      }'|'jW                  tY        dt0        jZ                  j]                  | j^                         d              |'jW                  |       |'jW                  tY        d!      ta        |%d"      z   d#tc        |&       d$z          |'jW                  tY        d%      ta        |d"      z   d#tc        |       d$z          |'jW                  tY        d&      ta        | d"      z   d#tc        |!       d$z          |$r8|'jW                  tY        d'      ta        |"d"      z   d#tc        |#       d$z          |rB|t        j
                  u r ||'je                         d(       y ||'je                                yyc c}w )+a  Prints a summary of a model.

    Args:
        model: Keras model instance.
        line_length: Total length of printed lines
            (e.g. set this to adapt the display to different
            terminal window sizes).
        positions: Relative or absolute positions of log elements in each line.
            If not provided, defaults to `[0.3, 0.6, 0.70, 1.]`.
        print_fn: Print function to use.
            It will be called on each line of the summary.
            You can set it to a custom function
            in order to capture the string summary.
            It defaults to `print` (prints to stdout).
        expand_nested: Whether to expand the nested models.
            If not provided, defaults to `False`.
        show_trainable: Whether to show if a layer is trainable.
            If not provided, defaults to `False`.
        layer_range: List or tuple containing two strings,
            the starting layer name and ending layer name (both inclusive),
            indicating the range of layers to be printed in the summary. The
            strings could also be regexes instead of an exact name. In this
             case, the starting layer will be the first layer that matches
            `layer_range[0]` and the ending layer will be the last element that
            matches `layer_range[1]`. By default (`None`) all
            layers in the model are included in the summary.
    r   )
Functional)
SequentialTr.   FX   )g?g?      ?)Layer (type)Output ShapeParam #)leftrj   rightl   )g333333?gQ?gGz?rf   )rg   rh   ri   zConnected to)rj   rj   rk   rj      g?rf   	Trainablecenter   z,Insufficient console width to print summary.)justifywidth)rr   
show_linesc           	      (   d}| j                   D ]{  }r|vr
|j                  D ]c  }|j                  }|j                  }t	        |j
                        }t	        |j                        }|r|dz  }||j                   d| d| dz  }e } |sd}|S )NrO   rD   [z][]-)rP   input_tensors_keras_history	operationr:   
node_indextensor_indexname)	r\   connectionsnodektkeras_historyinbound_layerr{   r|   relevant_nodess	           r   get_connectionsz&print_summary.<locals>.get_connections   s    (( 	D$n"<(( 	 " 1 1 - 7 7-m.F.FG
/0J0JK4'K$))*!J<r,qI			 Kr   c                    t        |       }|| j                  z   }| j                  j                  }t        j
                  j                  |      }|dt        t        j
                  j                  |             dz  }t        | d      st        d      }n6| j                  st        d      dz   }nt        | j                         d      }|||g}s|j                   |              	r{t        | d      rUt        | j                        dkD  r=|j                  | j                  rt!        dd	
             |S t!        dd
             |S |j                  t!        d             |S )N (rE   builtr   z
 (unbuilt),r   Y"   )r>   N	   rw   )ra   r}   	__class____name__richmarkupescaper<   rV   r:   r   r   appendrR   r   	trainabler?   )
r\   prefixrL   r}   cls_nameparamsfieldsr   sequential_likeshow_trainables
          r   get_layer_fieldsz'print_summary.<locals>.get_layer_fields  s;   )%0

"??++{{!!$'"%dkk&8&8&BCDAFFug&%a(F%a(<7F%););)=a(@BFf-MM/%01ui(S-?!-C c, 	 #3a0  in-r   c                    |rd|z  dz   dz   }nd} | |      }|g}r^t        | d      rR| j                  rF| j                  }|dz  }t        t        |            D ]  }|j	                   	||   |               |S )	Nz   u   └ rO   )r   layersr.   )nested_level)rV   r   rS   rR   extend)
r\   r   r   r   rowsnested_layersr]   expand_nestedr   print_layers
          r   r   z"print_summary.<locals>.print_layer)  s    \)E1C7FF!%7xWUH5%,,!LLMAL3}-. a 0|L r   _collected_trainable_weightsN)	highlightforce_terminalcolor_system)r   zModel: ""z Total params: r   r   rE   z Trainable params: z Non-trainable params: z Optimizer params: )
line_break)rO   )r   )3keras.src.modelsrc   rd   r   is_interactive_logging_enabled	print_msg
isinstancer   _operations_nodes_by_depthr"   rR   r   flattenrx   rP   r   minshutilget_terminal_sizecolumnsr   
ValueError	enumerater   tableColumnTable#get_layer_index_bound_by_layer_nameadd_rowrV   r   r   r&   trainable_weightsnon_trainable_weightscompiled	optimizerr   	variablesconsoleConsolebegin_captureprintr?   r   r   r}   r:   r4   end_capture)-modelline_length	positionsprint_fnr   r   layer_rangerc   rd   r   nodes_by_depthnodesr   r\   flagr   default_line_lengthheader	alignmentr   column_widthscurrentposrr   r   r]   r}   columnr   rowtrainable_counttrainable_memory_sizenon_trainable_countnon_trainable_memory_sizeoptimizer_weight_countoptimizer_memory_sizeoptimizer_builttotal_countr%   r   r   r   r   r   r   s-       ``                                  @@@@@r   print_summaryr   y   s   H ,+HCCE%%%$z* ""..557 		AA
A!DLL11C1C$D E I
 #(QJE		  
!00 (Du}.3O!#'D( '
  2!2	<-	!7!7	L5	&&--/ 	 AaN	  r!'01!QX1SE9	k"" V557??!C 4!4KMG C+%&019KLLU#5 GV$ 4""aL" # 

 	v JJg[TJE(8& 6fkJKAQ8  u% 	 CEMM3	  
 u45&u'I'IJ 2..!
 'u'>'>? 253J3J K&u'B'BC 253N3N O~~%//eoo.C.C!-eoo.G.G!H 25??3L3L M!" !!$77:PPK
#	$
	   ,,&&E ' 
 	,,&&&7 MM)ht{{'9'9%**'E&FaHIJMM%MM#$
k!_
.	/#$567q
9	:
 MM'(
oa0
2	3#$9:;1
=	>
 MM+,
1!4
6	7#$=>?q
A	B
 +,"8!;=>'(=>?qAB	
 x)))W((*u=W((*+	 O 2s   Wc                    |\t        |      dk7  rt        d| dt        |             t        |d   t              rt        |d   t              st        d|       dt        |       gS t	        |       D cg c]*  \  }}t        j                  |d   |j                        r|, }}}t	        |       D cg c]*  \  }}t        j                  |d   |j                        r|, }}}|r|st        d|       t        |      t        |      kD  rt        |      t        |      dz   gS t        |      t        |      dz   gS c c}}w c c}}w )a*  Get the layer indexes from the model based on layer names.

    The layer indexes can be used to slice the model into sub models for
    display.

    Args:
        model: `Model` instance.
        layer_names: a list or tuple of 2 strings, the starting layer name and
            ending layer name (both inclusive) for the result. All layers will
            be included when `None` is provided.

    Returns:
        The index value of layer based on its unique name (layer_names).
        Output will be [first_layer_index, last_layer_index + 1].
       zIlayer_range must be a list or tuple of length 2. Received: layer_range = z of length r   r.   z7layer_range should contain string type only. Received: zHPassed layer_names do not match the layer names in the model. Received: )
rR   r   r   rZ   r   rematchr}   r   max)r   r   idxr\   lower_indexupper_indexs         r   r   r     s     {q !!,[[9I8JL  +a.#.jNC7
 (M+ 
 3v; $F+C88KNEJJ/ 	K  $F+C88KNEJJ/ 	K  k$'
 	

 ;#k**K #k"2Q"677c+.233'
s   :/E:/Er	   )NNNFFN)	functoolsr
   r   r   r   rich.consolerich.markup
rich.table	keras.srcr   r   keras.src.utilsr   r   r   	lru_cacher   r&   r4   r:   r<   r?   ra   r   r   r7   r   r   <module>r      s      	        ' $2
 S* *! 	=$ 
"N L,^34r   