File size: 26,297 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the family's other two models on the fake backend (no device, no weights): DeepSeek-OCR-2 (the two
task presets of its model card, its modes) and Unlimited-OCR-2 (one or more pages per request, task ``parse``, the
``<PAGE>`` / ``<BLOCK>`` / ``<FORK>`` output formats, multi-page HTTP bodies), and the shipped samples' per-model
entries against the official goldens (when the development assets are present):

    TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_dsocr/tests/test_host_variants.py

``DSOCR_TEST_CPU=1`` also runs the CPU reference of Unlimited-OCR-2 on one page (needs the checkpoint; minutes).
"""

from __future__ import annotations

import base64
import json
import os
import sys

import pytest

CODE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, CODE)

from tt_dsocr import config as C  # noqa: E402
from tt_dsocr import frontend as FE  # noqa: E402
from tt_dsocr import postprocess as PP  # noqa: E402
from tt_dsocr.api import ByteTokenizer, DeepSeekOcr, InputError, infer_task, parse_messages_multi  # noqa: E402
from tt_dsocr.backends import FakeBackend  # noqa: E402
from tt_dsocr.tests._paths import ASSETS, GOLDEN, MODELS  # noqa: E402

SAMPLES = os.path.join(CODE, "tt_dsocr", "samples")
LINE = os.path.join(SAMPLES, "line_en", "sample.png")          # 709 x 64
FORMULA = os.path.join(SAMPLES, "formula_quad", "sample.png")  # 500 x 130
TABLE = os.path.join(SAMPLES, "table_sales", "sample.png")     # 790 x 376
UOCR_TOK = os.path.join(MODELS["unlimited-ocr-2"], "tokenizer.json")
OCR2_TOK = os.path.join(MODELS["deepseek-ocr-2"], "tokenizer.json")
UOCR_GOLDEN_RAW = ("<PAGE><BLOCK>equation[184, 243, 812, 760]<FORK>$$\nx = \\frac {- b \\pm \\sqrt {b ^ {2} - 4 a c}}"
                   "{2 a}\n$$")


def _model(variant, **env):
    return DeepSeekOcr.from_config(C.resolve_config(dict({"DSOCR_BACKEND": "fake", "DSOCR_VARIANT": variant}, **env)))


@pytest.fixture(scope="module")
def ocr2():
    m = _model("deepseek-ocr-2")
    yield m
    m.close()


@pytest.fixture(scope="module")
def uocr():
    m = _model("unlimited-ocr-2")
    yield m
    m.close()


# ---------------------------------------------------------------------------------------------- DeepSeek-OCR-2
def test_ocr2_tasks_and_modes(ocr2):
    r = ocr2.ocr(TABLE)
    assert (r.task, r.mode, r.output_format, r.finish_reason) == ("markdown", "gundam", "markdown", "stop")
    assert r.raw_text == FakeBackend.MARKDOWN and r.text == PP.to_markdown(FakeBackend.MARKDOWN)
    assert r.image["grid"] == [2, 1] and r.image["image_tokens"] == 257 + 2 * 144 == 545   # the golden's count
    assert r.image["image_size"] == 768 and r.image["max_crops"] == 6 and "pages" not in r.image
    r = ocr2.ocr(LINE, task="free", mode="base")
    assert r.text == FakeBackend.TEXT and r.output_format == "raw" and r.image["image_tokens"] == 257
    r = ocr2.ocr(FORMULA, task="free", mode="small")
    assert r.image["image_tokens"] == 145 and r.image["image_size"] == 768     # 12 x 12 + separator
    # the OCR-1 presets the OCR-2 card does not document: refused by name, accepted as a free prompt
    for kw in ({"task": "ocr"}, {"task": "figure"}, {"task": "describe"}, {"task": "locate", "ref": "x"},
               {"ref": "the date"}, {"mode": "tiny"}, {"mode": "large"}, {"max_crops": 7}, {"task": "parse"}):
        with pytest.raises(InputError):
            ocr2.prepare(LINE, **kw)
    r = ocr2.ocr(LINE, prompt="<image>\nParse the figure.")
    assert r.task == "prompt" and r.output_format == "raw"
    assert infer_task("Free OCR.", "deepseek-ocr-2") == "free" and infer_task("OCR this image.", "deepseek-ocr-2") \
        == "prompt" and infer_task("<image>\n<|grounding|>OCR this image.") == "ocr"
    with pytest.raises(InputError):
        ocr2.prepare([LINE, LINE])
    with pytest.raises(InputError):
        ocr2.prepare(images=[LINE, FORMULA])


def test_ocr2_info(ocr2):
    i = ocr2.info
    assert i["variant"] == "deepseek-ocr-2" and i["weights"] == {
        "repo": "deepseek-ai/DeepSeek-OCR-2", "revision": "aaa02f3811945a91062062994c5c4a3f4c0af2b0",
        "license": "Apache-2.0"}
    assert i["tasks"] == {"markdown": "<image>\n<|grounding|>Convert the document to markdown.",
                          "free": "<image>\nFree OCR."}
    assert list(i["modes"]) == ["gundam", "base", "small"] and i["modes"]["gundam"]["image_tokens"] == [257, 1121]
    assert i["defaults"]["task"] == "markdown" and i["defaults"]["ngram_preset"] == "hf"
    assert i["defaults"]["format"] == {"markdown": "markdown", "free": "raw", "prompt": "raw"}
    assert i["limits"]["max_pages"] == 1 and i["limits"]["images_per_request"] == 1
    assert os.path.isfile(os.path.join(CODE, "tt_dsocr", "licenses", C.VARIANTS["deepseek-ocr-2"].license_file))


@pytest.mark.skipif(not os.path.isfile(OCR2_TOK), reason="the DeepSeek-OCR-2 tokenizer is not available")
def test_ocr2_prompt_ids_match_the_goldens():
    tok = FE.Tokenizer(OCR2_TOK)
    images = {d["name"]: d for d in json.load(open(os.path.join(ASSETS, "images.json")))} \
        if os.path.isfile(os.path.join(ASSETS, "images.json")) else {}
    n = 0
    for case in ("formula_quad__gundam", "line_en__base", "table_sales__gundam"):
        mp = os.path.join(GOLDEN["deepseek-ocr-2"], case, "meta.json")
        if not os.path.isfile(mp):
            continue
        meta = json.load(open(mp))
        img = os.path.join(SAMPLES, meta["name"], "sample.png")
        p = FE.prepare(FE.OCR2, tok, img, meta["prompt_text"], meta["mode"])
        assert p.ids == meta["input_ids"] and p.image_pos[1] - p.image_pos[0] == meta["n_image_tokens"], case
        n += 1
    if not n:
        pytest.skip(f"no deepseek-ocr-2 goldens under {GOLDEN['deepseek-ocr-2']} ({len(images)} images)")


# ---------------------------------------------------------------------------------------------- Unlimited-OCR-2
def test_uocr_one_page(uocr):
    r = uocr.ocr(FORMULA)
    assert (r.task, r.mode, r.output_format, r.finish_reason) == ("parse", "gundam", "markdown", "stop")
    assert r.raw_text == FakeBackend.PAGE.format(n=1)
    assert r.text == "# Fake Page 1\n\n" + FakeBackend.TEXT + "\n\n![](images/page_0_0.jpg)\n\n$$\nx = 1\n$$"
    assert r.image["n_pages"] == 1 and r.image["image_tokens"] == 273 and r.image["max_crops"] == 16
    assert [x["label"] for x in r.refs] == ["title", "text", "image", "equation"] and r.refs[0]["page"] == 1
    assert r.refs[0]["boxes"] == [[int(52 / 999 * 500), int(40 / 999 * 130), int(948 / 999 * 500),
                                   int(98 / 999 * 130)]]
    assert r.sampling["no_repeat_ngram_size"] == 0                   # the official infer: no n-gram rule
    # BOS + <PAGE> + image tokens + the instruction (bytes of the fake tokenizer)
    assert r.usage["prompt_tokens"] == 1 + 1 + 273 + len("Multi page parsing.".encode())
    r = uocr.ocr(LINE, max_crops=16)
    assert r.image["grid"] == [11, 1] and r.image["image_tokens"] == 273 + 111 * 10     # 11 tiles: > OCR-1's 9
    r = uocr.ocr(LINE, mode="base")
    assert r.image["image_tokens"] == 273 and r.mode == "base"


def test_uocr_pages(uocr):
    r = uocr.ocr([TABLE, FORMULA], output_format="json")
    assert r.mode == "base" and r.image["n_pages"] == 2 and r.image["image_tokens"] == 2 * 273   # the auto policy
    assert [p["width"] for p in r.image["pages"]] == [790, 500] and r.image["width"] == 790
    assert r.raw_text == FakeBackend.PAGE.format(n=1) + FakeBackend.PAGE.format(n=2)
    pages = r.json["pages"]
    assert [p["page"] for p in pages] == [1, 2] and [(p["width"], p["height"]) for p in pages] == [(790, 376),
                                                                                                   (500, 130)]
    assert pages[1]["blocks"][3] == {"label": "equation", "kind": "block", "box_norm": [52, 820, 948, 960],
                                     "box": [int(52 / 999 * 500), int(820 / 999 * 130), int(948 / 999 * 500),
                                             int(960 / 999 * 130)], "text": "$$\nx = 2\n$$"}
    assert r.json["text"].startswith("<!-- page 1 -->\n\n# Fake Page 1") and "<!-- page 2 -->" in r.json["text"]
    assert "![](images/page_1_0.jpg)" in r.json["text"] and len(r.refs) == 8 and json.loads(r.text) == r.json
    r2 = uocr.ocr(images=[TABLE, FORMULA], mode="gundam", output_format="raw")
    assert r2.mode == "gundam" and r2.text == r.raw_text and r2.image["pages"][0]["grid"] == [2, 1]
    s = uocr.ocr_stream([TABLE, FORMULA, LINE])
    deltas = list(s)
    assert "".join(deltas) == s.result.raw_text and s.result.raw_text.count("<PAGE>") == 3
    # BOS + 3 x (<PAGE> + 273) + the instruction
    assert s.result.usage["prompt_tokens"] == 1 + 3 * 274 + len(b"Multi page parsing.")


def test_uocr_prompts_and_refusals(uocr):
    r = uocr.ocr([TABLE, FORMULA], prompt="Free OCR.")
    assert r.task == "prompt" and r.output_format == "raw"
    assert r.raw_text == "<PAGE>Fake reply to: Free OCR. (page 1)<PAGE>Fake reply to: Free OCR. (page 2)"
    p = uocr.prepare([TABLE, FORMULA], prompt="<PAGE><image><PAGE><image>Multi page parsing.")
    assert p.task == "parse" and p.fe.prompt == "<PAGE><image><PAGE><image>Multi page parsing."
    p = uocr.prepare([TABLE, FORMULA], prompt="<image>Multi page parsing.")     # one <image>: expanded per page
    assert p.task == "parse" and p.fe.prompt == "<PAGE><image><PAGE><image>Multi page parsing."
    assert uocr.prepare(FORMULA, task="parse").fe.prompt == "<PAGE><image>Multi page parsing."
    assert infer_task("Multi page parsing.", "unlimited-ocr-2") == "parse"
    assert infer_task("<PAGE><image>Multi page parsing.", "unlimited-ocr-2") == "parse"
    assert infer_task("Free OCR.", "unlimited-ocr-2") == "prompt"
    for kw in ({"task": "markdown"}, {"task": "locate", "ref": "x"}, {"ref": "x"}, {"mode": "tiny"},
               {"prompt": "<image>\nFree OCR."},                              # no <PAGE>: the non-marker fallback
               {"prompt": "<image><image><image>x"}, {"ngram_preset": "hf"}, {"ngram_preset": "vllm"},
               {"max_crops": 17}, {"images": [FORMULA]}):
        with pytest.raises(InputError):
            uocr.prepare(FORMULA, **kw)
    with pytest.raises(InputError, match="DSOCR_MAX_PAGES"):
        uocr.prepare([FORMULA] * 9)
    with pytest.raises(InputError):
        uocr.prepare([])
    with pytest.raises(InputError):
        uocr.prepare([FORMULA, None])


def test_uocr_ngram_presets(uocr):
    assert uocr.prepare(FORMULA).ngram.size == 0
    one = uocr.prepare(FORMULA, ngram_preset="sglang").ngram
    two = uocr.prepare([FORMULA, LINE], ngram_preset="sglang").ngram
    assert (one.size, one.window, two.size, two.window) == (35, 128, 35, 1024)   # the README's SGLang client
    ng = uocr.prepare(FORMULA, no_repeat_ngram_size=20, ngram_window=100).ngram
    assert (ng.size, ng.window) == (20, 100)


def test_uocr_limits():
    m = _model("unlimited-ocr-2", DSOCR_MAX_PAGES="2", DSOCR_MODES="gundam")
    with pytest.raises(InputError, match="DSOCR_MAX_PAGES"):
        m.prepare([FORMULA] * 3)
    p = m.prepare([FORMULA, FORMULA])        # several pages in Gundam (base is not enabled): fits the buckets
    assert p.mode == "gundam" and p.image_info["image_tokens"] == 2 * 273
    with pytest.raises(InputError, match="prefill bucket"):
        m.prepare([LINE, LINE])              # 2 x (1383 + 1) rows > the largest bucket (one Gundam page)
    m.close()


def test_uocr_info(uocr):
    i = uocr.info
    assert i["variant"] == "unlimited-ocr-2" and i["weights"]["repo"] == "baidu/Unlimited-OCR-2"
    assert i["weights"]["license"] == "MIT" and i["tasks"] == {"parse": "Multi page parsing."}
    assert list(i["modes"]) == ["gundam", "base"] and i["modes"]["gundam"]["image_tokens"] == [273, 2033]
    assert i["limits"]["max_pages"] == 8 and i["limits"]["kv_positions"] == 16384
    assert i["limits"]["max_prompt_rows"] == 2816 and i["buckets"]["prefill_rows"][-1] == 2816
    d = i["defaults"]
    assert (d["task"], d["mode"], d["mode_several_pages"], d["ngram_preset"], d["page_count_guard"],
            d["max_page_tokens"], d["max_crops"]) == ("parse", "gundam", "base", "off", True, 20000, 16)
    assert set(i["ngram_presets"]) == {"off", "sglang"} and i["engine"]["dec"] == "fake"
    lic = os.path.join(CODE, "tt_dsocr", "licenses", C.VARIANTS["unlimited-ocr-2"].license_file)
    text = open(lic).read()   # the official code repository's MIT License (the HF repository has no LICENSE file)
    assert text.startswith("MIT License") and "Copyright (c) 2026 Baidu" in text
    note = open(os.path.join(CODE, "tt_dsocr", "licenses", "NOTICE-Unlimited-OCR-2.txt")).read()
    assert "license: mit" in note and "no LICENSE file" in note and "github.com/baidu/Unlimited-OCR" in note


def test_byte_tokenizer_tags():
    t = ByteTokenizer()
    ids = t.encode("a<PAGE>b<BLOCK>x[1, 2, 3, 4]<FORK>c<CHILD>")
    assert ids[1] == 128827 and 128828 in ids and 128829 in ids and ids[-1] == 128830
    assert t.decode(ids) == "a<PAGE>b<BLOCK>x[1, 2, 3, 4]<FORK>c<CHILD>"
    assert t.decode(ids, skip_special_tokens=True) == "a<PAGE>b<BLOCK>x[1, 2, 3, 4]<FORK>c<CHILD>"   # non-special
    assert t.encode("Multi page parsing.") == [b + 3 for b in b"Multi page parsing."]


@pytest.mark.skipif(not os.path.isfile(UOCR_TOK), reason="the Unlimited-OCR-2 tokenizer is not available")
def test_uocr_real_tokenizer_prompt_ids():
    """The official prompt ids (UOCR2_NOTES 2.2): one page [0, <PAGE>, IMG x n, 37460, 4366, 76466, 16]; N base pages
    274 N + 5 rows."""
    tok = FE.Tokenizer(UOCR_TOK)
    m = DeepSeekOcr(C.resolve_config({"DSOCR_BACKEND": "fake", "DSOCR_VARIANT": "unlimited-ocr-2"}),
                    FakeBackend(C.resolve_config({"DSOCR_VARIANT": "unlimited-ocr-2"}), tok), tok)
    p = m.prepare(FORMULA, mode="base")
    assert p.fe.ids == [0, 128827] + [128815] * 273 + [37460, 4366, 76466, 16]
    p = m.prepare([FORMULA, LINE, TABLE])
    assert len(p.fe.ids) == 274 * 3 + 5 and p.fe.ids.count(128827) == 3 and p.mode == "base"
    assert tok.decode([128827, 128828, 128829]) == "<PAGE><BLOCK><FORK>"
    gm = os.path.join(GOLDEN["unlimited-ocr-2"], "formula_quad__gundam", "meta.json")
    if os.path.isfile(gm):
        meta = json.load(open(gm))
        assert m.prepare(FORMULA).fe.ids == meta["input_ids"]
        assert tok.decode(meta["gen_ids"][:-1]) == meta["text"] == UOCR_GOLDEN_RAW


@pytest.mark.skipif(os.environ.get("DSOCR_TEST_CPU") != "1" or not os.path.isfile(UOCR_TOK),
                    reason="DSOCR_TEST_CPU=1 and the checkpoint run the CPU reference backend")
def test_uocr_cpu_backend_formula():
    m = DeepSeekOcr.from_config(C.resolve_config({"DSOCR_BACKEND": "cpu", "DSOCR_VARIANT": "unlimited-ocr-2",
                                                  "DSOCR_MODEL_DIR": MODELS["unlimited-ocr-2"],
                                                  "DSOCR_MAX_CONTEXT": "4096", "DSOCR_MAX_PAGES": "1"}))
    s = m.ocr_stream(FORMULA, output_format="raw", max_new_tokens=60)
    deltas = list(s)
    r = s.result
    assert r.finish_reason == "stop" and "".join(deltas) == r.raw_text == UOCR_GOLDEN_RAW


# ---------------------------------------------------------------------------------------------- post-processing
def test_uocr_postprocess_golden():
    t, obj, refs = PP.apply_format_pages(UOCR_GOLDEN_RAW, "json", [(500, 130)])
    assert obj["text"] == "$$\nx = \\frac {- b \\pm \\sqrt {b ^ {2} - 4 a c}}{2 a}\n$$"
    (page,) = obj["pages"]
    assert page["blocks"] == [{"label": "equation", "kind": "block", "box_norm": [184, 243, 812, 760],
                               "box": [92, 31, 406, 98], "text": obj["text"]}]
    assert refs == [{"label": "equation", "boxes": [[92, 31, 406, 98]], "boxes_norm": [[184, 243, 812, 760]],
                     "page": 1}]
    assert PP.apply_format_pages(UOCR_GOLDEN_RAW, "raw", [(500, 130)])[0] == UOCR_GOLDEN_RAW
    assert PP.apply_format_pages(UOCR_GOLDEN_RAW + PP.EOS_TEXT, "markdown", [(500, 130)])[0] == obj["text"]
    with pytest.raises(ValueError):
        PP.apply_format_pages(UOCR_GOLDEN_RAW, "xml", [(500, 130)])


def test_uocr_postprocess_rules():
    raw = ("ignored<PAGE><BLOCK>title[52, 40, 948, 98]<FORK># T<BLOCK>image[100, 200, 300, 400]<FORK>"
           "<CHILD>caption[5, 6, 7, 8]<FORK>Fig. 1<PAGE><BLOCK>text[0, 0, 999, 999]<FORK>a <|ref|>x<|/ref|><|det|>"
           "[[1, 2, 3, 4]]<|/det|>b <|det|>image[1, 2, 3, 4]<|/det|><BLOCK>bad head<FORK>zz"
           "<BLOCK>eval[__import__('os')]<FORK>yy<PAGE>no image page")
    pages = PP.parse_pages(raw, [(1000, 1000), (999, 999)])
    assert [p["page"] for p in pages] == [1, 2, 3] and pages[2]["width"] is None
    assert pages[0]["text"] == "# T\n\n![](images/page_0_0.jpg)\n\nFig. 1"
    assert pages[0]["blocks"][2]["kind"] == "child" and pages[0]["blocks"][2]["box"] == [5, 6, 7, 8]
    b = pages[1]["blocks"]
    assert b[0]["text"] == "a b ![](images/page_1_0.jpg)" and b[0]["box"] == [0, 0, 999, 999]
    assert b[1]["label"] == "bad head" and "error" in b[1] and b[1]["box"] is None and b[1]["text"] == "zz"
    assert b[2]["label"] == "eval" and b[2]["box_norm"] is None and "error" in b[2]      # never evaluated
    assert pages[2]["blocks"] == [{"label": None, "kind": "block", "box_norm": None, "box": None,
                                   "text": "no image page"}]
    md = PP.pages_markdown(pages)
    assert md.startswith("<!-- page 1 -->\n\n# T") and "<!-- page 3 -->\n\nno image page" in md
    assert not any(t in md for t in PP.UOCR_TAGS)
    assert [r["page"] for r in PP.page_refs(pages)] == [1, 1, 1, 2]
    assert PP.split_pages("no tags at all") == ["no tags at all"] and PP.split_pages("x<PAGE>a<PAGE>b") == ["a", "b"]
    assert PP.parse_box("[[1, 2, 3, 4], [5, 6, 7, 8]]") == [[1, 2, 3, 4], [5, 6, 7, 8]]
    assert PP.parse_box("[1, 2, 3]") is None and PP.parse_box("[1, 2, 3, 4]") == [[1, 2, 3, 4]]
    # titles carry their heading level (the device's answer on a report page, 2026-12-02)
    p = PP.parse_page("<BLOCK>title<LEVEL1>[92, 65, 738, 96]<FORK>Quarterly Report\n<BLOCK>title<LEVEL2>[93, 149, 262, "
                      "169]<FORK>1. Summary\n<BLOCK>text[91, 177, 886, 278]<FORK>Body", 0, 1000, 1000)
    assert [(b["label"], b.get("level"), b["box_norm"], "error" in b) for b in p["blocks"]] == [
        ("title", 1, [92, 65, 738, 96], False), ("title", 2, [93, 149, 262, 169], False),
        ("text", None, [91, 177, 886, 278], False)]
    assert p["text"] == "Quarterly Report\n\n1. Summary\n\nBody"
    assert PP.parse_page("<BLOCK>title<LEVEL>[1, 2, 3, 4]<FORK>x", 0, 10, 10)["blocks"][0].get("error")


# ---------------------------------------------------------------------------------------------- the HTTP server
@pytest.fixture(scope="module")
def uclient():
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient

    from tt_dsocr.server.app import create_app

    app = create_app()
    app.state.dsocr.config_loader = lambda: C.resolve_config({"DSOCR_BACKEND": "fake",
                                                              "DSOCR_VARIANT": "unlimited-ocr-2"})
    with TestClient(app) as c:
        yield c


def _b(path):
    return open(path, "rb").read()


def _url(path):
    return "data:image/png;base64," + base64.b64encode(_b(path)).decode()


def test_uocr_server_routes(uclient):
    i = uclient.get("/info").json()
    assert i["variant"] == "unlimited-ocr-2" and i["max_pages"] == 8 and i["limits"]["max_pages"] == 8
    assert i["package"] == "changh95/Unlimited-OCR-2" and "multi-page" in i["task"]
    assert i["configuration"]["DSOCR_ENGINE"] == "vis=ttnn,pre=ttnn,dec=ttnn" and "image_url parts" in i["api"]["chat"]
    r = uclient.post("/ocr", files=[("file", ("a.png", _b(TABLE))), ("file", ("b.png", _b(FORMULA)))],
                     data={"format": "raw"})
    assert r.status_code == 200, r.text
    j = r.json()
    assert j["raw_text"].count("<PAGE>") == 2 and j["image"]["n_pages"] == 2 and j["mode"] == "base"
    assert j["refs"][-1]["page"] == 2
    j2 = uclient.post("/ocr", json={"images": [_url(TABLE), base64.b64encode(_b(FORMULA)).decode()],
                                    "format": "raw"}).json()
    assert j2["text"] == j["text"]
    body = {"messages": [{"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": _url(TABLE)}}, {"type": "image_url", "image_url": _url(FORMULA)},
        {"type": "text", "text": "<PAGE><image><PAGE><image>Multi page parsing."}]}]}
    j3 = uclient.post("/v1/chat/completions", json=body).json()
    assert j3["choices"][0]["message"]["content"] == j["raw_text"] and j3["image"]["n_pages"] == 2
    one = uclient.post("/ocr", files={"file": ("a.png", _b(FORMULA))}).json()
    assert one["format"] == "markdown" and one["task"] == "parse" and one["mode"] == "gundam"
    assert one["text"].startswith("# Fake Page 1") and "<PAGE>" not in one["text"]
    raw = uclient.post("/ocr?format=json", content=_b(FORMULA), headers={"content-type": "image/png"}).json()
    assert raw["json"]["pages"][0]["blocks"][0]["label"] == "title"
    with uclient.stream("POST", "/ocr", files=[("file", ("a.png", _b(TABLE))), ("file", ("b.png", _b(LINE)))],
                        data={"stream": "true"}) as r:
        lines = [ln for ln in r.iter_lines() if ln.startswith("data: ")]
    evs = [json.loads(x[6:]) for x in lines[:-1]]
    done = evs[-1]
    assert done["type"] == "done" and "".join(e["text"] for e in evs if e["type"] == "delta") == done["raw_text"]
    assert done["json"] is None and "<!-- page 2 -->" in done["text"]


@pytest.mark.parametrize("kind,payload", [
    ("files", [("file", ("a.png", b"x"))] * 9), ("json", {"images": []}), ("json", {"images": "abc"}),
    ("json", {"image": "x", "images": ["y"]}), ("json", {"images": ["@@@"]}), ("form", {"images": "x"}),
    ("form", {"task": "markdown"}), ("form", {"mode": "tiny"}), ("form", {"ngram_preset": "vllm"}),
    ("form", {"prompt": "<image>\nFree OCR."}), ("form", {"task": "locate", "ref": "x"}),
    ("json", {"images": [_url(FORMULA)] * 9})])
def test_uocr_server_refusals(uclient, kind, payload):
    if kind == "files":
        r = uclient.post("/ocr", files=payload)
    elif kind == "form":
        r = uclient.post("/ocr", files={"file": ("a.png", _b(FORMULA))}, data=payload)
    else:
        r = uclient.post("/ocr", json=payload)
    assert r.status_code == 400, r.text


def test_uocr_chat_refusals(uclient):
    nine = {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": _url(FORMULA)}] * 9}]}
    assert uclient.post("/v1/chat/completions", json=nine).status_code == 400
    none = {"messages": [{"role": "user", "content": "Multi page parsing."}]}
    r = uclient.post("/v1/chat/completions", json=none)
    assert r.status_code == 400 and "one image_url part per page" in r.json()["detail"]
    imgs, text = parse_messages_multi([{"role": "user", "content": [
        {"type": "image_url", "image_url": "a"}, {"type": "text", "text": "t"},
        {"type": "image_url", "image_url": {"url": "b"}}]}], 8)
    assert imgs == ["a", "b"] and text == "t"
    with pytest.raises(InputError):
        parse_messages_multi([{"role": "user", "content": [{"type": "image_url", "image_url": "a"}] * 3}], 2)


def test_ocr2_server_refuses_two_images():
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient

    from tt_dsocr.server.app import create_app

    app = create_app()
    app.state.dsocr.config_loader = lambda: C.resolve_config({"DSOCR_BACKEND": "fake",
                                                              "DSOCR_VARIANT": "deepseek-ocr-2"})
    with TestClient(app) as c:
        i = c.get("/info").json()
        assert i["max_pages"] == 1 and set(i["tasks"]) == {"markdown", "free"} and "DeepSeek-OCR-2" in i["task"]
        r = c.post("/ocr", files=[("file", ("a.png", _b(LINE))), ("file", ("b.png", _b(LINE)))])
        assert r.status_code == 400 and "one image per request" in r.json()["detail"]
        assert c.post("/ocr", json={"images": [_url(LINE), _url(LINE)]}).status_code == 400
        assert c.post("/ocr", json={"images": [_url(LINE)], "task": "free"}).json()["text"] == FakeBackend.TEXT
        for f in ({"task": "ocr"}, {"task": "locate", "ref": "x"}, {"mode": "tiny"}, {"task": "parse"}):
            assert c.post("/ocr", files={"file": ("a.png", _b(LINE))}, data=f).status_code == 400, f
        j = c.post("/ocr", files={"file": ("a.png", _b(TABLE))}).json()
        assert j["task"] == "markdown" and j["image"]["image_tokens"] == 545


# ---------------------------------------------------------------------------------------------- samples
def test_sample_entries_per_model():
    for name in ("line_en", "formula_quad", "table_sales"):
        s = json.load(open(os.path.join(SAMPLES, name, "sample.json")))
        for variant, ov in s["variants"].items():
            v = C.VARIANTS[variant]
            assert ov["task"] in v.tasks and ov["mode"] in [m[0] for m in v.modes], (name, variant)
            assert ov["prompt"] == C.TASK_PROMPTS[variant][ov["task"]], (name, variant)
            gm = os.path.join(GOLDEN[variant], f"{name}__{ov['mode']}", "meta.json")
            if os.path.isfile(gm) and ov["expected_text"]:
                assert PP.strip_eos(json.load(open(gm))["text"]) == ov["expected_text"], (name, variant)
    # the smoke test picks each model's entry
    sys.path.insert(0, os.path.join(CODE, "tt_dsocr", "server"))
    import importlib.util

    spec = importlib.util.spec_from_file_location("dsocr_smoke", os.path.join(CODE, "tt_dsocr", "server",
                                                                              "smoke_test.py"))
    smoke = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(smoke)
    assert {s["name"]: s["mode"] for s in smoke.samples("deepseek-ocr")} == {
        "formula_quad": "tiny", "line_en": "gundam", "table_sales": "gundam"}
    assert {s["name"]: (s["task"], s["mode"]) for s in smoke.samples("deepseek-ocr-2")} == {
        "formula_quad": ("free", "gundam"), "line_en": ("free", "base"), "table_sales": ("markdown", "gundam")}
    assert {s["task"] for s in smoke.samples("unlimited-ocr-2")} == {"parse"}