ADescribe · describe.audio
Audio collection profile (duration, loudness, clipping, silence)
What is in this collection of audio files — how long, how loud, clipped, silent or quiet?
Profiles the audio files listed in a column of paths (an audio folder added in Data): duration and channels, integrated loudness (LUFS, ITU-R BS.1770 K-weighting with gating), sample peak and RMS level, crest factor, the share of clipped samples, the share of silent frames and DC offset, per file and for the collection. Files that are silent, mostly silent, clipped, very quiet or very loud are flagged against thresholds you set, and the first files are drawn as waveforms. Every file is decoded once by the app at its own sample rate, with all its channels, and measured identically in Python and R.
A real result
Example “Folder defaults”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
| File | Flag | Duration (s) | Loudness (LUFS) | Peak (dBFS) | Clipped share | Silent share |
|---|---|---|---|---|---|---|
| chirp_loud.wav | Clipping | 0.8000 | −1.044 | −0.0003 | 0.5331 | 0 |
| quiet.wav | Quiet | 0.6000 | −54.284 | −50.484 | 0 | 0 |
| silence.wav | Silent | 0.5000 | — | — | 0 | 1 |
Files (first 200)
| File | Duration (s) | Sample rate (Hz) | Channels | Loudness (LUFS) | Flag |
|---|---|---|---|---|---|
| tone_a.wav | 0.8000 | 16,000 | 1 | −14.903 | OK |
| tone_b.wav | 0.5000 | 22,050 | 2 | −14.636 | OK |
| noise_a.wav | 0.6000 | 16,000 | 1 | −26.342 | OK |
| chirp_loud.wav | 0.8000 | 8,000 | 1 | −1.044 | Clipping |
| quiet.wav | 0.6000 | 16,000 | 1 | −54.284 | Quiet |
| silence.wav | 0.5000 | 8,000 | 1 | — | Silent |
| speechlike.wav | 1 | 16,000 | 1 | −21.888 | OK |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_clips/not_there.wav |
- 2 listed files could not be read and are left out.
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
| File | Flag | Duration (s) | Loudness (LUFS) | Peak (dBFS) | Clipped share | Silent share |
|---|---|---|---|---|---|---|
| chirp_loud.wav | Clipping | 0.8000 | −1.044 | −0.0003 | 0.5331 | 0 |
| quiet.wav | Quiet | 0.6000 | −54.284 | −50.484 | 0 | 0 |
| silence.wav | Silent | 0.5000 | — | — | 0 | 1 |
Files (first 200)
| File | Duration (s) | Sample rate (Hz) | Channels | Loudness (LUFS) | Flag |
|---|---|---|---|---|---|
| tone_a.wav | 0.8000 | 16,000 | 1 | −14.903 | OK |
| tone_b.wav | 0.5000 | 22,050 | 2 | −14.636 | OK |
| noise_a.wav | 0.6000 | 16,000 | 1 | −26.342 | OK |
| chirp_loud.wav | 0.8000 | 8,000 | 1 | −1.044 | Clipping |
| quiet.wav | 0.6000 | 16,000 | 1 | −54.284 | Quiet |
| silence.wav | 0.5000 | 8,000 | 1 | — | Silent |
| speechlike.wav | 1 | 16,000 | 1 | −21.888 | OK |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_clips/not_there.wav |
- 2 listed files could not be read and are left out.
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Folder defaultsaud1_clips · audio: path
- Grouped strictaud1_clips · audio: path · label: label
- Degenerate all naaud1_clips · audio: path
- Degenerate n1aud1_clips · audio: path
- Degenerate n2aud1_clips · audio: path
- Degenerate n3aud1_clips · audio: path
In the guides
Where it sits in the decision guides
- Type: structured (tabular), unstructured (text, images, audio, video), time series / sequential, graph / relational · DS & ML Decision Guide · Key data characteristics — what influences method choice
- Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
What you need
- Audio filecategorical · 1 column
- A column of audio file paths (an audio folder added in Data has one). WAV, FLAC, MP3, AAC/M4A and Ogg Vorbis are read.
- Group bycategorical · 0–1 column · 1–30 levels
- Optional: a column such as the subfolder or class; the summary is also given per group.
Choices you make
statistics
- Clipped at or abovedefault 0.999
A sample this close to full scale (1.0) counts as clipped.
- Silent below (dBFS)default -60
A 50 ms frame whose RMS level is below this counts as silent.
- Flag clipping abovedefault 0.001
Files with more than this share of clipped samples are flagged Clipping (0.001 = 0.1%).
- Flag mostly silent abovedefault 0.5
Files with more than this share of silent frames are flagged Mostly silent.
- Quiet below (LUFS)default -40
Files whose integrated loudness is below this are flagged Quiet. Broadcast targets are about −23 LUFS, streaming about −14.
- Loud above (LUFS)default -8
Files whose integrated loudness is above this are flagged Loud.
options
- Waveforms to drawdefault 4
How many files (in table order) to draw as waveforms.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Files decode
Files that can't be decoded or are missing are listed and left out of the profile.
Measured at each file's own rate
Every file is decoded at its own sample rate with all its channels, so peaks and clipping are the stored samples' own; levels between samples (true peak) are not measured.
Loudness needs 0.4 s
BS.1770 loudness gates 400 ms blocks; shorter files, and silent ones, have no loudness.
Recordings of people
Voices can identify people. Keep consent and purpose in mind before sharing results or files.
What it reports
- n_rows
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- n_files
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- n_unreadable
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- total_duration_s
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- duration_min
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- duration_median
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- duration_max
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- n_mono
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- n_stereo
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- n_multichannel
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- loudness_median
- How loud a whole recording sounds, in LUFS: K-weighted levels of 400 ms blocks, gated to ignore silence (ITU-R BS.1770).
- loudness_min
- How loud a whole recording sounds, in LUFS: K-weighted levels of 400 ms blocks, gated to ignore silence (ITU-R BS.1770).
- loudness_max
- How loud a whole recording sounds, in LUFS: K-weighted levels of 400 ms blocks, gated to ignore silence (ITU-R BS.1770).
- n_no_loudness
- How loud a whole recording sounds, in LUFS: K-weighted levels of 400 ms blocks, gated to ignore silence (ITU-R BS.1770).
- peak_max_dbfs
- A level in decibels below the loudest value a file can hold: 0 dBFS is full scale, −6 dBFS is half the amplitude.
- clip_share_mean
- Samples stuck at full scale because the signal was louder than the recording could hold; it sounds harsh and can't be undone.
- silence_share_mean
- The share of 50 ms frames whose RMS level is below the silence threshold (−60 dBFS by default).
- n_ok
- A first look at a folder of recordings: how many, how long, how loud, and which are silent, clipped, quiet or loud.
- n_silent
- The share of 50 ms frames whose RMS level is below the silence threshold (−60 dBFS by default).
- n_clipping
- Samples stuck at full scale because the signal was louder than the recording could hold; it sounds harsh and can't be undone.
- n_mostly_silent
- The share of 50 ms frames whose RMS level is below the silence threshold (−60 dBFS by default).
- n_quiet
- How loud a whole recording sounds, in LUFS: K-weighted levels of 400 ms blocks, gated to ignore silence (ITU-R BS.1770).
- n_loud
- How loud a whole recording sounds, in LUFS: K-weighted levels of 400 ms blocks, gated to ignore silence (ITU-R BS.1770).
- n_rates
- How 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.
Per group, level or term: files[<group>], loudness_median[<group>], duration_median[<group>], files_at_rate[<rate>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses numpy, pandas, scipy, codesplash; R uses nanoparquet, jsonlite, codesplashr.
Default traps between the two languages
- Both engines read the same decoded samples (the app's media tensors; WAV decoded by the codesplash.media twins outside the app) and run the same twins (codesplash.audio.describe / dsp ↔ codesplashr R/audio_describe.R / R/audio_dsp.R). The K-weighting biquads run as direct form II transposed (scipy.signal.lfilter) in Python and direct form I (stats::filter) in R, so loudness agrees to about 1e-13 rather than bit for bit.
The exact script CodeSplash ran for example “Folder defaults” · 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"}],
})
The exact script CodeSplash ran for example “Folder defaults” · 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"))
))
Sources
- ITU-R Recommendation BS.1770-4 (2015). Algorithms to measure audio programme loudness and true-peak audio level.
- EBU R 128 (2020). Loudness normalisation and permitted maximum level of audio signals.
- Steinmetz CJ, Reiss JD (2021). pyloudnorm: a simple yet flexible loudness meter in Python. AES Convention 150.
From the CodeSplash method registry · describe.audio v1.0.0.