quranic-universal-aligner / src /api /services /chapter_timing.py
hetchyy's picture
deploy qua@8f19ff1d
627555e verified
Raw History Blame Contribute Delete
7.26 kB
"""One audio chapter's stored segment times brought up to date, and its shards rebuilt.
The Inspector's timing call (after an align run, after a save, and in a timestamps run):
it sends the chapter's detailed.json entries, the recordings' bucket audio and the times it
stored last. Segments whose stored times are still valid are kept, the rest are timed by the
neural head in a lease, and, unless the caller asks for the times alone, the chapter's
shards are built from the result (:mod:`qua_sdk.integrations.segment_times`, the code the
Katana re-time runs). Audio is fetched only for a recording that has something to time: a
few segments by byte range through the recording's frame index, else the whole file, kept
for the next call, with a frame index built for the caller to store (:mod:`.chapter_audio`).
Times and shards travel as base64 of their Brotli files, written to the bucket as is.
A timestamps run calls twice: times alone for every chapter, each returning its madd lāzim
lengths, then shards with those lengths pooled (``delivery_lazim_ms``), the delivery basis of
the reading-variant picks (:mod:`qua_sdk.integrations.faces`). Built shards come with the
chapter's ``coverage`` counts and the ``untimed`` words, sounds and sakt among them
(:mod:`qua_sdk.integrations.shard_coverage`), the gate the caller publishes them under, and,
for Hafs, the chapter's ``profile_samples`` (:func:`qua_sdk.integrations.recitation_profile.samples`)
for the delivery's profile (:mod:`.recitation_profile`).
The opener specials (Isti'adha, Basmala, a combined row) are timed and built only when the
caller asks (``specials``): each opener then gets its own shard reading (part ``0:1`` / ``0:2``,
named by ``special``), a failed one is a ``failed_segments`` entry carrying ``special``, and one
whose reading cannot be built is left out and listed by uid in ``specials_skipped``. Without
the flag they are neither timed, kept nor built, exactly as before the flag existed.
"""
from __future__ import annotations
import base64
import contextlib
import logging
from src.api.errors import ApiError, ValidationError
from src.api.services import chapter_audio
from src.core.zero_gpu import cpu_mode
log = logging.getLogger(__name__)
class ChapterTimingFailedError(ApiError):
status = 502
code = "chapter_timing_failed"
def _b64(data: bytes) -> str:
return base64.b64encode(data).decode("ascii")
def run(body) -> dict:
"""Time the chapter on the device ``body.device`` names (see ``ChapterTimingRequest``)."""
with cpu_mode() if body.device == "CPU" else contextlib.nullcontext():
return _run(body)
def _run(body) -> dict:
from qua_sdk.integrations import faces as F
from qua_sdk.integrations import recitation_profile as RP
from qua_sdk.integrations import segment_times as ST
from qua_sdk.integrations import shard_coverage
from qua_sdk.integrations.shard_build import shard_bytes
from src.pipeline.timing_runtime import LeaseAligner, params
entries = [entry.model_dump() for entry in body.entries]
missing = [e["ref"] for e in entries if e["ref"] not in body.audio_refs]
if missing:
raise ValidationError(f"no audio_ref for entries {missing}")
specials = body.specials
_check_uids(entries, specials=specials)
try:
doc = ST.decode(base64.b64decode(body.times)) if body.times else ST.empty(body.chapter)
except ValueError as e:
raise ValidationError(f"times: {e}") from e
aligner, p = LeaseAligner(), params("hafs")
model = aligner.model_name(p)
totals = {"timed": 0, "kept": 0, "failed": 0}
frames: dict[str, str] = {}
skipped: list[dict] = []
try:
for entry in entries:
todo = ST.stale(entry["segments"], doc, model, specials=specials)
if body.full or todo or not ST.is_current(doc, model):
whole = body.full or not ST.is_current(doc, model)
spans = None if whole else [_span(seg) for seg in todo]
ref = entry["ref"]
audio = chapter_audio.recording(
body.audio_refs[ref], body.frame_refs.get(ref), spans
)
if audio.frames is not None:
frames[ref] = _b64(audio.frames)
stats = ST.time_recording(
entry, audio.samples, doc, aligner, p, full=body.full, specials=specials
)
else:
stats = {"timed": 0, "kept": len(entry["segments"]), "failed": 0}
for key in totals:
totals[key] += stats[key]
ST.prune(doc, entries, specials=specials)
if body.shards:
if body.delivery_lazim_ms is not None:
doc["_meta"]["lazim_p5_ms"] = F.p5(body.delivery_lazim_ms)
shards, failed = ST.chapter_shards(
entries,
doc,
audio_category=body.audio_category,
riwayah=body.riwayah,
specials=specials,
skipped=skipped,
)
for one in skipped:
log.warning("chapter %s: special %s left out of the shards: %s",
body.chapter, one["segment_uid"], one["error"])
out_shards = {str(ch): _b64(shard_bytes(shard)) for ch, shard in shards.items()}
coverage = shard_coverage.coverage(doc, shards)
samples = (
RP.merge(RP.samples(shard) for shard in shards.values())
if body.riwayah == "hafs"
else None
)
else:
out_shards, failed, coverage, samples = {}, ST.failed_segments(doc), None, None
except ApiError:
raise
except Exception as e:
raise ChapterTimingFailedError(f"{type(e).__name__}: {e}") from e
return {
"model": model,
"times": _b64(ST.encode(doc)),
"shards": out_shards,
"failed_segments": failed,
"lazim_ms": F.lazim_lengths([doc]),
"frames": frames,
"coverage": coverage,
"untimed": shard_coverage.untimed(coverage) if coverage is not None else None,
"profile_samples": samples,
"specials_skipped": [one["segment_uid"] for one in skipped],
**totals,
}
def _check_uids(entries: list[dict], *, specials: bool) -> None:
"""Every segment that gets timed needs its own ``segment_uid``: its times are stored by it,
and one without would drop out of the shards unreported."""
from qua_sdk.integrations.shard_build import timed_ref
seen: set[str] = set()
for entry in entries:
for seg in entry["segments"]:
if not timed_ref(seg, specials=specials):
continue
uid = seg.get("segment_uid")
if not uid or uid in seen:
problem = "a duplicate" if uid else "no"
raise ValidationError(f"segment {seg.get('matched_ref')!r} has {problem} segment_uid")
seen.add(uid)
def _span(seg: dict) -> tuple[int, int]:
"""The 16 kHz samples :func:`qua_sdk.integrations.segment_times.time_recording` cuts."""
sr = chapter_audio.SR
return int(seg["time_start"]) * sr // 1000, int(seg["time_end"]) * sr // 1000