Passed
Push — self-contained-model ( be8120...e0f8be )
by Matias
03:52
created

ImageProcessingContext::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 4
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017-2020 Matias De lellis <[email protected]>
4
 * @copyright Copyright (c) 2018, Branko Kokanovic <[email protected]>
5
 *
6
 * @author Branko Kokanovic <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
namespace OCA\FaceRecognition\BackgroundJob\Tasks;
25
26
use OCP\Image as OCP_Image;
27
28
use OCP\Files\File;
29
use OCP\Files\Folder;
30
use OCP\IUser;
31
32
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionBackgroundTask;
33
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionContext;
34
35
use OCA\FaceRecognition\Db\Face;
36
use OCA\FaceRecognition\Db\Image;
37
use OCA\FaceRecognition\Db\ImageMapper;
38
39
use OCA\FaceRecognition\Helper\Requirements;
40
41
use OCA\FaceRecognition\Model\DlibCnnModel;
42
use OCA\FaceRecognition\Model\ModelManager;
43
44
use OCA\FaceRecognition\Service\FileService;
45
use OCA\FaceRecognition\Service\SettingsService;
46
47
/**
48
 * Plain old PHP object holding all information
49
 * that are needed to process all faces from one image
50
 */
51
class ImageProcessingContext {
52
	/** @var string Path to the image being processed */
53
	private $imagePath;
54
55
	/** @var string Path to temporary, resized image */
56
	private $tempPath;
57
58
	/** @var float Ratio of resized image, when scaling it */
59
	private $ratio;
60
61
	/** @var array<Face> All found faces in image */
62
	private $faces;
63
64
	/**
65
	 * @var bool True if detection should be skipped, but image should be marked as processed.
66
	 * If this is set, $tempPath and $ratio will be invalid and $faces should be empty array.
67
	 */
68
	private $skipDetection;
69
70
	public function __construct(string $imagePath, string $tempPath, float $ratio, bool $skipDetection) {
71
		$this->imagePath = $imagePath;
72
		$this->tempPath = $tempPath;
73
		$this->ratio = $ratio;
74
		$this->faces = array();
75
		$this->skipDetection = $skipDetection;
76
	}
77
78
	public function getImagePath(): string {
79
		return $this->imagePath;
80
	}
81
82
	public function getTempPath(): string {
83
		return $this->tempPath;
84
	}
85
86
	public function getRatio(): float {
87
		return $this->ratio;
88
	}
89
90
	public function getSkipDetection(): bool {
91
		return $this->skipDetection;
92
	}
93
94
	/**
95
	 * Gets all faces
96
	 *
97
	 * @return Face[] Array of faces
98
	 */
99
	public function getFaces(): array {
100
		return $this->faces;
101
	}
102
103
	/**
104
	 * @param array<Face> $faces Array of faces to set
105
	 */
106
	public function setFaces($faces) {
107
		$this->faces = $faces;
108
	}
109
}
110
111
/**
112
 * Taks that get all images that are still not processed and processes them.
113
 * Processing image means that each image is prepared, faces extracted form it,
114
 * and for each found face - face descriptor is extracted.
115
 */
116
class ImageProcessingTask extends FaceRecognitionBackgroundTask {
117
	/** @var ImageMapper Image mapper*/
118
	protected $imageMapper;
119
120
	/** @var FileService */
121
	protected $fileService;
122
123
	/** @var SettingsService */
124
	protected $settingsService;
125
126
	/** @var ModelManager */
127
	protected $modelManager;
128
129
	/** @var  DlibCnnModel */
130
	private $model;
131
132
	/** @var int|null Maximum image area (cached, so it is not recalculated for each image) */
133
	private $maxImageAreaCached;
134
135
	/**
136
	 * @param ImageMapper $imageMapper Image mapper
137
	 * @param FileService $fileService
138
	 * @param SettingsService $settingsService
139
	 * @param ModelManager $modelManager Model manager
140
	 */
141
	public function __construct(ImageMapper     $imageMapper,
142
	                            FileService     $fileService,
143
	                            SettingsService $settingsService,
144
	                            ModelManager    $modelManager)
145
	{
146
		parent::__construct();
147
148
		$this->imageMapper        = $imageMapper;
149
		$this->fileService        = $fileService;
150
		$this->settingsService    = $settingsService;
151
		$this->modelManager       = $modelManager;
152
153
		$this->model              = null;
154
		$this->maxImageAreaCached = null;
155
	}
156
157
	/**
158
	 * @inheritdoc
159
	 */
160
	public function description() {
161
		return "Process all images to extract faces";
162
	}
163
164
	/**
165
	 * @inheritdoc
166
	 */
167
	public function execute(FaceRecognitionContext $context) {
168
		$this->setContext($context);
169
170
		$this->logInfo('NOTE: Starting face recognition. If you experience random crashes after this point, please look FAQ at https://github.com/matiasdelellis/facerecognition/wiki/FAQ');
171
172
		// Get current model.
173
		$modelVersion = $this->settingsService->getCurrentFaceModel();
174
		$this->model = $this->modelManager->getModel($modelVersion);
175
176
		// Open model.
177
		$this->model->open();
178
179
		$images = $context->propertyBag['images'];
180
		foreach($images as $image) {
181
			yield;
182
183
			$startMillis = round(microtime(true) * 1000);
184
185
			try {
186
				$imageProcessingContext = $this->findFaces($this->model, $image);
187
188
				if (($imageProcessingContext !== null) && ($imageProcessingContext->getSkipDetection() === false)) {
189
					$this->populateDescriptors($this->model, $imageProcessingContext);
190
				}
191
192
				if ($imageProcessingContext === null) {
193
					continue;
194
				}
195
196
				$endMillis = round(microtime(true) * 1000);
197
				$duration = max($endMillis - $startMillis, 0);
198
				$this->imageMapper->imageProcessed($image, $imageProcessingContext->getFaces(), $duration);
199
			} catch (\Exception $e) {
200
				if ($e->getMessage() === "std::bad_alloc") {
201
					throw new \RuntimeException("Not enough memory to run face recognition! Please look FAQ at https://github.com/matiasdelellis/facerecognition/wiki/FAQ");
202
				}
203
				$this->logInfo('Faces found: 0. Image will be skipped because of the following error: ' . $e->getMessage());
204
				$this->logDebug($e);
205
				$this->imageMapper->imageProcessed($image, array(), 0, $e);
206
			} finally {
207
				$this->fileService->clean();
208
			}
209
		}
210
211
		return true;
212
	}
213
214
	/**
215
	 * Given an image, it finds all faces on it.
216
	 * If image should be skipped, returns null.
217
	 * If there is any error, throws exception
218
	 *
219
	 * @param DlibCnnModel $model Resnet model
220
	 * @param Image $image Image to find faces on
221
	 * @return ImageProcessingContext|null Generated context that hold all information needed later for this image
222
	 */
223
	private function findFaces(DlibCnnModel $model, Image $image) {
224
		// todo: check if this hits I/O (database, disk...), consider having lazy caching to return user folder from user
225
		$file = $this->fileService->getFileById($image->getFile(), $image->getUser());
226
227
		if (empty($file)) {
228
			// If we cannot find a file probably it was deleted out of our control and we must clean our tables.
229
			$this->settingsService->setNeedRemoveStaleImages(true, $image->user);
230
			$this->logInfo('File with ID ' . $image->file . ' doesn\'t exist anymore, skipping it');
231
			return null;
232
		}
233
234
		$imagePath = $this->fileService->getLocalFile($file);
235
236
		$this->logInfo('Processing image ' . $imagePath);
237
		$imageProcessingContext = $this->prepareImage($imagePath);
238
		if ($imageProcessingContext->getSkipDetection() === true) {
239
			$this->logInfo('Faces found: 0 (image will be skipped because it is too small)');
240
			return $imageProcessingContext;
241
		}
242
243
		// Detect faces from model
244
		$facesFound = $model->detectFaces($imageProcessingContext->getTempPath());
245
246
		// Convert from dictionary of faces to our Face Db Entity
247
		$faces = array();
248
		foreach ($facesFound as $faceFound) {
249
			$face = Face::fromModel($image->getId(), $faceFound);
250
			$face->normalizeSize($imageProcessingContext->getRatio());
251
			$faces[] = $face;
252
		}
253
254
		$imageProcessingContext->setFaces($faces);
255
		$this->logInfo('Faces found: ' . count($faces));
256
257
		return $imageProcessingContext;
258
	}
259
260
	/**
261
	 * Given an image, it will rotate, scale and save image to temp location, ready to be consumed by pdlib.
262
	 *
263
	 * @param string $imagePath Path to image on disk
264
	 *
265
	 * @return ImageProcessingContext Generated context that hold all information needed later for this image.
266
	 */
267
	private function prepareImage(string $imagePath) {
268
		$image = new OCP_Image(null, $this->context->logger->getLogger(), $this->context->config);
269
		$image->loadFromFile($imagePath);
270
		$image->fixOrientation();
271
272
		if (!$image->valid()) {
273
			throw new \RuntimeException("Image is not valid, probably cannot be loaded");
274
		}
275
276
		// Ignore processing of images that are not large enough.
277
		$minImageSize = $this->settingsService->getMinimumImageSize();
278
		if ((imagesx($image->resource()) < $minImageSize) || (imagesy($image->resource()) < $minImageSize)) {
279
			return new ImageProcessingContext($imagePath, "", -1, true);
280
		}
281
282
		$maxImageArea = $this->getMaxImageArea();
283
		$ratio = $this->resizeImage($image, $maxImageArea);
284
285
		$tempfile = $this->fileService->getTemporaryFile(pathinfo($imagePath, PATHINFO_EXTENSION));
286
		$image->save($tempfile);
287
288
		return new ImageProcessingContext($imagePath, $tempfile, $ratio, false);
289
	}
290
291
	/**
292
	 * Resizes the image to reach max image area, but preserving ratio.
293
	 * Stolen and adopted from OC_Image->resize() (difference is that this returns ratio of resize.)
294
	 *
295
	 * @param Image $image Image to resize
296
	 * @param int $maxImageArea The maximum size of image we can handle (in pixels^2).
297
	 *
298
	 * @return float Ratio of resize. 1 if there was no resize
299
	 */
300
	public function resizeImage(OCP_Image $image, int $maxImageArea): float {
301
		if (!$image->valid()) {
302
			$message = "Image is not valid, probably cannot be loaded";
303
			$this->logInfo($message);
304
			throw new \RuntimeException($message);
305
		}
306
307
		$widthOrig = imagesx($image->resource());
308
		$heightOrig = imagesy($image->resource());
309
		if (($widthOrig <= 0) || ($heightOrig <= 0)) {
310
			$message = "Image is having non-positive width or height, cannot continue";
311
			$this->logInfo($message);
312
			throw new \RuntimeException($message);
313
		}
314
315
		$areaRatio = $maxImageArea / ($widthOrig * $heightOrig);
316
		$scaleFactor = sqrt($areaRatio);
317
318
		$newWidth = intval(round($widthOrig * $scaleFactor));
319
		$newHeight = intval(round($heightOrig * $scaleFactor));
320
321
		$success = $image->preciseResize($newWidth, $newHeight);
322
		if ($success === false) {
323
			throw new \RuntimeException("Error during image resize");
324
		}
325
326
		$this->logDebug(sprintf('Image scaled from %dx%d to %dx%d (since max image area is %d pixels^2)',
327
			$widthOrig, $heightOrig, $newWidth, $newHeight, $maxImageArea));
328
329
		return 1 / $scaleFactor;
330
	}
331
332
	/**
333
	 * Gets all face descriptors in a given image processing context. Populates "descriptor" in array of faces.
334
	 *
335
	 * @param DlibCnnModel $model Resnet model
336
	 * @param ImageProcessingContext Image processing context
337
	 */
338
	private function populateDescriptors(DlibCnnModel $model, ImageProcessingContext $imageProcessingContext) {
339
		$faces = $imageProcessingContext->getFaces();
340
341
		foreach($faces as &$face) {
342
			// For each face, we want to detect landmarks and compute descriptors.
343
			// We use already resized image (from temp, used to detect faces) for this.
344
			// (better would be to work with original image, but that will require
345
			// another orientation fix and another save to the temp)
346
			// But, since our face coordinates are already changed to align to original image,
347
			// we need to fix them up to align them to temp image here.
348
			$normalizedFace = clone $face;
349
			$normalizedFace->normalizeSize(1.0 / $imageProcessingContext->getRatio());
350
351
			// We are getting face landmarks from already prepared (temp) image (resized and with orienation fixed).
352
			$landmarks = $model->detectLandmarks($imageProcessingContext->getTempPath(), array(
353
				"left" => $normalizedFace->left, "top" => $normalizedFace->top,
354
				"bottom" => $normalizedFace->bottom, "right" => $normalizedFace->right));
355
			$face->landmarks = $landmarks['parts'];
356
357
			$descriptor = $model->computeDescriptor($imageProcessingContext->getTempPath(), $landmarks);
358
			$face->descriptor = $descriptor;
359
		}
360
	}
361
362
	/**
363
	 * Obtains max image area lazily (from cache, or calculates it and puts it to cache)
364
	 *
365
	 * @return int Max image area (in pixels^2)
366
	 */
367
	private function getMaxImageArea(): int {
368
		if (!is_null($this->maxImageAreaCached)) {
369
			return $this->maxImageAreaCached;
370
		}
371
372
		$this->maxImageAreaCached = $this->calculateMaxImageArea();
373
		return $this->maxImageAreaCached;
374
	}
375
376
	/**
377
	 * Calculates max image area. This is separate function, as there are several levels of user overrides.
378
	 *
379
	 * @return int Max image area (in pixels^2)
380
	 */
381
	private function calculateMaxImageArea(): int {
382
		// First check if we are provided value from command line
383
		//
384
		if (
385
			(array_key_exists('max_image_area', $this->context->propertyBag)) &&
386
			(!is_null($this->context->propertyBag['max_image_area']))
387
		) {
388
				return $this->context->propertyBag['max_image_area'];
389
		}
390
391
		// Check if admin persisted this setting in config and it is valid value
392
		//
393
		$maxImageArea = $this->settingsService->getMaximumImageArea();
394
		if ($maxImageArea > 0) {
395
			return $maxImageArea;
396
		}
397
398
		// Calculate it from memory
399
		//
400
		$allowedMemory = $this->context->propertyBag['memory'];
401
402
		// Based on amount on memory PHP have, we will determine maximum amount of image size that we need to scale to.
403
		// This reasoning and calculations are all based on analysis given here:
404
		// https://github.com/matiasdelellis/facerecognition/wiki/Performance-analysis-of-DLib%E2%80%99s-CNN-face-detection
405
		$maxImageArea = intval(($allowedMemory) / SettingsService::MEMORY_AREA_RELATIONSHIP); // TODO: Maybe another helper.
406
407
		return $maxImageArea;
408
	}
409
410
}