Passed
Push — self-contained-model ( 575670...f0e346 )
by Matias
04:11
created

DlibHogModel::isInstalled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
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 0
dl 0
loc 3
ccs 0
cts 3
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\Requirements;
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 = "Dlib HOG Model which needs lower requirements";
45
46
	/** Relationship between image size and memory consumed */
47
	const MEMORY_AREA_RELATIONSHIP = 1 * 1024;
48
49
	const FACE_MODEL_BZ2_URLS = [
50
		'https://github.com/davisking/dlib-models/raw/4af9b776281dd7d6e2e30d4a2d40458b1e254e40/shape_predictor_5_face_landmarks.dat.bz2',
51
		'https://github.com/davisking/dlib-models/raw/2a61575dd45d818271c085ff8cd747613a48f20d/dlib_face_recognition_resnet_model_v1.dat.bz2'
52
	];
53
54
	const FACE_MODEL_FILES = [
55
		'shape_predictor_5_face_landmarks.dat',
56
		'dlib_face_recognition_resnet_model_v1.dat'
57
	];
58
59
	const I_MODEL_PREDICTOR = 0;
60
	const I_MODEL_RESNET = 1;
61
62
	/** @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...
63
	private $fld;
64
65
	/** @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...
66
	private $fr;
67
68
	/** @var IDBConnection */
69
	private $connection;
70
71
	/** @var FileService */
72
	private $fileService;
73
74
	/** @var ModelService */
75
	private $modelService;
76
77
	/** @var SettingsService */
78
	private $settingsService;
79
80
81
	/**
82
	 * DlibCnnModel __construct.
83
	 *
84
	 * @param IDBConnection $connection
85
	 * @param FileService $fileService
86
	 * @param ModelService $modelService
87
	 * @param SettingsService $settingsService
88
	 */
89
	public function __construct(IDBConnection   $connection,
90
	                            FileService     $fileService,
91
	                            ModelService    $modelService,
92
	                            SettingsService $settingsService)
93
	{
94
		$this->connection       = $connection;
95
		$this->fileService      = $fileService;
96
		$this->modelService     = $modelService;
97
		$this->settingsService  = $settingsService;
98
	}
99
100
	public function getId(): int {
101
		return static::FACE_MODEL_ID;
102
	}
103
104
	public function getName(): string {
105
		return static::FACE_MODEL_NAME;
106
	}
107
108
	public function getDescription(): string {
109
		return static::FACE_MODEL_DESC;
110
	}
111
112
	public function isInstalled(): bool {
113
		$requirements = new Requirements($this->modelService, $this->getId());
114
		return $requirements->modelFilesPresent();
115
	}
116
117
	public function meetDependencies(): bool {
118
		return extension_loaded('pdlib') &&
119
		       version_compare(phpversion('pdlib'), '1.0.1', '>=');
120
	}
121
122
	public function install() {
123
		if ($this->isInstalled()) {
124
			return;
125
		}
126
127
		/* Still not installed but it is necessary to get the model folders */
128
		$this->modelService->useModelVersion($this->getId());
129
130
		/* Download and install models */
131
		$predictorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_PREDICTOR]);
132
		$this->fileService->bunzip2($predictorModelBz2, $this->modelService->getModelPath(static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
133
134
		$resnetModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_RESNET]);
135
		$this->fileService->bunzip2($resnetModelBz2, $this->modelService->getModelPath(static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
136
137
		/* Clean temporary files */
138
		$this->fileService->clean();
139
140
		// Insert on database and enable it
141
		$qb = $this->connection->getQueryBuilder();
142
		$query = $qb->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
143
			->from('facerecog_models')
144
			->where($qb->expr()->eq('id', $qb->createParameter('id')))
145
			->setParameter('id', $this->getId());
146
		$resultStatement = $query->execute();
147
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
148
		$resultStatement->closeCursor();
149
150
		if ((int)$data[0] <= 0) {
151
			$query = $this->connection->getQueryBuilder();
152
			$query->insert('facerecog_models')
153
			->values([
154
				'id' => $query->createNamedParameter($this->getId()),
155
				'name' => $query->createNamedParameter($this->getName()),
156
				'description' => $query->createNamedParameter($this->getDescription())
157
			])
158
			->execute();
159
		}
160
	}
161
162
	public function setDefault() {
163
		// Use default model, if it is not set already.
164
		if ($this->settingsService->getCurrentFaceModel() !== $this->getId()) {
165
			$this->settingsService->setCurrentFaceModel($this->getId());
166
		}
167
	}
168
169
	public function open() {
170
		$this->modelService->useModelVersion($this->getId());
171
172
		$this->fld = new \FaceLandmarkDetection($this->modelService->getModelPath(static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
173
		$this->fr = new \FaceRecognition($this->modelService->getModelPath(static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
174
	}
175
176
	public function getMemoryAreaRelation(): int {
177
		return self::MEMORY_AREA_RELATIONSHIP;
178
	}
179
180
	public function detectFaces(string $imagePath): array {
181
		$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

181
		$faces_detected = /** @scrutinizer ignore-call */ dlib_face_detection($imagePath);
Loading history...
182
		// To improve clustering a confidence value is needed, which this model does not provide
183
		return array_map (function (array $face) { $face['detection_confidence'] = 1.0; return $face; }, $faces_detected);
184
	}
185
186
	public function detectLandmarks(string $imagePath, array $rect): array {
187
		return $this->fld->detect($imagePath, $rect);
188
	}
189
190
	public function computeDescriptor(string $imagePath, array $landmarks): array {
191
		return $this->fr->computeDescriptor($imagePath, $landmarks);
192
	}
193
194
}
195