Passed
Push — settings-service ( 3465d4...14f764 )
by Matias
04:29
created

ImageProcessingContext::getRatio()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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