Passed
Push — settings-service ( 7803f5...566350 )
by Matias
04:05
created

ImageProcessingTask::getMaxImageArea()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 6
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\Service\FileService;
42
use OCA\FaceRecognition\Service\SettingsService;
43
44
/**
45
 * Plain old PHP object holding all information
46
 * that are needed to process all faces from one image
47
 */
48
class ImageProcessingContext {
49
	/** @var string Path to the image being processed */
50
	private $imagePath;
51
52
	/** @var string Path to temporary, resized image */
53
	private $tempPath;
54
55
	/** @var float Ratio of resized image, when scaling it */
56
	private $ratio;
57
58
	/** @var array<Face> All found faces in image */
59
	private $faces;
60
61
	/**
62
	 * @var bool True if detection should be skipped, but image should be marked as processed.
63
	 * If this is set, $tempPath and $ratio will be invalid and $faces should be empty array.
64
	 */
65
	private $skipDetection;
66
67
	public function __construct(string $imagePath, string $tempPath, float $ratio, bool $skipDetection) {
68
		$this->imagePath = $imagePath;
69
		$this->tempPath = $tempPath;
70
		$this->ratio = $ratio;
71
		$this->faces = array();
72
		$this->skipDetection = $skipDetection;
73
	}
74
75
	public function getImagePath(): string {
76
		return $this->imagePath;
77
	}
78
79
	public function getTempPath(): string {
80
		return $this->tempPath;
81
	}
82
83
	public function getRatio(): float {
84
		return $this->ratio;
85
	}
86
87
	public function getSkipDetection(): bool {
88
		return $this->skipDetection;
89
	}
90
91
	/**
92
	 * Gets all faces
93
	 *
94
	 * @return Face[] Array of faces
95
	 */
96
	public function getFaces(): array {
97
		return $this->faces;
98
	}
99
100
	/**
101
	 * @param array<Face> $faces Array of faces to set
102
	 */
103
	public function setFaces($faces) {
104
		$this->faces = $faces;
105
	}
106
}
107
108
/**
109
 * Taks that get all images that are still not processed and processes them.
110
 * Processing image means that each image is prepared, faces extracted form it,
111
 * and for each found face - face descriptor is extracted.
112
 */
113
class ImageProcessingTask extends FaceRecognitionBackgroundTask {
114
	/** @var ImageMapper Image mapper*/
115
	protected $imageMapper;
116
117
	/** @var FileService */
118
	private $fileService;
119
120
	/** @var int|null Maximum image area (cached, so it is not recalculated for each image) */
121
	private $maxImageAreaCached;
122
123
	/**
124
	 * @param ImageMapper $imageMapper Image mapper
125
	 * @param FileService $fileService
126
	 * @param SettingsService $settingsService
127
	 */
128
	public function __construct(ImageMapper     $imageMapper,
129
	                            FileService     $fileService,
130
	                            SettingsService $settingsService)
131
	{
132
		parent::__construct();
133
134
		$this->imageMapper        = $imageMapper;
135
		$this->fileService        = $fileService;
136
		$this->settingsService    = $settingsService;
0 ignored issues
show
Bug Best Practice introduced by
The property settingsService does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
137
		$this->maxImageAreaCached = null;
138
	}
139
140
	/**
141
	 * @inheritdoc
142
	 */
143
	public function description() {
144
		return "Process all images to extract faces";
145
	}
146
147
	/**
148
	 * @inheritdoc
149
	 */
150
	public function execute(FaceRecognitionContext $context) {
151
		$this->setContext($context);
152
153
		$requirements = new Requirements($context->modelService, $this->settingsService->getCurrentFaceModel());
154
155
		$images = $context->propertyBag['images'];
156
157
		$cfd = new \CnnFaceDetection($requirements->getFaceDetectionModel());
0 ignored issues
show
Bug introduced by
The type CnnFaceDetection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
158
		$fld = new \FaceLandmarkDetection($requirements->getLandmarksDetectionModel());
0 ignored issues
show
Bug introduced by
The type FaceLandmarkDetection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
159
		$fr = new \FaceRecognition($requirements->getFaceRecognitionModel());
0 ignored issues
show
Bug introduced by
The type FaceRecognition was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
160
161
		$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');
162
163
		foreach($images as $image) {
164
			yield;
165
166
			$startMillis = round(microtime(true) * 1000);
167
168
			try {
169
				$imageProcessingContext = $this->findFaces($cfd, $image);
170
171
				if (($imageProcessingContext !== null) && ($imageProcessingContext->getSkipDetection() === false)) {
172
					$this->populateDescriptors($fld, $fr, $imageProcessingContext);
173
				}
174
175
				if ($imageProcessingContext === null) {
176
					continue;
177
				}
178
179
				$endMillis = round(microtime(true) * 1000);
180
				$duration = max($endMillis - $startMillis, 0);
181
				$this->imageMapper->imageProcessed($image, $imageProcessingContext->getFaces(), $duration);
182
			} catch (\Exception $e) {
183
				if ($e->getMessage() === "std::bad_alloc") {
184
					throw new \RuntimeException("Not enough memory to run face recognition! Please look FAQ at https://github.com/matiasdelellis/facerecognition/wiki/FAQ");
185
				}
186
				$this->logInfo('Faces found: 0. Image will be skipped because of the following error: ' . $e->getMessage());
187
				$this->logDebug($e);
188
				$this->imageMapper->imageProcessed($image, array(), 0, $e);
189
			} finally {
190
				$this->fileService->clean();
191
			}
192
		}
193
194
		return true;
195
	}
196
197
	/**
198
	 * Given an image, it finds all faces on it.
199
	 * If image should be skipped, returns null.
200
	 * If there is any error, throws exception
201
	 *
202
	 * @param \CnnFaceDetection $cfd Face detection model
203
	 * @param Image $image Image to find faces on
204
	 * @return ImageProcessingContext|null Generated context that hold all information needed later for this image
205
	 */
206
	private function findFaces(\CnnFaceDetection $cfd, Image $image) {
207
		// todo: check if this hits I/O (database, disk...), consider having lazy caching to return user folder from user
208
		$file = $this->fileService->getFileById($image->getFile(), $image->getUser());
209
210
		if (empty($file)) {
211
			// If we cannot find a file probably it was deleted out of our control and we must clean our tables.
212
			$this->settingsService->setNeedRemoveStaleImages(true, $image->user);
213
			$this->logInfo('File with ID ' . $image->file . ' doesn\'t exist anymore, skipping it');
214
			return null;
215
		}
216
217
		$imagePath = $this->fileService->getLocalFile($file);
218
219
		$this->logInfo('Processing image ' . $imagePath);
220
		$imageProcessingContext = $this->prepareImage($imagePath);
221
		if ($imageProcessingContext->getSkipDetection() === true) {
222
			$this->logInfo('Faces found: 0 (image will be skipped because it is too small)');
223
			return $imageProcessingContext;
224
		}
225
226
		// Detect faces from model
227
		$facesFound = $cfd->detect($imageProcessingContext->getTempPath());
228
229
		// Convert from dictionary of faces to our Face Db Entity
230
		$faces = array();
231
		foreach ($facesFound as $faceFound) {
232
			$face = Face::fromModel($image->getId(), $faceFound);
233
			$face->normalizeSize($imageProcessingContext->getRatio());
234
			$faces[] = $face;
235
		}
236
237
		$imageProcessingContext->setFaces($faces);
238
		$this->logInfo('Faces found: ' . count($faces));
239
240
		return $imageProcessingContext;
241
	}
242
243
	/**
244
	 * Given an image, it will rotate, scale and save image to temp location, ready to be consumed by pdlib.
245
	 *
246
	 * @param string $imagePath Path to image on disk
247
	 *
248
	 * @return ImageProcessingContext Generated context that hold all information needed later for this image.
249
	 */
250
	private function prepareImage(string $imagePath) {
251
		$image = new OCP_Image(null, $this->context->logger->getLogger(), $this->context->config);
252
		$image->loadFromFile($imagePath);
253
		$image->fixOrientation();
254
255
		if (!$image->valid()) {
256
			throw new \RuntimeException("Image is not valid, probably cannot be loaded");
257
		}
258
259
		// Ignore processing of images that are not large enough.
260
		$minImageSize = $this->settingsService->getMinimumImageSize();
261
		if ((imagesx($image->resource()) < $minImageSize) || (imagesy($image->resource()) < $minImageSize)) {
262
			return new ImageProcessingContext($imagePath, "", -1, true);
263
		}
264
265
		$maxImageArea = $this->getMaxImageArea();
266
		$ratio = $this->resizeImage($image, $maxImageArea);
267
268
		$tempfile = $this->fileService->getTemporaryFile(pathinfo($imagePath, PATHINFO_EXTENSION));
269
		$image->save($tempfile);
270
271
		return new ImageProcessingContext($imagePath, $tempfile, $ratio, false);
272
	}
273
274
	/**
275
	 * Resizes the image to reach max image area, but preserving ratio.
276
	 * Stolen and adopted from OC_Image->resize() (difference is that this returns ratio of resize.)
277
	 *
278
	 * @param Image $image Image to resize
279
	 * @param int $maxImageArea The maximum size of image we can handle (in pixels^2).
280
	 *
281
	 * @return float Ratio of resize. 1 if there was no resize
282
	 */
283
	public function resizeImage(OCP_Image $image, int $maxImageArea): float {
284
		if (!$image->valid()) {
285
			$message = "Image is not valid, probably cannot be loaded";
286
			$this->logInfo($message);
287
			throw new \RuntimeException($message);
288
		}
289
290
		$widthOrig = imagesx($image->resource());
291
		$heightOrig = imagesy($image->resource());
292
		if (($widthOrig <= 0) || ($heightOrig <= 0)) {
293
			$message = "Image is having non-positive width or height, cannot continue";
294
			$this->logInfo($message);
295
			throw new \RuntimeException($message);
296
		}
297
298
		$areaRatio = $maxImageArea / ($widthOrig * $heightOrig);
299
		$scaleFactor = sqrt($areaRatio);
300
301
		$newWidth = intval(round($widthOrig * $scaleFactor));
302
		$newHeight = intval(round($heightOrig * $scaleFactor));
303
304
		$success = $image->preciseResize($newWidth, $newHeight);
305
		if ($success === false) {
306
			throw new \RuntimeException("Error during image resize");
307
		}
308
309
		$this->logDebug(sprintf('Image scaled from %dx%d to %dx%d (since max image area is %d pixels^2)',
310
			$widthOrig, $heightOrig, $newWidth, $newHeight, $maxImageArea));
311
312
		return 1 / $scaleFactor;
313
	}
314
315
	/**
316
	 * Gets all face descriptors in a given image processing context. Populates "descriptor" in array of faces.
317
	 *
318
	 * @param \FaceLandmarkDetection $fld Landmark detection model
319
	 * @param \FaceRecognition $fr Face recognition model
320
	 * @param ImageProcessingContext Image processing context
321
	 */
322
	private function populateDescriptors(\FaceLandmarkDetection $fld, \FaceRecognition $fr, ImageProcessingContext $imageProcessingContext) {
323
		$faces = $imageProcessingContext->getFaces();
324
325
		foreach($faces as &$face) {
326
			// For each face, we want to detect landmarks and compute descriptors.
327
			// We use already resized image (from temp, used to detect faces) for this.
328
			// (better would be to work with original image, but that will require
329
			// another orientation fix and another save to the temp)
330
			// But, since our face coordinates are already changed to align to original image,
331
			// we need to fix them up to align them to temp image here.
332
			$normalizedFace = clone $face;
333
			$normalizedFace->normalizeSize(1.0 / $imageProcessingContext->getRatio());
334
335
			// We are getting face landmarks from already prepared (temp) image (resized and with orienation fixed).
336
			$landmarks = $fld->detect($imageProcessingContext->getTempPath(), array(
337
				"left" => $normalizedFace->left, "top" => $normalizedFace->top,
338
				"bottom" => $normalizedFace->bottom, "right" => $normalizedFace->right));
339
			$face->landmarks = $landmarks['parts'];
340
341
			$descriptor = $fr->computeDescriptor($imageProcessingContext->getTempPath(), $landmarks);
342
			$face->descriptor = $descriptor;
343
		}
344
	}
345
346
	/**
347
	 * Obtains max image area lazily (from cache, or calculates it and puts it to cache)
348
	 *
349
	 * @return int Max image area (in pixels^2)
350
	 */
351
	private function getMaxImageArea(): int {
352
		if (!is_null($this->maxImageAreaCached)) {
353
			return $this->maxImageAreaCached;
354
		}
355
356
		$this->maxImageAreaCached = $this->calculateMaxImageArea();
357
		return $this->maxImageAreaCached;
358
	}
359
360
	/**
361
	 * Calculates max image area. This is separate function, as there are several levels of user overrides.
362
	 *
363
	 * @return int Max image area (in pixels^2)
364
	 */
365
	private function calculateMaxImageArea(): int {
366
		// First check if we are provided value from command line
367
		//
368
		if (
369
			(array_key_exists('max_image_area', $this->context->propertyBag)) &&
370
			(!is_null($this->context->propertyBag['max_image_area']))
371
		) {
372
				return $this->context->propertyBag['max_image_area'];
373
		}
374
375
		// Check if admin persisted this setting in config and it is valid value
376
		//
377
		$maxImageArea = $this->settingsService->getMaximumImageArea();
378
		if ($maxImageArea > 0) {
379
			return $maxImageArea;
380
		}
381
382
		// Calculate it from memory
383
		//
384
		$allowedMemory = $this->context->propertyBag['memory'];
385
		// Based on amount on memory PHP have, we will determine maximum amount of image size that we need to scale to.
386
		// This reasoning and calculations are all based on analysis given here:
387
		// https://github.com/matiasdelellis/facerecognition/wiki/Performance-analysis-of-DLib%E2%80%99s-CNN-face-detection
388
		$maxImageArea = intval((0.75 * $allowedMemory) / 1024); // in pixels^2
389
390
		return $maxImageArea;
391
	}
392
393
}