a
    Sic P                     @   s  d Z ddlZddl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 ddlmZ ddlmZ ddlmZ ed	g d
dd Zdd ZdBddZdd Zdd ZdCddZdd ZG dd dZdDddZdd  Zd!d" Ze  a!d#d$ Z"d%d& Z#ed'g d
d(d) Z$d*d+ Z%d,d- Z&d.d/ Z'd0d1 Z(d2d3 Z)d4d5 Z*ej+d6d7 Z,ej+d8d9 Z-d:d; Z.dEd<d=Z/d>d? Z0d@dA Z1dS )FzTensorFlow-related utilities.    N)backend)keras_tensor)object_identity)tf_contextlib)ops)keras_exportzkeras.utils.set_random_seed)v1c                 C   sX   t | ts$td|  dt|  dt|  tj|  tj|  t	| t
j_dS )a  Sets all random seeds for the program (Python, NumPy, and TensorFlow).

    You can use this utility to make almost any Keras program fully
    deterministic. Some limitations apply in cases where network communications
    are involved (e.g. parameter server distribution), which creates additional
    sources of randomness, or when certain non-deterministic cuDNN ops are
    involved.

    Calling this utility is equivalent to the following:

    ```python
    import random
    import numpy as np
    import tensorflow as tf
    random.seed(seed)
    np.random.seed(seed)
    tf.random.set_seed(seed)
    ```

    Arguments:
      seed: Integer, the random seed to use.
    z:Expected `seed` argument to be an integer. Received: seed=z
 (of type )N)
isinstanceint
ValueErrortyperandomseednptfset_seedRandomr   _SEED_GENERATOR	generator)r    r   P/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/utils/tf_utils.pyset_random_seed"   s    

r   c                 C   s,   t j| } | r$t| d t jr$dS dS d S )Nr   TF)r   nestflattenr
   Tensor)vr   r   r   is_tensor_or_tensor_listE   s    r   c                 C   s  t jj| dd} t| }|r0tt j|}t| }|r| }t|t	t
rXq:t|t jr|jdd ptg }||j7 }nTt|t jrz|jg}W q ty   g }Y q0 n"t |r| }ntd| |D ]0}||vr|| |r || || q|r:|s:|S q:|S )a_  Returns the set of tensors/ops reachable from `inputs`.

    Stops if all targets have been found (target is optional).

    Only valid in Symbolic mode, not Eager mode.

    Args:
      inputs: List of tensors.
      targets: List of tensors.

    Returns:
      A set of tensors reachable from the inputs (includes the inputs
      themselves).
    Texpand_compositesNz<Expected tf.Operation, tf.Variable, or tf.Tensor. Received: )r   r   r   r   ObjectIdentitySetcollectionsdequepopr
   tuple_user_convertible_tensor_types	Operationoutputs_control_outputsVariableopAttributeError	is_tensor	consumers	TypeErroradddiscard
appendleft)inputstargets	reachableremaining_targetsqueuexr'   yr   r   r   get_reachable_from_inputsM   sF    






r9   c                    s    rS t js4td dt t jjr^fddt D }nt jj	rvt
}n} fdd|D }t jj|S )a  Maps the atomic elements of a nested structure.

    Args:
      is_atomic_fn: A function that determines if an element of `nested` is
        atomic.
      map_fn: The function to apply to atomic elements of `nested`.
      nested: A nested structure.

    Returns:
      The nested structure, with atomic elements mapped according to `map_fn`.

    Raises:
      ValueError: If an element that is neither atomic nor a sequence is
        encountered.
    z.Received non-atomic and non-sequence element: z	 of type c                    s   g | ]} | qS r   r   ).0knestedr   r   
<listcomp>       z-map_structure_with_atomic.<locals>.<listcomp>c                    s   g | ]}t  |qS r   map_structure_with_atomicr:   ele)is_atomic_fnmap_fnr   r   r>      s   )r   r   	is_nestedr   r   __internal__
is_mappingsortedkeysis_attrs_astuplesequence_like)rD   rE   r=   valuesmapped_valuesr   )rD   rE   r=   r   rA      s"    
rA   c                 C   s   t jdd | S )zGets shapes from tensors.c                 S   s   t | dr| jS d S )Nshape)hasattrrP   r7   r   r   r   <lambda>   r?   zget_shapes.<locals>.<lambda>)r   r   map_structuretensorsr   r   r   
get_shapes   s    rW   Tc                    s,   dd   fdd}fdd}t ||| S )a  Converts nested shape representations to desired format.

    Performs:

    TensorShapes -> tuples if `to_tuples=True`.
    tuples of int or None -> TensorShapes if `to_tuples=False`.

    Valid objects to be converted are:
    - TensorShapes
    - tuples with elements of type int or None.
    - ints
    - None

    Args:
      input_shape: A nested structure of objects to be converted to
        TensorShapes.
      to_tuples: If `True`, converts all TensorShape to tuples. Otherwise
        converts all tuples representing shapes to TensorShapes.

    Returns:
      Nested structure of shapes in desired format.

    Raises:
      ValueError: when the input tensor shape can't be converted to tuples, eg
        unknown tensor shape.
    c                 S   s   | d u pt | ttjjjfS N)r
   r   r   compatr   	Dimensionvaluer   r   r   _is_shape_component   s    z+convert_shapes.<locals>._is_shape_componentc                    sH    | rdS t | tjrdS t | ttfrDt fdd| D rDdS dS )NTc                 3   s   | ]} |V  qd S rX   r   rB   r]   r   r   	<genexpr>   s   z;convert_shapes.<locals>._is_atomic_shape.<locals>.<genexpr>F)r
   r   TensorShaper$   listallinput_shaper^   r   r   _is_atomic_shape   s    z(convert_shapes.<locals>._is_atomic_shapec                    s   t | }  rt|  } | S rX   )r   r`   r$   as_listrc   	to_tuplesr   r   _convert_shape   s    
z&convert_shapes.<locals>._convert_shaper@   )rd   rh   re   ri   r   )r]   rh   r   convert_shapes   s    rj   c                 C   s   t |}|j}|s"td| t| tr4| g} nt| } t| D ]\}}|dk rD|| | |< qD| D ],}|dk sz||krftd| dt|  qft	| t	t
| krtdt|  | S )aT  Validate an axis value and returns its standardized form.

    Args:
      axis: Value to validate. Can be an integer or a list/tuple of integers.
        Integers may be negative.
      input_shape: Reference input shape that the axis/axes refer to.

    Returns:
      Normalized form of `axis`, i.e. a list with all-positive values.
    z0Input has undefined rank. Received: input_shape=r   zVInvalid value for `axis` argument. Expected 0 <= axis < inputs.rank (with inputs.rank=z). Received: axis=zDuplicate axis: )r   r`   rankr   r
   r   ra   	enumerater$   lenset)axisrd   rk   idxr7   r   r   r   validate_axis   s0    

rq   c                   @   s    e Zd ZdZdd Zdd ZdS )ListWrapperz9A wrapper for lists to be treated as elements for `nest`.c                 C   s
   || _ d S rX   _list)selflist_to_wrapr   r   r   __init__  s    zListWrapper.__init__c                 C   s   | j S rX   rs   )ru   r   r   r   rf     s    zListWrapper.as_listN)__name__
__module____qualname____doc__rw   rf   r   r   r   r   rr     s   rr   Fc                    s.   dd   fdd} fdd}t ||| S )a^  Either wraps or unwraps innermost node data lists in `ListWrapper`
    objects.

    Args:
      nested: A nested data structure.
      wrap: If `True`, wrap innermost lists in `ListWrapper` objects. If
        `False`, unwraps `ListWrapper` objects into lists.

    Returns:
      Structure of same type as nested, with lists wrapped/unwrapped.
    c                 S   s,   t | tr(t| dv r(t | d tr(dS dS )N)      r   TF)r
   ra   rm   strr<   r   r   r   _is_serialized_node_data,  s    
z9convert_inner_node_data.<locals>._is_serialized_node_datac                    s(   t | trdS  | rdS tj|  S )z<Returns `True` if `nested` is a list representing node data.T)r
   rr   r   r   rF   r<   )r   r   r   _is_atomic_nested7  s
    
z2convert_inner_node_data.<locals>._is_atomic_nestedc                    s@   r&t | tr| S  | r"t| S | S t | tr8|  S | S dS )z:Convert b/t `ListWrapper` object and list representations.N)r
   rr   rf   r<   r   wrapr   r   _convert_object_or_list?  s    

z8convert_inner_node_data.<locals>._convert_object_or_listr@   )r=   r   r   r   r   r   r   convert_inner_node_data  s    r   c                    s    fdd}|S )zDecorator that handles tuple/TensorShape conversion.

    Used in `compute_output_shape` and `build`.

    Args:
      fn: function to wrap.

    Returns:
      Wrapped function.
    c                    s6   |d urt |dd} | |}|d ur2t |dd}|S )NTrg   F)rj   )instancerd   output_shapefnr   r   wrapper]  s    
z&shape_type_conversion.<locals>.wrapperr   )r   r   r   r   r   shape_type_conversionQ  s    r   c                 C   s   t tt| S rX   )rb   mapis_symbolic_tensorrU   r   r   r   are_all_symbolic_tensorsk  s    r   c                 C   s   t | tjjS )a  Returns whether a tensor is of an ExtensionType.

    github.com/tensorflow/community/pull/269
    Currently it works by checking if `tensor` is a `CompositeTensor` instance,
    but this will be changed to use an appropriate extensiontype protocol
    check once ExtensionType is made public.

    Args:
      tensor: An object to test

    Returns:
      True if the tensor is an extension type object, false if not.
    )r
   r   rG   CompositeTensortensorr   r   r   is_extension_typer  s    r   c                 C   s   t | tjrt| dS t| r@tjj| dd}tdd |D S t | tjrbt	| ddp`t
  S t | ttrt| } t| S dS dS )	a[  Returns whether a tensor is symbolic (from a TF graph) or an eager
    tensor.

    A Variable can be seen as either: it is considered symbolic
    when we are in a graph scope, and eager when we are in an eager scope.

    Args:
      tensor: A tensor instance to test.

    Returns:
      True for symbolic tensors, False for eager tensors.
    graphTr   c                 s   s   | ]}t |d V  qdS )r   N)rQ   )r:   tr   r   r   r_     r?   z%is_symbolic_tensor.<locals>.<genexpr>_keras_historyFN)r
   r   r   rQ   r   r   r   anyr)   getattrexecuting_eagerlyr$   r%   r   convert_to_tensor_or_compositer   )r   component_tensorsr   r   r   r     s    

r   z6keras.__internal__.utils.register_symbolic_tensor_typec                 C   s$   | t vrt| tj t |  dS )a%  Allows users to specify types regarded as symbolic `Tensor`s.

    Used in conjunction with `tf.register_tensor_conversion_function`, calling
    `tf.keras.__internal__.utils.register_symbolic_tensor_type(cls)`
    allows non-`Tensor` objects to be plumbed through Keras layers.

    Example:

    ```python
    # One-time setup.
    class Foo:
      def __init__(self, input_):
        self._input = input_
      def value(self):
        return tf.constant(42.)

    tf.register_tensor_conversion_function(
        Foo, lambda x, *args, **kwargs: x.value())

    tf.keras.__internal__.utils.register_symbolic_tensor_type(Foo)

    # User-land.
    layer = tf.keras.layers.Lambda(lambda input_: Foo(input_))
    ```

    Args:
      cls: A `class` type which shall be regarded as a symbolic `Tensor`.
    N)r%   r   $register_keras_tensor_specializationUserRegisteredTypeKerasTensorr/   )clsr   r   r   register_symbolic_tensor_type  s
    r   c                 C   s@   t | r| jS t| dr2t| dr2t| j| jS t| S dS )z9Grab type_spec without converting array-likes to tensors.rP   dtypeN)r   
_type_specrQ   r   
TensorSpecrP   r   type_spec_from_valuer[   r   r   r   r     s
    r   c                 C   s   t | tjtjjjjfS )zCReturns true if `tensor` is a ragged tensor or ragged tensor value.)r
   r   RaggedTensorrY   r   raggedRaggedTensorValuer   r   r   r   	is_ragged  s    r   c                 C   s   t | tjtjjjfS )zCReturns true if `tensor` is a sparse tensor or sparse tensor value.)r
   r   SparseTensorrY   r   SparseTensorValuer   r   r   r   	is_sparse  s    r   c                 C   s   t | pt| t jS rX   )r   r,   r
   r)   rR   r   r   r   is_tensor_or_variable  s    r   c                 C   s   t | pt| S )z<Returns true if 'x' is a TF-native type or an ExtensionType.)r   r,   r   rR   r   r   r   is_tensor_or_extension_type  s    r   c                 C   s:   dd | D }|r6d dd |D }td| ddS )	aV  Prevent tf.layers.Layers from being used with Keras.

    Certain legacy layers inherit from their keras analogs; however they are
    not supported with keras and can lead to subtle and hard to diagnose bugs.

    Args:
      layers: A list of layers to check

    Raises:
      TypeError: If any elements of layers are tf.layers.Layers
    c                 S   s   g | ]}t |d dr|qS )_is_legacy_layerN)r   r:   lr   r   r   r>     r?   z+assert_no_legacy_layers.<locals>.<listcomp>
c                 s   s   | ]}d t | V  qdS )z  N)r~   r   r   r   r   r_     r?   z*assert_no_legacy_layers.<locals>.<genexpr>z+The following are legacy tf.layers.Layers:
z
To use keras as a framework (for instance using the Network, Model, or Sequential classes), please use the tf.keras.layers implementation instead. (Or, if writing custom layers, subclass from tf.keras.layers rather than tf.layers)N)joinr.   )layerslegacy_layers	layer_strr   r   r   assert_no_legacy_layers  s    
r   c                 c   sR   t jj rHt| ddrHt   dV  W d   qN1 s<0    Y  ndV  dS )zOpen an `init_scope` if in V2 mode and using the keras graph.

    Args:
      layer: The Layer/Model that is currently active.

    Yields:
      None
    _keras_styleTN)r   rY   r   #executing_eagerly_outside_functionsr   
init_scope)layerr   r   r   maybe_init_scope  s    
&r   c                  o   s`   t dd t| t|  D rVt   dV  W d   q\1 sJ0    Y  ndV  dS )zLReturns graph context manager if any of the inputs is a symbolic
    tensor.c                 s   s   | ]}t |V  qd S rX   )r   )r:   r   r   r   r   r_      r?   z5graph_context_for_symbolic_tensors.<locals>.<genexpr>N)r   ra   rN   r   	get_graph
as_default)argskwargsr   r   r   "graph_context_for_symbolic_tensors  s    "&r   c                 C   sR   t jj r(t t jj| t jjjS t	
 t jj| }|t jjjkS dS )z'True if the passed dataset is infinite.N)r   rY   r   r   equaldataexperimentalcardinalityINFINITE_CARDINALITYr   get_sessionrun)datasetdataset_sizer   r   r   dataset_is_infinite'  s    r   c                 C   s   t | tjr| }nxt| r"| j}nht| drHt| jd drH| jd jS t | tjr\| j	}n.t| drt| drtj
| j| j|d}ndS |s|S |j}|jdu s|jdkr|S | }d|d< t|}t|t|S )z?Returns a `TensorSpec` given a single `Tensor` or `TensorSpec`.r   r   r   rP   r   )rP   r   nameN)r
   r   TypeSpecr   r   rQ   r   r   KerasTensor	type_specr   rP   r   rk   rf   copydeepcopytype_spec_with_shaper`   )r   dynamic_batchr   specrP   
shape_listr   r   r   get_tensor_spec5  s,    

r   c                 C   s0   t | tjjjjr|  } dd }tj|| S )a  Syncs and converts a structure of `Tensor`s to `NumPy` arrays or Python
    scalar types.

    For each tensor, it calls `tensor.numpy()`. If the result is a scalar value,
    it converts it to a Python type, such as a float or int, by calling
    `result.item()`.

    Numpy scalars are converted, as Python types are often more convenient to
    deal with. This is especially useful for bfloat16 Numpy scalars, which don't
    support as many operations as other Numpy values.

    Async strategies (such as `TPUStrategy` and `ParameterServerStrategy`) are
    forced to
    sync during this process.

    Args:
      tensors: A structure of tensors.

    Returns:
      `tensors`, but scalar tensors are converted to Python types and non-scalar
      tensors are converted to Numpy arrays.
    c                 S   sD   t | tjr|  } t | tjtjfs*| S t| dkr@|  S | S )Nr   )	r
   r   r   numpyr   ndarraygenericndimitem)r   r   r   r   _to_single_numpy_or_python_typeq  s
    zEsync_to_numpy_or_python_type.<locals>._to_single_numpy_or_python_type)	r
   r   
distributer   coordinatorRemoteValuefetchr   rT   )rV   r   r   r   r   sync_to_numpy_or_python_typeW  s    
r   c                 C   sR   t | }t|dd}|du r*t| dg }|D ]}|t| |j q2t|S )z2Converts the given attrs to tuple non-recursively.__attrs_attrs__Nz! is not an attrs-decorated class.)r   r   r   appendr   r$   )attrsr   fieldsrN   fieldr   r   r   rL   ~  s    rL   )N)T)F)FN)2r{   r!   r   r   r   r   tensorflow.compat.v2rY   v2r   kerasr   keras.enginer   keras.utilsr   r   tensorflow.python.frameworkr    tensorflow.python.util.tf_exportr   r   r   r9   rA   rW   rj   rq   rr   r   r   r   rn   r%   r   r   r   r   r   r   r   r   r   contextmanagerr   r   r   r   r   rL   r   r   r   r   <module>   sT   

"
>%
6(

2#

%



"'