Classes and Methods

This section provides a full reference to the findface-facenapi context you can use in your plugin.

Tip

Use ctx from the activate parameters to access classes and methods directly from a plugin, e.g. use ctx.faces.Model.from_extraction_face(eface) to invoke Faces.Model.from_extraction_face(). To refer to classes and methods in a class that inherits from a HTTP API handler, use self.ctx: self.ctx.faces.Model.from_extraction_face(eface).

In this section:

Basic Classes

class MongoStore

Information about faces, galleries, cameras, persons, as well as authentication data are stored in the MongoDB database. The MongoStore class provides a base for interaction between findface-facenapi and MongoDB objects, being a wrapper around the MongoDB object collection. MongoStore wraps each object returned in a MongoDB query into an instance of the Model class ([Objects].Model), so that the object can have its own methods and properties and can be further processed through the findface-facenapi context.

Note

Objects can be of any type: face, gallery, camera, user, etc. MongoStore wraps them respectively into Faces.Model, Galleries.Model, Cameras.Model, Users.Model, etc.

find(self, filters, sort=None, skip=None, limit=None)

Searches for MongoDB objects that meet given requirements.

Parameters:
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
  • skip (elements of the MongoDB query dictionary or None) – (optional) criteria for skipping some of MongoDB objects
  • limit (int or None) – (optional) maximum number of returned objects
Returns:

Objects of a certain type

Return type:

List of instances of the [Objects].Model class

find_one(self, filters, sort=None, skip=None)

Returns the first MongoDB object that meets given requirements.

Parameters:
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
  • skip (elements of the MongoDB query dictionary or None) – (optional) criteria for skipping some of MongoDB objects
Returns:

Object of a certain type

Return type:

[Objects].Model instance

count(self, filters, sort=None, skip=None, limit=None)

Returns the total number of MongoDB objects of a certain type.

Parameters:
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
  • skip (elements of the MongoDB query dictionary or None) – (optional) criteria for skipping some of MongoDB objects
  • limit (int or None) – (optional) maximum number of counted objects
Returns:

Number of objects of a certain type

Return type:

int

remove_one(self, filters, sort=None)

Removes the first MongoDB object that meets given requirements.

Parameters:
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
Returns:

Removed object

Return type:

[Objects].Model instance

update_one(self, filters, update, sort=None, return_document=ReturnDocument.AFTER, **kwargs)

Updates a specified MongoDB object.

Parameters:
  • filters (elements of the MongoDB query dictionary or None) – filters
  • update – object property to update
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
Returns:

Updated object

Return type:

[Objects].Model instance

wrap_in_model(self, obj)

Wraps a MongoDB object into the Model class.

Parameters:obj (dict or OrderedDict) – MongoDB object
Returns:Object of a certain type
Return type:[Objects].Model instance
class UserStore(MongoStore)

Inherits from the MongoStore class. While MongoStore creates a base for interaction between findface-facenapi and MongoDB objects, the UserStore class provides user-based authentication for such interaction. It ensures that passing an unauthenticated request will cause an error instead of security vulnerabilities.

find(self, user, filters, sort=None, skip=None, limit=None)

Searches for MongoDB objects that meet given requirements.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
  • skip (elements of the MongoDB query dictionary or None) – (optional) criteria for skipping some of MongoDB objects
  • limit (int or None) – (optional) maximum number of returned objects
Returns:

Objects of a certain type

Return type:

List of instances of the [Objects].Model class

find_one(self, user, filters, sort=None, skip=None)

Returns the first MongoDB object that meets given requirements.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
  • skip (elements of the MongoDB query dictionary or None) – (optional) criteria for skipping some of MongoDB objects
Returns:

Object of a certain type

Return type:

[Objects].Model instance

count(self, user, filters, sort=None, skip=None, limit=None)

Returns the total number of MongoDB objects of a certain type.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
  • skip (elements of the MongoDB query dictionary or None) – (optional) criteria for skipping some of MongoDB objects
  • limit (int or None) – (optional) maximum number of counted objects
Returns:

Number of objects of a certain type

Return type:

int

remove_one(self, user, filters, sort=None)

Removes the first MongoDB object that meets given requirements.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • filters (elements of the MongoDB query dictionary or None) – filters
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
Returns:

Removed object

Return type:

[Objects].Model instance

update_one(self, user, filters, update, sort=None, return_document=ReturnDocument.AFTER, **kwargs)

Updates a specified MongoDB object.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • filters (elements of the MongoDB query dictionary or None) – filters
  • update – object property to update
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
Returns:

Updated object

Return type:

[Objects].Model instance

update_many(self, user, filters, update, sort=None, return_document=ReturnDocument.AFTER, **kwargs)

Updates specified MongoDB objects.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • filters (elements of the MongoDB query dictionary or None) – filters
  • update – object property to update
  • sort (elements of the MongoDB query dictionary or None) – (optional) criteria for sorting MongoDB objects
Returns:

Updated objects

Return type:

List of instances of the [Objects].Model class

User Enrollment

class Users(MongoStore)

Represents a collection of user objects. Each user object in the collection has the following properties:

  • _id - primary key, ObjectId
  • token - authentication token, must be unique, string
  • active - allows user to perform requests, bool

Each face and gallery in the system must belong to a certain user. User objects are also used for authentication.

``add(self, user)``

Enrolls a new user to the MongoDB database and returns it as an instance of the Users.Model class.

Parameters:user (dictionary) – user data
Returns:User object
Return type:Users.Model instance

Working with Faces and Galleries

class Faces.Model(OrderedDict)

Represents a face object.

classmethod from_extraction_face(cls, eface)

Creates a face object as an instance of the Faces.Model class.

Parameters:eface (dictionary) – set of face data received from ctx.extractor.extract()
Returns:Face object
Return type:Faces.Model instance
class Faces(UserStore)

Represents a collection of faces. Each face in the collection has the following properties:

  • _id - primary key, uint64
  • owner - owner id, ObjectId
  • facen - feature vector, base64
  • bbox - coordinates of the face region in the original image (bbox), Rectangle(self['x1'], self['y1'], self['x2'], self['y2'])
  • photo_hash - md5 of the original image
  • gallery - galleries that feature the face, list
  • meta - metadata, string or None
add(self, user, face)

Enrolls a face object to MongoDB, adding such parameters as _id and owner, and returns the updated face object. If the face has no id, this method generates a new id and inserts it into the face object. If the added face already has an id, this method fails at the attempt to insert a new id. In the case of a conflict, this method retries with another id up to 3 times.

Important

As this method updates only MongoDB and not the facen storage (tntapi), you will have to call Faces.add_to_galleries() after this method in order to add a face to a gallery.

Parameters:
  • user (ObjectId or Users.Model) – face owner passed as a user id or user object
  • face (Faces.Model instance) – face object
Returns:

Updated face object

Return type:

Faces.Model instance

Usage:

face = ctx.faces.Model.from_extraction_face(eface)
face['meta'] = meta
face = await ctx.faces.add(self.user, face)
regenerate_id(self, face)

Replaces a face’s id with a newly generated one.

Parameters:face (Faces.Model instance) – face object
Return type:Void
add_to_galleries(self, face, galleries)

Adds a face to specified galleries in MongoDB and the facen storage (tntapi). This method first attempts to add a face to galleries in the facen storage. In the case of success, it updates the face gallery field in MongoDB. If the face already exists in the facen storage gallery, the method generates an error.

Parameters:
  • face (Faces.Model instance) – face object
  • galleries (list[str]) – gallery names
Return type:

Void

del_from_galleries(self, face, galleries)

Removes a face from specified galleries in MongoDB and the facen storage (tntapi). This method first attempts to remove a face from galleries in the facen storage. In the case of success, it updates the face gallery field in MongoDB. If the face doesn’t exist in the facen storage gallery, it is considered to be successfully removed.

Parameters:
  • face (Faces.Model instance) – face object
  • galleries (list[str]) – gallery names
Return type:

Void

identify(self, user, gallery, face, limit, threshold, filters=None, ignore_errors=False)

Searches galleries for faces that resemble a given face with matching confidence larger or equal to the threshold.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • gallery – galleries to search in
  • face (Faces.Model or dictionary) – either a face object, or eface received from the ctx.extractor.extract() method
  • limit (int) – maximum number of returned faces
  • threshold (float) – minimum matching confidence between the given and returned faces, from 0 (lowest) to 1 (highest)
  • filters (elements of the MongoDB query dictionary or None) – (optional) filters
  • ignore_errors (bool) – (optional) If false and one or several tntapi shards are out of service, an error is returned. If true, no error is generated and available tntapi shards are used to obtain face identification results, indicating the number of live servers vs the total number of servers in the results.
Returns:

Results that feature properties of each found face in order of decreasing confidence.

Return type:

List-like object results

The results object features the following properties:

  • results.live_server: number of tntapi shards used to obtain face identification results (only if ignore_errors=True)
  • results.total_servers: total number of tntapi shards in the system (only if ignore_errors=True)
  • results[x]: namedtuple IdentifyResult featuring face and confidence.
  • results[x].face: face object
  • results[x].confidence: matching confidence, float
class ServerFaces(CoreFaces)

Extends functionality of the Faces class. Supports upload of original images, normalized images and thumbnails to the Uploads folder.

gen_ffupload_key(cls, face, suffix='.jpeg')

Populates the photo, thumbnail and normalized fields of a face object or a dictionary with relevant links to the original image, thumbnail and normalized image in the Uploads folder. These links will be used when invoking ServerFaces.upload().

Parameters:
  • face (Faces.Model instance or dictionary) – face object or face data
  • suffix (str) – (optional) suffix to the name of the image file
Returns:

Links

Return type:

‘%s/%s/%d_%s%s’ % (face[‘owner’], now.strftime(‘%Y%m%d’), face[‘_id’], token_hex(6), suffix)

upload_thumbnail(self, face, img: Image, url=None)

Uploads a face thumbnail to the Uploads folder or specified URL.

Parameters:
  • face (Faces.Model or dictionary) – either a face object, or eface received from the ctx.extractor.extract() method
  • img – original image facenapi.core.image.Image
  • url – upload URL
Return type:

Void

regenerate_id(self, face)

Regenerates a face id and URLs of the relevant original image, normalized face image, and the thumbnail (as they contain the face id).

Parameters:face (Faces.Model instance) – face object
Return type:Void
upload(self, face, img)

Uploads an original image, normalized face image and a thumbnail to the Uploads folder.

Parameters:
  • face (Faces.Model or dictionary) – either a face object, assigned the normalized property, or eface received from the ctx.extractor.extract() method
  • img – original image facenapi.core.image.Image
Return type:

Void

class Galleries(UserStore)

Represents a collection of galleries. Each gallery in the collection has the following properties:

  • owner - owner id, ObjectId
  • name - gallery name, string
add(self, user, gallery)

Creates a gallery in MongoDB and returns it as an instance of the Galleries.Model class.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • gallery (str) – gallery name
Returns:

Gallery object

Return type:

Galleries.Model instance

Raises:

ValueError – if the gallery name is not specified or already exists in MongoDB

Adding Camera

class Cameras(UserStore)

Represents a collection of cameras for video face detection.

``add(self, user, camera)``

Adds a camera to your system and returns it as an instance of the Cameras.Model class.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • camera (dictionary) – camera data
Returns:

Camera object

Return type:

Cameras.Model instance

Working with Persons

class Persons(UserStore)

Represents a collection of persons. Used to implement the advanced functions of Dynamic Person Creation and ‘Friend and Foe’ Identification.

Each person object in the collection has the following properties:

  • _id: person_id, uint64
  • owner: owner id, ObjectId
add(self, user, person)

Creates a person and returns it as a Persons.Model instance.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication and to populate the owner property)
  • person (dictionary) – person data
Returns:

Person object

Return type:

Persons.Model instance

identify(self, user, face, gallery, threshold, create=False, filters=None)

Searches galleries for persons whose faces resemble a given face with matching confidence larger or equal to the threshold.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • face (Faces.Model or dictionary) – either a face object, or eface received from the ctx.extractor.extract() method
  • gallery – galleries to search in
  • threshold (float) – minimum matching confidence between the given and returned faces, from 0 (lowest) to 1 (highest)
  • create (bool) – (optional) if True and no similar faces were found, the method creates a new person and returns person_id
  • filters (elements of the MongoDB query dictionary or None) – (optional) filters
Returns:

person_id of found persons, or person_id of a newly created person if no similar faces were found.

Return type:

uint64 or list[uint64]

is_friend(self, user, person_id, cam_id)

Checks if a person is a friend, for a given camera.

Parameters:
  • user (ObjectId or Users.Model) – user id or user object (for authentication)
  • person_id (uint64) – person_id of the person
  • cam_id (str) – camera id
Returns:

True if the person is a friend, and False otherwise.

Return type:

bool

Auxiliary Classes

class Counters(MongoStore)

Used to generate a new id for an object.

next(self, counter)

Increments the counter and returns its new value.

Parameters:

counter (int) – current value of the counter

Returns:

New value of the counter seq

Return type:

int

Raises:
  • TypeError – if the current value is not found
  • ValueError – if the current value is invalid