File size: 13,569 Bytes
63ba343
 
 
 
 
3d6ae90
134a1be
 
63ba343
 
 
 
 
 
003b05a
 
 
 
 
 
 
63ba343
 
 
 
 
 
58dde1b
003b05a
 
63ba343
 
 
 
 
 
134a1be
58dde1b
63ba343
ef8a4c9
 
 
 
58dde1b
 
ef8a4c9
 
 
 
 
 
 
 
58dde1b
ef8a4c9
63ba343
 
 
 
ef8a4c9
63ba343
 
 
 
 
 
 
 
 
 
 
 
 
ef8a4c9
58dde1b
63ba343
 
 
 
 
 
 
 
 
 
58dde1b
 
 
 
 
 
 
 
 
 
 
 
 
63ba343
 
58dde1b
 
 
 
63ba343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58dde1b
 
 
 
 
 
 
 
63ba343
 
 
 
 
 
 
ef8a4c9
 
 
3d6ae90
58dde1b
 
 
 
 
 
63ba343
 
134a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58dde1b
134a1be
 
 
 
 
 
63ba343
 
 
 
 
134a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63ba343
 
 
 
ef8a4c9
63ba343
 
 
 
ef8a4c9
63ba343
 
 
134a1be
9483678
63ba343
 
 
 
 
 
ef8a4c9
63ba343
ef8a4c9
 
 
 
 
63ba343
 
 
 
 
 
 
 
 
134a1be
 
63ba343
 
 
134a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63ba343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef8a4c9
 
 
 
 
 
63ba343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef8a4c9
 
 
 
 
 
63ba343
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"""Alignment services: the single implementation behind /api/v1 and the legacy

Gradio endpoints.



Every function here validates its inputs, runs the pipeline, persists a

processing session, and returns the response dict from ``response.build``.

Batch review checks are passed through the pipeline for the response only.

``align_audio`` / ``align_url`` are the API's request-log boundary (``src/core/request_log``):

one record per call, whatever surface or retry led there.

Failures leave as typed ``ApiError`` subclasses — never as bare exceptions or

error dicts.

"""

from __future__ import annotations

import json
import os
from contextlib import suppress

from config import ZEROGPU_QUEUE_MAX_ATTEMPTS

from src.api.errors import (
    AlignmentFailedError,
    DownloadFailedError,
    NoSpeechError,
    SessionNotFoundError,
    ValidationError,
)
from src.api.services import faults, response, sessions
from src.api.services.inference import FELL_BACK_TO_CPU as _FELL_BACK_TO_CPU
from src.api.services.inference import run as _run_inference
from src.api.services.validation import (
    validate_device,
    validate_model,
    validate_pad,
    validate_riwayah,
)
from src.core import request_log
from src.core.audio_decode import AudioTooLongError, UnreadableAudioError

SAMPLE_RATE = sessions.SAMPLE_RATE
FELL_BACK_TO_CPU = _FELL_BACK_TO_CPU


def _run(device, pipeline_call, request=None, _cpu_admission=None, _gpu_admission=None,

         cpu_limited=True):
    """Compatibility wrapper over the operation-agnostic inference runner."""
    return _run_inference(
        device,
        pipeline_call,
        request,
        _cpu_admission,
        _gpu_admission,
        max_gpu_attempts=ZEROGPU_QUEUE_MAX_ATTEMPTS,
        cpu_limited=cpu_limited,
    )


def _persist(result, model_name, riwayah, *, audio_id=None, audio_ready=False) -> str:
    """Create a processing session from a finished pipeline result."""
    from src.core.audio_cache import _load_audio
    audio, _ = _load_audio(result.audio_ref)
    return sessions.create(
        audio,
        result.raw_speech_intervals,
        result.raw_is_complete,
        result.intervals,
        model_name,
        riwayah,
        audio_id=audio_id,
        audio_ready=audio_ready,
    )


def _run_with_session(device, model_name, riwayah, pipeline_call, request=None,

                      _cpu_admission=None, _gpu_admission=None, cpu_limited=True):
    """Run inference while the final audio array saves on an I/O thread."""
    audio_id = sessions.reserve()
    audio_save = None

    def start_audio_save(audio):
        nonlocal audio_save
        if audio_save is None:
            audio_save = sessions.save_audio_async(audio_id, audio)

    try:
        try:
            result, device_used, warning = _run(
                device,
                lambda on: pipeline_call(on, start_audio_save),
                request,
                _cpu_admission,
                _gpu_admission,
                cpu_limited=cpu_limited,
            )
        except UnreadableAudioError as error:
            raise faults.unreadable_audio_error(error) from error
        except AudioTooLongError as error:
            raise faults.audio_too_long_error(error) from error
        if result.segments is None:
            raise NoSpeechError()
        if not _any_match(result.segments):
            from src.pipeline.errors import UNALIGNABLE_MESSAGE

            raise AlignmentFailedError(UNALIGNABLE_MESSAGE)

        # Test doubles and older internal callers may not invoke the callback.
        # Keep their established synchronous path; the real pipeline always
        # starts the save immediately after preprocessing.
        if audio_save is None:
            completed_id = _persist(result, model_name, riwayah)
            sessions.discard(audio_id)
            return result, device_used, warning, completed_id

        audio_save.result()
        _persist(
            result, model_name, riwayah,
            audio_id=audio_id, audio_ready=True,
        )
        return result, device_used, warning, audio_id
    except BaseException:
        if audio_save is not None:
            with suppress(Exception):
                audio_save.result()
        sessions.discard(audio_id)
        raise


def _any_match(payload) -> bool:
    """True when at least one card matched Quran text or a special segment."""
    rows = payload.get("segments") if isinstance(payload, dict) else None
    if rows is None:
        return True
    return any(row.get("ref_from") or row.get("special_type") for row in rows)


def _require_session(audio_id):
    session = sessions.load(audio_id)
    if session is None:
        raise SessionNotFoundError()
    return session


def align_audio(audio_data, pad_left_ms, pad_right_ms, model_name="Base",

                device="GPU", riwayah="hafs", request=None,

                rate_limit_checked=False, _cpu_admission=None,

                _gpu_admission=None, min_silence_floor_ms=None,

                include_review_checks=False, cpu_limited=True) -> dict:
    """Full pipeline on an uploaded file: segmentation -> ASR -> matching.



    ``cpu_limited=False`` (batch items, already run one at a time per owner) skips the

    per-caller CPU limit.

    """
    from src.pipeline import process_audio

    with request_log.capture(
        "api", "api_align", request,
        settings=_log_settings(pad_left_ms, pad_right_ms, model_name, device, riwayah,
                               min_silence_floor_ms=min_silence_floor_ms),
    ) as run:
        model_name = validate_model(model_name)
        device = validate_device(device)
        riwayah = validate_riwayah(riwayah)
        pad_left_ms = validate_pad(pad_left_ms, "pad_left_ms")
        pad_right_ms = validate_pad(pad_right_ms, "pad_right_ms")
        if run is not None:
            run.fields["riwayah"] = riwayah
        _log_audio(run, audio_data)
        result, device_used, warning, audio_id = _run_with_session(
            device, model_name, riwayah,
            lambda on, ready: process_audio(
                audio_data, pad_left_ms, pad_right_ms, model_name, on,
                riwayah=riwayah, request=request, return_html=False,
                rate_limit_checked=True,
                on_audio_ready=ready,
                min_silence_floor_ms=min_silence_floor_ms,
                include_review_checks=include_review_checks,
            ),
            request,
            _cpu_admission,
            _gpu_admission,
            cpu_limited=cpu_limited,
        )
        body = response.build(audio_id, result.segments,
                              warning=warning, device=device_used)
        if run is not None:
            run.finish(body)
        return body


def align_url(url, pad_left_ms, pad_right_ms, model_name="Base",

              device="GPU", riwayah="hafs", request=None) -> dict:
    """Full pipeline on a downloaded URL. Adds ``url_metadata`` to the response."""
    with request_log.capture(
        "api", "api_align_url", request,
        settings=_log_settings(pad_left_ms, pad_right_ms, model_name, device, riwayah),
        source_url=url if isinstance(url, str) else None,
    ) as run:
        model_name = validate_model(model_name)
        device = validate_device(device)
        riwayah = validate_riwayah(riwayah)
        pad_left_ms = validate_pad(pad_left_ms, "pad_left_ms")
        pad_right_ms = validate_pad(pad_right_ms, "pad_right_ms")
        if run is not None:
            run.fields["riwayah"] = riwayah
        return _align_url(url, pad_left_ms, pad_right_ms, model_name, device, riwayah,
                          request, run)


def _align_url(url, pad_left_ms, pad_right_ms, model_name, device, riwayah, request, run):
    if not url or not isinstance(url, str) or not url.strip():
        raise ValidationError("URL is required")
    url = url.strip()

    try:
        from src.ui.handlers import _download_url_core

        wav_path, url_meta = _download_url_core(url)
    except Exception as e:
        raise DownloadFailedError(f"Download failed: {e}") from e

    from src.pipeline import process_audio

    if run is not None:
        run.attach_audio(wav_path, origin=request_log.download_origin(url))
    try:
        result, device_used, warning, audio_id = _run_with_session(
            device, model_name, riwayah,
            lambda on, ready: process_audio(
                wav_path, pad_left_ms, pad_right_ms, model_name, on,
                riwayah=riwayah, request=request, return_html=False,
                rate_limit_checked=True,
                on_audio_ready=ready,
            ),
            request,
        )
    finally:
        with suppress(OSError):
            os.remove(wav_path)

    body = response.build(audio_id, result.segments,
                          warning=warning, device=device_used)
    body["url_metadata"] = {
        "title": url_meta.get("title"),
        "duration": url_meta.get("duration"),
        "source_url": url_meta.get("source_url"),
    }
    if run is not None:
        run.finish(body)
    return body


def _log_settings(pad_left_ms, pad_right_ms, model_name, device, riwayah, **extra) -> dict:
    """What the caller asked for, as the request log keeps it."""
    from src.core.space_profile import matcher_choice

    return {
        "pad_left_ms": pad_left_ms, "pad_right_ms": pad_right_ms,
        "requested_model": model_name, "requested_device": device,
        "riwayah": riwayah, "matcher": matcher_choice(),
        **{k: v for k, v in extra.items() if v is not None},
    }


def _log_audio(run, audio_data) -> None:
    """Keep an API request's audio: the spooled upload as is, decoded samples as FLAC."""
    if run is None:
        return
    if isinstance(audio_data, str):
        referenced = run.fields.get("audio_origin") == "referenced"
        run.attach_audio(audio_data, origin="referenced" if referenced else "original")
    elif isinstance(audio_data, tuple) and len(audio_data) == 2:
        sample_rate, samples = audio_data
        run.attach_audio(samples=samples, sample_rate=sample_rate, origin="encoded")


def retranscribe(audio_id, model_name="Base", device="GPU", riwayah="hafs",

                 request=None) -> dict:
    """Re-run ASR on a session's existing boundaries with a different model.



    Not exposed on any HTTP surface — the UI's Retranscribe button is the only

    caller. Kept here so it shares the pipeline plumbing with the rest.

    """
    model_name = validate_model(model_name)
    device = validate_device(device)
    riwayah = validate_riwayah(riwayah)
    session = _require_session(audio_id)

    if (model_name == session["model_name"]
            and sessions.intervals_hash(session["intervals"]) == session["intervals_hash"]):
        raise ValidationError(
            "Model and boundaries unchanged. Change model_name to retranscribe, "
            "or run a fresh alignment to change boundaries."
        )

    from src.pipeline import retranscribe_audio

    result, device_used, warning = _run(device, lambda on: retranscribe_audio(
        session["intervals"], session["audio"], SAMPLE_RATE,
        session["speech_intervals"], session["is_complete"],
        model_name, on, riwayah=riwayah, request=request, return_html=False,
        rate_limit_checked=True,
    ), request)
    if result.segments is None:
        raise AlignmentFailedError("Retranscription failed")

    sessions.update(audio_id, model_name=model_name, riwayah=riwayah)
    return response.build(audio_id, result.segments,
                          warning=warning, device=device_used)


def realign_from_timestamps(audio_id, timestamps, model_name="Base", device="GPU",

                            riwayah="hafs", request=None) -> dict:
    """Run ASR + matching on caller-supplied segment boundaries."""
    model_name = validate_model(model_name)
    device = validate_device(device)
    riwayah = validate_riwayah(riwayah)
    session = _require_session(audio_id)

    if isinstance(timestamps, str):
        try:
            timestamps = json.loads(timestamps)
        except ValueError as e:
            raise ValidationError(f"timestamps is not valid JSON: {e}") from e
    if not timestamps:
        raise ValidationError("timestamps is required")
    try:
        intervals = [(float(ts["start"]), float(ts["end"])) for ts in timestamps]
    except (KeyError, TypeError, ValueError) as e:
        raise ValidationError(
            "Each timestamp needs numeric 'start' and 'end' fields"
        ) from e

    from src.pipeline import realign_audio

    result, device_used, warning = _run(device, lambda on: realign_audio(
        intervals, session["audio"], SAMPLE_RATE,
        session["speech_intervals"], session["is_complete"],
        model_name, on, riwayah=riwayah, request=request, return_html=False,
        rate_limit_checked=True,
    ), request)
    if result.segments is None:
        raise AlignmentFailedError("Alignment failed")

    sessions.update(audio_id, intervals=result.intervals, model_name=model_name)
    return response.build(audio_id, result.segments,
                          warning=warning, device=device_used)