File size: 11,294 Bytes
8e313a5 d1d837e 8e313a5 | 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 | #!/usr/bin/env python3
"""Optional persistent HTTP server with a single model and cross-request batching.
POST /transcribe: {"inputs": [{"id": "clip", "audio_base64": "<WAV/FLAC bytes>"}]}
GET /health: readiness. No arbitrary server-side file paths are accepted.
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import queue
import signal
import threading
import time
from concurrent.futures import Future, TimeoutError
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import numpy as np
import soundfile as sf
from batch_inference import AudioInput, add_engine_arguments, engine_from_args
class ServerStopping(RuntimeError):
pass
@dataclass
class Job:
inputs: list[AudioInput]
future: Future
submitted: float
class BatchService:
def __init__(self, engine, *, wait_ms=20, queue_size=32, max_group_requests=8):
if wait_ms < 0 or queue_size < 1 or max_group_requests < 1:
raise ValueError("Invalid queue configuration")
self.engine = engine
self.wait = wait_ms / 1000
self.max_group_requests = max_group_requests
self.jobs = queue.Queue(maxsize=queue_size)
self.stopping = threading.Event()
self.worker = threading.Thread(target=self._work, daemon=True)
self.worker.start()
def submit(self, inputs):
if self.stopping.is_set():
raise ServerStopping("Server is stopping")
future = Future()
self.jobs.put_nowait(Job(inputs, future, time.perf_counter()))
return future
def _work(self):
while not self.stopping.is_set():
try:
first = self.jobs.get(timeout=0.1)
except queue.Empty:
continue
jobs = [first]
deadline = time.perf_counter() + self.wait
while len(jobs) < self.max_group_requests:
remaining = deadline - time.perf_counter()
if remaining <= 0:
break
try:
jobs.append(self.jobs.get(timeout=remaining))
except queue.Empty:
break
active = [job for job in jobs if job.future.set_running_or_notify_cancel()]
if not active:
continue
started = time.perf_counter()
inputs = []
for job_index, job in enumerate(active):
inputs.extend(
AudioInput(f"{job_index}:{index}", item.audio, item.sample_rate)
for index, item in enumerate(job.inputs)
)
try:
output = self.engine.transcribe(inputs)
offset = 0
for job in active:
results = output["results"][offset : offset + len(job.inputs)]
for result, original in zip(results, job.inputs, strict=True):
result["id"] = original.id
offset += len(job.inputs)
job.future.set_result(
{
"results": results,
"stats": output["stats"],
"request_seconds": time.perf_counter() - job.submitted,
"queue_seconds": started - job.submitted,
"group_requests": len(active),
}
)
except Exception as error:
for job in active:
job.future.set_exception(error)
while True:
try:
job = self.jobs.get_nowait()
except queue.Empty:
break
if not job.future.done():
job.future.set_exception(ServerStopping("Server stopped"))
def close(self):
self.stopping.set()
self.worker.join(timeout=30)
def make_handler(
service,
*,
max_body_bytes=64 * 1024 * 1024,
max_inputs=16,
max_audio_seconds=3600,
max_decoded_bytes=256 * 1024 * 1024,
request_timeout=300,
):
class Handler(BaseHTTPRequestHandler):
def setup(self):
super().setup()
self.connection.settimeout(30)
def respond(self, status, value):
body = json.dumps(value, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path != "/health":
self.respond(404, {"error": "Unknown endpoint"})
return
self.respond(
200,
{
"ready": not service.stopping.is_set()
and service.worker.is_alive(),
"device": str(service.engine.device),
"dtype": str(getattr(service.engine, "dtype", "unknown")),
"decoder_backend": (
getattr(service.engine, "decoder_backend", "unknown")
if getattr(service.engine, "decoder", None) is not None
else "greedy"
),
"batch_size": getattr(service.engine, "batch_size", None),
"queued_requests": service.jobs.qsize(),
},
)
def do_POST(self):
if self.path != "/transcribe":
self.respond(404, {"error": "Unknown endpoint"})
return
try:
length = int(self.headers.get("Content-Length", "0"))
if not 0 < length <= max_body_bytes:
self.respond(413, {"error": "Invalid or excessive request size"})
return
payload = json.loads(self.rfile.read(length))
entries = payload["inputs"]
if not isinstance(entries, list) or not 1 <= len(entries) <= max_inputs:
raise ValueError(f"Provide 1–{max_inputs} inputs")
inputs = []
duration = 0
decoded_bytes = 0
for entry in entries:
raw = base64.b64decode(entry["audio_base64"], validate=True)
with sf.SoundFile(io.BytesIO(raw)) as file:
seconds = len(file) / file.samplerate
duration += seconds
if duration > max_audio_seconds or seconds < 0.013:
raise ValueError(
"Audio duration is outside the request limits"
)
if (
not 8000 <= file.samplerate <= 192000
or not 1 <= file.channels <= 8
):
raise ValueError("Unsupported sample rate or channel count")
decoded_bytes += len(file) * file.channels * 4
if decoded_bytes > max_decoded_bytes:
self.respond(
413,
{
"error": "Decoded audio exceeds the request memory limit"
},
)
return
audio = file.read(dtype="float32")
if not np.isfinite(audio).all():
raise ValueError("Audio contains non-finite samples")
inputs.append(
AudioInput(str(entry["id"]), audio, file.samplerate)
)
if len({item.id for item in inputs}) != len(inputs):
raise ValueError("Input IDs must be unique within the request")
future = service.submit(inputs)
except ServerStopping:
self.respond(503, {"error": "Server is stopping; retry later"})
return
except queue.Full:
self.respond(503, {"error": "Inference queue is full; retry later"})
return
except (ValueError, KeyError, TypeError, sf.LibsndfileError) as error:
self.respond(400, {"error": str(error)})
return
try:
self.respond(200, future.result(timeout=request_timeout))
except TimeoutError:
future.cancel()
self.respond(504, {"error": "Request timed out"})
except ServerStopping:
self.respond(503, {"error": "Server is stopping; retry later"})
except ValueError as error:
self.respond(400, {"error": str(error)})
except Exception:
self.respond(500, {"error": "Inference failed"})
return Handler
def main():
parser = argparse.ArgumentParser(description=__doc__)
add_engine_arguments(parser)
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--batch-wait-ms", type=float, default=20)
parser.add_argument("--queue-size", type=int, default=32)
parser.add_argument("--max-group-requests", type=int, default=8)
parser.add_argument("--max-inputs", type=int, default=16)
parser.add_argument("--max-body-mib", type=int, default=64)
parser.add_argument("--max-audio-seconds", type=float, default=3600)
parser.add_argument("--max-decoded-mib", type=int, default=256)
parser.add_argument("--request-timeout", type=float, default=300)
args = parser.parse_args()
if (
min(
args.max_inputs,
args.max_body_mib,
args.max_audio_seconds,
args.max_decoded_mib,
args.request_timeout,
)
<= 0
):
parser.error("Request limits must be positive")
engine = engine_from_args(args)
service = BatchService(
engine,
wait_ms=args.batch_wait_ms,
queue_size=args.queue_size,
max_group_requests=args.max_group_requests,
)
server = ThreadingHTTPServer(
(args.host, args.port),
make_handler(
service,
max_inputs=args.max_inputs,
max_body_bytes=args.max_body_mib * 1024 * 1024,
max_audio_seconds=args.max_audio_seconds,
max_decoded_bytes=args.max_decoded_mib * 1024 * 1024,
request_timeout=args.request_timeout,
),
)
print(
f"Griot ready on http://{args.host}:{args.port}; device={engine.device}",
flush=True,
)
def stop(signum, frame):
if not service.stopping.is_set():
service.stopping.set()
threading.Thread(target=server.shutdown, daemon=True).start()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
service.close()
if __name__ == "__main__":
main()
|