import sys

if len(sys.argv) != 4:
    print("Run this script and training as:")
    print(" KERAS_BACKEND=tensorflow python convert_keras.py out_basename cpp_class model.h5")
    print("where:")
    print(" Output files will be called gen/out_basename*")
    print(" The input model to read in model.h5")
    raise SystemExit(1)

# This is an example of exporting a Keras-trained model
from pylab import randn, seed
# seed(123) # for making results reproducible during debugging
from keras import backend as K
from keras.models import load_model
from time import time
import tfconvert as tf2e
out_basename = sys.argv[1]
cpp_classname = sys.argv[2]
model = load_model(sys.argv[3])

x = model.get_input_at(0)
y = model.get_output_at(0)
print(model.summary())
print('input shape',x.get_shape())
print('output shape',y.get_shape())

sess = K.get_session()

# Generate some random data
N_tests = 10
test_shape = [dim.value if dim.value is not None else N_tests for dim in x.get_shape()]
test_input = randn( *test_shape )

# Run the test with timing
t1 = time()
for i in range(1000):
    result = model.predict(test_input)
t2 = time()
print('predict time %.1f us for 1000 loops' % ((t2-t1)*1e6))

m = tf2e.Model(sess) #,row_major=False)
m.build( x, y )

print('generating Numpy code...')
m.output_numpy(out_basename)
print('generating Numpy validation code...')
m.output_numpy_validation('%s_verify.py' % out_basename,test_input,result)

m.output_cpp(out_basename, cpp_classname)
m.output_cpp_validation('%s_verify.cpp' % out_basename,cpp_classname,test_input,result)

if False:
    # %run test3_verify.py 1
    # example debugging:
    m.ops['mul_238'].outputs[0].eval(session=sess, feed_dict={'gru_input_1:0':m.var_gru_input_1}) - m.var_mul_238
