1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2024-11-10
 * Description : Face classifier
 *
 * SPDX-FileCopyrightText: 2024-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * SPDX-FileCopyrightText: 2024-2025 by Michael Miller <michael underscore miller at msn dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "identityprovider.h"

// Qt includes

#include <QException>
#include <QReadWriteLock>
#include <QUuid>
#include <QThread>
#include <QThreadPool>
#include <QFuture>
#include <QtConcurrentRun>

// KDE includes

#include <klocalizedstring.h>

// Local includes

#include "digikam_debug.h"
#include "facedboperationgroup.h"
#include "facedbaccess.h"
#include "facedb.h"
#include "facescansettings.h"
#include "faceclassifier.h"
#include "recognitiontrainingupdatequeue.h"

namespace Digikam
{

QString IdentityProvider::FaceTrainingVersion = QLatin1String("8.6.0");
QString IdentityProvider::ExtractorModel      = QLatin1String("SFace");

class Q_DECL_HIDDEN IdentityProvider::Private
{
public:

    bool                            dbAvailable             = false;
    int                             seedMax                 = 0;

    QHash<int, Identity>            identityCache;

    QReadWriteLock                  trainingLock;
    RecognitionTrainingUpdateQueue  removeQueue;
    QThreadPool*                    removeThreadPool        = nullptr;
    QFuture<bool>                   removeThreadResult;
};

class Q_DECL_HIDDEN IdentityProviderCreator
{
public:

    IdentityProvider object;
};

Q_GLOBAL_STATIC(IdentityProviderCreator, identityProviderCreator)

// ---------------------------------------------------------------------------

IdentityProvider::IdentityProvider()
    : QObject(),
      d      (new Private)
{
    // Save face settings to remove old Detector and Recognizer models.

    FaceScanSettings prm;
    prm.readFromConfig();
    prm.detectModel    = FaceScanSettings::FaceDetectionModel::YuNet;
    prm.recognizeModel = FaceScanSettings::FaceRecognitionModel::SFace;
    prm.writeToConfig();

    // initialize the database

    if (!initialize())
    {
        qCWarning(DIGIKAM_FACESENGINE_LOG) << "IdentityProvider::initialize() failed!";
    }

    // Create a thread pool for the training remover.

    d->removeThreadPool = new QThreadPool(this);

#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))

    // Priority should be equal or greater than trainer or recognizer threads.

    d->removeThreadPool->setThreadPriority(QThread::NormalPriority);

#endif

    // We only need 1 thread for the training remover.

    d->removeThreadPool->setMaxThreadCount(1);

    // Run the remove queue listener thread.

    d->removeThreadResult = QtConcurrent::run(d->removeThreadPool,

#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))

                                              &IdentityProvider::trainingRemoveConcurrent,
                                              this

#else

                                              this,
                                              &IdentityProvider::trainingRemoveConcurrent

#endif

                                             );
}

IdentityProvider::~IdentityProvider()
{
    cancel();

    // final cleanup

    delete d;
}

IdentityProvider* IdentityProvider::instance()
{
    return &identityProviderCreator->object;
}

bool IdentityProvider::initialize()
{
    // Initialize the database.

    DbEngineParameters params   = CoreDbAccess::parameters().faceParameters();
    params.setFaceDatabasePath(CoreDbAccess::parameters().faceParameters().getFaceDatabaseNameOrDir());
    FaceDbAccess::setParameters(params, FaceScanSettings::FaceRecognitionModel::SFace);

    // Check if the database is available.

    d->dbAvailable              = FaceDbAccess::checkReadyForUse(nullptr);

    // do an integrity check

    if (!d->dbAvailable || !integrityCheck())
    {
        return false;
    }

    // load the identities

    const auto ids = FaceDbAccess().db()->identities();

    for (const Identity& identity : ids)<--- Shadow variable
    {
        d->identityCache[identity.id()] = identity;
    }

    return true;
}

void IdentityProvider::cancel()
{
    if (d && d->removeThreadResult.isRunning())
    {
        qCDebug(DIGIKAM_FACESENGINE_LOG) << "IdentityProvider::cancel: sent queue end signal";

        // Signal the remove thread to terminate.

        d->removeQueue.push(d->removeQueue.endSignal());

        // Wait for the remove thread to finish.

        d->removeThreadResult.waitForFinished();
    }
}

bool IdentityProvider::checkRetrainingRequired() const
{
    if (!d->dbAvailable)
    {
        // don't use this if we're not initialized

        qCDebug(DIGIKAM_FACESENGINE_LOG) << "IdentityProvider not initialized or database not available";
        QException().raise();
    }

    // return false if there are no identities in the database

    if (d->identityCache.isEmpty())
    {
        // write the current version to the database

        FaceDbAccess().db()->setTrainingVersionInfo(IdentityProvider::FaceTrainingVersion, IdentityProvider::ExtractorModel);
        return false;
    }

    // Check if the face training version is up-to-date.

    QString version;
    QString model;

    FaceDbAccess().db()->getTrainingVersionInfo(version, model);

    if (
        (IdentityProvider::FaceTrainingVersion == version) &&
        (IdentityProvider::ExtractorModel      == model)
       )
    {
        // retraining not needed

        return false;
    }

    // retraining needed

    return true;
}

bool IdentityProvider::integrityCheck()
{
    if (!d->dbAvailable)
    {
        return false;
    }

    d->trainingLock.lockForRead();

    bool result = FaceDbAccess().db()->integrityCheck();

    d->trainingLock.unlock();

    return result;
}

void IdentityProvider::vacuum()
{
    if (!d->dbAvailable)
    {
        return;
    }

    d->trainingLock.lockForWrite();

    FaceDbAccess().db()->vacuum();

    d->trainingLock.unlock();
}

// -----------------------------------------------------------------------

const QList<Identity> IdentityProvider::allIdentities() const
{
    // Return a copy of the identity cache.

    if (!d->dbAvailable)
    {
        return QList<Identity>();
    }

    d->trainingLock.lockForRead();

    QList<Identity> result = (d->identityCache.values());

    d->trainingLock.unlock();

    return result;
}

Identity IdentityProvider::identity(int id) const
{
    if (!d->dbAvailable)
    {
        return Identity();
    }

    d->trainingLock.lockForRead();

    Identity result = d->identityCache.value(id);

    d->trainingLock.unlock();

    return result;
}

Identity IdentityProvider::findIdentity(const QString& attribute, const QString& value) const
{
    if (!d->dbAvailable || attribute.isEmpty())
    {
        return Identity();
    }

    d->trainingLock.lockForRead();

    Identity result = findByAttribute(attribute, value);

    d->trainingLock.unlock();

    return result;
}

Identity IdentityProvider::findIdentity(const QMultiMap<QString, QString>& attributes) const
{
    if (!d->dbAvailable || attributes.isEmpty())
    {
        return Identity();
    }

    d->trainingLock.lockForRead();

    Identity match;

    // First and foremost, UUID.

    QString uuid = attributes.value(QLatin1String("uuid"));
    match        = findByAttribute(QLatin1String("uuid"), uuid);

    if (!match.isNull())
    {
        d->trainingLock.unlock();

        return match;
    }

    // A negative UUID match, with a given UUID, precludes any further search.

    if (!uuid.isNull())
    {
        d->trainingLock.unlock();

        return Identity();
    }

    // Full name.

    match = findByAttributes(QLatin1String("fullName"), attributes);

    if (!match.isNull())
    {
        d->trainingLock.unlock();

        return match;
    }

    // Name.

    match = findByAttributes(QLatin1String("name"), attributes);

    if (!match.isNull())
    {
        d->trainingLock.unlock();

        return match;
    }

    QMultiMap<QString, QString>::const_iterator it;

    for (it = attributes.begin() ; it != attributes.end() ; ++it)
    {
        if (
            (it.key() == QLatin1String("uuid"))     ||
            (it.key() == QLatin1String("fullName")) ||
            (it.key() == QLatin1String("name"))
           )
        {
            continue;
        }

        match = findByAttribute(it.key(), it.value());

        if (!match.isNull())
        {
            d->trainingLock.unlock();

            return match;
        }
    }

    d->trainingLock.unlock();

    return Identity();
}

Identity IdentityProvider::addIdentity(const QMultiMap<QString, QString>& attributes)
{
    if (!d->dbAvailable)
    {
        return Identity();
    }

    if (attributes.contains(QLatin1String("uuid")))
    {
        d->trainingLock.lockForRead();

        Identity matchByUuid = findIdentity(QLatin1String("uuid"), attributes.value(QLatin1String("uuid")));

        d->trainingLock.unlock();

        if (!matchByUuid.isNull())
        {
            // This situation is not well defined.

            qCDebug(DIGIKAM_FACESENGINE_LOG) << "Called addIdentity with a given UUID, "
                                                "and there is such a UUID already in the database."
                                             << "The existing identity is returned without adjusting properties!";

            return matchByUuid;
        }
    }

    Identity identity;<--- Shadow variable
    {
        FaceDbOperationGroup group;

        d->trainingLock.lockForWrite();

        int id = FaceDbAccess().db()->addIdentity();
        identity.setId(id);
        identity.setAttributesMap(attributes);
        identity.setAttribute(QLatin1String("uuid"), QUuid::createUuid().toString());

        FaceDbAccess().db()->updateIdentity(identity);

        d->trainingLock.unlock();
    }

    d->identityCache[identity.id()] = identity;

    return identity;
}

Identity IdentityProvider::addIdentityDebug(const QMultiMap<QString, QString>& attributes)
{
    Identity identity;<--- Shadow variable
    {
        identity.setId(attributes.value(QLatin1String("name")).toInt());
        identity.setAttributesMap(attributes);
        identity.setAttribute(QLatin1String("uuid"), QUuid::createUuid().toString());
    }

    d->trainingLock.lockForWrite();

    d->identityCache[identity.id()] = identity;

    d->trainingLock.unlock();

    return identity;
}

cv::Ptr<cv::ml::TrainData> IdentityProvider::getTrainingData() const
{
    cv::Ptr<cv::ml::TrainData> trainData = nullptr;

    if (!d->dbAvailable)
    {
        return trainData;
    }

    d->trainingLock.lockForRead();

    trainData = FaceDbAccess().db()->trainData();

    d->trainingLock.unlock();

    return trainData;
}

void IdentityProvider::deleteIdentity(const Identity& identityToBeDeleted)
{
    if (!d->dbAvailable || identityToBeDeleted.isNull())
    {
        return;
    }

    d->trainingLock.lockForWrite();

    FaceDbAccess().db()->deleteIdentity(identityToBeDeleted.id());
    d->identityCache.remove(identityToBeDeleted.id());

    d->trainingLock.unlock();
}

void IdentityProvider::deleteIdentities(QList<Identity> identitiesToBeDeleted)
{
    QList<Identity>::iterator identity = identitiesToBeDeleted.begin();<--- Shadow variable

    while (identity != identitiesToBeDeleted.end())
    {
        deleteIdentity(*identity);

        identity = identitiesToBeDeleted.erase(identity);
    }
}

void IdentityProvider::renameIdentity(const QString& uuid, const QString& newName)
{
    Identity identity = findIdentity(QLatin1String("uuid"), uuid);<--- Shadow variable

    if (!identity.isNull())
    {
        // remove the old name and fullName attributes

        identity.deleteAttributeValue(QLatin1String("name"), identity.attribute(QLatin1String("name")));
        identity.deleteAttributeValue(QLatin1String("fullName"), identity.attribute(QLatin1String("fullName")));

        // add the new name and fullName attributes

        identity.setAttribute(QLatin1String("name"), newName);
        identity.setAttribute(QLatin1String("fullName"), newName);

        // lock for write

        d->trainingLock.lockForWrite();

        // update the identity in the DB

        FaceDbAccess().db()->updateIdentity(identity);

        // update the identity in the cache

        d->identityCache[identity.id()] = identity;

        // unlock

        d->trainingLock.unlock();
    }
}

bool IdentityProvider::clearTraining(const QString& hash)
{
    d->trainingLock.lockForWrite();

    bool result = FaceDbAccess().db()->removeFaceVector(hash);

    d->trainingLock.unlock();

    return result;
}

void IdentityProvider::clearAllTraining()
{
    if (!d->dbAvailable)
    {
        return;
    }

    d->trainingLock.lockForWrite();

    d->identityCache.clear();
    FaceDbAccess().db()->clearIdentities();
    FaceDbAccess().db()->clearDNNTraining();

    d->trainingLock.unlock();
}

int IdentityProvider::addTraining(const Identity& identity, const QString& hash, const cv::Mat& feature)
{
    d->trainingLock.lockForWrite();

    int result = FaceDbAccess().db()->insertFaceVector(feature, identity.id(), hash);

    d->trainingLock.unlock();

    return result;
}

bool IdentityProvider::isValidId(int label) const
{
/*
    return ((label > d->seedMax) && d->identityCache.contains(label));
*/
    return (d->identityCache.contains(label));
}

//--------------------------------------------------------------
// private methods

/**
 * @note Takes care that there may be multiple values of attribute in identity's attributes.
 */
bool IdentityProvider::identityContains(const Identity& identity,
                                        const QString&  attribute,
                                        const QString&  value) const
{
    d->trainingLock.lockForRead();

    const QMultiMap<QString, QString> map          = identity.attributesMap();
    QMultiMap<QString, QString>::const_iterator it = map.constFind(attribute);

    for ( ; (it != map.constEnd()) && (it.key() == attribute) ; ++it)
    {
        if (it.value() == value)
        {
            d->trainingLock.unlock();
            return true;
        }
    }

    d->trainingLock.unlock();

    return false;
}

Identity IdentityProvider::findByAttribute(const QString& attribute,
                                        const QString& value) const
{
    d->trainingLock.lockForRead();

    for (const Identity& identity : std::as_const(d->identityCache))<--- Shadow variable
    {
        if (identityContains(identity, attribute, value))
        {
            // cppcheck-suppress useStlAlgorithm
            d->trainingLock.unlock();

            return identity;
        }
    }

    d->trainingLock.unlock();

    return Identity();
}

/**
 * @note Takes care that there may be multiple values of attribute in valueMap.
 */
Identity IdentityProvider::findByAttributes(const QString& attribute,
                                            const QMultiMap<QString, QString>& valueMap) const
{
    QMultiMap<QString, QString>::const_iterator it = valueMap.find(attribute);

    d->trainingLock.lockForRead();

    for ( ; (it != valueMap.end()) && (it.key() == attribute) ; ++it)
    {
        for (const Identity& identity : std::as_const(d->identityCache))<--- Shadow variable
        {
            if (identityContains(identity, attribute, it.value()))
            {
                // cppcheck-suppress useStlAlgorithm
                d->trainingLock.unlock();

                return identity;
            }
        }
    }

    d->trainingLock.unlock();

    return Identity();
}

bool IdentityProvider::trainingRemoveConcurrent()
{
    QString hash;

    while (true)
    {
        hash = d->removeQueue.pop_front();

        if (d->removeQueue.endSignal() != hash)
        {
            clearTraining(hash);
            hash.clear();

            FaceClassifier::instance()->retrain();
        }
        else
        {
            // send the end signal if anyone else is listening

            d->removeQueue.push(d->removeQueue.endSignal());


            break;
        }
    }

    qCDebug(DIGIKAM_FACESENGINE_LOG) << "IdentityProvider::trainingRemoveConcurrent thread terminated";

    return true;
}

} // namespace Digikam

#include "moc_identityprovider.cpp"