import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print("Installed Python packages:")
print(installed_packages_list)


import sys
import csv
from this_trainer.ch2017_mimo_trainer import Ch2017MimoTrainer 
from data_io.mimo_csv_adaptor import mimo_csv_adaptor 
from utils import my_numpy_utils as my_np
import gc
import keras.backend.tensorflow_backend as K

#block_seq_base_length=6000
#out_dec_factor=18
class PredictClass():
  def __init__(self):
    self.ch2017_mimo_trainer = Ch2017MimoTrainer(train_batch_size = 1, block_seq_base_length=sys.maxsize)
    self.mimo_csv_adaptor = mimo_csv_adaptor()
    self.weights_filename = "best_weights.hdf5"
        
  def read_file(self, filename):
    self.mimo_csv_adaptor.read_file(filename, 
                        out_dec_factor=self.ch2017_mimo_trainer.out_dec_factor)    
    #self.mimo_csv_adaptor.mimo.generate_block_input()
    
  def prepare_data(self, mimo, batch_size):
    # data is ready; nothing to do
    return self.mimo_csv_adaptor.mimo
  
  def do_test(self, weights_filename=None, do_plot=False):
    batch_size = 1
    test_model = self.ch2017_mimo_trainer.create_model(
      self.mimo_csv_adaptor.mimo, batch_size)
    self.ch2017_mimo_trainer.do_test(test_model, 
      self.mimo_csv_adaptor.mimo, batch_size, weights_filename=weights_filename, 
      csvOutputFile='answer.txt', do_evaluate=False)

    if do_plot:    
      print(self.mimo_csv_adaptor.mimo.block_output)
      self.mimo_csv_adaptor.mimo.plot_input()
      self.mimo_csv_adaptor.mimo.plot_output()

    # use last prediction as classification
    predictions = my_np.prob_to_class(self.mimo_csv_adaptor.mimo.block_output[0, :, :])

    # -1 to remove the 'no-signal class'
    print('Classification:' + self.mimo_csv_adaptor.labels[predictions[-1]-1])
    
    K.clear_session()
    
    
    
    #gc.collect()
  

    

if __name__ == "__main__":
  pc = PredictClass()
  pc.read_file(sys.argv[1])
  if len(sys.argv) > 2:
    weights_filename=sys.argv[2]
  else:
    weights_filename=None  
  pc.do_test(weights_filename)
  #print('Usage: PredictClass [filename]')
   
