Passed
Push — find-similar ( e726cf...a578af )
by Matias
04:51
created

CreateClustersTask::fillFaceRelationsFromPersons()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 22
nc 9
nop 2
dl 0
loc 34
ccs 0
cts 23
cp 0
crap 56
rs 8.6346
c 0
b 0
f 0
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
		$relations = $this->relationMapper->findByUserAsMatrix($userId, $modelId);
200
201
		// Cluster is associative array where key is person ID.
202
		// Value is array of face IDs. For old clusters, person IDs are some existing person IDs,
203
		// and for new clusters is whatever chinese whispers decides to identify them.
204
		//
205
		$currentClusters = $this->getCurrentClusters($faces);
206
		$newClusters = $this->getNewClusters($faces, $relations);
207
		$this->logInfo(count($newClusters) . ' persons found after clustering');
208
209
		// New merge
210
		$mergedClusters = $this->mergeClusters($currentClusters, $newClusters);
211
		$this->personMapper->mergeClusterToDatabase($userId, $currentClusters, $mergedClusters);
212
213
		// Remove all orphaned persons (those without any faces)
214
		// NOTE: we will do this for all models, not just for current one, but this is not problem.
215
		$orphansDeleted = $this->personMapper->deleteOrphaned($userId);
216
		if ($orphansDeleted > 0) {
217
			$this->logInfo('Deleted ' . $orphansDeleted . ' persons without faces');
218
		}
219
220
		// Fill relation table with new clusters.
221
		$relations = $this->fillFaceRelationsFromPersons($userId, $modelId);
222
		$this->logInfo($relations . ' relations added as suggestions');
223
224
		// Prevents not create/recreate the clusters unnecessarily.
225
		$this->settingsService->setNeedRecreateClusters(false, $userId);
226
		$this->settingsService->setForceCreateClusters(false, $userId);
227
	}
228
229
	private function getCurrentClusters(array $faces): array {
230
		$chineseClusters = array();
231
		foreach($faces as $face) {
232
			if ($face->person !== null) {
233
				if (!isset($chineseClusters[$face->person])) {
234
					$chineseClusters[$face->person] = array();
235
				}
236
				$chineseClusters[$face->person][] = $face->id;
237
			}
238
		}
239
		return $chineseClusters;
240
	}
241
242
	private function getNewClusters(array $faces, array $relations): array {
243
		// Create edges for chinese whispers
244
		$sensitivity = $this->settingsService->getSensitivity();
245
		$min_confidence = $this->settingsService->getMinimumConfidence();
246
		$edges = array();
247
248
		if (version_compare(phpversion('pdlib'), '1.0.2', '>=')) {
249
			for ($i = 0, $face_count1 = count($faces); $i < $face_count1; $i++) {
250
				$face1 = $faces[$i];
251
				if ($face1->confidence < $min_confidence) {
252
					$edges[] = array($i, $i);
253
					continue;
254
				}
255
				for ($j = $i, $face_count2 = count($faces); $j < $face_count2; $j++) {
256
					$face2 = $faces[$j];
257
					if ($this->relationMapper->existsOnMatrix($face1->id, $face2->id, $relations)) {
258
						$state = $this->relationMapper->getStateOnMatrix($face1->id, $face2->id, $relations);
259
						if ($state === Relation::ACCEPTED) {
260
							$edges[] = array($i, $j);
261
							continue;
262
						} else if ($state === Relation::REJECTED) {
263
							continue;
264
						}
265
					}
266
					$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

266
					$distance = /** @scrutinizer ignore-call */ dlib_vector_length($face1->descriptor, $face2->descriptor);
Loading history...
267
268
					if ($distance < $sensitivity) {
269
						$edges[] = array($i, $j);
270
					}
271
				}
272
			}
273
		} else {
274
			$euclidean = new Euclidean();
275
			for ($i = 0, $face_count1 = count($faces); $i < $face_count1; $i++) {
276
				$face1 = $faces[$i];
277
				if ($face1->confidence < $min_confidence) {
278
					$edges[] = array($i, $i);
279
					continue;
280
				}
281
				for ($j = $i, $face_count2 = count($faces); $j < $face_count2; $j++) {
282
					$face2 = $faces[$j];
283
					// todo: can't this distance be a method in $face1->distance($face2)?
284
					$distance = $euclidean->distance($face1->descriptor, $face2->descriptor);
285
286
					if ($distance < $sensitivity) {
287
						$edges[] = array($i, $j);
288
					}
289
				}
290
			}
291
		}
292
293
		$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

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

390
				$distance = /** @scrutinizer ignore-call */ dlib_vector_length($face1->descriptor, $face2->descriptor);
Loading history...
391
				if ($distance < ($sensitivity + $deviation)) {
392
					$relation = new Relation();
393
					$relation->setFace1($face1->getId());
394
					$relation->setFace2($face2->getId());
395
					$relation->setState(RELATION::PROPOSED);
396
					$relations[] = $relation;
397
				}
398
			}
399
		}
400
401
		// Merge new suggested relations
402
		return $this->relationMapper->merge($userId, $modelId, $relations);
403
	}
404
405
}
406