# SPDX-License-Identifier: Apache-2.0 # The markdown clean-up (``clean_content``, ``clean_repeated_content``, ``normalize_inline_formula`` and the per-label # formatting of ``format_markdown``) is adapted from the official GLM-OCR SDK (github.com/zai-org/GLM-OCR, # glmocr/postprocess/result_formatter.py and glmocr/utils/result_postprocess_utils.py, Copyright 2026 Zhipu AI, # Apache-2.0), reduced to one region whose label is the request's task (no layout analysis in this package). """Output formats of an OCR result (host only, standard library): * ``raw``: the decoded model output, unchanged. * ``markdown``: the SDK's clean-up of one region: repeated punctuation / repeated content removed, inline formulas normalized; ``formula`` output wrapped as a ``$$ ... $$`` display block (the model already writes it so); ``table`` output kept as the model's HTML ```` (Markdown renders HTML); ``text`` lines separated as Markdown paragraphs and leading bullets / enumerations normalized. * ``json``: the output parsed as JSON (information extraction): Markdown code fences (```` ```json ````) and text around the outermost object / array are tolerated; a parse failure is reported, not raised. """ from __future__ import annotations import json import re from collections import Counter from typing import Any, Optional, Tuple FORMATS = ("raw", "markdown", "json") EXTRACT_PREFACE = "请按下列JSON格式输出图中信息:\n" # ------------------------------------------------------------------------------------------------ prompts def schema_prompt(schema: Any) -> str: """The model card's information-extraction prompt: the Chinese preface + the JSON schema, pretty-printed with 4 spaces (as the card's example). ``schema`` is a dict / list or a JSON string.""" if isinstance(schema, str): try: schema = json.loads(schema) except ValueError as e: raise ValueError(f"schema is not valid JSON: {e}") from None if not isinstance(schema, (dict, list)) or not schema: raise ValueError("schema must be a non-empty JSON object (the fields to extract, values \"\")") return EXTRACT_PREFACE + json.dumps(schema, ensure_ascii=False, indent=4) # ------------------------------------------------------------------------------------------------ SDK clean-up def _find_consecutive_repeat(s: str, min_unit_len: int = 10, min_repeats: int = 10) -> Optional[str]: n = len(s) if n < min_unit_len * min_repeats: return None max_unit_len = n // min_repeats if max_unit_len < min_unit_len: return None pattern = re.compile(r"(.{" + str(min_unit_len) + "," + str(max_unit_len) + r"}?)\1{" + str(min_repeats - 1) + ",}", re.DOTALL) m = pattern.search(s) if m: return s[:m.start()] + m.group(1) return None def clean_repeated_content(content: str, min_len: int = 10, min_repeats: int = 10, line_threshold: int = 10) -> str: """Cut a degenerate repetition loop (a unit of >= 10 characters repeated >= 10 times, or one line making up >= 80 % of >= 10 lines): the SDK's ``clean_repeated_content``.""" stripped = content.strip() if not stripped: return content if len(stripped) > min_len * min_repeats: r = _find_consecutive_repeat(stripped, min_unit_len=min_len, min_repeats=min_repeats) if r is not None: return r lines = [ln.strip() for ln in content.split("\n") if ln.strip()] total = len(lines) if total >= line_threshold and lines: common, count = Counter(lines).most_common(1)[0] if count >= line_threshold and count / total >= 0.8: for i, ln in enumerate(lines): if ln == common: consecutive = sum(1 for j in range(i, min(i + 3, len(lines))) if lines[j] == common) if consecutive >= 3: original = content.split("\n") non_empty = 0 for idx, orig in enumerate(original): if orig.strip(): non_empty += 1 if non_empty == i + 1: return "\n".join(original[:idx + 1]) break return content _INLINE_FORMULA = re.compile(r"(? str: """``$ x $`` -> ``$x$``, with a space between surrounding letters / digits and the delimiters.""" if "$" not in content: return content parts, last = [], 0 for m in _INLINE_FORMULA.finditer(content): formula = m.group(1).strip() if not formula: continue start, end = m.start(), m.end() before = content[last:start] if before and before[-1].isalnum(): before += " " parts.append(before) parts.append(f"${formula}$") if end < len(content) and content[end].isalnum(): parts.append(" ") last = end if not parts: return content parts.append(content[last:]) return "".join(parts) def clean_content(content: Optional[str]) -> str: """The SDK's ``_clean_content``: strip literal ``\\t`` at the ends, collapse runs of >= 3 ``.`` / ``·`` / ``_`` to three, remove repetition loops of long outputs, normalize inline formulas.""" if content is None: return "" content = re.sub(r"^(\\t)+", "", content).lstrip() content = re.sub(r"(\\t)+$", "", content).rstrip() content = re.sub(r"(\.)\1{2,}", r"\1\1\1", content) content = re.sub(r"(·)\1{2,}", r"\1\1\1", content) content = re.sub(r"(_)\1{2,}", r"\1\1\1", content) content = re.sub(r"(\\_)\1{2,}", r"\1\1\1", content) if len(content) >= 2048: content = clean_repeated_content(content) content = normalize_inline_formula(content) return content.strip() def format_markdown(content: str, task: str) -> str: """One region of the SDK's Markdown output, its label being the task (``text`` / ``table`` / ``formula``; any other task (a free prompt, ``extract``) gets the plain clean-up).""" content = content or "" if task == "table": c = content.strip() return c if c.startswith("") else clean_content(content) if task == "formula": c = content.strip() c = c if c.startswith("$$") and c.endswith("$$") else clean_content(content) if c.startswith(("$$", "\\[", "\\(")): c = c[2:].strip() if c.endswith(("$$", "\\]", "\\)")): c = c[:-2].strip() return "$$\n" + c + "\n$$" c = clean_content(content) if task != "text": return c if c.startswith("```") and not c.endswith("```"): c = c + "\n```" if c.startswith(("·", "•", "* ")): c = "- " + c[1:].lstrip() m = re.match(r"^(\(|\()(\d+|[A-Za-z])(\)|\))(.*)$", c) if m: _, sym, _, rest = m.groups() c = f"({sym}) {rest.lstrip()}" m = re.match(r"^(\d+|[A-Za-z])(\.|\)|\))(.*)$", c) if m: sym, sep, rest = m.groups() sep = ")" if sep == ")" else sep c = f"{sym}{sep} {rest.lstrip()}" return re.sub(r"(? Tuple[Any, Optional[str]]: """(parsed value, None) or (None, error message). Tolerates code fences and text around the outermost JSON object / array.""" s = (text or "").strip() candidates = [] m = _FENCE.search(s) if m: candidates.append(m.group(1).strip()) candidates.append(s) for open_, close in (("{", "}"), ("[", "]")): i, j = s.find(open_), s.rfind(close) if 0 <= i < j: candidates.append(s[i:j + 1]) err = "empty output" for c in candidates: if not c: continue try: return json.loads(c, parse_constant=_no_constant), None except ValueError as e: err = str(e) return None, f"the output is not valid JSON ({err})" def apply_format(raw: str, task: str, fmt: str) -> Tuple[str, Any, Optional[str]]: """(text, parsed JSON or None, JSON error or None) of one output in format ``fmt``.""" if fmt == "raw": return raw, None, None if fmt == "markdown": return format_markdown(raw, task), None, None if fmt == "json": val, err = parse_json_output(raw) return (json.dumps(val, ensure_ascii=False, indent=2) if err is None else raw), val, err raise ValueError(f"format {fmt!r}: one of {FORMATS}")