package com.srs.stureg.tools;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.util.Base64Util;
import org.json.JSONObject;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;

public class FaceRecognition {

    public Double faceVetify(String pathSource,String pathLogin){
        String appId="33850699";
        String apiKey="35KXpW7rP7mwKUNdd1GTCcUU";
        String secretKey="NmAjlugaD1oLi3rjmeWfc63OgOmQ2NDV";
        AipFace client = new AipFace(appId, apiKey, secretKey);
        try{
            Double faceComparison = faceComparison(client, pathLogin, pathSource);
            return  faceComparison;
        }
        catch (Exception e){
            return  0D;
        }
    }


    private  Double faceComparison(AipFace client, String loginImagePath, String comparedImagePath) throws Exception {
        byte[] loginImageBytes = Files.readAllBytes(Paths.get(loginImagePath));
        byte[] comparedImageBytes = Files.readAllBytes(Paths.get(comparedImagePath));
        String image1 = Base64Util.encode(loginImageBytes);
        String image2 = Base64Util.encode(comparedImageBytes);

        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "BASE64");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<>();
        requests.add(req1);
        requests.add(req2);

        JSONObject match = client.match(requests);
        System.out.println(match.toString(2));
        return match.getJSONObject("result").getDouble("score");
    }

}
