# Speaker Diarization: Who Spoke When in Audio & Video (`andrew_babo/speaker-diarization`) Actor

Speaker diarization with sherpa-onnx: detect how many speakers there are, when each one talks, and optionally attach speaker labels to an existing transcript. Works on any audio or video.

- **URL**: https://apify.com/andrew\_babo/speaker-diarization.md
- **Developed by:** [Andrew Babo](https://apify.com/andrew_babo) (community)
- **Categories:** AI, Videos
- **Stats:** 40 total users, 18 monthly users, 68.8% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Speaker Diarization — Who Spoke When in Audio & Video

Find out **how many speakers** are in a recording and **when each one talks**.
Runs pyannote segmentation plus speaker embeddings through sherpa-onnx on CPU —
no GPU, no API keys, no local install.

Optionally pass an existing transcript and get the same words and segments back
with a speaker label attached, ready for a two-column interview transcript.

**Use it for:** interview and podcast transcripts, meeting minutes, call-centre
QA, subtitle attribution, dataset labelling, audio search.

### Quick start

```json
{
  "op": "diarize",
  "source": "https://example.com/interview.mp3"
}
```

Feature-detect the build (free, a few seconds, needs no source):

```json
{ "op": "capabilities" }
```

Label an existing transcript:

```json
{
  "op": "diarize",
  "source": "https://example.com/interview.mp3",
  "transcript": "https://api.apify.com/v2/key-value-stores/.../transcript.json",
  "options": { "num_speakers": 2 }
}
```

### Input

| Field | Type | Notes |
| --- | --- | --- |
| `op` | `diarize` | `capabilities` | default `diarize` |
| `source` | string | `https://` URL or `kv:<storeId>/<key>`. Any audio or video; converted to 16 kHz mono internally. |
| `transcript` | string | optional transcript JSON to label (word/segment timings in ms) |
| `options.num_speakers` | integer | set it when you know the exact count — most accurate |
| `options.cluster_threshold` | number | default `0.5`; used when `num_speakers` is unset |
| `options.min_duration_on` / `min_duration_off` | number | minimum speech / silence length |
| `options.threads` | integer | defaults to the run's vCPU count |
| `options.start_sec` / `duration_sec` / `overlap_sec` | number | diarize one window only |
| `output.signed_upload_url` | string | PUT `diarization.json` into your own storage |
| `cleanup` | `on_success` | `always` | `off` | artifact retention |
| `callback` | object | `{ url, secret_header: { name, value } }` webhook |

### Output

```json
{
  "status": "success",
  "op": "diarize",
  "artifacts": [{ "name": "diarization", "kv_key": "diarization.json", "url": "https://api.apify.com/v2/key-value-stores/.../diarization.json" }],
  "meta": {
    "duration_sec": 1820.5,
    "speaker_count": 2,
    "turns": [
      { "speaker": "SPEAKER_00", "start_ms": 0,     "end_ms": 8450 },
      { "speaker": "SPEAKER_01", "start_ms": 8600,  "end_ms": 15120 }
    ]
  }
}
```

With `transcript` set, the artifact also contains the input words and segments
with a `speaker` field added to each one.

**Speaker IDs are stable within one run only.** If you shard a long file, match
speakers across shards yourself (for example by overlapping a few seconds and
comparing who is talking there).

### Sharding a long recording

```json
{
  "op": "diarize",
  "source": "https://example.com/long.wav",
  "options": { "start_sec": 1800, "duration_sec": 900, "overlap_sec": 5 }
}
```

Turns are offset back to the original timeline; items past `duration_sec` are
flagged `_overlap`.

### Error handling

```json
{ "ok": false, "reason": "BAD_INPUT", "message": "..." }
```

| `reason` | Meaning | What to do |
| --- | --- | --- |
| `BAD_INPUT` | missing/unreadable source or transcript | check URLs are publicly reachable |
| `UPSTREAM_BLOCKED` | the host refused the download | host the file yourself first |
| `TIMEOUT` | run exceeded its timeout | shard the recording |
| `OOM_LIMIT` | not enough memory | run with 16 GB |
| `INTERNAL` | unexpected failure | retry; report the run ID |

### Performance

16 GB run (≈4 vCPU), CPU only:

| Recording | Typical time |
| --- | --- |
| 10 min | ~1 min |
| 60 min | ~5–8 min |
| 3 h | shard into 15–30 min windows |

Extracting mono 16 kHz audio first (see the **Video & Audio Toolkit** actor)
makes the download and conversion step much cheaper for video sources.

### FAQ

**Does it recognise *who* the people are?** No — it separates speakers and
labels them `SPEAKER_00`, `SPEAKER_01`… Mapping labels to real names is up to you.

**How accurate is the speaker count?** Very good for 2–4 clean speakers. Set
`num_speakers` when you know it; heavy crosstalk and noisy phone audio are the
hard cases.

**Can it label an existing transcript?** Yes — pass `transcript` and every word
and segment comes back with a `speaker` field.

**Video input?** Supported; the audio track is extracted automatically.

**Need visual speaker detection?** The **Face Detection & Auto Reframe** actor
detects the active speaker from mouth movement — the two signals complement
each other.

# Actor input Schema

## `op` (type: `string`):

Diarize speakers, or return supported capabilities.

## `source` (type: `string`):

https:// URL, or kv:<storeId>/<key> from an earlier run (e.g. the audio16k.wav produced by video-audio-toolkit). Any format works — it is converted to 16 kHz mono internally.

## `transcript` (type: `string`):

https:// URL or kv:<storeId>/<key> of a speech-to-text-whisper transcript.json. When set, the actor also returns the same words/segments with a speaker label attached.

## `options` (type: `object`):

{ num\_speakers, cluster\_threshold, min\_duration\_on, min\_duration\_off, threads }. Set num\_speakers when you know the exact count; otherwise clustering uses cluster\_threshold (default 0.5). Sharding: start\_sec, duration\_sec, overlap\_sec — diarize only that window; turns are offset back to the original timeline, items past duration\_sec flagged \_overlap. Speaker IDs are only consistent within one run/shard.

## `output` (type: `object`):

{ signed\_upload\_url } to PUT diarization.json straight into your own storage.

## `cleanup` (type: `string`):

on\_success = keep only result artifacts in the run's key-value store. always = also drop them after the signed upload. off = keep everything for debugging.

## `callback` (type: `object`):

{ url, secret\_header: { name, value } } — POSTed with the result JSON when the run finishes.

## Actor input object example

```json
{
  "op": "capabilities",
  "cleanup": "on_success"
}
```

# Actor output Schema

## `results` (type: `string`):

Full run result JSON: status, op, artifacts \[{name, kv\_key, url, bytes}], meta (speaker turns, labels), timings, errors.

## `resultRecord` (type: `string`):

The same result JSON stored as the RESULT record of the default key-value store.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "op": "capabilities"
};

// Run the Actor and wait for it to finish
const run = await client.actor("andrew_babo/speaker-diarization").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "op": "capabilities" }

# Run the Actor and wait for it to finish
run = client.actor("andrew_babo/speaker-diarization").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "op": "capabilities"
}' |
apify call andrew_babo/speaker-diarization --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,andrew_babo/speaker-diarization"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/fQOf878DOJOX8Hl9f/builds/2gx3hcVReC28upf4h/openapi.json
