"""Bucket chapter audio for the timing call: the frames a few segments need, else the whole file decoded once and kept. A save re-times a few segments. With the chapter's frame index (:mod:`qua_timing_batch.audio.windows`, stored by the Inspector at the request's frame ref) and at most :data:`MAX_WINDOWS` spans to time, :func:`recording` returns a :class:`Windowed` view that reads each span's frames from the bucket by byte range, in parallel: the same samples a whole-file decode gives. Otherwise the file is fetched and decoded whole, as the batch re-time decodes it (:func:`qua_timing_batch.audio.decode.decode`), and kept in memory by ref and content hash, least recently used first out once the cache passes ``TIMING_AUDIO_CACHE_MB``. A whole fetch whose stored index is missing or stale builds one, which the caller hands back for the Inspector to store. """ from __future__ import annotations import contextlib import dataclasses import logging import os import threading from collections import OrderedDict from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np from config import TIMING_AUDIO_CACHE_MB from src.api.v1.bucket_fetch import ( AudioFetchError, fetch_audio_ref, validate_audio_ref, validate_frames_ref, ) log = logging.getLogger(__name__) SR = 16_000 #: Spans read by byte range at most; more are cheaper to decode as one file. MAX_WINDOWS = 16 _PARALLEL = 8 _lock = threading.Lock() _cache: OrderedDict[tuple[str, str], np.ndarray] = OrderedDict() _indexes: dict[tuple[str, str], object] = {} @dataclasses.dataclass class Recording: samples: np.ndarray | Windowed frames: bytes | None # a freshly built frame index for the caller to store class Windowed: """Slices of a recording read through its frame index, ``spans`` read ahead.""" def __init__(self, audio_ref: str, index, spans: list[tuple[int, int]]): self._ref, self._index, self._read = audio_ref, index, {} with ThreadPoolExecutor(min(_PARALLEL, len(spans) or 1)) as pool: for span, samples in zip(spans, pool.map(lambda s: self._get(*s), spans), strict=True): self._read[span] = samples def __getitem__(self, key: slice) -> np.ndarray: span = (key.start, key.stop) return self._read[span] if span in self._read else self._get(*span) def _get(self, start: int, end: int) -> np.ndarray: fs = _fs() return self._index.read(lambda lo, hi: fs.cat_file(self._ref, start=lo, end=hi), start, end) def recording( audio_ref: str, frames_ref: str | None, spans: list[tuple[int, int]] | None ) -> Recording: """``audio_ref``'s samples for ``spans`` (``None``: all of them) at 16 kHz.""" ref = validate_audio_ref(audio_ref) frames_ref = validate_frames_ref(frames_ref) if frames_ref else None content = _content_hash(ref) index = _stored_index(frames_ref, content) if frames_ref else None if index is not None and spans is not None and len(spans) <= MAX_WINDOWS: try: return Recording(Windowed(ref, index, spans), None) except Exception: log.exception("[chapter audio] %s: windowed read failed, decoding it whole", ref) whole, data = _whole(ref, content) built = None if frames_ref and index is None and data is not None: built = _build(data, whole, content) return Recording(whole, built) def clear() -> None: with _lock: _cache.clear() _indexes.clear() def _whole(ref: str, content: str) -> tuple[np.ndarray, bytes | None]: """The decoded file, and its bytes when this call fetched it.""" from qua_timing_batch.audio.decode import decode key = (ref, content) with _lock: hit = _cache.get(key) if hit is not None: _cache.move_to_end(key) return hit, None path = fetch_audio_ref(ref) try: data = Path(path).read_bytes() audio = decode(Path(path), SR) finally: with contextlib.suppress(OSError): os.remove(path) audio.flags.writeable = False with _lock: _cache[key] = audio while ( len(_cache) > 1 and sum(a.nbytes for a in _cache.values()) > TIMING_AUDIO_CACHE_MB << 20 ): _cache.popitem(last=False) return audio, data def _build(data: bytes, whole: np.ndarray, content: str) -> bytes | None: from qua_timing_batch.audio.windows import build try: index = build(data, whole, SR) except Exception: log.exception("[chapter audio] frame index build failed") return None return None if index is None else dataclasses.replace(index, hash=content).encode() def _stored_index(frames_ref: str, content: str): """The frame index at ``frames_ref`` when it was built from this content, else ``None``.""" from qua_timing_batch.audio.windows import FrameWindows key = (frames_ref, content) with _lock: if key in _indexes: return _indexes[key] try: index = FrameWindows.decode(_fs().cat_file(frames_ref)) except FileNotFoundError: return None except Exception: log.exception("[chapter audio] unreadable frame index %s", frames_ref) return None if index.hash != content or index.sr != SR: return None with _lock: _indexes[key] = index return index def _content_hash(ref: str) -> str: fs = _fs() try: fs.invalidate_cache(ref) info = fs.info(ref) except Exception as exc: raise AudioFetchError(f"{ref}: {exc}") from exc return str(info.get("xet_hash") or info.get("etag") or (info.get("size"), info.get("mtime"))) def _fs(): from src.api.v1.bucket_fetch import _fs return _fs()