# -*- coding: utf-8 -*-
# @Author: Aliaksei Halachkin
# @Date:   2016-09-19 22:43:45
# @Last Modified by:   Aliaksei Halachkin
# @Last Modified time: 2016-09-19 22:59:58


import os.path
import os
from exceptions import Exception
import numpy as np
import pandas as pd
from shutil import copyfile

TRAINSET = "..\\training_data\\trainset_v3.csv"


def class_photos_to_folders(input_trainset_filename, output_dir):
    """Copy vehicle photos to folders, one folder for each class
    """
    trainset = pd.read_csv(input_trainset_filename, sep = ';')
    n_samples = trainset.shape[0]
    n_fails = 0
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for idx in range(n_samples):
        if idx % 100 == 0:
            print str(idx) + "\\" + str(n_samples) + " samples read" 
        try:
            filename = trainset.iloc[idx][0]
            class_name = trainset.iloc[idx][1]
            class_dir = os.path.join(output_dir, class_name) 
            if not os.path.exists(class_dir):
                os.makedirs(class_dir)

            copyfile(filename + '.jpg', os.path.join(class_dir, os.path.basename(filename) + '.jpg'))

        except Exception as e:
            n_fails += 1
            print e

    print str(n_samples - n_fails) + " samples read"
    print str(n_fails) + " samples failed to read"


if __name__ == "__main__":
    class_photos_to_folders(TRAINSET, "C:\\Users\\aliak_000\\Desktop\\Classes")
