Skip to content

das-Peak

vericlient.daspeak.client.DaspeakClient

Bases: Client

Class to interact with the Daspeak API.

Source code in src/vericlient/daspeak/client.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
class DaspeakClient(Client):
    """Class to interact with the Daspeak API."""

    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 DaspeakClient 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

        """
        api = APIs.DASPEAK
        super().__init__(
            api=api,
            apikey=apikey,
            timeout=timeout,
            environment=environment,
            location=location,
            url=url,
            headers=headers,
        )
        self._exceptions = [
            "AudioInputException",
            "SignalNoiseRatioException",
            "VoiceDurationIsNotEnoughException",
            "InvalidChannelException",
            "InsufficientQuality",
            "CalibrationNotAvailable",
            "ServerError",
            "InvalidCredential",
            "UnsupportedMediaType",
            "ModelNotAvailable",
        ]
        # Only `compare()` reads this, and `compare()` is deprecated: each of these has a
        # method of its own now.
        self._compare_functions_map = {
            CompareCredential2AudioInput: self.compare_credential_to_audio,
            CompareAudio2AudioInput: self.compare_audio_to_audio,
            CompareCredential2CredentialInput: self.compare_credential_to_credential,
            CompareAudio2CredentialsInput: self.identify_audio,
            CompareCredential2CredentialsInput: self.identify_credential,
        }
        self._exception_map = {
            "SignalNoiseRatioException": SignalNoiseRatioError,
            "VoiceDurationIsNotEnoughException": self._handle_voice_duration_error,
            "InvalidChannelException": InvalidSpecifiedChannelError,
            "InsufficientQuality": InsufficientQualityError,
            "CalibrationNotAvailable": self._handle_calibration_error,
            "InvalidCredential": InvalidCredentialError,
            "UnsupportedMediaType": UnsupportedMediaTypeError,
            "ModelNotAvailable": self._handle_model_not_available_error,
        }
        self._audio_input_errors = {
            "more channels than": TooManyAudioChannelsError,
            "unsupported codec": UnsupportedAudioCodecError,
            "sample rate": UnsupportedSampleRateError,
            "duration is longer": AudioDurationTooLongError,
        }

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

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

        """
        response = self._get(endpoint=DaspeakEndpoints.ALIVE.value)
        accepted_status_code = 200
        return response.status_code == accepted_status_code

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

        exception = response_json.get("exception")
        if not exception or exception not in self._exceptions:
            self._raise_server_error(response)

        if exception == "AudioInputException":
            error_message = response_json.get("error", "")
            for error_text, error_class in self._audio_input_errors.items():
                if error_text in error_message:
                    raise error_class
            raise ValueError(error_message)

        handler = self._exception_map.get(exception)
        if handler:
            if isinstance(handler, type) and issubclass(handler, VeriClientError):
                raise handler
            handler(response_json)

        raise ValueError(response_json.get("error", "Unknown error"))

    def _handle_voice_duration_error(self, response_json: dict) -> None:
        error_message = response_json.get("error", "")
        net_speech_detected = float(error_message.split(" ")[-3].replace("s", ""))
        raise NetSpeechDurationIsNotEnoughError(net_speech_detected)

    def _handle_model_not_available_error(self, response_json: dict) -> None:
        error_message = response_json.get("error", "")
        model_hash = error_message.rsplit(" ", 1)[-1]
        raise ModelNotAvailableError(model_hash)

    def _handle_calibration_error(self, response_json: dict) -> None:
        error_message = response_json.get("error", "")
        calibration = str(error_message.split(" ")[2])
        raise CalibrationNotAvailableError(calibration)

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

        Returns:
            The response from the service

        """
        response = self._get(endpoint=DaspeakEndpoints.MODELS.value)
        return ModelsOutput(**response.json())

    @legacy_model_argument(GetModelMetadataInput)
    def get_model_metadata(self, hash: str) -> GetModelMetadataOutput:  # noqa: A002
        """Get the metadata of a biometrics model.

        Args:
            hash: The hash of the model to describe

        Returns:
            The response from the service

        Raises:
            ModelNotAvailableError: If no model exists with that hash

        """
        data_model = GetModelMetadataInput(hash=hash)
        response = self._post(
            endpoint=DaspeakEndpoints.MODELS_METADATA.value,
            data={"hash": data_model.hash},
        )
        return GetModelMetadataOutput(**response.json())

    @legacy_model_argument(GetModelCalibrationsInput)
    def get_model_calibrations(self, hash: str) -> GetModelCalibrationsOutput:  # noqa: A002
        """Get the calibration modes a biometrics model supports.

        Any of the returned values is valid as the `calibration` argument of
        `generate_credential` and of the comparison inputs.

        Args:
            hash: The hash of the model to list the calibrations of

        Returns:
            The response from the service

        Raises:
            ModelNotAvailableError: If no model exists with that hash

        """
        data_model = GetModelCalibrationsInput(hash=hash)
        response = self._post(
            endpoint=DaspeakEndpoints.MODELS_CALIBRATION.value,
            data={"hash": data_model.hash},
        )
        return GetModelCalibrationsOutput(**response.json())

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

        Useful to find out whether a stored credential is still compatible with the models
        the service currently offers.

        Args:
            credential: The credential to read the originating model from

        Returns:
            The response from the service

        Raises:
            InvalidCredentialError: If the credential is not valid

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

    @legacy_model_argument(GenerateCredentialInput)
    def generate_credential(
        self,
        audio: str | bytes,
        hash: str,  # noqa: A002
        channel: int = 1,
        calibration: str = DEFAULT_CALIBRATION,
    ) -> GenerateCredentialOutput:
        """Generate a credential from a WAV file.

        Args:
            audio: The recording, as a path or as bytes
            hash: The hash of the biometrics model to use, from `get_models()`
            channel: Which channel to read, when the recording is stereo
            calibration: The calibration to use, from `get_model_calibrations()`

        Returns:
            The response from the service

        Raises:
            TooManyAudioChannelsError: If the audio has more channels than the service supports
            UnsupportedAudioCodecError: If the audio has an unsupported codec
            UnsupportedSampleRateError: If the audio has an unsupported sample rate
            AudioDurationTooLongError: If the audio duration is longer than the service supports
            SignalNoiseRatioError: If the signal-to-noise ratio is too low
            NetSpeechDurationIsNotEnoughError: If the net speech duration is not enough
            InvalidSpecifiedChannelError: If the specified channel is invalid
            InsufficientQualityError: If the audio quality is insufficient
            CalibrationNotAvailableError: If the calibration is not available
            UnsupportedMediaTypeError: If the media type is not supported

        """
        data_model = GenerateCredentialInput(audio=audio, hash=hash, channel=channel, calibration=calibration)
        endpoint = DaspeakEndpoints.MODELS_HASH_CREDENTIAL_AUDIO.value.replace("<hash>", data_model.hash)
        audio = get_virtual_file(data_model.audio)
        files = {
            "audio": ("audio", audio, "audio/wav"),
        }
        data = {
            "channel": data_model.channel,
            "calibration": data_model.calibration,
        }
        response = self._post(endpoint=endpoint, data=data, files=files)
        return GenerateCredentialOutput(**response.json())

    def compare(
        self,
        data_model: CompareInput,
    ) -> (
        CompareCredential2AudioOutput
        | CompareAudio2AudioOutput
        | CompareCredential2CredentialOutput
        | CompareAudio2CredentialsOutput
        | CompareCredential2CredentialsOutput
    ):
        """Compare two sets of data, dispatching on the type of the input model.

        Deprecated, and removed in 1.0.0. There are five comparisons behind this one method
        and the only way to pick between them was to pass one of five classes, so it could
        not be called at all without importing one. Each has a method of its own now:

        | This model | That method |
        |---|---|
        | `CompareCredential2AudioInput` | `compare_credential_to_audio` |
        | `CompareAudio2AudioInput` | `compare_audio_to_audio` |
        | `CompareCredential2CredentialInput` | `compare_credential_to_credential` |
        | `CompareAudio2CredentialsInput` | `identify_audio` |
        | `CompareCredential2CredentialsInput` | `identify_credential` |

        Args:
            data_model: One of the five comparison inputs

        Returns:
            The response from the service, of the kind matching the input

        Raises:
            TypeError: If `data_model` is not one of the five comparison inputs

        """
        method = self._compare_functions_map.get(type(data_model))
        if method is None:
            error = "data_model must be an instance of CompareInput"
            raise TypeError(error)

        warnings.warn(
            f"compare() is deprecated and will be removed in 1.0.0. Call {method.__name__}() instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return method(**dict(data_model))

    @legacy_model_argument(CompareCredential2AudioInput)
    def compare_credential_to_audio(
        self,
        credential_reference: str,
        audio_to_evaluate: str | bytes,
        channel: int = 1,
        calibration: str = DEFAULT_CALIBRATION,
    ) -> CompareCredential2AudioOutput:
        """Compare a stored credential against a recording.

        The everyday verification: enrol once into a credential, then check later recordings
        against it without keeping the original audio.

        Args:
            credential_reference: The stored credential
            audio_to_evaluate: The recording to check, as a path or as bytes
            channel: Which channel to read, when the recording is stereo
            calibration: The calibration to use, from `get_model_calibrations()`

        Returns:
            CompareCredential2AudioOutput: The score, and whether it passes

        Raises:
            InvalidCredentialError: If the credential is not valid
            NetSpeechDurationIsNotEnoughError: If the recording holds too little speech
            CalibrationNotAvailableError: If the calibration is not available

        """
        data_model = CompareCredential2AudioInput(
            credential_reference=credential_reference,
            audio_to_evaluate=audio_to_evaluate,
            channel=channel,
            calibration=calibration,
        )
        endpoint = DaspeakEndpoints.SIMILARITY_CREDENTIAL2AUDIO.value
        audio = get_virtual_file(data_model.audio_to_evaluate)
        files = {
            "audio_to_evaluate": ("audio", audio, "audio/wav"),
        }
        data = {
            "credential_reference": data_model.credential_reference,
            "channel": data_model.channel,
            "calibration": data_model.calibration,
        }
        response = self._post(endpoint=endpoint, data=data, files=files)
        return CompareCredential2AudioOutput(**response.json())

    @legacy_model_argument(CompareAudio2AudioInput)
    def compare_audio_to_audio(
        self,
        audio_reference: str | bytes,
        audio_to_evaluate: str | bytes,
        channel_reference: int = 1,
        channel_to_evaluate: int = 1,
        calibration: str = DEFAULT_CALIBRATION,
    ) -> CompareAudio2AudioOutput:
        """Compare two recordings directly, without generating a credential first.

        Args:
            audio_reference: The reference recording, as a path or as bytes
            audio_to_evaluate: The recording to check, as a path or as bytes
            channel_reference: Which channel of the reference to read
            channel_to_evaluate: Which channel of the recording to check
            calibration: The calibration to use, from `get_model_calibrations()`

        Returns:
            CompareAudio2AudioOutput: The score, and whether it passes

        Raises:
            NetSpeechDurationIsNotEnoughError: If either recording holds too little speech
            SignalNoiseRatioError: If either recording is too noisy
            CalibrationNotAvailableError: If the calibration is not available

        """
        data_model = CompareAudio2AudioInput(
            audio_reference=audio_reference,
            audio_to_evaluate=audio_to_evaluate,
            channel_reference=channel_reference,
            channel_to_evaluate=channel_to_evaluate,
            calibration=calibration,
        )
        endpoint = DaspeakEndpoints.SIMILARITY_AUDIO2AUDIO.value
        files = {
            "audio_reference": ("audio", get_virtual_file(data_model.audio_reference), "audio/wav"),
            "audio_to_evaluate": ("audio", get_virtual_file(data_model.audio_to_evaluate), "audio/wav"),
        }
        data = {
            "channel_reference": data_model.channel_reference,
            "channel_to_evaluate": data_model.channel_to_evaluate,
            "calibration": data_model.calibration,
        }
        response = self._post(endpoint=endpoint, data=data, files=files)
        return CompareAudio2AudioOutput(**response.json())

    @legacy_model_argument(CompareCredential2CredentialInput)
    def compare_credential_to_credential(
        self,
        credential_reference: str,
        credential_to_evaluate: str,
        calibration: str = DEFAULT_CALIBRATION,
    ) -> CompareCredential2CredentialOutput:
        """Compare two stored credentials.

        Args:
            credential_reference: The reference credential
            credential_to_evaluate: The credential to check against it
            calibration: The calibration to use, from `get_model_calibrations()`

        Returns:
            CompareCredential2CredentialOutput: The score, and whether it passes

        Raises:
            InvalidCredentialError: If either credential is not valid
            CalibrationNotAvailableError: If the calibration is not available

        """
        data_model = CompareCredential2CredentialInput(
            credential_reference=credential_reference,
            credential_to_evaluate=credential_to_evaluate,
            calibration=calibration,
        )
        endpoint = DaspeakEndpoints.SIMILARITY_CREDENTIAL2CREDENTIAL.value
        data = {
            "credential_reference": data_model.credential_reference,
            "credential_to_evaluate": data_model.credential_to_evaluate,
            "calibration": data_model.calibration,
        }
        response = self._post(endpoint=endpoint, data=data)
        return CompareCredential2CredentialOutput(**response.json())

    @legacy_model_argument(CompareAudio2CredentialsInput)
    def identify_audio(
        self,
        audio_to_evaluate: str | bytes,
        credential_list: list[tuple[str, str]],
        channel: int = 1,
        calibration: str = DEFAULT_CALIBRATION,
    ) -> CompareAudio2CredentialsOutput:
        """Find which of several credentials a recording belongs to.

        One against many, where the comparison methods are one against one.

        Args:
            audio_to_evaluate: The recording to identify, as a path or as bytes
            credential_list: The candidates, as `(identifier, credential)` pairs
            channel: Which channel to read, when the recording is stereo
            calibration: The calibration to use, from `get_model_calibrations()`

        Returns:
            CompareAudio2CredentialsOutput: A score per candidate

        Raises:
            InvalidCredentialError: If a credential is not valid
            NetSpeechDurationIsNotEnoughError: If the recording holds too little speech

        """
        data_model = CompareAudio2CredentialsInput(
            audio_to_evaluate=audio_to_evaluate,
            credential_list=credential_list,
            channel=channel,
            calibration=calibration,
        )
        endpoint = DaspeakEndpoints.IDENTIFICATION_AUDIO2CREDENTIALS.value
        files = {
            "audio_to_evaluate": ("audio", get_virtual_file(data_model.audio_to_evaluate), "audio/wav"),
        }
        data = {
            "credential_list": json.dumps(data_model.credential_list),
            "channel": data_model.channel,
            "calibration": data_model.calibration,
        }
        response = self._post(endpoint=endpoint, data=data, files=files)
        return CompareAudio2CredentialsOutput(**response.json())

    @legacy_model_argument(CompareCredential2CredentialsInput)
    def identify_credential(
        self,
        credential_to_evaluate: str,
        credential_list: list[tuple[str, str]],
        calibration: str = DEFAULT_CALIBRATION,
    ) -> CompareCredential2CredentialsOutput:
        """Find which of several credentials another credential belongs to.

        Args:
            credential_to_evaluate: The credential to identify
            credential_list: The candidates, as `(identifier, credential)` pairs
            calibration: The calibration to use, from `get_model_calibrations()`

        Returns:
            CompareCredential2CredentialsOutput: A score per candidate

        Raises:
            InvalidCredentialError: If a credential is not valid
            CalibrationNotAvailableError: If the calibration is not available

        """
        data_model = CompareCredential2CredentialsInput(
            credential_to_evaluate=credential_to_evaluate,
            credential_list=credential_list,
            calibration=calibration,
        )
        endpoint = DaspeakEndpoints.IDENTIFICATION_CREDENTIAL2CREDENTIALS.value
        data = {
            "credential_to_evaluate": data_model.credential_to_evaluate,
            "credential_list": json.dumps(data_model.credential_list),
            "calibration": data_model.calibration,
        }
        response = self._post(endpoint=endpoint, data=data)
        return CompareCredential2CredentialsOutput(**response.json())

alive

alive()

Check if the service is alive.

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

Source code in src/vericlient/daspeak/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=DaspeakEndpoints.ALIVE.value)
    accepted_status_code = 200
    return response.status_code == accepted_status_code

get_models

get_models()

Get the models available biometrics models in the service.

Returns:

Type Description
ModelsOutput

The response from the service

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

    Returns:
        The response from the service

    """
    response = self._get(endpoint=DaspeakEndpoints.MODELS.value)
    return ModelsOutput(**response.json())

get_model_metadata

get_model_metadata(hash)

Get the metadata of a biometrics model.

Parameters:

Name Type Description Default
hash str

The hash of the model to describe

required

Returns:

Type Description
GetModelMetadataOutput

The response from the service

Raises:

Type Description
ModelNotAvailableError

If no model exists with that hash

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(GetModelMetadataInput)
def get_model_metadata(self, hash: str) -> GetModelMetadataOutput:  # noqa: A002
    """Get the metadata of a biometrics model.

    Args:
        hash: The hash of the model to describe

    Returns:
        The response from the service

    Raises:
        ModelNotAvailableError: If no model exists with that hash

    """
    data_model = GetModelMetadataInput(hash=hash)
    response = self._post(
        endpoint=DaspeakEndpoints.MODELS_METADATA.value,
        data={"hash": data_model.hash},
    )
    return GetModelMetadataOutput(**response.json())

get_model_calibrations

get_model_calibrations(hash)

Get the calibration modes a biometrics model supports.

Any of the returned values is valid as the calibration argument of generate_credential and of the comparison inputs.

Parameters:

Name Type Description Default
hash str

The hash of the model to list the calibrations of

required

Returns:

Type Description
GetModelCalibrationsOutput

The response from the service

Raises:

Type Description
ModelNotAvailableError

If no model exists with that hash

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(GetModelCalibrationsInput)
def get_model_calibrations(self, hash: str) -> GetModelCalibrationsOutput:  # noqa: A002
    """Get the calibration modes a biometrics model supports.

    Any of the returned values is valid as the `calibration` argument of
    `generate_credential` and of the comparison inputs.

    Args:
        hash: The hash of the model to list the calibrations of

    Returns:
        The response from the service

    Raises:
        ModelNotAvailableError: If no model exists with that hash

    """
    data_model = GetModelCalibrationsInput(hash=hash)
    response = self._post(
        endpoint=DaspeakEndpoints.MODELS_CALIBRATION.value,
        data={"hash": data_model.hash},
    )
    return GetModelCalibrationsOutput(**response.json())

get_model_metadata_from_credential

get_model_metadata_from_credential(credential)

Get the metadata of the model a credential was generated with.

Useful to find out whether a stored credential is still compatible with the models the service currently offers.

Parameters:

Name Type Description Default
credential str

The credential to read the originating model from

required

Returns:

Type Description
GetModelMetadataFromCredentialOutput

The response from the service

Raises:

Type Description
InvalidCredentialError

If the credential is not valid

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

    Useful to find out whether a stored credential is still compatible with the models
    the service currently offers.

    Args:
        credential: The credential to read the originating model from

    Returns:
        The response from the service

    Raises:
        InvalidCredentialError: If the credential is not valid

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

generate_credential

generate_credential(
    audio, hash, channel=1, calibration=DEFAULT_CALIBRATION
)

Generate a credential from a WAV file.

Parameters:

Name Type Description Default
audio str | bytes

The recording, as a path or as bytes

required
hash str

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

required
channel int

Which channel to read, when the recording is stereo

1
calibration str

The calibration to use, from get_model_calibrations()

DEFAULT_CALIBRATION

Returns:

Type Description
GenerateCredentialOutput

The response from the service

Raises:

Type Description
TooManyAudioChannelsError

If the audio has more channels than the service supports

UnsupportedAudioCodecError

If the audio has an unsupported codec

UnsupportedSampleRateError

If the audio has an unsupported sample rate

AudioDurationTooLongError

If the audio duration is longer than the service supports

SignalNoiseRatioError

If the signal-to-noise ratio is too low

NetSpeechDurationIsNotEnoughError

If the net speech duration is not enough

InvalidSpecifiedChannelError

If the specified channel is invalid

InsufficientQualityError

If the audio quality is insufficient

CalibrationNotAvailableError

If the calibration is not available

UnsupportedMediaTypeError

If the media type is not supported

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(GenerateCredentialInput)
def generate_credential(
    self,
    audio: str | bytes,
    hash: str,  # noqa: A002
    channel: int = 1,
    calibration: str = DEFAULT_CALIBRATION,
) -> GenerateCredentialOutput:
    """Generate a credential from a WAV file.

    Args:
        audio: The recording, as a path or as bytes
        hash: The hash of the biometrics model to use, from `get_models()`
        channel: Which channel to read, when the recording is stereo
        calibration: The calibration to use, from `get_model_calibrations()`

    Returns:
        The response from the service

    Raises:
        TooManyAudioChannelsError: If the audio has more channels than the service supports
        UnsupportedAudioCodecError: If the audio has an unsupported codec
        UnsupportedSampleRateError: If the audio has an unsupported sample rate
        AudioDurationTooLongError: If the audio duration is longer than the service supports
        SignalNoiseRatioError: If the signal-to-noise ratio is too low
        NetSpeechDurationIsNotEnoughError: If the net speech duration is not enough
        InvalidSpecifiedChannelError: If the specified channel is invalid
        InsufficientQualityError: If the audio quality is insufficient
        CalibrationNotAvailableError: If the calibration is not available
        UnsupportedMediaTypeError: If the media type is not supported

    """
    data_model = GenerateCredentialInput(audio=audio, hash=hash, channel=channel, calibration=calibration)
    endpoint = DaspeakEndpoints.MODELS_HASH_CREDENTIAL_AUDIO.value.replace("<hash>", data_model.hash)
    audio = get_virtual_file(data_model.audio)
    files = {
        "audio": ("audio", audio, "audio/wav"),
    }
    data = {
        "channel": data_model.channel,
        "calibration": data_model.calibration,
    }
    response = self._post(endpoint=endpoint, data=data, files=files)
    return GenerateCredentialOutput(**response.json())

compare

compare(data_model)

Compare two sets of data, dispatching on the type of the input model.

Deprecated, and removed in 1.0.0. There are five comparisons behind this one method and the only way to pick between them was to pass one of five classes, so it could not be called at all without importing one. Each has a method of its own now:

This model That method
CompareCredential2AudioInput compare_credential_to_audio
CompareAudio2AudioInput compare_audio_to_audio
CompareCredential2CredentialInput compare_credential_to_credential
CompareAudio2CredentialsInput identify_audio
CompareCredential2CredentialsInput identify_credential

Parameters:

Name Type Description Default
data_model CompareInput

One of the five comparison inputs

required

Returns:

Type Description
CompareCredential2AudioOutput | CompareAudio2AudioOutput | CompareCredential2CredentialOutput | CompareAudio2CredentialsOutput | CompareCredential2CredentialsOutput

The response from the service, of the kind matching the input

Raises:

Type Description
TypeError

If data_model is not one of the five comparison inputs

Source code in src/vericlient/daspeak/client.py
def compare(
    self,
    data_model: CompareInput,
) -> (
    CompareCredential2AudioOutput
    | CompareAudio2AudioOutput
    | CompareCredential2CredentialOutput
    | CompareAudio2CredentialsOutput
    | CompareCredential2CredentialsOutput
):
    """Compare two sets of data, dispatching on the type of the input model.

    Deprecated, and removed in 1.0.0. There are five comparisons behind this one method
    and the only way to pick between them was to pass one of five classes, so it could
    not be called at all without importing one. Each has a method of its own now:

    | This model | That method |
    |---|---|
    | `CompareCredential2AudioInput` | `compare_credential_to_audio` |
    | `CompareAudio2AudioInput` | `compare_audio_to_audio` |
    | `CompareCredential2CredentialInput` | `compare_credential_to_credential` |
    | `CompareAudio2CredentialsInput` | `identify_audio` |
    | `CompareCredential2CredentialsInput` | `identify_credential` |

    Args:
        data_model: One of the five comparison inputs

    Returns:
        The response from the service, of the kind matching the input

    Raises:
        TypeError: If `data_model` is not one of the five comparison inputs

    """
    method = self._compare_functions_map.get(type(data_model))
    if method is None:
        error = "data_model must be an instance of CompareInput"
        raise TypeError(error)

    warnings.warn(
        f"compare() is deprecated and will be removed in 1.0.0. Call {method.__name__}() instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    return method(**dict(data_model))

compare_credential_to_audio

compare_credential_to_audio(
    credential_reference,
    audio_to_evaluate,
    channel=1,
    calibration=DEFAULT_CALIBRATION,
)

Compare a stored credential against a recording.

The everyday verification: enrol once into a credential, then check later recordings against it without keeping the original audio.

Parameters:

Name Type Description Default
credential_reference str

The stored credential

required
audio_to_evaluate str | bytes

The recording to check, as a path or as bytes

required
channel int

Which channel to read, when the recording is stereo

1
calibration str

The calibration to use, from get_model_calibrations()

DEFAULT_CALIBRATION

Returns:

Name Type Description
CompareCredential2AudioOutput CompareCredential2AudioOutput

The score, and whether it passes

Raises:

Type Description
InvalidCredentialError

If the credential is not valid

NetSpeechDurationIsNotEnoughError

If the recording holds too little speech

CalibrationNotAvailableError

If the calibration is not available

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(CompareCredential2AudioInput)
def compare_credential_to_audio(
    self,
    credential_reference: str,
    audio_to_evaluate: str | bytes,
    channel: int = 1,
    calibration: str = DEFAULT_CALIBRATION,
) -> CompareCredential2AudioOutput:
    """Compare a stored credential against a recording.

    The everyday verification: enrol once into a credential, then check later recordings
    against it without keeping the original audio.

    Args:
        credential_reference: The stored credential
        audio_to_evaluate: The recording to check, as a path or as bytes
        channel: Which channel to read, when the recording is stereo
        calibration: The calibration to use, from `get_model_calibrations()`

    Returns:
        CompareCredential2AudioOutput: The score, and whether it passes

    Raises:
        InvalidCredentialError: If the credential is not valid
        NetSpeechDurationIsNotEnoughError: If the recording holds too little speech
        CalibrationNotAvailableError: If the calibration is not available

    """
    data_model = CompareCredential2AudioInput(
        credential_reference=credential_reference,
        audio_to_evaluate=audio_to_evaluate,
        channel=channel,
        calibration=calibration,
    )
    endpoint = DaspeakEndpoints.SIMILARITY_CREDENTIAL2AUDIO.value
    audio = get_virtual_file(data_model.audio_to_evaluate)
    files = {
        "audio_to_evaluate": ("audio", audio, "audio/wav"),
    }
    data = {
        "credential_reference": data_model.credential_reference,
        "channel": data_model.channel,
        "calibration": data_model.calibration,
    }
    response = self._post(endpoint=endpoint, data=data, files=files)
    return CompareCredential2AudioOutput(**response.json())

compare_audio_to_audio

compare_audio_to_audio(
    audio_reference,
    audio_to_evaluate,
    channel_reference=1,
    channel_to_evaluate=1,
    calibration=DEFAULT_CALIBRATION,
)

Compare two recordings directly, without generating a credential first.

Parameters:

Name Type Description Default
audio_reference str | bytes

The reference recording, as a path or as bytes

required
audio_to_evaluate str | bytes

The recording to check, as a path or as bytes

required
channel_reference int

Which channel of the reference to read

1
channel_to_evaluate int

Which channel of the recording to check

1
calibration str

The calibration to use, from get_model_calibrations()

DEFAULT_CALIBRATION

Returns:

Name Type Description
CompareAudio2AudioOutput CompareAudio2AudioOutput

The score, and whether it passes

Raises:

Type Description
NetSpeechDurationIsNotEnoughError

If either recording holds too little speech

SignalNoiseRatioError

If either recording is too noisy

CalibrationNotAvailableError

If the calibration is not available

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(CompareAudio2AudioInput)
def compare_audio_to_audio(
    self,
    audio_reference: str | bytes,
    audio_to_evaluate: str | bytes,
    channel_reference: int = 1,
    channel_to_evaluate: int = 1,
    calibration: str = DEFAULT_CALIBRATION,
) -> CompareAudio2AudioOutput:
    """Compare two recordings directly, without generating a credential first.

    Args:
        audio_reference: The reference recording, as a path or as bytes
        audio_to_evaluate: The recording to check, as a path or as bytes
        channel_reference: Which channel of the reference to read
        channel_to_evaluate: Which channel of the recording to check
        calibration: The calibration to use, from `get_model_calibrations()`

    Returns:
        CompareAudio2AudioOutput: The score, and whether it passes

    Raises:
        NetSpeechDurationIsNotEnoughError: If either recording holds too little speech
        SignalNoiseRatioError: If either recording is too noisy
        CalibrationNotAvailableError: If the calibration is not available

    """
    data_model = CompareAudio2AudioInput(
        audio_reference=audio_reference,
        audio_to_evaluate=audio_to_evaluate,
        channel_reference=channel_reference,
        channel_to_evaluate=channel_to_evaluate,
        calibration=calibration,
    )
    endpoint = DaspeakEndpoints.SIMILARITY_AUDIO2AUDIO.value
    files = {
        "audio_reference": ("audio", get_virtual_file(data_model.audio_reference), "audio/wav"),
        "audio_to_evaluate": ("audio", get_virtual_file(data_model.audio_to_evaluate), "audio/wav"),
    }
    data = {
        "channel_reference": data_model.channel_reference,
        "channel_to_evaluate": data_model.channel_to_evaluate,
        "calibration": data_model.calibration,
    }
    response = self._post(endpoint=endpoint, data=data, files=files)
    return CompareAudio2AudioOutput(**response.json())

compare_credential_to_credential

compare_credential_to_credential(
    credential_reference,
    credential_to_evaluate,
    calibration=DEFAULT_CALIBRATION,
)

Compare two stored credentials.

Parameters:

Name Type Description Default
credential_reference str

The reference credential

required
credential_to_evaluate str

The credential to check against it

required
calibration str

The calibration to use, from get_model_calibrations()

DEFAULT_CALIBRATION

Returns:

Name Type Description
CompareCredential2CredentialOutput CompareCredential2CredentialOutput

The score, and whether it passes

Raises:

Type Description
InvalidCredentialError

If either credential is not valid

CalibrationNotAvailableError

If the calibration is not available

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(CompareCredential2CredentialInput)
def compare_credential_to_credential(
    self,
    credential_reference: str,
    credential_to_evaluate: str,
    calibration: str = DEFAULT_CALIBRATION,
) -> CompareCredential2CredentialOutput:
    """Compare two stored credentials.

    Args:
        credential_reference: The reference credential
        credential_to_evaluate: The credential to check against it
        calibration: The calibration to use, from `get_model_calibrations()`

    Returns:
        CompareCredential2CredentialOutput: The score, and whether it passes

    Raises:
        InvalidCredentialError: If either credential is not valid
        CalibrationNotAvailableError: If the calibration is not available

    """
    data_model = CompareCredential2CredentialInput(
        credential_reference=credential_reference,
        credential_to_evaluate=credential_to_evaluate,
        calibration=calibration,
    )
    endpoint = DaspeakEndpoints.SIMILARITY_CREDENTIAL2CREDENTIAL.value
    data = {
        "credential_reference": data_model.credential_reference,
        "credential_to_evaluate": data_model.credential_to_evaluate,
        "calibration": data_model.calibration,
    }
    response = self._post(endpoint=endpoint, data=data)
    return CompareCredential2CredentialOutput(**response.json())

identify_audio

identify_audio(
    audio_to_evaluate,
    credential_list,
    channel=1,
    calibration=DEFAULT_CALIBRATION,
)

Find which of several credentials a recording belongs to.

One against many, where the comparison methods are one against one.

Parameters:

Name Type Description Default
audio_to_evaluate str | bytes

The recording to identify, as a path or as bytes

required
credential_list list[tuple[str, str]]

The candidates, as (identifier, credential) pairs

required
channel int

Which channel to read, when the recording is stereo

1
calibration str

The calibration to use, from get_model_calibrations()

DEFAULT_CALIBRATION

Returns:

Name Type Description
CompareAudio2CredentialsOutput CompareAudio2CredentialsOutput

A score per candidate

Raises:

Type Description
InvalidCredentialError

If a credential is not valid

NetSpeechDurationIsNotEnoughError

If the recording holds too little speech

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(CompareAudio2CredentialsInput)
def identify_audio(
    self,
    audio_to_evaluate: str | bytes,
    credential_list: list[tuple[str, str]],
    channel: int = 1,
    calibration: str = DEFAULT_CALIBRATION,
) -> CompareAudio2CredentialsOutput:
    """Find which of several credentials a recording belongs to.

    One against many, where the comparison methods are one against one.

    Args:
        audio_to_evaluate: The recording to identify, as a path or as bytes
        credential_list: The candidates, as `(identifier, credential)` pairs
        channel: Which channel to read, when the recording is stereo
        calibration: The calibration to use, from `get_model_calibrations()`

    Returns:
        CompareAudio2CredentialsOutput: A score per candidate

    Raises:
        InvalidCredentialError: If a credential is not valid
        NetSpeechDurationIsNotEnoughError: If the recording holds too little speech

    """
    data_model = CompareAudio2CredentialsInput(
        audio_to_evaluate=audio_to_evaluate,
        credential_list=credential_list,
        channel=channel,
        calibration=calibration,
    )
    endpoint = DaspeakEndpoints.IDENTIFICATION_AUDIO2CREDENTIALS.value
    files = {
        "audio_to_evaluate": ("audio", get_virtual_file(data_model.audio_to_evaluate), "audio/wav"),
    }
    data = {
        "credential_list": json.dumps(data_model.credential_list),
        "channel": data_model.channel,
        "calibration": data_model.calibration,
    }
    response = self._post(endpoint=endpoint, data=data, files=files)
    return CompareAudio2CredentialsOutput(**response.json())

identify_credential

identify_credential(
    credential_to_evaluate,
    credential_list,
    calibration=DEFAULT_CALIBRATION,
)

Find which of several credentials another credential belongs to.

Parameters:

Name Type Description Default
credential_to_evaluate str

The credential to identify

required
credential_list list[tuple[str, str]]

The candidates, as (identifier, credential) pairs

required
calibration str

The calibration to use, from get_model_calibrations()

DEFAULT_CALIBRATION

Returns:

Name Type Description
CompareCredential2CredentialsOutput CompareCredential2CredentialsOutput

A score per candidate

Raises:

Type Description
InvalidCredentialError

If a credential is not valid

CalibrationNotAvailableError

If the calibration is not available

Source code in src/vericlient/daspeak/client.py
@legacy_model_argument(CompareCredential2CredentialsInput)
def identify_credential(
    self,
    credential_to_evaluate: str,
    credential_list: list[tuple[str, str]],
    calibration: str = DEFAULT_CALIBRATION,
) -> CompareCredential2CredentialsOutput:
    """Find which of several credentials another credential belongs to.

    Args:
        credential_to_evaluate: The credential to identify
        credential_list: The candidates, as `(identifier, credential)` pairs
        calibration: The calibration to use, from `get_model_calibrations()`

    Returns:
        CompareCredential2CredentialsOutput: A score per candidate

    Raises:
        InvalidCredentialError: If a credential is not valid
        CalibrationNotAvailableError: If the calibration is not available

    """
    data_model = CompareCredential2CredentialsInput(
        credential_to_evaluate=credential_to_evaluate,
        credential_list=credential_list,
        calibration=calibration,
    )
    endpoint = DaspeakEndpoints.IDENTIFICATION_CREDENTIAL2CREDENTIALS.value
    data = {
        "credential_to_evaluate": data_model.credential_to_evaluate,
        "credential_list": json.dumps(data_model.credential_list),
        "calibration": data_model.calibration,
    }
    response = self._post(endpoint=endpoint, data=data)
    return CompareCredential2CredentialsOutput(**response.json())

vericlient.daspeak.models

Module to define the models for the Daspeak API.

DEFAULT_CALIBRATION module-attribute

DEFAULT_CALIBRATION = 'telephone-channel'

The calibration the service applies when none is asked for.

DaspeakResponse

Bases: BaseModel

Base class for the Daspeak API responses.

Attributes:

Name Type Description
version str

The version of the API

Source code in src/vericlient/daspeak/models.py
class DaspeakResponse(BaseModel):
    """Base class for the Daspeak API responses.

    Attributes:
        version: The version of the API

    """

    version: str

ModelsOutput

Bases: DaspeakResponse

Output class for the get models endpoint.

Attributes:

Name Type Description
models list

The available models in the service

Source code in src/vericlient/daspeak/models.py
class ModelsOutput(DaspeakResponse):
    """Output class for the get models endpoint.

    Attributes:
        models: The available models in the service

    """

    models: list

BiometricsModelMetadata

Bases: BaseModel

Metadata describing a biometrics model.

Attributes:

Name Type Description
hash str

The hash that identifies the model

description str

The human readable description of the model, such as its release

Source code in src/vericlient/daspeak/models.py
class BiometricsModelMetadata(BaseModel):
    """Metadata describing a biometrics model.

    Attributes:
        hash: The hash that identifies the model
        description: The human readable description of the model, such as its release

    """

    hash: str
    description: str

GetModelMetadataInput

Bases: BaseModel

Input class for the model metadata endpoint.

Attributes:

Name Type Description
hash str

The hash of the biometrics model to describe

Source code in src/vericlient/daspeak/models.py
class GetModelMetadataInput(BaseModel):
    """Input class for the model metadata endpoint.

    Attributes:
        hash: The hash of the biometrics model to describe

    """

    model_config = ConfigDict(title="get_model_metadata()")

    hash: str

GetModelMetadataOutput

Bases: DaspeakResponse

Output class for the model metadata endpoint.

Attributes:

Name Type Description
metadata BiometricsModelMetadata

The metadata of the model

Source code in src/vericlient/daspeak/models.py
class GetModelMetadataOutput(DaspeakResponse):
    """Output class for the model metadata endpoint.

    Attributes:
        metadata: The metadata of the model

    """

    metadata: BiometricsModelMetadata

GetModelCalibrationsInput

Bases: BaseModel

Input class for the model calibration endpoint.

Attributes:

Name Type Description
hash str

The hash of the biometrics model to list the calibrations of

Source code in src/vericlient/daspeak/models.py
class GetModelCalibrationsInput(BaseModel):
    """Input class for the model calibration endpoint.

    Attributes:
        hash: The hash of the biometrics model to list the calibrations of

    """

    model_config = ConfigDict(title="get_model_calibrations()")

    hash: str

GetModelCalibrationsOutput

Bases: DaspeakResponse

Output class for the model calibration endpoint.

Attributes:

Name Type Description
calibrations list[str]

The calibration modes the model supports

Source code in src/vericlient/daspeak/models.py
class GetModelCalibrationsOutput(DaspeakResponse):
    """Output class for the model calibration endpoint.

    Attributes:
        calibrations: The calibration modes the model supports

    """

    calibrations: list[str]

GetModelMetadataFromCredentialInput

Bases: BaseModel

Input class for the model metadata from credential endpoint.

Attributes:

Name Type Description
credential str

The credential to read the originating model from

Source code in src/vericlient/daspeak/models.py
class GetModelMetadataFromCredentialInput(BaseModel):
    """Input class for the model metadata from credential endpoint.

    Attributes:
        credential: The credential to read the originating model from

    """

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

    credential: str

GetModelMetadataFromCredentialOutput

Bases: DaspeakResponse

Output class for the model metadata from credential endpoint.

Attributes:

Name Type Description
metadata BiometricsModelMetadata

The metadata of the model the credential was generated with

Source code in src/vericlient/daspeak/models.py
class GetModelMetadataFromCredentialOutput(DaspeakResponse):
    """Output class for the model metadata from credential endpoint.

    Attributes:
        metadata: The metadata of the model the credential was generated with

    """

    metadata: BiometricsModelMetadata

GenerateCredentialInput

Bases: BaseModel

Input class for the generate credential endpoint.

Attributes:

Name Type Description
audio Media

The audio to generate the credential with. It can be a path to a file or a bytes object with the audio content

hash str

The hash of the biometrics model to use

channel int

The nchannel of the audio if it is stereo

calibration str

The calibration to use

Source code in src/vericlient/daspeak/models.py
class GenerateCredentialInput(BaseModel):
    """Input class for the generate credential endpoint.

    Attributes:
        audio: The audio to generate the credential with.
            It can be a path to a file or a bytes object
            with the audio content
        hash: The hash of the biometrics model to use
        channel: The `nchannel` of the audio if it is stereo
        calibration: The calibration to use

    """

    audio: Media
    hash: str
    channel: int = 1
    calibration: str = DEFAULT_CALIBRATION

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

ModelMetadata

Bases: BaseModel

Metadata of the model used to generate the credential.

Attributes:

Name Type Description
hash str

The hash of the model

mode str

The mode of the model

Source code in src/vericlient/daspeak/models.py
class ModelMetadata(BaseModel):
    """Metadata of the model used to generate the credential.

    Attributes:
        hash: The hash of the model
        mode: The mode of the model

    """

    hash: str
    mode: str

GenerateCredentialOutput

Bases: DaspeakResponse

Output class for the generate credential endpoint.

Attributes:

Name Type Description
model ModelMetadata

The model used to generate the credential

credential str

The generated credential

authenticity float

The authenticity of the audio sample used

input_audio_duration float

The duration of the input audio

net_speech_duration float

The duration of the speech in the audio

Source code in src/vericlient/daspeak/models.py
class GenerateCredentialOutput(DaspeakResponse):
    """Output class for the generate credential endpoint.

    Attributes:
        model: The model used to generate the credential
        credential: The generated credential
        authenticity: The authenticity of the audio sample used
        input_audio_duration: The duration of the input audio
        net_speech_duration: The duration of the speech in the audio

    """

    model: ModelMetadata
    credential: str
    authenticity: float
    input_audio_duration: float
    net_speech_duration: float

    @field_validator("authenticity")
    def round_authenticity(cls, value: float) -> float:
        return round(value, 3)

CompareInput

Bases: BaseModel

Base class for the similarity inputs.

Attributes:

Name Type Description
calibration str

The calibration to use

Source code in src/vericlient/daspeak/models.py
class CompareInput(BaseModel):
    """Base class for the similarity inputs.

    Attributes:
        calibration: The calibration to use

    """

    calibration: str = DEFAULT_CALIBRATION

CompareOutput

Bases: DaspeakResponse

Base class for the similarity outputs.

Attributes:

Name Type Description
score float

The similarity score between the two inputs

Source code in src/vericlient/daspeak/models.py
class CompareOutput(DaspeakResponse):
    """Base class for the similarity outputs.

    Attributes:
        score: The similarity score between the two inputs

    """

    score: float

    @field_validator("score")
    def round_value(cls, value: float) -> float:
        return round(value, 3)

CompareCredential2CredentialInput

Bases: CompareInput

Input class for the similarity credential to credential endpoint.

Attributes:

Name Type Description
credential_reference str

The reference credential

credential_to_evaluate str

The credential to evaluate

calibration str

The calibration to use

Source code in src/vericlient/daspeak/models.py
class CompareCredential2CredentialInput(CompareInput):
    """Input class for the similarity credential to credential endpoint.

    Attributes:
        credential_reference: The reference credential
        credential_to_evaluate: The credential to evaluate
        calibration: The calibration to use

    """

    model_config = ConfigDict(title="compare_credential_to_credential()")

    credential_reference: str
    credential_to_evaluate: str

CompareCredential2CredentialOutput

Bases: CompareOutput

Output class for the similarity credential to credential endpoint.

Attributes:

Name Type Description
calibration str

The calibration used

Source code in src/vericlient/daspeak/models.py
class CompareCredential2CredentialOutput(CompareOutput):
    """Output class for the similarity credential to credential endpoint.

    Attributes:
        calibration: The calibration used

    """

    calibration: str

CompareCredential2AudioInput

Bases: CompareInput

Input class for the similarity credential to audio endpoint.

Attributes:

Name Type Description
credential_reference str

The reference credential

audio_to_evaluate Media

The audio to evaluate. It can be a path to a file or a bytes object with the audio content

channel int

The nchannel of the audio if it is stereo

Source code in src/vericlient/daspeak/models.py
class CompareCredential2AudioInput(CompareInput):
    """Input class for the similarity credential to audio endpoint.

    Attributes:
        credential_reference: The reference credential
        audio_to_evaluate: The audio to evaluate.
            It can be a path to a file or a bytes object
            with the audio content
        channel: The `nchannel` of the audio if it is stereo

    """

    credential_reference: str
    audio_to_evaluate: Media
    channel: int = 1

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

CompareCredential2AudioOutput

Bases: CompareOutput

Output class for the similarity credential to audio endpoint.

Attributes:

Name Type Description
model ModelMetadata

The model used to generate the credential

calibration str

The calibration used

authenticity_to_evaluate float

The authenticity of the audio sample used

input_audio_duration float

The duration of the input audio

net_speech_duration float

The duration of the speech in the audio

Source code in src/vericlient/daspeak/models.py
class CompareCredential2AudioOutput(CompareOutput):
    """Output class for the similarity credential to audio endpoint.

    Attributes:
        model: The model used to generate the credential
        calibration: The calibration used
        authenticity_to_evaluate: The authenticity of the audio sample used
        input_audio_duration: The duration of the input audio
        net_speech_duration: The duration of the speech in the audio

    """

    model: ModelMetadata
    calibration: str
    authenticity_to_evaluate: float
    input_audio_duration_to_evaluate: float
    net_speech_duration_to_evaluate: float

    @field_validator("authenticity_to_evaluate")
    def round_value(cls, value: float) -> float:
        return round(value, 3)

CompareAudio2AudioInput

Bases: CompareInput

Input class for the similarity audio to audio endpoint.

Attributes:

Name Type Description
audio_reference Media

The reference audio. It can be a path to a file or a bytes object with the audio content

audio_to_evaluate Media

The audio to evaluate. It can be a path to a file or a bytes object with the audio content

channel_reference int

The nchannel of the reference audio if it is stereo

channel_to_evaluate int

The nchannel of the audio to evaluate if it is stereo

Source code in src/vericlient/daspeak/models.py
class CompareAudio2AudioInput(CompareInput):
    """Input class for the similarity audio to audio endpoint.

    Attributes:
        audio_reference: The reference audio.
            It can be a path to a file or a bytes object
            with the audio content
        audio_to_evaluate: The audio to evaluate.
            It can be a path to a file or a bytes object
            with the audio content
        channel_reference: The `nchannel` of the reference audio if it is stereo
        channel_to_evaluate: The `nchannel` of the audio to evaluate if it is stereo

    """

    audio_reference: Media
    audio_to_evaluate: Media
    channel_reference: int = 1
    channel_to_evaluate: int = 1

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

CompareAudio2AudioOutput

Bases: CompareOutput

Output class for the similarity audio to audio endpoint.

Attributes:

Name Type Description
model ModelMetadata

The model used to generate the credential

calibration str

The calibration used

authenticity_reference float

The authenticity of the reference audio sample

authenticity_to_evaluate float

The authenticity of the audio to evaluate

input_audio_duration_reference float

The duration of the reference audio

input_audio_duration_to_evaluate float

The duration of the audio to evaluate

net_speech_duration_reference float

The duration of the speech in the reference audio

net_speech_duration_to_evaluate float

The duration of the speech in the audio to evaluate

Source code in src/vericlient/daspeak/models.py
class CompareAudio2AudioOutput(CompareOutput):
    """Output class for the similarity audio to audio endpoint.

    Attributes:
        model: The model used to generate the credential
        calibration: The calibration used
        authenticity_reference: The authenticity of the reference audio sample
        authenticity_to_evaluate: The authenticity of the audio to evaluate
        input_audio_duration_reference: The duration of the reference audio
        input_audio_duration_to_evaluate: The duration of the audio to evaluate
        net_speech_duration_reference: The duration of the speech in the reference audio
        net_speech_duration_to_evaluate: The duration of the speech in the audio to evaluate

    """

    model: ModelMetadata
    calibration: str
    authenticity_reference: float
    authenticity_to_evaluate: float
    input_audio_duration_reference: float
    input_audio_duration_to_evaluate: float
    net_speech_duration_reference: float
    net_speech_duration_to_evaluate: float

    @field_validator("authenticity_reference", "authenticity_to_evaluate")
    def round_value(cls, value: float) -> float:
        return round(value, 3)

CompareAudio2CredentialsInput

Bases: CompareInput

Input class for the identification audio to credentials endpoint.

Attributes:

Name Type Description
audio_to_evaluate Media

The audio to evaluate against the credential list. It can be a path to a file or a bytes object with the audio content

credential_list list[dict[str, str]]

The credentials to compare the audio with. The list contains touples with two strings: the id and the credential

channel int

The nchannel of the audio if it is stereo

Source code in src/vericlient/daspeak/models.py
class CompareAudio2CredentialsInput(CompareInput):
    """Input class for the identification audio to credentials endpoint.

    Attributes:
        audio_to_evaluate: The audio to evaluate against the credential list.
            It can be a path to a file or a bytes object
            with the audio content
        credential_list: The credentials to compare the audio with.
            The list contains touples with two strings: the id and the credential
        channel: The `nchannel` of the audio if it is stereo

    """

    audio_to_evaluate: Media
    credential_list: list[dict[str, str]]
    channel: int = 1

    @field_validator("credential_list", mode="before")
    def validate_and_build_list_format(cls, value: list):
        """Turn `(id, credential)` pairs into the shape the service wants.

        Accepts its own output as well, so `Model(**dict(model))` round-trips. Without that
        a model could not be rebuilt from its own fields, which is exactly what happens when
        one method hands its arguments to another.
        """
        if not value:
            error = "credential_list must not be empty"
            raise ValueError(error)
        if all(isinstance(item, dict) and {"id", "credential"} <= set(item) for item in value):
            return value
        error = "credential_list must contain pairs of two strings: an id and a credential"
        n_items = 2
        for item in value:
            if not isinstance(item, (tuple, list)) or len(item) != n_items:
                raise ValueError(error)
            if not all(isinstance(i, str) for i in item):
                raise ValueError(error)
        return [{"id": item[0], "credential": item[1]} for item in value]

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

validate_and_build_list_format

validate_and_build_list_format(value)

Turn (id, credential) pairs into the shape the service wants.

Accepts its own output as well, so Model(**dict(model)) round-trips. Without that a model could not be rebuilt from its own fields, which is exactly what happens when one method hands its arguments to another.

Source code in src/vericlient/daspeak/models.py
@field_validator("credential_list", mode="before")
def validate_and_build_list_format(cls, value: list):
    """Turn `(id, credential)` pairs into the shape the service wants.

    Accepts its own output as well, so `Model(**dict(model))` round-trips. Without that
    a model could not be rebuilt from its own fields, which is exactly what happens when
    one method hands its arguments to another.
    """
    if not value:
        error = "credential_list must not be empty"
        raise ValueError(error)
    if all(isinstance(item, dict) and {"id", "credential"} <= set(item) for item in value):
        return value
    error = "credential_list must contain pairs of two strings: an id and a credential"
    n_items = 2
    for item in value:
        if not isinstance(item, (tuple, list)) or len(item) != n_items:
            raise ValueError(error)
        if not all(isinstance(i, str) for i in item):
            raise ValueError(error)
    return [{"id": item[0], "credential": item[1]} for item in value]

CompareAudio2CredentialsOutput

Bases: DaspeakResponse

Output class for the identification audio to credentials endpoint.

Attributes:

Name Type Description
result dict

The result of the identification, a dictionary with the "id" and the "score" of the best match

scores list[dict]

The whole list of scores for each credential. The list contains dictionaries with two keys (and values): "id" and "score"

calibration str

The calibration used

model ModelMetadata

The model used to generate the credential

authenticity_to_evaluate float

The authenticity of the evaluated audio sample

input_audio_duration_to_evaluate float

The duration of the evaluated audio

net_speech_duration_to_evaluate float

The duration of the speech in the evaluated audio

Source code in src/vericlient/daspeak/models.py
class CompareAudio2CredentialsOutput(DaspeakResponse):
    """Output class for the identification audio to credentials endpoint.

    Attributes:
        result: The result of the identification, a dictionary with the "id" and the "score"
            of the best match
        scores: The whole list of scores for each credential.
            The list contains dictionaries with two keys (and values): "id" and "score"
        calibration: The calibration used
        model: The model used to generate the credential
        authenticity_to_evaluate: The authenticity of the evaluated audio sample
        input_audio_duration_to_evaluate: The duration of the evaluated audio
        net_speech_duration_to_evaluate: The duration of the speech in the evaluated audio

    """

    result: dict
    scores: list[dict]
    calibration: str
    model: ModelMetadata
    authenticity_to_evaluate: float
    input_audio_duration_to_evaluate: float
    net_speech_duration_to_evaluate: float

    @field_validator("authenticity_to_evaluate")
    def round_value(cls, value: float) -> float:
        return round(value, 3)

CompareCredential2CredentialsInput

Bases: CompareInput

Input class for the identification credential to credentials endpoint.

Attributes:

Name Type Description
credential_to_evaluate str

The credential to evaluate against the credential list

credential_list list[dict[str, str]]

The credentials to compare the audio with. The list contains touples with two strings: the id and the credential

Source code in src/vericlient/daspeak/models.py
class CompareCredential2CredentialsInput(CompareInput):
    """Input class for the identification credential to credentials endpoint.

    Attributes:
        credential_to_evaluate: The credential to evaluate against the credential list
        credential_list: The credentials to compare the audio with.
            The list contains touples with two strings: the id and the credential

    """

    model_config = ConfigDict(title="identify_credential()")

    credential_to_evaluate: str
    credential_list: list[dict[str, str]]

    @field_validator("credential_list", mode="before")
    def validate_and_build_list_format(cls, value: list):
        """Turn `(id, credential)` pairs into the shape the service wants.

        Accepts its own output as well, so `Model(**dict(model))` round-trips. Without that
        a model could not be rebuilt from its own fields, which is exactly what happens when
        one method hands its arguments to another.
        """
        if not value:
            error = "credential_list must not be empty"
            raise ValueError(error)
        if all(isinstance(item, dict) and {"id", "credential"} <= set(item) for item in value):
            return value
        error = "credential_list must contain pairs of two strings: an id and a credential"
        n_items = 2
        for item in value:
            if not isinstance(item, (tuple, list)) or len(item) != n_items:
                raise ValueError(error)
            if not all(isinstance(i, str) for i in item):
                raise ValueError(error)
        return [{"id": item[0], "credential": item[1]} for item in value]

validate_and_build_list_format

validate_and_build_list_format(value)

Turn (id, credential) pairs into the shape the service wants.

Accepts its own output as well, so Model(**dict(model)) round-trips. Without that a model could not be rebuilt from its own fields, which is exactly what happens when one method hands its arguments to another.

Source code in src/vericlient/daspeak/models.py
@field_validator("credential_list", mode="before")
def validate_and_build_list_format(cls, value: list):
    """Turn `(id, credential)` pairs into the shape the service wants.

    Accepts its own output as well, so `Model(**dict(model))` round-trips. Without that
    a model could not be rebuilt from its own fields, which is exactly what happens when
    one method hands its arguments to another.
    """
    if not value:
        error = "credential_list must not be empty"
        raise ValueError(error)
    if all(isinstance(item, dict) and {"id", "credential"} <= set(item) for item in value):
        return value
    error = "credential_list must contain pairs of two strings: an id and a credential"
    n_items = 2
    for item in value:
        if not isinstance(item, (tuple, list)) or len(item) != n_items:
            raise ValueError(error)
        if not all(isinstance(i, str) for i in item):
            raise ValueError(error)
    return [{"id": item[0], "credential": item[1]} for item in value]

CompareCredential2CredentialsOutput

Bases: DaspeakResponse

Output class for the identification credential to credentials endpoint.

Attributes:

Name Type Description
result dict

The result of the identification, a dictionary with the "id" and the "score" of the best match

scores list[dict]

The whole list of scores for each credential. The list contains dictionaries with two keys (and values): "id" and "score"

calibration str

The calibration used

Source code in src/vericlient/daspeak/models.py
class CompareCredential2CredentialsOutput(DaspeakResponse):
    """Output class for the identification credential to credentials endpoint.

    Attributes:
        result: The result of the identification, a dictionary with the "id" and the "score"
            of the best match
        scores: The whole list of scores for each credential.
            The list contains dictionaries with two keys (and values): "id" and "score"
        calibration: The calibration used

    """

    result: dict
    scores: list[dict]
    calibration: str

vericlient.daspeak.exceptions

Module to define the exceptions for the Daspeak API.

DaspeakError

Bases: VeriClientError

Base class for exceptions in the Daspeak API.

Source code in src/vericlient/daspeak/exceptions.py
class DaspeakError(VeriClientError):
    """Base class for exceptions in the Daspeak API."""

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

AudioInputError

Bases: DaspeakError

Exception raised for errors in the audio input.

Source code in src/vericlient/daspeak/exceptions.py
class AudioInputError(DaspeakError):
    """Exception raised for errors in the audio input."""

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

TooManyAudioChannelsError

Bases: AudioInputError

Exception raised for too many audio channels.

Source code in src/vericlient/daspeak/exceptions.py
class TooManyAudioChannelsError(AudioInputError):
    """Exception raised for too many audio channels."""

    def __init__(self) -> None:
        message = "The maximum allowed number of audio channels is 2, and the audio provided has more channels"
        super().__init__(message)

UnsupportedSampleRateError

Bases: AudioInputError

Exception raised for unsupported sample rates.

Source code in src/vericlient/daspeak/exceptions.py
class UnsupportedSampleRateError(AudioInputError):
    """Exception raised for unsupported sample rates."""

    def __init__(self) -> None:
        message = "The sample rate of the audio is not supported, must be 8 Khz or 16 Khz"
        super().__init__(message)

AudioDurationTooLongError

Bases: AudioInputError

Exception raised for audio duration too long.

Source code in src/vericlient/daspeak/exceptions.py
class AudioDurationTooLongError(AudioInputError):
    """Exception raised for audio duration too long."""

    def __init__(self) -> None:
        message = "The audio duration is too long, must be less than 30 seconds"
        super().__init__(message)

UnsupportedAudioCodecError

Bases: AudioInputError

Exception raised for unsupported audio codec.

Source code in src/vericlient/daspeak/exceptions.py
class UnsupportedAudioCodecError(AudioInputError):
    """Exception raised for unsupported audio codec."""

    def __init__(self) -> None:
        message = "The audio codec is not supported. Supported codecs are: 'PCM_16', 'ULAW', 'ALAW'"
        super().__init__(message)

SignalNoiseRatioError

Bases: DaspeakError

Exception raised for errors in the signal noise ratio.

Source code in src/vericlient/daspeak/exceptions.py
class SignalNoiseRatioError(DaspeakError):
    """Exception raised for errors in the signal noise ratio."""

    def __init__(self) -> None:
        message = "Noise level of the audio exceeded"
        super().__init__(message)

NetSpeechDurationIsNotEnoughError

Bases: DaspeakError

Exception raised for errors in the net speech duration.

Source code in src/vericlient/daspeak/exceptions.py
class NetSpeechDurationIsNotEnoughError(DaspeakError):
    """Exception raised for errors in the net speech duration."""

    def __init__(self, net_speech_detected: float) -> None:
        message = (
            f"You need at least 3 seconds of speech to perform the operation, "
            f"but only {net_speech_detected} seconds were detected"
        )
        super().__init__(message)

InvalidSpecifiedChannelError

Bases: DaspeakError

Exception raised for invalid specified channel.

Source code in src/vericlient/daspeak/exceptions.py
class InvalidSpecifiedChannelError(DaspeakError):
    """Exception raised for invalid specified channel."""

    def __init__(self) -> None:
        message = "The specified channel is invalid, must be 1 or 2"
        super().__init__(message)

InsufficientQualityError

Bases: DaspeakError

Exception raised for insufficient quality.

Source code in src/vericlient/daspeak/exceptions.py
class InsufficientQualityError(DaspeakError):
    """Exception raised for insufficient quality."""

    def __init__(self) -> None:
        message = "The audio quality is insufficient or may contain more than one speaker"
        super().__init__(message)

CalibrationNotAvailableError

Bases: DaspeakError

Exception raised for calibration not available.

Source code in src/vericlient/daspeak/exceptions.py
class CalibrationNotAvailableError(DaspeakError):
    """Exception raised for calibration not available."""

    def __init__(self, calibration: str) -> None:
        message = f"The calibration {calibration} is not available"
        super().__init__(message)

ModelNotAvailableError

Bases: DaspeakError

Exception raised when the requested biometrics model does not exist.

Source code in src/vericlient/daspeak/exceptions.py
class ModelNotAvailableError(DaspeakError):
    """Exception raised when the requested biometrics model does not exist."""

    def __init__(self, model_hash: str) -> None:
        message = f"The biometrics model {model_hash} is not available"
        super().__init__(message)