Automatic Speech Recognition
PyTorch
Safetensors
conformer
ctc
streaming
ghana
bfloat16
griot-edge / batch_server.py
DeeNA95's picture
Add Flashlight decoding and optimized container presets with matched benchmarks
d1d837e verified
Raw History Blame Contribute Delete
11.3 kB
#!/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()