o
    2hv                     @   sr  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 dd
lmZ eeeefZeh dZeh dZG dd dZG dd dZ eddd Z!dd Z"G dd dZ#dd Z$dd Z%dd Z&eddgd d! Z'd"d# Z(d3d$d%Z)d3d&d'Z*d(d) Z+d*d+ Z,ed,d-g	.d4d/d0Z-	d3d1d2Z.dS )5z6Object config serialization and deserialization logic.    N)
api_export)backend)keras_export)global_state)object_registration)KerasSaveable)python_utils)
tensorflow>   lossesmetrics
optimizersactivationsconstraintsinitializersregularizers>   keras.utils.get_filekeras.utils.load_imgkeras.models.load_modelkeras.saving.load_modelkeras.saving.load_weights"keras.preprocessing.image.load_img*keras.config.enable_unsafe_deserializationc                   @   s   e Zd Zdd Zdd ZdS )SerializableDictc                 K   
   || _ d S N)config)selfr    r   ]/var/www/html/chatgem/venv/lib/python3.10/site-packages/keras/src/saving/serialization_lib.py__init__0      
zSerializableDict.__init__c                 C   s
   t | jS r   )serialize_keras_objectr   r   r   r   r   	serialize3   r    zSerializableDict.serializeN)__name__
__module____qualname__r   r#   r   r   r   r   r   /   s    r   c                   @   s*   e Zd ZdZd
ddZdd Zdd Zd	S )SafeModeScopezBScope to propagate safe mode flag to nested deserialization calls.Tc                 C   r   r   )	safe_mode)r   r(   r   r   r   r   :   r    zSafeModeScope.__init__c                 C   s   t  | _td| j d S Nsafe_mode_saving)in_safe_modeoriginal_valuer   set_global_attributer(   r"   r   r   r   	__enter__=   s   zSafeModeScope.__enter__c                 O   s   t d| j d S r)   )r   r-   r,   r   argskwargsr   r   r   __exit__A   s   zSafeModeScope.__exit__N)T)r$   r%   r&   __doc__r   r.   r2   r   r   r   r   r'   7   s
    
r'   r   c                   C   s   t dd dS )zADisables safe mode globally, allowing deserialization of lambdas.r*   FNr   r-   r   r   r   r   enable_unsafe_deserializationG   s   r5   c                   C   s
   t dS r)   r   get_global_attributer   r   r   r   r+   M   r    r+   c                   @   s    e Zd ZdZdd Zdd ZdS )ObjectSharingScopez?Scope to enable detection and reuse of previously seen objects.c                 C   s   t di  t di  d S Nshared_objects/id_to_obj_mapshared_objects/id_to_config_mapr4   r"   r   r   r   r.   T   s   zObjectSharingScope.__enter__c                 O   s   t dd  t dd  d S r9   r4   r/   r   r   r   r2   X   s   zObjectSharingScope.__exit__N)r$   r%   r&   r3   r.   r2   r   r   r   r   r8   Q   s    r8   c                 C   s"   t d}|dur|| dS dS )z:Retrieve an object previously seen during deserialization.r:   N)r   r7   get)obj_idid_to_obj_mapr   r   r   get_shared_object_   s   r?   c                 C   sf   |d dkr
d|d< t d}|du rdS tt| }||vr%|||< dS ||d< || }||d< dS )z>Call after serializing an object, to keep track of its config.module__main__Nr;   shared_object_id)r   r7   intid)objr   id_to_config_mapr=   prev_configr   r   r   !record_object_after_serializationh   s   rH   c                 C   s"   t d}|du rdS | ||< dS )zFCall after deserializing an object, to keep track of it in the future.r:   Nr6   )rE   r=   r>   r   r   r   #record_object_after_deserializationz   s   rI   z#keras.saving.serialize_keras_objectz"keras.utils.serialize_keras_objectc           
      C   s  | du r| S t | tr| S t | ttfr&dd | D }t | tr$t|S |S t | tr/t| S t | tr>dd| didS t | trUdt	| j
t	| jt	| jd	dS t | ttrad
i dS t | tjrt| dd}|rzt|}|d j|d< d| j| j|ddS tjrt | tjr| jdur|  S dS t| rdt|  t| jddS t| jtj krt | tj!r| j"dkrd|  t| jddS | # S tjrt | tj$r| jS t | t%j&r| j dkrt'j(dt)*|  dd ddt+,| idS tjr(t | tj-r(| . }tt/dd |}d| j0j | j0j|ddS t1| }t2| j0|}|durCt3| | t4| | |S t | t%j&rN| j}n| j0j}| j0j }|dkr^d}nt | t%j&rkt56| }nt56| j0}||||d}	t3| |	 t4| |	 |	S )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()`.
    Nc                 S   s   g | ]}t |qS r   r!   .0xr   r   r   
<listcomp>   s    z*serialize_keras_object.<locals>.<listcomp>	__bytes__valueutf-8)
class_namer   	__slice__)startstopstep__ellipsis___keras_historyr   __keras_tensor__)shapedtypekeras_history
__tensor__)rP   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                 S   s*   t | tjr
|  S t | tjr| jS | S r   )
isinstancetfTensorShapeas_listDTypenamerM   r   r   r   <lambda>   s   

z(serialize_keras_object.<locals>.<lambda>__typespec__)rR   	spec_namer@   r   registered_namebuiltinsr@   rR   r   rl   )7rb   PLAIN_TYPESlisttupledictserialize_dictbytesdecodeslicer!   rT   rU   rV   typeEllipsisr   KerasTensorgetattrrg   rZ   r[   rc   	availablerd   _dimsre   	is_tensorconvert_to_numpytoliststandardize_dtyper%   npr$   ndarrayndimitemrf   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_configrH   r   get_registered_name)
rE   
config_arrhistory	ts_configinner_configconfig_with_public_classr@   rR   rl   r   r   r   r   r!      s   







	







r!   c                 C   sP   t | dr|  }|d urt||d< t | dr&|  }|d ur&t||d< d S )Nget_build_configbuild_configget_compile_configcompile_config)hasattrr   rs   r   )rE   r   r   r   r   r   r   r   )  s   

r   c                 C   sd   t | }|du rt| }|du rdS | j| j||dS |d}d|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()`.
    Nrn   .)r   get_name_from_symbolr   r   r%   r$   splitjoin)clsr   keras_api_namerl   partsr   r   r   r   5  s    
	

r   c                 C   sr   |r	|d||dS t | }|r#|d}d|dd d||dS t| }|s1| jdks1dS | 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.
    functionrn   r   Nr   rm   )r   r   r   r   r   r   r%   )fnr   fn_module_namer   r   rl   r   r   r   serialize_with_public_fnX  s,   


r   c                 C   s|   t | tjrt| S t| dr'|  }t |ts#td|  d| t	|S t| dr1t| 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.)rb   r   r   r   r   r   r   rr   	TypeErrorrs   rw   )rE   r   r   r   r   r   |  s    




r   c                 C   s   dd |   D S )Nc                 S   s   i | ]	\}}|t |qS r   rJ   rL   keyrP   r   r   r   
<dictcomp>  s    z"serialize_dict.<locals>.<dictcomp>)items)rE   r   r   r   rs     s   rs   z%keras.saving.deserialize_keras_objectz$keras.utils.deserialize_keras_objectTc                    sH  t  }|dur	|n|dd} pi  tdi }tj}i  || | du r,dS t| tr> r> | dur> |  S t| t	t
frO fdd| D S |durd\}}	}
t| trd| v re| d }d| vrptd	|   r| d  v s| d
 v st|tr| v rd}
n3| d dkr| d }	|	dkr| d } n | d
 } n| dddu rtd| d  d| d  d| d } |
s| |vr| S t||  tjrtt||  | |	 dS tt||  |d dS t| tr| S t| tstd|  d| vsd| vr fdd|  D S | d }| d pi } pi  |dkr6tj|d |d d}|d |_|S |dkrFtj|d |d dS |dkrVtj|d |d dS | d d krd|d d!S | d d"krmtS | d d#krtt|d$  d%t|d&  d%t|d'  d%S | d d(krrtd)t|d S t dur| d d*krt!| d+ | d
 | d d,|  d-}t"d.d/ |}|#t
|S | dd}| d
|}|dkr|}t!|||d|  d-S d0| v rt$| d0 }|dur|S t!|||d,|  d-}t|tjr|S t%|d1s td2| d3|  t& }t'}|b |O z|(|}W n tyO } zt| d4|  d5| d}~ww | d6d}|re|j)se|*| d|_)| d7d}|rv|+| d|_,W d   n	1 sw   Y  W d   n	1 sw   Y  d0| v rt-|| d0  |S )8a:  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_dictc                    s   g | ]	}t | d qS custom_objectsr(   deserialize_keras_objectrK   r   r   r   rN     s    z,deserialize_keras_object.<locals>.<listcomp>)NNFr   rR   z%Unknown `config` as a `dict`, config=rl   Tr   r@   rm   _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: c                    s    i | ]\}}|t | d qS r   r   r   r   r   r   r   a  s    z,deserialize_keras_object.<locals>.<dictcomp>rY   rZ   r[   )r[   r\   r]   rP   r^   rO   rQ   rW   rS   rT   r   rU   rV   ra   aF  Requested the deserialization of a Python lambda. This carries a potential risk of arbitrary code execution and thus it is disallowed by default. If you trust the source of the artifact, you can override this error by passing `safe_mode=False` to the loading function, or calling `keras.config.enable_unsafe_deserialization().rj   rk   class)obj_typefull_configr   c                 S   s2   t | tr
t| S ttjt| rtt| S | S r   )rb   rp   rc   rd   r   dtypesstrrz   rh   r   r   r   ri     s   z*deserialize_keras_object.<locals>.<lambda>rB   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   r7   r   GLOBAL_CUSTOM_OBJECTSrb   r   r<   rp   rq   rr   
ValueErrorr   r   r   r   r   r   ro   r   r   ry    _pre_serialization_keras_historyconvert_to_tensorr   arrayencoderx   rv   r   	func_loadrc   _retrieve_class_or_fnr   _deserializer?   r   CustomObjectScoper'   r   builtbuild_from_configcompile_from_configcompiledrI   )r   r   r(   r1   safe_scope_argr   tlcogcor   r   has_custom_objectrR   rE   r@   rl   fn_namer   custom_obj_scopesafe_mode_scopeinstanceer   r   r   r   r   r     s  h











	


	
	

 
r   c                 C   s  |dkrt j| |d}nt j||d}|d ur|S |r|dks$|drA|d |  }|tv r6td| dt|}|d urA|S |dkr{|dkr{tD ]}	td|	 d |  }|d ur`|  S qKd	| vr{d	|  }
| D ]\}}|	|
rz|  S qm|j
dd
dd }|dv rz%t|}	t|	| d }t|trt|tr|W S td| d|  d ty   td| d|  d| d| w td| d|  d| )Nr   r   keraszkeras.r   zCannot deserialize `z;`, loading functions are not allowed during deserializationrm   >   )maxsplitr   >   r   keras_cv	keras_hub	keras_nlpzCould not deserialize 'z,' because it is not a KerasSaveable subclassz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
startswithLOADING_APISr   r   get_symbol_from_nameBUILTIN_MODULESr   endswithr   	importlibimport_modulevarsr<   rb   rw   
issubclassr   ModuleNotFoundErrorr   )rg   rl   r@   r   r   r   
custom_objapi_namerE   modseparated_namecustom_namecustom_objectpackager   r   r   r     sr   



r   r   )NT)/r3   r   r   r   r   numpyr   	keras.srcr   r   keras.src.api_exportr   keras.src.backend.commonr   keras.src.savingr   keras.src.saving.keras_saveabler   keras.src.utilsr   keras.src.utils.module_utilsr	   rc   r   rC   floatboolro   	frozensetr   r   r   r'   r5   r+   r8   r?   rH   rI   r!   r   r   r   r   rs   r   r   r   r   r   r   <module>   sj    
	

  

#$  \