Completed
Push — master ( bd4a48...a13ca6 )
by Branko
12s queued 10s
created

ImageProcessingContext   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 57
ccs 17
cts 19
cp 0.8947
rs 10
c 0
b 0
f 0
wmc 7

7 Methods

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