
    2Vhr                     t   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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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g      d        Z#d Z$d#dZ%d#dZ&d Z'd Z( edd g      	 d$d!       Z)	 d#d"Z*y)%z6Object config serialization and deserialization logic.    N)
api_export)backend)keras_export)global_state)object_registration)python_utils)
tensorflow)activationsconstraintsinitializerslossesmetrics
optimizersregularizersc                       e Zd Zd Zd Zy)SerializableDictc                     || _         y N)config)selfr   s     R/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/saving/serialization_lib.py__init__zSerializableDict.__init__!   s	        c                 ,    t        | j                        S r   )serialize_keras_objectr   r   s    r   	serializezSerializableDict.serialize$   s    %dkk22r   N)__name__
__module____qualname__r   r    r   r   r   r       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__+   s	    "r   c                 b    t               | _        t        j                  d| j                         y Nsafe_mode_saving)in_safe_modeoriginal_valuer   set_global_attributer%   r   s    r   	__enter__zSafeModeScope.__enter__.   s!    *n))*<dnnMr   c                 D    t        j                  d| j                         y r'   )r   r+   r*   r   argskwargss      r   __exit__zSafeModeScope.__exit__2   s    )) 3 3	
r   N)T)r   r   r    __doc__r   r,   r1   r!   r   r   r#   r#   (   s    L#N
r   r#   z*keras.config.enable_unsafe_deserializationc                  0    t        j                  dd       y)zADisables safe mode globally, allowing deserialization of lambdas.r(   FNr   r+   r!   r   r   enable_unsafe_deserializationr5   8   s     %%&8%@r   c                  ,    t        j                  d      S r'   r   get_global_attributer!   r   r   r)   r)   >   s    ,,-?@@r   c                       e Zd ZdZd Zd Zy)ObjectSharingScopez?Scope to enable detection and reuse of previously seen objects.c                 \    t        j                  di        t        j                  di        y Nshared_objects/id_to_obj_mapshared_objects/id_to_config_mapr4   r   s    r   r,   zObjectSharingScope.__enter__E   s$    ))*H"M))*KRPr   c                 \    t        j                  dd        t        j                  dd        y r<   r4   r.   s      r   r1   zObjectSharingScope.__exit__I   s&    ))*H$O))-t	
r   N)r   r   r    r2   r,   r1   r!   r   r   r:   r:   B   s    IQ
r   r:   c                 V    t        j                  d      }||j                  | d      S y)z:Retrieve an object previously seen during deserialization.r=   N)r   r8   get)obj_idid_to_obj_maps     r   get_shared_objectrD   P   s5     55&M    .. !r   c                     |d   dk(  rd|d<   t        j                  d      }|yt        t        |             }||vr|||<   y||d<   ||   }||d<   y)z>Call after serializing an object, to keep track of its config.module__main__Nr>   shared_object_id)r   r8   intid)objr   id_to_config_maprB   prev_configs        r   !record_object_after_serializationrN   Y   sy    h:%x#88) C\F%%#) %+!"&v.*0&'r   c                 >    t        j                  d      }|y| ||<   y)zFCall after deserializing an object, to keep track of it in the future.r=   Nr7   )rK   rB   rC   s      r   #record_object_after_deserializationrP   k   s*     55&M M&r   z#keras.saving.serialize_keras_objectz"keras.utils.serialize_keras_objectc                 	   | | 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              rBdt	        | j                        t	        | j                        t	        | j                        ddS t        | t        t                    rdi dS t        | t        j                         rIt#        | d	d      }|rt        |      }|d
   j$                  |d
<   d| j&                  | j(                  |ddS t*        j,                  r8t        | t*        j.                        r| j0                  | j3                         S dS t        j4                  |       rFdt        j6                  |       j9                         t        j:                  | j(                        ddS t        |       j<                  t>        j@                  k(  rlt        | t>        jB                        rB| jD                  d
kD  r3d| j9                         t        j:                  | j(                        ddS | jG                         S t*        j,                  r&t        | t*        jH                        r| j$                  S t        | tJ        jL                        rV| j@                  dk(  rGtO        jP                  dtS        jT                  |        d       ddtW        jX                  |       idS t*        j,                  rpt        | t*        jZ                        rV| j]                         }t        t_        d |            }d| j`                  j@                  | j`                  j<                  |ddS tc        |       }te        | j`                  |      }|tg        | |       ti        | |       |S t        | tJ        jL                        r| j<                  }n| j`                  j<                  }| j`                  j@                  }|dk(  rd}	nOt        | tJ        jL                        rtk        jl                  |       }	ntk        jl                  | j`                        }	||||	d}
tg        | |
       ti        | |
       |
S c c}w )a	  Retrieve the config dict by serializing the Keras object.

    `serialize_keras_object()` serializes a 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 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   	__slice__)startstopstep__ellipsis___keras_historyr   __keras_tensor__)shapedtypekeras_history
__tensor__)rS   r^   	__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>   sG    !!R^^4 IIK  %/q"(($;!&&  BC r   __typespec__)rU   	spec_namerF   r   registered_namebuiltinsrF   rU   r   rq   )7rf   PLAIN_TYPESlisttupler   dictserialize_dictbytesdecodeslicerW   rX   rY   typeEllipsisr   KerasTensorgetattrrk   r]   r^   rg   	availablerh   _dimsri   	is_tensorconvert_to_numpytoliststandardize_dtyper   npr   ndarrayndimitemrj   typesFunctionTypewarningswarninspect	getsourcer   	func_dumpTypeSpec
_serializemap	__class___get_class_or_fn_configserialize_with_public_classget_build_and_compile_configrN   r   get_registered_name)rK   rm   
config_arrhistory	ts_configinner_configconfig_with_public_classrF   rU   rq   r   s              r   r   r   u   s+   * {
#{#
#e}%9<=A,Q/=
=$.sE$:uZ J
J#tc"" #u%

7 34
 	
 #u%/		:.sxx8.sxx8
 	
 #tH~&,;;#w**+#/67mG GAJ,!(
 	
 
||
37 #		 5s{{}?4?& 11#6==? 22399=
 	
 Cyr{{*c2::&388a<) ZZ\$66syyA  88:	||
31xx#u))*s||z/I6
 7>6G6G6L5MO 	
 '//4
 	
 
||
34NN$	
 	
	 )//mm..#
 	
 +3/L:|   +$S*BC)#/GH'' #u))*))''Jc5--.1EEcJO1EEO
  *	F !f-%c62MM >s   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)hasattrr   rx   r   )rK   r   r   r   s       r   r   r     sb    s&'++-#%3L%AF>"s()//1%'5n'EF#$
r   c                     t        j                  |       }|3t        j                  |       }|y| j                  | j
                  ||dS |j                  d      }dj                  |dd       |d   |ddS )zSerializes classes from public Keras API or object registration.

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

    Called to check and retrieve the config of any function that has a public
    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.
    functionrs   r   Nr   rr   )r   r   r   r   r   r   r   )fnr   fn_module_namer   r   rq   s         r   serialize_with_public_fnr   I  s     $$%	
 	
  44R8N$$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.)rf   r   r   r   r   r   r   rw   	TypeErrorrx   r|   )rK   r   s     r   r   r   m  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   )rK   keyrS   s      r   rx   rx     s+    ADM:3C'..MMMs   .z%keras.saving.deserialize_keras_objectz$keras.utils.deserialize_keras_objectc           
      z
   t               }||n|}|j                  dd      }|xs i }t        j                  di       }t        j
                  }i |||}| 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        t#        ||    | |
      |      S t        t%        ||    |	      |      S t        | t&              r| S t        | t              st        d|        d| vsd| vr0| j)                         D ci c]  \  }}|t        |||       c}}S | d   }| d   xs i }	|xs i }|dk(  r)t+        j,                  |	d   |	d         }|	d   |_        |S |dk(  rt+        j0                  |	d   |	d         S |dk(  rt3        j4                  |	d   |	d         S | d   dk(  r|	d   j7                  d      S | d   dk(  rt8        S | d   d k(  r:t;        t        |	d!   ||      t        |	d"   ||      t        |	d#   ||            S | d   d$k(  r%|rt        d%      t=        j>                  |	d         S t@        I| d   d&k(  rAtC        | d'   | d	   | d   d(| |)      }tE        d* |	      }	|jG                  t        |	            S | j                  dd      }| j                  d	|      }|dk(  r|	}tC        |||d| |)      S d+| v rtI        | d+         }||S tC        |||d(| |)      }t        |t        j                         r|S tK        |d,      st        d-| d.|        t	        jL                  |      }tO        |      }|5  |5  	 |jQ                  |	      }| j                  d1d      }|r$|jR                  s|jU                  |       d
|_)        | j                  d2d      }|r|jW                  |       d
|_,        ddd       ddd       d+| v rt[        | d+          S c c}w c c}}w # t        $ r}t        | d/|  d0|       d}~ww xY w# 1 sw Y   UxY w# 1 sw Y   YxY w)3a:  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 Keras object, such as an `Optimizer`, `Layer`,
    `Metrics`, etc. The saving and loading library uses the following keys to
    record information of a 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. Built-in 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 Keras namespace, the library tracks
    it by its `module` and `class_name`. For example:

    ```python
    dict_structure = {
      "class_name": "MetricsList",
      "config": {
          ...
      },
      "module": "keras.trainers.compile_utils",
      "registered_name": "MetricsList"
    }

    # Returns a `MetricsList` 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 Keras v3 model format. Defaults to `True`.

    Returns:
        The object described by the `config` dictionary.
    Nmodule_objectscustom_objects_scope_dict)custom_objectsr%   )NNFr   rU   z%Unknown `config` as a `dict`, config=rq   Tr   rF   rr   _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: r\   r]   r^   )r^   r_   r`   rS   ra   rR   rT   rZ   rV   rW   rX   rY   rd   aR  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, or call `keras.config.enable_unsafe_deserialization()`.ro   rp   class)obj_typefull_configr   c                     t        | t              rt        j                  |       S t	        t        j
                  t        |             rt        t        |       S | S r   )rf   ru   rg   rh   r   dtypesstrr   rl   s    r   rn   z*deserialize_keras_object.<locals>.<lambda>  sL    a& q!  )0		3q6(Bgb!n  IJ r   rH   from_configz&Unable to reconstruct an instance of 'zM' because the class is missing a `from_config()` method. Full object config: z could not be deserialized properly. Please ensure that components that are Python object instances (layers, models, etc.) returned by `get_config()` are explicitly deserialized in the model's `from_config()` method.

config=z.

Exception encountered: r   r   ).r)   popr   r8   r   GLOBAL_CUSTOM_OBJECTSrf   r   rA   ru   rv   deserialize_keras_objectrw   
ValueErrorr   r   r   r   r   rt   r   r   r~    _pre_serialization_keras_historyconvert_to_tensorr   arrayencoder}   r{   r   	func_loadrg   _retrieve_class_or_fnr   _deserializerD   r   CustomObjectScoper#   r   builtbuild_from_configcompile_from_configcompiledrP   )r   r   r%   r0   safe_scope_argr   tlcogcorm   r   r   has_custom_objectr   rS   rU   rK   rF   rq   fn_namer   custom_obj_scopesafe_mode_scopeinstanceer   r   s                             r   r   r     s   P "^N"0"<)IZZ 0$7N#)rN,,-H"MD

3
3C66$6#6N~ 	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 ''!!!g)>
 0<O/L,
\!((!g)>
 	
 [ xxW-\'5JKKl{*G$++G44l~-l{*$W%-#
 %V$-#
 %V$-#
 	
" l|+J  %%l7&;<<	~&..@#;$%8)
 
 
 l 344 ZZ$'Fjj!2J?OZ$)
 	
 V#'9 :;?J
%C #u))*
3&4ZL A##)(,
 	
 +<<^L#I.O	 %? %
	|4H zz.$7&&|4!HN$4d;((8 $H'% %* V#+f/0	
 O}
V
z  	% 
 %X%A!F 	% % % %sU   S6S;T1T%T-A$T%T1	T"
TT""T%%T.	*T11T:c                    |dk(  rt        j                  | |      }nt        j                  ||      }||S |r|dk(  s|j                  d      r!|dz   | z   }t        j                  |      }||S |dk(  rj|dk(  ret
        D ]&  }	t        j                  d|	z   dz   | z         }|$|c S  d| vr2d| z   }
|j                         D ]  \  }}|j                  |
      s|c S  |j                  dd	      d
   }|dv r6	 t        j                  |      }	t        |	      j                  | d       }||S 	 t        d| d|  d|       # t        $ r t        d| d|  d| d|       w xY w)Nr   r   keraszkeras.r   rr   >   )maxsplitr   >   r   keras_cv	keras_hub	keras_nlpz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_MODULESr   endswithr   	importlibimport_modulevarsrA   ModuleNotFoundErrorr   )rk   rq   rF   r   r   r   
custom_objapi_namerK   modseparated_namecustom_namecustom_objectpackages                 r   r   r     s   
 :(>>

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

 
 W 1 1( ;|d*H11(;C
 z!f
&:&  55sNS(4/ ?J $!$t2@2F2F2H -.K"++N;,,- ,,sQ,/2EE
--f53immD$/?J # 
H:Rv .  +m	-  ' ,XJb ?))/ 1++6-9 s   <3E !E&r   )NT)+r2   r   r   r   r   numpyr   	keras.srcr   r   keras.src.api_exportr   keras.src.backend.commonr   keras.src.savingr   keras.src.utilsr   keras.src.utils.module_utilsr	   rg   r   rI   floatboolrt   r   r   r#   r5   r)   r:   rD   rN   rP   r   r   r   r   r   rx   r   r   r!   r   r   <module>r      s   <         - 1 0 ( 9C%3 3
 
  :;A <A
A
 
/1$  -,\\~	 F!
H
0N /. ,0VVt
 JNGr   