a
    SicF                     @   s   d Z ddlZddlZddlm  mZ ddlmZ ddlm	Z	 ddl
mZ zddlZW nV ey   zddlZW n6 ey   zddlZW n ey   dZY n0 Y n0 Y n0 dd Zdd	 Zd
d Zdd ZeddddZeddddZdS )z)Utilities related to model visualization.    N)io_utils)layer_utils)keras_exportc                   C   s   t duS )z#Returns True if PyDot is available.N)pydot r   r   Q/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/utils/vis_utils.pycheck_pydot-   s    r   c                	   C   s@   t  s
dS ztjt  W dS  ttjfy:   Y dS 0 dS )z6Returns True if both PyDot and Graphviz are available.FTN)r   r   DotcreateOSErrorZInvocationExceptionr   r   r   r   check_graphviz2   s    r   c                 C   s0   ddl m} ddlm} t| |o.t| j|jS )Nr   
functionalWrapper)keras.enginer   keras.layersr   
isinstancelayer
Functional)r   r   r   r   r   r   is_wrapped_model?   s
    r   c                 C   s"   |  ||s| t|| d S )N)Zget_edgeadd_edger   ZEdge)dotsrcdstr   r   r   r   H   s    r   zkeras.utils.model_to_dotFTTB`   c
           )   
      sX  | j stdddlm}
 ddlm} ddlm} t s@td|rpt	j
d| jd}|d	| j |d
d n8t	 }|d| |dd |d| |jdd |durJt|dkrtd| dt| t|d trt|d tstd| t| |}|d dk s0|d t| jkrJtdt| j d| i }i }i }i }| j}| jst	jtt| | jd}|| |S t| |jr| j s|   t|j| j}t|D ]\}}|r||d k s||d krqtt|}|j}|jj}t||r|rzt|j|
j rzt!|j|||||dd}|" }|d ||jj< |d ||jj< |#| n&d$||jj}|jjj}d$||}|rt||
j rt!||||||dd}|" }|d ||j< |d ||j< |#| |}|	r`t%|dr`|j&dur`t%|j&dr2|j&j}n"t%|j&d rJ|j&j}n
t|j&}d!||f }|rrd"||f }|rd#d$ } d"|| |j'f }|rd%d&  z |j(}!W n t)y   d'}!Y n0 t%|d(r |j*}"n,t%|d)rd*+ fd+d,|j,D }"nd'}"d-||"|!f }|r.t||
j st	j||d}|| qt|D ]\}}|r||d ksR||d krqRtt|}t|j-D ]\}}|jd. t| }#|#| j.v rt/j01|j2D ]z}$tt|$}%|s|3|%sJ |3|sJ t4||%| qt|$|
j st5|$st||
j stt5|st|3|%sVJ |3|sfJ t4||%| nXt||
j rt4||%||j 6  n2t5|rHt4||%| ||jj 6 }&t4|||& nzt|$|
j r"||$j 6 }&t||
j r||j 6 }'t4||&|' nt4||&| n&t5|$r|$jj}(t4|||( 6 | qΐqqR|S )/aw  Convert a Keras model to dot format.

    Args:
      model: A Keras model instance.
      show_shapes: whether to display shape information.
      show_dtype: whether to display layer dtypes.
      show_layer_names: whether to display layer names.
      rankdir: `rankdir` argument passed to PyDot,
          a string specifying the format of the plot:
          'TB' creates a vertical plot;
          'LR' creates a horizontal plot.
      expand_nested: whether to expand nested models into clusters.
      dpi: Dots per inch.
      subgraph: whether to return a `pydot.Cluster` instance.
      layer_range: input of `list` containing two `str` items, which is the
          starting layer name and ending layer name (both inclusive) indicating
          the range of layers for which the `pydot.Dot` will be generated. It
          also accepts regex patterns instead of exact name. In such case, start
          predicate will be the first element it matches to `layer_range[0]`
          and the end predicate will be the last element it matches to
          `layer_range[1]`. By default `None` which considers all layers of
          model. Note that you must pass range such that the resultant subgraph
          must be complete.
      show_layer_activations: Display layer activations (only for layers that
          have an `activation` property).

    Returns:
      A `pydot.Dot` instance representing the Keras model or
      a `pydot.Cluster` instance representing nested model if
      `subgraph=True`.

    Raises:
      ValueError: if `model_to_dot` is called before the model is built.
      ImportError: if pydot is not available.
    yThis model has not yet been built. Build the model first by calling `build()` or by calling the model on a batch of data.r   r   )
sequentialr   zFYou must install pydot (`pip install pydot`) for model_to_dot to work.Zdashed)style
graph_namelabelZ	labeljustlrankdirZconcentrateTdpirecordshapeN   z;layer_range must be of shape (2,). Received: layer_range = z of length    z7layer_range should contain string type only. Received: z2Both values in layer_range should be in range (0, z. Received: )r!   )subgraphz{}({})
activationname__name__z{%s|%s}z%s|%sc                 S   s   | d u rdS t | S d S )N?)str)dtyper   r   r   format_dtype  s    z"model_to_dot.<locals>.format_dtypec                 S   s$   t | t d dddddS )NNone{z/{}z/})r0   replacer&   r   r   r   format_shape  s    z"model_to_dot.<locals>.format_shaper/   input_shapeinput_shapesz, c                    s   g | ]} |qS r   r   ).0Zishaper7   r   r   
<listcomp>"      z model_to_dot.<locals>.<listcomp>z!{%s}|{input:|output:}|{{%s}|{%s}}z_ib-)7built
ValueErrorr   r   r   r   r   r   ImportErrorr   Clusterr-   setr	   Zset_node_defaultslenr   r0   r   #get_layer_index_bound_by_layer_namelayers_is_graph_networkNodeidadd_node
Sequentialbuildsuper	enumerate	__class__r.   r   r   model_to_dotZ	get_nodesZadd_subgraphformathasattrr,   r1   output_shapeAttributeErrorr8   joinr9   _inbound_nodes_network_nodestfnestflatteninbound_layersget_noder   r   get_name))modelshow_shapes
show_dtypeshow_layer_namesr#   expand_nestedr$   r*   layer_rangeshow_layer_activationsr   r   r   r   Zsub_n_first_nodeZsub_n_last_nodeZsub_w_first_nodeZsub_w_last_noderE   nodeir   layer_id
layer_name
class_nameZsubmodel_wrapperZsub_w_nodesZchild_class_nameZsubmodel_not_wrapperZsub_n_nodesr!   Zactivation_namer2   ZoutputlabelsZinputlabelsnode_keyinbound_layerZinbound_layer_idr-   output_nameinbound_layer_namer   r;   r   rO   M   s   1
"
"







"


rO   zkeras.utils.plot_model	model.pngc
                 C   s   | j stdt s8d}
dtjv r0t|
 dS t|
t| ||||||||	d	}t	|}|du rhdS t
j|\}}|sd}n|dd }|j||d |d	krzd
dlm} |j|dW S  ty   Y n0 dS )a  Converts a Keras model to dot format and save to a file.

    Example:

    ```python
    input = tf.keras.Input(shape=(100,), dtype='int32', name='input')
    x = tf.keras.layers.Embedding(
        output_dim=512, input_dim=10000, input_length=100)(input)
    x = tf.keras.layers.LSTM(32)(x)
    x = tf.keras.layers.Dense(64, activation='relu')(x)
    x = tf.keras.layers.Dense(64, activation='relu')(x)
    x = tf.keras.layers.Dense(64, activation='relu')(x)
    output = tf.keras.layers.Dense(1, activation='sigmoid', name='output')(x)
    model = tf.keras.Model(inputs=[input], outputs=[output])
    dot_img_file = '/tmp/model_1.png'
    tf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True)
    ```

    Args:
      model: A Keras model instance
      to_file: File name of the plot image.
      show_shapes: whether to display shape information.
      show_dtype: whether to display layer dtypes.
      show_layer_names: whether to display layer names.
      rankdir: `rankdir` argument passed to PyDot,
          a string specifying the format of the plot: 'TB' creates a vertical
            plot; 'LR' creates a horizontal plot.
      expand_nested: Whether to expand nested models into clusters.
      dpi: Dots per inch.
      layer_range: input of `list` containing two `str` items, which is the
        starting layer name and ending layer name (both inclusive) indicating
        the range of layers for which the plot will be generated. It also
        accepts regex patterns instead of exact name. In such case, start
        predicate will be the first element it matches to `layer_range[0]` and
        the end predicate will be the last element it matches to
        `layer_range[1]`. By default `None` which considers all layers of model.
        Note that you must pass range such that the resultant subgraph must be
        complete.
      show_layer_activations: Display layer activations (only for layers that
        have an `activation` property).

    Raises:
      ImportError: if graphviz or pydot are not available.
      ValueError: if `plot_model` is called before the model is built.

    Returns:
      A Jupyter notebook Image object if Jupyter is installed.
      This enables in-line display of the model plots in notebooks.
    r   zYou must install pydot (`pip install pydot`) and install graphviz (see instructions at https://graphviz.gitlab.io/download/) for plot_model to work.zIPython.core.magics.namespaceN)r^   r_   r`   r#   ra   r$   rb   rc   pngr)   )rP   Zpdfr   )display)filename)r>   r?   r   sysmodulesr   	print_msgr@   rO   path_to_stringospathsplitextwriteIPythonro   Image)r]   Zto_filer^   r_   r`   r#   ra   r$   rb   rc   messager   _	extensionro   r   r   r   
plot_modeln  sH    ?


r~   )	FFTr   Fr   FNF)	rm   FFTr   Fr   NF)__doc__ru   rq   tensorflow.compat.v2compatv2rW   keras.utilsr   r    tensorflow.python.util.tf_exportr   Zpydot_ngr   r@   Z	pydotplusr   r   r   r   rO   r~   r   r   r   r   <module>   sX   	           "         