Passed
Push — settings-service ( 0cfa6c...7803f5 )
by Matias
04:04
created

CreateClustersTask::getNewClusters()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

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

251
		$newChineseClustersByIndex = /** @scrutinizer ignore-call */ dlib_chinese_whispers($edges);
Loading history...
252
		$newClusters = array();
253
		for ($i = 0, $c = count($newChineseClustersByIndex); $i < $c; $i++) {
254
			if (!isset($newClusters[$newChineseClustersByIndex[$i]])) {
255
				$newClusters[$newChineseClustersByIndex[$i]] = array();
256
			}
257
			$newClusters[$newChineseClustersByIndex[$i]][] = $faces[$i]->id;
258
		}
259
260
		return $newClusters;
261
	}
262
263
	/**
264
	 * todo: only reason this is public is because of tests. Go figure it out better.
265
	 */
266
	public function mergeClusters(array $oldCluster, array $newCluster): array {
267
		// Create map of face transitions
268
		$transitions = array();
269
		foreach ($newCluster as $newPerson=>$newFaces) {
270
			foreach ($newFaces as $newFace) {
271
				$oldPersonFound = null;
272
				foreach ($oldCluster as $oldPerson => $oldFaces) {
273
					if (in_array($newFace, $oldFaces)) {
274
						$oldPersonFound = $oldPerson;
275
						break;
276
					}
277
				}
278
				$transitions[$newFace] = array($oldPersonFound, $newPerson);
279
			}
280
		}
281
		// Count transitions
282
		$transitionCount = array();
283
		foreach ($transitions as $transition) {
284
			$key = $transition[0] . ':' . $transition[1];
285
			if (array_key_exists($key, $transitionCount)) {
286
				$transitionCount[$key]++;
287
			} else {
288
				$transitionCount[$key] = 1;
289
			}
290
		}
291
		// Create map of new person -> old person transitions
292
		$newOldPersonMapping = array();
293
		$oldPersonProcessed = array(); // store this, so we don't waste cycles for in_array()
294
		arsort($transitionCount);
295
		foreach ($transitionCount as $transitionKey => $count) {
296
			$transition = explode(":", $transitionKey);
297
			$oldPerson = intval($transition[0]);
298
			$newPerson = intval($transition[1]);
299
			if (!array_key_exists($newPerson, $newOldPersonMapping)) {
300
				if (($oldPerson === 0) || (!array_key_exists($oldPerson, $oldPersonProcessed))) {
301
					$newOldPersonMapping[$newPerson] = $oldPerson;
302
					$oldPersonProcessed[$oldPerson] = 0;
303
				} else {
304
					$newOldPersonMapping[$newPerson] = 0;
305
				}
306
			}
307
		}
308
		// Starting with new cluster, convert all new person IDs with old person IDs
309
		$maxOldPersonId = 1;
310
		if (count($oldCluster) > 0) {
311
			$maxOldPersonId = max(array_keys($oldCluster)) + 1;
312
		}
313
314
		$result = array();
315
		foreach ($newCluster as $newPerson => $newFaces) {
316
			$oldPerson = $newOldPersonMapping[$newPerson];
317
			if ($oldPerson === 0) {
318
				$result[$maxOldPersonId] = $newFaces;
319
				$maxOldPersonId++;
320
			} else {
321
				$result[$oldPerson] = $newFaces;
322
			}
323
		}
324
		return $result;
325
	}
326
}
327