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
examples: add document-ocr (multi-model OCR pipeline)
Filip Makraduli524794246023
diff --git a/examples/README.md b/examples/README.mdindex b19b74bd9..cb92870ec 100644--- a/examples/README.md+++ b/examples/README.md@@ -17,6 +17,7 @@ service keys.| [Private fine-tuned compliance RAG](./regulatory-rag) | Hot-loading a domain LoRA encoder and a custom token-pruning adapter on SIE | `encode`, `score`, `extract` | Custom SIE Docker image, GPU recommended | Advanced runnable example || [Build a multimodal wine recommender with OCR](./wine-recommender) | Combining preference-based retrieval with OCR-driven label detection in one UI | `encode`, `score`, `extract` | Docker Compose app plus local SIE endpoint; API key optional for unauthenticated SIE | Runnable demo || [Build a multi-modal product classifier with embeddings](./taxonomy-classification) | Evaluating text, image, NLI, and reranking approaches for hierarchical product taxonomy classification | `extract`, `encode`, `score` | SIE endpoint, Shopify dataset prep via `uv run` scripts, standalone `uv` project | Runnable evaluation example |+| [Swap an OCR model with one identifier change](./document-ocr) | Driving recognition (VLM-OCR), structured extraction (Donut), and zero-shot NER (GLiNER) through the same `extract` call by swapping the model ID | `extract` | Docker Compose plus Node UI, no API key required, hosted version on [Hugging Face Spaces](https://huggingface.co/spaces/superlinked/document-ocr) | Runnable demo |For docs publishing, lead with the quickest runnable demos, then use thebenchmark and evaluation examples for deeper technical users.diff --git a/examples/document-ocr/.env.example b/examples/document-ocr/.env.examplenew file mode 100644index 000000000..17520ba39--- /dev/null+++ b/examples/document-ocr/.env.example@@ -0,0 +1,3 @@+SIE_URL=http://localhost:8080+SIE_API_KEY=+PORT=3032diff --git a/examples/document-ocr/.gitignore b/examples/document-ocr/.gitignorenew file mode 100644index 000000000..2e8157a95--- /dev/null+++ b/examples/document-ocr/.gitignore@@ -0,0 +1,3 @@+node_modules/+.env+*.logdiff --git a/examples/document-ocr/README.md b/examples/document-ocr/README.mdnew file mode 100644index 000000000..91559ebb4--- /dev/null+++ b/examples/document-ocr/README.md@@ -0,0 +1,293 @@+# document-ocr++**Swap an OCR model with one identifier change. See what changes in the output.**++Three different model architectures, one inference server, one SDK call. This+demo is a working browser UI that runs document images through a recognition+model, a fine-tuned document model, and a zero-shot NER, all behind the same+`client.extract(...)` API. Pick a model from any of the three dropdowns; watch+the pipeline run again with that one identifier swapped.++<!-- Drop screenshots or a GIF here. Suggested:+ docs/cover.png (the browser UI mid-run)+ docs/run.gif (a sample to typed fields end to end) -->++++> Built on [SIE](https://github.com/superlinked/sie), the open-source inference+> engine from Superlinked. Apache 2.0. Run it locally with `docker compose up`;+> a hosted Hugging Face Space is coming soon.++---++## What this demo actually shows++OCR is almost never a single-model problem. A real pipeline has three concerns:++1. **Recognition** (image to text). Modern VLM-OCRs like Florence-2 and+ LightOnOCR take a whole document and emit Markdown.+2. **Structured extraction** (image to JSON). End-to-end document models like+ Donut on CORD skip the text intermediate entirely and emit nested JSON+ directly: `{ "total": { "total_price": "28.52" }, ... }`.+3. **Zero-shot NER on the recognized text** (text to typed fields). When you+ want to declare entity labels at query time (e.g. `["merchant", "total",+ "date"]`) instead of fine-tuning a new model.++The SIE pitch this demo makes visceral: **all three are the same SDK call,+the same auth, the same rate-limit budget, the same Docker image.** Only the+model ID changes.++```python+# Recognition: VLM-OCR, returns Markdown+client.extract(+ "lightonai/LightOnOCR-2-1B",+ Item(images=[image_bytes]),+)++# Structured: end-to-end Donut, returns JSON tree+client.extract(+ "naver-clova-ix/donut-base-finetuned-cord-v2",+ Item(images=[image_bytes]),+)++# NER: zero-shot, returns typed entities+client.extract(+ "urchade/gliner_multi-v2.1",+ Item(text=recognized_markdown),+ labels=["merchant", "total", "date", "line_item"],+)+```++Each cell in the demo's UI has a **"See the SIE call"** disclosure that shows+the exact line of code that just ran. Swap a dropdown, the snippet updates with+the one parameter that changed.++---++## Run it++There are two ways to try this demo:++- **Hosted on Hugging Face Spaces** (zero install, just click):+ [superlinked/document-ocr](https://huggingface.co/spaces/superlinked/document-ocr)+- **Local Docker** (steps below):++```bash+git clone https://github.com/superlinked/sie+cd sie/examples/document-ocr+npm install+npm start+```++`npm start` runs `docker compose up -d` (boots `ghcr.io/superlinked/sie-server:latest-cpu-transformers5`,+preloads three small models), then starts a Node UI server and opens+http://localhost:3032.++- **First start**: ~5-8 minutes on a typical home connection (~5 GB of+ LightOnOCR + Donut + GLiNER weights download from Hugging Face into a+ Docker volume; LightOnOCR is the big one at ~4 GB).+- **Subsequent restarts**: 30-60 seconds. Weights are cached in+ `/app/.cache/huggingface` inside the `sie-cache` Docker volume.+- **Per-sample click**: ~20-30 s on Linux x86_64 native, ~60-90 s on Apple+ Silicon (Rosetta tax on the amd64-only SIE image).++```bash+docker compose down # when done+```++**GPU variant** (Linux + NVIDIA, makes GLM-OCR / Paddle / LightOnOCR fast):++```bash+npm run start:gpu # uses compose.gpu.yml + latest-cuda12-default+```++---++## Specific things to try in the UI++The UI itself surfaces these as a "Try these moments" strip above the panels,+so a visitor sees the prompts even without reading the README. The same four+moments, with a little more context:++1. **Click any sample → open the "See the SIE call" disclosure under+ "Recognition".** You'll see the actual `client.extract(...)` call with+ the LightOnOCR-2-1B model ID. The disclosure updates when any dropdown+ changes; only the model string changes between calls.+2. **Switch the Structured dropdown** from `donut-cord-v2` to+ `donut-rvlcdip`. Same Donut architecture, different fine-tuning. The+ output shape changes from a CORD-shaped JSON tree to a document-type+ classification. Same model class, same SDK call, completely different+ output category.+3. **Switch the NER dropdown** from `gliner_multi-v2.1` to `NuNER_Zero`.+ Different model family entirely (NuMind vs urchade), same SDK call, same+ labels. The architecture-swap-with-one-string-change pitch.+4. **Compare two samples back to back**: click `receipt.png` (Donut on CORD+ dominates because that's exactly its fine-tuning distribution), then+ click `letter.png` (the opposite: Donut produces garbage shaped like+ CORD; recognition + GLiNER carry the pipeline).++Each of these illustrates a concrete SIE pitch: model swap, output-shape+swap, quality swap, document-type fit.++---++## Why SIE specifically for OCR++You could build this demo with three SaaS APIs (one embedding/OCR provider,+one document AI provider, one NER provider). It would work. It would also be:++- **Three auth flows.** Three API keys, three rate-limit budgets, three+ outage stories.+- **Three SDKs.** Each with its own retry semantics, error model, input+ encoding.+- **Three deployment stories.** When you eventually want to run this in your+ own VPC (because, for instance, you can't send customer PDFs to a third+ party), you have three Helm charts, three sets of secrets to rotate.++SIE collapses that into one process:++- **One server, three primitives.** `encode`, `score`, `extract`. This demo+ uses `extract` for all three model classes; the other two cover semantic+ search and reranking.+- **One SDK call.** `client.extract(model_id, item)` works for VLM-OCR,+ end-to-end document AI, and zero-shot NER. Swap the model ID alone.+- **Open source, runs in your VPC.** Customer documents never leave the+ host running this compose. Compliance teams stop blocking you.+- **85+ models, swappable.** Need a different OCR-VLM, a domain-tuned+ GLiNER, a layout model, a multilingual reranker, or a custom LoRA?+ All live in the same catalog. Swap a model ID in `src/config.ts`.+- **Same code laptop to Kubernetes.** SIE ships a Helm chart, KEDA+ autoscaling, and Terraform modules for GKE/EKS. The code in this demo+ runs unchanged against a production cluster; only the URL changes.++---++## Architecture in one diagram++```+ ┌───────────────────────────┐+ │ one document image │+ └─────────────┬─────────────┘+ │+ ┌──────────────▼──────────────┐+ │ one SIE server │+ │ client.extract(model_id) │+ └──┬───────────┬───────────┬──┘+ │ │ │+ ┌──────▼──┐ ┌─────▼─────┐ ┌──▼──────┐+ │ VLM- │ │ Donut │ │ GLiNER │+ │ OCR │ │ (E2E) │ │ (NER) │+ │ Markdown│ │ JSON │ │ entities│+ └─────────┘ └───────────┘ └─────────┘+```++The Node server in `web/server.ts` chains the three calls and streams progress+via Server-Sent Events. The browser renders each panel as the corresponding+event lands.++---++## Model lineup++The dropdowns expose nine models across three categories. Models marked+"alternate" are listed in the UI but lazy-load on first click; the demo+auto-disables anything not in the running server's `/v1/models` catalog (so+GPU-only models show up disabled on the CPU compose).++| Stage | Default (preloaded) | Alternates |+|---|---|---|+| Recognition | `lightonai/LightOnOCR-2-1B` (2.1B, Markdown output) | `PaddlePaddle/PaddleOCR-VL-1.5` (GPU image); `zai-org/GLM-OCR` (9B, GPU only) |+| Structured | `naver-clova-ix/donut-base-finetuned-cord-v2` | `naver-clova-ix/donut-base-finetuned-docvqa`; `naver-clova-ix/donut-base-finetuned-rvlcdip` (16-class document classifier) |+| Zero-shot NER | `urchade/gliner_multi-v2.1` | `urchade/gliner_large-v2.1`; `urchade/gliner_multi_pii-v1`; `numind/NuNER_Zero` (different architecture, useful contrast against GLiNER) |++Defaults are pinned in [`src/config.ts`](src/config.ts). To add a new model,+add a `ModelOption` entry and a HuggingFace model ID; SIE handles the rest.+The demo runs on the `latest-cpu-transformers5` SIE image; this is the+bundle where `lighton_ocr` / `glm_ocr` / `paddle` adapters live. The+Florence-2 family ships in SIE's `default` bundle (which pins+`transformers<5`) and is not loadable from this image. See+[sie-internal#828](https://github.com/superlinked/sie-internal/issues/828)+for the bundle-composition story.++---++## What's in the box++```+src/+ config.ts model lineup (defaults + alternates per category)+ types.ts SampleDoc, ExtractedField, TriageResult+ events.ts typed SSE events streamed to the browser+ ocr.ts VLM-OCR caller (Florence-2, LightOnOCR, etc.)+ donut.ts image-to-JSON caller (Donut variants)+ extract.ts GLiNER caller for zero-shot NER on text+ pipeline.ts recognition → structured + NER orchestrator++data/samples/ 6 synthetic document images (receipt, invoice, business+ card, event poster, presentation slide, business letter)+ + index.json metadata (labels per document type)+scripts/+ generate_samples.py regenerates the bundled images via Pillow++web/+ server.ts Node http server, /api/run SSE endpoint, static assets+ public/ index.html, style.css, app.js (vanilla, no build step)++compose.yml CPU compose (local docker compose up)+compose.gpu.yml CUDA compose with NVIDIA device reservations+```++**~1,400 lines total.** No bundler, no React, no build step. The UI is vanilla+HTML + CSS + JavaScript driven by `EventSource` for the SSE stream from SIE.++---++## Extend it++- **Add a layout step.** Some VLM-OCR models return per-region text and+ bounding boxes (e.g. PaddleOCR-VL with `task: "layout"`). Render them as+ overlays on the source image to demonstrate layout-aware OCR.+- **Switch to multi-page PDFs.** Replace `Item.images` with+ `Item.document` and use SIE's Docling adapter. Docling parses entire PDFs+ with layout + table-structure detection in one call.+- **Embed the recognized text.** Pair `extract` with `client.encode` to+ build a semantic search index over your processed documents. The SDK+ call is the same; the model ID picks an embedding model from SIE's 85++ catalog.+- **Fine-tune for your schema.** If your documents look like one of the+ Donut training corpora (CORD, RVL-CDIP, DocVQA), pick the matching+ variant and skip the GLiNER step entirely.+- **Add a reranker after retrieval.** `client.score(reranker_id, query,+ documents)` does cross-encoder reranking; many real-world OCR pipelines+ need a "did we extract the right field" verification pass.++---++## Honest scope and known limits++- **Apple Silicon performance is poor** because the SIE Docker image is+ `linux/amd64` only and runs through Rosetta. Per-call latency on a Mac+ is ~60-90 s for LightOnOCR; on Linux x86_64 it is ~20 s.+- **GLM-OCR and Paddle are GPU-only in practice.** They need CUDA, so the+ CPU compose lists them but auto-disables them in the dropdown. The CUDA+ image variant (used by `compose.gpu.yml`) loads them.+- **This is a demo, not a production OCR pipeline.** The bundled sample+ images are synthetic; production OCR needs real-world layout coverage,+ per-merchant tuning, and human review hooks.++---++## Built with++- [SIE](https://github.com/superlinked/sie) (Apache 2.0): the inference+ engine that hosts all three model classes+- [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B)+ (Apache 2.0): LightOn's Pixtral+Qwen3 OCR-VLM+- [Donut](https://huggingface.co/naver-clova-ix/donut-base-finetuned-cord-v2)+ (MIT): NAVER Clova's end-to-end document understanding model+- [GLiNER](https://huggingface.co/urchade/gliner_multi-v2.1) (Apache 2.0):+ Urchade's zero-shot NER+- Sample images: programmatically generated with Pillow; no real customer+ data++Star [superlinked/sie](https://github.com/superlinked/sie) if this was useful.diff --git a/examples/document-ocr/compose.gpu.yml b/examples/document-ocr/compose.gpu.ymlnew file mode 100644index 000000000..a3b788616--- /dev/null+++ b/examples/document-ocr/compose.gpu.yml@@ -0,0 +1,37 @@+services:+ sie:+ # GPU compose uses the transformers5 bundle so we can serve LightOnOCR /+ # GLM-OCR / Paddle (their adapters need transformers>=5). Florence-2 is+ # in the catalog but its tokenizer relies on a transformers<5 API and is+ # therefore unavailable on this image (sie-internal#828, #832). The CPU+ # compose covers Florence-2.+ image: ghcr.io/superlinked/sie-server:latest-cuda12-transformers5+ command:+ - serve+ - --port+ - "8080"+ - --preload+ - lightonai/LightOnOCR-2-1B,naver-clova-ix/donut-base-finetuned-cord-v2,urchade/gliner_multi-v2.1,zai-org/GLM-OCR,PaddlePaddle/PaddleOCR-VL-1.5+ ports:+ - "8080:8080"+ restart: unless-stopped+ healthcheck:+ test: ["CMD", "curl", "-fsS", "http://localhost:8080/healthz"]+ interval: 5s+ timeout: 3s+ retries: 120+ start_period: 360s+ volumes:+ - sie-cache:/app/.cache/huggingface+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: all+ capabilities: [gpu]++volumes:+ sie-cache:+ name: sie-cache+ external: falsediff --git a/examples/document-ocr/compose.yml b/examples/document-ocr/compose.ymlnew file mode 100644index 000000000..6b090791b--- /dev/null+++ b/examples/document-ocr/compose.yml@@ -0,0 +1,34 @@+services:+ sie:+ # transformers5 bundle so LightOnOCR-2-1B (the recognition default) loads.+ # Florence-2 family is incompatible with transformers>=5 (tokenizer API+ # change), so the UI auto-disables those entries on this image+ # (sie-internal#828 tracks unifying the bundles).+ image: ghcr.io/superlinked/sie-server:latest-cpu-transformers5+ # linux/amd64 is a no-op on x86_64 Linux hosts; on Apple Silicon it forces+ # Rosetta translation (slower but works for local testing).+ platform: linux/amd64+ command:+ - serve+ - --port+ - "8080"+ - --preload+ - lightonai/LightOnOCR-2-1B,naver-clova-ix/donut-base-finetuned-cord-v2,urchade/gliner_multi-v2.1+ ports:+ - "8080:8080"+ restart: unless-stopped+ healthcheck:+ test: ["CMD", "curl", "-fsS", "http://localhost:8080/healthz"]+ interval: 5s+ timeout: 3s+ retries: 90+ start_period: 240s+ volumes:+ # SIE's image sets HF_HOME=/app/.cache/huggingface; mount the volume+ # there so the model weights survive `docker compose down/up`.+ - sie-cache:/app/.cache/huggingface++volumes:+ sie-cache:+ name: sie-cache+ external: falsediff --git a/examples/document-ocr/data/samples/README.md b/examples/document-ocr/data/samples/README.mdnew file mode 100644index 000000000..97b3de996--- /dev/null+++ b/examples/document-ocr/data/samples/README.md@@ -0,0 +1,18 @@+# Bundled sample documents++Six synthetic, public-domain images covering the document shapes most+real-world OCR pipelines hit:++- `receipt.png`: printed grocery receipt, line items + totals+- `invoice.png`: vendor invoice, multi-column form layout+- `business-card.png`: tight contact card, mixed text sizes+- `table.png`: dense numerical table with totals row+- `handwritten.png`: jittered text that simulates informal handwriting+- `multi-column.png`: two-column newspaper-style layout where reading order+ matters++`index.json` carries metadata for each: the GLiNER labels we ask for, plus a+short description shown in the UI.++Regenerate with `python scripts/generate_samples.py`. Pillow is the only+dep; no real customer data is involved.diff --git a/examples/document-ocr/data/samples/business-card.png b/examples/document-ocr/data/samples/business-card.pngnew file mode 100644index 000000000..509379d8bBinary files /dev/null and b/examples/document-ocr/data/samples/business-card.png differdiff --git a/examples/document-ocr/data/samples/event-poster.png b/examples/document-ocr/data/samples/event-poster.pngnew file mode 100644index 000000000..7ffe29fdfBinary files /dev/null and b/examples/document-ocr/data/samples/event-poster.png differdiff --git a/examples/document-ocr/data/samples/index.json b/examples/document-ocr/data/samples/index.jsonnew file mode 100644index 000000000..8ae33cfa9--- /dev/null+++ b/examples/document-ocr/data/samples/index.json@@ -0,0 +1,87 @@+[+ {+ "id": "receipt",+ "filename": "receipt.png",+ "label": "Grocery receipt",+ "description": "Printed receipt with line items, subtotal, tax, total. Donut on CORD reads this end-to-end.",+ "labels": [+ "merchant",+ "date",+ "line_item",+ "subtotal",+ "tax",+ "total",+ "payment_method"+ ]+ },+ {+ "id": "invoice",+ "filename": "invoice.png",+ "label": "Vendor invoice",+ "description": "Multi-column invoice with billing party, line items, subtotal, tax, total.",+ "labels": [+ "vendor",+ "invoice_number",+ "date",+ "due_date",+ "billing_party",+ "line_item",+ "total"+ ]+ },+ {+ "id": "business-card",+ "filename": "business-card.png",+ "label": "Business card",+ "description": "Tight layout, mixed text sizes, multiple contact fields. Good NER showcase.",+ "labels": [+ "company",+ "person",+ "role",+ "email",+ "phone",+ "address",+ "website"+ ]+ },+ {+ "id": "event-poster",+ "filename": "event-poster.png",+ "label": "Event poster",+ "description": "Large-text poster with title, date, artists, ticket info. Florence-2 OCR's home turf.",+ "labels": [+ "event",+ "date",+ "venue",+ "artist",+ "price",+ "organization"+ ]+ },+ {+ "id": "slide",+ "filename": "slide.png",+ "label": "Presentation slide",+ "description": "Roadmap slide with title and three numbered items. Clean printed text on a single background.",+ "labels": [+ "initiative",+ "person",+ "date",+ "quarter"+ ]+ },+ {+ "id": "letter",+ "filename": "letter.png",+ "label": "Business letter",+ "description": "Short printed business letter with sender, date, recipient, body, and signature.",+ "labels": [+ "company",+ "person",+ "address",+ "date",+ "amount",+ "phone"+ ]+ }+]\ No newline at end of filediff --git a/examples/document-ocr/data/samples/invoice.png b/examples/document-ocr/data/samples/invoice.pngnew file mode 100644index 000000000..e3ff3bbbbBinary files /dev/null and b/examples/document-ocr/data/samples/invoice.png differdiff --git a/examples/document-ocr/data/samples/letter.png b/examples/document-ocr/data/samples/letter.pngnew file mode 100644index 000000000..4be5ce6dcBinary files /dev/null and b/examples/document-ocr/data/samples/letter.png differdiff --git a/examples/document-ocr/data/samples/receipt.png b/examples/document-ocr/data/samples/receipt.pngnew file mode 100644index 000000000..85d9874b2Binary files /dev/null and b/examples/document-ocr/data/samples/receipt.png differdiff --git a/examples/document-ocr/data/samples/slide.png b/examples/document-ocr/data/samples/slide.pngnew file mode 100644index 000000000..2a6612530Binary files /dev/null and b/examples/document-ocr/data/samples/slide.png differdiff --git a/examples/document-ocr/docs/.gitkeep b/examples/document-ocr/docs/.gitkeepnew file mode 100644index 000000000..e69de29bbdiff --git a/examples/document-ocr/package-lock.json b/examples/document-ocr/package-lock.jsonnew file mode 100644index 000000000..3a49e90d2--- /dev/null+++ b/examples/document-ocr/package-lock.json@@ -0,0 +1,617 @@+{+ "name": "document-ocr",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "document-ocr",+ "version": "0.1.0",+ "dependencies": {+ "@superlinked/sie-sdk": "^0.3.1"+ },+ "devDependencies": {+ "@types/node": "^22.10.0",+ "tsx": "^4.21.0",+ "typescript": "^5.7.2"+ },+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",+ "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz",+ "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz",+ "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz",+ "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz",+ "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz",+ "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz",+ "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz",+ "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz",+ "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz",+ "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz",+ "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz",+ "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz",+ "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz",+ "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz",+ "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz",+ "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz",+ "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz",+ "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz",+ "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz",+ "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz",+ "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz",+ "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz",+ "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz",+ "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz",+ "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz",+ "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@msgpack/msgpack": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz",+ "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==",+ "license": "ISC",+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/@superlinked/sie-sdk": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/@superlinked/sie-sdk/-/sie-sdk-0.3.2.tgz",+ "integrity": "sha512-SqNXHzBLsXHjvrZRyLm/RCia3jqLkf1fMMRmQFS9URllROgTvSSRazccHwUQovHiytHfGdIqNZCwDShFikjwKg==",+ "license": "MIT",+ "dependencies": {+ "@msgpack/msgpack": "^3.0.0"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@types/node": {+ "version": "22.19.18",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.18.tgz",+ "integrity": "sha512-9v00a+dn2yWVsYDEunWC4g/TcRKVq3r8N5FuZp7u0SGrPvdN9c2yXI9bBuf5Fl0hNCb+QTIePTn5pJs2pwBOQQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/esbuild": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz",+ "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.7",+ "@esbuild/android-arm": "0.27.7",+ "@esbuild/android-arm64": "0.27.7",+ "@esbuild/android-x64": "0.27.7",+ "@esbuild/darwin-arm64": "0.27.7",+ "@esbuild/darwin-x64": "0.27.7",+ "@esbuild/freebsd-arm64": "0.27.7",+ "@esbuild/freebsd-x64": "0.27.7",+ "@esbuild/linux-arm": "0.27.7",+ "@esbuild/linux-arm64": "0.27.7",+ "@esbuild/linux-ia32": "0.27.7",+ "@esbuild/linux-loong64": "0.27.7",+ "@esbuild/linux-mips64el": "0.27.7",+ "@esbuild/linux-ppc64": "0.27.7",+ "@esbuild/linux-riscv64": "0.27.7",+ "@esbuild/linux-s390x": "0.27.7",+ "@esbuild/linux-x64": "0.27.7",+ "@esbuild/netbsd-arm64": "0.27.7",+ "@esbuild/netbsd-x64": "0.27.7",+ "@esbuild/openbsd-arm64": "0.27.7",+ "@esbuild/openbsd-x64": "0.27.7",+ "@esbuild/openharmony-arm64": "0.27.7",+ "@esbuild/sunos-x64": "0.27.7",+ "@esbuild/win32-arm64": "0.27.7",+ "@esbuild/win32-ia32": "0.27.7",+ "@esbuild/win32-x64": "0.27.7"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/get-tsconfig": {+ "version": "4.14.0",+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.0.tgz",+ "integrity": "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "resolve-pkg-maps": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"+ }+ },+ "node_modules/resolve-pkg-maps": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"+ }+ },+ "node_modules/tsx": {+ "version": "4.21.0",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",+ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "~0.27.0",+ "get-tsconfig": "^4.7.5"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ }+ }+}diff --git a/examples/document-ocr/package.json b/examples/document-ocr/package.jsonnew file mode 100644index 000000000..5de72cbc4--- /dev/null+++ b/examples/document-ocr/package.json@@ -0,0 +1,24 @@+{+ "name": "document-ocr",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "engines": {+ "node": ">=22"+ },+ "scripts": {+ "start": "docker compose up -d && tsx web/server.ts",+ "start:gpu": "docker compose -f compose.gpu.yml up -d && tsx web/server.ts",+ "ui": "tsx web/server.ts",+ "typecheck": "tsc -p tsconfig.json --noEmit",+ "regen-samples": "python3 scripts/generate_samples.py"+ },+ "dependencies": {+ "@superlinked/sie-sdk": "^0.3.1"+ },+ "devDependencies": {+ "@types/node": "^22.10.0",+ "tsx": "^4.21.0",+ "typescript": "^5.7.2"+ }+}diff --git a/examples/document-ocr/scripts/generate_samples.py b/examples/document-ocr/scripts/generate_samples.pynew file mode 100644index 000000000..58e5117bf--- /dev/null+++ b/examples/document-ocr/scripts/generate_samples.py@@ -0,0 +1,344 @@+"""Generate the bundled sample document images.++Synthetic, public-domain content: no real receipts/invoices/customer data.+Run once to regenerate `data/samples/*.png`. The output is committed; this+script is here so the fixtures are reproducible.+"""+from __future__ import annotations++import json+import random+from pathlib import Path++from PIL import Image, ImageDraw, ImageFont++OUT_DIR = Path(__file__).resolve().parents[1] / "data" / "samples"+OUT_DIR.mkdir(parents=True, exist_ok=True)+++def font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:+ candidates_regular = [+ "/System/Library/Fonts/Supplemental/Courier New.ttf",+ "/System/Library/Fonts/Menlo.ttc",+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",+ "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",+ ]+ candidates_bold = [+ "/System/Library/Fonts/Supplemental/Courier New Bold.ttf",+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf",+ "/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf",+ ]+ options = candidates_bold if bold else candidates_regular+ for p in options:+ if Path(p).is_file():+ return ImageFont.truetype(p, size)+ return ImageFont.load_default()+++def render_lines(lines: list[tuple[str, int, bool]], width: int = 480, padding: int = 24, line_height: int | None = None) -> Image.Image:+ height_estimate = padding * 2 + sum((line_height or sz + 6) for (_, sz, _) in lines)+ img = Image.new("RGB", (width, height_estimate), color=(255, 255, 255))+ draw = ImageDraw.Draw(img)+ y = padding+ for text, size, bold in lines:+ f = font(size, bold=bold)+ draw.text((padding, y), text, fill=(0, 0, 0), font=f)+ y += (line_height or size + 6)+ return img+++def make_receipt() -> Image.Image:+ lines = [+ ("ACME GROCERS", 22, True),+ ("123 Market Lane", 12, False),+ ("Springfield, IL 62701", 12, False),+ ("Tel: (555) 010-2034", 12, False),+ ("", 8, False),+ ("Date: 2026-04-12 Time: 14:32", 12, False),+ ("Cashier: Aki ", 12, False),+ ("--------------------------------", 12, False),+ ("Whole Wheat Bread 4.50", 14, False),+ ("Organic Milk 1L 3.20", 14, False),+ ("Bananas (1.2 kg) 2.40", 14, False),+ ("Free Range Eggs x12 6.99", 14, False),+ ("Coffee Beans 250g 9.75", 14, False),+ ("--------------------------------", 12, False),+ ("Subtotal 26.84", 14, False),+ ("Sales Tax (6.25%) 1.68", 14, False),+ ("TOTAL 28.52", 16, True),+ ("", 8, False),+ ("Paid: VISA ****1234", 12, False),+ ("Thank you, please come again!", 12, False),+ ]+ return render_lines(lines, width=460)+++def make_invoice() -> Image.Image:+ lines = [+ ("BLUERIDGE SUPPLIES, LLC", 20, True),+ ("Invoice No: INV-2026-0381", 14, True),+ ("Date Issued: 2026-03-22", 12, False),+ ("Due Date: 2026-04-21", 12, False),+ ("", 8, False),+ ("Bill To:", 13, True),+ ("Northwind Coffee Co.", 12, False),+ ("412 Pine Street, Suite 5", 12, False),+ ("Portland, OR 97204", 12, False),+ ("", 8, False),+ ("--------------------------------------------", 11, False),+ ("Description Qty Price Amount", 12, True),+ ("--------------------------------------------", 11, False),+ ("Espresso machine filter 4 45.00 180.00", 12, False),+ ("Replacement gasket 8 6.50 52.00", 12, False),+ ("Shop towels (case) 2 24.00 48.00", 12, False),+ ("Calibration service 1 95.00 95.00", 12, False),+ ("--------------------------------------------", 11, False),+ (" Subtotal 375.00", 12, False),+ (" Tax (8%) 30.00", 12, False),+ (" TOTAL 405.00", 14, True),+ ("", 8, False),+ ("Payment terms: Net 30. Wire to acct 4421-0119.", 11, False),+ ]+ return render_lines(lines, width=600)+++def make_business_card() -> Image.Image:+ img = Image.new("RGB", (520, 260), color=(255, 255, 255))+ draw = ImageDraw.Draw(img)+ draw.rectangle([(0, 0), (519, 22)], fill=(124, 93, 255))+ draw.text((20, 4), "STARGAZER ROBOTICS", fill=(255, 255, 255), font=font(13, bold=True))++ draw.text((30, 50), "Dr. Mira Okafor", fill=(0, 0, 0), font=font(22, bold=True))+ draw.text((30, 84), "Principal Research Engineer", fill=(60, 60, 80), font=font(14, bold=False))++ draw.text((30, 130), "Email: [email protected]", fill=(0, 0, 0), font=font(13, bold=False))+ draw.text((30, 155), "Phone: +1 (415) 555-0188", fill=(0, 0, 0), font=font(13, bold=False))+ draw.text((30, 180), "Office: 1900 Embarcadero, Oakland CA 94606", fill=(0, 0, 0), font=font(13, bold=False))+ draw.text((30, 210), "stargazer-robotics.com / @stargazer_rob", fill=(60, 60, 90), font=font(12, bold=False))++ return img+++def make_table() -> Image.Image:+ lines = [+ ("Q1 2026 Department Spend (in USD)", 18, True),+ ("Source: Internal finance, ledger close 2026-04-05", 11, False),+ ("", 6, False),+ ("Department Headcount Salary Cloud Travel Total", 13, True),+ ("------------------------------------------------------------", 11, False),+ ("Engineering 42 581,200 91,400 12,800 685,400", 13, False),+ ("Sales 18 240,300 4,100 38,900 283,300", 13, False),+ ("Marketing 11 168,750 7,900 15,200 191,850", 13, False),+ ("Operations 7 88,400 1,200 3,400 93,000", 13, False),+ ("Customer Success 12 148,900 2,400 9,500 160,800", 13, False),+ ("Legal & Compliance 4 72,600 900 750 74,250", 13, False),+ ("------------------------------------------------------------", 11, False),+ ("TOTAL 94 1,300,150 107,900 80,550 1,488,600", 14, True),+ ("", 6, False),+ ("Notes: Cloud excludes prepaid commits ($240k YTD).", 11, False),+ (" Travel includes T&E, but not relocation expenses.", 11, False),+ ]+ return render_lines(lines, width=720)+++def make_handwritten_note() -> Image.Image:+ # Not actually handwriting (we lack a reliable cursive font), so this is+ # a "casual jotting" style: tighter line spacing, a few intentional jitters,+ # to give the OCR-VLM something less template-like to read.+ img = Image.new("RGB", (540, 360), color=(252, 252, 240))+ draw = ImageDraw.Draw(img)+ rng = random.Random(42)++ def jitter_text(xy, text, size):+ x, y = xy+ for ch in text:+ dx = rng.randint(-1, 1)+ dy = rng.randint(-1, 1)+ draw.text((x + dx, y + dy), ch, fill=(20, 20, 30), font=font(size, bold=False))+ x += int(size * 0.55) + rng.randint(-1, 2)++ jitter_text((30, 24), "Reminders for Friday:", 16)+ jitter_text((40, 60), "1. Call Tom about the warranty claim", 14)+ jitter_text((40, 88), " - they need photo by 5pm", 13)+ jitter_text((40, 120), "2. Pick up book from library", 14)+ jitter_text((40, 148), " (Hawking, A Brief History of Time)", 12)+ jitter_text((40, 184), "3. Sushi for dinner - Mira likes Aoba", 14)+ jitter_text((40, 218), "4. Order replacement HDMI cable", 14)+ jitter_text((40, 246), " 2m or 3m, USB-C end", 12)+ jitter_text((30, 296), "Total errands today: 4", 14)+ jitter_text((30, 322), "Budget: $80 cash, $200 card", 13)+ return img+++def make_multi_column() -> Image.Image:+ # Two columns of "newspaper-like" text to test reading-order handling.+ img = Image.new("RGB", (740, 460), color=(255, 255, 255))+ draw = ImageDraw.Draw(img)+ draw.text((30, 20), "THE MORNING WIRE", fill=(0, 0, 0), font=font(22, bold=True))+ draw.text((30, 50), "Vol. XII, No. 47 Tuesday, March 17, 2026 Price: 1.50", fill=(60, 60, 60), font=font(11, bold=False))+ draw.line([(30, 80), (710, 80)], fill=(0, 0, 0), width=1)++ col_a = [+ "City Council Approves",+ "Riverside Park Expansion",+ "",+ "After two years of public debate, the",+ "city council voted 7-2 yesterday to",+ "approve the long-discussed Riverside",+ "Park expansion. The 14-acre extension",+ "will include a wetland boardwalk, two",+ "playgrounds, and a community amphi-",+ "theater. Funding comes from a 2024",+ "bond measure plus a state matching",+ "grant.",+ "",+ "Construction is expected to begin in",+ "May with phased openings through",+ "late 2027.",+ ]+ col_b = [+ "Local Bakery Closes",+ "After Forty Years",+ "",+ "Sundance Bakery, a fixture on Elm",+ "Street since 1986, will close at the",+ "end of next month. Owner Lila",+ "Carnesale cited rising commercial",+ "rents and the difficulty of finding",+ "overnight bakers as the deciding",+ "factors.",+ "",+ "A farewell event is planned for the",+ "final Saturday, with proceeds going",+ "to the regional food bank.",+ "",+ "Loyal customers are already pre-",+ "ordering their favorites for the last",+ "week of operation.",+ ]++ y = 100+ for line in col_a:+ size = 14 if not line.startswith(line[:2].upper()) or line == "" else 14+ draw.text((30, y), line, fill=(0, 0, 0), font=font(13, bold=line in {"City Council Approves", "Riverside Park Expansion"}))+ y += 18++ y = 100+ for line in col_b:+ draw.text((400, y), line, fill=(0, 0, 0), font=font(13, bold=line in {"Local Bakery Closes", "After Forty Years"}))+ y += 18++ return img+++def make_event_poster() -> Image.Image:+ # Poster-style. Florence-2 OCR shines on this: large text, simple layout,+ # high contrast, plenty of whitespace.+ img = Image.new("RGB", (780, 1040), color=(252, 246, 235))+ draw = ImageDraw.Draw(img)+ draw.rectangle([(0, 0), (779, 90)], fill=(124, 93, 255))+ draw.text((40, 18), "SPRING JAZZ FESTIVAL", fill=(255, 255, 255), font=font(34, bold=True))+ draw.text((40, 58), "Riverside Park Amphitheater", fill=(240, 230, 255), font=font(18, bold=False))++ draw.text((40, 150), "Saturday, May 24, 2026", fill=(20, 20, 30), font=font(28, bold=True))+ draw.text((40, 200), "Gates open 6:00 PM Music 7:00 PM - 10:00 PM", fill=(40, 40, 60), font=font(18, bold=False))+ draw.line([(40, 250), (740, 250)], fill=(124, 93, 255), width=2)++ draw.text((40, 280), "FEATURED ARTISTS", fill=(124, 93, 255), font=font(20, bold=True))+ draw.text((40, 320), "Maya Brennan Quintet", fill=(20, 20, 30), font=font(22, bold=False))+ draw.text((40, 358), "Otis Park & The Resolve", fill=(20, 20, 30), font=font(22, bold=False))+ draw.text((40, 396), "Jeong-min Trio (special guest)", fill=(20, 20, 30), font=font(22, bold=False))++ draw.line([(40, 460), (740, 460)], fill=(124, 93, 255), width=2)+ draw.text((40, 490), "TICKETS", fill=(124, 93, 255), font=font(20, bold=True))+ draw.text((40, 530), "Advance: $18 Door: $24 Under 12: free", fill=(20, 20, 30), font=font(20, bold=False))+ draw.text((40, 570), "Visit springjazzfest.org or call 555-0142", fill=(20, 20, 30), font=font(18, bold=False))++ draw.text((40, 660), "Presented by Riverside Arts Council", fill=(60, 60, 90), font=font(16, bold=False))+ draw.text((40, 690), "with support from Bluebird Coffee Roasters", fill=(60, 60, 90), font=font(16, bold=False))+ return img+++def make_slide() -> Image.Image:+ # Presentation slide. Clean, lots of whitespace, big text. Florence-2 OCR+ # tends to read this well: it's the kind of "single image with prominent+ # text" the model was trained on.+ img = Image.new("RGB", (960, 540), color=(255, 255, 255))+ draw = ImageDraw.Draw(img)+ draw.rectangle([(0, 0), (959, 70)], fill=(20, 20, 40))+ draw.text((40, 18), "Q2 2026 Product Roadmap", fill=(255, 255, 255), font=font(28, bold=True))++ draw.text((50, 130), "1. Ship the unified search experience", fill=(20, 20, 30), font=font(24, bold=False))+ draw.text((80, 168), "across web and mobile clients", fill=(80, 80, 100), font=font(18, bold=False))++ draw.text((50, 230), "2. Move billing onto the new ledger service", fill=(20, 20, 30), font=font(24, bold=False))+ draw.text((80, 268), "complete the dual-write cutover by June 15", fill=(80, 80, 100), font=font(18, bold=False))++ draw.text((50, 330), "3. Launch the developer documentation site", fill=(20, 20, 30), font=font(24, bold=False))+ draw.text((80, 368), "public preview at WWDC keynote", fill=(80, 80, 100), font=font(18, bold=False))++ draw.text((50, 470), "Owners: P. Lin (search), M. Okafor (billing), R. Tate (docs)", fill=(60, 60, 90), font=font(14, bold=False))+ return img+++def make_letter() -> Image.Image:+ # Short business letter. Clean printed paragraphs.+ lines = [+ ("Westmoor Acoustics, Inc.", 16, True),+ ("418 Crown Street, Sausalito, CA 94965", 12, False),+ ("", 8, False),+ ("April 8, 2026", 13, False),+ ("", 8, False),+ ("Dear Ms. Hernandez,", 14, False),+ ("", 6, False),+ ("Thank you for your interest in the model 218 studio monitor.", 13, False),+ ("We have reserved a pair under your name; they will ship from", 13, False),+ ("our Oakland warehouse on April 15 and should arrive by", 13, False),+ ("April 20 via FedEx Ground.", 13, False),+ ("", 6, False),+ ("Your order total of $1,940.00 includes the 5-year transferable", 13, False),+ ("warranty and one calibration visit. Please retain the enclosed", 13, False),+ ("serial number card for any future service request.", 13, False),+ ("", 6, False),+ ("If you have questions, our service line is (415) 555-0173,", 13, False),+ ("open weekdays 9 AM to 5 PM Pacific time.", 13, False),+ ("", 6, False),+ ("Sincerely,", 13, False),+ ("", 8, False),+ ("Jane Salisbury", 14, True),+ ("Customer Account Manager", 12, False),+ ]+ return render_lines(lines, width=640, padding=32)+++SAMPLES = [+ ("receipt.png", "Grocery receipt", "Printed receipt with line items, subtotal, tax, total. Donut on CORD reads this end-to-end.", make_receipt, ["merchant", "date", "line_item", "subtotal", "tax", "total", "payment_method"]),+ ("invoice.png", "Vendor invoice", "Multi-column invoice with billing party, line items, subtotal, tax, total.", make_invoice, ["vendor", "invoice_number", "date", "due_date", "billing_party", "line_item", "total"]),+ ("business-card.png", "Business card", "Tight layout, mixed text sizes, multiple contact fields. Good NER showcase.", make_business_card, ["company", "person", "role", "email", "phone", "address", "website"]),+ ("event-poster.png", "Event poster", "Large-text poster with title, date, artists, ticket info. Florence-2 OCR's home turf.", make_event_poster, ["event", "date", "venue", "artist", "price", "organization"]),+ ("slide.png", "Presentation slide", "Roadmap slide with title and three numbered items. Clean printed text on a single background.", make_slide, ["initiative", "person", "date", "quarter"]),+ ("letter.png", "Business letter", "Short printed business letter with sender, date, recipient, body, and signature.", make_letter, ["company", "person", "address", "date", "amount", "phone"]),+]+++def main() -> None:+ index = []+ for filename, label, description, factory, labels in SAMPLES:+ img = factory()+ out_path = OUT_DIR / filename+ img.save(out_path, "PNG", optimize=True)+ index.append({+ "id": filename.replace(".png", ""),+ "filename": filename,+ "label": label,+ "description": description,+ "labels": labels,+ })+ print(f"wrote {out_path} ({img.size[0]}x{img.size[1]})")++ (OUT_DIR / "index.json").write_text(json.dumps(index, indent=2))+ print(f"wrote {OUT_DIR / 'index.json'} ({len(index)} samples)")+++if __name__ == "__main__":+ main()diff --git a/examples/document-ocr/src/config.ts b/examples/document-ocr/src/config.tsnew file mode 100644index 000000000..1abefef34--- /dev/null+++ b/examples/document-ocr/src/config.ts@@ -0,0 +1,88 @@+export type ModelOption = {+ id: string;+ label: string;+ description: string;+ gpuRequired?: boolean;+ /** Adapter-specific options passed via SIE's `options` field. */+ options?: Record<string, unknown>;+};++export const RECOGNITION_MODELS: ModelOption[] = [+ {+ id: "lightonai/LightOnOCR-2-1B",+ label: "LightOnOCR-2-1B (default)",+ description: "Pixtral encoder + Qwen3 decoder, 2.1B. Strong Markdown output across dense layouts. ~4 GB to download on first call.",+ },+ {+ id: "PaddlePaddle/PaddleOCR-VL-1.5",+ label: "PaddleOCR-VL-1.5 (GPU image)",+ description: "Paddle's VLM-OCR, 1.5B. Six task modes. Available on the CUDA image (compose.gpu.yml).",+ options: { task: "ocr" },+ gpuRequired: true,+ },+ {+ id: "zai-org/GLM-OCR",+ label: "GLM-OCR (GPU only)",+ description: "CogViT + GLM-0.5B decoder, 9B in bfloat16. Premium quality, needs ~18 GB VRAM (compose.gpu.yml).",+ gpuRequired: true,+ },+];++export const STRUCTURED_MODELS: ModelOption[] = [+ {+ id: "naver-clova-ix/donut-base-finetuned-cord-v2",+ label: "Donut on CORD (receipts)",+ description: "Fine-tuned for the CORD receipt schema. Pixels in, nested JSON out.",+ },+ {+ id: "naver-clova-ix/donut-base-finetuned-docvqa",+ label: "Donut on DocVQA",+ description: "Same Donut architecture, fine-tuned for visual question answering. Returns text answers.",+ },+ {+ id: "naver-clova-ix/donut-base-finetuned-rvlcdip",+ label: "Donut on RVL-CDIP (doc classification)",+ description: "Same Donut architecture, fine-tuned for document-type classification across 16 classes (invoice, receipt, form, ...).",+ },+];++export const NER_MODELS: ModelOption[] = [+ {+ id: "urchade/gliner_multi-v2.1",+ label: "GLiNER multi (multilingual)",+ description: "280M, zero-shot NER, 100+ languages. Good default.",+ },+ {+ id: "urchade/gliner_large-v2.1",+ label: "GLiNER large (English)",+ description: "440M, English-focused, higher quality on English text.",+ },+ {+ id: "urchade/gliner_multi_pii-v1",+ label: "GLiNER multi PII",+ description: "GLiNER fine-tuned for PII extraction. Good for redaction-style pipelines on documents.",+ },+ {+ id: "numind/NuNER_Zero",+ label: "NuNER Zero",+ description: "NuMind's zero-shot NER. Different architecture from GLiNER; useful for comparing zero-shot NER families on the same input text.",+ },+];++export const config = {+ sieUrl: process.env.SIE_URL ?? "http://localhost:8080",+ sieApiKey: process.env.SIE_API_KEY,++ defaults: {+ recognition: RECOGNITION_MODELS[0].id,+ structured: STRUCTURED_MODELS[0].id,+ ner: NER_MODELS[0].id,+ },++ paths: {+ samples: "data/samples/index.json",+ sampleDir: "data/samples",+ },++ port: Number(process.env.PORT ?? 3032),+} as const;diff --git a/examples/document-ocr/src/donut.ts b/examples/document-ocr/src/donut.tsnew file mode 100644index 000000000..f52108fec--- /dev/null+++ b/examples/document-ocr/src/donut.ts@@ -0,0 +1,25 @@+import { detectImageFormat, type SIEClient } from "@superlinked/sie-sdk";+import type { DonutEntity } from "./types.js";++/** Run any image-input "structured" extractor (Donut variants, etc.). */+export async function structuredExtract(+ client: SIEClient,+ model: string,+ imageBytes: Uint8Array,+ options?: Record<string, unknown>,+): Promise<{ entities: DonutEntity[]; data: unknown }> {+ const format = detectImageFormat(imageBytes);+ if (format === "unknown") throw new Error("could not detect image format");+ const wire = { data: imageBytes, format };+ const result = await client.extract(+ model,+ { images: [wire] as unknown as Uint8Array[] },+ { labels: [], options } as unknown as Parameters<typeof client.extract>[2],+ );+ const entities = (result.entities ?? []).map((e) => ({+ label: e.label,+ text: e.text,+ }));+ const data = (result as unknown as { data?: unknown }).data;+ return { entities, data };+}diff --git a/examples/document-ocr/src/events.ts b/examples/document-ocr/src/events.tsnew file mode 100644index 000000000..f993e5528--- /dev/null+++ b/examples/document-ocr/src/events.ts@@ -0,0 +1,13 @@+import type { DonutEntity, ExtractedField } from "./types.js";++export type PipelineEvent =+ | { type: "models"; data: { extractor: string; recognition: string; structured: string } }+ | { type: "recognition_start"; data: { model: string } }+ | { type: "recognition_chunk"; data: { textLen: number } }+ | { type: "recognition_done"; data: { markdown: string; ms: number } }+ | { type: "donut_start" }+ | { type: "donut_done"; data: { entities: DonutEntity[]; rawData: unknown; ms: number } }+ | { type: "gliner_start"; data: { labels: string[] } }+ | { type: "gliner_done"; data: { fields: ExtractedField[]; ms: number } }+ | { type: "done"; data: { totalMs: number } }+ | { type: "error"; data: { message: string; stage: string } };diff --git a/examples/document-ocr/src/extract.ts b/examples/document-ocr/src/extract.tsnew file mode 100644index 000000000..5552f33cb--- /dev/null+++ b/examples/document-ocr/src/extract.ts@@ -0,0 +1,17 @@+import type { SIEClient } from "@superlinked/sie-sdk";+import type { ExtractedField } from "./types.js";++export async function extractFields(+ client: SIEClient,+ model: string,+ text: string,+ labels: string[],+): Promise<ExtractedField[]> {+ if (!text.trim()) return [];+ const result = await client.extract(model, { text }, { labels, threshold: 0.4 });+ return (result.entities ?? []).map((e) => ({+ label: e.label,+ text: e.text,+ score: e.score,+ }));+}diff --git a/examples/document-ocr/src/ocr.ts b/examples/document-ocr/src/ocr.tsnew file mode 100644index 000000000..9d66823fe--- /dev/null+++ b/examples/document-ocr/src/ocr.ts@@ -0,0 +1,24 @@+import { detectImageFormat, type SIEClient } from "@superlinked/sie-sdk";++export async function recognize(+ client: SIEClient,+ model: string,+ imageBytes: Uint8Array,+ options?: Record<string, unknown>,+): Promise<string> {+ const format = detectImageFormat(imageBytes);+ if (format === "unknown") throw new Error("could not detect image format");+ const wire = { data: imageBytes, format };+ // The TS SDK types declare images as Uint8Array[], but the wire format+ // expects {data, format} dicts. Cast around the typing gap.+ const result = await client.extract(+ model,+ { images: [wire] as unknown as Uint8Array[] },+ // The TS SDK's ExtractOptions doesn't declare `options`, but the wire+ // protocol forwards it to the adapter. Cast to bridge the typing gap.+ { labels: [], options } as unknown as Parameters<typeof client.extract>[2],+ );+ if (!result.entities || result.entities.length === 0) return "";+ const text = result.entities[0]?.text;+ return typeof text === "string" ? text : "";+}diff --git a/examples/document-ocr/src/pipeline.ts b/examples/document-ocr/src/pipeline.tsnew file mode 100644index 000000000..6bca3cc9b--- /dev/null+++ b/examples/document-ocr/src/pipeline.ts@@ -0,0 +1,102 @@+import type { SIEClient } from "@superlinked/sie-sdk";+import { NER_MODELS, RECOGNITION_MODELS, STRUCTURED_MODELS } from "./config.js";+import { structuredExtract } from "./donut.js";+import type { PipelineEvent } from "./events.js";+import { extractFields } from "./extract.js";+import { recognize } from "./ocr.js";+import type { SampleDoc, TriageResult } from "./types.js";++export type RunInput = {+ client: SIEClient;+ imageBytes: Uint8Array;+ sample: SampleDoc;+ recognitionModel: string;+ structuredModel: string;+ nerModel: string;+ emit: (event: PipelineEvent) => void;+};++function lookup<T extends { id: string }>(list: T[], id: string): T {+ const found = list.find((m) => m.id === id);+ if (!found) throw new Error(`unknown model id: ${id}`);+ return found;+}++export async function runPipeline({+ client,+ imageBytes,+ sample,+ recognitionModel,+ structuredModel,+ nerModel,+ emit,+}: RunInput): Promise<TriageResult> {+ const t0 = Date.now();++ emit({+ type: "models",+ data: { extractor: nerModel, recognition: recognitionModel, structured: structuredModel },+ });++ // Recognition+ const recOpt = lookup(RECOGNITION_MODELS, recognitionModel);+ emit({ type: "recognition_start", data: { model: recognitionModel } });+ const tRec = Date.now();+ let markdown = "";+ try {+ markdown = await recognize(client, recOpt.id, imageBytes, recOpt.options);+ } catch (err) {+ emit({+ type: "error",+ data: { stage: "recognition", message: `${recognitionModel} failed: ${(err as Error).message}` },+ });+ throw err;+ }+ const recognitionMs = Date.now() - tRec;+ emit({ type: "recognition_done", data: { markdown, ms: recognitionMs } });++ // Structured (Donut variants, etc.)+ const strOpt = lookup(STRUCTURED_MODELS, structuredModel);+ emit({ type: "donut_start" });+ const tDon = Date.now();+ let donut = { entities: [] as { label: string; text: string }[], data: undefined as unknown };+ try {+ donut = await structuredExtract(client, strOpt.id, imageBytes, strOpt.options);+ } catch (err) {+ emit({+ type: "error",+ data: { stage: "donut", message: `${structuredModel} failed: ${(err as Error).message}` },+ });+ }+ const donutMs = Date.now() - tDon;+ emit({ type: "donut_done", data: { entities: donut.entities, rawData: donut.data, ms: donutMs } });++ // NER (GLiNER variants)+ const nerOpt = lookup(NER_MODELS, nerModel);+ emit({ type: "gliner_start", data: { labels: sample.labels } });+ const tGli = Date.now();+ let fields: { label: string; text: string; score: number }[] = [];+ try {+ fields = await extractFields(client, nerOpt.id, markdown, sample.labels);+ } catch (err) {+ emit({+ type: "error",+ data: { stage: "gliner", message: `${nerModel} failed: ${(err as Error).message}` },+ });+ }+ const glinerMs = Date.now() - tGli;+ emit({ type: "gliner_done", data: { fields, ms: glinerMs } });++ const totalMs = Date.now() - t0;+ emit({ type: "done", data: { totalMs } });++ return {+ sampleId: sample.id,+ recognitionModel,+ markdown,+ donutEntities: donut.entities,+ donutData: donut.data,+ glinerFields: fields,+ timings: { recognitionMs, donutMs, glinerMs, totalMs },+ };+}diff --git a/examples/document-ocr/src/types.ts b/examples/document-ocr/src/types.tsnew file mode 100644index 000000000..42ed7ed69--- /dev/null+++ b/examples/document-ocr/src/types.ts@@ -0,0 +1,33 @@+export type SampleDoc = {+ id: string;+ filename: string;+ label: string;+ description: string;+ labels: string[];+};++export type ExtractedField = {+ label: string;+ text: string;+ score: number;+};++export type DonutEntity = {+ label: string;+ text: string;+};++export type TriageResult = {+ sampleId: string;+ recognitionModel: string;+ markdown: string;+ donutEntities: DonutEntity[];+ donutData: unknown;+ glinerFields: ExtractedField[];+ timings: {+ recognitionMs: number;+ donutMs: number;+ glinerMs: number;+ totalMs: number;+ };+};diff --git a/examples/document-ocr/tsconfig.json b/examples/document-ocr/tsconfig.jsonnew file mode 100644index 000000000..5c39b6e00--- /dev/null+++ b/examples/document-ocr/tsconfig.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "strict": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "noEmit": true+ },+ "include": ["src", "web"]+}diff --git a/examples/document-ocr/web/public/app.js b/examples/document-ocr/web/public/app.jsnew file mode 100644index 000000000..5024ca095--- /dev/null+++ b/examples/document-ocr/web/public/app.js@@ -0,0 +1,300 @@+const els = {+ badge: document.getElementById("badge"),+ models: document.getElementById("models"),+ sieState: document.getElementById("sie-state"),+ events: document.getElementById("events"),+ selectRecognition: document.getElementById("select-recognition"),+ selectStructured: document.getElementById("select-structured"),+ selectNer: document.getElementById("select-ner"),+ recognition: document.getElementById("recognition"),+ recognitionMeta: document.getElementById("recognition-meta"),+ extraction: document.getElementById("extraction"),+ extractionMeta: document.getElementById("extraction-meta"),+ footer: document.getElementById("footer"),+ sieUrl: document.getElementById("sie-url"),+ timings: document.getElementById("timings"),+ snippetRecognition: document.getElementById("snippet-recognition"),+ snippetStructured: document.getElementById("snippet-structured"),+ snippetNer: document.getElementById("snippet-ner"),+};++let activeSampleId = null;+let activeSample = null;+let timings = { recognitionMs: 0, donutMs: 0, glinerMs: 0 };+let donutBuf = { entities: [], data: null };+let glinerBuf = [];+let modelConfig = null;+let registeredSet = new Set();+let cudaAvailable = false;++function setBadge(text, cls) {+ els.badge.textContent = text;+ els.badge.className = "badge" + (cls ? " " + cls : "");+}+function shortModel(id) {+ if (!id) return "";+ const slash = id.indexOf("/");+ return slash === -1 ? id : id.slice(slash + 1);+}+function escapeHtml(s) {+ return String(s).replace(+ /[&<>"']/g,+ (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c],+ );+}++function findModel(list, id) {+ return list ? list.find((m) => m.id === id) : null;+}++function snippetRecognition(modelId) {+ if (!modelConfig) return "";+ const opt = findModel(modelConfig.recognition, modelId);+ const hasOpts = opt && opt.options && Object.keys(opt.options).length > 0;+ const lines = [+ 'client.extract(',+ ` <span class="str">"${escapeHtml(modelId)}"</span>,`,+ ' Item(images=[image_bytes]),',+ ];+ if (hasOpts) {+ const optsJson = JSON.stringify(opt.options).replace(/"/g, '"');+ lines.push(` <span class="arg">options</span>=${escapeHtml(optsJson)},`);+ }+ lines.push(')');+ return `<span class="com"># Recognition: one call against SIE</span>\n` + lines.join("\n");+}++function snippetStructured(modelId) {+ return (+ `<span class="com"># Structured: same client.extract, different model_id</span>\n` ++ `client.extract(\n` ++ ` <span class="str">"${escapeHtml(modelId)}"</span>,\n` ++ ` Item(images=[image_bytes]),\n` ++ `)`+ );+}++function snippetNer(modelId, sample) {+ const labels = sample ? sample.labels : ["merchant", "total", "date"];+ const labelsStr = "[" + labels.map((l) => `<span class="str">"${escapeHtml(l)}"</span>`).join(", ") + "]";+ return (+ `<span class="com"># NER: text input this time, declared labels</span>\n` ++ `client.extract(\n` ++ ` <span class="str">"${escapeHtml(modelId)}"</span>,\n` ++ ` Item(text=recognized_markdown),\n` ++ ` <span class="arg">labels</span>=${labelsStr},\n` ++ `)`+ );+}++function updateSnippets() {+ if (!els.snippetRecognition) return;+ els.snippetRecognition.innerHTML = snippetRecognition(els.selectRecognition.value);+ els.snippetStructured.innerHTML = snippetStructured(els.selectStructured.value);+ els.snippetNer.innerHTML = snippetNer(els.selectNer.value, activeSample);+}++function populateDropdown(selectEl, options, defaultId) {+ selectEl.innerHTML = "";+ for (const opt of options) {+ const node = document.createElement("option");+ node.value = opt.id;+ const inCatalog = registeredSet.size === 0 || registeredSet.has(opt.id);+ const blockedByCuda = opt.gpuRequired && !cudaAvailable;+ const available = inCatalog && !blockedByCuda;+ const labelSuffix = !available+ ? blockedByCuda+ ? " (GPU image needed)"+ : opt.gpuRequired+ ? " (GPU image needed)"+ : " (not registered)"+ : "";+ node.textContent = opt.label + labelSuffix;+ if (!available) node.disabled = true;+ if (opt.id === defaultId) node.selected = true;+ node.title = opt.description;+ selectEl.appendChild(node);+ }+ selectEl.addEventListener("change", updateSnippets);+}++function renderSamples(samples, onClick) {+ if (!samples || samples.length === 0) {+ els.events.innerHTML = '<p class="hint">no samples</p>';+ return;+ }+ els.events.innerHTML = samples+ .map(+ (s) => `<div class="event" data-id="${escapeHtml(s.id)}">+ <img src="/samples/${encodeURIComponent(s.filename)}" alt="${escapeHtml(s.label)}" />+ <div>+ <div class="label">${escapeHtml(s.label)}</div>+ <div class="desc">${escapeHtml(s.description)}</div>+ </div>+ </div>`,+ )+ .join("");+ for (const node of els.events.querySelectorAll(".event")) {+ node.addEventListener("click", () => {+ for (const n of els.events.querySelectorAll(".event")) n.classList.remove("active");+ node.classList.add("active");+ activeSample = samples.find((s) => s.id === node.dataset.id) || null;+ updateSnippets();+ onClick(node.dataset.id);+ });+ }+}++function updateTimings() {+ const total = timings.recognitionMs + timings.donutMs + timings.glinerMs;+ els.timings.textContent =+ total > 0+ ? `recognition ${timings.recognitionMs}ms · structured ${timings.donutMs}ms · ner ${timings.glinerMs}ms · total ${total}ms`+ : "";+}++function renderExtraction() {+ let html = "";++ if (glinerBuf.length > 0) {+ html += `<div class="section"><h3>NER (${escapeHtml(shortModel(els.selectNer.value))})</h3>`;+ for (const f of glinerBuf) {+ html += `<div class="field">+ <span class="label-name">${escapeHtml(f.label)}</span>+ <span class="text">${escapeHtml(f.text)}</span>+ <span class="score">${f.score.toFixed(2)}</span>+ </div>`;+ }+ html += "</div>";+ }++ if (donutBuf.entities.length > 0) {+ html += `<div class="section"><h3>Structured (${escapeHtml(shortModel(els.selectStructured.value))})</h3>`;+ for (const e of donutBuf.entities.slice(0, 25)) {+ html += `<div class="donut-row">+ <span class="key">${escapeHtml(e.label)}</span>+ <span class="val">${escapeHtml(e.text)}</span>+ </div>`;+ }+ html += "</div>";+ }++ if (!html) html = '<p class="hint">running...</p>';+ els.extraction.innerHTML = html;+}++function runSample(sampleId) {+ activeSampleId = sampleId;+ setBadge("running", "running");+ els.recognition.innerHTML = '<p class="hint">running recognition...</p>';+ els.extraction.innerHTML = '<p class="hint">waiting...</p>';+ els.recognitionMeta.textContent = "";+ els.extractionMeta.textContent = "";+ timings = { recognitionMs: 0, donutMs: 0, glinerMs: 0 };+ donutBuf = { entities: [], data: null };+ glinerBuf = [];+ updateTimings();++ const recognition = els.selectRecognition.value;+ const structured = els.selectStructured.value;+ const ner = els.selectNer.value;+ const url = `/api/run?id=${encodeURIComponent(sampleId)}&recognition=${encodeURIComponent(recognition)}&structured=${encodeURIComponent(structured)}&ner=${encodeURIComponent(ner)}`;+ const es = new EventSource(url);++ es.addEventListener("models", (e) => {+ const d = JSON.parse(e.data);+ els.models.innerHTML = `recognition: <code>${shortModel(d.recognition)}</code> · structured: <code>${shortModel(d.structured)}</code> · ner: <code>${shortModel(d.extractor)}</code>`;+ });+ es.addEventListener("recognition_start", () => {+ els.recognitionMeta.textContent = "loading model + generating...";+ });+ es.addEventListener("recognition_done", (e) => {+ const d = JSON.parse(e.data);+ timings.recognitionMs = d.ms;+ els.recognitionMeta.textContent = `${d.markdown.length} chars in ${d.ms}ms`;+ els.recognition.textContent = d.markdown;+ updateTimings();+ });+ es.addEventListener("donut_start", () => {+ els.extractionMeta.textContent = "running structured...";+ });+ es.addEventListener("donut_done", (e) => {+ const d = JSON.parse(e.data);+ timings.donutMs = d.ms;+ donutBuf = { entities: d.entities, data: d.rawData };+ els.extractionMeta.textContent = `structured ${d.ms}ms`;+ renderExtraction();+ updateTimings();+ });+ es.addEventListener("gliner_start", () => {+ els.extractionMeta.textContent = "running NER...";+ });+ es.addEventListener("gliner_done", (e) => {+ const d = JSON.parse(e.data);+ timings.glinerMs = d.ms;+ glinerBuf = d.fields;+ els.extractionMeta.textContent = `ner ${d.ms}ms · ${d.fields.length} fields`;+ renderExtraction();+ updateTimings();+ });+ es.addEventListener("done", (e) => {+ const d = JSON.parse(e.data);+ setBadge(`done ${d.totalMs}ms`, "green");+ es.close();+ });+ es.addEventListener("error", (e) => {+ setBadge("error", "red");+ if (e.data) {+ try {+ const m = JSON.parse(e.data);+ els.recognitionMeta.textContent = `${m.stage}: ${m.message}`;+ } catch {+ /* */+ }+ }+ es.close();+ });+}++async function init() {+ // Fetch SIE health (and registered models)+ let registered = [];+ try {+ const r = await fetch("/api/health");+ const j = await r.json();+ els.sieUrl.textContent = j.sieUrl;+ if (!j.sie) {+ els.sieState.textContent = "SIE not reachable yet (still preloading models?)";+ } else {+ els.sieState.textContent = `SIE healthy · ${j.registeredModels} models registered`;+ registered = j.registered ?? [];+ cudaAvailable = !!j.cuda;+ }+ } catch {+ els.sieState.textContent = "could not reach the local server";+ }+ registeredSet = new Set(registered);++ // Fetch model menus (config-side)+ try {+ const r = await fetch("/api/models");+ modelConfig = await r.json();+ populateDropdown(els.selectRecognition, modelConfig.recognition, modelConfig.defaults.recognition);+ populateDropdown(els.selectStructured, modelConfig.structured, modelConfig.defaults.structured);+ populateDropdown(els.selectNer, modelConfig.ner, modelConfig.defaults.ner);+ updateSnippets();+ } catch (e) {+ console.error("failed to load model config", e);+ }++ // Fetch sample documents+ try {+ const r = await fetch("/api/samples");+ const samples = await r.json();+ renderSamples(samples, runSample);+ } catch {+ els.events.innerHTML = '<p class="hint">failed to load samples</p>';+ }+}++init();diff --git a/examples/document-ocr/web/public/index.html b/examples/document-ocr/web/public/index.htmlnew file mode 100644index 000000000..7b862fe8e--- /dev/null+++ b/examples/document-ocr/web/public/index.html@@ -0,0 +1,154 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>document-ocr</title>+ <link rel="stylesheet" href="/static/style.css" />+ </head>+ <body>+ <header>+ <div class="title">+ <span class="logo">📄</span>+ <h1>document-ocr</h1>+ <span class="badge" id="badge">idle</span>+ </div>+ <div class="meta" id="models">SIE: <code>...</code></div>+ <div class="meta" id="sie-state">checking SIE...</div>+ <div class="cta-row">+ <a class="cta" href="https://github.com/superlinked/brave-new-demos/tree/main/document-ocr" target="_blank" rel="noopener">+ <span>↗</span> Source on GitHub+ </a>+ <a class="cta" href="https://github.com/superlinked/sie" target="_blank" rel="noopener">+ <span>★</span> SIE repo+ </a>+ </div>+ </header>++ <section class="hero">+ <div class="hero-text">+ <p>+ OCR is rarely a single-model problem. This demo runs three model+ classes through <strong>one SIE server</strong>: a VLM-OCR recognizes+ the document into Markdown, a fine-tuned Donut emits a JSON tree+ directly, and a zero-shot NER (GLiNER) pulls typed fields out of+ the recognition output. Pick a sample on the left, swap any of the+ three models in the dropdowns, watch SIE hot-swap them with+ <em>one identifier change</em>.+ </p>+ </div>+ <div class="hero-diagram">+ <div class="diagram">+ <div class="diagram-input">image</div>+ <div class="diagram-arrow">↓</div>+ <div class="diagram-server">one SIE server · <code>client.extract(model_id, item)</code></div>+ <div class="diagram-arrows">+ <span>↓</span><span>↓</span><span>↓</span>+ </div>+ <div class="diagram-models">+ <div class="diagram-box diagram-recognition">VLM-OCR<br><span>(LightOnOCR-2-1B, PaddleOCR-VL, GLM-OCR)</span></div>+ <div class="diagram-box diagram-structured">Donut<br><span>(end-to-end JSON)</span></div>+ <div class="diagram-box diagram-ner">GLiNER<br><span>(zero-shot NER)</span></div>+ </div>+ </div>+ </div>+ </section>++ <section class="why-sie">+ <h3>Why SIE</h3>+ <p>+ Three different model architectures (a vision-language model, a+ fine-tuned encoder-decoder, a span-based NER), one inference engine,+ one HTTP API, one SDK call. Without SIE, this demo would be three+ separate inference services with three SDKs, three auth flows, three+ rate limits. With SIE, swap a string in <code>client.extract(...)</code>+ and the underlying architecture changes.+ </p>+ </section>++ <section class="tour">+ <h3>Try these moments</h3>+ <ol class="tour-list">+ <li>+ <strong>Click any sample on the left.</strong> All three models run+ in one pipeline. The footer prints per-stage timings as each one+ lands.+ </li>+ <li>+ <strong>Open "See the SIE call"</strong> in any panel, then swap the+ model dropdown above. The snippet updates with the one parameter+ that changed. That is the swap-a-string pitch in action.+ </li>+ <li>+ <strong>Click the receipt, then the multi-column page.</strong>+ Donut (fine-tuned on receipts) dominates the first; recognition+ dominates the second. Same pipeline, different model wins.+ </li>+ <li>+ <strong>Switch NER from <code>gliner_multi</code> to+ <code>gliner_large</code>.</strong> Same labels, same input text,+ different confidence scores. Model quality is a single dropdown+ away.+ </li>+ </ol>+ </section>++ <main>+ <section class="panel" id="panel-events">+ <header><h2>Sample documents</h2></header>+ <div class="meta-row">+ <label class="model-pick">+ <span class="dropdown-label">Recognition</span>+ <select id="select-recognition"></select>+ </label>+ <label class="model-pick">+ <span class="dropdown-label">Structured</span>+ <select id="select-structured"></select>+ </label>+ <label class="model-pick">+ <span class="dropdown-label">NER</span>+ <select id="select-ner"></select>+ </label>+ </div>+ <div class="list" id="events">loading...</div>+ </section>++ <section class="panel" id="panel-recognition">+ <header>+ <h2>Recognition (Markdown)</h2>+ <span class="hint" id="recognition-meta"></span>+ </header>+ <details class="sdk-snippet">+ <summary>See the SIE call</summary>+ <pre><code id="snippet-recognition">// pick a recognition model in the dropdown</code></pre>+ </details>+ <div class="markdown" id="recognition">+ <p class="hint">Click a sample on the left.</p>+ </div>+ </section>++ <section class="panel" id="panel-extraction">+ <header>+ <h2>Extraction</h2>+ <span class="hint" id="extraction-meta"></span>+ </header>+ <details class="sdk-snippet">+ <summary>See the SIE calls</summary>+ <pre><code id="snippet-structured">// structured (Donut)</code>++<code id="snippet-ner">// NER (GLiNER)</code></pre>+ </details>+ <div class="extraction" id="extraction">+ <p class="hint">Typed fields will appear here.</p>+ </div>+ </section>+ </main>++ <footer>+ <span id="footer">SIE on <code id="sie-url">http://localhost:8080</code></span>+ <span id="timings"></span>+ </footer>++ <script src="/static/app.js"></script>+ </body>+</html>diff --git a/examples/document-ocr/web/public/style.css b/examples/document-ocr/web/public/style.cssnew file mode 100644index 000000000..f06e6551d--- /dev/null+++ b/examples/document-ocr/web/public/style.css@@ -0,0 +1,264 @@+:root {+ --bg: #0e1014;+ --panel: #161a22;+ --line: #232936;+ --text: #e6e8ec;+ --muted: #8b94a7;+ --accent: #7c5dff;+ --accent-2: #62b6ff;+ --green: #5fd28b;+ --red: #ff6b6b;+ --yellow: #f7c948;+ --magenta: #c89cff;+}++* { box-sizing: border-box; }+html, body {+ margin: 0; padding: 0; background: var(--bg); color: var(--text);+ font: 14px ui-monospace, SFMono-Regular, Menlo, monospace;+ min-height: 100%;+}+body { display: flex; flex-direction: column; min-height: 100vh; }++header {+ display: flex; align-items: center; gap: 16px;+ padding: 12px 20px; border-bottom: 1px solid var(--line);+ flex-wrap: wrap;+}+.title { display: flex; align-items: center; gap: 12px; }+.logo { font-size: 18px; }+h1 { font-size: 16px; margin: 0; font-weight: 600; }+.badge {+ padding: 3px 10px; border-radius: 999px; background: var(--line);+ color: var(--muted); font-size: 11px; text-transform: uppercase;+ letter-spacing: 0.5px;+}+.badge.running { background: rgba(98, 182, 255, 0.15); color: var(--accent-2); }+.badge.green { background: rgba(95, 210, 139, 0.18); color: var(--green); }+.badge.red { background: rgba(255, 107, 107, 0.18); color: var(--red); }+.meta { color: var(--muted); font-size: 12px; }++.cta-row {+ margin-left: auto; display: flex; gap: 8px;+}+.cta {+ display: inline-flex; align-items: center; gap: 6px;+ padding: 5px 10px; border-radius: 6px;+ background: var(--line); color: var(--accent-2);+ font-size: 11px; text-decoration: none;+ border: 1px solid transparent;+ transition: border-color 0.1s;+}+.cta:hover { border-color: var(--accent); }+.cta span { font-size: 12px; }++.hero {+ padding: 14px 20px;+ background: linear-gradient(180deg, rgba(124,93,255,0.10), transparent);+ border-bottom: 1px solid var(--line);+ display: grid; grid-template-columns: 1.4fr 1fr; gap: 24px; align-items: center;+}+.hero-text p { margin: 0; color: var(--muted); line-height: 1.6; }+.hero-text strong { color: var(--text); }+.hero-text em { color: var(--accent-2); font-style: normal; font-weight: 600; }++.diagram {+ display: flex; flex-direction: column; align-items: center; gap: 2px;+ font-size: 11px;+}+.diagram-input {+ padding: 4px 14px; border: 1px dashed var(--muted); border-radius: 6px;+ color: var(--text);+}+.diagram-arrow { color: var(--muted); font-size: 14px; line-height: 1; }+.diagram-server {+ padding: 6px 14px; border: 1px solid var(--accent); border-radius: 6px;+ color: var(--text); background: rgba(124,93,255,0.10);+ font-size: 11px;+}+.diagram-server code {+ background: transparent; color: var(--accent-2);+ padding: 0;+}+.diagram-arrows {+ display: flex; gap: 80px; color: var(--muted); font-size: 14px;+ line-height: 1;+}+.diagram-models {+ display: flex; gap: 10px;+}+.diagram-box {+ padding: 6px 10px; border: 1px solid var(--line); border-radius: 6px;+ background: var(--panel); color: var(--text); text-align: center;+ min-width: 110px; font-weight: 600;+}+.diagram-box span {+ display: block; color: var(--muted); font-weight: normal;+ font-size: 9px; margin-top: 2px;+}+.diagram-recognition { border-color: rgba(98,182,255,0.4); }+.diagram-structured { border-color: rgba(200,156,255,0.4); }+.diagram-ner { border-color: rgba(95,210,139,0.4); }++.why-sie {+ padding: 12px 20px; border-bottom: 1px solid var(--line);+ background: rgba(124,93,255,0.04);+}+.why-sie h3 {+ margin: 0 0 6px 0; font-size: 11px; letter-spacing: 0.6px;+ text-transform: uppercase; color: var(--accent); font-weight: 600;+}+.why-sie p { margin: 0; color: var(--muted); line-height: 1.6; max-width: 1100px; }++.tour {+ padding: 12px 20px; border-bottom: 1px solid var(--line);+ background: rgba(98,182,255,0.04);+}+.tour h3 {+ margin: 0 0 6px 0; font-size: 11px; letter-spacing: 0.6px;+ text-transform: uppercase; color: var(--accent-2); font-weight: 600;+}+.tour-list {+ margin: 0; padding-left: 22px;+ color: var(--muted); line-height: 1.55;+ max-width: 1100px;+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 4px 24px;+}+.tour-list li { padding: 3px 0; }+.tour-list strong { color: var(--text); font-weight: 600; }+.tour-list code {+ background: var(--line); padding: 1px 5px; border-radius: 3px;+ color: var(--accent-2); font-size: 11px;+}++main {+ flex: 1; display: grid;+ grid-template-columns: 0.95fr 1.4fr 1.2fr;+ gap: 12px; padding: 12px 20px; overflow: hidden;+ min-height: 480px;+}++.panel {+ display: flex; flex-direction: column;+ background: var(--panel); border: 1px solid var(--line);+ border-radius: 10px; overflow: hidden; min-height: 0;+}+.panel header {+ padding: 10px 14px; border-bottom: 1px solid var(--line);+ display: flex; justify-content: space-between; align-items: baseline;+}+.panel h2 {+ font-size: 12px; letter-spacing: 0.6px; text-transform: uppercase;+ margin: 0; color: var(--muted);+}+#panel-events h2 { color: var(--accent); }+#panel-recognition h2 { color: var(--accent-2); }+#panel-extraction h2 { color: var(--magenta); }++.hint { color: var(--muted); font-size: 11px; }++.list, .markdown, .extraction {+ flex: 1; overflow: auto; padding: 12px 14px; margin: 0;+}++.sdk-snippet {+ border-bottom: 1px solid var(--line);+ background: rgba(0,0,0,0.2);+ font-size: 11px;+}+.sdk-snippet summary {+ padding: 6px 14px; cursor: pointer;+ color: var(--accent-2); user-select: none;+ font-weight: 500;+}+.sdk-snippet summary::marker { color: var(--accent-2); }+.sdk-snippet pre {+ margin: 0; padding: 8px 14px 10px;+ white-space: pre-wrap; word-break: break-word;+ color: var(--text); font-size: 11px; line-height: 1.45;+}+.sdk-snippet code .arg { color: var(--magenta); }+.sdk-snippet code .str { color: var(--green); }+.sdk-snippet code .com { color: var(--muted); }++.meta-row {+ padding: 10px 14px; border-bottom: 1px solid var(--line);+ font-size: 11px; color: var(--muted);+ display: flex; flex-direction: column; gap: 6px;+}+.model-pick {+ display: flex; align-items: center; gap: 8px;+ font-size: 11px;+}+.dropdown-label {+ color: var(--muted); text-transform: uppercase;+ letter-spacing: 0.5px; min-width: 80px;+}+.meta-row select {+ flex: 1; min-width: 0;+ background: var(--bg); color: var(--text); border: 1px solid var(--line);+ border-radius: 6px; padding: 4px 8px; font: inherit;+ font-size: 11px;+}+.meta-row select:disabled, .meta-row option:disabled {+ color: var(--muted);+}++.event {+ padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px;+ margin-bottom: 10px; cursor: pointer;+ transition: border-color 0.1s;+ display: flex; gap: 12px; align-items: center;+}+.event:hover { border-color: var(--accent); }+.event.active { border-color: var(--accent); background: rgba(124,93,255,0.08); }+.event img {+ width: 64px; height: 64px; object-fit: cover;+ border-radius: 4px; background: #fff;+ flex-shrink: 0;+}+.event .label { font-weight: 600; color: var(--text); font-size: 13px; }+.event .desc { color: var(--muted); font-size: 11px; margin-top: 2px; line-height: 1.4; }++.markdown {+ white-space: pre-wrap; word-break: break-word;+ font-size: 13px; line-height: 1.55;+}++.extraction .section {+ margin-bottom: 14px; padding-bottom: 10px;+ border-bottom: 1px dashed var(--line);+}+.extraction .section:last-child { border-bottom: 0; margin-bottom: 0; }+.extraction h3 {+ font-size: 11px; letter-spacing: 0.6px; text-transform: uppercase;+ color: var(--muted); margin: 0 0 6px 0; font-weight: 500;+}+.field {+ display: flex; gap: 8px; padding: 4px 0;+ font-size: 12px;+}+.field .label-name {+ color: var(--accent-2); font-weight: 500; min-width: 90px;+}+.field .text { color: var(--text); flex: 1; }+.field .score { color: var(--muted); font-size: 11px; }++.donut-row { padding: 3px 0; font-size: 12px; }+.donut-row .key { color: var(--magenta); }+.donut-row .val { color: var(--text); margin-left: 8px; }++footer {+ padding: 10px 20px; border-top: 1px solid var(--line);+ color: var(--muted); font-size: 12px;+ display: flex; justify-content: space-between; gap: 12px;+}+code { background: var(--line); padding: 1px 6px; border-radius: 4px; }++@media (max-width: 900px) {+ .hero { grid-template-columns: 1fr; }+ main { grid-template-columns: 1fr; }+ .cta-row { margin-left: 0; }+}diff --git a/examples/document-ocr/web/server.ts b/examples/document-ocr/web/server.tsnew file mode 100644index 000000000..6d50e1797--- /dev/null+++ b/examples/document-ocr/web/server.ts@@ -0,0 +1,193 @@+import fs from "node:fs";+import http from "node:http";+import path from "node:path";+import { spawnSync } from "node:child_process";+import { fileURLToPath } from "node:url";+import { SIEClient } from "@superlinked/sie-sdk";+import { NER_MODELS, RECOGNITION_MODELS, STRUCTURED_MODELS, config } from "../src/config.js";+import type { PipelineEvent } from "../src/events.js";+import { runPipeline } from "../src/pipeline.js";+import type { SampleDoc } from "../src/types.js";++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(__dirname, "..");+const PUBLIC_DIR = path.resolve(__dirname, "public");+const SAMPLES_PATH = path.resolve(ROOT, config.paths.samples);+const SAMPLE_DIR = path.resolve(ROOT, config.paths.sampleDir);++const MIME: Record<string, string> = {+ ".html": "text/html; charset=utf-8",+ ".css": "text/css; charset=utf-8",+ ".js": "text/javascript; charset=utf-8",+ ".json": "application/json",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+};++function send(res: http.ServerResponse, status: number, body: string, type = "text/plain") {+ res.writeHead(status, { "content-type": type });+ res.end(body);+}++function serveFile(res: http.ServerResponse, file: string) {+ if (!fs.existsSync(file)) return send(res, 404, "not found");+ const ext = path.extname(file).toLowerCase();+ res.writeHead(200, { "content-type": MIME[ext] ?? "application/octet-stream" });+ fs.createReadStream(file).pipe(res);+}++function setupSse(res: http.ServerResponse) {+ res.writeHead(200, {+ "content-type": "text/event-stream",+ "cache-control": "no-cache",+ connection: "keep-alive",+ });+ return (event: { type: string; data?: unknown }) => {+ res.write(`event: ${event.type}\n`);+ res.write(`data: ${JSON.stringify(event.data ?? null)}\n\n`);+ };+}++async function fetchModels(): Promise<{ ok: boolean; names: string[]; cuda: boolean }> {+ try {+ const r = await fetch(`${config.sieUrl}/v1/models`, { signal: AbortSignal.timeout(3000) });+ if (!r.ok) return { ok: false, names: [], cuda: false };+ const json = (await r.json()) as {+ models?: { name: string; device?: string; state?: string }[];+ };+ const models = json.models ?? [];+ // GPU compose preloads GPU-only models. If any catalog entry is currently+ // loaded on a non-cpu device, treat this server as GPU-capable.+ const cuda = models.some((m) => (m.device ?? "").toLowerCase().includes("cuda"));+ return { ok: true, names: models.map((m) => m.name), cuda };+ } catch {+ return { ok: false, names: [], cuda: false };+ }+}++function readJson<T>(p: string): T {+ return JSON.parse(fs.readFileSync(p, "utf8")) as T;+}++async function handleRun(+ req: http.IncomingMessage,+ res: http.ServerResponse,+ sampleId: string,+ recognitionModel: string,+ structuredModel: string,+ nerModel: string,+) {+ const push = setupSse(res);+ let closed = false;+ req.on("close", () => {+ closed = true;+ });++ const samples = readJson<SampleDoc[]>(SAMPLES_PATH);+ const sample = samples.find((s) => s.id === sampleId);+ if (!sample) {+ push({ type: "error", data: { stage: "lookup", message: `unknown sample id: ${sampleId}` } });+ return res.end();+ }++ const imagePath = path.resolve(SAMPLE_DIR, sample.filename);+ if (!fs.existsSync(imagePath)) {+ push({ type: "error", data: { stage: "lookup", message: `sample image not found: ${sample.filename}` } });+ return res.end();+ }+ const imageBytes = fs.readFileSync(imagePath);++ const client = new SIEClient(config.sieUrl, {+ apiKey: config.sieApiKey,+ timeout: 600_000, // 10 min request timeout (CPU + Rosetta is slow)+ waitForCapacity: true, // retry while a model is warming up+ provisionTimeout: 900_000, // 15 min ceiling on cold-load polling+ });++ try {+ await runPipeline({+ client,+ imageBytes,+ sample,+ recognitionModel,+ structuredModel,+ nerModel,+ emit: (event: PipelineEvent) => {+ if (closed) return;+ push({ type: event.type, data: "data" in event ? event.data : null });+ },+ });+ } catch (err) {+ push({ type: "error", data: { stage: "pipeline", message: (err as Error).message } });+ } finally {+ await client.close().catch(() => {});+ res.end();+ }+}++const server = http.createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);+ const p = url.pathname;++ if (p === "/" || p === "/index.html") return serveFile(res, path.join(PUBLIC_DIR, "index.html"));+ if (p.startsWith("/static/")) return serveFile(res, path.join(PUBLIC_DIR, p.slice("/static/".length)));+ if (p.startsWith("/samples/")) return serveFile(res, path.join(SAMPLE_DIR, p.slice("/samples/".length)));++ if (p === "/api/health") {+ const { ok, names, cuda } = await fetchModels();+ return send(+ res,+ 200,+ JSON.stringify({+ sie: ok,+ sieUrl: config.sieUrl,+ registeredModels: names.length,+ registered: names,+ cuda,+ }),+ "application/json",+ );+ }+ if (p === "/api/models") {+ return send(+ res,+ 200,+ JSON.stringify({+ recognition: RECOGNITION_MODELS,+ structured: STRUCTURED_MODELS,+ ner: NER_MODELS,+ defaults: config.defaults,+ }),+ "application/json",+ );+ }+ if (p === "/api/samples") {+ return send(res, 200, fs.readFileSync(SAMPLES_PATH, "utf8"), "application/json");+ }+ if (p === "/api/run") {+ const id = url.searchParams.get("id");+ const recognitionModel =+ url.searchParams.get("recognition") ?? config.defaults.recognition;+ const structuredModel = url.searchParams.get("structured") ?? config.defaults.structured;+ const nerModel = url.searchParams.get("ner") ?? config.defaults.ner;+ if (!id) return send(res, 400, "missing id");+ return handleRun(req, res, id, recognitionModel, structuredModel, nerModel);+ }++ return send(res, 404, "not found");+});++server.listen(config.port, () => {+ const url = `http://localhost:${config.port}`;+ console.log(`document-ocr ui: ${url}`);+ if (process.env.OPEN_BROWSER !== "0") {+ const opener =+ process.platform === "darwin"+ ? "open"+ : process.platform === "win32"+ ? "start"+ : "xdg-open";+ spawnSync(opener, [url], { stdio: "ignore" });+ }+});