Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(examples): add image OCR and fixed-page evaluation

svonavaf7ba07fecea1
diff --git a/examples/document-to-markdown/.env.example b/examples/document-to-markdown/.env.example
index 535bc541f..ee9f66e3d 100644
--- a/examples/document-to-markdown/.env.example
+++ b/examples/document-to-markdown/.env.example
@@ -1,2 +1,2 @@
-SIE_CLUSTER_URL=http://localhost:8080
+SIE_URL=http://localhost:8080
SIE_API_KEY=
diff --git a/examples/document-to-markdown/README.md b/examples/document-to-markdown/README.md
index 3600e27a5..60e0b2070 100644
--- a/examples/document-to-markdown/README.md
+++ b/examples/document-to-markdown/README.md
@@ -170,13 +170,61 @@ pip install "sie-server[local]"
sie-server serve
```
-For SIE Cloud, change only the endpoint and key:
+To use another SIE deployment, change only the endpoint and optional key:
```bash
-SIE_CLUSTER_URL=https://api.superlinked.com
+SIE_URL=https://your-sie-server.example
SIE_API_KEY=...
```
+`SIE_URL` takes precedence over the supported legacy `SIE_CLUSTER_URL` variable.
+
+## Page-image OCR and a reproducible 24-page evaluation
+
+To convert an image through the ordinary public SDK:
+
+```bash
+export SIE_URL=https://your-sie-server.example
+uv run convert-image page.png --out page.md
+```
+
+The command uses `SIEClient.extract`, the original encoded image bytes, and
+`lightonai/LightOnOCR-3-4B` by default. Use `--model` for another compatible
+Markdown extraction model. It passes `max_new_tokens=4096`, `temperature=0.1`,
+and `top_p=1.0`, and saves returned Markdown unchanged. The endpoint can be
+hosted anywhere; an API key is optional when the endpoint permits it. This
+single-image convenience command uses the SDK's normal capacity handling.
+
+The separate [fixed 24-page evaluation kit](https://huggingface.co/datasets/superlinked/sie-task-evidence/tree/8f287c3789438c81b4f094e8a96861d5805b101d/document-to-markdown/2026-10-09/lightonocr3-fixed24-completion-diagnostic-v1)
+contains exact PNG/PDF inputs, source attribution, both annotation views,
+saved Markdown, quality scores, and portable rerun and scoring scripts. It
+covers 24 document families, with 49 reading-order and 51 table checks.
+The correlated checks are averaged within each page, then equally across all
+24 pages. The saved SIE result is **81.25% against unchanged original gold**
+and **87.5% against the separately pinned, source-checked annotation view**.
+Three unknown outcomes remain in both denominators. Saved comparator coverage
+differs, so the kit does not establish a fair headline ranking or a native
+retail cost ratio. It keeps the measured checkpoint separate from later
+public revisions whose equivalence remains unresolved.
+
+Download the archive at its immutable dataset revision and check its digest:
+
+```bash
+curl -fL 'https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/8f287c3789438c81b4f094e8a96861d5805b101d/document-to-markdown/2026-10-09/lightonocr3-fixed24-completion-diagnostic-v1/markdown24-portable-kit.tar.gz' -o markdown24-portable-kit.tar.gz
+printf '%s %s\n' '329b6b8a8c58fd8bf0c1d917cc8d736093041f900a348383a59424111972c9ab' 'markdown24-portable-kit.tar.gz' | sha256sum --check
+mkdir markdown24-kit
+tar -xzf markdown24-portable-kit.tar.gz -C markdown24-kit
+```
+
+Follow the kit's README for the pinned Python 3.12 SDK and genuine
+`olmocr==0.4.27` scoring environment. Its `rerun_sie.py` accepts `SIE_URL`
+and uses one physical extraction POST per page, with no warmup or automatic
+resending of unknown outcomes. It records all 24 outcomes and stops after a
+nonreceived result. Its scorer explicitly selects original or source-valid
+gold; downloaded saved scores need no model or scoring run to inspect.
+The 24-page OCR evaluation is independent of the four-PDF Docling
+demonstration and its 25 checks above.
+
## Source and result layout
In this repository, and nothing else:
diff --git a/examples/document-to-markdown/document_to_markdown/config.py b/examples/document-to-markdown/document_to_markdown/config.py
index 04b9fb576..0eebd5d8a 100644
--- a/examples/document-to-markdown/document_to_markdown/config.py
+++ b/examples/document-to-markdown/document_to_markdown/config.py
@@ -99,7 +99,7 @@ def load_config() -> AppConfig:
raw = _load_yaml()
cluster_raw = raw["cluster"]
cluster = ClusterConfig(
- url=os.environ.get("SIE_CLUSTER_URL", cluster_raw["url"]).rstrip("/"),
+ url=os.environ.get("SIE_URL", os.environ.get("SIE_CLUSTER_URL", cluster_raw["url"])).rstrip("/"),
api_key=os.environ.get("SIE_API_KEY", cluster_raw.get("api_key", "")),
model=str(cluster_raw["model"]),
profile=str(cluster_raw.get("profile", "default")),
diff --git a/examples/document-to-markdown/document_to_markdown/ocr.py b/examples/document-to-markdown/document_to_markdown/ocr.py
new file mode 100644
index 000000000..f81261d8e
--- /dev/null
+++ b/examples/document-to-markdown/document_to_markdown/ocr.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+
+import argparse
+import os
+from pathlib import Path
+
+from dotenv import load_dotenv
+from sie_sdk import SIEClient
+from sie_sdk.types import Item
+
+from document_to_markdown.config import ROOT
+
+DEFAULT_MODEL = "lightonai/LightOnOCR-3-4B"
+
+
+def convert_image(image: Path, *, sie_url: str, model: str = DEFAULT_MODEL, timeout_s: float = 360) -> str:
+ image_bytes = image.read_bytes()
+ client = SIEClient(sie_url, api_key=os.environ.get("SIE_API_KEY") or None, timeout_s=timeout_s)
+ try:
+ result = client.extract(
+ model,
+ Item(id=image.stem, images=[image_bytes]),
+ options={"max_new_tokens": 4096, "temperature": 0.1, "top_p": 1.0},
+ )
+ if result.get("error"):
+ raise RuntimeError(str(result["error"]))
+ markdown = result.get("data", {}).get("markdown")
+ if not isinstance(markdown, str) or not markdown.strip():
+ raise RuntimeError("Model returned no Markdown")
+ return markdown
+ finally:
+ client.close()
+
+
+def main() -> None:
+ load_dotenv(ROOT / ".env")
+ parser = argparse.ArgumentParser(description="Convert a page image to Markdown through a compatible SIE URL")
+ parser.add_argument("image", type=Path)
+ parser.add_argument("--sie-url", default=os.environ.get("SIE_URL", "http://localhost:8080"))
+ parser.add_argument("--model", default=DEFAULT_MODEL)
+ parser.add_argument("--timeout", type=float, default=360)
+ parser.add_argument("--out", required=True, type=Path)
+ args = parser.parse_args()
+ # Reserve the output before dispatch so an existing result is never replaced.
+ output = args.out.open("x", encoding="utf-8")
+ try:
+ with output:
+ markdown = convert_image(args.image, sie_url=args.sie_url, model=args.model, timeout_s=args.timeout)
+ output.write(markdown)
+ except BaseException:
+ args.out.unlink(missing_ok=True)
+ raise
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/document-to-markdown/pyproject.toml b/examples/document-to-markdown/pyproject.toml
index 784905745..261ed02a3 100644
--- a/examples/document-to-markdown/pyproject.toml
+++ b/examples/document-to-markdown/pyproject.toml
@@ -14,6 +14,7 @@ dependencies = [
[project.scripts]
fetch-documents = "document_to_markdown.fetch:main"
convert-documents = "document_to_markdown.convert:main"
+convert-image = "document_to_markdown.ocr:main"
eval-documents = "document_to_markdown.evaluate:main"
verify-run = "document_to_markdown.verify:main"
diff --git a/examples/document-to-markdown/tests/test_config.py b/examples/document-to-markdown/tests/test_config.py
index 72f023daa..16315dccd 100644
--- a/examples/document-to-markdown/tests/test_config.py
+++ b/examples/document-to-markdown/tests/test_config.py
@@ -35,3 +35,12 @@ def test_select_documents_keeps_requested_order() -> None:
def test_select_documents_rejects_unknown_slug() -> None:
with pytest.raises(ValueError, match="Unknown document slug"):
select_documents(load_config(), ["missing"])
+
+
+def test_sie_url_takes_precedence_with_legacy_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_CLUSTER_URL", "https://legacy.example/prefix/")
+ monkeypatch.setenv("SIE_URL", "https://chosen.example/gateway/")
+ assert load_config().cluster.url == "https://chosen.example/gateway"
+
+ monkeypatch.delenv("SIE_URL")
+ assert load_config().cluster.url == "https://legacy.example/prefix"
diff --git a/examples/document-to-markdown/tests/test_ocr.py b/examples/document-to-markdown/tests/test_ocr.py
new file mode 100644
index 000000000..629266a56
--- /dev/null
+++ b/examples/document-to-markdown/tests/test_ocr.py
@@ -0,0 +1,104 @@
+from __future__ import annotations
+
+import base64
+import sys
+from pathlib import Path
+from typing import Any
+
+import httpx
+import msgpack
+import pytest
+from sie_sdk import RequestError
+
+from document_to_markdown import ocr
+from document_to_markdown.ocr import convert_image
+
+PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aN3cAAAAASUVORK5CYII=")
+
+
[email protected]("url", ["http://localhost:8080", "https://chosen.example/gateway"])
+def test_original_png_options_and_markdown_through_actual_sdk(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, url: str
+) -> None:
+ image = tmp_path / "page.png"
+ image.write_bytes(PNG)
+ calls: list[httpx.Request] = []
+ clients: list[httpx.Client] = []
+ markdown = "# Heading\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n"
+ client_type = httpx.Client
+
+ def reply(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ return httpx.Response(
+ 200,
+ content=msgpack.packb({"items": [{"entities": [], "data": {"markdown": markdown}}]}, use_bin_type=True),
+ headers={"Content-Type": "application/msgpack"},
+ )
+
+ def create_client(**kwargs: Any) -> httpx.Client:
+ client = client_type(transport=httpx.MockTransport(reply), **kwargs)
+ clients.append(client)
+ return client
+
+ monkeypatch.setattr("sie_sdk.client.sync.httpx.Client", create_client)
+ monkeypatch.setenv("SIE_API_KEY", "test-key")
+ assert convert_image(image, sie_url=url, model="example/model") == markdown
+ assert len(calls) == 1
+ assert str(calls[0].url) == f"{url}/v1/extract/example/model"
+ assert calls[0].headers["Authorization"] == "Bearer test-key"
+ body = msgpack.unpackb(calls[0].content, raw=False)
+ assert body["items"][0]["images"][0]["data"] == PNG
+ assert body["params"]["options"] == {"max_new_tokens": 4096, "temperature": 0.1, "top_p": 1.0}
+ assert clients[0].is_closed
+
+
+def test_terminal_error_closes_client(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ image = tmp_path / "page.png"
+ image.write_bytes(PNG)
+ clients: list[httpx.Client] = []
+ client_type = httpx.Client
+
+ def create_client(**kwargs: Any) -> httpx.Client:
+ transport = httpx.MockTransport(lambda request: httpx.Response(400, json={"error": "invalid request"}))
+ client = client_type(transport=transport, **kwargs)
+ clients.append(client)
+ return client
+
+ monkeypatch.setattr("sie_sdk.client.sync.httpx.Client", create_client)
+ with pytest.raises(RequestError):
+ convert_image(image, sie_url="https://chosen.example")
+ assert clients[0].is_closed
+
+
+def test_cli_failed_conversion_removes_new_output(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ output = tmp_path / "page.md"
+ monkeypatch.setattr(sys, "argv", ["convert-image", str(tmp_path / "missing.png"), "--out", str(output)])
+ with pytest.raises(FileNotFoundError):
+ ocr.main()
+ assert not output.exists()
+
+
+def test_cli_existing_output_preserved_without_dispatch(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ output = tmp_path / "page.md"
+ output.write_text("existing result", encoding="utf-8")
+ calls: list[Path] = []
+
+ def convert(image: Path, **kwargs: Any) -> str:
+ calls.append(image)
+ return "replacement"
+
+ monkeypatch.setattr(ocr, "convert_image", convert)
+ monkeypatch.setattr(sys, "argv", ["convert-image", "page.png", "--out", str(output)])
+ with pytest.raises(FileExistsError):
+ ocr.main()
+ assert output.read_text(encoding="utf-8") == "existing result"
+ assert calls == []
+
+
+def test_cli_success_preserves_markdown(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ output = tmp_path / "page.md"
+ markdown = "# Résumé\n\n| A | B |\n|---|---|\n"
+ monkeypatch.setattr(ocr, "convert_image", lambda *args, **kwargs: markdown)
+ monkeypatch.setattr(sys, "argv", ["convert-image", "page.png", "--out", str(output)])
+ ocr.main()
+ assert output.read_text(encoding="utf-8") == markdown