fantasynth-tools · music-events

Music events

An offline pipeline turns a finished track into a timeline of musical events: beat grid, drum hits, notes, per-instrument energy curves, named sections and, for songs with lyrics, every sung word. Fantasynth reads that timeline to sync visuals to the music.

Runs on a CUDA GPU (tested on an RTX 5090) About 1.5 min per track Spec CONTRACT.md · usage README.md
The music-events viewer: coloured section bars, word boxes, drum lanes, a piano roll of notes and stem loudness curves under a beat ruler
The viewer on a test track: sections, sung words (text hidden here), vocal onsets, drum lanes, notes and stem curves, with the track renamed.

Overview

The pipeline runs AI models on your own machine and keeps its heavy state (Python environments, model weights, audio, results) in a workspace folder outside the repo. Its product is one file per track, events.json. This page covers the pipeline and that file; Fantasynth's side of it is not part of this repo.

Source audioyour own files, in musicDir
run_all.py10 stages, one command per track, ending in a report card
out/<slug>/events.jsonplus stems, raw detections, listening checks
viewer.htmlinspect by eye and ear before exporting
export_app.pycompact events, track JSON, FLAC copy, into a Fantasynth checkout
GridA rigid tempo fit, moved onto the kick attack.
HitsSeven drum lanes, voted by three detectors.
CurvesLoudness, brightness and onset strength per stem.
Sung wordsThe known lyric, timed word by word from the vocals.
Grid accuracy±2 ms on the kick
Kick precision0.96 to 1.00 3 test tracks
Seek accuracy±0.1 ms FLAC
Lyric word starts79 to 90% within ±60 ms

Quick start

Run everything from the root of the fantasynth-tools repo, except the tests. <ws> is the workspace; python music-events\workspace.py prints it. Setup is Windows-only today (setup.ps1, Scripts\python.exe).

Set up (once per machine, or to repair)

powershell -ExecutionPolicy Bypass -File music-events\setup.ps1      # -DryRun prints the commands
copy music-events\config.example.json <ws>\config.json           # then list your tracks in it

Analyse a new track

<ws>\venv-main\Scripts\python.exe music-events\run_all.py "C:\path\to\music\My Track.mp3" --slug my-track
# optional: --from assemble        (resume from a stage)
#           --track my_track       (the track JSON holding the lyric text; default: appTrack in config.json)
#           --app C:\path\to\fantasynth   (the checkout that track JSON lives in)

Inspect it in the viewer

<ws>\venv-main\Scripts\python.exe music-events\serve.py
# open http://127.0.0.1:8765/viewer.html?slug=my-track

Export it into Fantasynth

<ws>\venv-main\Scripts\python.exe music-events\export_app.py --slug my-track --flac
# the checkout comes from --app, else FANTASYNTH_APP, else "app" in config.json
# add --lyrics to replace the track's inline lyrics with the aligned, word-level ones

Run the tests (from music-events/)

<ws>\venv-main\Scripts\python.exe -m unittest discover -s tests

Offline pipeline

The code is in the repo. Everything heavy lives in one workspace folder outside it, shared by every checkout and worktree, so the multi-gigabyte environments, model weights and audio stay out of git.

Repo path (music-events/)Contents
run_all.pyRuns every stage for one track.
scripts/*.pyOne script per stage; each takes --slug or --all. scripts/lyrics_align.py is the aligner's maths, imported by the lyrics stage.
config.example.jsonTemplate for the workspace config.json.
report.py, tests/The per-track report card and the unit tests.
viewer.html, serve.pyThe inspection viewer and its local server.
export_app.pyWrites events into a Fantasynth checkout and edits the track JSON.
measure/Chromium seek accuracy per audio format; re-run when Chrome updates.
setup.ps1, requirements-*.txt, constraints-main.txtBuilds both environments. The constraints file pins the CUDA torch build.
workspace.pyPath and config resolution for everything in the workspace.

Workspace and config

workspace.py resolves the workspace: MUSIC_EVENTS_WORKSPACE if set, otherwise <main checkout>/../../music-events if that folder already exists, otherwise <main checkout>/../music-events, a folder next to your clone. Worktrees resolve to the same folder because the main checkout is found through git's common directory. Everything that names a track or a machine lives in <workspace>/config.json, never in the repo:

{
  "app": "C:/path/to/fantasynth",       // the Fantasynth checkout export_app.py writes into
  "musicDir": "C:/path/to/music",       // optional: where the source audio lives
  "tracks": {
    "my-track": {
      "file": "My Track.mp3",           // the audio file in musicDir
      "appTrack": "my_track",           // public/music/<appTrack>.json in the checkout
      "title": "My Track",              // display title, for a new track file
      "bpm": 120, "gridMarker": 0.5,    // optional, diagnostic only
      "handTimed": "fitted by hand",    // optional: do not align this track's lyrics
      "pron": { "DJ": "dee jay" },      // optional: pronunciation fixes
      "all": false                      // optional: leave out of --all (default true)
    }
  }
}

Every key is optional; an unknown key or a value of the wrong type stops the run, and keys starting with _ are ignored. --all means every slug in tracks except those with "all": false (for export_app.py, those with an appTrack; for report.py, every analysed slug in out/). The music folder is LOCAL_MUSIC_PATH when set, else musicDir, else ~/Music/Live. The Fantasynth checkout is resolved lazily, only by the commands that read or write it (export_app.py, the lyrics stage, and run_all.py before its first stage when lyrics will read a track file): --app, then FANTASYNTH_APP, then config.app, else an error. A folder without public/music/index.json is refused. Importing a module or running the tests never needs it.

Rebuilding the workspace

Nothing in the workspace is irreplaceable except config.json: every other folder is rebuilt by code in the repo. Two inputs live outside the repo, though: your source music, and third-party download links.

Workspace pathSizeRebuilt byDepends on
venv-main/, venv-bp/several GBsetup.ps1 + pinned requirementsPython 3.13 and 3.10 installed; the pinned packages still on PyPI and the PyTorch index. Proven by a real install into an empty workspace.
models/1.1 GBDownloaded by the separate stage on first runpython-audio-separator's GitHub model-configs release. The one fragile input: the checkpoints' original release already disappeared once. Keep a backup of this folder outside the repo.
models/torch/2.4 GBDownloaded by the lyrics stage on first run (TORCH_HOME)torchaudio's MMS_FA and WAV2VEC2_ASR_LARGE_LV60K_960H from pytorch.org. Only needed for tracks with lyric text.
audio/≈40 MB per trackThe decode stage of run_all.pyYour source files, never in the repo.
out/≈1 GB per trackEvery stage of run_all.pyThe steps above.

Also rebuilt automatically: the Beat This! and all-in-one weights in ~/.cache, and the FLAC copies next to the MP3s (export_app.py --flac). measure/ writes its own seektest/ folder when run.

Not quite deterministic

all-in-one-infer varies from run to run on the same install: beats move by one 10 ms frame, a section boundary by about 0.2 s, and the downbeat vote shifts. On the test tracks the rigid grid fit and bar snapping absorbed it, and a full re-run reproduced events.json byte for byte. A track with a weak downbeat could still come out with a different section or bar phase, so check its report card.

Stages

StageToolOutput
decodeffmpegaudio/<slug>.wav
gridBeat This! (final0) + all-in-one-infer 3.1.0grid.json: rigid tempo fit, downbeat phase, raw sections
separateBS-Roformer-SW, then MDX23C DrumSep6 stems (drums, bass, vocals, guitar, piano, other) + 6 drum stems (kick, snare, toms, hh, ride, crash)
drumsADTOF-pytorch on the drum stem and on the mix; librosa onsets per drum stemraw_adtof.json, raw_adtof_mix.json, raw_drumsep_onsets.json
notesBasic Pitch per pitched stem (venv-bp)raw_notes_<stem>.json
curveslibrosa, 100 fpscurves.npz: RMS, spectral centroid, onset strength
lyricstorchaudio MMS_FA + WAV2VEC2_ASR_LARGE_LV60K_960H (CTC), one global Viterbi, librosa features (see Lyric alignment)raw_lyrics.json: word timings, confidence, extras, vocal onsets (seconds); lyrics_em/: cached emissions
assembleassemble.pyevents.json, with lyrics and vocalOnsets when there are any
renderrender_check.pycheck_grid, check_drums_split, check_drums_mix, check_bass_split, and with lyrics check_lyrics_split, check_vocal_onsets_split (.mp3)
reportreport.pyreport.json and a printed report card: measures events.json against the stems and gives each layer a verdict (solid, mostly, check)

Measured per track: grid 21 to 29 s (most of it all-in-one-infer), separation 20 to 24 s, drum detection about 5 s, lyric emissions about 7 s (37 s with the first model load) and every lyric alignment under 1 s. The other stages weren't timed.

Assembly rules

scripts/assemble.py merges the raw stages. Each rule came from a measurement on a test track; its docstring gives the numbers.

AreaRule
GridOne rigid fit (the test tracks never change tempo), BPM snapped to an integer when the fit allows it, downbeat phase chosen by vote. t0 is then moved onto the median on-beat kick attack, because the beat trackers land 5 to 20 ms late (shifts of −5 to −18 ms on the test tracks).
Grid seedSeeded twice, from a sequential beat-index chain and from a phase-coherence period scan (±3%); the coherence fit wins only with strictly more inliers. On one track the chain miscounted through a drumless intro and settled at 119.65 BPM with 40 of 439 inliers, where the kicks say 121 (291 inliers). On another, the coherence seed alone lands at 136.77 against a true 136, which is why the guard is strict.
Drum votingThree detectors: ADTOF on the drum stem, ADTOF on the full mix, and onsets on the matching DrumSep stem. Hits within 30 ms are one cluster; a hit is kept with two or more votes. Clustering is non-maximum suppression, best cluster first.
Solo DrumSep hitsA snare or hat heard only by DrumSep is kept when that drum stem is at least 10 dB louder than every other drum stem there. This is what catches build-up rolls.
HatsA hat that coincides with a kick or snare needs DrumSep's hi-hat vote (ADTOF reads kicks and claps as hats). A DrumSep-only hat is also kept at −8 dB dominance when no kick or dominant snare onset is within 30 ms.
Toms, cymbalsToms need both ADTOF passes and no kick in the window. Cymbals need the drum-stem ADTOF vote. Crash versus ride is decided by the louder DrumSep stem.
Open hatsOpen if the hi-hat stem takes at least 150 ms to fall 12 dB, measured only up to the next hit.
SwingPer lane. If the 2nd and 4th 16ths form a dense cluster at least 25 ms later than the on-beat hits, the lane gets a swung slot as well as the straight one. On one test track the hats swung +36.5 ms while its snares were straight.
SnappingEvery hit snaps to the nearest 16th (straight or swung slot). A hit further than a third of a 16th away keeps its raw position and gets residual r = 0.
Sectionsallin1 boundaries snap to bars, then to the 8-bar phrase grid (offset found by vote, moves of one bar at most). Sections split at 4-bar marks when kick presence changes by 0.75 or stem level steps 6 dB (drums) or 9 dB (bass), floored at −50 dBFS. Labels (intro, build, drop, breakdown, groove, outro) come from kick fill and drums+bass energy. With lyrics, a boundary one bar from a vocal entry moves onto it first (see Lyric-informed sections).
Lyrics, vocal onsetsConverted to beats on the shifted grid and rounded to 3 decimals, never snapped: a singer is not quantised. A span's len is its rounded end minus its rounded start, so legato words that tile in seconds still tile in beats.

Measured reliability

Measured from the audio at ±30 ms on the snapped fire time, first by independent verification and now by report.py, which reproduces the same numbers. P = precision (hits that are real), R = recall (real hits found). Three electronic test tracks (A, B, C), 126 to 129 BPM. Letters match the comments in the code.

TrackGrid vs kickKick P / RSnare P / RHats P / R
Test track A−6.2 ms0.96 / 0.950.90 / 0.480.85 / 0.98
Test track B−1.5 ms1.00 / 0.991.00 / 0.690.99 / 0.90
Test track C−1.6 ms0.99 / 1.001.00 / 0.960.96 / 0.99
LayerVerdictNotes
Beat grid, downbeatssolidCorrect on all three tracks; integer BPM.
Kickssolid95 to 100% in both directions.
Energy curvessolidCorrelation 0.9997+ with the audio at zero lag.
Snares, hatsmostlySwing, claps and bleed are the hard cases. Track A's swung hats reach a precision of about 0.83 against real strikes.
SectionsmostlyHeuristic labels; drops are right everywhere. allin1 boundaries can differ between identical runs.
Lyricssolid / mostlySolid on one test track, mostly on three. Every word placed. See Measured.
Vocal onsetsinfoA measurement, not a verdict: 73 to 85% of the pitch-jump onsets have no Basic Pitch vocal note within 50 ms.
NotesdraftIn the file, never checked against the audio.

Lyric alignment

The lyrics stage times every word of a track's known lyric text against the vocals stem. Nothing is transcribed, so nothing can be misheard: the text comes from the track's own JSON (or a plain text file), and the stage only decides when each word is sung. The method is a port of mexicat/pdoom-video's CTC alignment (MIT; see THIRD_PARTY_NOTICES.md). The maths is scripts/lyrics_align.py: numpy, scipy and librosa only, no torch at import, so it is unit-tested on its own. The stage is scripts/lyrics.py: text, emissions on the GPU, the prior and the output file. It runs after curves and before assemble.

Words placedall 4 test tracks
Word starts ±60 ms0.79 to 0.90 chance 0.61 to 0.71
Emissions≈7 s per track
Alignment< 1 s whole song, one pass

Run it

<ws>\venv-main\Scripts\python.exe music-events\scripts\lyrics.py --slug my-track
<ws>\venv-main\Scripts\python.exe music-events\scripts\lyrics.py --slug my-track --track my_track --app C:\path\to\fantasynth
<ws>\venv-main\Scripts\python.exe music-events\scripts\lyrics.py --slug my-track --text lyrics.txt --window 0
# then: run_all.py "<track.mp3>" --slug my-track --from assemble
InputEffect
--track <name>The text is the inline lyrics of public/music/<name>.json in the Fantasynth checkout, word- or line-level; only the words are used, and the line times only as the prior below. Default: the slug's appTrack in config.json. run_all.py --track passes it through. A track file that cannot be found is an error: nothing is written.
--text <file>A plain text file, one lyric line per line. Overrides --track and needs no checkout. It has no line times, so no prior.
--window <s>The line-time prior, ± seconds around each line's reference time. Default 3.0; 0 turns it off.
pronPer track in config.json: {"AGI": "ay gee i", "DJ": "dee jay"}. A key matches a display token exactly, or case-folded without edge punctuation. A spelling of several sub-words gives the word one syllable span per sub-word. Digits are spelled out on their own ("1998" as nineteen ninety eight). No test track needed an entry.
handTimedPer track in config.json. A listed track is not aligned: its inline lyrics were timed by hand, so the stage takes each word's t and d and the line grouping straight from the track file, verbatim (rest words dropped). The words carry no confidence, so the events file has no lyrics.words.v. Vocal onsets and extras are computed as usual, and lyrics.source reads hand-timed (public/music/<track>.json). export_app.py --lyrics never writes a listed track.
ModelsDownloaded on first use into <workspace>/models/torch (TORCH_HOME), about 2.4 GB for the two. Emissions are cached per model and channel in out/<slug>/lyrics_em/ (4 to 8 MB per track, six files) and recomputed when stems/vocals.wav is newer.
No text, silent voiceA track without text still gets vocal onsets. A vocals stem below −40 dBFS, the notes gate, gets nothing. raw_lyrics.json is always written.

Method

Known textdisplay tokens → pronunciation sub-words
6 emissions2 CTC models × mono, left, right
One Viterbiwhole song, a garbage token between lines
Refinestarts and ends from the vocal signal
Confidenceagreement of 4 other alignments + posterior
StepWhat it does
Textpron() turns each display token into pronunciation sub-words (letters and inner apostrophes). A token with nothing pronounceable is left out of the alignment, and a line with no words left is left out too.
EmissionsMMS_FA and WAV2VEC2_ASR_LARGE_LV60K_960H, 20 ms frames, computed in 20 s chunks with 3 s of context each side. Both vocabularies map onto one alphabet (blank, a to z, apostrophe; LV60K's word separator folds into blank). Each runs on the vocals stem as mono, left and right at 16 kHz: a double-tracked chorus is often panned, so one side is closer to a single voice.
FusionThe six are averaged as probabilities (a mixture), not multiplied, so one model's confident "no" cannot veto another's "yes".
AlignmentOne constrained Viterbi (numba) over the whole song. The target is ★ line0 ★ line1 ★ … ★, and the garbage token ★ scores 1.5 nats below each frame's best symbol. It absorbs ad-libs, backing vocals and repeats the text does not list, while lyric letters win wherever they really match.
RefinementPer sub-word, on 5 ms features (RMS, sibilance ratio, log-mel flux, pYIN f0), because CTC has known biases. rest-onset: after at least 50 ms of silence, start at the voice's re-entry, at most 0.5 s before the CTC start. onset-snap: snap to a flux peak just before the CTC start (a wider window for a vowel), rejecting peaks followed by frication, which are the previous word's last consonant. fricative: for s, sh, ch, z, f, th, j, x and h (not voiced "the, that, this…"), walk back to where the 4 to 10 kHz noise begins. Ends follow the voice: the first point after the CTC end where it stays 15 dB below the word's level for 60 ms, capped at the next word; a gap under 30 ms closes (legato). When the voice never drops that far, the end is capped at the CTC end + 1 s (END_TAIL) rather than running on to the next word: uncapped, one word on a test track lasted 27 s.
Confidence0.4 + 0.4 × agreement + 0.2 × posterior (the CTC posterior, saturating at 0.5). Agreement is the share of four other alignments (each model alone on mono; both models on the left channel alone, and on the right) whose raw start is within 60 ms. Written as v in events.json and c in Fantasynth's lyrics.
rest-onset is capped at 0.5 s

The original rule had no limit. On one test track it moved word starts up to 3.2 s early, onto backing vocals and reverb tails that happened to re-enter first. A re-entry further back than 0.5 s is taken to be some other voice and left to onset-snap. Across the four test tracks, 3% of word starts were set by rest-onset, 38% by onset-snap, 10% by the fricative rule, and 48% stayed at the CTC start.

Flux onsets were 31 ms late

librosa.onset.onset_strength pads its output by lag + n_fft / (2 hop) frames, assuming its own default n_fft of 2048. The features use a 1024-point STFT, so every vocal flux onset came out about 31 ms late (a bug inherited from pdoom-video's vocal_feats.py). It now gets n_fft=1024. The fix moved every flux vocalOnset and every onset-snap word start; all numbers on this page are from after it.

The line-time prior

Lyrics repeat. When a hook is sung more often than the text lists it, the unconstrained path is free to give a listed line to a different repeat. On one test track, without a prior, lines inside repeated hooks drifted up to 15 s onto other repeats of the same words. A track JSON usually has approximate line times already (from an LRC file, say), so every letter of line i must lie within that line's reference time ± 3 s (--window). The window never sets a time; the audio still does. With it, 71% of that track's line starts sat within 500 ms of its coarse line times (95% within 1 s), and the unlisted repeats landed in extras.

The stage also runs the free alignment and compares. A line whose free start is more than 1 s from the constrained one keeps the free start as free in raw_lyrics.json, for review, and the count is printed. "Moved" means the two paths disagree, not that the prior was wrong. If the windows admit no path at all, the stage warns and aligns without them. On the four test tracks the two paths disagreed on 17% to 100% of the lines. The extreme was a short text against a song with about 89 s of singing outside it, so the free path had many repeats to choose from.

The prior is frozen on the first run, in out/<slug>/lyrics_prior.json (track, text, times), and reused while the lyric text is unchanged. Otherwise, after export_app.py --lyrics, the track file holds the aligner's own output and would become its own prior, so a misplaced line could never move again. The stage warns when the track's lyrics already carry c and no frozen prior exists.

Vocal onsets and extras

Two by-products of the same vocal features, written whether or not the track has text.

OutputHowWhat it is for
vocalOnsets kind 0, fluxLog-mel flux peaks at least 90 ms apart, above 1.5× their 0.4 s mean plus 15% of the p99, on active voice only. Strength is the peak over the track's p95, clamped to 0.1..1.Consonant and syllable attacks.
vocalOnsets kind 1, pitch jumpThe median-filtered pitch changes by more than 0.8 semitone across 80 ms while voiced, at least 100 ms apart, and no flux onset within 80 ms. Fixed strength 0.35.Legato note changes: singing without an attack. 73 to 85% of them have no Basic Pitch vocal note start within 50 ms, so they add timing Basic Pitch lacks.
lyrics.extrasVocal activity (RMS at a 5 ms hop, median-filtered, above −36 dB) that no word covers, with 100 ms of padding around each word, runs closer than 0.4 s merged, and only runs of 0.5 s or more kept.Ad-libs, backing pads, chants and repeats the text does not list.

Lyric-informed sections

assemble.py uses the words to refine section starts, after the 8-bar phrase snap and before the energy splits and labels. A vocal entry is the first word of a line that starts at least 4 beats after the previous word ends, or the first line (lyric_entries). The pickup rule, from pdoom-video's analyze.py, maps an entry at beat e in bar k to a target bar (entry_bar): bar k when it falls in the first half of the bar (a long pickup belongs to its own bar), bar k + 1 when it falls in the second half (a short pickup leads into the next downbeat).

  • An inner boundary exactly one bar from a target moves onto it (apply_vocal_entries), unless a section would drop under 2 bars.
  • The first and last boundary never move; a boundary already on a target, or moved once, stays.
  • A moved section's labelSource ends in ; lyrics entry bar N. When an energy split cuts it, only the fragment that starts on the moved boundary carries the note.

Across the four aligned test tracks it moved one boundary, by one bar onto a vocal pickup. Phrase-snapped EDM sections already sat on their vocal entries.

Measured

Every word of all four test texts was placed. report.py judges the result against evidence of its own on stems/vocals.wav, never the pipeline's vocalOnsets (the aligner snaps starts to flux peaks, so those would vouch for themselves). The evidence is level rises (6 dB over 100 ms, dated at the half-rise) and spectral-flux peaks, because a legato word that tiles onto the previous one has no level rise. P is the share of word starts within 60 ms of either. Evidence this dense sits near most instants, so the report also gives the chance rate a start placed at random in the voice would get, and judges on kappa = (P − chance) / (1 − chance). Entries (a word 250 ms or more after the previous one) are scored against level rises alone, where chance is low. Coverage is the share of active voice inside a word or an extra.

TrackVerdictPChanceKappaMedian errorEntries PCoverage
Test track Bmostly0.7920.620.447−1.9 ms0.7140.99
Test track Cmostly0.8120.610.517−1.3 ms0.9550.99
Test track Dsolid0.8960.680.676+0.1 ms0.750.98
Test track Emostly0.810.710.334−6.5 ms0.6540.97

Verdicts: solid needs P ≥ 0.85, kappa ≥ 0.50 and coverage ≥ 90%; mostly 0.70 / 0.30 / 75%; any unordered, overlapping or zero-length word, or a silent stem, is check. The thresholds are provisional: they were set before the first real alignment, with Basic Pitch vocal note starts standing in for word starts. Median word confidence ranged from 0.61 to 0.89. The lowest, track B, is a heavily effected vocal: treat an alignment like that as provisional.

Against WhisperX timings

Track D already had word-level timings from a WhisperX transcription. Scored on the same words against the same independent evidence:

TimingsPKappaLine entries on a vocal riseVerdict
Forced alignment (this stage)0.8960.6760.75solid
WhisperX0.7750.2960.459check

Against WhisperX directly, 68% of the starts agree within 100 ms and 87% within 250 ms, with a median offset of −32 ms. The disagreements cluster in a repeated ad-lib passage.

The viewer

viewer.html is a single-page inspector for one analysed track. It draws the extracted data over a playhead and plays either the original audio or one of the synthesised listening checks, so you can judge a track by eye and ear before exporting it.

my-track ▾drums split ▾playzoom ━━●━━☑ follow 120 BPM · beat 0 at 0.5000s · fit p95 10.00 ms · kick 300 · snare 150 · hatOpen 280
Section band: coloured by label (intro, build, drop, breakdown, groove, outro).
Drum lanes: kick, snare, toms, hatClosed, hatOpen, crash, ride. Bar height is velocity; a hollow bar is an off-grid hit.
Piano roll: notes per stem (bass, other, vocals, piano).
Curves: RMS loudness of drums, bass, vocals and other.
Lyrics (when present): words as boxes coloured by confidence, red low to green high, text inside when there is room; a white bar at each line start; a faint band for extras.
Vocal onsets: ticks, height by strength; yellow for flux, pink for a pitch jump.
Playhead: white line; the view follows it while playing.

Controls

  • Track menu or ?slug=<slug> in the URL selects the analysed track. Any slug in out/ works.
  • Audio menu picks what plays: original, drums mix, drums split, grid clicks, bass split.
  • Click anywhere to seek. Space plays and pauses. Zoom sets pixels per beat; follow keeps the playhead in view.

Listening checks

FileWhat you hearUse it to check
check_grid.mp3Original + metronome (high beep on downbeats) + a chime at each section start.Tempo, bar phase, section boundaries.
check_drums_split.mp3Left ear: original. Right ear: drums synthesised from the events.Timing. On headphones, a flam between the ears is a misplaced hit.
check_drums_mix.mp3Original ducked, synthesised drums on top.Missing or extra hits, open versus closed hats.
check_bass_split.mp3Left: original. Right: bass notes as a simple synth.Note timing and pitch (draft quality).
check_lyrics_split.mp3Left: the vocals stem. Right: a tick at every aligned word start: 2 kHz, 3 kHz and louder on a line start, 700 Hz for a word with confidence below 0.6, soft ticks on the syllables of a spelled word.Word timing. A tick early or late against the word's first consonant is an error.
check_vocal_onsets_split.mp3Left: the vocals stem. Right: 1.2 kHz for a flux onset, 600 Hz for a pitch jump.Whether the onsets land on sung attacks and note changes.

The two vocal checks are rendered only when the track has lyrics or vocal onsets. The audio menu does not list them yet; open /out/<slug>/check_lyrics_split.mp3 from serve.py directly.

Why serve.py

Python's built-in http.server can't answer range requests, and Chrome's <audio> stalls without them. serve.py is a small static server that adds them. It serves viewer.html from music-events/ and /out/… and /audio/… from the workspace. It binds to 127.0.0.1 only, on port 8765 by default (serve.py 8766 picks another).

events.json format

The canonical specification, with every field, is CONTRACT.md. In short: time is measured in beats on the fitted grid, and beat 0 is a downbeat. To convert, seconds = gridMarker + beat × 60 / bpm. Arrays are columnar per lane, so they map straight onto typed arrays. The values below are invented.

{
  "version": 2,
  "tempo": [{ "beat": 0, "bpm": 120 }],
  "gridMarker": 0.5,                 // seconds of beat 0
  "meter": 4,
  "lengthBeats": 400.0,
  "gridFit": { "residualMsMedian": 3.0, "shiftToKicksMs": -10.0, "hatSwing": { ... } },
  "sections": [{ "startBeat": 0, "beats": 32, "label": "intro", "energy": 0.1, "labelSource": "rule(...)" }],
  "drums": {
    "kick":  { "b": [32, 33, ...], "v": [0.9, ...], "c": [1, ...], "swing": 0 },
    "snare": { ... }, "toms": { ... }, "hatClosed": { ... }, "hatOpen": { ... }, "crash": { ... }, "ride": { ... }
  },
  "notes": { "bass": { "b": [...], "len": [...], "pitch": [...], "v": [...], "swing": 0 }, "other": ..., "vocals": ..., "piano": ..., "guitar": ... },
  "curves": {
    "samplesPerBeat": 24, "encoding": "u8-base64-p5p95",
    "stems": { "drums": { "rms_db": "base64…", "centroid": "…", "onset": "…" }, "kick": { "rms_db": "…" }, ... }
  },
  "lyrics": {                        // only when the lyrics stage placed some words
    "lines":  { "b": [40.0, ...], "len": [6.0, ...], "text": ["la la la", ...] },
    "words":  { "b": [...], "len": [...], "v": [0.8, ...], "w": ["la", ...], "line": [0, ...], "syl": [null, ...] },
    "extras": { "b": [...], "len": [...] },
    "source": "forced alignment (MMS_FA + wav2vec2 LV60K, CTC, mono/L/R mixture)"
  },
  "vocalOnsets": { "b": [...], "v": [...], "kind": [0, 1, ...] }   // only when the voice is not silent
}
FieldMeaning
bBeat position, snapped (straight or swung slot) for drums and notes; never snapped for lyrics and vocal onsets.
vVelocity 0..1: ADTOF activation, or DrumSep level for DrumSep-only hits.
cConfidence: share of detectors that agreed (0.33 means DrumSep alone).
swingBeats added to the 2nd and 4th 16th of each beat, for that lane.
len, pitchNote length in beats; MIDI pitch.
r, source, offGridQA only: snap residual in ms, provenance, off-grid count. Stripped from the exported copy.
lyrics, vocalOnsetsAdditive, so version stays 2; each is omitted when empty. See CONTRACT.md for every sub-field.
curvesValues 0..255, normalised per track from the 5th to the 95th percentile. Sample k sits at beat k/24.
version2. Version 2 renamed the drum lane tom to toms and the curve stem hh to hats. A reader should accept the version 1 spellings as aliases.

Exporting to Fantasynth

export_app.py copies a track's events into a Fantasynth checkout and updates its track JSON with minimal text edits. It never re-serialises the file, so the lyrics and formatting stay byte for byte. A re-run changes nothing.

OptionEffect
--slug, --track, --allWhich analysed track goes to which public/music/<track>.json. --track defaults to the slug's appTrack; --all is every slug in config.json with an appTrack (and not "all": false).
--appThe target checkout. Else FANTASYNTH_APP, else app in config.json, else an error.
--flacWrites a 16-bit FLAC next to the MP3 (never overwrites), checks that it decodes bit-identically to audio/<slug>.wav, then switches the track's url to it.
--force-sectionsReplaces existing sections. Without it, sections are only written when the track has none.
--lyricsReplaces the track's inline lyrics with the aligned ones: {"lines": [{"words": [{"t", "d", "w", "c"}]}]}, grouped into the lines the text came in. t and d are seconds from the events file's own grid at full precision (3 decimals; d never below 0.001), w the token as the text had it, c the confidence (2 decimals). A gap of more than 2 s between lines (REST_S), and the tail to the song's end, becomes an empty line {"t", "d", "w": ""}: the rest convention of hand-made track files, since a line stays on screen until the next one starts. It refuses only when the events file has no lyrics block, before writing anything (with --all it skips those by name). A track file with no inline lyrics gets them appended, which is how a --text track gets its lyrics. A handTimed track is skipped, with or without --all, and the export says why. Seconds, not beats, so a later gridMarker edit does not move them.

It writes public/music/events/<track>.events.json (about 0.5 MB, three-quarters of it curves). In the track JSON it only ever touches bpm, gridMarker, events, url, sections and, with --lyrics, lyrics (MANAGED), and it verifies every other key is unchanged. A missing track file is created from title and file in config.json, and added to public/music/index.json in title order. lyrics and vocalOnsets pass into the events file whole; an unknown field anywhere still stops the export.

Seek accuracy

After a seek, Chrome's <audio> reports the wrong position for MP3s: the file's encoder delay stops being compensated. measure/ captures the output with an AudioWorklet and compares it with the known audio. In ms, positive means the reported position is later than the sound:

FormatFrom 0Seek 0.5 to 120 sSeek 150+ sVerdict
MP30.0+25.0−1.1varies, can't be corrected
FLAC 16-bit0.0±0.1±0.1exact (chosen)
WAV 16-bit0.0±0.1±0.1exact, 7.2× MP3 size
AAC (.m4a)±0.1±0.1±0.1exact, but re-encodes
Ogg Opus−6.50.00.0constant error from 0

A FLAC decoded from the MP3 is bit-identical to what the events were extracted from, so nothing needs re-analysis. It costs 4.6× the MP3's size. All 44.1 kHz media also reads 1.8 ms ahead because Chrome resamples to 48 kHz; that's constant and harmless. The number belongs to Chromium's decoder, so re-run the measurement when Chrome updates. measure/ has its own package.json for Playwright; the commands are in the README.

Tests

Unit tests (unittest) on synthetic fixtures: no audio, no models, no Fantasynth checkout. Run them from music-events/ with <ws>\venv-main\Scripts\python.exe -m unittest discover -s tests. report.py re-measures any analysed track on demand.

TestCovers
tests/test_report.pyThe report card's measurements, including degenerate and empty inputs; the lyrics check (chance, kappa, entries, coverage, order and overlap) and the vocal onset measurement.
tests/test_lyrics_align.pyThe aligner on synthetic emissions and features: the pronunciation table and numbers sung as words; words landing on their frames with junk going to ★, the numba and Python kernels agreeing, sub-word spans, repeated letters needing a blank, unpronounceable tokens skipped, text longer than the audio refused; refinement keeping order and tiling legato, the rest-onset cap, extras, a pitch jump with no attack found as an onset, confidence from agreement.
tests/test_assemble.pyThe lyrics block in beats from the shifted grid, legato words still tiling after rounding, non-ASCII lyrics surviving, never snapped, omitted when empty; vocal entries, the pickup rule both ways, two bars away not moving, first and last edges fixed, no section under two bars, the labelSource note.
tests/test_export_app.pylyrics and vocalOnsets passed whole, absent blocks absent, unknown fields stopping the export; the lyric format's seconds, grouping and rounding from the events grid at full precision; the splice into CRLF and LF track files, re-runs as no-ops, a track without lyrics getting them appended, other edits unable to touch lyrics; refusal before anything is written.
tests/test_config.pyconfig.json validation (unknown keys, wrong types, _ comments), the music folder order, --all from the config, the checkout resolution order and its errors (no fall-through), and the lyrics stage exiting with nothing written when a named track file or the checkout is missing.
tests/test_hand_timed.pyA hand-timed track: its times and grouping taken verbatim, no confidence, onsets and extras still computed, an unlisted track still aligned; assemble refusing a mix of aligned and hand-timed words; export_app.py --lyrics skipping it, also under --all.

Known limitations

IssueImpact
One tempo, one meter and one bar phase per track.A track edited to drop beats can't be expressed. One test track loses 2 beats in its breakdown: its second half has the right beats and hits, but bar lines and sections 2 beats off, and it runs about 25 ms early against the grid.
Notes are unverified; sections are heuristics.Treat both as drafts to correct.
Lyric alignment has no hand-correction pass.pdoom-video corrected 17 words by hand, each with its acoustic evidence. Here the low-confidence words (v < 0.6) are listed, not reviewed.
The line-time prior is only as good as the track's line times.--text has none, so a text-file track aligns freely and a repeated hook can land on another repeat. Check the lines that carry free. Deleting lyrics_prior.json after an export would refreeze the prior from the aligner's own output.
The lyrics thresholds are provisional, and chance is high (0.61 to 0.71).Read kappa, not P.
Syllable spans exist only for spelled tokens.An acronym in pron or a number gets syl; an ordinary word never does.
The vocal listening checks are not in the viewer's audio menu.Open them by URL from serve.py.
Setup is Windows-only.setup.ps1 and the venv paths assume Windows. The stage scripts are plain Python.

Gotchas

pip can swap torch for a CPU build

A bare pip install in venv-main once replaced CUDA torch with torch 2.14 CPU through a torchvision dependency, silently. Install with -c music-events\constraints-main.txt --extra-index-url https://download.pytorch.org/whl/cu128, and check torch.cuda.is_available() after any install.

Hidden tabs don't load media

Chrome defers <audio> loading in hidden tabs, including automation tabs (visibilityState: hidden). Open the viewer in a normal tab.

Round the ends, not the lengths

Rounding a word's b and len separately broke the tiling of legato words: two words that touched in seconds came out one rounding step apart, or overlapping. len is derived from the rounded end minus the rounded start, in seconds in lyrics.py and in beats in assemble.py.

Read JSON as UTF-8

Reading a UTF-8 track file with the Windows default code page turned a non-ASCII character in a lyric into mojibake. Every JSON read on the lyric path passes encoding="utf-8".

onnxruntime has no Blackwell kernels

ONNX separators silently fall back to CPU on a Blackwell GPU (tested on an RTX 5090). The pipeline uses the PyTorch-native models.

Licences

The MIT licence of this repo covers its code only. The models the pipeline downloads at runtime carry their own terms: several are non-commercial (CC BY-NC, CC BY-NC-SA), one package has no licence, and some weights state none. The default pipeline is not suitable for commercial use. Whether a model's terms carry over to the generated JSON is unsettled. The per-model table is in the README's Model weights and licences.