Skip to content

ADescribe · audio.diarize

Who spoke when (speaker diarization)

In each recording, when does someone speak, how many people speak, and who talks how much?

Finds the speech in each recording (energy voice activity), cuts it into short windows, turns every window into an ECAPA-TDNN speaker embedding (SpeechBrain's VoxCeleb model, written out in Python and R on torch; a one-time download you approve), groups the windows by voice with average-linkage clustering and returns timed segments labeled S1, S2, … with talk time and speaker changes. Give the number of speakers when you know it; otherwise it is estimated. With a table of reference turns it scores the result with the diarization error rate (missed speech, false alarms and wrong speaker, with a collar). The embeddings are biometric: they stay in memory and are never saved.

Experimental Python and R agree to 6 decimals Also called speaker diarization, diarisation, who spoke when…

A real result

Example “Conversations reference”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Who spoke whenRecorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

2 recordings (13.6 s, 9.9 s of speech) split into 7 segments with 3 speakers at most per recording and 5 changes of speaker. Against the reference turns, the diarization error rate is 0.0% (collar 0.5 s).

Segments
7
Most speakers in a recording
3
DER
0.0%

Plots

Who spoke when: conv_two.wavWho or what is active when — and where do they overlap?
View data
End (s)SpeakerStart (s)
1.915S10.2950
4.165S22.345
5.805S14.595
Who spoke when: conv_three.wavWho or what is active when — and where do they overlap?
View data
End (s)SpeakerStart (s)
1.705S10.2850
3.665S22.145
5.415S34.095
6.865S25.845

Assumptions

  • One speaker at a time — Each moment gets one speaker; overlapping speech counts as an error against references that mark it.
  • Number of speakers — Estimated per recording: groups merge while their average similarity is at least 0.5 (at most 10). Set the number when you know it.
  • Voices identify people — The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording.

Who spoke when

pathStart (s)End (s)SecondsSpeaker
media/aud3/conv_two.wav0.29501.9151.620S1
media/aud3/conv_two.wav2.3454.1651.820S2
media/aud3/conv_two.wav4.5955.8051.210S1
media/aud3/conv_three.wav0.28501.7051.420S1
media/aud3/conv_three.wav2.1453.6651.520S2
media/aud3/conv_three.wav4.0955.4151.320S3
media/aud3/conv_three.wav5.8456.8651.020S2

Talk time per speaker

pathSpeakerSecondsShare of speech
media/aud3/conv_two.wavS12.8300.6086
media/aud3/conv_two.wavS21.8200.3914
media/aud3/conv_three.wavS11.4200.2689
media/aud3/conv_three.wavS22.5400.4811
media/aud3/conv_three.wavS31.3200.2500

Diarization error rate (collar 0.5 s)

pathScored secondsMissed speech (s)False alarm (s)Wrong speaker (s)DERReference speakersFound speakers
media/aud3/conv_two.wav3.100000022
media/aud3/conv_three.wav3.200000033
  • Energy voice activity (within 35 dB of the loudest 25-ms frame), 1.5-s windows every 0.75 s, ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm + wrong speaker) / reference speech, with the best one-to-one speaker mapping.
Python

2 recordings (13.6 s, 9.9 s of speech) split into 7 segments with 3 speakers at most per recording and 5 changes of speaker. Against the reference turns, the diarization error rate is 0.0% (collar 0.5 s).

Segments
7
Most speakers in a recording
3
DER
0.0%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • One speaker at a time — Each moment gets one speaker; overlapping speech counts as an error against references that mark it.
  • Number of speakers — Estimated per recording: groups merge while their average similarity is at least 0.5 (at most 10). Set the number when you know it.
  • Voices identify people — The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording.

Who spoke when

pathStart (s)End (s)SecondsSpeaker
media/aud3/conv_two.wav0.29501.9151.620S1
media/aud3/conv_two.wav2.3454.1651.820S2
media/aud3/conv_two.wav4.5955.8051.210S1
media/aud3/conv_three.wav0.28501.7051.420S1
media/aud3/conv_three.wav2.1453.6651.520S2
media/aud3/conv_three.wav4.0955.4151.320S3
media/aud3/conv_three.wav5.8456.8651.020S2

Talk time per speaker

pathSpeakerSecondsShare of speech
media/aud3/conv_two.wavS12.8300.6086
media/aud3/conv_two.wavS21.8200.3914
media/aud3/conv_three.wavS11.4200.2689
media/aud3/conv_three.wavS22.5400.4811
media/aud3/conv_three.wavS31.3200.2500

Diarization error rate (collar 0.5 s)

pathScored secondsMissed speech (s)False alarm (s)Wrong speaker (s)DERReference speakersFound speakers
media/aud3/conv_two.wav3.100000022
media/aud3/conv_three.wav3.200000033
  • Energy voice activity (within 35 dB of the loudest 25-ms frame), 1.5-s windows every 0.75 s, ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm + wrong speaker) / reference speech, with the best one-to-one speaker mapping.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Conversations referenceaud3_conversations · audio: path
  • Conversations three speakersaud3_conversations · audio: path
  • Degenerate all naaud3_conversations · audio: path
  • Degenerate n1aud3_conversations · audio: path
  • Pdna missing pathpdna_audio · audio: path

In the guides

Where it sits in the decision guides

  • Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
  • Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Audio file pathcategorical · 1 column
A column of recordings with several speakers (meetings, interviews, calls), such as the path column of an audio folder.

Choices you make

options

Number of speakersdefault —

How many people speak in each recording, when you know it; this is the most reliable setting.

Same voice above this similaritydefault 0.5

With the number estimated, windows join one speaker while their average cosine similarity is at least this. Higher finds more speakers.

Most speakersdefault 10

The estimate never finds more speakers than this per recording.

statistics

Reference turns (optional)default —

A table of who really spoke when (one row per turn) to score the result with the diarization error rate.

Collar (s)default 0.5

Total width around each reference boundary that isn't scored (half on each side); NIST's ±0.25 s is 0.5.

Skip overlapping speechdefault off

Leave out the times when the reference has two or more speakers at once.

Advanced

Window (s)default 1.5

Length of the speech windows embedded one by one; longer is steadier but blurs quick turns.

Window step (s)default 0.75

Time between window starts; boundaries fall halfway between window centers.

Speech within (dB of the loudest)default 35

A 25-ms frame counts as speech when it is within this many dB of the recording's loudest frame.

Shortest speech (s)default 0.25

Shorter bursts of sound are ignored.

Shortest pause (s)default 0.3

Shorter pauses are filled so one turn isn't cut in two.

Seconds read per filedefault 600

Only the first part of each file is diarized.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • One speaker at a timeNot checked from data: state why it holds

    Each moment gets one speaker; overlapping speech is an error against references that mark it.

  • Number of speakersNot checked from data: state why it holds

    An estimated count depends on the similarity setting; give the number when you know it.

  • Voices identify peopleNot checked from data: state why it holds

    The speaker embeddings used for clustering stay in memory and are never saved; speaker names are per recording.

What it reports

n_rows
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_files
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_diarized
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_unreadable
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_no_path
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
audio_seconds
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
speech_seconds
Finding when someone speaks; here a 25-ms frame is speech when it is within a set number of dB of the loudest frame.
n_segments
Splitting a recording into segments by speaker (S1, S2, …), with talk time and speaker changes.
n_windows
Finding when someone speaks; here a 25-ms frame is speech when it is within a set number of dB of the loudest frame.
mean_speakers
Splitting a recording into segments by speaker (S1, S2, …), with talk time and speaker changes.
max_speakers_found
Splitting a recording into segments by speaker (S1, S2, …), with talk time and speaker changes.
n_turns
Splitting a recording into segments by speaker (S1, S2, …), with talk time and speaker changes.
collar
(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping.
n_scored_files
(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping.
der
(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping.
der_miss
(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping.
der_false_alarm
(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping.
der_confusion
(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping.
der_scored_seconds
(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping.

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, torch, safetensors, codesplash; R uses torch, jsonlite, nanoparquet, codesplashr.

Default traps between the two languages

  • Voice activity, windows and segment boundaries are exact arithmetic on the same samples; the ECAPA embeddings agree to about 1e-14 and are clustered on cosine distances rounded to 1e-12, so both engines find the same speakers and segments; the error rate comes from the shared interval twin.
Python

The exact script CodeSplash ran for example “Conversations reference” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Who spoke when (speaker diarization)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.diarize 1.0.1 · spec a92eda9a5f1bbd1b
# Dataset: aud3_conversations (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd
import torch

import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import diarize as dz  # voice activity, windows, clustering, segments (twin: codesplashr cs_diarize_*)
from codesplash.audio import ecapa  # ECAPA-TDNN speaker embeddings (twin: codesplashr cs_ecapa_*)
from codesplash.evaluate import intervals  # diarization error rate (twin: codesplashr cs_eval_der)
from codesplash.graph import dataset_option  # the reference table of the `reference` option, written by the host

# %% Audio files listed in the path column
PATH = "path"
N_SPEAKERS = None  # None: estimated from the similarity
SIMILARITY = 0.5
MAX_SPEAKERS = int(10)
WIN, STEP = 1.5, 0.75
VAD_DB, MIN_SPEECH, MIN_GAP = 35, 0.25, 0.3
COLLAR = 0.5
SKIP_OVERLAP = False
REF = {"file": "file", "start": "start",
       "end": "end", "speaker": "speaker"}
SR = 16000
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud3_conversations.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud3_conversations.parquet", columns=[PATH])
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
paths = [None if (pd.isna(p) or not str(p).strip()) else str(p) for p in df[PATH].tolist()]  # None, NaN, pd.NA: no path
if all(p is None for p in paths):
    cs.cs_error("CS_E_ALL_MISSING", column=PATH)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":600,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.diarize/conversations-reference/out-python", df, "tests/parity/fixtures/aud3_conversations.parquet")
media_ids = cs_media.ids_of(media, df)
if media.get("root") is None:
    media["root"] = DATA_DIR  # outside the app, relative paths start next to the data file
warnings = []
status = cs_media.status(media, [m if p is not None else None for m, p in zip(media_ids, paths)])
ok = [i for i, (p, s) in enumerate(zip(paths, status)) if p is not None and s is None]
n_no_path = sum(p is None for p in paths)
unreadable = [i for i, (p, s) in enumerate(zip(paths, status)) if p is not None and s is not None]
if not ok:
    i = unreadable[0]
    cs.cs_error("CS_E_MEDIA_DECODE", file=paths[i], reason=status[i])
if n_no_path:
    warnings.append(f"{n_no_path} rows have no file path and are left out.")
if unreadable:
    warnings.append(f"{len(unreadable)} files couldn't be decoded and are left out (first: {paths[unreadable[0]]}: {status[unreadable[0]]}).")

# %% Who spoke when: voice activity → windows → ECAPA embeddings (kept in memory) → clustering → segments
torch.set_num_threads(1)
model = ecapa.load(ecapa.locate())
progress = cs.progress(f"Diarizing {len(ok)} recordings", total=len(ok))
files, segs = [], []
for k, i in enumerate(ok):
    x = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
    regions = dz.vad(x, SR, VAD_DB, -60.0, MIN_SPEECH, MIN_GAP)
    wins = dz.windows(regions, WIN, STEP)
    if wins:
        clips = [x[slice(*dz.sample_range(s, e, SR, x.size))] for s, e, _ in wins]
        E = ecapa.embed(model, clips)
        labels = dz.ahc(E, N_SPEAKERS, SIMILARITY, MAX_SPEAKERS)
        del E  # speaker embeddings are biometric: never saved or shown
        fs = dz.segments(regions, wins, labels)
    else:
        fs = []
    n_spk = (max(s[2] for s in fs) + 1) if fs else 0
    talk = dz.talk_time(fs, n_spk)
    files.append({"row": i, "path": paths[i], "seconds": x.size / SR, "speech": float(sum(e - s for s, e, _ in fs)), "windows": len(wins),
                  "speakers": n_spk, "turns": dz.turns(fs), "talk": talk, "segs": fs})
    for s, e, spk in fs:
        segs.append({"row": i, "media_id": media_ids[i], "path": paths[i], "start": s, "end": e, "duration": e - s, "speaker": f"S{spk + 1}"})
    progress.update(k + 1)
progress.done()
if not segs:
    warnings.append("No speech was found: every frame is quieter than the voice-activity threshold allows.")

# %% Against reference turns (diarization error rate)
der_rows, totals = [], None
if REF is not None:
    ref = dataset_option("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-python", "reference")
    if ref is None or not len(ref):
        warnings.append("The reference table is empty; no error rate was computed.")
    else:
        keyset = {}
        for f in files:
            for key in (f["path"], os.path.basename(f["path"]), media_ids[f["row"]]):
                keyset.setdefault(str(key), f)
        rkeys = ref[REF["file"]].astype(str).tolist()
        matched = {}
        for j, rk in enumerate(rkeys):
            f = keyset.get(rk) or keyset.get(os.path.basename(rk))
            if f is not None:
                matched.setdefault(f["row"], []).append(j)
        if not matched:
            warnings.append(f"No reference row names a diarized file ({REF['file']} should hold the file path, its name or its media id).")
        tot = {"total": 0.0, "miss": 0.0, "false_alarm": 0.0, "confusion": 0.0}
        for f in files:
            js = matched.get(f["row"])
            if not js:
                continue
            r = [(float(ref[REF["start"]].iloc[j]), float(ref[REF["end"]].iloc[j]), str(ref[REF["speaker"]].iloc[j])) for j in js]
            h = [(s, e, f"S{spk + 1}") for s, e, spk in f["segs"]]
            d = intervals.der(r, h, COLLAR, SKIP_OVERLAP)
            for key in tot:
                tot[key] += float(d[key])
            der_rows.append({"file": f["path"], "scored": d["total"], "miss": d["miss"], "false_alarm": d["false_alarm"], "confusion": d["confusion"],
                             "der": d["der"], "ref_speakers": len(d["ref_speakers"]), "hyp_speakers": len(d["hyp_speakers"])})
        if der_rows:
            totals = tot
            totals["der"] = (tot["miss"] + tot["false_alarm"] + tot["confusion"]) / tot["total"] if tot["total"] > 0 else None

# %% Artifact: one row per segment (who spoke when; no embeddings)
out = csml.out_dir("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-python")
seg_df = pd.DataFrame(segs, columns=["row", "media_id", "path", "start", "end", "duration", "speaker"])
seg_df["row"] = seg_df["row"].astype(np.int64)
seg_df.to_parquet(os.path.join(out, "segments.parquet"), index=False)

# %% Assumptions
assumptions = [
    {"key": "overlap", "label": "One speaker at a time", "status": "info",
     "detail": "Each moment gets one speaker; overlapping speech counts as an error against references that mark it."},
    {"key": "speaker_count", "label": "Number of speakers", "status": "info",
     "detail": (f"Fixed at {N_SPEAKERS} per recording." if N_SPEAKERS is not None else
                f"Estimated per recording: groups merge while their average similarity is at least {SIMILARITY:g} (at most {MAX_SPEAKERS}). Set the number when you know it.")},
    {"key": "biometric", "label": "Voices identify people", "status": "info",
     "detail": "The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording."},
]

# %% Result
speech = float(sum(f["speech"] for f in files))
values = {"n_rows": len(df), "n_files": len(ok) + len(unreadable), "n_diarized": len(ok), "n_unreadable": len(unreadable), "n_no_path": n_no_path,
          "audio_seconds": float(sum(f["seconds"] for f in files)), "speech_seconds": speech, "n_segments": len(segs),
          "n_windows": int(sum(f["windows"] for f in files)), "mean_speakers": float(np.mean([f["speakers"] for f in files])),
          "max_speakers_found": int(max(f["speakers"] for f in files)), "n_turns": int(sum(f["turns"] for f in files)),
          "collar": COLLAR, "n_scored_files": len(der_rows),
          "der": totals["der"] if totals else None, "der_miss": totals["miss"] if totals else None,
          "der_false_alarm": totals["false_alarm"] if totals else None, "der_confusion": totals["confusion"] if totals else None,
          "der_scored_seconds": totals["total"] if totals else None}
talk_rows = []
for f in files:
    for s_i, t in enumerate(f["talk"]):
        talk_rows.append({"file": f["path"], "speaker": f"S{s_i + 1}", "seconds": float(t), "share": float(t / f["speech"]) if f["speech"] > 0 else None})
tables = [
    {"key": "segments", "title": "Who spoke when", "columns": [
        {"key": "path", "label": PATH, "type": "string"}, {"key": "start", "label": "Start (s)", "type": "number"},
        {"key": "end", "label": "End (s)", "type": "number"}, {"key": "duration", "label": "Seconds", "type": "number"},
        {"key": "speaker", "label": "Speaker", "type": "string"}],
     "rows": [{k: s[k] for k in ("path", "start", "end", "duration", "speaker")} for s in segs[:1000]],
     "note": "First 1,000 segments." if len(segs) > 1000 else None},
    {"key": "talk_time", "title": "Talk time per speaker", "columns": [
        {"key": "file", "label": PATH, "type": "string"}, {"key": "speaker", "label": "Speaker", "type": "string"},
        {"key": "seconds", "label": "Seconds", "type": "number"}, {"key": "share", "label": "Share of speech", "type": "number"}],
     "rows": talk_rows[:1000]},
]
if der_rows:
    tables.append({"key": "der", "title": f"Diarization error rate (collar {COLLAR:g} s{', overlap not scored' if SKIP_OVERLAP else ''})", "columns": [
        {"key": "file", "label": PATH, "type": "string"}, {"key": "scored", "label": "Scored seconds", "type": "number"},
        {"key": "miss", "label": "Missed speech (s)", "type": "number"}, {"key": "false_alarm", "label": "False alarm (s)", "type": "number"},
        {"key": "confusion", "label": "Wrong speaker (s)", "type": "number"}, {"key": "der", "label": "DER", "type": "number"},
        {"key": "ref_speakers", "label": "Reference speakers", "type": "integer"}, {"key": "hyp_speakers", "label": "Found speakers", "type": "integer"}],
        "rows": der_rows})
charts = []
for f in files[:4]:
    if not f["segs"]:
        continue
    lanes = [f"S{s_i + 1}" for s_i in range(f["speakers"])]
    charts.append(cs.chart(f"timeline-{f['row'] + 1}", "segment-timeline", f"Who spoke when: {os.path.basename(f['path'])}", {
        "start": cs.col("Start (s)", [s for s, _, _ in f["segs"]]),
        "end": cs.col("End (s)", [e for _, e, _ in f["segs"]]),
        "lane": cs.col("Speaker", [f"S{k + 1}" for _, _, k in f["segs"]], "categorical", levels=lanes)},
        controls={"labels": False, "overlap": True}))
summary = (f"{len(ok)} recording{'s' if len(ok) != 1 else ''} ({values['audio_seconds']:.1f} s, {speech:.1f} s of speech) split into "
           f"{len(segs)} segments with {values['max_speakers_found']} speaker{'s' if values['max_speakers_found'] != 1 else ''} at most per recording "
           f"and {values['n_turns']} changes of speaker.")
if totals and totals["der"] is not None:
    summary += f" Against the reference turns, the diarization error rate is {100 * totals['der']:.1f}% (collar {COLLAR:g} s)."
cs.publish({
    "method": "audio.diarize",
    "methodVersion": "1.0.1",
    "title": "Who spoke when",
    "engine": cs.engine_info("numpy", "torch"),
    "n": len(ok),
    "summary": summary,
    "statistics": [{"key": "n_segments", "label": "Segments", "value": len(segs), "format": "integer"},
                   {"key": "max_speakers_found", "label": "Most speakers in a recording", "value": values["max_speakers_found"], "format": "integer"}]
                  + ([{"key": "der", "label": "DER", "value": totals["der"], "format": "percent"}] if totals and totals["der"] is not None else []),
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Energy voice activity (within {VAD_DB:g} dB of the loudest 25-ms frame), {WIN:g}-s windows every {STEP:g} s, ECAPA-TDNN speaker "
              "embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway "
              "between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm "
              "+ wrong speaker) / reference speech, with the best one-to-one speaker mapping."],
    "charts": charts,
    "artifacts": [{"key": "segments", "path": os.path.join(out, "segments.parquet"), "format": "parquet"}],
    "values": values,
})
R

The exact script CodeSplash ran for example “Conversations reference” · R version 4.5.1 (2025-06-13)

# Who spoke when (speaker diarization)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.diarize 1.0.1 · spec a92eda9a5f1bbd1b
# Dataset: aud3_conversations (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_diarize_* (voice activity, windows, clustering, segments), cs_ecapa_* (embeddings), cs_eval_der

# %% Audio files listed in the path column
PATH <- "path"
N_SPEAKERS <- NULL  # NULL: estimated from the similarity
SIMILARITY <- 0.5
MAX_SPEAKERS <- as.integer(10)
WIN <- 1.5
STEP <- 0.75
VAD_DB <- 35
MIN_SPEECH <- 0.25
MIN_GAP <- 0.3
COLLAR <- 0.5
SKIP_OVERLAP <- FALSE
REF <- list(file = "file", start = "start",
            end = "end", speaker = "speaker")
SR <- 16000
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_conversations.parquet"))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud3_conversations.parquet", col_select = PATH))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
paths <- as.character(df[[PATH]])
paths[is.na(paths) | !nzchar(trimws(paths))] <- NA_character_
if (all(is.na(paths))) cs_error("CS_E_ALL_MISSING", column = PATH)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":600,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.diarize/conversations-reference/out-r", df,
                        "tests/parity/fixtures/aud3_conversations.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root)) media$root <- DATA_DIR  # outside the app, relative paths start next to the data file
warnings <- character(0)
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, media_ids))
ok <- which(!is.na(paths) & is.na(status))
n_no_path <- sum(is.na(paths))
unreadable <- which(!is.na(paths) & !is.na(status))
if (!length(ok)) cs_error("CS_E_MEDIA_DECODE", file = paths[unreadable[1]], reason = status[unreadable[1]])
if (n_no_path > 0) warnings <- c(warnings, sprintf("%d rows have no file path and are left out.", n_no_path))
if (length(unreadable)) warnings <- c(warnings, sprintf("%d files couldn't be decoded and are left out (first: %s: %s).",
                                                        length(unreadable), paths[unreadable[1]], status[unreadable[1]]))

# %% Who spoke when: voice activity -> windows -> ECAPA embeddings (kept in memory) -> clustering -> segments
torch::torch_set_num_threads(1L)
model <- cs_ecapa_load(cs_ecapa_locate())
progress <- cs_progress(sprintf("Diarizing %d recordings", length(ok)), total = length(ok))
files <- list()
seg_rows <- list()
for (k in seq_along(ok)) {
  i <- ok[k]
  x <- as.numeric(cs_media_audio(media, media_ids[i])[[1]])
  regions <- cs_diarize_vad(x, SR, VAD_DB, -60, MIN_SPEECH, MIN_GAP)
  wins <- cs_diarize_windows(regions, WIN, STEP)
  if (nrow(wins) > 0) {
    clips <- lapply(seq_len(nrow(wins)), function(w) {
      r <- cs_diarize_sample_range(wins$start[w], wins$end[w], SR, length(x))
      x[r[1]:r[2]]
    })
    E <- cs_ecapa_embed(model, clips)
    labels <- cs_diarize_ahc(E, N_SPEAKERS, SIMILARITY, MAX_SPEAKERS)
    rm(E)  # speaker embeddings are biometric: never saved or shown
    fs <- cs_diarize_segments(regions, wins, labels)
  } else {
    fs <- data.frame(start = numeric(0), end = numeric(0), speaker = integer(0))
  }
  n_spk <- if (nrow(fs)) max(fs$speaker) + 1L else 0L
  files[[k]] <- list(row = i, path = paths[i], seconds = length(x) / SR, speech = sum(fs$end - fs$start), windows = nrow(wins),
                     speakers = n_spk, turns = cs_diarize_turns(fs), talk = cs_diarize_talk_time(fs, n_spk), segs = fs)
  for (q in seq_len(nrow(fs))) seg_rows[[length(seg_rows) + 1L]] <- list(row = as.integer(i - 1L), media_id = media_ids[i], path = paths[i],
    start = fs$start[q], end = fs$end[q], duration = fs$end[q] - fs$start[q], speaker = sprintf("S%d", fs$speaker[q] + 1L))
  cs_progress_update(progress, k)
}
cs_progress_done(progress)
if (!length(seg_rows)) warnings <- c(warnings, "No speech was found: every frame is quieter than the voice-activity threshold allows.")

# %% Against reference turns (diarization error rate)
der_rows <- list()
totals <- NULL
if (!is.null(REF)) {
  ref <- cs_graph_dataset_option("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-r", "reference")
  if (is.null(ref) || nrow(ref) == 0) {
    warnings <- c(warnings, "The reference table is empty; no error rate was computed.")
  } else {
    keys <- character(0)
    owners <- integer(0)
    for (k in seq_along(files)) {
      f <- files[[k]]
      for (key in c(f$path, basename(f$path), media_ids[f$row])) if (!(key %in% keys)) {
        keys <- c(keys, key)
        owners <- c(owners, k)
      }
    }
    rkeys <- as.character(ref[[REF$file]])
    matched <- vector("list", length(files))
    for (j in seq_along(rkeys)) {
      hit <- match(rkeys[j], keys)
      if (is.na(hit)) hit <- match(basename(rkeys[j]), keys)
      if (!is.na(hit)) matched[[owners[hit]]] <- c(matched[[owners[hit]]], j)
    }
    if (all(vapply(matched, is.null, logical(1)))) {
      warnings <- c(warnings, sprintf("No reference row names a diarized file (%s should hold the file path, its name or its media id).", REF$file))
    }
    tot <- c(total = 0, miss = 0, false_alarm = 0, confusion = 0)
    for (k in seq_along(files)) {
      js <- matched[[k]]
      if (is.null(js)) next
      f <- files[[k]]
      r <- data.frame(start = as.numeric(ref[[REF$start]][js]), end = as.numeric(ref[[REF$end]][js]),
                      speaker = as.character(ref[[REF$speaker]][js]), stringsAsFactors = FALSE)
      h <- data.frame(start = f$segs$start, end = f$segs$end, speaker = sprintf("S%d", f$segs$speaker + 1L), stringsAsFactors = FALSE)
      d <- cs_eval_der(r, h, collar = COLLAR, skip_overlap = SKIP_OVERLAP)
      for (key in names(tot)) tot[[key]] <- tot[[key]] + as.numeric(d[[key]])
      der_rows[[length(der_rows) + 1L]] <- list(file = f$path, scored = d$total, miss = d$miss, false_alarm = d$false_alarm,
                                                 confusion = d$confusion, der = d$der, ref_speakers = length(d$ref_speakers),
                                                 hyp_speakers = length(d$hyp_speakers))
    }
    if (length(der_rows)) {
      totals <- as.list(tot)
      totals$der <- if (tot[["total"]] > 0) (tot[["miss"]] + tot[["false_alarm"]] + tot[["confusion"]]) / tot[["total"]] else NULL
    }
  }
}

# %% Artifact: one row per segment (who spoke when; no embeddings)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.diarize/conversations-reference/out-r")
seg_df <- if (length(seg_rows)) do.call(rbind, lapply(seg_rows, as.data.frame, stringsAsFactors = FALSE)) else
  data.frame(row = integer(0), media_id = character(0), path = character(0), start = numeric(0), end = numeric(0),
             duration = numeric(0), speaker = character(0))
nanoparquet::write_parquet(seg_df, file.path(out, "segments.parquet"))

# %% Assumptions
assumptions <- list(
  list(key = "overlap", label = "One speaker at a time", status = "info",
       detail = "Each moment gets one speaker; overlapping speech counts as an error against references that mark it."),
  list(key = "speaker_count", label = "Number of speakers", status = "info",
       detail = if (!is.null(N_SPEAKERS)) sprintf("Fixed at %d per recording.", as.integer(N_SPEAKERS)) else
         sprintf("Estimated per recording: groups merge while their average similarity is at least %s (at most %d). Set the number when you know it.",
                 format(SIMILARITY), MAX_SPEAKERS)),
  list(key = "biometric", label = "Voices identify people", status = "info",
       detail = "The speaker embeddings used for clustering stay in memory and are never saved; speaker names (S1, S2, …) are per recording.")
)

# %% Result
speech <- sum(vapply(files, function(f) f$speech, numeric(1)))
values <- list(n_rows = nrow(df), n_files = length(ok) + length(unreadable), n_diarized = length(ok), n_unreadable = length(unreadable),
               n_no_path = n_no_path, audio_seconds = sum(vapply(files, function(f) f$seconds, numeric(1))), speech_seconds = speech,
               n_segments = length(seg_rows), n_windows = sum(vapply(files, function(f) f$windows, numeric(1))),
               mean_speakers = mean(vapply(files, function(f) f$speakers, numeric(1))),
               max_speakers_found = as.integer(max(vapply(files, function(f) f$speakers, numeric(1)))),
               n_turns = as.integer(sum(vapply(files, function(f) f$turns, numeric(1)))), collar = COLLAR, n_scored_files = length(der_rows),
               der = if (!is.null(totals)) totals$der else NULL, der_miss = if (!is.null(totals)) totals$miss else NULL,
               der_false_alarm = if (!is.null(totals)) totals$false_alarm else NULL, der_confusion = if (!is.null(totals)) totals$confusion else NULL,
               der_scored_seconds = if (!is.null(totals)) totals$total else NULL)
talk_rows <- list()
for (f in files) for (s_i in seq_along(f$talk)) talk_rows[[length(talk_rows) + 1L]] <- list(file = f$path, speaker = sprintf("S%d", s_i),
  seconds = f$talk[s_i], share = if (f$speech > 0) f$talk[s_i] / f$speech else NULL)
tables <- list(
  list(key = "segments", title = "Who spoke when", columns = list(
    list(key = "path", label = PATH, type = "string"), list(key = "start", label = "Start (s)", type = "number"),
    list(key = "end", label = "End (s)", type = "number"), list(key = "duration", label = "Seconds", type = "number"),
    list(key = "speaker", label = "Speaker", type = "string")),
    rows = lapply(head(seg_rows, 1000), function(s) s[c("path", "start", "end", "duration", "speaker")]),
    note = if (length(seg_rows) > 1000) "First 1,000 segments." else NULL),
  list(key = "talk_time", title = "Talk time per speaker", columns = list(
    list(key = "file", label = PATH, type = "string"), list(key = "speaker", label = "Speaker", type = "string"),
    list(key = "seconds", label = "Seconds", type = "number"), list(key = "share", label = "Share of speech", type = "number")),
    rows = head(talk_rows, 1000))
)
if (length(der_rows)) tables[[length(tables) + 1L]] <- list(key = "der",
  title = sprintf("Diarization error rate (collar %s s%s)", format(COLLAR), if (isTRUE(SKIP_OVERLAP)) ", overlap not scored" else ""),
  columns = list(list(key = "file", label = PATH, type = "string"), list(key = "scored", label = "Scored seconds", type = "number"),
                 list(key = "miss", label = "Missed speech (s)", type = "number"), list(key = "false_alarm", label = "False alarm (s)", type = "number"),
                 list(key = "confusion", label = "Wrong speaker (s)", type = "number"), list(key = "der", label = "DER", type = "number"),
                 list(key = "ref_speakers", label = "Reference speakers", type = "integer"), list(key = "hyp_speakers", label = "Found speakers", type = "integer")),
  rows = der_rows)
charts <- list()
for (f in head(files, 4)) {
  if (!nrow(f$segs)) next
  lanes <- sprintf("S%d", seq_len(f$speakers))
  charts[[length(charts) + 1L]] <- cs_chart(sprintf("timeline-%d", f$row), "segment-timeline", sprintf("Who spoke when: %s", basename(f$path)), list(
    start = cs_col("Start (s)", f$segs$start),
    end = cs_col("End (s)", f$segs$end),
    lane = cs_col("Speaker", sprintf("S%d", f$segs$speaker + 1L), "categorical", levels = lanes)),
    controls = list(labels = FALSE, overlap = TRUE))
}
summary <- sprintf("%d recording%s (%.1f s, %.1f s of speech) split into %d segments with %d speaker%s at most per recording and %d changes of speaker.",
                   length(ok), if (length(ok) != 1) "s" else "", values$audio_seconds, speech, length(seg_rows), values$max_speakers_found,
                   if (values$max_speakers_found != 1) "s" else "", values$n_turns)
if (!is.null(totals) && !is.null(totals$der)) summary <- paste(summary, sprintf("Against the reference turns, the diarization error rate is %.1f%% (collar %s s).",
                                                                               100 * totals$der, format(COLLAR)))
statistics <- list(list(key = "n_segments", label = "Segments", value = length(seg_rows), format = "integer"),
                   list(key = "max_speakers_found", label = "Most speakers in a recording", value = values$max_speakers_found, format = "integer"))
if (!is.null(totals) && !is.null(totals$der)) statistics[[length(statistics) + 1L]] <- list(key = "der", label = "DER", value = totals$der, format = "percent")
cs_publish(list(
  method = "audio.diarize",
  methodVersion = "1.0.1",
  title = "Who spoke when",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(ok),
  summary = summary,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = as.list(warnings),
  notes = list(sprintf(paste0("Energy voice activity (within %s dB of the loudest 25-ms frame), %s-s windows every %s s, ECAPA-TDNN speaker ",
                              "embeddings by SpeechBrain (Ravanelli et al. 2021), average-linkage clustering on cosine distance, and boundaries halfway ",
                              "between window centers. The embeddings are biometric and are discarded after clustering. DER = (missed speech + false alarm ",
                              "+ wrong speaker) / reference speech, with the best one-to-one speaker mapping."), format(VAD_DB), format(WIN), format(STEP))),
  charts = charts,
  artifacts = list(list(key = "segments", path = file.path(out, "segments.parquet"), format = "parquet")),
  values = values
))

Sources

  • Anguera, X., Bozonnet, S., Evans, N., Fredouille, C., Friedland, G., & Vinyals, O. (2012). Speaker diarization: A review of recent research. IEEE TASLP, 20(2), 356–370.
  • Sell, G., & Garcia-Romero, D. (2014). Speaker diarization with PLDA i-vector scoring and unsupervised calibration. IEEE SLT Workshop, 413–417.
  • Desplanques, B., Thienpondt, J., & Demuynck, K. (2020). ECAPA-TDNN: Emphasized channel attention, propagation and aggregation in TDNN based speaker verification. Proceedings of Interspeech, 3830–3834.
  • Bredin, H. (2017). pyannote.metrics: a toolkit for reproducible evaluation, diagnostic, and error analysis of speaker diarization systems. Proceedings of Interspeech, 3587–3591.
  • NIST (2009). The 2009 (RT-09) Rich Transcription meeting recognition evaluation plan (diarization error rate).

From the CodeSplash method registry · audio.diarize v1.0.1.