www in docker support

This commit is contained in:
MaddoScientisto 2026-04-22 18:41:37 +02:00
commit c227fce036
2145 changed files with 399596 additions and 58 deletions

View file

@ -0,0 +1,141 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.db.WcString;
import it.acxent.util.StringTokenizer;
import it.acxent.util.Vectumerator;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Face extends DBAdapter implements Serializable {
public static final String PATH_IMG_FACE = "_face/";
private static final long serialVersionUID = 1701107257097L;
private long id_face;
private String md5;
public Face(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public Face() {}
public void setId_face(long newId_face) {
this.id_face = newId_face;
}
public void setMd5(String newMd5) {
this.md5 = newMd5;
}
public long getId_face() {
return this.id_face;
}
public String getMd5() {
return (this.md5 == null) ? "" : this.md5.trim();
}
protected ResParm checkDeleteCascade() {
return new ResParm(true);
}
protected void deleteCascade() {}
public Vectumerator<Face> findByCR(FaceCR CR, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from FACE AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
if (!CR.getSearchTxt().trim().isEmpty()) {
StringTokenizer st = new StringTokenizer(CR.getSearchTxt().trim(), " ");
StringBuffer txt = new StringBuffer("(");
while (st.hasMoreTokens()) {
String token = st.nextToken();
txt.append("(A.Cognome like '%" + token + "%' or A.Nome like '%" + token + "%')");
if (st.hasMoreTokens())
txt.append(" and ");
}
txt.append(")");
wc.addWc(txt.toString());
}
if (!CR.getLabel().isEmpty())
wc.addWc("A.label ='" + CR.getLabel() + "'");
if (!CR.getMd5().isEmpty())
wc.addWc("A.md5 ='" + CR.getMd5() + "'");
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
return findRows(stmt, pageNumber, pageRows);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
public void xxfindByMd5Recognition(String l_md5) {
String s_Sql_Find = "select A.* from FACE AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.md5='" + l_md5 + "'");
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public String getFullFileName() {
return getPathFaceImg() + getPathFaceImg() + ".jpg";
}
public String getPathFaceImg() {
return getParm("path_img_base").getTesto() + "_face/" + getParm("path_img_base").getTesto();
}
public String getPathIdStepDir() {
if (getPathIdStep() <= 0L)
return "";
if (getId_face() == 0L)
System.out.println("getPathIdStepDir pio");
return "_" + getPathIdStep() * (getId_face() / getPathIdStep() + 1L) + "/";
}
public ResParm superSave() {
return save();
}
public void findByMd5(String l_md5) {
String s_Sql_Find = "select A.* from FACE AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.md5='" + l_md5 + "'");
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public void findByLabel(long l_label) {
String s_Sql_Find = "select A.* from FACE AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.id_face=" + l_label);
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
}

View file

@ -0,0 +1,42 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
public class FaceCR extends CRAdapter {
private long id_face;
private String md5;
private String label;
public FaceCR(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FaceCR() {}
public void setId_face(long newId_face) {
this.id_face = newId_face;
}
public void setMd5(String newMd5) {
this.md5 = newMd5;
}
public void setLabel(String newLabel) {
this.label = newLabel;
}
public long getId_face() {
return this.id_face;
}
public String getMd5() {
return (this.md5 == null) ? "" : this.md5.trim();
}
public String getLabel() {
return (this.label == null) ? "" : this.label.trim();
}
}

View file

@ -0,0 +1,196 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.db.WcString;
import it.acxent.util.StringTokenizer;
import it.acxent.util.Vectumerator;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class FaceFaceRecognizer extends DBAdapter implements Serializable {
private static final long serialVersionUID = 1724847547826L;
private long id_faceFaceRecognizer;
private long id_faceRecognizer;
private long id_face;
private long id_faceLabel;
private long flgLock;
private FaceRecognizer faceRecognizer;
private Face face;
private Face faceLabel;
public FaceFaceRecognizer(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FaceFaceRecognizer() {}
public void setId_faceFaceRecognizer(long newId_faceFaceRecognizer) {
this.id_faceFaceRecognizer = newId_faceFaceRecognizer;
}
public void setId_faceRecognizer(long newId_faceRecognizer) {
this.id_faceRecognizer = newId_faceRecognizer;
setFaceRecognizer(null);
}
public void setId_face(long newId_face) {
this.id_face = newId_face;
setFace(null);
}
public void setId_faceLabel(long newId_faceLabel) {
this.id_faceLabel = newId_faceLabel;
setFaceLabel(null);
}
public void setFlgLock(long newFlgLock) {
this.flgLock = newFlgLock;
}
public long getId_faceFaceRecognizer() {
return this.id_faceFaceRecognizer;
}
public long getId_faceRecognizer() {
return this.id_faceRecognizer;
}
public long getId_face() {
return this.id_face;
}
public long getId_faceLabel() {
return this.id_faceLabel;
}
public long getFlgLock() {
return this.flgLock;
}
public void setFaceRecognizer(FaceRecognizer newFaceRecognizer) {
this.faceRecognizer = newFaceRecognizer;
}
public FaceRecognizer getFaceRecognizer() {
this.faceRecognizer = (FaceRecognizer)getSecondaryObject(this.faceRecognizer, FaceRecognizer.class, getId_faceRecognizer());
return this.faceRecognizer;
}
public void setFace(Face newFace) {
this.face = newFace;
}
public Face getFace() {
this.face = (Face)getSecondaryObject(this.face, Face.class, getId_face());
return this.face;
}
public void setFaceLabel(Face newFaceLabel) {
this.faceLabel = newFaceLabel;
}
public Face getFaceLabel() {
this.faceLabel = (Face)getSecondaryObject(this.faceLabel, Face.class, getId_faceLabel());
return this.faceLabel;
}
protected ResParm checkDeleteCascade() {
return new ResParm(true);
}
protected void deleteCascade() {}
public Vectumerator<FaceFaceRecognizer> findByCR(FaceFaceRecognizerCR CR, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from FACE_FACE_RECOGNIZER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
if (!CR.getSearchTxt().trim().isEmpty()) {
StringTokenizer st = new StringTokenizer(CR.getSearchTxt().trim(), " ");
StringBuffer txt = new StringBuffer("(");
while (st.hasMoreTokens()) {
String token = st.nextToken();
txt.append("(A.Cognome like '%" + token + "%' or A.Nome like '%" + token + "%')");
if (st.hasMoreTokens())
txt.append(" and ");
}
txt.append(")");
wc.addWc(txt.toString());
}
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
return findRows(stmt, pageNumber, pageRows);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
public boolean isLabelPrincipale() {
if (getId_faceFaceRecognizer() > 0L && getId_face() == getId_faceLabel())
return true;
return false;
}
public ResParm resetTrainingByFaceRecognizer(long l_id_facerecognizer) {
return update("update FACE_FACE_RECOGNIZER SET id_facelabel=null where id_faceRecognizer=" + l_id_facerecognizer);
}
public void findByRecognizerLabel(long l_id_faceRecognizer, long l_label) {
String s_Sql_Find = "select A.* from FACE_FACE_RECOGNIZER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.id_faceRecognizer=" + l_id_faceRecognizer);
wc.addWc("A.id_face=" + l_label);
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public long getTotFaceByFaceRecognizer(long l_id_faceRecognizer) {
String s_Sql_Find = "select count(*) as tot from FACE_FACE_RECOGNIZER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.id_faceRecognizer=" + l_id_faceRecognizer);
wc.addWc("A.id_faceLabel>0");
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
return (long)getTots(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
return 0L;
}
}
public Vectumerator<FaceFaceRecognizer> findByFaceRecognizer(long l_id_faceRecognizer, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from FACE_FACE_RECOGNIZER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.id_faceRecognizer=" + l_id_faceRecognizer);
wc.addWc("A.id_faceLabel>0");
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
return findRows(stmt, pageNumber, pageRows);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
}

View file

@ -0,0 +1,106 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
public class FaceFaceRecognizerCR extends CRAdapter {
private static final long serialVersionUID = 3284264235323747301L;
private long id_faceFaceRecognizer;
private long id_faceRecognizer;
private long id_face;
private long id_faceLabel;
private long flgLock;
private FaceRecognizer faceRecognizer;
private Face face;
private Face faceLabel;
public FaceFaceRecognizerCR(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FaceFaceRecognizerCR() {}
public void setId_faceFaceRecognizer(long newId_faceFaceRecognizer) {
this.id_faceFaceRecognizer = newId_faceFaceRecognizer;
}
public void setId_faceRecognizer(long newId_faceRecognizer) {
this.id_faceRecognizer = newId_faceRecognizer;
setFaceRecognizer(null);
}
public void setId_face(long newId_face) {
this.id_face = newId_face;
setFace(null);
}
public void setId_faceLabel(long newId_faceLabel) {
this.id_faceLabel = newId_faceLabel;
setFaceLabel(null);
}
public void setFlgLock(long newFlgLock) {
this.flgLock = newFlgLock;
}
public long getId_faceFaceRecognizer() {
return this.id_faceFaceRecognizer;
}
public long getId_faceRecognizer() {
return this.id_faceRecognizer;
}
public long getId_face() {
return this.id_face;
}
public long getId_faceLabel() {
return this.id_faceLabel;
}
public long getFlgLock() {
return this.flgLock;
}
public void setFaceRecognizer(FaceRecognizer newFaceRecognizer) {
this.faceRecognizer = newFaceRecognizer;
}
public FaceRecognizer getFaceRecognizer() {
this.faceRecognizer = (FaceRecognizer)getSecondaryObject(this.faceRecognizer, FaceRecognizer.class,
getId_faceRecognizer());
return this.faceRecognizer;
}
public void setFace(Face newFace) {
this.face = newFace;
}
public Face getFace() {
this.face = (Face)getSecondaryObject(this.face, Face.class,
getId_face());
return this.face;
}
public void setFaceLabel(Face newFaceLabel) {
this.faceLabel = newFaceLabel;
}
public Face getFaceLabel() {
this.faceLabel = (Face)getSecondaryObject(this.faceLabel, Face.class,
getId_faceLabel());
return this.faceLabel;
}
}

View file

@ -0,0 +1,554 @@
package it.acxent.face.fr;
import it.acxent.common.StatusMsg;
import it.acxent.db.ApplParmFull;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.db.WcString;
import it.acxent.face.api.opencv.FaceRecognition;
import it.acxent.face.api.opencv.TrainingImage;
import it.acxent.util.Timer;
import it.acxent.util.Vectumerator;
import java.io.File;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfInt;
import org.opencv.face.EigenFaceRecognizer;
import org.opencv.face.FisherFaceRecognizer;
import org.opencv.face.LBPHFaceRecognizer;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class FaceRecognizer extends it.acxent.dm.FaceRecognizer implements Serializable {
class ThreadCaricaModelli extends Thread {
private FaceRecognizerCR CR;
private boolean useFile = false;
public ThreadCaricaModelli(FaceRecognizerCR l_CR, boolean l_usaFile) {
this.CR = l_CR;
this.useFile = l_usaFile;
if (!FaceRecognizer.threadCaricaModelli) {
FaceRecognizer.threadCaricaModelli = true;
start();
}
}
public void run() {
boolean debug = true;
String TAG_THREAD_MSG = " CACHE MODELS ";
Timer timerTotal = new Timer();
Timer timer = new Timer();
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " CACHE MODELS FaceRecognition.getInstance ");
FaceRecognition.getInstance(FaceRecognizer.this.getApFull());
timerTotal.start();
Vectumerator<FaceRecognizer> vec = FaceRecognizer.this.findByCR(this.CR, 0, 0);
int i = 0;
while (vec.hasMoreElements()) {
i++;
FaceRecognizer row = (FaceRecognizer)vec.nextElement();
if (this.useFile) {
if (row.isModelFileExist(0L)) {
timer.start();
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " CACHE MODELS Recognizer modelli files " + String.valueOf(DBAdapter.getNow()) + " ...." + row.getCodice());
StatusMsg.updateMsgByTag(FaceRecognizer.this.getApFull(), " CACHE MODELS ", " Recognizer " + row.getCodice() + " ...." + String.valueOf(timer.getTStart()));
row.precaricaModelliFiles();
timer.stop();
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " CACHE MODELS Recognizer modelli files " + String.valueOf(DBAdapter.getNow()) + " ...." + row.getCodice());
continue;
}
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " CACHE MODELS Recognizer modelli files " + String.valueOf(DBAdapter.getNow()) + " FILE NON TROVATO: " + row.getCodice());
continue;
}
if (row.getFlgDisabilita() == 0L) {
timer.start();
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " CACHE MODELS Recognizer by training " + String.valueOf(DBAdapter.getNow()) + " ...." + row.getCodice());
StatusMsg.updateMsgByTag(FaceRecognizer.this.getApFull(), " CACHE MODELS ", " Recognizer " + row.getCodice() + " ...." + String.valueOf(timer.getTStart()));
row.precaricaModelli();
timer.stop();
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " CACHE MODELS Recognizer by training " + String.valueOf(DBAdapter.getNow()) + " ...." + row.getCodice());
}
}
timerTotal.stop();
StatusMsg.updateMsgByTag(FaceRecognizer.this.getApFull(), " CACHE MODELS ", "FINE: " + timerTotal.getDurata());
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " CACHE MODELS FINE: " + String.valueOf(DBAdapter.getNow()));
DBAdapter.sleepInSecond(4);
StatusMsg.deleteMsgByTag(FaceRecognizer.this.getApFull(), " CACHE MODELS ");
FaceRecognizer.threadCaricaModelli = false;
}
}
private boolean debug = false;
private static final long serialVersionUID = 1701089773600L;
private long id_users;
private Users users;
private org.opencv.face.FaceRecognizer ocvFrLBPH;
private org.opencv.face.FaceRecognizer ocvFrEigen;
private org.opencv.face.FaceRecognizer ocvFrFish;
public static boolean threadCaricaModelli = false;
private long nTrainingImagesMax;
private long flgTrainingMode;
private long flgDisabilita;
private static final ConcurrentHashMap<String, org.opencv.face.FaceRecognizer> recognizerCache = new ConcurrentHashMap<>();
private static final ReentrantLock trainingLock = new ReentrantLock();
public static final String TAG_TRAINING_RUN = "TRAINING_RUN";
public FaceRecognizer(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FaceRecognizer() {}
public static synchronized ResParm addNTrainingImages(FaceRecognizer bean, long newNTrainingImages) {
bean.setNTrainingImages(bean.getNTrainingImages() + newNTrainingImages);
return bean.save();
}
protected ResParm checkDeleteCascade() {
return new ResParm(true);
}
protected void deleteCascade() {}
public Vectumerator<FaceRecognizer> findByCR(FaceRecognizerCR CR, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from FACE_RECOGNIZER AS A";
String s_Sql_Order = " order by A.descrizione";
WcString wc = new WcString();
if (CR.getId_faceRecognizer() > 0L)
wc.addWc("A.id_faceRecognizer=" + CR.getId_faceRecognizer());
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
return findRows(stmt, pageNumber, pageRows);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
public void findByCode(String l_code) {
String s_Sql_Find = "select A.* from FACE_RECOGNIZER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.codice='" + l_code + "'");
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public void findByFaceRecognizer(long l_id_faceRecognizer) {
String s_Sql_Find = "select A.* from FACE_FACE_RECOGNIZER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.id_faceRecognizer=" + l_id_faceRecognizer);
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public boolean isModelFileExist(long recognizerType) {
String fullFileName = getFullFileName(recognizerType);
return new File(fullFileName).exists();
}
@Deprecated
public org.opencv.face.FaceRecognizer getOcvFaceRecognizerWithLoadedModelOriginal(long recognizerType) {
String fullFileName = getFullFileName(recognizerType);
String cacheKey = "" + recognizerType + ":" + recognizerType;
if (recognizerCache.containsKey(cacheKey))
return recognizerCache.get(cacheKey);
return null;
}
public org.opencv.face.FaceRecognizer getOcvFaceRecognizerWithLoadedModel(long recognizerType) {
boolean debug = false;
String fullFileName = getFullFileName(recognizerType);
String cacheKey = "" + recognizerType + ":" + recognizerType;
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel key: " + cacheKey);
if (debug) {
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel elenco chiavi presenti!!");
for (String key : recognizerCache.keySet())
System.out.println("Key: " + key);
}
if (recognizerCache.containsKey(cacheKey)) {
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel key: " + cacheKey + " TROVATO!!!!");
return recognizerCache.get(cacheKey);
}
trainingLock.lock();
try {
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel key: " + cacheKey + " DENTRO IL LOCK!");
if (recognizerCache.containsKey(cacheKey)) {
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel key: " + cacheKey + " TROVATO ALL'INTERNO DEL LOCK!!!!");
return recognizerCache.get(cacheKey);
}
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel prima di trainingAndCreateModel...");
trainingAndCreateModel(false);
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel FATTO!!!");
if (recognizerCache.containsKey(cacheKey)) {
if (debug)
System.out.println(
String.valueOf(DBAdapter.getNowTs()) + " getOcvFaceRecognizerWithLoadedModel key: " + String.valueOf(DBAdapter.getNowTs()) + " TROVATO DOPO IL TRAINING");
return recognizerCache.get(cacheKey);
}
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel key: " + cacheKey + " NON TROVATO DOPO IL TRAINING!!!!");
throw new IllegalStateException("Impossibile creare il modello per il tipo di recognizer: " + recognizerType);
} finally {
trainingLock.unlock();
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModel key: " + cacheKey + " FUORI IL LOCK!");
}
}
public org.opencv.face.FaceRecognizer getOcvFaceRecognizerWithLoadedModelByFile(long recognizerType) {
boolean debug = true;
String fullFileName = getFullFileName(recognizerType);
String cacheKey = "" + recognizerType + ":" + recognizerType;
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile key: " + cacheKey);
if (debug) {
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile elenco chiavi presenti!!");
for (String key : recognizerCache.keySet())
System.out.println("Key: " + key);
}
if (recognizerCache.containsKey(cacheKey)) {
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile key: " + cacheKey + " TROVATO!!!!");
return recognizerCache.get(cacheKey);
}
if (!isModelFileExist(recognizerType)) {
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile key: " + cacheKey + " CACHE NON TROVATA E FILE MODELLO NON TROVATO! RITORNO NULL");
return null;
}
trainingLock.lock();
try {
if (debug)
System.out.println(
String.valueOf(DBAdapter.getNowTs()) + " getOcvFaceRecognizerWithLoadedModelByFile key: " + String.valueOf(DBAdapter.getNowTs()) + " DENTRO IL LOCK!");
if (recognizerCache.containsKey(cacheKey)) {
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile key: " + cacheKey + " TROVATO ALL'INTERNO DEL LOCK!!!!");
return recognizerCache.get(cacheKey);
}
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile prima di recognizer.read...");
org.opencv.face.FaceRecognizer recognizer = getOcvFaceRecognizerForModel(recognizerType);
try {
recognizer.read(fullFileName);
recognizerCache.put(cacheKey, recognizer);
} catch (Exception e) {
System.out.println(String.valueOf(DBAdapter.getNowTs()) + " getOcvFaceRecognizerWithLoadedModelByFile prima di recognizer.read ECCEZIONE! " + String.valueOf(DBAdapter.getNowTs()));
e.printStackTrace();
}
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile FATTO!!!");
if (recognizerCache.containsKey(cacheKey)) {
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile key: " + cacheKey + " TROVATO DOPO IL TRAINING");
return recognizerCache.get(cacheKey);
}
if (debug)
DBAdapter.printDebug(debug, " getOcvFaceRecognizerWithLoadedModelByFile key: " + cacheKey + " NON TROVATO DOPO IL TRAINING!!!!");
throw new IllegalStateException("Impossibile creare il modello per il tipo di recognizer: " + recognizerType);
} finally {
trainingLock.unlock();
if (debug)
System.out.println(
String.valueOf(DBAdapter.getNowTs()) + " getOcvFaceRecognizerWithLoadedModelByFile key: " + String.valueOf(DBAdapter.getNowTs()) + " FUORI IL LOCK!");
}
}
public void removeOcvFaceRecognizerWithLoadedModel(long recognizerType) {
String fullFileName = getFullFileName(recognizerType);
String cacheKey = "" + recognizerType + ":" + recognizerType;
if (recognizerCache.containsKey(cacheKey))
recognizerCache.remove(cacheKey);
}
public void removeAllOcvFaceRecognizerWithLoadedModel() {
synchronized (recognizerCache) {
recognizerCache.clear();
}
}
public void addOcvFaceRecognizerWithLoadedModel(long recognizerType, org.opencv.face.FaceRecognizer recognizer) {
String fullFileName = getFullFileName(recognizerType);
String cacheKey = "" + recognizerType + ":" + recognizerType;
if (recognizerCache.containsKey(cacheKey))
recognizerCache.remove(cacheKey);
DBAdapter.printDebug(this.debug, " addOcvFaceRecognizerWithLoadedModel key: " + cacheKey);
recognizerCache.put(cacheKey, recognizer);
}
public void precaricaModelliFiles() {
for (int i = 0; i < 1; i++)
getOcvFaceRecognizerWithLoadedModelByFile((long)i);
}
public void precaricaModelli() {
for (int i = 0; i < 1; i++)
getOcvFaceRecognizerWithLoadedModel((long)i);
}
private org.opencv.face.FaceRecognizer getOcvFaceRecognizerForModel(long recognizerType) {
if (recognizerType == 0L)
return (org.opencv.face.FaceRecognizer)LBPHFaceRecognizer.create();
if (recognizerType == 2L)
return (org.opencv.face.FaceRecognizer)EigenFaceRecognizer.create();
if (recognizerType == 1L)
return (org.opencv.face.FaceRecognizer)FisherFaceRecognizer.create();
return null;
}
public long getId_users() {
return this.id_users;
}
public Users getUsers() {
this.users = (Users)getSecondaryObject((DBAdapter)this.users, Users.class, getId_users());
return this.users;
}
public void setId_users(long newId_users) {
this.id_users = newId_users;
setUsers(null);
}
public void setUsers(Users newUsers) {
this.users = newUsers;
}
public String getFullFileName(long l_tipo) {
return getPathRecognizer() + getPathRecognizer() + "_" + getTipo(l_tipo);
}
public String getFullFileNameBin(long l_tipo) {
return getPathRecognizer() + getPathRecognizer() + "_" + getTipo(l_tipo) + ".dat";
}
public String getPathRecognizer() {
return getParm("path_img_base").getTesto() + "_recognizer/";
}
public ResParm trainingAndCreateModel(boolean saveModel) {
ResParm rp = new ResParm();
String TAG_THREAD_MSG = "TRAINING_RUN";
Timer timer = new Timer();
timer.start();
try {
boolean debug = true;
if (debug)
System.out.println(String.valueOf(DBAdapter.getNowTs()) + " TRAINING_RUN trainingAndCreateModel FaceRecognition.getInstance ");
FaceRecognition.getInstance(getApFull());
if (getId_faceRecognizer() == 0L) {
if (debug)
DBAdapter.printDebug(debug, " TRAINING_RUN trainingAndCreateModel NO getId_faceRecognizer ");
rp.setStatus(false);
rp.setMsg("Errore! FaceRecognizer nullo !!");
} else {
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "START TRAINING FOR: " + getCodice());
if (debug)
DBAdapter.printDebug(debug, " TRAINING_RUN START TRAINING FOR: " + getCodice());
int NUM_IMMAGINI_MAX = (int)getNTrainingImagesMax();
int totFotoElaborate = 0;
FaceFaceRecognizer faceFR = new FaceFaceRecognizer(getApFull());
long totRecord = faceFR.getTotFaceByFaceRecognizer(getId_faceRecognizer());
if (debug)
DBAdapter.printDebug(debug, " TRAINING_RUN totrecordfacebyfacerec: " + totRecord);
int j = 0;
List<TrainingImage> imageFilenames = new ArrayList<>();
Vectumerator<FaceFaceRecognizer> vec = faceFR.findByFaceRecognizer(getId_faceRecognizer(), 1, NUM_IMMAGINI_MAX);
while (vec.hasMoreElements()) {
j++;
FaceFaceRecognizer row = (FaceFaceRecognizer)vec.nextElement();
imageFilenames.add(new TrainingImage(row.getFace().getFullFileName(), (int)row.getId_faceLabel()));
if (j % 10 == 0)
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "(MAX: " + NUM_IMMAGINI_MAX + ") Preparing images for model: " + j + "/" + totRecord);
}
totFotoElaborate = j;
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "Training create for " + totFotoElaborate + "/" + totRecord + " ... FR CODE: " +
getCodice() + " .... ");
if (debug)
DBAdapter.printDebug(debug, " TRAINING_RUN trainingCreate --> trainingcreate");
rp = trainingCreate(imageFilenames, totFotoElaborate);
File path = new File(getPathRecognizer());
if (!path.exists())
path.mkdirs();
for (int i = 0; i < 1; i++) {
if (debug)
DBAdapter.printDebug(debug, " TRAINING_RUN trainingAndCreateModel salvo modello: " +
getFullFileName((long)i));
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "Saving " + getFullFileName((long)i) + " " + totFotoElaborate + "/" + totRecord + " ... FR CODE: " +
getCodice() + " .... ");
if (saveModel) {
getOcvFaceRecognizer((long)i).save(getFullFileName((long)i));
} else {
File theFile = new File(getFullFileName((long)i));
if (theFile.exists())
theFile.delete();
}
if (debug)
DBAdapter.printDebug(debug, " TRAINING_RUN trainingAndCreateModel metto in CACHE....: " +
getFullFileName((long)i));
addOcvFaceRecognizerWithLoadedModel((long)i, getOcvFaceRecognizer((long)i));
}
timer.stop();
setTsStart(timer.getTStart());
setTsStop(timer.getTStop());
setNTrainingImages((long)totFotoElaborate);
rp.append(save());
}
} catch (Exception e) {
e.printStackTrace();
rp.setStatus(false);
rp.setException(e);
if (this.debug)
DBAdapter.printDebug(this.debug, " TRAINING_RUN trainingAndCreateModel ECCEZIONE!!!! " + e.getMessage());
}
if (this.debug)
System.out.println(
String.valueOf(DBAdapter.getNowTs()) + " TRAINING_RUN FINITO MODELLO " + String.valueOf(DBAdapter.getNowTs()) + " DURATA: " + getCodice());
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "FINITO MODELLO " + getCodice() + " DURATA: " + timer.getDurata());
DBAdapter.sleepInSecond(5);
StatusMsg.deleteMsgByTag(getApFull(), "TRAINING_RUN");
return rp;
}
private ResParm trainingCreate(List<TrainingImage> trainingImages, int counter) {
ResParm rp = new ResParm();
try {
boolean debug = true;
int j = 0;
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + "trainingCreate " + String.valueOf(DBAdapter.getNow()) + " immagini. counterStart: " + trainingImages.size());
if (trainingImages.size() > 0) {
Mat labels = new Mat(trainingImages.size(), 1, CvType.CV_32SC1);
MatOfInt labelsMat = new MatOfInt();
List<Mat> trainingImagesMat = new ArrayList<>();
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + "train: ciclo trainingImages. size: " + String.valueOf(DBAdapter.getNow()));
for (TrainingImage trainingImage : trainingImages) {
File imageFile = new File(trainingImage.getImageFileName());
Mat image = Imgcodecs.imread(imageFile.getAbsolutePath());
Mat grayImage = new Mat();
Imgproc.cvtColor(image, grayImage, 6);
trainingImagesMat.add(grayImage);
labels.put(j, 0, new double[] { (double)trainingImage.getLabel() });
j++;
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " train: " + String.valueOf(DBAdapter.getNow()) + " count...:" + trainingImage.getImageFileName() + "/" + j + " label: " + counter);
}
labels.convertTo((Mat)labelsMat, CvType.CV_32SC1);
for (int i = 0; i < 1; i++) {
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " addestramento per modello n.: " + String.valueOf(DBAdapter.getNow()) + " ...");
getOcvFaceRecognizer((long)i).train(trainingImagesMat, labels);
if (debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " addestramento per modello n.: " + String.valueOf(DBAdapter.getNow()) + " FATTO!");
}
}
} catch (Exception e) {
e.printStackTrace();
rp.setStatus(false);
rp.setException(e);
if (this.debug)
System.out.println(String.valueOf(DBAdapter.getNow()) + " trainingCreate ECCEZIONE!!!! " + String.valueOf(DBAdapter.getNow()));
}
return rp;
}
public ResParm resetTraining() {
FaceFaceRecognizer ffr = new FaceFaceRecognizer(getApFull());
return ffr.resetTrainingByFaceRecognizer(getId_faceRecognizer());
}
private org.opencv.face.FaceRecognizer getOcvFaceRecognizer(long l_type) {
if (l_type == 0L) {
if (this.ocvFrLBPH == null)
this.ocvFrLBPH = (org.opencv.face.FaceRecognizer)LBPHFaceRecognizer.create();
return this.ocvFrLBPH;
}
if (l_type == 2L) {
if (this.ocvFrEigen == null)
this.ocvFrEigen = (org.opencv.face.FaceRecognizer)EigenFaceRecognizer.create();
return this.ocvFrEigen;
}
if (l_type == 1L) {
if (this.ocvFrFish == null)
this.ocvFrFish = (org.opencv.face.FaceRecognizer)FisherFaceRecognizer.create();
return this.ocvFrFish;
}
return null;
}
public final ResParm startCaricaModelli(FaceRecognizerCR l_CR, boolean useFile) {
if (!threadCaricaModelli) {
new ThreadCaricaModelli(l_CR, useFile);
return new ResParm(true, "Thread threadCaricaModelli avviato. usefile: " + useFile);
}
return new ResParm(false, "ATTENZIONE!! Thread in esecuzione!!!");
}
public long getNTrainingImagesMax() {
return (this.nTrainingImagesMax <= 0L) ? 10000L : this.nTrainingImagesMax;
}
public void setNTrainingImagesMax(long nTrainingImagesMax) {
this.nTrainingImagesMax = nTrainingImagesMax;
}
public long getFlgTrainingMode() {
return this.flgTrainingMode;
}
public void setFlgTrainingMode(long flgTrainingMode) {
this.flgTrainingMode = flgTrainingMode;
}
public long getFlgDisabilita() {
return this.flgDisabilita;
}
public void setFlgDisabilita(long flgDisabilita) {
this.flgDisabilita = flgDisabilita;
}
}

View file

@ -0,0 +1,116 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
import it.acxent.db.DBAdapter;
import java.sql.Date;
public class FaceRecognizerCR extends CRAdapter {
private long id_faceRecognizer;
private String flgTIpo;
private String codice;
private String descrizione;
private String sessionId;
private String fileName;
private long nTrainingImages;
private Date dataTraining;
private long id_users;
private Users users;
public FaceRecognizerCR(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FaceRecognizerCR() {}
public void setId_faceRecognizer(long newId_faceRecognizer) {
this.id_faceRecognizer = newId_faceRecognizer;
}
public void setFlgTIpo(String newFlgTIpo) {
this.flgTIpo = newFlgTIpo;
}
public void setCodice(String newCodice) {
this.codice = newCodice;
}
public void setDescrizione(String newDescrizione) {
this.descrizione = newDescrizione;
}
public void setSessionId(String newSessionId) {
this.sessionId = newSessionId;
}
public void setFileName(String newFileName) {
this.fileName = newFileName;
}
public void setNTrainingImages(long newNTrainingImages) {
this.nTrainingImages = newNTrainingImages;
}
public void setDataTraining(Date newDataTraining) {
this.dataTraining = newDataTraining;
}
public long getId_faceRecognizer() {
return this.id_faceRecognizer;
}
public String getFlgTIpo() {
return (this.flgTIpo == null) ? "" : this.flgTIpo.trim();
}
public String getCodice() {
return (this.codice == null) ? "" : this.codice.trim();
}
public String getDescrizione() {
return (this.descrizione == null) ? "" : this.descrizione.trim();
}
public String getSessionId() {
return (this.sessionId == null) ? "" : this.sessionId.trim();
}
public String getFileName() {
return (this.fileName == null) ? "" : this.fileName.trim();
}
public long getNTrainingImages() {
return this.nTrainingImages;
}
public Date getDataTraining() {
return this.dataTraining;
}
public long getId_users() {
return this.id_users;
}
public Users getUsers() {
this.users = (Users)getSecondaryObject((DBAdapter)this.users, Users.class, getId_users());
return this.users;
}
public void setId_users(long newId_users) {
this.id_users = newId_users;
setUsers(null);
}
public void setUsers(Users newUsers) {
this.users = newUsers;
}
}

View file

@ -0,0 +1,155 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.db.WcString;
import it.acxent.util.Vectumerator;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Facer extends DBAdapter implements Serializable {
private static final long serialVersionUID = 1730299088138L;
private long id_facer;
private long id_faceRecognizer;
private String md5;
private long label;
private String fileAlternativo;
private double confidence;
private FaceRecognizer faceRecognizer;
public static final String PATH_IMG_FACE_RECOGNITION = "_faceRecognition/";
public Facer(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public Facer() {}
public void setId_facer(long newId_facer) {
this.id_facer = newId_facer;
}
public void setId_faceRecognizer(long newId_faceRecognizer) {
this.id_faceRecognizer = newId_faceRecognizer;
setFaceRecognizer(null);
}
public void setMd5(String newMd5) {
this.md5 = newMd5;
}
public void setLabel(long newLabel) {
this.label = newLabel;
}
public long getId_facer() {
return this.id_facer;
}
public long getId_faceRecognizer() {
return this.id_faceRecognizer;
}
public String getMd5() {
return (this.md5 == null) ? "" : this.md5.trim();
}
public long getLabel() {
return this.label;
}
public void setFaceRecognizer(FaceRecognizer newFaceRecognizer) {
this.faceRecognizer = newFaceRecognizer;
}
public FaceRecognizer getFaceRecognizer() {
this.faceRecognizer = (FaceRecognizer)getSecondaryObject(this.faceRecognizer, FaceRecognizer.class, getId_faceRecognizer());
return this.faceRecognizer;
}
protected ResParm checkDeleteCascade() {
return new ResParm(true);
}
protected void deleteCascade() {}
public Vectumerator<Facer> findByCR(FacerCR CR, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from FACER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
if (CR.getLabel() > 0L)
wc.addWc("A.label =" + CR.getLabel());
if (!CR.getMd5().isEmpty())
wc.addWc("A.md5 ='" + CR.getMd5() + "'");
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
return findRows(stmt, pageNumber, pageRows);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
public String getFullFileName() {
return getPathFaceImg() + getPathFaceImg() + ".jpg";
}
public void findByMd5Recognizer(String l_md5, long l_id_faceRecognizer) {
String s_Sql_Find = "select A.* from FACER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.md5='" + l_md5 + "'");
wc.addWc("A.id_faceRecognizer=" + l_id_faceRecognizer);
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public void findByLabel(long l_label) {
String s_Sql_Find = "select A.* from FACER AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.label=" + l_label);
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public String getPathFaceImg() {
return getParm("path_img_base").getTesto() + "_faceRecognition/" + getParm("path_img_base").getTesto();
}
public String getFileAlternativo() {
return (this.fileAlternativo == null) ? "" : this.fileAlternativo.trim();
}
public void setFileAlternativo(String fileAlternativo) {
this.fileAlternativo = fileAlternativo;
}
public double getConfidence() {
return this.confidence;
}
public void setConfidence(double confidence) {
this.confidence = confidence;
}
}

View file

@ -0,0 +1,66 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
public class FacerCR extends CRAdapter {
private long id_facer;
private long id_faceRecognizer;
private String md5;
private long label;
private FaceRecognizer faceRecognizer;
public FacerCR(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FacerCR() {}
public void setId_facer(long newId_facer) {
this.id_facer = newId_facer;
}
public void setId_faceRecognizer(long newId_faceRecognizer) {
this.id_faceRecognizer = newId_faceRecognizer;
setFaceRecognizer(null);
}
public void setMd5(String newMd5) {
this.md5 = newMd5;
}
public void setLabel(long newLabel) {
this.label = newLabel;
}
public long getId_facer() {
return this.id_facer;
}
public long getId_faceRecognizer() {
return this.id_faceRecognizer;
}
public String getMd5() {
return (this.md5 == null) ? "" : this.md5.trim();
}
public long getLabel() {
return this.label;
}
public void setFaceRecognizer(FaceRecognizer newFaceRecognizer) {
this.faceRecognizer = newFaceRecognizer;
}
public FaceRecognizer getFaceRecognizer() {
this.faceRecognizer = (FaceRecognizer)getSecondaryObject(this.faceRecognizer, FaceRecognizer.class,
getId_faceRecognizer());
return this.faceRecognizer;
}
}

View file

@ -0,0 +1,228 @@
package it.acxent.face.fr;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import it.acxent.db.ApplParmFull;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.db.WcString;
import it.acxent.dm.FaceDetectionMethod;
import it.acxent.util.Vectumerator;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class FotoRequest extends DBAdapter implements Serializable {
private static final long serialVersionUID = 1700680369881L;
public static final long REQUEST_TYPE_DETECT_ERROR = -1L;
public static final long REQUEST_TYPE_DETECT_ALL = 0L;
public static final long REQUEST_TYPE_DETECT_FACE = 1L;
public static final long REQUEST_TYPE_DETECT_NUMBERS = 3L;
private long id_fotoRequest;
private long id_users;
private String md5;
private String json;
private long nRichieste;
private FaceDetectionMethod faceDetectionMethod;
private Users users;
private long faceDetectionMethodCode;
private long flgRequestType;
public FotoRequest(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FotoRequest() {}
public static final String getRequestType(long l_flgRequestType) {
if (l_flgRequestType == 0L)
return "Completa";
if (l_flgRequestType == 1L)
return "Completa";
if (l_flgRequestType == 3L)
return "Completa";
return "";
}
public void setId_fotoRequest(long newId_fotoRequest) {
this.id_fotoRequest = newId_fotoRequest;
}
public void setId_users(long newId_users) {
this.id_users = newId_users;
setUsers(null);
}
public void setMd5(String newMd5) {
this.md5 = newMd5;
}
public void setJson(String newJsonCompleto) {
this.json = newJsonCompleto;
}
public void setNRichieste(long newNRichieste) {
this.nRichieste = newNRichieste;
}
public long getId_fotoRequest() {
return this.id_fotoRequest;
}
public long getId_users() {
return this.id_users;
}
public String getMd5() {
return (this.md5 == null) ? "" : this.md5.trim();
}
public String getJson() {
if (hasDetectFacesResponseFaces(this.json))
return this.json.trim();
return "";
}
public long getNRichieste() {
return this.nRichieste;
}
public void setUsers(Users newUsers) {
this.users = newUsers;
}
public Users getUsers() {
this.users = (Users)getSecondaryObject((DBAdapter)this.users, Users.class, getId_users());
return this.users;
}
protected ResParm checkDeleteCascade() {
return new ResParm(true);
}
protected void deleteCascade() {}
public Vectumerator<FotoRequest> findByCR(FotoRequestCR CR, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from FOTO_REQUEST AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
if (CR.getId_users() > 0L)
wc.addWc("A.id_users=" + CR.getId_users());
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
return findRows(stmt, pageNumber, pageRows);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
public Vectumerator<FotoRequest> findByUsers(long l_id_users, int pageNumber, int pageRows) {
FotoRequestCR CR = new FotoRequestCR();
CR.setId_users(l_id_users);
return findByCR(CR, pageNumber, pageRows);
}
public void findByUserMd5DetectionmethodRequesttype(long l_id_user, String l_md5, long l_flgFaceDetectionMethod, long l_flgRequestType) {
String s_Sql_Find = "select A.* from FOTO_REQUEST AS A";
String s_Sql_Order = "";
WcString wc = new WcString();
wc.addWc("A.id_users=" + l_id_user);
wc.addWc("A.md5='" + l_md5 + "'");
if (l_flgRequestType == 0L) {
wc.addWc("(A.flgRequestType is null || A.flgRequestType=0) ");
} else {
wc.addWc("A.flgRequestType=" + l_flgRequestType);
}
if (l_flgFaceDetectionMethod == 0L) {
wc.addWc("(A.faceDetectionMethodCode is null || A.faceDetectionMethodCode=0) ");
} else {
wc.addWc("A.faceDetectionMethodCode=" + l_flgFaceDetectionMethod);
}
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find + wc.toString());
findFirstRecord(stmt);
} catch (SQLException e) {
removeCPConnection();
handleDebug(e);
}
}
public static boolean hasDetectFacesResponseFaces(String jsonString) {
if (jsonString == null || jsonString.isEmpty())
return false;
try {
JsonElement parsed = JsonParser.parseString(jsonString);
if (!parsed.isJsonObject())
return false;
JsonObject json = parsed.getAsJsonObject();
if (json.has("responses")) {
JsonArray responses = json.getAsJsonArray("responses");
if (responses.size() > 0) {
JsonObject response = responses.get(0).getAsJsonObject().getAsJsonObject("response");
JsonArray annotations = response.getAsJsonArray("faceAnnotations");
return (annotations != null && annotations.size() > 0);
}
}
} catch (JsonSyntaxException e) {
return false;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void setJson(long l_flgRequestType, String l_json) {
setFlgRequestType(l_flgRequestType);
setJson(l_json);
}
public void addRichiesta() {
setNRichieste(getNRichieste() + 1L);
}
public final FaceDetectionMethod getFaceDetectionMethod() {
if (this.faceDetectionMethod == null && getFaceDetectionMethodCode() >= 0L) {
this.faceDetectionMethod = new FaceDetectionMethod(getApFull());
this.faceDetectionMethod.findByCodice(getFaceDetectionMethodCode());
}
return (this.faceDetectionMethod == null) ? new FaceDetectionMethod(getApFull()) : this.faceDetectionMethod;
}
public long getFaceDetectionMethodCode() {
return this.faceDetectionMethodCode;
}
public void setFaceDetectionMethodCode(long flgFaceDetectionMethod) {
this.faceDetectionMethodCode = flgFaceDetectionMethod;
}
public long getFlgRequestType() {
return this.flgRequestType;
}
public void setFlgRequestType(long flgRequestType) {
this.flgRequestType = flgRequestType;
}
public void setFaceDetectionMethod(FaceDetectionMethod faceDetectionMethod) {
this.faceDetectionMethod = faceDetectionMethod;
}
}

View file

@ -0,0 +1,97 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
import it.acxent.db.DBAdapter;
public class FotoRequestCR extends CRAdapter {
private long id_fotoRequest;
private long id_users;
private String md5;
private String jsonCompleto;
private String jsonNumeri;
private String jsonFace;
private long nRichieste;
private Users users;
public FotoRequestCR(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public FotoRequestCR() {}
public void setId_fotoRequest(long newId_fotoRequest) {
this.id_fotoRequest = newId_fotoRequest;
}
public void setId_users(long newId_users) {
this.id_users = newId_users;
setUsers(null);
}
public void setMd5(String newMd5) {
this.md5 = newMd5;
}
public void setJsonCompleto(String newJsonCompleto) {
this.jsonCompleto = newJsonCompleto;
}
public void setJsonNumeri(String newJsonNumeri) {
this.jsonNumeri = newJsonNumeri;
}
public void setJsonFace(String newJsonFace) {
this.jsonFace = newJsonFace;
}
public void setNRichieste(long newNRichieste) {
this.nRichieste = newNRichieste;
}
public long getId_fotoRequest() {
return this.id_fotoRequest;
}
public long getId_users() {
return this.id_users;
}
public String getMd5() {
return (this.md5 == null) ? "" : this.md5.trim();
}
public String getJsonCompleto() {
return (this.jsonCompleto == null) ? "" : this.jsonCompleto.trim();
}
public String getJsonNumeri() {
return (this.jsonNumeri == null) ? "" : this.jsonNumeri.trim();
}
public String getJsonFace() {
return (this.jsonFace == null) ? "" : this.jsonFace.trim();
}
public long getNRichieste() {
return this.nRichieste;
}
public void setUsers(Users newUsers) {
this.users = newUsers;
}
public Users getUsers() {
this.users = (Users)getSecondaryObject((DBAdapter)this.users, Users.class,
getId_users());
return this.users;
}
}

View file

@ -0,0 +1,73 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParm;
import it.acxent.db.ApplParmFull;
import it.acxent.db.DBAdapter;
import it.acxent.util.DbConsole;
import java.sql.Time;
import java.util.StringTokenizer;
public class Test extends DbConsole {
public static void main(String[] args) {
Test bean = new Test();
bean.doImport();
System.exit(0);
}
public void doImport() {
String db = "fr";
int i = 0;
int se1 = 10;
int se2 = 100;
String hostname = "localhost:3308";
String temp = getCi().readLine("Hostname (" + hostname + "):");
if (!temp.isEmpty())
hostname = temp;
temp = getCi().readLine("Database name (" + db + "):");
if (!temp.isEmpty())
db = temp;
System.out.println("Db: " + db);
ApplParmFull apTarget = new ApplParmFull(new ApplParm(3, "//" + hostname + "/" + db, "root", "root", 1, 10, 300));
apTarget.setDebug(false);
StringBuffer msg = new StringBuffer();
try {
FotoRequest bean = new FotoRequest(apTarget);
bean.findByPrimaryKey(28402L);
String json = bean.getJson();
System.out.println(json.length());
System.out.println(json);
String jc = DBAdapter.compressText(json);
System.out.println(jc.length());
String ja = DBAdapter.decompressText(jc);
System.out.println(ja.length());
System.out.println(ja);
bean.save();
} catch (Exception e) {
e.printStackTrace();
}
}
protected Time getTimeFromString(String theTime) {
try {
if (theTime.matches("[0-9][0-9][0-9][0-9]"))
theTime = theTime.substring(0, 2) + ":" + theTime.substring(0, 2);
if (theTime.matches("[0-9]{1,2}+:[0-9]{1,2}+")) {
StringTokenizer st = new StringTokenizer(theTime, ":");
int hour = Integer.parseInt(st.nextToken());
int min = Integer.parseInt(st.nextToken());
int sec = st.hasMoreElements() ? Integer.parseInt(st.nextToken()) : 0;
return new Time((long)((hour - 1) * 3600000 + min * 60000 + sec * 1000));
}
if (theTime.matches("[0-9]{1,2}+:[0-9]{1,2}+:[0-9]{1,2}+")) {
StringTokenizer st = new StringTokenizer(theTime, ":");
int hour = Integer.parseInt(st.nextToken());
int min = Integer.parseInt(st.nextToken());
int sec = st.hasMoreElements() ? Integer.parseInt(st.nextToken()) : 0;
return new Time((long)((hour - 1) * 3600000 + min * 60000 + sec * 1000));
}
return null;
} catch (Exception e) {
return null;
}
}
}

View file

@ -0,0 +1,162 @@
package it.acxent.face.fr;
import it.acxent.common.Parm;
import it.acxent.db.ApplParmFull;
import it.acxent.db.WcString;
import it.acxent.face.api.vision.GoogleVisionApi;
import it.acxent.util.StringTokenizer;
import it.acxent.util.Vectumerator;
import java.io.File;
import java.sql.PreparedStatement;
public class Users extends it.acxent.anag.Users {
public Users() {}
public Users(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public void initApplicationParms(ApplParmFull ap) {
if (ap != null) {
super.initApplicationParms(ap);
String l_tipoParm = "";
Parm bean = new Parm(ap);
l_tipoParm = "FACE-FR";
bean.findByCodice("path_opencv_lib");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("path_opencv_lib");
bean.setDescrizione("path_opencv_lib");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/usr/local/Cellar/opencv/4.8.1_1/share/java/opencv4/libopencv_java481.dylib");
bean.setNota("PERCORSO LIBRERIA NATIVA OPENCV<BR>MAC: /usr/local/Cellar/opencv/4.8.1_1/share/java/opencv4/libopencv_java481.dylib<br>ubuntu: /home/ocv/build/lib/libopencv_java480.so");
bean.save();
bean.findByCodice("path_img_base");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("path_img_base");
bean.setDescrizione("path_img_base");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/Users/acolzi/Downloads/_ocv/img/");
bean.setNota("PERCORSO MEMORIZZAZIONI IMMAGINI CHE ARRIVANO<br>/Users/acolzi/Downloads/_ocv/img/");
bean.save();
File dirFace = new File(bean.getTesto() + "_face/");
if (!dirFace.exists())
dirFace.mkdirs();
File dirFaceRecognition = new File(bean.getTesto() + "_faceRecognition/");
if (!dirFaceRecognition.exists())
dirFaceRecognition.mkdirs();
bean.findByCodice("path_img_tmp");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("path_img_tmp");
bean.setDescrizione("path_img_tmp");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/Users/acolzi/Downloads/_ocv/_tmp/");
bean.setNota("PERCORSO MEMORIZZAZIONI TEMPORANEO IMMAGINI<br>/Users/acolzi/Downloads/_ocv/_tmp/ /mnt/foto/_ocv/_tmp/");
bean.save();
File dirTmp = new File(bean.getTesto());
if (!dirTmp.exists())
dirTmp.mkdirs();
bean.findByCodice("PATH_FACE_TRAINING_MODELS");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("PATH_FACE_TRAINING_MODELS");
bean.setDescrizione("PATH_FACE_TRAINING_MODELS");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/Users/acolzi/Downloads/_ocv/models/training/");
bean.setNota("PERCORSO DOVE MEMORIZZO I TRAINIG MODELS<br>/Users/acolzi/Downloads/_ocv/models/training/");
bean.save();
File dirTM = new File(bean.getTesto());
if (!dirTM.exists())
dirTM.mkdirs();
bean.findByCodice("NUMBER_BOX_DECT_CONFIG");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("NUMBER_BOX_DECT_CONFIG");
bean.setDescrizione("NUMBER_BOX_DECT_CONFIG");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/Users/acolzi/Downloads/_ocv/models/detection.cfg");
bean.setNota("DETECTION CONFIG PER BOX PETTORALI<br>/Users/acolzi/Downloads/_ocv/models/detection.cfg");
bean.save();
bean.findByCodice("NUMBER_BOX_DECT_MODEL");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("NUMBER_BOX_DECT_MODEL");
bean.setDescrizione("NUMBER_BOX_DECT_MODEL");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/Users/acolzi/Downloads/_ocv/models/detection.weights");
bean.setNota("DETECTION MODEL PER BOX PETTORALI<br>/Users/acolzi/Downloads/_ocv/models/detection.weights");
bean.save();
bean.findByCodice("NUMBER_RECOG_CONFIG");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("NUMBER_RECOG_CONFIG");
bean.setDescrizione("NUMBER_RECOG_CONFIG");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/Users/acolzi/Downloads/_ocv/models/recognition.cfg");
bean.setNota("RECOGNITION CONFIG PER IMMAGINE CON SOLO NUMERI<br>/Users/acolzi/Downloads/_ocv/models/recognition.cfg");
bean.save();
bean.findByCodice("NUMBER_RECOG_MODEL");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("NUMBER_RECOG_MODEL");
bean.setDescrizione("NUMBER_RECOG_MODEL");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/Users/acolzi/Downloads/_ocv/models/recognition.weights");
bean.setNota("RECOGNITION MODEL PER IMMAGINE CON SOLO NUMERI<br>/Users/acolzi/Downloads/_ocv/models/recognition.weights");
bean.save();
GoogleVisionApi.initApplicationParms(ap);
}
}
public Vectumerator<Users> findByCR(UsersCR CR, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from USERS AS A";
WcString wc = new WcString();
wc.addWc("dataFineVld is null");
wc = managePolicyFind(CR, wc);
if (!CR.isCode1())
wc.addWc("A.id_users <>1");
if (!CR.getFlgValido().isEmpty())
wc.addWc("A.flgValido='" + CR.getFlgValido() + "'");
if (!CR.getSearchTxt().trim().isEmpty()) {
String temp = CR.getSearchTxt().trim().replace("*", "%");
StringTokenizer st = new StringTokenizer(temp, " ");
StringBuffer txt = new StringBuffer("(");
int countToken = 0;
while (st.hasMoreTokens()) {
String token = prepareSqlString(st.nextToken());
countToken++;
if (countToken > 1)
token = "%" + token;
txt.append("(A.nome like'%" + token + "%' or A.cognome like'%" + token + "%' or A.eMail like'%" + token + "%' or A.codFisc like'%" + token + "%' or A.login like'%" + token + "%')");
if (st.hasMoreTokens())
txt.append(" and ");
}
txt.append(")");
wc.addWc(txt.toString());
}
if (!CR.getEMail().isEmpty())
wc.addWc("A.eMail like'%" + CR.getEMail() + "%'");
if (CR.getFlgMl() == 0L) {
wc.addWc("(A.flgMl is null or A.flgMl=0)");
} else if (CR.getFlgMl() > 0L) {
wc.addWc("A.flgMl =" + CR.getFlgMl());
}
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find);
return findRows(stmt, pageNumber, pageRows);
} catch (Exception e) {
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
}

View file

@ -0,0 +1,15 @@
package it.acxent.face.fr;
import it.acxent.db.ApplParmFull;
public class UsersCR extends it.acxent.common.UsersCR {
public boolean isCode1() {
return false;
}
public UsersCR(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public UsersCR() {}
}

View file

@ -0,0 +1 @@
package it.acxent.face.fr;

View file

@ -0,0 +1,41 @@
package it.acxent.face.fr.rest;
public class FaceRestResult {
private String msg;
public FaceRestResult(String msg, boolean status, Object result) {
this.msg = msg;
this.ok = status;
this.result = result;
}
private boolean ok = true;
private Object result;
public FaceRestResult() {}
public String getMsg() {
return (this.msg == null) ? "" : this.msg.trim();
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isOk() {
return this.ok;
}
public void setOk(boolean status) {
this.ok = status;
}
public Object getResult() {
return this.result;
}
public void setResult(Object result) {
this.result = result;
}
}

View file

@ -0,0 +1,891 @@
package it.acxent.face.fr.rest;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import it.acxent.common.StatusMsg;
import it.acxent.db.ApplParm;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.dm.FaceDetectionMethod;
import it.acxent.dm.FaceDetectionMethodCR;
import it.acxent.face.api.opencv.FaceRecognition;
import it.acxent.face.api.opencv.TrainingImage;
import it.acxent.face.fr.Face;
import it.acxent.face.fr.FaceFaceRecognizer;
import it.acxent.face.fr.FaceRecognizer;
import it.acxent.face.fr.Facer;
import it.acxent.face.fr.FotoRequest;
import it.acxent.face.fr.Users;
import it.acxent.rest._AblRestAdapter;
import it.acxent.util.Debug;
import it.acxent.util.Timer;
import it.acxent.util.Vectumerator;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfInt;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
@WebServlet(urlPatterns = {"/face/*"})
public class FaceRestSvlt extends _AblRestAdapter {
private static Debug debugHelper = new Debug();
private static final boolean debug = false;
private Cache<String, Object> cache;
private static final long serialVersionUID = -8266400675249237394L;
public void __templateChiamata(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
boolean debug = false;
String parametroTest = getRequestParameter(req, "id");
if (debug)
System.out.println(" parm id: " + parametroTest + " apiParms: " +
getApiParms() + " json post: " + getApiJSONObject().toString(4));
try {
long l_id_user = getRequestLongParameter(req, "id_user");
boolean authOk = checkBasicAuth(req, res);
if (!authOk)
sendHtmlMsgResponse(req, res, "testina di vitello, _elencofoto");
} catch (Exception e) {
e.printStackTrace();
sendHtmlMsgResponse(req, res, "testina di vitello,_elencofoto eccezione: " + e.getMessage());
}
}
protected DBAdapter getBean(HttpServletRequest req) {
return null;
}
protected CRAdapter getBeanCR(HttpServletRequest req) {
return null;
}
public void _detectFacesAndNumbers_POST(HttpServletRequest req, HttpServletResponse res) {
boolean debug = true;
if (debug) {
System.out.println("************ _detectFacesAndNumbers_POST req res *********************");
System.out.println(req.toString());
System.out.println("************");
System.out.println(res.toString());
System.out.println("************");
}
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 1");
ApplParmFull apFull = getApFull(req);
HashSet<File> hsFiles = new HashSet<>();
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 2");
Users user = getUsersByBasicAuth(req, res);
StringBuilder err = new StringBuilder();
StringBuilder msg = new StringBuilder();
try {
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 3");
JSONObject jo = getApiJSONObject();
if (debug) {
System.out.println("************ _detectFacesAndNumbers_POST *********************");
System.out.println("json in arrivo");
System.out.println(jo.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
}
String pathBase = getApFull().getParm("path_img_tmp").getTesto();
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 3.1 : " + pathBase);
File pathBaseFile = new File(pathBase);
if (!pathBaseFile.exists())
pathBaseFile.mkdirs();
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 4");
boolean itsOk = true;
FaceRecognition fa = null;
fa = FaceRecognition.getInstance(apFull);
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 5");
JSONArray jresponses = new JSONArray();
int numberOfFaces = 0;
int numberOfNumbers = 0;
JSONArray jRequestsA = jo.getJSONArray("requests");
for (int i = 0; i < jRequestsA.length(); i++) {
JSONObject jRequest = jRequestsA.getJSONObject(i);
String imageContent = null, imagePath = null;
boolean hasImage = false;
if (jRequest.has("path")) {
imagePath = jRequest.getString("path");
} else {
hasImage = true;
imageContent = jRequest.getJSONObject("image").getString("content");
}
String md5 = jRequest.getString("md5");
long detectionMethod = jRequest.getLong("faceDetectionType");
boolean numbers = jRequest.getBoolean("numbers");
FotoRequest fr = new FotoRequest(getApFull());
long l_requestType = 0L;
if (!numbers && detectionMethod > 0L) {
l_requestType = 1L;
} else if (numbers == true && detectionMethod < 0L) {
l_requestType = 3L;
} else if (!numbers && detectionMethod < 0L) {
l_requestType = -1L;
}
if (l_requestType >= 0L) {
fr.findByUserMd5DetectionmethodRequesttype(user.getId_users(), md5, detectionMethod, l_requestType);
String dbJson = fr.getJson();
if (!dbJson.isEmpty() && !dbJson.equals("{}")) {
JSONObject jresponse = new JSONObject(dbJson);
jresponses.put(jresponse);
fr.addRichiesta();
fr.save();
} else {
String currentImage;
if (hasImage) {
byte[] decodedBytes = Base64.getDecoder().decode(imageContent);
currentImage = pathBase + pathBase + ".jpg";
File file = new File(currentImage);
if (!file.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(decodedBytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null)
fos.close();
}
}
hsFiles.add(file);
} else {
currentImage = imagePath;
}
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 6");
JSONObject jresponse = fa.detectFaces(currentImage, detectionMethod, numbers);
if (hasImage)
for (File elemento : hsFiles)
elemento.delete();
jresponses.put(jresponse);
if (jresponse.has("numOfFaces"))
numberOfFaces += jresponse.getInt("numOfFaces");
if (jresponse.has("numOfNumbers"))
numberOfNumbers += jresponse.getInt("numOfNumbers");
if (user.getId_users() > 0L) {
fr.setId_users(user.getId_users());
fr.setJson(jresponse.toString());
fr.setMd5(md5);
fr.setFaceDetectionMethodCode(detectionMethod);
fr.setFlgRequestType(l_requestType);
fr.addRichiesta();
fr.save();
}
}
} else {
itsOk = false;
err.append("Tipo richiesta e metodo detect faces non impostati");
}
}
if (debug)
System.out.println("************ _detectFacesAndNumbers_POST 7");
JSONObject joRes = new JSONObject();
if (itsOk) {
joRes.put("success", "true");
joRes.put("msg", "Trovate in totale " + numberOfFaces + " visi e " + numberOfNumbers + " numeri su " +
jresponses.length() + " foto: " + msg.toString());
joRes.put("responses", jresponses);
} else {
joRes.put("success", "false");
joRes.put("msg", "Errore! " + err.toString());
}
if (debug) {
System.out.println("************ _detectFacesAndNumbers_POST RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
}
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JSONObject joRes = new JSONObject();
joRes.put("success", "false");
joRes.put("msg", "Eccezione!! " + e.getMessage());
System.out.println("************ _detectFacesAndNumbers_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
}
}
public static void main(String[] args) {
String hostname = "localhost";
String db = "cc";
ApplParmFull ap = new ApplParmFull(new ApplParm(14, "//" + hostname + ":1433;databaseName=" + db + ";user=sa;password=T3st000!", null, null, 1, 10, 300));
}
protected boolean checkBasicAuth(HttpServletRequest req, HttpServletResponse res) {
boolean authOk = false;
try {
String[] auth = getBasicAuthorizationHeaders(req, res);
if (auth != null) {
Users bean = getUsersByBasicAuth(req, res);
if (bean.getDBState() == 1) {
authOk = true;
} else {
System.out.println("FaceRestSvlt.checkBasicAuth KO: login-->" + auth[0] + " pwd-->" + auth[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return authOk;
}
protected String getApiBaseUrl() {
return "/fr/face/";
}
protected Users getUsersByBasicAuth(HttpServletRequest req, HttpServletResponse res) {
String[] auth = getBasicAuthorizationHeaders(req, res);
Users bean = new Users(getApFull());
if (auth != null)
bean.findLogonUtente(auth[0], auth[1], req.getRemoteAddr());
return bean;
}
public void _trainingSendImages_POST(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
boolean debug = false;
StringBuilder err = new StringBuilder();
try {
JSONObject jo = getApiJSONObject();
if (debug) {
System.out.println("************ _trainingSendimages_POST *********************");
System.out.println("json in arrivo");
System.out.println(jo.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
}
long newFaces = 0L;
long newFacesNoImg = 0L;
long findFaces = 0L;
JSONObject joRes = new JSONObject();
String code = jo.getString("code");
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "RECEIVING TRAINING IMAGES FOR " + code + " .... ");
FaceRecognizer frzer = new FaceRecognizer(getApFull());
frzer.findByCode(code);
if (frzer.getId_faceRecognizer() == 0L) {
joRes.put("success", "false");
joRes.put("msg", "ERRORE! Recognizer " + code + " non trovato.");
} else {
JSONArray jRequestsA = jo.getJSONArray("requests");
JSONArray jNoImageA = new JSONArray();
JSONArray jLabelsA = new JSONArray();
Face face = new Face(getApFull());
Face faceLabel = new Face(getApFull());
FaceFaceRecognizer ffr = new FaceFaceRecognizer(getApFull());
Timer timer = new Timer();
timer.start();
String eta = " ....";
for (int i = 0; i < jRequestsA.length(); i++) {
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "RECEIVING TRAINING IMAGES FOR " + code + " .... " + i + 1 + "/" +
jRequestsA.length() + 1 + " new: " + newFaces + " new noimg: " + newFacesNoImg + " find faces:" + findFaces + eta);
JSONObject jRequest = jRequestsA.getJSONObject(i);
String md5 = jRequest.getString("md5");
long label = jRequest.getLong("label");
System.out.println(String.valueOf(DBAdapter.getNow()) + " _trainingSendImages_POST: getting md5: " + String.valueOf(DBAdapter.getNow()));
if (label > 0L) {
faceLabel.findByPrimaryKey(label);
if (faceLabel.getId_face() == 0L) {
err.append("Inviata immagine con label non trovate: " + label);
err.append("\n");
}
}
if (err.length() == 0) {
face.findByMd5(md5);
if (face.getId_face() == 0L) {
newFaces++;
if (jRequest.has("image")) {
face.setMd5(md5);
ResParm rp = face.save();
if (rp.getStatus()) {
String imageContent = jRequest.getJSONObject("image")
.getString("content");
File path = new File(face.getPathFaceImg());
if (!path.exists())
path.mkdirs();
byte[] decodedBytes = Base64.getDecoder().decode(imageContent);
File file = new File(face.getFullFileName());
if (!file.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(decodedBytes);
} catch (Exception e) {
e.printStackTrace();
err.append("Impossibile salvare l'immagine md5 " + md5 + ". " + e.getMessage());
err.append("\n");
} finally {
if (fos != null)
fos.close();
}
}
} else {
err.append("Impossibile salvare record md5 " + md5);
err.append("\n");
}
} else {
newFacesNoImg++;
JSONObject jMd5 = new JSONObject();
jMd5.put("md5", md5);
jNoImageA.put(jMd5);
}
} else {
findFaces++;
}
StatusMsg.updateMsgByTag(getApFull(), "TRAINING_RUN", "RECEIVING TRAINING IMAGES FOR " + code + " .... " + i + 1 + "/" +
jRequestsA.length() + 1 + " new: " + newFaces + " new noimg: " + newFacesNoImg + " find faces:" + findFaces + eta);
if (face.getId_face() > 0L) {
ffr.findByRecognizerLabel(frzer.getId_faceRecognizer(), face.getId_face());
boolean doSave = false;
if (ffr.getId_faceFaceRecognizer() == 0L) {
ffr.setId_face(face.getId_face());
ffr.setId_faceRecognizer(frzer.getId_faceRecognizer());
doSave = true;
}
if (ffr.getId_faceLabel() != label) {
ffr.setId_faceLabel(label);
doSave = true;
}
if (doSave)
ResParm resParm = ffr.save();
JSONObject jLabelrow = new JSONObject();
jLabelrow.put("md5", face.getMd5());
jLabelrow.put("label", ffr.getId_faceLabel());
jLabelrow.put("labelMd5", ffr.getFaceLabel().getMd5());
jLabelsA.put(jLabelrow);
}
}
eta = " " + timer.getEta((long)jRequestsA.length(), (long)i);
}
if (err.length() > 0) {
joRes.put("success", "false");
joRes.put("msg", "Codice " + code + " Errore: " + err.toString());
} else {
joRes.put("success", "true");
joRes.put("msg", "Training in corso: ricezione immagini....");
joRes.put("code", code);
joRes.put("numberTrainingImages",
ffr.getTotFaceByFaceRecognizer(frzer.getId_faceRecognizer()));
if (jNoImageA.length() > 0)
joRes.put("noImg", jNoImageA);
if (jLabelsA.length() > 0)
joRes.put("labels", jLabelsA);
}
}
if (!debug);
System.out.println("************ _trainingSendimages_POST RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JSONObject joRes = new JSONObject();
joRes.put("success", "false");
joRes.put("msg", "Eccezione!! " + e.getMessage());
System.out.println("************ _trainingSendimages_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
}
StatusMsg.deleteMsgByTag(getApFull(), "TRAINING_RUN");
}
private ResParm trainingCreate(String l_sessionId, List<TrainingImage> trainingImages, int recognizerType) {
ResParm rp = new ResParm();
org.opencv.face.FaceRecognizer ocvFr = (org.opencv.face.FaceRecognizer)getCache()
.getIfPresent(l_sessionId + "_" + l_sessionId);
int counter = 0;
String counterKey = l_sessionId + "_" + l_sessionId + "_counter";
Integer Icounter = (Integer)getCache().getIfPresent(counterKey);
if (Icounter != null)
counter = Icounter;
if (trainingImages.size() > 0) {
Mat labels = new Mat(trainingImages.size(), 1, CvType.CV_32SC1);
MatOfInt labelsMat = new MatOfInt();
List<Mat> trainingImagesMat = new ArrayList<>();
for (TrainingImage trainingImage : trainingImages) {
File imageFile = new File(trainingImage.getImageFileName());
Mat image = Imgcodecs.imread(imageFile.getAbsolutePath());
Mat grayImage = new Mat();
Imgproc.cvtColor(image, grayImage, 6);
trainingImagesMat.add(grayImage);
labels.put(counter, 0, new double[] { (double)trainingImage.getLabel() });
counter++;
}
labels.convertTo((Mat)labelsMat, CvType.CV_32SC1);
ocvFr.train(trainingImagesMat, labels);
getCache().put(counterKey, Integer.valueOf(counter));
}
return rp;
}
private Cache<String, Object> getCache() {
if (this.cache == null)
this.cache = CacheBuilder.newBuilder().maximumSize(100L).expireAfterAccess(100L, TimeUnit.MINUTES).build();
return this.cache;
}
public void _recognize_POST(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
boolean debug = true;
Users user = getUsersByBasicAuth(req, res);
StringBuilder err = new StringBuilder();
try {
JSONObject jo = getApiJSONObject();
if (debug) {
System.out.println("************ _recognize_POST *********************");
System.out.println("json in arrivo");
System.out.println(jo.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
debugHelper.writeLog("************ _recognize_POST *********************");
debugHelper.writeLog("json in arrivo");
debugHelper.writeLog(jo.toString(4));
debugHelper.writeLog("*-------------- FINE ---------------------------*");
}
JSONObject joRes = new JSONObject();
JSONArray jResponses = new JSONArray();
String code = jo.getString("code");
FaceRecognition fa = null;
fa = FaceRecognition.getInstance(apFull);
FaceRecognizer frzer = new FaceRecognizer(getApFull());
frzer.findByCode(code);
if (frzer.getId_faceRecognizer() == 0L) {
joRes.put("success", "false");
joRes.put("msg", "ERRORE! Recognizer " + code + " non trovato.");
} else {
JSONArray jRequestsA = jo.getJSONArray("requests");
JSONArray jNoImageA = new JSONArray();
Facer facer = new Facer(getApFull());
for (int i = 0; i < jRequestsA.length(); i++) {
JSONObject jRequest = jRequestsA.getJSONObject(i);
String md5 = jRequest.getString("md5");
facer.findByMd5Recognizer(md5, frzer.getId_faceRecognizer());
if (facer.getId_facer() == 0L)
if (jRequest.has("image")) {
facer.setMd5(md5);
facer.setId_faceRecognizer(frzer.getId_faceRecognizer());
ResParm rp = facer.save();
if (rp.getStatus()) {
String imageContent = jRequest.getJSONObject("image")
.getString("content");
File path = new File(facer.getPathFaceImg());
if (!path.exists())
path.mkdirs();
byte[] decodedBytes = Base64.getDecoder().decode(imageContent);
File file = new File(facer.getFullFileName());
if (!file.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(decodedBytes);
} catch (Exception e) {
e.printStackTrace();
err.append("Impossibile salvare l'immagine md5 " + md5 + ". " + e.getMessage());
err.append("\n");
} finally {
if (fos != null)
fos.close();
}
}
} else {
err.append("Impossibile salvare record md5 " + md5);
err.append("\n");
}
} else if (jRequest.has("originalPath")) {
String originalFilePath = jRequest.getString("originalPath");
File originalFile = new File(originalFilePath);
if (originalFile.exists()) {
if (debug)
DBAdapter.printDebug(debug, " _recognize_POST trovato " + originalFilePath);
facer.setMd5(md5);
facer.setId_faceRecognizer(frzer.getId_faceRecognizer());
facer.setFileAlternativo(originalFilePath);
ResParm rp = facer.save();
if (!rp.getStatus()) {
err.append("Impossibile salvare record md5 " + md5 + " filealt: " + originalFilePath);
err.append("\n");
}
} else {
JSONObject jMd5 = new JSONObject();
jMd5.put("md5", md5);
jNoImageA.put(jMd5);
}
} else {
JSONObject jMd5 = new JSONObject();
jMd5.put("md5", md5);
jNoImageA.put(jMd5);
}
JSONObject jResponse = new JSONObject();
if (facer.getId_facer() > 0L) {
String currentFileName;
if (facer.getFileAlternativo().isEmpty()) {
currentFileName = facer.getFullFileName();
} else {
currentFileName = facer.getFileAlternativo();
}
if (debug)
System.out.println(
String.valueOf(DBAdapter.getNowTs()) + " _recognize_POST chiamo face recognition su " + String.valueOf(DBAdapter.getNowTs()));
JSONArray jLabelsA = fa.faceRecognition(currentFileName, frzer);
jResponse.put("md5", md5);
jResponse.put("labels", jLabelsA);
jResponses.put(jResponse);
if (debug)
DBAdapter.printDebug(debug, " _recognize_POST risposta da face recognition;\n" +
jResponses.toString(4));
}
}
if (err.length() > 0) {
joRes.put("success", "false");
joRes.put("msg", "Codice " + code + " Errore: " + err.toString());
} else {
joRes.put("success", "true");
joRes.put("msg", "Recognizer Ok.");
joRes.put("code", code);
if (jResponses.length() > 0)
joRes.put("responses", jResponses);
if (jNoImageA.length() > 0)
joRes.put("noImg", jNoImageA);
}
joRes.put("success", "true");
joRes.put("msg", "Recognizer Ok");
joRes.put("code", code);
}
if (debug) {
System.out.println("************ _recognize_POST RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
debugHelper.writeLog("************ _recognize_POST RISPOSTA AL CLIENT *********************");
debugHelper.writeLog(joRes.toString(4));
}
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JSONObject joRes = new JSONObject();
joRes.put("success", "false");
joRes.put("msg", "Eccezione!! " + e.getMessage());
System.out.println("************ _recognize_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
debugHelper.writeLog("************ _recognize_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
debugHelper.writeLog(joRes.toString(4));
debugHelper.writeLog("*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
}
}
public void _syncFaceDetectionMethods_GET(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
try {
JSONObject joRes = new JSONObject();
FaceDetectionMethod fdm = new FaceDetectionMethod(apFull);
Vectumerator<FaceDetectionMethod> vec = fdm.findByCR(new FaceDetectionMethodCR(), 0, 0);
JSONArray jaFdm = new JSONArray();
while (vec.hasMoreElements()) {
FaceDetectionMethod row = (FaceDetectionMethod)vec.nextElement();
JSONObject jRow = new JSONObject();
jRow.put("codice", row.getCodice());
jRow.put("flgDetectionType", row.getFlgDetectionType());
jRow.put("descrizione", row.getDescrizione());
jRow.put("descrizioneLunga", row.getDescrizioneLunga());
jaFdm.put(jRow);
}
joRes.put("faceDetectionMethods", jaFdm);
joRes.put("success", "true");
joRes.put("msg", "Trovati " + vec.getTotNumberOfRecords() + " metodi");
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JSONObject joRes = new JSONObject();
joRes.put("success", "false");
joRes.put("msg", "Eccezione!! " + e.getMessage());
System.out.println("************ _trainingRun_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
}
}
public void _checkLabel_POST(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
ResParm rp = new ResParm(true);
boolean debug = false;
try {
JSONObject jo = getApiJSONObject();
if (debug) {
System.out.println("************ _checklabel_POST *********************");
System.out.println("json in arrivo");
System.out.println(jo.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
}
JSONObject joRes = new JSONObject();
long label = jo.getLong("label");
String md5 = jo.getString("md5");
boolean reqImage = jo.getBoolean("reqImage");
boolean addLabel = jo.getBoolean("addLabel");
FaceRecognizer frzer = new FaceRecognizer(apFull);
String code = "";
if (jo.has("code")) {
code = jo.getString("code");
frzer.findByCode(code);
}
Face face = new Face(apFull);
if (!md5.isEmpty()) {
face.findByMd5(md5);
if (debug)
System.out.println("-- face find by md5--> " + face.getDescRecord());
} else if (face.getId_face() == 0L && label > 0L) {
face.findByLabel(label);
}
if (face.getId_face() == 0L) {
if (addLabel && !md5.isEmpty()) {
face.setMd5(md5);
rp = face.save();
if (debug)
System.out.println("-- face add nuovo by md5--> " + face.getDescRecord());
if (rp.getStatus()) {
StringBuilder err = new StringBuilder();
String imageContent = jo.getJSONObject("image")
.getString("content");
File path = new File(face.getPathFaceImg());
if (!path.exists())
path.mkdirs();
byte[] decodedBytes = Base64.getDecoder().decode(imageContent);
File file = new File(face.getFullFileName());
if (!file.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(decodedBytes);
} catch (Exception e) {
e.printStackTrace();
err.append("Impossibile salvare l'immagine md5 " + face.getMd5() + ". " + e.getMessage());
err.append("\n");
} finally {
if (fos != null)
fos.close();
}
}
if (err.length() > 0) {
handleDebug(err.toString());
rp.setStatus(false);
rp.setMsg(err.toString());
}
} else {
handleDebug(rp.getErrMsg());
}
FaceFaceRecognizer ffr = new FaceFaceRecognizer(getApFull());
if (frzer.getId_faceRecognizer() == 0L) {
rp.setStatus(false);
rp.setMsg("Attenzione! Aggiunta immagine ma impossibile associare a recognizer nullo!");
} else {
ffr.setId_faceRecognizer(frzer.getId_faceRecognizer());
ffr.setId_face(face.getId_face());
ffr.setId_faceLabel(face.getId_face());
rp = ffr.save();
if (debug)
System.out.println("-- ffr add nuovo dopo face--> " + ffr.getDescRecord());
}
if (debug)
System.out.println("-- prima della scrittura finale se creato addlabel --> " + ffr.getDescRecord());
if (rp.getStatus()) {
joRes.put("success", "true");
joRes.put("msg", rp.getMsg());
joRes.put("id", ffr.getId_face());
joRes.put("label", ffr.getId_faceLabel());
joRes.put("labelMd5", face.getMd5());
} else {
joRes.put("success", "false");
joRes.put("msg", rp.getMsg());
joRes.put("id", ffr.getId_face());
joRes.put("label", ffr.getId_faceLabel());
joRes.put("labelMd5", face.getMd5());
}
} else {
rp.setStatus(false);
rp.setMsg("Label " + label + " non trovata ");
joRes.put("success", "false");
joRes.put("msg", "Label " + label + " non trovata: " + rp.getMsg());
}
} else {
FaceFaceRecognizer ffr = new FaceFaceRecognizer(getApFull());
if (addLabel) {
if (frzer.getId_faceRecognizer() == 0L) {
rp.setStatus(false);
rp.setMsg("Attenzione! Aggiunta immagine ma impossibile associare a recognizer nullo!");
} else {
ffr.findByRecognizerLabel(frzer.getId_faceRecognizer(), face.getId_face());
if (debug)
System.out.println("-- ffr add o modificato trovato???--> " + ffr.getDescRecord());
if (ffr.getId_faceFaceRecognizer() == 0L || ffr.getId_face() != ffr.getId_faceLabel()) {
ffr.setId_faceRecognizer(frzer.getId_faceRecognizer());
ffr.setId_face(face.getId_face());
ffr.setId_faceLabel(face.getId_face());
ffr.save();
if (debug)
System.out.println("-- ffr add o modificato se trovato face con md5--> " + ffr.getDescRecord());
}
}
} else if (frzer.getId_faceRecognizer() == 0L) {
rp.setStatus(false);
rp.setMsg("Attenzione! Impossibile associare a recognizer nullo!");
} else {
ffr.findByRecognizerLabel(frzer.getId_faceRecognizer(), face.getId_face());
if (ffr.getId_faceFaceRecognizer() == 0L) {
ffr.setId_faceRecognizer(frzer.getId_faceRecognizer());
ffr.setId_face(face.getId_face());
ffr.save();
}
}
if (debug)
System.out.println("-- prima della scrittura finale se trovato --> " + ffr.getDescRecord());
joRes.put("success", "true");
joRes.put("msg", rp.getMsg());
joRes.put("id", ffr.getId_face());
joRes.put("label", ffr.getId_faceLabel());
joRes.put("labelMd5", face.getMd5());
if (reqImage) {
JSONObject jImage = new JSONObject();
byte[] fileContent = FileUtils.readFileToByteArray(new File(face.getFullFileName()));
String encodedString = Base64.getEncoder().encodeToString(fileContent);
jImage.put("content", encodedString);
joRes.put("image", jImage);
}
}
if (debug) {
System.out.println("************ _checklabel_POST RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
}
System.out.println(String.valueOf(DBAdapter.getNow()) + " _checkLabel_POST. md5: " + String.valueOf(DBAdapter.getNow()) + " label: " + md5);
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JSONObject joRes = new JSONObject();
joRes.put("success", "false");
joRes.put("msg", "Eccezione!! " + e.getMessage());
System.out.println("************ _checklabel_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
}
}
public void _trainingRun_POST(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
boolean debug = true;
try {
JSONObject jo = getApiJSONObject();
if (debug) {
System.out.println("************ _trainingRun_POST *********************");
System.out.println("json in arrivo");
System.out.println(jo.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
}
JSONObject joRes = new JSONObject();
String code = jo.getString("code");
FaceRecognizer frzer = new FaceRecognizer(apFull);
frzer.findByCode(code);
if (frzer.getId_faceRecognizer() == 0L) {
if (debug)
System.out.println("_trainingRun_POST RECOGNIZER NON TROVATO ");
joRes.put("success", "false");
joRes.put("msg", "ERRORE! Recognizer " + code + " non trovato.");
} else {
if (debug)
System.out.println("_trainingRun_POST trainingAndCreateModel su thread separato.... ");
Thread thread = new Thread(() -> {
ResParm rpT = new ResParm();
try {
rpT = frzer.trainingAndCreateModel(true);
if (debug)
System.out.println("_trainingRun_POST MODELLO CREATO.... " + rpT.getMsg());
} catch (Exception e) {
if (debug)
System.out.println("_trainingRun_POST MODELLO NON CREATO....: " + e.getMessage());
}
});
thread.start();
if (debug)
System.out.println("_trainingRun_POST preparo la risposta........................................... ");
joRes.put("code", code);
joRes.put("numberTrainingImages", frzer.getNTrainingImages());
joRes.put("success", "true");
joRes.put("msg", "Training concluso con successo. Creazione modello in corso...");
}
if (debug) {
System.out.println("************ _trainingRun_POST RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
}
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JSONObject joRes = new JSONObject();
joRes.put("success", "false");
joRes.put("msg", "Eccezione!! " + e.getMessage());
System.out.println("************ _trainingRun_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
}
}
public void _resetTraining_POST(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
try {
JSONObject jo = getApiJSONObject();
JSONObject joRes = new JSONObject();
String code = jo.getString("code");
FaceRecognizer frzer = new FaceRecognizer(apFull);
frzer.findByCode(code);
if (frzer.getId_faceRecognizer() == 0L) {
joRes.put("success", "false");
joRes.put("msg", "ERRORE! Recognizer " + code + " non trovato.");
} else {
ResParm rp = frzer.resetTraining();
if (rp.getStatus()) {
joRes.put("success", "true");
joRes.put("msg", "Codice " + code + " resettato");
} else {
joRes.put("success", "false");
joRes.put("msg", "Codice " + code + " NON resettato correttamente: " + rp.getMsg());
}
}
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JSONObject joRes = new JSONObject();
joRes.put("success", "false");
joRes.put("msg", "Eccezione!! " + e.getMessage());
System.out.println("************ _resetTrainig_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
System.out.println(joRes.toString(4));
System.out.println("*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
}
}
protected Class<? extends _AblRestAdapter> getConcreteApiClass() {
return null;
}
}

View file

@ -0,0 +1 @@
package it.acxent.face.fr.rest;

View file

@ -0,0 +1,30 @@
package it.acxent.face.fr.servlet.admin;
import it.acxent.db.CRAdapter;
import it.acxent.db.DBAdapter;
import it.acxent.dm.FaceDetectionMethod;
import it.acxent.dm.FaceDetectionMethodCR;
import it.acxent.servlet.AblServletSvlt;
import it.acxent.servlet.AddImgSvlt;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FaceDetectionMethodSvlt extends AblServletSvlt implements AddImgSvlt {
private static final long serialVersionUID = 5676887616087638826L;
protected void fillComboAfterDetail(DBAdapter beanA, HttpServletRequest req, HttpServletResponse res) {}
protected void fillComboAfterSearch(CRAdapter CRA, HttpServletRequest req, HttpServletResponse res) {}
protected DBAdapter getBean(HttpServletRequest req) {
return new FaceDetectionMethod(getApFull(req));
}
protected CRAdapter getBeanCR(HttpServletRequest req) {
return new FaceDetectionMethodCR(getApFull(req));
}
protected void search(HttpServletRequest req, HttpServletResponse res) {
super.search(req, res);
}
}

View file

@ -0,0 +1,100 @@
package it.acxent.face.fr.servlet.admin;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.face.fr.FaceRecognizer;
import it.acxent.face.fr.FaceRecognizerCR;
import it.acxent.servlet.AblServletSvlt;
import it.acxent.servlet.AddImgSvlt;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FaceRecognizerSvlt extends AblServletSvlt implements AddImgSvlt {
private static final long serialVersionUID = 5676887616087638826L;
private static boolean debug = true;
protected void fillComboAfterDetail(DBAdapter beanA, HttpServletRequest req, HttpServletResponse res) {}
protected void fillComboAfterSearch(CRAdapter CRA, HttpServletRequest req, HttpServletResponse res) {}
protected DBAdapter getBean(HttpServletRequest req) {
return new FaceRecognizer(getApFull(req));
}
protected CRAdapter getBeanCR(HttpServletRequest req) {
return new FaceRecognizerCR(getApFull(req));
}
protected void search(HttpServletRequest req, HttpServletResponse res) {
super.search(req, res);
}
public void _resetTraining(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
FaceRecognizer bean = new FaceRecognizer(apFull);
long l_id = getRequestLongParameter(req, "id_faceRecognizer");
ResParm rp = new ResParm();
bean.findByPrimaryKey(l_id);
rp = bean.resetTraining();
if (rp.getStatus()) {
sendMessage(req, "Reset training ok");
} else {
sendMessage(req, "Errore! " + rp.getMsg());
}
showBean(req, res);
}
public void _rebuildModel(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
FaceRecognizer bean = new FaceRecognizer(apFull);
long l_id = getRequestLongParameter(req, "id_faceRecognizer");
FaceRecognizerCR CR = new FaceRecognizerCR(apFull);
CR.setId_faceRecognizer(l_id);
bean.findByPrimaryKey(l_id);
Thread thread = new Thread(() -> {
try {
ResParm rp = new ResParm();
bean.trainingAndCreateModel(true);
DBAdapter.printDebug(debug, " trainingAndCreateModel. Operazione completata: " + rp.getMsg());
} catch (Exception e) {
e.printStackTrace();
}
});
thread.start();
sendMessage(req, "trainingAndCreateModel lanciato in un thread separato....");
showBean(req, res);
}
public void _precaricaModelliFile(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
FaceRecognizerCR CR = new FaceRecognizerCR(apFull);
fillObject(req, CR);
CR.setPageRow(getPageRow(req));
FaceRecognizer bean = new FaceRecognizer(apFull);
ResParm rp = bean.startCaricaModelli(CR, true);
sendMessage(req, rp.getMsg());
search(req, res);
}
public void _removeAllModelFromCache(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
FaceRecognizer bean = new FaceRecognizer(apFull);
bean.removeAllOcvFaceRecognizerWithLoadedModel();
sendMessage(req, "Rimossi i modelli dalla cache");
search(req, res);
}
public void _precaricaModelli(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
FaceRecognizerCR CR = new FaceRecognizerCR(apFull);
fillObject(req, CR);
CR.setPageRow(getPageRow(req));
FaceRecognizer bean = new FaceRecognizer(apFull);
ResParm rp = bean.startCaricaModelli(CR, false);
sendMessage(req, rp.getMsg());
search(req, res);
}
}

View file

@ -0,0 +1,30 @@
package it.acxent.face.fr.servlet.admin;
import it.acxent.db.CRAdapter;
import it.acxent.db.DBAdapter;
import it.acxent.face.fr.Face;
import it.acxent.face.fr.FaceCR;
import it.acxent.servlet.AblServletSvlt;
import it.acxent.servlet.AddImgSvlt;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FaceSvlt extends AblServletSvlt implements AddImgSvlt {
private static final long serialVersionUID = 5676887616087638826L;
protected void fillComboAfterDetail(DBAdapter beanA, HttpServletRequest req, HttpServletResponse res) {}
protected void fillComboAfterSearch(CRAdapter CRA, HttpServletRequest req, HttpServletResponse res) {}
protected DBAdapter getBean(HttpServletRequest req) {
return new Face(getApFull(req));
}
protected CRAdapter getBeanCR(HttpServletRequest req) {
return new FaceCR(getApFull(req));
}
protected void search(HttpServletRequest req, HttpServletResponse res) {
super.search(req, res);
}
}

View file

@ -0,0 +1,88 @@
package it.acxent.face.fr.servlet.admin;
import it.acxent.db.DBAdapter;
import it.acxent.face.fr.Face;
import it.acxent.servlet.AcStndSvlt;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetFileSvlt extends AcStndSvlt {
private static final long serialVersionUID = -3037980260742696647L;
protected boolean checkLoginProfile(HttpServletRequest req) {
try {
return true;
} catch (Exception e) {
handleDebug(e);
return false;
}
}
protected String getLoginPage(HttpServletRequest req, HttpServletResponse res) {
return "/documentoCR.jsp";
}
protected void otherCommands(HttpServletRequest req, HttpServletResponse res) {
chiamaJsp(req, res);
}
protected void chiamaJsp(HttpServletRequest req, HttpServletResponse res) {
try {
String fileName = "";
long l_id_face = getRequestLongParameter(req, "id_face");
String l_labelMd5 = getRequestParameter(req, "labelMd5");
if (!l_labelMd5.isEmpty()) {
Face ff = new Face(getApFull());
ff.findByMd5(l_labelMd5);
if (ff.getDBState() == 1)
fileName = ff.getFullFileName();
} else if (l_id_face > 0L) {
Face ff = new Face(getApFull());
ff.findByPrimaryKey(l_id_face);
if (ff.getDBState() == 1)
fileName = ff.getFullFileName();
}
File theFile = new File(fileName);
if (theFile.exists())
if (fileName.toLowerCase().endsWith("gif")) {
System.out.println("Getfile www gifs-->>>>");
res.setContentType("image/gif");
ByteArrayOutputStream ba = DBAdapter.getByteArrayFromFile(fileName);
res.setContentLength(ba.size());
try {
ServletOutputStream out = res.getOutputStream();
ba.writeTo((OutputStream)out);
out.flush();
} catch (Exception e) {
handleDebug(e, 0);
}
} else {
theFile = new File(fileName);
if (theFile.exists()) {
res.setContentType("image/jpg");
ByteArrayOutputStream ba = DBAdapter.getByteArrayFromFile(fileName);
res.setContentLength(ba.size());
try {
ServletOutputStream out = res.getOutputStream();
ba.writeTo((OutputStream)out);
out.flush();
} catch (Exception e) {
handleDebug(e, 0);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void mostraDettaglio(HttpServletRequest req, HttpServletResponse res) {}
protected void accessiSql(HttpServletRequest req, HttpServletResponse res) {}
protected void search(HttpServletRequest req, HttpServletResponse res) {}
}

View file

@ -0,0 +1,29 @@
package it.acxent.face.fr.servlet.admin;
import it.acxent.db.ApplParmFull;
import it.acxent.db.ResParm;
import it.acxent.face.fr.FaceRecognizer;
import it.acxent.face.fr.FaceRecognizerCR;
import it.acxent.servlet.AcServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(loadOnStartup = 1)
public class InitRecognizerSvlt extends AcServlet {
private static final long serialVersionUID = -4052399191302059215L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {}
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplParmFull apFull = getApFullSc(config);
System.out.println("InitRecognizerSvlt ");
FaceRecognizer bean = new FaceRecognizer(apFull);
FaceRecognizerCR CR = new FaceRecognizerCR(apFull);
ResParm rp = bean.startCaricaModelli(CR, false);
System.out.println("InitRecognizerSvlt ... thread lanciato...");
}
}

View file

@ -0,0 +1 @@
package it.acxent.face.fr.servlet.admin;

View file

@ -0,0 +1,95 @@
package it.acxent.face.fr.zoo;
import it.acxent.common.Parm;
import it.acxent.db.ApplParmFull;
import it.acxent.db.WcString;
import it.acxent.util.StringTokenizer;
import it.acxent.util.Vectumerator;
import java.sql.PreparedStatement;
public class Users extends it.acxent.anag.Users {
public Users() {}
public Users(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public void initApplicationParms(ApplParmFull ap) {
if (ap != null) {
super.initApplicationParms(ap);
String l_tipoParm = "";
Parm bean = new Parm(ap);
l_tipoParm = "FACE-FR-ZOO";
bean.findByCodice("PATH_ZOO_BACKEND_TARGET");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("PATH_ZOO_BACKEND_TARGET");
bean.setDescrizione("PATH_ZOO_BACKEND_TARGET");
bean.setFlgTipo(1L);
bean.setNota(" Choose one of the backend-target pair:<br>0: (default) OpenCV implementation + CPU, <br>1: CUDA + GPU (CUDA), <br>2: CUDA + GPU (CUDA FP16), <br>3: TIM-VX + NPU, <br>4: CANN + NPU");
bean.save();
bean.findByCodice("PATH_ZOO_FACE_DETECTION_SCRIPT");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("PATH_ZOO_FACE_DETECTION_SCRIPT");
bean.setDescrizione("PATH_ZOO_FACE_DETECTION_SCRIPT");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/home/sites/fr/admin/_shell/detection.sh");
bean.setNota("Script completo per recognizer: <br>/home/sites/zoo/admin/_shell/detection.sh<br>I parametri sono<br> --input_json INPUT_JSON<br>Path del file JSON di input.\n --output_json OUTPUT_JSON<br>Path del file JSON di output.\n --backend_target BACKEND_TARGET, -bt BACKEND_TARGET<br> -d DELETE Cancella file json input_json alla fine");
bean.save();
bean.findByCodice("PATH_ZOO_FACE_RECOGNITION_SCRIPT");
bean.setFlgAdmin(1L);
bean.setTipoParm(l_tipoParm);
bean.setCodice("PATH_ZOO_FACE_RECOGNITION_SCRIPT");
bean.setDescrizione("PATH_ZOO_FACE_RECOGNITION_SCRIPT");
bean.setFlgTipo(0L);
if (bean.getTesto().isEmpty())
bean.setTesto("/home/sites/fr/admin/_shell/recognizer.sh");
bean.setNota("Script completo per recognizer: <br>/home/sites/zoo/admin/_shell/recognizer.sh<br>I parametri sono<br> --input_json INPUT_JSON<br>Path del file JSON di input.\n --output_json OUTPUT_JSON<br>Path del file JSON di output.\n --backend_target BACKEND_TARGET, -bt BACKEND_TARGET<br> -d DELETE Cancella file json input_json alla fine");
bean.save();
}
}
public Vectumerator<Users> findByCR(UsersCR CR, int pageNumber, int pageRows) {
String s_Sql_Find = "select A.* from USERS AS A";
WcString wc = new WcString();
wc.addWc("dataFineVld is null");
wc = managePolicyFind(CR, wc);
if (!CR.isCode1())
wc.addWc("A.id_users <>1");
if (!CR.getFlgValido().isEmpty())
wc.addWc("A.flgValido='" + CR.getFlgValido() + "'");
if (!CR.getSearchTxt().trim().isEmpty()) {
String temp = CR.getSearchTxt().trim().replace("*", "%");
StringTokenizer st = new StringTokenizer(temp, " ");
StringBuffer txt = new StringBuffer("(");
int countToken = 0;
while (st.hasMoreTokens()) {
String token = prepareSqlString(st.nextToken());
countToken++;
if (countToken > 1)
token = "%" + token;
txt.append("(A.nome like'%" + token + "%' or A.cognome like'%" + token + "%' or A.eMail like'%" + token + "%' or A.codFisc like'%" + token + "%' or A.login like'%" + token + "%')");
if (st.hasMoreTokens())
txt.append(" and ");
}
txt.append(")");
wc.addWc(txt.toString());
}
if (!CR.getEMail().isEmpty())
wc.addWc("A.eMail like'%" + CR.getEMail() + "%'");
if (CR.getFlgMl() == 0L) {
wc.addWc("(A.flgMl is null or A.flgMl=0)");
} else if (CR.getFlgMl() > 0L) {
wc.addWc("A.flgMl =" + CR.getFlgMl());
}
try {
PreparedStatement stmt = getConn().prepareStatement(s_Sql_Find + s_Sql_Find);
return findRows(stmt, pageNumber, pageRows);
} catch (Exception e) {
handleDebug(e);
return AB_EMPTY_VECTUMERATOR;
}
}
}

View file

@ -0,0 +1,15 @@
package it.acxent.face.fr.zoo;
import it.acxent.db.ApplParmFull;
public class UsersCR extends it.acxent.common.UsersCR {
public boolean isCode1() {
return false;
}
public UsersCR(ApplParmFull newApplParmFull) {
super(newApplParmFull);
}
public UsersCR() {}
}

View file

@ -0,0 +1 @@
package it.acxent.face.fr.zoo;

View file

@ -0,0 +1,387 @@
package it.acxent.face.fr.zoo.rest;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import it.acxent.db.ApplParm;
import it.acxent.db.ApplParmFull;
import it.acxent.db.CRAdapter;
import it.acxent.db.DBAdapter;
import it.acxent.db.ResParm;
import it.acxent.face.api.opencv.TrainingImage;
import it.acxent.face.fr.FotoRequest;
import it.acxent.face.fr.zoo.Users;
import it.acxent.rest._AblRestAdapter;
import it.acxent.util.Debug;
import it.acxent.util.FileWr;
import it.acxent.util.ShellWrapper;
import it.acxent.util.Timer;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfInt;
import org.opencv.face.FaceRecognizer;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
@WebServlet(urlPatterns = {"/facezoo/*"})
public class FaceZooRestSvlt extends _AblRestAdapter {
private static Debug debugHelper = new Debug();
private static final boolean debug = false;
private Cache<String, Object> cache;
private static final long serialVersionUID = -8266400675249237394L;
public void __templateChiamata(HttpServletRequest req, HttpServletResponse res) {
ApplParmFull apFull = getApFull(req);
boolean debug = false;
String parametroTest = getRequestParameter(req, "id");
DBAdapter.printDebug(" parm id: " + parametroTest + " apiParms: " + getApiParms() + " json post: " + getApiJSONObject().toString(4));
try {
long l_id_user = getRequestLongParameter(req, "id_user");
boolean authOk = checkBasicAuth(req, res);
if (!authOk)
sendHtmlMsgResponse(req, res, "testina di vitello, _elencofoto");
} catch (Exception e) {
e.printStackTrace();
sendHtmlMsgResponse(req, res, "testina di vitello,_elencofoto eccezione: " + e.getMessage());
}
}
protected DBAdapter getBean(HttpServletRequest req) {
return null;
}
protected CRAdapter getBeanCR(HttpServletRequest req) {
return null;
}
public void _detectFaces_POST(HttpServletRequest req, HttpServletResponse res) {
boolean debug = true;
Timer timer = null;
timer = new Timer();
timer.start();
DBAdapter.printDebug(debug, "************ _detectFaces_POST 1");
int MAX_ATTEMPTS = 3;
int RETRY_DELAY_MS = 1000;
JsonObject jresPy = null;
HttpSession oldSession = req.getSession(false);
Users user = getUsersByBasicAuth(req, res);
StringBuilder err = new StringBuilder();
StringBuilder msg = new StringBuilder();
StringBuilder errMsg = new StringBuilder();
FotoRequest fr = new FotoRequest(getApFull());
try {
DBAdapter.printDebug(debug, "************ _detectFaces_POST 2");
JsonObject jo = getApiJsonObject();
DBAdapter.printDebug(debug, "************ _detectFaces_POST 3 *********************");
DBAdapter.printDebug(debug, "json in arrivo");
DBAdapter.printDebug(DBAdapter.gsonToString(jo));
DBAdapter.printDebug(debug, "*-------------- FINE JSON IN ARRIVO ---------------------------*");
String pathBase = getApFull().getParm("path_img_tmp").getTesto();
String targetDirJsonData = pathBase + "_json/";
File targetDirFile = new File(targetDirJsonData);
if (!targetDirFile.exists())
targetDirFile.mkdirs();
JsonArray jresponses = new JsonArray();
int numberOfFaces = 0;
boolean cachedFaces = false;
JsonObject jsonData = new JsonObject();
float confidenceThresold = jo.get("conf_threshold").getAsFloat();
jsonData.addProperty("conf_threshold", Float.valueOf(confidenceThresold));
long detectionMethod = (long)(100 + (int)(confidenceThresold * 100.0F));
HashSet<File> hsFiles = new HashSet<>();
JsonArray jQueryA = new JsonArray();
JsonArray jRequestsA = jo.getAsJsonArray("requests");
for (int i = 0; i < jRequestsA.size(); i++) {
JsonObject jRequest = jRequestsA.get(i).getAsJsonObject();
String imageContent = null, imagePath = null;
boolean hasImage = false;
if (jRequest.has("path")) {
imagePath = jRequest.get("path").getAsString();
} else {
hasImage = true;
JsonObject imageObject = jRequest.getAsJsonObject("image");
imageContent = imageObject.get("content").getAsString();
}
String md5 = jRequest.get("md5").getAsString();
if (oldSession != null) {
DBAdapter.printDebug(debug, "************ _detectFaces_POST 1.2.1 session id: " +
req.getSession().getId() + " i: " + i + " md5: " + md5);
} else {
DBAdapter.printDebug(debug, "************ _detectFaces_POST 1.2.2 session id inesistente md5: " + md5);
}
long l_requestType = 1L;
DBAdapter.printDebug(debug, "************ _detectFaces_POST 4 findByUserMd5DetectionmethodRequesttype *********************");
DBAdapter.printDebug(debug, "md5: " + md5);
fr.findByUserMd5DetectionmethodRequesttype(user.getId_users(), md5, detectionMethod, l_requestType);
String dbJson = fr.getJson();
if (!dbJson.isEmpty()) {
JsonObject jresponse = JsonParser.parseString(dbJson).getAsJsonObject();
jresponses.add((JsonElement)jresponse);
fr.addRichiesta();
fr.save();
cachedFaces = true;
DBAdapter.printDebug("************ _detectFaces_POST 5 findByUserMd5DetectionmethodRequesttype OK *********************");
DBAdapter.printDebug(debug, "md5: " + md5);
JsonObject jsonObject = JsonParser.parseString(fr.getJson()).getAsJsonObject();
DBAdapter.printDebug(debug, "json sul db" + DBAdapter.gsonToString(jsonObject));
} else {
DBAdapter.printDebug(debug, "************ _detectFaces_POST 6 PREPARO RICHIESTA PHYTON *********************");
DBAdapter.printDebug(debug, "md5: " + md5);
JsonObject jQueryRow = new JsonObject();
jQueryRow.addProperty("md5", md5);
if (hasImage) {
byte[] decodedBytes = Base64.getDecoder().decode(imageContent);
String currentImage = pathBase + pathBase + ".jpg";
File file = new File(currentImage);
if (!file.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(decodedBytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null)
fos.close();
}
}
jQueryRow.addProperty("path", currentImage);
hsFiles.add(file);
} else {
jQueryRow.addProperty("path", imagePath);
}
jQueryA.add((JsonElement)jQueryRow);
}
}
if (jQueryA.size() > 0) {
jsonData.add("query", (JsonElement)jQueryA);
DBAdapter.printDebug(debug, "_detectFaces_POST jsonData:\n" + DBAdapter.gsonToString(jsonData));
String rndName = getTimeNameForFileUpload();
String json_data_path = targetDirJsonData + "jDataDetect_" + targetDirJsonData + ".json";
String json_res_path = targetDirJsonData + "jDataDetect_" + targetDirJsonData + "_res.json";
DBAdapter.printDebug(debug, "************ _detectFaces_POST 7 writing json *********************");
DBAdapter.printDebug(debug, "json_data_path: " + json_data_path);
jsonData.addProperty("debug", "FaceZooRest._detectFaces_POST");
FileWr fw = new FileWr(json_data_path, false);
fw.writeLine(DBAdapter.gsonToString(jsonData));
fw.closeFile();
List<String> pythonScript = Arrays.asList(getParm("PATH_ZOO_FACE_DETECTION_SCRIPT").getTesto(), "--input_json", json_data_path, "--output_json", json_res_path);
for (int attempt = 1; attempt <= 3; attempt++) {
String result = ShellWrapper.executeShellScript(pythonScript);
jresPy = DBAdapter.tryParseJsonObject(result);
if (jresPy != null)
break;
if (attempt < 3)
try {
Thread.sleep(1000L);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
if (jresPy == null)
throw new RuntimeException("Errore: impossibile ottenere un JSON valido dopo 3 tentativi");
DBAdapter.printDebug(debug, "************ _detectFaces_POST 8 RISPOSTA SCRIPT PYTHON *********************");
DBAdapter.printDebug(DBAdapter.gsonToString(jresPy));
JsonArray jresponsesPy = jresPy.getAsJsonArray("responses");
for (int j = 0; j < jresponsesPy.size(); j++) {
JsonObject jresponsePy = jresponsesPy.get(j).getAsJsonObject();
jresponses.add((JsonElement)jresponsePy);
String md5 = jresponsePy.getAsJsonObject("response").get("md5")
.getAsString();
if (user.getId_users() > 0L) {
fr.setId_users(user.getId_users());
fr.setJson(jresponsePy.toString());
fr.setMd5(md5);
fr.setFaceDetectionMethodCode(detectionMethod);
fr.setFlgRequestType(1L);
fr.addRichiesta();
fr.save();
}
}
for (File elemento : hsFiles)
elemento.delete();
}
JsonObject joRes = new JsonObject();
if (errMsg.length() == 0) {
String target = "vertices";
numberOfFaces = DBAdapter.countOccurrences(jresponses.toString(), target);
joRes.addProperty("success", "true");
joRes.addProperty("msg", "Trovate in totale " + numberOfFaces + " visi su " +
jresponses.size() + " foto. FaceCached?" + cachedFaces + " : " + msg.toString());
joRes.add("responses", (JsonElement)jresponses);
} else {
joRes.addProperty("success", "false");
joRes.addProperty("msg", "Errore! " + err.toString());
}
DBAdapter.printDebug(debug, "************ _detectFaces_POST 9 RISPOSTA AL CLIENT *********************");
DBAdapter.printDebug(DBAdapter.gsonToString(joRes));
DBAdapter.printDebug(debug, "*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, joRes.toString());
timer.stop();
DBAdapter.printDebug(debug, " _detectFaces_POST. Resp size: Trovate in totale " + numberOfFaces + " visi su " +
jresponses.size() + " foto. FaceCached?" + cachedFaces + " ms " + timer.getDurataMilliSec());
} catch (RuntimeException e) {
JsonObject joRes = new JsonObject();
joRes.addProperty("success", "false");
joRes.addProperty("msg", "Eccezione!! " + e.getMessage());
DBAdapter.printDebug(debug, "************ _detectFaces_POST ECCEZIONE RUNTIME!!!! RISPOSTA AL CLIENT *********************");
DBAdapter.printDebug(DBAdapter.gsonToString(joRes));
DBAdapter.printDebug(debug, "*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, DBAdapter.gsonToString(joRes));
} catch (Exception e) {
e.printStackTrace();
JsonObject joRes = new JsonObject();
joRes.addProperty("success", "false");
joRes.addProperty("msg", "Eccezione!! " + e.getMessage());
DBAdapter.printDebug(debug, "************ _detectFaces_POST ECCEZIONE!!!! RISPOSTA AL CLIENT *********************");
DBAdapter.printDebug(DBAdapter.gsonToString(joRes));
DBAdapter.printDebug(debug, "*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, DBAdapter.gsonToString(joRes));
}
}
public static void main(String[] args) {
String hostname = "localhost";
String db = "cc";
ApplParmFull ap = new ApplParmFull(new ApplParm(14, "//" + hostname + ":1433;databaseName=" + db + ";user=sa;password=T3st000!", null, null, 1, 10, 300));
}
protected boolean checkBasicAuth(HttpServletRequest req, HttpServletResponse res) {
boolean authOk = false;
try {
String[] auth = getBasicAuthorizationHeaders(req, res);
if (auth != null) {
Users bean = getUsersByBasicAuth(req, res);
if (bean.getDBState() == 1) {
authOk = true;
} else {
DBAdapter.printDebug(false, "FaceRestSvlt.checkBasicAuth KO: login-->" + auth[0] + " pwd-->" + auth[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return authOk;
}
protected String getApiBaseUrl() {
return "/fr/face/";
}
protected Users getUsersByBasicAuth(HttpServletRequest req, HttpServletResponse res) {
String[] auth = getBasicAuthorizationHeaders(req, res);
Users bean = new Users(getApFull());
if (auth != null)
bean.findLogonUtente(auth[0], auth[1], req.getRemoteAddr());
return bean;
}
private ResParm trainingCreate(String l_sessionId, List<TrainingImage> trainingImages, int recognizerType) {
ResParm rp = new ResParm();
FaceRecognizer ocvFr = (FaceRecognizer)getCache()
.getIfPresent(l_sessionId + "_" + l_sessionId);
int counter = 0;
String counterKey = l_sessionId + "_" + l_sessionId + "_counter";
Integer Icounter = (Integer)getCache().getIfPresent(counterKey);
if (Icounter != null)
counter = Icounter;
DBAdapter.printDebug(false, "trainingCreate " + trainingImages.size() + " immagini");
if (trainingImages.size() > 0) {
Mat labels = new Mat(trainingImages.size(), 1, CvType.CV_32SC1);
MatOfInt labelsMat = new MatOfInt();
List<Mat> trainingImagesMat = new ArrayList<>();
for (TrainingImage trainingImage : trainingImages) {
File imageFile = new File(trainingImage.getImageFileName());
Mat image = Imgcodecs.imread(imageFile.getAbsolutePath());
Mat grayImage = new Mat();
Imgproc.cvtColor(image, grayImage, 6);
trainingImagesMat.add(grayImage);
labels.put(counter, 0, new double[] { (double)trainingImage.getLabel() });
DBAdapter.printDebug("train: " +
trainingImage.getImageFileName() + " count:" + counter + " label: " + trainingImage.getLabel());
counter++;
}
labels.convertTo((Mat)labelsMat, CvType.CV_32SC1);
ocvFr.train(trainingImagesMat, labels);
getCache().put(counterKey, Integer.valueOf(counter));
}
return rp;
}
private Cache<String, Object> getCache() {
if (this.cache == null)
this.cache = CacheBuilder.newBuilder().maximumSize(100L).expireAfterAccess(100L, TimeUnit.MINUTES).build();
return this.cache;
}
public void _scoring_POST(HttpServletRequest req, HttpServletResponse res) {
boolean debug = false;
boolean debug2 = false;
Timer timer = null;
timer = new Timer();
timer.start();
String result = "";
String json_data_path = null;
String json_res_path = null;
try {
List<String> pythonScript;
JsonObject jo = getApiJsonObject();
DBAdapter.printDebug(debug, "************ _scoringZoo_POST *********************");
DBAdapter.printDebug(debug, "json in arrivo");
DBAdapter.printDebug(DBAdapter.gsonToString(jo));
DBAdapter.printDebug(debug, "*-------------- FINE ---------------------------*");
JsonObject joRes = new JsonObject();
json_data_path = jo.get("json_data_path").getAsString();
json_res_path = jo.get("json_res_path").getAsString();
if (debug || debug2) {
pythonScript = Arrays.asList(getParm("PATH_ZOO_FACE_RECOGNITION_SCRIPT").getTesto(), "--input_json", json_data_path, "--output_json", json_res_path, "-d");
} else {
pythonScript = Arrays.asList(getParm("PATH_ZOO_FACE_RECOGNITION_SCRIPT").getTesto(), "--input_json", json_data_path, "-d");
}
result = ShellWrapper.executeShellScript(pythonScript);
DBAdapter.printDebug(debug, " RESULT from SCRIPT PY: " + String.valueOf(pythonScript) + ":\n" + result);
DBAdapter.printDebug(debug, "\n--------------------------");
joRes = JsonParser.parseString(result.trim()).getAsJsonObject();
DBAdapter.printDebug(debug, "************ _scoringZoo_POST RISPOSTA AL CLIENT *********************");
DBAdapter.printDebug(DBAdapter.gsonToString(joRes));
timer.stop();
int numResponses = -1;
if (joRes.has("responses"))
numResponses = joRes.getAsJsonArray("responses").size();
DBAdapter.printDebug(debug, " _scoringZoo_POST.. Resp size: " + numResponses + " ms " + timer.getDurataMilliSec() + " json_data_path: " + json_data_path);
sendJsonMsgResponse(req, res, joRes.toString());
} catch (Exception e) {
e.printStackTrace();
JsonObject joRes = new JsonObject();
joRes.addProperty("success", "false");
joRes.addProperty("msg", "Ritorno: " + result + "\nEccezione!! " + e.getMessage());
DBAdapter.printDebug(debug, "************ _scoringZoo_POST ECCEZIONE!!!! json_data_path: " + json_data_path + "\nRISPOSTA AL CLIENT *********************");
DBAdapter.printDebug(DBAdapter.gsonToString(joRes));
DBAdapter.printDebug(debug, "*-------------- FINE ---------------------------*");
sendJsonMsgResponse(req, res, DBAdapter.gsonToString(joRes));
}
}
protected Class<? extends _AblRestAdapter> getConcreteApiClass() {
return null;
}
}

View file

@ -0,0 +1 @@
package it.acxent.face.fr.zoo.rest;