Audio alignment

SpectrogramGuidedAligner cuts speech into one AudioSegment per transcript token, cutting at the quietest, steadiest point between words since explanations mask segments.

Install

pip install "mllm-shap[audio,transformers]"

audio decodes (soundfile) and refines boundaries (librosa); transformers runs the default Wav2Vec2 model.

Align a transcript

from pathlib import Path

from mllm_shap import AudioPart
from mllm_shap.alignment import SpectrogramGuidedAligner, Wav2Vec2Ctc

model = Wav2Vec2Ctc("facebook/wav2vec2-base-960h", revision="main", device="cpu")
aligner = SpectrogramGuidedAligner(model)
audio = AudioPart(Path("speech.wav"), sample_rate=16000)
for segment in aligner.align("I had that curiosity beside me", audio):
    print(segment.token, round(segment.start_time, 2), round(segment.end_time, 2))

align takes a string (split on whitespace) or a token list; a token the model cannot spell, such as a dash, gets no segment. attach_audio=True stores each segment’s samples as WAV bytes in segment.audio. Segments last 50 ms or more; times are in seconds, sample indices at the audio’s own rate.

How it works

  1. The CTC (connectionist temporal classification) model scores every frame.

  2. A Viterbi pass aligns the transcript’s characters to frames in order, with the model’s word separator between tokens.

  3. A token spans its first to last character. Each boundary moves, within the gap between two tokens, to the minimum of energy_weight * rms + flux_weight * flux (normalised RMS energy and spectral flux). The first and last edges search 80 ms around their rough position.

  4. A boundary moves only to a quiet point (RMS at most half the window mean); AudioSegment.boundary_refined says whether both edges moved.

Waveform of a 3.4 s sentence with nine word segments, dashed CTC edges, arrows to the refined boundaries, and the RMS energy below.

Nine words of a recorded sentence. Dashed: rough CTC edges; arrows: refinement; solid: final boundaries, each in a dip of the RMS energy (bottom). Speech never goes quiet between “curiosity” and “beside”, so that boundary stays.

With energy_weight=0, flux_weight=1 cuts follow spectral change: a few move 10 to 40 ms; 1 of 9 boundaries lands on a quiet point, not 7. plot_audio_segments() (extra viz) draws this figure; values colours segments like the attribution renderers.

Audio players

explanation.players: sgpa_segments (SgpaSegmentPartitioner) makes each spoken word a player. Only messages with an AudioPart and its transcript as text add players. A PlayerSpan covers the word in the transcript and its audio (samples), so policies mask both: delete cuts the samples, pad and neutral silence them.

from mllm_shap import ExplainConfig, Message, Role, TextPart

spoken = Message(role=Role.USER, content=(TextPart("I had that curiosity"), audio))
config = ExplainConfig.model_validate({
    "backend": {"kind": "mock", "model_id": "stub"},
    "explanation": {
        "players": "sgpa_segments",
        "plugin_options": {"sgpa_segments": {
            "model_id": "facebook/wav2vec2-base-960h", "revision": "main"}},
    },
})
The sentence's word segments coloured by their attribution values.

Words as players, coloured by attribution. The mock backend scores every word alike, so the colours match.

Options: model_id, revision, device, energy_weight, flux_weight, text_roles (roles whose typed words are players too; none by default) and transcript. transcript: send (default) sends the masked transcript with the masked audio; align_only sends the audio alone, so values reflect what the model hears. Backends that hear audio: Audio input.

Equal-duration players

explanation.players: uniform_segments cuts each audio message into equal pieces on whole frame_ms frames (default 20 ms), one per transcript word unless option segments says otherwise. It sends no transcript and needs no alignment model: the control for sgpa_segments with transcript: align_only, same player count, other boundaries.

Other CTC models

Any object with sample_rate, blank_id, vocab and log_probs(waveform) is a CtcModel, such as a Wav2Vec2 checkpoint for another language or a fixed matrix in tests. Pin revision to a commit hash for reproducible segments.

Notebook: Audio alignment with SGPA. Method: SGPA (spectrogram-guided phonetic alignment), arXiv:2603.02250.