Speech to text with Whisper
Transcribe a folder of recordings with Whisper, read the timed segments and their confidence, spot invented text, and score transcripts against references.
What runs in CodeSplash
- Speech to text (Whisper) Experimental
You will be able to
- Explain how Whisper turns 30-second windows of audio into timed text segments
- Read average log-probability and no-speech probability, and recognize invented or looping text
- Save transcripts and segments as data and score them with word and character error rates
Read first
Recordings as text
ReadInterviews, calls and voice notes become something you can count, search and compare once they are text. WhisperWhisperOpenAI's speech-recognition model: an audio encoder and a text decoder trained on 680,000 hours of transcribed web audio. does the speech to textSpeech to textWriting down what is said in a recording. The output is text plus, here, timed segments and a confidence per segment. step on this computer. The app writes Whisper out in both Python and R, and both produce the same words.
The example folder holds four kinds of sound: 11 seconds of President Kennedy's 1961 inaugural address (public domain), the same clip twice with a pause between, a synthetic vowel sound, and near silence.
Make a guess
PredictPredict first
Four files are transcribed: real speech, the same speech twice, a synthetic vowel and near silence. How many timed segments with text do you expect?
Make your guess between 0 and 20 segments, then reveal.
Reveal
Whisper wrote 4 segments. The near-silent file got none: its only window was skipped as silence.
Windows and segments
Read4 files (48.0 s) → 4 segments, 289 words; most common language en.
- Files transcribed
- 4
- Segments
- 4
- Words
- 289
- Mean log-probability
- −0.2208
Plots
View data
| End (s) | Text | File | Start (s) | Average log-probability |
|---|---|---|---|---|
| 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk.wav | 0 | −0.3321 |
| 2.500 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah | vowels.wav | 0 | −0.0561 |
| 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk_long_8k.wav | 0 | −0.3195 |
| 32 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk_long_8k.wav | 11 | −0.1754 |
View data
| Average log-probability per token |
|---|
| −0.3321 |
| −0.0561 |
| −0.3195 |
| −0.1754 |
Assumptions
- Text can be invented
- Language from the first 30 seconds
- One pass, no retries
- Recordings of people
Transcripts
| File | Language | Length (s) | Segments | Transcript |
|---|---|---|---|---|
| jfk.wav | en | 11 | 1 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
| vowels.wav | en | 2.500 | 1 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah … |
| quiet.wav | en | 1.500 | 0 | |
| jfk_long_8k.wav | en | 33 | 2 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
Segments
| File | Start (s) | End (s) | Text | Avg log-probability | No-speech probability |
|---|---|---|---|---|---|
| jfk.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3321 | 0.0692 |
| vowels.wav | 0 | 2.500 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah | −0.0561 | 0.6014 |
| jfk_long_8k.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3195 | 0.2623 |
| jfk_long_8k.wav | 11 | 32 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.1754 | 0.1035 |
- 1 rows have no file path and are left out.
- 1 of 5 files couldn't be decoded, so their rows got missing values (first: aud2_speech/broken.wav).
The exact R script · R R version 4.5.1 (2025-06-13)
# Speech to text (Whisper)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.transcribe 1.1.0 · spec d10f895fcf7fa3fc
# Dataset: aud2_speech (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Audio files listed in the path column
PATH <- "path"
REFERENCE <- NULL
MODEL <- "tiny"
LANGUAGE <- tolower(trimws("")) # empty: detected per file
if (!nzchar(LANGUAGE)) LANGUAGE <- NULL
TASK <- "transcribe"
TIMESTAMPS <- TRUE
CONDITION <- TRUE
NO_SPEECH <- 0.6
LOGPROB <- -1
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud2_speech.parquet", mustWork = FALSE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud2_speech.parquet", col_select = c(PATH, REFERENCE)))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
if (!is.null(LANGUAGE) && !(LANGUAGE %in% cs_whisper_model_languages(MODEL))) {
cs_error("CS_E_INVALID_OPTION", option = "language", allowed = "a language code Whisper knows (en, de, es, …) or empty", value = LANGUAGE)
}
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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-98732/audio.transcribe/defaults_tiny/out-r", df,
"tests/parity/fixtures/aud2_speech.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 <- list()
ids_or_na <- vapply(seq_along(paths), function(i) if (is.na(paths[i]) || is.na(media_ids[i])) NA_character_ else as.character(media_ids[i]), "")
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, ids_or_na))
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)) {
i <- unreadable[1]
cs_error("CS_E_MEDIA_DECODE", file = paths[i], reason = status[i])
}
if (n_no_path > 0) warnings <- c(warnings, sprintf("%d rows have no file path and are left out.", n_no_path))
# %% Whisper (greedy decoding, 30-second windows; ADR 0101)
cs_deep_profile_configure(list(profile = "parity"))
model <- cs_whisper_load(cs_whisper_locate(MODEL))
files <- list(); segs <- list(); token_lists <- list()
first_failure <- NULL
for (k in seq_along(ok)) {
i <- ok[k]
# Outside the app the files are decoded here, so a bad file shows up now.
clip <- tryCatch(cs_media_audio(media, media_ids[i])[[1]], cs_error = function(e) {
if (!(e$code %in% c("CS_E_MEDIA_DECODE", "CS_E_MEDIA_UNSUPPORTED"))) stop(e)
e
})
if (inherits(clip, "cs_error")) {
unreadable <- c(unreadable, i)
if (is.null(first_failure)) first_failure <- clip
next
}
r <- cs_whisper_transcribe(model, clip, LANGUAGE, TASK, TIMESTAMPS, CONDITION, NO_SPEECH, LOGPROB)
token_lists[[k]] <- r$tokens
files[[k]] <- list(row = i - 1L, media_id = media_ids[i], path = paths[i], language = r$language, language_prob = r$language_prob,
duration_s = r$duration, segments = length(r$segments), text = r$text, windows = r$windows, skipped = r$skipped)
for (j in seq_along(r$segments)) {
s <- r$segments[[j]]
segs[[length(segs) + 1L]] <- list(media_id = media_ids[i], path = paths[i], row = i - 1L, segment = j, start = s$start, end = s$end,
text = s$text, avg_logprob = s$avg_logprob, no_speech_prob = s$no_speech_prob, language = r$language)
}
}
if (!length(files)) stop(first_failure)
unreadable <- sort(unreadable)
if (length(unreadable)) {
warnings <- c(warnings, cs_warning("CS_W_MEDIA_SKIPPED", count = length(unreadable), total = nrow(df) - n_no_path,
file = paths[unreadable[1]]))
}
fcol <- function(x, key, type = "") vapply(x, function(e) e[[key]], type)
# %% Artifacts: one row per file (row-aligned with the input) and one row per timed segment
out <- cs_ml_out_dir("target/academy-parity/run-98732/audio.transcribe/defaults_tiny/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(fcol(files, "row", 1L)), text = fcol(files, "text", ""),
language = fcol(files, "language", ""), stringsAsFactors = FALSE),
file.path(out, "transcripts.parquet"))
seg_df <- data.frame(
media_id = fcol(segs, "media_id", ""), path = fcol(segs, "path", ""), row = as.integer(fcol(segs, "row", 1L)),
segment = as.integer(fcol(segs, "segment", 1L)), start = fcol(segs, "start", 0), end = fcol(segs, "end", 0),
text = fcol(segs, "text", ""), avg_logprob = fcol(segs, "avg_logprob", 0), no_speech_prob = fcol(segs, "no_speech_prob", 0),
language = fcol(segs, "language", ""), stringsAsFactors = FALSE
)
nanoparquet::write_parquet(seg_df, file.path(out, "segments.parquet"))
# %% Result
lang_all <- fcol(files, "language", "")
langs <- table(lang_all)
lang_codes <- names(langs)
lang_n <- as.integer(langs)
ord <- order(-lang_n, lang_codes, method = "radix")
top_language <- lang_codes[ord[1]]
lp <- fcol(segs, "avg_logprob", 0)
texts <- fcol(files, "text", "")
values <- list(
n_rows = nrow(df),
n_files = nrow(df) - n_no_path,
n_transcribed = length(files),
n_unreadable = length(unreadable),
n_no_path = n_no_path,
audio_seconds = sum(fcol(files, "duration_s", 0)),
speech_seconds = sum(fcol(segs, "end", 0) - fcol(segs, "start", 0)),
n_segments = length(segs),
n_windows = sum(fcol(files, "windows", 1L)),
n_skipped_windows = sum(fcol(files, "skipped", 1L)),
n_tokens = sum(lengths(token_lists)),
n_words = sum(cs_whisper_word_count(texts)),
token_check = cs_whisper_token_check(token_lists),
mean_avg_logprob = if (length(lp)) mean(lp) else NULL,
mean_no_speech_prob = if (length(segs)) mean(fcol(segs, "no_speech_prob", 0)) else NULL,
n_low_confidence = sum(lp < LOGPROB),
language = top_language,
n_languages = length(lang_codes),
model = MODEL,
task = TASK
)
for (code in sort(lang_codes, method = "radix")) values[[sprintf("language[%s]", code)]] <- as.integer(langs[[code]])
for (k in seq_len(min(20L, length(files)))) {
values[[sprintf("text[%d]", k)]] <- files[[k]]$text
if (!is.null(files[[k]]$language_prob)) values[[sprintf("language_prob[%d]", k)]] <- files[[k]]$language_prob
}
short <- function(t) if (nchar(t) <= 600) t else paste0(substr(t, 1, 600), " …")
tables <- list(
list(key = "transcripts", title = "Transcripts", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "language", label = "Language", type = "string"),
list(key = "duration", label = "Length (s)", type = "number"), list(key = "segments", label = "Segments", type = "integer"),
list(key = "text", label = "Transcript", type = "string")),
rows = lapply(files, function(f) list(file = basename(f$path), language = f$language, duration = f$duration_s, segments = f$segments,
text = short(f$text)))),
list(key = "segments", title = if (length(segs) > 500) "Segments (first 500)" else "Segments", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "start", label = "Start (s)", type = "number"), list(key = "end", label = "End (s)", type = "number"),
list(key = "text", label = "Text", type = "string"), list(key = "avg_logprob", label = "Avg log-probability", type = "number"),
list(key = "no_speech_prob", label = "No-speech probability", type = "number")),
rows = lapply(utils::head(segs, 500), function(s) list(file = basename(s$path), start = s$start, end = s$end, text = s$text,
avg_logprob = s$avg_logprob, no_speech_prob = s$no_speech_prob)))
)
charts <- list()
if (length(segs)) {
lane_rows <- vapply(utils::head(files, 30), function(f) f$row, 1L) # one lane per file, at most 30
lanes <- unique(vapply(utils::head(files, 30), function(f) basename(f$path), ""))
shown <- Filter(function(s) s$row %in% lane_rows, segs)
charts[[length(charts) + 1L]] <- cs_chart("timeline", "segment-timeline", "Segments over time", list(
start = cs_col("Start (s)", vapply(shown, function(s) s$start, 0), "numeric"),
end = cs_col("End (s)", vapply(shown, function(s) s$end, 0), "numeric"),
lane = cs_col("File", vapply(shown, function(s) basename(s$path), ""), "categorical", lanes),
label = cs_col("Text", vapply(shown, function(s) s$text, ""), "categorical"),
value = cs_col("Average log-probability", vapply(shown, function(s) s$avg_logprob, 0), "numeric")
), controls = list(labels = TRUE, overlap = FALSE))
}
if (length(lp)) {
charts[[length(charts) + 1L]] <- cs_chart("confidence", "histogram", "Average log-probability of each segment",
list(x = cs_col("Average log-probability per token", lp, "numeric")), controls = list(scale = "count", kde = FALSE))
}
detected <- paste(sprintf("%s (%d)", lang_codes[ord], lang_n[ord]), collapse = ", ")
assumptions <- c(list(
list(key = "hallucination", label = "Text can be invented", status = if (values$n_low_confidence > 0) "warn" else "info",
message = if (values$n_low_confidence > 0) {
sprintf("%d of %d segments have an average log-probability below %s: listen to them before relying on the text.",
values$n_low_confidence, length(segs), format(LOGPROB))
} else {
"No segment falls below the log-probability cutoff; Whisper can still mishear names and numbers."
}),
list(key = "language_detection", label = "Language from the first 30 seconds", status = "info",
message = if (!is.null(LANGUAGE)) sprintf("Set to %s for every file.", LANGUAGE) else sprintf("Detected per file: %s.", detected)),
list(key = "greedy_decoding", label = "One pass, no retries", status = "info",
message = sprintf("%d windows decoded once each; %d skipped as silence.", values$n_windows, values$n_skipped_windows)),
list(key = "speech_privacy", label = "Recordings of people", status = "info",
message = "Transcripts stay on this computer. Get consent before transcribing other people's recordings.")
), cs_deep_profile_warning_rows())
cs_publish(list(
title = "Speech to text (Whisper)",
engine = cs_engine_info("torch", "safetensors", "jsonlite", "nanoparquet", "codesplashr"),
n = length(files),
summary = sprintf("%d files (%.1f s) → %d segments, %d words; most common language %s.", length(files), values$audio_seconds,
length(segs), values$n_words, top_language),
statistics = list(
list(key = "n_transcribed", label = "Files transcribed", value = length(files)),
list(key = "n_segments", label = "Segments", value = length(segs)),
list(key = "n_words", label = "Words", value = values$n_words),
list(key = "mean_avg_logprob", label = "Mean log-probability", value = values$mean_avg_logprob)
),
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "transcripts", path = file.path(out, "transcripts.parquet"), format = "parquet"),
list(key = "segments", path = file.path(out, "segments.parquet"), format = "parquet"))
))
4 files (48.0 s) → 4 segments, 289 words; most common language en.
- Files transcribed
- 4
- Segments
- 4
- Words
- 289
- Mean log-probability
- −0.2208
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Text can be invented
- Language from the first 30 seconds
- One pass, no retries
- Recordings of people
Transcripts
| File | Language | Length (s) | Segments | Transcript |
|---|---|---|---|---|
| jfk.wav | en | 11 | 1 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
| vowels.wav | en | 2.500 | 1 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah … |
| quiet.wav | en | 1.500 | 0 | |
| jfk_long_8k.wav | en | 33 | 2 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
Segments
| File | Start (s) | End (s) | Text | Avg log-probability | No-speech probability |
|---|---|---|---|---|---|
| jfk.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3321 | 0.0692 |
| vowels.wav | 0 | 2.500 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah | −0.0561 | 0.6014 |
| jfk_long_8k.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3195 | 0.2623 |
| jfk_long_8k.wav | 11 | 32 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.1754 | 0.1035 |
- 1 rows have no file path and are left out.
- 1 of 5 files couldn't be decoded, so their rows got missing values (first: aud2_speech/broken.wav).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Speech to text (Whisper)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.transcribe 1.1.0 · spec d10f895fcf7fa3fc
# Dataset: aud2_speech (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
from collections import Counter
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import whisper as wh
from codesplash.deep import profile as cs_profile
# %% Audio files listed in the path column
PATH = "path"
REFERENCE = None
MODEL = "tiny"
LANGUAGE = "".strip().lower() or None # empty: detected per file
TASK = "transcribe"
TIMESTAMPS = True
CONDITION = True
NO_SPEECH = 0.6
LOGPROB = -1
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud2_speech.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud2_speech.parquet", columns=[PATH] if REFERENCE is None else [PATH, REFERENCE])
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
if LANGUAGE is not None and LANGUAGE not in wh.languages(MODEL):
cs.cs_error("CS_E_INVALID_OPTION", option="language", allowed="a language code Whisper knows (en, de, es, …) or empty", value=LANGUAGE)
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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-98732/audio.transcribe/defaults_tiny/out-python", df, "tests/parity/fixtures/aud2_speech.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.")
# %% Whisper (greedy decoding, 30-second windows; ADR 0101)
cs_profile.configure({"profile": "parity"})
model = wh.load(wh.locate(MODEL))
progress = cs.progress(f"Transcribing {len(ok)} files with Whisper {MODEL}", total=len(ok))
files, segs, token_lists = [], [], []
first_failure = None
for k, i in enumerate(ok):
try:
clip = cs_media.audio(media, [media_ids[i]])[0]
except cs.CsError as e: # outside the app the files are decoded here, so a bad file shows up now
if e.code not in ("CS_E_MEDIA_DECODE", "CS_E_MEDIA_UNSUPPORTED"):
raise
unreadable.append(i)
first_failure = first_failure or e
progress.update(k + 1)
continue
r = wh.transcribe(model, clip, LANGUAGE, TASK, TIMESTAMPS, CONDITION, NO_SPEECH, LOGPROB)
token_lists.append(r["tokens"])
files.append({"row": i, "media_id": media_ids[i], "path": paths[i], "language": r["language"], "language_prob": r["language_prob"],
"duration_s": r["duration"], "segments": len(r["segments"]), "text": r["text"], "windows": r["windows"], "skipped": r["skipped"]})
for j, s in enumerate(r["segments"], start=1):
segs.append({"media_id": media_ids[i], "path": paths[i], "row": i, "segment": j, "start": s["start"], "end": s["end"], "text": s["text"],
"avg_logprob": s["avg_logprob"], "no_speech_prob": s["no_speech_prob"], "language": r["language"]})
progress.update(k + 1)
progress.done()
if not files:
raise first_failure
unreadable.sort()
if unreadable:
warnings.append(cs.cs_warning("CS_W_MEDIA_SKIPPED", count=len(unreadable), total=len(df) - n_no_path, file=paths[unreadable[0]]))
# %% Artifacts: one row per file (row-aligned with the input) and one row per timed segment
out = csml.out_dir("target/academy-parity/run-98732/audio.transcribe/defaults_tiny/out-python")
pd.DataFrame({"row": np.array([f["row"] for f in files], dtype=np.int64), "text": [f["text"] for f in files],
"language": [f["language"] for f in files]}).to_parquet(os.path.join(out, "transcripts.parquet"), index=False)
seg_df = pd.DataFrame(segs, columns=["media_id", "path", "row", "segment", "start", "end", "text", "avg_logprob", "no_speech_prob", "language"])
seg_df["row"] = seg_df["row"].astype(np.int64)
seg_df["segment"] = seg_df["segment"].astype(np.int64)
seg_df.to_parquet(os.path.join(out, "segments.parquet"), index=False)
# %% Result
langs = Counter(f["language"] for f in files)
top_language = sorted(langs.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
lp = [s["avg_logprob"] for s in segs]
values = {
"n_rows": len(df),
"n_files": len(df) - n_no_path,
"n_transcribed": len(files),
"n_unreadable": len(unreadable),
"n_no_path": n_no_path,
"audio_seconds": float(sum(f["duration_s"] for f in files)),
"speech_seconds": float(sum(s["end"] - s["start"] for s in segs)),
"n_segments": len(segs),
"n_windows": sum(f["windows"] for f in files),
"n_skipped_windows": sum(f["skipped"] for f in files),
"n_tokens": sum(len(t) for t in token_lists),
"n_words": sum(len(f["text"].split()) for f in files),
"token_check": wh.token_check(token_lists),
"mean_avg_logprob": float(np.mean(lp)) if lp else None,
"mean_no_speech_prob": float(np.mean([s["no_speech_prob"] for s in segs])) if segs else None,
"n_low_confidence": sum(v < LOGPROB for v in lp),
"language": top_language,
"n_languages": len(langs),
"model": MODEL,
"task": TASK,
}
for code in sorted(langs):
values[f"language[{code}]"] = langs[code]
for k, f in enumerate(files[:20], start=1):
values[f"text[{k}]"] = f["text"]
if f["language_prob"] is not None:
values[f"language_prob[{k}]"] = f["language_prob"]
tables = [
{"key": "transcripts", "title": "Transcripts", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "language", "label": "Language", "type": "string"},
{"key": "duration", "label": "Length (s)", "type": "number"}, {"key": "segments", "label": "Segments", "type": "integer"},
{"key": "text", "label": "Transcript", "type": "string"}],
"rows": [{"file": os.path.basename(f["path"]), "language": f["language"], "duration": f["duration_s"], "segments": f["segments"],
"text": f["text"] if len(f["text"]) <= 600 else f["text"][:600] + " …"} for f in files]},
{"key": "segments", "title": f"Segments{' (first 500)' if len(segs) > 500 else ''}", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "start", "label": "Start (s)", "type": "number"}, {"key": "end", "label": "End (s)", "type": "number"},
{"key": "text", "label": "Text", "type": "string"}, {"key": "avg_logprob", "label": "Avg log-probability", "type": "number"},
{"key": "no_speech_prob", "label": "No-speech probability", "type": "number"}],
"rows": [{"file": os.path.basename(s["path"]), "start": s["start"], "end": s["end"], "text": s["text"], "avg_logprob": s["avg_logprob"],
"no_speech_prob": s["no_speech_prob"]} for s in segs[:500]]},
]
charts = []
if segs:
lane_rows = [f["row"] for f in files[:30]] # one lane per file, at most 30
lanes = list(dict.fromkeys(os.path.basename(f["path"]) for f in files[:30]))
shown = [s for s in segs if s["row"] in lane_rows]
charts.append(cs.chart("timeline", "segment-timeline", "Segments over time", {
"start": cs.col("Start (s)", [s["start"] for s in shown], "numeric"),
"end": cs.col("End (s)", [s["end"] for s in shown], "numeric"),
"lane": cs.col("File", [os.path.basename(s["path"]) for s in shown], "categorical", lanes),
"label": cs.col("Text", [s["text"] for s in shown], "categorical"),
"value": cs.col("Average log-probability", [s["avg_logprob"] for s in shown], "numeric"),
}, controls={"labels": True, "overlap": False}))
if lp:
charts.append(cs.chart("confidence", "histogram", "Average log-probability of each segment", {
"x": cs.col("Average log-probability per token", lp, "numeric")}, controls={"scale": "count", "kde": False}))
assumptions = [
{"key": "hallucination", "label": "Text can be invented", "status": "warn" if values["n_low_confidence"] else "info",
"message": (f"{values['n_low_confidence']} of {len(segs)} segments have an average log-probability below {LOGPROB:g}: listen to them before relying on the text."
if values["n_low_confidence"] else "No segment falls below the log-probability cutoff; Whisper can still mishear names and numbers.")},
{"key": "language_detection", "label": "Language from the first 30 seconds", "status": "info",
"message": (f"Set to {LANGUAGE} for every file." if LANGUAGE else f"Detected per file: {', '.join(f'{c} ({n})' for c, n in sorted(langs.items(), key=lambda kv: (-kv[1], kv[0])))}.")},
{"key": "greedy_decoding", "label": "One pass, no retries", "status": "info",
"message": f"{values['n_windows']} windows decoded once each; {values['n_skipped_windows']} skipped as silence."},
{"key": "speech_privacy", "label": "Recordings of people", "status": "info",
"message": "Transcripts stay on this computer. Get consent before transcribing other people's recordings."},
] + cs_profile.warning_rows()
cs.publish({
"title": "Speech to text (Whisper)",
"engine": cs.engine_info("torch", "safetensors", "numpy", "pandas"),
"n": len(files),
"summary": f"{len(files)} files ({values['audio_seconds']:.1f} s) → {len(segs)} segments, {values['n_words']} words; most common language {top_language}.",
"statistics": [
{"key": "n_transcribed", "label": "Files transcribed", "value": len(files)},
{"key": "n_segments", "label": "Segments", "value": len(segs)},
{"key": "n_words", "label": "Words", "value": values["n_words"]},
{"key": "mean_avg_logprob", "label": "Mean log-probability", "value": values["mean_avg_logprob"]},
],
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "transcripts", "path": os.path.join(out, "transcripts.parquet"), "format": "parquet"},
{"key": "segments", "path": os.path.join(out, "segments.parquet"), "format": "parquet"}],
})
Whisper hears 30 seconds at a time30-second windowWhisper hears 30 s at a time. The next window starts where the last complete segment ended, or after the window.. In each window it writes a timestamp, some words and another timestamp: that pair marks a segmentTranscript segmentA stretch of speech with a start and end time (in seconds from the file's start) and its text.. The next window starts where the last complete segment ended. The 33-second file needed two windows; in all, 5 windows were decoded and 1 skipped.
Unless you set it, the language is guessed per file from its first 30 seconds (spoken language detectionSpoken language detectionWhisper picks the most likely of its 99 language tokens from the first 30 seconds of each file.). Here every file came out as en.
Check yourself
A 33-second recording ends its first window with a complete segment at 11 seconds and an unfinished one after it. Where does the second window start?
Show the answer
Answer: b
Starting at the last complete segment means words cut off by the window edge aren't lost or half-written.
Confident is not the same as right
ExploreThe synthetic vowel has no words, yet Whisper wrote "ah ah ah …" until it hit the token limit for the window. Its average log-probabilityAverage log-probabilityThe mean log-probability Whisper gave its own tokens in a window: near 0 is confident, below −1 is doubtful. is still fairly high: the model was sure of its loop.
4 files (48.0 s) → 5 segments, 180 words; most common language en.
- Files transcribed
- 4
- Segments
- 5
- Words
- 180
- Mean log-probability
- −0.4774
Plots
View data
| End (s) | Text | File | Start (s) | Average log-probability |
|---|---|---|---|---|
| 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk.wav | 0 | −0.3319 |
| 2.500 | Ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah | vowels.wav | 0 | −0.0551 |
| 2 | Thank you. | quiet.wav | 0 | −1.319 |
| 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk_long_8k.wav | 0 | −0.3316 |
| 31 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk_long_8k.wav | 11 | −0.3496 |
View data
| Average log-probability per token |
|---|
| −0.3319 |
| −0.0551 |
| −1.319 |
| −0.3316 |
| −0.3496 |
Assumptions
- Text can be invented
- Language from the first 30 seconds
- One pass, no retries
- Recordings of people
Transcripts
| File | Language | Length (s) | Segments | Transcript |
|---|---|---|---|---|
| jfk.wav | en | 11 | 1 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
| vowels.wav | en | 2.500 | 1 | Ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah |
| quiet.wav | en | 1.500 | 1 | Thank you. |
| jfk_long_8k.wav | en | 33 | 2 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
Segments
| File | Start (s) | End (s) | Text | Avg log-probability | No-speech probability |
|---|---|---|---|---|---|
| jfk.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3319 | 0.0692 |
| vowels.wav | 0 | 2.500 | Ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah | −0.0551 | 0.6014 |
| quiet.wav | 0 | 2 | Thank you. | −1.319 | 0.8613 |
| jfk_long_8k.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3316 | 0.2623 |
| jfk_long_8k.wav | 11 | 31 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3496 | 0.2054 |
Error rates against the references
| File | WER (%) | CER (%) | Reference words |
|---|---|---|---|
| jfk.wav | 13.636 | 2.778 | 22 |
| jfk_long_8k.wav | 13.636 | 2.765 | 44 |
- 1 rows have no file path and are left out.
- 1 of 5 files couldn't be decoded, so their rows got missing values (first: aud2_speech/broken.wav).
The exact R script · R R version 4.5.1 (2025-06-13)
# Speech to text (Whisper)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.transcribe 1.1.0 · spec 10e898d098f83171
# Dataset: aud2_speech (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Audio files listed in the path column
PATH <- "path"
REFERENCE <- "reference"
MODEL <- "tiny"
LANGUAGE <- tolower(trimws("")) # empty: detected per file
if (!nzchar(LANGUAGE)) LANGUAGE <- NULL
TASK <- "translate"
TIMESTAMPS <- TRUE
CONDITION <- FALSE
NO_SPEECH <- 0.9
LOGPROB <- -2
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud2_speech.parquet", mustWork = FALSE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud2_speech.parquet", col_select = c(PATH, REFERENCE)))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
if (!is.null(LANGUAGE) && !(LANGUAGE %in% cs_whisper_model_languages(MODEL))) {
cs_error("CS_E_INVALID_OPTION", option = "language", allowed = "a language code Whisper knows (en, de, es, …) or empty", value = LANGUAGE)
}
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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-98732/audio.transcribe/translate_no_context/out-r", df,
"tests/parity/fixtures/aud2_speech.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 <- list()
ids_or_na <- vapply(seq_along(paths), function(i) if (is.na(paths[i]) || is.na(media_ids[i])) NA_character_ else as.character(media_ids[i]), "")
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, ids_or_na))
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)) {
i <- unreadable[1]
cs_error("CS_E_MEDIA_DECODE", file = paths[i], reason = status[i])
}
if (n_no_path > 0) warnings <- c(warnings, sprintf("%d rows have no file path and are left out.", n_no_path))
# %% Whisper (greedy decoding, 30-second windows; ADR 0101)
cs_deep_profile_configure(list(profile = "parity"))
model <- cs_whisper_load(cs_whisper_locate(MODEL))
files <- list(); segs <- list(); token_lists <- list()
first_failure <- NULL
for (k in seq_along(ok)) {
i <- ok[k]
# Outside the app the files are decoded here, so a bad file shows up now.
clip <- tryCatch(cs_media_audio(media, media_ids[i])[[1]], cs_error = function(e) {
if (!(e$code %in% c("CS_E_MEDIA_DECODE", "CS_E_MEDIA_UNSUPPORTED"))) stop(e)
e
})
if (inherits(clip, "cs_error")) {
unreadable <- c(unreadable, i)
if (is.null(first_failure)) first_failure <- clip
next
}
r <- cs_whisper_transcribe(model, clip, LANGUAGE, TASK, TIMESTAMPS, CONDITION, NO_SPEECH, LOGPROB)
token_lists[[k]] <- r$tokens
files[[k]] <- list(row = i - 1L, media_id = media_ids[i], path = paths[i], language = r$language, language_prob = r$language_prob,
duration_s = r$duration, segments = length(r$segments), text = r$text, windows = r$windows, skipped = r$skipped)
for (j in seq_along(r$segments)) {
s <- r$segments[[j]]
segs[[length(segs) + 1L]] <- list(media_id = media_ids[i], path = paths[i], row = i - 1L, segment = j, start = s$start, end = s$end,
text = s$text, avg_logprob = s$avg_logprob, no_speech_prob = s$no_speech_prob, language = r$language)
}
}
if (!length(files)) stop(first_failure)
unreadable <- sort(unreadable)
if (length(unreadable)) {
warnings <- c(warnings, cs_warning("CS_W_MEDIA_SKIPPED", count = length(unreadable), total = nrow(df) - n_no_path,
file = paths[unreadable[1]]))
}
fcol <- function(x, key, type = "") vapply(x, function(e) e[[key]], type)
# %% Artifacts: one row per file (row-aligned with the input) and one row per timed segment
out <- cs_ml_out_dir("target/academy-parity/run-98732/audio.transcribe/translate_no_context/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(fcol(files, "row", 1L)), text = fcol(files, "text", ""),
language = fcol(files, "language", ""), stringsAsFactors = FALSE),
file.path(out, "transcripts.parquet"))
seg_df <- data.frame(
media_id = fcol(segs, "media_id", ""), path = fcol(segs, "path", ""), row = as.integer(fcol(segs, "row", 1L)),
segment = as.integer(fcol(segs, "segment", 1L)), start = fcol(segs, "start", 0), end = fcol(segs, "end", 0),
text = fcol(segs, "text", ""), avg_logprob = fcol(segs, "avg_logprob", 0), no_speech_prob = fcol(segs, "no_speech_prob", 0),
language = fcol(segs, "language", ""), stringsAsFactors = FALSE
)
nanoparquet::write_parquet(seg_df, file.path(out, "segments.parquet"))
# %% Result
lang_all <- fcol(files, "language", "")
langs <- table(lang_all)
lang_codes <- names(langs)
lang_n <- as.integer(langs)
ord <- order(-lang_n, lang_codes, method = "radix")
top_language <- lang_codes[ord[1]]
lp <- fcol(segs, "avg_logprob", 0)
texts <- fcol(files, "text", "")
values <- list(
n_rows = nrow(df),
n_files = nrow(df) - n_no_path,
n_transcribed = length(files),
n_unreadable = length(unreadable),
n_no_path = n_no_path,
audio_seconds = sum(fcol(files, "duration_s", 0)),
speech_seconds = sum(fcol(segs, "end", 0) - fcol(segs, "start", 0)),
n_segments = length(segs),
n_windows = sum(fcol(files, "windows", 1L)),
n_skipped_windows = sum(fcol(files, "skipped", 1L)),
n_tokens = sum(lengths(token_lists)),
n_words = sum(cs_whisper_word_count(texts)),
token_check = cs_whisper_token_check(token_lists),
mean_avg_logprob = if (length(lp)) mean(lp) else NULL,
mean_no_speech_prob = if (length(segs)) mean(fcol(segs, "no_speech_prob", 0)) else NULL,
n_low_confidence = sum(lp < LOGPROB),
language = top_language,
n_languages = length(lang_codes),
model = MODEL,
task = TASK
)
for (code in sort(lang_codes, method = "radix")) values[[sprintf("language[%s]", code)]] <- as.integer(langs[[code]])
for (k in seq_len(min(20L, length(files)))) {
values[[sprintf("text[%d]", k)]] <- files[[k]]$text
if (!is.null(files[[k]]$language_prob)) values[[sprintf("language_prob[%d]", k)]] <- files[[k]]$language_prob
}
short <- function(t) if (nchar(t) <= 600) t else paste0(substr(t, 1, 600), " …")
tables <- list(
list(key = "transcripts", title = "Transcripts", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "language", label = "Language", type = "string"),
list(key = "duration", label = "Length (s)", type = "number"), list(key = "segments", label = "Segments", type = "integer"),
list(key = "text", label = "Transcript", type = "string")),
rows = lapply(files, function(f) list(file = basename(f$path), language = f$language, duration = f$duration_s, segments = f$segments,
text = short(f$text)))),
list(key = "segments", title = if (length(segs) > 500) "Segments (first 500)" else "Segments", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "start", label = "Start (s)", type = "number"), list(key = "end", label = "End (s)", type = "number"),
list(key = "text", label = "Text", type = "string"), list(key = "avg_logprob", label = "Avg log-probability", type = "number"),
list(key = "no_speech_prob", label = "No-speech probability", type = "number")),
rows = lapply(utils::head(segs, 500), function(s) list(file = basename(s$path), start = s$start, end = s$end, text = s$text,
avg_logprob = s$avg_logprob, no_speech_prob = s$no_speech_prob)))
)
# %% Word and character error rates against the references (R/text_error_rates.R, as in evaluate.text)
LOWER <- TRUE
refs_all <- as.character(df[[REFERENCE]])
has_ref <- vapply(files, function(f) { x <- refs_all[f$row + 1L]; !is.na(x) && nzchar(trimws(x)) }, TRUE)
scored <- files[has_ref]
values$n_scored <- length(scored)
if (length(scored)) {
e <- colSums(cs_tm_error_segments(vapply(scored, function(f) f$text, ""), lapply(scored, function(f) refs_all[f$row + 1L]), lowercase = LOWER))
values["wer"] <- list(cs_tm_error_rate(e[1], e[2])); values["cer"] <- list(cs_tm_error_rate(e[6], e[7]))
values$wer_sub <- as.integer(e[3]); values$wer_del <- as.integer(e[4]); values$wer_ins <- as.integer(e[5])
values$wer_ref_words <- as.integer(e[2]); values$cer_ref_chars <- as.integer(e[7])
rows_er <- lapply(scored, function(f) {
x <- cs_tm_error_segments(f$text, list(refs_all[f$row + 1L]), lowercase = LOWER)[1, ]
list(file = basename(f$path), wer = cs_tm_error_rate(x[1], x[2]), cer = cs_tm_error_rate(x[6], x[7]), words = as.integer(x[2]))
})
tables[[length(tables) + 1L]] <- list(key = "error_rates", title = "Error rates against the references", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "wer", label = "WER (%)", type = "number"), list(key = "cer", label = "CER (%)", type = "number"),
list(key = "words", label = "Reference words", type = "integer")), rows = rows_er)
} else {
warnings <- c(warnings, "No transcribed file has a reference, so no error rates.")
}
charts <- list()
if (length(segs)) {
lane_rows <- vapply(utils::head(files, 30), function(f) f$row, 1L) # one lane per file, at most 30
lanes <- unique(vapply(utils::head(files, 30), function(f) basename(f$path), ""))
shown <- Filter(function(s) s$row %in% lane_rows, segs)
charts[[length(charts) + 1L]] <- cs_chart("timeline", "segment-timeline", "Segments over time", list(
start = cs_col("Start (s)", vapply(shown, function(s) s$start, 0), "numeric"),
end = cs_col("End (s)", vapply(shown, function(s) s$end, 0), "numeric"),
lane = cs_col("File", vapply(shown, function(s) basename(s$path), ""), "categorical", lanes),
label = cs_col("Text", vapply(shown, function(s) s$text, ""), "categorical"),
value = cs_col("Average log-probability", vapply(shown, function(s) s$avg_logprob, 0), "numeric")
), controls = list(labels = TRUE, overlap = FALSE))
}
if (length(lp)) {
charts[[length(charts) + 1L]] <- cs_chart("confidence", "histogram", "Average log-probability of each segment",
list(x = cs_col("Average log-probability per token", lp, "numeric")), controls = list(scale = "count", kde = FALSE))
}
detected <- paste(sprintf("%s (%d)", lang_codes[ord], lang_n[ord]), collapse = ", ")
assumptions <- c(list(
list(key = "hallucination", label = "Text can be invented", status = if (values$n_low_confidence > 0) "warn" else "info",
message = if (values$n_low_confidence > 0) {
sprintf("%d of %d segments have an average log-probability below %s: listen to them before relying on the text.",
values$n_low_confidence, length(segs), format(LOGPROB))
} else {
"No segment falls below the log-probability cutoff; Whisper can still mishear names and numbers."
}),
list(key = "language_detection", label = "Language from the first 30 seconds", status = "info",
message = if (!is.null(LANGUAGE)) sprintf("Set to %s for every file.", LANGUAGE) else sprintf("Detected per file: %s.", detected)),
list(key = "greedy_decoding", label = "One pass, no retries", status = "info",
message = sprintf("%d windows decoded once each; %d skipped as silence.", values$n_windows, values$n_skipped_windows)),
list(key = "speech_privacy", label = "Recordings of people", status = "info",
message = "Transcripts stay on this computer. Get consent before transcribing other people's recordings.")
), cs_deep_profile_warning_rows())
cs_publish(list(
title = "Speech to text (Whisper)",
engine = cs_engine_info("torch", "safetensors", "jsonlite", "nanoparquet", "codesplashr"),
n = length(files),
summary = sprintf("%d files (%.1f s) → %d segments, %d words; most common language %s.", length(files), values$audio_seconds,
length(segs), values$n_words, top_language),
statistics = list(
list(key = "n_transcribed", label = "Files transcribed", value = length(files)),
list(key = "n_segments", label = "Segments", value = length(segs)),
list(key = "n_words", label = "Words", value = values$n_words),
list(key = "mean_avg_logprob", label = "Mean log-probability", value = values$mean_avg_logprob)
),
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "transcripts", path = file.path(out, "transcripts.parquet"), format = "parquet"),
list(key = "segments", path = file.path(out, "segments.parquet"), format = "parquet"))
))
4 files (48.0 s) → 5 segments, 180 words; most common language en.
- Files transcribed
- 4
- Segments
- 5
- Words
- 180
- Mean log-probability
- −0.4774
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Text can be invented
- Language from the first 30 seconds
- One pass, no retries
- Recordings of people
Transcripts
| File | Language | Length (s) | Segments | Transcript |
|---|---|---|---|---|
| jfk.wav | en | 11 | 1 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
| vowels.wav | en | 2.500 | 1 | Ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah |
| quiet.wav | en | 1.500 | 1 | Thank you. |
| jfk_long_8k.wav | en | 33 | 2 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
Segments
| File | Start (s) | End (s) | Text | Avg log-probability | No-speech probability |
|---|---|---|---|---|---|
| jfk.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3319 | 0.0692 |
| vowels.wav | 0 | 2.500 | Ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah, ah | −0.0551 | 0.6014 |
| quiet.wav | 0 | 2 | Thank you. | −1.319 | 0.8613 |
| jfk_long_8k.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3316 | 0.2623 |
| jfk_long_8k.wav | 11 | 31 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.3496 | 0.2054 |
Error rates against the references
| File | WER (%) | CER (%) | Reference words |
|---|---|---|---|
| jfk.wav | 13.636 | 2.778 | 22 |
| jfk_long_8k.wav | 13.636 | 2.765 | 44 |
- 1 rows have no file path and are left out.
- 1 of 5 files couldn't be decoded, so their rows got missing values (first: aud2_speech/broken.wav).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Speech to text (Whisper)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.transcribe 1.1.0 · spec 10e898d098f83171
# Dataset: aud2_speech (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
from collections import Counter
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import whisper as wh
from codesplash.deep import profile as cs_profile
# %% Audio files listed in the path column
PATH = "path"
REFERENCE = "reference"
MODEL = "tiny"
LANGUAGE = "".strip().lower() or None # empty: detected per file
TASK = "translate"
TIMESTAMPS = True
CONDITION = False
NO_SPEECH = 0.9
LOGPROB = -2
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud2_speech.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud2_speech.parquet", columns=[PATH] if REFERENCE is None else [PATH, REFERENCE])
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
if LANGUAGE is not None and LANGUAGE not in wh.languages(MODEL):
cs.cs_error("CS_E_INVALID_OPTION", option="language", allowed="a language code Whisper knows (en, de, es, …) or empty", value=LANGUAGE)
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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-98732/audio.transcribe/translate_no_context/out-python", df, "tests/parity/fixtures/aud2_speech.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.")
# %% Whisper (greedy decoding, 30-second windows; ADR 0101)
cs_profile.configure({"profile": "parity"})
model = wh.load(wh.locate(MODEL))
progress = cs.progress(f"Transcribing {len(ok)} files with Whisper {MODEL}", total=len(ok))
files, segs, token_lists = [], [], []
first_failure = None
for k, i in enumerate(ok):
try:
clip = cs_media.audio(media, [media_ids[i]])[0]
except cs.CsError as e: # outside the app the files are decoded here, so a bad file shows up now
if e.code not in ("CS_E_MEDIA_DECODE", "CS_E_MEDIA_UNSUPPORTED"):
raise
unreadable.append(i)
first_failure = first_failure or e
progress.update(k + 1)
continue
r = wh.transcribe(model, clip, LANGUAGE, TASK, TIMESTAMPS, CONDITION, NO_SPEECH, LOGPROB)
token_lists.append(r["tokens"])
files.append({"row": i, "media_id": media_ids[i], "path": paths[i], "language": r["language"], "language_prob": r["language_prob"],
"duration_s": r["duration"], "segments": len(r["segments"]), "text": r["text"], "windows": r["windows"], "skipped": r["skipped"]})
for j, s in enumerate(r["segments"], start=1):
segs.append({"media_id": media_ids[i], "path": paths[i], "row": i, "segment": j, "start": s["start"], "end": s["end"], "text": s["text"],
"avg_logprob": s["avg_logprob"], "no_speech_prob": s["no_speech_prob"], "language": r["language"]})
progress.update(k + 1)
progress.done()
if not files:
raise first_failure
unreadable.sort()
if unreadable:
warnings.append(cs.cs_warning("CS_W_MEDIA_SKIPPED", count=len(unreadable), total=len(df) - n_no_path, file=paths[unreadable[0]]))
# %% Artifacts: one row per file (row-aligned with the input) and one row per timed segment
out = csml.out_dir("target/academy-parity/run-98732/audio.transcribe/translate_no_context/out-python")
pd.DataFrame({"row": np.array([f["row"] for f in files], dtype=np.int64), "text": [f["text"] for f in files],
"language": [f["language"] for f in files]}).to_parquet(os.path.join(out, "transcripts.parquet"), index=False)
seg_df = pd.DataFrame(segs, columns=["media_id", "path", "row", "segment", "start", "end", "text", "avg_logprob", "no_speech_prob", "language"])
seg_df["row"] = seg_df["row"].astype(np.int64)
seg_df["segment"] = seg_df["segment"].astype(np.int64)
seg_df.to_parquet(os.path.join(out, "segments.parquet"), index=False)
# %% Result
langs = Counter(f["language"] for f in files)
top_language = sorted(langs.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
lp = [s["avg_logprob"] for s in segs]
values = {
"n_rows": len(df),
"n_files": len(df) - n_no_path,
"n_transcribed": len(files),
"n_unreadable": len(unreadable),
"n_no_path": n_no_path,
"audio_seconds": float(sum(f["duration_s"] for f in files)),
"speech_seconds": float(sum(s["end"] - s["start"] for s in segs)),
"n_segments": len(segs),
"n_windows": sum(f["windows"] for f in files),
"n_skipped_windows": sum(f["skipped"] for f in files),
"n_tokens": sum(len(t) for t in token_lists),
"n_words": sum(len(f["text"].split()) for f in files),
"token_check": wh.token_check(token_lists),
"mean_avg_logprob": float(np.mean(lp)) if lp else None,
"mean_no_speech_prob": float(np.mean([s["no_speech_prob"] for s in segs])) if segs else None,
"n_low_confidence": sum(v < LOGPROB for v in lp),
"language": top_language,
"n_languages": len(langs),
"model": MODEL,
"task": TASK,
}
for code in sorted(langs):
values[f"language[{code}]"] = langs[code]
for k, f in enumerate(files[:20], start=1):
values[f"text[{k}]"] = f["text"]
if f["language_prob"] is not None:
values[f"language_prob[{k}]"] = f["language_prob"]
tables = [
{"key": "transcripts", "title": "Transcripts", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "language", "label": "Language", "type": "string"},
{"key": "duration", "label": "Length (s)", "type": "number"}, {"key": "segments", "label": "Segments", "type": "integer"},
{"key": "text", "label": "Transcript", "type": "string"}],
"rows": [{"file": os.path.basename(f["path"]), "language": f["language"], "duration": f["duration_s"], "segments": f["segments"],
"text": f["text"] if len(f["text"]) <= 600 else f["text"][:600] + " …"} for f in files]},
{"key": "segments", "title": f"Segments{' (first 500)' if len(segs) > 500 else ''}", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "start", "label": "Start (s)", "type": "number"}, {"key": "end", "label": "End (s)", "type": "number"},
{"key": "text", "label": "Text", "type": "string"}, {"key": "avg_logprob", "label": "Avg log-probability", "type": "number"},
{"key": "no_speech_prob", "label": "No-speech probability", "type": "number"}],
"rows": [{"file": os.path.basename(s["path"]), "start": s["start"], "end": s["end"], "text": s["text"], "avg_logprob": s["avg_logprob"],
"no_speech_prob": s["no_speech_prob"]} for s in segs[:500]]},
]
# %% Word and character error rates against the references (codesplash.text.error_rates, as in evaluate.text)
from codesplash.text import error_rates as er
LOWER = True
refs_all = df[REFERENCE].tolist()
scored = [f for f in files if refs_all[f["row"]] is not None and not (isinstance(refs_all[f["row"]], float) and refs_all[f["row"]] != refs_all[f["row"]])
and str(refs_all[f["row"]]).strip()]
values["n_scored"] = len(scored)
if scored:
e = er.segments([f["text"] for f in scored], [[str(refs_all[f["row"]])] for f in scored], lowercase=LOWER).sum(axis=0)
values.update({"wer": er.rate(e[0], e[1]), "cer": er.rate(e[5], e[6]), "wer_sub": int(e[2]), "wer_del": int(e[3]), "wer_ins": int(e[4]),
"wer_ref_words": int(e[1]), "cer_ref_chars": int(e[6])})
rows_er = []
for f in scored:
x = er.segments([f["text"]], [[str(refs_all[f["row"]])]], lowercase=LOWER)[0]
rows_er.append({"file": os.path.basename(f["path"]), "wer": er.rate(x[0], x[1]), "cer": er.rate(x[5], x[6]), "words": int(x[1])})
tables.append({"key": "error_rates", "title": "Error rates against the references", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "wer", "label": "WER (%)", "type": "number"}, {"key": "cer", "label": "CER (%)", "type": "number"},
{"key": "words", "label": "Reference words", "type": "integer"}], "rows": rows_er})
else:
warnings.append("No transcribed file has a reference, so no error rates.")
charts = []
if segs:
lane_rows = [f["row"] for f in files[:30]] # one lane per file, at most 30
lanes = list(dict.fromkeys(os.path.basename(f["path"]) for f in files[:30]))
shown = [s for s in segs if s["row"] in lane_rows]
charts.append(cs.chart("timeline", "segment-timeline", "Segments over time", {
"start": cs.col("Start (s)", [s["start"] for s in shown], "numeric"),
"end": cs.col("End (s)", [s["end"] for s in shown], "numeric"),
"lane": cs.col("File", [os.path.basename(s["path"]) for s in shown], "categorical", lanes),
"label": cs.col("Text", [s["text"] for s in shown], "categorical"),
"value": cs.col("Average log-probability", [s["avg_logprob"] for s in shown], "numeric"),
}, controls={"labels": True, "overlap": False}))
if lp:
charts.append(cs.chart("confidence", "histogram", "Average log-probability of each segment", {
"x": cs.col("Average log-probability per token", lp, "numeric")}, controls={"scale": "count", "kde": False}))
assumptions = [
{"key": "hallucination", "label": "Text can be invented", "status": "warn" if values["n_low_confidence"] else "info",
"message": (f"{values['n_low_confidence']} of {len(segs)} segments have an average log-probability below {LOGPROB:g}: listen to them before relying on the text."
if values["n_low_confidence"] else "No segment falls below the log-probability cutoff; Whisper can still mishear names and numbers.")},
{"key": "language_detection", "label": "Language from the first 30 seconds", "status": "info",
"message": (f"Set to {LANGUAGE} for every file." if LANGUAGE else f"Detected per file: {', '.join(f'{c} ({n})' for c, n in sorted(langs.items(), key=lambda kv: (-kv[1], kv[0])))}.")},
{"key": "greedy_decoding", "label": "One pass, no retries", "status": "info",
"message": f"{values['n_windows']} windows decoded once each; {values['n_skipped_windows']} skipped as silence."},
{"key": "speech_privacy", "label": "Recordings of people", "status": "info",
"message": "Transcripts stay on this computer. Get consent before transcribing other people's recordings."},
] + cs_profile.warning_rows()
cs.publish({
"title": "Speech to text (Whisper)",
"engine": cs.engine_info("torch", "safetensors", "numpy", "pandas"),
"n": len(files),
"summary": f"{len(files)} files ({values['audio_seconds']:.1f} s) → {len(segs)} segments, {values['n_words']} words; most common language {top_language}.",
"statistics": [
{"key": "n_transcribed", "label": "Files transcribed", "value": len(files)},
{"key": "n_segments", "label": "Segments", "value": len(segs)},
{"key": "n_words", "label": "Words", "value": values["n_words"]},
{"key": "mean_avg_logprob", "label": "Mean log-probability", "value": values["mean_avg_logprob"]},
],
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "transcripts", "path": os.path.join(out, "transcripts.parquet"), "format": "parquet"},
{"key": "segments", "path": os.path.join(out, "segments.parquet"), "format": "parquet"}],
})
Here the silence gate was set loose (no-speech threshold 0.9), so the near-silent file was decoded too, and Whisper wrote "Thank you." to it. That is invented textInvented transcript textFluent text nobody said, often on silence, music or noise ("Thank you."), or a phrase repeated until the window ends.: common on silence, music and noise. The no-speech probabilityNo-speech probabilityWhisper's own estimate, at the start of each window, that the window has no speech worth writing down. was high, but not above 0.9.
Check yourself
A transcript of a long pause reads "Thank you for watching." What is the best next step?
Show the answer
Answer: b
Whisper learned that videos often end with thanks, so silence pulls that phrase out. Confidence measures how sure the model was, not whether anyone spoke.
Scoring against references
Checkpoint4 files (48.0 s) → 4 segments, 270 words; most common language en.
- Files transcribed
- 4
- Segments
- 4
- Words
- 270
- Mean log-probability
- −0.4138
Plots
View data
| End (s) | Text | File | Start (s) | Average log-probability |
|---|---|---|---|---|
| 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk.wav | 0 | −0.1683 |
| 2.500 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah | vowels.wav | 0 | −0.0599 |
| 30 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | jfk_long_8k.wav | 0 | −0.2339 |
| 33 | God, free. | jfk_long_8k.wav | 30 | −1.193 |
View data
| Average log-probability per token |
|---|
| −0.1683 |
| −0.0599 |
| −0.2339 |
| −1.193 |
Assumptions
- Text can be invented
- Language from the first 30 seconds
- One pass, no retries
- Recordings of people
Transcripts
| File | Language | Length (s) | Segments | Transcript |
|---|---|---|---|---|
| jfk.wav | en | 11 | 1 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
| vowels.wav | en | 2.500 | 1 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah … |
| quiet.wav | en | 1.500 | 0 | |
| jfk_long_8k.wav | en | 33 | 2 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. God, free. |
Segments
| File | Start (s) | End (s) | Text | Avg log-probability | No-speech probability |
|---|---|---|---|---|---|
| jfk.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.1683 | 0.0692 |
| vowels.wav | 0 | 2.500 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah | −0.0599 | 0.6014 |
| jfk_long_8k.wav | 0 | 30 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.2339 | 0.2623 |
| jfk_long_8k.wav | 30 | 33 | God, free. | −1.193 | 0.2446 |
Error rates against the references
| File | WER (%) | CER (%) | Reference words |
|---|---|---|---|
| jfk.wav | 13.636 | 2.778 | 22 |
| jfk_long_8k.wav | 56.818 | 47.926 | 44 |
- 1 rows have no file path and are left out.
- 1 of 5 files couldn't be decoded, so their rows got missing values (first: aud2_speech/broken.wav).
The exact R script · R R version 4.5.1 (2025-06-13)
# Speech to text (Whisper)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.transcribe 1.1.0 · spec 0ff81111bf1cd49a
# Dataset: aud2_speech (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Audio files listed in the path column
PATH <- "path"
REFERENCE <- "reference"
MODEL <- "tiny"
LANGUAGE <- tolower(trimws("en")) # empty: detected per file
if (!nzchar(LANGUAGE)) LANGUAGE <- NULL
TASK <- "transcribe"
TIMESTAMPS <- FALSE
CONDITION <- TRUE
NO_SPEECH <- 0.6
LOGPROB <- -1
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud2_speech.parquet", mustWork = FALSE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud2_speech.parquet", col_select = c(PATH, REFERENCE)))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
if (!is.null(LANGUAGE) && !(LANGUAGE %in% cs_whisper_model_languages(MODEL))) {
cs_error("CS_E_INVALID_OPTION", option = "language", allowed = "a language code Whisper knows (en, de, es, …) or empty", value = LANGUAGE)
}
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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-98732/audio.transcribe/references_english_no_timestamps/out-r", df,
"tests/parity/fixtures/aud2_speech.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 <- list()
ids_or_na <- vapply(seq_along(paths), function(i) if (is.na(paths[i]) || is.na(media_ids[i])) NA_character_ else as.character(media_ids[i]), "")
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, ids_or_na))
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)) {
i <- unreadable[1]
cs_error("CS_E_MEDIA_DECODE", file = paths[i], reason = status[i])
}
if (n_no_path > 0) warnings <- c(warnings, sprintf("%d rows have no file path and are left out.", n_no_path))
# %% Whisper (greedy decoding, 30-second windows; ADR 0101)
cs_deep_profile_configure(list(profile = "parity"))
model <- cs_whisper_load(cs_whisper_locate(MODEL))
files <- list(); segs <- list(); token_lists <- list()
first_failure <- NULL
for (k in seq_along(ok)) {
i <- ok[k]
# Outside the app the files are decoded here, so a bad file shows up now.
clip <- tryCatch(cs_media_audio(media, media_ids[i])[[1]], cs_error = function(e) {
if (!(e$code %in% c("CS_E_MEDIA_DECODE", "CS_E_MEDIA_UNSUPPORTED"))) stop(e)
e
})
if (inherits(clip, "cs_error")) {
unreadable <- c(unreadable, i)
if (is.null(first_failure)) first_failure <- clip
next
}
r <- cs_whisper_transcribe(model, clip, LANGUAGE, TASK, TIMESTAMPS, CONDITION, NO_SPEECH, LOGPROB)
token_lists[[k]] <- r$tokens
files[[k]] <- list(row = i - 1L, media_id = media_ids[i], path = paths[i], language = r$language, language_prob = r$language_prob,
duration_s = r$duration, segments = length(r$segments), text = r$text, windows = r$windows, skipped = r$skipped)
for (j in seq_along(r$segments)) {
s <- r$segments[[j]]
segs[[length(segs) + 1L]] <- list(media_id = media_ids[i], path = paths[i], row = i - 1L, segment = j, start = s$start, end = s$end,
text = s$text, avg_logprob = s$avg_logprob, no_speech_prob = s$no_speech_prob, language = r$language)
}
}
if (!length(files)) stop(first_failure)
unreadable <- sort(unreadable)
if (length(unreadable)) {
warnings <- c(warnings, cs_warning("CS_W_MEDIA_SKIPPED", count = length(unreadable), total = nrow(df) - n_no_path,
file = paths[unreadable[1]]))
}
fcol <- function(x, key, type = "") vapply(x, function(e) e[[key]], type)
# %% Artifacts: one row per file (row-aligned with the input) and one row per timed segment
out <- cs_ml_out_dir("target/academy-parity/run-98732/audio.transcribe/references_english_no_timestamps/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(fcol(files, "row", 1L)), text = fcol(files, "text", ""),
language = fcol(files, "language", ""), stringsAsFactors = FALSE),
file.path(out, "transcripts.parquet"))
seg_df <- data.frame(
media_id = fcol(segs, "media_id", ""), path = fcol(segs, "path", ""), row = as.integer(fcol(segs, "row", 1L)),
segment = as.integer(fcol(segs, "segment", 1L)), start = fcol(segs, "start", 0), end = fcol(segs, "end", 0),
text = fcol(segs, "text", ""), avg_logprob = fcol(segs, "avg_logprob", 0), no_speech_prob = fcol(segs, "no_speech_prob", 0),
language = fcol(segs, "language", ""), stringsAsFactors = FALSE
)
nanoparquet::write_parquet(seg_df, file.path(out, "segments.parquet"))
# %% Result
lang_all <- fcol(files, "language", "")
langs <- table(lang_all)
lang_codes <- names(langs)
lang_n <- as.integer(langs)
ord <- order(-lang_n, lang_codes, method = "radix")
top_language <- lang_codes[ord[1]]
lp <- fcol(segs, "avg_logprob", 0)
texts <- fcol(files, "text", "")
values <- list(
n_rows = nrow(df),
n_files = nrow(df) - n_no_path,
n_transcribed = length(files),
n_unreadable = length(unreadable),
n_no_path = n_no_path,
audio_seconds = sum(fcol(files, "duration_s", 0)),
speech_seconds = sum(fcol(segs, "end", 0) - fcol(segs, "start", 0)),
n_segments = length(segs),
n_windows = sum(fcol(files, "windows", 1L)),
n_skipped_windows = sum(fcol(files, "skipped", 1L)),
n_tokens = sum(lengths(token_lists)),
n_words = sum(cs_whisper_word_count(texts)),
token_check = cs_whisper_token_check(token_lists),
mean_avg_logprob = if (length(lp)) mean(lp) else NULL,
mean_no_speech_prob = if (length(segs)) mean(fcol(segs, "no_speech_prob", 0)) else NULL,
n_low_confidence = sum(lp < LOGPROB),
language = top_language,
n_languages = length(lang_codes),
model = MODEL,
task = TASK
)
for (code in sort(lang_codes, method = "radix")) values[[sprintf("language[%s]", code)]] <- as.integer(langs[[code]])
for (k in seq_len(min(20L, length(files)))) {
values[[sprintf("text[%d]", k)]] <- files[[k]]$text
if (!is.null(files[[k]]$language_prob)) values[[sprintf("language_prob[%d]", k)]] <- files[[k]]$language_prob
}
short <- function(t) if (nchar(t) <= 600) t else paste0(substr(t, 1, 600), " …")
tables <- list(
list(key = "transcripts", title = "Transcripts", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "language", label = "Language", type = "string"),
list(key = "duration", label = "Length (s)", type = "number"), list(key = "segments", label = "Segments", type = "integer"),
list(key = "text", label = "Transcript", type = "string")),
rows = lapply(files, function(f) list(file = basename(f$path), language = f$language, duration = f$duration_s, segments = f$segments,
text = short(f$text)))),
list(key = "segments", title = if (length(segs) > 500) "Segments (first 500)" else "Segments", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "start", label = "Start (s)", type = "number"), list(key = "end", label = "End (s)", type = "number"),
list(key = "text", label = "Text", type = "string"), list(key = "avg_logprob", label = "Avg log-probability", type = "number"),
list(key = "no_speech_prob", label = "No-speech probability", type = "number")),
rows = lapply(utils::head(segs, 500), function(s) list(file = basename(s$path), start = s$start, end = s$end, text = s$text,
avg_logprob = s$avg_logprob, no_speech_prob = s$no_speech_prob)))
)
# %% Word and character error rates against the references (R/text_error_rates.R, as in evaluate.text)
LOWER <- FALSE
refs_all <- as.character(df[[REFERENCE]])
has_ref <- vapply(files, function(f) { x <- refs_all[f$row + 1L]; !is.na(x) && nzchar(trimws(x)) }, TRUE)
scored <- files[has_ref]
values$n_scored <- length(scored)
if (length(scored)) {
e <- colSums(cs_tm_error_segments(vapply(scored, function(f) f$text, ""), lapply(scored, function(f) refs_all[f$row + 1L]), lowercase = LOWER))
values["wer"] <- list(cs_tm_error_rate(e[1], e[2])); values["cer"] <- list(cs_tm_error_rate(e[6], e[7]))
values$wer_sub <- as.integer(e[3]); values$wer_del <- as.integer(e[4]); values$wer_ins <- as.integer(e[5])
values$wer_ref_words <- as.integer(e[2]); values$cer_ref_chars <- as.integer(e[7])
rows_er <- lapply(scored, function(f) {
x <- cs_tm_error_segments(f$text, list(refs_all[f$row + 1L]), lowercase = LOWER)[1, ]
list(file = basename(f$path), wer = cs_tm_error_rate(x[1], x[2]), cer = cs_tm_error_rate(x[6], x[7]), words = as.integer(x[2]))
})
tables[[length(tables) + 1L]] <- list(key = "error_rates", title = "Error rates against the references", columns = list(
list(key = "file", label = "File", type = "string"), list(key = "wer", label = "WER (%)", type = "number"), list(key = "cer", label = "CER (%)", type = "number"),
list(key = "words", label = "Reference words", type = "integer")), rows = rows_er)
} else {
warnings <- c(warnings, "No transcribed file has a reference, so no error rates.")
}
charts <- list()
if (length(segs)) {
lane_rows <- vapply(utils::head(files, 30), function(f) f$row, 1L) # one lane per file, at most 30
lanes <- unique(vapply(utils::head(files, 30), function(f) basename(f$path), ""))
shown <- Filter(function(s) s$row %in% lane_rows, segs)
charts[[length(charts) + 1L]] <- cs_chart("timeline", "segment-timeline", "Segments over time", list(
start = cs_col("Start (s)", vapply(shown, function(s) s$start, 0), "numeric"),
end = cs_col("End (s)", vapply(shown, function(s) s$end, 0), "numeric"),
lane = cs_col("File", vapply(shown, function(s) basename(s$path), ""), "categorical", lanes),
label = cs_col("Text", vapply(shown, function(s) s$text, ""), "categorical"),
value = cs_col("Average log-probability", vapply(shown, function(s) s$avg_logprob, 0), "numeric")
), controls = list(labels = TRUE, overlap = FALSE))
}
if (length(lp)) {
charts[[length(charts) + 1L]] <- cs_chart("confidence", "histogram", "Average log-probability of each segment",
list(x = cs_col("Average log-probability per token", lp, "numeric")), controls = list(scale = "count", kde = FALSE))
}
detected <- paste(sprintf("%s (%d)", lang_codes[ord], lang_n[ord]), collapse = ", ")
assumptions <- c(list(
list(key = "hallucination", label = "Text can be invented", status = if (values$n_low_confidence > 0) "warn" else "info",
message = if (values$n_low_confidence > 0) {
sprintf("%d of %d segments have an average log-probability below %s: listen to them before relying on the text.",
values$n_low_confidence, length(segs), format(LOGPROB))
} else {
"No segment falls below the log-probability cutoff; Whisper can still mishear names and numbers."
}),
list(key = "language_detection", label = "Language from the first 30 seconds", status = "info",
message = if (!is.null(LANGUAGE)) sprintf("Set to %s for every file.", LANGUAGE) else sprintf("Detected per file: %s.", detected)),
list(key = "greedy_decoding", label = "One pass, no retries", status = "info",
message = sprintf("%d windows decoded once each; %d skipped as silence.", values$n_windows, values$n_skipped_windows)),
list(key = "speech_privacy", label = "Recordings of people", status = "info",
message = "Transcripts stay on this computer. Get consent before transcribing other people's recordings.")
), cs_deep_profile_warning_rows())
cs_publish(list(
title = "Speech to text (Whisper)",
engine = cs_engine_info("torch", "safetensors", "jsonlite", "nanoparquet", "codesplashr"),
n = length(files),
summary = sprintf("%d files (%.1f s) → %d segments, %d words; most common language %s.", length(files), values$audio_seconds,
length(segs), values$n_words, top_language),
statistics = list(
list(key = "n_transcribed", label = "Files transcribed", value = length(files)),
list(key = "n_segments", label = "Segments", value = length(segs)),
list(key = "n_words", label = "Words", value = values$n_words),
list(key = "mean_avg_logprob", label = "Mean log-probability", value = values$mean_avg_logprob)
),
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "transcripts", path = file.path(out, "transcripts.parquet"), format = "parquet"),
list(key = "segments", path = file.path(out, "segments.parquet"), format = "parquet"))
))
4 files (48.0 s) → 4 segments, 270 words; most common language en.
- Files transcribed
- 4
- Segments
- 4
- Words
- 270
- Mean log-probability
- −0.4138
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Text can be invented
- Language from the first 30 seconds
- One pass, no retries
- Recordings of people
Transcripts
| File | Language | Length (s) | Segments | Transcript |
|---|---|---|---|---|
| jfk.wav | en | 11 | 1 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. |
| vowels.wav | en | 2.500 | 1 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah … |
| quiet.wav | en | 1.500 | 0 | |
| jfk_long_8k.wav | en | 33 | 2 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. God, free. |
Segments
| File | Start (s) | End (s) | Text | Avg log-probability | No-speech probability |
|---|---|---|---|---|---|
| jfk.wav | 0 | 11 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.1683 | 0.0692 |
| vowels.wav | 0 | 2.500 | ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah | −0.0599 | 0.6014 |
| jfk_long_8k.wav | 0 | 30 | And so my fellow Americans ask not what your country can do for you ask what you can do for your country. | −0.2339 | 0.2623 |
| jfk_long_8k.wav | 30 | 33 | God, free. | −1.193 | 0.2446 |
Error rates against the references
| File | WER (%) | CER (%) | Reference words |
|---|---|---|---|
| jfk.wav | 13.636 | 2.778 | 22 |
| jfk_long_8k.wav | 56.818 | 47.926 | 44 |
- 1 rows have no file path and are left out.
- 1 of 5 files couldn't be decoded, so their rows got missing values (first: aud2_speech/broken.wav).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Speech to text (Whisper)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.transcribe 1.1.0 · spec 0ff81111bf1cd49a
# Dataset: aud2_speech (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
from collections import Counter
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import whisper as wh
from codesplash.deep import profile as cs_profile
# %% Audio files listed in the path column
PATH = "path"
REFERENCE = "reference"
MODEL = "tiny"
LANGUAGE = "en".strip().lower() or None # empty: detected per file
TASK = "transcribe"
TIMESTAMPS = False
CONDITION = True
NO_SPEECH = 0.6
LOGPROB = -1
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud2_speech.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud2_speech.parquet", columns=[PATH] if REFERENCE is None else [PATH, REFERENCE])
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
if LANGUAGE is not None and LANGUAGE not in wh.languages(MODEL):
cs.cs_error("CS_E_INVALID_OPTION", option="language", allowed="a language code Whisper knows (en, de, es, …) or empty", value=LANGUAGE)
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\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-98732/audio.transcribe/references_english_no_timestamps/out-python", df, "tests/parity/fixtures/aud2_speech.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.")
# %% Whisper (greedy decoding, 30-second windows; ADR 0101)
cs_profile.configure({"profile": "parity"})
model = wh.load(wh.locate(MODEL))
progress = cs.progress(f"Transcribing {len(ok)} files with Whisper {MODEL}", total=len(ok))
files, segs, token_lists = [], [], []
first_failure = None
for k, i in enumerate(ok):
try:
clip = cs_media.audio(media, [media_ids[i]])[0]
except cs.CsError as e: # outside the app the files are decoded here, so a bad file shows up now
if e.code not in ("CS_E_MEDIA_DECODE", "CS_E_MEDIA_UNSUPPORTED"):
raise
unreadable.append(i)
first_failure = first_failure or e
progress.update(k + 1)
continue
r = wh.transcribe(model, clip, LANGUAGE, TASK, TIMESTAMPS, CONDITION, NO_SPEECH, LOGPROB)
token_lists.append(r["tokens"])
files.append({"row": i, "media_id": media_ids[i], "path": paths[i], "language": r["language"], "language_prob": r["language_prob"],
"duration_s": r["duration"], "segments": len(r["segments"]), "text": r["text"], "windows": r["windows"], "skipped": r["skipped"]})
for j, s in enumerate(r["segments"], start=1):
segs.append({"media_id": media_ids[i], "path": paths[i], "row": i, "segment": j, "start": s["start"], "end": s["end"], "text": s["text"],
"avg_logprob": s["avg_logprob"], "no_speech_prob": s["no_speech_prob"], "language": r["language"]})
progress.update(k + 1)
progress.done()
if not files:
raise first_failure
unreadable.sort()
if unreadable:
warnings.append(cs.cs_warning("CS_W_MEDIA_SKIPPED", count=len(unreadable), total=len(df) - n_no_path, file=paths[unreadable[0]]))
# %% Artifacts: one row per file (row-aligned with the input) and one row per timed segment
out = csml.out_dir("target/academy-parity/run-98732/audio.transcribe/references_english_no_timestamps/out-python")
pd.DataFrame({"row": np.array([f["row"] for f in files], dtype=np.int64), "text": [f["text"] for f in files],
"language": [f["language"] for f in files]}).to_parquet(os.path.join(out, "transcripts.parquet"), index=False)
seg_df = pd.DataFrame(segs, columns=["media_id", "path", "row", "segment", "start", "end", "text", "avg_logprob", "no_speech_prob", "language"])
seg_df["row"] = seg_df["row"].astype(np.int64)
seg_df["segment"] = seg_df["segment"].astype(np.int64)
seg_df.to_parquet(os.path.join(out, "segments.parquet"), index=False)
# %% Result
langs = Counter(f["language"] for f in files)
top_language = sorted(langs.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
lp = [s["avg_logprob"] for s in segs]
values = {
"n_rows": len(df),
"n_files": len(df) - n_no_path,
"n_transcribed": len(files),
"n_unreadable": len(unreadable),
"n_no_path": n_no_path,
"audio_seconds": float(sum(f["duration_s"] for f in files)),
"speech_seconds": float(sum(s["end"] - s["start"] for s in segs)),
"n_segments": len(segs),
"n_windows": sum(f["windows"] for f in files),
"n_skipped_windows": sum(f["skipped"] for f in files),
"n_tokens": sum(len(t) for t in token_lists),
"n_words": sum(len(f["text"].split()) for f in files),
"token_check": wh.token_check(token_lists),
"mean_avg_logprob": float(np.mean(lp)) if lp else None,
"mean_no_speech_prob": float(np.mean([s["no_speech_prob"] for s in segs])) if segs else None,
"n_low_confidence": sum(v < LOGPROB for v in lp),
"language": top_language,
"n_languages": len(langs),
"model": MODEL,
"task": TASK,
}
for code in sorted(langs):
values[f"language[{code}]"] = langs[code]
for k, f in enumerate(files[:20], start=1):
values[f"text[{k}]"] = f["text"]
if f["language_prob"] is not None:
values[f"language_prob[{k}]"] = f["language_prob"]
tables = [
{"key": "transcripts", "title": "Transcripts", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "language", "label": "Language", "type": "string"},
{"key": "duration", "label": "Length (s)", "type": "number"}, {"key": "segments", "label": "Segments", "type": "integer"},
{"key": "text", "label": "Transcript", "type": "string"}],
"rows": [{"file": os.path.basename(f["path"]), "language": f["language"], "duration": f["duration_s"], "segments": f["segments"],
"text": f["text"] if len(f["text"]) <= 600 else f["text"][:600] + " …"} for f in files]},
{"key": "segments", "title": f"Segments{' (first 500)' if len(segs) > 500 else ''}", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "start", "label": "Start (s)", "type": "number"}, {"key": "end", "label": "End (s)", "type": "number"},
{"key": "text", "label": "Text", "type": "string"}, {"key": "avg_logprob", "label": "Avg log-probability", "type": "number"},
{"key": "no_speech_prob", "label": "No-speech probability", "type": "number"}],
"rows": [{"file": os.path.basename(s["path"]), "start": s["start"], "end": s["end"], "text": s["text"], "avg_logprob": s["avg_logprob"],
"no_speech_prob": s["no_speech_prob"]} for s in segs[:500]]},
]
# %% Word and character error rates against the references (codesplash.text.error_rates, as in evaluate.text)
from codesplash.text import error_rates as er
LOWER = False
refs_all = df[REFERENCE].tolist()
scored = [f for f in files if refs_all[f["row"]] is not None and not (isinstance(refs_all[f["row"]], float) and refs_all[f["row"]] != refs_all[f["row"]])
and str(refs_all[f["row"]]).strip()]
values["n_scored"] = len(scored)
if scored:
e = er.segments([f["text"] for f in scored], [[str(refs_all[f["row"]])] for f in scored], lowercase=LOWER).sum(axis=0)
values.update({"wer": er.rate(e[0], e[1]), "cer": er.rate(e[5], e[6]), "wer_sub": int(e[2]), "wer_del": int(e[3]), "wer_ins": int(e[4]),
"wer_ref_words": int(e[1]), "cer_ref_chars": int(e[6])})
rows_er = []
for f in scored:
x = er.segments([f["text"]], [[str(refs_all[f["row"]])]], lowercase=LOWER)[0]
rows_er.append({"file": os.path.basename(f["path"]), "wer": er.rate(x[0], x[1]), "cer": er.rate(x[5], x[6]), "words": int(x[1])})
tables.append({"key": "error_rates", "title": "Error rates against the references", "columns": [
{"key": "file", "label": "File", "type": "string"}, {"key": "wer", "label": "WER (%)", "type": "number"}, {"key": "cer", "label": "CER (%)", "type": "number"},
{"key": "words", "label": "Reference words", "type": "integer"}], "rows": rows_er})
else:
warnings.append("No transcribed file has a reference, so no error rates.")
charts = []
if segs:
lane_rows = [f["row"] for f in files[:30]] # one lane per file, at most 30
lanes = list(dict.fromkeys(os.path.basename(f["path"]) for f in files[:30]))
shown = [s for s in segs if s["row"] in lane_rows]
charts.append(cs.chart("timeline", "segment-timeline", "Segments over time", {
"start": cs.col("Start (s)", [s["start"] for s in shown], "numeric"),
"end": cs.col("End (s)", [s["end"] for s in shown], "numeric"),
"lane": cs.col("File", [os.path.basename(s["path"]) for s in shown], "categorical", lanes),
"label": cs.col("Text", [s["text"] for s in shown], "categorical"),
"value": cs.col("Average log-probability", [s["avg_logprob"] for s in shown], "numeric"),
}, controls={"labels": True, "overlap": False}))
if lp:
charts.append(cs.chart("confidence", "histogram", "Average log-probability of each segment", {
"x": cs.col("Average log-probability per token", lp, "numeric")}, controls={"scale": "count", "kde": False}))
assumptions = [
{"key": "hallucination", "label": "Text can be invented", "status": "warn" if values["n_low_confidence"] else "info",
"message": (f"{values['n_low_confidence']} of {len(segs)} segments have an average log-probability below {LOGPROB:g}: listen to them before relying on the text."
if values["n_low_confidence"] else "No segment falls below the log-probability cutoff; Whisper can still mishear names and numbers.")},
{"key": "language_detection", "label": "Language from the first 30 seconds", "status": "info",
"message": (f"Set to {LANGUAGE} for every file." if LANGUAGE else f"Detected per file: {', '.join(f'{c} ({n})' for c, n in sorted(langs.items(), key=lambda kv: (-kv[1], kv[0])))}.")},
{"key": "greedy_decoding", "label": "One pass, no retries", "status": "info",
"message": f"{values['n_windows']} windows decoded once each; {values['n_skipped_windows']} skipped as silence."},
{"key": "speech_privacy", "label": "Recordings of people", "status": "info",
"message": "Transcripts stay on this computer. Get consent before transcribing other people's recordings."},
] + cs_profile.warning_rows()
cs.publish({
"title": "Speech to text (Whisper)",
"engine": cs.engine_info("torch", "safetensors", "numpy", "pandas"),
"n": len(files),
"summary": f"{len(files)} files ({values['audio_seconds']:.1f} s) → {len(segs)} segments, {values['n_words']} words; most common language {top_language}.",
"statistics": [
{"key": "n_transcribed", "label": "Files transcribed", "value": len(files)},
{"key": "n_segments", "label": "Segments", "value": len(segs)},
{"key": "n_words", "label": "Words", "value": values["n_words"]},
{"key": "mean_avg_logprob", "label": "Mean log-probability", "value": values["mean_avg_logprob"]},
],
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "transcripts", "path": os.path.join(out, "transcripts.parquet"), "format": "parquet"},
{"key": "segments", "path": os.path.join(out, "segments.parquet"), "format": "parquet"}],
})
When you have what was really saidTranscript error ratesWord and character error rates of each transcript against its reference, over the files that have one., add it as the reference column. The word error rate here is 42.4% over 2 files: case counted, punctuation counted, and the long file's second sentence was misheard.
Check yourself
Whisper heard every word right but left out the commas. Will the word error rate be 0%?
Show the answer
Answer: b
Normalize punctuation and case the same way for every system before comparing them. Ignore case handles case; punctuation still counts.
Do it on your own data
In the appAdd an audio folder in Data (the files stay where they are), then open Speech to text (Whisper). Start with the tiny model; each model asks before its one-time download. Medium, large v3 and large v3 turboWhisper large-v3 and large-v3-turboOpenAI's largest Whisper checkpoints: 128-band log-mel input, 100 languages (Cantonese added); turbo keeps 4 of 32 decoder layers. make fewer mistakes, especially in other languages, but each 30-second window takes about as long as the audio itself on a CPU in the Parity profile. On the result, the transcript icon adds transcript and transcript_language columns to the dataset, the rows icon saves the segments as a dataset, and with a reference column Score against references opens Generated-text metrics with error rates on.
from codesplash.audio import whisper
model = whisper.load(whisper.locate("tiny"))
r = whisper.transcribe(model, samples_16k) # float samples at 16 kHz, mono
for s in r["segments"]:
print(f'{s["start"]:6.2f}–{s["end"]:6.2f} {s["text"]} ({s["avg_logprob"]:.2f})')library(codesplashr)
model <- cs_whisper_load(cs_whisper_locate("tiny"))
r <- cs_whisper_transcribe(model, samples_16k) # numeric samples at 16 kHz, mono
for (s in r$segments) cat(sprintf("%6.2f-%6.2f %s (%.2f)\n", s$start, s$end, s$text, s$avg_logprob))Recap
Recap- Whisper decodes 30-second windows into timed segments; the next window starts at the last complete segment.
- Average log-probability measures the model's confidence, not correctness; loops and invented "Thank you." can score well.
- Keep the silence gate, read low-confidence segments, and score against references with case and punctuation in mind.
Concepts in this lesson