File size: 2,402 Bytes
b926cc4
 
 
 
 
 
64de8e2
003b05a
58dde1b
b926cc4
627555e
58dde1b
b926cc4
627555e
b926cc4
 
 
 
0fa1343
 
 
 
 
627555e
0fa1343
 
627555e
 
 
b926cc4
 
58dde1b
 
 
 
 
 
b926cc4
 
 
 
 
 
 
 
 
 
0fa1343
 
627555e
b926cc4
 
 
 
627555e
b926cc4
 
 
 
 
 
 
 
64de8e2
b926cc4
 
 
 
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
"""Audio-only QUA boundary segmentation service."""

from __future__ import annotations

import time

from config import ANALYSIS_HIGHPASS_HZ, OUTPUT_LICENSE, PAD_LEFT_DEFAULT, PAD_RIGHT_DEFAULT

from src.api.services import faults
from src.api.services.inference import run as run_inference
from src.api.services.validation import validate_model
from src.core.audio_decode import AudioTooLongError, UnreadableAudioError, get_decoded_16k
from src.core.audio_filters import highpass
from src.core.space_profile import segmenter_head
from src.core.zero_gpu import force_cpu_mode, reset_quota_flag
from src.pipeline.gpu_runtime import run_segmentation_only_gpu


def segment_audio(
    audio_path: str,
    *,
    pad_left_ms: int = PAD_LEFT_DEFAULT,
    pad_right_ms: int = PAD_RIGHT_DEFAULT,
    model_name: str = "Base",
    request=None,
) -> dict:
    """Decode one recording and return the ``model_name`` head's speech intervals only;
    ``engine`` names that head."""
    model_name = validate_model(model_name)
    reset_quota_flag()
    prep_started = time.perf_counter()
    try:
        audio, sample_rate = get_decoded_16k(audio_path)
    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 ANALYSIS_HIGHPASS_HZ > 0:
        audio = highpass(audio, sample_rate, ANALYSIS_HIGHPASS_HZ)
    prep_s = time.perf_counter() - prep_started

    def run(device: str):
        if device == "CPU":
            force_cpu_mode()
        return run_segmentation_only_gpu(
            audio,
            sample_rate,
            pad_left_ms,
            pad_right_ms,
            model_name=model_name,
        )

    (regions, load_s, inference_s), device, warning = run_inference("GPU", run, request)
    body = {
        "engine": segmenter_head(model_name),
        "segments": [
            {"start_s": region.start_s, "end_s": region.end_s}
            for region in regions.regions
        ],
        # Decode/filter + worker model load + inference. Admission and ZeroGPU
        # scheduling happen outside these clocks and are intentionally omitted.
        "processing_seconds": prep_s + load_s + inference_s,
        "device": device,
        "license": OUTPUT_LICENSE,
    }
    if warning:
        body["warning"] = warning
    return body