#!/usr/bin/env python
# coding: utf-8

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import Ui_MainWindow as ui

from IRM80x62_thermal import Thermal
from camera import Camera
from detector import FaceDetector
from anti import AntiSpoofing
from heater import Heater
from aligner import BoxAligner
from correcter import Correcter

import cv2
import numpy as np
import time

class Main(QMainWindow, ui.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.resize(640,480)
        self.label.setScaledContents(True)
        self.label_2.setScaledContents(True)
        self.thermal = Thermal(width = 80, height = 62, framerate = 4, frame_width = 640, frame_height = 480, log=None, port="/dev/ttyUSB0")
        self.camera = Camera(width=640, height=480, framerate=30, log=None, channel=0, flip=1)
        self.detector = FaceDetector(model_path="../Ultra-Light-Fast-Generic-Face-Detector-1MB/MNN/model/version-RFB/RFB-320.mnn" , input_size=(320,240))
        # self.anti = AntiSpoofing(model_path="../Ultra-Light-Fast-Generic-Face-Detector-1MB/MNN/model/4_0_0_80x80_MiniFASNetV1SE.mnn")
        self.aligner = BoxAligner(img_h = 480,img_w = 640)
        self.heater = Heater(pwm_pin=12 , target_temp=36.0)
        self.correcter = Correcter(model_path="../thermal-tk/20210421_correcter.sav")
        self.thermal.start()
        time.sleep(2)
        self.camera.start()
        time.sleep(2)
        self.heater.start()
        time.sleep(2)
        self.num_frame = 0
        self.painter = QPainter(self)
    def paintEvent(self, QPaintEvent):
        # 繪圖事件
        ret, frame = self.camera.capture()
        thermal_ret,thermal_frame, thermal_row = self.thermal.capture()
        if(thermal_ret and ret):
            self.num_frame+=1
            blackbody_max = thermal_row[:,:34].max()
            heater_temp = self.heater.last_temp
            #heater_temp = 36.5
            print(heater_temp)
            # 偵測人臉
#             if(self.num_frame % 2 == 0):
            if(True):
                stime = time.time()
                boxes, labels, probs = self.detector.predict(frame)
                processing_time = time.time()-stime
                self.label_3.setText(str(processing_time))
                # 取出所有偵測的結果
                for i in range(boxes.shape[0]):
                    box = boxes[i, :]
                    score = probs[i]
                    if(score > 0.9):
                        #scaled_box = anti.scale_box(img_h=480,img_w=640,box=box)
                        #expanded_face = frame[scaled_box[1]:scaled_box[3],scaled_box[0]:scaled_box[2]].copy()
                        #live_score = anti.predict(expanded_face)
                        live_score = 0.9
                        if(live_score > 0.9):
                            color = (0, 255, 0)
                        else:
                            color = ( 0, 0, 255)
                        thermal_box = self.aligner.box_aligment([box])[0]
                        cv2.rectangle(thermal_frame, (thermal_box[0], thermal_box[1]), (thermal_box[2], thermal_box[3]), color, 2)
                        cv2.rectangle(frame, (box[0], box[1]), (box[2], box[3]), color, 2)
                        face_temp = self.max_temperature(thermal_box,thermal_row)
                        corrected_face_temp = self.correcter.predict(x_detect_k= face_temp, x_black_k= blackbody_max, x_black_c= heater_temp)
                        cv2.putText(frame, "{:.2f}->{:.2f}".format(face_temp,corrected_face_temp), ((box[0]+box[2])//2, (box[1]+box[3])//2), cv2.FONT_HERSHEY_COMPLEX_SMALL,1, (0, 255, 255), 1, cv2.LINE_AA)
                        cv2.putText(thermal_frame, "{:.2f}".format(heater_temp), (320//4, 64//4), cv2.FONT_HERSHEY_COMPLEX_SMALL,1, (0, 0, 0), 1, cv2.LINE_AA)
            # 顯示至UI
            frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
            thermal_frame=cv2.cvtColor(thermal_frame,cv2.COLOR_BGR2RGB)
            Qframe=QImage(frame.data,frame.shape[1],frame.shape[0],frame.shape[1]*3,QImage.Format_RGB888)
            Qthermal_frame=QImage(thermal_frame.data,thermal_frame.shape[1],thermal_frame.shape[0],thermal_frame.shape[1]*3,QImage.Format_RGB888)
            pixMap=QPixmap.fromImage(Qframe)
            thermal_pixMap=QPixmap.fromImage(Qthermal_frame)
            self.label.setPixmap(pixMap)
            self.label_2.setPixmap(thermal_pixMap)
            self.update()
    def closeEvent(self,event):
        # 關閉程式後執行
        self.thermal.stop()
        self.camera.stop()
        self.heater.stop()
    def max_temperature(self,box,thermal_row,black_h=0,thermal_height=62,thermal_width=80,image_height=480,image_width=640):
        scale_ratio_h = thermal_height/image_height
        scale_ratio_w = thermal_width/image_width
        x1 = max(int(box[0]*scale_ratio_w),0)
        y1 = max(int(box[1]*scale_ratio_h),black_h)
        x2 = min(int(box[2]*scale_ratio_w),thermal_width)
        y2 = min(int(box[3]*scale_ratio_h),thermal_height)
        box_temperature = thermal_row[y1:y2,x1:x2]
        if(box_temperature.size != 0):
            return box_temperature.max()
        else:
            return 0
if __name__ == '__main__':
    import sys
    import os
    app = QtWidgets.QApplication(sys.argv)
    window = Main()
    window.show()
    status = app.exec_()
    time.sleep(1)
#     sys.exit(app.exec_())
    os._exit(status)

