mx.iteso.desi.cloud.hw3.AWSFaceCompare.java Source code

Java tutorial

Introduction

Here is the source code for mx.iteso.desi.cloud.hw3.AWSFaceCompare.java

Source

/*
 * Copyright 2017 Mario Contreras <marioc@nazul.net>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package mx.iteso.desi.cloud.hw3;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.CompareFacesRequest;
import com.amazonaws.services.rekognition.model.CompareFacesResult;
import com.amazonaws.services.rekognition.model.Image;
import com.amazonaws.services.rekognition.model.S3Object;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author parres
 */
public class AWSFaceCompare {

    private final String srcBucket;
    private final AmazonRekognition arek;
    private final String accessKey;
    private final String secretKey;
    private final Regions region;
    private final AmazonS3 s3;
    private static final Float SIMILARITY_THRESHOLD = 80.0f;

    public AWSFaceCompare(String accessKey, String secretKey, Regions region, String srcBucket) {
        this.srcBucket = srcBucket;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.region = region;

        AWSCredentialsProvider credProvider = new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(accessKey, secretKey));
        arek = AmazonRekognitionClientBuilder.standard().withCredentials(credProvider).withRegion(region).build();
        s3 = AmazonS3ClientBuilder.standard().withCredentials(credProvider).withRegion(region).build();
    }

    private void upload(String filename) {
        PutObjectRequest request = new PutObjectRequest(Config.srcBucket, "Compare/" + filename,
                new File(filename));
        s3.putObject(request);
    }

    public Face compare(ByteBuffer imageBuffer) {
        final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(srcBucket).withPrefix("Faces/");
        ListObjectsV2Result result;
        ArrayList<String> s3Files = new ArrayList<>();
        Face empty = new Face("", 0.0f);

        try {
            String sourceFile = "source.jpg";
            Path file = Paths.get(sourceFile);
            Files.write(file, imageBuffer.array(), StandardOpenOption.CREATE);
            upload(sourceFile);
        } catch (IOException ex) {
            Logger.getLogger(FaceAddFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        do {
            result = s3.listObjectsV2(req);

            for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {
                s3Files.add(objectSummary.getKey());
            }
            req.setContinuationToken(result.getNextContinuationToken());
        } while (result.isTruncated() == true);

        for (String s3File : s3Files) {
            if (s3File.endsWith(".jpg")) {
                System.out.println("Checking " + s3File + "...");
                Face face = compare("Compare/source.jpg", s3File);
                if (face.getCofidence() > SIMILARITY_THRESHOLD) {
                    return face;
                }
            }
        }
        return empty;
    }

    // From: http://docs.aws.amazon.com/rekognition/latest/dg/get-started-exercise-compare-faces.html
    private Image getImageUtil(String key) {
        return new Image().withS3Object(new S3Object().withBucket(srcBucket).withName(key));
    }

    // From: http://docs.aws.amazon.com/rekognition/latest/dg/get-started-exercise-compare-faces.html
    private CompareFacesResult callCompareFaces(Image sourceImage, Image targetImage, Float similarityThreshold) {
        CompareFacesRequest compareFacesRequest = new CompareFacesRequest().withSourceImage(sourceImage)
                .withTargetImage(targetImage);
        return arek.compareFaces(compareFacesRequest);
    }

    // From: http://docs.aws.amazon.com/rekognition/latest/dg/get-started-exercise-compare-faces.html
    private Face compare(String sourceKey, String targetKey) {
        Image source = getImageUtil(sourceKey);
        Image target = getImageUtil(targetKey);
        CompareFacesResult compareFacesResult = callCompareFaces(source, target,
                AWSFaceCompare.SIMILARITY_THRESHOLD);

        if (compareFacesResult.getFaceMatches().size() > 0) {
            return new Face(targetKey, compareFacesResult.getFaceMatches().get(0).getSimilarity());
        } else {
            return new Face("", 0.0f);
        }
    }
}

// EOF