Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(examples): use real PDFs for vision doc RAG
svonava2ba8efc3c86c
diff --git a/examples/vision-doc-rag/.gitignore b/examples/vision-doc-rag/.gitignoreindex a787e9203..9a052846f 100644--- a/examples/vision-doc-rag/.gitignore+++ b/examples/vision-doc-rag/.gitignore@@ -1,6 +1,9 @@.venv/__pycache__/data/pages.json+data/pdfs_manifest.json+data/pages_manifest.json+data/pdfs/data/pages/data/multivectors.npzdata/metadata.jsondiff --git a/examples/vision-doc-rag/README.md b/examples/vision-doc-rag/README.mdindex f179051c7..f2ca37754 100644--- a/examples/vision-doc-rag/README.md+++ b/examples/vision-doc-rag/README.md@@ -1,64 +1,70 @@# Vision-first document RAG-Retrieve by image, answer by image. ColQwen2.5 reads each page as a picture-and ranks them via late interaction; Florence-2-DocVQA reads the winning-page and produces the textual answer. OCR never enters the score path, so-charts, screenshots, tables, and any other layout cue that would die in a-text round-trip still drives ranking. Everything runs on one SIE endpoint.+Retrieve by image, answer by image. ColQwen2.5 reads each PDF page as a+picture and ranks pages via late interaction; Florence-2-DocVQA reads the+winning page and produces the textual answer. OCR never enters the score path,+so schematics, pinout diagrams, architecture slides, charts, and other layout+cues still drive ranking. Everything runs on one SIE endpoint.Each page also carries a `client` tag, so the same corpus serves multiple-tenants from one index — queries scoped to `acme-corp` cannot retrieve a-`globex` page, no separate index per tenant required.+tenants from one index. Queries scoped to `embedded-lab` cannot retrieve+`ops-eng` or `aerospace` pages.++## Corpus++The demo fetches a small public PDF batch on demand and renders selected pages+to PNGs. The page selections are deliberately capped so local ingest stays+fast while still indexing visually rich pages.++| Tenant | Sources | Visual signal |+|---|---|---|+| `embedded-lab` | Raspberry Pi Pico datasheet, Arduino UNO R3 datasheet, Arduino UNO R3 schematic | Pinout diagrams, board diagrams, circuit schematics |+| `ops-eng` | PostgreSQL manual, CNCF Kubernetes / cloud-native architecture material | Architecture diagrams, operational flows, dense technical tables |+| `aerospace` | NASA NTRS nozzle and booster reports | Engineering drawings, cross-sections, charts, mission technical figures |++Generated files are ignored:++```text+data/pdfs/ # downloaded PDFs+data/pdfs_manifest.json # source manifest from fetch_pdfs.py+data/pages/ # rendered PNG pages+data/pages_manifest.json # page-level metadata from render_pages.py+data/metadata.json # index metadata from ingest.py+data/multivectors.npz # page multivectors from ingest.py+```## SIE features used-- `encode` — `vidore/colqwen2.5-v0.2` on page images at ingest and on the- query text at search time. Output is a `[tokens, 128]` multivector. Late- interaction (`sie_sdk.scoring.maxsim`) is the only ranking signal.-- `extract` — `mynkchaudhry/Florence-2-FT-DocVQA`. Called twice, with two- jobs: with `instruction=<your question>` to get a textual answer for the- top page, and without `instruction` to OCR the same page for a display- snippet. The OCR snippet is UX-only — it never enters the score path.-- `score` *(optional)* — `Qwen/Qwen3-VL-Reranker-2B` second-stage rerank- over `(query text, page image)`. Off by default while we wait for an- upstream adapter fix; flip `search.visual_rerank: true` in `config.yaml`- to enable it on a cluster that's ready.--## Why vision end-to-end--OCR-then-text-rerank throws away the exact signal we pick ColQwen for —-charts, screenshots, tables, callouts, and the spatial layout that tells-a wiki page apart from a checklist. The rerank stays visual or doesn't-happen. The OCR step shows on-screen text next to the page image so the-user can copy/paste from the result, nothing more.--## Multi-tenant by construction--Every page carries a `client` field in `data/pages.json`. The metadata list-loaded by `python/search.py` is filtered by `client_name` before MaxSim-runs, so a query scoped to `acme-corp` cannot retrieve a `globex` page.-Real deployments would push `client` down into the multivector store's-filter expression; the demo keeps everything in memory because the corpus-is tiny.+- `encode` - `vidore/colqwen2.5-v0.2` on page images at ingest and on query+ text at search time. Output is a `[tokens, 128]` multivector. Late+ interaction (`sie_sdk.scoring.maxsim`) is the first-stage ranking signal.+- `extract` - `mynkchaudhry/Florence-2-FT-DocVQA`. Called with+ `instruction=<your question>` to get a textual answer for the top page, and+ without `instruction` to OCR the same page for a display snippet. The OCR+ snippet is UX-only; it never enters ranking.+- `score` optional - `Qwen/Qwen3-VL-Reranker-2B` second-stage rerank over+ `(query text, page image)`. Off by default while we wait for an upstream+ adapter fix; flip `search.visual_rerank: true` in `config.yaml` to enable it+ on a cluster that's ready.## Run it-You need Python 3.12 and a reachable SIE cluster (or local `docker run`).+You need Python 3.12 and a reachable SIE cluster.```bash-# 1. SIE locally (or point SIE_CLUSTER_URL / SIE_API_KEY at a managed cluster).+# 1. SIE locally, or point SIE_CLUSTER_URL / SIE_API_KEY at a managed cluster.docker run -p 8080:8080 ghcr.io/superlinked/sie-server:latest-cpu-default-# 2. Generate the synthetic corpus and render each page to a PNG.+# 2. Fetch public PDFs and render selected pages to PNG.cd examples/vision-doc-ragpip install -r python/requirements.txt-python data/fetch_dataset.py+python data/fetch_pdfs.pypython data/render_pages.py-# 3. Encode every page with ColQwen2.5 and save the multivectors.+# 3. Encode every rendered page with ColQwen2.5 and save the multivectors.python python/ingest.py-# 4a. CLI demo — runs four scoped queries and prints results.+# 4a. CLI demo.python python/search.py# 4b. Or start the UI.@@ -66,30 +72,34 @@ uvicorn --app-dir python server:app --port 8888open http://localhost:8888```-First run on a cold cluster pays a one-time model load: ColQwen2.5 and-Florence-2 are both several GB, expect roughly a minute on CPU and a few+`render_pages.py` uses `pdf2image` when Poppler is available. If Poppler is+not installed, it falls back to PyMuPDF, which is installed from+`python/requirements.txt`.++First run on a cold cluster pays a one-time model load. ColQwen2.5 and+Florence-2 are both several GB, so expect roughly a minute on CPU and a fewseconds on GPU before the warm path kicks in.-### Pointing at a managed cluster+### Managed cluster```bashexport SIE_CLUSTER_URL="https://your-cluster-host:8080"export SIE_API_KEY="SL-..."```-The defaults in `config.yaml` point at `http://localhost:8080` so the env-vars only matter when you're hitting something remote. Set `cluster.gpu`-to a profile name like `l4-spot` if the cluster needs an explicit GPU-class.+The defaults in `config.yaml` point at `http://localhost:8080`. Set+`cluster.gpu` to a profile name like `l4-spot` if the cluster needs an+explicit GPU class.## Try these queries| Tenant | Query | Why it's interesting ||---|---|---|-| `acme-corp` | how do I sign in to the VPN? | Visual layout match — the page is titled "VPN setup for new engineers" with a bulleted body, and ColQwen2.5 picks it without keyword overlap with "sign in". DocVQA reads the page and answers with the client name and the auth method. |-| `globex` | what is the parental leave policy? | Disambiguates from "time off" — the right page mentions parental leave only halfway down the body. The textual answer cites the week count. |-| `initech` | audit prep evidence and walkthroughs | All three Initech pages are compliance-flavored; the visual model breaks the tie by reading the checklist layout. |-| `globex` | how do I sign in to the VPN? | Tenant filter — even though the same query hit acme-corp earlier, scoping to globex returns the closest globex page (Wi-Fi guide) and never leaks acme content. |+| `embedded-lab` | Raspberry Pi Pico pinout GP21 | Should land on a pinout/table page even when the visual label is abbreviated. |+| `embedded-lab` | where is the ATmega16U2 on the schematic? | Circuit schematic retrieval, not prose retrieval. |+| `ops-eng` | cloud native architecture diagram | Finds a visual architecture page or slide instead of relying on OCR text only. |+| `aerospace` | solid rocket motor nozzle design figure | Targets an engineering drawing or figure-heavy report page. |+| `ops-eng` | Raspberry Pi Pico pinout GP21 | Tenant filter: the query cannot leak embedded-lab pages when scoped to ops-eng. |## API@@ -98,33 +108,27 @@ class.| Parameter | Required | Description ||---|---|---|| `q` | yes | Search query |-| `client` | no | Tenant filter (e.g. `acme-corp`). Omitted ⇒ search runs across all tenants. |+| `client` | no | Tenant filter, for example `embedded-lab`. Omitted means search all tenants. |```bash-curl "http://localhost:8888/api/search?q=how+do+I+sign+in+to+the+VPN&client=acme-corp"+curl "http://localhost:8888/api/search?q=Raspberry+Pi+Pico+pinout+GP21&client=embedded-lab"``````json{- "query": "how do I sign in to the VPN",- "client": "acme-corp",- "answer": "Okta credentials with Duo Push for 2FA",- "timings": {- "encode_query_s": 0.12,- "maxsim_s": 0.003,- "docvqa_s": 0.91,- "ocr_snippet_s": 0.84- },+ "query": "Raspberry Pi Pico pinout GP21",+ "client": "embedded-lab",+ "answer": "GP21 can be used for ...","results": [{- "page_id": "ACME-101",- "client": "acme-corp",- "title": "VPN setup for new engineers",- "space": "Engineering",- "author": "alice@acme",- "web_url": "https://acme.atlassian.net/wiki/spaces/ENG/pages/101",- "page_image": "/pages/ACME-101.png",- "ocr_snippet": "VPN Setup for New Engineers · ...",+ "page_id": "embedded-lab__raspberry-pi-pico-datasheet__p005",+ "client": "embedded-lab",+ "title": "Raspberry Pi Pico Datasheet",+ "publisher": "Raspberry Pi Ltd",+ "source_pdf": "raspberry-pi-pico-datasheet.pdf",+ "page_number": 5,+ "citation": "raspberry-pi-pico-datasheet.pdf · p.5",+ "page_image": "/pages/embedded-lab/raspberry-pi-pico-datasheet_p005.png","scores": { "maxsim": 14.44, "rerank": null }}]@@ -133,48 +137,68 @@ curl "http://localhost:8888/api/search?q=how+do+I+sign+in+to+the+VPN&client=acme### `GET /api/clients`, `GET /api/stats`-Tenant list and runtime config (active models, rerank on/off, page count).+Tenant list and runtime config: active models, rerank on/off, and page count.## How it works-```- ┌──────────────────────────────────────────────────────────────┐- │ ingest.py (once per corpus) │- │ pages.json ─▶ render_pages.py ─▶ data/pages/*.png │- │ ─▶ SIE.encode(ColQwen2.5, images, multivector) │- │ ─▶ data/multivectors.npz + data/metadata.json │- └──────────────────────────────────────────────────────────────┘- │- ▼- ┌──────────────────────────────────────────────────────────────┐- │ search.py / server.py (per query) │- │ q ─▶ SIE.encode(ColQwen2.5, text, is_query=True) │- │ ─▶ filter metadata by tenant │- │ ─▶ sie_sdk.scoring.maxsim → top_k_candidates │- │ ─▶ [optional] SIE.score(Qwen3-VL-Reranker, q, images) │- │ ─▶ SIE.extract(Florence-2-DocVQA, instruction=q, │- │ images=[top_page]) ⇒ textual answer │- │ ─▶ SIE.extract(Florence-2-DocVQA, images=[top_page]) │- │ ⇒ OCR snippet (UI) │- └──────────────────────────────────────────────────────────────┘+```text+ ingest.py (once per corpus)+ fetch_pdfs.py -> data/pdfs/{tenant}/*.pdf+ -> render_pages.py -> data/pages/{tenant}/*.png+ -> data/pages_manifest.json+ -> SIE.encode(ColQwen2.5, images, multivector)+ -> data/multivectors.npz + data/metadata.json++ search.py / server.py (per query)+ q -> SIE.encode(ColQwen2.5, text, is_query=True)+ -> filter metadata by tenant+ -> sie_sdk.scoring.maxsim -> top_k_candidates+ -> optional SIE.score(Qwen3-VL-Reranker, q, images)+ -> SIE.extract(Florence-2-DocVQA, instruction=q, images=[top_page])+ -> SIE.extract(Florence-2-DocVQA, images=[top_page]) for display OCR```-OCR is never on the score path. The visual reranker (when enabled) ranks-over the same modality as retrieval, so layout cues survive both stages.+OCR is never on the score path. The visual reranker, when enabled, ranks over+the same modality as retrieval, so layout cues survive both stages.-The corpus is small enough that MaxSim runs in Python. For thousands of-pages, hand the multivectors to LanceDB or Vespa; only the SIE calls stay-the same.+The corpus is small enough that MaxSim runs in Python. For thousands of pages,+hand the multivectors to LanceDB, Vespa, or another multivector store; the SIE+calls stay the same.## Customize-`config.yaml` is the single tuning surface:+`data/fetch_pdfs.py` owns the curated source list. Add a source with:++```python+{+ "client": "my-tenant",+ "slug": "my-manual",+ "title": "My Manual",+ "publisher": "Example Publisher",+ "license": "CC BY 4.0",+ "url": "https://example.com/my-manual.pdf",+ "pages": [1, 2, 7, 8],+}+```++Then rerun:++```bash+python data/fetch_pdfs.py+python data/render_pages.py+python python/ingest.py+```++`config.yaml` is the model and rendering tuning surface:```yamlmodels:- retriever: "vidore/colqwen2.5-v0.2" # smaller: vidore/colpali-v1.3-hf+ retriever: "vidore/colqwen2.5-v0.2"docvqa: "mynkchaudhry/Florence-2-FT-DocVQA"- reranker: "Qwen/Qwen3-VL-Reranker-2B" # used only when search.visual_rerank: true+ reranker: "Qwen/Qwen3-VL-Reranker-2B"+render:+ backend: "auto"+ dpi: 160search:top_k_candidates: 5top_k_results: 3@@ -183,22 +207,18 @@ search:ocr_snippet: true```-Swap any model for another from the-[SIE model catalog](https://superlinked.com/models) and the pipeline keeps-working.-## Project layout```textexamples/vision-doc-rag/├── config.yaml├── data/-│ ├── fetch_dataset.py # synthetic 3-tenant page corpus-│ ├── render_pages.py # pages.json → PNG screenshots-│ ├── pages.json # generated-│ ├── pages/ # generated PNGs-│ ├── metadata.json # generated by ingest-│ └── multivectors.npz # generated by ingest+│ ├── fetch_pdfs.py # curated public PDF source list + downloader+│ ├── render_pages.py # PDFs -> PNG pages + pages_manifest.json+│ ├── pdfs/ # generated+│ ├── pages/ # generated PNGs+│ ├── metadata.json # generated by ingest+│ └── multivectors.npz # generated by ingest├── python/│ ├── ingest.py│ ├── search.pydiff --git a/examples/vision-doc-rag/config.yaml b/examples/vision-doc-rag/config.yamlindex 8b35ffda3..587548f28 100644--- a/examples/vision-doc-rag/config.yaml+++ b/examples/vision-doc-rag/config.yaml@@ -25,14 +25,11 @@ models:# Re-enable with search.visual_rerank: true once that ships.reranker: "Qwen/Qwen3-VL-Reranker-2B"-# Page rendering (used by data/render_pages.py to turn the synthetic page-# corpus into PNGs; replace with pdf2image, screenshots, or your own files-# for a real deployment).+# Page rendering. `auto` tries pdf2image/Poppler first and falls back to+# PyMuPDF when Poppler is not installed.render:- width: 1024- height: 1280- body_font_size: 20- title_font_size: 30+ backend: "auto" # auto | pdf2image | pymupdf+ dpi: 160# Retrievalsearch:diff --git a/examples/vision-doc-rag/data/fetch_dataset.py b/examples/vision-doc-rag/data/fetch_dataset.pydeleted file mode 100644index eb901a6c3..000000000--- a/examples/vision-doc-rag/data/fetch_dataset.py+++ /dev/null@@ -1,211 +0,0 @@-"""Synthetic multi-tenant page corpus.--Three fictional clients, each with a handful of pages — engineering runbooks,-HR policies, finance procedures. Small enough to encode in a minute on a warm-GPU cluster, varied enough to make multi-tenant filtering and visual retrieval-meaningful. Replace `PAGES` with your own pages (wiki export, Notion dump,-PDF batch, etc.) to point the demo at real content.-"""--import json-from pathlib import Path--PAGES = [- # ── acme-corp: engineering ────────────────────────────────────────────- {- "client": "acme-corp",- "page_id": "ACME-101",- "title": "VPN setup for new engineers",- "space": "Engineering",- "author": "alice@acme",- "web_url": "https://acme.atlassian.net/wiki/spaces/ENG/pages/101",- "body": [- "All engineers need to connect through the corporate VPN to reach internal services.",- "We use Cisco AnyConnect on macOS and Windows, and the OpenConnect CLI on Linux.",- "Download the client from it.acme.com/vpn, then sign in with your Okta credentials.",- "Two-factor confirmation goes through Duo Push.",- "If you hit a TLS error on first connection, check that the device certificate from Jamf is installed.",- "For on-call rotations, request the always-on VPN profile from IT — it auto-reconnects after suspend.",- ],- },- {- "client": "acme-corp",- "page_id": "ACME-102",- "title": "On-call rotation and paging",- "space": "Engineering",- "author": "bob@acme",- "web_url": "https://acme.atlassian.net/wiki/spaces/ENG/pages/102",- "body": [- "Engineering on-call runs Monday to Monday handovers at 10:00 PT.",- "Primary takes the pager, secondary takes the laptop, both are paid the on-call stipend.",- "Pages route through PagerDuty; the escalation policy is primary -> secondary (15 min) -> manager.",- "During an incident open a Zoom bridge and a Slack channel named #inc-YYYYMMDD-summary.",- "Postmortems are due within five working days and live in the Incidents space.",- ],- },- {- "client": "acme-corp",- "page_id": "ACME-103",- "title": "Deploying to production with our CI/CD pipeline",- "space": "Engineering",- "author": "carol@acme",- "web_url": "https://acme.atlassian.net/wiki/spaces/ENG/pages/103",- "body": [- "We use GitHub Actions for CI and ArgoCD for delivery to Kubernetes.",- "Merging to main triggers a build, runs the test suite, pushes an image to ECR, and updates the staging manifest.",- "Production rollouts are gated by a manual approval in ArgoCD and require two reviewers from the service team.",- "Use the rolling strategy with maxSurge=25% by default.",- "Hotfix tags follow the pattern v1.2.3-hotfix.N and skip staging only with on-call approval recorded in the PR.",- ],- },- {- "client": "acme-corp",- "page_id": "ACME-104",- "title": "Local development setup",- "space": "Engineering",- "author": "dan@acme",- "web_url": "https://acme.atlassian.net/wiki/spaces/ENG/pages/104",- "body": [- "Install mise to manage runtimes — it pins Node, Python, and Go versions per repo.",- "Run `mise install` in the repo root, then `make dev` to spin up Postgres, Redis, and the API gateway in Docker.",- "The seed data covers the last 30 days of staging traffic, sanitized of PII.",- "If port 5432 is already taken, override DEV_PG_PORT in your shell profile.",- ],- },- # ── globex: HR and admin ──────────────────────────────────────────────- {- "client": "globex",- "page_id": "GLOBEX-201",- "title": "Time off and vacation policy",- "space": "HR",- "author": "hr@globex",- "web_url": "https://globex.atlassian.net/wiki/spaces/HR/pages/201",- "body": [- "Globex offers 25 working days of paid vacation per year, accruing monthly from the start date.",- "Requests go through Workday at least two weeks in advance for absences longer than three days.",- "Sick leave is separate and uncapped, but anything over three consecutive days requires a doctor's note.",- "Parental leave is 18 weeks at full pay for the primary caregiver and 6 weeks for the secondary, regardless of gender.",- "Unused vacation rolls over up to 10 days into the next calendar year; the rest is paid out.",- ],- },- {- "client": "globex",- "page_id": "GLOBEX-202",- "title": "Expense reports and reimbursement",- "space": "HR",- "author": "finance@globex",- "web_url": "https://globex.atlassian.net/wiki/spaces/HR/pages/202",- "body": [- "Submit expenses in Expensify within 30 days of the transaction.",- "Receipts are mandatory for any item over $25; below that, a description and category are enough.",- "Travel bookings should go through Navan when possible — direct bookings need pre-approval from your manager.",- "Reimbursements process every Friday and land in your payroll account the following Tuesday.",- "Per diem for international travel is $80 USD equivalent for meals.",- ],- },- {- "client": "globex",- "page_id": "GLOBEX-203",- "title": "Office perks and meals",- "space": "HR",- "author": "office@globex",- "web_url": "https://globex.atlassian.net/wiki/spaces/HR/pages/203",- "body": [- "Lunch is catered Monday through Thursday in the main cafe from 12:00 to 14:00.",- "There are always vegetarian, vegan, and gluten-free options labeled at the buffet.",- "Friday is a free-lunch credit you can spend at any partner restaurant in the office app.",- "Snacks and drinks in the micro-kitchens are unlimited; please refill empty trays.",- "The wellness stipend is $100 per month, claimable in Expensify under category Wellness.",- ],- },- {- "client": "globex",- "page_id": "GLOBEX-204",- "title": "Office Wi-Fi and guest network",- "space": "IT",- "author": "it@globex",- "web_url": "https://globex.atlassian.net/wiki/spaces/IT/pages/204",- "body": [- "Connect to Globex-Corp for the employee network; sign in with your @globex.com SSO.",- "Globex-Guest is for visitors — the rotating daily password is on the lobby screen.",- "Printing requires the Globex-Print network and a one-time pairing with your laptop using the Mobility Print app.",- "If your laptop will not join, forget the network and rejoin; the cert is renewed weekly and old caches get stuck.",- ],- },- # ── initech: finance and compliance ───────────────────────────────────- {- "client": "initech",- "page_id": "INIT-301",- "title": "SOX controls and quarterly attestation",- "space": "Compliance",- "author": "compliance@initech",- "web_url": "https://initech.atlassian.net/wiki/spaces/COMP/pages/301",- "body": [- "Initech is subject to SOX 404 reporting for financial controls over revenue, expense, and access management.",- "Every quarter, control owners attest in AuditBoard that their controls operated as designed.",- "Evidence is automatically collected from Workday, NetSuite, and Okta where possible; manual evidence goes in the AuditBoard Drive folder.",- "External auditors test a sample of controls in Q3; expect requests for screenshots and approver lists.",- "Exceptions must be logged within five business days of detection.",- ],- },- {- "client": "initech",- "page_id": "INIT-302",- "title": "Vendor onboarding and due diligence",- "space": "Procurement",- "author": "procurement@initech",- "web_url": "https://initech.atlassian.net/wiki/spaces/PROC/pages/302",- "body": [- "New vendors above $50,000 annual spend require a security review and a SOC 2 Type II report on file.",- "Submit the vendor questionnaire through Vanta; legal will review the MSA within five business days.",- "Payment terms default to Net 60; faster terms require CFO approval and reduce the risk score in NetSuite.",- "Sanctioned-country checks run automatically via the OFAC integration; any hit halts the workflow until cleared.",- "Annual recertification of high-risk vendors happens every January.",- ],- },- {- "client": "initech",- "page_id": "INIT-303",- "title": "Audit prep checklist",- "space": "Compliance",- "author": "audit@initech",- "web_url": "https://initech.atlassian.net/wiki/spaces/COMP/pages/303",- "body": [- "Two weeks before the auditors arrive, freeze the control population in AuditBoard and export the evidence index.",- "Confirm with control owners that they will be available for walkthrough interviews — block 60 minutes in their calendars.",- "Pull the user access review reports for the prior two quarters from Okta and confirm sign-off in writing.",- "Have the change management JIRA queries ready: filter by label sox-relevant and status Done.",- "If a control failed mid-period, document the compensating control and the date the gap was closed.",- ],- },- {- "client": "initech",- "page_id": "INIT-304",- "title": "Procurement card limits and exceptions",- "space": "Procurement",- "author": "procurement@initech",- "web_url": "https://initech.atlassian.net/wiki/spaces/PROC/pages/304",- "body": [- "Procurement cards (P-cards) have a default monthly limit of $5,000 and a single-transaction limit of $1,500.",- "Use them for low-dollar, low-risk purchases — software subscriptions and conference tickets are the common cases.",- "Limit-increase requests need manager and CFO approval and a documented business need.",- "Personal use, cash advances, and split transactions to bypass the single-transaction limit are policy violations.",- "All P-card transactions reconcile in Coupa within 14 days of statement close.",- ],- },-]---def main():- out = Path(__file__).resolve().parent / "pages.json"- out.write_text(json.dumps(PAGES, indent=2))- by_client = {}- for p in PAGES:- by_client[p["client"]] = by_client.get(p["client"], 0) + 1- print(f"Wrote {len(PAGES)} pages to {out}")- for client, n in sorted(by_client.items()):- print(f" {client}: {n} pages")---if __name__ == "__main__":- main()diff --git a/examples/vision-doc-rag/data/fetch_pdfs.py b/examples/vision-doc-rag/data/fetch_pdfs.pynew file mode 100644index 000000000..21ade8444--- /dev/null+++ b/examples/vision-doc-rag/data/fetch_pdfs.py@@ -0,0 +1,158 @@+"""Download the public PDF corpus for the visual document RAG demo.++The corpus is intentionally small and curated. Each source has a tenant, a+stable slug, source metadata, and a limited page selection so the demo can be+indexed quickly while still containing diagrams, schematics, screenshots, and+technical figures that reward visual retrieval.+"""++from __future__ import annotations++import json+import shutil+import sys+import tempfile+from pathlib import Path+from urllib.error import HTTPError, URLError+from urllib.request import Request, urlopen+++SOURCES = [+ {+ "client": "embedded-lab",+ "slug": "raspberry-pi-pico-datasheet",+ "title": "Raspberry Pi Pico Datasheet",+ "publisher": "Raspberry Pi Ltd",+ "license": "CC BY-ND 4.0",+ "url": "https://datasheets.raspberrypi.com/pico/pico-datasheet.pdf",+ "pages": [4, 5, 6, 7, 8, 9],+ },+ {+ "client": "embedded-lab",+ "slug": "arduino-uno-r3-datasheet",+ "title": "Arduino UNO R3 Datasheet",+ "publisher": "Arduino",+ "license": "Arduino documentation / open hardware terms",+ "url": "https://docs.arduino.cc/resources/datasheets/A000066-datasheet.pdf",+ "pages": [5, 6, 7, 8, 9, 10, 11],+ },+ {+ "client": "embedded-lab",+ "slug": "arduino-uno-r3-schematic",+ "title": "Arduino UNO R3 Schematic",+ "publisher": "Arduino",+ "license": "CC BY-SA 4.0 hardware reference design",+ "url": "https://docs.arduino.cc/resources/schematics/A000066-schematics.pdf",+ "pages": [1, 2],+ },+ {+ "client": "ops-eng",+ "slug": "postgresql-18-manual",+ "title": "PostgreSQL 18 Documentation",+ "publisher": "PostgreSQL Global Development Group",+ "license": "PostgreSQL License",+ "url": "https://www.postgresql.org/files/documentation/pdf/18/postgresql-18-A4.pdf",+ "pages": [19, 20, 21, 22, 23, 24],+ },+ {+ "client": "ops-eng",+ "slug": "kubernetes-infrastructure-abstraction",+ "title": "Kubernetes as Infrastructure Abstraction",+ "publisher": "Cloud Native Computing Foundation",+ "license": "CNCF public presentation material",+ "url": "https://www.cncf.io/wp-content/uploads/2020/08/2019-09-Kubernetes-as-Infrastructure-Abstraction.pdf",+ "pages": [6, 7, 8, 9, 10, 11],+ },+ {+ "client": "ops-eng",+ "slug": "cloud-native-ai-whitepaper",+ "title": "Cloud Native Artificial Intelligence Whitepaper",+ "publisher": "Cloud Native Computing Foundation",+ "license": "CNCF documentation / report terms",+ "url": "https://www.cncf.io/wp-content/uploads/2024/03/cloud_native_ai24_031424a-2.pdf",+ "pages": [11, 12, 13, 14, 15, 16],+ },+ {+ "client": "aerospace",+ "slug": "solid-rocket-motor-nozzles",+ "title": "Solid Rocket Motor Nozzles",+ "publisher": "NASA Technical Reports Server",+ "license": "NASA STI public release",+ "url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19760013126.pdf",+ "pages": [1, 2, 3, 4, 5, 6],+ },+ {+ "client": "aerospace",+ "slug": "liquid-rocket-engine-nozzles",+ "title": "Liquid Rocket Engine Nozzles",+ "publisher": "NASA Technical Reports Server",+ "license": "NASA STI public release",+ "url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770009165.pdf",+ "pages": [1, 2, 3, 4, 5, 6],+ },+ {+ "client": "aerospace",+ "slug": "sls-booster-state-machine",+ "title": "State Machine Modeling of the Space Launch System Solid Rocket Boosters",+ "publisher": "NASA Technical Reports Server",+ "license": "NASA STI public release",+ "url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20160000328.pdf",+ "pages": [1, 2, 3, 4, 5, 6],+ },+]+++def _download(url: str, out: Path) -> bool:+ """Download url to out atomically. Return True when a new file was written."""+ if out.exists() and out.stat().st_size > 0:+ return False++ out.parent.mkdir(parents=True, exist_ok=True)+ request = Request(+ url,+ headers={+ "User-Agent": "sie-vision-doc-rag-demo/1.0",+ "Accept": "application/pdf,*/*",+ },+ )+ with tempfile.NamedTemporaryFile(delete=False, dir=out.parent, suffix=".tmp") as tmp:+ tmp_path = Path(tmp.name)+ try:+ with urlopen(request, timeout=60) as response:+ shutil.copyfileobj(response, tmp)+ except (HTTPError, URLError, TimeoutError):+ tmp_path.unlink(missing_ok=True)+ raise++ tmp_path.replace(out)+ return True+++def main() -> None:+ here = Path(__file__).resolve().parent+ pdf_root = here / "pdfs"+ manifest = []++ for source in SOURCES:+ pdf_path = pdf_root / source["client"] / f"{source['slug']}.pdf"+ try:+ downloaded = _download(source["url"], pdf_path)+ except Exception as exc:+ print(f"Failed to download {source['url']}: {type(exc).__name__}: {exc}", file=sys.stderr)+ raise++ row = dict(source)+ row["pdf_path"] = str(pdf_path.relative_to(here))+ row["source_pdf"] = pdf_path.name+ manifest.append(row)++ status = "downloaded" if downloaded else "cached"+ print(f" {status:10s} {source['client']:12s} {source['slug']} -> {row['pdf_path']}")++ out = here / "pdfs_manifest.json"+ out.write_text(json.dumps({"sources": manifest}, indent=2) + "\n")+ print(f"\nWrote {len(manifest)} PDF sources to {out}")+++if __name__ == "__main__":+ main()diff --git a/examples/vision-doc-rag/data/render_pages.py b/examples/vision-doc-rag/data/render_pages.pyindex 4043d71b4..9c1233058 100644--- a/examples/vision-doc-rag/data/render_pages.py+++ b/examples/vision-doc-rag/data/render_pages.py@@ -1,105 +1,146 @@-"""Render the synthetic pages to PNG screenshots.+"""Rasterize the curated PDF corpus to page PNGs.-Each entry in pages.json becomes one image in data/pages/<page_id>.png. The-layout is intentionally plain — a title, a metadata line, and a body block —-so ColQwen2.5 sees the same kind of visual structure it would in real wikis,-docs, or PDFs. Replace this script with `pdf2image` (or screenshots) when-pointing at real content.+The script tries pdf2image first because it produces excellent page images+when Poppler is installed. If Poppler or pdf2image is unavailable, it falls+back to PyMuPDF so the demo still works with only Python package dependencies."""+from __future__ import annotations+import jsonimport sysfrom pathlib import Pathimport yaml-from PIL import Image, ImageDraw, ImageFont---def _font(size: int):- """Try the platform Helvetica, fall back to PIL's default bitmap font."""- for path in [- "/System/Library/Fonts/Helvetica.ttc",- "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",- "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",- ]:- if Path(path).exists():- return ImageFont.truetype(path, size)- return ImageFont.load_default()---def _wrap(text: str, font: ImageFont.ImageFont, max_width: int) -> list[str]:- """Greedy word wrap so body paragraphs fit the page width."""- lines: list[str] = []- for paragraph in text.split("\n"):- words = paragraph.split()- current = ""- for word in words:- candidate = f"{current} {word}".strip()- if font.getlength(candidate) <= max_width:- current = candidate- else:- if current:- lines.append(current)- current = word- if current:- lines.append(current)- return lines---def render_page(page: dict, width: int, height: int, body_size: int, title_size: int) -> Image.Image:- img = Image.new("RGB", (width, height), "white")- draw = ImageDraw.Draw(img)- title_font = _font(title_size)- meta_font = _font(int(body_size * 0.9))- body_font = _font(body_size)-- margin = 48- cursor_y = margin- draw.text((margin, cursor_y), page["title"], fill="black", font=title_font)- cursor_y += int(title_size * 1.6)- meta = f"{page['space']} · {page['author']} · {page['page_id']}"- draw.text((margin, cursor_y), meta, fill=(96, 96, 96), font=meta_font)- cursor_y += int(title_size * 1.2)- draw.line([(margin, cursor_y), (width - margin, cursor_y)], fill=(200, 200, 200), width=2)- cursor_y += int(body_size * 1.2)-- max_text_width = width - 2 * margin- line_gap = int(body_size * 1.5)- for bullet in page["body"]:- # Render each body line as a wrapped paragraph block.- lines = _wrap(bullet, body_font, max_text_width)- for line in lines:- draw.text((margin, cursor_y), line, fill="black", font=body_font)- cursor_y += line_gap- cursor_y += int(line_gap * 0.4) # paragraph spacing-- return img---def main():+++def _selected_pages(source: dict, total_pages: int) -> list[int]:+ pages = source.get("pages")+ if pages:+ selected = [int(p) for p in pages if 1 <= int(p) <= total_pages]+ else:+ start = int(source.get("start_page", 1))+ max_pages = int(source.get("max_pages", 6))+ selected = list(range(start, min(total_pages, start + max_pages - 1) + 1))++ if not selected:+ raise ValueError(f"No valid pages selected for {source['slug']} ({total_pages} pages)")+ return selected+++def _pdf_page_count_with_pymupdf(pdf_path: Path) -> int:+ import fitz++ with fitz.open(pdf_path) as doc:+ return doc.page_count+++def _render_with_pdf2image(pdf_path: Path, page_number: int, out_path: Path, dpi: int) -> None:+ from pdf2image import convert_from_path++ images = convert_from_path(+ str(pdf_path),+ dpi=dpi,+ first_page=page_number,+ last_page=page_number,+ fmt="png",+ single_file=True,+ )+ if not images:+ raise RuntimeError(f"pdf2image returned no image for {pdf_path} page {page_number}")+ images[0].save(out_path)+++def _render_with_pymupdf(pdf_path: Path, page_number: int, out_path: Path, dpi: int) -> None:+ import fitz++ zoom = dpi / 72+ matrix = fitz.Matrix(zoom, zoom)+ with fitz.open(pdf_path) as doc:+ page = doc.load_page(page_number - 1)+ pixmap = page.get_pixmap(matrix=matrix, alpha=False)+ pixmap.save(out_path)+++def _render_page(pdf_path: Path, page_number: int, out_path: Path, dpi: int, backend: str) -> str:+ out_path.parent.mkdir(parents=True, exist_ok=True)+ if backend in {"auto", "pdf2image"}:+ try:+ _render_with_pdf2image(pdf_path, page_number, out_path, dpi)+ return "pdf2image"+ except Exception as exc:+ if backend == "pdf2image":+ raise+ print(+ f" pdf2image unavailable for {pdf_path.name} p.{page_number} "+ f"({type(exc).__name__}); falling back to PyMuPDF",+ file=sys.stderr,+ )++ _render_with_pymupdf(pdf_path, page_number, out_path, dpi)+ return "pymupdf"+++def main() -> None:here = Path(__file__).resolve().parent- pages_path = here / "pages.json"- if not pages_path.exists():- print("pages.json not found; run fetch_dataset.py first", file=sys.stderr)+ root = here.parent+ manifest_path = here / "pdfs_manifest.json"+ if not manifest_path.exists():+ print("pdfs_manifest.json not found; run `python data/fetch_pdfs.py` first", file=sys.stderr)sys.exit(1)- config = yaml.safe_load((here.parent / "config.yaml").read_text())- render = config["render"]++ config = yaml.safe_load((root / "config.yaml").read_text())+ render_config = config.get("render", {})+ dpi = int(render_config.get("dpi", 160))+ backend = render_config.get("backend", "auto")+ active_backend = backendout_dir = here / "pages"- out_dir.mkdir(exist_ok=True)-- pages = json.loads(pages_path.read_text())- for p in pages:- img = render_page(- p,- width=render["width"],- height=render["height"],- body_size=render["body_font_size"],- title_size=render["title_font_size"],- )- out = out_dir / f"{p['page_id']}.png"- img.save(out)- print(f" {p['client']:10s} {p['page_id']:10s} -> {out.relative_to(here.parent)}")- print(f"Rendered {len(pages)} pages to {out_dir}")++ pdf_manifest = json.loads(manifest_path.read_text())+ page_manifest: list[dict] = []+ backend_counts: dict[str, int] = {}++ for source in pdf_manifest["sources"]:+ pdf_path = here / source["pdf_path"]+ if not pdf_path.exists():+ raise FileNotFoundError(f"Missing PDF: {pdf_path}. Run data/fetch_pdfs.py.")++ total_pages = _pdf_page_count_with_pymupdf(pdf_path)+ for page_number in _selected_pages(source, total_pages):+ page_id = f"{source['client']}__{source['slug']}__p{page_number:03d}"+ image_path = out_dir / source["client"] / f"{source['slug']}_p{page_number:03d}.png"+ used_backend = _render_page(pdf_path, page_number, image_path, dpi, active_backend)+ if backend == "auto" and used_backend == "pymupdf":+ active_backend = "pymupdf"+ backend_counts[used_backend] = backend_counts.get(used_backend, 0) + 1++ rel_image_path = image_path.relative_to(here)+ page_manifest.append(+ {+ "page_id": page_id,+ "client": source["client"],+ "title": source["title"],+ "publisher": source["publisher"],+ "license": source["license"],+ "source_url": source["url"],+ "source_pdf": source["source_pdf"],+ "source_pdf_path": source["pdf_path"],+ "page_number": page_number,+ "image_path": str(rel_image_path),+ }+ )+ print(+ f" {source['client']:12s} {source['slug']:38s} "+ f"p.{page_number:<4d} -> data/{rel_image_path}"+ )++ out = here / "pages_manifest.json"+ out.write_text(json.dumps(page_manifest, indent=2) + "\n")++ print(f"\nRendered {len(page_manifest)} pages to {out_dir}")+ print(f"Wrote page manifest to {out}")+ for name, count in sorted(backend_counts.items()):+ print(f" {name}: {count} pages")if __name__ == "__main__":diff --git a/examples/vision-doc-rag/python/ingest.py b/examples/vision-doc-rag/python/ingest.pyindex 15607f306..8b0f8e119 100644--- a/examples/vision-doc-rag/python/ingest.py+++ b/examples/vision-doc-rag/python/ingest.py@@ -1,9 +1,10 @@"""Build the per-tenant visual index.-For every page PNG we ask SIE to encode the image with vidore/colqwen2.5-v0.2,-which returns a [tokens, 128] multivector. Each page's multivector goes into a-single .npz on disk, alongside a metadata.json that keeps the client name,-page id, title, and source url for routing and filtering at query time.+For every rendered PDF page PNG we ask SIE to encode the image with+vidore/colqwen2.5-v0.2, which returns a [tokens, 128] multivector. Each page's+multivector goes into a single .npz on disk, alongside a metadata.json that+keeps the client name, source PDF, page number, and source URL for routing,+filtering, and citation at query time.There is no vector database here. MaxSim at the scale of one team's wiki(hundreds to thousands of pages) is cheap and avoids the indexing step.@@ -30,22 +31,22 @@ def load_config():def load_pages():- pages_path = Path(__file__).resolve().parent.parent / "data" / "pages.json"+ pages_path = Path(__file__).resolve().parent.parent / "data" / "pages_manifest.json"if not pages_path.exists():raise FileNotFoundError(- "data/pages.json not found. Run `python data/fetch_dataset.py` "+ "data/pages_manifest.json not found. Run `python data/fetch_pdfs.py` ""and `python data/render_pages.py` first.")return json.loads(pages_path.read_text())def encode_pages(client: SIEClient, model: str, pages: list[dict], gpu: str, timeout: float):- pages_dir = Path(__file__).resolve().parent.parent / "data" / "pages"+ data_dir = Path(__file__).resolve().parent.parent / "data"multivectors: list[np.ndarray] = []metadata: list[dict] = []for i, page in enumerate(pages, 1):- image_path = pages_dir / f"{page['page_id']}.png"+ image_path = data_dir / page["image_path"]if not image_path.exists():raise FileNotFoundError(f"Missing page image: {image_path}. Run data/render_pages.py.")@@ -66,14 +67,18 @@ def encode_pages(client: SIEClient, model: str, pages: list[dict], gpu: str, tim"page_id": page["page_id"],"client": page["client"],"title": page["title"],- "space": page["space"],- "author": page["author"],- "web_url": page["web_url"],- "image_path": str(image_path.relative_to(image_path.parent.parent.parent)),+ "publisher": page["publisher"],+ "license": page["license"],+ "source_url": page["source_url"],+ "source_pdf": page["source_pdf"],+ "source_pdf_path": page["source_pdf_path"],+ "page_number": page["page_number"],+ "image_path": page["image_path"],"num_tokens": int(mv.shape[0]),})- print(f" [{i}/{len(pages)}] {page['page_id']:10s} {page['client']:10s} {mv.shape} in {elapsed:.1f}s")+ citation = f"{page['source_pdf']} · p.{page['page_number']}"+ print(f" [{i}/{len(pages)}] {page['client']:12s} {citation:44s} {mv.shape} in {elapsed:.1f}s")return multivectors, metadatadiff --git a/examples/vision-doc-rag/python/requirements.txt b/examples/vision-doc-rag/python/requirements.txtindex bd32dcbc7..1ea77ae9d 100644--- a/examples/vision-doc-rag/python/requirements.txt+++ b/examples/vision-doc-rag/python/requirements.txt@@ -1,6 +1,8 @@-sie-sdk==0.1.10+sie-sdk==0.3.4fastapi>=0.115.0uvicorn>=0.30.0numpy>=1.26.0pyyaml>=6.0Pillow>=10.3.0+pdf2image>=1.17.0+PyMuPDF>=1.24.0diff --git a/examples/vision-doc-rag/python/search.py b/examples/vision-doc-rag/python/search.pyindex 52dd2211d..a4d6b3caa 100644--- a/examples/vision-doc-rag/python/search.py+++ b/examples/vision-doc-rag/python/search.py@@ -44,6 +44,15 @@ def load_index():raise FileNotFoundError("data/multivectors.npz missing. Run `python python/ingest.py` first.")npz = np.load(data_dir / "multivectors.npz")metadata = json.loads((data_dir / "metadata.json").read_text())+ required = {"page_id", "client", "source_pdf", "page_number", "image_path", "publisher", "source_url"}+ if metadata:+ missing = required - set(metadata[0])+ if missing:+ raise ValueError(+ "data/metadata.json was generated by an older corpus shape. "+ "Run `python data/fetch_pdfs.py`, `python data/render_pages.py`, "+ "then `python python/ingest.py`."+ )multivectors = {m["page_id"]: npz[m["page_id"]] for m in metadata}return multivectors, metadata@@ -173,7 +182,7 @@ def search(provision_timeout_s=timeout,)timings["docvqa_s"] = round(time.time() - t0, 3)- answer = _docvqa_answer(qa[0].get("entities", []) if qa else [])+ answer = _docvqa_answer(qa["entities"])except Exception as exc:timings["docvqa_error"] = type(exc).__name__@@ -191,7 +200,7 @@ def search(provision_timeout_s=timeout,)timings["ocr_snippet_s"] = round(time.time() - t0, 3)- top["ocr_snippet"] = _ocr_snippet(ocr[0].get("entities", []) if ocr else [])+ top["ocr_snippet"] = _ocr_snippet(ocr["entities"])except Exception as exc:timings["ocr_snippet_error"] = type(exc).__name__@@ -211,11 +220,11 @@ def print_run(out: dict, query: str, client_filter: str | None):rerank = r.get("_rerank_score")rerank_str = f"rerank={rerank:.4f}" if rerank is not None else "rerank=—"print(f"\n {i}. [{r['client']}] {r['title']}")- print(f" {r['page_id']} · {r['space']} · {r['author']}")+ print(f" {r['source_pdf']} · p.{r['page_number']} · {r['publisher']}")print(f" maxsim={r['_maxsim_score']:.3f} {rerank_str}")if r.get("ocr_snippet"):print(f" OCR snippet: {r['ocr_snippet'][:200]}")- print(f" url: {r['web_url']}")+ print(f" url: {r['source_url']}")def main():@@ -227,11 +236,11 @@ def main():api_key = os.environ.get("SIE_API_KEY", config["cluster"]["api_key"])demo = [- ("how do I sign in to the VPN?", "acme-corp"),- ("what is the parental leave policy?", "globex"),- ("audit prep evidence and walkthroughs", "initech"),+ ("Raspberry Pi Pico pinout GP21", "embedded-lab"),+ ("cloud native architecture diagram", "ops-eng"),+ ("solid rocket motor nozzle design figure", "aerospace"),# No tenant filter: shows the query routes across tenants.- ("expense reports and per diem", None),+ ("ATmega16U2 power tree diagram", None),]with SIEClient(cluster_url, api_key=api_key) as client:for query, tenant in demo:diff --git a/examples/vision-doc-rag/python/server.py b/examples/vision-doc-rag/python/server.pyindex d61e59621..990857fac 100644--- a/examples/vision-doc-rag/python/server.py+++ b/examples/vision-doc-rag/python/server.py@@ -81,10 +81,13 @@ def api_search("page_id": r["page_id"],"client": r["client"],"title": r["title"],- "space": r["space"],- "author": r["author"],- "web_url": r["web_url"],- "page_image": f"/pages/{r['page_id']}.png",+ "publisher": r["publisher"],+ "license": r["license"],+ "source_url": r["source_url"],+ "source_pdf": r["source_pdf"],+ "page_number": r["page_number"],+ "citation": f"{r['source_pdf']} · p.{r['page_number']}",+ "page_image": f"/{r['image_path']}","ocr_snippet": r.get("ocr_snippet", ""),"scores": {"maxsim": round(r["_maxsim_score"], 4),diff --git a/examples/vision-doc-rag/static/index.html b/examples/vision-doc-rag/static/index.htmlindex 392c87915..2b3eb7c31 100644--- a/examples/vision-doc-rag/static/index.html+++ b/examples/vision-doc-rag/static/index.html@@ -120,7 +120,7 @@<main><form id="searchForm"><select id="clientSel"><option value="">All clients</option></select>- <input id="q" type="text" placeholder="e.g. how do I sign in to the VPN?" autofocus />+ <input id="q" type="text" placeholder="e.g. Raspberry Pi Pico pinout GP21" autofocus /><button type="submit">Search</button></form><div id="stats" class="stats"></div>@@ -135,6 +135,14 @@const answerEl = document.getElementById("answer");const statsEl = document.getElementById("stats");+ function escapeHtml(value) {+ return String(value ?? "")+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """);+ }+async function loadStats() {const r = await fetch("/api/stats").then(r => r.json());for (const c of r.clients) {@@ -162,7 +170,7 @@answerEl.innerHTML = `<div class="answer-card"><div class="label">Answer (Florence-2-DocVQA)</div>- <div class="text">${res.answer.replace(/</g, "<")}</div>+ <div class="text">${escapeHtml(res.answer)}</div></div>`;}if (!res.results.length) {@@ -173,12 +181,13 @@const rerank = r.scores.rerank == null ? "—" : r.scores.rerank;return `<div class="result">- <a href="${r.page_image}" target="_blank"><img src="${r.page_image}" alt="${r.title}"/></a>+ <a href="${escapeHtml(r.page_image)}" target="_blank"><img src="${escapeHtml(r.page_image)}" alt="${escapeHtml(r.title)}"/></a><div>- <div class="title">${r.title}</div>- <div class="meta"><span class="tag">${r.client}</span> ${r.space} · ${r.author} · ${r.page_id}</div>+ <div class="title">${escapeHtml(r.title)}</div>+ <div class="meta"><span class="tag">${escapeHtml(r.client)}</span> ${escapeHtml(r.citation)} · ${escapeHtml(r.publisher)}</div>+ <div class="meta">${escapeHtml(r.license)} · <a href="${escapeHtml(r.source_url)}" target="_blank" rel="noreferrer">source PDF</a></div><div class="scores">maxsim=${r.scores.maxsim} rerank=${rerank}</div>- ${r.ocr_snippet ? `<div class="snippet">${r.ocr_snippet.replace(/</g, "<")}</div>` : ""}+ ${r.ocr_snippet ? `<div class="snippet">${escapeHtml(r.ocr_snippet)}</div>` : ""}</div></div>`;}).join("");