import os
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array, load_img
from keras.utils.np_utils import to_categorical
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import LabelEncoder, StandardScaler


def load_numeric_training(standardize=True):
    data = pd.read_csv('../train.csv')
    ID = data.pop('id')
    y = data.pop('species')
    y = LabelEncoder().fit(y).transform(y)
    X = StandardScaler().fit(data).transform(data) if standardize else data.values
    return ID.values, X, y


def load_numeric_test(standardize=True):
    data = pd.read_csv('../test.csv')
    ID = data.pop('id')
    test = StandardScaler().fit(data).transform(data) if standardize else data.values
    return ID.values, test


def resize_img(img, max_dim=96):
    max_axis = np.argmax(img.size)
    scale = max_dim / img.size[max_axis]
    return img.resize((int(img.size[0] * scale), int(img.size[1] * scale)))


def load_img_data(ids, max_dim=96, center=True):
    X = np.empty((len(ids), max_dim, max_dim, 1))
    for i, id in enumerate(ids):
        img = load_img('../images/{}.jpg'.format(id), grayscale=True)
        img = resize_img(img, max_dim=max_dim)
        x = img_to_array(img)
        h, w = x.shape[:2]
        if center:
            h1 = (max_dim - h) >> 1
            h2 = h1 + h
            w1 = (max_dim - w) >> 1
            w2 = w1 + w
        else:
            h1, h2, w1, w2 = 0, h, 0, w
        X[i][h1:h2, w1:w2][:] = x
    return 
np.around(X / 255)