Voices: compare speakers and find who spoke when
Turn recordings into speaker embeddings, compare voices and score how well they separate known speakers, then split conversations into speaker turns and score them with the diarization error rate. Speaker embeddings are biometric data.
What runs in CodeSplash
- Compare voices (speaker embeddings) Experimental
- Who spoke when (speaker diarization) Experimental
You will be able to
- Explain what a speaker embedding captures and why it is biometric data
- Read voice similarities, voice groups and the equal error rate of same-speaker pairs
- Diarize a conversation (voice activity, windows, clustering) and score it with the diarization error rate and its collar
A vector for a voice
ReadA speaker embeddingSpeaker embeddingA vector (192 values from ECAPA-TDNN) that is close for recordings of the same voice, whatever is said. Biometric data. is a list of numbers (192 here, from the ECAPA-TDNN model SpeechBrain trained on VoxCeleb interviews) that comes out close for two recordings of the same voice, whatever is said. That makes it a voiceprint: it can identify a person, so it is biometric dataBiometric dataData that can identify a person by their body or behavior, such as a speaker embedding. It never goes to an AI provider.. The app keeps such results on this computer and out of every AI feature, marks saved embeddings as biometric, and lists them in Erase everywhere. Get consent before comparing other people's voices.
The examples use six clips of three synthetic voices (a formant synthesizer: no real person) and two synthetic conversations.
Make a guess
PredictPredict first
Each synthetic voice has two clips. Every pair of the six clips becomes a trial: same voice or not. What equal error rate do you expect?
Reveal
It is 0.0%: the three voices differ in pitch and vocal-tract length, so every same-voice pair is more similar than every different-voice pair. Real recordings are much harder.
Comparing voices
Read6 recordings were turned into 192-value speaker embeddings and fell into 3 voice groups at cosine similarity 0.5. Among 3 same-speaker and 12 different-speaker pairs, the equal error rate was 0.0% and the closest other file had the same speaker 100% of the time.
- Voice groups
- 3
- Mean similarity to the closest file
- 0.6686
- EER
- 0.0%
Plots
View data
| File | Similarity | File | Cosine similarity |
|---|---|---|---|
| 1. ana_1.wav | 1.00 | 1. ana_1.wav | 1 |
| 2. ana_2.wav | 0.76 | 1. ana_1.wav | 0.7616 |
| 3. ben_1.wav | 0.28 | 1. ana_1.wav | 0.2784 |
| 4. ben_2.wav | 0.32 | 1. ana_1.wav | 0.3230 |
| 5. cal_1.wav | 0.48 | 1. ana_1.wav | 0.4774 |
| 6. cal_2.wav | 0.41 | 1. ana_1.wav | 0.4109 |
| 1. ana_1.wav | 0.76 | 2. ana_2.wav | 0.7616 |
| 2. ana_2.wav | 1.00 | 2. ana_2.wav | 1 |
| 3. ben_1.wav | 0.33 | 2. ana_2.wav | 0.3310 |
| 4. ben_2.wav | 0.35 | 2. ana_2.wav | 0.3481 |
| 5. cal_1.wav | 0.48 | 2. ana_2.wav | 0.4788 |
| 6. cal_2.wav | 0.45 | 2. ana_2.wav | 0.4478 |
| 1. ana_1.wav | 0.28 | 3. ben_1.wav | 0.2784 |
| 2. ana_2.wav | 0.33 | 3. ben_1.wav | 0.3310 |
| 3. ben_1.wav | 1.00 | 3. ben_1.wav | 1 |
| 4. ben_2.wav | 0.66 | 3. ben_1.wav | 0.6615 |
| 5. cal_1.wav | 0.46 | 3. ben_1.wav | 0.4587 |
| 6. cal_2.wav | 0.42 | 3. ben_1.wav | 0.4151 |
| 1. ana_1.wav | 0.32 | 4. ben_2.wav | 0.3230 |
| 2. ana_2.wav | 0.35 | 4. ben_2.wav | 0.3481 |
| 3. ben_1.wav | 0.66 | 4. ben_2.wav | 0.6615 |
| 4. ben_2.wav | 1.00 | 4. ben_2.wav | 1 |
| 5. cal_1.wav | 0.57 | 4. ben_2.wav | 0.5736 |
| 6. cal_2.wav | 0.50 | 4. ben_2.wav | 0.4951 |
| 1. ana_1.wav | 0.48 | 5. cal_1.wav | 0.4774 |
| 2. ana_2.wav | 0.48 | 5. cal_1.wav | 0.4788 |
| 3. ben_1.wav | 0.46 | 5. cal_1.wav | 0.4587 |
| 4. ben_2.wav | 0.57 | 5. cal_1.wav | 0.5736 |
| 5. cal_1.wav | 1.00 | 5. cal_1.wav | 1 |
| 6. cal_2.wav | 0.58 | 5. cal_1.wav | 0.5826 |
| 1. ana_1.wav | 0.41 | 6. cal_2.wav | 0.4109 |
| 2. ana_2.wav | 0.45 | 6. cal_2.wav | 0.4478 |
| 3. ben_1.wav | 0.42 | 6. cal_2.wav | 0.4151 |
| 4. ben_2.wav | 0.50 | 6. cal_2.wav | 0.4951 |
| 5. cal_1.wav | 0.58 | 6. cal_2.wav | 0.5826 |
| 6. cal_2.wav | 1.00 | 6. cal_2.wav | 1 |
View data
| Miss rate (same speaker rejected) | False alarm rate (different speakers accepted) |
|---|---|
| 0 | 1 |
| 0 | 0.9167 |
| 0 | 0.8333 |
| 0 | 0.7500 |
| 0 | 0.6667 |
| 0 | 0.5833 |
| 0 | 0.5000 |
| 0 | 0.4167 |
| 0 | 0.3333 |
| 0 | 0.2500 |
| 0 | 0.1667 |
| 0 | 0.0833 |
| 0 | 0 |
| 0.3333 | 0 |
| 0.6667 | 0 |
View data
| Pair | Cosine similarity |
|---|---|
| Same speaker | 0.7616 |
| Different speakers | 0.2784 |
| Different speakers | 0.3230 |
| Different speakers | 0.4774 |
| Different speakers | 0.4109 |
| Different speakers | 0.3310 |
| Different speakers | 0.3481 |
| Different speakers | 0.4788 |
| Different speakers | 0.4478 |
| Same speaker | 0.6615 |
| Different speakers | 0.4587 |
| Different speakers | 0.4151 |
| Different speakers | 0.5736 |
| Different speakers | 0.4951 |
| Same speaker | 0.5826 |
Assumptions
- Voices identify people — Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices.
- One speaker per file — Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations.
- Recordings like VoxCeleb — The model learned from interview speech; shortest file 1.50 s.
Voices
| path | Seconds | Voice group | Most similar file | Cosine similarity | speaker |
|---|---|---|---|---|---|
| media/aud3/ana_1.wav | 1.500 | V1 | ana_2.wav | 0.7616 | ana |
| media/aud3/ana_2.wav | 1.500 | V1 | ana_1.wav | 0.7616 | ana |
| media/aud3/ben_1.wav | 1.500 | V2 | ben_2.wav | 0.6615 | ben |
| media/aud3/ben_2.wav | 1.500 | V2 | ben_1.wav | 0.6615 | ben |
| media/aud3/cal_1.wav | 1.500 | V3 | cal_2.wav | 0.5826 | cal |
| media/aud3/cal_2.wav | 1.500 | V3 | cal_1.wav | 0.5826 | cal |
Same speaker or not: every pair of files with a known speaker
| Measure | Value |
|---|---|
| Target pairs (same speaker) | 3 |
| Non-target pairs | 12 |
| Mean similarity, same speaker | 0.6686 |
| Mean similarity, different speakers | 0.4198 |
| Equal error rate | 0 |
| Minimum DCF (π = 0.01) | 0 |
| Closest-file speaker accuracy | 1 |
- ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare voices (speaker embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.speakers 1.0.0 · spec 0256aeda2cef25d2
# Dataset: aud3_voices (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ecapa_* (ECAPA-TDNN), cs_diarize_ahc (grouping), cs_verif_* (EER, DCF)
# %% Audio files listed in the path column
PATH <- "path"
SPEAKER <- "speaker"
N_GROUPS <- NULL # NULL: grouped by the similarity threshold
SIMILARITY <- 0.5
P_TARGET <- 0.01
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_voices.parquet"))
df <- nanoparquet::read_parquet("tests/parity/fixtures/aud3_voices.parquet", col_select = if (is.null(SPEAKER)) PATH else c(PATH, SPEAKER))
df <- as.data.frame(df)
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\":60,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-r", df,
"tests/parity/fixtures/aud3_voices.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)
ids_for <- ifelse(is.na(paths), NA_character_, media_ids)
status <- cs_media_status(media, ids_for)
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 (length(ok) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Comparing voices", min = 2, n = length(ok))
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]]))
# %% Speaker embeddings (ECAPA-TDNN, float64 on one thread: the Parity profile). Biometric: kept out of AI.
torch::torch_set_num_threads(1L)
model <- cs_ecapa_load(cs_ecapa_locate())
progress <- cs_progress(sprintf("Embedding %d voices", length(ok)), total = length(ok))
secs <- numeric(length(ok))
E <- matrix(0, nrow = length(ok), ncol = as.integer(model$config$lin_neurons))
for (k in seq_along(ok)) {
clip <- as.numeric(cs_media_audio(media, media_ids[ok[k]])[[1]])
secs[k] <- length(clip) / 16000
E[k, ] <- cs_ecapa_embed(model, list(clip))[1, ]
cs_progress_update(progress, k)
}
cs_progress_done(progress)
S <- cs_ecapa_cosine(E, E)
# %% Voice groups (average linkage on cosine distance) and each file's closest other file
labels <- cs_diarize_ahc(E, n_speakers = N_GROUPS, similarity = SIMILARITY, max_speakers = length(ok))
n_groups <- max(labels) + 1L
names_ <- basename(paths[ok])
near <- character(length(ok))
near_sim <- numeric(length(ok))
for (k in seq_along(ok)) {
row <- S[k, ]
row[k] <- -Inf
j <- which.max(row)
near[k] <- names_[j]
near_sim[k] <- S[k, j]
}
# %% Known speakers: every pair of files is a trial (same speaker or not)
spk <- NULL
trial <- NULL
nn_acc <- NULL
if (!is.null(SPEAKER)) {
spk <- as.character(df[[SPEAKER]])
lab <- spk[ok]
# Every pair a < b of files whose speakers are known, in the order a, then b, built in one pass (growing the two
# vectors pair by pair copied them once per pair: hours at the row cap).
k <- length(ok)
pa <- rep.int(seq_len(k), k - seq_len(k))
pb <- as.integer(unlist(lapply(seq_len(k), function(a) if (a < k) (a + 1L):k else integer(0)), use.names = FALSE))
known <- !is.na(lab[pa]) & !is.na(lab[pb])
pa <- pa[known]
pb <- pb[known]
sc <- as.numeric(S[cbind(pa, pb)])
same <- lab[pa] == lab[pb]
if (any(same) && any(!same)) {
trial <- cs_verif_summary(sc, same, P_TARGET, 1, 1, "linear")
trial$mean_target <- mean(sc[same])
trial$mean_nontarget <- mean(sc[!same])
trial$pts <- cs_verif_det_points(sc, same)
trial$scores <- sc
trial$same <- same
} else {
warnings <- c(warnings, "Known speakers need at least two files of one speaker and two different speakers for verification scores.")
}
hits <- 0L
n_id <- 0L
for (a in seq_along(ok)) {
if (is.na(lab[a]) || sum(seq_along(ok) != a & !is.na(lab) & lab == lab[a]) == 0) next
row <- vapply(seq_along(ok), function(b) if (b != a && !is.na(lab[b])) S[a, b] else -Inf, numeric(1))
j <- which.max(row)
hits <- hits + as.integer(lab[j] == lab[a])
n_id <- n_id + 1L
}
nn_acc <- if (n_id > 0) hits / n_id else NULL
}
# %% Artifact: one row per embedded file (biometric — never shared with AI)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-r")
art <- data.frame(row = as.integer(ok - 1L), media_id = media_ids[ok], path = paths[ok], voice_group = sprintf("V%d", labels + 1L),
stringsAsFactors = FALSE)
for (d in seq_len(ncol(E))) art[[sprintf("emb_%d", d)]] <- E[, d]
nanoparquet::write_parquet(art, file.path(out, "speakers.parquet"))
# %% Assumptions
assumptions <- list(
list(key = "biometric", label = "Voices identify people", status = "info",
detail = "Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices."),
list(key = "one_speaker", label = "One speaker per file", status = "info",
detail = "Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations."),
list(key = "domain", label = "Recordings like VoxCeleb", status = if (min(secs) < 1) "warn" else "pass",
detail = paste0(sprintf("The model learned from interview speech; shortest file %.2f s", min(secs)),
if (min(secs) < 1) "; below about 1 s the embeddings are unreliable." else "."))
)
# %% Result
values <- list(n_rows = nrow(df), n_files = length(ok) + length(unreadable), n_embedded = length(ok), n_unreadable = length(unreadable),
n_no_path = n_no_path, audio_seconds = sum(secs), dim = ncol(E), n_groups = n_groups,
similarity_threshold = if (is.null(N_GROUPS)) SIMILARITY else NULL, mean_nearest_similarity = mean(near_sim), p_target = P_TARGET,
n_target_trials = if (!is.null(trial)) as.integer(trial$n_target) else NULL,
n_nontarget_trials = if (!is.null(trial)) as.integer(trial$n_nontarget) else NULL,
mean_target_similarity = if (!is.null(trial)) trial$mean_target else NULL,
mean_nontarget_similarity = if (!is.null(trial)) trial$mean_nontarget else NULL,
eer = if (!is.null(trial)) trial$eer else NULL, min_dcf = if (!is.null(trial)) trial$min_dcf else NULL, nn_accuracy = nn_acc)
file_rows <- lapply(seq_along(ok), function(k) {
r <- list(file = paths[ok[k]], seconds = secs[k], voice_group = sprintf("V%d", labels[k] + 1L), nearest = near[k], similarity = near_sim[k])
if (!is.null(spk)) r$speaker <- spk[ok[k]]
r
})
cols <- list(list(key = "file", label = PATH, type = "string"), list(key = "seconds", label = "Seconds", type = "number"),
list(key = "voice_group", label = "Voice group", type = "string"), list(key = "nearest", label = "Most similar file", type = "string"),
list(key = "similarity", label = "Cosine similarity", type = "number"))
if (!is.null(spk)) cols[[length(cols) + 1L]] <- list(key = "speaker", label = SPEAKER, type = "string")
tables <- list(list(key = "files", title = "Voices", columns = cols, rows = head(file_rows, 500),
note = if (length(file_rows) > 500) "First 500 files." else NULL))
if (!is.null(trial)) tables[[length(tables) + 1L]] <- list(key = "verification", title = "Same speaker or not: every pair of files with a known speaker",
columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(measure = "Target pairs (same speaker)", value = trial$n_target),
list(measure = "Non-target pairs", value = trial$n_nontarget),
list(measure = "Mean similarity, same speaker", value = trial$mean_target),
list(measure = "Mean similarity, different speakers", value = trial$mean_nontarget),
list(measure = "Equal error rate", value = trial$eer),
list(measure = sprintf("Minimum DCF (π = %s)", format(P_TARGET)), value = trial$min_dcf),
list(measure = "Closest-file speaker accuracy", value = nn_acc)))
m <- min(length(ok), 40L)
lv <- sprintf("%d. %s", seq_len(m), names_[seq_len(m)])
ia <- rep(seq_len(m), each = m)
ib <- rep(seq_len(m), times = m)
charts <- list(cs_chart("similarity", "matrix-heatmap", paste0("Voice similarity (cosine)", if (length(ok) > 40) " — first 40 files" else ""), list(
row = cs_col("File", lv[ia], "categorical", levels = lv),
col = cs_col("File", lv[ib], "categorical", levels = lv),
value = cs_col("Cosine similarity", S[cbind(ia, ib)]),
label = cs_col("Similarity", sprintf("%.2f", S[cbind(ia, ib)]), "categorical")),
controls = list(scale = "sequential")))
scores_note <- list()
if (!is.null(trial)) {
pts <- trial$pts
inner <- which(is.finite(pts$threshold))
keep <- inner[cs_verif_thin(length(inner))]
charts[[length(charts) + 1L]] <- cs_chart("det", "det-curve", "Detection error tradeoff of the voice comparisons", list(
fpr = cs_col("False alarm rate (different speakers accepted)", pts$fpr[keep]),
fnr = cs_col("Miss rate (same speaker rejected)", pts$fnr[keep])),
controls = list(eer = trial$eer, minDcf = trial$min_dcf, minDcfFpr = trial$min_dcf_fpr, minDcfFnr = trial$min_dcf_fnr))
# Every pair up to 20,000; above that a seeded sample within each kind of pair (Python draws the same pairs). The EER,
# detection costs and DET curve above use every pair.
shown <- cs_verif_chart_sample(trial$same, 20000L, seed = 1L)
n_pairs <- length(trial$same)
big <- function(x) formatC(x, format = "d", big.mark = ",")
if (length(shown) < n_pairs) scores_note <- list(paste0(sprintf("The similarity chart draws a seeded sample of %s of the %s pairs (the rarer kind keeps ",
big(length(shown)), big(n_pairs)),
"up to half of it, so both curves keep their shape; the same pairs in Python and R). The equal error rate, ",
"the detection costs and the DET curve use every pair."))
charts[[length(charts) + 1L]] <- cs_chart("scores", "density", paste0("Similarity of same-speaker and different-speaker pairs",
if (length(shown) < n_pairs) sprintf(" — a sample of %s of %s pairs", big(length(shown)), big(n_pairs)) else ""), list(
x = cs_col("Cosine similarity", trial$scores[shown]),
group = cs_col("Pair", ifelse(trial$same[shown], "Same speaker", "Different speakers"), "categorical", levels = c("Different speakers", "Same speaker"))),
controls = list(compare = FALSE))
}
summary <- paste0(sprintf("%d recordings were turned into %d-value speaker embeddings and fell into %d voice group%s", length(ok), ncol(E),
n_groups, if (n_groups != 1) "s" else ""),
if (is.null(N_GROUPS)) sprintf(" at cosine similarity %s.", format(SIMILARITY)) else " (the number asked for).")
if (!is.null(trial) && !is.null(nn_acc)) summary <- paste(summary, sprintf(
"Among %d same-speaker and %d different-speaker pairs, the equal error rate was %.1f%% and the closest other file had the same speaker %.0f%% of the time.",
as.integer(trial$n_target), as.integer(trial$n_nontarget), 100 * trial$eer, 100 * nn_acc))
statistics <- list(list(key = "n_groups", label = "Voice groups", value = n_groups, format = "integer"),
list(key = "mean_nearest_similarity", label = "Mean similarity to the closest file", value = values$mean_nearest_similarity))
if (!is.null(trial)) statistics[[length(statistics) + 1L]] <- list(key = "eer", label = "EER", value = trial$eer, format = "percent")
cs_publish(list(
method = "audio.speakers",
methodVersion = "1.0.0",
title = "Speaker embeddings",
engine = cs_engine_info("torch", "nanoparquet"),
n = length(ok),
biometric = TRUE,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = as.list(warnings),
notes = c(list(paste0("ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. ",
"Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the ",
"embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider.")),
scores_note),
charts = charts,
artifacts = list(list(key = "speakers", path = file.path(out, "speakers.parquet"), format = "parquet", biometric = TRUE)),
values = values
))
6 recordings were turned into 192-value speaker embeddings and fell into 3 voice groups at cosine similarity 0.5. Among 3 same-speaker and 12 different-speaker pairs, the equal error rate was 0.0% and the closest other file had the same speaker 100% of the time.
- Voice groups
- 3
- Mean similarity to the closest file
- 0.6686
- EER
- 0.0%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Voices identify people — Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices.
- One speaker per file — Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations.
- Recordings like VoxCeleb — The model learned from interview speech; shortest file 1.50 s.
Voices
| path | Seconds | Voice group | Most similar file | Cosine similarity | speaker |
|---|---|---|---|---|---|
| media/aud3/ana_1.wav | 1.500 | V1 | ana_2.wav | 0.7616 | ana |
| media/aud3/ana_2.wav | 1.500 | V1 | ana_1.wav | 0.7616 | ana |
| media/aud3/ben_1.wav | 1.500 | V2 | ben_2.wav | 0.6615 | ben |
| media/aud3/ben_2.wav | 1.500 | V2 | ben_1.wav | 0.6615 | ben |
| media/aud3/cal_1.wav | 1.500 | V3 | cal_2.wav | 0.5826 | cal |
| media/aud3/cal_2.wav | 1.500 | V3 | cal_1.wav | 0.5826 | cal |
Same speaker or not: every pair of files with a known speaker
| Measure | Value |
|---|---|
| Target pairs (same speaker) | 3 |
| Non-target pairs | 12 |
| Mean similarity, same speaker | 0.6686 |
| Mean similarity, different speakers | 0.4198 |
| Equal error rate | 0 |
| Minimum DCF (π = 0.01) | 0 |
| Closest-file speaker accuracy | 1 |
- ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare voices (speaker embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.speakers 1.0.0 · spec 0256aeda2cef25d2
# Dataset: aud3_voices (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 # average-linkage grouping (twin: codesplashr cs_diarize_*)
from codesplash.audio import ecapa # ECAPA-TDNN speaker embeddings (twin: codesplashr cs_ecapa_*)
from codesplash.evaluate import verification as vf # EER and DCF of the trials (twin: codesplashr cs_verif_*)
# %% Audio files listed in the path column
PATH = "path"
SPEAKER = "speaker"
N_GROUPS = None # None: grouped by the similarity threshold
SIMILARITY = 0.5
P_TARGET = 0.01
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud3_voices.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud3_voices.parquet", columns=[PATH] if SPEAKER is None else [PATH, SPEAKER])
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\":60,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-python", df, "tests/parity/fixtures/aud3_voices.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 len(ok) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Comparing voices", min=2, n=len(ok))
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]]}).")
# %% Speaker embeddings (ECAPA-TDNN, float64 on one thread: the Parity profile). Biometric: kept out of AI.
torch.set_num_threads(1)
model = ecapa.load(ecapa.locate())
progress = cs.progress(f"Embedding {len(ok)} voices", total=len(ok))
clips, E = [], np.zeros((len(ok), int(model["config"]["lin_neurons"])))
for k, i in enumerate(ok):
clip = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
clips.append(clip.size / 16000.0)
E[k] = ecapa.embed(model, [clip])[0]
progress.update(k + 1)
progress.done()
S = ecapa.cosine(E, E)
# %% Voice groups (average linkage on cosine distance) and each file's closest other file
labels = dz.ahc(E, n_speakers=N_GROUPS, similarity=SIMILARITY, max_speakers=len(ok))
n_groups = int(labels.max()) + 1
names = [os.path.basename(paths[i]) for i in ok]
near, near_sim = [], []
for k in range(len(ok)):
row = S[k].copy()
row[k] = -np.inf
j = int(np.argmax(row))
near.append(names[j])
near_sim.append(float(S[k, j]))
# %% Known speakers: every pair of files is a trial (same speaker or not)
spk = None
trial = None
nn_acc = None
if SPEAKER is not None:
spk = [None if pd.isna(v) else str(v) for v in df[SPEAKER].tolist()] # None, NaN, pd.NA: unknown speaker
lab = [spk[i] for i in ok]
# Every pair a < b of files whose speakers are known, in the order a, then b, built in one pass (a loop over the
# pairs held two Python lists of them: about 80 bytes and one interpreter step per pair at the row cap).
levels = {}
code = np.array([-1 if v is None else levels.setdefault(v, len(levels)) for v in lab], dtype=np.int64)
pa, pb = np.triu_indices(len(ok), 1)
known = (code[pa] >= 0) & (code[pb] >= 0)
pa, pb = pa[known], pb[known]
sc = np.asarray(S[pa, pb], dtype=np.float64)
same = code[pa] == code[pb]
del pa, pb, known
if same.any() and (~same).any():
trial = vf.summary(sc, same, P_TARGET, 1.0, 1.0, "linear")
trial["mean_target"] = float(sc[same].mean())
trial["mean_nontarget"] = float(sc[~same].mean())
trial["pts"] = vf.det_points(sc, same)
trial["scores"], trial["same"] = sc, same
else:
warnings.append("Known speakers need at least two files of one speaker and two different speakers for verification scores.")
hits, n_id = 0, 0
for a in range(len(ok)):
if lab[a] is None or sum(1 for b in range(len(ok)) if b != a and lab[b] == lab[a]) == 0:
continue
row = np.array([S[a, b] if (b != a and lab[b] is not None) else -np.inf for b in range(len(ok))])
j = int(np.argmax(row))
hits += int(lab[j] == lab[a])
n_id += 1
nn_acc = hits / n_id if n_id else None
# %% Artifact: one row per embedded file (biometric — never shared with AI)
out = csml.out_dir("target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-python")
art = pd.DataFrame({"row": np.array(ok, dtype=np.int64), "media_id": [media_ids[i] for i in ok], "path": [paths[i] for i in ok],
"voice_group": [f"V{g + 1}" for g in labels]})
for d in range(E.shape[1]):
art[f"emb_{d + 1}"] = E[:, d]
art.to_parquet(os.path.join(out, "speakers.parquet"), index=False)
# %% Assumptions
assumptions = [
{"key": "biometric", "label": "Voices identify people", "status": "info",
"detail": "Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices."},
{"key": "one_speaker", "label": "One speaker per file", "status": "info",
"detail": "Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations."},
{"key": "domain", "label": "Recordings like VoxCeleb", "status": "warn" if min(clips) < 1.0 else "pass",
"detail": f"The model learned from interview speech; shortest file {min(clips):.2f} s" + ("; below about 1 s the embeddings are unreliable." if min(clips) < 1.0 else ".")},
]
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_rows": len(df), "n_files": len(ok) + len(unreadable), "n_embedded": len(ok), "n_unreadable": len(unreadable), "n_no_path": n_no_path,
"audio_seconds": float(sum(clips)), "dim": int(E.shape[1]), "n_groups": n_groups, "similarity_threshold": SIMILARITY if N_GROUPS is None else None,
"mean_nearest_similarity": float(np.mean(near_sim)), "p_target": P_TARGET,
"n_target_trials": int(trial["n_target"]) if trial else None, "n_nontarget_trials": int(trial["n_nontarget"]) if trial else None,
"mean_target_similarity": trial["mean_target"] if trial else None, "mean_nontarget_similarity": trial["mean_nontarget"] if trial else None,
"eer": trial["eer"] if trial else None, "min_dcf": trial["min_dcf"] if trial else None, "nn_accuracy": nn_acc}
file_rows = []
for k, i in enumerate(ok):
r = {"file": paths[i], "seconds": clips[k], "voice_group": f"V{labels[k] + 1}", "nearest": near[k], "similarity": near_sim[k]}
if spk is not None:
r["speaker"] = spk[i]
file_rows.append(r)
cols = [{"key": "file", "label": PATH, "type": "string"}, {"key": "seconds", "label": "Seconds", "type": "number"},
{"key": "voice_group", "label": "Voice group", "type": "string"}, {"key": "nearest", "label": "Most similar file", "type": "string"},
{"key": "similarity", "label": "Cosine similarity", "type": "number"}]
if spk is not None:
cols.append({"key": "speaker", "label": SPEAKER, "type": "string"})
tables = [{"key": "files", "title": "Voices", "columns": cols, "rows": file_rows[:500], "note": "First 500 files." if len(file_rows) > 500 else None}]
if trial:
tables.append({"key": "verification", "title": "Same speaker or not: every pair of files with a known speaker",
"columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"measure": "Target pairs (same speaker)", "value": trial["n_target"]},
{"measure": "Non-target pairs", "value": trial["n_nontarget"]},
{"measure": "Mean similarity, same speaker", "value": trial["mean_target"]},
{"measure": "Mean similarity, different speakers", "value": trial["mean_nontarget"]},
{"measure": "Equal error rate", "value": trial["eer"]},
{"measure": f"Minimum DCF (π = {P_TARGET:g})", "value": trial["min_dcf"]},
{"measure": "Closest-file speaker accuracy", "value": nn_acc}]})
charts = []
m = min(len(ok), 40)
lv = [f"{k + 1}. {names[k]}" for k in range(m)]
charts.append(cs.chart("similarity", "matrix-heatmap", "Voice similarity (cosine)" + (" — first 40 files" if len(ok) > 40 else ""), {
"row": cs.col("File", [lv[a] for a in range(m) for _ in range(m)], "categorical", levels=lv),
"col": cs.col("File", [lv[b] for _ in range(m) for b in range(m)], "categorical", levels=lv),
"value": cs.col("Cosine similarity", [float(S[a, b]) for a in range(m) for b in range(m)]),
"label": cs.col("Similarity", [f"{S[a, b]:.2f}" for a in range(m) for b in range(m)], "categorical")},
controls={"scale": "sequential"}))
scores_note = []
if trial:
pts = trial["pts"]
inner = [i for i in range(pts["threshold"].size) if np.isfinite(pts["threshold"][i])]
keep = [inner[j] for j in vf.thin(len(inner))]
charts.append(cs.chart("det", "det-curve", "Detection error tradeoff of the voice comparisons", {
"fpr": cs.col("False alarm rate (different speakers accepted)", [float(pts["fpr"][i]) for i in keep]),
"fnr": cs.col("Miss rate (same speaker rejected)", [float(pts["fnr"][i]) for i in keep])},
controls={"eer": trial["eer"], "minDcf": trial["min_dcf"], "minDcfFpr": trial["min_dcf_fpr"], "minDcfFnr": trial["min_dcf_fnr"]}))
# Every pair up to 20,000; above that a seeded sample within each kind of pair (R draws the same pairs). The EER,
# detection costs and DET curve above use every pair.
shown = vf.chart_sample(trial["same"], 20000, seed=1)
n_pairs = int(trial["same"].size)
if shown.size < n_pairs:
scores_note.append(f"The similarity chart draws a seeded sample of {shown.size:,} of the {n_pairs:,} pairs (the rarer kind keeps "
"up to half of it, so both curves keep their shape; the same pairs in Python and R). The equal error rate, "
"the detection costs and the DET curve use every pair.")
charts.append(cs.chart("scores", "density", "Similarity of same-speaker and different-speaker pairs"
+ (f" — a sample of {shown.size:,} of {n_pairs:,} pairs" if shown.size < n_pairs else ""), {
"x": cs.col("Cosine similarity", [float(v) for v in trial["scores"][shown]]),
"group": cs.col("Pair", ["Same speaker" if t else "Different speakers" for t in trial["same"][shown]], "categorical",
levels=["Different speakers", "Same speaker"])},
controls={"compare": False}))
summary = (f"{len(ok)} recordings were turned into {E.shape[1]}-value speaker embeddings and fell into {n_groups} voice "
f"group{'s' if n_groups != 1 else ''}" + (f" at cosine similarity {SIMILARITY:g}." if N_GROUPS is None else " (the number asked for)."))
if trial:
summary += (f" Among {trial['n_target']} same-speaker and {trial['n_nontarget']} different-speaker pairs, the equal error rate was "
f"{100 * trial['eer']:.1f}% and the closest other file had the same speaker {100 * nn_acc:.0f}% of the time." if nn_acc is not None else "")
cs.publish({
"method": "audio.speakers",
"methodVersion": "1.0.0",
"title": "Speaker embeddings",
"engine": cs.engine_info("numpy", "torch"),
"n": len(ok),
"biometric": True,
"summary": summary,
"statistics": [{"key": "n_groups", "label": "Voice groups", "value": n_groups, "format": "integer"},
{"key": "mean_nearest_similarity", "label": "Mean similarity to the closest file", "value": values["mean_nearest_similarity"]}]
+ ([{"key": "eer", "label": "EER", "value": trial["eer"], "format": "percent"}] if trial else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": ["ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. "
"Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the "
"embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider."]
+ scores_note,
"charts": charts,
"artifacts": [{"key": "speakers", "path": os.path.join(out, "speakers.parquet"), "format": "parquet", "biometric": True}],
"values": values,
})
The heatmap shows the cosine similarityVoice similarityThe cosine of two speaker embeddings: near 1 for the same voice, lower for different voices; scale varies by recording. of every pair: same-voice pairs average 0.67, different-voice pairs 0.42. Recordings join a voice groupVoice groupRecordings joined by average-linkage clustering while their average similarity stays above the threshold. while their average similarity stays above the threshold; here they fell into 3 groups. With the known speakers, the same-speaker pairsSame-speaker pairsWith known speakers, every pair of files is a trial; the EER and minimum DCF say how well similarity separates them. give an equal error rate, the same metric Evaluate verification scores reports for any system.
Check yourself
Why does the app never send a Compare voices result to an AI assistant, even one that only sees summaries?
Show the answer
Answer: b
A voiceprint is like a fingerprint. Laws such as the GDPR treat biometric data for identification as a special category, so the app keeps it out of every AI path.
Check yourself
Two recordings of one person, one on a phone and one in a studio, have similarity 0.35; two different people in the same studio have 0.40. What is going on?
Show the answer
Answer: a
Embeddings carry the microphone and room as well as the voice. Compare like with like, and check the equal error rate by condition.
Who spoke when
Explore2 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
View data
| End (s) | Speaker | Start (s) |
|---|---|---|
| 1.915 | S1 | 0.2950 |
| 4.165 | S2 | 2.345 |
| 5.805 | S1 | 4.595 |
View data
| End (s) | Speaker | Start (s) |
|---|---|---|
| 1.705 | S1 | 0.2850 |
| 3.665 | S2 | 2.145 |
| 5.415 | S3 | 4.095 |
| 6.865 | S2 | 5.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
| path | Start (s) | End (s) | Seconds | Speaker |
|---|---|---|---|---|
| media/aud3/conv_two.wav | 0.2950 | 1.915 | 1.620 | S1 |
| media/aud3/conv_two.wav | 2.345 | 4.165 | 1.820 | S2 |
| media/aud3/conv_two.wav | 4.595 | 5.805 | 1.210 | S1 |
| media/aud3/conv_three.wav | 0.2850 | 1.705 | 1.420 | S1 |
| media/aud3/conv_three.wav | 2.145 | 3.665 | 1.520 | S2 |
| media/aud3/conv_three.wav | 4.095 | 5.415 | 1.320 | S3 |
| media/aud3/conv_three.wav | 5.845 | 6.865 | 1.020 | S2 |
Talk time per speaker
| path | Speaker | Seconds | Share of speech |
|---|---|---|---|
| media/aud3/conv_two.wav | S1 | 2.830 | 0.6086 |
| media/aud3/conv_two.wav | S2 | 1.820 | 0.3914 |
| media/aud3/conv_three.wav | S1 | 1.420 | 0.2689 |
| media/aud3/conv_three.wav | S2 | 2.540 | 0.4811 |
| media/aud3/conv_three.wav | S3 | 1.320 | 0.2500 |
Diarization error rate (collar 0.5 s)
| path | Scored seconds | Missed speech (s) | False alarm (s) | Wrong speaker (s) | DER | Reference speakers | Found speakers |
|---|---|---|---|---|---|---|---|
| media/aud3/conv_two.wav | 3.100 | 0 | 0 | 0 | 0 | 2 | 2 |
| media/aud3/conv_three.wav | 3.200 | 0 | 0 | 0 | 0 | 3 | 3 |
- 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.
The exact R script · R 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
))
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
| path | Start (s) | End (s) | Seconds | Speaker |
|---|---|---|---|---|
| media/aud3/conv_two.wav | 0.2950 | 1.915 | 1.620 | S1 |
| media/aud3/conv_two.wav | 2.345 | 4.165 | 1.820 | S2 |
| media/aud3/conv_two.wav | 4.595 | 5.805 | 1.210 | S1 |
| media/aud3/conv_three.wav | 0.2850 | 1.705 | 1.420 | S1 |
| media/aud3/conv_three.wav | 2.145 | 3.665 | 1.520 | S2 |
| media/aud3/conv_three.wav | 4.095 | 5.415 | 1.320 | S3 |
| media/aud3/conv_three.wav | 5.845 | 6.865 | 1.020 | S2 |
Talk time per speaker
| path | Speaker | Seconds | Share of speech |
|---|---|---|---|
| media/aud3/conv_two.wav | S1 | 2.830 | 0.6086 |
| media/aud3/conv_two.wav | S2 | 1.820 | 0.3914 |
| media/aud3/conv_three.wav | S1 | 1.420 | 0.2689 |
| media/aud3/conv_three.wav | S2 | 2.540 | 0.4811 |
| media/aud3/conv_three.wav | S3 | 1.320 | 0.2500 |
Diarization error rate (collar 0.5 s)
| path | Scored seconds | Missed speech (s) | False alarm (s) | Wrong speaker (s) | DER | Reference speakers | Found speakers |
|---|---|---|---|---|---|---|---|
| media/aud3/conv_two.wav | 3.100 | 0 | 0 | 0 | 0 | 2 | 2 |
| media/aud3/conv_three.wav | 3.200 | 0 | 0 | 0 | 0 | 3 | 3 |
- 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.
The exact Python script · Python 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,
})
Speaker diarizationSpeaker diarizationSplitting a recording into segments by speaker (S1, S2, …), with talk time and speaker changes. splits a conversation into turns. First voice activity detectionVoice activity detection (VAD)Finding when someone speaks; here a 25-ms frame is speech when it is within a set number of dB of the loudest frame. finds the speech by energy; the speech is cut into windows of a second and a half, each window gets a speaker embedding, the windows are grouped by voice, and boundaries fall halfway between windows with different speakers. The embeddings are thrown away afterwards; speakers are named S1, S2, … per recording. Here the method found 7 segments.
Against the reference turns the diarization error rateDiarization error rate (DER)(Missed speech + false alarm + wrong speaker) / reference speech, after the best one-to-one speaker mapping. is 0.0%: missed speech, false alarms and wrong-speaker time over 6.3 s of scored speech, with a 0.5-second collar around each reference boundary left out.
Check yourself
Two papers report DER on the same meetings: 8% and 14%. What should you check before comparing them?
Show the answer
Answer: b
A 0.5-second collar can halve the error of a system whose boundaries are a little late; skipping overlap removes the hardest parts. Always report both.
Telling it how many
Checkpoint2 recordings (13.6 s, 9.9 s of speech) split into 8 segments with 3 speakers at most per recording and 6 changes of speaker.
- Segments
- 8
- Most speakers in a recording
- 3
Plots
View data
| End (s) | Speaker | Start (s) |
|---|---|---|
| 1.915 | S1 | 0.2950 |
| 3.095 | S2 | 2.345 |
| 4.165 | S3 | 3.095 |
| 5.805 | S1 | 4.595 |
View data
| End (s) | Speaker | Start (s) |
|---|---|---|
| 1.705 | S1 | 0.2850 |
| 3.665 | S2 | 2.145 |
| 5.415 | S3 | 4.095 |
| 6.865 | S2 | 5.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 — Fixed at 3 per recording.
- 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
| path | Start (s) | End (s) | Seconds | Speaker |
|---|---|---|---|---|
| media/aud3/conv_two.wav | 0.2950 | 1.915 | 1.620 | S1 |
| media/aud3/conv_two.wav | 2.345 | 3.095 | 0.7500 | S2 |
| media/aud3/conv_two.wav | 3.095 | 4.165 | 1.070 | S3 |
| media/aud3/conv_two.wav | 4.595 | 5.805 | 1.210 | S1 |
| media/aud3/conv_three.wav | 0.2850 | 1.705 | 1.420 | S1 |
| media/aud3/conv_three.wav | 2.145 | 3.665 | 1.520 | S2 |
| media/aud3/conv_three.wav | 4.095 | 5.415 | 1.320 | S3 |
| media/aud3/conv_three.wav | 5.845 | 6.865 | 1.020 | S2 |
Talk time per speaker
| path | Speaker | Seconds | Share of speech |
|---|---|---|---|
| media/aud3/conv_two.wav | S1 | 2.830 | 0.6086 |
| media/aud3/conv_two.wav | S2 | 0.7500 | 0.1613 |
| media/aud3/conv_two.wav | S3 | 1.070 | 0.2301 |
| media/aud3/conv_three.wav | S1 | 1.420 | 0.2689 |
| media/aud3/conv_three.wav | S2 | 2.540 | 0.4811 |
| media/aud3/conv_three.wav | S3 | 1.320 | 0.2500 |
- Energy voice activity (within 35 dB of the loudest 25-ms frame), 1-s windows every 0.5 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.
The exact R script · R 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 53f7a64b22a6474d
# 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 <- 3 # NULL: estimated from the similarity
SIMILARITY <- 0.5
MAX_SPEAKERS <- as.integer(10)
WIN <- 1
STEP <- 0.5
VAD_DB <- 35
MIN_SPEECH <- 0.25
MIN_GAP <- 0.3
COLLAR <- 0.5
SKIP_OVERLAP <- FALSE
REF <- NULL
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-three-speakers/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-three-speakers/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-three-speakers/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
))
2 recordings (13.6 s, 9.9 s of speech) split into 8 segments with 3 speakers at most per recording and 6 changes of speaker.
- Segments
- 8
- Most speakers in a recording
- 3
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 — Fixed at 3 per recording.
- 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
| path | Start (s) | End (s) | Seconds | Speaker |
|---|---|---|---|---|
| media/aud3/conv_two.wav | 0.2950 | 1.915 | 1.620 | S1 |
| media/aud3/conv_two.wav | 2.345 | 3.095 | 0.7500 | S2 |
| media/aud3/conv_two.wav | 3.095 | 4.165 | 1.070 | S3 |
| media/aud3/conv_two.wav | 4.595 | 5.805 | 1.210 | S1 |
| media/aud3/conv_three.wav | 0.2850 | 1.705 | 1.420 | S1 |
| media/aud3/conv_three.wav | 2.145 | 3.665 | 1.520 | S2 |
| media/aud3/conv_three.wav | 4.095 | 5.415 | 1.320 | S3 |
| media/aud3/conv_three.wav | 5.845 | 6.865 | 1.020 | S2 |
Talk time per speaker
| path | Speaker | Seconds | Share of speech |
|---|---|---|---|
| media/aud3/conv_two.wav | S1 | 2.830 | 0.6086 |
| media/aud3/conv_two.wav | S2 | 0.7500 | 0.1613 |
| media/aud3/conv_two.wav | S3 | 1.070 | 0.2301 |
| media/aud3/conv_three.wav | S1 | 1.420 | 0.2689 |
| media/aud3/conv_three.wav | S2 | 2.540 | 0.4811 |
| media/aud3/conv_three.wav | S3 | 1.320 | 0.2500 |
- Energy voice activity (within 35 dB of the loudest 25-ms frame), 1-s windows every 0.5 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.
The exact Python script · Python 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 53f7a64b22a6474d
# 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 = 3 # None: estimated from the similarity
SIMILARITY = 0.5
MAX_SPEAKERS = int(10)
WIN, STEP = 1, 0.5
VAD_DB, MIN_SPEECH, MIN_GAP = 35, 0.25, 0.3
COLLAR = 0.5
SKIP_OVERLAP = False
REF = None
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-three-speakers/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-three-speakers/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-three-speakers/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,
})
Without a number of speakers, the method merges windows while their average similarity is at least the threshold, so the count depends on that setting. Forcing three speakers on every recording split the two-person conversation into three. Give the number when you know it.
Check yourself
A two-person interview comes out with five speakers. What is the most likely fix?
Show the answer
Answer: b
Too many speakers means windows of one voice weren't similar enough to merge: noise, laughter or a change of microphone can do that. Telling the method the count is the most reliable fix.
Do it on your own data
In the appAdd an audio folder in Data, then open Compare voices or Who spoke when. ECAPA-TDNN is a one-time 83 MB download that asks first. On a Compare voices result, Save speaker embeddings stores them as a dataset tagged biometric, which AI features never read. For diarization scores, add a table of reference turns (file, start, end, speaker).
from codesplash.audio import diarize, ecapa
model = ecapa.load(ecapa.locate())
regions = diarize.vad(samples_16k)
wins = diarize.windows(regions)
emb = ecapa.embed(model, [samples_16k[slice(*diarize.sample_range(s, e, 16000, len(samples_16k)))] for s, e, _ in wins])
segments = diarize.segments(regions, wins, diarize.ahc(emb, n_speakers=2))library(codesplashr)
model <- cs_ecapa_load(cs_ecapa_locate())
regions <- cs_diarize_vad(samples_16k)
wins <- cs_diarize_windows(regions)
emb <- cs_ecapa_embed(model, lapply(seq_len(nrow(wins)), function(w) {
r <- cs_diarize_sample_range(wins$start[w], wins$end[w], 16000, length(samples_16k)); samples_16k[r[1]:r[2]] }))
segments <- cs_diarize_segments(regions, wins, cs_diarize_ahc(emb, n_speakers = 2))Concepts in this lesson