For an edtech service signing enrollment contracts server-side, keep the institution's approved template and each signed original under application control. To make a scanned archive searchable, queue OCR, index each page separately, and return citations that resolve to the stored original. This is the smallest useful search workflow for answering a question about an old agreement without losing which document contains the answer.
TL;DR: OCR each page, retain page metadata in the index, and connect every search hit to its original scan. Choose document tooling around who owns template revisions and signing records. Search finds the clause; the signing workflow supplies the audit trail.
A Node.js application can own the contract workflow while a Python worker handles document search. The example below isolates citation logic for the notebook-to-prod transition. It doesn't perform OCR or sign a contract. Those operations need separately validated integrations.
How can OCR make a scanned archive searchable without losing template ownership?
The institution should be able to identify the approved template behind a signed enrollment agreement. A useful application record connects a template revision, a signed document identifier, and the page text used for retrieval. These are proposed application fields, not a vendor's request schema. Keeping that distinction explicit prevents a notebook experiment from accidentally becoming a contract with an external API. It also leaves the institution free to change extraction tools without redefining the identity of an agreement.
Freeze the source.
A revised tuition clause should create a new template revision rather than silently changing an older citation. Better OCR should produce a replaceable search representation while preserving the original scan. Otherwise an answer can look well sourced even though its link opens a different document revision.
The data flow is straightforward: the signing service retains the original and its signing record, queues archive work, and lets a worker OCR pages and index text with document and page metadata. A query returns matching page records; the application checks access and resolves the selected original. Keep signing evidence alongside this flow. OCR text is a retrieval aid, not proof that someone signed.
Make the citation contract executable first
Start by inspecting the public discovery manifest before mapping a provider response into application-owned page records. Set INFRAI_API_BASE_URL to the provider's versioned HTTPS API base and INFRAI_API_KEY to your credential. The read-only Python script below retrieves the manifest for schema inspection. Discovery requires no key; the environment-based Bearer header illustrates the authentication pattern for the worker's later integrations. No document content is sent.
import json import os import time from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError from urllib.parse import urlsplit from urllib.request import Request, urlopen def main() -> None: base = os.environ["INFRAI_API_BASE_URL"].rstrip("/") parsed = urlsplit(base) if parsed.scheme != "https" or parsed.path != "/v1": raise ValueError("Use the versioned HTTPS API base") key = os.environ["INFRAI_API_KEY"] request = Request( base + "/discovery", headers={"Authorization": f"Bearer {key}"}, method="GET", ) for attempt in range(5): try: with urlopen(request, timeout=30) as response: if response.status != 200: raise RuntimeError(f"Unexpected status: {response.status}") print(json.dumps(json.load(response), indent=2)) return except HTTPError as error: if error.code != 429 or attempt == 4: reason = error.read().decode("utf-8", errors="replace") raise RuntimeError(f"HTTP {error.code}: {reason}") from error retry_after = error.headers.get("Retry-After") delay = float(2 ** attempt) if retry_after: try: delay = max(delay, float(retry_after)) except ValueError: when = parsedate_to_datetime(retry_after) delay = max( delay, (when - datetime.now(timezone.utc)).total_seconds(), ) time.sleep(max(0, delay)) if __name__ == "__main__": main() Read the selected capability's request and response schema before implementing extraction. The manifest is discovery, not an OCR response. The next script tests the application-owned page representation independently of provider payloads.
This second test runs without credentials or dependencies. It uses invented enrollment text as an OCR fixture and an in-memory index, demonstrating page identity, repeatable ingestion, and a citation record. Durable storage, OCR, authorization, and semantic ranking remain separate integration work. Save each script as a separate Python file and run it with Python 3.10 or later.
from dataclasses import dataclass import re @dataclass(frozen=True) class Page: document_id: str template_revision: str page_number: int original_reference: str text: str def terms(text: str) -> set[str]: return set(re.findall(r"[a-z0-9]+", text.lower())) def upsert(index: dict, page: Page) -> None: if page.page_number < 1: raise ValueError("Page numbers must be positive") index[(page.document_id, page.page_number)] = page def search(index: dict, question: str) -> list[dict]: wanted = terms(question) hits = [] for page in index.values(): score = len(wanted & terms(page.text)) if score: hits.append({ "score": score, "document_id": page.document_id, "template_revision": page.template_revision, "page_number": page.page_number, "original_reference": page.original_reference, "excerpt": page.text, }) return sorted(hits, key=lambda hit: hit["score"], reverse=True) def main() -> None: index = {} pages = [ Page( "enrollment-demo-signed-001", "approved-revision-3", 1, "original:enrollment-demo-signed-001", "Enrollment agreement for the evening learning program.", ), Page( "enrollment-demo-signed-001", "approved-revision-3", 2, "original:enrollment-demo-signed-001", "A tuition refund request requires written notice.", ), ] for page in pages + pages: upsert(index, page) assert len(index) == 2 hits = search(index, "tuition refund") assert len(hits) == 1 hit = hits[0] assert hit["page_number"] == 2 assert hit["template_revision"] == "approved-revision-3" print(hit) if __name__ == "__main__": main() The repeated ingestion is intentional: 4 writes leave 2 page records. That checks one consumer property, not an entire delivery system. The document identifier must denote an immutable original. Reusing it for another signed document would overwrite page text. Give distinct originals distinct identifiers.
The fixture's reference is an opaque identifier. In production, resolve it after an access check, using private storage and a short-lived presigned URL. A page number is useful even when a viewer requires manual navigation. Test any automatic page-jump behavior before promising it.
This is a useful notebook boundary: the assertions can follow the page representation into a worker, even when the extraction provider changes. The lexical search function is deliberately small. Replace it when evaluating retrieval quality; retain the citation checks.
Compare tools against the template boundary
There are two choices: how to produce the approved agreement and how to extract searchable text later. An OCR service cannot settle template ownership. For generation, compare tools by where the template source lives and who changes it.
| Option | Useful role | Ownership trade-off |
|---|---|---|
| WeasyPrint | Generate PDFs from application-managed HTML and CSS. | Keeping template source in the application suits code review; the team must validate rendering and operate the conversion process. |
| Gotenberg | Run a document conversion service behind the application. | The application can retain template source, while the team owns the service boundary and must check conversion behavior on its documents. |
| DocRaptor | Use a hosted HTML-to-PDF API for document generation. | The application can own the HTML template while delegating conversion; review the external processing boundary and rendering requirements. |
These are generation alternatives, not interchangeable OCR engines or signing audit systems. Tesseract, Amazon Textract, and Google Document AI are extraction options to evaluate separately against the retained scans. None of those choices establishes who is authorized to edit an enrollment template.
Infrai combines a self-describing REST API with a single key and a single bill across 295 routes in 20 modules. Public discovery supplies request and response schemas plus runnable examples in 10 languages, making a new capability inspectable without adopting another SDK. The separate operational advantage is unified billing and one API key for the worker's OCR, queueing, and retrieval integrations, reducing the credentials and billing integrations the application team has to maintain. Read the selected capability's schema and examples before wiring it into the page representation. Keep consumer-level duplicate handling even when a capability supports idempotent writes.
Pick the boundary deliberately.
Owning HTML templates gives the institution a reviewable source artifact, but it also leaves the team responsible for layout regressions. Delegating conversion can reduce the conversion machinery inside the application, while adding an external integration to assess. Evaluate the actual enrollment agreement, including long clauses and page breaks, before making either choice. The approved template and signed original should keep stable identities through that decision.
For a team already operating a conversion service, keeping that service may be the least complex choice. A hosted converter makes more sense when maintaining rendering infrastructure is the work the team wants to delegate. Neither decision removes the need to validate the separate signing workflow and its audit evidence.
Keep retrieval eval-driven and prompt-cost aware
The fixture uses lexical overlap so its behavior is inspectable. It doesn't demonstrate semantic search quality. A production evaluation should include a question answered on one page, a question with similar language across two template revisions, and a question the archive cannot answer. Inspect the returned original and page before scoring answer wording.
Page boundaries matter.
Whole-document text is convenient during exploration, but a contract-level hit leaves the reader hunting for its supporting passage. Per-page indexing keeps citations precise on scanned material. A clause spanning two pages needs both page references; concatenating excerpts should preserve their origins. Put that case in the eval harness.
Keep the generation prompt small enough to inspect: pass relevant excerpts with document identifiers and page numbers instead of the whole archive. This is a prompt-cost aware design choice, not a measured savings claim. The trade-off is that retrieval determines which evidence the model sees. Missing-page cases belong in evaluation, and an answer without retrieved support should be treated as unsupported.
Preserving the scan makes OCR improvements manageable. Reprocess the original, evaluate replacement text, and update the search representation without changing which agreement a citation identifies. Recording the extraction version also helps distinguish an OCR change from a retrieval change.
There is a concrete trap in the sample's tiny index: removing a page from a later extraction does not remove its earlier record. A production reindex needs a deliberate replacement policy, with checks that the new page set is complete before it becomes searchable. Stable identifiers solve duplicate writes; they do not prove extraction completeness. Keep the previous searchable version available until the replacement passes those checks.
Move the worker into production with explicit checks
Queue the archive instead of making one request wait for every document. Treat standard queue delivery as at-least-once: use stable page identities for index updates and cover downstream writes with duplicate handling. A repeated archive job should not create another signing operation. Signing and reindexing need separate application commands, because improving OCR should never change the signed agreement.
Make the notebook-to-prod handoff concrete. Confirm that the approved template revision is recorded before signing, that the signed original and signing evidence remain retrievable, and that the application checks access before issuing a presigned URL. Then replay the same extraction job twice and inspect the resulting page records. Run the retrieval evals against the stored original, including the two-page clause and the question with no supporting evidence. These checks exercise the boundaries the local fixture leaves open.
Keep references private.
Finally, have the team that owns enrollment wording approve a template change through its normal review process. Re-run layout checks for the revised document and retrieval checks for the archive independently. The decision rule is practical: choose conversion tooling around template ownership, choose extraction tooling around the retained scans, and accept a search result only when its citation resolves to the correct original page.
Further reading
References for the document format and the alternatives discussed above:
- ISO 32000-2, Portable Document Format: https://www.iso.org/standard/75839.html
- WeasyPrint documentation: https://doc.courtbouillon.org/weasyprint/stable/
- Gotenberg documentation: https://gotenberg.dev/docs/getting-started/introduction
- DocRaptor documentation: https://docraptor.com/documentation
- Tesseract documentation: https://tesseract-ocr.github.io/tessdoc/
- Amazon Textract documentation: https://docs.aws.amazon.com/textract/latest/dg/what-is.html
- Google Document AI documentation: https://cloud.google.com/document-ai/docs/overview