diff --git a/Linux_Workspace.vpw b/Linux_Workspace.vpw index 110127c0..1614899f 100644 --- a/Linux_Workspace.vpw +++ b/Linux_Workspace.vpw @@ -8,6 +8,7 @@ + diff --git a/Projects/img_mill/side/workingConfig.tar.bz2 b/Projects/img_mill/side/workingConfig.tar.bz2 new file mode 100644 index 00000000..213765da Binary files /dev/null and b/Projects/img_mill/side/workingConfig.tar.bz2 differ diff --git a/Projects/img_slim/Debug/default.conf b/Projects/img_slim/Debug/default.conf new file mode 100644 index 00000000..f5ac34f3 --- /dev/null +++ b/Projects/img_slim/Debug/default.conf @@ -0,0 +1,25 @@ +NETWORK_SERVER : +{ + NW_LISTEN_PORT = 2222; +}; +KERNEL : +{ + DBC : + { + DATABASE_HOST = "localhost"; + DATABASE_NAME = "dfsl_gunter"; + DATABASE_USER = "dbroot"; + DATABASE_PASSWORD = "123567"; + DATABASE_PORT = 3306; + }; + DNN : + { + PICTURES_BASE = "/srv/vault"; + NET_CONFIG_FILE = "conf/yolo9000.cfg"; + NET_WEIGHTS_FILE = "data/yolo9000.weights"; + DETECTION_PROBABILITY = 0.5; + USE_CLASS_MAP = false; + NET_TARGET_DEVICE = "CPU"; + NET_BACKEND_ENGINE = "DEFAULT"; + }; +}; diff --git a/Projects/img_slim/IM_Backend.cpp b/Projects/img_slim/IM_Backend.cpp new file mode 100644 index 00000000..6c8ffd9c --- /dev/null +++ b/Projects/img_slim/IM_Backend.cpp @@ -0,0 +1,258 @@ +#include "IM_Backend.h" + +// Global Variables + +CSTR gsCFG_ADDRESS; +uint16_t guCFG_PORT = DEFAULT_SERVER_PORT; +CSTR gsCFG_LICENSE; +CSTR gsCFG_DB_SERVER; +CSTR gsCFG_DB_NAME; +CSTR gsCFG_DB_USER; +CSTR gsCFG_DB_PASSWORD; +CSTR gsCFG_PID_FILE = (CSTR) DEFAULT_SERVER_PID_FILE; +SOFTWARE_INFO gsSOFT_INFO; +bool gbCFG_MASTER_ROLE = true; + +bool gModule_GeoFence_Enabled = true; +bool gModule_SMS_Enabled = false; +bool gModule_Email_Enabled = false; +bool gSignal_Handler_Enabled = true; + +#define LOG( X ) m_pLog->Log( "main", 0, X ) +#define LOG_ERROR( X ) m_pLog->Log( "main", 0, _LOG_ERROR, X ) + +IM_Kernel * Kernel = NULL; +basicLogCollection * m_pLog = NULL; +networkServer * NetworkManager = NULL; + +void (*old_update_handler_2)(int); //SIGINT +void (*old_kill_handler_3)(int); //SIGQUIT +void (*old_kill_handler_9)(int); //SIGKILL +void (*old_alarm_handler_14)(int); //SIGALRM +void (*old_kill_handler_15)(int); //SIGTERM + + + + +void signal_SIGKILL_handler( int SIG ){ + if( Kernel!= NULL ){ + if( gSignal_Handler_Enabled ){ + m_pLog->Log("SIG", 0, _LOG_DEBUG, "Shutdown Service by Signal" ); + Kernel->setStatus( TH_ENDED ); // Closing all Connections; + } else { + m_pLog->Log("SIG", 0, _LOG_DEBUG, "Shutdown Signal Handler Disabled" ); + }; + }; +}; + +//#include + +int main (int argc, char *argv[]){ + basicSettingsProvider * SETTINGS = NULL; + bool WBG; // Working Background + bool SSE; // Server Statistics Engine + bool NDC; // No Default Configuration + CSTR FLE_NAME; + CSTR DCF_NAME; + CSTR SSP_NAME; + objectFileLoggingService * FLE = NULL; + objectConsoleLoggingService * CLE = NULL; + // default init + WBG = true; + FLE_NAME = (CSTR) DEFAULT_SERVER_LOG_FILE; + SSE = true; + NDC = true; + DCF_NAME = (CSTR) DEFAULT_SERVER_CONFIG_PATH; + SSP_NAME = (CSTR) DEFAULT_SERVER_SOCKET_PATH; + gsSOFT_INFO.SW_BUILD_DATE = UNIX_TIMESTAMP; + gsSOFT_INFO.DATA_VALID = false; + m_pLog = basicLogCollection::getInstance( _LOG_TIME ); + gsSOFT_INFO.SW_MODE_FLAGS = 0 +#ifdef SKIP_TARGET_LOG + | SW_INFO_NO_TARGET_LOG +#endif +#ifdef HIBERNATE_ENABLE + | SW_INFO_HIBERNATE_ENA +#endif +#ifdef TGD + | SW_INFO_TGD_MOTORS + #ifdef TGD_VERSION_2 + | SW_INFO_TGD_VER_2 + #endif +#endif +#ifdef ENCODER_8192 + | SW_INFO_EU_PROJECT +#endif +#ifdef NO_BLACK_TARGETS + | SW_INFO_NO_BLACK_TARGETS +#endif +#ifndef NO_MOTORS + | SW_INFO_MOTOR_CTRL_ENA +#endif +#ifdef THREADED_FLIP + | SW_INFO_THREAD_FLIP +#endif +#ifndef PRU_SLAVE + | SW_INFO_FLAG_MASTER +#endif +#ifdef DEBUG + | SW_INFO_DEBUG_MODE +#endif + ; + + + // Reading Config + if( argc > 1 ){ + for( int i = 0; i < argc; i++ ){ + switch( argv[i][0] ){ + case '-': + case '\\': + case '/':{ + switch( argv[i][1] ){ + case 'h': case 'H': case 'v': case 'V': case '?':{ + printf( "Image Mill Neural Network Server\n"); + printf( "Software version <%s>\n", VERSION_NUMBER ); + printf( " -h -H This Message\n" ); + printf( " -i -I Interactive Mode\n" ); + return 0; + break; + }; + case 'i': case 'I':{ + WBG = false; + CLE = new objectConsoleLoggingService(); + if( CLE != NULL ) { + m_pLog->addHandler( CLE ); + }; + break; + }; + case 'c': case 'C':{ + DCF_NAME = (CSTR) malloc( MAX_PATH_LEN ); + if( DCF_NAME != NULL ) { + sprintf( DCF_NAME, "%s", argv[i+1] ); + } else { + printf("ERROR!\n\n"); + return -1; + }; + break; + }; + }; + break; + }; + }; + }; + }; + + FLE = new objectFileLoggingService( FLE_NAME ); + if( FLE != NULL ) { + m_pLog->addHandler( FLE ); + }; + LOG("Starting Log Engine!"); + if ( fileExist( DCF_NAME ) ){ + SETTINGS = basicSettingsProvider::getInstance(DCF_NAME); + } else { + SETTINGS = basicSettingsProvider::getInstance(); + }; + + // Demonizing or not + if( WBG ){ + printf( "Image Mill Neural Network Server ver. %s\n", VERSION_NUMBER ); + printf( "Configuration Applied:\n"); + printf( " Service Established %s at %d\n", gsCFG_ADDRESS, guCFG_PORT ); + printf( " PID File: %s\n", gsCFG_PID_FILE ); + printf( " Log File: %s\n", FLE_NAME ); + printf( " License: %s\n", gsCFG_LICENSE ); + printf( " Database Server: %s Database: %s\n", gsCFG_DB_SERVER, gsCFG_DB_NAME ); + if( NDC ){ + printf( " No configuration file (%s) supplied.\n", DCF_NAME); + } else { + printf( " Configuration read from: %s\n", DCF_NAME ); + }; + + //Demonizing + pid_t pid, sid; + sync(); + close( STDIN_FILENO ); + close( STDOUT_FILENO ); + close( STDERR_FILENO ); + + pid = fork(); + if( pid < 0 ){ + return pid; + }; + if( pid > 0 ){ + return 0; + }; + //umask(0); + sid = setsid(); + if (sid < 0) { + return sid; + }; + + pid = fork(); + if( pid < 0 ){ + return pid; + }; + if( pid > 0 ){ + FILE *pPIDF = fopen( gsCFG_PID_FILE, "w+" ); + if( pPIDF ){ + fprintf( pPIDF, "%d\n", pid ); + fclose( pPIDF ); + } + return 0; + }; + }; + + uint8_t m_bKernelExitCode = 0; + + NetworkManager = new networkServer(); + if( NetworkManager != NULL ) { + if( NetworkManager->BootUp() ){ + LOG("Net Service is UP"); + } else { + delete(NetworkManager); + NetworkManager = NULL; + }; + }; + do{ + //Loop till some Restart action + Kernel = IM_Kernel::getInstance(); + if( Kernel == NULL ) { + // Aborting Work + LOG_ERROR( "++++ Kernel failed to born ++++" ); + unlink( gsCFG_PID_FILE ); + LOG( "PID File Deleted" ); + delete( m_pLog ); + return -1; + } else { + if ( Kernel->start() == false ){ + LOG_ERROR("Kernel create failure!"); + } else { + LOG( "++++ Server Started ++++" ); + if( NetworkManager!= NULL ) { + NetworkManager->attachEngine( Kernel ); + }; + //Install Signal Listeners + old_kill_handler_15 = signal( 15, signal_SIGKILL_handler ); + old_kill_handler_9 = signal( 9, signal_SIGKILL_handler ); + // Waiting for Worker to Shut Down + Kernel->stop( false ); + m_bKernelExitCode = Kernel->getExitCause(); + signal( 9, old_kill_handler_9 ); + signal( 15, old_kill_handler_15 ); + }; + //Since Kernel is Singletone Object no need to delete + delete( Kernel ); + LOG( "++++ Server Ended ++++" ); + }; + } while( m_bKernelExitCode > 0 ); + + if( NetworkManager ) delete( NetworkManager ); + //LOG( "++++ CDC DEL ++++" ); + unlink( gsCFG_PID_FILE ); + LOG( "PID File Deleted" ); + if( FLE!= NULL ) delete( FLE ); + if( CLE!= NULL ) delete( CLE ); + delete( m_pLog ); + return(0); +} + diff --git a/Projects/img_slim/IM_Backend.h b/Projects/img_slim/IM_Backend.h new file mode 100644 index 00000000..4db45f83 --- /dev/null +++ b/Projects/img_slim/IM_Backend.h @@ -0,0 +1,48 @@ +/******************************************************************* +* +* DESCRIPTION: Iage Mill project main header file +* +* AUTHOR: Gagua +* +* HISTORY: +* +* DATE:5/29/2019 +* +*******************************************************************/ +#ifndef __IMG_MILL_BACKEND_MAIN_HEADER__ +#define __IMG_MILL_BACKEND_MAIN_HEADER__ + +/** include files **/ + +#include +#include +#include + +#include "../../lib/components/base/basicSettings.h" +#include "../../lib/components/base/basicLogCollection.h" +#include "../../lib/components/base/basicMemoryOperation.h" +#include "../../lib/components/object/objectFileLoggingService.h" +#include "../../lib/components/object/objectConsoleLoggingService.h" +#include "../../lib/data/net/netServer.h" +//#include "../../lib/data/mysql/database_class.h" +#include "IM_Kernel.h" + +/** local definitions **/ +//http://xmsecu.com:8080/ocx/NewActive.exe +/* default settings */ + +/** external functions **/ + +/** external data **/ + +/** internal functions **/ + +/** public data **/ + +/** private data **/ + +/** public functions **/ + +/** private functions **/ + +#endif diff --git a/Projects/img_slim/IM_ClientHandler.cpp b/Projects/img_slim/IM_ClientHandler.cpp new file mode 100644 index 00000000..69629f90 --- /dev/null +++ b/Projects/img_slim/IM_ClientHandler.cpp @@ -0,0 +1,230 @@ +#include "IM_ClientHandler.h" +#include "IM_Kernel.h" + +#include "../../lib/components/base/basicFunctionality.h" +#include "../../lib/data/json/json_tool.h" +#include "../../lib/data/protocol/xmlParser.h" + +#include +#include +#include +#include + + + +#define LOG( X ) m_pLog->Log( "NCH", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG234[256];\ + sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "NCH", this, _LOG_ERROR, _tBfrErrMSG234 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "NCH", this, _LOG_ERROR, X ); +#endif + +// Constructor implementation +IM_ClientHandler::IM_ClientHandler( int SOCKET, networkServiceEngine *ptr ) : networkClientHandler( SOCKET, ptr ), IM_ClientProtocol(){ + m_pLog = basicLogCollection::getInstance(); + m_pDBA = IM_DataBaseAdapter::getInstance(); + m_pMyCurrentJob = NULL; + if( create() ){ + m_pPort = new serverPort( SOCKET ); + if( m_pPort != NULL ){ + setTransport( m_pPort ); +#ifdef DEBUG + LOG("Port Created OK!"); +#endif + if( m_pPort->create() ){ + LOG("Port Init OK!"); + } else LOG_ERROR("Not Connected!"); + } else LOG_ERROR("Port Not Created!"); + } else LOG_ERROR( "Protocol Parser Creation Failed!"); +}; + +// Destructor implementation +IM_ClientHandler::~IM_ClientHandler(){ + if( m_pPort != NULL ) delete( m_pPort ); + if( m_pMyCurrentJob ) free( (IM_JOB *)m_pMyCurrentJob ); +}; + +bool IM_ClientHandler::getStatus( void ){ + if( m_pPort!= NULL ) { + return m_pPort->getStatus(); + }; + return false; +}; + +bool IM_ClientHandler::handleItem( IM_ITEM_DATA *ptr ){ + if( ptr ) { + if( m_pEngine != NULL ) { + IM_Kernel *tKernel = (IM_Kernel *)m_pEngine; + IM_JOB *tJOB; + tJOB = (IM_JOB*)malloc(sizeof(IM_JOB)); + if( tJOB ) { + if( m_pMyCurrentJob ) { + LOG("CLEANNING UNCLEAN JOB!"); + //AnyWay Clean Memory that was Used! + free((IM_JOB *)m_pMyCurrentJob); + }; + m_pMyCurrentJob = (void*) tJOB; + memset( tJOB, 0 , sizeof(IM_JOB)); + tJOB->dbID = ptr->item_id; + tJOB->image_type = ptr->type; + tJOB->job_type = ptr->process_type; + tJOB->width = ptr->width; + tJOB->height = ptr->height; + memcpy( tJOB->md5, ptr->md5, 32 ); + tKernel->enqueueJob( tJOB ); + }; + }; + free( ptr ); + }; + return true; +}; + +bool IM_ClientHandler::packetHandler( protocolPackage *Package ){ + if( Package ) { + if( Package->m_pData ) { + if (Package->m_nSize > 3 ) { + if( Package->m_pData[Package->m_nSize-4] == 13 ) Package->m_pData[Package->m_nSize-4] = 0; + if( Package->m_pData[Package->m_nSize-3] == 10 ) Package->m_pData[Package->m_nSize-3] = 0; + } + Package->m_pData[Package->m_nSize-2] = 0; + Package->m_pData[Package->m_nSize-1] = 0; + LOG( (CSTR) Package->m_pData ); + try{ + XMLNode node1 = XMLNode::parseString( (const char *)Package->m_pData, "root"); + if( !node1.isEmpty() ){ + LOG( node1.getName() ); + if( strstr(node1.getName(),"ClockSync")!=NULL ){ +#ifdef __linux__ + unsigned long long t0, t1, t2, t3; +#else + unsigned __int64 t0, t1, t2, t3; +#endif + XMLNode node3 = node1.getChildNode("t0", 0); + XMLNode node4 = node1.getChildNode("t1", 0); + XMLNode node5 = node1.getChildNode("t2", 0); +/* + t3 = getSHDTimeValue(); +#ifdef __linux__ + t0 = atoll(node3.getText(0)); + t1 = atoll(node4.getText(0)); + t2 = atoll(node5.getText(0)); +#else + t0 = _atoi64(node3.getText(0)); + t1 = _atoi64(node4.getText(0)); + t2 = _atoi64(node5.getText(0)); +#endif + int offset = ((t1-t0)+(t2-t3))/2; + int latency = (t3-t0)-(t2-t1); + int jagajaga = offset+latency; + //if( 0 & correctSHTime( jagajaga ) ){ + // LOG("Time is Synced"); + // g_iTimeDiff = 0; + //} else { + // LOG_ERROR("Time Sync Unucessfull - Will use DIFF!"); + g_iTimeDiff = jagajaga; + //}; +*/ + }; + }; + } catch( exception e ){ + LOG_ERROR("Some Error in XML Parser!"); + }; + // JSON Parsing + try{ + Json::Value root; + Json::Reader reader; + if( !reader.parse( (char *)Package->m_pData, root ) ){ + LOG_ERROR( "The package data is nor a valid JSON data nor valid XML data" ); + return true; + }; + if( root.size() ){ + IM_ITEM_DATA * tData = NULL; + Json::Value tVal; + + tVal = root["item_id"]; + + if( tVal != NULL ){ + int itemID = atoi( tVal.asString().c_str() ) ; + if( itemID > 0 ) { + tData = m_pDBA->getItemDataById( itemID ); + if( tData!= NULL ) tData->process_type = IM_PROC_TYPE_DNN; + }; + }; + + tVal = root["item_md5"]; + if( tVal != NULL ){ + if( strlen( tVal.asString().c_str())== 32 ){ + tData = m_pDBA->getItemDataByMd5( (CSTR) tVal.asString().c_str() ); + if( tData!= NULL ) tData->process_type = IM_PROC_TYPE_DNN; + }; + }; + + tVal = root["process_type"]; + if( tVal != NULL ){ + if( tData!= NULL ) tData->process_type = atoi( tVal.asString().c_str()); + }; + + if( tData!= NULL ){ + return handleItem( tData ); + } else { + m_pPort->sendData( (uint8_t *) "{\"STATUS\":\"ERROR\"}\n", 19 ); + } + }; + } catch ( exception e ){ + LOG_ERROR("Some Error in JSON Parser!"); + m_pPort->sendData( (uint8_t *) "{\"STATUS\":\"ERROR\"}\n", 19 ); + }; + }; + }; + return true; +}; + +bool IM_ClientHandler::dispatchEvent( EVENT_CONTAINER *Evt ){ + if( Evt!= NULL ) { + if( Evt->m_eClass == EVT_CLASS_IMAGE ){ + if( Evt->m_eType == EVT_READY ){ + IM_RESULT *tData = (IM_RESULT*) Evt->m_pEvtData; + if( tData!= NULL ) { + if( tData->pJOB == m_pMyCurrentJob ) { + LOG("JOB Finished Sucessfully!"); + for( int i=0; i < tData->nBoxCount; i++ ){ + m_pDBA->insertItemROI( + tData->pJOB->dbID, + tData->boxes[i].classID, + tData->boxes[i].weight, + tData->boxes[i].x, + tData->boxes[i].y, + tData->boxes[i].width, + tData->boxes[i].height + ); + }; + //handle finished Job + free( (IM_JOB *)m_pMyCurrentJob ); + m_pMyCurrentJob = NULL; + free( (IM_CLASS_BOUNDARY_BOX *)tData->boxes ); + free( (IM_RESULT *)Evt->m_pEvtData ); + Evt->m_pEvtData = NULL; + m_pPort->sendData( (uint8_t *) "{\"STATUS\":\"OK\"}\n", 16 ); + }; + } else { + LOG("JOB Finished Without Detection!"); + free( (IM_JOB *)m_pMyCurrentJob ); + m_pMyCurrentJob = NULL; + m_pPort->sendData( (uint8_t *) "{\"STATUS\":\"ERROR\"}\n", 19 ); + }; + }; + }; + return true; + }; + return false; +}; + + +#undef LOG +#undef LOG_ERROR + + diff --git a/Projects/img_slim/IM_ClientHandler.h b/Projects/img_slim/IM_ClientHandler.h new file mode 100644 index 00000000..15771f4b --- /dev/null +++ b/Projects/img_slim/IM_ClientHandler.h @@ -0,0 +1,34 @@ +#ifndef __IM_CLIENTHANDLER_H_INCL__ +#define __IM_CLIENTHANDLER_H_INCL__ + +#include "../../lib/data/net/netClientHandler.h" +#include "IM_ClientProtocol.h" +#include "IM_DataBaseAdapter.h" + + +/** + * TODO: Add class description + * + * @author Gagua + */ +class IM_ClientHandler : public networkClientHandler, public IM_ClientProtocol{ + private: + basicLogCollection * m_pLog; + void * m_pMyCurrentJob; + IM_DataBaseAdapter * m_pDBA; + protected: + virtual bool packetHandler( protocolPackage *Package ); + public: + // Constructor + explicit IM_ClientHandler( int SOCKET, networkServiceEngine *ptr=NULL ); + + // Destructor + virtual ~IM_ClientHandler(); + virtual bool getStatus( void ); + bool handleItem( IM_ITEM_DATA *ptr ); + virtual bool dispatchEvent( EVENT_CONTAINER *Evt ); +}; + + + +#endif // __IM_CLIENTHANDLER_H_INCL__ diff --git a/Projects/img_slim/IM_ClientProtocol.cpp b/Projects/img_slim/IM_ClientProtocol.cpp new file mode 100644 index 00000000..48a1e802 --- /dev/null +++ b/Projects/img_slim/IM_ClientProtocol.cpp @@ -0,0 +1,57 @@ +#include "IM_ClientProtocol.h" + +#define LOG( X ) m_pLog->Log( "NCP", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG234[256];\ + sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "NCP", this, _LOG_ERROR, _tBfrErrMSG234 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "NCP", this, _LOG_ERROR, X ); +#endif + +// Constructor implementation +IM_ClientProtocol::IM_ClientProtocol() : protocolParser(){ + +}; + +// Destructor implementation +IM_ClientProtocol::~IM_ClientProtocol(){ + +}; + +int IM_ClientProtocol::packetChecker(U8 *Buffer, size_t BufferSize){ + // double enter -> finish package + if( BufferSize > 2 ){ + if( ( Buffer[BufferSize-2] == 13 ) && ( Buffer[BufferSize-1] == 13 ) ) return 0; + }; + if( BufferSize > 3 ){ + if( ( Buffer[BufferSize-4] == 13 ) && ( Buffer[BufferSize-3] == 10 ) && ( Buffer[BufferSize-2] == 13 ) && ( Buffer[BufferSize-1] == 10 ) ) return 0; + }; + return 1; +}; + +protocolPackage *IM_ClientProtocol::packetExtractor(U8 *Buffer, size_t BufferSize){ + protocolPackage *tVal = NULL; + tVal = (protocolPackage *) malloc( sizeof(protocolPackage)); + if(tVal) { + tVal->m_pData = (U8*)malloc( BufferSize+1 ); + if( tVal->m_pData ) { + tVal->m_nCode = 200; + tVal->m_nSize = BufferSize; + memcpy( tVal->m_pData, Buffer, BufferSize ); + tVal->m_pData[BufferSize]=0; + } else { + free( tVal ); + tVal = NULL; + }; + }; + return tVal; +}; + + + +#undef LOG +#undef LOG_ERROR + diff --git a/Projects/img_slim/IM_ClientProtocol.h b/Projects/img_slim/IM_ClientProtocol.h new file mode 100644 index 00000000..41a88538 --- /dev/null +++ b/Projects/img_slim/IM_ClientProtocol.h @@ -0,0 +1,24 @@ +#ifndef __IM_CLIENTPROTOCOL_H_INCL__ +#define __IM_CLIENTPROTOCOL_H_INCL__ + +#include "../../lib/data/protocol/protocol.h" + +/** + * TODO: Add class description + * + * @author Gagua + */ +class IM_ClientProtocol : public protocolParser { + protected: + virtual int packetChecker(U8 *Buffer, size_t BufferSize); + virtual protocolPackage *packetExtractor(U8 *Buffer, size_t BufferSize); + virtual bool packetHandler( protocolPackage *Package ){ return false; }; + public: + // Constructor + IM_ClientProtocol(); + + // Destructor + virtual ~IM_ClientProtocol(); +}; + +#endif // __IM_CLIENTPROTOCOL_H_INCL__ diff --git a/Projects/img_slim/IM_DLibWorker.cpp b/Projects/img_slim/IM_DLibWorker.cpp new file mode 100644 index 00000000..b45eac56 --- /dev/null +++ b/Projects/img_slim/IM_DLibWorker.cpp @@ -0,0 +1,476 @@ +#include "IM_DLibWorker.h" +#include +#include "../../lib/alg/generic/md5.h" +#include "../../lib/components/base/basicFunctionality.h" + +#define LOG( X ) m_pLog->Log( "WDLIB", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG234[256];\ + sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "WDLIB", this, _LOG_ERROR, _tBfrErrMSG234 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "WDLIB", this, _LOG_ERROR, X ); +#endif + + + +// Constructor implementation +IM_DlibWorker::IM_DlibWorker( config_setting_t * Settings ) : basicThread(), m_mBufferProtectorMutex(){ + m_pLog = basicLogCollection::getInstance(); + m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DLIB" ); + m_pEvtHeap = basicEventHeap::getInstance(); + m_pDBA = IM_DataBaseAdapter::getInstance(); + +// m_eBackendEngine = cv::dnn::DNN_BACKEND_DEFAULT; +// m_eTargetDevice = cv::dnn::DNN_TARGET_CPU; + m_pActiveJob = NULL; + +#ifdef DARKNET + m_pDarknetDetector = NULL; +#endif + m_fDetectionProbability = .7f; + m_bUseShapePredictor = false; + m_bUseFaceRecognition = false; + m_bDataIsActive = false; +}; + +// Destructor implementation +IM_DlibWorker::~IM_DlibWorker(){ +#ifdef DARKNET + if( m_pDarknetDetector ) delete( m_pDarknetDetector ); +#endif +}; + +bool IM_DlibWorker::create( void ){ + char tBuff[256]; + if( m_pSettings == NULL ){ + return false; + } else { + config_setting_t * tSetting; + tSetting = config_setting_get_member( m_pSettings, "PICTURES_BASE" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "PICTURES_BASE", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "/srv/vault" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Pictures Base Path! Using default!"); + }; + sprintf( m_pPicturesBase, "%s", config_setting_get_string(tSetting)); + tSetting = config_setting_get_member( m_pSettings, "FACEES_BASE" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "FACEES_BASE", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "/srv/vault/faces" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Face Pictures Base Path! Using default!"); + }; + sprintf( m_pFacesBase, "%s", config_setting_get_string(tSetting)); + tSetting = config_setting_get_member( m_pSettings, "USE_SHAPE_PREDICTOR" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "USE_SHAPE_PREDICTOR", CONFIG_TYPE_BOOL ); + config_setting_set_bool( tSetting, 0 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Class Map Usage Set! Using default!"); + }; + m_bUseShapePredictor = (bool) config_setting_get_bool(tSetting); + if( m_bUseShapePredictor ) { + tSetting = config_setting_get_member( m_pSettings, "USE_FACE_RECOGNITION" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "USE_FACE_RECOGNITION", CONFIG_TYPE_BOOL ); + config_setting_set_bool( tSetting, 0 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Class Map Usage Set! Using default!"); + }; + m_bUseFaceRecognition = (bool) config_setting_get_bool(tSetting); + + tSetting = config_setting_get_member( m_pSettings, "SHAPE_PREDICTOR_LANDMARKS" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "SHAPE_PREDICTOR_LANDMARKS", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "data/shape_predictor_5_face_landmarks.dat" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Net Config File! Using default!"); + }; + sprintf( m_pShapePredictorPath, "%s", config_setting_get_string(tSetting)); + if( m_bUseFaceRecognition ) { + tSetting = config_setting_get_member( m_pSettings, "NET_CONFIG_FILE" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "NET_CONFIG_FILE", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "data/dlib_face_recognition_resnet_model_v1.dat" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Net Weights File! Using default!"); + }; + sprintf( m_pNetModelPath, "%s", config_setting_get_string(tSetting)); + }; + } else m_bUseFaceRecognition = false; + + tSetting = config_setting_get_member( m_pSettings, "DETECTION_PROBABILITY" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "DETECTION_PROBABILITY", CONFIG_TYPE_FLOAT ); + config_setting_set_float( tSetting, 0.5f ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Probability Set! Using default!"); + }; + m_fDetectionProbability = config_setting_get_float(tSetting); + + tSetting = config_setting_get_member( m_pSettings, "OUTPUT_CHOWN_USER" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "OUTPUT_CHOWN_USER", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "www-data" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No CHOWN USER! Using default!"); + }; + sprintf( m_sChownUser, "%s", config_setting_get_string(tSetting)); + + tSetting = config_setting_get_member( m_pSettings, "OUTPUT_CHOWN_GROUP" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "OUTPUT_CHOWN_GROUP", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "www-data" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No CHOWN GROUP! Using default!"); + }; + sprintf( m_sChownGroup, "%s", config_setting_get_string(tSetting)); + + + /* + tSetting = config_setting_get_member( m_pSettings, "USE_CLASS_MAP" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "USE_CLASS_MAP", CONFIG_TYPE_BOOL ); + config_setting_set_bool( tSetting, 0 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Class Map Usage Set! Using default!"); + }; + m_bUseClassMapping = (bool) config_setting_get_bool(tSetting); + if( m_bUseClassMapping ) { + char tMapFileName[1024]; + FILE *fd; + tSetting = config_setting_get_member( m_pSettings, "CLASS_MAP_FILE" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "CLASS_MAP_FILE", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "data/coco9k.map" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Class Map File Set! Using default!"); + }; + sprintf( tMapFileName, "%s", config_setting_get_string(tSetting) ); + fd = fopen( tMapFileName, "r" ); + if( fd ) { + uint32_t tV; + uint32_t idx = 0; + char tB[128]; + while( !feof(fd) ) { + if( fgets( tB, 128, fd ) ){ + tV = atoi( tB )+1; + m_vClassesMap.push_back( tV ); + idx++; + }; + }; + fclose( fd ); + sprintf( tB, "Loadded %d classes map", idx ); + LOG( tB ); + } else { + m_bUseClassMapping = false; + }; + }; + tSetting = config_setting_get_member( m_pSettings, "NET_TARGET_DEVICE" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "NET_TARGET_DEVICE", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "CPU" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Net Target Device! Using default!"); + }; + if( strstr( config_setting_get_string(tSetting), "CPU" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_CPU; + if( strstr( config_setting_get_string(tSetting), "OPENCL_FP16" )!=NULL ){ + m_eTargetDevice = cv::dnn::DNN_TARGET_OPENCL_FP16; + } else { + if( strstr( config_setting_get_string(tSetting), "OPENCL" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_OPENCL; + }; + if( strstr( config_setting_get_string(tSetting), "MYRIAD" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_MYRIAD; + if( strstr( config_setting_get_string(tSetting), "VULKAN" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_VULKAN; + if( strstr( config_setting_get_string(tSetting), "FPGA" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_FPGA; + if( strstr( config_setting_get_string(tSetting), "CUDA_FP16" )!=NULL ){ + m_eTargetDevice = cv::dnn::DNN_TARGET_CUDA_FP16; + } else { + if( strstr( config_setting_get_string(tSetting), "CUDA" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_CUDA; + }; + if( strstr( config_setting_get_string(tSetting), "HDDL" )!=NULL ) m_eTargetDevice = cv::dnn::DNN_TARGET_HDDL; + sprintf( tBuff, "Device: %s", config_setting_get_string(tSetting) ); + LOG( tBuff ); + + tSetting = config_setting_get_member( m_pSettings, "NET_BACKEND_ENGINE" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "NET_BACKEND_ENGINE", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "DEFAULT" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No Net Backend Engine! Using default!"); + }; + if( strstr( config_setting_get_string(tSetting), "DEFAULT" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_DEFAULT; + if( strstr( config_setting_get_string(tSetting), "HALIDE" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_HALIDE; + if( strstr( config_setting_get_string(tSetting), "INFERENCE" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_INFERENCE_ENGINE; + if( strstr( config_setting_get_string(tSetting), "OPENCV" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_OPENCV; + if( strstr( config_setting_get_string(tSetting), "VKCOM" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_VKCOM; + if( strstr( config_setting_get_string(tSetting), "CUDA" )!=NULL ) m_eBackendEngine = cv::dnn::DNN_BACKEND_CUDA; + sprintf( tBuff, "Engine: %s", config_setting_get_string(tSetting) ); + LOG( tBuff ); + */ + basicSettingsProvider::getInstance()->validate(); + }; + if( m_bUseShapePredictor ) { + if( m_bUseFaceRecognition ) { + sprintf( tBuff, "loading Data from disk... Shape: %s Face: %s", m_pShapePredictorPath, m_pNetModelPath ); + } else { + sprintf( tBuff, "loading Data from disk... Shape Predictor: %s ", m_pShapePredictorPath ); + }; + LOG( tBuff ); + if(!fileExist( m_pShapePredictorPath )) { + LOG_ERROR("No Shape Predictor file exists!"); + return false; + }; + if( m_bUseFaceRecognition ) { + if(!fileExist( m_pNetModelPath )) { + LOG_ERROR("No Net Model file exists!"); + return false; + }; + } + } + + m_oFaceDetector = get_frontal_face_detector(); + + if( m_bUseShapePredictor ) { + + deserialize( m_pShapePredictorPath ) >> m_oShapePredictor; + + if( m_bUseFaceRecognition ) { + + deserialize( m_pNetModelPath ) >> m_oNet; + + }; + }; + + return init(); +}; + +std::vector> jitter_image( const matrix& img ){ + // All this function does is make 100 copies of img, all slightly jittered by being + // zoomed, rotated, and translated a little bit differently. They are also randomly + // mirrored left to right. + thread_local dlib::rand rnd; + + std::vector> crops; + for (int i = 0; i < 100; ++i) + crops.push_back(jitter_image(img,rnd)); + + return crops; +}; + +CSTR IM_DlibWorker::m_fSaveFace( matrix &Picture, CSTR md5, uint32_t index ){ + char tPathSrc[1024]; + char tPathDest[1024]; + CSTR nMd5; + CSTR nPath; + sprintf( tPathSrc, "%s/%s_%d.jpg", m_pFacesBase, md5, index ); + LOG("Save Face"); + LOG( tPathSrc ); + save_jpeg( Picture, tPathSrc, 75 ); + nMd5 = MD5File( tPathSrc ); + nPath = buildMd5Path( m_pFacesBase, nMd5, 0755, m_sChownUser, m_sChownGroup ); + sprintf( tPathDest, "%s/%s.jpg", nPath, nMd5 ); + free( nPath ); + //fileCopy( tPathSrc, tPathDest ); + //remove( tPathSrc ); + rename ( tPathSrc, tPathDest ); + ch_chown( tPathDest, m_sChownUser, m_sChownGroup ); + return nMd5; +}; + +IM_RESULT *IM_DlibWorker::m_fImageAnalyzer( cv::Mat &Pic ){ + IM_RESULT * retVal = NULL; + cv_image Picture(Pic); + std::vector> faces; + std::vector dbIDs; + uint32_t idx = 0; + CSTR tVAL = NULL; + for( auto face : m_oFaceDetector( Picture ) ){ + //dlib::rectangle face + if( m_bUseShapePredictor ) { + auto shape = m_oShapePredictor( Picture, face ); + matrix face_chip; + extract_image_chip( Picture, get_face_chip_details( shape, 150, 0.25 ), face_chip ); + tVAL = m_fSaveFace( face_chip, m_pActiveJob->md5, idx ); + faces.push_back( move( face_chip ) ); + } else { + matrix face_chip; + extract_image_chip( Picture, face, face_chip ); + tVAL = m_fSaveFace( face_chip, m_pActiveJob->md5, idx ); + }; + if( tVAL!= NULL ) { + uint32_t tID; + tID = m_pDBA->insertItemFace( m_pActiveJob->dbID, tVAL, face.left(), face.top(), face.width(), face.height() ); + dbIDs.push_back( tID ); + + char tB[64]; + sprintf(tB,"ID:%d", tID); + LOG(tB); + + free( tVAL ); + tVAL = NULL; + }; + idx++; + }; + + if( m_bUseShapePredictor ) { + //if (faces.size() == 0){ + // cout << "No faces found in image!" << endl; + // return 1; + //} + if( m_bUseFaceRecognition ) { + // This call asks the DNN to convert each face image in faces into a 128D vector. + // In this 128D vector space, images from the same person will be close to each other + // but vectors from different people will be far apart. So we can use these vectors to + // identify if a pair of images are from the same person or from different people. + if( faces.size() ) { + //LOG("Have Detected Faces!"); + //std::vector> face_descriptors = m_oNet( faces ); + try{ + for( int idx = 0; idx < faces.size(); idx++ ) { + matrix face_descriptor = mean( mat( m_oNet( jitter_image( faces[idx] ) ) ) ); + //matrix face_descriptor = m_oNet( faces[0] ); + //LOG("Classification Done!"); + for( int i = 0; i < face_descriptor.size(); i++ ) m_pDBA->updateItemFace( dbIDs[idx], i, face_descriptor( i, 0 ) ); + }; + } catch ( std::exception& e ){ + LOG_ERROR( e.what() ); + }; + } else { + LOG("No Faces Found!"); + }; + + //std::vector> face_descriptors = m_oNet( faces ); + + // In particular, one simple thing we can do is face clustering. This next bit of code + // creates a graph of connected faces and then uses the Chinese whispers graph clustering + // algorithm to identify how many people there are and which faces belong to whom. + /* + std::vector edges; + for (size_t i = 0; i < face_descriptors.size(); ++i){ + for (size_t j = i; j < face_descriptors.size(); ++j){ + // Faces are connected in the graph if they are close enough. Here we check if + // the distance between two face descriptors is less than 0.6, which is the + // decision threshold the network was trained to use. Although you can + // certainly use any other threshold you find useful. + if (length(face_descriptors[i]-face_descriptors[j]) < 0.6) + edges.push_back(sample_pair(i,j)); + }; + }; + std::vector labels; + const auto num_clusters = chinese_whispers(edges, labels); + */ + // This will correctly indicate that there are 4 people in the image. + //cout << "number of people found in the image: "<< num_clusters << endl; + + + // Now let's display the face clustering results on the screen. You will see that it + // correctly grouped all the faces. + /* + std::vector win_clusters(num_clusters); + for( size_t cluster_id = 0; cluster_id < num_clusters; ++cluster_id ){ + std::vector> temp; + for( size_t j = 0; j < labels.size(); ++j ){ + if (cluster_id == labels[j]) temp.push_back(faces[j]); + }; + win_clusters[cluster_id].set_title("face cluster " + cast_to_string(cluster_id)); + win_clusters[cluster_id].set_image(tile_images(temp)); + }; + + // Finally, let's print one of the face descriptors to the screen. + cout << "face descriptor for one face: " << trans(face_descriptors[0]) << endl; + + // It should also be noted that face recognition accuracy can be improved if jittering + // is used when creating face descriptors. In particular, to get 99.38% on the LFW + // benchmark you need to use the jitter_image() routine to compute the descriptors, + // like so: + matrix face_descriptor = mean(mat(net(jitter_image(faces[0])))); + cout << "jittered face descriptor for one face: " << trans(face_descriptor) << endl; + // If you use the model without jittering, as we did when clustering the bald guys, it + // gets an accuracy of 99.13% on the LFW benchmark. So jittering makes the whole + // procedure a little more accurate but makes face descriptor calculation slower. + */ + }; + }; + return retVal; +}; + +void IM_DlibWorker::m_fThreadProc( void ){ + m_bThreadStatus = TH_WORKING; + EVENT_CONTAINER *EVT_PTR = NULL; + while( m_bThreadStatus < TH_ENDED ) { + while (!m_bDataIsActive && m_bThreadStatus < TH_ENDED ) SLEEP( 20 ); + if( m_mBufferProtectorMutex.try_lock() ){ + if( m_bDataIsActive ){ + EVT_PTR =(EVENT_CONTAINER *) malloc(sizeof(EVENT_CONTAINER)); + if( EVT_PTR ) { + memset( EVT_PTR, 0, sizeof(EVENT_CONTAINER)); + EVT_PTR->m_eClass = EVT_CLASS_IMAGE; + EVT_PTR->m_eType = EVT_READY; + if( IM_RESULT *tData = m_fImageAnalyzer( m_oWorkingMat ) ){ + //generate detection event + EVT_PTR->m_pEvtData = tData; + } else { + //generate NOT detection event + EVT_PTR->m_pEvtData = NULL; + }; + }; + m_pActiveJob = NULL; + m_bDataIsActive = false; + }; + m_mBufferProtectorMutex.unlock(); + }; + if( EVT_PTR != NULL ) { + m_pEvtHeap->broadcast( EVT_PTR ); + EVT_PTR = NULL; + }; + }; +}; + +bool IM_DlibWorker::enqueueJob( IM_JOB *ptr ){ + if( ptr ) { + char tPath[1024]; + char p1[3]; + char p2[3]; + char p3[3]; + LOG( ptr->md5 ); + memcpy( p1, ptr->md5 , 2); p1[2]=(char)0; + memcpy( p2, ptr->md5+2, 2); p2[2]=(char)0; + memcpy( p3, ptr->md5+4, 2); p3[2]=(char)0; + switch( ptr->image_type ) { + case IM_ITEM_TYPE_JPEG: sprintf( tPath, "%s/%s/%s/%s/%s.jpg", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; + case IM_ITEM_TYPE_PNG: sprintf( tPath, "%s/%s/%s/%s/%s.png", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; + case IM_ITEM_TYPE_GIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; + case IM_ITEM_TYPE_AGIF: sprintf( tPath, "%s/%s/%s/%s/%s.gif", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; + case IM_ITEM_TYPE_TIFF: sprintf( tPath, "%s/%s/%s/%s/%s.tiff", m_pPicturesBase, p1, p2, p3, ptr->md5 ); break; + }; +#ifdef DEBUG + LOG( tPath ); +#endif + Mat Frame = cv::imread( tPath, IMREAD_COLOR ); + try{ + while( m_bThreadStatus < TH_ENDED ) { + if( m_mBufferProtectorMutex.try_lock() ) { + Frame.copyTo( m_oWorkingMat ); +#ifdef DEBUG + cv::imwrite("cur-test-img.jpg", m_oWorkingMat ); + //save_jpeg( m_oInputImg, "cur-test-img.jpg", 75 ); +#endif + m_bDataIsActive = true; + m_pActiveJob = ptr; + m_mBufferProtectorMutex.unlock(); + return true; + } else SLEEP(5); + }; + } catch ( exception e ){ + LOG_ERROR( "Failure during Image Read!" ); + }; + }; + return false; +}; + +#undef LOG +#undef LOG_ERROR diff --git a/Projects/img_slim/IM_DLibWorker.h b/Projects/img_slim/IM_DLibWorker.h new file mode 100644 index 00000000..ae0b9992 --- /dev/null +++ b/Projects/img_slim/IM_DLibWorker.h @@ -0,0 +1,118 @@ +#ifndef __IMAGE_MILL_DLIB_WORKER_HEADER__ +#define __IMAGE_MILL_DLIB_WORKER_HEADER__ + +#include "../../lib/components/base/basicThread.h" +#include "../../lib/components/base/basicMutex.h" +#include "../../lib/components/base/basicSettingsProvider.h" +#include "../../lib/components/base/basicEventHeap.h" + +#include "IM_DataStructs.h" +#include "IM_DataBaseAdapter.h" + +#define DLIB + +#ifdef DLIB + #define GPU + //#include + //#include + #undef GPU +#endif + +#include +#include +#include +#include +#include + +#include +//#include +#include +#include +#include +#include +#include + + +using namespace cv; +using namespace dlib; +using namespace std; + +template