Passed
Push — self-contained-model ( 13b347...b458ac )
by Matias
04:07
created

DlibHogModel::isInstalled()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 12
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\Service\FileService;
30
use OCA\FaceRecognition\Service\ModelService;
31
use OCA\FaceRecognition\Service\SettingsService;
32
33
use OCA\FaceRecognition\Model\IModel;
34
35
class DlibHogModel implements IModel {
36
37
	/*
38
	 * Model files.
39
	 */
40
	const FACE_MODEL_ID = 3;
41
	const FACE_MODEL_NAME = "DlibHog";
42
	const FACE_MODEL_DESC = "Dlib HOG Model which needs lower requirements";
43
44
	/** Relationship between image size and memory consumed */
45
	const MEMORY_AREA_RELATIONSHIP = 1 * 1024;
46
47
	const FACE_MODEL_BZ2_URLS = [
48
		'https://github.com/davisking/dlib-models/raw/4af9b776281dd7d6e2e30d4a2d40458b1e254e40/shape_predictor_5_face_landmarks.dat.bz2',
49
		'https://github.com/davisking/dlib-models/raw/2a61575dd45d818271c085ff8cd747613a48f20d/dlib_face_recognition_resnet_model_v1.dat.bz2'
50
	];
51
52
	const FACE_MODEL_FILES = [
53
		'shape_predictor_5_face_landmarks.dat',
54
		'dlib_face_recognition_resnet_model_v1.dat'
55
	];
56
57
	const I_MODEL_PREDICTOR = 0;
58
	const I_MODEL_RESNET = 1;
59
60
	/** @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...
61
	private $fld;
62
63
	/** @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...
64
	private $fr;
65
66
	/** @var IDBConnection */
67
	private $connection;
68
69
	/** @var FileService */
70
	private $fileService;
71
72
	/** @var ModelService */
73
	private $modelService;
74
75
	/** @var SettingsService */
76
	private $settingsService;
77
78
79
	/**
80
	 * DlibCnnModel __construct.
81
	 *
82
	 * @param IDBConnection $connection
83
	 * @param FileService $fileService
84
	 * @param ModelService $modelService
85
	 * @param SettingsService $settingsService
86
	 */
87 1
	public function __construct(IDBConnection   $connection,
88
	                            FileService     $fileService,
89
	                            ModelService    $modelService,
90
	                            SettingsService $settingsService)
91
	{
92 1
		$this->connection       = $connection;
93 1
		$this->fileService      = $fileService;
94 1
		$this->modelService     = $modelService;
95 1
		$this->settingsService  = $settingsService;
96 1
	}
97
98
	public function getId(): int {
99
		return static::FACE_MODEL_ID;
100
	}
101
102
	public function getName(): string {
103
		return static::FACE_MODEL_NAME;
104
	}
105
106
	public function getDescription(): string {
107
		return static::FACE_MODEL_DESC;
108
	}
109
110
	public function isInstalled(): bool {
111
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]))
112
			return false;
113
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]))
114
			return false;
115
		return true;
116
	}
117
118
	public function meetDependencies(): bool {
119
		return extension_loaded('pdlib') &&
120
		       version_compare(phpversion('pdlib'), '1.0.1', '>=');
121
	}
122
123
	public function install() {
124
		if ($this->isInstalled()) {
125
			return;
126
		}
127
128
		// Create main folder where install models.
129
		$this->modelService->prepareModelFolder($this->getId());
130
131
		/* Download and install models */
132
		$predictorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_PREDICTOR]);
133
		$this->fileService->bunzip2($predictorModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
134
135
		$resnetModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_RESNET]);
136
		$this->fileService->bunzip2($resnetModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
137
138
		/* Clean temporary files */
139
		$this->fileService->clean();
140
141
		// Insert on database and enable it
142
		$qb = $this->connection->getQueryBuilder();
143
		$query = $qb->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
144
			->from('facerecog_models')
145
			->where($qb->expr()->eq('id', $qb->createParameter('id')))
146
			->setParameter('id', $this->getId());
147
		$resultStatement = $query->execute();
148
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
149
		$resultStatement->closeCursor();
150
151
		if ((int)$data[0] <= 0) {
152
			$query = $this->connection->getQueryBuilder();
153
			$query->insert('facerecog_models')
154
			->values([
155
				'id' => $query->createNamedParameter($this->getId()),
156
				'name' => $query->createNamedParameter($this->getName()),
157
				'description' => $query->createNamedParameter($this->getDescription())
158
			])
159
			->execute();
160
		}
161
	}
162
163
	public function open() {
164
		$this->fld = new \FaceLandmarkDetection($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
165
		$this->fr = new \FaceRecognition($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
166
	}
167
168
	public function getMemoryAreaRelation(): int {
169
		return self::MEMORY_AREA_RELATIONSHIP;
170
	}
171
172
	public function detectFaces(string $imagePath): array {
173
		$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

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