File size: 31,593 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# SPDX-License-Identifier: Apache-2.0
"""Python API of GLM-OCR on one Tenstorrent Blackhole p150.

    from tt_glmocr import config as C
    from tt_glmocr.api import GlmOcr

    with GlmOcr.from_config(C.resolve_config()) as m:        # opens the p150, loads weights, captures the traces
        r = m.ocr("page.png")                                 # task "text" -> OcrResult
        print(r.text, r.finish_reason, r.usage, r.timings)
        r = m.ocr("table.png", task="table", output_format="markdown")
        r = m.ocr("id.png", task="extract", schema={"name": "", "date_of_birth": ""}, output_format="json")
        print(r.json)
        s = m.ocr_stream("page.png")                         # text deltas as tokens are decoded
        for delta in s:
            print(delta, end="", flush=True)
        print(s.result.usage)

Backends (``GLMOCR_BACKEND``): ``device`` (the p150), ``cpu`` (the clean-room CPU reference; slow), ``fake`` (a
deterministic stand-in for tests; no weights or device). The host work (image decoding, the official smart_resize /
patches / prompt / 3D positions, detokenization, stop rules, output formats) is done here for every backend.

The work of a request is split in two: :meth:`GlmOcr.prepare` (CPU only, thread-safe: image decoding, resizing,
patches, prompt, validation) and :meth:`GlmOcr.run` (the backend; one request at a time). The server prepares a request
on a thread pool while the device serves the previous one.
"""

from __future__ import annotations

import base64
import binascii
import io
import json
import math
import os
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple

from . import config as C
from . import frontend as FE
from . import postprocess as PP
from .backends import Backend, CpuBackend, DeviceBackend, FakeBackend, Sampling, close_chip, open_chip

__version__ = "0.1.0"
__all__ = ["GlmOcr", "OcrResult", "OcrStream", "Prepared", "InputError", "TASKS", "ByteTokenizer", "load_image",
           "parse_messages", "__version__"]

TASKS = ("text", "table", "formula", "extract")
FORMATS = PP.FORMATS
MAX_SEED = 2 ** 63 - 1


class InputError(ValueError):
    """A request the model cannot serve (HTTP 400, or ``status``)."""

    def __init__(self, msg: str, status: int = 400):
        super().__init__(msg)
        self.status = status


# ================================================================================================ results
@dataclass
class Prepared:
    """One request after the host front end (CPU): what :meth:`GlmOcr.run` needs."""

    image: Optional[FE.Image]
    prompt: FE.Prompt
    prompt_text: str
    task: str
    output_format: str
    max_new_tokens: int
    sampling: Sampling
    image_info: Optional[Dict[str, Any]]
    preprocess_ms: float


@dataclass
class OcrResult:
    text: str                      # the output in ``output_format``
    raw_text: str                  # the decoded model output (special tokens removed)
    tokens: List[int]              # generated token ids (the stop token excluded)
    finish_reason: str             # "stop" (stop token) | "length" (max_new_tokens / KV capacity) | "cancelled"
    task: str
    output_format: str
    usage: Dict[str, int]
    timings: Dict[str, Any]
    image: Optional[Dict[str, Any]] = None
    json: Any = None               # the parsed output (output_format "json", or task "extract" when it parses)
    json_error: Optional[str] = None
    sampling: Dict[str, Any] = field(default_factory=dict)

    def as_dict(self) -> Dict[str, Any]:
        return {"text": self.text, "raw_text": self.raw_text, "finish_reason": self.finish_reason, "task": self.task,
                "format": self.output_format, "json": self.json, "json_error": self.json_error, "usage": self.usage,
                "image": self.image, "sampling": self.sampling, "timings": self.timings}


# ================================================================================================ tokenizer stand-in
class ByteTokenizer:
    """UTF-8 bytes as token ids 0..255 (the fake backend without a checkpoint): every non-ASCII character spans
    several tokens, which exercises the streaming detokenizer. Ids >= 256 are special (skipped when decoding)."""

    def encode(self, text: str) -> List[int]:
        return list(text.encode("utf-8"))

    def decode(self, ids: Sequence[int], skip_special: bool = True) -> str:
        out, buf = [], bytearray()
        for t in ids:
            t = int(t)
            if t < 256:
                buf.append(t)
                continue
            if buf:
                out.append(buf.decode("utf-8", errors="replace"))
                buf = bytearray()
            if not skip_special:
                out.append(f"<{t}>")
        if buf:
            out.append(buf.decode("utf-8", errors="replace"))
        return "".join(out)


class Detokenizer:
    """Incremental detokenization of byte-level BPE: decodes a small window of the latest tokens and emits only
    text that is stable (no trailing U+FFFD of an incomplete UTF-8 sequence); the concatenated deltas equal
    ``tok.decode(all tokens)``."""

    def __init__(self, tok):
        self.tok = tok
        self.ids: List[int] = []
        self.prefix = 0
        self.read = 0
        self.emitted: List[str] = []

    def push(self, t: int) -> str:
        self.ids.append(int(t))
        prefix_text = self.tok.decode(self.ids[self.prefix:self.read])
        new_text = self.tok.decode(self.ids[self.prefix:])
        if len(new_text) > len(prefix_text) and not new_text.endswith("�") and new_text.startswith(prefix_text):
            d = new_text[len(prefix_text):]
            self.prefix, self.read = self.read, len(self.ids)
            self.emitted.append(d)
            return d
        return ""

    def flush(self) -> str:
        """What is left at the end (an incomplete character is emitted as U+FFFD, as a full decode gives it)."""
        full = self.tok.decode(self.ids)
        done = "".join(self.emitted)
        d = full[len(done):] if full.startswith(done) else ""
        if d:
            self.emitted.append(d)
        self.prefix = self.read = len(self.ids)
        return d


# ================================================================================================ inputs
class _NoUnsafeRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        if urllib.parse.urlparse(newurl).scheme not in ("http", "https"):
            raise InputError(f"image URL redirected to a non-http(s) location: {newurl!r}")
        return super().redirect_request(req, fp, code, msg, headers, newurl)


def fetch_url(url: str, max_bytes: int, timeout: float) -> bytes:
    opener = urllib.request.build_opener(_NoUnsafeRedirect())
    req = urllib.request.Request(url, headers={"User-Agent": "tt-glmocr/" + __version__})
    try:
        with opener.open(req, timeout=timeout) as r:
            data = r.read(max_bytes + 1)
    except InputError:
        raise
    except urllib.error.HTTPError as e:
        raise InputError(f"fetching the image URL failed: HTTP {e.code}") from None
    except Exception as e:  # noqa: BLE001 -- network errors, timeouts, bad URLs
        raise InputError(f"fetching the image URL failed: {type(e).__name__}: {e}") from None
    if len(data) > max_bytes:
        raise InputError(f"the image at the URL is larger than {max_bytes} bytes", status=413)
    return data


def decode_data_url(s: str) -> bytes:
    """``data:image/png;base64,....`` or plain base64 -> bytes."""
    if s.startswith("data:"):
        head, sep, s = s.partition(",")
        if not sep or ";base64" not in head:
            raise InputError("image data URL: expected data:<mime>;base64,<data>")
    try:
        return base64.b64decode("".join(s.split()), validate=True)
    except (binascii.Error, ValueError):
        raise InputError("image is not valid base64") from None


def _to_rgb(im):
    """RGB PIL image; transparency composited onto white (transformers' ``convert_to_rgb``); 16-bit greyscale
    scaled to 8 bits."""
    from PIL import Image

    if im.mode in ("I;16", "I;16L", "I;16B", "I;16N", "I"):
        import numpy as np

        a = np.asarray(im, dtype=np.float64)
        top = 65535.0 if im.mode.startswith("I;16") or a.max() > 255 else 255.0
        im = Image.fromarray(np.clip(np.round(a * (255.0 / top)), 0, 255).astype(np.uint8), "L")
    has_alpha = "A" in im.getbands() or im.info.get("transparency") is not None
    if has_alpha:
        im = im.convert("RGBA")
        bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
        return Image.alpha_composite(bg, im).convert("RGB")
    return im if im.mode == "RGB" else im.convert("RGB")


def load_image(src: Any, *, max_pixels: float = 50e6, allow_urls: bool = False, allow_paths: bool = True,
               max_bytes: int = 64 << 20, url_timeout: float = 15.0):
    """Any supported image source -> RGB PIL image.

    Sources: PIL image; uint8 numpy array (H x W, H x W x 3, H x W x 4); bytes (PNG, JPEG, WebP, BMP, TIFF, GIF: the
    first frame); a ``data:`` URL or base64 string; an http(s) URL (``allow_urls``); a file path (``allow_paths``).
    Encoded images are turned upright by their EXIF orientation (as transformers' ``load_image``)."""
    from PIL import Image, ImageOps

    if isinstance(src, Image.Image):
        im, encoded = src, False
    elif type(src).__module__ == "numpy":
        import numpy as np

        a = np.asarray(src)
        if a.dtype != np.uint8 or a.ndim not in (2, 3) or (a.ndim == 3 and a.shape[2] not in (1, 3, 4)):
            raise InputError(f"image array: uint8 H x W [x 1|3|4] expected, got {a.dtype} {a.shape}")
        if a.ndim == 3 and a.shape[2] == 1:
            a = a[..., 0]
        im, encoded = Image.fromarray(np.ascontiguousarray(a)), False
    else:
        if isinstance(src, os.PathLike):
            src = os.fspath(src)
        if isinstance(src, str):
            s = src.strip()
            if s.startswith(("http://", "https://")):
                if not allow_urls:
                    raise InputError("image URLs are disabled on this server (GLMOCR_ALLOW_URLS=1 enables them); "
                                     "send the image as a data URL / base64")
                data = fetch_url(s, max_bytes, url_timeout)
            elif s.startswith("data:"):
                data = decode_data_url(s)
            elif allow_paths and len(s) < 4096 and os.path.isfile(s):
                with open(s, "rb") as f:
                    data = f.read()
            else:
                data = decode_data_url(s)
        elif isinstance(src, (bytes, bytearray, memoryview)):
            data = bytes(src)
        else:
            raise InputError(f"unsupported image source {type(src).__name__}")
        if not data:
            raise InputError("empty image")
        try:
            im = Image.open(io.BytesIO(data))
        except Image.DecompressionBombError as e:
            raise InputError(f"image too large: {e}", status=413) from None
        except Exception as e:  # noqa: BLE001 -- not an image PIL can read
            raise InputError(f"cannot decode the image: {type(e).__name__}: {e}") from None
        encoded = True
    w, h = im.size
    if w < 1 or h < 1:
        raise InputError(f"empty image ({w} x {h})")
    if w * h > max_pixels:
        raise InputError(f"image of {w} x {h} = {w * h / 1e6:.1f} MP exceeds GLMOCR_MAX_INPUT_MEGAPIXELS="
                         f"{max_pixels / 1e6:g}", status=413)
    try:
        if encoded:
            im.load()
            im = ImageOps.exif_transpose(im)
        return _to_rgb(im)
    except InputError:
        raise
    except Exception as e:  # noqa: BLE001 -- truncated / corrupt files fail at load()
        raise InputError(f"cannot decode the image: {type(e).__name__}: {e}") from None


def parse_messages(messages: Any) -> Tuple[Any, str]:
    """OpenAI chat ``messages`` -> (image source or None, prompt text). Single-turn OCR: the LAST user message is the
    request (its text parts joined, at most one image); system and earlier messages are ignored."""
    if not isinstance(messages, list) or not messages:
        raise InputError("messages: a non-empty list")
    if any(not isinstance(m, dict) for m in messages):
        raise InputError("messages: each message is an object with role and content")
    users = [m for m in messages if m.get("role") == "user"]
    if not users:
        raise InputError("messages: no user message")
    c = users[-1].get("content")
    if not isinstance(c, (str, list)):
        raise InputError("message content: a string or a list of parts")
    if isinstance(c, list):
        images = [p for p in c if isinstance(p, dict) and p.get("type") in ("image_url", "image", "input_image")]
        if len(images) > 1:
            raise InputError(f"{len(images)} images in the message: GLM-OCR serves one image per request")
        for p in c:
            if not isinstance(p, dict) or p.get("type") not in ("text", "image_url", "image", "input_image"):
                raise InputError(f"unsupported content part {p!r:.80}: text and image_url parts only")
    try:
        img, text = FE.messages_to_request(messages)
    except (ValueError, AttributeError, TypeError) as e:
        raise InputError(f"messages: {e}") from None
    return img, text or ""


def infer_task(prompt_text: str) -> str:
    t = prompt_text.strip()
    for k, v in FE.TASK_PROMPTS.items():
        if t == v:
            return k
    if t.startswith(PP.EXTRACT_PREFACE.strip()):
        return "extract"
    return "prompt"


# ================================================================================================ the model
class GlmOcr:
    MODEL_NAME = C.MODEL_NAME

    def __init__(self, cfg: C.ServeConfig, backend: Backend, tok, model_dir: Optional[str] = None,
                 owned_device: Any = None):
        self.cfg, self.backend, self.tok = cfg, backend, tok
        self.model_dir = model_dir
        self._owned_device = owned_device
        self._lock = threading.Lock()
        self._closed = False
        self.last_timings: Dict[str, Any] = {}

    # ------------------------------------------------------------------ construction
    @classmethod
    def from_config(cls, cfg: Optional[C.ServeConfig] = None, *, device: Any = None,
                    log: Callable[[str], None] = print) -> "GlmOcr":
        """Build the model for ``cfg`` (default: the environment). Backend ``device``: ``device`` is an opened p150
        the caller keeps owning (the server opens it on its main thread); without one the p150 is opened here and
        closed by :meth:`close`."""
        cfg = cfg or C.resolve_config()
        if cfg.backend == "fake":
            tok = FE.Tokenizer(cfg.model_dir) if cfg.model_dir else ByteTokenizer()
            return cls(cfg, FakeBackend(cfg, tok), tok, cfg.model_dir)
        model_dir = C.resolve_model_dir(cfg)
        tok = FE.Tokenizer(model_dir)
        if cfg.backend == "cpu":
            return cls(cfg, CpuBackend(cfg, model_dir, log=log), tok, model_dir)
        owned = None
        if device is None:
            log(f"Opening device {cfg.device_id} (dispatch {cfg.dispatch})")
            device = owned = open_chip(cfg)
        try:
            be = DeviceBackend(cfg, device, model_dir, log=log)
        except BaseException:
            if owned is not None:
                close_chip(owned)
            raise
        return cls(cfg, be, tok, model_dir, owned_device=owned)

    def close(self) -> None:
        if self._closed:
            return
        self._closed = True
        try:
            self.backend.close()
        finally:
            dev, self._owned_device = self._owned_device, None
            if dev is not None:
                close_chip(dev)

    def __enter__(self) -> "GlmOcr":
        return self

    def __exit__(self, *exc) -> None:
        self.close()

    # ------------------------------------------------------------------ limits
    @property
    def max_image_tokens(self) -> int:
        return int(self.backend.max_image_tokens)

    @property
    def max_pixels_cap(self) -> int:
        return C.tokens_to_max_pixels(self.max_image_tokens)

    @property
    def default_max_pixels(self) -> int:
        return min(C.OFFICIAL_MAX_PIXELS, self.max_pixels_cap)

    # ------------------------------------------------------------------ validation
    def sampling(self, temperature=None, top_k=None, top_p=None, repetition_penalty=None, seed=None) -> Sampling:
        t = 0.0 if temperature is None else _float(temperature, "temperature")
        if not 0.0 <= t <= 2.0:
            raise InputError(f"temperature {t:g}: 0 (greedy, the official decoding) .. 2")
        k = 0 if top_k is None else _int(top_k, "top_k")
        if not 0 <= k <= self.cfg.k_max:
            raise InputError(f"top_k {k}: 0 (off) .. {self.cfg.k_max} (GLMOCR_K_MAX)")
        p = 1.0 if top_p is None else _float(top_p, "top_p")
        if not 0.0 < p <= 1.0:
            raise InputError(f"top_p {p:g}: (0, 1]")
        rp = 1.0 if repetition_penalty is None else _float(repetition_penalty, "repetition_penalty")
        if not 1.0 <= rp <= 2.0:
            raise InputError(f"repetition_penalty {rp:g}: 1.0 (off, the official default) .. 2.0")
        if seed is not None:
            seed = _int(seed, "seed")
            if not 0 <= seed <= MAX_SEED:
                raise InputError(f"seed {seed}: 0 .. 2^63 - 1")
        elif t > 0:
            seed = int.from_bytes(os.urandom(8), "little") & MAX_SEED
        return Sampling(t, k, p, rp, seed)

    def pixel_limits(self, max_pixels=None, min_pixels=None, max_image_tokens=None) -> Tuple[int, int]:
        """(min_pixels, max_pixels) in the official processor units (2 frames x h x w)."""
        cap = self.max_pixels_cap
        if max_pixels is not None and max_image_tokens is not None:
            raise InputError("give max_pixels or max_image_tokens, not both")
        if max_image_tokens is not None:
            n = _int(max_image_tokens, "max_image_tokens")
            if not C.OFFICIAL_MIN_PIXELS // (C.FRAMES * C.PIXELS_PER_TOKEN) <= n <= self.max_image_tokens:
                raise InputError(f"max_image_tokens {n}: 8 .. {self.max_image_tokens} (GLMOCR_MAX_IMAGE_TOKENS)")
            mx = C.tokens_to_max_pixels(n)
        elif max_pixels is not None:
            mx = _int(max_pixels, "max_pixels")
            if not C.OFFICIAL_MIN_PIXELS <= mx <= cap:
                raise InputError(f"max_pixels {mx}: {C.OFFICIAL_MIN_PIXELS} .. {cap} (official units: 2 x height x "
                                 f"width; {cap} = {self.max_image_tokens} image tokens, GLMOCR_MAX_IMAGE_TOKENS)")
        else:
            mx = self.default_max_pixels
        mn = C.OFFICIAL_MIN_PIXELS if min_pixels is None else _int(min_pixels, "min_pixels")
        if not C.OFFICIAL_MIN_PIXELS <= mn <= mx:
            raise InputError(f"min_pixels {mn}: {C.OFFICIAL_MIN_PIXELS} .. max_pixels ({mx})")
        return mn, mx

    def resolve_prompt(self, task: Optional[str], prompt: Optional[str], schema: Any) -> Tuple[str, str]:
        """(task, prompt text): the card's task presets, the extraction prompt from a schema, or a free prompt."""
        if task is not None and task not in TASKS:
            raise InputError(f"task {task!r}: one of {list(TASKS)}")
        if prompt is not None and not isinstance(prompt, str):
            raise InputError("prompt: a string")
        prompt = prompt if prompt and prompt.strip() else None
        if schema is not None and schema != "":
            if task not in (None, "extract"):
                raise InputError(f"schema is for task 'extract' (got task {task!r})")
            if prompt is not None:
                raise InputError("give schema or prompt, not both")
            try:
                return "extract", PP.schema_prompt(schema)
            except ValueError as e:
                raise InputError(str(e)) from None
        if prompt is not None:
            return (task or infer_task(prompt)), prompt
        if task == "extract":
            raise InputError("task 'extract' needs a schema (the JSON fields to fill) or a full prompt")
        task = task or "text"
        return task, FE.TASK_PROMPTS[task]

    # ------------------------------------------------------------------ the two halves of a request
    def prepare(self, image: Any = None, *, task: Optional[str] = None, prompt: Optional[str] = None,
                schema: Any = 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,
                max_image_tokens: Optional[int] = None, output_format: Optional[str] = None,
                allow_paths: bool = True) -> Prepared:
        """Validate a request and run the host front end (CPU only; no device, thread-safe)."""
        t0 = time.perf_counter()
        task, text = self.resolve_prompt(task, prompt, schema)
        fmt = (output_format or "raw").strip().lower()
        if fmt not in FORMATS:
            raise InputError(f"format {output_format!r}: one of {list(FORMATS)}")
        sp = self.sampling(temperature, top_k, top_p, repetition_penalty, seed)
        mn, mx = self.pixel_limits(max_pixels, min_pixels, max_image_tokens)
        try:  # lone surrogates (valid JSON escapes, not text) would fail inside the tokenizer: a 400, not a 500
            text.encode("utf-8")
        except UnicodeEncodeError as e:
            raise InputError(f"the prompt is not valid Unicode text ({e.reason} at character {e.start})") from None
        n_text = len(self.tok.encode(text))
        if n_text > self.cfg.max_prompt_tokens:
            raise InputError(f"the prompt has {n_text} tokens > GLMOCR_MAX_PROMPT_TOKENS={self.cfg.max_prompt_tokens}")
        if max_new_tokens is not None:
            n_new = _int(max_new_tokens, "max_new_tokens")
            if not 1 <= n_new <= self.cfg.max_new_tokens:
                raise InputError(f"max_new_tokens {n_new}: 1 .. {self.cfg.max_new_tokens} (GLMOCR_MAX_NEW_TOKENS)")
        else:
            n_new = self.cfg.default_max_new_tokens
        img = info = None
        if image is not None:
            pil = load_image(image, max_pixels=self.cfg.max_input_megapixels * 1e6, allow_urls=self.cfg.allow_urls,
                             allow_paths=allow_paths, max_bytes=int(self.cfg.max_body_mb * (1 << 20)),
                             url_timeout=self.cfg.url_timeout_s)
            try:
                img = FE.preprocess(pil, min_pixels=mn, max_pixels=mx)
            except ValueError as e:  # smart_resize: aspect ratio >= 200
                raise InputError(f"cannot resize the image: {e}") from None
            if img.n_tokens > self.max_image_tokens:
                raise InputError(f"the image needs {img.n_tokens} image tokens after resizing > "
                                 f"{self.max_image_tokens} (GLMOCR_MAX_IMAGE_TOKENS); lower max_pixels")
            (H, W), (h, w) = img.original, img.resized
            info = {"width": W, "height": H, "resized_width": w, "resized_height": h, "image_tokens": img.n_tokens,
                    "patches": img.n_patches, "grid": [img.llm_grid[0], img.llm_grid[1]],
                    "min_pixels": mn, "max_pixels": mx}
        pr = FE.build_prompt(self.tok, text, img)
        if pr.L > self.backend.max_prompt:
            raise InputError(f"the prompt is {pr.L} tokens (image + text) > the largest prefill bucket "
                             f"{self.backend.max_prompt}")
        room = int(self.backend.room(pr.L))
        if room < 1:
            raise InputError(f"the prompt of {pr.L} tokens leaves no room in the KV cache ({self.backend.max_context}"
                             " positions, GLMOCR_MAX_CONTEXT)")
        return Prepared(img, pr, text, task, fmt, min(n_new, room), sp, info, 1e3 * (time.perf_counter() - t0))

    def _run_iter(self, p: Prepared, cancel: Optional[threading.Event] = None):
        """Generator: yields text deltas, returns the :class:`OcrResult` (StopIteration.value)."""
        with self._lock:
            if self._closed:
                raise RuntimeError("the model is closed")
            t0 = time.perf_counter()
            toks: List[int] = []
            finish = "length"
            first_ms = None
            det = Detokenizer(self.tok)
            gen = self.backend.generate(p.prompt, p.image, p.max_new_tokens, p.sampling)
            n_gen = 0
            try:
                for t in gen:
                    t = int(t)
                    n_gen += 1
                    if first_ms is None:
                        first_ms = 1e3 * (time.perf_counter() - t0)
                    if t in FE.EOS_IDS:
                        finish = "stop"
                        break
                    toks.append(t)
                    d = det.push(t)
                    if d:
                        yield d
                    if cancel is not None and cancel.is_set():
                        finish = "cancelled"
                        break
                    if n_gen >= p.max_new_tokens:
                        break
            finally:
                gen.close()
            tail = det.flush()
            if tail:
                yield tail
            run_ms = 1e3 * (time.perf_counter() - t0)
            bt = self.backend.timings()
        raw = self.tok.decode(toks)
        text, val, err = PP.apply_format(raw, p.task, p.output_format)
        if p.task == "extract" and p.output_format != "json":
            val, err = PP.parse_json_output(raw)
        timings = {"preprocess_ms": round(p.preprocess_ms, 3),
                   "first_token_ms": round(p.preprocess_ms + (first_ms or 0.0), 3),
                   "generate_ms": round(run_ms, 3), "total_ms": round(p.preprocess_ms + run_ms, 3)}
        timings.update({k: (round(v, 3) if isinstance(v, float) else v) for k, v in bt.items()})
        self.last_timings = timings
        usage = {"prompt_tokens": p.prompt.L, "image_tokens": p.prompt.n_image,
                 "completion_tokens": n_gen, "total_tokens": p.prompt.L + n_gen}
        return OcrResult(text, raw, toks, finish, p.task, p.output_format, usage, timings, p.image_info, val, err,
                         dict(p.sampling.as_dict(), max_new_tokens=p.max_new_tokens))

    def run(self, p: Prepared, on_delta: Optional[Callable[[str], None]] = None,
            cancel: Optional[threading.Event] = None) -> OcrResult:
        """Generate for a prepared request (one at a time); ``on_delta(text)`` receives the text as it is decoded."""
        it = self._run_iter(p, cancel)
        while True:
            try:
                d = next(it)
            except StopIteration as stop:
                return stop.value
            if on_delta is not None:
                on_delta(d)

    # ------------------------------------------------------------------ one-call entry points
    def ocr(self, image: Any = None, task: Optional[str] = None, prompt: Optional[str] = None, schema: Any = None, *,
            on_delta: Optional[Callable[[str], None]] = None, cancel: Optional[threading.Event] = None,
            **kw) -> OcrResult:
        """OCR one image. ``task``: ``text`` (default), ``table`` (HTML), ``formula`` (LaTeX), ``extract`` (with
        ``schema``: a dict / JSON of the fields to fill); ``prompt`` replaces the task's prompt. Keyword arguments:
        ``max_new_tokens``, ``temperature``, ``top_k``, ``top_p``, ``repetition_penalty``, ``seed``,
        ``max_pixels`` / ``max_image_tokens``, ``min_pixels``, ``output_format`` (raw | markdown | json)."""
        return self.run(self.prepare(image, task=task, prompt=prompt, schema=schema, **kw), on_delta, cancel)

    def ocr_stream(self, image: Any = None, task: Optional[str] = None, prompt: Optional[str] = None,
                   schema: Any = None, *, cancel: Optional[threading.Event] = None, **kw) -> "OcrStream":
        """Like :meth:`ocr`, as an iterator of text deltas; the result is ``stream.result`` after the iteration."""
        return OcrStream(self._run_iter(self.prepare(image, task=task, prompt=prompt, schema=schema, **kw), cancel))

    # ------------------------------------------------------------------ description
    @property
    def info(self) -> Dict[str, Any]:
        c = self.cfg
        return {
            "model": C.MODEL_NAME, "version": __version__,
            "weights": {"repo": C.WEIGHTS_REPO, "revision": c.revision, "license": "MIT"},
            **self.backend.info,
            "limits": {"max_image_tokens": self.max_image_tokens, "max_pixels": self.max_pixels_cap,
                       "min_pixels": C.OFFICIAL_MIN_PIXELS, "max_prompt_tokens": c.max_prompt_tokens,
                       "max_new_tokens": c.max_new_tokens, "kv_positions": int(self.backend.max_context),
                       "max_prompt_rows": int(self.backend.max_prompt), "k_max": c.k_max,
                       "max_input_megapixels": c.max_input_megapixels, "max_body_mb": c.max_body_mb,
                       "image_urls": c.allow_urls, "images_per_request": 1, "batch": 1},
            "buckets": {"vision_patches": list(c.vis_buckets), "vision_image_tokens": [b // 4 for b in c.vis_buckets],
                        "prefill_rows": list(c.pre_buckets)},
            "defaults": {"task": "text", "format": "raw", "max_new_tokens": c.default_max_new_tokens,
                         "temperature": 0.0, "top_k": 0, "top_p": 1.0, "repetition_penalty": 1.0,
                         "max_pixels": self.default_max_pixels, "min_pixels": C.OFFICIAL_MIN_PIXELS},
            "tasks": dict(FE.TASK_PROMPTS, extract=PP.EXTRACT_PREFACE + "<schema JSON, indent 4>"),
            "formats": list(FORMATS), "stop_token_ids": list(FE.EOS_IDS),
        }


class OcrStream:
    """Iterator of text deltas of one request; ``result`` (an :class:`OcrResult`) once exhausted."""

    def __init__(self, it):
        self._it = it
        self.result: Optional[OcrResult] = None

    def __iter__(self) -> Iterator[str]:
        try:
            while True:
                try:
                    d = next(self._it)
                except StopIteration as stop:
                    self.result = stop.value
                    return
                yield d
        finally:
            self.close()

    def close(self) -> None:
        self._it.close()


def _float(v: Any, name: str) -> float:
    if isinstance(v, bool):
        raise InputError(f"{name}: a number")
    try:
        x = float(v)
    except (TypeError, ValueError):
        raise InputError(f"{name}={v!r}: a number") from None
    if not math.isfinite(x):
        raise InputError(f"{name}={v!r}: a finite number")
    return x


def _int(v: Any, name: str) -> int:
    if isinstance(v, bool):
        raise InputError(f"{name}: an integer")
    if isinstance(v, float):
        if not v.is_integer():
            raise InputError(f"{name}={v!r}: an integer")
        return int(v)
    try:
        return int(str(v).strip())
    except (TypeError, ValueError):
        raise InputError(f"{name}={v!r}: an integer") from None