# CremyX Diarize (`andrew_babo/cremyx-diarize`) Actor

Speaker diarization with sherpa-onnx: returns speaker turns and can label an existing word-level transcript with speaker IDs.

- **URL**: https://apify.com/andrew\_babo/cremyx-diarize.md
- **Developed by:** [Kevin Phạm](https://apify.com/andrew_babo) (community)
- **Categories:** AI, Videos
- **Stats:** 2 total users, 2 monthly users, 70.0% 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?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## cremyx-diarize

sherpa-onnx speaker diarization: *ai nói, nói lúc nào*. Thay cho việc bắt user
cài sherpa-onnx + model trên máy.

- Base image: `node:22-bookworm-slim` (sherpa-onnx chỉ có binary glibc, không chạy Alpine)
- Model nướng sẵn: `sherpa-onnx-pyannote-segmentation-3-0` + `nemo_en_titanet_small.onnx`

### Input

```jsonc
{
  "source": "kv:<storeId>/audio.wav",       // hoặc https://… (mp4/m4a/mp3/wav đều được)
  "transcript": "kv:<storeId>/transcript.json", // tuỳ chọn: transcript của cremyx-asr
  "options": {
    "num_speakers": null,        // biết chắc số người nói thì điền (vd 2) → chính xác hơn nhiều
    "cluster_threshold": 0.5,    // dùng khi không biết số người; nhỏ hơn = tách nhiều người hơn
    "min_duration_on": 0.3,      // đoạn nói ngắn hơn (giây) thì bỏ
    "min_duration_off": 0.5,     // khoảng lặng đủ dài để tách 2 lượt nói
    "threads": null              // mặc định = số CPU (tối đa 8)
  },
  "output": { "signed_upload_url": null },
  "cleanup": "on_success",
  "callback": null
}
```

Nguồn luôn được convert về WAV 16 kHz mono trong actor, nên đưa mp4 vào cũng được.

### Output

```jsonc
{
  "status": "success",
  "op": "diarize",
  "artifacts": [
    { "name": "diarization", "kv_key": "diarization.json" },
    { "name": "transcript_speakers", "kv_key": "transcript-speakers.json" }  // chỉ khi truyền "transcript"
  ],
  "meta": {
    "engine": "sherpa-onnx",
    "duration_sec": 184.2,
    "speaker_count": 2,
    "speakers": [
      { "speaker": "SPEAKER_00", "turns": 24, "speech_ms": 96500 },
      { "speaker": "SPEAKER_01", "turns": 21, "speech_ms": 71200 }
    ],
    "turn_count": 45,
    "turns": [{ "start_ms": 1200, "end_ms": 5400, "speaker": "SPEAKER_00" }],
    "transcript_labelled": true
  }
}
```

`speakers` đã sắp theo tổng thời gian nói giảm dần — phần tử đầu là "người nói
chính" của clip.

#### Gắn nhãn người nói vào transcript

Truyền thêm `transcript` (artifact `transcript.json` của `cremyx-asr`) thì actor
trả về `transcript-speakers.json`: **y hệt** transcript gốc nhưng mỗi `word` và
mỗi `segment` có thêm trường `speaker`. Nhãn được gán theo lượt nói chồng lấn
nhiều nhất về thời gian.

```jsonc
{ "id": 0, "text": "Xin", "startMs": 120, "endMs": 310, "confidence": 0.93, "speaker": "SPEAKER_00" }
```

### Mẹo dùng

- Biết trước số người nói (podcast 2 người, phỏng vấn 1-1) → **luôn** set
  `num_speakers`. Đây là yếu tố ảnh hưởng chất lượng lớn nhất.
- Nhiều người nói chồng nhau: diarization đưa mỗi thời điểm về một người duy
  nhất, không tách overlap.
- Nhạc nền lớn làm giảm độ chính xác — nếu có track voice riêng thì dùng track đó.

### Ví dụ nối chuỗi

```js
const wav  = await tools.mediaTools({ op: 'audio16k', source: videoUrl });
const asr  = await tools.asr({ source: wav.kv('audio') });
const diar = await tools.diarize({
  source: wav.kv('audio'),
  transcript: asr.kv('transcript'),
  options: { num_speakers: 2 },
});
console.log(diar.meta.speakers);
```

### Shard window (v2)

Hỗ trợ `options.start_sec` / `duration_sec` / `overlap_sec` giống cremyx-asr; turn timestamp được offset về timeline gốc, turn trong đuôi overlap có `_overlap: true`.

Lưu ý: nhãn speaker (SPEAKER\_00…) chỉ nhất quán **trong một run**. Cần speaker nhất quán cả video → chạy full file, hoặc shard dài (5–10 phút).

Memory mặc định run: 8 GB.

# 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 cremyx-media-tools). Any format works — it is converted to 16 kHz mono internally.

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

https:// URL or kv:<storeId>/<key> of a cremyx-asr 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": "diarize",
  "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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("andrew_babo/cremyx-diarize").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("andrew_babo/cremyx-diarize").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 '{}' |
apify call andrew_babo/cremyx-diarize --silent --output-dataset

```

## MCP server setup

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

```

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/CTEPvdGbgRNephLwO/openapi.json
