#!/usr/bin/python

import sys, os
import cv2
import numpy as np
import scipy.ndimage as nd
import csv

import joblib
from joblib import Parallel, delayed

import collection
from glob import glob

whichActivity = "testing"
if len(sys.argv) > 1:
    whichActivity = sys.argv[1]

if whichActivity == "training": 
    folder = "/home/rkjha/Documents/Copy/CS365/project/data/fakedata/images_training_rev1/"
else:
    folder = "/home/rkjha/Documents/Copy/CS365/project/data/fakedata/images_test_rev1/"

f = "/home/rkjha/Documents/Copy/CS365/project/data/fakedata/training_solutions_rev1.csv"

files = glob(folder+"/*")

points = [collection.get_ImageFeatures(f) for f in files]

mapping = collection.getNameField()

forest = joblib.load(collection.getCurrentFolderLocation()+"/galaxy_forest")
forest.set_params(n_jobs=1)

scaler2 = joblib.load(collection.getCurrentFolderLocation()+"/scaler2")
points = scaler2.transform(points)

myPredictions = forest.predict(points)

scaler1 = joblib.load(collection.getCurrentFolderLocation()+"/scaler1")
myPredictions = scaler1.inverse_transform(myPredictions)

myPredictions[myPredictions<1e-7] = 0

all_res = []
for f, prediction in zip(files,myPredictions):
    res = {}
    res['GalaxyID'] = os.path.basename(f)[:-len(".jpg")]
    for i in xrange(37):
        res[mapping[i+1]] = prediction[i]
    all_res.append(res)

writerDict = csv.DictWriter(open("/predictions.csv","w"),fieldnames=mapping)
writerDict.writeheader()

for res in all_res:
    writerDict.writerow(res)
