File size: 12,604 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
# SPDX-License-Identifier: Apache-2.0
"""Host front end of the DeepSeek-OCR family (CPU only; Pillow + numpy + tokenizers, no transformers).

A clean-room re-implementation of the input building of the official ``infer`` (DeepSeek-OCR / DeepSeek-OCR-2
``modeling_deepseekocr*.py``): prompt -> ids with the ``<image>`` placeholder expanded to the image tokens of the
chosen resolution mode, the global view (``ImageOps.pad`` / ``resize``) and the Gundam tiles (``dynamic_preprocess``),
normalised to ``(x / 255 - 0.5) / 0.5``. Image resampling is Pillow's own (the official code uses Pillow too), so the
pixels are bit-exact.
"""

from __future__ import annotations

import io
import math
import os
from dataclasses import dataclass, field
from typing import List, Optional, Sequence, Tuple

import numpy as np

IMAGE_TOKEN = "<image>"
IMAGE_TOKEN_ID = 128815
BOS_ID, EOS_ID = 0, 1
PAD_COLOR = (127, 127, 127)  # tuple(int(x * 255) for x in (0.5, 0.5, 0.5))


@dataclass(frozen=True)
class Variant:
    """Per-model constants. ``newline``: image_newline after every token row (OCR-1); ``tile``: Gundam tile size;
    ``crop_min / crop_max``: dynamic_preprocess defaults."""
    name: str
    newline: bool
    tile: int
    crop_min: int
    crop_max: int
    modes: Tuple[Tuple[str, int, int, bool], ...]  # (mode, base_size, image_size, crop)


OCR1 = Variant("deepseek-ocr", True, 640, 2, 9, (
    ("tiny", 512, 512, False), ("small", 640, 640, False), ("base", 1024, 1024, False),
    ("large", 1280, 1280, False), ("gundam", 1024, 640, True)))
OCR2 = Variant("deepseek-ocr-2", False, 768, 2, 6, (
    ("gundam", 1024, 768, True), ("base", 1024, 1024, False), ("small", 768, 768, False)))
# Unlimited-OCR-2 (baidu): DeepSeek-OCR's DeepEncoder and token layout per page, up to 16 Gundam tiles; a request is
# one or more pages ("<PAGE><image>" per page); one page defaults to Gundam, several to Base (the official auto policy)
UOCR2 = Variant("unlimited-ocr-2", True, 640, 2, 16, (("gundam", 1024, 640, True), ("base", 1024, 1024, False)))
# schift-ocr-1-beta (schift-io; a Korean fine-tune of baidu/Unlimited-OCR v1): DeepSeek-OCR's DeepEncoder, token layout
# and input building (one image, ``infer``), its dynamic_preprocess allowing 2..32 tiles
SCHIFT = Variant("schift-ocr-1-beta", True, 640, 2, 32, (("gundam", 1024, 640, True), ("base", 1024, 1024, False)))
VARIANTS = {v.name: v for v in (OCR1, OCR2, UOCR2, SCHIFT)}
PAGE_TOKEN, PAGE_TOKEN_ID = "<PAGE>", 128827
UOCR2_DEFAULT_PROMPT = "Multi page parsing."

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.",
}


def mode_params(v: Variant, mode: str) -> Tuple[int, int, bool]:
    for m, b, s, c in v.modes:
        if m == mode:
            return b, s, c
    raise ValueError(f"unknown mode {mode!r} for {v.name}: {[m[0] for m in v.modes]}")


# ------------------------------------------------------------------------------------------------ images
def load_image(data) -> "Image.Image":
    """bytes / path / PIL image -> RGB PIL image with the EXIF orientation applied (official ``load_image``)."""
    from PIL import Image, ImageOps

    if isinstance(data, (bytes, bytearray)):
        im = Image.open(io.BytesIO(data))
    elif isinstance(data, str):
        im = Image.open(data)
    else:
        im = data
    try:
        im = ImageOps.exif_transpose(im)
    except Exception:  # noqa: BLE001 (the official falls back to the raw image)
        pass
    return im.convert("RGB")


def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
    best_ratio_diff = float("inf")
    best_ratio = (1, 1)
    area = width * height
    for ratio in target_ratios:
        target_aspect_ratio = ratio[0] / ratio[1]
        ratio_diff = abs(aspect_ratio - target_aspect_ratio)
        if ratio_diff < best_ratio_diff:
            best_ratio_diff = ratio_diff
            best_ratio = ratio
        elif ratio_diff == best_ratio_diff:
            if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
                best_ratio = ratio
    return best_ratio


def crop_grid(width: int, height: int, min_num: int, max_num: int, image_size: int) -> Tuple[int, int]:
    """The (columns, rows) grid of ``dynamic_preprocess`` (official tie-break order: sorted by i * j, stable over the
    set iteration order is irrelevant because ties on (diff, area rule) resolve to the last candidate in sort order;
    the set is sorted by area only, so equal-area candidates keep Python's set order: replicated exactly below)."""
    aspect_ratio = width / height
    target_ratios = set((i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1)
                        if i * j <= max_num and i * j >= min_num)
    target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
    return find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size)


def tiles_of(image, grid: Tuple[int, int], image_size: int) -> list:
    cols, rows = grid
    tw, th = image_size * cols, image_size * rows
    resized = image.resize((tw, th))
    out = []
    for i in range(cols * rows):
        box = ((i % cols) * image_size, (i // cols) * image_size, ((i % cols) + 1) * image_size,
               ((i // cols) + 1) * image_size)
        out.append(resized.crop(box))
    return out


def to_pixels(im) -> np.ndarray:
    """PIL RGB -> float32 [3, H, W] = (x / 255 - 0.5) / 0.5 (torchvision ToTensor + Normalize, fp32)."""
    a = np.asarray(im, dtype=np.uint8).astype(np.float32) / np.float32(255.0)
    a = (a - np.float32(0.5)) / np.float32(0.5)
    return np.ascontiguousarray(a.transpose(2, 0, 1))


@dataclass
class Prepared:
    variant: str
    mode: str
    base_size: int
    image_size: int
    crop: bool
    ids: List[int]                 # full prompt ids (BOS ... image tokens ... text)
    image_pos: Tuple[int, int]     # [start, end) of the image tokens in ids
    global_px: np.ndarray          # [3, S, S] fp32 (S = base_size in crop mode, else image_size)
    tiles_px: Optional[np.ndarray]  # [n, 3, t, t] fp32 or None
    grid: Tuple[int, int]          # (columns, rows) of the tiles ((1, 1) = none)
    image_wh: Tuple[int, int]
    prompt: str
    extra: dict = field(default_factory=dict)

    @property
    def n_tiles(self) -> int:
        return 0 if self.tiles_px is None else int(self.tiles_px.shape[0])


def image_token_count(v: Variant, base_size: int, image_size: int, crop: bool, grid: Tuple[int, int]) -> int:
    nl = 1 if v.newline else 0
    if crop:
        qb = math.ceil((base_size // 16) / 4)
        n = (qb + nl) * qb + 1
        if grid[0] > 1 or grid[1] > 1:
            q = math.ceil((image_size // 16) / 4)
            n += (q * grid[0] + nl) * (q * grid[1])
        return n
    q = math.ceil((image_size // 16) / 4)
    return (q + nl) * q + 1


class Tokenizer:
    """tokenizers backend of the official LlamaTokenizerFast (byte-level BPE, no normaliser)."""

    def __init__(self, path: str):
        from tokenizers import Tokenizer as T

        p = os.path.join(path, "tokenizer.json") if os.path.isdir(path) else path
        self.tk = T.from_file(p)

    def encode(self, text: str) -> List[int]:
        return self.tk.encode(text, add_special_tokens=False).ids

    def decode(self, ids: Sequence[int], skip_special_tokens: bool = False) -> str:
        return self.tk.decode(list(int(i) for i in ids), skip_special_tokens=skip_special_tokens)

    def token_id(self, s: str) -> Optional[int]:
        return self.tk.token_to_id(s)


def normalize_prompt(text: str, sep: str = "\n") -> str:
    """The 'plain' template of ``format_messages``: the message stripped; then the prompt stripped. Adds the
    ``<image>`` placeholder at the front when absent (one image per request), followed by ``sep`` (the variant's
    ``image_sep``: a newline for DeepSeek-OCR's prompt form, nothing for schift-ocr-1-beta's ``<image>document
    parsing.``)."""
    t = text.strip()
    if IMAGE_TOKEN not in t:
        t = IMAGE_TOKEN + sep + t
    if t.count(IMAGE_TOKEN) != 1:
        raise ValueError("the prompt must contain exactly one <image> placeholder")
    return t.strip()


def _views(v: Variant, image, mode: str, min_crops: Optional[int], max_crops: Optional[int]):
    """-> (global view pixels, tiles pixels or None, grid, image (w, h), image tokens) of one image."""
    from PIL import ImageOps

    base_size, image_size, crop = mode_params(v, mode)
    image = load_image(image)
    w, h = image.size
    tiles = None
    grid = (1, 1)
    if crop:
        if not (w <= v.tile and h <= v.tile):
            mn = v.crop_min if min_crops is None else int(min_crops)
            mx = v.crop_max if max_crops is None else int(max_crops)
            grid = crop_grid(w, h, mn, mx, v.tile)
            if grid[0] > 1 or grid[1] > 1:
                tiles = np.stack([to_pixels(t) for t in tiles_of(image, grid, v.tile)])
        gview = ImageOps.pad(image, (base_size, base_size), color=PAD_COLOR)
    else:
        im = image.resize((image_size, image_size)) if image_size <= v.tile else image
        gview = ImageOps.pad(im, (image_size, image_size), color=PAD_COLOR)
    return to_pixels(gview), tiles, grid, (w, h), image_token_count(v, base_size, image_size, crop, grid)


def prepare(v: Variant, tok: Tokenizer, image, prompt: str, mode: str = "gundam", min_crops: Optional[int] = None,
            max_crops: Optional[int] = None) -> Prepared:
    if v.name == UOCR2.name:
        return prepare_pages(v, tok, [image], prompt, mode, min_crops, max_crops)
    base_size, image_size, crop = mode_params(v, mode)
    prompt = normalize_prompt(prompt)
    before, after = prompt.split(IMAGE_TOKEN)
    gpx, tiles, grid, wh, n_img = _views(v, image, mode, min_crops, max_crops)
    ids = [BOS_ID] + tok.encode(before)
    start = len(ids)
    ids += [IMAGE_TOKEN_ID] * n_img
    end = len(ids)
    ids += tok.encode(after)
    return Prepared(v.name, mode, base_size, image_size, crop, ids, (start, end), gpx, tiles, grid, wh, prompt)


def uocr2_prompt(prompt: str, n_pages: int) -> str:
    """The official ``infer`` prompt rule: no ``<image>`` -> ``"<PAGE><image>" * n + prompt`` (default prompt
    "Multi page parsing."); one ``<image>`` with several pages -> expanded per page; else one per page, as is."""
    prompt = prompt or UOCR2_DEFAULT_PROMPT
    n_ph = prompt.count(IMAGE_TOKEN)
    if n_ph == 0:
        return (PAGE_TOKEN + IMAGE_TOKEN) * n_pages + prompt
    if n_pages > 1 and n_ph == 1:
        return prompt.replace(IMAGE_TOKEN, (PAGE_TOKEN + IMAGE_TOKEN) * n_pages)
    if n_ph != n_pages:
        raise ValueError(f"the prompt has {n_ph} <image> placeholders but {n_pages} images")
    return prompt


def prepare_pages(v: Variant, tok: Tokenizer, images: Sequence, prompt: str = "", mode: Optional[str] = None,
                  min_crops: Optional[int] = None, max_crops: Optional[int] = None) -> Prepared:
    """Unlimited-OCR-2 input building (the official ``_uocr_build_inputs`` + ``infer`` prompt rule): BOS, per page the
    text before its ``<image>`` (``<PAGE>``) + its image tokens, then the instruction. ``mode`` None = the official
    auto policy (Gundam for one page, Base for several). ``extra["pages"]``: per page {global_px, tiles_px, grid,
    image_wh, image_pos}; the top-level view fields are those of page 0."""
    images = list(images)
    if not images:
        raise ValueError("no image")
    mode = mode or ("gundam" if len(images) == 1 else "base")
    base_size, image_size, crop = mode_params(v, mode)
    prompt = uocr2_prompt(prompt.strip() if prompt else "", len(images))
    splits = prompt.split(IMAGE_TOKEN)
    ids = [BOS_ID]
    pages = []
    for seg, im in zip(splits, images):
        ids += tok.encode(seg)
        gpx, tiles, grid, wh, n_img = _views(v, im, mode, min_crops, max_crops)
        start = len(ids)
        ids += [IMAGE_TOKEN_ID] * n_img
        pages.append({"global_px": gpx, "tiles_px": tiles, "grid": grid, "image_wh": wh, "image_pos": (start, len(ids))})
    ids += tok.encode(splits[-1])
    p0 = pages[0]
    return Prepared(v.name, mode, base_size, image_size, crop, ids, (p0["image_pos"][0], pages[-1]["image_pos"][1]),
                    p0["global_px"], p0["tiles_px"], p0["grid"], p0["image_wh"], prompt, {"pages": pages})