Completed
Push — master ( f54c15...91bfdb )
by Matias
13s queued 11s
created

DlibCnnModel::install()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 3.1568

Importance

Changes 0
Metric Value
cc 3
eloc 26
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 40
ccs 20
cts 27
cp 0.7407
crap 3.1568
rs 9.504
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\DlibCnnModel;
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 DlibCnnModel implements IModel {
38
39
	/*
40
	 * Model files.
41
	 */
42
	const FACE_MODEL_ID = -1;
43
	const FACE_MODEL_NAME = "";
44
	const FACE_MODEL_DESC = "";
45
	const FACE_MODEL_DOC = "";
46
47
	/** Relationship between image size and memory consumed */
48
	const MEMORY_AREA_RELATIONSHIP = -1;
49
	const MINIMUM_MEMORY_REQUIREMENTS = -1;
50
51
	const FACE_MODEL_BZ2_URLS = array();
52
	const FACE_MODEL_FILES = array();
53
54
	const I_MODEL_DETECTOR = 0;
55
	const I_MODEL_PREDICTOR = 1;
56
	const I_MODEL_RESNET = 2;
57
58
	const PREFERRED_MIMETYPE = 'image/png';
59
60
	/** @var \CnnFaceDetection */
0 ignored issues
show
Bug introduced by
The type CnnFaceDetection 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 $cfd;
62
63
	/** @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...
64
	private $fld;
65
66
	/** @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...
67
	private $fr;
68
69
	/** @var IDBConnection */
70
	private $connection;
71
72
	/** @var FileService */
73
	private $fileService;
74
75
	/** @var ModelService */
76
	private $modelService;
77
78
	/** @var SettingsService */
79
	private $settingsService;
80
81
82
	/**
83
	 * DlibCnnModel __construct.
84
	 *
85
	 * @param IDBConnection $connection
86
	 * @param FileService $fileService
87
	 * @param ModelService $modelService
88
	 * @param SettingsService $settingsService
89
	 */
90 1
	public function __construct(IDBConnection   $connection,
91
	                            FileService     $fileService,
92
	                            ModelService    $modelService,
93
	                            SettingsService $settingsService)
94
	{
95 1
		$this->connection       = $connection;
96 1
		$this->fileService      = $fileService;
97 1
		$this->modelService     = $modelService;
98 1
		$this->settingsService  = $settingsService;
99 1
	}
100
101 4
	public function getId(): int {
102 4
		return static::FACE_MODEL_ID;
103
	}
104
105
	public function getName(): string {
106
		return static::FACE_MODEL_NAME;
107
	}
108
109
	public function getDescription(): string {
110
		return static::FACE_MODEL_DESC;
111
	}
112
113
	public function getDocumentation(): string {
114
		return static::FACE_MODEL_DOC;
115
	}
116
117 4
	public function isInstalled(): bool {
118 4
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_DETECTOR]))
119 1
			return false;
120 3
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]))
121
			return false;
122 3
		if (!$this->modelService->modelFileExists($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]))
123
			return false;
124 3
		return true;
125
	}
126
127
	public function meetDependencies(string &$error_message): bool {
128
		if (!extension_loaded('pdlib')) {
129
			$error_message = "The PDlib PHP extension is not loaded";
130
			return false;
131
		}
132
		if (MemoryLimits::getAvailableMemory() < static::MINIMUM_MEMORY_REQUIREMENTS) {
133
			$error_message = "Your system does not meet the minimum memory requirements";
134
			return false;
135
		}
136
		return true;
137
	}
138
139
	public function getMaximumArea(): int {
140
		return intval(MemoryLimits::getAvailableMemory()/static::MEMORY_AREA_RELATIONSHIP);
141
	}
142
143 4
	public function getPreferredMimeType(): string {
144 4
		return static::PREFERRED_MIMETYPE;
145
	}
146
147 4
	public function install() {
148 4
		if ($this->isInstalled()) {
149 3
			return;
150
		}
151
152
		// Create main folder where install models.
153 1
		$this->modelService->prepareModelFolder($this->getId());
154
155
		/* Download and install models */
156 1
		$detectorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_DETECTOR]);
157 1
		$this->fileService->bunzip2($detectorModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_DETECTOR]));
158
159 1
		$predictorModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_PREDICTOR]);
160 1
		$this->fileService->bunzip2($predictorModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
161
162 1
		$resnetModelBz2 = $this->fileService->downloaldFile(static::FACE_MODEL_BZ2_URLS[self::I_MODEL_RESNET]);
163 1
		$this->fileService->bunzip2($resnetModelBz2, $this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
164
165
		/* Clean temporary files */
166 1
		$this->fileService->clean();
167
168
		// Insert on database and enable it
169 1
		$qb = $this->connection->getQueryBuilder();
170 1
		$query = $qb->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
171 1
			->from('facerecog_models')
172 1
			->where($qb->expr()->eq('id', $qb->createParameter('id')))
173 1
			->setParameter('id', $this->getId());
174 1
		$resultStatement = $query->execute();
175 1
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
176 1
		$resultStatement->closeCursor();
177
178 1
		if ((int)$data[0] <= 0) {
179
			$query = $this->connection->getQueryBuilder();
180
			$query->insert('facerecog_models')
181
			->values([
182
				'id' => $query->createNamedParameter($this->getId()),
183
				'name' => $query->createNamedParameter($this->getName()),
184
				'description' => $query->createNamedParameter($this->getDescription())
185
			])
186
			->execute();
187
		}
188 1
	}
189
190 4
	public function open() {
191 4
		$this->cfd = new \CnnFaceDetection($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_DETECTOR]));
192 4
		$this->fld = new \FaceLandmarkDetection($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_PREDICTOR]));
193 4
		$this->fr = new \FaceRecognition($this->modelService->getFileModelPath($this->getId(), static::FACE_MODEL_FILES[self::I_MODEL_RESNET]));
194 4
	}
195
196 2
	public function detectFaces(string $imagePath): array {
197 2
		return $this->cfd->detect($imagePath, 0);
198
	}
199
200 1
	public function detectLandmarks(string $imagePath, array $rect): array {
201 1
		return $this->fld->detect($imagePath, $rect);
202
	}
203
204 1
	public function computeDescriptor(string $imagePath, array $landmarks): array {
205 1
		return $this->fr->computeDescriptor($imagePath, $landmarks);
206
	}
207
208
}
209