Completed
Push — master ( 4a9dd8...1b56cd )
by Matias
04:44 queued 04:40
created

DlibHogModel::detectFaces()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
/**
3
 * @copyright Copyright (c) 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
25
namespace OCA\FaceRecognition\Model\DlibHogModel;
26
27
use OCP\IDBConnection;
28
29
use OCA\FaceRecognition\Helper\MemoryLimits;
30
31
use OCA\FaceRecognition\Service\FileService;
32
use OCA\FaceRecognition\Service\ModelService;
33
use OCA\FaceRecognition\Service\SettingsService;
34
35
use OCA\FaceRecognition\Model\IModel;
36
37
class DlibHogModel implements IModel {
38
39
	/*
40
	 * Model files.
41
	 */
42
	const FACE_MODEL_ID = 3;
43
	const FACE_MODEL_NAME = 'DlibHog';
44
	const FACE_MODEL_DESC = 'DDlib HOG Model which needs lower requirements';
45
	const FACE_MODEL_DOC = 'https://github.com/matiasdelellis/facerecognition/wiki/Models#model-3';
46
47
	/** This model practically does not consume memory. Directly set the limits. */
48
	const MAXIMUM_IMAGE_AREA = SettingsService::MAXIMUM_ANALYSIS_IMAGE_AREA;
49
	const MINIMUM_MEMORY_REQUIREMENTS = 128 * 1024 * 1024;
50
51
	const FACE_MODEL_BZ2_URLS = [
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
		'shape_predictor_5_face_landmarks.dat',
58
		'dlib_face_recognition_resnet_model_v1.dat'
59
	];
60
61
	const I_MODEL_PREDICTOR = 0;
62
	const I_MODEL_RESNET = 1;
63
64
	const PREFERRED_MIMETYPE = 'image/png';
65
66
	/** @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...
67
	private $fld;
68
69
	/** @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...
70
	private $fr;
71
72
	/** @var IDBConnection */
73
	private $connection;
74
75
	/** @var FileService */
76
	private $fileService;
77
78
	/** @var ModelService */
79
	private $modelService;
80
81
	/** @var SettingsService */
82
	private $settingsService;
83
84
85
	/**
86
	 * DlibCnnModel __construct.
87
	 *
88
	 * @param IDBConnection $connection
89
	 * @param FileService $fileService
90
	 * @param ModelService $modelService
91
	 * @param SettingsService $settingsService
92
	 */
93 1
	public function __construct(IDBConnection   $connection,
94
	                            FileService     $fileService,
95
	                            ModelService    $modelService,
96
	                            SettingsService $settingsService)
97
	{
98 1
		$this->connection       = $connection;
99 1
		$this->fileService      = $fileService;
100 1
		$this->modelService     = $modelService;
101 1
		$this->settingsService  = $settingsService;
102 1
	}
103
104
	public function getId(): int {
105
		return static::FACE_MODEL_ID;
106
	}
107
108
	public function getName(): string {
109
		return static::FACE_MODEL_NAME;
110
	}
111
112
	public function getDescription(): string {
113
		return static::FACE_MODEL_DESC;
114
	}
115
116
	public function getDocumentation(): string {
117
		return static::FACE_MODEL_DOC;
118
	}
119
120
	public function isInstalled(): bool {
121
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]))
122
			return false;
123
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]))
124
			return false;
125
		return true;
126
	}
127
128
	public function meetDependencies(string &$error_message): bool {
129
		if (!extension_loaded('pdlib')) {
130
			$error_message = "The PDlib PHP extension is not loaded";
131
			return false;
132
		}
133
		if (!version_compare(phpversion('pdlib'), '1.0.1', '>=')) {
134
			$error_message = "The PDlib PHP extension version is too old";
135
			return false;
136
		}
137
		if (MemoryLimits::getAvailableMemory() < static::MINIMUM_MEMORY_REQUIREMENTS) {
138
			$error_message = "Your system does not meet the minimum memory requirements";
139
			return false;
140
		}
141
		return true;
142
	}
143
144
	public function getMaximumArea(): int {
145
		return intval(self::MAXIMUM_IMAGE_AREA);
146
	}
147
148
	public function getPreferredMimeType(): string {
149
		return static::PREFERRED_MIMETYPE;
150
	}
151
152
	public function install() {
153
		if ($this->isInstalled()) {
154
			return;
155
		}
156
157
		// Create main folder where install models.
158
		$this->modelService->prepareModelFolder($this->getId());
159
160
		/* Download and install models */
161
		$predictorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_PREDICTOR]);
162
		$this->fileService->bunzip2($predictorModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
163
164
		$resnetModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_RESNET]);
165
		$this->fileService->bunzip2($resnetModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
166
167
		/* Clean temporary files */
168
		$this->fileService->clean();
169
170
		// Insert on database and enable it
171
		$qb = $this->connection->getQueryBuilder();
172
		$query = $qb->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
173
			->from('facerecog_models')
174
			->where($qb->expr()->eq('id', $qb->createParameter('id')))
175
			->setParameter('id', $this->getId());
176
		$resultStatement = $query->execute();
177
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
178
		$resultStatement->closeCursor();
179
180
		if ((int)$data[0] <= 0) {
181
			$query = $this->connection->getQueryBuilder();
182
			$query->insert('facerecog_models')
183
			->values([
184
				'id' => $query->createNamedParameter($this->getId()),
185
				'name' => $query->createNamedParameter($this->getName()),
186
				'description' => $query->createNamedParameter($this->getDescription())
187
			])
188
			->execute();
189
		}
190
	}
191
192
	public function open() {
193
		$this->fld = new \FaceLandmarkDetection($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
194
		$this->fr = new \FaceRecognition($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
195
	}
196
197
	public function detectFaces(string $imagePath): array {
198
		$faces_detected = 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

198
		$faces_detected = /** @scrutinizer ignore-call */ dlib_face_detection($imagePath);
Loading history...
199
		// To improve clustering a confidence value is needed, which this model does not provide
200
		return array_map (function (array $face) { $face['detection_confidence'] = 1.0; return $face; }, $faces_detected);
201
	}
202
203
	public function detectLandmarks(string $imagePath, array $rect): array {
204
		return $this->fld->detect($imagePath, $rect);
205
	}
206
207
	public function computeDescriptor(string $imagePath, array $landmarks): array {
208
		return $this->fr->computeDescriptor($imagePath, $landmarks);
209
	}
210
211
}
212