|
1 | 1 | """This module contains functions for plotting audio-related data.""" |
2 | 2 |
|
3 | 3 | import os |
4 | | -from typing import Any, Dict, Tuple, Union |
| 4 | +from typing import Any, Dict, List, Tuple, Union |
5 | 5 |
|
6 | 6 | # Use non-interactive backend when not in a notebook (e.g., papermill, CI) |
7 | 7 | if not os.environ.get("DISPLAY") and "inline" not in os.environ.get("MPLBACKEND", ""): |
@@ -485,6 +485,190 @@ def plot_waveform_and_specgram( |
485 | 485 | return fig |
486 | 486 |
|
487 | 487 |
|
| 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 | + |
488 | 672 | def play_audio(audio: Audio) -> None: |
489 | 673 | """Play an `Audio` object inline (Jupyter/IPython), supporting 1–2 channels. |
490 | 674 |
|
|
0 commit comments