"""One-line summary printed once per align request. Built from request context (device/queue/model/audio length), the SDK's ``Alignment`` + per-stage metrics, and the app-measured segmentation/ASR wall times. ``emit(prefix)`` is the only thing callers need — ``prefix`` is ``"ALIGN UI"`` or ``"ALIGN API"`` depending on the caller. Word timing prints as ``timing=`` after ``match=``: the align-pass ``timing`` stage plus any batch timed inside the request (``metered_timing``/``record_timing``). Nothing else prints a per-request line. Fields sit at fixed widths so the ``|`` separators line up down the log and one column can be scanned without reading the rest. A request that was silently realigned with Large carries its first attempt in ``retry``; every figure the retry moved then prints as ``before→after``, and every counter it re-derived as ``before; after``. """ from __future__ import annotations from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass, field _external_queue_wait_s = ContextVar("external_queue_wait_s", default=0.0) _timing_meter: ContextVar[list | None] = ContextVar("timing_meter", default=None) # Column widths, sized for what these fields actually hold: a two-model label, # a whole-mushaf card count, and times that reach into the hundreds of seconds # on a multi-hour recitation. _MODEL_W = 16 _SEGS_W = 10 _CONF_W = 14 _ASR_W = 19 _MATCH_W = 19 _TOTAL_W = 21 _TIMING_W = 15 @contextmanager def external_queue_wait(wait_s: float): """Include an admission wait that happened before the pipeline timer.""" token = _external_queue_wait_s.set( _external_queue_wait_s.get() + max(0.0, float(wait_s)), ) try: yield finally: _external_queue_wait_s.reset(token) @contextmanager def metered_timing(): """Collect the word-timing seconds recorded inside the block.""" meter: list[float] = [] token = _timing_meter.set(meter) try: yield meter finally: _timing_meter.reset(token) def record_timing(seconds: float) -> None: """Add one timing batch's seconds to the enclosing ``metered_timing``, if any.""" meter = _timing_meter.get() if meter is not None: meter.append(float(seconds)) def _metric(metrics, key: str): """Read one counter off a stage's metrics (StageMetrics or plain dict).""" if metrics is None: return None return metrics.get(key) def _arrow(before, after, render) -> str: """``after`` alone, or ``before→after`` when there is a before.""" return render(after) if before is None else f"{render(before)}→{render(after)}" def _both(before, after, render) -> str: """Two independent readings of one counter, first attempt first.""" return render(after) if before is None else f"{render(before)}; {render(after)}" def _slots(values) -> str: return "|".join(str(v) for v in values) def _stages(values) -> str: return "/".join(str(v) for v in values) @dataclass class StageTimings: """Where a request's wall time went — measured, not inferred. ``queue_s`` is the only residual: lease wall time minus everything below it. Keeping model loads in ``load_s`` matters because they happen inside the GPU lease, so they are billed even though they are not inference. ``prep_s`` and ``finalize_s`` are the audio-sized costs either side of the inference: decoding and filtering the recording on the way in, and slicing and rendering it on the way out. On a multi-hour recitation they dominate the stages people assume are the slow part. """ queue_s: float = 0.0 load_s: float = 0.0 prep_s: float = 0.0 seg_wall_s: float = 0.0 asr_wall_s: float = 0.0 finalize_s: float = 0.0 timing_s: float = 0.0 @dataclass class AlignmentStats: """Everything the summary reads off one ``Alignment`` and its stage metrics. Both the request's final alignment and a first attempt a silent retry replaced are reduced to this, so the two sides of the line are derived by the same rules. """ conf: float | None = None missing_words: tuple[int, int] = (0, 0) failed: tuple[int, int] = (0, 0) repeat_events: int = 0 match_wall_s: float = 0.0 anchor_window_segments: int = 0 anchor_ngram_size: int | None = None anchor_unmargined: int = 0 # the surah a margin-waived last resort settled on reanchor_recovered: int = 0 def anchor_ladder(self) -> str: """How far down the ladder the anchor came from; "" for the base rung.""" steps = [] if self.anchor_window_segments: steps.append(f"w{self.anchor_window_segments}") if self.anchor_ngram_size: steps.append(f"n{self.anchor_ngram_size}") if self.anchor_unmargined: steps.append(f"unmargined:{self.anchor_unmargined}") return ",".join(steps) def alignment_stats(alignment, stages) -> AlignmentStats: """Reduce one alignment to its summary fields. ``None`` gives empty stats.""" match_stage = (stages or {}).get("matching") match_metrics = getattr(match_stage, "metrics", None) ngram_size = _metric(match_metrics, "anchor_ngram_size") stats = AlignmentStats( match_wall_s=getattr(match_stage, "wall_s", None) or 0.0, anchor_window_segments=int(_metric(match_metrics, "anchor_window_segments") or 0), anchor_ngram_size=int(ngram_size) if ngram_size else None, anchor_unmargined=int(_metric(match_metrics, "anchor_unmargined") or 0), reanchor_recovered=int(_metric(match_metrics, "reanchor_recovered") or 0), ) if alignment is None: return stats segments = alignment.segments matched = alignment.matched missing_events = getattr(alignment, "missing_word_events", []) confs = [s.confidence for s in matched] stats.conf = sum(confs) / len(confs) if confs else None stats.missing_words = ( sum(event.position in ("before", "after") for event in missing_events), sum(event.position == "between" for event in missing_events), ) # A row the matcher could not place: no ref, and not one the result # deliberately hides (consumed by a merge, or a filtered special). # Split by cause: the DP tried and failed after its relaxed retry, vs # everything else that leaves an empty row (too few phonemes to attempt, # or a score the emit step zeroed). A runtime that reports no attempt # counters puts the whole count in the second slot. unplaced = sum( 1 for s in segments if not s.matched_ref and s.merged_into is None and not s.filtered ) attempted = int(_metric(match_metrics, "segments_attempted") or 0) passed = int(_metric(match_metrics, "segments_passed") or 0) dp_failed = min(max(attempted - passed, 0), unplaced) stats.failed = (dp_failed, unplaced - dp_failed) stats.repeat_events = sum(1 for s in segments if s.wrap_word_ranges) return stats @dataclass class RequestSummary: device: str queue_s: float model: str audio_min: float load_s: float prep_s: float seg_wall_s: float asr_wall_s: float finalize_s: float total_s: float n_segs: int missing_recovered: tuple[int, int, int] repeats: tuple[int, int] stats: AlignmentStats = field(default_factory=AlignmentStats) retry: object | None = None error: str | None = None timing_s: float = 0.0 fused: tuple[int, int] = (0, 0) # fused special events → cards after the split @classmethod def build( cls, *, device, model, audio_min, timings, total_s, alignment, stages, n_segs, recovery_counts=None, repeat_cards_after=None, fused=(0, 0), retry=None, error=None, ) -> RequestSummary: """Assemble the summary from request context + one SDK Alignment. ``alignment`` may be None (pipeline errored before matching ran) — every derived field falls back to its empty value. ``retry`` is the replaced first attempt's ``RetryRecord`` when a silent Large realignment produced this result. """ stats = alignment_stats(alignment, stages) external_wait_s = _external_queue_wait_s.get() return cls( device=device, queue_s=timings.queue_s + external_wait_s, model=model, audio_min=audio_min, load_s=timings.load_s, prep_s=timings.prep_s, seg_wall_s=timings.seg_wall_s, asr_wall_s=timings.asr_wall_s, finalize_s=timings.finalize_s, timing_s=timings.timing_s, total_s=total_s + external_wait_s, n_segs=n_segs, missing_recovered=( int(getattr(recovery_counts, "rescore", 0)), int(getattr(recovery_counts, "large", 0)), int(getattr(recovery_counts, "merge", 0)), ), repeats=( stats.repeat_events, stats.repeat_events if repeat_cards_after is None else int(repeat_cards_after), ), fused=fused, stats=stats, retry=retry, error=error, ) @property def _before(self) -> AlignmentStats | None: """The replaced attempt's stats, or None when the request ran once.""" return self.retry.stats if self.retry is not None else None @property def conf(self) -> float | None: return self.stats.conf @property def failed(self) -> tuple[int, int]: return self.stats.failed @property def missing_words(self) -> tuple[int, int]: return self.stats.missing_words @property def match_wall_s(self) -> float: return self.stats.match_wall_s def _model_field(self) -> str: if self.retry is None: return f"model={self.model}" return f"model={self.retry.model}→{self.model}" def _conf_field(self) -> str: """Mean matched confidence — of the kept attempt, and of the replaced one.""" before = self._before if self.conf is None and before is None: return "conf=-" # An attempt that never anchored has no confidence of its own; 0.00 is # what it scored. conf_before = None if before is None else (before.conf or 0.0) return "conf=" + _arrow( conf_before, self.conf or 0.0, lambda v: f"{v:.2f}") def _times_field(self) -> str: retry = self.retry asr_before = None if retry is None else retry.asr_s match_before = None if retry is None else retry.stats.match_wall_s total_before = None if retry is None else self.total_s - retry.extra_s asr = "asr=" + _arrow(asr_before, self.asr_wall_s, lambda v: f"{v:6.2f}s") match = "match=" + _arrow(match_before, self.match_wall_s, lambda v: f"{v:5.2f}s") total = "total=" + _arrow(total_before, self.total_s, lambda v: f"{v:6.2f}s") return " ".join(( f"queue={self.queue_s:5.1f}s", f"seg={self.seg_wall_s:5.2f}s", asr.ljust(_ASR_W), match.ljust(_MATCH_W), f"timing={self.timing_s:5.2f}s".ljust(_TIMING_W), total.ljust(_TOTAL_W), )) def _counter_parts(self) -> list[str]: """The tail: only the counters this request actually tripped.""" before = self._before retry = self.retry parts = [] failed_before = None if before is None else before.failed if any(self.failed) or (failed_before and any(failed_before)): parts.append("failed=" + _both(failed_before, self.failed, _slots)) missing_before = None if before is None else before.missing_words if any(self.missing_words) or (missing_before and any(missing_before)): parts.append( "missing_words=" + _both(missing_before, self.missing_words, _slots)) recovered_before = None if retry is None else retry.recovered if any(self.missing_recovered) or (recovered_before and any(recovered_before)): parts.append( "missing_recovered=" + _both(recovered_before, self.missing_recovered, _stages)) repeats_before = None if before is None else before.repeat_events if self.repeats[0] or repeats_before: cards = f"{self.repeats[0]}→{self.repeats[1]}" parts.append( f"repeats={cards}" if repeats_before is None else f"repeats={repeats_before}; {cards}" ) if self.fused[0]: parts.append(f"fused={self.fused[0]}→{self.fused[1]}") ladder = self.stats.anchor_ladder() if ladder: parts.append(f"anchor={ladder}") if self.stats.reanchor_recovered: parts.append(f"reanchor_recovered={self.stats.reanchor_recovered}") if retry is not None: parts.append(f"realigned={retry.reason}") if self.error: parts.append(f"error={self.error}") return parts def format_line(self, prefix: str) -> str: """Render the summary as a single column-aligned line.""" parts = [ self._model_field().ljust(_MODEL_W), f"audio={self.audio_min:6.1f}min", f"{self.n_segs} segs".ljust(_SEGS_W), self._conf_field().ljust(_CONF_W), self.device, self._times_field(), *self._counter_parts(), ] return (f"[{prefix}] " + " | ".join(parts)).rstrip() def emit(self, prefix: str) -> None: print(self.format_line(prefix))