o
    Ne1                     @   s   d 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 eeeefZdd Zdd Zd	d
 ZdddZ	dddZdS )z6Object config serialization and deserialization logic.    N)object_registration)	tf_exportc                 C   s  | du r| S t | tr| S t | ttfrdd | D S t | tr$t| S t | tr3dd| didS t | tj	r=| 
 S t | tjrQd|   | jjd	dS t| jtjkrot | tjrkd
|  | jjd	dS |  S t | tjrx| jS tj| jdd}|du rt | tjr| j}n| jj}| jj}|dkrd}n't | tjrt| }nt| j}n|d}d|dd }|d }d}||t | |d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  serialize_keras_object.0xr   r   [D:\Projects\ConvertPro\env\Lib\site-packages\keras/saving/experimental/serialization_lib.py
<listcomp>4   s    z*serialize_keras_object.<locals>.<listcomp>	__bytes__valueutf-8)
class_nameconfig
__tensor__)r   dtype	__numpy__keras)Zapi_namebuiltins.)moduler   r   registered_name)!
isinstancePLAIN_TYPESlisttupledictserialize_dictbytesdecodetfZTensorShapeas_listZTensornumpytolistr   nametype
__module__np__name__ZndarrayitemZDTyper   Zget_canonical_name_for_symbol	__class__typesFunctionTyper   Zget_registered_namesplitjoin_get_class_or_fn_config)objZkeras_api_namer   r   r   partsr   r   r
   r      sl   



	
r   c                 C   s   t | tjrt| ddkrtd|  | jS t| dr3|  }t |ts/td|  d| t	|S td|  dt
|  d	)
z1Return the object's config depending on its type.r*   z<lambda>z`lambda` objects cannot be serialized. Make sure there are no `lambda` objects being returned by a `get_config()` method. Received the following: 
get_configzThe `get_config()` method of z$ should return a dict. It returned: zCannot serialize object z	 of type zG. To be serializable, a class must implement the `get_config()` method.)r   r-   r.   getattr	TypeErrorr*   hasattrr4   r   r   r'   )r2   r   r   r   r
   r1   y   s(   

r1   c                 C   s   dd |   D S )Nc                 S   s   i | ]	\}}|t |qS r   r   r   keyr   r   r   r
   
<dictcomp>   s    z"serialize_dict.<locals>.<dictcomp>)items)r2   r   r   r
   r      s   r   c                    s   pi  | du r
dS t | tr!t | tr | dur |  S | S t | ttfr1 fdd| D S t | ts=td|  d| vsEd| vrP fdd|  D S | d }| d }|d	krgt	j
|d
 |d dS |dkrvtj|d
 |d dS | d dkr|d
 dS | dd}| d|}|dkr|}t|||d|  dS t|||d|  d}t|dstd| d|  t  ||W  d   S 1 sw   Y  dS )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 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, such as
      "keras.engine.compile_utils". Built-in Keras classes
      expect to have prefix `keras`.
    - `registered_name`: String. The key the class is registered under via
      `keras.utils.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 defaults to 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": "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.utils.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_dict: the python dict structure to deserialize the Keras object
        from.

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

    Nc                    s   g | ]}t | d qS custom_objectsdeserialize_keras_objectr   r=   r   r
   r     s    
z,deserialize_keras_object.<locals>.<listcomp>zCould not parse config: r   r   c                    s   i | ]\}}|t | d qS r<   r?   r8   r=   r   r
   r:   
  s    z,deserialize_keras_object.<locals>.<dictcomp>r   r   r   )r   r   r   r   r   r   function)obj_typefull_configr>   classfrom_configz&Unable to reconstruct an instance of 'zM' because the class is missing a `from_config()` method. Full object config: )r   r   strgetr   r   r   r6   r;   r"   Zconstantr)   arrayencode_retrieve_class_or_fnr7   r   Zcustom_object_scoperE   )r   r>   r   Zinner_configr   r   fn_nameclsr   r=   r
   r@      sl   ^





$r@   c           	      C   s   t j||d}|d ur|S |rT|dks|dr't|d |  }|d ur'|S zt|}W n tyE   td| d|  d| d| w t	|
| d }|d urT|S td	| d|  d
| )Nr=   r   zkeras.r   zCould not deserialize z 'z' because its parent module z) cannot be imported. Full object config: zCould not locate zo'. Make sure custom classes are decorated with `@keras.utils.register_keras_serializable`. Full object config: )r   Zget_registered_object
startswithr   Zget_symbol_from_name	importlibimport_moduleModuleNotFoundErrorr6   varsrG   )	r&   r   r   rB   rC   r>   Z
custom_objr2   modr   r   r
   rJ   A  s:   rJ   )N)__doc__rN   r-   r$   r)   Ztensorflow.compat.v2compatv2r"   Zkeras.savingr   Ztensorflow.python.utilr   rF   intfloatboolr   r   r1   r   r@   rJ   r   r   r   r
   <module>   s   Z
 )