Passed
Push — find-similar ( e73d27...200d3c )
by Matias
04:37
created

CreateClustersTask   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 341
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 5
Bugs 0 Features 1
Metric Value
eloc 182
dl 0
loc 341
ccs 0
cts 180
cp 0
rs 4.5599
c 5
b 0
f 1
wmc 58

8 Methods

Rating   Name   Duplication   Size   Complexity  
B fillFaceRelationsFromPersons() 0 28 8
F mergeClusters() 0 59 14
A getCurrentClusters() 0 11 4
A __construct() 0 13 1
A description() 0 2 1
C createClusterIfNeeded() 0 110 15
A execute() 0 21 3
C getNewClusters() 0 52 12

How to fix   Complexity   

Complex Class

Complex classes like CreateClustersTask often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CreateClustersTask, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @copyright Copyright (c) 2017-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
namespace OCA\FaceRecognition\BackgroundJob\Tasks;
25
26
use OCP\IUser;
27
28
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionBackgroundTask;
29
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionContext;
30
31
use OCA\FaceRecognition\Db\FaceMapper;
32
use OCA\FaceRecognition\Db\ImageMapper;
33
use OCA\FaceRecognition\Db\PersonMapper;
34
35
use OCA\FaceRecognition\Db\Relation;
36
use OCA\FaceRecognition\Db\RelationMapper;
37
38
use OCA\FaceRecognition\Helper\Euclidean;
39
40
use OCA\FaceRecognition\Service\SettingsService;
41
/**
42
 * Taks that, for each user, creates person clusters for each.
43
 */
44
class CreateClustersTask extends FaceRecognitionBackgroundTask {
45
	/** @var PersonMapper Person mapper*/
46
	private $personMapper;
47
48
	/** @var ImageMapper Image mapper*/
49
	private $imageMapper;
50
51
	/** @var FaceMapper Face mapper*/
52
	private $faceMapper;
53
54
	/** @var RelationMapper Relation mapper*/
55
	private $relationMapper;
56
57
	/** @var SettingsService Settings service*/
58
	private $settingsService;
59
60
	/**
61
	 * @param PersonMapper
62
	 * @param ImageMapper
63
	 * @param FaceMapper
64
	 * @param SettingsService
65
	 */
66
	public function __construct(PersonMapper    $personMapper,
67
	                            ImageMapper     $imageMapper,
68
	                            FaceMapper      $faceMapper,
69
	                            RelationMapper  $relationMapper,
70
	                            SettingsService $settingsService)
71
	{
72
		parent::__construct();
73
74
		$this->personMapper    = $personMapper;
75
		$this->imageMapper     = $imageMapper;
76
		$this->faceMapper      = $faceMapper;
77
		$this->relationMapper  = $relationMapper;
78
		$this->settingsService = $settingsService;
79
	}
80
81
	/**
82
	 * @inheritdoc
83
	 */
84
	public function description() {
85
		return "Create new persons or update existing persons";
86
	}
87
88
	/**
89
	 * @inheritdoc
90
	 */
91
	public function execute(FaceRecognitionContext $context) {
92
		$this->setContext($context);
93
94
		// We cannot yield inside of Closure, so we need to extract all users and iterate outside of closure.
95
		// However, since we don't want to do deep copy of IUser, we keep only UID in this array.
96
		//
97
		$eligable_users = array();
98
		if (is_null($this->context->user)) {
99
			$this->context->userManager->callForSeenUsers(function (IUser $user) use (&$eligable_users) {
100
				$eligable_users[] = $user->getUID();
101
			});
102
		} else {
103
			$eligable_users[] = $this->context->user->getUID();
104
		}
105
106
		foreach($eligable_users as $user) {
107
			$this->createClusterIfNeeded($user);
108
			yield;
109
		}
110
111
		return true;
112
	}
113
114
	private function createClusterIfNeeded(string $userId) {
115
		// Check that we processed enough images to start creating clusters
116
		//
117
		$modelId = $this->settingsService->getCurrentFaceModel();
118
119
		$hasPersons = $this->personMapper->countPersons($userId, $modelId) > 0;
120
121
		// Depending on whether we already have clusters, decide if we should create/recreate them.
122
		//
123
		if ($hasPersons) {
124
			// OK, we already got some persons. We now need to evaluate whether we want to recreate clusters.
125
			// We want to recreate clusters/persons if:
126
			// * Some cluster/person is invalidated (is_valid is false for someone)
127
			//     This means some image that belonged to this user is changed, deleted etc.
128
			// * There are some new faces. Now, we don't want to jump the gun here. We want to either have:
129
			// ** more than 10 new faces, or
130
			// ** less than 10 new faces, but they are older than 2h
131
			//  (basically, we want to avoid recreating cluster for each new face being uploaded,
132
			//  however, we don't want to wait too much as clusters could be changed a lot)
133
			//
134
			$haveNewFaces = false;
135
			$facesWithoutPersons = $this->faceMapper->countFaces($userId, $modelId, true);
136
			$this->logDebug(sprintf('Found %d faces without associated persons for user %s and model %d',
137
				$facesWithoutPersons, $userId, $modelId));
138
			// todo: get rid of magic numbers (move to config)
139
			if ($facesWithoutPersons >= 10) {
140
				$haveNewFaces = true;
141
			} else if ($facesWithoutPersons > 0) {
142
				// We have some faces, but not that many, let's see when oldest one is generated.
143
				$face = $this->faceMapper->getOldestCreatedFaceWithoutPerson($userId, $modelId);
144
				$oldestFaceTimestamp = $face->creationTime->getTimestamp();
145
				$currentTimestamp = (new \DateTime())->getTimestamp();
146
				$this->logDebug(sprintf('Oldest face without persons for user %s and model %d is from %s',
147
					$userId, $modelId, $face->creationTime->format('Y-m-d H:i:s')));
148
				// todo: get rid of magic numbers (move to config)
149
				if ($currentTimestamp - $oldestFaceTimestamp > 2 * 60 * 60) {
150
					$haveNewFaces = true;
151
				}
152
			}
153
154
			$stalePersonsCount = $this->personMapper->countPersons($userId, $modelId, true);
155
			$haveStalePersons = $stalePersonsCount > 0;
156
			$staleCluster = $haveStalePersons === false && $haveNewFaces === false;
157
158
			$forceRecreation = $this->settingsService->getNeedRecreateClusters($userId);
159
160
			$this->logDebug(sprintf('Found %d changed persons for user %s and model %d', $stalePersonsCount, $userId, $modelId));
161
162
			if ($staleCluster && !$forceRecreation) {
163
				// If there is no invalid persons, and there is no recent new faces, no need to recreate cluster
164
				$this->logInfo('Clusters already exist, estimated there is no need to recreate them');
165
				return;
166
			}
167
			else if ($forceRecreation) {
168
				$this->logInfo('Clusters already exist, but there was some change that requires recreating the clusters');
169
			}
170
		} else {
171
			// User should not be able to use this directly, used in tests
172
			$forceCreation = $this->settingsService->getForceCreateClusters($userId);
173
174
			// These are basic criteria without which we should not even consider creating clusters.
175
			// These clusters will be small and not "stable" enough and we should better wait for more images to come.
176
			// todo: 2 queries to get these 2 counts, can we do this smarter?
177
			$imageCount = $this->imageMapper->countUserImages($userId, $modelId);
178
			$imageProcessed = $this->imageMapper->countUserProcessedImages($userId, $modelId);
179
			$percentImagesProcessed = 0;
180
			if ($imageCount > 0) {
181
				$percentImagesProcessed = $imageProcessed / floatval($imageCount);
182
			}
183
			$facesCount = $this->faceMapper->countFaces($userId, $modelId);
184
			// todo: get rid of magic numbers (move to config)
185
			if (!$forceCreation && ($facesCount < 1000) && ($imageCount < 100) && ($percentImagesProcessed < 0.95)) {
186
				$this->logInfo(
187
					'Skipping cluster creation, not enough data (yet) collected. ' .
188
					'For cluster creation, you need either one of the following:');
189
				$this->logInfo(sprintf('* have 1000 faces already processed (you have %d),', $facesCount));
190
				$this->logInfo(sprintf('* have 100 images (you have %d),', $imageCount));
191
				$this->logInfo(sprintf('* or you need to have 95%% of you images processed (you have %.2f%%)', $percentImagesProcessed));
192
				return;
193
			}
194
		}
195
196
		$faces = $this->faceMapper->getFaces($userId, $modelId);
197
		$this->logInfo(count($faces) . ' faces found for clustering');
198
199
		// Cluster is associative array where key is person ID.
200
		// Value is array of face IDs. For old clusters, person IDs are some existing person IDs,
201
		// and for new clusters is whatever chinese whispers decides to identify them.
202
		//
203
		$currentClusters = $this->getCurrentClusters($faces);
204
		$newClusters = $this->getNewClusters($faces);
205
		$this->logInfo(count($newClusters) . ' persons found after clustering');
206
207
		// New merge
208
		$mergedClusters = $this->mergeClusters($currentClusters, $newClusters);
209
		$this->personMapper->mergeClusterToDatabase($userId, $currentClusters, $mergedClusters);
210
211
		// Remove all orphaned persons (those without any faces)
212
		// NOTE: we will do this for all models, not just for current one, but this is not problem.
213
		$orphansDeleted = $this->personMapper->deleteOrphaned($userId);
214
		if ($orphansDeleted > 0) {
215
			$this->logInfo('Deleted ' . $orphansDeleted . ' persons without faces');
216
		}
217
218
		// Fill relation table with new clusters.
219
		$this->fillFaceRelationsFromPersons($userId);
220
221
		// Prevents not create/recreate the clusters unnecessarily.
222
		$this->settingsService->setNeedRecreateClusters(false, $userId);
223
		$this->settingsService->setForceCreateClusters(false, $userId);
224
	}
225
226
	private function getCurrentClusters(array $faces): array {
227
		$chineseClusters = array();
228
		foreach($faces as $face) {
229
			if ($face->person !== null) {
230
				if (!isset($chineseClusters[$face->person])) {
231
					$chineseClusters[$face->person] = array();
232
				}
233
				$chineseClusters[$face->person][] = $face->id;
234
			}
235
		}
236
		return $chineseClusters;
237
	}
238
239
	private function getNewClusters(array $faces): array {
240
		// Create edges for chinese whispers
241
		$sensitivity = $this->settingsService->getSensitivity();
242
		$min_confidence = $this->settingsService->getMinimumConfidence();
243
		$edges = array();
244
245
		if (version_compare(phpversion('pdlib'), '1.0.2', '>=')) {
246
			for ($i = 0, $face_count1 = count($faces); $i < $face_count1; $i++) {
247
				$face1 = $faces[$i];
248
				if ($face1->confidence < $min_confidence) {
249
					$edges[] = array($i, $i);
250
					continue;
251
				}
252
				for ($j = $i, $face_count2 = count($faces); $j < $face_count2; $j++) {
253
					$face2 = $faces[$j];
254
					$distance = dlib_vector_length($face1->descriptor, $face2->descriptor);
0 ignored issues
show
Bug introduced by
The function dlib_vector_length 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

254
					$distance = /** @scrutinizer ignore-call */ dlib_vector_length($face1->descriptor, $face2->descriptor);
Loading history...
255
256
					if ($distance < $sensitivity) {
257
						$edges[] = array($i, $j);
258
					}
259
				}
260
			}
261
		} else {
262
			$euclidean = new Euclidean();
263
			for ($i = 0, $face_count1 = count($faces); $i < $face_count1; $i++) {
264
				$face1 = $faces[$i];
265
				if ($face1->confidence < $min_confidence) {
266
					$edges[] = array($i, $i);
267
					continue;
268
				}
269
				for ($j = $i, $face_count2 = count($faces); $j < $face_count2; $j++) {
270
					$face2 = $faces[$j];
271
					// todo: can't this distance be a method in $face1->distance($face2)?
272
					$distance = $euclidean->distance($face1->descriptor, $face2->descriptor);
273
274
					if ($distance < $sensitivity) {
275
						$edges[] = array($i, $j);
276
					}
277
				}
278
			}
279
		}
280
281
		$newChineseClustersByIndex = dlib_chinese_whispers($edges);
0 ignored issues
show
Bug introduced by
The function dlib_chinese_whispers 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

281
		$newChineseClustersByIndex = /** @scrutinizer ignore-call */ dlib_chinese_whispers($edges);
Loading history...
282
		$newClusters = array();
283
		for ($i = 0, $c = count($newChineseClustersByIndex); $i < $c; $i++) {
284
			if (!isset($newClusters[$newChineseClustersByIndex[$i]])) {
285
				$newClusters[$newChineseClustersByIndex[$i]] = array();
286
			}
287
			$newClusters[$newChineseClustersByIndex[$i]][] = $faces[$i]->id;
288
		}
289
290
		return $newClusters;
291
	}
292
293
	/**
294
	 * todo: only reason this is public is because of tests. Go figure it out better.
295
	 */
296
	public function mergeClusters(array $oldCluster, array $newCluster): array {
297
		// Create map of face transitions
298
		$transitions = array();
299
		foreach ($newCluster as $newPerson=>$newFaces) {
300
			foreach ($newFaces as $newFace) {
301
				$oldPersonFound = null;
302
				foreach ($oldCluster as $oldPerson => $oldFaces) {
303
					if (in_array($newFace, $oldFaces)) {
304
						$oldPersonFound = $oldPerson;
305
						break;
306
					}
307
				}
308
				$transitions[$newFace] = array($oldPersonFound, $newPerson);
309
			}
310
		}
311
		// Count transitions
312
		$transitionCount = array();
313
		foreach ($transitions as $transition) {
314
			$key = $transition[0] . ':' . $transition[1];
315
			if (array_key_exists($key, $transitionCount)) {
316
				$transitionCount[$key]++;
317
			} else {
318
				$transitionCount[$key] = 1;
319
			}
320
		}
321
		// Create map of new person -> old person transitions
322
		$newOldPersonMapping = array();
323
		$oldPersonProcessed = array(); // store this, so we don't waste cycles for in_array()
324
		arsort($transitionCount);
325
		foreach ($transitionCount as $transitionKey => $count) {
326
			$transition = explode(":", $transitionKey);
327
			$oldPerson = intval($transition[0]);
328
			$newPerson = intval($transition[1]);
329
			if (!array_key_exists($newPerson, $newOldPersonMapping)) {
330
				if (($oldPerson === 0) || (!array_key_exists($oldPerson, $oldPersonProcessed))) {
331
					$newOldPersonMapping[$newPerson] = $oldPerson;
332
					$oldPersonProcessed[$oldPerson] = 0;
333
				} else {
334
					$newOldPersonMapping[$newPerson] = 0;
335
				}
336
			}
337
		}
338
		// Starting with new cluster, convert all new person IDs with old person IDs
339
		$maxOldPersonId = 1;
340
		if (count($oldCluster) > 0) {
341
			$maxOldPersonId = max(array_keys($oldCluster)) + 1;
342
		}
343
344
		$result = array();
345
		foreach ($newCluster as $newPerson => $newFaces) {
346
			$oldPerson = $newOldPersonMapping[$newPerson];
347
			if ($oldPerson === 0) {
348
				$result[$maxOldPersonId] = $newFaces;
349
				$maxOldPersonId++;
350
			} else {
351
				$result[$oldPerson] = $newFaces;
352
			}
353
		}
354
		return $result;
355
	}
356
357
	private function fillFaceRelationsFromPersons(string $userId) {
358
		$deviation = $this->settingsService->getDeviation();
359
		if (!version_compare(phpversion('pdlib'), '1.0.2', '>=') || ($deviation === 0.0))
360
			return;
361
362
		$sensitivity = $this->settingsService->getSensitivity();
363
		$modelId = $this->settingsService->getCurrentFaceModel();
364
365
		// Get the representative faces of each person
366
		$mainFaces = array();
367
		$persons = $this->personMapper->findAll($userId, $modelId);
368
		foreach ($persons as $person) {
369
			$mainFaces[] = $this->faceMapper->findRepresentativeFromPerson($userId, $person->getId(), $sensitivity, $modelId);
370
		}
371
372
		// Get similar faces taking into account the deviation and insert new relations
373
		for ($i = 0, $face_count1 = count($mainFaces); $i < $face_count1; $i++) {
374
			$face1 = $mainFaces[$i];
375
			for ($j = $i+1, $face_count2 = count($mainFaces); $j < $face_count2; $j++) {
376
				$face2 = $mainFaces[$j];
377
				$distance = dlib_vector_length($face1->descriptor, $face2->descriptor);
0 ignored issues
show
Bug introduced by
The function dlib_vector_length 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

377
				$distance = /** @scrutinizer ignore-call */ dlib_vector_length($face1->descriptor, $face2->descriptor);
Loading history...
378
				if ($distance < ($sensitivity + $deviation)) {
379
					$relation = new Relation();
380
					$relation->setFace1($face1->getId());
381
					$relation->setFace2($face2->getId());
382
					$relation->setState(RELATION::PROPOSED);
383
					if (!$this->relationMapper->exists($relation)) {
384
						$this->relationMapper->insert($relation);
385
					}
386
				}
387
			}
388
		}
389
	}
390
391
}
392