Passed
Push — fix-thumbnails ( 16e349 )
by Matias
03:19
created

CreateClustersTask::getNewClusters()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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

221
		$newChineseClustersByIndex = /** @scrutinizer ignore-call */ dlib_chinese_whispers($edges);
Loading history...
222
		$newClusters = array();
223
		for ($i = 0, $c = count($newChineseClustersByIndex); $i < $c; $i++) {
224
			if (!isset($newClusters[$newChineseClustersByIndex[$i]])) {
225
				$newClusters[$newChineseClustersByIndex[$i]] = array();
226
			}
227
			$newClusters[$newChineseClustersByIndex[$i]][] = $faces[$i]->id;
228
		}
229
230
		return $newClusters;
231
	}
232
233
	/**
234
	 * todo: only reason this is public is because of tests. Go figure it out better.
235
	 */
236 2
	public function mergeClusters(array $oldCluster, array $newCluster): array {
237
		// Create map of face transitions
238 2
		$transitions = array();
239 2
		foreach ($newCluster as $newPerson=>$newFaces) {
240 2
			foreach ($newFaces as $newFace) {
241 2
				$oldPersonFound = null;
242 2
				foreach ($oldCluster as $oldPerson => $oldFaces) {
243 2
					if (in_array($newFace, $oldFaces)) {
244 2
						$oldPersonFound = $oldPerson;
245 2
						break;
246
					}
247
				}
248 2
				$transitions[$newFace] = array($oldPersonFound, $newPerson);
249
			}
250
		}
251
		// Count transitions
252 2
		$transitionCount = array();
253 2
		foreach ($transitions as $transition) {
254 2
			$key = $transition[0] . ':' . $transition[1];
255 2
			if (array_key_exists($key, $transitionCount)) {
256 2
				$transitionCount[$key]++;
257
			} else {
258 2
				$transitionCount[$key] = 1;
259
			}
260
		}
261
		// Create map of new person -> old persion transitions
262 2
		$newOldPersonMapping = array();
263 2
		$oldPersonProcessed = array(); // store this, so we don't waste cycles for in_array()
264 2
		arsort($transitionCount);
265 2
		foreach ($transitionCount as $transitionKey => $count) {
266 2
			$transition = explode(":", $transitionKey);
267 2
			$oldPerson = intval($transition[0]);
268 2
			$newPerson = intval($transition[1]);
269 2
			if (!array_key_exists($newPerson, $newOldPersonMapping)) {
270 2
				if (($oldPerson === 0) || (!array_key_exists($oldPerson, $oldPersonProcessed))) {
271 2
					$newOldPersonMapping[$newPerson] = $oldPerson;
272 2
					$oldPersonProcessed[$oldPerson] = 0;
273
				} else {
274 2
					$newOldPersonMapping[$newPerson] = 0;
275
				}
276
			}
277
		}
278
		// Starting with new cluster, convert all new person IDs with old person IDs
279 2
		$maxOldPersonId = 1;
280 2
		if (count($oldCluster) > 0) {
281 2
			$maxOldPersonId = max(array_keys($oldCluster)) + 1;
282
		}
283
284 2
		$result = array();
285 2
		foreach ($newCluster as $newPerson => $newFaces) {
286 2
			$oldPerson = $newOldPersonMapping[$newPerson];
287 2
			if ($oldPerson === 0) {
288 2
				$result[$maxOldPersonId] = $newFaces;
289 2
				$maxOldPersonId++;
290
			} else {
291 2
				$result[$oldPerson] = $newFaces;
292
			}
293
		}
294 2
		return $result;
295
	}
296
}
297