File size: 3,031 Bytes
9a34ecf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: CC-BY-NC-4.0
"""A custom handler for managed inference endpoints that serve a model repository through its own handler.py
(Hugging Face Inference Endpoints). It calls the model's own decoder, model.transcribe(), one request at a time.
The repository's requirements.txt lists what the handler needs beside the endpoint's own image. Checked by calling
it locally the way the endpoint toolkit does; not yet run on the managed service.

Requests: the audio file as the request body with its audio content type (audio/wav, audio/flac, audio/mpeg, ...)
and the options as query parameters (?digits=true&word_timestamps=true), or JSON {"inputs": "<the file in base64>",
"parameters": {...}}. Options: digits, latin, word_timestamps, confidence (true or false, default false). The answer
is {"text": ...}, plus "words" [{"word", "start", "end"}] and "confidence" when asked.
"""

from __future__ import annotations

import base64
import math
import sys
import tempfile

import torch
from transformers import AutoModelForSpeechSeq2Seq

OPTIONS = ("digits", "latin", "word_timestamps", "confidence")


def as_bool(name: str, value) -> bool:
    if isinstance(value, bool):
        return value
    if str(value).strip().lower() in ("true", "1", "yes", "false", "0", "no", ""):
        return str(value).strip().lower() in ("true", "1", "yes")
    raise ValueError(f"{name} must be true or false, not {value!r}")


class EndpointHandler:
    def __init__(self, path: str = ""):
        gpu = torch.cuda.is_available()  # on a GPU the weights' own bfloat16 (do not pass dtype=None: float32)
        cpu = {} if gpu else {"dtype": torch.float32}
        model = AutoModelForSpeechSeq2Seq.from_pretrained(path, trust_remote_code=True, **cpu)
        self.model = model.to("cuda" if gpu else "cpu").eval()
        self.load_audio = sys.modules[type(model).__module__].load_audio  # the loader of the model's own code

    def __call__(self, data: dict) -> dict:
        audio, params = data.get("inputs"), data.get("parameters") or {}
        if isinstance(audio, str):
            audio = base64.b64decode(audio)
        if not isinstance(audio, (bytes, bytearray)) or not audio:
            raise ValueError("send the audio file as the request body, or as base64 in inputs")
        with tempfile.NamedTemporaryFile() as f:
            f.write(audio)
            f.flush()
            try:
                wave = self.load_audio(f.name)
            except Exception as e:
                raise ValueError(f"the body could not be read as audio ({type(e).__name__})") from e
        if wave.size == 0:
            raise ValueError("the audio holds no samples")
        out = self.model.transcribe(wave, **{k: as_bool(k, params.get(k, False)) for k in OPTIONS})
        if not isinstance(out, dict):
            return {"text": out}
        if out.get("confidence") is not None and not math.isfinite(out["confidence"]):
            out["confidence"] = None  # a few samples of audio: no score to give
        return out