Completed
Push — master ( 09d563...df1aee )
by Matias
16s queued 11s
created

DlibHogModel::meetDependencies()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 6
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 = "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 1
	public function __construct(IDBConnection   $connection,
90
	                            FileService     $fileService,
91
	                            ModelService    $modelService,
92
	                            SettingsService $settingsService)
93
	{
94 1
		$this->connection       = $connection;
95 1
		$this->fileService      = $fileService;
96 1
		$this->modelService     = $modelService;
97 1
		$this->settingsService  = $settingsService;
98 1
	}
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
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]))
114
			return false;
115
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]))
116
			return false;
117
		return true;
118
	}
119
120
	public function meetDependencies(): bool {
121
		return extension_loaded('pdlib') &&
122
		       version_compare(phpversion('pdlib'), '1.0.1', '>=');
123
	}
124
125
	public function getMaximumArea(): int {
126
		return intval(MemoryLimits::getAvailableMemory()/self::MEMORY_AREA_RELATIONSHIP);
127
	}
128
129
	public function install() {
130
		if ($this->isInstalled()) {
131
			return;
132
		}
133
134
		// Create main folder where install models.
135
		$this->modelService->prepareModelFolder($this->getId());
136
137
		/* Download and install models */
138
		$predictorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_PREDICTOR]);
139
		$this->fileService->bunzip2($predictorModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
140
141
		$resnetModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_RESNET]);
142
		$this->fileService->bunzip2($resnetModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
143
144
		/* Clean temporary files */
145
		$this->fileService->clean();
146
147
		// Insert on database and enable it
148
		$qb = $this->connection->getQueryBuilder();
149
		$query = $qb->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
150
			->from('facerecog_models')
151
			->where($qb->expr()->eq('id', $qb->createParameter('id')))
152
			->setParameter('id', $this->getId());
153
		$resultStatement = $query->execute();
154
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
155
		$resultStatement->closeCursor();
156
157
		if ((int)$data[0] <= 0) {
158
			$query = $this->connection->getQueryBuilder();
159
			$query->insert('facerecog_models')
160
			->values([
161
				'id' => $query->createNamedParameter($this->getId()),
162
				'name' => $query->createNamedParameter($this->getName()),
163
				'description' => $query->createNamedParameter($this->getDescription())
164
			])
165
			->execute();
166
		}
167
	}
168
169
	public function open() {
170
		$this->fld = new \FaceLandmarkDetection($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
171
		$this->fr = new \FaceRecognition($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
172
	}
173
174
	public function detectFaces(string $imagePath): array {
175
		$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

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