Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(server): add LightOnOCR-3 Markdown output profile
svonava849a6a08ad76
diff --git a/packages/sie_server/models/lightonai__LightOnOCR-3-4B.yaml b/packages/sie_server/models/lightonai__LightOnOCR-3-4B.yamlindex f75dfc024..56e4fa6a4 100644--- a/packages/sie_server/models/lightonai__LightOnOCR-3-4B.yaml+++ b/packages/sie_server/models/lightonai__LightOnOCR-3-4B.yaml@@ -33,6 +33,10 @@ tasks:# untrimmed. The upstream client repairs escaped math dollars by default. Upstream's published# olmOCR-bench scores also drop header/footer/page-number blocks and apply its Markdown# post-processing.+# The explicit `markdown` profile defaults to `grounding` and applies that published conversion:+# omit margin/aside blocks and leading unmarked text, repair escaped math dollars, then PP3.+# This is a lossy output policy; footnotes remain and all-margin pages can return empty text.+# Native opt-in: set loadtime `output_postprocess: lightonocr3_markdown` and send `grounding`.## Serving: the default profile runs the checkpoint on SGLang (sglang-vision-extract bundle) with# continuous batching, no system prompt, the chat template's enable_thinking=False, and only the@@ -50,7 +54,7 @@ profiles:compute_precision: bfloat16adapter_path: sie_server.adapters.sglang_vision_extract.adapter:SGLangVisionExtractAdapteradapter_options:- loadtime:+ loadtime: &sglang_loadtimemem_fraction_static: 0.85served_model_name: lightonai/LightOnOCR-3-4Btrust_remote_code: false@@ -69,6 +73,14 @@ profiles:runtime:max_new_tokens: 12288num_beams: 1+ markdown:+ extends: default+ adapter_options:+ # Profile inheritance replaces loadtime, so retain every engine/sampling option.+ loadtime:+ <<: *sglang_loadtime+ default_prompt: grounding+ output_postprocess: lightonocr3_markdowntransformers:max_batch_tokens: 16384compute_precision: bfloat16diff --git a/packages/sie_server/src/sie_server/adapters/lighton_ocr/_markdown.py b/packages/sie_server/src/sie_server/adapters/lighton_ocr/_markdown.pynew file mode 100644index 000000000..fd97a1b61--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/lighton_ocr/_markdown.py@@ -0,0 +1,984 @@+"""Pinned LightOnOCR-3 grounding-to-Markdown conversion; standard library only.++Adapted from lightonai/LightOnOCR at 36755d461be079737860a5f03ae0c803501269e9:+https://github.com/lightonai/LightOnOCR/tree/36755d461be079737860a5f03ae0c803501269e9++Sources: benchmarks/ocr_bench/providers/loocr_grounding.py (block omission),+benchmarks/ocr_bench/runner.py (page join), and lightonocr/postprocess/+fix_escaped_dollars.py and postprocess_ocr_markdown.py (dollar repair and PP3).+The exact recipe is page join after margin omission, then dollar repair, then PP3.++Local adaptations combine the required definitions in one module, omit CLI and+PP1/PP2 entrypoints, and call the PP3 branch directly without package imports.+Formatting and typing follow this repository; conversion semantics are preserved.+The upstream Apache-2.0 license is reproduced below.+"""++# SPDX-License-Identifier: Apache-2.0+# ruff: noqa: RUF001+# Unicode mathematical characters are part of the pinned conversion rules.+#+# Apache License+# Version 2.0, January 2004+# http://www.apache.org/licenses/+#+# TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION+#+# 1. Definitions.+#+# "License" shall mean the terms and conditions for use, reproduction,+# and distribution as defined by Sections 1 through 9 of this document.+#+# "Licensor" shall mean the copyright owner or entity authorized by+# the copyright owner that is granting the License.+#+# "Legal Entity" shall mean the union of the acting entity and all+# other entities that control, are controlled by, or are under common+# control with that entity. For the purposes of this definition,+# "control" means (i) the power, direct or indirect, to cause the+# direction or management of such entity, whether by contract or+# otherwise, or (ii) ownership of fifty percent (50%) or more of the+# outstanding shares, or (iii) beneficial ownership of such entity.+#+# "You" (or "Your") shall mean an individual or Legal Entity+# exercising permissions granted by this License.+#+# "Source" form shall mean the preferred form for making modifications,+# including but not limited to software source code, documentation+# source, and configuration files.+#+# "Object" form shall mean any form resulting from mechanical+# transformation or translation of a Source form, including but+# not limited to compiled object code, generated documentation,+# and conversions to other media types.+#+# "Work" shall mean the work of authorship, whether in Source or+# Object form, made available under the License, as indicated by a+# copyright notice that is included in or attached to the work+# (an example is provided in the Appendix below).+#+# "Derivative Works" shall mean any work, whether in Source or Object+# form, that is based on (or derived from) the Work and for which the+# editorial revisions, annotations, elaborations, or other modifications+# represent, as a whole, an original work of authorship. For the purposes+# of this License, Derivative Works shall not include works that remain+# separable from, or merely link (or bind by name) to the interfaces of,+# the Work and Derivative Works thereof.+#+# "Contribution" shall mean any work of authorship, including+# the original version of the Work and any modifications or additions+# to that Work or Derivative Works thereof, that is intentionally+# submitted to Licensor for inclusion in the Work by the copyright owner+# or by an individual or Legal Entity authorized to submit on behalf of+# the copyright owner. For the purposes of this definition, "submitted"+# means any form of electronic, verbal, or written communication sent+# to the Licensor or its representatives, including but not limited to+# communication on electronic mailing lists, source code control systems,+# and issue tracking systems that are managed by, or on behalf of, the+# Licensor for the purpose of discussing and improving the Work, but+# excluding communication that is conspicuously marked or otherwise+# designated in writing by the copyright owner as "Not a Contribution."+#+# "Contributor" shall mean Licensor and any individual or Legal Entity+# on behalf of whom a Contribution has been received by Licensor and+# subsequently incorporated within the Work.+#+# 2. Grant of Copyright License. Subject to the terms and conditions of+# this License, each Contributor hereby grants to You a perpetual,+# worldwide, non-exclusive, no-charge, royalty-free, irrevocable+# copyright license to reproduce, prepare Derivative Works of,+# publicly display, publicly perform, sublicense, and distribute the+# Work and such Derivative Works in Source or Object form.+#+# 3. Grant of Patent License. Subject to the terms and conditions of+# this License, each Contributor hereby grants to You a perpetual,+# worldwide, non-exclusive, no-charge, royalty-free, irrevocable+# (except as stated in this section) patent license to make, have made,+# use, offer to sell, sell, import, and otherwise transfer the Work,+# where such license applies only to those patent claims licensable+# by such Contributor that are necessarily infringed by their+# Contribution(s) alone or by combination of their Contribution(s)+# with the Work to which such Contribution(s) was submitted. If You+# institute patent litigation against any entity (including a+# cross-claim or counterclaim in a lawsuit) alleging that the Work+# or a Contribution incorporated within the Work constitutes direct+# or contributory patent infringement, then any patent licenses+# granted to You under this License for that Work shall terminate+# as of the date such litigation is filed.+#+# 4. Redistribution. You may reproduce and distribute copies of the+# Work or Derivative Works thereof in any medium, with or without+# modifications, and in Source or Object form, provided that You+# meet the following conditions:+#+# (a) You must give any other recipients of the Work or+# Derivative Works a copy of this License; and+#+# (b) You must cause any modified files to carry prominent notices+# stating that You changed the files; and+#+# (c) You must retain, in the Source form of any Derivative Works+# that You distribute, all copyright, patent, trademark, and+# attribution notices from the Source form of the Work,+# excluding those notices that do not pertain to any part of+# the Derivative Works; and+#+# (d) If the Work includes a "NOTICE" text file as part of its+# distribution, then any Derivative Works that You distribute must+# include a readable copy of the attribution notices contained+# within such NOTICE file, excluding those notices that do not+# pertain to any part of the Derivative Works, in at least one+# of the following places: within a NOTICE text file distributed+# as part of the Derivative Works; within the Source form or+# documentation, if provided along with the Derivative Works; or,+# within a display generated by the Derivative Works, if and+# wherever such third-party notices normally appear. The contents+# of the NOTICE file are for informational purposes only and+# do not modify the License. You may add Your own attribution+# notices within Derivative Works that You distribute, alongside+# or as an addendum to the NOTICE text from the Work, provided+# that such additional attribution notices cannot be construed+# as modifying the License.+#+# You may add Your own copyright statement to Your modifications and+# may provide additional or different license terms and conditions+# for use, reproduction, or distribution of Your modifications, or+# for any such Derivative Works as a whole, provided Your use,+# reproduction, and distribution of the Work otherwise complies with+# the conditions stated in this License.+#+# 5. Submission of Contributions. Unless You explicitly state otherwise,+# any Contribution intentionally submitted for inclusion in the Work+# by You to the Licensor shall be under the terms and conditions of+# this License, without any additional terms or conditions.+# Notwithstanding the above, nothing herein shall supersede or modify+# the terms of any separate license agreement you may have executed+# with Licensor regarding such Contributions.+#+# 6. Trademarks. This License does not grant permission to use the trade+# names, trademarks, service marks, or product names of the Licensor,+# except as required for reasonable and customary use in describing the+# origin of the Work and reproducing the content of the NOTICE file.+#+# 7. Disclaimer of Warranty. Unless required by applicable law or+# agreed to in writing, Licensor provides the Work (and each+# Contributor provides its Contributions) on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+# implied, including, without limitation, any warranties or conditions+# of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+# PARTICULAR PURPOSE. You are solely responsible for determining the+# appropriateness of using or redistributing the Work and assume any+# risks associated with Your exercise of permissions under this License.+#+# 8. Limitation of Liability. In no event and under no legal theory,+# whether in tort (including negligence), contract, or otherwise,+# unless required by applicable law (such as deliberate and grossly+# negligent acts) or agreed to in writing, shall any Contributor be+# liable to You for damages, including any direct, indirect, special,+# incidental, or consequential damages of any character arising as a+# result of this License or out of the use or inability to use the+# Work (including but not limited to damages for loss of goodwill,+# work stoppage, computer failure or malfunction, or any and all+# other commercial damages or losses), even if such Contributor+# has been advised of the possibility of such damages.+#+# 9. Accepting Warranty or Additional Liability. While redistributing+# the Work or Derivative Works thereof, You may choose to offer,+# and charge a fee for, acceptance of support, warranty, indemnity,+# or other liability obligations and/or rights consistent with this+# License. However, in accepting such obligations, You may act only+# on Your own behalf and on Your sole responsibility, not on behalf+# of any other Contributor, and only if You agree to indemnify,+# defend, and hold each Contributor harmless for any liability+# incurred by, or claims asserted against, such Contributor by reason+# of your accepting any such warranty or additional liability.+#+# END OF TERMS AND CONDITIONS+#+# APPENDIX: How to apply the Apache License to your work.+#+# To apply the Apache License to your work, attach the following+# boilerplate notice, with the fields enclosed by brackets "[]"+# replaced with your own identifying information. (Don't include+# the brackets!) The text should be enclosed in the appropriate+# comment syntax for the file format. We also recommend that a+# file or class name and description of purpose be included on the+# same "printed page" as the copyright notice for easier+# identification within third-party archives.+#+# Copyright [yyyy] [name of copyright owner]+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++from __future__ import annotations++import re+from collections import Counter+from collections.abc import Callable+from typing import Any++_BLOCK_MARKER_RE = re.compile(r"!\[([a-zA-Z_+]+)\]\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)[ \t]*")+++MARGIN_LABELS = frozenset(+ {+ "header",+ "footer",+ "page_number",+ "page_header",+ "page_footer",+ "header_image",+ "footer_image",+ "aside_text",+ }+)+++def _base_label(raw_label: str) -> str:+ return raw_label.strip().lower().rstrip("+")+++class LoocrGroundingProvider:+ @staticmethod+ def parse_blocks(content: str) -> list[dict[str, Any]]:+ """The raw grounding string as ordered ``{label, bbox, text}`` blocks."""+ matches = list(_BLOCK_MARKER_RE.finditer(content))+ ends = [m.start() for m in matches[1:]] + [len(content)] if matches else []+ return [+ {+ "label": m.group(1),+ "bbox": [int(m.group(i)) for i in range(2, 6)],+ "text": content[m.end() : end].strip(),+ }+ for m, end in zip(matches, ends, strict=True)+ ]++ @classmethod+ def omit_margins(cls, content: str) -> str:+ """Raw grounding string -> markdown without margin blocks (``MARGIN_LABELS``) or markers.++ Block texts are joined by blank lines and text before the first marker is dropped; an output+ with no marker is kept as is.+ """+ return cls.omit_labels(content, MARGIN_LABELS)++ @classmethod+ def omit_labels(cls, content: str, labels: frozenset[str]) -> str:+ """Raw grounding string -> markdown without the blocks whose label (``+`` stripped) is in ``labels``."""+ blocks = cls.parse_blocks(content)+ if not blocks:+ return content.strip()+ return "\n\n".join(b["text"] for b in blocks if b["text"] and _base_label(b["label"]) not in labels)+++def _join(texts: list[str]) -> str:+ return "\n\n".join(t.strip() for t in texts if t and t.strip())+++ATOM = re.compile(+ r"\\(?:[A-Za-z]+|[^\r\n])|(?:\d+(?:\.\d*)?|\.\d+)|[^\W\d_]\w*|[-−–—+*/=<>:;,.'!|_^%&()\[\]{}]", re.UNICODE+)+++def math_body(body: str) -> bool:+ r"""Conservative lexical evidence, not proof of mathematical correctness.++ No vocabulary of document/model-specific symbols. Alphabetic runs are+ identifiers; adjacent prose words are not accepted as implicit products.+ Command arguments can contain text (e.g. \\text{a long description}).+ """+ body = body.strip()+ if not body or "<td" in body.lower() or "</" in body:+ return False+ depth = 0+ for lexeme in re.findall(r"\\.|[{}]", body):+ if lexeme == "{":+ depth += 1+ elif lexeme == "}":+ depth -= 1+ if depth < 0:+ return False+ if depth:+ return False+ # Mask balanced command arguments for lexical checks; preserve the source.+ clean = []+ pos = 0+ while pos < len(body):+ m = re.match(r"\\[A-Za-z]+", body[pos:])+ if m:+ clean.append(m[0])+ pos += len(m[0])+ while pos < len(body) and body[pos] == "{":+ depth = 1+ pos += 1+ while pos < len(body) and depth:+ if body[pos] == "\\":+ pos += 2+ continue+ depth += (body[pos] == "{") - (body[pos] == "}")+ pos += 1+ if depth:+ return False+ clean.append("{}")+ else:+ clean.append(body[pos])+ pos += 1+ clean = "".join(clean)+ previous = None+ pos = 0+ for m in ATOM.finditer(clean):+ if clean[pos : m.start()].strip():+ return False+ word = bool(re.fullmatch(r"[^\W\d_]\w*", m[0], re.UNICODE))+ if word and previous and (len(m[0]) > 1 or len(previous) > 1):+ return False+ previous = m[0] if word else None+ pos = m.end()+ return not clean[pos:].strip()+++def plausible_math(body: str) -> bool:+ stripped = body.strip()+ if not math_body(body) or re.fullmatch(r"[^\W\d_]{2,}", stripped):+ return False+ if body != stripped and not re.search(r"[\w\\]", stripped):+ return False+ if len(stripped) > 1 and stripped[0] in ",;":+ return False+ # Ignore escaped delimiters and command text arguments for bracket balance.+ # Mixed interval endpoints [a,b) are allowed; missing endpoints abstain.+ simple = re.sub(r"\\text\{[^{}]*\}", "", stripped)+ level = 0+ for lexeme in re.findall(r"\\.|[()\[\]]", simple):+ if lexeme in ("(", "["):+ level += 1+ elif lexeme in (")", "]"):+ level -= 1+ if level < 0:+ return False+ return level == 0+++PROTECTED = re.compile(+ r"^[ \t]*(?P<fence>`{3,}|~{3,})[^\n]*\n.*?(?:^[ \t]*(?P=fence)[ \t]*(?:\n|$)|\Z)"+ r"|(?P<ticks>`+)[^`\n]*(?P=ticks)"+ r"|^(?: {4}|\t)[^\n]*(?:\n|$)"+ r"|<!--.*?(?:-->|\Z)"+ r"|<(?:pre|code|script|style)\b[^>]*>.*?(?:</(?:pre|code|script|style)\s*>|\Z)"+ r'|<[/!?A-Za-z](?:"[^"]*"|\x27[^\x27]*\x27|[^\x27">])*>'+ r"|(?:https?://|mailto:|www\.)[^\s<>]+"+ r"|^[ \t]{0,3}\[[^\]\n]+\]:[^\n]*"+ r"|(?<!\\)\$\$.*?(?<!\\)\$\$|\\\[.*?\\\]|\\\(.*?\\\)",+ re.MULTILINE | re.DOTALL | re.IGNORECASE,+)+++TOKEN = re.compile(r"(?<![\\$])\\?\$(?!\$)")+++INLINE = re.compile(r"(?<![\\$])\$(?!\$)((?:\\.|[^$\\\n])*)(?<!\\)\$(?!\$)")+++NUMERIC_START = re.compile(r"[+\-−]?\s*(?:\d|[.,]\d)")+++def _ranges(text: str) -> list[tuple[int, int]]:+ spans = [(m.start(), m.end()) for m in PROTECTED.finditer(text)]+ # Protect balanced inline-link destinations, including relative URLs.+ for m in re.finditer(r"\]\(", text):+ pos = m.end()+ depth = 1+ while pos < len(text) and text[pos] != "\n" and depth:+ if text[pos] == "\\":+ pos += 2+ continue+ if text[pos] == "(":+ depth += 1+ elif text[pos] == ")":+ depth -= 1+ pos += 1+ if depth == 0:+ spans.append((m.start(), pos))+ # A literal dollar inside a complete valid-looking math span is not a broken+ # closing delimiter. Protect the complete span before attempting recovery.+ for m in INLINE.finditer(text):+ if plausible_math(m[1]):+ spans.append((m.start(), m.end()))+ merged = []+ for start, end in sorted(spans):+ if merged and start <= merged[-1][1]:+ merged[-1] = (merged[-1][0], max(end, merged[-1][1]))+ else:+ merged.append((start, end))+ return merged+++def repair_dollar_delimiters(text: str, *, audit: list[dict[str, Any]] | None = None) -> tuple[str, Counter[str]]:+ """Return repaired text and counters; optional audit collects exact edits.++ Paired escaped numeric math is eligible; numeric opening-only spans abstain+ because they are indistinguishable locally from prices before math footnotes.+ Bare multi-letter words abstain. No scorer, model or reference access.+ """+ counts = Counter()+ edits = []++ def scan(start: int, end: int) -> None:+ part = text[start:end]+ tokens = list(TOKEN.finditer(part))+ i = 0+ while i + 1 < len(tokens):+ left, right = tokens[i : i + 2]+ body = part[left.end() : right.start()]+ el = left[0].startswith("\\")+ er = right[0].startswith("\\")+ if not el and not er:+ i += 2 if plausible_math(body) else 1+ continue+ numeric = bool(NUMERIC_START.match(body.strip()))+ after = part[right.end() :]+ before = part[: left.start()]+ env = re.fullmatch(r"\s*\\begin\{([A-Za-z*]+)\}.*\\end\{\1\}\s*", body, re.DOTALL)+ # Currency code glued to a dollar, e.g. US$, S$, HK$.+ code_currency = el and bool(re.search(r"(?<!\w)[A-Z]{1,3}$", before))+ ambiguous = (+ (("\n" in body or "\r" in body) and not env)+ or bool(re.search(r"\n[ \t]*\n", body))+ or code_currency+ or (el and not er and numeric)+ or (numeric and bool(NUMERIC_START.match(after.lstrip(" \t"))))+ or bool(re.fullmatch(r"[^\W\d_]{2,}", body.strip()))+ or not plausible_math(body)+ )+ if ambiguous:+ counts["skipped_ambiguous_pairs"] += 1+ i += 1+ continue+ a = start + left.start()+ b = start + right.end()+ replacement = "$" + body + "$"+ edits.append((a, b, replacement))+ counts["repaired_pairs"] += 1+ counts["removed_backslashes"] += el + er+ if audit is not None:+ audit.append(+ {+ "start": a,+ "end": b,+ "before": text[a:b],+ "after": replacement,+ "context": text[max(0, a - 90) : b + 90],+ }+ )+ i += 2++ previous = 0+ for a, b in _ranges(text):+ scan(previous, a)+ previous = b+ scan(previous, len(text))+ for a, b, replacement in reversed(edits):+ text = text[:a] + replacement + text[b:]+ return text, counts+++def fix_escaped_dollars(text: str) -> str:+ """Convert one OCR Markdown string; no other formatting transformations."""+ return repair_dollar_delimiters(text)[0]+++PROSE_DOLLARS = re.compile(r"(?<!\\)(?<!\$)\$(?!\$)([^\n$]+?)(?<!\\)\$(?!\$)")+++OPAQUE = re.compile(+ r"^[ \t]*(?P<fence>`{3,}|~{3,})[^\n]*\n.*?(?:^[ \t]*(?P=fence)[ \t]*(?:\n|$)|\Z)"+ r"|(?P<ticks>`+)[^`\n]*(?P=ticks)"+ r"|(?<!\\)\$\$.*?(?<!\\)\$\$"+ r"|\\\[.*?\\\]|\\\(.*?\\\)"+ r"|(?<![\\$])\$(?!\$)(?:\\.|[^$\n\\])*?(?<!\\)\$(?!\$)",+ re.MULTILINE | re.DOTALL,+)+++def normalize_table_math(text: str) -> tuple[str, Counter[str]]:+ """Render only simple inline math as text inside HTML/Markdown cells.++ No fractions, scripts, arbitrary commands, display equations or currency+ amounts are rewritten. This preserves mathematical content and table shape.+ """+ counts: Counter[str] = Counter()+ symbols = {+ "diamond": "◊",+ "times": "×",+ "pm": "±",+ "leq": "≤",+ "geq": "≥",+ "neq": "≠",+ "alpha": "α",+ "beta": "β",+ "gamma": "γ",+ "mu": "μ",+ "sigma": "σ",+ "Delta": "Δ",+ }+ inline = re.compile(r"(?<![\\$])\$(?!\$)([^$\n]+?)(?<!\\)\$(?!\$)|\\\(([^\n]+?)\\\)")++ def cell(content: str) -> str:+ changed = False++ def replace(match: re.Match[str]) -> str:+ nonlocal changed+ inner = match.group(1) if match.group(1) is not None else match.group(2)+ rendered = re.sub(r"\\([A-Za-z]+)", lambda m: symbols.get(m[1], m[0]), inner).strip()+ if (+ not re.fullmatch(r"[A-Za-z0-9\s.,()+\-=/<>αβγμσΔ◊×±≤≥≠]+", rendered)+ or not re.search(r"[A-Za-zαβγμσΔ◊×±≤≥≠]", rendered)+ or any(len(word) > 1 for word in re.findall(r"[A-Za-z]+", rendered))+ ):+ return match.group(0)+ changed = True+ counts["normalized_table_math_spans"] += 1+ return rendered++ result = inline.sub(replace, content)+ if changed:+ result = re.sub(r"\(\s+", "(", result)+ result = re.sub(r"\s+\)", ")", result)+ return result++ def transform(part: str) -> str:+ part = re.sub(+ r"(<t[dh]\b[^>]*>)(.*?)(</t[dh]\s*>)",+ lambda m: m[1] + cell(m[2]) + m[3],+ part,+ flags=re.IGNORECASE | re.DOTALL,+ )+ lines = part.splitlines(keepends=True)+ separator = re.compile(r"\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*")+ index = 1+ while index < len(lines):+ if separator.fullmatch(lines[index]) and "|" in lines[index - 1]:+ lines[index - 1] = cell(lines[index - 1])+ index += 1+ while index < len(lines) and "|" in lines[index] and lines[index].strip():+ lines[index] = cell(lines[index])+ index += 1+ else:+ index += 1+ return "".join(lines)++ # Apply to text outside code; existing math is handled by the cell parser.+ code = re.compile(+ r"^[ \t]*(?P<f>`{3,}|~{3,})[^\n]*\n.*?(?:^[ \t]*(?P=f)[ \t]*(?:\n|$)|\Z)|(?P<t>`+)[^`\n]*(?P=t)",+ re.MULTILINE | re.DOTALL,+ )+ parts, start = [], 0+ for match in code.finditer(text):+ parts.extend((transform(text[start : match.start()]), match[0]))+ start = match.end()+ parts.append(transform(text[start:]))+ return "".join(parts), counts+++CODE = re.compile(+ r"^[ \t]*(?P<f>`{3,}|~{3,})[^\n]*\n.*?(?:^[ \t]*(?P=f)[ \t]*(?:\n|$)|\Z)"+ r"|(?P<t>`+)[^`\n]*(?P=t)",+ re.MULTILINE | re.DOTALL,+)+++def outside_matches(text: str, protected: re.Pattern[str], transform: Callable[[str], str]) -> str:+ parts, start = [], 0+ for match in protected.finditer(text):+ parts.extend((transform(text[start : match.start()]), match[0]))+ start = match.end()+ parts.append(transform(text[start:]))+ return "".join(parts)+++def transform_cells(text: str, cell: Callable[[str], str]) -> str:+ """Visit HTML cells and cells in Markdown tables with separator rows."""++ def transform(part: str) -> str:+ part = re.sub(+ r"(<t[dh]\b[^>]*>)(.*?)(</t[dh]\s*>)",+ lambda m: m[1] + cell(m[2]) + m[3],+ part,+ flags=re.IGNORECASE | re.DOTALL,+ )+ lines = part.splitlines(keepends=True)+ separator = re.compile(r"\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*")++ def row(line: str) -> str:+ # Escaped pipes and math containing pipes are ambiguous: preserve them.+ if "\\|" in line or "$" in line:+ return line+ return "|".join(cell(value) for value in line.split("|"))++ index = 1+ while index < len(lines):+ if separator.fullmatch(lines[index]) and "|" in lines[index - 1]:+ lines[index - 1] = row(lines[index - 1])+ index += 1+ while index < len(lines) and "|" in lines[index] and lines[index].strip():+ lines[index] = row(lines[index])+ index += 1+ else:+ index += 1+ return "".join(lines)++ return outside_matches(text, CODE, transform)+++def normalize_table_spacing(text: str) -> tuple[str, Counter[str]]:+ counts: Counter[str] = Counter()++ def cell(value: str) -> str:+ body = value.strip()+ if re.fullmatch(r"\d+(?:\.\d+)?\s*:\s*\d+(?:\.\d+)?", body):+ new = re.sub(r"\s*:\s*", ":", body)+ elif re.fullmatch(r"[+-]?\d{1,3}(?:[ \u00a0\u202f]\d{3})+(?:\.\d+)?", body):+ new = re.sub(r"[ \u00a0\u202f]", "", body)+ elif re.fullmatch(r"[μµ]\s+(?:m|g|l|L|s|A|V|W|F|M)", body):+ new = re.sub(r"\s+", "", body)+ else:+ return value+ if new != body:+ counts["normalized_table_spacing_cells"] += 1+ return value.replace(body, new, 1)++ return transform_cells(text, cell), counts+++def remove_table_leaders(text: str) -> tuple[str, Counter[str]]:+ counts: Counter[str] = Counter()++ def cell(value: str) -> str:+ if not re.search(r"[^\W\d_]", value) or re.search(r"[<>$\\]", value):+ return value+ new, number = re.subn(r"[ \t]*(?:\.{3,}|…{2,})[ \t]*(?=\s*$)", "", value)+ counts["removed_table_leaders"] += number+ return new++ return transform_cells(text, cell), counts+++def shorten_form_blanks(text: str) -> tuple[str, Counter[str]]:+ counts: Counter[str] = Counter()++ def transform(part: str) -> str:+ # Only standalone blanks on lines containing a field label.+ def line(value: str) -> str:+ if not re.search(r"[^\W\d_]", value) or value.lstrip().startswith(("<", "|")):+ return value+ new, number = re.subn(r"(?<!\S)_{10,}(?!\S)", "________", value)+ counts["shortened_form_blanks"] += number+ return new++ return "".join(line(value) for value in part.splitlines(keepends=True))++ return outside_matches(text, OPAQUE, transform), counts+++def join_adjacent_math(text: str) -> tuple[str, Counter[str]]:+ counts: Counter[str] = Counter()+ inline = re.compile(r"(?<![\\$])\$(?!\$)([^$\n]+?)(?<!\\)\$(?!\$)")++ def transform(part: str) -> str:+ matches = list(inline.finditer(part))+ if not matches:+ return part+ parts, start, index = [], 0, 0++ def eligible(body: str) -> bool:+ # Require an equation/relation in each span; currency and prose+ # cannot join. Math itself is copied verbatim.+ return bool(re.search(r"[=<>]|\\(?:leq|geq|neq)\b", body))++ while index < len(matches):+ first = last = matches[index]+ body = first[1]+ while index + 1 < len(matches) and eligible(last[1]):+ following = matches[index + 1]+ gap = part[last.end() : following.start()]+ if not re.fullmatch(r"[ \t]*[,;][ \t]*", gap) or not eligible(following[1]):+ break+ body += gap + following[1]+ last = following+ index += 1+ counts["joined_adjacent_math_spans"] += 1+ parts.extend((part[start : first.start()], "$" + body + "$"))+ start = last.end()+ index += 1+ parts.append(part[start:])+ return "".join(parts)++ protected = re.compile(+ CODE.pattern + r"|(?<!\\)\$\$.*?(?<!\\)\$\$|\\\[.*?\\\]|\\\(.*?\\\)", re.MULTILINE | re.DOTALL+ )+ return outside_matches(text, protected, transform), counts+++def normalize_prose_math(text: str) -> tuple[str, Counter[str]]:+ """Render simple inline notation on prose lines; preserve actual formulas."""+ counts: Counter[str] = Counter()+ symbols = {+ "alpha": "α",+ "beta": "β",+ "gamma": "γ",+ "delta": "δ",+ "Delta": "Δ",+ "mu": "μ",+ "sigma": "σ",+ "theta": "θ",+ "pi": "π",+ "omega": "ω",+ "tanh": "tanh",+ }+ protected = re.compile(+ CODE.pattern + r"|<table\b.*?</table>"+ r"|(?<!\\)\$\$.*?(?<!\\)\$\$|\\\[.*?\\\]",+ re.MULTILINE | re.DOTALL | re.IGNORECASE,+ )++ def transform(part: str) -> str:+ lines = []+ for line in part.splitlines(keepends=True):+ # Mixed dollar errors are deliberately preserved, as requested.+ prose = PROSE_DOLLARS.sub("", line)+ if (+ "\\$" in line+ or "|" in line+ or line.lstrip().startswith(("<", "!["))+ or len(re.findall(r"\b[A-Za-z]{2,}\b", prose)) < 3+ ):+ lines.append(line)+ continue++ def replace(match: re.Match[str]) -> str:+ body = match[1].strip()+ # A prose sentence can contain a complete equation. Retain its+ # delimiters so formula consumers can still extract it.+ if any(char in body for char in "=<>"):+ return match[0]+ rendered = re.sub(r"\\([A-Za-z]+)", lambda m: symbols.get(m[1], m[0]), body)+ if (+ not re.fullmatch(r"[A-Za-zαβγδΔμσθπω0-9 .,+/()=<>-]+", rendered)+ or not re.search(r"[A-Za-zαβγδΔμσθπω]", rendered)+ or any(len(w) > 1 and w != "tanh" for w in re.findall(r"[A-Za-z]+", rendered))+ ):+ return match[0]+ counts["normalized_prose_math_spans"] += 1+ return rendered++ lines.append(PROSE_DOLLARS.sub(replace, line))+ return "".join(lines)++ return outside_matches(text, protected, transform), counts+++def normalize_prose_math_lists(text: str) -> tuple[str, Counter[str]]:+ """Keep linked math spans wrapped; normalize isolated prose notation as PP1."""+ counts = Counter()+ protected = re.compile(+ CODE.pattern + r"|<table\b.*?</table>|(?<!\\)\$\$.*?(?<!\\)\$\$|\\\[.*?\\\]",+ re.MULTILINE | re.DOTALL | re.IGNORECASE,+ )++ def transform(part: str) -> str:+ lines = []+ for line in part.splitlines(keepends=True):+ spans = list(PROSE_DOLLARS.finditer(line))+ keep = set()+ for left, right in zip(spans, spans[1:]): # noqa: RUF007 - pinned adjacent-span recipe+ gap = line[left.end() : right.start()]+ if re.fullmatch(r"[ \t]*(?:[,;][ \t]*(?:(?:and|or)[ \t]+)?|(?:and|or)[ \t]+)", gap):+ keep.update((left.start(), right.start()))+ # Use original normalization on the complete line to preserve its+ # eligibility checks, then reconstruct from each span's decision.+ eligible = normalize_prose_math(line)[0]+ if eligible == line or not keep:+ value, c = normalize_prose_math(line)+ counts.update(c)+ lines.append(value)+ continue+ prose = PROSE_DOLLARS.sub("", line)++ def replace(m: re.Match[str]) -> str:+ if m.start() in keep:+ counts["preserved_linked_math_spans"] += 1+ return m[0]+ # Original renderer with the same surrounding prose eligibility.+ prefix = " ".join(prose.splitlines())+ probe = prefix + m[0]+ value, c = normalize_prose_math(probe)+ counts.update(c)+ return value[len(prefix) :]++ lines.append(PROSE_DOLLARS.sub(replace, line))+ return "".join(lines)++ return outside_matches(text, protected, transform), counts+++def repair_latex_syntax(text: str) -> tuple[str, Counter[str]]:+ """Expand known operators, escape text ampersands, reconnect split fences.++ Never change dollar escaping or invent missing delimiters/content.+ """+ counts: Counter[str] = Counter()+ math = re.compile(+ r"(?<!\\)\$\$(.*?)\$\$|\\\[(.*?)\\\]"+ r"|(?<![\\$])\$(?!\$)([^$\n]*?)(?<!\\)\$(?!\$)|\\\((.*?)\\\)",+ re.DOTALL,+ )+ display = re.compile(r"(?<!\\)\$\$(.*?)\$\$", re.DOTALL)++ def transform(part: str) -> str:+ def repair(match: re.Match[str]) -> str:+ original = match[0]+ # Leave every expression containing escaped dollars untouched.+ if "\\$" in original:+ return original+ new, n = re.subn(r"\\esssup(?![A-Za-z])", lambda _m: r"\operatorname*{ess\,sup}", original)+ counts["expanded_esssup"] += n++ def textext(m: re.Match[str]) -> str:+ body, n = re.subn(r"(?<!\\)&", r"\\&", m[1])+ counts["escaped_text_ampersands"] += n+ return r"\text{" + body + "}"++ return re.sub(r"\\text\{([^{}]*)\}", textext, new)++ part = math.sub(repair, part)+ matches = list(display.finditer(part))+ parts, start, i = [], 0, 0++ def balance(body: str) -> int:+ level = 0+ for lexeme in re.findall(r"\\(left|right)\b", body):+ level += 1 if lexeme == "left" else -1+ if level < 0:+ return -1+ return level++ while i < len(matches):+ first = matches[i]+ body, end, j = first[1], first.end(), i+ # Join only adjacent display blocks until an existing \left is+ # closed by an existing \right, without intervening prose.+ while balance(body) > 0 and j + 1 < len(matches):+ following = matches[j + 1]+ if part[end : following.start()].strip():+ break+ body += "\n" + following[1]+ end, j = following.end(), j + 1+ if balance(body) == 0:+ break+ if j > i and balance(body) == 0 and "\\$" not in body:+ parts.extend((part[start : first.start()], "$$" + body + "$$"))+ counts["joined_split_display_blocks"] += j - i+ start, i = end, j + 1+ else:+ i += 1+ parts.append(part[start:])+ return "".join(parts)++ return outside_matches(text, CODE, transform), counts+++TRANSFORMS = {+ "table-math": normalize_table_math,+ "table-spacing": normalize_table_spacing,+ "table-leaders": remove_table_leaders,+ "form-blanks": shorten_form_blanks,+ "adjacent-math": join_adjacent_math,+ "prose-math": normalize_prose_math,+ "latex-syntax": repair_latex_syntax,+}+++def merge_inline_math(text: str) -> tuple[str, Counter[str]]:+ counts = Counter()+ marker = "$"+ pattern = r"(?<![\\$])\$(?!\$)([^$\n]+?)(?<!\\)\$(?!\$)"+ formula = re.compile(pattern, re.DOTALL)+ protected = CODE.pattern + r"|^.*\\\$.*$"+ protected += r"|(?<!\\)\$\$.*?(?<!\\)\$\$|\\\[.*?\\\]|\\\(.*?\\\)"+ # Avoid DOTALL on the escaped-dollar line alternative.+ protected = re.compile(protected.replace(r"^.*\\\$.*$", r"^[^\n]*\\\$[^\n]*$"), re.MULTILINE | re.DOTALL)++ def transform(part: str) -> str:+ matches = list(formula.finditer(part))+ pieces, start, i = [], 0, 0++ def eligible(m: re.Match[str]) -> bool:+ return not re.fullmatch(r"-?\d{1,3}(?:,\d{3})*", m[1].strip())++ while i < len(matches):+ first = last = matches[i]+ body = first[1]+ while eligible(last) and i + 1 < len(matches) and eligible(matches[i + 1]):+ following = matches[i + 1]+ gap = part[last.end() : following.start()]+ if not re.fullmatch(r"(?:\s|,|and)*", gap, re.IGNORECASE):+ break+ body += (gap if gap.strip() else " ") + following[1]+ last = following+ counts["merged_inline_pairs"] += 1+ i += 1+ pieces.extend([part[start : first.start()], marker + body + marker])+ start = last.end()+ i += 1+ pieces.append(part[start:])+ return "".join(pieces)++ return outside_matches(text, protected, transform), counts+++TRANSFORMS["infinity-inline"] = merge_inline_math+++PP1_STEPS = (+ "table-math",+ "table-spacing",+ "table-leaders",+ "form-blanks",+ "adjacent-math",+ "latex-syntax",+ "prose-math",+ "infinity-inline",+)+++PP3_STEPS = tuple(name for name in PP1_STEPS if name not in ("table-leaders", "form-blanks"))+++def _pp3(text: str) -> str:+ """Apply the pinned cleanup(profile="pp3") branch."""+ text, _ = repair_dollar_delimiters(text)+ for name in PP3_STEPS:+ transform = normalize_prose_math_lists if name == "prose-math" else TRANSFORMS[name]+ text, _ = transform(text)+ return text+++def lightonocr3_markdown(raw_response: str) -> str:+ """Convert one generated page using LightOnOCR's published Markdown recipe.++ Margin/aside blocks and text before the first grounding marker are omitted.+ Footnotes remain; a page containing only omitted blocks becomes empty.+ """+ markdown = _join([LoocrGroundingProvider.omit_margins(raw_response)])+ markdown = fix_escaped_dollars(markdown)+ return _pp3(markdown)diff --git a/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.py b/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.pyindex ca2b8214d..b1fb95a13 100644--- a/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/lighton_ocr/adapter.py@@ -11,6 +11,7 @@ import torch.nn.functional as Ffrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDims+from sie_server.adapters.lighton_ocr._markdown import lightonocr3_markdownfrom sie_server.core.inference_output import EncodeOutput, ExtractOutputfrom sie_server.core.prepared import LightOnOCR3Payload, LightOnOCRPayload, PreparedItemfrom sie_server.core.preprocessor import LightOnOCRPreprocessor@@ -535,8 +536,12 @@ class LightOnOCR3Adapter(LightOnOCRAdapter):top_p: float = 1.0,attn_implementation: str = "sdpa",revision: str | None = None,+ output_postprocess: str | None = None,**kwargs: Any,) -> None:+ if output_postprocess not in (None, "lightonocr3_markdown"):+ msg = "output_postprocess must be None or 'lightonocr3_markdown'"+ raise ValueError(msg)if "system_prompt" in kwargs or "user_text" in kwargs:msg = "LightOnOCR-3 uses only its trained image-only or grounding prompt"raise ValueError(msg)@@ -559,6 +564,7 @@ class LightOnOCR3Adapter(LightOnOCRAdapter):)self._temperature = temperatureself._top_p = top_p+ self._output_postprocess = output_postprocessself._generation_options({})def load(self, device: str) -> None:@@ -623,7 +629,7 @@ class LightOnOCR3Adapter(LightOnOCRAdapter):options: dict[str, Any] | None = None,prepared_items: list[Any] | None = None,) -> ExtractOutput:- """Return raw Markdown or grounding text; only the exact trained modes are supported."""+ """Extract with the trained prompts and optional loadtime Markdown conversion."""if self._model is None or self._processor is None or self._preprocessor is None or self._device is None:raise RuntimeError(_ERR_NOT_LOADED)instruction = LightOnOCR3Preprocessor.validate_instruction(instruction)@@ -658,6 +664,8 @@ class LightOnOCR3Adapter(LightOnOCRAdapter):with torch.inference_mode():output_ids = self._model.generate(**inputs, **generation_options)text = self._processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True)+ if self._output_postprocess == "lightonocr3_markdown":+ text = lightonocr3_markdown(text)all_entities.append([Entity(text=text, label="markdown", score=1.0)])return ExtractOutput(entities=all_entities, pages=[1 for _ in items])diff --git a/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py b/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.pyindex 638d16c1e..da2874dc5 100644--- a/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py@@ -21,6 +21,7 @@ from sie_server.adapters._generation_base import GenerationResult, collect_generfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters.base import ModelCapabilities, ModelDims+from sie_server.adapters.lighton_ocr._markdown import lightonocr3_markdownfrom sie_server.adapters.sglang.generation import SGLangGenerationAdapterfrom sie_server.core.inference_output import ExtractOutputfrom sie_server.types.inputs import InvalidMediaError@@ -75,6 +76,7 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):top_p: float = 1.0,chat_template_kwargs: dict[str, Any] | None = None,allowed_instructions: list[str] | None = None,+ output_postprocess: str | None = None,disable_cuda_graph: bool = False,attention_backend: str | None = None,extra_launch_args: list[str] | None = None,@@ -82,6 +84,9 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):startup_timeout_s: float | None = None,**kwargs: Any,) -> None:+ if output_postprocess not in (None, "lightonocr3_markdown"):+ msg = "output_postprocess must be None or 'lightonocr3_markdown'"+ raise ValueError(msg)super().__init__(model_name_or_path=str(model_name_or_path),max_seq_length=max_seq_length,@@ -119,6 +124,7 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):self._top_p = float(top_p)self._chat_template_kwargs = dict(chat_template_kwargs or {})self._allowed_instructions = None if allowed_instructions is None else frozenset(allowed_instructions)+ self._output_postprocess = output_postprocess# One bound across every batch in flight, created on the request loop.self._request_slots: asyncio.Semaphore | None = Noneself._processor: Any = None@@ -273,6 +279,9 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):raise RuntimeError(_ERR_NOT_LOADED)runtime = options or {}+ if "output_postprocess" in runtime:+ msg = "output_postprocess is a loadtime option"+ raise ValueError(msg)max_new_tokens = int(runtime.get("max_new_tokens", self._max_new_tokens))num_beams = int(runtime.get("num_beams", self._num_beams))if num_beams != 1:@@ -301,7 +310,20 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):self._request_loop,)results = future.result()- entities = [[Entity(text=result.text.strip(), label=entity_label, score=1.0)] for result in results]+ entities = [+ [+ Entity(+ text=(+ lightonocr3_markdown(result.text)+ if self._output_postprocess == "lightonocr3_markdown"+ else result.text.strip()+ ),+ label=entity_label,+ score=1.0,+ )+ ]+ for result in results+ ]# SGLang reports each request's prompt tokens (chat template plus the# image's vision tokens) and the completion tokens it decoded. Both are# reported alongside the page or image count, which stays unchanged;diff --git a/packages/sie_server/tests/adapters/test_lighton_ocr3.py b/packages/sie_server/tests/adapters/test_lighton_ocr3.pyindex 0c3ca84bb..719087b75 100644--- a/packages/sie_server/tests/adapters/test_lighton_ocr3.py+++ b/packages/sie_server/tests/adapters/test_lighton_ocr3.py@@ -124,6 +124,55 @@ def test_multi_image_order_and_generation_overrides(adapter: LightOnOCR3Adapter)assert all(call["max_new_tokens"] == 8 and call["temperature"] == 0.2 for call in adapter._model.calls)+class _GroundingProcessor(_Processor):+ def decode(self, generated: torch.Tensor, *, skip_special_tokens: bool) -> str:+ assert skip_special_tokens is True+ self.decoded.append(generated.clone())+ if int(generated[0]) == 106:+ return "only margin"+ return (+ "prefix\nheader\n"+ f"body {int(generated[0])}\nsecond line\n"+ "aside\n"+ "retained footnote\n"+ "footer"+ )+++def test_native_markdown_opt_in_converts_each_decoded_page() -> None:+ value = LightOnOCR3Adapter(+ "lightonai/LightOnOCR-3-4B", max_new_tokens=32, output_postprocess="lightonocr3_markdown"+ )+ value._model = _Model()+ value._processor = _GroundingProcessor()+ value._device = "cpu"+ value._create_preprocessor()++ result = value.extract([_item(2), _item(6)], instruction="grounding")++ assert result.entities == [+ [{"text": "body 102\nsecond line\n\nretained footnote", "label": "markdown", "score": 1.0}],+ [{"text": "", "label": "markdown", "score": 1.0}],+ ]+ assert result.pages == [1, 1]+ assert result.input_token_counts is result.output_token_counts is None+ assert len(value._model.calls) == len(value._processor.decoded) == 2+ assert all(+ {key: call[key] for key in ("max_new_tokens", "do_sample", "num_beams", "temperature", "top_p")}+ == {"max_new_tokens": 32, "do_sample": True, "num_beams": 1, "temperature": 0.1, "top_p": 1.0}+ for call in value._model.calls+ )+ assert all(+ call["messages"][0]["content"][1:] == [{"type": "text", "text": "grounding"}] for call in value._processor.calls+ )++[email protected]("output_postprocess", ["unknown", "", False, 1, {}, []])+def test_native_rejects_unknown_output_postprocessors(output_postprocess: Any) -> None:+ with pytest.raises(ValueError, match="output_postprocess"):+ LightOnOCR3Adapter("lightonai/LightOnOCR-3-4B", output_postprocess=output_postprocess)++@pytest.mark.parametrize("instruction", ["Grounding", " grounding", "Text Recognition:", "Extract tables only"])def test_untrained_prompt_rejected_before_processing(adapter: LightOnOCR3Adapter, instruction: str) -> None:with pytest.raises(ValueError, match="supports only"):@@ -155,6 +204,7 @@ def test_single_image_contract_rejects_complete_request(adapter: LightOnOCR3Adap{"do_sample": False},{"num_beams": 2},{"enable_thinking": True},+ {"output_postprocess": "lightonocr3_markdown"},],)def test_invalid_generation_controls_fail_before_model(adapter: LightOnOCR3Adapter, options: dict[str, Any]) -> None:diff --git a/packages/sie_server/tests/adapters/test_lighton_ocr_markdown.py b/packages/sie_server/tests/adapters/test_lighton_ocr_markdown.pynew file mode 100644index 000000000..65cf4300b--- /dev/null+++ b/packages/sie_server/tests/adapters/test_lighton_ocr_markdown.py@@ -0,0 +1,83 @@+# ruff: noqa: RUF001+# Intentional Unicode in the source-qualified fixtures.+"""Synthetic outputs qualified against LightOnOCR's pinned published recipe.++Expected constants were produced with lightonai/LightOnOCR at+36755d461be079737860a5f03ae0c803501269e9: omit_margins, _join,+fix_escaped_dollars, then pp3. No document text or model inference is needed.+"""++import pytest+from sie_server.adapters.lighton_ocr._markdown import lightonocr3_markdown+++ ("raw", "expected"),+ [+ pytest.param(+ "discard this prefix\n\nheader\n"+ "\nbody\nsecond line\n"+ "\naside\n"+ "\nretained footnote\n"+ "\nfooter\n\n42",+ "body\nsecond line\n\nretained footnote",+ id="block-omission-and-retained-footnote",+ ),+ pytest.param(r"We use \$x^2\$ here. Price \$5.", r"We use $x^2$ here. Price \$5.", id="math-and-currency"),+ pytest.param(+ "```tex\n\\$x^2\\$\n```\n\nInline `\\$y^2\\$` stays.\n\nMath \\$z^2\\$.",+ "```tex\n\\$x^2\\$\n```\n\nInline `\\$y^2\\$` stays.\n\nMath $z^2$.",+ id="fenced-and-inline-code",+ ),+ pytest.param(+ "| $x$ | $x^2$ |\n| --- | --- |\n| \\$y\\$ | \\$5 |",+ "| x | $x^2$ |\n| --- | --- |\n| y | \\$5 |",+ id="table-math",+ ),+ pytest.param(+ "preamble\n\nRésumé — 東京\nδεύτερη γραμμή\n\n注釈 αβγ",+ "Résumé — 東京\nδεύτερη γραμμή\n\n注釈 αβγ",+ id="multiline-unicode",+ ),+ pytest.param(" first line\n\nsecond line\n ", "first line\n\nsecond line", id="no-marker-fallback"),+ pytest.param(+ "Label .............\nName: _____________",+ "Label .............\nName: _____________",+ id="pp3-preserves-dots-and-form-blanks",+ ),+ pytest.param(+ r"We consider the variables \$x\$, \$y\$ and \$z\$ in this sentence.",+ "We consider the variables $x, y and z$ in this sentence.",+ id="pp3-linked-math",+ ),+ pytest.param(" \n\t ", "", id="blank"),+ pytest.param(+ "header\nfooter",+ "",+ id="all-margin",+ ),+ ],+)+def test_published_markdown_recipe(raw: str, expected: str) -> None:+ assert lightonocr3_markdown(raw) == expected+++ "label",+ ["header", "footer", "page_number", "page_header", "page_footer", "header_image", "footer_image", "aside_text"],+)+def test_all_published_margin_labels_are_omitted(label: str) -> None:+ raw = f"omit\nbody"+ assert lightonocr3_markdown(raw) == "body"+++ "raw",+ ["body", "body", "body"],+)+def test_marker_grammar_keeps_unrecognized_markers(raw: str) -> None:+ assert lightonocr3_markdown(raw) == raw+++def test_empty_retained_blocks_do_not_add_separators() -> None:+ assert lightonocr3_markdown("\n \nnote") == "note"diff --git a/packages/sie_server/tests/adapters/test_sglang_vision_extract.py b/packages/sie_server/tests/adapters/test_sglang_vision_extract.pyindex 3bb9ecedd..3d69dff0f 100644--- a/packages/sie_server/tests/adapters/test_sglang_vision_extract.py+++ b/packages/sie_server/tests/adapters/test_sglang_vision_extract.py@@ -404,7 +404,7 @@ def test_page_metering_replaces_image_units_and_stamps_successes() -> None:items = [Item(images=[_image("page")])]future = MagicMock()future.result.return_value = [- GenerationResult(text="# page", finish_reason="stop", prompt_tokens=2590, completion_tokens=836)+ GenerationResult(text=" \n# page \n ", finish_reason="stop", prompt_tokens=2590, completion_tokens=836)]def submit(coroutine: Any, loop: Any) -> MagicMock:@@ -671,10 +671,10 @@ class _KwargsProcessor(_FakeProcessor):_LIGHTONOCR3 = "lightonai/LightOnOCR-3-4B"-def _lightonocr3_default_adapter() -> SGLangVisionExtractAdapter:+def _lightonocr3_adapter(profile_name: str = "default") -> SGLangVisionExtractAdapter:model_path = Path(__file__).resolve().parents[2] / "models" / "lightonai__LightOnOCR-3-4B.yaml"config = ModelConfig.model_validate(yaml.safe_load(model_path.read_text()))- profile = config.resolve_profile("default")+ profile = config.resolve_profile(profile_name)assert profile.adapter_path == "sie_server.adapters.sglang_vision_extract.adapter:SGLangVisionExtractAdapter"loadtime: dict[str, Any] = dict(profile.loadtime)instance = SGLangVisionExtractAdapter(_LIGHTONOCR3, revision=config.hf_revision, **loadtime)@@ -685,7 +685,7 @@ def _lightonocr3_default_adapter() -> SGLangVisionExtractAdapter:@pytest.mark.parametrize("instruction", [None, "", "grounding"])def test_lightonocr3_profile_uses_trained_prompts_without_system_or_thinking(instruction: str | None) -> None:- instance = _lightonocr3_default_adapter()+ instance = _lightonocr3_adapter()prompt, label = instance._resolve_prompt_and_label(instruction, {})assert label == "markdown"instance._build_prompt(prompt)@@ -700,7 +700,7 @@ def test_lightonocr3_profile_uses_trained_prompts_without_system_or_thinking(ins@pytest.mark.parametrize("instruction", ["Grounding", "Text Recognition:", "Extract tables only"])def test_lightonocr3_profile_rejects_untrained_instructions(instruction: str) -> None:- instance = _lightonocr3_default_adapter()+ instance = _lightonocr3_adapter()instance._request_loop = MagicMock()with pytest.raises(ValueError, match="instruction must be omitted or one of"):instance.extract([Item(images=[_image("page")])], instruction=instruction)@@ -708,7 +708,7 @@ def test_lightonocr3_profile_rejects_untrained_instructions(instruction: str) ->@pytest.mark.asyncioasync def test_lightonocr3_profile_sampling_reaches_sglang_request() -> None:- instance = _lightonocr3_default_adapter()+ instance = _lightonocr3_adapter()bodies: list[dict[str, Any]] = []def handle(request: httpx.Request) -> httpx.Response:@@ -735,6 +735,95 @@ async def test_lightonocr3_profile_sampling_reaches_sglang_request() -> None:def test_sampling_defaults_stay_greedy(adapter: SGLangVisionExtractAdapter) -> None:assert (adapter._temperature, adapter._top_p, adapter._chat_template_kwargs) == (0.0, 1.0, {})assert adapter._allowed_instructions is None+ assert adapter._output_postprocess is None++[email protected]("instruction", [None, "", "grounding"])+def test_markdown_profile_defaults_to_grounding_and_preserves_engine_usage(instruction: str | None) -> None:+ instance = _lightonocr3_adapter("markdown")+ generated_images: list[ImageInput] = []+ processor = instance._processor++ async def generate(prompt: str, *, images: list[ImageInput], **sampling: Any) -> AsyncIterator[GenerationChunk]:+ assert prompt == "rendered prompt"+ assert sampling == {"max_new_tokens": 12288, "temperature": 0.1, "top_p": 1.0}+ assert len(images) == 1+ generated_images.extend(images)+ raw = (+ "prefix\nheader\n"+ "We use \\$x^2\\$ here. Price \\$5.\n"+ "footer"+ )+ yield GenerationChunk(+ text_delta=raw, done=True, finish_reason="stop", prompt_tokens=2590, completion_tokens=836+ )++ instance.generate = generate # ty: ignore[invalid-assignment]+ instance._start_request_loop()+ try:+ result = instance.extract([Item(images=[_image("page")])], instruction=instruction)+ finally:+ instance.unload()++ assert instance._processor is None+ assert processor.messages == [+ {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "grounding"}]}+ ]+ assert processor.template_kwargs == {"enable_thinking": False}+ assert generated_images == [_image("page")]+ assert result.entities == [[{"text": r"We use $x^2$ here. Price \$5.", "label": "markdown", "score": 1.0}]]+ assert result.pages == [1]+ assert result.input_token_counts == [2590]+ assert result.output_token_counts == [836]+++def test_markdown_profile_keeps_empty_page_and_original_generated_token_counts() -> None:+ instance = _lightonocr3_adapter("markdown")+ generated_images: list[ImageInput] = []+ processor = instance._processor++ async def generate(prompt: str, *, images: list[ImageInput], **sampling: Any) -> AsyncIterator[GenerationChunk]:+ assert prompt == "rendered prompt"+ generated_images.extend(images)+ raw = "discarded"+ if images[0]["data"] == b"body":+ raw = "body"+ yield GenerationChunk(text_delta=raw[:10])+ yield GenerationChunk(+ text_delta=raw[10:], done=True, finish_reason="stop", prompt_tokens=2048, completion_tokens=90+ )++ instance.generate = generate # ty: ignore[invalid-assignment]+ instance._start_request_loop()+ try:+ result = instance.extract([Item(images=[_image("body")]), Item(images=[_image("margin")])])+ finally:+ instance.unload()++ assert generated_images == [_image("body"), _image("margin")]+ assert processor.messages == [+ {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "grounding"}]}+ ]+ assert processor.template_kwargs == {"enable_thinking": False}+ assert result.entities == [+ [{"text": "body", "label": "markdown", "score": 1.0}],+ [{"text": "", "label": "markdown", "score": 1.0}],+ ]+ assert result.pages == [1, 1]+ assert result.input_token_counts == [2048, 2048]+ assert result.output_token_counts == [90, 90]++[email protected]("output_postprocess", ["unknown", "", False, 1, {}, []])+def test_sglang_rejects_unknown_output_postprocessors(output_postprocess: Any) -> None:+ with pytest.raises(ValueError, match="output_postprocess"):+ SGLangVisionExtractAdapter(_LIGHTONOCR3, output_postprocess=output_postprocess)+++def test_output_postprocess_cannot_be_a_runtime_option(adapter: SGLangVisionExtractAdapter) -> None:+ adapter._request_loop = MagicMock()+ with pytest.raises(ValueError, match="output_postprocess is a loadtime option"):+ adapter.extract([Item(images=[_image("page")])], options={"output_postprocess": "lightonocr3_markdown"})@pytest.mark.parametrize(diff --git a/packages/sie_server/tests/config/test_lightonocr3_profiles.py b/packages/sie_server/tests/config/test_lightonocr3_profiles.pyindex 29035bd6e..86c2845d3 100644--- a/packages/sie_server/tests/config/test_lightonocr3_profiles.py+++ b/packages/sie_server/tests/config/test_lightonocr3_profiles.py@@ -9,7 +9,7 @@ import yamlfrom sie_sdk.bundle_utils import match_bundle_modelsfrom sie_server.adapters.lighton_ocr.adapter import LightOnOCR3Adapterfrom sie_server.adapters.sglang_vision_extract.adapter import SGLangVisionExtractAdapter-from sie_server.core.loader import load_adapter, load_model_config, validate_pinned_revision+from sie_server.core.loader import expand_profile_variants, load_adapter, load_model_config, validate_pinned_revision_SERVER = Path(__file__).resolve().parents[2]_MODELS = _SERVER / "models"@@ -29,7 +29,7 @@ def test_catalog_pins_checkpoint_and_upstream_generation() -> None:assert config["inputs"] == {"text": False, "image": True, "audio": False, "video": False}assert config["tasks"] == {"encode": None, "score": None, "extract": {}}assert config["max_sequence_length"] == 24576- assert list(config["profiles"]) == ["default", "transformers"]+ assert list(config["profiles"]) == ["default", "markdown", "transformers"]default = config["profiles"]["default"]assert default["adapter_path"] == f"{_SGLANG_ADAPTER}:SGLangVisionExtractAdapter"assert default["compute_precision"] == "bfloat16"@@ -48,6 +48,8 @@ def test_catalog_pins_checkpoint_and_upstream_generation() -> None:assert loadtime["extra_launch_args"] == ["--disable-radix-cache"]assert "system_prompt" not in loadtimeassert "extra_env" not in loadtime+ assert "default_prompt" not in loadtime+ assert "output_postprocess" not in loadtimeassert default["adapter_options"]["runtime"] == {"max_new_tokens": 12288, "num_beams": 1}transformers = config["profiles"]["transformers"]assert transformers["adapter_path"] == f"{_ADAPTER}:LightOnOCR3Adapter"@@ -85,14 +87,52 @@ def test_transformers_profile_builds_profile_generation() -> None:assert adapter._model_name_or_path == _MODELassert adapter._revision == _REVISIONassert adapter._compute_precision == "bfloat16"+ assert adapter._output_postprocess is Noneassert adapter._generation_options({}) == _GENERATIONassert adapter._generation_options({"max_new_tokens": 1024})["max_new_tokens"] == 1024with pytest.raises(ValueError, match="max_new_tokens"):adapter._generation_options({"max_new_tokens": 12289})+def test_markdown_profile_retains_default_generation_context_and_engine_options() -> None:+ config = load_model_config(_CONFIG)+ default = config.resolve_profile("default")+ markdown = config.resolve_profile("markdown")+ assert config.max_sequence_length == 24576+ assert markdown.max_batch_tokens == default.max_batch_tokens == 16384+ assert markdown.compute_precision == default.compute_precision == "bfloat16"+ assert markdown.adapter_path == default.adapter_path == f"{_SGLANG_ADAPTER}:SGLangVisionExtractAdapter"+ assert dict(markdown.runtime) == dict(default.runtime) == {"max_new_tokens": 12288, "num_beams": 1}+ assert dict(markdown.loadtime) == {+ **default.loadtime,+ "default_prompt": "grounding",+ "output_postprocess": "lightonocr3_markdown",+ }+ variants = expand_profile_variants([config])+ variant = variants[f"{_MODEL}:markdown"]+ validate_pinned_revision(variant)+ adapter = load_adapter(variant, _MODELS, device="cuda:0")+ assert isinstance(adapter, SGLangVisionExtractAdapter)+ assert adapter._revision == _REVISION+ assert adapter._compute_precision == "bfloat16"+ assert adapter._max_seq_length == 24576+ assert adapter._output_postprocess == "lightonocr3_markdown"+ assert adapter._resolve_prompt_and_label(None, {}) == ("grounding", "markdown")+ assert adapter._max_new_tokens == 12288+ assert (adapter._temperature, adapter._top_p) == (0.1, 1.0)+ assert adapter._chat_template_kwargs == {"enable_thinking": False}+ assert adapter._allowed_instructions == frozenset({"grounding"})+ assert adapter._meter_pages is True+ assert adapter.max_concurrent_dispatch() == 128+ assert adapter._extra_launch_args == ["--disable-radix-cache"]++def test_default_routes_to_sglang_vision_extract_bundle_only() -> None:assert _ADAPTER in yaml.safe_load((_BUNDLES / "transformers5.yaml").read_text())["adapters"]for bundle in sorted(_BUNDLES.glob("*.yaml")):expected = bundle.name == "sglang-vision-extract.yaml"assert (_MODEL in match_bundle_models(bundle, _MODELS)) == expected, bundle.name+ assert (f"{_MODEL}:markdown" in match_bundle_models(bundle, _MODELS)) == expected, bundle.name+ assert (f"{_MODEL}:transformers" in match_bundle_models(bundle, _MODELS)) == (+ bundle.name == "transformers5.yaml"+ )