Cursor Agent commited on
Commit
1bfd408
·
unverified ·
1 Parent(s): e3c2072

Add custom endpoint handler with micro-batching

Browse files
Files changed (2) hide show
  1. README.md +25 -0
  2. handler.py +202 -0
README.md CHANGED
@@ -169,6 +169,31 @@ The 10-second chunking eliminates the long-ayah drift problem entirely — every
169
 
170
  ## Usage
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  ### Basic Transcription
173
 
174
  ```python
 
169
 
170
  ## Usage
171
 
172
+ ### Hugging Face Inference Endpoint (custom handler, recommended)
173
+
174
+ This repo now includes a custom `handler.py` for HF Inference Endpoints that supports:
175
+
176
+ - micro-batching concurrent requests on one GPU worker
177
+ - low-latency queue window (`ASR_BATCH_WINDOW_MS`)
178
+ - bounded batching (`ASR_MAX_BATCH_SIZE`)
179
+ - output shape compatible with clients expecting `{ text, chunks }`
180
+
181
+ #### Endpoint configuration
182
+
183
+ Set your endpoint to use this repository revision and custom handler.
184
+
185
+ Optional environment variables:
186
+
187
+ | Variable | Default | Description |
188
+ |---|---|---|
189
+ | `ASR_BATCH_WINDOW_MS` | `35` | Queue window to coalesce near-simultaneous requests into one forward pass |
190
+ | `ASR_MAX_BATCH_SIZE` | `4` | Max requests per micro-batch |
191
+ | `ASR_REQUEST_TIMEOUT_S` | `45` | Per-request queue wait timeout |
192
+
193
+ The handler accepts raw `audio/wav` bytes or JSON payloads with:
194
+ - `inputs` (base64/string/bytes audio), and optional
195
+ - `parameters` (`language`, `task`, `return_timestamps`, `chunk_length_s`, `temperature`)
196
+
197
  ### Basic Transcription
198
 
199
  ```python
handler.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import binascii
3
+ import os
4
+ import queue
5
+ import threading
6
+ import time
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ import numpy as np
11
+ import torch
12
+ from transformers import pipeline
13
+ from transformers.pipelines.audio_utils import ffmpeg_read
14
+
15
+ SAMPLE_RATE = 16000
16
+
17
+
18
+ @dataclass
19
+ class _QueuedRequest:
20
+ audio: np.ndarray
21
+ params: Dict[str, Any]
22
+ event: threading.Event = field(default_factory=threading.Event)
23
+ result: Optional[Dict[str, Any]] = None
24
+ error: Optional[Exception] = None
25
+
26
+
27
+ class EndpointHandler:
28
+ """
29
+ Custom HF Inference Endpoint handler with micro-batching.
30
+
31
+ Why this exists:
32
+ - default ASR handling is effectively one-request-at-a-time on many setups
33
+ - this handler coalesces near-simultaneous requests into one GPU forward pass
34
+ - response shape is compatible with callers expecting {text, chunks}
35
+ """
36
+
37
+ def __init__(self, path: str = ""):
38
+ model_path = path or "wasimlhr/whisper-quran-v1"
39
+ use_cuda = torch.cuda.is_available()
40
+ torch_dtype = torch.float16 if use_cuda else torch.float32
41
+ device = 0 if use_cuda else -1
42
+
43
+ self._pipe = pipeline(
44
+ task="automatic-speech-recognition",
45
+ model=model_path,
46
+ device=device,
47
+ torch_dtype=torch_dtype,
48
+ )
49
+
50
+ self._batch_window_ms = self._read_int("ASR_BATCH_WINDOW_MS", 35, 1, 200)
51
+ self._max_batch_size = self._read_int("ASR_MAX_BATCH_SIZE", 4, 1, 16)
52
+ self._request_timeout_s = float(os.getenv("ASR_REQUEST_TIMEOUT_S", "45"))
53
+
54
+ self._queue: "queue.Queue[_QueuedRequest]" = queue.Queue()
55
+ self._worker = threading.Thread(target=self._drain_loop, daemon=True)
56
+ self._worker.start()
57
+
58
+ print(
59
+ f"[handler] initialized model={model_path} device={device} "
60
+ f"batch_window_ms={self._batch_window_ms} max_batch_size={self._max_batch_size}"
61
+ )
62
+
63
+ @staticmethod
64
+ def _read_int(name: str, default: int, min_v: int, max_v: int) -> int:
65
+ try:
66
+ value = int(os.getenv(name, str(default)))
67
+ except ValueError:
68
+ value = default
69
+ return max(min_v, min(max_v, value))
70
+
71
+ def __call__(self, data: Any) -> Dict[str, Any]:
72
+ payload, raw_params = self._extract_payload_and_params(data)
73
+ audio = self._decode_audio(payload)
74
+ params = self._normalize_params(raw_params)
75
+
76
+ req = _QueuedRequest(audio=audio, params=params)
77
+ self._queue.put(req)
78
+
79
+ if not req.event.wait(timeout=self._request_timeout_s):
80
+ raise TimeoutError("ASR request timed out while waiting in handler queue")
81
+ if req.error is not None:
82
+ raise RuntimeError(f"ASR request failed: {req.error}")
83
+ return req.result or {"text": "", "chunks": []}
84
+
85
+ def _drain_loop(self) -> None:
86
+ while True:
87
+ first = self._queue.get()
88
+ batch = [first]
89
+
90
+ deadline = time.perf_counter() + (self._batch_window_ms / 1000.0)
91
+ while len(batch) < self._max_batch_size:
92
+ timeout = deadline - time.perf_counter()
93
+ if timeout <= 0:
94
+ break
95
+ try:
96
+ batch.append(self._queue.get(timeout=timeout))
97
+ except queue.Empty:
98
+ break
99
+
100
+ self._process_batch(batch)
101
+
102
+ def _process_batch(self, batch: List[_QueuedRequest]) -> None:
103
+ groups: Dict[Tuple[Any, ...], List[_QueuedRequest]] = {}
104
+ for req in batch:
105
+ groups.setdefault(self._group_key(req.params), []).append(req)
106
+
107
+ for group in groups.values():
108
+ params = group[0].params
109
+ inputs = [{"array": r.audio, "sampling_rate": SAMPLE_RATE} for r in group]
110
+
111
+ try:
112
+ outputs = self._pipe(
113
+ inputs,
114
+ return_timestamps=params["return_timestamps"],
115
+ batch_size=len(group),
116
+ chunk_length_s=params["chunk_length_s"],
117
+ generate_kwargs={
118
+ "language": params["language"],
119
+ "task": params["task"],
120
+ "temperature": params["temperature"],
121
+ },
122
+ )
123
+ if isinstance(outputs, dict):
124
+ outputs = [outputs]
125
+ for req, out in zip(group, outputs):
126
+ req.result = self._format_output(out)
127
+ req.event.set()
128
+ except Exception as exc: # noqa: BLE001
129
+ for req in group:
130
+ req.error = exc
131
+ req.event.set()
132
+
133
+ @staticmethod
134
+ def _group_key(params: Dict[str, Any]) -> Tuple[Any, ...]:
135
+ return (
136
+ params["language"],
137
+ params["task"],
138
+ params["return_timestamps"],
139
+ params["chunk_length_s"],
140
+ params["temperature"],
141
+ )
142
+
143
+ @staticmethod
144
+ def _format_output(output: Dict[str, Any]) -> Dict[str, Any]:
145
+ text = str(output.get("text", "")).strip()
146
+ chunks_out: List[Dict[str, Any]] = []
147
+ for ch in output.get("chunks", []) or []:
148
+ if not isinstance(ch, dict):
149
+ continue
150
+ ctext = str(ch.get("text", "")).strip()
151
+ ts = ch.get("timestamp")
152
+ if isinstance(ts, (list, tuple)) and len(ts) >= 2:
153
+ start, end = ts[0], ts[1]
154
+ else:
155
+ start, end = None, None
156
+ chunks_out.append({"text": ctext, "start": start, "end": end, "timestamp": [start, end]})
157
+ return {"text": text, "chunks": chunks_out}
158
+
159
+ @staticmethod
160
+ def _normalize_params(params: Dict[str, Any]) -> Dict[str, Any]:
161
+ params = params or {}
162
+ return {
163
+ "language": str(params.get("language", "ar")),
164
+ "task": str(params.get("task", "transcribe")),
165
+ "return_timestamps": bool(params.get("return_timestamps", True)),
166
+ "chunk_length_s": float(params.get("chunk_length_s", 20)),
167
+ "temperature": float(params.get("temperature", 0.0)),
168
+ }
169
+
170
+ @staticmethod
171
+ def _extract_payload_and_params(data: Any) -> Tuple[Any, Dict[str, Any]]:
172
+ if isinstance(data, (bytes, bytearray)):
173
+ return bytes(data), {}
174
+ if isinstance(data, dict):
175
+ params = data.get("parameters", {}) or {}
176
+ if "inputs" in data:
177
+ return data["inputs"], params
178
+ if "audio" in data:
179
+ return data["audio"], params
180
+ raise ValueError("Expected 'inputs' or 'audio' in request body")
181
+ raise TypeError(f"Unsupported request type: {type(data)}")
182
+
183
+ @staticmethod
184
+ def _decode_audio(payload: Any) -> np.ndarray:
185
+ if isinstance(payload, dict) and "array" in payload:
186
+ arr = np.asarray(payload["array"], dtype=np.float32)
187
+ return arr
188
+
189
+ if isinstance(payload, str):
190
+ if payload.startswith("data:") and "," in payload:
191
+ payload = payload.split(",", 1)[1]
192
+ try:
193
+ audio_bytes = base64.b64decode(payload, validate=True)
194
+ except (binascii.Error, ValueError) as exc:
195
+ raise ValueError("String payload must be base64-encoded audio bytes") from exc
196
+ elif isinstance(payload, (bytes, bytearray)):
197
+ audio_bytes = bytes(payload)
198
+ else:
199
+ raise TypeError(f"Unsupported audio payload type: {type(payload)}")
200
+
201
+ audio = ffmpeg_read(audio_bytes, SAMPLE_RATE)
202
+ return np.asarray(audio, dtype=np.float32)