"""Word-timing services: word timestamps over aligned segments.""" from __future__ import annotations import json from config import OUTPUT_LICENSE, TIMING_MIN_SEGMENT_S from qua_sdk.components.matching.lib.reference.specials import ( SPECIAL_TEXT, TRANSITION_TEXT, ) from src.api.errors import SessionNotFoundError, TimingFailedError, ValidationError from src.api.services import audio_io, sessions from src.api.services.validation import validate_granularity, validate_riwayah _SPECIAL_TEXT = {**SPECIAL_TEXT, **TRANSITION_TEXT} DEFAULT_CONFIDENCE = 1.0 def _parse_segments(segments_json): if isinstance(segments_json, str): try: return json.loads(segments_json) except ValueError as e: raise ValidationError(f"segments is not valid JSON: {e}") from e return segments_json def normalize_segments(segments): """Fill defaults so callers can pass minimal segment dicts (times + refs). Auto-assigns ``segment`` numbers, defaults ``confidence``, and derives ``matched_text`` from ``special_type`` for special segments. """ normalized = [] for i, seg in enumerate(segments): entry = dict(seg) entry.setdefault("segment", i + 1) entry.setdefault("confidence", DEFAULT_CONFIDENCE) if "matched_text" not in entry: entry["matched_text"] = _SPECIAL_TEXT.get(entry.get("special_type", ""), "") normalized.append(entry) return normalized def _compute(segments, seg_dir, granularity, riwayah, *, minimal=True) -> dict: from src.ui.mfa_compute import compute_mfa_timestamps_api try: if minimal: result = compute_mfa_timestamps_api( segments, seg_dir, granularity, riwayah=riwayah, ) else: result = compute_mfa_timestamps_api( segments, seg_dir, granularity, riwayah=riwayah, minimal=False, ) except Exception as e: raise TimingFailedError(f"Word timing failed: {e}") from e result["license"] = OUTPUT_LICENSE return result def _log_bad_spans(segments, audio_s: float, source: str) -> None: """One line per segment whose span, clamped to the audio, is too short to time; the segment still goes through and comes back with its own timing error.""" for seg in segments: start, end = float(seg.get("time_from", 0)), float(seg.get("time_to", 0)) if min(end, audio_s) - max(start, 0.0) >= TIMING_MIN_SEGMENT_S: continue print(f"[TIMESTAMPS] {source}: segment {seg.get('segment')} {seg.get('ref_from')}-" f"{seg.get('ref_to')} spans {start:.3f}-{end:.3f}s of {audio_s:.3f}s audio", flush=True) def timestamps_for_session( audio_id, segments_json=None, granularity="words", *, minimal=True, ) -> dict: """Compute word timings using a session's stored audio.""" granularity = validate_granularity(granularity) session = sessions.load(audio_id) if session is None: raise SessionNotFoundError() provided = _parse_segments(segments_json) if provided: segments = normalize_segments(provided) else: segments = sessions.load_segments(audio_id) if not segments: raise ValidationError("No segments found in session") _log_bad_spans(segments, len(session["audio"]) / audio_io.SAMPLE_RATE, "session") try: seg_dir = audio_io.write_segment_wavs( session["audio"], audio_io.SAMPLE_RATE, segments, ) except Exception as e: raise TimingFailedError(f"Failed to create segment audio: {e}") from e result = _compute( segments, seg_dir, granularity, session.get("riwayah", "hafs"), minimal=minimal, ) result["audio_id"] = audio_id return result def timestamps_direct(audio_data, segments_json, granularity="words", riwayah="hafs") -> dict: """Compute word timings from caller-supplied audio and segments.""" granularity = validate_granularity(granularity) riwayah = validate_riwayah(riwayah) provided = _parse_segments(segments_json) if not provided: raise ValidationError("No segments provided") segments = normalize_segments(provided) try: audio, sample_rate = audio_io.preprocess(audio_data) except Exception as e: raise ValidationError(f"Failed to preprocess audio: {e}") from e _log_bad_spans(segments, len(audio) / sample_rate, "direct") try: seg_dir = audio_io.write_segment_wavs(audio, sample_rate, segments) except Exception as e: raise TimingFailedError(f"Failed to create segment audio: {e}") from e return _compute(segments, seg_dir, granularity, riwayah)