api.neuralobjsearch.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. /**
  3. * Draft and dirty implementation of chunks object detection
  4. */
  5. class NeuralObjSearch {
  6. /**
  7. * binpaths config as key=>value
  8. *
  9. * @var array
  10. */
  11. protected $binpaths = array();
  12. /**
  13. * Base WR web URL
  14. *
  15. * @var string
  16. */
  17. protected $baseUrl = '';
  18. /**
  19. * Stardust process manager instance
  20. *
  21. * @var object
  22. */
  23. protected $stardust = '';
  24. /**
  25. * Cameras object placeholder
  26. *
  27. * @var object
  28. */
  29. protected $cameras = '';
  30. /**
  31. * Storages object placeholder
  32. *
  33. * @var object
  34. */
  35. protected $storages = '';
  36. /**
  37. * Neural detector engine placeholder
  38. *
  39. * @var object
  40. */
  41. protected $detector = '';
  42. /**
  43. * System message helper
  44. *
  45. * @var object
  46. */
  47. protected $messages = '';
  48. /**
  49. * Contains default screenshot options
  50. *
  51. * @var string
  52. */
  53. protected $screenshotOpts = '-loglevel error -frames:v 1 -q:v 15';
  54. /**
  55. * Contains ffmpeg binary path
  56. *
  57. * @var string
  58. */
  59. protected $ffmpgPath = '';
  60. /**
  61. * Default chunk time offset to screenshot
  62. *
  63. * @var string
  64. */
  65. protected $timeOffset = '00:00:01';
  66. //some props that may be configurable in future
  67. protected $confidenceThreshold = 42;
  68. protected $timeLimit = 1200;
  69. protected $cachePath = 'howl/nd';
  70. //some predefined stuff here
  71. const AJAX_CONTAINER = 'neuralobjectssearchcontainer';
  72. const ROUTE_CHAN_DETECT = 'neuralobjects';
  73. const ROUTE_DATE = 'searchondate';
  74. const DETECTOR_PID = 'NEURAL_DETECTOR';
  75. public function __construct() {
  76. $this->setOptions();
  77. $this->initMessages();
  78. $this->initStardust();
  79. }
  80. /**
  81. * Sets required instance properties
  82. *
  83. * @return void
  84. */
  85. protected function setOptions() {
  86. global $ubillingConfig;
  87. $this->binPaths = $ubillingConfig->getBinpaths();
  88. $this->ffmpgPath = $this->binPaths['FFMPG_PATH'];
  89. $webPath = pathinfo($_SERVER['REQUEST_URI']);
  90. $webPath = $webPath['dirname'];
  91. $proto = 'http://';
  92. $this->baseUrl = $proto . $_SERVER['HTTP_HOST'] . $webPath . '/';
  93. }
  94. /**
  95. * Renders AJAX container
  96. *
  97. * @return string
  98. */
  99. public function renderContainer() {
  100. $result = '';
  101. $result .= wf_AjaxLoader();
  102. $result .= wf_AjaxContainer(self::AJAX_CONTAINER, '', '');
  103. $result .= wf_CleanDiv();
  104. return($result);
  105. }
  106. /**
  107. * Inits message helper for further usage
  108. *
  109. * @return void
  110. */
  111. protected function initMessages() {
  112. $this->messages = new UbillingMessageHelper();
  113. }
  114. /**
  115. * Inits process manager
  116. *
  117. * @return void
  118. */
  119. protected function initStardust() {
  120. $this->stardust = new StarDust(self::DETECTOR_PID);
  121. }
  122. /**
  123. * Inits camera instance
  124. *
  125. * @return void
  126. */
  127. protected function initCameras() {
  128. $this->cameras = new Cameras();
  129. }
  130. /**
  131. * Inits storages instance
  132. *
  133. * @return void
  134. */
  135. protected function initStorages() {
  136. $this->storages = new Storages();
  137. }
  138. /**
  139. * Inits neural detector engine API
  140. *
  141. * @return void
  142. */
  143. protected function initDetector() {
  144. $this->detector = new NREngine();
  145. }
  146. /**
  147. * Renders object detection results for some channel
  148. *
  149. * @param string $channelId
  150. * @param array $detectionsArray
  151. *
  152. * @return string
  153. */
  154. protected function renderDetections($channelId, $detectionsArray) {
  155. $result = '';
  156. if (!empty($detectionsArray)) {
  157. $delimiter = ', ';
  158. $chanUrl = Archive::URL_ME . '&' . Archive::ROUTE_VIEW . '=' . $channelId;
  159. $cells = wf_TableCell(__('Time'));
  160. $cells .= wf_TableCell(__('Objects'));
  161. $rows = wf_TableRow($cells, 'row1');
  162. foreach ($detectionsArray as $chunkTimeStamp => $detectedObjects) {
  163. $chunkTime = date("H:i", $chunkTimeStamp);
  164. $chunkDate = date("Y-m-d", $chunkTimeStamp);
  165. $objectsList = '';
  166. if (!empty($detectedObjects)) {
  167. foreach ($detectedObjects as $io => $each) {
  168. $objectsList .= __($each) . $delimiter;
  169. }
  170. }
  171. $objectsList = rtrim($objectsList, $delimiter);
  172. $viewUrl = $chanUrl . '&' . Archive::ROUTE_SHOWDATE . '=' . $chunkDate . '&' . Archive::ROUTE_TIMESEGMENT . '=' . $chunkTime;
  173. $cells = wf_TableCell(wf_Link($viewUrl, $chunkTime, false, 'camlink'));
  174. $cells .= wf_TableCell($objectsList);
  175. $rows .= wf_TableRow($cells, 'row5');
  176. }
  177. $result .= wf_TableBody($rows, '100%', 0, 'resp-table');
  178. } else {
  179. $result .= $this->messages->getStyledMessage(__('Nothing found'), 'warning');
  180. $result .= wf_delimiter();
  181. }
  182. return($result);
  183. }
  184. /**
  185. * Performs fast all chunks object detection for some channel
  186. *
  187. * @param string $channelId
  188. * @param string $date
  189. *
  190. * @return void
  191. */
  192. public function renderObjectDetector($channelId, $date = '') {
  193. $result = '';
  194. if ($this->stardust->notRunning()) {
  195. $this->stardust->start();
  196. set_time_limit($this->timeLimit);
  197. $this->initDetector();
  198. if ($this->detector->isAlive()) {
  199. $this->initCameras();
  200. $this->initStorages();
  201. $cameraId = $this->cameras->getCameraIdByChannel($channelId);
  202. if ($cameraId) {
  203. $dateFrom = $date;
  204. $allCamerasData = $this->cameras->getAllCamerasFullData();
  205. $cameraData = $allCamerasData[$cameraId]['CAMERA'];
  206. $cameraStorageData = $allCamerasData[$cameraId]['STORAGE'];
  207. $dateFromTs = strtotime($dateFrom . ' 00:00:00');
  208. $dateToTs = strtotime($dateFrom . ' 23:59:59');
  209. $minuteBetweenNow = strtotime('-1 minute', time());
  210. $storagePath = $cameraStorageData['path'];
  211. $storagePathLastChar = substr($storagePath, 0, -1);
  212. $howlChunkPath = Storages::PATH_HOWL . '/';
  213. $chunksList = $this->storages->getChannelChunks($cameraData['storageid'], $cameraData['channel']);
  214. $filteredChunks = array();
  215. $detectionsTmp = array();
  216. if (!empty($chunksList)) {
  217. //cache alloc
  218. if (!file_exists($this->cachePath)) {
  219. mkdir($this->cachePath, 0777);
  220. }
  221. if (!file_exists($this->cachePath . '/' . $channelId)) {
  222. mkdir($this->cachePath . '/' . $channelId, 0777);
  223. }
  224. //per chunk hell
  225. foreach ($chunksList as $chunkTimeStamp => $chunkPath) {
  226. if (zb_isTimeStampBetween($dateFromTs, $dateToTs, $chunkTimeStamp)) {
  227. $howlChunkFullPath = str_replace($storagePath, $howlChunkPath, $chunkPath);
  228. $howlChunkFullPath = str_replace('//', '/', $howlChunkFullPath);
  229. //excluding last minute chunk - it may be unfinished now
  230. if ($chunkTimeStamp < $minuteBetweenNow) {
  231. $filteredChunks[$chunkTimeStamp] = $howlChunkFullPath;
  232. }
  233. }
  234. }
  235. if (!empty($filteredChunks)) {
  236. foreach ($filteredChunks as $eachChunk => $eachChunkPath) {
  237. $fsCacheDir = $this->cachePath . '/' . $channelId . '/';
  238. $fsCacheName = $fsCacheDir . $eachChunk . '.ndobj';
  239. $chunkScreenName = $fsCacheDir . $eachChunk . '.jpg';
  240. if (!file_exists($fsCacheName)) {
  241. //print($eachChunkPath . '<br>');
  242. if (!file_exists($chunkScreenName)) {
  243. $command = $this->ffmpgPath . ' -ss ' . $this->timeOffset . ' -i ' . $chunkPath . ' ' . $this->screenshotOpts . ' ' . $chunkScreenName;
  244. print($command.'<br>');
  245. // shell_exec($command);
  246. }
  247. // $chunkDetections = $this->detector->detectObjects($eachUrl);
  248. // if (isset($chunkDetections['detections'])) {
  249. // if (!empty($chunkDetections['detections'])) {
  250. // foreach ($chunkDetections as $io => $each) {
  251. // $chunkDatetime = date("Y-m-d H:i:s", $eachChunk);
  252. // $objectsList = array();
  253. // foreach ($chunkDetections['detections'] as $io => $each) {
  254. // if ($each['confidence'] >= $this->confidenceThreshold) {
  255. // $objectsList [] = $each['label'];
  256. // }
  257. // }
  258. //
  259. // if (!empty($objectsList)) {
  260. // $detectionsTmp[$eachChunk] = $objectsList;
  261. // }
  262. // //filling chunk cache
  263. // file_put_contents($fsCacheName, json_encode($objectsList));
  264. // }
  265. // }
  266. // }
  267. } else {
  268. //reading from cache
  269. $rawObjList = file_get_contents($fsCacheName);
  270. $rawObjList = json_decode($rawObjList, true);
  271. if (!empty($rawObjList)) {
  272. $detectionsTmp[$eachChunk] = $rawObjList;
  273. }
  274. }
  275. }
  276. }
  277. if (!empty($detectionsTmp)) {
  278. $result .= $this->renderDetections($channelId, $detectionsTmp);
  279. }
  280. }
  281. } else {
  282. $result .= $this->messages->getStyledMessage(__('Camera') . ' ' . __('not exists'), 'error');
  283. $result .= wf_delimiter();
  284. }
  285. } else {
  286. $result .= $this->messages->getStyledMessage(__('Neural object recognition service now is offline'), 'error');
  287. $result .= wf_delimiter();
  288. }
  289. $this->stardust->stop();
  290. } else {
  291. $result .= $this->messages->getStyledMessage(__('Neural network is busy at this moment'), 'warning');
  292. $result .= wf_delimiter();
  293. }
  294. die($result);
  295. }
  296. }