Download code/tt_dsocr/server/worker.py from changh95/Unlimited-OCR-2: direct link, hf CLI and curl.
- Browser
- Download file 7.69 kB
-
https://huggingface.co/changh95/Unlimited-OCR-2/resolve/main/code/tt_dsocr/server/worker.py
- Command line
-
hf download hf://changh95/Unlimited-OCR-2/code/tt_dsocr/server/worker.py
-
curl -L -o worker.py https://huggingface.co/changh95/Unlimited-OCR-2/resolve/main/code/tt_dsocr/server/worker.py
7.69 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| # Adapted from this workspace's GLM-OCR bundle (tt_glmocr/server/worker.py, itself from the Qwen3-ASR and | |
| # Qwen3-TTS bundles; Apache-2.0). | |
| """The device worker of the HTTP server: ONE thread owns the model (every device call, from the build to the | |
| shutdown, runs on it) and requests wait in a bounded FIFO (batch 1). The chip itself is opened and closed by the | |
| server's lifespan on the main thread (see app.py). | |
| * :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 (the client went away). | |
| 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_dsocr.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 self.future.done(): | |
| return | |
| if kind == "done": | |
| self.future.set_result(payload) | |
| else: | |
| self.future.set_exception(payload) | |
| class DeviceWorker: | |
| def __init__(self, depth: int, timeout_s: float, name: str = "dsocr-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() | |
| def alive(self) -> bool: | |
| return self._thread.is_alive() | |
| def thread_id(self) -> Optional[int]: | |
| return self._thread.ident | |
| def submit(self, fn: Callable[[Job], Any], *, on_event: Optional[Callable[[str, Any], None]] = None, | |
| kind: str = "ocr", 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 (DSOCR_QUEUE_DEPTH=" | |
| f"{self.depth}); retry later") | |
| self.waiting += 1 | |
| if priority: | |
| job.enqueued = float("inf") # never times out in the queue | |
| 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).""" | |
| return self.submit(lambda _job: fn(), kind=kind, priority=True).future.result(timeout) | |
| def _loop(self) -> None: | |
| while True: | |
| job = self._q.get() | |
| if job is None: | |
| break | |
| with self._lock: | |
| self.waiting -= 1 | |
| self.running = job | |
| outcome: tuple = ("error", RuntimeError("the job did not run")) | |
| try: | |
| waited = time.monotonic() - job.enqueued if job.enqueued != float("inf") else 0.0 | |
| if job.cancel.is_set(): | |
| outcome = ("error", QueueTimeout("cancelled while waiting in the queue")) | |
| elif self._closing and job.kind not in ("call", "close"): | |
| outcome = ("error", ShuttingDown("the server is shutting down")) | |
| elif waited > self.timeout_s: | |
| outcome = ("error", QueueTimeout(f"waited {waited:.1f} s in the queue (DSOCR_QUEUE_TIMEOUT_S=" | |
| f"{self.timeout_s:g})")) | |
| else: | |
| job.started = time.monotonic() | |
| job.state = "running" | |
| job.emit("started", waited) | |
| try: | |
| outcome = ("done", job.fn(job)) | |
| except BaseException as e: # noqa: BLE001 -- reported to the waiting handler | |
| outcome = ("error", e) | |
| finally: | |
| # free the slot BEFORE the waiter learns the outcome: a request sent right after sees an idle worker | |
| with self._lock: | |
| self.running = None | |
| self.completed += 1 | |
| job._finish(*outcome) | |
| 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=10.0) | |