Spaces:
Running on Zero
Running on Zero
Download src/api/services/align.py from QUD-Technologies/quranic-universal-aligner: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/QUD-Technologies/quranic-universal-aligner/resolve/main/src/api/services/align.py
- Command line
-
hf download hf://spaces/QUD-Technologies/quranic-universal-aligner/src/api/services/align.py
-
curl -L -o align.py https://huggingface.co/spaces/QUD-Technologies/quranic-universal-aligner/resolve/main/src/api/services/align.py
13.6 kB
| """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) | |