Download code/tt_paddleocr/api.py from changh95/PaddleOCR-VL: direct link, hf CLI and curl.
- Browser
- Download file 31 kB
-
https://huggingface.co/changh95/PaddleOCR-VL/resolve/main/code/tt_paddleocr/api.py
- Command line
-
hf download hf://changh95/PaddleOCR-VL/code/tt_paddleocr/api.py
-
curl -L -o api.py https://huggingface.co/changh95/PaddleOCR-VL/resolve/main/code/tt_paddleocr/api.py
31 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Python API of PaddleOCR-VL (vl / 1.5 / 1.6) on one Tenstorrent Blackhole p150. | |
| from tt_paddleocr import serve_config as S | |
| from tt_paddleocr.api import PaddleOCRVL | |
| ocr = PaddleOCRVL.from_config(S.resolve_config({"PADDLEOCR_PROFILE": "1.6"})) # opens the device, builds programs | |
| r = ocr.recognize("crop.png", task="ocr") # ocr | table | formula | chart (+ spotting | seal: 1.5 / 1.6) | |
| print(r["text"], r["result"], r["timings"]) | |
| r = ocr.recognize(img, prompt="Table Recognition:", temperature=0.7, top_p=0.9, seed=1) | |
| for delta in ocr.stream("crop.png", task="table"): print(delta, end="") | |
| ocr.close() | |
| Backends (``PADDLEOCR_BACKEND``): ``tt`` = the device pipeline (tt/model.py ``DevicePipeline``), ``cpu`` = the | |
| clean-room reference on the host (slow; development), ``fake`` = a deterministic stand-in for host tests (no weights, | |
| no device; uses the checkpoint's tokenizer.json when ``PADDLEOCR_WEIGHTS_DIR`` has one, else a byte-level stub). | |
| The per-request (RUNTIME) parameters of :meth:`PaddleOCRVL.recognize`: task / prompt, max_new_tokens, temperature, | |
| top_k, top_p, repetition_penalty, seed, max_pixels, min_pixels, skip_special_tokens; everything else is fixed when | |
| the server starts (serve_config.ServeConfig, COMPILE-TIME). | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import os | |
| import queue | |
| import threading | |
| import time | |
| from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple | |
| from . import __version__ | |
| from . import config as C | |
| from . import frontend as FE | |
| from . import postprocess as PP | |
| from . import serve_config as S | |
| from .tt.model_types import GenParams, Limits, RunResult | |
| TEXT_SPECIAL = {C.UNK, C.BOS, C.EOS, C.CLS, C.IMAGE_START, C.IMAGE_END, C.IMAGE_PLACEHOLDER} | |
| class InputError(ValueError): | |
| status = 400 | |
| class Cancelled(RuntimeError): | |
| """Raised from ``on_token`` when the request was cancelled (client went away / shutdown).""" | |
| # ================================================================================================ images | |
| def decode_image(data, max_mpix: float = 64.0): | |
| """bytes / path / PIL image / HxWx3 uint8 array -> PIL image. The pixel count is checked from the header BEFORE | |
| decoding (decompression-bomb guard); the first frame of an animation is used; EXIF orientation is NOT applied | |
| (as the official processor).""" | |
| from PIL import Image | |
| limit = int(max_mpix * 1e6) | |
| if isinstance(data, Image.Image): | |
| img = data | |
| elif isinstance(data, (bytes, bytearray, memoryview)): | |
| if not data: | |
| raise InputError("empty image") | |
| Image.MAX_IMAGE_PIXELS = max(limit, 1) | |
| try: | |
| img = Image.open(io.BytesIO(bytes(data))) | |
| except Image.DecompressionBombError: | |
| raise InputError(f"image larger than {max_mpix:g} megapixels (PADDLEOCR_MAX_IMAGE_MPIX)") from None | |
| except Exception as e: # noqa: BLE001 -- PIL raises many types on garbage | |
| raise InputError(f"cannot decode the image: {type(e).__name__}: {e}") from None | |
| elif isinstance(data, str): | |
| if not os.path.isfile(data): | |
| raise InputError(f"image file not found: {data}") | |
| with open(data, "rb") as f: | |
| return decode_image(f.read(), max_mpix) | |
| else: | |
| try: | |
| import numpy as np | |
| arr = np.asarray(data) | |
| except Exception: # noqa: BLE001 | |
| raise InputError(f"unsupported image type {type(data).__name__}") from None | |
| if arr.ndim not in (2, 3) or arr.dtype != np.uint8: | |
| raise InputError("an array image must be uint8 HxW or HxWxC") | |
| img = Image.fromarray(arr) | |
| w, h = img.size | |
| if w < 1 or h < 1: | |
| raise InputError("empty image") | |
| if w * h > limit: | |
| raise InputError(f"image of {w}x{h} pixels exceeds {max_mpix:g} megapixels (PADDLEOCR_MAX_IMAGE_MPIX)") | |
| if max(w, h) / min(w, h) > 200: | |
| raise InputError(f"image aspect ratio {max(w, h) / min(w, h):.0f} exceeds 200 (the model's limit)") | |
| try: | |
| if getattr(img, "n_frames", 1) > 1: | |
| img.seek(0) | |
| img.load() | |
| except Exception as e: # noqa: BLE001 | |
| raise InputError(f"cannot decode the image: {type(e).__name__}: {e}") from None | |
| return img | |
| # ================================================================================================ tokenizer stub | |
| class _Enc: | |
| def __init__(self, ids): | |
| self.ids = ids | |
| class StubTokenizer: | |
| """Byte-level stand-in for the checkpoint's tokenizer.json (fake backend without weights): the special tokens of | |
| the template, the table and LOC tokens keep their real ids; any other text is UTF-8 bytes (id 1000 + byte).""" | |
| SPECIAL = {"<unk>": C.UNK, "<s>": C.BOS, "</s>": C.EOS, "<|begin_of_sentence|>": C.CLS, | |
| "<|IMAGE_START|>": C.IMAGE_START, "<|IMAGE_END|>": C.IMAGE_END, | |
| "<|IMAGE_PLACEHOLDER|>": C.IMAGE_PLACEHOLDER, | |
| "<ecel>": 101308, "<fcel>": 101309, "<xcel>": 101310, "<lcel>": 101311, "<ucel>": 101312, | |
| "<nl>": 101313} | |
| SKIP = {C.UNK, C.BOS, C.EOS, C.CLS, C.IMAGE_START, C.IMAGE_END, C.IMAGE_PLACEHOLDER} | |
| def __init__(self): | |
| import re | |
| self._inv = {v: k for k, v in self.SPECIAL.items()} | |
| names = sorted(self.SPECIAL, key=len, reverse=True) | |
| self._re = re.compile("(" + "|".join(re.escape(n) for n in names) + r"|<\|LOC_\d+\|>)") | |
| def token_to_id(self, name: str): | |
| if name in self.SPECIAL: | |
| return self.SPECIAL[name] | |
| if name.startswith("<|LOC_") and name.endswith("|>"): | |
| return C.LOC0 + int(name[6:-2]) | |
| return None | |
| def encode(self, text: str, add_special_tokens: bool = False) -> _Enc: | |
| ids: List[int] = [] | |
| for part in self._re.split(text): | |
| if not part: | |
| continue | |
| tid = self.token_to_id(part) | |
| if tid is not None: | |
| ids.append(tid) | |
| else: | |
| ids.extend(1000 + b for b in part.encode("utf-8")) | |
| return _Enc(ids) | |
| def decode(self, ids, skip_special_tokens: bool = True) -> str: | |
| out, buf = [], bytearray() | |
| for t in ids: | |
| t = int(t) | |
| if 1000 <= t < 1256: | |
| buf.append(t - 1000) | |
| continue | |
| if buf: | |
| out.append(buf.decode("utf-8", errors="replace")) | |
| buf = bytearray() | |
| if skip_special_tokens and t in self.SKIP: | |
| continue | |
| if C.LOC0 <= t <= C.LOC0 + 1000: | |
| out.append(f"<|LOC_{t - C.LOC0}|>") | |
| else: | |
| out.append(self._inv.get(t, "")) | |
| if buf: | |
| out.append(buf.decode("utf-8", errors="replace")) | |
| return "".join(out) | |
| def stub_prompts(prof: C.ProfileConfig) -> FE.PromptBuilder: | |
| pb = FE.PromptBuilder.__new__(FE.PromptBuilder) | |
| pb.tok = StubTokenizer() | |
| pb.prof = prof | |
| pb._cache = {} | |
| return pb | |
| class DeltaStream: | |
| """Incremental detokenization (prefix / read offsets): text deltas that join to ``decode(all)``; holds back while | |
| the tail decodes to an incomplete UTF-8 sequence (byte-fallback tokens <0x..>).""" | |
| def __init__(self, prompts: FE.PromptBuilder, skip_special_tokens: bool = True, | |
| stop_ids: Tuple[int, ...] = (C.EOS,)): | |
| self.p, self.skip, self.stop = prompts, skip_special_tokens, set(stop_ids) | |
| self.ids: List[int] = [] | |
| self.prefix = 0 | |
| self.read = 0 | |
| self.emitted = "" | |
| def push(self, t: int) -> str: | |
| if int(t) in self.stop: | |
| return "" | |
| self.ids.append(int(t)) | |
| prefix_text = self.p.decode(self.ids[self.prefix:self.read], self.skip) | |
| new_text = self.p.decode(self.ids[self.prefix:], self.skip) | |
| if len(new_text) > len(prefix_text) and not new_text.endswith("�"): | |
| d = new_text[len(prefix_text):] | |
| self.prefix, self.read = self.read, len(self.ids) | |
| self.emitted += d | |
| return d | |
| return "" | |
| def finish(self) -> str: | |
| full = self.p.decode(self.ids, self.skip) | |
| if full.startswith(self.emitted): | |
| d = full[len(self.emitted):] | |
| self.emitted = full | |
| return d | |
| return "" | |
| # ================================================================================================ host sampling | |
| def sample_next(logits, params: GenParams, history: List[int], gen) -> int: | |
| """HF order: repetition penalty (over prompt + generated ids) -> temperature -> top-k -> top-p -> multinomial.""" | |
| import torch | |
| x = logits.float().clone() | |
| if params.repetition_penalty and params.repetition_penalty != 1.0 and history: | |
| idx = torch.tensor(sorted(set(int(i) for i in history if 0 <= int(i) < x.numel())), dtype=torch.long) | |
| s = x[idx] | |
| x[idx] = torch.where(s > 0, s / params.repetition_penalty, s * params.repetition_penalty) | |
| if not params.temperature or params.temperature <= 0: | |
| return int(x.argmax()) | |
| x = x / float(params.temperature) | |
| if params.top_k and params.top_k > 0: | |
| k = min(int(params.top_k), x.numel()) | |
| thr = torch.topk(x, k).values[-1] | |
| x = torch.where(x < thr, torch.full_like(x, float("-inf")), x) | |
| if params.top_p is not None and params.top_p < 1.0: | |
| sx, si = torch.sort(x, descending=True) | |
| cp = torch.softmax(sx, -1).cumsum(-1) | |
| drop = cp > float(params.top_p) | |
| drop[1:] = drop[:-1].clone() | |
| drop[0] = False | |
| x[si[drop]] = float("-inf") | |
| p = torch.softmax(x, -1) | |
| return int(torch.multinomial(p, 1, generator=gen)) | |
| # ================================================================================================ backends | |
| class FakeBackend: | |
| """Deterministic stand-in (host tests): a canned answer per task prompt found in the prompt ids, one token per | |
| step; ``max_new_tokens`` truncates (stop ``length``).""" | |
| ANSWERS = { | |
| "OCR:": "Hello from the fake backend. 你好", | |
| "Table Recognition:": "<fcel>Model<fcel>Score<nl><fcel>A<lcel><nl><fcel>B<fcel>2<nl>", | |
| "Formula Recognition:": "\\[E=m c^{2}\\]", | |
| "Chart Recognition:": "Quarter | Revenue\nQ1 | 120\nQ2 | 135", | |
| "Spotting:": "Hello<|LOC_100|><|LOC_200|><|LOC_300|><|LOC_200|><|LOC_300|><|LOC_250|><|LOC_100|>" | |
| "<|LOC_250|>World<|LOC_400|><|LOC_500|><|LOC_600|><|LOC_500|><|LOC_600|><|LOC_550|>" | |
| "<|LOC_400|><|LOC_550|>", | |
| "Seal Recognition:": "测试印章", | |
| } | |
| def __init__(self, cfg: S.ServeConfig, prompts: FE.PromptBuilder): | |
| self.cfg, self.p = cfg, prompts | |
| def run(self, img: FE.ImageInput, ids: List[int], params: GenParams, | |
| on_token: Optional[Callable[[int], None]] = None) -> RunResult: | |
| t0 = time.perf_counter() | |
| prompt_text = self.p.decode(ids, skip_special_tokens=True) | |
| ans = next((a for k, a in self.ANSWERS.items() if k in prompt_text), "fake answer") | |
| toks = self.p.tok.encode(ans, add_special_tokens=False).ids + [C.EOS] | |
| out: List[int] = [] | |
| stop = "length" | |
| for t in toks[:params.max_new_tokens]: | |
| out.append(t) | |
| if on_token is not None: | |
| on_token(t) | |
| if t in params.stop_ids: | |
| stop = "eos" | |
| break | |
| ms = (time.perf_counter() - t0) * 1e3 | |
| return RunResult(out, stop, len(ids), {"vision": 0.0, "prefill": 0.0, "first_token": 0.0, "decode": ms, | |
| "total": ms}) | |
| def info(self) -> Dict[str, Any]: | |
| return {"backend": "fake", "engine": {}, "device": None} | |
| def limits(self) -> Limits: | |
| return Limits(self.cfg.vis_buckets[-1], self.cfg.max_prompt, self.cfg.max_positions) | |
| def close(self): | |
| pass | |
| class CpuBackend: | |
| """The clean-room reference (reference/model.py) on the host CPU: fp32, KV cache, host sampling.""" | |
| def __init__(self, cfg: S.ServeConfig, weights_dir: str): | |
| import torch | |
| from .reference.model import Reference | |
| torch.set_num_threads(max(1, cfg.torch_threads)) | |
| self.cfg = cfg | |
| self.ref = Reference.load(weights_dir, cfg.profile) | |
| def run(self, img: FE.ImageInput, ids: List[int], params: GenParams, | |
| on_token: Optional[Callable[[int], None]] = None) -> RunResult: | |
| import torch | |
| ref, c = self.ref, self.ref.cfg.dec | |
| T = {} | |
| t0 = time.perf_counter() | |
| with torch.no_grad(): | |
| pe = ref.project(ref.vision(img), img.gh, img.gw) | |
| T["vision"] = (time.perf_counter() - t0) * 1e3 | |
| pos, delta = FE.rope_index(ids, img.gh, img.gw) | |
| cos, sin = FE.mrope_cos_sin(pos, c.head_dim, c.theta, c.mrope_section) | |
| cache = [None] * c.layers | |
| h = ref.decoder(ref.embed(ids, pe), torch.from_numpy(cos), torch.from_numpy(sin), cache) | |
| lg = ref.logits(h[-1:])[0] | |
| T["prefill"] = (time.perf_counter() - t0) * 1e3 - T["vision"] | |
| gen = torch.Generator().manual_seed(int(params.seed if params.seed is not None | |
| else int.from_bytes(os.urandom(4), "little"))) | |
| hist = list(ids) | |
| out: List[int] = [] | |
| stop = "length" | |
| L = len(ids) | |
| for s in range(params.max_new_tokens): | |
| t = sample_next(lg, params, hist, gen) | |
| out.append(t) | |
| hist.append(t) | |
| if s == 0: | |
| T["first_token"] = (time.perf_counter() - t0) * 1e3 | |
| if on_token is not None: | |
| on_token(t) | |
| if t in params.stop_ids: | |
| stop = "eos" | |
| break | |
| if s == params.max_new_tokens - 1: | |
| break | |
| p = L + s + delta | |
| cs, sn = FE.mrope_cos_sin(__import__("numpy").full((3, 1), p), c.head_dim, c.theta, c.mrope_section) | |
| h = ref.decoder(ref.W["model.embed_tokens.weight"][t][None], torch.from_numpy(cs), | |
| torch.from_numpy(sn), cache) | |
| lg = ref.logits(h)[0] | |
| T["total"] = (time.perf_counter() - t0) * 1e3 | |
| T["decode"] = T["total"] - T.get("first_token", T["total"]) | |
| return RunResult(out, stop, len(ids), T) | |
| def info(self) -> Dict[str, Any]: | |
| return {"backend": "cpu", "engine": {"all": "cpu-reference-fp32"}, "device": None} | |
| def limits(self) -> Limits: | |
| return Limits(self.cfg.vis_buckets[-1], self.cfg.max_prompt, self.cfg.max_positions) | |
| def close(self): | |
| pass | |
| def build_device_backend(device, weights_dir: str, cfg: S.ServeConfig, log=print): | |
| """THE construction of the device pipeline (tt/model.py); every compile-time setting goes through | |
| ``ServeConfig.device_settings()``.""" | |
| from .tt.model import DevicePipeline | |
| mcfg = C.ModelConfig.from_dir(weights_dir, cfg.profile) | |
| pipe = DevicePipeline(device, weights_dir, mcfg, cfg.device_settings(), log=log) | |
| if cfg.trace or cfg.warmup != "none": | |
| pipe.prepare() # warm-up (compile) + trace capture of every bucket before the server reports READY | |
| return pipe | |
| def open_tt_device(cfg: S.ServeConfig): | |
| """Open the chip (call on the thread that will close it: the server's main thread).""" | |
| from .ttaw.device import open_device | |
| return open_device(cfg.device_id, dispatch=cfg.dispatch, num_command_queues=cfg.num_command_queues, | |
| l1_small_size=32768, trace_region_size=cfg.trace_region_mb << 20) | |
| def describe_tt_device(device) -> Dict[str, Any]: | |
| try: | |
| from .ttaw.device import describe_device | |
| return describe_device(device) | |
| except Exception as e: # noqa: BLE001 | |
| return {"error": f"{type(e).__name__}: {e}"} | |
| # ================================================================================================ the API | |
| class PaddleOCRVL: | |
| def __init__(self, cfg: S.ServeConfig, backend, prompts: FE.PromptBuilder, prof: C.ProfileConfig, | |
| weights_dir: Optional[str] = None, device=None, owns_device: bool = False): | |
| self.cfg, self.backend, self.prompts, self.prof = cfg, backend, prompts, prof | |
| self.weights_dir = weights_dir | |
| self.device, self.owns_device = device, owns_device | |
| self._lock = threading.Lock() | |
| self.requests = 0 | |
| # ------------------------------------------------------------------ construction | |
| def from_config(cls, cfg: Optional[S.ServeConfig] = None, device=None, log=print) -> "PaddleOCRVL": | |
| """``device``: an opened chip (the server opens it on its main thread); None with the tt backend: the chip is | |
| opened here and closed by :meth:`close`.""" | |
| cfg = cfg or S.resolve_config() | |
| if cfg.backend == "fake": | |
| wd = cfg.weights_dir | |
| prof = C.PROFILE_CONFIGS[cfg.profile] | |
| if wd and os.path.isfile(os.path.join(wd, "tokenizer.json")): | |
| prompts = FE.PromptBuilder.from_dir(wd, prof) | |
| else: | |
| prompts = stub_prompts(prof) | |
| return cls(cfg, FakeBackend(cfg, prompts), prompts, prof, wd) | |
| wd = cfg.weights_dir or C.resolve_weights_dir(cfg.profile, cfg.revision) | |
| mcfg = C.ModelConfig.from_dir(wd, cfg.profile) | |
| prompts = FE.PromptBuilder.from_dir(wd, mcfg.prof) | |
| if cfg.backend == "cpu": | |
| return cls(cfg, CpuBackend(cfg, wd), prompts, mcfg.prof, wd) | |
| owns = device is None | |
| if owns: | |
| device = open_tt_device(cfg) | |
| try: | |
| backend = build_device_backend(device, wd, cfg, log) | |
| except BaseException: | |
| if owns: | |
| from .ttaw.device import close_device | |
| close_device(device) | |
| raise | |
| return cls(cfg, backend, prompts, mcfg.prof, wd, device, owns) | |
| def from_env(cls, env: Optional[Dict[str, str]] = None, log=print) -> "PaddleOCRVL": | |
| return cls.from_config(S.resolve_config(env), log=log) | |
| # ------------------------------------------------------------------ requests | |
| def _params(self, *, max_new_tokens, temperature, top_k, top_p, repetition_penalty, seed) -> GenParams: | |
| cfg = self.cfg | |
| mnt = cfg.default_max_new_tokens if max_new_tokens is None else max_new_tokens | |
| if not isinstance(mnt, int) or isinstance(mnt, bool) or not 1 <= mnt <= cfg.max_new_tokens_cap: | |
| raise InputError(f"max_new_tokens={max_new_tokens!r}: 1 .. {cfg.max_new_tokens_cap} " | |
| "(PADDLEOCR_MAX_NEW_TOKENS)") | |
| temp = 0.0 if temperature is None else float(temperature) | |
| if not 0.0 <= temp <= 2.0: | |
| raise InputError(f"temperature={temperature!r}: 0 (greedy, the official decoding) .. 2") | |
| tk = 0 if top_k is None else top_k | |
| if not isinstance(tk, int) or isinstance(tk, bool) or not 0 <= tk <= cfg.k_max: | |
| raise InputError(f"top_k={top_k!r}: 0 (off) .. {cfg.k_max} (PADDLEOCR_K_MAX)") | |
| tp = 1.0 if top_p is None else float(top_p) | |
| if not 0.0 < tp <= 1.0: | |
| raise InputError(f"top_p={top_p!r}: (0, 1]") | |
| rp = 1.0 if repetition_penalty is None else float(repetition_penalty) | |
| if not 1.0 <= rp <= 2.0: | |
| raise InputError(f"repetition_penalty={repetition_penalty!r}: 1 (off) .. 2") | |
| if seed is not None and (not isinstance(seed, int) or isinstance(seed, bool) or not 0 <= seed < 2 ** 63): | |
| raise InputError(f"seed={seed!r}: an integer in [0, 2^63)") | |
| return GenParams(max_new_tokens=mnt, temperature=temp, top_k=tk, top_p=tp, repetition_penalty=rp, | |
| seed=seed, stop_ids=(C.EOS,)) | |
| def _task(self, task: Optional[str], prompt: Optional[str]) -> Tuple[str, str]: | |
| cfg = self.cfg | |
| if prompt is not None and not isinstance(prompt, str): | |
| raise InputError("prompt must be a string") | |
| if prompt is not None: | |
| try: | |
| prompt.encode("utf-8") # a lone UTF-16 surrogate (valid JSON "\ud800") is not text: 400, not a 500 | |
| except UnicodeEncodeError: | |
| raise InputError("prompt is not valid Unicode text (lone surrogate)") from None | |
| if prompt is not None and not prompt.strip(): | |
| prompt = None | |
| if task is None: | |
| task = "ocr" if prompt is None else "custom" | |
| task = str(task).strip().lower() | |
| if task != "custom" and task not in cfg.tasks: | |
| raise InputError(f"task {task!r} is not available in profile {cfg.profile} (tasks: " | |
| f"{', '.join(cfg.tasks)}" + ("" if cfg.profile != "vl" else | |
| "; spotting / seal need profile 1.5 or 1.6") + ")") | |
| if task == "custom" and prompt is None: | |
| raise InputError("task 'custom' needs a prompt") | |
| return task, (prompt if prompt is not None else C.TASKS[task]) | |
| def _pixels(self, task: str, max_pixels: Optional[int], min_pixels: Optional[int]) -> Tuple[int, int]: | |
| cfg = self.cfg | |
| mx = cfg.max_pixels | |
| if max_pixels is not None: | |
| if not isinstance(max_pixels, int) or isinstance(max_pixels, bool) or \ | |
| not S.MIN_PIXELS_FLOOR <= max_pixels <= mx: | |
| raise InputError(f"max_pixels={max_pixels!r}: {S.MIN_PIXELS_FLOOR} .. {mx} (PADDLEOCR_MAX_PIXELS)") | |
| mxp = min(FE.task_max_pixels(task if task != "custom" else "ocr", self.prof, max_pixels), mx) | |
| mnp = cfg.min_pixels if min_pixels is None else min_pixels | |
| if not isinstance(mnp, int) or isinstance(mnp, bool) or not S.MIN_PIXELS_FLOOR <= mnp <= mxp: | |
| raise InputError(f"min_pixels={min_pixels!r}: {S.MIN_PIXELS_FLOOR} .. max_pixels ({mxp})") | |
| return mnp, mxp | |
| def validate(self, image, task: Optional[str] = None, prompt: Optional[str] = None, *, | |
| max_new_tokens: Optional[int] = None, temperature: Optional[float] = None, | |
| top_k: Optional[int] = None, top_p: Optional[float] = None, | |
| repetition_penalty: Optional[float] = None, seed: Optional[int] = None, | |
| max_pixels: Optional[int] = None, min_pixels: Optional[int] = None, **_ignored): | |
| """Every check that needs no pre-processing (the server runs it before queueing); returns the decoded PIL | |
| image (pass it to :meth:`recognize`).""" | |
| self._params(max_new_tokens=max_new_tokens, temperature=temperature, top_k=top_k, top_p=top_p, | |
| repetition_penalty=repetition_penalty, seed=seed) | |
| task, _ = self._task(task, prompt) | |
| self._pixels(task, max_pixels, min_pixels) | |
| return decode_image(image, self.cfg.max_image_mpix) | |
| def prepare(self, image, task: Optional[str] = None, prompt: Optional[str] = None, | |
| max_pixels: Optional[int] = None, min_pixels: Optional[int] = None): | |
| """Validate + pre-process: (task, prompt text, PIL image, ImageInput, prompt ids).""" | |
| cfg = self.cfg | |
| task, text = self._task(task, prompt) | |
| mnp, mxp = self._pixels(task, max_pixels, min_pixels) | |
| img = decode_image(image, cfg.max_image_mpix) | |
| try: | |
| ii = FE.preprocess(FE.task_image(img, task), mnp, mxp) | |
| except ValueError as e: | |
| raise InputError(str(e)) from None | |
| ids = self.prompts.ids(text, ii.n_tokens) | |
| n_text = len(ids) - ii.n_tokens | |
| if n_text > cfg.max_prompt_tokens: | |
| raise InputError(f"the prompt has {n_text} text tokens (with the template) > PADDLEOCR_MAX_PROMPT_TOKENS=" | |
| f"{cfg.max_prompt_tokens}") | |
| lim = self.backend.limits() | |
| if ii.n_patches > lim.max_patches: | |
| raise InputError(f"{ii.n_patches} patches > the largest vision bucket {lim.max_patches}: lower max_pixels") | |
| if len(ids) > lim.max_prompt: | |
| raise InputError(f"{len(ids)} prompt tokens > the largest prefill bucket {lim.max_prompt}") | |
| return task, text, img, ii, ids | |
| def recognize(self, image, task: Optional[str] = None, prompt: Optional[str] = None, *, | |
| max_new_tokens: Optional[int] = None, temperature: Optional[float] = None, | |
| top_k: Optional[int] = None, top_p: Optional[float] = None, | |
| repetition_penalty: Optional[float] = None, seed: Optional[int] = None, | |
| max_pixels: Optional[int] = None, min_pixels: Optional[int] = None, | |
| skip_special_tokens: bool = True, return_tokens: bool = False, | |
| on_delta: Optional[Callable[[str], None]] = None, | |
| cancel: Optional[threading.Event] = None) -> Dict[str, Any]: | |
| """Recognize ONE element (or a whole page with task ocr / spotting). Returns ``text`` (the model output, | |
| special tokens skipped: the official decode), ``raw_text``, ``result`` (task view: table html / spotting | |
| items / latex / chart rows), ``stop`` (eos | length), ``usage``, ``timings`` (ms), ``image`` (sizes, grid).""" | |
| t0 = time.perf_counter() | |
| params = self._params(max_new_tokens=max_new_tokens, temperature=temperature, top_k=top_k, top_p=top_p, | |
| repetition_penalty=repetition_penalty, seed=seed) | |
| task, text, img, ii, ids = self.prepare(image, task, prompt, max_pixels, min_pixels) | |
| lim = self.backend.limits() | |
| room = lim.max_positions - len(ids) | |
| if room < 1: | |
| raise InputError(f"{len(ids)} prompt tokens leave no room in the KV capacity {lim.max_positions}") | |
| if params.max_new_tokens > room: | |
| params.max_new_tokens = room | |
| t1 = time.perf_counter() | |
| ds = DeltaStream(self.prompts, skip_special_tokens, params.stop_ids) | |
| def on_token(t: int) -> None: | |
| if cancel is not None and cancel.is_set(): | |
| raise Cancelled("request cancelled") | |
| d = ds.push(t) | |
| if d and on_delta is not None: | |
| on_delta(d) | |
| with self._lock: | |
| try: | |
| res: RunResult = self.backend.run(ii, ids, params, on_token) | |
| except ValueError as e: # the backends raise ValueError for requests they cannot serve | |
| raise InputError(str(e)) from None | |
| tail = ds.finish() | |
| if tail and on_delta is not None: | |
| on_delta(tail) | |
| self.requests += 1 | |
| gen = [t for t in res.tokens if t not in params.stop_ids] | |
| out_text = self.prompts.decode(gen, skip_special_tokens) | |
| raw = self.prompts.decode(gen, False) | |
| w, h = img.size | |
| timings = {k: (round(float(v), 3) if isinstance(v, (int, float)) else v) | |
| for k, v in (res.timings or {}).items()} | |
| timings["preprocess"] = round((t1 - t0) * 1e3, 3) | |
| timings["request"] = round((time.perf_counter() - t0) * 1e3, 3) | |
| n = len(gen) | |
| dec = timings.get("decode") | |
| if isinstance(dec, float) and n > 1 and "per_token" not in timings: | |
| timings["per_token"] = round(dec / max(1, n - 1), 3) | |
| out = { | |
| "text": out_text, "raw_text": raw, "task": task, "prompt": text, "profile": self.cfg.profile, | |
| "stop": res.stop, "result": PP.structured(task, self.prompts.decode(gen, True), w, h), | |
| "usage": {"prompt_tokens": len(ids), "image_tokens": ii.n_tokens, "completion_tokens": n, | |
| "total_tokens": len(ids) + n}, | |
| "timings": timings, | |
| "image": {"size": [w, h], "model_input_size": list(ii.source_size), "resized": list(ii.resized), | |
| "grid": [ii.gh, ii.gw], "patches": ii.n_patches}, | |
| "params": {"max_new_tokens": params.max_new_tokens, "temperature": params.temperature, | |
| "top_k": params.top_k, "top_p": params.top_p, | |
| "repetition_penalty": params.repetition_penalty, "seed": params.seed}, | |
| } | |
| if return_tokens: | |
| out["tokens"] = list(res.tokens) | |
| return out | |
| def stream(self, image, task: Optional[str] = None, prompt: Optional[str] = None, **kw) -> Iterator[str]: | |
| """Text deltas as they are decoded (runs :meth:`recognize` on a helper thread); the last item of the | |
| iteration is followed by nothing; errors are raised in the caller.""" | |
| q: "queue.Queue[Tuple[str, Any]]" = queue.Queue() | |
| cancel = threading.Event() | |
| def work(): | |
| try: | |
| r = self.recognize(image, task, prompt, on_delta=lambda d: q.put(("d", d)), cancel=cancel, **kw) | |
| q.put(("done", r)) | |
| except BaseException as e: # noqa: BLE001 | |
| q.put(("err", e)) | |
| th = threading.Thread(target=work, daemon=True) | |
| th.start() | |
| try: | |
| while True: | |
| k, v = q.get() | |
| if k == "d": | |
| yield v | |
| elif k == "done": | |
| self.last_result = v | |
| return | |
| else: | |
| raise v | |
| finally: | |
| cancel.set() | |
| # ------------------------------------------------------------------ info / close | |
| def info(self) -> Dict[str, Any]: | |
| cfg = self.cfg | |
| lim = self.backend.limits() | |
| d = {"profile": cfg.profile, "weights": {"repo": cfg.repo, "revision": cfg.revision, | |
| "dir": self.weights_dir}, | |
| "backend": cfg.backend, "tasks": list(cfg.tasks), "version": __version__, | |
| "limits": {"max_patches": lim.max_patches, "max_prompt_tokens": lim.max_prompt, | |
| "max_positions": lim.max_positions, "max_pixels": cfg.max_pixels, | |
| "min_pixels": cfg.min_pixels, "max_new_tokens": cfg.max_new_tokens_cap, | |
| "default_max_new_tokens": cfg.default_max_new_tokens, "k_max": cfg.k_max, | |
| "max_prompt_text_tokens": cfg.max_prompt_tokens, "max_image_mpix": cfg.max_image_mpix}, | |
| "buckets": {"vision": list(cfg.vis_buckets), "prefill": list(cfg.pre_buckets)}} | |
| try: | |
| d.update({k: v for k, v in self.backend.info().items() if k not in ("profile",)}) | |
| except Exception as e: # noqa: BLE001 | |
| d["backend_info_error"] = f"{type(e).__name__}: {e}" | |
| if self.device is not None and "device" not in d: | |
| d["device"] = describe_tt_device(self.device) | |
| elif self.device is not None and not d.get("device"): | |
| d["device"] = describe_tt_device(self.device) | |
| return d | |
| def close(self): | |
| try: | |
| self.backend.close() | |
| finally: | |
| if self.owns_device and self.device is not None: | |
| from .ttaw.device import close_device | |
| dev, self.device = self.device, None | |
| close_device(dev) | |