Completed
Push — master ( 8cda4e...9c3f97 )
by Matias
05:59 queued 05:56
created

DlibCnnModel::getPreferredMimeType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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