Skip to content

das-Face

vericlient.dasface.client.DasfaceClient

Bases: Client

Class to interact with the das-Face API.

das-Face differs from the other two clients in how it is spoken to: requests carry JSON with base64 encoded images rather than multipart file parts, its fields are camelCase, and it is served under /v2. None of that reaches the caller — images go in as a path or as bytes, and attributes keep their Python names.

Source code in src/vericlient/dasface/client.py
 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
class DasfaceClient(Client):
    """Class to interact with the das-Face API.

    das-Face differs from the other two clients in how it is spoken to: requests carry JSON
    with base64 encoded images rather than multipart file parts, its fields are camelCase,
    and it is served under `/v2`. None of that reaches the caller — images go in as a path or
    as bytes, and attributes keep their Python names.
    """

    def __init__(
        self,
        apikey: str | None = None,
        timeout: int | None = None,
        environment: str | None = None,
        location: str | None = None,
        url: str | None = None,
        headers: dict | None = None,
    ) -> None:
        """Create the DasfaceClient class.

        Args:
            apikey: The API key to use
            timeout: The timeout to use in the requests
            environment: The environment to use
            location: The location to use
            url: The URL to use in case of a custom target
            headers: The headers to be used in the requests

        """
        super().__init__(
            api=APIs.DASFACE,
            apikey=apikey,
            timeout=timeout,
            environment=environment,
            location=location,
            url=url,
            headers=headers,
        )
        # From the v3.35 specification, which enumerates these codes; v3.26 did not.
        # UnknownHashAndModeError and PathNotFoundError are not in it and were found against
        # work/eu. FormatNumberError, CorruptedSecretError and MetadataValidationError all
        # mean the credential cannot be used, which is what the caller needs to know, so they
        # share the library's own exception rather than leaking three service-internal names.
        self._exceptions = {
            "FaceNotFoundError": FaceNotFoundError,
            "MoreThanOneFaceError": MoreThanOneFaceError,
            "FaceAlignmentError": FaceAlignmentError,
            "FaceTooSmallForIAS": FaceTooSmallForIasError,
            "ObsoleteCredentialModelError": ObsoleteCredentialModelError,
            "MetadataEqError": IncompatibleCredentialsError,
            "UnknownHashAndModeError": UnknownHashAndModeError,
            "PathNotFoundError": PathNotFoundError,
            "ExpiredOrInvalidChallengeError": ExpiredOrInvalidChallengeError,
            "UnsupportedMediaTypeError": UnsupportedMediaTypeError,
            "FormatNumberError": InvalidCredentialError,
            "CorruptedSecretError": InvalidCredentialError,
            "MetadataValidationError": InvalidCredentialError,
            "ZeroLengthVideoError": ZeroLengthVideoError,
            "NotEnoughVideoDataError": NotEnoughVideoDataError,
            "VideoExtractionError": VideoExtractionError,
            "InvalidFPSVideoError": InvalidVideoMetadataError,
            "InvalidNumFramesVideoError": InvalidVideoMetadataError,
        }

    def alive(self) -> bool:
        """Check if the service is alive.

        Returns
            bool: True if the service is alive, False otherwise

        """
        response = self._get(endpoint=DasfaceEndpoints.ALIVE.value)
        accepted_status_code = 204
        return response.status_code == accepted_status_code

    def _handle_error_response(self, response: Response) -> None:
        """Handle error responses from the API.

        das-Face reports its failures as `{code, message, status}`.
        """
        payload = self._error_payload(response)
        code = payload.get("code")

        handler = self._exceptions.get(code)
        if handler:
            raise handler

        # One code covers every malformed input, and what it was is split between the message
        # and the per-field errors, so both are passed through rather than swallowed.
        if code == "FormValidationError":
            errors = [(field, reason) for field, reason in payload.get("errors") or []]
            raise FormValidationError(payload.get("message"), errors)

        # An unrecognised code still says more than a generic server error would.
        if code:
            raise DasfaceApiError(code, payload.get("message"))

        self._raise_server_error(response)

    def get_models(self) -> ModelsOutput:
        """Get the biometrics models available in the service.

        One entry per hash and mode, so the same hash appears several times.

        Returns:
            ModelsOutput: The available models

        """
        response = self._get(endpoint=DasfaceEndpoints.MODELS.value)
        return ModelsOutput(models=response.json())

    @legacy_model_argument(GenerateCredentialInput)
    def generate_credential(
        self,
        image: str | bytes,
        hash: str | None = None,  # noqa: A002
        mode: str | None = None,
        inemex: bool = False,  # noqa: FBT001, FBT002
    ) -> GenerateCredentialOutput:
        """Generate a credential from a photo.

        A credential is the biometric representation of a face, and what gets stored and
        compared later. The model is part of it, so `hash` and `mode` are required: take
        them from `get_models()`. The service has no endpoint that picks a model for you.

        Setting `inemex` uses the INE Mexico variant of the endpoint, which needs a specific
        agreement with Veridas. That one does have a default-model form, so with `inemex`
        set the model may be left out.

        Args:
            image: The photo, as a path or as bytes
            hash: The hash of the model to use, from `get_models()`
            mode: The mode to use, from `get_models()`
            inemex: Use the INE Mexico variant of the endpoint

        Returns:
            GenerateCredentialOutput: The credential and the model behind it

        Raises:
            FaceTooSmallForIasError: If the face is too small to analyse
            UnknownHashAndModeError: If no model matches that hash and mode
            FormValidationError: If the photo cannot be read

        """
        data_model = GenerateCredentialInput(image=image, hash=hash, mode=mode, inemex=inemex)
        if not data_model.inemex:
            endpoint = DasfaceEndpoints.MODEL_CREDENTIAL_PHOTO.value
        elif data_model.hash:
            endpoint = DasfaceEndpoints.INEMEX_MODEL_CREDENTIAL_PHOTO.value
        else:
            endpoint = DasfaceEndpoints.INEMEX_DEFAULT_CREDENTIAL_PHOTO.value
        if data_model.hash:
            endpoint = endpoint.replace("<hash>", data_model.hash).replace("<mode>", data_model.mode)

        response = self._post(
            endpoint=endpoint,
            json_={"targetImage": encode_base64(data_model.image)},
        )
        return GenerateCredentialOutput(**response.json())

    @legacy_model_argument(GetModelMetadataFromCredentialInput)
    def get_model_metadata_from_credential(self, credential: str) -> GetModelMetadataFromCredentialOutput:
        """Get the model a credential was generated with.

        Useful to tell whether a credential stored some time ago still matches a model the
        service offers today.

        Args:
            credential: The credential to inspect

        Returns:
            GetModelMetadataFromCredentialOutput: The model behind the credential

        Raises:
            FormValidationError: If the credential is not a credential

        """
        data_model = GetModelMetadataFromCredentialInput(credential=credential)
        response = self._post(
            endpoint=DasfaceEndpoints.MODELS_METADATA_FROM_CREDENTIAL.value,
            json_={"credential": data_model.credential},
        )
        return GetModelMetadataFromCredentialOutput(**response.json())

    @legacy_model_argument(VerifyPhotoInput)
    def verify_photo(
        self,
        anchor_image: str | bytes,
        target_image: str | bytes,
        mode: str | None = None,
    ) -> VerificationOutput:
        """Compare two photos and report how confident the service is that they match.

        Args:
            anchor_image: The reference photo, as a path or as bytes
            target_image: The photo to evaluate, as a path or as bytes
            mode: The model mode to use. The service picks its default when omitted

        Returns:
            VerificationOutput: The confidence, from 0 to 1

        Raises:
            FaceNotFoundError: If either photo holds no face
            MoreThanOneFaceError: If either photo holds more than one
            FaceAlignmentError: If a face's key points could not be located
            FormValidationError: If a photo cannot be read

        """
        data_model = VerifyPhotoInput(anchor_image=anchor_image, target_image=target_image, mode=mode)
        body = {
            "anchorImage": encode_base64(data_model.anchor_image),
            "targetImage": encode_base64(data_model.target_image),
        }
        if data_model.mode is not None:
            body["mode"] = data_model.mode

        response = self._post(endpoint=DasfaceEndpoints.VERIFICATION_PHOTO.value, json_=body)
        return VerificationOutput(**response.json())

    @legacy_model_argument(VerifyVideoInput)
    def verify_video(self, anchor_image: str | bytes, target_video: str | bytes) -> VerificationOutput:
        """Compare a photo against the face in a video.

        Args:
            anchor_image: The reference photo, as a path or as bytes
            target_video: The video to evaluate, as a path or as bytes

        Returns:
            VerificationOutput: The confidence, from 0 to 1

        Raises:
            FaceNotFoundError: If no face is found
            ZeroLengthVideoError: If the video is empty or corrupted
            NotEnoughVideoDataError: If the video holds too few usable frames

        """
        data_model = VerifyVideoInput(anchor_image=anchor_image, target_video=target_video)
        response = self._post(
            endpoint=DasfaceEndpoints.VERIFICATION_VIDEO.value,
            json_={
                "anchorImage": encode_base64(data_model.anchor_image),
                "targetVideo": encode_base64(data_model.target_video),
            },
        )
        return VerificationOutput(**response.json())

    @legacy_model_argument(VerifyCredentialInput)
    def verify_credential(self, anchor_image: str | bytes, target_credential: str) -> VerificationOutput:
        """Compare a photo against a stored credential.

        This is the usual verification: the credential was generated once at enrolment, and
        every later check compares a fresh photo against it without needing the original.

        Args:
            anchor_image: The photo, as a path or as bytes
            target_credential: The credential to compare it with

        Returns:
            VerificationOutput: The confidence, from 0 to 1

        Raises:
            InvalidCredentialError: If the credential cannot be read
            ObsoleteCredentialModelError: If it came from a model the service has dropped
            FaceNotFoundError: If the photo holds no face

        """
        data_model = VerifyCredentialInput(anchor_image=anchor_image, target_credential=target_credential)
        response = self._post(
            endpoint=DasfaceEndpoints.VERIFICATION_CREDENTIAL.value,
            json_={
                "anchorImage": encode_base64(data_model.anchor_image),
                "targetCredential": data_model.target_credential,
            },
        )
        return VerificationOutput(**response.json())

    @legacy_model_argument(PhotoAuthenticityInput)
    def check_photo_authenticity(self, image: str | bytes) -> PhotoAuthenticityOutput:
        """Check whether a selfie is a genuine capture rather than a photo of a screen or print.

        The face has to fill enough of the frame: a small one is rejected with
        FaceTooSmallForIasError rather than scored low.

        Args:
            image: The selfie to analyse, as a path or as bytes

        Returns:
            PhotoAuthenticityOutput: The confidence, from 0 to 1

        Raises:
            FaceTooSmallForIasError: If the face is too small to analyse
            FaceNotFoundError: If the photo holds no face
            MoreThanOneFaceError: If it holds more than one

        """
        data_model = PhotoAuthenticityInput(image=image)
        response = self._post(
            endpoint=DasfaceEndpoints.AUTHENTICITY_PHOTO.value,
            json_={"targetImage": encode_base64(data_model.image)},
        )
        return PhotoAuthenticityOutput(**response.json())

    @legacy_model_argument(VideoAuthenticityInput)
    def check_video_authenticity(self, anchor_image: str | bytes, target_video: str | bytes) -> VideoAuthenticityOutput:
        """Check whether a video is a genuine recording, and of the expected person.

        Answers both questions at once, and they are independent: a genuine recording of
        somebody else scores high on authenticity and low on similarity.

        Args:
            anchor_image: The photo of the expected person, as a path or as bytes
            target_video: The video to analyse, as a path or as bytes

        Returns:
            VideoAuthenticityOutput: The authenticity and the similarity, each from 0 to 1

        Raises:
            FaceTooSmallForIasError: If a face is too small to analyse
            ZeroLengthVideoError: If the video is empty or corrupted
            VideoExtractionError: If the video cannot be decoded
            NotEnoughVideoDataError: If it holds too few usable frames

        """
        data_model = VideoAuthenticityInput(anchor_image=anchor_image, target_video=target_video)
        response = self._post(
            endpoint=DasfaceEndpoints.AUTHENTICITY_VIDEO_PHOTO.value,
            json_={
                "anchorImage": encode_base64(data_model.anchor_image),
                "targetVideo": encode_base64(data_model.target_video),
            },
        )
        return VideoAuthenticityOutput(**response.json())

    @legacy_model_argument(SequentialChallengeInput)
    def generate_sequential_challenge(
        self,
        length: int | None = None,
        expiration: int | None = None,
    ) -> SequentialChallengeOutput:
        """Generate a liveness challenge: a sequence of actions for the subject to perform.

        The point of a challenge is that the recording cannot have been prepared in advance,
        since the actions are only known once the challenge is issued. Show the actions to
        the subject, record them, and send the recording back to
        `analyse_challenge_response` together with this token.

        Args:
            length: How many actions to ask for, from 1 to 6. The service defaults to 2
            expiration: How long the challenge stays valid, in seconds, from 300 to 1800.
                The service defaults to 1800

        Returns:
            SequentialChallengeOutput: The token to pass on, and the actions to prompt for

        Raises:
            FormValidationError: If the length or the expiration is out of range

        """
        data_model = SequentialChallengeInput(length=length, expiration=expiration)
        body = {
            key: value
            for key, value in (("length", data_model.length), ("expiration", data_model.expiration))
            if value is not None
        }

        response = self._post(endpoint=DasfaceEndpoints.CHALLENGES_GENERATION_SEQUENTIAL.value, json_=body)
        return self._read_challenge(response)

    def _read_challenge(self, response: Response) -> SequentialChallengeOutput:
        """Read a challenge out of the JWS token the service answers with.

        The signature is not checked. It is not this client's to check: the token is signed
        for the service to verify when the recording comes back, and the key is not
        published. The payload is read only to save every caller writing the same base64
        split, and the token is passed on exactly as it arrived.
        """
        token = response.text.strip()
        try:
            payload = token.split(".")[1]
            challenge = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
            actions = [
                ChallengeAction(
                    name=action["name"],
                    action_class=action["class"],
                    parameters=action.get("parameters") or {},
                )
                for action in challenge["challenge"]["actions"]
            ]
            return SequentialChallengeOutput(
                token=token,
                id=challenge["id"],
                timestamp=challenge["timestamp"],
                expires=challenge["expires"],
                actions=actions,
            )
        except (IndexError, KeyError, TypeError, ValueError, binascii.Error):
            # A 200 whose token cannot be read is the service breaking its own contract.
            self._raise_server_error(response)
            raise

    @legacy_model_argument(ChallengeAnalysisInput)
    def analyse_challenge_response(
        self,
        token: str,
        annotations: str | bytes,
        anchor_image: str | bytes,
        target_video: str | bytes,
    ) -> ChallengeAnalysisOutput:
        """Analyse the recording of a challenge against the photo of the expected person.

        One figure answers all of it: whether the recording is genuine, whether it performs
        the challenge that was issued, and whether it is the right person.

        Unlike every other endpoint here, this one reports what went wrong inside a
        successful response. A confidence of `None` means the analysis could not be
        completed, and the `errors` of the result say why.

        Args:
            token: The token from `generate_sequential_challenge`, unchanged
            annotations: The SDK's WebVTT annotations, as a path or as bytes. A `str` is read
                as a path, so pass in-memory text as `text.encode()`
            anchor_image: The photo of the expected person, as a path or as bytes
            target_video: The recording of the challenge, as a path or as bytes

        Returns:
            ChallengeAnalysisOutput: The confidence, or `None` with the errors behind it

        Raises:
            ExpiredOrInvalidChallengeError: If the challenge is no longer valid
            FormValidationError: If the token, the annotations or a media file cannot be read

        """
        data_model = ChallengeAnalysisInput(
            token=token,
            annotations=annotations,
            anchor_image=anchor_image,
            target_video=target_video,
        )
        response = self._post(
            endpoint=DasfaceEndpoints.CHALLENGES_ANALYSIS_VIDEO_PHOTO.value,
            json_={
                "token": data_model.token,
                "annotations": encode_base64(data_model.annotations),
                "anchorImage": encode_base64(data_model.anchor_image),
                "targetVideo": encode_base64(data_model.target_video),
            },
        )
        payload = response.json()
        return ChallengeAnalysisOutput(
            confidence=payload.get("confidence"),
            errors=[ChallengeError(code=code, message=message) for code, message in payload.get("errors") or []],
        )

alive

alive()

Check if the service is alive.

Returns bool: True if the service is alive, False otherwise

Source code in src/vericlient/dasface/client.py
def alive(self) -> bool:
    """Check if the service is alive.

    Returns
        bool: True if the service is alive, False otherwise

    """
    response = self._get(endpoint=DasfaceEndpoints.ALIVE.value)
    accepted_status_code = 204
    return response.status_code == accepted_status_code

get_models

get_models()

Get the biometrics models available in the service.

One entry per hash and mode, so the same hash appears several times.

Returns:

Name Type Description
ModelsOutput ModelsOutput

The available models

Source code in src/vericlient/dasface/client.py
def get_models(self) -> ModelsOutput:
    """Get the biometrics models available in the service.

    One entry per hash and mode, so the same hash appears several times.

    Returns:
        ModelsOutput: The available models

    """
    response = self._get(endpoint=DasfaceEndpoints.MODELS.value)
    return ModelsOutput(models=response.json())

generate_credential

generate_credential(
    image, hash=None, mode=None, inemex=False
)

Generate a credential from a photo.

A credential is the biometric representation of a face, and what gets stored and compared later. The model is part of it, so hash and mode are required: take them from get_models(). The service has no endpoint that picks a model for you.

Setting inemex uses the INE Mexico variant of the endpoint, which needs a specific agreement with Veridas. That one does have a default-model form, so with inemex set the model may be left out.

Parameters:

Name Type Description Default
image str | bytes

The photo, as a path or as bytes

required
hash str | None

The hash of the model to use, from get_models()

None
mode str | None

The mode to use, from get_models()

None
inemex bool

Use the INE Mexico variant of the endpoint

False

Returns:

Name Type Description
GenerateCredentialOutput GenerateCredentialOutput

The credential and the model behind it

Raises:

Type Description
FaceTooSmallForIasError

If the face is too small to analyse

UnknownHashAndModeError

If no model matches that hash and mode

FormValidationError

If the photo cannot be read

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(GenerateCredentialInput)
def generate_credential(
    self,
    image: str | bytes,
    hash: str | None = None,  # noqa: A002
    mode: str | None = None,
    inemex: bool = False,  # noqa: FBT001, FBT002
) -> GenerateCredentialOutput:
    """Generate a credential from a photo.

    A credential is the biometric representation of a face, and what gets stored and
    compared later. The model is part of it, so `hash` and `mode` are required: take
    them from `get_models()`. The service has no endpoint that picks a model for you.

    Setting `inemex` uses the INE Mexico variant of the endpoint, which needs a specific
    agreement with Veridas. That one does have a default-model form, so with `inemex`
    set the model may be left out.

    Args:
        image: The photo, as a path or as bytes
        hash: The hash of the model to use, from `get_models()`
        mode: The mode to use, from `get_models()`
        inemex: Use the INE Mexico variant of the endpoint

    Returns:
        GenerateCredentialOutput: The credential and the model behind it

    Raises:
        FaceTooSmallForIasError: If the face is too small to analyse
        UnknownHashAndModeError: If no model matches that hash and mode
        FormValidationError: If the photo cannot be read

    """
    data_model = GenerateCredentialInput(image=image, hash=hash, mode=mode, inemex=inemex)
    if not data_model.inemex:
        endpoint = DasfaceEndpoints.MODEL_CREDENTIAL_PHOTO.value
    elif data_model.hash:
        endpoint = DasfaceEndpoints.INEMEX_MODEL_CREDENTIAL_PHOTO.value
    else:
        endpoint = DasfaceEndpoints.INEMEX_DEFAULT_CREDENTIAL_PHOTO.value
    if data_model.hash:
        endpoint = endpoint.replace("<hash>", data_model.hash).replace("<mode>", data_model.mode)

    response = self._post(
        endpoint=endpoint,
        json_={"targetImage": encode_base64(data_model.image)},
    )
    return GenerateCredentialOutput(**response.json())

get_model_metadata_from_credential

get_model_metadata_from_credential(credential)

Get the model a credential was generated with.

Useful to tell whether a credential stored some time ago still matches a model the service offers today.

Parameters:

Name Type Description Default
credential str

The credential to inspect

required

Returns:

Name Type Description
GetModelMetadataFromCredentialOutput GetModelMetadataFromCredentialOutput

The model behind the credential

Raises:

Type Description
FormValidationError

If the credential is not a credential

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(GetModelMetadataFromCredentialInput)
def get_model_metadata_from_credential(self, credential: str) -> GetModelMetadataFromCredentialOutput:
    """Get the model a credential was generated with.

    Useful to tell whether a credential stored some time ago still matches a model the
    service offers today.

    Args:
        credential: The credential to inspect

    Returns:
        GetModelMetadataFromCredentialOutput: The model behind the credential

    Raises:
        FormValidationError: If the credential is not a credential

    """
    data_model = GetModelMetadataFromCredentialInput(credential=credential)
    response = self._post(
        endpoint=DasfaceEndpoints.MODELS_METADATA_FROM_CREDENTIAL.value,
        json_={"credential": data_model.credential},
    )
    return GetModelMetadataFromCredentialOutput(**response.json())

verify_photo

verify_photo(anchor_image, target_image, mode=None)

Compare two photos and report how confident the service is that they match.

Parameters:

Name Type Description Default
anchor_image str | bytes

The reference photo, as a path or as bytes

required
target_image str | bytes

The photo to evaluate, as a path or as bytes

required
mode str | None

The model mode to use. The service picks its default when omitted

None

Returns:

Name Type Description
VerificationOutput VerificationOutput

The confidence, from 0 to 1

Raises:

Type Description
FaceNotFoundError

If either photo holds no face

MoreThanOneFaceError

If either photo holds more than one

FaceAlignmentError

If a face's key points could not be located

FormValidationError

If a photo cannot be read

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(VerifyPhotoInput)
def verify_photo(
    self,
    anchor_image: str | bytes,
    target_image: str | bytes,
    mode: str | None = None,
) -> VerificationOutput:
    """Compare two photos and report how confident the service is that they match.

    Args:
        anchor_image: The reference photo, as a path or as bytes
        target_image: The photo to evaluate, as a path or as bytes
        mode: The model mode to use. The service picks its default when omitted

    Returns:
        VerificationOutput: The confidence, from 0 to 1

    Raises:
        FaceNotFoundError: If either photo holds no face
        MoreThanOneFaceError: If either photo holds more than one
        FaceAlignmentError: If a face's key points could not be located
        FormValidationError: If a photo cannot be read

    """
    data_model = VerifyPhotoInput(anchor_image=anchor_image, target_image=target_image, mode=mode)
    body = {
        "anchorImage": encode_base64(data_model.anchor_image),
        "targetImage": encode_base64(data_model.target_image),
    }
    if data_model.mode is not None:
        body["mode"] = data_model.mode

    response = self._post(endpoint=DasfaceEndpoints.VERIFICATION_PHOTO.value, json_=body)
    return VerificationOutput(**response.json())

verify_video

verify_video(anchor_image, target_video)

Compare a photo against the face in a video.

Parameters:

Name Type Description Default
anchor_image str | bytes

The reference photo, as a path or as bytes

required
target_video str | bytes

The video to evaluate, as a path or as bytes

required

Returns:

Name Type Description
VerificationOutput VerificationOutput

The confidence, from 0 to 1

Raises:

Type Description
FaceNotFoundError

If no face is found

ZeroLengthVideoError

If the video is empty or corrupted

NotEnoughVideoDataError

If the video holds too few usable frames

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(VerifyVideoInput)
def verify_video(self, anchor_image: str | bytes, target_video: str | bytes) -> VerificationOutput:
    """Compare a photo against the face in a video.

    Args:
        anchor_image: The reference photo, as a path or as bytes
        target_video: The video to evaluate, as a path or as bytes

    Returns:
        VerificationOutput: The confidence, from 0 to 1

    Raises:
        FaceNotFoundError: If no face is found
        ZeroLengthVideoError: If the video is empty or corrupted
        NotEnoughVideoDataError: If the video holds too few usable frames

    """
    data_model = VerifyVideoInput(anchor_image=anchor_image, target_video=target_video)
    response = self._post(
        endpoint=DasfaceEndpoints.VERIFICATION_VIDEO.value,
        json_={
            "anchorImage": encode_base64(data_model.anchor_image),
            "targetVideo": encode_base64(data_model.target_video),
        },
    )
    return VerificationOutput(**response.json())

verify_credential

verify_credential(anchor_image, target_credential)

Compare a photo against a stored credential.

This is the usual verification: the credential was generated once at enrolment, and every later check compares a fresh photo against it without needing the original.

Parameters:

Name Type Description Default
anchor_image str | bytes

The photo, as a path or as bytes

required
target_credential str

The credential to compare it with

required

Returns:

Name Type Description
VerificationOutput VerificationOutput

The confidence, from 0 to 1

Raises:

Type Description
InvalidCredentialError

If the credential cannot be read

ObsoleteCredentialModelError

If it came from a model the service has dropped

FaceNotFoundError

If the photo holds no face

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(VerifyCredentialInput)
def verify_credential(self, anchor_image: str | bytes, target_credential: str) -> VerificationOutput:
    """Compare a photo against a stored credential.

    This is the usual verification: the credential was generated once at enrolment, and
    every later check compares a fresh photo against it without needing the original.

    Args:
        anchor_image: The photo, as a path or as bytes
        target_credential: The credential to compare it with

    Returns:
        VerificationOutput: The confidence, from 0 to 1

    Raises:
        InvalidCredentialError: If the credential cannot be read
        ObsoleteCredentialModelError: If it came from a model the service has dropped
        FaceNotFoundError: If the photo holds no face

    """
    data_model = VerifyCredentialInput(anchor_image=anchor_image, target_credential=target_credential)
    response = self._post(
        endpoint=DasfaceEndpoints.VERIFICATION_CREDENTIAL.value,
        json_={
            "anchorImage": encode_base64(data_model.anchor_image),
            "targetCredential": data_model.target_credential,
        },
    )
    return VerificationOutput(**response.json())

check_photo_authenticity

check_photo_authenticity(image)

Check whether a selfie is a genuine capture rather than a photo of a screen or print.

The face has to fill enough of the frame: a small one is rejected with FaceTooSmallForIasError rather than scored low.

Parameters:

Name Type Description Default
image str | bytes

The selfie to analyse, as a path or as bytes

required

Returns:

Name Type Description
PhotoAuthenticityOutput PhotoAuthenticityOutput

The confidence, from 0 to 1

Raises:

Type Description
FaceTooSmallForIasError

If the face is too small to analyse

FaceNotFoundError

If the photo holds no face

MoreThanOneFaceError

If it holds more than one

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(PhotoAuthenticityInput)
def check_photo_authenticity(self, image: str | bytes) -> PhotoAuthenticityOutput:
    """Check whether a selfie is a genuine capture rather than a photo of a screen or print.

    The face has to fill enough of the frame: a small one is rejected with
    FaceTooSmallForIasError rather than scored low.

    Args:
        image: The selfie to analyse, as a path or as bytes

    Returns:
        PhotoAuthenticityOutput: The confidence, from 0 to 1

    Raises:
        FaceTooSmallForIasError: If the face is too small to analyse
        FaceNotFoundError: If the photo holds no face
        MoreThanOneFaceError: If it holds more than one

    """
    data_model = PhotoAuthenticityInput(image=image)
    response = self._post(
        endpoint=DasfaceEndpoints.AUTHENTICITY_PHOTO.value,
        json_={"targetImage": encode_base64(data_model.image)},
    )
    return PhotoAuthenticityOutput(**response.json())

check_video_authenticity

check_video_authenticity(anchor_image, target_video)

Check whether a video is a genuine recording, and of the expected person.

Answers both questions at once, and they are independent: a genuine recording of somebody else scores high on authenticity and low on similarity.

Parameters:

Name Type Description Default
anchor_image str | bytes

The photo of the expected person, as a path or as bytes

required
target_video str | bytes

The video to analyse, as a path or as bytes

required

Returns:

Name Type Description
VideoAuthenticityOutput VideoAuthenticityOutput

The authenticity and the similarity, each from 0 to 1

Raises:

Type Description
FaceTooSmallForIasError

If a face is too small to analyse

ZeroLengthVideoError

If the video is empty or corrupted

VideoExtractionError

If the video cannot be decoded

NotEnoughVideoDataError

If it holds too few usable frames

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(VideoAuthenticityInput)
def check_video_authenticity(self, anchor_image: str | bytes, target_video: str | bytes) -> VideoAuthenticityOutput:
    """Check whether a video is a genuine recording, and of the expected person.

    Answers both questions at once, and they are independent: a genuine recording of
    somebody else scores high on authenticity and low on similarity.

    Args:
        anchor_image: The photo of the expected person, as a path or as bytes
        target_video: The video to analyse, as a path or as bytes

    Returns:
        VideoAuthenticityOutput: The authenticity and the similarity, each from 0 to 1

    Raises:
        FaceTooSmallForIasError: If a face is too small to analyse
        ZeroLengthVideoError: If the video is empty or corrupted
        VideoExtractionError: If the video cannot be decoded
        NotEnoughVideoDataError: If it holds too few usable frames

    """
    data_model = VideoAuthenticityInput(anchor_image=anchor_image, target_video=target_video)
    response = self._post(
        endpoint=DasfaceEndpoints.AUTHENTICITY_VIDEO_PHOTO.value,
        json_={
            "anchorImage": encode_base64(data_model.anchor_image),
            "targetVideo": encode_base64(data_model.target_video),
        },
    )
    return VideoAuthenticityOutput(**response.json())

generate_sequential_challenge

generate_sequential_challenge(length=None, expiration=None)

Generate a liveness challenge: a sequence of actions for the subject to perform.

The point of a challenge is that the recording cannot have been prepared in advance, since the actions are only known once the challenge is issued. Show the actions to the subject, record them, and send the recording back to analyse_challenge_response together with this token.

Parameters:

Name Type Description Default
length int | None

How many actions to ask for, from 1 to 6. The service defaults to 2

None
expiration int | None

How long the challenge stays valid, in seconds, from 300 to 1800. The service defaults to 1800

None

Returns:

Name Type Description
SequentialChallengeOutput SequentialChallengeOutput

The token to pass on, and the actions to prompt for

Raises:

Type Description
FormValidationError

If the length or the expiration is out of range

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(SequentialChallengeInput)
def generate_sequential_challenge(
    self,
    length: int | None = None,
    expiration: int | None = None,
) -> SequentialChallengeOutput:
    """Generate a liveness challenge: a sequence of actions for the subject to perform.

    The point of a challenge is that the recording cannot have been prepared in advance,
    since the actions are only known once the challenge is issued. Show the actions to
    the subject, record them, and send the recording back to
    `analyse_challenge_response` together with this token.

    Args:
        length: How many actions to ask for, from 1 to 6. The service defaults to 2
        expiration: How long the challenge stays valid, in seconds, from 300 to 1800.
            The service defaults to 1800

    Returns:
        SequentialChallengeOutput: The token to pass on, and the actions to prompt for

    Raises:
        FormValidationError: If the length or the expiration is out of range

    """
    data_model = SequentialChallengeInput(length=length, expiration=expiration)
    body = {
        key: value
        for key, value in (("length", data_model.length), ("expiration", data_model.expiration))
        if value is not None
    }

    response = self._post(endpoint=DasfaceEndpoints.CHALLENGES_GENERATION_SEQUENTIAL.value, json_=body)
    return self._read_challenge(response)

analyse_challenge_response

analyse_challenge_response(
    token, annotations, anchor_image, target_video
)

Analyse the recording of a challenge against the photo of the expected person.

One figure answers all of it: whether the recording is genuine, whether it performs the challenge that was issued, and whether it is the right person.

Unlike every other endpoint here, this one reports what went wrong inside a successful response. A confidence of None means the analysis could not be completed, and the errors of the result say why.

Parameters:

Name Type Description Default
token str

The token from generate_sequential_challenge, unchanged

required
annotations str | bytes

The SDK's WebVTT annotations, as a path or as bytes. A str is read as a path, so pass in-memory text as text.encode()

required
anchor_image str | bytes

The photo of the expected person, as a path or as bytes

required
target_video str | bytes

The recording of the challenge, as a path or as bytes

required

Returns:

Name Type Description
ChallengeAnalysisOutput ChallengeAnalysisOutput

The confidence, or None with the errors behind it

Raises:

Type Description
ExpiredOrInvalidChallengeError

If the challenge is no longer valid

FormValidationError

If the token, the annotations or a media file cannot be read

Source code in src/vericlient/dasface/client.py
@legacy_model_argument(ChallengeAnalysisInput)
def analyse_challenge_response(
    self,
    token: str,
    annotations: str | bytes,
    anchor_image: str | bytes,
    target_video: str | bytes,
) -> ChallengeAnalysisOutput:
    """Analyse the recording of a challenge against the photo of the expected person.

    One figure answers all of it: whether the recording is genuine, whether it performs
    the challenge that was issued, and whether it is the right person.

    Unlike every other endpoint here, this one reports what went wrong inside a
    successful response. A confidence of `None` means the analysis could not be
    completed, and the `errors` of the result say why.

    Args:
        token: The token from `generate_sequential_challenge`, unchanged
        annotations: The SDK's WebVTT annotations, as a path or as bytes. A `str` is read
            as a path, so pass in-memory text as `text.encode()`
        anchor_image: The photo of the expected person, as a path or as bytes
        target_video: The recording of the challenge, as a path or as bytes

    Returns:
        ChallengeAnalysisOutput: The confidence, or `None` with the errors behind it

    Raises:
        ExpiredOrInvalidChallengeError: If the challenge is no longer valid
        FormValidationError: If the token, the annotations or a media file cannot be read

    """
    data_model = ChallengeAnalysisInput(
        token=token,
        annotations=annotations,
        anchor_image=anchor_image,
        target_video=target_video,
    )
    response = self._post(
        endpoint=DasfaceEndpoints.CHALLENGES_ANALYSIS_VIDEO_PHOTO.value,
        json_={
            "token": data_model.token,
            "annotations": encode_base64(data_model.annotations),
            "anchorImage": encode_base64(data_model.anchor_image),
            "targetVideo": encode_base64(data_model.target_video),
        },
    )
    payload = response.json()
    return ChallengeAnalysisOutput(
        confidence=payload.get("confidence"),
        errors=[ChallengeError(code=code, message=message) for code, message in payload.get("errors") or []],
    )

vericlient.dasface.models

Module to define the models for the das-Face API.

Note the naming: das-Face fields are camelCase on the wire, where das-Peak and VCSP use snake_case. The models use Python names and alias them, so callers write anchor_image and the service receives anchorImage.

BiometricsModel

Bases: BaseModel

One biometrics model the service offers.

Attributes:

Name Type Description
hash str

The hash that identifies the model

mode str

The mode it runs in, such as default-mode or document-mode

tag str

Its release tag

methods list[str]

The biometric methods it implements

length int

The length of the credentials it produces

Source code in src/vericlient/dasface/models.py
class BiometricsModel(BaseModel):
    """One biometrics model the service offers.

    Attributes:
        hash: The hash that identifies the model
        mode: The mode it runs in, such as `default-mode` or `document-mode`
        tag: Its release tag
        methods: The biometric methods it implements
        length: The length of the credentials it produces

    """

    hash: str
    mode: str
    tag: str
    methods: list[str]
    length: int

ModelsOutput

Bases: BaseModel

Output class for the models endpoint.

Attributes:

Name Type Description
models list[BiometricsModel]

Every model the service offers, one entry per hash and mode

Source code in src/vericlient/dasface/models.py
class ModelsOutput(BaseModel):
    """Output class for the models endpoint.

    Attributes:
        models: Every model the service offers, one entry per hash and mode

    """

    models: list[BiometricsModel]

ModelMetadata

Bases: BaseModel

Metadata identifying the model a credential was generated with.

Attributes:

Name Type Description
hash str

The hash of the model

mode str

The mode it ran in

tag str | None

Its release tag, when the service reports one

Source code in src/vericlient/dasface/models.py
class ModelMetadata(BaseModel):
    """Metadata identifying the model a credential was generated with.

    Attributes:
        hash: The hash of the model
        mode: The mode it ran in
        tag: Its release tag, when the service reports one

    """

    hash: str
    mode: str
    tag: str | None = None

GenerateCredentialInput

Bases: BaseModel

Input class for generating a credential from a photo.

The model is part of the credential: two credentials only compare if they were generated with the same one. The service does not pick a model on its own, so hash and mode are required. Take them from get_models().

The only exception is the INE Mexico variant, which does have a default-model form: with inemex set, leaving hash and mode out uses it.

Attributes:

Name Type Description
image Media

The photo, as a path or as bytes

hash str | None

The hash of the model to use, from get_models()

mode str | None

The mode to use, from get_models()

inemex bool

Use the INE Mexico variant of the endpoint. It needs a specific agreement with Veridas

Source code in src/vericlient/dasface/models.py
class GenerateCredentialInput(BaseModel):
    """Input class for generating a credential from a photo.

    The model is part of the credential: two credentials only compare if they were
    generated with the same one. The service does not pick a model on its own, so `hash`
    and `mode` are required. Take them from `get_models()`.

    The only exception is the INE Mexico variant, which does have a default-model form:
    with `inemex` set, leaving `hash` and `mode` out uses it.

    Attributes:
        image: The photo, as a path or as bytes
        hash: The hash of the model to use, from `get_models()`
        mode: The mode to use, from `get_models()`
        inemex: Use the INE Mexico variant of the endpoint. It needs a specific agreement
            with Veridas

    """

    model_config = ConfigDict(arbitrary_types_allowed=True, title="generate_credential()")

    image: Media
    hash: str | None = None
    mode: str | None = None
    inemex: bool = False

    @model_validator(mode="after")
    def model_must_be_named_in_full(self) -> "GenerateCredentialInput":
        """Require hash and mode together, and require them at all outside INE Mexico.

        A model key is the pair, so half of it is always an error. Only the INE Mexico
        endpoint has a default-model form, so everywhere else the pair is mandatory:
        there is no endpoint that lets the service choose.

        A model validator rather than a field one, because pydantic does not run field
        validators over a field left at its default, which is exactly the case being caught.
        """
        if bool(self.hash) != bool(self.mode):
            error = "hash and mode go together: give both or neither"
            raise ValueError(error)
        if not self.inemex and not self.hash:
            error = "hash and mode are required: take them from get_models()"
            raise ValueError(error)
        return self

model_must_be_named_in_full

model_must_be_named_in_full()

Require hash and mode together, and require them at all outside INE Mexico.

A model key is the pair, so half of it is always an error. Only the INE Mexico endpoint has a default-model form, so everywhere else the pair is mandatory: there is no endpoint that lets the service choose.

A model validator rather than a field one, because pydantic does not run field validators over a field left at its default, which is exactly the case being caught.

Source code in src/vericlient/dasface/models.py
@model_validator(mode="after")
def model_must_be_named_in_full(self) -> "GenerateCredentialInput":
    """Require hash and mode together, and require them at all outside INE Mexico.

    A model key is the pair, so half of it is always an error. Only the INE Mexico
    endpoint has a default-model form, so everywhere else the pair is mandatory:
    there is no endpoint that lets the service choose.

    A model validator rather than a field one, because pydantic does not run field
    validators over a field left at its default, which is exactly the case being caught.
    """
    if bool(self.hash) != bool(self.mode):
        error = "hash and mode go together: give both or neither"
        raise ValueError(error)
    if not self.inemex and not self.hash:
        error = "hash and mode are required: take them from get_models()"
        raise ValueError(error)
    return self

GenerateCredentialOutput

Bases: BaseModel

Output class for generating a credential from a photo.

Attributes:

Name Type Description
credential str

The biometric representation of the face

model ModelMetadata

The model it was generated with

Source code in src/vericlient/dasface/models.py
class GenerateCredentialOutput(BaseModel):
    """Output class for generating a credential from a photo.

    Attributes:
        credential: The biometric representation of the face
        model: The model it was generated with

    """

    credential: str
    model: ModelMetadata

GetModelMetadataFromCredentialInput

Bases: BaseModel

Input class for reading which model produced a credential.

Attributes:

Name Type Description
credential str

The credential to inspect

Source code in src/vericlient/dasface/models.py
class GetModelMetadataFromCredentialInput(BaseModel):
    """Input class for reading which model produced a credential.

    Attributes:
        credential: The credential to inspect

    """

    model_config = ConfigDict(title="get_model_metadata_from_credential()")

    credential: str

GetModelMetadataFromCredentialOutput

Bases: BaseModel

Output class for reading which model produced a credential.

Attributes:

Name Type Description
metadata ModelMetadata

The model the credential was generated with

Source code in src/vericlient/dasface/models.py
class GetModelMetadataFromCredentialOutput(BaseModel):
    """Output class for reading which model produced a credential.

    Attributes:
        metadata: The model the credential was generated with

    """

    metadata: ModelMetadata

VerifyPhotoInput

Bases: BaseModel

Input class for comparing two photos.

Attributes:

Name Type Description
anchor_image Media

The reference photo, as a path or as bytes

target_image Media

The photo to evaluate, as a path or as bytes

mode str | None

The model mode to use, such as document-mode. The service picks its default when omitted

Source code in src/vericlient/dasface/models.py
class VerifyPhotoInput(BaseModel):
    """Input class for comparing two photos.

    Attributes:
        anchor_image: The reference photo, as a path or as bytes
        target_image: The photo to evaluate, as a path or as bytes
        mode: The model mode to use, such as `document-mode`. The service picks its default
            when omitted

    """

    model_config = ConfigDict(arbitrary_types_allowed=True, title="verify_photo()")

    anchor_image: Media
    target_image: Media
    mode: str | None = None

VerifyVideoInput

Bases: BaseModel

Input class for comparing a photo against a video.

Attributes:

Name Type Description
anchor_image Media

The reference photo, as a path or as bytes

target_video Media

The video to evaluate, as a path or as bytes

Source code in src/vericlient/dasface/models.py
class VerifyVideoInput(BaseModel):
    """Input class for comparing a photo against a video.

    Attributes:
        anchor_image: The reference photo, as a path or as bytes
        target_video: The video to evaluate, as a path or as bytes

    """

    model_config = ConfigDict(arbitrary_types_allowed=True, title="verify_video()")

    anchor_image: Media
    target_video: Media

VerifyCredentialInput

Bases: BaseModel

Input class for comparing a photo against a stored credential.

Attributes:

Name Type Description
anchor_image Media

The photo, as a path or as bytes

target_credential str

The credential to compare it with

Source code in src/vericlient/dasface/models.py
class VerifyCredentialInput(BaseModel):
    """Input class for comparing a photo against a stored credential.

    Attributes:
        anchor_image: The photo, as a path or as bytes
        target_credential: The credential to compare it with

    """

    model_config = ConfigDict(arbitrary_types_allowed=True, title="verify_credential()")

    anchor_image: Media
    target_credential: str

VerificationOutput

Bases: BaseModel

Output class for a verification.

Attributes:

Name Type Description
confidence float

How confident the service is that both faces belong to the same person, from 0 to 1

Source code in src/vericlient/dasface/models.py
class VerificationOutput(BaseModel):
    """Output class for a verification.

    Attributes:
        confidence: How confident the service is that both faces belong to the same person,
            from 0 to 1

    """

    confidence: float

PhotoAuthenticityInput

Bases: BaseModel

Input class for checking whether a selfie is a genuine capture.

Attributes:

Name Type Description
image Media

The selfie to analyse, as a path or as bytes

Source code in src/vericlient/dasface/models.py
class PhotoAuthenticityInput(BaseModel):
    """Input class for checking whether a selfie is a genuine capture.

    Attributes:
        image: The selfie to analyse, as a path or as bytes

    """

    model_config = ConfigDict(arbitrary_types_allowed=True, title="check_photo_authenticity()")

    image: Media

PhotoAuthenticityOutput

Bases: BaseModel

Output class for a photo authenticity check.

Attributes:

Name Type Description
confidence float

How confident the service is that the photo is a genuine capture rather than a photo of a screen or a print, from 0 to 1

Source code in src/vericlient/dasface/models.py
class PhotoAuthenticityOutput(BaseModel):
    """Output class for a photo authenticity check.

    Attributes:
        confidence: How confident the service is that the photo is a genuine capture rather
            than a photo of a screen or a print, from 0 to 1

    """

    confidence: float

VideoAuthenticityInput

Bases: BaseModel

Input class for checking a video's authenticity and who is in it.

Attributes:

Name Type Description
anchor_image Media

The photo of the person the video should show, as a path or as bytes

target_video Media

The video to analyse, as a path or as bytes

Source code in src/vericlient/dasface/models.py
class VideoAuthenticityInput(BaseModel):
    """Input class for checking a video's authenticity and who is in it.

    Attributes:
        anchor_image: The photo of the person the video should show, as a path or as bytes
        target_video: The video to analyse, as a path or as bytes

    """

    model_config = ConfigDict(arbitrary_types_allowed=True, title="check_video_authenticity()")

    anchor_image: Media
    target_video: Media

VideoAuthenticityOutput

Bases: BaseModel

Output class for a video authenticity check.

Both figures matter, and they answer different questions: a genuine recording of the wrong person scores high on one and low on the other.

Attributes:

Name Type Description
authenticity float

How confident the service is that the video is a genuine recording

similarity float

How closely the face in the video matches the anchor photo

Source code in src/vericlient/dasface/models.py
class VideoAuthenticityOutput(BaseModel):
    """Output class for a video authenticity check.

    Both figures matter, and they answer different questions: a genuine recording of the
    wrong person scores high on one and low on the other.

    Attributes:
        authenticity: How confident the service is that the video is a genuine recording
        similarity: How closely the face in the video matches the anchor photo

    """

    authenticity: float
    similarity: float

SequentialChallengeInput

Bases: BaseModel

Input class for requesting a sequential liveness challenge.

Attributes:

Name Type Description
length int | None

How many actions the challenge asks for, from 1 to 6. The service defaults to 2, which it describes as standard security, and 6 as high security

expiration int | None

How long the challenge stays valid, in seconds, from 300 to 1800. The service defaults to 1800

Source code in src/vericlient/dasface/models.py
class SequentialChallengeInput(BaseModel):
    """Input class for requesting a sequential liveness challenge.

    Attributes:
        length: How many actions the challenge asks for, from 1 to 6. The service defaults
            to 2, which it describes as standard security, and 6 as high security
        expiration: How long the challenge stays valid, in seconds, from 300 to 1800. The
            service defaults to 1800

    """

    model_config = ConfigDict(title="generate_sequential_challenge()")

    length: int | None = None
    expiration: int | None = None

ChallengeAction

Bases: BaseModel

One action the subject is asked to perform.

Attributes:

Name Type Description
name str

The name the annotations refer to this action by, such as action-0

action_class str

What kind of action it is, such as move-head-and-back. Named this way because class is a Python keyword; the token itself calls it class

parameters dict

The details of the action, such as {"direction": "right"}

Source code in src/vericlient/dasface/models.py
class ChallengeAction(BaseModel):
    """One action the subject is asked to perform.

    Attributes:
        name: The name the annotations refer to this action by, such as `action-0`
        action_class: What kind of action it is, such as `move-head-and-back`. Named this way
            because `class` is a Python keyword; the token itself calls it `class`
        parameters: The details of the action, such as `{"direction": "right"}`

    """

    name: str
    action_class: str
    parameters: dict

SequentialChallengeOutput

Bases: BaseModel

Output class for a sequential liveness challenge.

The service answers with a signed token rather than JSON. Pass token on unchanged: the capture SDK needs it, and so does analyse_challenge_response. The rest of the fields are read from inside it, because a caller has to know which actions to prompt for.

Attributes:

Name Type Description
token str

The JWS token, exactly as the service returned it

id str

The identifier of this challenge

timestamp datetime

When the challenge was issued

expires datetime

When it stops being accepted

actions list[ChallengeAction]

The actions to perform, in order

Source code in src/vericlient/dasface/models.py
class SequentialChallengeOutput(BaseModel):
    """Output class for a sequential liveness challenge.

    The service answers with a signed token rather than JSON. Pass `token` on unchanged: the
    capture SDK needs it, and so does `analyse_challenge_response`. The rest of the fields
    are read from inside it, because a caller has to know which actions to prompt for.

    Attributes:
        token: The JWS token, exactly as the service returned it
        id: The identifier of this challenge
        timestamp: When the challenge was issued
        expires: When it stops being accepted
        actions: The actions to perform, in order

    """

    token: str
    id: str
    timestamp: datetime
    expires: datetime
    actions: list[ChallengeAction]

ChallengeAnalysisInput

Bases: BaseModel

Input class for analysing the recording of a challenge.

Attributes:

Name Type Description
token str

The token from generate_sequential_challenge, unchanged

annotations Media

The SDK's WebVTT annotations of the recording, as a path or as bytes. A str is read as a path, so pass in-memory text as text.encode()

anchor_image Media

The photo of the person the recording should show, as a path or as bytes

target_video Media

The recording of the challenge, as a path or as bytes

Source code in src/vericlient/dasface/models.py
class ChallengeAnalysisInput(BaseModel):
    """Input class for analysing the recording of a challenge.

    Attributes:
        token: The token from `generate_sequential_challenge`, unchanged
        annotations: The SDK's WebVTT annotations of the recording, as a path or as bytes.
            A `str` is read as a path, so pass in-memory text as `text.encode()`
        anchor_image: The photo of the person the recording should show, as a path or as bytes
        target_video: The recording of the challenge, as a path or as bytes

    """

    model_config = ConfigDict(arbitrary_types_allowed=True, title="analyse_challenge_response()")

    token: str
    annotations: Media
    anchor_image: Media
    target_video: Media

ChallengeError

Bases: BaseModel

One reason the analysis could not produce a confidence.

Attributes:

Name Type Description
code str

The error code, such as FaceTooSmallForIAS

message str

What the service said about it

Source code in src/vericlient/dasface/models.py
class ChallengeError(BaseModel):
    """One reason the analysis could not produce a confidence.

    Attributes:
        code: The error code, such as `FaceTooSmallForIAS`
        message: What the service said about it

    """

    code: str
    message: str

ChallengeAnalysisOutput

Bases: BaseModel

Output class for the analysis of a challenge recording.

This endpoint reports its failures in a successful response rather than as an error status, which no other das-Face endpoint does. A confidence of None means the analysis could not be completed and errors says why — a face too small to analyse comes back here, where every other endpoint raises.

Attributes:

Name Type Description
confidence float | None

How confident the service is that the recording is a genuine response to the challenge by the person in the anchor photo, from 0 to 1, or None if it could not tell

errors list[ChallengeError]

What went wrong, empty when nothing did

Source code in src/vericlient/dasface/models.py
class ChallengeAnalysisOutput(BaseModel):
    """Output class for the analysis of a challenge recording.

    This endpoint reports its failures in a successful response rather than as an error
    status, which no other das-Face endpoint does. A `confidence` of `None` means the
    analysis could not be completed and `errors` says why — a face too small to analyse
    comes back here, where every other endpoint raises.

    Attributes:
        confidence: How confident the service is that the recording is a genuine response to
            the challenge by the person in the anchor photo, from 0 to 1, or `None` if it
            could not tell
        errors: What went wrong, empty when nothing did

    """

    confidence: float | None
    errors: list[ChallengeError]

vericlient.dasface.exceptions

Module to define the exceptions for the das-Face API.

das-Face reports failures differently from the other services: its error bodies carry {code, message, status}, where das-Peak uses {error, exception} and VCSP uses {error, title, reason}.

The v3.35 specification enumerates these codes properly, which v3.26 did not. Three of the codes below are not in it: UnknownHashAndModeError and PathNotFoundError, both found against work/eu, and ExpiredOrInvalidChallengeError, which v3.26 documents for the challenge endpoints that v3.35 dropped.

DasfaceError

Bases: VeriClientError

Base class for exceptions in the das-Face API.

Source code in src/vericlient/dasface/exceptions.py
class DasfaceError(VeriClientError):
    """Base class for exceptions in the das-Face API."""

    def __init__(self, message: str) -> None:
        super().__init__(message)

FaceNotFoundError

Bases: DasfaceError

Exception raised when no face could be located in the image.

Source code in src/vericlient/dasface/exceptions.py
class FaceNotFoundError(DasfaceError):
    """Exception raised when no face could be located in the image."""

    def __init__(self) -> None:
        message = "No face was found in the image."
        super().__init__(message)

MoreThanOneFaceError

Bases: DasfaceError

Exception raised when the image holds more than one face.

Source code in src/vericlient/dasface/exceptions.py
class MoreThanOneFaceError(DasfaceError):
    """Exception raised when the image holds more than one face."""

    def __init__(self) -> None:
        message = "More than one face was found in the image; it has to hold exactly one."
        super().__init__(message)

FaceAlignmentError

Bases: DasfaceError

Exception raised when the face's key points could not be located.

Source code in src/vericlient/dasface/exceptions.py
class FaceAlignmentError(DasfaceError):
    """Exception raised when the face's key points could not be located."""

    def __init__(self) -> None:
        message = "The face was found but its key points could not be located, so it cannot be analysed."
        super().__init__(message)

ObsoleteCredentialModelError

Bases: DasfaceError

Exception raised when a credential was generated with a model the service has dropped.

Worth catching on its own: it means the credential has to be regenerated from the original photo, not that the request was wrong.

Source code in src/vericlient/dasface/exceptions.py
class ObsoleteCredentialModelError(DasfaceError):
    """Exception raised when a credential was generated with a model the service has dropped.

    Worth catching on its own: it means the credential has to be regenerated from the
    original photo, not that the request was wrong.
    """

    def __init__(self) -> None:
        message = (
            "The credential was generated with a model the service no longer offers. Generate a new one from the original photo."
        )
        super().__init__(message)

IncompatibleCredentialsError

Bases: DasfaceError

Exception raised when two credentials cannot be compared with each other.

Credentials are only comparable when they come from the same model and mode.

Source code in src/vericlient/dasface/exceptions.py
class IncompatibleCredentialsError(DasfaceError):
    """Exception raised when two credentials cannot be compared with each other.

    Credentials are only comparable when they come from the same model and mode.
    """

    def __init__(self) -> None:
        message = "The credentials were generated with different models, so they cannot be compared."
        super().__init__(message)

ZeroLengthVideoError

Bases: DasfaceError

Exception raised when the video is empty or was corrupted in transit.

Source code in src/vericlient/dasface/exceptions.py
class ZeroLengthVideoError(DasfaceError):
    """Exception raised when the video is empty or was corrupted in transit."""

    def __init__(self) -> None:
        message = "The video is empty or was corrupted in transit."
        super().__init__(message)

NotEnoughVideoDataError

Bases: DasfaceError

Exception raised when the video holds too few usable frames to analyse.

Source code in src/vericlient/dasface/exceptions.py
class NotEnoughVideoDataError(DasfaceError):
    """Exception raised when the video holds too few usable frames to analyse."""

    def __init__(self) -> None:
        message = "The video does not hold enough usable frames to analyse."
        super().__init__(message)

VideoExtractionError

Bases: DasfaceError

Exception raised when the video could not be decoded.

Source code in src/vericlient/dasface/exceptions.py
class VideoExtractionError(DasfaceError):
    """Exception raised when the video could not be decoded."""

    def __init__(self) -> None:
        message = "The video could not be decoded. Check its container and codec."
        super().__init__(message)

InvalidVideoMetadataError

Bases: DasfaceError

Exception raised when the video's frame rate or frame count are not usable.

das-Face reports these as two separate codes, InvalidFPSVideoError and InvalidNumFramesVideoError; both mean the same thing to a caller.

Source code in src/vericlient/dasface/exceptions.py
class InvalidVideoMetadataError(DasfaceError):
    """Exception raised when the video's frame rate or frame count are not usable.

    das-Face reports these as two separate codes, `InvalidFPSVideoError` and
    `InvalidNumFramesVideoError`; both mean the same thing to a caller.
    """

    def __init__(self) -> None:
        message = "The video's frame rate or frame count is not valid."
        super().__init__(message)

FaceTooSmallForIasError

Bases: DasfaceError

Exception raised when the face is too small for the authenticity analysis.

Source code in src/vericlient/dasface/exceptions.py
class FaceTooSmallForIasError(DasfaceError):
    """Exception raised when the face is too small for the authenticity analysis."""

    def __init__(self) -> None:
        message = (
            "The face is too small for the authenticity analysis. Its bounding box has to be "
            "wider; a larger photo, or one where the face fills more of the frame, will pass."
        )
        super().__init__(message)

FormValidationError

Bases: DasfaceError

Exception raised when the request body is not what the endpoint expects.

das-Face uses one code for every malformed input: an image that is not decodable, a string that is not valid base64, a credential that is not a credential, and a missing required field all arrive as this.

The service splits the explanation in two. Its message names the form it was validating — Incorrect parameters in GenerateSequentialChallengeForm — and its errors name the field and what is wrong with it. Only the second half is any use, so both are reported and errors is kept for a caller that wants to act on a specific field.

Attributes:

Name Type Description
errors

The (field, reason) pairs the service listed, empty if it listed none

Source code in src/vericlient/dasface/exceptions.py
class FormValidationError(DasfaceError):
    """Exception raised when the request body is not what the endpoint expects.

    das-Face uses one code for every malformed input: an image that is not decodable, a
    string that is not valid base64, a credential that is not a credential, and a missing
    required field all arrive as this.

    The service splits the explanation in two. Its `message` names the form it was validating
    — `Incorrect parameters in GenerateSequentialChallengeForm` — and its `errors` name the
    field and what is wrong with it. Only the second half is any use, so both are reported
    and `errors` is kept for a caller that wants to act on a specific field.

    Attributes:
        errors: The `(field, reason)` pairs the service listed, empty if it listed none

    """

    def __init__(self, message: str | None = None, errors: list[tuple[str, str]] | None = None) -> None:
        self.errors = errors or []
        fields = "; ".join(f"{field}: {reason}" for field, reason in self.errors)
        detail = ": " + " — ".join(part for part in (message, fields) if part) if message or fields else "."
        super().__init__(f"The request was rejected as invalid{detail}")

UnknownHashAndModeError

Bases: DasfaceError

Exception raised when no biometrics model matches the given hash and mode.

Source code in src/vericlient/dasface/exceptions.py
class UnknownHashAndModeError(DasfaceError):
    """Exception raised when no biometrics model matches the given hash and mode."""

    def __init__(self) -> None:
        message = "No biometrics model matches that hash and mode. Use get_models() to list them."
        super().__init__(message)

PathNotFoundError

Bases: DasfaceError

Exception raised when the endpoint is not available on the target deployment.

Some endpoints in the specification are not enabled everywhere. On the EU sandbox, authenticity/photo/unequal-pair answers with this.

Source code in src/vericlient/dasface/exceptions.py
class PathNotFoundError(DasfaceError):
    """Exception raised when the endpoint is not available on the target deployment.

    Some endpoints in the specification are not enabled everywhere. On the EU sandbox,
    `authenticity/photo/unequal-pair` answers with this.
    """

    def __init__(self) -> None:
        message = "The service does not expose that endpoint. It may not be enabled for this deployment."
        super().__init__(message)

DasfaceApiError

Bases: DasfaceError

Exception raised for a failure das-Face reports with a code this client does not map.

The specification documents only status codes, so the set of codes is discovered by provoking them. Rather than swallow an unrecognised one into a generic server error, it is surfaced with the code and message the service gave, which is what an integrator needs to report it.

Source code in src/vericlient/dasface/exceptions.py
class DasfaceApiError(DasfaceError):
    """Exception raised for a failure das-Face reports with a code this client does not map.

    The specification documents only status codes, so the set of codes is discovered by
    provoking them. Rather than swallow an unrecognised one into a generic server error, it
    is surfaced with the code and message the service gave, which is what an integrator needs
    to report it.
    """

    def __init__(self, code: str, message: str | None = None) -> None:
        detail = f": {message}" if message else ""
        super().__init__(f"The service reported {code}{detail}")
        self.code = code

ExpiredOrInvalidChallengeError

Bases: DasfaceError

Exception raised when a challenge token is no longer accepted.

A challenge is valid for as long as its expiration said, 1800 seconds by default. Past that the recording cannot be analysed and a fresh challenge has to be generated.

Source code in src/vericlient/dasface/exceptions.py
class ExpiredOrInvalidChallengeError(DasfaceError):
    """Exception raised when a challenge token is no longer accepted.

    A challenge is valid for as long as its `expiration` said, 1800 seconds by default. Past
    that the recording cannot be analysed and a fresh challenge has to be generated.
    """

    def __init__(self) -> None:
        message = "The challenge has expired or is not valid. Generate a new one."
        super().__init__(message)