Regalamiunsorriso/decompiled-libs/www/acxent-face-1.0.0/it/acxent/face/api/FaceRecognitionApi.java

1288 lines
58 KiB
Java
Raw Normal View History

2026-04-22 18:41:37 +02:00
package it.acxent.face.api;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import it.acxent.cc.Attivita;
import it.acxent.common.Parm;
import it.acxent.common.StatusMsg;
import it.acxent.db.ApplParm;
import it.acxent.db.ApplParmFull;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.face.FaceRecognizer;
import it.acxent.face.FaceScoreZoo;
import it.acxent.face.pc.SaveScoreProcessor;
import it.acxent.rest.HttpClientConfig;
import it.acxent.util.DoubleOperator;
import it.acxent.util.FileWr;
import it.acxent.util.ScaleImage;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class FaceRecognitionApi {
public static final String CUPS_SESSION_ID = "_CUPS_SESSION_ID";
public static final String API_FR_DEV = "http://localhost/fr/face/";
public static final String API_FR_PRODUCTION = "https://fr.f3ct.net/face/";
public static final String API_FACE_ZOO_DEV = "http://localhost/frzoo/facezoo/";
public static final String API_FACE_ZOO_PRODUCTION = "https://frz.f3ct.net/facezoo/";
public static final String API_FACE_SCORING_SELFIE_DEV = "http://localhost/face/face/";
public static final String API_FACE_SCORING_SELFIE_PRODUCTION = "https://face.f3ct.net/rest/";
public static final String P_FACE_RECOGNITION_API_USER = "FACE_RECOGNITION_API_USER";
public static final String P_FACE_RECOGNITION_API_PWD = "FACE_RECOGNITION_API_PWD";
public static final String P_FACE_RECOGNITION_DEV = "FACE_RECOGNITION_DEV";
public static final String P_FACE_RECOGNITION_API_SERVER_PROD = "FACE_RECOGNITION_API_SERVER_PROD";
public static final String P_FACE_RECOGNITION_API_SERVER_DEV = "FACE_RECOGNITION_API_SERVER_DEV";
public static final String P_FACE_RECOGNITION_API_SERVER_ZOO_PROD = "FACE_RECOGNITION_API_SERVER_ZOO_PROD";
public static final String P_FACE_RECOGNITION_API_SERVER_ZOO_DEV = "FACE_RECOGNITION_API_SERVER_ZOO_DEV";
public static final String P_FACE_SCORING_SELFIE_API_SERVER_PROD = "FACE_SCORING_SELFIE_API_SERVER_PROD";
public static final String P_FACE_SCORING_SELFIE_API_SERVER_DEV = "FACE_SCORING_SELFIE_API_SERVER_DEV";
public static final String P_FACE_SCORING_USE_FACE_SCORE_ZOO_CACHE = "FACE_SCORING_USE_FACE_SCORE_ZOO_CACHE";
private static final String URI_CMD_IMAGE_DETECT_FACES_AND_NUMBERS = "detectFacesAndNumbers/";
private static final String URI_CMD_CHECK_LABEL = "checkLabel/";
private static final String URI_CMD_TRAINING_RUN = "trainingRun/";
private static final String URI_CMD_RESET_TRAINING = "resetTraining/";
private static final String URI_CMD_TRAINING_SEND_IMAGES = "trainingSendImages/";
private static final String URI_CMD_RECOGNIZE = "recognize/";
private static final String URI_CMD_TRAINING_STOP = "trainingStop/";
private static final String URI_CMD_SYNC_FACE_DETECTION_METHODS = "syncFaceDetectionMethods/";
private static final String URI_CMD_SCORING = "scoring/";
private static final String URI_CMD_IMAGE_DETECT_FACES = "detectFaces/";
private static final String URI_CMD_SELFIE_SCORING = "scoringSelfie/";
private Attivita attivita;
private static boolean debug = false;
private ApplParmFull apFull = null;
private String apiUser;
private String apiPwd;
private ApplParmFull apFullCache = null;
public FaceRecognitionApi(ApplParmFull apFull) {
this.apFull = apFull;
}
public FaceRecognitionApi(ApplParmFull apFull, String l_user, String l_pwd) {
this.apFull = apFull;
setApiUser(l_user);
setApiPwd(l_pwd);
}
public FaceRecognitionApi() {}
public static void initApplicationParms(ApplParmFull ap) {
if (ap != null) {
DBAdapter.logDebug(true, "FACE initParms: start");
String l_tipoParm = "FACE-API";
Parm bean = new Parm(ap);
StatusMsg.updateMsgByTag(ap, "INIT", l_tipoParm);
bean.findByCodice("FACE_RECOGNITION_API_USER");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_RECOGNITION_API_USER");
bean.setDescrizione("FACE_RECOGNITION_API_USER");
if (bean.getTesto().isEmpty())
bean.setTesto("acolzi");
bean.setNota("API USER ACCESSO AL RICONOSCIMENTO FACCIALE");
bean.save();
bean.findByCodice("FACE_RECOGNITION_API_PWD");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_RECOGNITION_API_PWD");
bean.setDescrizione("FACE_RECOGNITION_API_PWD");
if (bean.getTesto().isEmpty())
bean.setTesto("pio");
bean.setNota("API PWD ACCESSO AL RICONOSCIMENTO FACCIALE");
bean.save();
bean.findByCodice("FACE_RECOGNITION_DEV");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_RECOGNITION_DEV");
bean.setDescrizione("FACE_RECOGNITION_DEV");
bean.setFlgTipo(5L);
bean.setNota("TRUE--> PRODUZIONE FALSE --> SVILUPPO");
bean.save();
bean.findByCodice("FACE_RECOGNITION_API_SERVER_DEV");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_RECOGNITION_API_SERVER_DEV");
bean.setDescrizione("FACE_RECOGNITION_API_SERVER_DEV");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("http://localhost/fr/face/");
bean.setNota("ENDPOINT FACE RECOGNITION TRAMITE MODELLI SU PROXY FRZ (NO PYTHON /face) CHIAMATO DA FACE IN SVILUPPO (http://localhost/fr/face/)");
bean.save();
bean.findByCodice("FACE_RECOGNITION_API_SERVER_PROD");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_RECOGNITION_API_SERVER_PROD");
bean.setDescrizione("FACE_RECOGNITION_API_SERVER_PROD");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("https://fr.f3ct.net/face/");
bean.setNota("ENDPOINT FACE RECOGNITION TRAMITE MODELLI SU PROXY FRZ (NO PYTHON /face) CHIAMATO DA FACE IN PRODUZIONE (https://fr.f3ct.net/fr/face/)");
bean.save();
bean.findByCodice("FACE_RECOGNITION_API_SERVER_ZOO_DEV");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_RECOGNITION_API_SERVER_ZOO_DEV");
bean.setDescrizione("FACE_RECOGNITION_API_SERVER_ZOO_DEV");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("http://localhost/frzoo/facezoo/");
bean.setNota("ENDPOINT FACE RECOGNITION SU PROXY FRZ TRAMITE SCOORING ZOO (/facezoo) CHIAMATO DA FACE IN PRODUZIONE IN SVILUPPO (http://localhost/zoo/facezoo/)");
bean.save();
bean.findByCodice("FACE_RECOGNITION_API_SERVER_ZOO_PROD");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_RECOGNITION_API_SERVER_ZOO_PROD");
bean.setDescrizione("FACE_RECOGNITION_API_SERVER_ZOO_PROD");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("https://frz.f3ct.net/facezoo/");
bean.setNota("ENDPOINT FACE RECOGNITION SU PROXY FRZ TRAMITE SCOORING ZOO (/facezoo) CHIAMATO DA FACE IN PRODUZIONE (https://frz.f3ct.net/zoo/facezoo/)");
bean.save();
bean.findByCodice("FACE_SCORING_SELFIE_API_SERVER_PROD");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_SCORING_SELFIE_API_SERVER_PROD");
bean.setDescrizione("FACE_SCORING_SELFIE_API_SERVER_PROD");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("https://face.f3ct.net/rest/");
bean.setNota("ENDPOINT SCORING SELFIE SU FACE (/rest) CHE POI CHIAMA ZOO CHIAMATO DA FOTOEVENTI O SERVIZIO ESTERNO IN PRODUZIONE (https://face.f3ctive.net/rest/)");
bean.save();
bean.findByCodice("FACE_SCORING_SELFIE_API_SERVER_DEV");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_SCORING_SELFIE_API_SERVER_DEV");
bean.setDescrizione("FACE_SCORING_SELFIE_API_SERVER_DEV");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("http://localhost/face/face/");
bean.setNota("ENDPOINT SCORING SELFIE SU FACE CHE POI CHIAMA ZOO CHIAMATO DA FOTOEVENTI O SERVIZIO ESTERNO IN SVILUPPO (http://localhost/face/rest/)");
bean.save();
bean.findByCodice("FACE_SCORING_USE_FACE_SCORE_ZOO_CACHE");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("FACE_SCORING_USE_FACE_SCORE_ZOO_CACHE");
bean.setDescrizione("FACE_SCORING_USE_FACE_SCORE_ZOO_CACHE");
bean.setFlgTipo(5L);
bean.setNota("ATTIVA LA CACHE SU FACE_SCORE_ZOO SU DB face_cache");
bean.save();
DBAdapter.logDebug(true, "FACE initParms: stop");
StatusMsg.deleteMsgByTag(ap, "INIT");
}
}
public static void main(String[] args) {
String hostname = "localhost:3308";
String db = "fr";
ApplParmFull ap = new ApplParmFull(new ApplParm(17, "//" + hostname + "/" + db, db, "root", "root", 1, 10, 300));
FaceRecognitionApi bean = new FaceRecognitionApi(ap, "acolzi", "pio");
FaceRecognitionApiResult resF = bean.__syncFaceDetectionMethods();
}
protected String getBase64BasicCredential() {
String encoding = getApiUser() + ":" + getApiUser();
return "Basic " + Base64.getEncoder().encodeToString(encoding.getBytes());
}
public ApplParmFull getApFull() {
return this.apFull;
}
public ApplParmFull getApFullCache() {
if (this.apFullCache == null && getApFull() != null) {
ApplParm apTemp = getApFull().getAp();
ApplParm apCache = new ApplParm(apTemp.getDbType(), apTemp.getDatabase() + "_cache", apTemp.getCatalog() + "_cache",
apTemp.getUser(), apTemp.getPassword(), apTemp.getInitialCons(), apTemp.getMaxCons(), apTemp.getTimeout());
this.apFullCache = new ApplParmFull(apCache);
}
return this.apFullCache;
}
public void setApFull(ApplParmFull apFull) {
this.apFull = apFull;
}
public Attivita getAttivita() {
if (this.attivita == null)
this.attivita = Attivita.getDefaultInstance(getApFull());
return this.attivita;
}
private String getApiEndpoint() {
if (isProduction())
return this.apFull.getParm("FACE_RECOGNITION_API_SERVER_PROD").getTesto();
return this.apFull.getParm("FACE_RECOGNITION_API_SERVER_DEV").getTesto();
}
private String getApiEndpointZoo() {
if (isProduction())
return this.apFull.getParm("FACE_RECOGNITION_API_SERVER_ZOO_PROD").getTesto();
return this.apFull.getParm("FACE_RECOGNITION_API_SERVER_ZOO_DEV").getTesto();
}
private String getApiEndpointScoringSelfie() {
if (isProduction())
return this.apFull.getParm("FACE_SCORING_SELFIE_API_SERVER_PROD").getTesto();
return this.apFull.getParm("FACE_SCORING_SELFIE_API_SERVER_DEV").getTesto();
}
public boolean isProduction() {
return !this.apFull.getParm("FACE_RECOGNITION_DEV").isTrue();
}
private String getApiFaceUser() {
return this.apFull.getParm("FACE_RECOGNITION_API_USER").getTesto();
}
private String getApiFacePwd() {
return this.apFull.getParm("FACE_RECOGNITION_API_PWD").getTesto();
}
public FaceRecognitionApiResult __detectFaces(String l_imageFileName, String l_md5, long l_flgFaceDetectionMethod, boolean detectNumbers, double confDetectLevel, boolean useOriginalPath) {
DBAdapter.printDebug(FaceRecognitionApi.debug, "FaceRecognitionApi --> detectFaces");
boolean debug = true;
if (l_flgFaceDetectionMethod == 20L)
return __detectFacesYnetApache(l_imageFileName, l_md5, confDetectLevel, useOriginalPath);
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
File l_imageFileNameFile = new File(l_imageFileName);
if (!l_imageFileNameFile.exists()) {
resER.setOk(false);
resER.setMsg("File " + l_imageFileName + " not found!");
return resER;
}
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(getApiEndpoint() + "detectFacesAndNumbers/");
DBAdapter.printDebug(debug, "detectFaces URI: " + getApiEndpoint() + "detectFacesAndNumbers/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
JsonObject jBody = new JsonObject();
JsonArray jRequest = new JsonArray();
JsonObject jRequestRow = new JsonObject();
JsonObject jImage = new JsonObject();
jRequestRow.addProperty("md5", l_md5);
if (!useOriginalPath) {
byte[] fileContent = FileUtils.readFileToByteArray(l_imageFileNameFile);
String encodedString = Base64.getEncoder().encodeToString(fileContent);
jImage.addProperty("content", encodedString);
} else {
jImage.addProperty("originalPath", l_imageFileName);
}
jRequestRow.add("image", (JsonElement)jImage);
if (l_flgFaceDetectionMethod > 0L) {
jRequestRow.addProperty("faceDetectionType", Long.valueOf(l_flgFaceDetectionMethod));
} else {
jRequestRow.addProperty("faceDetectionType", Long.valueOf(2L));
}
jRequestRow.addProperty("numbers", Boolean.valueOf(detectNumbers));
jRequest.add((JsonElement)jRequestRow);
jBody.add("requests", (JsonElement)jRequest);
DBAdapter.printDebug(debug, "detectFaces jdata: " + DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody), StandardCharsets.UTF_8);
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
System.out.println("\ncontent = " + content);
}
if (statusCode >= 400) {
resER.setOk(false);
resER.setMsg(content);
resER.setResult(content);
} else {
JsonObject jo = DBAdapter.tryParseJsonObject(content);
if (jo != null && jo.has("success") &&
jo.get("success").getAsBoolean()) {
DBAdapter.printDebug(debug, "Faces found: " + jo.get("msg").getAsString());
resER.setMsg("Faces found: " + jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
DBAdapter.printDebug(debug, "Error: " + jo.get("msg").getAsString());
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
} catch (Exception e) {
DBAdapter.printDebug(debug, e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
private String getApiUser() {
return (this.apiUser == null) ? getApiFaceUser() : this.apiUser.trim();
}
public void setApiUser(String apiUser) {
this.apiUser = apiUser;
}
private String getApiPwd() {
return (this.apiPwd == null) ? getApiFacePwd() : this.apiPwd.trim();
}
public void setApiPwd(String apiPwd) {
this.apiPwd = apiPwd;
}
public FaceRecognitionApiResult __recognize(long l_id_faceRecogizer, List<TrainingImage> trainingImages, boolean sendImage) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
boolean debug = false;
DBAdapter.printDebug(" FaceRecognitionApi --> recognize endopoint: " + getApiEndpoint() + "recognize/");
FaceRecognizer frzer = new FaceRecognizer(getApFull());
frzer.findByPrimaryKey(l_id_faceRecogizer);
if (frzer.getId_faceRecognizer() == 0L) {
resER.setMsg("Error: codice Face recognizer non trovato. ");
resER.setOk(false);
DBAdapter.printDebug(debug, " FaceRecognitionApi --> rError: codice Face recognizer non trovato: " + l_id_faceRecogizer);
} else {
resER = __recognize(frzer.getCodice(), trainingImages, sendImage);
}
return resER;
}
public FaceRecognitionApiResult __trainingStop(long l_id_faceRecognizer) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
try {
if (debug)
System.out.println("FaceRecognitionApi --> trainingStop");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(getApiEndpoint() + "trainingStop/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
FaceRecognizer frzer = new FaceRecognizer(getApFull());
frzer.findByPrimaryKey(l_id_faceRecognizer);
if (frzer.getId_faceRecognizer() == 0L) {
resER.setMsg("Error: codice Face recognizer non trovato.");
resER.setOk(false);
} else {
JsonObject jBody = new JsonObject();
jBody.addProperty("code", frzer.getCodice());
if (debug)
System.out.println(DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
System.out.println("\ncontent = " + content);
}
if (statusCode >= 400) {
resER.setOk(false);
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
resER.setMsg(DBAdapter.gsonToString(jo));
resER.setResult(jo);
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (jo.get("success").getAsBoolean()) {
resER.setMsg(jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public FaceRecognitionApiResult __trainingSendImages(long l_id_faceRecognizer, List<TrainingImage> trainingImages, boolean sendImage) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
boolean debug = false;
try {
if (debug)
System.out.println("FaceRecognitionApi --> trainingSendImages");
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)
.setSocketTimeout(300000)
.build();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
HttpPost request = new HttpPost(getApiEndpoint() + "trainingSendImages/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
FaceRecognizer frzer = new FaceRecognizer(getApFull());
frzer.findByPrimaryKey(l_id_faceRecognizer);
if (frzer.getId_faceRecognizer() == 0L) {
resER.setMsg("Error: codice Face recognizer non trovato.");
resER.setOk(false);
} else {
JsonObject jBody = new JsonObject();
jBody.addProperty("code", frzer.getCodice());
JsonArray jRequests = new JsonArray();
for (TrainingImage trainingImage : trainingImages) {
JsonObject jRequestRow = new JsonObject();
if (sendImage) {
JsonObject jImage = new JsonObject();
byte[] fileContent = FileUtils.readFileToByteArray(new File(trainingImage.getImageFileName()));
String encodedString = Base64.getEncoder().encodeToString(fileContent);
jImage.addProperty("content", encodedString);
jRequestRow.add("image", (JsonElement)jImage);
}
jRequestRow.addProperty("md5", trainingImage.getMd5());
jRequestRow.addProperty("label", Long.valueOf(trainingImage.getLabel()));
jRequests.add((JsonElement)jRequestRow);
}
jBody.add("requests", (JsonElement)jRequests);
if (debug)
System.out.println(DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
System.out.println("\ncontent = " + content);
}
if (statusCode >= 400) {
resER.setOk(false);
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
resER.setMsg(DBAdapter.gsonToString(jo));
resER.setResult(jo);
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (jo.get("success").getAsBoolean()) {
resER.setMsg(jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public FaceRecognitionApiResult __syncFaceDetectionMethods() {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
try {
if (debug)
System.out.println("FaceRecognitionApi --> _syncFaceDetectionMethods");
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(getApiEndpoint() + "syncFaceDetectionMethods/");
if (debug);
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
System.out.println("\ncontent = " + content);
}
if (statusCode >= 400) {
resER.setOk(false);
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
resER.setMsg(DBAdapter.gsonToString(jo));
resER.setResult(jo);
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (jo.get("success").getAsBoolean()) {
resER.setMsg(jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public FaceRecognitionApiResult __trainingRun(long l_id_faceRecognizer) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
try {
if (debug)
System.out.println("FaceRecognitionApi --> trainingRun");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(getApiEndpoint() + "trainingRun/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
FaceRecognizer frzer = new FaceRecognizer(getApFull());
frzer.findByPrimaryKey(l_id_faceRecognizer);
if (frzer.getId_faceRecognizer() == 0L) {
resER.setMsg("Error: codice Face recognizer non trovato.");
resER.setOk(false);
} else {
JsonObject jBody = new JsonObject();
jBody.addProperty("code", frzer.getCodice());
jBody.addProperty("recognizerType", Integer.valueOf(0));
if (debug)
System.out.println(DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
System.out.println("\ncontent = " + content);
}
if (statusCode >= 400) {
resER.setOk(false);
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
resER.setMsg(DBAdapter.gsonToString(jo));
resER.setResult(jo);
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (jo.get("success").getAsBoolean()) {
resER.setMsg(jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public FaceRecognitionApiResult __checkLabel(long l_label, String l_code) {
return __checkAddLabel(l_label, "", false, false, null, l_code);
}
public FaceRecognitionApiResult __updateLabel(long l_Newlabel, String l_md5, String l_code) {
return __checkAddLabel(l_Newlabel, l_md5, false, false, null, l_code);
}
public FaceRecognitionApiResult __reqImage(long l_label, String l_md5) {
return __checkAddLabel(l_label, l_md5, true, false, null, null);
}
public FaceRecognitionApiResult __addLabel(String l_md5, String imgFile, String l_code) {
return __checkAddLabel(0L, l_md5, false, true, imgFile, l_code);
}
private FaceRecognitionApiResult __checkAddLabel(long l_label, String l_md5, boolean reqImage, boolean addlabel, String imgFile, String l_code) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
try {
if (debug)
System.out.println("FaceRecognitionApi --> _checkLabel");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(getApiEndpoint() + "checkLabel/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
if (l_label == 0L && l_md5.isEmpty()) {
resER.setMsg("Error: label=0.");
resER.setOk(false);
} else {
JsonObject jBody = new JsonObject();
jBody.addProperty("label", Long.valueOf(l_label));
jBody.addProperty("md5", l_md5);
jBody.addProperty("reqImage", Boolean.valueOf(reqImage));
jBody.addProperty("addLabel", Boolean.valueOf(addlabel));
jBody.addProperty("code", l_code);
if (addlabel) {
JsonObject jImage = new JsonObject();
byte[] fileContent = FileUtils.readFileToByteArray(new File(imgFile));
String encodedString = Base64.getEncoder().encodeToString(fileContent);
jImage.addProperty("content", encodedString);
jBody.add("image", (JsonElement)jImage);
}
if (debug)
System.out.println(DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody), StandardCharsets.UTF_8);
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
System.out.println("\ncontent = " + content);
}
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (statusCode >= 400) {
resER.setOk(false);
resER.setMsg(DBAdapter.gsonToString(jo));
resER.setResult(jo);
} else if (jo.get("success").getAsBoolean()) {
resER.setMsg("Faces found: " + jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public FaceRecognitionApiResult __resetTraining(long l_id_faceRecognizer) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
try {
if (debug)
System.out.println("FaceRecognitionApi --> resetSession");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(getApiEndpoint() + "resetTraining/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
FaceRecognizer frzer = new FaceRecognizer(getApFull());
frzer.findByPrimaryKey(l_id_faceRecognizer);
if (frzer.getId_faceRecognizer() == 0L) {
resER.setMsg("Error: codice Face recognizer non trovato.");
resER.setOk(false);
} else {
JsonObject jBody = new JsonObject();
jBody.addProperty("code", frzer.getCodice());
if (debug)
System.out.println(DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
System.out.println("\ncontent = " + content);
}
if (statusCode >= 400) {
resER.setOk(false);
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
resER.setMsg(DBAdapter.gsonToString(jo));
resER.setResult(jo);
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (jo.get("success").getAsBoolean()) {
resER.setMsg(jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public FaceRecognitionApiResult __scoring(String jsonDataPath, String jsonResPath) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
boolean debug = false;
boolean debug2 = false;
boolean useCache = getApFull().getParm("FACE_SCORING_USE_FACE_SCORE_ZOO_CACHE").isTrue();
DBAdapter.printDebug((debug || debug2), "1 FaceRecognitionApi --> _scoring");
SaveScoreProcessor ssProcessor = SaveScoreProcessor.getInstance(getApFull(), 10);
try {
StringBuilder sbMsg = new StringBuilder();
int totScoreDb = 0;
JsonObject joRes = new JsonObject();
String jsonString = FileUtils.readFileToString(new File(jsonDataPath), StandardCharsets.UTF_8);
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
JsonObject target = jsonObject.getAsJsonObject("target");
JsonObject targetRes = target.deepCopy();
targetRes.remove("path");
joRes.add("target", (JsonElement)targetRes);
String targetMd5 = target.get("md5").getAsString();
JsonArray jResponses = new JsonArray();
JsonArray jResponseZoo = new JsonArray();
JsonArray queryArray = jsonObject.getAsJsonArray("query");
if (useCache) {
FaceScoreZoo fsz = new FaceScoreZoo(getApFullCache());
for (int i = queryArray.size() - 1; i >= 0; i--) {
JsonObject queryItem = queryArray.get(i).getAsJsonObject();
String queryMd5 = queryItem.get("md5").getAsString();
fsz.findByMd512(targetMd5, queryMd5);
if (fsz.getId_faceScoreZoo() > 0L) {
String queryType = queryItem.get("type").getAsString();
JsonObject jRow = new JsonObject();
jRow.addProperty("md5", queryMd5);
jRow.addProperty("score", Float.valueOf(fsz.getScore()));
jRow.addProperty("type", queryType);
jRow.addProperty("db", Boolean.valueOf(true));
jResponses.add((JsonElement)jRow);
queryArray.remove(i);
totScoreDb++;
}
}
DBAdapter.printDebug(debug, "2.1 FaceRecognitionApi --> _scoring removing query done .. tot db:" + totScoreDb);
}
if (queryArray.size() > 0) {
if (totScoreDb > 0) {
DBAdapter.printDebug(debug, "2.6 FaceRecognitionApi --> socrascrivo file dopo pulizia fa face_score");
jsonObject.addProperty("debug", "FaceRecognitionApiResult _scoring dopo pulizia da face_score");
FileWr fw = new FileWr(jsonDataPath, false);
fw.writeLine(DBAdapter.gsonToString(jsonObject));
fw.closeFile();
}
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(getApiEndpointZoo() + "scoring/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
JsonObject jBody = new JsonObject();
jBody.addProperty("json_data_path", jsonDataPath);
jBody.addProperty("json_res_path", jsonResPath);
DBAdapter.printDebug(debug, "3 invio a api rest....");
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
DBAdapter.printDebug(debug, "3.1 ritornato. statuscode: " + statusCode);
if (statusCode >= 400) {
resER.setOk(false);
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
sbMsg.append(DBAdapter.gsonToString(jo));
sbMsg.append("\n");
DBAdapter.printDebug(debug, "4 FaceRecognitionApi --> _scoring salto fase 3 per statuscode 400.");
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (jo.get("success").getAsBoolean()) {
sbMsg.append(jo.get("msg").getAsString());
sbMsg.append("\n");
resER.setOk(true);
DBAdapter.printDebug(debug, "4.1 salvo saveScoreResponse: useCache: " + useCache);
if (useCache)
ssProcessor.aggiungiInCoda(getApFullCache(), jo);
DBAdapter.printDebug(debug, "4.2 FaceRecognitionApi --> _scoring determino jResponseZoo.");
jResponseZoo = jo.getAsJsonArray("responses");
DBAdapter.printDebug(debug, "4.3 FaceRecognitionApi --> _scoring jResponseZoo fatto: " + jResponseZoo.size());
} else {
sbMsg.append("Error: " + jo.get("msg").getAsString());
sbMsg.append("\n");
resER.setOk(false);
DBAdapter.printDebug(debug, "5 FaceRecognitionApi --> _scoring salto fase 3 per success false.");
}
}
}
int totScoreZoo = 0;
int jResponsesSize = jResponses.size();
DBAdapter.printDebug(debug, "A.1 prima di unione response.. current response size: " + jResponsesSize);
if (jResponseZoo.size() > 0) {
totScoreZoo = jResponseZoo.size();
DBAdapter.printDebug(debug, "6 A.2 FaceRecognitionApi --> _scoring unisco response. jResponseZoo.len: " + totScoreZoo);
jResponses.addAll(jResponseZoo);
DBAdapter.printDebug(debug, "6 A.3 FaceRecognitionApi --> jResponsesSize finale: " + jResponses.size());
}
joRes.addProperty("success", Boolean.valueOf(true));
joRes.addProperty("msg", "Scoring: " +
sbMsg.toString() + "\n From DB:" + totScoreDb + " from zoo: " + totScoreZoo);
joRes.add("responses", (JsonElement)jResponses);
resER.setOk(true);
resER.setResult(joRes);
DBAdapter.printDebug(debug, "7 FaceRecognitionApi --> _scoring From DB:" + totScoreDb + " from zoo: " + totScoreZoo);
} catch (Exception e) {
DBAdapter.printDebug(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
DBAdapter.printDebug(debug, "*********** ERRORE MALFORMED JSON: " + jsonDataPath);
}
return resER;
}
private FaceRecognitionApiResult __detectFacesYnet(String l_imageFileName, String l_md5, double confDetectLevel) {
boolean debug = false;
DBAdapter.printDebug(debug, "1 ------------ FaceRecognitionApi NO COOKIE OKHTTP--> _detectFacesYnet");
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
File l_imageFileNameFile = new File(l_imageFileName);
if (!l_imageFileNameFile.exists()) {
resER.setOk(false);
resER.setMsg("File " + l_imageFileName + " not found!");
return resER;
}
DBAdapter.printDebug(debug, "2 FaceRecognitionApi --> _detectFacesYnet filename: " + l_imageFileName + " md5 .:" + l_md5);
try {
OkHttpClient client = new OkHttpClient.Builder().connectionPool(new ConnectionPool(0, 1L, TimeUnit.NANOSECONDS))
.followSslRedirects(false).build();
DBAdapter.printDebug(debug, "_detectFacesYnet URI: " + getApiEndpointZoo() + "detectFaces/");
JsonObject jBody = new JsonObject();
jBody.addProperty("conf_threshold", Double.valueOf(confDetectLevel));
JsonArray jRequest = new JsonArray();
JsonObject jRequestRow = new JsonObject();
JsonObject jImage = new JsonObject();
boolean usePath = getApFull().getParm("FACE_DETECTION_USE_PATH").isTrue();
if (usePath) {
jRequestRow.addProperty("path", l_imageFileName);
} else {
byte[] fileContent = FileUtils.readFileToByteArray(l_imageFileNameFile);
String encodedString = Base64.getEncoder().encodeToString(fileContent);
jImage.addProperty("content", encodedString);
jRequestRow.add("image", (JsonElement)jImage);
}
jRequestRow.addProperty("md5", l_md5);
jRequest.add((JsonElement)jRequestRow);
jBody.add("requests", (JsonElement)jRequest);
DBAdapter.printDebug(debug, "3 FaceRecognitionApi --> _detectFacesYnet filename: " + l_imageFileName + " md5 .:" + l_md5 + " jbody:\n" +
DBAdapter.gsonToString(jBody));
RequestBody body = RequestBody.create(new Gson().toJson((JsonElement)jBody), MediaType.parse("application/json"));
Request request = new Request.Builder().url(getApiEndpointZoo() + "detectFaces/")
.addHeader("Authorization", getBase64BasicCredential()).addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json").addHeader("Content-Language", "it-IT").addHeader("Cookie", "")
.post(body).build();
Response response = client.newCall(request).execute();
String content = response.body().string();
int statusCode = response.code();
DBAdapter.printDebug(debug, "4 FaceRecognitionApi --> _detectFacesYnet filename: " + l_imageFileName + " md5 .:" + l_md5 + " response:");
DBAdapter.printDebug(debug, "4Status Code: " + statusCode + " md5 .:" + l_md5);
DBAdapter.printDebug(debug, "\n4content = " + content + " md5 .:" + l_md5);
if (statusCode >= 400) {
resER.setOk(false);
resER.setMsg(content);
resER.setResult(content);
} else {
JsonObject jo = DBAdapter.tryParseJsonObject(content);
if (jo != null && jo.has("success") &&
jo.get("success").getAsBoolean()) {
resER.setMsg("Faces found: " + jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
} catch (Exception e) {
DBAdapter.printDebug(debug, e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public FaceRecognitionApiResult __scoringSelfie(long l_codGara, String l_imageFileName, String l_md5, boolean sendImage, boolean sendNotifiche) {
boolean debug = false;
DBAdapter.printDebug(debug, "1 ------------ FaceRecognitionApi NO COOKIE--> _scoringSelfie\ncodGara:" + l_codGara + "\nl_imageFileName: " + l_imageFileName + "\nl_md5" + l_md5);
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
File l_imageFileNameFile = new File(l_imageFileName);
if (!l_imageFileNameFile.exists()) {
DBAdapter.printDebug(debug, "1.1 ------------ FaceRecognitionApi NO COOKIE--> _scoringSelfie NIENTE FILE");
resER.setOk(false);
resER.setMsg("File " + l_imageFileName + " not found!");
return resER;
}
DBAdapter.printDebug(debug, "2 FaceRecognitionApi --> _scoringSelfie filename: " + l_imageFileName + " md5 .:" + l_md5);
try {
CloseableHttpClient client = new HttpClientConfig().createHttpClient();
HttpPost request = new HttpPost(getApiEndpointScoringSelfie() + "scoringSelfie/");
DBAdapter.printDebug(debug, "_scoringSelfie URI: " + getApiEndpointScoringSelfie() + "scoringSelfie/");
request.setHeader("User-Agent", "_scoringSelfie_" + DBAdapter.getTimeNameForFileUpload());
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
JsonObject jBody = new JsonObject();
jBody.addProperty("id_gara", Long.valueOf(l_codGara));
jBody.addProperty("sendNotifiche", Boolean.valueOf(sendNotifiche));
boolean usePath = false;
if (usePath) {
jBody.addProperty("originalPath", l_imageFileName);
} else if (sendImage) {
byte[] fileContent = FileUtils.readFileToByteArray(l_imageFileNameFile);
String encodedString = Base64.getEncoder().encodeToString(fileContent);
JsonObject jImage = new JsonObject();
jImage.addProperty("content", encodedString);
jBody.add("image", (JsonElement)jImage);
}
jBody.addProperty("md5", l_md5);
DBAdapter.printDebug(debug, "3 FaceRecognitionApi --> _scoringSelfie filename: " + l_imageFileName + " md5 .:" + l_md5 + " jbody:\n" +
DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
if (debug) {
String sessionid = "";
Header[] headers = closeableHttpResponse.getHeaders("Set-Cookie");
for (Header header : headers) {
if (header.getValue().contains("JSESSIONID"))
sessionid = header.getValue();
}
DBAdapter.printDebug(debug, "3.1 FaceRecognitionApi --> _scoringSelfie filename: " + l_imageFileName + " md5 .:" + l_md5 + " sessionid: " + sessionid);
}
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
DBAdapter.printDebug("4 FaceRecognitionApi --> _scoringSelfie filename: " + l_imageFileName + " md5 .:" + l_md5 + " response:");
DBAdapter.printDebug(debug, "4Status Code: " + statusCode + " md5 .:" + l_md5);
DBAdapter.printDebug(debug, "4content =\n" + content + "\nmd5 .:" + l_md5);
if (statusCode >= 400) {
resER.setOk(false);
resER.setMsg(content);
resER.setResult(content);
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
DBAdapter.printDebug(debug, "5 --> content:\n" + content + "\n---------");
if (jo.has("success") && jo.get("success").getAsBoolean()) {
resER.setMsg("Faces found: " + jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + content);
resER.setOk(false);
resER.setResult(jo);
}
}
} catch (Exception e) {
DBAdapter.printDebug(true, "5 " + e.getMessage());
DBAdapter.printDebug(true, "5 chiamata con errore: " + getApiEndpointScoringSelfie() + "scoringSelfie/");
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
DBAdapter.printDebug(debug, "5 fine errore: isOk: " + resER.isOk());
}
return resER;
}
public FaceRecognitionApiResult __recognize(String codeRecognizer, List<TrainingImage> trainingImages, boolean sendImage) {
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
boolean debug = true;
try {
if (debug)
System.out.println(
String.valueOf(DBAdapter.getNowTs()) + " FaceRecognitionApi --> recognize endpoint: " + String.valueOf(DBAdapter.getNowTs()) + "recognize/");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(getApiEndpoint() + "recognize/");
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
JsonObject jBody = new JsonObject();
jBody.addProperty("code", codeRecognizer);
JsonArray jRequests = new JsonArray();
if (debug)
DBAdapter.printDebug(debug, " FaceRecognitionApi _recognize --> preparo json body:");
for (TrainingImage trainingImage : trainingImages) {
JsonObject jRequestRow = new JsonObject();
if (sendImage) {
JsonObject jImage = new JsonObject();
byte[] fileContent = FileUtils.readFileToByteArray(new File(trainingImage.getImageFileName()));
String encodedString = Base64.getEncoder().encodeToString(fileContent);
jImage.addProperty("content", encodedString);
jRequestRow.add("image", (JsonElement)jImage);
}
jRequestRow.addProperty("md5", trainingImage.getMd5());
jRequestRow.addProperty("originalPath", trainingImage.getImageFileName());
jRequests.add((JsonElement)jRequestRow);
}
jBody.add("requests", (JsonElement)jRequests);
if (debug)
DBAdapter.printDebug(debug, " FaceRecognitionApi jbody:\n" + DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if (debug) {
System.out.println("Status Code: " + statusCode);
DBAdapter.printDebug(debug, " FaceRecognitionApi --> recognize \ncontent = " + content);
}
if (statusCode >= 400) {
resER.setOk(false);
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
resER.setMsg(DBAdapter.gsonToString(jo));
resER.setResult(jo);
} else {
JsonObject jo = JsonParser.parseString(content).getAsJsonObject();
if (jo.get("success").getAsBoolean()) {
resER.setMsg(jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
JsonObject jo = new JsonObject();
jo.addProperty("success", Boolean.valueOf(false));
jo.addProperty("msg", e.getMessage());
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
}
return resER;
}
private FaceRecognitionApiResult __detectFacesYnetApache(String l_imageFileName, String l_md5, double confDetectLevel, boolean usePath) {
boolean debug = true;
if (debug)
DBAdapter.printDebug(debug, "1 ------------ FaceRecognitionApi NO COOKIE--> _detectFacesYnet");
FaceRecognitionApiResult resER = new FaceRecognitionApiResult();
File l_imageFileNameFile = new File(l_imageFileName);
if (!l_imageFileNameFile.exists()) {
resER.setOk(false);
resER.setMsg("File " + l_imageFileName + " not found!");
return resER;
}
DBAdapter.printDebug(debug, "2 FaceRecognitionApi --> _detectFacesYnet filename: " + l_imageFileName + " md5 .:" + l_md5);
try {
CloseableHttpClient client = new HttpClientConfig().createHttpClient();
HttpPost request = new HttpPost(getApiEndpointZoo() + "detectFaces/");
DBAdapter.printDebug(debug, "_detectFacesYnet URI: " + getApiEndpointZoo() + "detectFaces/");
request.setHeader("User-Agent", "_detectFacesYnetApache_" + DBAdapter.getTimeNameForFileUpload());
request.setHeader("Authorization", getBase64BasicCredential());
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Content-Language", "it-IT");
JsonObject jBody = new JsonObject();
jBody.addProperty("conf_threshold", Double.valueOf(confDetectLevel));
JsonArray jRequest = new JsonArray();
JsonObject jRequestRow = new JsonObject();
JsonObject jImage = new JsonObject();
if (usePath) {
jRequestRow.addProperty("path", l_imageFileName);
} else {
byte[] fileContent = FileUtils.readFileToByteArray(l_imageFileNameFile);
String encodedString = Base64.getEncoder().encodeToString(fileContent);
jImage.addProperty("content", encodedString);
jRequestRow.add("image", (JsonElement)jImage);
}
jRequestRow.addProperty("md5", l_md5);
jRequest.add((JsonElement)jRequestRow);
jBody.add("requests", (JsonElement)jRequest);
DBAdapter.printDebug(debug, "3 FaceRecognitionApi --> _detectFacesYnet filename: " + l_imageFileName + " md5 .:" + l_md5 + " jbody:\n" +
DBAdapter.gsonToString(jBody));
StringEntity postingString = new StringEntity(new Gson().toJson((JsonElement)jBody));
request.setEntity((HttpEntity)postingString);
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
if (debug) {
String sessionid = "";
Header[] headers = closeableHttpResponse.getHeaders("Set-Cookie");
for (Header header : headers) {
if (header.getValue().contains("JSESSIONID"))
sessionid = header.getValue();
}
DBAdapter.printDebug(debug, "3.1 FaceRecognitionApi --> _detectFacesYnet filename: " + l_imageFileName + " md5 .:" + l_md5 + " sessionid: " + sessionid);
}
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
DBAdapter.printDebug(debug, "4 FaceRecognitionApi --> _detectFacesYnet filename: " + l_imageFileName + " md5 .:" + l_md5 + " response:");
DBAdapter.printDebug(debug, "4Status Code: " + statusCode + " md5 .:" + l_md5);
DBAdapter.printDebug(debug, "4content = " + content + " md5 .:" + l_md5);
if (statusCode >= 400) {
resER.setOk(false);
resER.setMsg(content);
resER.setResult(content);
DBAdapter.printDebug(debug, "5 status >400 content = " + content + " md5 .:" + l_md5);
} else {
JsonObject jo = DBAdapter.tryParseJsonObject(content);
if (jo != null && jo.has("success") &&
jo.get("success").getAsBoolean()) {
resER.setMsg("Faces found: " + jo.get("msg").getAsString());
resER.setOk(true);
resER.setResult(jo);
DBAdapter.printDebug(debug, "6 face found content = " + content + " md5 .:" + l_md5);
} else {
resER.setMsg("Error: " + jo.get("msg").getAsString());
resER.setOk(false);
resER.setResult(jo);
DBAdapter.printDebug(debug, "7 Error" + jo.get("msg").getAsString() + " md5 .:" + l_md5);
}
}
} catch (Exception e) {
DBAdapter.printDebug(debug, e.getMessage());
e.printStackTrace();
resER.setOk(false);
resER.setMsg(e.getMessage());
}
return resER;
}
public static final ResParm createFace(String fileSrc, String fileFace, long faceTopVx, long faceTopVy, long faceBottomVx, long faceBottomVy, int faceSizeRecognizer, int margin, boolean overwrite) {
boolean debug = false;
ResParm rp = new ResParm();
if (debug)
DBAdapter.printDebug(debug, "faceRecognitionApi.createFace ... " + fileSrc + " ---> " + fileFace);
int faceTopLeftX = 0;
int faceTopLeftY = 0;
int faceBottomRightX = 0;
int faceBottomRightY = 0;
int faceWidth = 0;
int faceHeight = 0;
try {
if (margin < 0)
margin = 10;
File faceImgFile = new File(fileFace);
String faceRicognitionSourceImg = fileSrc;
if (!faceImgFile.exists() || overwrite) {
if (faceImgFile.exists())
faceImgFile.delete();
BufferedImage sourceImage = ImageIO.read(new File(faceRicognitionSourceImg));
int sourceWidth = sourceImage.getWidth();
int sourceHeight = sourceImage.getHeight();
faceTopLeftX = (int)faceTopVx - margin;
if (faceTopLeftX < 0)
faceTopLeftX = 0;
faceTopLeftY = (int)faceTopVy - margin;
if (faceTopLeftY < 0)
faceTopLeftY = 0;
faceBottomRightX = (int)faceBottomVx + margin;
faceBottomRightY = (int)faceBottomVy + margin;
faceWidth = faceBottomRightX - faceTopLeftX;
faceHeight = faceBottomRightY - faceTopLeftY;
if (faceTopLeftX + faceWidth > sourceWidth)
faceWidth = sourceWidth - faceTopLeftX;
if (faceTopLeftY + faceHeight > sourceHeight)
faceHeight = sourceHeight - faceTopLeftY;
DoubleOperator percW = new DoubleOperator((double)sourceWidth, 4);
percW.divide((float)faceWidth);
percW.subtract(1);
percW.multiply(100);
DoubleOperator percH = new DoubleOperator((double)sourceHeight, 4);
percH.divide((float)faceHeight);
percH.subtract(1);
percH.multiply(100);
File targetDir = new File(DBAdapter.getPathFromFileName(fileFace));
if (!targetDir.exists())
targetDir.mkdirs();
if (percW.getResult() < 26.0D || percH.getResult() < 26.0D) {
DBAdapter.copyFile(faceRicognitionSourceImg, fileFace);
} else {
BufferedImage faceImage = sourceImage.getSubimage(faceTopLeftX, faceTopLeftY, faceWidth, faceHeight);
if (faceWidth != faceSizeRecognizer) {
Image resultImage = faceImage.getScaledInstance(faceSizeRecognizer, faceSizeRecognizer, 16);
BufferedImage biRescaled = ScaleImage.toBufferedImage(resultImage, 1);
ImageIO.write(biRescaled, "jpg", faceImgFile);
} else {
ImageIO.write(faceImage, "jpg", faceImgFile);
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("createFaceImage: " + faceTopLeftX + " " + faceTopLeftY + " " + faceWidth + " " + faceHeight);
}
return rp;
}
}