#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os

import numpy as np


fpath_this = os.path.realpath(__file__)
dpath_this = os.path.dirname(fpath_this)

print('# accuracies')
for label in range(6):
    # パスを用意
    fname_in = str.format("outputs_resnet_{}.csv", label)
    fname_out = str.format("result_resnet_{}.csv", label)

    fpath_in = os.path.join(dpath_this, fname_in)
    fpath_out = os.path.join(dpath_this, fname_out)

    # csvファイルを読込み
    data = np.loadtxt(fpath_in, dtype=str, delimiter=',')
    header = data[0]
    aug_img_names = data[1:, 0]
    list_probs = data[1:, 1:]

    # 確率を平均
    d = {}
    for i, aug_img_name in enumerate(aug_img_names):
        aug_img_root, ext = os.path.splitext(aug_img_name)
        img_root = str.rsplit(aug_img_root, '_', 1)[0]
        img_name = img_root + ext
        if img_name in d.keys():
            d[img_name].append(list_probs[i])
        else:
            d[img_name] = [list_probs[i]]

    list_avg_probs = []
    img_names = d.keys()
    for img_name in img_names:
        arr_probs = np.asarray(d[img_name], np.float32)
        avg_probs = np.mean(arr_probs, axis=0)
        list_avg_probs.append(avg_probs)

    # 正解数を計算
    n_imgs = len(img_names)
    arr_avg_probs = np.asarray(list_avg_probs)
    preds = np.argmax(arr_avg_probs, axis=1)
    correct = np.sum(preds == label)
    print(str.format("label {}: {} / {}", label, correct, n_imgs))

    # csvファイルへ書出し
    img_names = np.asarray(img_names)
    img_names = np.reshape(img_names, (-1, 1))
    result = np.vstack((header, np.hstack((img_names, arr_avg_probs))))
    np.savetxt(fpath_out, result, fmt='%s', delimiter=',')
