File size: 8,966 Bytes
aa204f5 | 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 | # 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 ``<table>`` (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"(?<!\$)\$\s*((?:[^$\\]|\\.)+?)\s*\$(?!\$)")
def normalize_inline_formula(content: str) -> 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("<table") and c.endswith("</table>") 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"(?<!\n)\n(?!\n)", "\n\n", c)
# ------------------------------------------------------------------------------------------------ JSON
_FENCE = re.compile(r"```(?:json|JSON)?\s*\n?(.*?)\n?\s*```", re.DOTALL)
def _no_constant(name: str):
raise ValueError(f"{name} is not JSON") # NaN / Infinity: Python's json accepts them, strict JSON does not
def parse_json_output(text: str) -> 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}")
|