Metadata-Version: 2.5
Name: voicemaildetector
Version: 0.3.0
Summary: Python client for the Voicemail Detector API: answering machine detection for live calls and recordings.
Project-URL: Homepage, https://voicemaildetector.com
Project-URL: Documentation, https://voicemaildetector.com/docs
Project-URL: Source, https://github.com/voicemaildetector/voicemaildetector-python
Author-email: Voicemail Detector <contact@voicemaildetector.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: amd,answering machine detection,asterisk,dialer,telephony,telnyx,twilio,voice ai,voicemail,voicemail detection
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Communications :: Telephony
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: websockets>=14.1
Provides-Extra: test
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# Voicemail Detector for Python

Answering machine detection for outbound calls and voice AI. Send the callee's audio and get back
`human`, `machine` or `unknown`, usually within 2.5 to 4.5 seconds of the answer. The call never
waits for the verdict: your agent or voice AI talks from the first second, and you hang up on
machines when the verdict arrives.

- Live calls over a WebSocket, recordings over REST, with a regular and an asyncio client.
- Mono G.711 µ-law, A-law or 16-bit PCM: 8 kHz from telephone trunks, or up to 48 kHz from a
  browser (WebRTC) or a voice AI pipeline, at whatever rate you have it.
- Typed errors with a `retryable` flag. One dependency (`websockets`). Python 3.10 or newer.

Get an API key at [voicemaildetector.com](https://voicemaildetector.com/dashboard/key): 500 calls
a month are free.

## Install

```sh
pip install voicemaildetector
```

## A live call

Open one stream per call when it is answered, send the callee's audio as it arrives and end the
stream when the call is over. The connection opens in the background; frames sent before it does
are held and sent once it opens.

```python
from voicemaildetector import VoicemailDetector

vd = VoicemailDetector()  # reads VD_API_KEY

def on_result(result):
    if result.verdict == "machine":
        hang_up()

with vd.stream(encoding="mulaw", on_result=on_result) as call:
    for frame in callee_audio():  # 20 ms frames
        call.send(frame)
# Leaving the block ends the stream and waits for the last results.
```

`call.verdict()` returns the first decision, or `None` if the stream ended without one;
`call.wait()` returns once the server is done with the call; iterating over `call` gives every
result as it comes. All three take an optional `timeout` in seconds.

On asyncio, `send` and `end` never block, so they fit inside a media pipeline:

```python
from voicemaildetector import AsyncVoicemailDetector

vd = AsyncVoicemailDetector()

async with vd.stream(encoding="pcm16") as call:
    async for frame in callee_audio():
        call.send(frame)
    verdict = await call.verdict()
```

A call can get two results: the `decision`, and later an `after_human` machine result when a
machine shows up after a human verdict, for example a greeting that starts after a pause. Keep
sending audio for `watch_ms` after a human verdict to get it.

## Wideband audio: WebRTC and voice AI

Browsers and voice AI pipelines usually hand you the callee's audio at 16, 24 or 48 kHz. Send it
at that rate, as 16-bit PCM, and say which; the API takes care of the rest. Do not resample it
yourself.

```python
call = vd.stream(encoding="pcm16", sample_rate=16000)
call.send(frame)  # 16-bit PCM from the pipeline, at 16 kHz


# Float samples in [-1, 1] become 16-bit PCM like this:
import array

def pcm16(samples):
    return array.array("h", (int(max(-1.0, min(1.0, s)) * 32767) for s in samples)).tobytes()
```

In a browser, send the audio through your own server: the API key never belongs in a web page.

## A recording

```python
result = vd.detect("call-0193.wav")
print(result.verdict)  # machine
```

`detect` takes a file path, bytes or a binary file object, up to 8 MiB. A WAV file carries its own
format and rate; raw audio needs `encoding`, and `sample_rate` when it is not 8000.

## Options

```python
VoicemailDetector(
    api_key="vd_…",        # default: VD_API_KEY
    base_url="…",          # default: VD_API_URL, then https://api.voicemaildetector.com
    timeout=60.0,          # for detect, in seconds
    user_agent="my-dialer/2.3",
)

vd.stream(
    encoding="mulaw",          # "mulaw", "alaw" or "pcm16"; required for streams
    sample_rate=8000,          # Hz: 8000 (default), 11025, 12000, 16000, 22050, 24000, 32000, 44100 or 48000
    decision_timeout_ms=6000,  # the most audio heard before the first verdict, 1000 to 30000
    watch_ms=30000,            # how long to keep listening after a human verdict, up to 60000
    on_result=print,           # every result; a function, or a coroutine function on asyncio
    on_error=print,            # once, if the stream fails
)
```

`detect` takes the same `encoding`, `sample_rate`, `decision_timeout_ms` and `watch_ms`. A WAV file
carries its own format and rate.

## Results

`Result(verdict="machine", stage="decision", at_ms=4500)`

| field | values |
|---|---|
| `verdict` | `human`, `machine` or `unknown` (the line stayed silent, or the audio ended first) |
| `stage` | `decision` for the first verdict, `after_human` when a later result overturns `human` |
| `at_ms` | milliseconds of audio heard, from the answer, when the result was given |

## Errors

Every failure is a `VoicemailDetectorError` with a `code`, the HTTP `status` when there was one,
and `retryable`. On a stream it is raised by `verdict()`, `wait()` and the iteration, and passed to
`on_error`. A dialer that must never depend on the detector carries on as if the verdict were
`unknown` when `on_error` is called.

| code | when | retryable |
|---|---|---|
| `unauthorized` | the API key is missing, revoked or malformed | no |
| `payment_required` | the account has no calls left | no |
| `too_many_calls` | the account is at its limit of calls at once | no |
| `busy` | the API is at capacity; the next call will likely go through | yes |
| `not_ready` | the API is starting | yes |
| `bad_request`, `bad_audio`, `too_large` | the request or its audio was refused | no |
| `connection`, `timeout` | the network failed or the API did not answer in time | yes |
| `internal` | the API failed | yes |

A refused call is refused at once and never queued, so your dialer can fall back right away.

## Twilio and Telnyx, without a relay

Twilio Media Streams and Telnyx media streaming can send the call's audio straight to Voicemail
Detector, which posts the verdict to your app as a webhook shaped like the platform's own
answering machine detection (`AnsweredBy=machine_start` for Twilio,
`call.machine.detection.ended` for Telnyx). Guide: https://voicemaildetector.com/docs/twilio-telnyx

Every webhook is signed with your API key. Check it on the raw body before acting on it:

```python
from voicemaildetector import verify_webhook

# Flask: request.get_data() is the raw body
if not verify_webhook(request.get_data(), request.headers.get("X-VD-Signature")):
    abort(401)
```

## Examples

- [detect_file.py](examples/detect_file.py): a recording.
- [stream_wav.py](examples/stream_wav.py): a WAV played as a live call.
- [twilio_media_stream.py](examples/twilio_media_stream.py): a relay for Twilio Media Streams
  that hangs up on machines, for when you want the audio to pass through your own server.
- [telnyx_media_stream.py](examples/telnyx_media_stream.py): the same for Telnyx.

On Asterisk or Vicidial, the [connector](https://github.com/voicemaildetector/connector) replaces
`AMD()` with one line of dialplan.

## More

- API reference: https://voicemaildetector.com/docs
- Node.js: https://github.com/voicemaildetector/voicemaildetector-node
- Security: [SECURITY.md](SECURITY.md)

Apache-2.0.
