Passed
Push — improve-logging-error ( ee992d )
by Branko
13:10
created

ImageProcessingTask   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 272
Duplicated Lines 0 %

Test Coverage

Coverage 86.18%

Importance

Changes 0
Metric Value
eloc 119
dl 0
loc 272
ccs 106
cts 123
cp 0.8618
rs 10
c 0
b 0
f 0
wmc 30

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A description() 0 2 1
A getMaxImageArea() 0 7 2
A populateDescriptors() 0 19 2
A prepareImage() 0 20 4
A resizeImage() 0 30 5
A findFaces() 0 34 4
B execute() 0 47 7
A calculateMaxImageArea() 0 25 4
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017, 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\IConfig;
31
use OCP\ITempManager;
32
use OCP\IUser;
33
34
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionBackgroundTask;
35
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionContext;
36
use OCA\FaceRecognition\Db\Face;
37
use OCA\FaceRecognition\Db\Image;
38
use OCA\FaceRecognition\Db\ImageMapper;
39
use OCA\FaceRecognition\Helper\Requirements;
40
use OCA\FaceRecognition\Migration\AddDefaultFaceModel;
41
42
/**
43
 * Plain old PHP object holding all information
44
 * that are needed to process all faces from one image
45
 */
46
class ImageProcessingContext {
47
	/** @var string Path to the image being processed */
48
	private $imagePath;
49
50
	/** @var string Path to temporary, resized image */
51
	private $tempPath;
52
53
	/** @var float Ratio of resized image, when scaling it */
54
	private $ratio;
55
56
	/** @var array<Face> All found faces in image */
57
	private $faces;
58
59
	/**
60
	 * @var bool True if detection should be skipped, but image should be marked as processed.
61
	 * If this is set, $tempPath and $ratio will be invalid and $faces should be empty array.
62
	 */
63
	private $skipDetection;
64
65 3
	public function __construct(string $imagePath, string $tempPath, float $ratio, bool $skipDetection) {
66 3
		$this->imagePath = $imagePath;
67 3
		$this->tempPath = $tempPath;
68 3
		$this->ratio = $ratio;
69 3
		$this->faces = array();
70 3
		$this->skipDetection = $skipDetection;
71 3
	}
72
73
	public function getImagePath(): string {
74
		return $this->imagePath;
75
	}
76
77 2
	public function getTempPath(): string {
78 2
		return $this->tempPath;
79
	}
80
81 1
	public function getRatio(): float {
82 1
		return $this->ratio;
83
	}
84
85 3
	public function getSkipDetection(): bool {
86 3
		return $this->skipDetection;
87
	}
88
89
	/**
90
	 * Gets all faces
91
	 *
92
	 * @return Face[] Array of faces
93
	 */
94 3
	public function getFaces(): array {
95 3
		return $this->faces;
96
	}
97
98
	/**
99
	 * @param array<Face> $faces Array of faces to set
100
	 */
101 2
	public function setFaces($faces) {
102 2
		$this->faces = $faces;
103 2
	}
104
}
105
106
/**
107
 * Taks that get all images that are still not processed and processes them.
108
 * Processing image means that each image is prepared, faces extracted form it,
109
 * and for each found face - face descriptor is extracted.
110
 */
111
class ImageProcessingTask extends FaceRecognitionBackgroundTask {
112
	/** @var IConfig Config */
113
	private $config;
114
115
	/** @var ImageMapper Image mapper*/
116
	protected $imageMapper;
117
118
	/** @var ITempManager */
119
	private $tempManager;
120
121
	/** @var int|null Maximum image area (cached, so it is not recalculated for each image) */
122
	private $maxImageAreaCached;
123
124
	/**
125
	 * @param ImageMapper $imageMapper Image mapper
126
	 */
127 5
	public function __construct(IConfig $config, ImageMapper $imageMapper, ITempManager $tempManager) {
128 5
		parent::__construct();
129 5
		$this->config = $config;
130 5
		$this->imageMapper = $imageMapper;
131 5
		$this->tempManager = $tempManager;
132 5
		$this->maxImageAreaCached = null;
133 5
	}
134
135
	/**
136
	 * @inheritdoc
137
	 */
138 4
	public function description() {
139 4
		return "Process all images to extract faces";
140
	}
141
142
	/**
143
	 * @inheritdoc
144
	 */
145 4
	public function execute(FaceRecognitionContext $context) {
146 4
		$this->setContext($context);
147
148 4
		$model = intval($this->config->getAppValue('facerecognition', 'model', AddDefaultFaceModel::DEFAULT_FACE_MODEL_ID));
149 4
		$requirements = new Requirements($context->appManager, $model);
150
151 4
		$dataDir = rtrim($context->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data'), '/');
152 4
		$images = $context->propertyBag['images'];
153
154 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...
155 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...
156 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...
157
158 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');
159
160 4
		foreach($images as $image) {
161 4
			yield;
162
163 4
			$imageProcessingContext = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $imageProcessingContext is dead and can be removed.
Loading history...
164 4
			$startMillis = round(microtime(true) * 1000);
165
166
			try {
167 4
				$imageProcessingContext = $this->findFaces($cfd, $dataDir, $image);
168 3
				if (($imageProcessingContext !== null) && ($imageProcessingContext->getSkipDetection() === false)) {
169 2
					$this->populateDescriptors($fld, $fr, $imageProcessingContext);
170
				}
171
172 3
				if ($imageProcessingContext === null) {
173
					continue;
174
				}
175
176 3
				$endMillis = round(microtime(true) * 1000);
177 3
				$duration = max($endMillis - $startMillis, 0);
178 3
				$this->imageMapper->imageProcessed($image, $imageProcessingContext->getFaces(), $duration);
179 1
			} catch (\Exception $e) {
180 1
				if ($e->getMessage() === "std::bad_alloc") {
181
					throw new \RuntimeException("Not enough memory to run face recognition! Please look FAQ at https://github.com/matiasdelellis/facerecognition/wiki/FAQ");
182
				}
183 1
				$this->logInfo('Faces found: 0. Image will be skipped because of the following error: ' . $e->getMessage());
184 1
				$this->logDebug($e);
185 1
				$this->imageMapper->imageProcessed($image, array(), 0, $e);
186 4
			} finally {
187 4
				$this->tempManager->clean();
188
			}
189
		}
190
191 4
		return true;
192
	}
193
194
	/**
195
	 * Given an image, it finds all faces on it.
196
	 * If image should be skipped, returns null.
197
	 * If there is any error, throws exception
198
	 *
199
	 * @param \CnnFaceDetection $cfd Face detection model
200
	 * @param string $dataDir Directory where data is stored
201
	 * @param Image $image Image to find faces on
202
	 * @return ImageProcessingContext|null Generated context that hold all information needed later for this image
203
	 */
204 4
	private function findFaces(\CnnFaceDetection $cfd, string $dataDir, Image $image) {
205
		// todo: check if this hits I/O (database, disk...), consider having lazy caching to return user folder from user
206 4
		$userFolder = $this->context->rootFolder->getUserFolder($image->user);
207 4
		$userRoot = $userFolder->getParent();
208 4
		$file = $userRoot->getById($image->file);
209 4
		if (empty($file)) {
210
			$this->logInfo('File with ID ' . $image->file . ' doesn\'t exist anymore, skipping it');
211
			return null;
212
		}
213
214
		// todo: this concat is wrong with shared files.
215 4
		$imagePath = $dataDir . $file[0]->getPath();
216 4
		$this->logInfo('Processing image ' . $imagePath);
217 4
		$imageProcessingContext = $this->prepareImage($imagePath);
218 3
		if ($imageProcessingContext->getSkipDetection() === true) {
219 1
			$this->logInfo('Faces found: 0 (image will be skipped because it is too small)');
220 1
			return $imageProcessingContext;
221
		}
222
223
		// Detect faces from model
224 2
		$facesFound = $cfd->detect($imageProcessingContext->getTempPath());
225
226
		// Convert from dictionary of faces to our Face Db Entity
227 2
		$faces = array();
228 2
		foreach ($facesFound as $faceFound) {
229 1
			$face = Face::fromModel($image->getId(), $faceFound);
230 1
			$face->normalizeSize($imageProcessingContext->getRatio());
231 1
			$faces[] = $face;
232
		}
233
234 2
		$imageProcessingContext->setFaces($faces);
235 2
		$this->logInfo('Faces found: ' . count($faces));
236
237 2
		return $imageProcessingContext;
238
	}
239
240
	/**
241
	 * Given an image, it will rotate, scale and save image to temp location, ready to be consumed by pdlib.
242
	 *
243
	 * @param string $imagePath Path to image on disk
244
	 *
245
	 * @return ImageProcessingContext Generated context that hold all information needed later for this image.
246
	 */
247 4
	private function prepareImage(string $imagePath) {
248 4
		$image = new OCP_Image(null, $this->context->logger->getLogger(), $this->context->config);
249 4
		$image->loadFromFile($imagePath);
250 3
		$image->fixOrientation();
251 3
		if (!$image->valid()) {
252
			throw new \RuntimeException("Image is not valid, probably cannot be loaded");
253
		}
254
255
		// Ignore processing of images that are not large enough.
256 3
		$minImageSize = intval($this->config->getAppValue('facerecognition', 'min_image_size', '512'));
257 3
		if ((imagesx($image->resource()) < $minImageSize) || (imagesy($image->resource()) < $minImageSize)) {
258 1
			return new ImageProcessingContext($imagePath, "", -1, true);
259
		}
260
261 2
		$maxImageArea = $this->getMaxImageArea();
262 2
		$ratio = $this->resizeImage($image, $maxImageArea);
263
264 2
		$tempfile = $this->tempManager->getTemporaryFile(pathinfo($imagePath, PATHINFO_EXTENSION));
265 2
		$image->save($tempfile);
266 2
		return new ImageProcessingContext($imagePath, $tempfile, $ratio, false);
267
	}
268
269
	/**
270
	 * Resizes the image to reach max image area, but preserving ratio.
271
	 * Stolen and adopted from OC_Image->resize() (difference is that this returns ratio of resize.)
272
	 *
273
	 * @param OC_Image $image Image to resize
0 ignored issues
show
Bug introduced by
The type OCA\FaceRecognition\BackgroundJob\Tasks\OC_Image 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...
274
	 * @param int $maxImageArea The maximum size of image we can handle (in pixels^2).
275
	 *
276
	 * @return float Ratio of resize. 1 if there was no resize
277
	 */
278 3
	public function resizeImage(OCP_Image $image, int $maxImageArea): float {
279 3
		if (!$image->valid()) {
280
			$message = "Image is not valid, probably cannot be loaded";
281
			$this->logInfo($message);
282
			throw new \RuntimeException($message);
283
		}
284
285 3
		$widthOrig = imagesx($image->resource());
286 3
		$heightOrig = imagesy($image->resource());
287 3
		if (($widthOrig <= 0) || ($heightOrig <= 0)) {
288
			$message = "Image is having non-positive width or height, cannot continue";
289
			$this->logInfo($message);
290
			throw new \RuntimeException($message);
291
		}
292
293 3
		$areaRatio = $maxImageArea / ($widthOrig * $heightOrig);
294 3
		$scaleFactor = sqrt($areaRatio);
295
296 3
		$newWidth = intval(round($widthOrig * $scaleFactor));
297 3
		$newHeight = intval(round($heightOrig * $scaleFactor));
298
299 3
		$success = $image->preciseResize($newWidth, $newHeight);
300 3
		if ($success === false) {
301
			throw new \RuntimeException("Error during image resize");
302
		}
303
304 3
		$this->logDebug(sprintf('Image scaled from %dx%d to %dx%d (since max image area is %d pixels^2)',
305 3
			$widthOrig, $heightOrig, $newWidth, $newHeight, $maxImageArea));
306
307 3
		return 1 / $scaleFactor;
308
	}
309
310
	/**
311
	 * Gets all face descriptors in a given image processing context. Populates "descriptor" in array of faces.
312
	 *
313
	 * @param \FaceLandmarkDetection $fld Landmark detection model
314
	 * @param \FaceRecognition $fr Face recognition model
315
	 * @param ImageProcessingContext Image processing context
316
	 */
317 2
	private function populateDescriptors(\FaceLandmarkDetection $fld, \FaceRecognition $fr, ImageProcessingContext $imageProcessingContext) {
318 2
		$faces = $imageProcessingContext->getFaces();
319
320 2
		foreach($faces as &$face) {
321
			// For each face, we want to detect landmarks and compute descriptors.
322
			// We use already resized image (from temp, used to detect faces) for this.
323
			// (better would be to work with original image, but that will require
324
			// another orientation fix and another save to the temp)
325
			// But, since our face coordinates are already changed to align to original image,
326
			// we need to fix them up to align them to temp image here.
327 1
			$normalizedFace = clone $face;
328 1
			$normalizedFace->normalizeSize(1.0 / $imageProcessingContext->getRatio());
329
330
			// We are getting face landmarks from already prepared (temp) image (resized and with orienation fixed).
331 1
			$landmarks = $fld->detect($imageProcessingContext->getTempPath(), array(
332 1
				"left" => $normalizedFace->left, "top" => $normalizedFace->top,
333 1
				"bottom" => $normalizedFace->bottom, "right" => $normalizedFace->right));
334 1
			$descriptor = $fr->computeDescriptor($imageProcessingContext->getTempPath(), $landmarks);
335 1
			$face->descriptor = $descriptor;
336
		}
337 2
	}
338
339
	/**
340
	 * Obtains max image area lazily (from cache, or calculates it and puts it to cache)
341
	 *
342
	 * @return int Max image area (in pixels^2)
343
	 */
344 2
	private function getMaxImageArea(): int {
345 2
		if (!is_null($this->maxImageAreaCached)) {
346
			return $this->maxImageAreaCached;
347
		}
348
349 2
		$this->maxImageAreaCached = $this->calculateMaxImageArea();
350 2
		return $this->maxImageAreaCached;
351
	}
352
353
	/**
354
	 * Calculates max image area. This is separate function, as there are several levels of user overrides.
355
	 *
356
	 * @return int Max image area (in pixels^2)
357
	 */
358 2
	private function calculateMaxImageArea(): int {
359
		// First check if we are provided value from command line
360
		//
361
		if (
362 2
			(array_key_exists('max_image_area', $this->context->propertyBag)) &&
363 2
			(!is_null($this->context->propertyBag['max_image_area']))
364
		) {
365
				return $this->context->propertyBag['max_image_area'];
366
		}
367
368
		// Check if admin persisted this setting in config and it is valid value
369
		//
370 2
		$maxImageArea = intval($this->config->getAppValue('facerecognition', 'max_image_area', 0));
371 2
		if ($maxImageArea > 0) {
372 2
			return $maxImageArea;
373
		}
374
375
		// Calculate it from memory
376
		//
377
		$allowedMemory = $this->context->propertyBag['memory'];
378
		// Based on amount on memory PHP have, we will determine maximum amount of image size that we need to scale to.
379
		// This reasoning and calculations are all based on analysis given here:
380
		// https://github.com/matiasdelellis/facerecognition/wiki/Performance-analysis-of-DLib%E2%80%99s-CNN-face-detection
381
		$maxImageArea = intval((0.75 * $allowedMemory) / 1024); // in pixels^2
382
		return $maxImageArea;
383
	}
384
}