nida-tts / src /nida /data /timings.py
Bilal7Dev's picture
Nida v0.5 (research preview): weights, 16 voices, code, model card
c0bce59 verified
Raw History Blame Contribute Delete
25.6 kB
"""Unit timelines for the aligned text path (E11, ADR-0008): ``timings.jsonl``.
The aligned model gives every text *unit* an explicit duration instead of letting attention
find the text-to-frame mapping. This module builds, per dataset segment, the timeline of
units over the segment's latent frames and reads/writes it. It is pure (no torch, no
numpy); the ``timings`` pilot stage (:meth:`nida.data.pilot.Pilot._stage_timings`) feeds
it the CTC word alignment.
Units tile the model token sequence ``model_tokens(parse(text))`` (the sequence
:func:`nida.model.vocab.encode_text` encodes, one token = one id):
* a *word* unit = the character tokens of one word plus the single ``" "`` separator token
that follows it (if any);
* an *event* unit = one ``<ev:ID>`` token plus its following ``" "`` (if any);
* an opening span marker ``<sp:ID>`` belongs to the unit that follows it, a closing marker
``</sp:ID>`` to the unit that precedes it (markers have no duration of their own).
Unit ``k`` covers tokens ``[char_start_k, char_end_k)``; ``char_start_0 = 0``,
``char_start_{k+1} = char_end_k`` and ``char_end_last = n_tokens``. Its ``frame_start_k`` is
the latent frame where it begins; it lasts until the next unit's start, the last unit until
``num_frames``. Silence between units therefore belongs to the unit before it, and leading
silence to the first unit (``frame_start_0 = 0``).
``timings.jsonl`` (one object per line, sorted by ``segment_id``)::
{"segment_id": "...", "num_frames": 75, "frame_hop_ms": 39.9..., "n_tokens": 31,
"units": [[char_start, char_end, frame_start], ...]}
Where the times come from: a word unit starts at its CTC forced-alignment start, an event
unit at the ``start_ms`` of its tag record (``tags_json`` of the annotate row), both
converted with ``round(ms / frame_hop_ms)``. Segments that cannot be given a valid timeline
are returned as quarantine records with a ``timings_*`` reason; nothing is dropped silently.
"""
from __future__ import annotations
import json
import math
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Literal, NamedTuple, TypeGuard
from nida.data.fusion import normalise_word
from nida.data.types import QuarantineRecord, TimedWord
from nida.model.vocab import encode_text
from nida.text.tags import EVENTS, Event, Span, TagSyntaxError, Word, model_tokens, parse
from nida.utils.io import atomic_write_text
__all__ = [
"STAGE",
"TIMINGS_FILENAME",
"IndexEntry",
"SegmentTimings",
"SpokenWord",
"TagTime",
"TextUnit",
"TimelineResult",
"TimingsError",
"Unit",
"build_timings",
"group_units",
"load_timings",
"match_words",
"ms_to_frame",
"parse_tag_times",
"read_index",
"spoken_words",
"text_units",
"write_timings",
]
STAGE = "timings"
TIMINGS_FILENAME = "timings.jsonl"
_KEYS = frozenset({"segment_id", "num_frames", "frame_hop_ms", "n_tokens", "units"})
class TimingsError(ValueError):
"""A timeline or a ``timings.jsonl`` file violates the format; names the segment."""
def __init__(self, message: str, segment_id: str | None = None) -> None:
super().__init__(message if segment_id is None else f"segment {segment_id}: {message}")
self.segment_id = segment_id
def _is_int(value: object) -> TypeGuard[int]:
return type(value) is int
class Unit(NamedTuple):
"""One unit: tokens ``[char_start, char_end)`` begin at latent frame ``frame_start``."""
char_start: int
char_end: int
frame_start: int
@dataclass(frozen=True)
class SegmentTimings:
"""The unit timeline of one segment; every invariant is checked on construction.
Attributes:
segment_id: Dataset segment id.
num_frames: Latent frames of the segment.
frame_hop_ms: Latent frame hop in ms (dataset ``meta.json``).
n_tokens: Number of model tokens (``len(encode_text(text))``).
units: Contiguous units tiling ``[0, n_tokens)`` with non-decreasing frame starts
in ``[0, num_frames)``; the first starts at frame 0.
Raises:
TimingsError: on any violation.
"""
segment_id: str
num_frames: int
frame_hop_ms: float
n_tokens: int
units: tuple[Unit, ...]
def __post_init__(self) -> None:
sid = self.segment_id
if not isinstance(sid, str) or not sid:
raise TimingsError(f"invalid segment id {sid!r}")
if not _is_int(self.num_frames) or self.num_frames < 1:
raise TimingsError(f"num_frames must be an int >= 1, got {self.num_frames!r}", sid)
hop = self.frame_hop_ms
if isinstance(hop, bool) or not isinstance(hop, int | float):
raise TimingsError(f"frame_hop_ms must be a number, got {hop!r}", sid)
if not (math.isfinite(hop) and hop > 0):
raise TimingsError(f"frame_hop_ms must be finite and > 0, got {hop!r}", sid)
if not _is_int(self.n_tokens) or self.n_tokens < 1:
raise TimingsError(f"n_tokens must be an int >= 1, got {self.n_tokens!r}", sid)
if not self.units:
raise TimingsError("no units", sid)
expected_start = 0
previous_frame = 0
for index, unit in enumerate(self.units):
if len(unit) != 3 or not all(_is_int(x) for x in unit):
raise TimingsError(f"unit {index} must be three ints, got {tuple(unit)!r}", sid)
char_start, char_end, frame_start = unit
if char_start != expected_start:
raise TimingsError(
f"unit {index} starts at token {char_start}, expected {expected_start} "
"(units must tile the tokens)",
sid,
)
if char_end <= char_start:
raise TimingsError(f"unit {index} is empty: tokens [{char_start}, {char_end})", sid)
if not 0 <= frame_start < self.num_frames:
raise TimingsError(
f"unit {index} starts at frame {frame_start}, outside [0, {self.num_frames})",
sid,
)
if index == 0 and frame_start != 0:
raise TimingsError(f"first unit must start at frame 0, got {frame_start}", sid)
if frame_start < previous_frame:
raise TimingsError(
f"unit {index} starts at frame {frame_start} before unit {index - 1} "
f"({previous_frame}): frame starts must not decrease",
sid,
)
previous_frame = frame_start
expected_start = char_end
if expected_start != self.n_tokens:
raise TimingsError(
f"units end at token {expected_start}, but n_tokens is {self.n_tokens}", sid
)
@property
def zero_length_units(self) -> int:
"""Units that share their start frame with the next unit (duration 0 frames)."""
return sum(1 for a, b in zip(self.units, self.units[1:], strict=False) if a[2] == b[2])
def to_json(self) -> str:
"""The ``timings.jsonl`` line (without newline)."""
return json.dumps(
{
"segment_id": self.segment_id,
"num_frames": self.num_frames,
"frame_hop_ms": self.frame_hop_ms,
"n_tokens": self.n_tokens,
"units": [list(unit) for unit in self.units],
},
ensure_ascii=False,
allow_nan=False,
)
@classmethod
def from_obj(cls, obj: object, where: str) -> SegmentTimings:
"""Build from a decoded JSON object.
Raises:
TimingsError: on a wrong shape, key set or type (``where`` locates the line) or
any invariant violation.
"""
if not isinstance(obj, dict) or set(obj) != _KEYS:
keys = sorted(obj) if isinstance(obj, dict) else type(obj).__name__
raise TimingsError(f"{where}: expected an object with keys {sorted(_KEYS)}, got {keys}")
sid = obj["segment_id"]
units_raw = obj["units"]
if not isinstance(sid, str) or not sid:
raise TimingsError(f"{where}: segment_id must be a non-empty string")
if not isinstance(units_raw, list):
raise TimingsError(f"{where}: units must be a list", sid)
units: list[Unit] = []
for index, raw in enumerate(units_raw):
if not isinstance(raw, list) or len(raw) != 3 or not all(_is_int(x) for x in raw):
raise TimingsError(f"{where}: unit {index} must be a list of three ints", sid)
units.append(Unit(raw[0], raw[1], raw[2]))
hop = obj["frame_hop_ms"]
if isinstance(hop, bool) or not isinstance(hop, int | float):
raise TimingsError(f"{where}: frame_hop_ms must be a number", sid)
return cls(sid, obj["num_frames"], float(hop), obj["n_tokens"], tuple(units))
# ------------------------------------------------------------------------ text units
@dataclass(frozen=True)
class TextUnit:
"""A unit of the token sequence: tokens ``[char_start, char_end)``.
``label`` is the word text (``kind == "word"``) or the event id (``"event"``).
"""
kind: Literal["word", "event"]
char_start: int
char_end: int
label: str
def _is_marker(token: str) -> bool:
return len(token) > 1 and token.startswith("<") and token.endswith(">")
def group_units(tokens: Sequence[str]) -> list[TextUnit]:
"""Group model tokens (:func:`nida.text.tags.model_tokens`) into units.
Raises:
TimingsError: if the sequence is not what ``model_tokens`` produces (a marker or
separator with no unit to belong to).
"""
units: list[TextUnit] = []
count = len(tokens)
i = 0
while i < count:
start = i
while i < count and tokens[i].startswith("<sp:"):
i += 1
if i == count or tokens[i] == " " or tokens[i].startswith("</sp:"):
raise TimingsError(f"token {i} ({tokens[min(i, count - 1)]!r}) belongs to no unit")
if tokens[i].startswith("<ev:"):
kind: Literal["word", "event"] = "event"
label = tokens[i].removeprefix("<ev:").removesuffix(">")
i += 1
else:
kind = "word"
first = i
while i < count and not _is_marker(tokens[i]) and tokens[i] != " ":
i += 1
label = "".join(tokens[first:i])
if not label:
raise TimingsError(f"token {first} ({tokens[first]!r}) starts no word")
while i < count and tokens[i].startswith("</sp:"):
i += 1
if i < count and tokens[i] == " ":
i += 1
units.append(TextUnit(kind, start, i, label))
return units
def text_units(tagged_text: str) -> tuple[list[TextUnit], int]:
"""Units and token count of a tagged text.
Returns:
``(units, n_tokens)`` where ``n_tokens == len(model_tokens(parse(text)))``.
Raises:
TagSyntaxError: for text that is not valid tag grammar.
TimingsError: if the token grouping disagrees with the parse tree (a bug here).
"""
items = parse(tagged_text)
tokens = model_tokens(items)
units = group_units(tokens)
expected: list[tuple[str, str]] = []
for item in items:
for leaf in item.children if isinstance(item, Span) else (item,):
if isinstance(leaf, Word):
expected.append(("word", leaf.text))
elif isinstance(leaf, Event):
expected.append(("event", leaf.id))
if [(u.kind, u.label) for u in units] != expected:
raise TimingsError(f"token grouping {units!r} disagrees with the parse tree {expected!r}")
return units, len(tokens)
# ------------------------------------------------------------------------ matching
@dataclass(frozen=True)
class SpokenWord:
"""An aligned word as it reads in the dataset text.
``optional`` marks a gap filler that fusion may or may not have kept in the text.
"""
text: str
start_ms: int
optional: bool = False
def spoken_words(words: Sequence[TimedWord]) -> list[SpokenWord]:
"""Aligned words (fillers inserted) as fusion wrote them into the text.
Applies fusion's per-word normalisation (:func:`nida.data.fusion.normalise_word`). A word
without an alignment score is a gap filler (``insert_fillers`` gives them none, while
``align_words`` always scores its words): it is optional because fusion's event
handling and the S6 detectors that filtered it at annotate time are not replayed here.
Raises:
ValueError: if fusion would have rejected a word.
"""
return [SpokenWord(normalise_word(w.text), w.start_ms, w.align_score is None) for w in words]
def match_words(text_words: Sequence[str], spoken: Sequence[SpokenWord]) -> list[int] | None:
"""Start time (ms) of every word of the text, or ``None`` if they do not correspond.
Every mandatory spoken word must appear in the text, in order; an optional one (gap
filler) is used when the text has it at that point and skipped otherwise. If an optional
word and the next mandatory word both equal the next text word, the mandatory one wins
(a text that really has both then fails to match and is quarantined, never mistimed).
"""
starts: list[int] = []
j = 0
for k, word in enumerate(spoken):
if j < len(text_words) and text_words[j] == word.text:
if word.optional:
following = next((w for w in spoken[k + 1 :] if not w.optional), None)
if following is not None and following.text == text_words[j]:
continue
starts.append(word.start_ms)
j += 1
elif not word.optional:
return None
return starts if j == len(text_words) else None
class TagTime(NamedTuple):
"""The part of a tag record (``tags_json``) that the timeline needs."""
tag: str
start_ms: int
end_ms: int
def parse_tag_times(tags_json: str) -> list[TagTime]:
"""Tag records of an annotate row in time order ``(start_ms, end_ms, tag)``.
Raises:
TimingsError: if ``tags_json`` is not a list of records with a ``tag`` string and
non-negative integer ``start_ms`` / ``end_ms``.
"""
try:
raw = json.loads(tags_json)
except json.JSONDecodeError as err:
raise TimingsError(f"tags_json is not valid JSON ({err.msg})") from err
if not isinstance(raw, list):
raise TimingsError("tags_json must be a list")
out: list[TagTime] = []
for record in raw:
if not isinstance(record, dict):
raise TimingsError(f"tag record must be an object, got {record!r}")
tag, start_ms, end_ms = record.get("tag"), record.get("start_ms"), record.get("end_ms")
if not (isinstance(tag, str) and _is_int(start_ms) and _is_int(end_ms) and start_ms >= 0):
raise TimingsError(f"invalid tag record {record!r}")
out.append(TagTime(tag, start_ms, end_ms))
return sorted(out, key=lambda t: (t.start_ms, t.end_ms, t.tag))
def ms_to_frame(time_ms: int, frame_hop_ms: float) -> int:
"""``round(time_ms / frame_hop_ms)`` (Python rounding: halves go to the even frame)."""
return round(time_ms / frame_hop_ms)
# ------------------------------------------------------------------------ timeline
@dataclass(frozen=True)
class TimelineResult:
"""Either ``timings`` (valid timeline) or ``quarantine`` (machine-readable reason).
``clamped_units`` counts unit starts that rounded to ``num_frames`` or beyond and were
moved to the last frame (a unit that begins in the final half frame).
"""
timings: SegmentTimings | None
quarantine: QuarantineRecord | None
clamped_units: int = 0
def __post_init__(self) -> None:
if (self.timings is None) == (self.quarantine is None):
raise ValueError("TimelineResult needs exactly one of timings / quarantine")
def build_timings(
segment_id: str,
text: str,
tags_json: str,
words: Sequence[TimedWord],
*,
num_frames: int,
frame_hop_ms: float,
) -> TimelineResult:
"""Unit timeline of one segment from its text, tag records and aligned words.
Args:
segment_id: Dataset segment id.
text: Dataset tagged text (the string :func:`nida.model.vocab.encode_text` encodes).
tags_json: The annotate row's tag records; events of the text map in order onto the
event records in time order (span records are ignored).
words: CTC-aligned words of the primary transcript with CTC-gap fillers inserted
(see :func:`spoken_words`), segment-relative ms.
num_frames: Latent frames of the segment.
frame_hop_ms: Latent frame hop in ms.
Returns:
A timeline, or a quarantine record with stage ``timings`` and reason
``timings_bad_text`` (not valid tag grammar), ``timings_untokenizable`` (a
character outside the model vocabulary), ``timings_bad_tags`` (unreadable
``tags_json``), ``timings_text_mismatch`` (the text's words are not the aligned
words), ``timings_event_mismatch`` (the text's events are not the tag records) or
``timings_order`` (a unit would start before the previous one).
"""
def drop(reason: str, **details: object) -> TimelineResult:
return TimelineResult(None, QuarantineRecord(segment_id, STAGE, reason, dict(details)))
try:
units, n_tokens = text_units(text)
except TagSyntaxError as err:
return drop("timings_bad_text", error=str(err))
try:
n_ids = len(encode_text(text))
except ValueError as err:
return drop("timings_untokenizable", error=str(err))
if n_ids != n_tokens:
raise TimingsError(f"{n_ids} ids for {n_tokens} tokens: encode_text disagrees", segment_id)
if not units:
return drop("timings_bad_text", error="text has no tokens")
try:
tag_times = parse_tag_times(tags_json)
except TimingsError as err:
return drop("timings_bad_tags", error=str(err))
text_words = [u.label for u in units if u.kind == "word"]
try:
spoken = spoken_words(words)
except ValueError as err:
return drop("timings_text_mismatch", error=str(err), text_words=text_words)
word_starts = match_words(text_words, spoken)
if word_starts is None:
return drop(
"timings_text_mismatch",
text_words=text_words,
aligned_words=[w.text for w in spoken],
optional_aligned_words=[w.text for w in spoken if w.optional],
)
event_ids = [u.label for u in units if u.kind == "event"]
event_tags = [t for t in tag_times if t.tag in EVENTS]
if event_ids != [t.tag for t in event_tags]:
return drop(
"timings_event_mismatch",
text_events=event_ids,
tag_events=[t.tag for t in event_tags],
)
words_left, events_left = iter(word_starts), iter(t.start_ms for t in event_tags)
starts_ms = [next(words_left if u.kind == "word" else events_left) for u in units]
frames = [ms_to_frame(ms, frame_hop_ms) for ms in starts_ms]
frames[0] = 0
last_frame = num_frames - 1
clamped = sum(1 for f in frames if f > last_frame)
frames = [min(f, last_frame) for f in frames]
for k in range(1, len(frames)):
if frames[k] < frames[k - 1]:
return drop(
"timings_order",
unit_index=k,
unit_starts_ms=starts_ms,
unit_start_frames=frames,
units=[[u.kind, u.label] for u in units],
)
timings = SegmentTimings(
segment_id,
num_frames,
frame_hop_ms,
n_tokens,
tuple(Unit(u.char_start, u.char_end, f) for u, f in zip(units, frames, strict=True)),
)
return TimelineResult(timings, None, clamped)
# ------------------------------------------------------------------------ files
def write_timings(path: Path, timings: Iterable[SegmentTimings]) -> int:
"""Atomically write ``timings.jsonl`` (sorted by ``segment_id``); returns the line count.
Raises:
TimingsError: on a repeated segment id (nothing is written).
"""
by_id: dict[str, SegmentTimings] = {}
for item in timings:
if item.segment_id in by_id:
raise TimingsError("repeated segment id", item.segment_id)
by_id[item.segment_id] = item
lines = "".join(by_id[sid].to_json() + "\n" for sid in sorted(by_id))
atomic_write_text(path, lines)
return len(by_id)
class IndexEntry(NamedTuple):
"""The ``index.jsonl`` fields the timelines are checked against."""
num_frames: int
text: str
def read_index(dataset_dir: Path) -> dict[str, IndexEntry]:
"""``segment_id -> (num_frames, text)`` of ``<dataset_dir>/index.jsonl`` (file order).
Raises:
TimingsError: if the file is missing or a line lacks the fields / repeats an id.
"""
path = dataset_dir / "index.jsonl"
if not path.is_file():
raise TimingsError(f"{path} is missing")
out: dict[str, IndexEntry] = {}
for number, line in enumerate(path.read_text(encoding="utf-8").split("\n"), start=1):
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError as err:
raise TimingsError(f"{path}:{number}: invalid JSON ({err.msg})") from err
if not isinstance(obj, dict):
raise TimingsError(f"{path}:{number}: expected an object")
sid, frames, text = obj.get("segment_id"), obj.get("num_frames"), obj.get("text")
if not (isinstance(sid, str) and sid and _is_int(frames) and isinstance(text, str)):
raise TimingsError(f"{path}:{number}: needs segment_id, num_frames and text")
if sid in out:
raise TimingsError(f"{path}:{number}: repeated segment id", sid)
out[sid] = IndexEntry(frames, text)
return out
def _read_meta_hop(dataset_dir: Path) -> float:
path = dataset_dir / "meta.json"
if not path.is_file():
raise TimingsError(f"{path} is missing (the dataset stage has not finished)")
try:
meta = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as err:
raise TimingsError(f"{path}: invalid JSON ({err.msg})") from err
hop = meta.get("frame_hop_ms") if isinstance(meta, dict) else None
if isinstance(hop, bool) or not isinstance(hop, int | float) or not 0 < hop < math.inf:
raise TimingsError(f"{path}: frame_hop_ms must be a positive number, got {hop!r}")
return float(hop)
def load_timings(dataset_dir: Path, *, check_index: bool = True) -> dict[str, SegmentTimings]:
"""Read and validate ``<dataset_dir>/timings.jsonl``.
Every line must satisfy the :class:`SegmentTimings` invariants, and its
``frame_hop_ms`` must equal the dataset's ``meta.json`` value. With ``check_index``
(default) each segment must also be in ``index.jsonl`` with the same ``num_frames`` and
``n_tokens == len(encode_text(text))``, so a timeline can never be used with another
text or latent than it was built for. Segments quarantined by the stage are simply
absent from the result.
Returns:
``{segment_id: timings}`` in file (``segment_id``) order.
Raises:
TimingsError: on a missing/malformed file, a repeated id, any invariant violation or
a mismatch with ``meta.json`` / ``index.jsonl`` (the message names the segment).
"""
path = dataset_dir / TIMINGS_FILENAME
if not path.is_file():
raise TimingsError(f"{path} is missing (run `data-pilot --stage timings`)")
meta_hop = _read_meta_hop(dataset_dir)
index = read_index(dataset_dir) if check_index else None
out: dict[str, SegmentTimings] = {}
for number, line in enumerate(path.read_text(encoding="utf-8").split("\n"), start=1):
if not line:
continue
where = f"{path}:{number}"
try:
obj = json.loads(line)
except json.JSONDecodeError as err:
raise TimingsError(f"{where}: invalid JSON ({err.msg})") from err
item = SegmentTimings.from_obj(obj, where)
sid = item.segment_id
if sid in out:
raise TimingsError(f"{where}: repeated segment id", sid)
if not math.isclose(item.frame_hop_ms, meta_hop, rel_tol=1e-9):
raise TimingsError(
f"frame_hop_ms {item.frame_hop_ms} differs from meta.json ({meta_hop})", sid
)
if index is not None:
entry = index.get(sid)
if entry is None:
raise TimingsError("not in index.jsonl", sid)
if entry.num_frames != item.num_frames:
raise TimingsError(
f"num_frames {item.num_frames} differs from index.jsonl ({entry.num_frames})",
sid,
)
try:
n_ids = len(encode_text(entry.text))
except ValueError as err:
raise TimingsError(f"index text cannot be encoded ({err})", sid) from err
if n_ids != item.n_tokens:
raise TimingsError(
f"n_tokens {item.n_tokens} differs from the {n_ids} ids of the index text",
sid,
)
out[sid] = item
return out