nida-tts / src /nida /data /events.py
Bilal7Dev's picture
Nida v0.5 (research preview): weights, 16 voices, code, model card
c0bce59 verified
Raw History Blame Contribute Delete
8.29 kB
"""S6 — frame-level sound-event probabilities → :class:`EventDetection` intervals.
The tagger (PANNs ``Cnn14_DecisionLevelMax``) gives per-frame probabilities for AudioSet
classes. Each Nida event kind maps to one or more AudioSet classes (tag-spec §2, R3); the
kind's frame probability is the maximum over its classes. A detection is a maximal run of
frames at or above ``onset`` (gaps up to ``merge_gap_ms`` are bridged); its confidence is
the maximum frame probability inside the run. Fusion (S7) then applies the per-kind
confidence bands, so ``onset`` must not exceed any band's ``low`` — otherwise a
middle-band event could vanish here instead of dropping its segment. Runs shorter than
the kind's ``min_ms`` are not detections; for each kind the highest confidence among such
blips is returned (``too_short``), never silently discarded — the caller drops a segment
whose blip reaches the fusion band ``low`` (precision before recall, tag-spec §7).
"""
from __future__ import annotations
import math
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING
from nida.data.types import EventDetection
from nida.text.tags import EVENTS
if TYPE_CHECKING:
import numpy as np
from numpy.typing import NDArray
__all__ = ["EventConfig", "FrameDetections", "detect_events"]
_NON_DETECTABLE = frozenset({"pause_short", "pause_long"})
@dataclass(frozen=True)
class EventConfig:
"""configs/data/events.yaml. ``classes[kind]`` lists AudioSet display names."""
classes: Mapping[str, tuple[str, ...]]
onset: float
merge_gap_ms: int
min_ms: Mapping[str, int]
def __post_init__(self) -> None:
kinds = set(EVENTS) - _NON_DETECTABLE
if set(self.classes) != kinds:
raise ValueError(
f"classes must map exactly {sorted(kinds)}; "
f"missing={sorted(kinds - set(self.classes))} "
f"extra={sorted(set(self.classes) - kinds)}"
)
if set(self.min_ms) != kinds:
raise ValueError("min_ms must have exactly one entry per detectable event kind")
seen: dict[str, str] = {}
for kind, names in self.classes.items():
if not names:
raise ValueError(f"event kind {kind!r} maps to no AudioSet class")
for name in names:
if name in seen:
raise ValueError(
f"AudioSet class {name!r} mapped to {seen[name]!r} and {kind!r}"
)
seen[name] = kind
if not (math.isfinite(self.onset) and 0.0 < self.onset <= 1.0):
raise ValueError(f"onset must be in (0, 1], got {self.onset!r}")
for name, value in [("merge_gap_ms", self.merge_gap_ms), *self.min_ms.items()]:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ValueError(f"{name} must be a non-negative int, got {value!r}")
@classmethod
def from_mapping(cls, raw: Mapping[str, object]) -> EventConfig:
expected = {"classes", "onset", "merge_gap_ms", "min_ms"}
if set(raw) != expected:
raise ValueError(
f"event config keys: missing={sorted(expected - set(raw))} "
f"unknown={sorted(set(raw) - expected)}"
)
classes, min_ms, onset, gap = (
raw["classes"],
raw["min_ms"],
raw["onset"],
raw["merge_gap_ms"],
)
if not isinstance(classes, Mapping) or not all(
isinstance(v, list) and all(isinstance(n, str) for n in v) for v in classes.values()
):
raise ValueError("classes must map kinds to lists of class names")
if not isinstance(min_ms, Mapping):
raise ValueError("min_ms must be a mapping")
if isinstance(onset, bool) or not isinstance(onset, int | float):
raise ValueError("onset must be a number")
if isinstance(gap, bool) or not isinstance(gap, int):
raise ValueError("merge_gap_ms must be an int")
return cls(
classes={str(k): tuple(v) for k, v in classes.items()},
onset=float(onset),
merge_gap_ms=gap,
min_ms={str(k): v for k, v in min_ms.items()}, # validated in __post_init__
)
def check_onset_against(self, band_lows: Mapping[str, float]) -> None:
"""Raise if ``onset`` exceeds a fusion band's ``low`` for some event kind."""
missing = sorted(set(self.classes) - set(band_lows))
if missing:
raise ValueError(f"no fusion band for event kinds {missing}")
too_high = sorted(k for k in self.classes if band_lows[k] < self.onset)
if too_high:
raise ValueError(f"onset {self.onset} above the fusion band low of {too_high}")
@dataclass(frozen=True)
class FrameDetections:
detections: tuple[EventDetection, ...]
too_short: Mapping[str, float] # kind -> max confidence among too-short runs
def detect_events(
probs: NDArray[np.float32],
class_names: Sequence[str],
*,
frame_hop_ms: float,
duration_ms: int,
cfg: EventConfig,
source: str,
) -> FrameDetections:
"""Turn framewise class probabilities ``[num_frames, len(class_names)]`` into detections.
Frame ``t`` covers ``[t * hop, (t + 1) * hop)`` ms, clamped to ``duration_ms``.
Raises:
ValueError: shape mismatch, values outside [0, 1] or non-finite, a configured
class missing from ``class_names``, a bad hop or duration, or a frame count
inconsistent with ``duration_ms`` (more than one frame of slack).
"""
import numpy as np
if probs.ndim != 2 or probs.shape[1] != len(class_names):
raise ValueError(f"probs shape {probs.shape} does not match {len(class_names)} classes")
if len(set(class_names)) != len(class_names):
raise ValueError("duplicate class names")
in_range = probs.size == 0 or (float(np.min(probs)) >= 0.0 and float(np.max(probs)) <= 1.0)
if not np.all(np.isfinite(probs)) or not in_range:
raise ValueError("probabilities must be finite and in [0, 1]")
if not (math.isfinite(frame_hop_ms) and frame_hop_ms >= 1):
raise ValueError(f"frame_hop_ms must be a finite number >= 1 ms, got {frame_hop_ms!r}")
if type(duration_ms) is not int or duration_ms <= 0:
raise ValueError(f"invalid duration_ms {duration_ms!r}")
expected_frames = duration_ms / frame_hop_ms
if abs(probs.shape[0] - expected_frames) > 1 + 1e-9:
raise ValueError(
f"{probs.shape[0]} frames for {duration_ms} ms at {frame_hop_ms} ms hop "
f"(expected about {expected_frames:.1f})"
)
column = {name: i for i, name in enumerate(class_names)}
missing = sorted({n for names in cfg.classes.values() for n in names} - set(column))
if missing:
raise ValueError(f"tagger output lacks configured classes {missing}")
gap_frames = math.floor(cfg.merge_gap_ms / frame_hop_ms)
detections: list[EventDetection] = []
too_short: dict[str, float] = {}
for kind in sorted(cfg.classes):
kind_probs = probs[:, [column[n] for n in cfg.classes[kind]]].max(axis=1)
active = np.flatnonzero(kind_probs >= cfg.onset)
if active.size == 0:
continue
runs: list[tuple[int, int]] = [] # inclusive frame ranges
start = prev = int(active[0])
for frame in active[1:].tolist():
if frame - prev - 1 > gap_frames:
runs.append((start, prev))
start = frame
prev = frame
runs.append((start, prev))
for first, last in runs:
start_ms = min(round(first * frame_hop_ms), duration_ms - 1)
end_ms = min(round((last + 1) * frame_hop_ms), duration_ms)
conf = float(np.max(kind_probs[first : last + 1]))
if end_ms - start_ms < cfg.min_ms[kind]:
too_short[kind] = max(too_short.get(kind, 0.0), conf)
continue
detections.append(EventDetection(kind, start_ms, end_ms, conf, source))
detections.sort(key=lambda d: (d.start_ms, d.end_ms, d.kind))
return FrameDetections(tuple(detections), too_short)