# SPDX-License-Identifier: Apache-2.0 # Copied from the Qwen3-ASR bundle of this workspace (tt_paddleocr.server.worker.py, Apache-2.0; itself from Qwen3-TTS). """The device worker of the HTTP server: ONE thread owns the model (every device call, from start-up to shutdown, runs on it), and requests wait in a bounded FIFO (batch 1). * :meth:`DeviceWorker.submit` queues a job; more than ``depth`` waiting jobs -> :class:`QueueFull` (HTTP 429). * A job that waited longer than ``timeout_s`` when the worker reaches it is dropped with :class:`QueueTimeout` (HTTP 503); the HTTP handler also stops waiting for it after ``timeout_s`` and cancels it. * A job reports through ``on_event(kind, payload)`` (called ON THE WORKER THREAD; the server forwards to the event loop): ``("started", wait_s)``, any number of job-specific events (text deltas), then ``("done", result)`` or ``("error", exception)``. ``job.cancel`` is a ``threading.Event`` the job polls (client went away). * :meth:`call` runs a function on the worker and waits for it (start-up, shutdown). Standard library only. """ from __future__ import annotations import concurrent.futures import logging import queue import threading import time from typing import Any, Callable, Optional __all__ = ["DeviceWorker", "Job", "QueueFull", "QueueTimeout", "ShuttingDown"] LOG = logging.getLogger("tt_paddleocr.server.worker") class QueueFull(RuntimeError): pass class QueueTimeout(RuntimeError): pass class ShuttingDown(RuntimeError): pass class Job: def __init__(self, fn: Callable[["Job"], Any], on_event: Optional[Callable[[str, Any], None]], kind: str): self.fn = fn self.on_event = on_event self.kind = kind self.cancel = threading.Event() self.future: "concurrent.futures.Future[Any]" = concurrent.futures.Future() self.enqueued = time.monotonic() self.started: Optional[float] = None self.state = "queued" def emit(self, kind: str, payload: Any = None) -> None: if self.on_event is not None: try: self.on_event(kind, payload) except Exception: # noqa: BLE001 -- the receiver went away (event loop closed) LOG.debug("event %s dropped", kind) def _finish(self, kind: str, payload: Any) -> None: self.state = kind self.emit(kind, payload) if kind == "done": if not self.future.done(): self.future.set_result(payload) elif not self.future.done(): self.future.set_exception(payload) class DeviceWorker: def __init__(self, depth: int, timeout_s: float, name: str = "paddleocr-device"): self.depth = int(depth) self.timeout_s = float(timeout_s) self._q: "queue.Queue[Optional[Job]]" = queue.Queue() self._lock = threading.Lock() self.waiting = 0 self.running: Optional[Job] = None self.completed = 0 self._closing = False self._thread = threading.Thread(target=self._loop, name=name, daemon=True) self._thread.start() # ------------------------------------------------------------------------------------------ submit def submit(self, fn: Callable[[Job], Any], *, on_event: Optional[Callable[[str, Any], None]] = None, kind: str = "recognition", priority: bool = False) -> Job: """Queue ``fn(job)``. ``priority`` jobs (start-up, shutdown) ignore the depth limit.""" job = Job(fn, on_event, kind) with self._lock: if self._closing and not priority: raise ShuttingDown("the server is shutting down") if not priority and self.waiting >= self.depth and (self.running is not None or self.waiting > 0): raise QueueFull(f"{self.waiting} request(s) are waiting and one is running (PADDLEOCR_QUEUE_DEPTH=" f"{self.depth}); retry later") self.waiting += 1 self._q.put(job) return job def call(self, fn: Callable[[], Any], timeout: Optional[float] = None, kind: str = "call") -> Any: """Run ``fn()`` on the worker thread and return its result (blocking).""" job = self.submit(lambda _job: fn(), kind=kind, priority=True) job.enqueued = float("inf") # never times out in the queue return job.future.result(timeout) # ------------------------------------------------------------------------------------------ loop def _loop(self) -> None: while True: job = self._q.get() if job is None: break with self._lock: self.waiting -= 1 self.running = job try: if job.cancel.is_set(): job._finish("error", QueueTimeout("cancelled while waiting in the queue")) continue if self._closing and job.kind not in ("call", "close"): job._finish("error", ShuttingDown("the server is shutting down")) continue waited = time.monotonic() - job.enqueued if job.enqueued != float("inf") else 0.0 if waited > self.timeout_s: job._finish("error", QueueTimeout(f"waited {waited:.1f} s in the queue (PADDLEOCR_QUEUE_TIMEOUT_S=" f"{self.timeout_s:g})")) continue job.started = time.monotonic() job.state = "running" job.emit("started", waited) try: out = job.fn(job) except BaseException as e: # noqa: BLE001 -- reported to the waiting handler job._finish("error", e) else: job._finish("done", out) finally: with self._lock: self.running = None self.completed += 1 # ------------------------------------------------------------------------------------------ shutdown def status(self) -> dict: r = self.running return {"waiting": self.waiting, "running": None if r is None else r.kind, "depth": self.depth, "timeout_s": self.timeout_s, "completed": self.completed} def shutdown(self, close_fn: Optional[Callable[[], Any]] = None, wait_s: float = 100.0) -> None: """Refuse new jobs, cancel the queued ones and the running one, run ``close_fn`` on the worker, stop.""" with self._lock: self._closing = True r = self.running if r is not None: r.cancel.set() drained = [] while True: try: j = self._q.get_nowait() except queue.Empty: break if j is not None: drained.append(j) for j in drained: with self._lock: self.waiting -= 1 j._finish("error", ShuttingDown("the server is shutting down")) if close_fn is not None: job = Job(lambda _j: close_fn(), None, "close") job.enqueued = float("inf") with self._lock: self.waiting += 1 self._q.put(job) try: job.future.result(wait_s) except concurrent.futures.TimeoutError: LOG.error("closing the model did not finish within %.0f s", wait_s) except Exception as e: # noqa: BLE001 LOG.error("closing the model failed: %s: %s", type(e).__name__, e) self._q.put(None) self._thread.join(timeout=5.0)