Skip to content

Sound as data: samples, rates and honest splits

A recording is a list of numbers with a rate, a bit depth and a history. Learn what each limits, why resampling isn't relabeling, how to profile a folder before modeling, and why audio must be split by speaker and session.

Introductory ~12 min7 steps

What runs in CodeSplash

You will be able to

  • Explain what the sample rate and the bit depth limit
  • Tell resampling from relabeling the rate, and say what each does to pitch and length
  • Profile a folder of recordings before any model sees it
  • Split audio by speaker and recording session, not by clip

Read first

01

Air pressure, sampled

Read

A recording is a long list of numbers: the air pressure at a microphone, measured at a fixed rate. The sample rateSample rateHow many samples per second a recording stores (16,000 for speech, 44,100 or 48,000 for music); it caps the highest frequency at half that. sets the highest frequency the list can hold, the Nyquist frequencyNyquist frequencyHalf the sample rate: the highest frequency a recording can hold. Higher tones fold back as false lower ones (aliasing)., at half the rate. Speech stored at 16,000 samples a second keeps tones up to 8,000 Hz; music at 44,100 keeps the whole range of hearing.

The bit depthBit depthHow many bits store each sample. It sets how quiet a detail can be before it sinks into rounding noise. sets the other limit: how quiet a detail can be before rounding noise hides it.

Every model in this track starts from these numbers, so keep the rate, the channel count, the amplitude units and any resampling history with the data. The audio data contractData contract: audio waveformsSamples over time per channel: fix the sample rate, channels and level, and split by speaker, recording and source mixture. lists them.

02

Resampling is not relabeling

Predict

Predict first

A 16 kHz file is saved with its header changed to say 32 kHz, and the samples are left alone. How does it play?

It sounds the same but shorterIt plays twice as fast and an octave higherNothing changes, because the samples are identical
Reveal

Twice as fast and an octave higher. Each sample now lasts half as long, so every frequency doubles and the clip lasts half the time. To change the rate honestly, resample: filter out everything above the new Nyquist frequency, then compute new samples. ResamplingAudio resamplingChanging a recording's sample rate (for example to 16 kHz) with a low-pass filter so no false tones appear; stereo is averaged to mono. changes the number of samples, not the pitch.

03

Profile before you model

Read
Audio collection profile (duration, loudness, clipping, silence)Recorded · Python and R agreeRecorded 2026-11-25 · 27 values compared
R

7 audio files, 4.8 s in all; 1 silent, 1 clipped, 1 quiet.

Files read
7
Total duration (s)
4.800
Median loudness (LUFS)
−18.395
Clipped files
1

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • Measured at each file's own rate — Sample rates: 8000 Hz (2 files), 16000 Hz (4 files), 22050 Hz (1 files).
  • Loudness needs 0.4 s — 1 files are silent or shorter than one 400 ms block, so they have no loudness.
  • Recordings of people — Voices can identify people; check consent before sharing files or results.

Flagged files

FileFlagDuration (s)Loudness (LUFS)Peak (dBFS)Clipped shareSilent share
chirp_loud.wavClipping0.8000−1.044−0.00030.53310
quiet.wavQuiet0.6000−54.284−50.48400
silence.wavSilent0.5000——01

Files (first 200)

FileDuration (s)Sample rate (Hz)ChannelsLoudness (LUFS)Flag
tone_a.wav0.800016,0001−14.903OK
tone_b.wav0.500022,0502−14.636OK
noise_a.wav0.600016,0001−26.342OK
chirp_loud.wav0.80008,0001−1.044Clipping
quiet.wav0.600016,0001−54.284Quiet
silence.wav0.50008,0001—Silent
speechlike.wav116,0001−21.888OK

Files that could not be read

FilePath
notes.wavaud1_clips/notes.wav
not_there.wavaud1_clips/not_there.wav
  • 2 listed files could not be read and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Audio collection profile (duration, loudness, clipping, silence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.audio 1.0.0 · spec 1f5dd86ebe1c5a81
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_clips.parquet", col_select = c("path")))
n_input <- nrow(df)
df[["path"]] <- factor(df[["path"]], levels = sort(unique(df[["path"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("path")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("path"))  # infinite values stop the run (registry/errors.yaml)
# %% 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\":false,\"offset_seconds\":0,\"sample_rate\":null}}", simplifyVector = FALSE), "target/academy-parity/run-8142/describe.audio/folder_defaults/out-r", df,
                        "tests/parity/fixtures/aud1_clips.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root) || !nzchar(media$root)) {
  media$root <- dirname(normalizePath("tests/parity/fixtures/aud1_clips.parquet", mustWork = FALSE))  # relative paths start next to the data file
}

# %% Decode and measure each file (channels x samples at the analysis rate)
PATH <- "path"
LABEL <- NULL
CLIP_LEVEL <- 0.999; SILENCE_DB <- -60
CLIP_FLAG <- 0.001; SILENCE_FLAG <- 0.5; QUIET <- -40; LOUD <- -8
N_WAVES <- 4
status <- cs_media_status(media, media_ids)
paths <- as.character(df[[PATH]])
labels <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
files <- list(); clips <- list()
for (i in seq_along(media_ids)) {
  rec <- list(row = i - 1L, path = paths[i], file = basename(paths[i]), group = if (!is.null(labels)) labels[i] else NULL)
  x <- NULL
  rate <- NA_real_
  if (is.na(status[i])) {
    x <- tryCatch(cs_media_audio(media, media_ids[i])[[1]], cs_error = function(e) NULL)
    if (!is.null(x)) rate <- as.numeric(cs_media_audio_rates(media, media_ids[i])[1])  # each file at its own rate
  }
  if (is.null(x)) {
    rec$status <- "unreadable"
    files[[length(files) + 1]] <- rec
    next
  }
  s <- cs_audio_clip_stats(x, rate, CLIP_LEVEL, SILENCE_DB, 0.05, 0.025)
  rec <- c(rec, list(status = "ok", sample_rate = rate), s)
  rec$flag <- cs_audio_flag(s, CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD)
  files[[length(files) + 1]] <- rec
  if (length(clips) < N_WAVES) clips[[length(clips) + 1]] <- list(rec = rec, x = x, rate = rate)  # kept only for the waveforms
}
ok <- Filter(function(r) r$status == "ok", files)
if (!length(ok)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an audio file that exists and can be decoded", count = length(files))
n_bad <- length(files) - length(ok)
if (n_bad) warnings <- c(warnings, sprintf("%d listed files could not be read and are left out.", n_bad))

# %% Artifact: one row per listed file
out <- cs_ml_out_dir("target/academy-parity/run-8142/describe.audio/folder_defaults/out-r")
fld <- function(field, na) lapply(files, function(r) if (is.null(r[[field]])) na else r[[field]])
art <- data.frame(
  row = vapply(files, function(r) as.integer(r$row), 0L), path = vapply(files, function(r) r$path, ""),
  file = vapply(files, function(r) r$file, ""), group = vapply(fld("group", NA_character_), as.character, ""),
  status = vapply(files, function(r) r$status, ""), sample_rate = vapply(fld("sample_rate", NA_real_), as.numeric, 0),
  duration_s = vapply(fld("duration_s", NA_real_), as.numeric, 0), channels = vapply(fld("channels", NA_integer_), as.integer, 0L),
  samples = vapply(fld("samples", NA_integer_), as.integer, 0L),
  loudness_lufs = vapply(fld("loudness_lufs", NA_real_), as.numeric, 0), peak_dbfs = vapply(fld("peak_dbfs", NA_real_), as.numeric, 0),
  rms_dbfs = vapply(fld("rms_dbfs", NA_real_), as.numeric, 0), crest_db = vapply(fld("crest_db", NA_real_), as.numeric, 0),
  clip_share = vapply(fld("clip_share", NA_real_), as.numeric, 0), silence_share = vapply(fld("silence_share", NA_real_), as.numeric, 0),
  dc_offset = vapply(fld("dc_offset", NA_real_), as.numeric, 0), flag = vapply(fld("flag", NA_character_), as.character, ""),
  stringsAsFactors = FALSE
)
nanoparquet::write_parquet(art, file.path(out, "audio_files.parquet"))

# %% Summary
fin <- function(v) !is.null(v) && is.finite(v)
D <- vapply(ok, function(r) r$duration_s, 0)
L <- unlist(lapply(ok, function(r) if (fin(r$loudness_lufs)) r$loudness_lufs else NULL))
flags <- vapply(ok, function(r) r$flag, "")
ch <- vapply(ok, function(r) r$channels, 0)
cshare <- unlist(lapply(ok, function(r) if (fin(r$clip_share)) r$clip_share else NULL))
sshare <- unlist(lapply(ok, function(r) if (fin(r$silence_share)) r$silence_share else NULL))
values <- list(
  n_rows = length(files), n_files = length(ok), n_unreadable = n_bad,
  total_duration_s = sum(D), duration_min = min(D), duration_median = stats::median(D), duration_max = max(D),
  n_mono = sum(ch == 1), n_stereo = sum(ch == 2), n_multichannel = sum(ch > 2),
  loudness_median = if (length(L)) stats::median(L) else NULL, loudness_min = if (length(L)) min(L) else NULL,
  loudness_max = if (length(L)) max(L) else NULL, n_no_loudness = length(ok) - length(L),
  peak_max_dbfs = max(vapply(ok, function(r) r$peak_dbfs, 0)),
  clip_share_mean = if (length(cshare)) mean(cshare) else NULL,
  silence_share_mean = if (length(sshare)) mean(sshare) else NULL,
  n_ok = sum(flags == "OK"), n_silent = sum(flags == "Silent"), n_clipping = sum(flags == "Clipping"),
  n_mostly_silent = sum(flags == "Mostly silent"), n_quiet = sum(flags == "Quiet"), n_loud = sum(flags == "Loud"),
  n_rates = length(unique(vapply(ok, function(r) r$sample_rate, 0)))
)
rates_ok <- vapply(ok, function(r) r$sample_rate, 0)
for (rate in sort(unique(rates_ok))) values[[sprintf("files_at_rate[%d]", as.integer(rate))]] <- sum(rates_ok == rate)
group_rows <- list()
if (!is.null(LABEL)) {
  for (g in levels(df[[LABEL]])) {
    rs <- Filter(function(r) identical(r$group, g), ok)
    if (!length(rs)) next
    lg <- unlist(lapply(rs, function(r) if (fin(r$loudness_lufs)) r$loudness_lufs else NULL))
    values[[sprintf("files[%s]", g)]] <- length(rs)
    values[[sprintf("duration_median[%s]", g)]] <- stats::median(vapply(rs, function(r) r$duration_s, 0))
    if (length(lg)) values[[sprintf("loudness_median[%s]", g)]] <- stats::median(lg)
    group_rows[[length(group_rows) + 1]] <- list(group = g, files = length(rs), duration_median = values[[sprintf("duration_median[%s]", g)]],
                                                 loudness_median = values[[sprintf("loudness_median[%s]", g)]],
                                                 flagged = sum(vapply(rs, function(r) r$flag != "OK", TRUE)))
  }
}

# %% Result
FLAG_LEVELS <- c("OK", "Silent", "Clipping", "Mostly silent", "Quiet", "Loud", "Empty")
fl <- Filter(function(r) r$flag != "OK", ok)
fl <- fl[seq_len(min(50, length(fl)))]
nf <- function(v) if (is.numeric(v) && !is.finite(v)) NULL else v
tables <- list(list(
  key = "flagged", title = "Flagged files",
  columns = list(list(key = "file", label = "File"), list(key = "flag", label = "Flag"), list(key = "duration_s", label = "Duration (s)", type = "number"),
                 list(key = "loudness_lufs", label = "Loudness (LUFS)", type = "number"), list(key = "peak_dbfs", label = "Peak (dBFS)", type = "number"),
                 list(key = "clip_share", label = "Clipped share", type = "number"), list(key = "silence_share", label = "Silent share", type = "number")),
  rows = lapply(fl, function(r) list(file = r$file, flag = r$flag, duration_s = nf(r$duration_s), loudness_lufs = nf(r$loudness_lufs),
                                     peak_dbfs = nf(r$peak_dbfs), clip_share = nf(r$clip_share), silence_share = nf(r$silence_share)))
))
if (length(group_rows)) {
  tables[[length(tables) + 1]] <- list(key = "groups", title = paste0("By ", LABEL), columns = list(
    list(key = "group", label = LABEL), list(key = "files", label = "Files", type = "integer"), list(key = "duration_median", label = "Median duration (s)", type = "number"),
    list(key = "loudness_median", label = "Median loudness (LUFS)", type = "number"), list(key = "flagged", label = "Flagged", type = "integer")), rows = group_rows)
}
tables[[length(tables) + 1]] <- list(key = "files", title = "Files (first 200)", columns = list(
  list(key = "file", label = "File"), list(key = "duration_s", label = "Duration (s)", type = "number"), list(key = "sample_rate", label = "Sample rate (Hz)", type = "integer"),
  list(key = "channels", label = "Channels", type = "integer"), list(key = "loudness_lufs", label = "Loudness (LUFS)", type = "number"), list(key = "flag", label = "Flag")),
  rows = lapply(ok[seq_len(min(200, length(ok)))], function(r) list(file = r$file, media_id = media_ids[r$row + 1], duration_s = r$duration_s, sample_rate = as.integer(r$sample_rate),
                                                                   channels = r$channels, loudness_lufs = nf(r$loudness_lufs), flag = r$flag)))
bad <- Filter(function(r) r$status != "ok", files)
if (length(bad)) {
  bad <- bad[seq_len(min(50, length(bad)))]
  tables[[length(tables) + 1]] <- list(key = "unreadable", title = "Files that could not be read", columns = list(list(key = "file", label = "File"), list(key = "path", label = "Path")),
                                       rows = lapply(bad, function(r) list(file = r$file, path = r$path)))
}
charts <- list()
if (length(L)) charts[[length(charts) + 1]] <- cs_chart("loudness", "histogram", "Integrated loudness", list(x = cs_col("Loudness (LUFS)", L, "numeric")), controls = list(scale = "count", kde = FALSE))
withl <- Filter(function(r) fin(r$loudness_lufs), ok)
if (length(withl)) {
  charts[[length(charts) + 1]] <- cs_chart("levels", "scatter", "Loudness by duration", list(
    x = cs_col("Duration (s)", vapply(withl, function(r) r$duration_s, 0), "numeric"),
    y = cs_col("Loudness (LUFS)", vapply(withl, function(r) r$loudness_lufs, 0), "numeric"),
    color = cs_col("Flag", vapply(withl, function(r) r$flag, ""), "categorical", FLAG_LEVELS)
  ), controls = list(fit = "none"))
}
if (N_WAVES > 0 && length(clips)) {
  t0 <- numeric(0); t1 <- numeric(0); lo <- numeric(0); hi <- numeric(0); rm <- numeric(0); trk <- character(0)
  for (cl in clips) {
    e <- cs_audio_envelope(cl$x, cl$rate, 600)
    t0 <- c(t0, e$start); t1 <- c(t1, e$end); lo <- c(lo, e$min); hi <- c(hi, e$max); rm <- c(rm, e$rms); trk <- c(trk, rep(cl$rec$file, length(e$min)))
  }
  charts[[length(charts) + 1]] <- cs_chart("waveforms", "waveform", "Waveforms", list(
    time = cs_col("Time (s)", t0, "numeric"), end = cs_col("End (s)", t1, "numeric"),
    min = cs_col("Min", lo, "numeric"), max = cs_col("Max", hi, "numeric"), rms = cs_col("RMS", rm, "numeric"),
    track = cs_col("File", trk, "categorical", unique(trk))
  ), controls = list(clip = CLIP_LEVEL))
}
assumptions <- list(
  list(key = "decoded", label = "Files decode", status = if (n_bad) "warn" else "pass",
       detail = if (n_bad) sprintf("%d of %d listed files could not be read.", n_bad, length(files)) else "Every listed file was decoded."),
  list(key = "native_rate", label = "Measured at each file's own rate", status = "info",
       detail = paste0("Sample rates: ", paste(vapply(sort(unique(rates_ok)), function(k) sprintf("%d Hz (%d files)", as.integer(k), sum(rates_ok == k)), ""), collapse = ", "), ".")),
  list(key = "short_files", label = "Loudness needs 0.4 s", status = if (values$n_no_loudness) "warn" else "pass",
       detail = if (values$n_no_loudness) sprintf("%d files are silent or shorter than one 400 ms block, so they have no loudness.", values$n_no_loudness) else "Every file has a loudness."),
  list(key = "personal_data", label = "Recordings of people", status = "info", detail = "Voices can identify people; check consent before sharing files or results.")
)
cs_publish(list(
  title = "Audio collection profile (duration, loudness, clipping, silence)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(ok),
  summary = sprintf("%d audio files, %.1f s in all; %d silent, %d clipped, %d quiet.", length(ok), values$total_duration_s, values$n_silent, values$n_clipping, values$n_quiet),
  statistics = list(
    list(key = "n_files", label = "Files read", value = length(ok)),
    list(key = "total_duration_s", label = "Total duration (s)", value = values$total_duration_s),
    list(key = "loudness_median", label = "Median loudness (LUFS)", value = values$loudness_median),
    list(key = "n_clipping", label = "Clipped files", value = values$n_clipping)
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "audio_files", path = file.path(out, "audio_files.parquet"), format = "parquet"))
))
Python

7 audio files, 4.8 s in all; 1 silent, 1 clipped, 1 quiet.

Files read
7
Total duration (s)
4.800
Median loudness (LUFS)
−18.395
Clipped files
1

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • Measured at each file's own rate — Sample rates: 8000 Hz (2 files), 16000 Hz (4 files), 22050 Hz (1 files).
  • Loudness needs 0.4 s — 1 files are silent or shorter than one 400 ms block, so they have no loudness.
  • Recordings of people — Voices can identify people; check consent before sharing files or results.

Flagged files

FileFlagDuration (s)Loudness (LUFS)Peak (dBFS)Clipped shareSilent share
chirp_loud.wavClipping0.8000−1.044−0.00030.53310
quiet.wavQuiet0.6000−54.284−50.48400
silence.wavSilent0.5000——01

Files (first 200)

FileDuration (s)Sample rate (Hz)ChannelsLoudness (LUFS)Flag
tone_a.wav0.800016,0001−14.903OK
tone_b.wav0.500022,0502−14.636OK
noise_a.wav0.600016,0001−26.342OK
chirp_loud.wav0.80008,0001−1.044Clipping
quiet.wav0.600016,0001−54.284Quiet
silence.wav0.50008,0001—Silent
speechlike.wav116,0001−21.888OK

Files that could not be read

FilePath
notes.wavaud1_clips/notes.wav
not_there.wavaud1_clips/not_there.wav
  • 2 listed files could not be read and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Audio collection profile (duration, loudness, clipping, silence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.audio 1.0.0 · spec 1f5dd86ebe1c5a81
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import describe as ad
from codesplash.errors import CsError

# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_clips.parquet", columns=["path"])
n_input = len(df)
df["path"] = pd.Categorical(df["path"], categories=sorted(df["path"].dropna().unique()))
df = df.dropna(subset=["path"])  # listwise deletion over the analysis columns
df["path"] = df["path"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["path"])  # infinite values stop the run (registry/errors.yaml)
# %% 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\":false,\"offset_seconds\":0,\"sample_rate\":null}}"), "target/academy-parity/run-8142/describe.audio/folder_defaults/out-python", df, "tests/parity/fixtures/aud1_clips.parquet")
media_ids = cs_media.ids_of(media, df)
if not media.get("root"):
    media["root"] = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud1_clips.parquet"))  # relative paths start next to the data file

# %% Decode and measure each file (channels × samples at the analysis rate)
PATH = "path"
LABEL = None
CLIP_LEVEL, SILENCE_DB = 0.999, -60
CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD = 0.001, 0.5, -40, -8
N_WAVES = 4
status = cs_media.status(media, media_ids)
paths = df[PATH].astype(str).tolist()
labels = df[LABEL].astype(str).tolist() if LABEL is not None else None
files, clips = [], []
for i, mid in enumerate(media_ids):
    rec = {"row": i, "path": paths[i], "file": os.path.basename(paths[i]), "group": labels[i] if labels else None}
    x = None
    if status[i] is None:
        try:
            x = cs_media.audio(media, [mid])[0]
            rate = float(cs_media.audio_rates(media, [mid])[0])  # each file at its own rate
        except CsError:
            x = None
    if x is None:
        rec["status"] = "unreadable"
        files.append(rec)
        continue
    s = ad.clip_stats(x, rate, CLIP_LEVEL, SILENCE_DB, 0.05, 0.025)
    rec.update(status="ok", sample_rate=rate, **s)
    rec["flag"] = ad.flag(s, CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD)
    files.append(rec)
    if len(clips) < N_WAVES:
        clips.append((rec, x, rate))  # kept only for the waveforms
ok = [r for r in files if r["status"] == "ok"]
if not ok:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an audio file that exists and can be decoded", count=len(files))
warnings = list(warnings)
n_bad = len(files) - len(ok)
if n_bad:
    warnings.append(f"{n_bad} listed files could not be read and are left out.")

# %% Artifact: one row per listed file
out = csml.out_dir("target/academy-parity/run-8142/describe.audio/folder_defaults/out-python")
COLS = ["row", "path", "file", "group", "status", "sample_rate", "duration_s", "channels", "samples", "loudness_lufs", "peak_dbfs", "rms_dbfs", "crest_db",
        "clip_share", "silence_share", "dc_offset", "flag"]
art = pd.DataFrame([{c: r.get(c) for c in COLS} for r in files], columns=COLS)
for c in ("path", "file", "group", "status", "flag"):
    art[c] = art[c].astype("string")
for c in ("sample_rate", "duration_s", "loudness_lufs", "peak_dbfs", "rms_dbfs", "crest_db", "clip_share", "silence_share", "dc_offset"):
    art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
for c in ("channels", "samples"):
    art[c] = pd.array([None if pd.isna(v) else int(v) for v in art[c]], dtype="Int64")
art.to_parquet(os.path.join(out, "audio_files.parquet"), index=False)

# %% Summary
def fin(v):
    return v is not None and math.isfinite(v)


D = np.array([r["duration_s"] for r in ok])
L = np.array([r["loudness_lufs"] for r in ok if fin(r["loudness_lufs"])])
flags = [r["flag"] for r in ok]
values = {
    "n_rows": len(files), "n_files": len(ok), "n_unreadable": n_bad,
    "total_duration_s": float(np.sum(D)), "duration_min": float(np.min(D)), "duration_median": float(np.median(D)), "duration_max": float(np.max(D)),
    "n_mono": sum(r["channels"] == 1 for r in ok), "n_stereo": sum(r["channels"] == 2 for r in ok), "n_multichannel": sum(r["channels"] > 2 for r in ok),
    "loudness_median": float(np.median(L)) if len(L) else None, "loudness_min": float(np.min(L)) if len(L) else None,
    "loudness_max": float(np.max(L)) if len(L) else None, "n_no_loudness": len(ok) - len(L),
    "peak_max_dbfs": float(max(r["peak_dbfs"] for r in ok)),
    "clip_share_mean": float(np.mean([r["clip_share"] for r in ok if fin(r["clip_share"])])) if any(fin(r["clip_share"]) for r in ok) else None,
    "silence_share_mean": float(np.mean([r["silence_share"] for r in ok if fin(r["silence_share"])])) if any(fin(r["silence_share"]) for r in ok) else None,
    "n_ok": flags.count("OK"), "n_silent": flags.count("Silent"), "n_clipping": flags.count("Clipping"),
    "n_mostly_silent": flags.count("Mostly silent"), "n_quiet": flags.count("Quiet"), "n_loud": flags.count("Loud"),
    "n_rates": len({r["sample_rate"] for r in ok}),
}
for rate in sorted({r["sample_rate"] for r in ok}):
    values[f"files_at_rate[{int(rate)}]"] = sum(r["sample_rate"] == rate for r in ok)
group_rows = []
if LABEL is not None:
    for g in [str(v) for v in df[LABEL].cat.categories]:
        rs = [r for r in ok if r["group"] == g]
        if not rs:
            continue
        lg = [r["loudness_lufs"] for r in rs if fin(r["loudness_lufs"])]
        values[f"files[{g}]"] = len(rs)
        values[f"duration_median[{g}]"] = float(np.median([r["duration_s"] for r in rs]))
        if lg:
            values[f"loudness_median[{g}]"] = float(np.median(lg))
        group_rows.append({"group": g, "files": len(rs), "duration_median": values[f"duration_median[{g}]"],
                           "loudness_median": values.get(f"loudness_median[{g}]"), "flagged": sum(r["flag"] != "OK" for r in rs)})

# %% Result
FLAG_LEVELS = ["OK", "Silent", "Clipping", "Mostly silent", "Quiet", "Loud", "Empty"]
flagged = [r for r in ok if r["flag"] != "OK"][:50]
tables = [{
    "key": "flagged", "title": "Flagged files",
    "columns": [{"key": "file", "label": "File"}, {"key": "flag", "label": "Flag"}, {"key": "duration_s", "label": "Duration (s)", "type": "number"},
                {"key": "loudness_lufs", "label": "Loudness (LUFS)", "type": "number"}, {"key": "peak_dbfs", "label": "Peak (dBFS)", "type": "number"},
                {"key": "clip_share", "label": "Clipped share", "type": "number"}, {"key": "silence_share", "label": "Silent share", "type": "number"}],
    "rows": [{k: (r[k] if not isinstance(r[k], float) or math.isfinite(r[k]) else None) for k in ("file", "flag", "duration_s", "loudness_lufs", "peak_dbfs", "clip_share", "silence_share")} for r in flagged],
}]
if group_rows:
    tables.append({"key": "groups", "title": f"By {LABEL}", "columns": [
        {"key": "group", "label": LABEL}, {"key": "files", "label": "Files", "type": "integer"}, {"key": "duration_median", "label": "Median duration (s)", "type": "number"},
        {"key": "loudness_median", "label": "Median loudness (LUFS)", "type": "number"}, {"key": "flagged", "label": "Flagged", "type": "integer"}], "rows": group_rows})
tables.append({"key": "files", "title": "Files (first 200)", "columns": [
    {"key": "file", "label": "File"}, {"key": "duration_s", "label": "Duration (s)", "type": "number"}, {"key": "sample_rate", "label": "Sample rate (Hz)", "type": "integer"},
    {"key": "channels", "label": "Channels", "type": "integer"}, {"key": "loudness_lufs", "label": "Loudness (LUFS)", "type": "number"}, {"key": "flag", "label": "Flag"}],
    "rows": [{"file": r["file"], "media_id": media_ids[r["row"]], "duration_s": r["duration_s"], "sample_rate": int(r["sample_rate"]), "channels": r["channels"],
              "loudness_lufs": r["loudness_lufs"] if math.isfinite(r["loudness_lufs"]) else None, "flag": r["flag"]} for r in ok[:200]]})
bad = [r for r in files if r["status"] != "ok"][:50]
if bad:
    tables.append({"key": "unreadable", "title": "Files that could not be read", "columns": [{"key": "file", "label": "File"}, {"key": "path", "label": "Path"}],
                   "rows": [{"file": r["file"], "path": r["path"]} for r in bad]})
charts = []
if len(L):
    charts.append(cs.chart("loudness", "histogram", "Integrated loudness", {"x": cs.col("Loudness (LUFS)", L, "numeric")}, controls={"scale": "count", "kde": False}))
withl = [r for r in ok if fin(r["loudness_lufs"])]
if withl:
    charts.append(cs.chart("levels", "scatter", "Loudness by duration", {
        "x": cs.col("Duration (s)", [r["duration_s"] for r in withl], "numeric"),
        "y": cs.col("Loudness (LUFS)", [r["loudness_lufs"] for r in withl], "numeric"),
        "color": cs.col("Flag", [r["flag"] for r in withl], "categorical", FLAG_LEVELS),
    }, controls={"fit": "none"}))
if N_WAVES > 0:
    t0, t1, lo, hi, rm, trk = [], [], [], [], [], []
    for rec, x, rate in clips:
        e = ad.envelope(x, rate, 600)
        t0 += e["start"]; t1 += e["end"]; lo += e["min"]; hi += e["max"]; rm += e["rms"]; trk += [rec["file"]] * len(e["min"])
    if t0:
        charts.append(cs.chart("waveforms", "waveform", "Waveforms", {
            "time": cs.col("Time (s)", t0, "numeric"), "end": cs.col("End (s)", t1, "numeric"),
            "min": cs.col("Min", lo, "numeric"), "max": cs.col("Max", hi, "numeric"), "rms": cs.col("RMS", rm, "numeric"),
            "track": cs.col("File", trk, "categorical", list(dict.fromkeys(trk))),
        }, controls={"clip": CLIP_LEVEL}))
assumptions = [
    {"key": "decoded", "label": "Files decode", "status": "warn" if n_bad else "pass",
     "detail": f"{n_bad} of {len(files)} listed files could not be read." if n_bad else "Every listed file was decoded."},
    {"key": "native_rate", "label": "Measured at each file's own rate", "status": "info",
     "detail": "Sample rates: " + ", ".join(f"{int(k)} Hz ({v} files)" for k, v in sorted({r['sample_rate']: sum(q['sample_rate'] == r['sample_rate'] for q in ok) for r in ok}.items())) + "."},
    {"key": "short_files", "label": "Loudness needs 0.4 s", "status": "warn" if values["n_no_loudness"] else "pass",
     "detail": f"{values['n_no_loudness']} files are silent or shorter than one 400 ms block, so they have no loudness." if values["n_no_loudness"] else "Every file has a loudness."},
    {"key": "personal_data", "label": "Recordings of people", "status": "info", "detail": "Voices can identify people; check consent before sharing files or results."},
]
cs.publish({
    "title": "Audio collection profile (duration, loudness, clipping, silence)",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": len(ok),
    "summary": f"{len(ok)} audio files, {values['total_duration_s']:.1f} s in all; {values['n_silent']} silent, {values['n_clipping']} clipped, {values['n_quiet']} quiet.",
    "statistics": [
        {"key": "n_files", "label": "Files read", "value": len(ok)},
        {"key": "total_duration_s", "label": "Total duration (s)", "value": values["total_duration_s"]},
        {"key": "loudness_median", "label": "Median loudness (LUFS)", "value": values["loudness_median"]},
        {"key": "n_clipping", "label": "Clipped files", "value": values["n_clipping"]},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "audio_files", "path": os.path.join(out, "audio_files.parquet"), "format": "parquet"}],
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

This small test folder has 7 readable files at 3 different sample rates. 1 is clipped, 1 is silent, and 2 rows point at files that can't be read.

Fed to a model as is, the folder would mix rates, a silent clip and a distorted one. Profile first: rates, channels, lengths, loudness, silence. Then decide on purpose: resample to one rate, mix to mono or keep the channels, and flag or drop the broken files.

04

Clips are not independent

Read

Ten clips from one speaker aren't ten independent examples. They share a voice, a microphone and a room. If one speaker's clips land on both sides of a split, a model can learn to recognize the voice or the room and still score well, then fail on new people.

Use a speaker-disjoint splitSpeaker-disjoint splitA split where no speaker or recording session appears on both sides, so scores apply to voices and rooms the model never heard. for claims about new speakers, and split by recording session for claims about new rooms or devices. Augmented copies, neighboring windows of one file and overlapping clips stay on the same side as their source.

05

See the leak

Explore

DExplorable · Leakage detective

Why does a model that scores brilliantly in testing fail on real data?

Read the pipeline on the left. Will its cross-validation score overstate real-world accuracy by more than 6 points?

How sure?

The pipeline

200
60
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Pick Split rows at random when customers repeat. Cross-validated accuracy rises above accuracy on new data because the same customer sits on both sides. Audio has the same shortcut with speakers, sessions and microphones in place of customers.

06

Check: sound as data

Checkpoint

Check yourself

A file is recorded at 8,000 samples a second. What is the highest frequency it can represent?

Show the answer

Answer: b

The Nyquist frequency is half the sample rate. Tones above it fold back as false lower tones unless they were filtered out before sampling.

Check yourself

You need every file at 16 kHz for a model. One file is at 48 kHz. What should you do?

Show the answer

Answer: c

Relabeling changes pitch and speed. Dropping samples without a filter lets content above the new Nyquist frequency alias into the audible band. Filter, then resample.

Check yourself

A voice-command model will be used by new customers. Your data has 400 clips from 20 speakers. Which split supports that claim?

Show the answer

Answer: b

Only a speaker-disjoint split tests on voices the model never heard. The other splits put every test speaker in training too.

Check yourself

You add noisy and sped-up copies of each training clip. Where do the copies go?

Show the answer

Answer: a

A copy shares its source's speaker, words and room. Putting it on the other side of the split leaks the answer.

07

Recap

Recap
  • The sample rate caps the highest frequency at half its value; the bit depth caps how quiet a detail can be.
  • Resample with a filter; never relabel the rate.
  • Profile a folder before modeling: rates, channels, lengths, loudness, silence and unreadable files.
  • Split by speaker and session; keep augmented copies with their source.

Concepts in this lesson