from __future__ import print_function
import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from data import cfg_mnet, cfg_re50
from layers.functions.prior_box import PriorBox
from utils.nms.py_cpu_nms import py_cpu_nms
import cv2
from models.retinaface import RetinaFace
from utils.box_utils import decode, decode_landm
import time

parser = argparse.ArgumentParser(description='Retinaface')

parser.add_argument('-m', '--trained_model', default='./20-point-weights/Retinaface_192_v0529a-1/mobilenet0.25_Final.pth',
                    type=str, help='Trained state_dict file path to open')
parser.add_argument('--network', default='mobile0.25', help='Backbone network mobile0.25 or resnet50')
parser.add_argument('--cpu', action="store_true", default=True, help='Use cpu inference')
parser.add_argument('--confidence_threshold', default=0.8, type=float, help='confidence_threshold')
parser.add_argument('--top_k', default=5000, type=int, help='top_k')
parser.add_argument('--nms_threshold', default=0.4, type=float, help='nms_threshold')
parser.add_argument('--keep_top_k', default=750, type=int, help='keep_top_k')
parser.add_argument('-s', '--save_image', action="store_true", default=True, help='show detection results')
parser.add_argument('--vis_thres', default=0.6, type=float, help='visualization_threshold')
args = parser.parse_args()


def check_keys(model, pretrained_state_dict):
    ckpt_keys = set(pretrained_state_dict.keys())
    model_keys = set(model.state_dict().keys())
    used_pretrained_keys = model_keys & ckpt_keys
    unused_pretrained_keys = ckpt_keys - model_keys
    missing_keys = model_keys - ckpt_keys
    print('Missing keys:{}'.format(len(missing_keys)))
    print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))
    print('Used keys:{}'.format(len(used_pretrained_keys)))
    assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'
    return True


def remove_prefix(state_dict, prefix):
    ''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
    print('remove prefix \'{}\''.format(prefix))
    f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
    return {f(key): value for key, value in state_dict.items()}


def load_model(model, pretrained_path, load_to_cpu):
    print('Loading pretrained model from {}'.format(pretrained_path))
    if load_to_cpu:
        pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)
    else:
        device = torch.cuda.current_device()
        pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))
    if "state_dict" in pretrained_dict.keys():
        pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.')
    else:
        pretrained_dict = remove_prefix(pretrained_dict, 'module.')
    check_keys(model, pretrained_dict)
    model.load_state_dict(pretrained_dict, strict=False)
    return model


if __name__ == '__main__':
    torch.set_grad_enabled(False)
    cfg = None
    if args.network == "mobile0.25":
        cfg = cfg_mnet
    elif args.network == "resnet50":
        cfg = cfg_re50
    # net and model
    net = RetinaFace(cfg=cfg, phase = 'test')
    net = load_model(net, args.trained_model, args.cpu)
    net.eval()
    print('Finished loading model!')
    print(net)
    cudnn.benchmark = True
    device = torch.device("cpu" if args.cpu else "cuda")
    net = net.to(device)

    resize = 1

    # testing begin
    for i in range(1):
        image_path = "./curve/bsj_test006.png"
        img_raw = cv2.imread(image_path, cv2.IMREAD_COLOR)
        raw_height, raw_width, _ = img_raw.shape
        print("src shape: ", img_raw.shape)
        long_size = raw_width
        if raw_height > raw_width:
            long_size = raw_height
        image_scale = 192 * 1.0 / long_size

        size = (int(raw_width*image_scale), int(raw_height*image_scale))
        img_raw = cv2.resize(img_raw, size)
        print("resize shape: ", img_raw.shape)

        img = np.float32(img_raw)

        im_height, im_width, _ = img.shape
        scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
        # print(scale)
        img -= (104, 117, 123)
        img = img.transpose(2, 0, 1) # h w c -> c h w
        img = torch.from_numpy(img).unsqueeze(0) # c h w  -> 1 c h w
        img = img.to(device)
        scale = scale.to(device)

        tic = time.time()
        loc, conf, landms = net(img)  # forward pass
        print('net forward time: {:.4f}'.format(time.time() - tic))
        # print(loc.shape)
        # print(conf.shape)
        # print(landms.shape)
        # print(loc)
        # print(conf)
        # print(landms)
        
        priorbox = PriorBox(cfg, image_size=(im_height, im_width))
        # print(priorbox)
        priors = priorbox.forward()
        priors = priors.to(device)
        prior_data = priors.data
        # print(prior_data)
        # print(prior_data.shape)

        boxes = decode(loc.data.squeeze(0), prior_data, cfg['variance'])
        # print("loc.data shape")
        # print(loc.data.shape)

        # print("loc.data.squeeze(0)")
        # print(loc.data.squeeze(0))

        # print("boxes")
        # print(boxes)
        # print("boxes shape")
        # print(boxes.shape)

        boxes = boxes * scale / resize
        # print("scale shape")
        # print(scale.shape)
        # print("after <boxes * scale / resize>")
        # print(boxes)

        boxes = boxes.cpu().numpy()
        # print("after <boxes.cpu().numpy()>")
        # print(boxes)

        scores = conf.squeeze(0).data.cpu().numpy()[:, 1]
        # print("conf.squeeze(0).data.cpu().numpy()")
        # print(conf.squeeze(0).data.cpu().numpy())
        # print("QLHUA TEST=== each prior box have face prob:")
        # print(scores)


        landms = decode_landm(landms.data.squeeze(0), prior_data, cfg['variance'], cfg['landmark_num'])
        
        # print("landms after decode_landm")
        # print(landms.shape)
        # print(landms)
        if cfg['landmark_num'] == 5:
            scale1 = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                                img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                                img.shape[3], img.shape[2]])
        elif cfg['landmark_num'] == 20:
            scale1 = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                               img.shape[3], img.shape[2], img.shape[3], img.shape[2]])
        # print("scale1")
        # print(scale1)

        scale1 = scale1.to(device)
        # print("scale1 after to device")
        # print(scale1)
        landms = landms * scale1 / resize
        landms = landms.cpu().numpy()

        # print("landms after scale1")
        # print(landms)

        # ignore low scores
        inds = np.where(scores > args.confidence_threshold)[0]
        inds_tmp = np.where(scores > args.confidence_threshold)
        # print(inds_tmp)
        
        # print(inds.shape)
        # print(inds)
        
        boxes = boxes[inds]
        landms = landms[inds]
        scores = scores[inds]

        # print("after ignore low scores")
        # print("boxes shape")
        # print(boxes.shape)
        # print(boxes)

        # print("landms shape")
        # print(landms.shape)
        # print(landms)

        # print("scores shape")
        # print(scores.shape)
        # print(scores)

        # keep top-K before NMS
        # print("scores.argsort()")
        order_tmp = scores.argsort()
        # print(order_tmp)
        

        order = scores.argsort()[::-1][:args.top_k]
        boxes = boxes[order]
        landms = landms[order]
        scores = scores[order]

        # print("after order")
        # print("boxes")
        # print(boxes)

        # print("landms")
        # print(landms)

        # print("scores")
        # print(scores)


        # print("do NMS")
        # do NMS
        dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)
        # print("dets data:")
        # print(dets)
        keep = py_cpu_nms(dets, args.nms_threshold)

        # print("keep")
        # print(keep)
        # keep = nms(dets, args.nms_threshold,force_cpu=args.cpu)
        dets = dets[keep, :]
        # print(dets)
        landms = landms[keep]

        # keep top-K faster NMS
        dets = dets[:args.keep_top_k, :]
        landms = landms[:args.keep_top_k, :]

        dets = np.concatenate((dets, landms), axis=1)
        # print("after nms")
        # print("dets.shape")
        # print(dets.shape)
        # print(dets)

        # show image
        if args.save_image:
            for b in dets:
                if b[4] < args.vis_thres:
                    continue
                text = "{:.4f}".format(b[4])
                print(text)
                b = list(map(int, b))
                print(int)
                print(b)
                cv2.rectangle(img_raw, (b[0], b[1]), (b[2], b[3]), (0, 0, 255), 2)
                cx = b[0]
                cy = b[1] + 12
                cv2.putText(img_raw, text, (cx, cy),
                            cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255))

                # landms
                if cfg['landmark_num'] == 5:
                    cv2.circle(img_raw, (b[5], b[6]), 1, (0, 0, 255), 4)
                    cv2.circle(img_raw, (b[7], b[8]), 1, (0, 255, 255), 4)
                    cv2.circle(img_raw, (b[9], b[10]), 1, (255, 0, 255), 4)
                    cv2.circle(img_raw, (b[11], b[12]), 1, (0, 255, 0), 4)
                    cv2.circle(img_raw, (b[13], b[14]), 1, (255, 0, 0), 4)
                elif cfg['landmark_num'] == 20:
                    cv2.circle(img_raw, (b[5], b[6]), 1, (0, 0, 255), 4)
                    cv2.circle(img_raw, (b[7], b[8]), 1, (0, 255, 255), 4)
                    cv2.circle(img_raw, (b[9], b[10]), 1, (255, 0, 255), 4)
                    cv2.circle(img_raw, (b[11], b[12]), 1, (0, 255, 0), 4)
                    cv2.circle(img_raw, (b[13], b[14]), 1, (255, 0, 0), 4)
                    cv2.circle(img_raw, (b[15], b[16]), 1, (0, 0, 255), 4)
                    cv2.circle(img_raw, (b[17], b[18]), 1, (0, 255, 255), 4)
                    cv2.circle(img_raw, (b[19], b[20]), 1, (255, 0, 255), 4)
                    cv2.circle(img_raw, (b[21], b[22]), 1, (0, 255, 0), 4)
                    cv2.circle(img_raw, (b[23], b[24]), 1, (255, 0, 0), 4)
                    cv2.circle(img_raw, (b[25], b[26]), 1, (0, 0, 255), 4)
                    cv2.circle(img_raw, (b[27], b[28]), 1, (0, 255, 255), 4)
                    cv2.circle(img_raw, (b[29], b[30]), 1, (255, 0, 255), 4)
                    cv2.circle(img_raw, (b[31], b[32]), 1, (0, 255, 0), 4)
                    cv2.circle(img_raw, (b[33], b[34]), 1, (255, 0, 0), 4)
                    cv2.circle(img_raw, (b[35], b[36]), 1, (0, 0, 255), 4)
                    cv2.circle(img_raw, (b[37], b[38]), 1, (0, 255, 255), 4)
                    cv2.circle(img_raw, (b[39], b[40]), 1, (255, 0, 255), 4)
                    cv2.circle(img_raw, (b[41], b[42]), 1, (0, 255, 0), 4)
                    cv2.circle(img_raw, (b[43], b[44]), 1, (255, 0, 0), 4)
            # save image

            name = "result.jpg"
            cv2.imwrite(name, img_raw)

