# SPDX-License-Identifier: Apache-2.0 # The grounding regex and the Markdown clean-up rules follow DeepSeek-OCR's ``infer(save_results=True)`` # (deepseek-ai/DeepSeek-OCR modeling_deepseekocr.py: ``re_match``, the ``![](images/.jpg)`` placeholders, # ``\coloneqq`` / ``\eqqcolon``; DeepSeek, MIT); written anew. Unlike the official code, box lists are parsed with a # strict regular expression + ``ast.literal_eval`` (the official code calls ``eval`` on model output) and no image crops # or drawings are written. """Output formats of a DeepSeek-OCR result (host only, standard library). Grounded output (``<|grounding|>`` prompts) carries layout / text boxes as ``<|ref|>label<|/ref|><|det|>[[x1, y1, x2, y2], ...]<|/det|>`` with coordinates 0..999 relative to the image. * ``raw``: the decoded model output (special tokens kept, the EOS removed), unchanged. * ``markdown``: the official ``save_results`` text: stripped; ``<|ref|>image<|/ref|><|det|>..<|/det|>`` regions become ``![](images/.jpg)`` placeholders (i = the image region's index); the other ref / det groups are removed and ``\\coloneqq`` -> ``:=``, ``\\eqqcolon`` -> ``=:`` (applied as the official code does: once per removed group, so only when there is one). For the ``ocr`` task (``<|grounding|>OCR this image.``, whose labels are the recognized text) a removed group is replaced by its label instead (``keep_labels``): the official rule would drop the text. * ``json``: ``{"text": , "refs": [{"label", "boxes" (pixels of the original image, the official ``int(v / 999 * size)``), "boxes_norm" (0..999 as the model wrote them)}], "image": {"width", "height"}}``. Unlimited-OCR-2 (:func:`apply_format_pages`; written anew: the official ``_uocr_save_results`` only splits the output at ```` and applies the rules above per page, which leave its own layout tags in place) writes one ```` per input page, each page a sequence of layout blocks ``label[x1, y1, x2, y2]content`` (box 0..999 of that page; ```` opens a nested block the same way), e.g. ``equation[184, 243, 812, 760]$$ ... $$``: * ``raw``: unchanged (every tag kept). * ``markdown``: per page the block contents without the tags, blocks separated by a blank line; ``image`` blocks become ``![](images/page_

_.jpg)`` placeholders (the official file names: p = 0-based page index, i = the image block's index on the page); grounding groups of the DeepSeek-OCR kind are cleaned as above. Several pages are separated by ```` lines (k = 1-based page number); text before the first ```` is dropped (the official split). * ``json``: ``{"text": , "pages": [{"page" (1-based), "width", "height", "text", "blocks": [{"label", "kind" ("block" | "child"), "box" (pixels of that page), "box_norm" (0..999), "text"}]}], "refs"}`` (``refs``: every block with a box, as ``{"label", "boxes", "boxes_norm", "page"}``). """ from __future__ import annotations import ast import json import re from typing import Any, Dict, List, Optional, Sequence, Tuple FORMATS = ("raw", "markdown", "json") EOS_TEXT = "<|end▁of▁sentence|>" REF_RE = re.compile(r"(<\|ref\|>(.*?)<\|/ref\|><\|det\|>(.*?)<\|/det\|>)", re.DOTALL) _NUM = r"\s*-?\d+(?:\.\d+)?\s*" _BOX = r"\[" + _NUM + r"(?:," + _NUM + r"){3}\]" BOXES_RE = re.compile(r"^\s*\[\s*" + _BOX + r"(?:\s*,\s*" + _BOX + r")*\s*,?\s*\]\s*$") MAX_DET_CHARS = 20000 # a <|det|> payload longer than this is not parsed (a degenerate output) #: the det-only grounding form (schift-ocr-1-beta / Unlimited-OCR v1 write every block this way; the official #: ``re_match`` of those models accepts it besides the ref / det pair): ``<|det|>label [x1, y1, x2, y2]<|/det|>content`` DET_LABEL_RE = re.compile(r"(<\|det\|>\s*([A-Za-z_][\w-]*)\s*(\[[^\]]+\])\s*<\|/det\|>)", re.DOTALL) ONE_BOX_RE = re.compile(r"^\s*" + _BOX + r"\s*$") def strip_eos(text: str) -> str: while text.endswith(EOS_TEXT): text = text[:-len(EOS_TEXT)] return text def re_match(text: str) -> Tuple[List[Tuple[str, str, str]], List[str], List[str]]: """The official ``re_match`` (DeepSeek-OCR's ref / det pairs, then the det-only blocks of schift-ocr-1-beta / Unlimited-OCR v1): (all (whole, label, det) matches, whole image matches, whole other matches). DeepSeek-OCR never writes the det-only form (its ``<|det|>`` holds a box list right away), so its results are unchanged.""" matches = REF_RE.findall(text) + DET_LABEL_RE.findall(text) images = [m[0] for m in matches if m[1].strip() == "image" or "<|ref|>image<|/ref|>" in m[0]] other = [m[0] for m in matches if not (m[1].strip() == "image" or "<|ref|>image<|/ref|>" in m[0])] return matches, images, other def parse_boxes(det: str, single_ok: bool = False) -> Optional[List[List[float]]]: """``[[x1, y1, x2, y2], ...]`` -> a list of 4-number lists, or None when it is not exactly that (never eval).""" if single_ok and isinstance(det, str) and len(det) <= MAX_DET_CHARS and ONE_BOX_RE.match(det): det = "[" + det.strip() + "]" # one box ``[x1, y1, x2, y2]`` (the det-only form; the official code wraps it) if not isinstance(det, str) or len(det) > MAX_DET_CHARS or not BOXES_RE.match(det): return None try: v = ast.literal_eval(det.strip()) except (ValueError, SyntaxError, MemoryError, RecursionError): return None if not isinstance(v, (list, tuple)) or not all(isinstance(b, (list, tuple)) and len(b) == 4 for b in v): return None return [[(int(x) if float(x).is_integer() else float(x)) for x in b] for b in v] def to_pixels(box: List[float], width: int, height: int) -> List[int]: """0..999 -> pixels of the original image, as the official ``draw_bounding_boxes``: ``int(v / 999 * size)``.""" x1, y1, x2, y2 = box return [int(x1 / 999 * width), int(y1 / 999 * height), int(x2 / 999 * width), int(y2 / 999 * height)] def extract_refs(text: str, width: int, height: int) -> List[Dict[str, Any]]: """Every ref / det group of ``text``, in order: ``{"label", "boxes", "boxes_norm"}`` (+ ``"error"`` when the box list does not parse; its boxes are then empty).""" out = [] text = strip_eos(text or "") groups = sorted([(m.start(), m.group(2), m.group(3), False) for m in REF_RE.finditer(text)] + [(m.start(), m.group(2), m.group(3), True) for m in DET_LABEL_RE.finditer(text)]) for _pos, label, det, single in groups: bn = parse_boxes(det, single_ok=single) r: Dict[str, Any] = {"label": label} if bn is None: r.update(boxes=[], boxes_norm=[], error="the box list is not [[x1, y1, x2, y2], ...]") else: r.update(boxes=[to_pixels(b, width, height) for b in bn], boxes_norm=bn) out.append(r) return out def to_markdown(text: str, keep_labels: bool = False) -> str: """The official ``save_results`` text (see the module docstring).""" outputs = strip_eos(text or "").strip() _matches, images, other = re_match(outputs) for idx, m in enumerate(images): outputs = outputs.replace(m, "![](images/" + str(idx) + ".jpg)\n") for m in other: rm = REF_RE.match(m) repl = rm.group(2) if (keep_labels and rm) else "" outputs = outputs.replace(m, repl).replace("\\coloneqq", ":=").replace("\\eqqcolon", "=:") return outputs def apply_format(raw: str, task: str, fmt: str, image_wh: Optional[Tuple[int, int]] ) -> Tuple[str, Optional[Dict[str, Any]], List[Dict[str, Any]]]: """(text in ``fmt``, the JSON object (format ``json``) or None, the parsed ref / det groups).""" w, h = image_wh or (0, 0) refs = extract_refs(raw, w, h) if fmt == "raw": return raw, None, refs md = to_markdown(raw, keep_labels=(task == "ocr")) if fmt == "markdown": return md, None, refs if fmt == "json": obj = {"text": md, "refs": refs, "image": {"width": w, "height": h}} blocks = det_blocks(raw, w, h) if blocks: obj["blocks"] = blocks return json.dumps(obj, ensure_ascii=False, indent=2), obj, refs raise ValueError(f"format {fmt!r}: one of {FORMATS}") def det_blocks(text: str, width: int, height: int) -> List[Dict[str, Any]]: """The det-only blocks (schift-ocr-1-beta) in order: ``{"label", "boxes", "boxes_norm", "text"}``, ``text`` = the content up to the next block (stripped; image blocks have none). [] when the output has no det-only block.""" text = strip_eos(text or "") ms = list(DET_LABEL_RE.finditer(text)) out = [] for i, m in enumerate(ms): end = ms[i + 1].start() if i + 1 < len(ms) else len(text) bn = parse_boxes(m.group(3), single_ok=True) b: Dict[str, Any] = {"label": m.group(2)} if bn is None: b.update(boxes=[], boxes_norm=[], error="the box is not [x1, y1, x2, y2]") else: b.update(boxes=[to_pixels(x, width, height) for x in bn], boxes_norm=bn) b["text"] = text[m.end():end].strip() out.append(b) return out # ================================================================================================ Unlimited-OCR-2 PAGE_TAG, BLOCK_TAG, FORK_TAG, CHILD_TAG = "", "", "", "" UOCR_TAGS = (PAGE_TAG, BLOCK_TAG, FORK_TAG, CHILD_TAG) _SPLIT_RE = re.compile(r"(|)") _HEAD_RE = re.compile(r"^\s*([A-Za-z_][\w\- ]{0,63}?)\s*(\[.{0,4000}\])\s*$", re.DOTALL) _ONE_BOX_RE = re.compile(r"^\s*" + _BOX + r"\s*$") #: the det-only grounding form the official ``re_match`` also accepts: ``<|det|>label[x1, y1, x2, y2]<|/det|>`` _DET_LABEL_RE = re.compile(r"(<\|det\|>\s*([A-Za-z_][\w-]*)\s*(\[[^\]]+\])\s*<\|/det\|>)", re.DOTALL) def split_pages(text: str) -> List[str]: """The official split: the parts after each ```` (text before the first one is dropped), or the whole text when it has no ````.""" t = strip_eos(text or "") return t.split(PAGE_TAG)[1:] if PAGE_TAG in t else [t] def parse_box(spec: str) -> Optional[List[List[float]]]: """``[x1, y1, x2, y2]`` or ``[[x1, y1, x2, y2], ...]`` -> a list of boxes, or None (never eval).""" if not isinstance(spec, str) or len(spec) > MAX_DET_CHARS: return None if _ONE_BOX_RE.match(spec): b = parse_boxes("[" + spec.strip() + "]") return b return parse_boxes(spec) def _clean_grounding(text: str, page_idx: int, img_idx: List[int]) -> str: """DeepSeek-OCR-style grounding groups inside a block: image groups -> placeholders, others removed.""" groups = [(m[0], m[1]) for m in REF_RE.findall(text)] + [(m[0], m[1]) for m in _DET_LABEL_RE.findall(text)] for whole, label in groups: if label.strip() == "image": text = text.replace(whole, f"![](images/page_{page_idx}_{img_idx[0]}.jpg)\n", 1) img_idx[0] += 1 else: text = text.replace(whole, "", 1) return text def parse_page(page_text: str, page_idx: int, width: Optional[int], height: Optional[int]) -> Dict[str, Any]: """One page of Unlimited-OCR-2 output -> ``{"page", "width", "height", "text", "blocks"}`` (``page_idx`` 0-based; ``width`` / ``height`` None: no input page of that index, so no pixel boxes).""" parts = _SPLIT_RE.split(page_text or "") blocks: List[Dict[str, Any]] = [] md: List[str] = [] img_idx = [0] segs = [(None, parts[0])] + [(parts[i], parts[i + 1]) for i in range(1, len(parts) - 1, 2)] for tag, seg in segs: if tag is None and not seg.strip(): continue label, boxes_norm, body, err = None, None, seg, None if FORK_TAG in seg: head, body = seg.split(FORK_TAG, 1) m = _HEAD_RE.match(head) if m: label = m.group(1).strip() boxes_norm = parse_box(m.group(2)) if boxes_norm is None: err = "the box is not [x1, y1, x2, y2]" else: label = head.strip() or None err = "the block header is not label[x1, y1, x2, y2]" for t in UOCR_TAGS: body = body.replace(t, "") body = _clean_grounding(body, page_idx, img_idx).strip() b: Dict[str, Any] = {"label": label, "kind": "child" if tag == CHILD_TAG else "block"} if boxes_norm: b["box_norm"] = boxes_norm[0] if len(boxes_norm) == 1 else boxes_norm px = [to_pixels(x, width, height) for x in boxes_norm] if width and height else None b["box"] = (px[0] if len(px) == 1 else px) if px else None else: b["box_norm"], b["box"] = None, None if err: b["error"] = err b["text"] = body blocks.append(b) piece = body if label == "image": piece = (f"![](images/page_{page_idx}_{img_idx[0]}.jpg)" + ("\n" + body if body else "")) img_idx[0] += 1 if piece: md.append(piece) return {"page": page_idx + 1, "width": width, "height": height, "text": "\n\n".join(md), "blocks": blocks} def parse_pages(raw: str, pages_wh: Sequence[Tuple[int, int]]) -> List[Dict[str, Any]]: """Every page of an Unlimited-OCR-2 output (``pages_wh``: the input pages' (width, height), in order).""" out = [] for i, pt in enumerate(split_pages(raw)): w, h = pages_wh[i] if i < len(pages_wh) else (None, None) out.append(parse_page(pt, i, w, h)) return out def pages_markdown(pages: List[Dict[str, Any]]) -> str: if len(pages) == 1: return pages[0]["text"] return "\n\n".join(f"\n\n{p['text']}".rstrip() for p in pages) def page_refs(pages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: refs = [] for p in pages: for b in p["blocks"]: if b.get("box_norm") is None: continue nb = b["box_norm"] if isinstance(b["box_norm"][0], list) else [b["box_norm"]] pb = (b["box"] if isinstance(b["box"][0], list) else [b["box"]]) if b.get("box") else [] refs.append({"label": b["label"], "boxes": pb, "boxes_norm": nb, "page": p["page"]}) return refs def apply_format_pages(raw: str, fmt: str, pages_wh: Sequence[Tuple[int, int]] ) -> Tuple[str, Optional[Dict[str, Any]], List[Dict[str, Any]]]: """Unlimited-OCR-2: (text in ``fmt``, the JSON object (format ``json``) or None, the boxed blocks as refs).""" if fmt not in FORMATS: raise ValueError(f"format {fmt!r}: one of {FORMATS}") pages = parse_pages(raw, pages_wh) refs = page_refs(pages) if fmt == "raw": return raw, None, refs md = pages_markdown(pages) if fmt == "markdown": return md, None, refs obj = {"text": md, "pages": pages, "refs": refs} return json.dumps(obj, ensure_ascii=False, indent=2), obj, refs