import argparse
parser = argparse.ArgumentParser(description='Train a PLC model')
parser.add_argument('bits', metavar='<bits file>', help='binary features file (int16)')
parser.add_argument('output', metavar='<output>', help='output features')
parser.add_argument('--model', metavar='<model>', default='rdovae', help='PLC model python definition (without .py)')
group1 = parser.add_mutually_exclusive_group()
group1.add_argument('--weights', metavar='<input weights>', help='model weights')
parser.add_argument('--cond-size', metavar='<units>', default=1024, type=int, help='number of units in conditioning network (default 1024)')
parser.add_argument('--batch-size', metavar='<batch size>', default=1, type=int, help='batch size to use (default 128)')
parser.add_argument('--seq-length', metavar='<sequence length>', default=1000, type=int, help='sequence length to use (default 1000)')
args = parser.parse_args()
import importlib
rdovae = importlib.import_module(args.model)
import sys
import numpy as np
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger
import tensorflow.keras.backend as K
import h5py
import tensorflow as tf
from rdovae import pvq_quantize
from rdovae import apply_dead_zone
batch_size = args.batch_size
model, encoder, decoder, qembedding = rdovae.new_rdovae_model(nb_used_features=20, nb_bits=80, batch_size=batch_size, cond_size=args.cond_size)
model.load_weights(args.weights)
lpc_order = 16
nbits=80
bits_file = args.bits
sequence_size = args.seq_length
bits = np.memmap(bits_file + "-syms.f32", dtype='float32', mode='r')
nb_sequences = len(bits)//(40*sequence_size)//batch_size*batch_size
bits = bits[:nb_sequences*sequence_size*40]
bits = np.reshape(bits, (nb_sequences, sequence_size//2, 20*4))
print(bits.shape)
lambda_val = 0.001 * np.ones((nb_sequences, sequence_size//2, 1))
quant_id = np.round(3.8*np.log(lambda_val/.0002)).astype('int16')
quant_id = quant_id[:,:,0]
quant_embed = qembedding(quant_id)
quant_scale = tf.math.softplus(quant_embed[:,:,:nbits])
dead_zone = tf.math.softplus(quant_embed[:, :, nbits : 2 * nbits])
bits = bits*quant_scale
bits = np.round(apply_dead_zone([bits, dead_zone]).numpy())
bits = bits/quant_scale
state = np.memmap(bits_file + "-state.f32", dtype='float32', mode='r')
state = np.reshape(state, (nb_sequences, sequence_size//2, 24))
state = state[:,-1,:]
state = pvq_quantize(state, 82)
print("shapes are:")
print(bits.shape)
print(state.shape)
bits = bits[:,1::2,:]
features = decoder.predict([bits, state], batch_size=batch_size)
features.astype('float32').tofile(args.output)