File size: 8,090 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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the front end (no device): image-token counts, the Gundam crop grid, prompt normalization, the prompt
ids of the official ``infer`` (the workspace goldens: ``prepare()`` must reproduce their ``input_ids`` exactly) and
the detokenization of the official outputs.

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

Tests that need the checkpoint's tokenizer (``DSOCR_MODEL_DIR`` or the workspace copy) or the goldens
(``DSOCR_ASSETS``) skip when they are absent.
"""

from __future__ import annotations

import glob
import json
import os
import sys

import numpy as np
import pytest

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

from tt_dsocr import frontend as FE  # noqa: E402
from tt_dsocr import postprocess as PP  # noqa: E402
from tt_dsocr.api import ByteTokenizer, Detokenizer, infer_task  # noqa: E402
from tt_dsocr.tests._paths import ASSETS, GOLDEN, MODELS  # noqa: E402

MODEL = os.environ.get("DSOCR_MODEL_DIR") or MODELS["deepseek-ocr"]
HAVE_TOK = os.path.isfile(os.path.join(MODEL, "tokenizer.json"))
SAMPLES = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "samples")
GOLDEN_CASES = sorted(glob.glob(os.path.join(GOLDEN["deepseek-ocr"], "*", "meta.json")))
IMAGES = {}
if os.path.isfile(os.path.join(ASSETS, "images.json")):
    IMAGES = {e["name"]: e for e in json.load(open(os.path.join(ASSETS, "images.json")))}


@pytest.fixture(scope="module")
def tok():
    if not HAVE_TOK:
        pytest.skip(f"the DeepSeek-OCR tokenizer is not available ({MODEL})")
    return FE.Tokenizer(MODEL)


def _png_size(path):
    from PIL import Image

    with Image.open(path) as im:
        return im.size


# ---------------------------------------------------------------------------------------------- counts, grids
def test_image_token_counts():
    v = FE.OCR1
    counts = {m: FE.image_token_count(v, b, s, c, (1, 1)) for m, b, s, c in v.modes}
    assert counts == {"tiny": 73, "small": 111, "base": 273, "large": 421, "gundam": 273}
    assert FE.image_token_count(v, 1024, 640, True, (3, 3)) == 273 + 31 * 30
    assert FE.image_token_count(v, 1024, 640, True, (9, 1)) == 1183
    assert FE.image_token_count(v, 1024, 640, True, (1, 9)) == 1263
    v2 = FE.OCR2
    assert FE.image_token_count(v2, 1024, 768, True, (1, 1)) == 257
    assert FE.image_token_count(v2, 1024, 768, True, (3, 2)) == 257 + 6 * 144


@pytest.mark.parametrize("wh,grid", [((709, 64), (9, 1)), ((900, 260), (3, 1)), ((64, 709), (1, 9)),
                                     ((1240, 1754), (2, 3)), ((1920, 1080), (4, 2)), ((800, 800), (2, 2))])
def test_crop_grid(wh, grid):
    g = FE.crop_grid(wh[0], wh[1], 2, 9, 640)
    assert g == grid, (wh, g)
    assert 2 <= g[0] * g[1] <= 9


def test_prepare_layout_byte_tokenizer():
    tk = ByteTokenizer()
    line = os.path.join(SAMPLES, "line_en", "sample.png")
    p = FE.prepare(FE.OCR1, tk, line, "Free OCR.", "gundam")
    assert p.prompt == "<image>\nFree OCR." and p.grid == (9, 1) and p.n_tiles == 9
    s, e = p.image_pos
    assert p.ids[0] == FE.BOS_ID and e - s == 1183 and set(p.ids[s:e]) == {FE.IMAGE_TOKEN_ID}
    assert tk.decode(p.ids[1:s]) == "" and tk.decode(p.ids[e:]) == "\nFree OCR."
    assert p.global_px.shape == (3, 1024, 1024) and p.tiles_px.shape == (9, 3, 640, 640)
    assert p.global_px.dtype == np.float32 and -1.0 <= p.global_px.min() and p.global_px.max() <= 1.0
    p = FE.prepare(FE.OCR1, tk, line, "<image>\nFree OCR.", "tiny")
    assert p.image_pos[1] - p.image_pos[0] == 73 and p.tiles_px is None and p.global_px.shape == (3, 512, 512)
    small = os.path.join(SAMPLES, "formula_quad", "sample.png")        # 500 x 130 <= 640: Gundam without tiles
    p = FE.prepare(FE.OCR1, tk, small, "Free OCR.", "gundam")
    assert p.tiles_px is None and p.grid == (1, 1) and p.image_pos[1] - p.image_pos[0] == 273
    p = FE.prepare(FE.OCR1, tk, line, "Free OCR.", "gundam", min_crops=1, max_crops=2)
    assert p.grid == (2, 1) and p.n_tiles == 2


def test_normalize_prompt_and_tasks():
    assert FE.normalize_prompt("  Free OCR. ") == "<image>\nFree OCR."
    assert FE.normalize_prompt("<image>\nFree OCR.") == "<image>\nFree OCR."
    with pytest.raises(ValueError):
        FE.normalize_prompt("<image><image>")
    assert FE.TASKS == {
        "markdown": "<image>\n<|grounding|>Convert the document to markdown.",
        "ocr": "<image>\n<|grounding|>OCR this image.",
        "free": "<image>\nFree OCR.",
        "figure": "<image>\nParse the figure.",
        "describe": "<image>\nDescribe this image in detail.",
        "locate": "<image>\nLocate <|ref|>{ref}<|/ref|> in the image.",
    }
    for k, v in FE.TASKS.items():
        assert infer_task(v.format(ref="the title")) == k
    assert infer_task("Free OCR.") == "free" and infer_task(" <image>\nFree OCR. ") == "free"
    assert infer_task("What is this?") == "prompt" and infer_task("<image><image>") == "prompt"


# ---------------------------------------------------------------------------------------------- the real tokenizer
def test_special_tokens(tok):
    for s, i in (("<image>", 128815), ("<|ref|>", 128816), ("<|/ref|>", 128817), ("<|det|>", 128818),
                 ("<|/det|>", 128819), ("<|grounding|>", 128820), ("<td>", 128821), ("</td>", 128822)):
        assert tok.token_id(s) == i, s
    assert tok.decode([0, 1]) == "<|begin▁of▁sentence|>" + PP.EOS_TEXT
    ids = tok.encode(FE.TASKS["markdown"].split(FE.IMAGE_TOKEN)[1])
    assert 128820 in ids and tok.decode(ids) == "\n<|grounding|>Convert the document to markdown."


@pytest.mark.parametrize("meta_path", GOLDEN_CASES or [None], ids=[os.path.basename(os.path.dirname(p))
                                                                 for p in GOLDEN_CASES] or ["none"])
def test_golden_input_ids(tok, meta_path):
    if meta_path is None:
        pytest.skip(f"no deepseek-ocr goldens under {GOLDEN['deepseek-ocr']}")
    meta = json.load(open(meta_path))
    img = IMAGES.get(meta["name"])
    if img is None or not os.path.isfile(os.path.join(ASSETS, img["file"])):
        pytest.skip(f"golden image {meta['name']} is missing")
    path = os.path.join(ASSETS, img["file"])
    p = FE.prepare(FE.OCR1, tok, path, meta["prompt_text"], meta["mode"])
    assert p.ids == meta["input_ids"]
    assert p.image_pos[1] - p.image_pos[0] == meta["n_image_tokens"]
    assert (p.base_size, p.image_size, p.crop) == (meta["base_size"], meta["image_size"], meta["crop_mode"])
    assert list(p.image_wh) == meta["image_wh"] == list(_png_size(path))
    if meta["crop_mode"]:
        assert list(p.grid) == meta["spatial_crop"][0]
    # the official output decodes to the golden text (special tokens kept); the streaming deltas join to it
    gen = meta.get("gen_ids")
    if gen:
        assert tok.decode(gen) == meta["text"]
        body = gen[:-1] if gen[-1] == FE.EOS_ID else gen
        d = Detokenizer(tok)
        deltas = [d.push(t) for t in body] + [d.flush()]
        assert "".join(deltas) == PP.strip_eos(meta["text"]) and all("�" not in x for x in deltas)


def test_golden_samples_match_the_shipped_samples():
    """The shipped samples are the golden test images (same bytes) and carry the golden outputs."""
    import hashlib

    for name in ("line_en", "formula_quad", "table_sales"):
        s = json.load(open(os.path.join(SAMPLES, name, "sample.json")))
        data = open(os.path.join(SAMPLES, name, s["file"]), "rb").read()
        assert hashlib.sha256(data).hexdigest() == s["sha256"] and len(data) == s["bytes"]
        assert s["task"] in FE.TASKS and s["mode"] in [m[0] for m in FE.OCR1.modes]
        assert FE.TASKS[s["task"]] == s["prompt"]
        golden = os.path.join(GOLDEN["deepseek-ocr"], f"{name}__{s['mode']}", "meta.json")
        if os.path.isfile(golden) and s["expected_text"]:
            meta = json.load(open(golden))
            assert meta["prompt_text"] == s["prompt"]
            assert PP.strip_eos(meta["text"]) == s["expected_text"], name