File size: 43,407 Bytes
b8b3105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's GLM-OCR bundle (tt_glmocr/api.py, Apache-2.0).
"""Python API of the DeepSeek-OCR family on one Tenstorrent Blackhole p150.

    from tt_dsocr import config as C
    from tt_dsocr.api import DeepSeekOcr

    with DeepSeekOcr.from_config(C.resolve_config()) as m:  # opens the p150, loads weights, captures the traces
        r = m.ocr("page.png")                                 # task "markdown", mode "gundam" -> OcrResult
        print(r.text, r.finish_reason, r.usage, r.timings)
        r = m.ocr("page.png", task="free", mode="base")        # plain text, one 1024 x 1024 view
        r = m.ocr("page.png", task="locate", ref="the title")  # boxes: r.json["refs"][0]["boxes"] (pixels)
        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)

    # Unlimited-OCR-2 (DSOCR_VARIANT=unlimited-ocr-2): one or more pages per request, task "parse"
    r = m.ocr(["page1.png", "page2.png"])                    # r.json["pages"][k]["blocks"]: label, box, text

Each variant offers its own task presets (``config.TASK_PROMPTS``): DeepSeek-OCR the six above, DeepSeek-OCR-2 the
two of its model card (``markdown``, ``free``), Unlimited-OCR-2 ``parse``; a free ``prompt`` is always accepted.

Backends (``DSOCR_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 views / Gundam
tiles / prompt ids, detokenization, stop rule, output formats) is done here for every backend.

The work of a request is split in two: :meth:`DeepSeekOcr.prepare` (CPU only, thread-safe: validation, image
decoding, views, prompt) and :meth:`DeepSeekOcr.run` (the backend; one request at a time, under a lock). 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 re
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 (NGRAM_PRESETS, SGLANG_MULTIPAGE_WINDOW, Backend, CpuBackend, DeviceBackend, FakeBackend, NGram,
                       Sampling, close_chip, open_chip)

__version__ = "0.1.0"
__all__ = ["DeepSeekOcr", "OcrResult", "OcrStream", "Prepared", "InputError", "TASKS", "DEFAULT_FORMAT",
           "ByteTokenizer", "Detokenizer", "load_image", "parse_messages", "parse_messages_multi", "infer_task",
           "__version__"]

TASKS = tuple(FE.TASKS)                     # DeepSeek-OCR: markdown, ocr, free, figure, describe, locate
#: the output format of a request without one (``prompt`` = a free prompt)
DEFAULT_FORMAT = dict(C.DEFAULT_FORMAT)
FORMATS = PP.FORMATS
MAX_SEED = 2 ** 63 - 1
MAX_NGRAM = 64
MAX_WHITELIST = 64
MAX_REF_CHARS = 512


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:`DeepSeekOcr.run` needs."""

    fe: FE.Prepared                # ids, image_pos, global_px, tiles_px, grid, prompt
    task: str
    mode: str
    output_format: str
    max_new_tokens: int
    sampling: Sampling
    ngram: NGram
    image_info: 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 kept, the EOS removed)
    tokens: List[int]              # generated token ids (the EOS excluded)
    finish_reason: str             # "stop" (EOS) | "length" (max_new_tokens / KV capacity) | "cancelled"
    task: str
    mode: str
    output_format: str
    usage: Dict[str, int]
    timings: Dict[str, Any]
    image: Dict[str, Any]
    refs: List[Dict[str, Any]] = field(default_factory=list)   # the ref / det groups (labels, boxes in pixels)
    json: Any = None               # format "json": {"text", "refs", "image"}
    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,
                "mode": self.mode, "format": self.output_format, "json": self.json, "refs": self.refs,
                "usage": self.usage, "image": self.image, "sampling": self.sampling, "timings": self.timings}


# ================================================================================================ tokenizer stand-in
class ByteTokenizer:
    """UTF-8 bytes as token ids ``3 + byte`` (the fake backend without a checkpoint; ids 0 / 1 / 2 are BOS / EOS /
    PAD as in the real tokenizer): every non-ASCII character spans several tokens, which exercises the streaming
    detokenizer. Other ids are special (``<image>`` = 128815)."""

    OFFSET = 3
    SPECIAL = {0: "<|begin▁of▁sentence|>", 1: PP.EOS_TEXT, 2: "<|▁pad▁|>", FE.IMAGE_TOKEN_ID: FE.IMAGE_TOKEN,
               128827: "<PAGE>", 128828: "<BLOCK>", 128829: "<FORK>", 128830: "<CHILD>"}
    #: Unlimited-OCR-2's layout tokens: encoded to their ids (as the real tokenizer's added tokens) and never skipped
    TAGS = {"<PAGE>": 128827, "<BLOCK>": 128828, "<FORK>": 128829, "<CHILD>": 128830}
    _TAG_RE = re.compile("(" + "|".join(re.escape(t) for t in TAGS) + ")")

    def encode(self, text: str) -> List[int]:
        out: List[int] = []
        for part in self._TAG_RE.split(text):
            if part in self.TAGS:
                out.append(self.TAGS[part])
            elif part:
                out += [b + self.OFFSET for b in part.encode("utf-8")]
        return out

    def decode(self, ids: Sequence[int], skip_special_tokens: bool = False) -> str:
        out, buf = [], bytearray()
        for t in ids:
            t = int(t)
            if self.OFFSET <= t < self.OFFSET + 256:
                buf.append(t - self.OFFSET)
                continue
            if buf:
                out.append(buf.decode("utf-8", errors="replace"))
                buf = bytearray()
            if not skip_special_tokens or t in self.TAGS.values():
                out.append(self.SPECIAL.get(t, f"<{t}>"))
        if buf:
            out.append(buf.decode("utf-8", errors="replace"))
        return "".join(out)

    def token_id(self, s: str) -> Optional[int]:
        return next((k for k, v in self.SPECIAL.items() if v == s), None)


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)`` (special tokens kept: ``<|ref|>``, ``<td>``, ... are part of the output)."""

    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-dsocr/" + __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 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, as the official ``load_image``: EXIF orientation applied, then
    ``convert("RGB")`` (transparency is dropped as the official code drops it).

    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``).
    The pixel count is checked BEFORE the pixels are decoded (``max_pixels``: HTTP 413)."""
    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 (DSOCR_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 DSOCR_MAX_INPUT_MEGAPIXELS="
                         f"{max_pixels / 1e6:g}", status=413)
    try:
        if encoded:
            im.load()
        try:
            im = ImageOps.exif_transpose(im)
        except Exception:  # noqa: BLE001 -- the official load_image falls back to the raw image
            pass
        return im if im.mode == "RGB" else im.convert("RGB")
    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 _content_parts(c: Any) -> List[Dict[str, Any]]:
    if isinstance(c, str):
        return [{"type": "text", "text": c}]
    if not isinstance(c, list):
        raise InputError("message content: a string or a list of parts")
    return c


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 with newlines, at most one image part); system and earlier messages are
    ignored."""
    images, text = parse_messages_multi(messages, 1)
    return (images[0] if images else None), text


def parse_messages_multi(messages: Any, max_images: int = 1) -> Tuple[List[Any], str]:
    """Like :func:`parse_messages` with up to ``max_images`` image parts (Unlimited-OCR-2's pages, in order)."""
    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")
    parts = _content_parts(users[-1].get("content"))
    texts: List[str] = []
    images: List[Any] = []
    for p in parts:
        if not isinstance(p, dict) or p.get("type") not in ("text", "input_text", "image_url", "image", "input_image"):
            raise InputError(f"unsupported content part {p!r:.80}: text and image_url parts only")
        if p["type"] in ("text", "input_text"):
            t = p.get("text")
            if not isinstance(t, str):
                raise InputError("a text part needs a string 'text'")
            texts.append(t)
        else:
            v = p.get("image_url", p.get("image"))
            if isinstance(v, dict):
                v = v.get("url")
            images.append(v)
    if len(images) > max_images:
        raise InputError(f"{len(images)} images in the message: " + (
            "this model reads one image per request" if max_images == 1 else
            f"at most {max_images} pages per request (DSOCR_MAX_PAGES)"))
    return images, "\n".join(t for t in texts if t.strip())


_LOCATE_RE = re.compile(r"<image>\nLocate <\|ref\|>(.*)<\|/ref\|> in the image\.", re.DOTALL)


def infer_task(prompt_text: str, variant: str = C.DEFAULT_VARIANT) -> str:
    """The task preset of ``variant`` a prompt is (after ``frontend.normalize_prompt``; Unlimited-OCR-2: the
    instruction after the ``<PAGE><image>`` runs), else ``prompt``."""
    tasks = C.TASK_PROMPTS[variant]
    if C.VARIANTS[variant].multipage:
        instr = re.sub(r"^(?:\s*(?:<PAGE>)?\s*<image>)*", "", prompt_text or "").strip()
        if not instr or not prompt_text.strip():
            return "prompt"
        return next((k for k, v in tasks.items() if instr == v), "prompt")
    try:  # a preset of this variant (schift-ocr-1-beta: "<image>document parsing.")
        n = FE.normalize_prompt(prompt_text)
        for k, v in tasks.items():
            if k != "locate" and n == FE.normalize_prompt(v):
                return k
    except ValueError:
        pass
    t = _infer_ocr_task(prompt_text)
    return t if t in tasks else "prompt"


def _infer_ocr_task(prompt_text: str) -> str:
    try:
        t = FE.normalize_prompt(prompt_text)
    except ValueError:
        return "prompt"
    for k, v in FE.TASKS.items():
        if k != "locate" and t == FE.normalize_prompt(v):
            return k
    return "locate" if _LOCATE_RE.fullmatch(t) else "prompt"


# ================================================================================================ the model
class DeepSeekOcr:
    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.variant = FE.VARIANTS[cfg.variant]
        self.vinfo = cfg.info
        self.tasks = C.TASK_PROMPTS[cfg.variant]
        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) -> "DeepSeekOcr":
        """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) -> "DeepSeekOcr":
        return self

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

    # ------------------------------------------------------------------ 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} (DSOCR_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 ngram(self, size=None, window=None, whitelist=None, preset=None, n_pages: int = 1) -> NGram:
        """The no-repeat n-gram rule: ``preset`` (the variant's, ``config.VariantInfo.ngram_presets``; the first is
        the default = the official ``infer``): ``hf`` (DeepSeek-OCR / -2: 20 over the whole sequence), ``vllm``
        (DeepSeek-OCR's vLLM recipe: 30, window 90, whitelist ``<td>`` / ``</td>``), ``off`` (Unlimited-OCR-2's
        default), ``sglang`` (Unlimited-OCR-2's SGLang client: 35, window 128 for one page, 1024 for several);
        explicit ``size`` / ``window`` / ``whitelist`` replace the preset's values."""
        presets = self.vinfo.ngram_presets
        p = presets[0] if preset is None else str(preset).strip().lower()
        if p not in presets:
            raise InputError(f"ngram_preset {preset!r}: one of {list(presets)} ({self.cfg.variant})")
        base = NGRAM_PRESETS[p]
        if p == "sglang" and n_pages > 1:
            base = NGram(base.size, SGLANG_MULTIPAGE_WINDOW, base.whitelist)
        n = base.size if size is None else _int(size, "no_repeat_ngram_size")
        if n != 0 and not 2 <= n <= MAX_NGRAM:
            raise InputError(f"no_repeat_ngram_size {n}: 0 (off) or 2 .. {MAX_NGRAM}")
        w = base.window if window is None else _int(window, "ngram_window")
        if w != 0 and not (max(n, 2) <= w <= self.cfg.kv_positions):
            raise InputError(f"ngram_window {w}: 0 (the whole sequence) or no_repeat_ngram_size .. "
                             f"{self.cfg.kv_positions}")
        wl = base.whitelist if whitelist is None else _int_list(whitelist, "ngram_whitelist")
        if len(wl) > MAX_WHITELIST or any(not 0 <= t < C.VOCAB for t in wl):
            raise InputError(f"ngram_whitelist: at most {MAX_WHITELIST} token ids in [0, {C.VOCAB})")
        return NGram(n, w, tuple(sorted(set(wl))))

    def resolve_mode(self, mode=None, n_pages: int = 1) -> str:
        """``mode`` or the default: ``DSOCR_DEFAULT_MODE``; Unlimited-OCR-2 several pages: ``base`` (the official
        auto policy: Gundam tiles for one page, one 1024 view per page for several) when it is enabled."""
        if mode is None and n_pages > 1 and "base" in self.cfg.modes:
            mode = "base"
        m = self.cfg.default_mode if mode is None else str(mode).strip().lower()
        known = [x[0] for x in self.variant.modes]
        if m not in known:
            raise InputError(f"mode {mode!r}: one of {known} ({self.cfg.variant})")
        if m not in self.cfg.modes:
            raise InputError(f"mode {m!r} is not enabled on this server (DSOCR_MODES={','.join(self.cfg.modes)})")
        return m

    def crop_limits(self, min_crops=None, max_crops=None) -> Tuple[int, int]:
        """(min_crops, max_crops) of the Gundam tile grid: official 2 / 9 (OCR-1), 2 / 6 (OCR-2), 2 / 16
        (Unlimited-OCR-2), capped by DSOCR_MAX_CROPS."""
        cap = self.cfg.max_crops
        mx = min(self.variant.crop_max, cap) if max_crops is None else _int(max_crops, "max_crops")
        mn = min(self.variant.crop_min, mx) if min_crops is None else _int(min_crops, "min_crops")
        if not 1 <= mn <= mx <= cap:
            raise InputError(f"min_crops {mn} / max_crops {mx}: 1 <= min_crops <= max_crops <= {cap} "
                             "(DSOCR_MAX_CROPS)")
        return mn, mx

    def resolve_prompt(self, task: Optional[str], prompt: Optional[str], ref: Optional[str]) -> Tuple[str, str]:
        """(task, prompt text): a task preset of the variant (``locate`` needs ``ref``) or a free prompt
        (``<image>\\n`` is added in front when it has no ``<image>``; Unlimited-OCR-2: ``<PAGE><image>`` per page)."""
        if task is not None and not isinstance(task, str):
            raise InputError("task: a string")
        task = task.strip().lower() if task is not None and task.strip() else None
        if task is not None and task not in self.tasks:
            raise InputError(f"task {task!r}: one of {list(self.tasks)} (the presets {self.cfg.variant} offers; any "
                             "instruction can be sent as 'prompt')")
        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 ref is not None and not isinstance(ref, str):
            raise InputError("ref: a string")
        for name, text in (("prompt", prompt), ("ref", ref)):
            if text is not None:
                try:  # a lone UTF-16 surrogate ("\ud800", valid JSON) is not encodable text: 400, not a tokenizer 500
                    text.encode("utf-8")
                except UnicodeEncodeError:
                    raise InputError(f"{name}: not valid Unicode text (unpaired surrogate code point)") from None
        ref = ref.strip() if ref and ref.strip() else None
        if prompt is not None:
            if ref is not None:
                raise InputError("give prompt or ref (task locate), not both")
            t = infer_task(prompt, self.cfg.variant)
            return (task or t), prompt
        if ref is not None and "locate" not in self.tasks:
            raise InputError(f"ref is for task 'locate', which {self.cfg.variant} does not offer")
        task = task or ("locate" if ref is not None else self.vinfo.default_task)
        if task == "locate":
            if ref is None:
                raise InputError("task 'locate' needs 'ref' (the object or text to find)")
            if len(ref) > MAX_REF_CHARS or "<|" in ref or "|>" in ref or FE.IMAGE_TOKEN in ref:
                raise InputError(f"ref: plain text of at most {MAX_REF_CHARS} characters without special tokens")
            return task, self.tasks["locate"].format(ref=ref)
        if ref is not None:
            raise InputError(f"ref is for task 'locate' (got task {task!r})")
        return task, self.tasks[task]

    def page_sources(self, image: Any = None, images: Any = None) -> List[Any]:
        """The request's image sources, in page order (``images`` a list, or ``image`` one source or a list)."""
        if images is not None and image is not None:
            raise InputError("give image or images, not both")
        src = images if images is not None else image
        pages = list(src) if isinstance(src, (list, tuple)) else ([] if src is None else [src])
        if not pages or any(p is None for p in pages):
            raise InputError("an image is required" + (
                f" ({self.vinfo.display} reads one image per request)" if not self.vinfo.multipage else
                f" (1 .. {self.cfg.max_pages} page images per request)"))
        if not self.vinfo.multipage and len(pages) != 1:
            raise InputError(f"{len(pages)} images: {self.vinfo.display} reads one image per request")
        if len(pages) > self.cfg.max_pages:
            raise InputError(f"{len(pages)} pages: at most {self.cfg.max_pages} per request (DSOCR_MAX_PAGES)")
        return pages

    def _text_tokens(self, text: str, n_pages: int) -> Tuple[str, int]:
        """(the normalized prompt, its text tokens: BOS + the text around the image placeholders; Unlimited-OCR-2's
        ``<PAGE>`` markers count as page rows, not text)."""
        if not self.vinfo.multipage:
            norm = FE.normalize_prompt(text)
            before, after = norm.split(FE.IMAGE_TOKEN)
            return norm, 1 + len(self.tok.encode(before)) + len(self.tok.encode(after))
        full = FE.uocr2_prompt(text.strip(), n_pages)
        if full.count(FE.PAGE_TOKEN + FE.IMAGE_TOKEN) != n_pages:
            raise ValueError("Unlimited-OCR-2 needs '<PAGE><image>' for every page (the prompt layout it was trained "
                             "on); leave <image> out of the prompt and the server writes it")
        ids = [t for seg in full.split(FE.IMAGE_TOKEN) for t in self.tok.encode(seg)]
        return text, 1 + len(ids) - min(n_pages, ids.count(FE.PAGE_TOKEN_ID))

    # ------------------------------------------------------------------ the two halves of a request
    def prepare(self, image: Any = None, *, images: Any = None, task: Optional[str] = None,
                prompt: Optional[str] = None, ref: Optional[str] = None, mode: Optional[str] = None,
                min_crops: Optional[int] = None, max_crops: Optional[int] = 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,
                no_repeat_ngram_size: Optional[int] = None, ngram_window: Optional[int] = None,
                ngram_whitelist: Any = None, ngram_preset: Optional[str] = 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). ``image``: one image
        (Unlimited-OCR-2: or a list of page images); ``images``: the page images as a list."""
        t0 = time.perf_counter()
        srcs = self.page_sources(image, images)
        n_pages = len(srcs)
        task, text = self.resolve_prompt(task, prompt, ref)
        fmt = (output_format or DEFAULT_FORMAT[task]).strip().lower() if isinstance(output_format or "", str) else ""
        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)
        ng = self.ngram(no_repeat_ngram_size, ngram_window, ngram_whitelist, ngram_preset, n_pages)
        mode = self.resolve_mode(mode, n_pages)
        mn, mx = self.crop_limits(min_crops, max_crops)
        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} (DSOCR_MAX_NEW_TOKENS)")
        else:
            n_new = self.cfg.default_max_new_tokens
        if len(text) > 64 * self.cfg.max_prompt_tokens:
            raise InputError(f"the prompt has {len(text)} characters: too long (DSOCR_MAX_PROMPT_TOKENS="
                             f"{self.cfg.max_prompt_tokens})")
        try:
            norm, n_text = self._text_tokens(text, n_pages)
        except ValueError as e:
            raise InputError(str(e)) from None
        if n_text > self.cfg.max_prompt_tokens:
            raise InputError(f"the prompt has {n_text} text tokens > DSOCR_MAX_PROMPT_TOKENS="
                             f"{self.cfg.max_prompt_tokens}")
        pils = [load_image(src, 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) for src in srcs]
        try:
            if self.vinfo.multipage:
                fp = FE.prepare_pages(self.variant, self.tok, pils, norm, mode, mn, mx)
            else:
                fp = FE.prepare(self.variant, self.tok, pils[0], norm, mode, mn, mx)
        except ValueError as e:
            raise InputError(f"cannot prepare the image: {e}") from None
        pages = (fp.extra or {}).get("pages")
        n_img = (sum(p["image_pos"][1] - p["image_pos"][0] for p in pages) if pages is not None
                 else fp.image_pos[1] - fp.image_pos[0])
        L = len(fp.ids)
        if L > self.backend.max_prompt:
            hint = ""
            if pages is not None and n_pages > 1 and mode != "base":
                hint = "; several pages fit best in mode base"
            raise InputError(f"the prompt is {L} tokens ({n_img} image + {L - n_img} text) > the largest prefill "
                             f"bucket {self.backend.max_prompt}{hint}")
        room = int(self.backend.room(L))
        if room < 1:
            raise InputError(f"the prompt of {L} tokens leaves no room in the KV cache ({self.backend.max_context} "
                             "positions, DSOCR_MAX_CONTEXT)")
        w, h = fp.image_wh
        info = {"width": w, "height": h, "mode": mode, "base_size": fp.base_size, "image_size": fp.image_size,
                "crop": fp.crop, "grid": [fp.grid[0], fp.grid[1]], "tiles": fp.n_tiles, "image_tokens": n_img,
                "min_crops": mn, "max_crops": mx}
        if pages is not None:
            info["tiles"] = sum(0 if p["tiles_px"] is None else int(p["tiles_px"].shape[0]) for p in pages)
            info["n_pages"] = len(pages)
            info["pages"] = [{"width": p["image_wh"][0], "height": p["image_wh"][1], "grid": list(p["grid"]),
                              "tiles": 0 if p["tiles_px"] is None else int(p["tiles_px"].shape[0]),
                              "image_tokens": p["image_pos"][1] - p["image_pos"][0]} for p in pages]
        return Prepared(fp, task, mode, fmt, min(n_new, room), sp, ng, 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.fe, p.max_new_tokens, p.sampling, p.ngram)
            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 == FE.EOS_ID:
                        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 = PP.strip_eos(self.tok.decode(toks))
        pages = (p.fe.extra or {}).get("pages")
        if pages is not None:
            text, obj, refs = PP.apply_format_pages(raw, p.output_format, [pg["image_wh"] for pg in pages])
        else:
            text, obj, refs = PP.apply_format(raw, p.task, p.output_format, p.fe.image_wh)
        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
        L = len(p.fe.ids)
        usage = {"prompt_tokens": L, "image_tokens": p.image_info["image_tokens"], "completion_tokens": n_gen,
                 "total_tokens": L + n_gen}
        return OcrResult(text, raw, toks, finish, p.task, p.mode, p.output_format, usage, timings, p.image_info,
                         refs, obj, dict(p.sampling.as_dict(), max_new_tokens=p.max_new_tokens, **p.ngram.as_dict()))

    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, *,
            on_delta: Optional[Callable[[str], None]] = None, cancel: Optional[threading.Event] = None,
            **kw) -> OcrResult:
        """OCR one image (Unlimited-OCR-2: ``image`` may be a list of page images, in order). ``task`` (the
        variant's presets): ``markdown`` (default: the document as Markdown with layout boxes), ``ocr`` (grounded text
        lines), ``free`` (plain text), ``figure``, ``describe``, ``locate`` (with ``ref``); DeepSeek-OCR-2:
        ``markdown`` / ``free``; Unlimited-OCR-2: ``parse``. ``prompt`` replaces the task's prompt. Keyword
        arguments: ``ref``, ``mode`` (the variant's modes), ``min_crops`` / ``max_crops``, ``max_new_tokens``,
        ``temperature``, ``top_k``, ``top_p``, ``repetition_penalty``, ``seed``, ``no_repeat_ngram_size``,
        ``ngram_window``, ``ngram_whitelist``, ``ngram_preset`` (the variant's presets), ``output_format`` (raw |
        markdown | json)."""
        return self.run(self.prepare(image, task=task, prompt=prompt, **kw), on_delta, cancel)

    def ocr_stream(self, image: Any = None, task: Optional[str] = None, prompt: Optional[str] = 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, **kw), cancel))

    # ------------------------------------------------------------------ description
    @property
    def info(self) -> Dict[str, Any]:
        c, v = self.cfg, self.cfg.info
        modes = {}
        for m in c.modes:
            b, s, crop = C.mode_params(v, m)
            lo, hi = C.mode_image_tokens(v, m, c.max_crops)
            modes[m] = {"base_size": b, "image_size": s, "crop": crop, "tile": v.tile if crop else None,
                        "image_tokens": [lo, hi]}
        defaults: Dict[str, Any] = {
            "task": v.default_task, "mode": c.default_mode,
            "format": {k: DEFAULT_FORMAT[k] for k in list(self.tasks) + ["prompt"]},
            "max_new_tokens": c.default_max_new_tokens, "temperature": 0.0, "top_k": 0, "top_p": 1.0,
            "repetition_penalty": 1.0, "ngram_preset": v.ngram_presets[0],
            "min_crops": min(v.crop_min, c.max_crops), "max_crops": min(v.crop_max, c.max_crops)}
        if v.multipage:
            defaults.update(mode_several_pages="base" if "base" in c.modes else c.default_mode,
                            page_count_guard=True, max_page_tokens=C.MAX_PAGE_TOKENS)
        return {
            "model": c.model_name, "variant": c.variant, "version": __version__,
            "weights": {"repo": c.weights_repo, "revision": c.revision, "license": v.license},
            **self.backend.info,
            "modes": modes, "default_mode": c.default_mode,
            "limits": {"max_image_tokens": c.max_image_tokens, "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), "max_crops": c.max_crops, "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": c.max_pages, "max_pages": c.max_pages,
                       "batch": 1},
            "buckets": {"prefill_rows": list(c.pre_buckets)},
            "defaults": defaults,
            "tasks": dict(self.tasks), "formats": list(FORMATS),
            "ngram_presets": {k: NGRAM_PRESETS[k].as_dict() for k in v.ngram_presets},
            "stop_token_ids": [FE.EOS_ID],
            "performance": f"the package's model card (https://huggingface.co/{v.package_repo}): accuracy vs the "
                           "official float32 model and the measured speed on one p150",
        }


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


def _int_list(v: Any, name: str) -> List[int]:
    """A list of ints, a JSON array string or a comma-separated string (form fields)."""
    if isinstance(v, str):
        s = v.strip()
        if not s:
            return []
        if s.startswith("["):
            try:
                v = json.loads(s)
            except ValueError:
                raise InputError(f"{name}: a JSON array of token ids") from None
        else:
            v = [x for x in s.split(",") if x.strip()]
    if not isinstance(v, (list, tuple)):
        raise InputError(f"{name}: a list of token ids")
    if len(v) > MAX_WHITELIST:
        raise InputError(f"{name}: at most {MAX_WHITELIST} token ids")
    return [_int(x, name) for x in v]