# -*- coding: utf-8 -*-
"""
    File name:      read_weights_ecg.py
    Author:         Tetsuro Tatsuoka
    Date created:   04/12/2018
    Last modified:  04/12/2018
    Version:        1.0.0
    Python version: 3.6.3
    Description:    Read weights of hdf5 file generated by Keras

    Revision history:
        1.0.0   04/12/2018  - Initial coding.
"""
import os
import h5py
import numpy as np
import pickle

def read_weights(filepath):
    """
        Read weights from hdf5 file and save pickle file
    
        Parameters:
            filepath    path of hdf5 file
        Returns:
            paths       path of each weights in hdf5 tree
            weights     list of numpy.array of weights and bias
    """
    with h5py.File(filepath, mode='r') as f:
        if 'layer_names' not in f.attrs:
            print('No layer_names attributs')
            os.close()

        paths = []
        weights = []
        for layer_name in f.attrs['layer_names']:
            print('Layer name: ' + layer_name.decode('utf8'))
            
            for weight_name in f[layer_name].attrs['weight_names']:
                weight_path = layer_name + b'/' + weight_name
                
                path_str = weight_path.decode('utf8')
                paths.append(path_str)
                
                weights_array = np.array(f[weight_path])
                weights.append(weights_array)
                
                if path_str.find('recurrent_kernel:') > -1:
                    print('Rec.kernel: ' + str(weights_array.shape))
                elif path_str.find('kernel:') > -1:
                    print('    Kernel: ' + str(weights_array.shape))
                elif path_str.find('bias:') > -1:
                    print('      Bias: ' + str(weights_array.shape))
    
    no_ext, ext = os.path.splitext(filepath)
    filepath = no_ext + '.pkl'
    with open(filepath,'wb') as f:
        pickle.dump(weights, f)

    return paths, weights
