
    0hu                        d 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	c 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eeefZ ej<                         Z ej<                         Z d	Z!d
Z" G d d      Z# G d d      Z$ ed      d        Z%d Z& G d d      Z'd Z(d Z)d Z* edd      d        Z+d Z,d#dZ-d#dZ.d Z/d Z0 edd       	 d$d!       Z1	 d#d"Z2y)%z6Object config serialization and deserialization logic.    N)object_registration)serialization)in_tf_saved_model_scope)generic_utils)	tf_export)keras_export)z%tensorflow.python.ops.custom_gradient)activationsconstraintsinitializerslossesmetrics
optimizersregularizersc                       e Zd Zd Zd Zy)Configc                     || _         y N)config)selfr   s     _/var/www/html/engine/venv/lib/python3.12/site-packages/tf_keras/src/saving/serialization_lib.py__init__zConfig.__init__7   s	        c                 ,    t        | j                        S r   )serialize_keras_objectr   r   s    r   	serializezConfig.serialize:   s    %dkk22r   N)__name__
__module____qualname__r   r    r   r   r   r   6   s    3r   r   c                   $    e Zd ZdZddZd Zd Zy)SafeModeScopezBScope to propagate safe mode flag to nested deserialization calls.c                     || _         y r   )	safe_mode)r   r$   s     r   r   zSafeModeScope.__init__A   s	    "r   c                 L    t               | _        | j                  t        _        y r   )in_safe_modeoriginal_valuer$   	SAFE_MODEr   s    r   	__enter__zSafeModeScope.__enter__D   s    *n"nn	r   c                 .    | j                   t        _        y r   )r'   r(   r$   r   argskwargss      r   __exit__zSafeModeScope.__exit__H   s    "11	r   N)T)r   r   r   __doc__r   r)   r.   r    r   r   r"   r"   >   s    L#-2r   r"   z0keras.__internal__.enable_unsafe_deserializationc                      dt         _        y)zADisables safe mode globally, allowing deserialization of lambdas.FN)r(   r$   r    r   r   enable_unsafe_deserializationr1   L   s      Ir   c                  $    t        t        dd       S )Nr$   )getattrr(   r    r   r   r&   r&   R   s    9k400r   c                       e Zd ZdZd Zd Zy)ObjectSharingScopez?Scope to enable detection and reuse of previously seen objects.c                 F    dt         _        i t         _        i t         _        y NTSHARED_OBJECTSenabledid_to_obj_mapid_to_config_mapr   s    r   r)   zObjectSharingScope.__enter__Y   s    !%')$*,'r   c                 F    dt         _        i t         _        i t         _        y )NFr8   r+   s      r   r.   zObjectSharingScope.__exit__^   s    !&')$*,'r   N)r   r   r   r/   r)   r.   r    r   r   r5   r5   V   s    I-
-r   r5   c                 f    t        t        dd      r t        j                  j                  | d      S y)z:Retrieve an object previously seen during deserialization.r:   FN)r3   r9   r;   get)obj_ids    r   get_shared_objectrA   d   s,    ~y%0++//== 1r   c                     |d   dk(  rd|d<   t        t        dd      syt        t        |             }|t        j                  vr|t        j                  |<   y||d<   t        j                  |   }||d<   y)z>Call after serializing an object, to keep track of its config.module__main__Nr:   Fshared_object_id)r3   r9   intidr<   )objr   r@   prev_configs       r   !record_object_after_serializationrJ   j   sy    h:%x>9e4C\F^44428''/%+!"$55f=*0&'r   c                 N    t        t        dd      sy| t        j                  |<   y)zFCall after deserializing an object, to keep track of it in the future.r:   FN)r3   r9   r;   )rH   r@   s     r   #record_object_after_deserializationrL   y   s!    >9e4+.N  (r   z#keras.saving.serialize_keras_objectz"keras.utils.serialize_keras_objectc                 	  
 t         j                  j                  j                         r
t	               rt        j                  |       S | | S t        | t              r| S t        | t        t        f      r5| D cg c]  }t        |       }}t        | t              rt        |      S |S t        | t              rt        |       S t        | t              rdd| j                  d      idS t        | t         j                        r| j                   | j#                         S dS t        | t         j$                        r8d| j'                         j)                         | j*                  j,                  ddS t/        |       j0                  t2        j4                  k(  rct        | t2        j6                        r9| j8                  dkD  r*d	| j)                         | j*                  j,                  ddS | j;                         S t        | t         j<                        r| j,                  S t        | t         j>                  j@                  jB                        r| jD                  S t        | tF        jH                        rV| j4                  d
k(  rGtK        jL                  dtO        jP                  |        d       ddtS        jT                  |       idS t        | t         jV                        r| jY                         }t        t[        d |            }| j\                  j4                  }d}t_        | d      rSt         j`                  jb                  je                  |       }t        |      }tg        jh                  | j\                        }d|| j\                  j0                  ||dS tk        |       }tm        | j\                  |      
t        |tn              r|dk(  r| S 
4tq        
fdtr        D              r| S tu        | 
       tw        | 
       
S t        | tF        jH                        r| j0                  }n| j\                  j0                  }| j\                  j4                  }|dk(  rd}nOt        | tF        jH                        rtg        jh                  |       }ntg        jh                  | j\                        }||||d}	tu        | |	       tw        | |	       |	S c c}w )a  Retrieve the config dict by serializing the TF-Keras object.

    `serialize_keras_object()` serializes a TF-Keras object to a python
    dictionary that represents the object, and is a reciprocal function of
    `deserialize_keras_object()`. See `deserialize_keras_object()` for more
    information about the config format.

    Args:
      obj: the TF-Keras object to serialize.

    Returns:
      A python dict that represents the object. The python dict can be
      deserialized via `deserialize_keras_object()`.
    N	__bytes__valueutf-8)
class_namer   
__tensor__)rO   dtyper   	__numpy__z<lambda>a  The object being serialized includes a `lambda`. This is unsafe. In order to reload the object, you will have to pass `safe_mode=False` to the loading function. Please avoid using `lambda` in the future, and use named Python functions instead. This is the `lambda` being serialized:    )
stacklevel
__lambda__c                     t        | t        j                        r| j                         S t        | t        j                        r| j
                  S | S r   )
isinstancetfTensorShapeas_listDTypenamexs    r   <lambda>z(serialize_keras_object.<locals>.<lambda>   s>    a0 ))+  *1bhh 7aff => r   _tf_extension_type_fields__typespec__)rQ   	spec_namerC   r   registered_nameop_dispatch_handlerc              3   ,   K   | ]  }|d    v   yw)rC   Nr    ).0modconfig_with_public_classs     r   	<genexpr>z)serialize_keras_object.<locals>.<genexpr>   s$      
 +H55
s   builtinsrC   rQ   r   re   )<rZ   __internal__tf2r:   r   legacy_serializationr   rY   PLAIN_TYPESlisttupledictserialize_dictbytesdecoder[   _dimsr\   TensornumpytolistrS   r^   typer   npr   ndarrayndimitemr]   compatv1	DimensionrO   typesFunctionTypewarningswarninspect	getsourcer   	func_dumpTypeSpec
_serializemap	__class__hasattrexperimentalextension_typeas_dictr   get_registered_name_get_class_or_fn_configserialize_with_public_classstranyNON_SERIALIZABLE_CLASS_MODULESget_build_and_compile_configrJ   )rH   r`   
config_arr	ts_configrd   re   inner_configrC   rQ   r   rj   s             @r   r   r      s    * ??&&(,C,E#::3??
{
#{#
#e}%9<=A,Q/=
=$.sE$:uZ J
J#tc"" #u%

7 34
 	
 #r~~& #		 5s{{}?4?#ryy!&++-
 	
 Cyr{{*c2::&388a<) ZZ\ YY^^  88:#rxx xx#ryy||--.yy#u))*s||z/I6
 7>6G6G6L5MO 	
 '005
 	
 #r{{#NN$	@ 	
	 MM**	33466>>sCI&y1I1EEO )"mm...
 	
 +3/L:|  ,$9N)N
+ 
5
 
 J$S*BC)#/GH'' #u))*))''Jc5--.1EEcJO1EEO
  *	F !f-%c62MC >s   9Sc                     t        | d      r | j                         }|t        |      |d<   t        | d      r | j                         }|t        |      |d<   y )Nget_build_configbuild_configget_compile_configcompile_config)r   r   ru   r   )rH   r   r   r   s       r   r   r   #  sb    s&'++-#%3L%AF>"s()//1%'5n'EF#$
r   c                     t        j                  | d      }|3t        j                  |       }|y| j                  | j
                  ||dS |j                  d      }dj                  |dd       |d   |ddS )a  Serializes classes from public TF-Keras API or object registration.

    Called to check and retrieve the config of any class that has a public
    TF-Keras API or has been registered as serializable via
    `keras.saving.register_keras_serializable()`.
    kerasapi_nameNrm   .)r   get_canonical_name_for_symbolr   r   r   r   splitjoin)clsr   keras_api_namere   partss        r   r   r   /  s     <<gN
 -AA#F" nn,,".	
 	
   %E((5":&Bi	 r   c                 
   |r|d||dS t        j                  | d      }|r*|j                  d      }dj                  |dd       d||dS t	        j
                  |       }|s| j                  dk(  sy| j                  d||dS )	aU  Serializes functions from public TF-Keras API or object registration.

    Called to check and retrieve the config of any function that has a public
    TF-Keras API or has been registered as serializable via
    `keras.saving.register_keras_serializable()`. If function's module name is
    already known, returns corresponding config.
    functionrm   r   r   r   Nr   rl   )r   r   r   r   r   r   r   )fnr   fn_module_namer   r   re   s         r   serialize_with_public_fnr   S  s     $$%	
 	
 <<
WN $$S)hhuSbz*$%	
 	
 .AA"Er}}
'Bmm$.	
 	
r   c                 h   t        | t        j                        rt        j                  |       S t        | d      r<| j                         }t        |t              st        d|  d|       t        |      S t        | d      rt        j                  |       S t        d|  dt        |        d      )z1Return the object's config depending on its type.
get_configzThe `get_config()` method of z$ should return a dict. It returned: r   zCannot serialize object z	 of type zG. To be serializable, a class must implement the `get_config()` method.)rY   r   r   r   r   r   r   rt   	TypeErrorru   r|   )rH   r   s     r   r   r   y  s     #u))*"66s;;sL!!&$'/u 5((.x1  f%%	j	!"66s;;&se9T#YK @@ @
 	
r   c                 h    | j                         D ci c]  \  }}|t        |       c}}S c c}}w r   )itemsr   )rH   keyrO   s      r   ru   ru     s+    ADM:3C'..MMMs   .z%keras.saving.deserialize_keras_objectz$keras.utils.deserialize_keras_objectc           
      
   t               }||n|}|j                  dd      }|xs i }t        j                  j                  }t        j
                  }i |||}|j                  dd      }|r%t        dt        |j                                      t        j                  j                  j                         r
t               rt        j                  | |||      S | yt!        | t"              r|r|j%                  |       ||    S t!        | t        t&        f      r| D 	cg c]  }	t        |	||       c}	S |d\  }
}}t!        | t(              rd| v r| d   }
d	| vrt        d
|        |r1| d	   |v s'| j%                  d      |v st!        |
t"              r|
|v rd}nM| d	   dk(  r| d   }|dk(  r| d   } n5| d   } n/| j%                  dd      t+        d| d	    d| d	    d      | d	   } |sY| |vr| S t!        ||    t,        j.                        rt        t1        ||    | |      |      S t        t3        ||    |
      |      S t!        | t4              r| S t!        | t(              st+        d|        d	| vsd| vr0| j7                         D ci c]  \  }}|t        |||       c}}S | d	   }| d   xs i }
|xs i }|dk(  rt        j8                  |
d   |
d         S |dk(  rt;        j<                  |
d   |
d         S | d	   dk(  r|
d   j?                  d      S | d	   dk(  r%|rt        d      tA        jB                  |
d         S | d	   d k(  rtE        | d!   | d   | d   d"| |#      }tG        |d$      r7|
j7                         D ci c]  \  }}|t        |||       }
}} |d,i |
S | d   |jI                  |
      S tK        d% |
      }
|jM                  t'        |
            S | j%                  dd      }| j%                  d|      }|dk(  r|
}tE        |||d| |#      S d&| v rtO        | d&         }||S tE        |||d"| |#      }t!        |t,        j.                        r|S tG        |d'      st+        d(| d)|        t        jP                  |      }tS        |      }|5  |5  |jI                  |
      }| j%                  d*d      }|r|jU                  |       | j%                  d+d      }|r|jW                  |       ddd       ddd       d&| v rtY        | d&          S c c}	w c c}}w c c}}w # 1 sw Y   7xY w# 1 sw Y   ;xY w)-a  Retrieve the object by deserializing the config dict.

    The config dict is a Python dictionary that consists of a set of key-value
    pairs, and represents a TF-Keras object, such as an `Optimizer`, `Layer`,
    `Metrics`, etc. The saving and loading library uses the following keys to
    record information of a TF-Keras object:

    - `class_name`: String. This is the name of the class,
      as exactly defined in the source
      code, such as "LossesContainer".
    - `config`: Dict. Library-defined or user-defined key-value pairs that store
      the configuration of the object, as obtained by `object.get_config()`.
    - `module`: String. The path of the python module, such as
      "keras.engine.compile_utils". Built-in TF-Keras classes
      expect to have prefix `keras`.
    - `registered_name`: String. The key the class is registered under via
      `keras.saving.register_keras_serializable(package, name)` API. The key has
      the format of '{package}>{name}', where `package` and `name` are the
      arguments passed to `register_keras_serializable()`. If `name` is not
      provided, it uses the class name. If `registered_name` successfully
      resolves to a class (that was registered), the `class_name` and `config`
      values in the dict will not be used. `registered_name` is only used for
      non-built-in classes.

    For example, the following dictionary represents the built-in Adam optimizer
    with the relevant config:

    ```python
    dict_structure = {
        "class_name": "Adam",
        "config": {
            "amsgrad": false,
            "beta_1": 0.8999999761581421,
            "beta_2": 0.9990000128746033,
            "decay": 0.0,
            "epsilon": 1e-07,
            "learning_rate": 0.0010000000474974513,
            "name": "Adam"
        },
        "module": "keras.optimizers",
        "registered_name": None
    }
    # Returns an `Adam` instance identical to the original one.
    deserialize_keras_object(dict_structure)
    ```

    If the class does not have an exported TF-Keras namespace, the library
    tracks it by its `module` and `class_name`. For example:

    ```python
    dict_structure = {
      "class_name": "LossesContainer",
      "config": {
          "losses": [...],
          "total_loss_mean": {...},
      },
      "module": "keras.engine.compile_utils",
      "registered_name": "LossesContainer"
    }

    # Returns a `LossesContainer` instance identical to the original one.
    deserialize_keras_object(dict_structure)
    ```

    And the following dictionary represents a user-customized `MeanSquaredError`
    loss:

    ```python
    @keras.saving.register_keras_serializable(package='my_package')
    class ModifiedMeanSquaredError(keras.losses.MeanSquaredError):
      ...

    dict_structure = {
        "class_name": "ModifiedMeanSquaredError",
        "config": {
            "fn": "mean_squared_error",
            "name": "mean_squared_error",
            "reduction": "auto"
        },
        "registered_name": "my_package>ModifiedMeanSquaredError"
    }
    # Returns the `ModifiedMeanSquaredError` object
    deserialize_keras_object(dict_structure)
    ```

    Args:
        config: Python dict describing the object.
        custom_objects: Python dict containing a mapping between custom
            object names the corresponding classes or functions.
        safe_mode: Boolean, whether to disallow unsafe `lambda` deserialization.
            When `safe_mode=False`, loading an object has the potential to
            trigger arbitrary code execution. This argument is only
            applicable to the TF-Keras v3 model format. Defaults to `True`.

    Returns:
      The object described by the `config` dictionary.

    Nmodule_objectsprintable_module_nameobjectz-The following argument(s) are not supported: )custom_objectsr$   )NNFr   rQ   z%Unknown `config` as a `dict`, config=re   Tr   rC   rl   _z#Cannot deserialize object of type `z`. If `zj` is a custom class, please register it using the `@keras.saving.register_keras_serializable()` decorator.r   )r   zCould not parse config: rR   rO   rS   )rS   rT   rN   rP   rW   a  Requested the deserialization of a `lambda` object. This carries a potential risk of arbitrary code execution and thus it is disallowed by default. If you trust the source of the saved model, you can pass `safe_mode=False` to the loading function in order to allow `lambda` loading.rc   rd   class)obj_typefull_configr   rb   c                     t        | t              rt        j                  |       S t	        t        j
                  t        |             rt        t        |       S | S r   )rY   rr   rZ   r[   r   dtypesr   r3   r_   s    r   ra   z*deserialize_keras_object.<locals>.<lambda>  sC    !T" nnQ' $+BIIs1v$>'"a. DE r   rE   from_configz&Unable to reconstruct an instance of 'zM' because the class is missing a `from_config()` method. Full object config: r   r   r    )-r&   popr   _THREAD_LOCAL_CUSTOM_OBJECTS__dict___GLOBAL_CUSTOM_OBJECTS
ValueErrorrr   keysrZ   rn   ro   r:   r   rp   deserialize_keras_objectrY   r   r?   rs   rt   r   r   r   r   r   rq   r   constantr}   arrayencoder   	func_load_retrieve_class_or_fnr   r   r   _deserializerA   custom_object_scoper"   build_from_configcompile_from_configrL   )r   r   r$   r-   safe_scope_argr   tlcogcor   r`   r   r   has_custom_objectr   rO   rQ   r   rC   re   fn_namerH   custom_obj_scopesafe_mode_scopeinstancer   r   s                             r   r   r     s   R "^N"0"<)IZZ 0$7N#)rN;;DDD

4
4C66$6#6N #JJ'>I;FKKM"#%
 	
 ??&&(,C,E#<<NN4I
 	
 ~ 	63v&2 f%%&4-(
 	
  %.I
 	
 !:K7n&7fd#6!%h/6) ;F8D 
 |$6::/0NB|S1$6 %)! %3!'!1!Z/#H-F#$56F ::h,4#"<01 2"<01 2%%   - ^+.0%2D2DE/,&v. $2	  ,+"6*  .	  &+&fd#26(;<<6!XV%;
 %lln	
 U )n	 
 	
 %J(#)rL#)rN \!{{<0W8MNN[ xxW-\'5JKKl{*G$++G44l|+K  &&|G'<==l~-#;$%8)
 334
 #/"4"4"6	 C -.I L  &&&#$0??<00 G 	
 l 344 ZZ$'Fjj!2J?OZ$)
 	
 V#'9 :;?J
%C #u))*
3&4ZL A##)(,
 	
 +>>~N#I.O	 9? 9??<0zz.$7&&|4$4d;((89 9 V#+f/0	
 O
R
R@9 9 9 9s7   #T7T<U3U6AUUU	UUc                    |dk(  rt        j                  | |      }nt        j                  ||      }||S |rM|dk(  s'|dk(  s"|j                  d      s|j                  d      r*|dz   | z   }d|v rd	|z   }t        j                  |      }||S |dk(  r4|d
k(  r/t
        D ]&  }	t        j                  d|	z   dz   | z         }|$|c S  	 |j                  d      rd|z   }t        j                  |      }	t        |	      j                  | d       }|q|t        |	      j                  |d       }| j                  d      dk(  r@| j                  d      \  }
}t        |	      j                  |
d       }|t        ||d       nd }||S t        d| d|  d|       # t        $ r t        d| d|  d| d|       w xY w)Nr   r   tf_kerasr   zkeras.z	tf_keras.r   z__internal__.legacyz
compat.v1.rl   tf_zCould not deserialize z 'z' because its parent module z) cannot be imported. Full object config:    zCould not locate zr'. Make sure custom classes are decorated with `@keras.saving.register_keras_serializable()`. Full object config: )r   get_registered_object
startswithr   get_symbol_from_nameBUILTIN_MODULES	importlibimport_moduleModuleNotFoundErrorr   varsr?   countr   r3   )r^   re   rC   r   r   r   
custom_objr   rH   ri   
outer_name
inner_name	outer_objs                r   r   r     s2   
 :(>>

 )>>N

  j    *  -|d*H %0'(200:C
 z!f
&:& 44sNS(4/ ?J
	  )))&1C 3immD$';*3immOT: zz#!#)-C&
J IMM*d;	 !, Iz48  ?J

H:Rv .  +m	- 5 # 	(
"TF ;%%+H -''2m5 	s   +F !F>r   r7   )3r/   r   r   	threadingr   r   rz   r}   tensorflow.compat.v2r   v2rZ   tf_keras.src.savingr   tf_keras.src.saving.legacyr   rp   ,tf_keras.src.saving.legacy.saved_model.utilsr   tf_keras.src.utilsr   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   r   rF   floatboolrq   localr9   r(   r   r   r   r"   r1   r&   r5   rA   rJ   rL   r   r   r   r   r   ru   r   r   r    r   r   <module>r      s/   =       ! ! 3 L P , - 9C% "IOO	 "L 3 32 2 @A  B 
1- ->1/ )+O]]@	!H#
L
0N +*
 ,0J	J\
 JNXr   