import boto3
import pandas as pd
import numpy as np
import json

client=boto3.client('rekognition')


class NumpyEncoder(json.JSONEncoder):
    """ Custom encoder for numpy data types """
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
            return float(obj)
        elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):
            return {'real': obj.real, 'imag': obj.imag}
        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()
        elif isinstance(obj, (np.bool_)):
            return bool(obj)
        elif isinstance(obj, (np.void)):
            return None
        return json.JSONEncoder.default(self, obj)


#################
# IDENTIFICATION

df = pd.read_csv("identification.csv")
data = []

for index, row in df.iterrows():
    print(index)
    sourceFile = "commercial/{}_target.jpg".format(row['question_id'])
    targetFile = "commercial/{}_gallery.jpg".format(row['question_id'])
    imageSource=open(sourceFile,'rb')
    imageTarget=open(targetFile,'rb')
    response=client.compare_faces(SimilarityThreshold=80,
                                  SourceImage={'Bytes': imageSource.read()},
                                  TargetImage={'Bytes': imageTarget.read()})
    info = {}
    info['question_id'] = row['question_id']
    info['correct_answer'] = row['correct']
    info['response'] = response
    data += [info]

aws_identification = {
    'task': "identification",
    'service': "aws",
    'answers': data
    }


with open('aws_identification.json', 'w') as f:
    json.dump(aws_identification, f, cls=NumpyEncoder)




#################
# VERIFICATION


df = pd.read_csv("verification.csv")

data = []

for index, row in df.iterrows():
    print(index)
    sourceFile = "verification/{}".format(row['target_image'])
    targetFile = "verification/{}".format(row['other_image'])
    imageSource=open(sourceFile,'rb')
    imageTarget=open(targetFile,'rb')
    response=client.compare_faces(SimilarityThreshold=80,
                                  SourceImage={'Bytes': imageSource.read()},
                                  TargetImage={'Bytes': imageTarget.read()})
    info = {}
    info['question_id'] = row['question_id']
    info['correct_answer'] = row['correct_answer']
    info['response'] = response
    data += [info]

aws_verification = {
    'task': "verification",
    'service': "aws",
    'answers': data
    }


with open('aws_verification.json', 'w') as f:
    json.dump(aws_verification, f, cls=NumpyEncoder)
