Download code/tt_dsocr/frontend.py from changh95/schift-ocr-1-beta: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/changh95/schift-ocr-1-beta/resolve/main/code/tt_dsocr/frontend.py
- Command line
-
hf download hf://changh95/schift-ocr-1-beta/code/tt_dsocr/frontend.py
-
curl -L -o frontend.py https://huggingface.co/changh95/schift-ocr-1-beta/resolve/main/code/tt_dsocr/frontend.py
12.6 kB
| # 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)) | |
| 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)) | |
| 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) | |
| 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}) | |