Skip to content

Commit b8e8377

Browse files
satraclaude
andauthored
Reusable plot_aligned_panels, 10ms/5ms spectrograms, enhancement early (#466)
* Add plot_aligned_panels, standardize spectrograms, enhancement early New senselab API: - plot_aligned_panels(): reusable multi-panel time-aligned visualization supporting waveform, spectrogram, features, segments, and overlay panels - Default spectrogram: 10ms window, 5ms hop (n_fft=256, hop_length=80) Tutorial 1: - Speech enhancement moved to Section 2 (early, before analysis) - Before/after comparison plots throughout - All inline plots replaced with plot_aligned_panels Tutorial 2: - Forced alignment viz uses plot_aligned_panels - PPG aligned viz uses plot_aligned_panels Lab: - Acoustic analysis and comparison plots use plot_aligned_panels All spectrograms standardized to 10ms window / 5ms hop. All time axes verified against audio duration. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * Address review comments: mono check, CPU safety, Path import, squeeze fix plot_aligned_panels: - Add mono audio enforcement (raises ValueError) - CPU safety: .cpu() before .numpy() for GPU tensors - Filter sample_rate from non-mel spectrogram params PPG: - Fix squeeze() without dim arg — now only squeeze batch dim (dim 0) Tutorials: - Add Path import to load cells (needed when recording cell skipped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * Use whisper-large-v3-turbo for accurate ASR in Tutorial 2 whisper-small was truncating/hallucinating on the test audio (only transcribed "This is Johnny" from a 5s multi-speaker clip). whisper-large-v3-turbo correctly transcribes the full content. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 0573932 commit b8e8377

6 files changed

Lines changed: 474 additions & 389 deletions

File tree

src/senselab/audio/tasks/features_extraction/ppg.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,10 @@ def _to_frame_major_posteriorgram(posteriorgram: torch.Tensor) -> torch.Tensor:
218218
Raises:
219219
ValueError: If the tensor has fewer than 2 dimensions after squeezing.
220220
"""
221-
t = posteriorgram.squeeze() # remove batch dim if present
221+
t = posteriorgram.detach().cpu()
222+
# Remove only the batch dimension (dim 0) if it's size 1
223+
if t.ndim == 3 and t.shape[0] == 1:
224+
t = t.squeeze(0)
222225
if t.ndim < 2:
223226
raise ValueError(f"Expected at least a 2-D posteriorgram after squeezing, got shape {t.shape}")
224227
# The ppgs library outputs (phonemes, frames) where the phoneme count
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
"""This module contains functions for plotting audio-related data."""
22

3-
from .plotting import play_audio, plot_specgram, plot_waveform # noqa: F401
3+
from .plotting import play_audio, plot_aligned_panels, plot_specgram, plot_waveform # noqa: F401

src/senselab/audio/tasks/plotting/plotting.py

Lines changed: 185 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""This module contains functions for plotting audio-related data."""
22

33
import os
4-
from typing import Any, Dict, Tuple, Union
4+
from typing import Any, Dict, List, Tuple, Union
55

66
# Use non-interactive backend when not in a notebook (e.g., papermill, CI)
77
if not os.environ.get("DISPLAY") and "inline" not in os.environ.get("MPLBACKEND", ""):
@@ -485,6 +485,190 @@ def plot_waveform_and_specgram(
485485
return fig
486486

487487

488+
def plot_aligned_panels(
489+
audio: Audio,
490+
panels: List[Dict[str, Any]],
491+
title: str = "",
492+
figsize: Tuple[float, float] | None = None,
493+
spectrogram_params: Dict[str, Any] | None = None,
494+
context: _Context = "auto",
495+
) -> Figure:
496+
"""Create a multi-panel time-aligned visualization from an Audio object.
497+
498+
Each panel shares the same time axis. Supported panel types:
499+
500+
- ``{"type": "waveform"}`` -- waveform amplitude.
501+
- ``{"type": "spectrogram", "mel": True/False}`` -- linear or mel spectrogram.
502+
- ``{"type": "features", "data": [(times, values, label, color), ...]}`` --
503+
scatter/line overlay of feature curves (e.g., pitch, formants).
504+
- ``{"type": "segments", "segments": [{"label": str, "start": float, "end": float}, ...]}``
505+
-- colored horizontal bars for phoneme/word segments.
506+
- ``{"type": "overlay_on_spectrogram", "mel": True/False, "overlays": [...]}`` --
507+
spectrogram with scatter overlays (each overlay is a dict with keys
508+
``times``, ``values``, ``label``, ``color``, and optional ``size``).
509+
510+
Args:
511+
audio: Input mono audio.
512+
panels: List of panel specification dicts (see above).
513+
title: Overall figure title.
514+
figsize: Base ``(width, height)`` in inches **before** context scaling.
515+
Defaults to ``(14, sum_of_panel_heights)``.
516+
spectrogram_params: Parameters forwarded to torchaudio spectrogram transforms.
517+
Defaults to ``{"n_fft": 256, "hop_length": 80, "win_length": 160}``.
518+
context: Size preset or numeric scale.
519+
520+
Returns:
521+
matplotlib.figure.Figure: The created figure.
522+
"""
523+
import torchaudio.transforms as T
524+
525+
# Enforce mono
526+
if audio.waveform.shape[0] != 1:
527+
raise ValueError("plot_aligned_panels requires mono audio. Downmix multi-channel first.")
528+
529+
if spectrogram_params is None:
530+
spectrogram_params = {"n_fft": 256, "hop_length": 80, "win_length": 160}
531+
532+
sr = audio.sampling_rate
533+
duration = audio.waveform.shape[1] / sr
534+
535+
# Height ratios
536+
ratio_map = {
537+
"waveform": 1,
538+
"spectrogram": 2,
539+
"features": 1,
540+
"segments": 1,
541+
"overlay_on_spectrogram": 2,
542+
}
543+
height_ratios = [ratio_map.get(p.get("type", "waveform"), 1) for p in panels]
544+
545+
scale = _resolve_scale(context)
546+
rc = _rc_for_scale(scale)
547+
if figsize is None:
548+
base_h = float(sum(height_ratios)) * 1.8
549+
base = (14.0, max(base_h, 4.0))
550+
else:
551+
base = figsize
552+
scaled_size = (base[0] * scale, base[1] * scale)
553+
554+
# Helper: compute spectrogram tensor (cached across panels in this call)
555+
_spec_cache: Dict[str, np.ndarray] = {}
556+
557+
def _get_spec(mel: bool) -> Tuple[np.ndarray, float, float]:
558+
key = "mel" if mel else "linear"
559+
if key not in _spec_cache:
560+
wf = audio.waveform.squeeze().cpu()
561+
# Filter out sample_rate from params for non-mel transforms
562+
filtered_params = {k: v for k, v in spectrogram_params.items() if k != "sample_rate"}
563+
if mel:
564+
transform = T.MelSpectrogram(sample_rate=sr, **filtered_params)
565+
else:
566+
transform = T.Spectrogram(**filtered_params)
567+
spec_tensor = transform(wf)
568+
_spec_cache[key] = _power_to_db(spec_tensor.cpu().numpy())
569+
spec_db = _spec_cache[key]
570+
if mel:
571+
return spec_db, 0.0, float(spec_db.shape[0] - 1)
572+
else:
573+
return spec_db, 0.0, float(sr / 2)
574+
575+
with rc_context(rc):
576+
fig, axes = plt.subplots(
577+
len(panels),
578+
1,
579+
figsize=scaled_size,
580+
sharex=True,
581+
gridspec_kw={"height_ratios": height_ratios},
582+
squeeze=False,
583+
)
584+
axes_list = [axes[i, 0] for i in range(len(panels))]
585+
586+
waveform_np = audio.waveform.squeeze().cpu().numpy()
587+
time_wav = np.linspace(0, duration, len(waveform_np), endpoint=False)
588+
589+
for ax, panel in zip(axes_list, panels):
590+
ptype = panel.get("type", "waveform")
591+
592+
if ptype == "waveform":
593+
ax.plot(time_wav, waveform_np, linewidth=0.3, color="steelblue")
594+
ax.set_ylabel("Amplitude")
595+
ax.grid(True, alpha=0.2)
596+
597+
elif ptype == "spectrogram":
598+
mel = panel.get("mel", False)
599+
spec_db, f0, f1 = _get_spec(mel)
600+
ax.imshow(
601+
spec_db,
602+
aspect="auto",
603+
origin="lower",
604+
extent=[0, duration, f0, f1],
605+
cmap="magma",
606+
)
607+
ax.set_ylabel("Mel bins" if mel else "Frequency (Hz)")
608+
609+
elif ptype == "features":
610+
data = panel.get("data", [])
611+
for times, values, label, color in data:
612+
t_np = times.cpu().numpy() if torch.is_tensor(times) else np.asarray(times)
613+
v_np = values.cpu().numpy() if torch.is_tensor(values) else np.asarray(values)
614+
ax.scatter(t_np, v_np, s=3, c=color, label=label, alpha=0.7)
615+
ax.set_ylabel("Value")
616+
ax.legend(loc="upper right", fontsize=7)
617+
ax.grid(True, alpha=0.3)
618+
619+
elif ptype == "segments":
620+
seg_list = panel.get("segments", [])
621+
unique_labels = sorted({s["label"] for s in seg_list})
622+
y_map = {lbl: i for i, lbl in enumerate(unique_labels)}
623+
cmap = plt.get_cmap("tab20", max(len(unique_labels), 1))
624+
for seg in seg_list:
625+
y = y_map[seg["label"]]
626+
w = seg["end"] - seg["start"]
627+
ax.barh(y, w, left=seg["start"], height=0.7, color=cmap(y), alpha=0.85, edgecolor="none")
628+
ax.set_yticks(range(len(unique_labels)))
629+
ax.set_yticklabels(unique_labels, fontsize=7)
630+
ax.set_ylabel("Segment")
631+
ax.grid(axis="x", linestyle="--", alpha=0.3)
632+
633+
elif ptype == "overlay_on_spectrogram":
634+
mel = panel.get("mel", False)
635+
spec_db, f0, f1 = _get_spec(mel)
636+
ax.imshow(
637+
spec_db,
638+
aspect="auto",
639+
origin="lower",
640+
extent=[0, duration, f0, f1],
641+
cmap="magma",
642+
alpha=0.9,
643+
)
644+
overlays = panel.get("overlays", [])
645+
for ov in overlays:
646+
t_np = ov["times"].cpu().numpy() if torch.is_tensor(ov["times"]) else np.asarray(ov["times"])
647+
v_np = ov["values"].cpu().numpy() if torch.is_tensor(ov["values"]) else np.asarray(ov["values"])
648+
ax.scatter(
649+
t_np,
650+
v_np,
651+
s=ov.get("size", 3),
652+
c=ov["color"],
653+
label=ov.get("label", ""),
654+
zorder=3,
655+
alpha=0.7,
656+
)
657+
ax.set_ylabel("Mel bins" if mel else "Frequency (Hz)")
658+
if overlays:
659+
ax.legend(loc="upper right", fontsize=7)
660+
661+
# Shared x-axis config
662+
axes_list[-1].set_xlabel("Time (seconds)")
663+
axes_list[0].set_xlim(0, duration)
664+
665+
if title:
666+
fig.suptitle(title)
667+
fig.tight_layout(rect=(0, 0, 1, 0.96) if title else (0, 0, 1, 1))
668+
plt.show(block=False)
669+
return fig
670+
671+
488672
def play_audio(audio: Audio) -> None:
489673
"""Play an `Audio` object inline (Jupyter/IPython), supporting 1–2 channels.
490674

0 commit comments

Comments
 (0)