Passed
Push — self-contained-model ( d2c701...575670 )
by Matias
03:50
created

DlibHogModel   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 148
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 62
c 1
b 0
f 0
dl 0
loc 148
ccs 0
cts 74
cp 0
rs 10
wmc 16

12 Methods

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

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