from PIL import Image
from multiprocessing import Process
import sim.histogram as htg
import sim.aHash as ah
import sim.pHash as ph
import sim.dHash as dh
import os
import feature
from flask import redirect,url_for


# if __name__ == '__main__':

class simi:
    def similarity(self, path):
        print("begin")
        # print(m)
        # print(path)

        folder_path = "upload/" + path
        dirs = os.listdir(folder_path)

        # 文件夹下有tmp张图片
        tmp = 0
        for item in dirs:
            if os.path.isfile(os.path.join(folder_path, item)):
                tmp += 1
        # print(tmp)

        list = [[] for j in range(int(tmp*(tmp-1)*0.5))] # [[], [], [], [], [], []]

        index = 0
        for i in range(1,tmp+1):
            for j in range(i+1,tmp+1):
                str1 = folder_path + '/img' + str(i) + '.png'
                str2 = folder_path + '/img' + str(j) + '.png'
                # print(str1)
                # print(index)
                # print('------------------')
                list[index].append(str1)
                list[index].append(str2)

                img1 = Image.open(str1)
                img2 = Image.open(str2)
                img1_htg = htg.regularizeImage(img1)
                img2_htg = htg.regularizeImage(img2)
                hg1 = img1_htg.histogram()
                hg2 = img2_htg.histogram()

                # draw the histogram in a no-blocking way
                sub_thread = Process(target=htg.drawHistogram, args=(hg1, hg2,))
                sub_thread.start()

                # print the histogram similarity
                htg_result = htg.calMultipleHistogramSimilarity(img1_htg, img2_htg)
                list[index].append(htg_result)
                print('依据图片直方图距离计算相似度：{}'.format(htg_result))

                # aHash Calculation
                ah_result = ah.calaHashSimilarity(img1, img2)
                list[index].append(ah_result)
                print('依据平均哈希算法计算相似度：{}/{}'.format(ah_result, 64))

                # pHash Calculation
                ph_result = ph.calpHashSimilarity(img1, img2)
                list[index].append(ph_result)
                print('依据感知哈希算法计算相似度：{}/{}'.format(ph_result, 64))

                # dHash Calculation
                dh_result = dh.caldHashSimilarity(img1, img2)
                list[index].append(dh_result)
                print('依据差异哈希算法计算相似度：{}/{}'.format(dh_result, 64))

                index = index + 1
        # print(list)
        # print(index)
        # print(tmp)

        the_feature = feature.feat()
        message = the_feature.call_feature_extraction_1(folder_path,list,index,tmp)

        # return redirect(url_for('call_feature',alist = list))
        return message






