Passed
Push — modelV4 ( 46d108 )
by Matias
05:25
created

DlibCnnHogModel::install()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 26
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 40
ccs 0
cts 29
cp 0
crap 12
rs 9.504
1
<?php
2
/**
3
 * @copyright Copyright (c) 2020, Matias De lellis <[email protected]>
4
 *
5
 * @author Matias De lellis <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License as
11
 * published by the Free Software Foundation, either version 3 of the
12
 * License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\FaceRecognition\Model\DlibCnnHogModel;
25
26
use OCP\IDBConnection;
27
28
use OCA\FaceRecognition\Helper\MemoryLimits;
29
30
use OCA\FaceRecognition\Service\FileService;
31
use OCA\FaceRecognition\Service\ModelService;
32
use OCA\FaceRecognition\Service\SettingsService;
33
34
use OCA\FaceRecognition\Model\IModel;
35
36
class DlibCnnHogModel implements IModel {
37
38
	/*
39
	 * Model files.
40
	 */
41
	const FACE_MODEL_ID = 4;
42
	const FACE_MODEL_NAME = "CnnHog5";
43
	const FACE_MODEL_DESC = "Default Cnn model with Hog validation, and 5 point landmarks preprictor";
44
	const FACE_MODEL_DOC = "";
45
46
	/** Relationship between image size and memory consumed */
47
	const MEMORY_AREA_RELATIONSHIP = 1 * 1024;
48
	const MINIMUM_MEMORY_REQUIREMENTS = 1 * 1024 * 1024 * 1024;
49
50
	const FACE_MODEL_BZ2_URLS = [
51
		'https://github.com/davisking/dlib-models/raw/94cdb1e40b1c29c0bfcaf7355614bfe6da19460e/mmod_human_face_detector.dat.bz2',
52
		'https://github.com/davisking/dlib-models/raw/4af9b776281dd7d6e2e30d4a2d40458b1e254e40/shape_predictor_5_face_landmarks.dat.bz2',
53
		'https://github.com/davisking/dlib-models/raw/2a61575dd45d818271c085ff8cd747613a48f20d/dlib_face_recognition_resnet_model_v1.dat.bz2'
54
	];
55
56
	const FACE_MODEL_FILES = [
57
		'mmod_human_face_detector.dat',
58
		'shape_predictor_5_face_landmarks.dat',
59
		'dlib_face_recognition_resnet_model_v1.dat'
60
	];
61
62
	const I_MODEL_DETECTOR = 0;
63
	const I_MODEL_PREDICTOR = 1;
64
	const I_MODEL_RESNET = 2;
65
66
	const PREFERRED_MIMETYPE = 'image/png';
67
68
	/** @var \CnnFaceDetection */
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...
69
	private $cfd;
70
71
	/** @var \FaceLandmarkDetection */
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...
72
	private $fld;
73
74
	/** @var \FaceRecognition */
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...
75
	private $fr;
76
77
	/** @var IDBConnection */
78
	private $connection;
79
80
	/** @var FileService */
81
	private $fileService;
82
83
	/** @var ModelService */
84
	private $modelService;
85
86
	/** @var SettingsService */
87
	private $settingsService;
88
89
90
	/**
91
	 * DlibCnnModel __construct.
92
	 *
93
	 * @param IDBConnection $connection
94
	 * @param FileService $fileService
95
	 * @param ModelService $modelService
96
	 * @param SettingsService $settingsService
97
	 */
98
	public function __construct(IDBConnection   $connection,
99
	                            FileService     $fileService,
100
	                            ModelService    $modelService,
101
	                            SettingsService $settingsService)
102
	{
103
		$this->connection       = $connection;
104
		$this->fileService      = $fileService;
105
		$this->modelService     = $modelService;
106
		$this->settingsService  = $settingsService;
107
	}
108
109
	public function getId(): int {
110
		return static::FACE_MODEL_ID;
111
	}
112
113
	public function getName(): string {
114
		return static::FACE_MODEL_NAME;
115
	}
116
117
	public function getDescription(): string {
118
		return static::FACE_MODEL_DESC;
119
	}
120
121
	public function getDocumentation(): string {
122
		return static::FACE_MODEL_DOC;
123
	}
124
125
	public function isInstalled(): bool {
126
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_DETECTOR]))
127
			return false;
128
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]))
129
			return false;
130
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]))
131
			return false;
132
		return true;
133
	}
134
135
	public function meetDependencies(string &$error_message): bool {
136
		if (!extension_loaded('pdlib')) {
137
			$error_message = "The PDlib PHP extension is not loaded";
138
			return false;
139
		}
140
		if (!version_compare(phpversion('pdlib'), '1.0.1', '>=')) {
141
			$error_message = "The PDlib PHP extension version is too old";
142
			return false;
143
		}
144
		if (MemoryLimits::getAvailableMemory() < static::MINIMUM_MEMORY_REQUIREMENTS) {
145
			$error_message = "Your system does not meet the minimum memory requirements";
146
			return false;
147
		}
148
		return true;
149
	}
150
151
	public function getMaximumArea(): int {
152
		return intval(MemoryLimits::getAvailableMemory()/static::MEMORY_AREA_RELATIONSHIP);
153
	}
154
155
	public function getPreferredMimeType(): string {
156
		return static::PREFERRED_MIMETYPE;
157
	}
158
159
	public function install() {
160
		if ($this->isInstalled()) {
161
			return;
162
		}
163
164
		// Create main folder where install models.
165
		$this->modelService->prepareModelFolder($this->getId());
166
167
		/* Download and install models */
168
		$detectorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_DETECTOR]);
169
		$this->fileService->bunzip2($detectorModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_DETECTOR]));
170
171
		$predictorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_PREDICTOR]);
172
		$this->fileService->bunzip2($predictorModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
173
174
		$resnetModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_RESNET]);
175
		$this->fileService->bunzip2($resnetModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
176
177
		/* Clean temporary files */
178
		$this->fileService->clean();
179
180
		// Insert on database and enable it
181
		$qb = $this->connection->getQueryBuilder();
182
		$query = $qb->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
183
			->from('facerecog_models')
184
			->where($qb->expr()->eq('id', $qb->createParameter('id')))
185
			->setParameter('id', $this->getId());
186
		$resultStatement = $query->execute();
187
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
188
		$resultStatement->closeCursor();
189
190
		if ((int)$data[0] <= 0) {
191
			$query = $this->connection->getQueryBuilder();
192
			$query->insert('facerecog_models')
193
			->values([
194
				'id' => $query->createNamedParameter($this->getId()),
195
				'name' => $query->createNamedParameter($this->getName()),
196
				'description' => $query->createNamedParameter($this->getDescription())
197
			])
198
			->execute();
199
		}
200
	}
201
202
	public function open() {
203
		$this->cfd = new \CnnFaceDetection($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_DETECTOR]));
204
		$this->fld = new \FaceLandmarkDetection($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
205
		$this->fr = new \FaceRecognition($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
206
	}
207
208
	public function detectFaces(string $imagePath): array {
209
		$detectedFaces = [];
210
211
		$cnnFaces = $this->cfd->detect($imagePath, 0);
212
		$hogFaces = dlib_face_detection($imagePath);
0 ignored issues
show
Bug introduced by
The function dlib_face_detection was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

212
		$hogFaces = /** @scrutinizer ignore-call */ dlib_face_detection($imagePath);
Loading history...
213
214
		foreach ($cnnFaces as $proposedFace) {
215
			$detectedFaces[] = $this->validateFace($proposedFace, $hogFaces);
216
		}
217
218
		return $detectedFaces;
219
	}
220
221
	public function detectLandmarks(string $imagePath, array $rect): array {
222
		return $this->fld->detect($imagePath, $rect);
223
	}
224
225
	public function computeDescriptor(string $imagePath, array $landmarks): array {
226
		return $this->fr->computeDescriptor($imagePath, $landmarks);
227
	}
228
229
	private function validateFace($proposedFace, $validataFaces) {
0 ignored issues
show
Unused Code introduced by
The parameter $validataFaces is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

229
	private function validateFace($proposedFace, /** @scrutinizer ignore-unused */ $validataFaces) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
230
		foreach ($validateFaces as $validateFace) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $validateFaces does not exist. Did you maybe mean $validataFaces?
Loading history...
231
			$overlayPercent = $this->getOverlayPercent($proposedFace, $validateFace);
232
			/**
233
			 * The weak link in our default model is the landmark detector that
234
			 * can't align profile faces correctly.
235
			 * The Hog detector also fails and cannot detect these faces.
236
			 *
237
			 * So, if Hog detects it (Overlay > 80%), we know that the landmark
238
			 * detector will do it too.
239
			 * Just return it.
240
			 */
241
			if ($overlayPercent > 0.8) {
242
				return $proposedFace;
243
			}
244
		}
245
246
		/**
247
		 * If Hog don't detect this face, they are probably in profile or rotated.
248
		 * These are bad to compare, so we lower the confidence, to avoid clustering.
249
		 */
250
		$confidence = $proposedFace['detection_confidence'];
251
		$proposedFace['detection_confidence'] = $confidence * 0.9;
252
253
		return $proposedFace;
254
	}
255
256
	private function getOverlayPercent($rectP, $rectV): float {
257
		// Proposed face rect
258
		$leftP = $rectP->getLeft();
259
		$rightP = $rectP->getRight();
260
		$topP = $rectP->getTop();
261
		$bottomP = $rectP->getBottom();
262
263
		// Validate face rect
264
		$leftV = $rectV->getLeft();
265
		$rightV = $rectV->getRight();
266
		$topV = $rectV->getTop();
267
		$bottomV = $rectV->getBottom();
268
269
		// If one rectangle is on left side of other
270
		if ($leftP > $rightV || $leftV > $rightP)
271
			return 0.0;
272
273
		// If one rectangle is above other
274
		if ($topP > $bottomV || $topV > $bottomP)
275
			return 0.0;
276
277
		// Overlap area.
278
		$leftO = max($leftP, $leftV);
279
		$rightO = min($rightP, $rightV);
280
		$topO = max($topP, $topV);
281
		$bottomO = min($bottomP, $botomV);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $botomV does not exist. Did you maybe mean $bottomV?
Loading history...
282
283
		// Get area of both rect areas
284
		$areaP = ($rightP - $leftP) * ($bottomP - $topP);
285
		$areaV = ($rightV - $leftV) * ($bottomV - $topV);
286
		$overlapArea = ($rightO - $leftO) * ($bottomO - $topO);
287
288
		// Calculate and return the overlay percent.
289
		return floatval($overlapArea / ($areaP + $areaV - $overlapArea));
290
	}
291
292
}
293