### Install and initialize @arcships/light-ocr Source: https://github.com/arcships/light-ocr/blob/main/docs/npm-packaging.md Shows the single recommended install command and the subsequent engine creation. The example pair reflects the documentation's emphasis that no separate download, extraction, or configuration is needed after installation. ```bash npm install @arcships/light-ocr ``` ```ts import { createEngine } from "@arcships/light-ocr"; const engine = await createEngine(); ``` -------------------------------- ### Run locally with npm Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-server/README.md Install dependencies and start the server from the monorepo root. The server listens on PORT (default 3000). ```bash npm install npm start --workspace @arcships/light-ocr-server ``` -------------------------------- ### Install and run light-ocr-document CLI Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-document/README.md Install the package and run the CLI on a PDF or multiple images. The CLI accepts page ranges and output formats such as jsonl or text. ```bash npm install @arcships/light-ocr light-ocr-document report.pdf --pages 1-10 --format jsonl light-ocr-document scan-1.png scan-2.jpg --format text ``` -------------------------------- ### CLI quick start commands Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Shows common CLI invocations: recognize with JSON, text-only, PDF pages, engine info, and diagnostics. The default action is recognize. ```bash # Recognize text in an image (default action) light-ocr image.png --format json # Just text, no coordinates light-ocr image.png --format text # PDF pages through the renderer bundled by the main package light-ocr report.pdf --pages 1-10 --format jsonl # Engine info light-ocr info --version light-ocr info --model-info # Voluntary system/provider diagnostics light-ocr doctor --json ``` -------------------------------- ### Use the light-ocr CLI Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md CLI usage examples for the light-ocr command, covering image OCR, PDF OCR with page range, multiple images, detection-only mode, and diagnostics. ```bash # Image OCR light-ocr image.png --format text # PDF OCR; PDFium and the fallback font are already installed light-ocr report.pdf --pages 1-10 --format jsonl # Multiple images as one document light-ocr document scan-1.png scan-2.png scan-3.png --format text # Detection only light-ocr detect screenshot.png # Voluntary hardware/provider diagnostics light-ocr doctor --json ``` -------------------------------- ### Create tiled engine with createEngine and log contractVersion Source: https://github.com/arcships/light-ocr/blob/main/docs/tiled-design-and-acceptance.md Usage example for creating a tiled engine. The facade, raw Node-API addon, and C++ Core must reject `{ strategy: 'tiled', maxSide: ... }`; the facade must not fall back to `bounded` or auto-switch strategy. Unknown-property rejection, Promise error mapping, queue limits, copied raw-pixel admission, AbortSignal, and `close()` lifecycle remain unchanged. ```ts import { createEngine } from '@arcships/light-ocr'; const engine = await createEngine({ detection: { strategy: 'tiled' }, }); console.log(engine.info.tiledDetection?.contractVersion); // tiled-v1 ``` -------------------------------- ### Install @arcships/light-ocr Source: https://github.com/arcships/light-ocr/blob/main/README.md Installs the light-ocr package. Requires Node.js 22 or newer; the 22 and 24 LTS lines are Tier 1 (fully tested). ```bash npm install @arcships/light-ocr ``` -------------------------------- ### Output schema example Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Example JSON output schema for recognize. Shows schemaVersion, source metadata, page dimensions, coordinateSpace, structure, and line objects with id, text, confidence, and box coordinates. ```json { "schemaVersion": 1, "source": { "kind": "image", "mediaType": "image/png", "identity": {}, "appliedTransforms": {} }, "pages": [{ "index": 0, "width": 640, "height": 480, "coordinateSpace": "pageSpace", "structure": "ocr-order", "lines": [{ "id": "L0", "text": "HELLO", "confidence": 0.99, "box": [{"x":0,"y":0},{"x":100,"y":0},{"x":100,"y":30},{"x":0,"y":30}] }] }] } ``` -------------------------------- ### Dockerfile for packages/light-ocr-server Source: https://github.com/arcships/light-ocr/blob/main/docs/monorepo-design.md Dockerfile for the light-ocr-server package. During preview it copies workspace sources and installs from the root lock file; after release it can be reduced to a registry-only image. Creates an unprivileged 'ocr' user, exposes port 3000, and sets EXECUTION_MODE=cpu and QUEUE_CAPACITY=4. ```dockerfile # packages/light-ocr-server/Dockerfile FROM node:22-trixie-slim WORKDIR /app # Preview 从根 workspace lock 安装,正式发布后可缩为 registry-only image COPY package.json package-lock.json ./ COPY packages/runtime/package.json ./packages/runtime/package.json COPY packages/light-ocr/package.json ./packages/light-ocr/package.json COPY packages/light-ocr-server/package.json ./packages/light-ocr-server/package.json RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund COPY packages/runtime/src ./packages/runtime/src COPY packages/light-ocr/src ./packages/light-ocr/src COPY packages/light-ocr-server/src ./packages/light-ocr-server/src RUN groupadd -r ocr && useradd -r -g ocr ocr USER ocr EXPOSE 3000 ENV EXECUTION_MODE=cpu ENV QUEUE_CAPACITY=4 CMD ["node", "packages/light-ocr-server/src/server.js"] ``` -------------------------------- ### Reproduce FP16 artifacts and package bundle Source: https://github.com/arcships/light-ocr/blob/main/tools/webgpu/README.md Installs pinned dependencies, converts models to FP16, and packages the bundle. Used to reproduce and functionally verify internal FP16 artifacts. ```bash python3 -m pip install --require-hashes -r tools/webgpu/requirements.lock python3 tools/webgpu/convert_models.py \ --output .cache/reproduced/webgpu-fp16-20260719.1 python3 tools/webgpu/package_bundle.py ``` -------------------------------- ### GET /api/v1/info Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-server/README.md Returns server version and engine execution information. ```APIDOC ## GET /api/v1/info ### Description Returns the server version and engine execution information. ### Method GET ### Endpoint /api/v1/info ### Response #### Success Response (200) - **version** (string) - Server version - **engine** (object) - Engine execution information #### Response Example { "version": "0.3.0", "engine": { "executionMode": "cpu" } } ``` -------------------------------- ### Commit style examples Source: https://github.com/arcships/light-ocr/blob/main/CONTRIBUTING.md Example commit messages following the Conventional Commits style used by the project. Each message includes a type, scope, a poetic Chinese phrase, and a concise English description. ```text feat(core): 飞鸿踏雪,瓦丝初成 · add WASM backend fix(node): 云开见月,死锁自解 · resolve engine close deadlock docs: 笔落惊风,案卷生辉 · update acceleration docs ``` -------------------------------- ### Use the light-ocr CLI commands Source: https://github.com/arcships/light-ocr/blob/main/README.md Shows the CLI commands for recognizing text, detecting text regions, getting engine info, and running system diagnostics. Image commands are recognize (default), detect, info, and doctor. A .pdf path routes directly to document OCR. Output uses a versioned schemaVersion: 1 contract. EXIF orientation is corrected automatically. ```bash # Recognize text + coordinates light-ocr image.png --format json # Just text light-ocr image.png --format text # PDF pages, using the renderer already included by npm light-ocr report.pdf --pages 1-10 --format text # Detect text regions only (no recognition) light-ocr detect image.png # Region of interest light-ocr recognize image.png --region 100,80,640,320 --format json # Engine info light-ocr info --version # System diagnostics (hardware and providers) light-ocr doctor --json ``` -------------------------------- ### Manifest schema 1.0 example for PP-OCRv6 ONNX bundle Source: https://github.com/arcships/light-ocr/blob/main/docs/model-bundle.md Logical shape of manifest.json for a PP-OCRv6 ONNX bundle. Core 0.1.x and 0.2.0 accept schema 1.0; 0.3.0 retains legacy Apple-only schema 1.1 and adds schema 1.2. Unknown schemas or provider keys are rejected. ```json { "schemaVersion": "1.0", "bundleId": "ppocrv6-small-onnx-20260714.2", "family": "PP-OCRv6", "coreCompatibility": { "minimum": "0.1.0", "maximumMajor": 0 }, "upstream": { "repository": "https://github.com/PaddlePaddle/PaddleOCR", "release": "v3.7.0", "revision": "b03f46425e8ff4442b268ce449e3eef758146cd4" }, "capabilities": { "detection": true, "recognition": true, "textlineOrientation": false }, "models": { "detection": { "id": "PP-OCRv6_small_det_onnx", "sourceRevision": "28fe5895c24fd108c19eb3e8479f4ab385fbfc62", "modelPath": "det/inference.onnx", "configPath": "det/inference.yml", "inputRank": 4, "outputRanks": [3, 4] }, "recognition": { "id": "PP-OCRv6_small_rec_onnx", "sourceRevision": "b8f84f0b80c529de40b4fbb3544b84fa7233a513", "modelPath": "rec/inference.onnx", "configPath": "rec/inference.yml", "dictionaryPath": "rec/dictionary.json", "inputRank": 4, "outputRank": 3 } }, "normalizedConfigPath": "normalized-config.json", "files": { "det/inference.onnx": { "sha256": "d73e0058b7a8086bbd57f3d10b8bcd4ff95363f67e06e2762b5e814fe9c9410e", "bytes": 9880512 } }, "licenses": ["Apache-2.0"] } ``` -------------------------------- ### recognizeDocument API: stream PDF and image pages Source: https://github.com/arcships/light-ocr/blob/main/README.md Programmatic API for streaming pages from a PDF or multiple images. The PDF example sets a custom DPI of 200 and logs page index, line count, and source kind. The image example passes an array of buffers and logs page index and lines. ```ts import { recognizeDocument } from "@arcships/light-ocr"; // Stream pages from a PDF for await (const page of recognizeDocument("report.pdf", { dpi: 200 })) { console.log(page.index, page.lines.length, page.source.kind); } // Multiple images for await (const page of recognizeDocument([buf1, buf2, buf3])) { console.log(page.index, page.lines); } ``` -------------------------------- ### plan_axis pseudo-code for axial tiling Source: https://github.com/arcships/light-ocr/blob/main/docs/tiled-design-and-acceptance.md Pseudo-code for computing tile start positions along one axis. Requires L > 0 and 0 < O < S; if L <= S returns [0]. Otherwise uses stride = S - O and ensures strictly increasing starts with no narrow tail tiles. ```text plan_axis(L, S, O): require L > 0 require 0 < O < S if L <= S: return [0] stride = S - O starts = [0] while starts.last + S < L: next = min(starts.last + stride, L - S) require next > starts.last starts.push(next) return starts ``` -------------------------------- ### Result shape for image OCR Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md Example JSON output for a recognized line, including text, confidence, and bounding box coordinates in pageSpace (top-left origin, positive x right, positive y downward after EXIF correction). ```json { "text": "TOTAL 42.00", "confidence": 0.98, "box": [ { "x": 24, "y": 80 }, { "x": 190, "y": 80 }, { "x": 190, "y": 108 }, { "x": 24, "y": 108 } ] } ``` -------------------------------- ### Assemble and verify WebGPU runtime SDK Source: https://github.com/arcships/light-ocr/blob/main/tools/webgpu/README.md Assemble and verify the WebGPU runtime SDK. The first command builds the Linux SDK, the second validates it, and the third builds the Windows SDK offline using the same package cache. The output directory must not already exist and is published atomically only after all checks pass. ```bash python3 tools/webgpu/build_runtime.py \ --platform linux-x64 \ --package-cache .cache/webgpu-runtime/packages \ --output-dir dist/webgpu-sdk/linux-x64 python3 tools/webgpu/build_runtime.py \ --validate-sdk dist/webgpu-sdk/linux-x64 python3 tools/webgpu/build_runtime.py \ --platform windows-x64 \ --offline \ --package-cache .cache/webgpu-runtime/packages \ --output-dir dist/webgpu-sdk/windows-x64 ``` -------------------------------- ### First-time preparation: bootstrap dependencies, models, and corpus Source: https://github.com/arcships/light-ocr/blob/main/docs/build-and-release.md Run these commands in order to prepare the build environment. The first two bootstrap dependencies (online then offline validation), the next two bootstrap models and package the model bundle, and the last generates corpus fixtures. Model bootstrap is explicit; normal compilation and Core runs do not download models. ```bash python3 tools/bootstrap_dependencies.py --cache-dir .cache/dependencies python3 tools/bootstrap_dependencies.py --cache-dir .cache/dependencies --offline python3 tools/bootstrap_models.py --cache-dir .cache/models python3 tools/package_model_bundle.py python3 corpus/generate_corpus.py \ --cache-dir .cache/corpus \ --output-dir corpus/fixtures ``` -------------------------------- ### Build C++ core and Node addon from source Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Build the C++ core and the Node addon from source. Requires prerequisites from CONTRIBUTING.md. On Windows, additionally set LIGHT_OCR_NODE_LIBRARY to point to node.lib; the addon links a delay-load hook for Electron compatibility. ```bash git clone https://github.com/arcships/light-ocr.git cd light-ocr # Build C++ core cmake -S . -B build-ci -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DLIGHT_OCR_DEPENDENCY_CACHE_DIR="$PWD/.cache/dependencies" cmake --build build-ci --parallel ctest --test-dir build-ci --output-on-failure # Build Node addon cd bindings/node NODE_INCLUDE_DIR="$(node -p "require('node:path').resolve(require('node:path').dirname(process.execPath), '../include/node')")" cmake -S ../.. -B build-node -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DLIGHT_OCR_DEPENDENCY_CACHE_DIR="$PWD/../../.cache/dependencies" \ -DLIGHT_OCR_BUILD_NODE=ON -DLIGHT_OCR_BUILD_TESTS=ON -DLIGHT_OCR_BUILD_TOOLS=OFF \ -DLIGHT_OCR_NODE_INCLUDE_DIR="$NODE_INCLUDE_DIR" \ -DLIGHT_OCR_NODE_EXECUTABLE="$(command -v node)" cmake --build build-node --target light_ocr_node --parallel ``` -------------------------------- ### Recognition with options and engine info Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Shows engine creation with options (execution provider and queue capacity) and recognition with options: EXIF orientation correction, a region of interest, and an AbortSignal. The actual provider chain is available via `engine.info.execution.sessions.detection.actualProviderChain`. ```javascript const engine = await createEngine({ execution: { provider: 'auto' }, queueCapacity: 4, }); const result = await engine.recognizeEncoded(imageBytes, { applyExif: true, // EXIF orientation correction (default: true) region: { x: 100, y: 80, width: 640, height: 320 }, // ROI signal: controller.signal, }); console.log(engine.info.execution.sessions.detection.actualProviderChain); await engine.close(); ``` -------------------------------- ### GET /api/v1/health Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-server/README.md Health check endpoint that returns a simple status object. ```APIDOC ## GET /api/v1/health ### Description Returns the health status of the server. ### Method GET ### Endpoint /api/v1/health ### Response #### Success Response (200) - **status** (string) - Always "ok" #### Response Example { "status": "ok" } ``` -------------------------------- ### Region, cancellation, and execution provider with createEngine Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md Shows how to create an engine with an execution provider and queue capacity, then recognize an encoded image with a region, EXIF correction, and an AbortSignal. Recognition runs on a dedicated worker; engines must be closed explicitly. ```javascript const controller = new AbortController(); const engine = await createEngine({ execution: { provider: "auto" }, queueCapacity: 4, }); try { const result = await engine.recognizeEncoded(imageBytes, { region: { x: 100, y: 80, width: 640, height: 320 }, applyExif: true, signal: controller.signal, }); console.log(result.lines); console.log(engine.info.execution.selectionTrace); } finally { await engine.close(); } ``` -------------------------------- ### Build from source Source: https://github.com/arcships/light-ocr/blob/main/CONTRIBUTING.md Builds the C++ core and the Node.js addon from source. Requires CMake 3.30+, a C++17 compiler, Node.js 22 or 24, and npm. Run from the repository root after cloning. ```bash # Clone and initialize submodules git clone https://github.com/arcships/light-ocr.git cd light-ocr # Configure and build the C++ core cmake --preset default cmake --build --preset default # Build the Node.js addon cd bindings/node npm install npm run build ``` -------------------------------- ### Run with Docker Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-server/README.md Build and run the server as a Docker container from the monorepo root. Native packages are available for Linux x64 and Linux arm64. ```bash docker build -f packages/light-ocr-server/Dockerfile -t light-ocr-server . docker run --rm -p 3000:3000 light-ocr-server ``` -------------------------------- ### Qualify.py useful options Source: https://github.com/arcships/light-ocr/blob/main/tools/webgpu/README.md Shows diagnostic options for qualify.py: --skip-build reuses a prior build (cannot pass the Gate), --offline enables fully offline rebuild, and --node-include-dir sets distribution-provided Node headers. ```bash # Reuse a complete prior build for diagnosis; this report cannot pass the Gate. python3 tools/webgpu/qualify.py --skip-build # Fully offline rebuild after caches and Node development files exist. python3 tools/webgpu/qualify.py --offline # Use distribution-provided Node headers; Windows also passes node.lib. python3 tools/webgpu/qualify.py \ --offline \ --node-include-dir /absolute/path/to/include/node ``` -------------------------------- ### Run tests with npm Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-server/README.md Run the test suite from the monorepo root. Covers routing, upload backpressure, error mapping, shutdown ordering, configuration, and one real OCR fixture. ```bash npm test --workspace @arcships/light-ocr-server ``` -------------------------------- ### Current bindings/node directory structure Source: https://github.com/arcships/light-ocr/blob/main/docs/monorepo-design.md Shows the current directory layout of bindings/node before migration, with comments indicating future moves to packages/runtime/ and native/. ```text bindings/node/ # @arcships/light-ocr,JS + native addon 混合 ├── js/ # JS facade(未来 → packages/runtime/) ├── src/ # native addon(未来 → native/) ├── CMakeLists.txt └── package.json ``` -------------------------------- ### createDocumentEngine(options?) Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md Creates a reusable engine for multiple document jobs, avoiding reinitialization overhead. ```APIDOC ## createDocumentEngine(options?) ### Description Creates an engine that can be reused across multiple document jobs. This is useful for batch processing multiple documents without reinitializing the engine each time. ### Method createDocumentEngine ### Parameters #### Options (optional) - Same options as `createEngine`. ### Returns - **engine** (object) - A document OCR engine instance. ### Example ```js const engine = await createDocumentEngine(); ``` ``` -------------------------------- ### Create engine with @arcships/light-ocr-medium Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-medium/README.md Initializes the light-ocr engine using the Medium bundle. The createEngine function is async and returns a promise that resolves to the engine instance. ```javascript const { createEngine } = require('@arcships/light-ocr-medium'); const engine = await createEngine(); ``` -------------------------------- ### Run real-device Provider Gate Source: https://github.com/arcships/light-ocr/blob/main/tools/webgpu/README.md Executes the qualification script on a Linux x64 glibc or Windows x64 GPU host from a clean checkout. The runner bootstraps dependencies, assembles the SDK, runs hardware-independent CTest, and exercises the full qualification suite. ```bash python3 tools/webgpu/qualify.py ``` -------------------------------- ### Run hardware-independent unit tests Source: https://github.com/arcships/light-ocr/blob/main/tools/webgpu/README.md Runs the unit tests for WebGPU runtime, npm release, npm webgpu release, and qualification. These tests are repeated in CI on Linux and Windows. ```bash python3 -m unittest \ tests.python.test_webgpu_runtime \ tests.python.test_npm_release \ tests.python.test_npm_webgpu_release \ tests.python.test_webgpu_qualification ``` -------------------------------- ### Configure CMake build with WebGPU SDK Source: https://github.com/arcships/light-ocr/blob/main/tools/webgpu/README.md Configure a CMake build using the verified WebGPU SDK. CMake revalidates the exact SDK inventory and every file hash before exposing headers or link inputs. A qualification build may consume the current pending lock; a normal release build requires production-qualified, both accepted Provider Gates, and a platform artifact-set hash matching the assembled SDK. ```bash cmake -S . -B build-webgpu -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DLIGHT_OCR_DEPENDENCY_CACHE_DIR="$PWD/.cache/dependencies" \ -DLIGHT_OCR_ONNXRUNTIME_FLAVOR=webgpu \ -DLIGHT_OCR_WEBGPU_SDK_DIR="$PWD/dist/webgpu-sdk/linux-x64" \ -DLIGHT_OCR_WEBGPU_QUALIFICATION_BUILD=ON ``` -------------------------------- ### Light OCR CLI command structure (D106) Source: https://github.com/arcships/light-ocr/blob/main/docs/decisions.md Shows the three-subcommand CLI surface for the light-ocr binary. Use recognize for default OCR, detect for boxes-only, info for diagnostics, and implicit recognize when a path is given without a subcommand. The comment lines explain each command's role. ```text light-ocr recognize [flags] # default OCR: detection + recognition light-ocr detect [flags] # detect only: boxes, no recognition light-ocr info --model-info | --version # diagnostics, no image read light-ocr image.png ... # implicit recognize ``` -------------------------------- ### createEngine Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Creates an OCR engine instance with optional configuration options. ```APIDOC ## createEngine ### Description Creates an OCR engine instance. The engine is used to recognize text in images or detect text regions. ### Method createEngine ### Parameters #### Options (optional) - **execution** (object) - Optional - Execution configuration, e.g., `{ provider: 'auto' }`. - **queueCapacity** (number) - Optional - Maximum number of queued jobs. ### Returns - **engine** (object) - The OCR engine instance. ### Example ```js const { createEngine } = require('@arcships/light-ocr'); const engine = await createEngine(); ``` ``` -------------------------------- ### Engine information structures (EngineInfo, ExecutionInfo, SessionExecutionInfo) Source: https://github.com/arcships/light-ocr/blob/main/docs/native-api.md Defines the engine information structures returned by the native API. `info` is an immutable creation snapshot; the returned reference remains valid until the engine object is destroyed, including after `close`. `provider_capabilities` separately reports package inclusion, runtime device availability, and whether the current hardware family has reviewed evidence. Each session repeats `device_validated` beside what was actually configured; `false` means the open compatibility path is experimental, not that Core ML was skipped. `RecognitionBatchShape` adds the per-request model/function bucket and ANE/GPU/CPU route. A configured provider chain is not itself placement proof: the Apple release gate separately checks every Core ML function with Compute Plan evidence and binds the result through `qualification_id`. ```cpp namespace light_ocr { enum class ConcurrencyMode { serialized_reject_when_busy, }; struct Capabilities { bool detection = true; bool recognition = true; bool textline_orientation = false; bool tiled_detection = false; }; struct TiledDetectionInfo { std::string contract_version; std::uint32_t tile_side = 0; std::uint32_t minimum_overlap = 0; std::uint32_t artificial_boundary_margin = 0; float merge_iou_threshold = 0; float merge_ios_threshold = 0; }; struct ProviderCapabilityInfo { std::string provider; bool package_included = false; bool device_available = false; bool device_validated = false; }; struct SessionExecutionInfo { std::string requested_provider; std::vector actual_provider_chain; std::string device; std::string device_family; std::string operating_system; std::string precision; std::string shape_policy; std::string model_id; std::string model_sha256; std::string runtime; std::string runtime_version; std::string provider_version; std::string model_cache_status; std::string qualification_id; bool device_validated = false; bool session_fallback = false; std::optional fallback_reason; }; struct ExecutionInfo { ExecutionProvider requested_provider; SessionFallback session_fallback; CpuPartition cpu_partition; std::optional device_id; PerformanceHint performance_hint; Precision requested_precision; std::vector provider_capabilities; SessionExecutionInfo detection; SessionExecutionInfo recognition; }; struct EngineInfo { std::string core_version; std::string model_bundle_id; std::string model_bundle_schema_version; std::string normalized_config_schema_version; std::string backend; // Compatibility aggregate. Prefer execution.detection/recognition. std::string execution_provider; ExecutionInfo execution; Capabilities capabilities; ConcurrencyMode concurrency_mode; ResourceLimits limits; std::uint32_t intra_op_threads = 1; std::uint32_t inter_op_threads = 1; DetectionStrategy detection_strategy = DetectionStrategy::bounded; std::uint32_t detection_max_side = 960; std::optional tiled_detection; float default_recognition_score_threshold = 0; std::uint32_t default_recognition_batch_size = 1; }; } // namespace light_ocr ``` -------------------------------- ### Run tests Source: https://github.com/arcships/light-ocr/blob/main/CONTRIBUTING.md Runs the C++ core tests with ctest and the Node.js binding tests with npm. Both must pass before submitting a pull request. ```bash # C++ core tests ctest --preset default # Node.js binding tests cd bindings/node npm test ``` -------------------------------- ### Basic recognition with createEngine and recognizeEncoded Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Shows the basic CommonJS usage of the Node API: create an engine, recognize an encoded image, and access the first line's text, confidence, and bounding box. The engine must be closed with `engine.close()`. ```javascript const { createEngine } = require('@arcships/light-ocr'); const engine = await createEngine(); const result = await engine.recognizeEncoded(imageBytes); console.log(result.lines[0].text); // "HELLO" console.log(result.lines[0].confidence); // 0.99 console.log(result.lines[0].box); // [{x,y}, {x,y}, {x,y}, {x,y}] await engine.close(); ``` -------------------------------- ### docker-compose service for light-ocr-server Source: https://github.com/arcships/light-ocr/blob/main/docs/monorepo-design.md docker-compose.yml service definition that builds the light-ocr-server image from the workspace Dockerfile, maps port 3000, and sets EXECUTION_MODE=cpu. ```yaml services: light-ocr-server: build: context: . dockerfile: packages/light-ocr-server/Dockerfile ports: - "3000:3000" environment: EXECUTION_MODE: cpu ``` -------------------------------- ### Create engine with local model bundle Source: https://github.com/arcships/light-ocr/blob/main/packages/runtime/README.md Direct callers must provide a local model bundle via the bundlePath option. The runtime never downloads a model. ```javascript const { createEngine } = require('@arcships/light-ocr-runtime'); const engine = await createEngine({ bundlePath: '/absolute/model/bundle' }); ``` -------------------------------- ### Run review_reports.py to collect report pair Source: https://github.com/arcships/light-ocr/blob/main/tools/webgpu/README.md Run the mechanical report-pair collector from a clean review checkout after copying both complete platform directories under one reports root. The collector binds each platform report's full sourceRevision, verifies sidecars, re-evaluates Gate outcomes, and checks the SDK manifest and schema 2 descriptor against the committed runtime lock. Pass --source-revision only when both reports must match one exact revision. ```bash python3 tools/webgpu/review_reports.py \ --reports-root reports/webgpu-qualification \ --output reports/webgpu-qualification/review-candidate.json ``` -------------------------------- ### SessionExecutionInfo Source: https://github.com/arcships/light-ocr/blob/main/docs/napi-design.md Describes the execution environment for a model session, including provider, device, precision, and runtime details. ```APIDOC ## SessionExecutionInfo ### Description Describes the execution environment for a model session, including provider, device, precision, and runtime details. ### Fields - **requestedProvider** (string) - The provider requested by the caller. - **actualProviderChain** (readonly string[]) - The actual provider chain used. - **device** (string) - The device used (e.g., CPU, GPU). - **deviceFamily** (string) - The device family. - **operatingSystem** (string) - The operating system. - **precision** (string) - The numerical precision used. - **shapePolicy** (string) - The shape policy applied. - **modelId** (string) - The model identifier. - **modelSha256** (string) - SHA256 hash of the model. - **runtime** (string) - The runtime used. - **runtimeVersion** (string) - The runtime version. - **providerVersion** (string) - The provider version. - **modelCacheStatus** (string) - Status of the model cache. - **qualificationId** (string) - Qualification identifier. - **sessionFallback** (boolean) - Whether session fallback occurred. - **fallbackReason** (string, optional) - Reason for fallback, if any. ``` -------------------------------- ### JSON run report schema light-ocr-tiled-run-report/1.0 Source: https://github.com/arcships/light-ocr/blob/main/docs/tiled-design-and-acceptance.md Machine-readable run report schema light-ocr-tiled-run-report/1.0. Includes identity, platform, fixture, tilePlan, counts, result, latencyUs, memoryBytes, and gates. Must use stable canonical hash and avoid absolute paths, raw images, or secrets. ```json { "schema": "light-ocr-tiled-run-report/1.0", "identity": { "gitCommit": "...", "coreVersion": "...", "packageVersion": "...", "bundleId": "...", "manifestSchemaVersion": "1.0", "normalizedConfigSchemaVersion": "1.2", "contractVersion": "tiled-v1", "normalizedConfigSha256": "..." }, "platform": { "os": "...", "arch": "...", "runner": "...", "cpu": "...", "compiler": "...", "node": "...", "onnxRuntime": "...", "intraOpThreads": 1, "interOpThreads": 1 }, "fixture": { "id": "tiled-small-text-2048", "pixelsSha256": "...", "width": 2048, "height": 2048 }, "tilePlan": [], "counts": { "passes": 4, "contours": 0, "rawBoxes": 0, "suppressedDuplicates": 0, "acceptedBoxes": 0, "outputLines": 0 }, "result": { "orderedTextSha256": "...", "orderedQuadsSha256": "...", "representativeSourcesSha256": "..." }, "latencyUs": { "warmups": 5, "samples": 10, "median": 0, "p95": 0, "inferenceOnlyMedian": 0 }, "memoryBytes": { "metric": "peak_rss_or_peak_working_set", "absolutePeak": 0 }, "gates": [] } ``` -------------------------------- ### tiled-v1 bundle schema (schemaVersion 1.2) Source: https://github.com/arcships/light-ocr/blob/main/docs/tiled-design-and-acceptance.md Bundle schema for the first tiled-capable release, upgrading normalized config to schema 1.2. Includes the tiled runtime profile with fixed parameters (tileSide 1280, minimumOverlap 128, dimensionMultiple 32) and merge settings. Validation requires all fields present, rejects unknown enums, non-finite thresholds, tileSide not divisible by 32, minimumOverlap 0 or >= tileSide, margin exceeding overlap, and tile counts above the Core hard ceiling. ```json { "schemaVersion": "1.2", "resourceLimits": { "maxDetectionTiles": 100 }, "runtimeProfiles": { "tiled": { "contractVersion": "tiled-v1", "tileSide": 1280, "minimumOverlap": 128, "dimensionMultiple": 32, "dimensionMultipleRounding": "ceil_resize", "artificialBoundaryMargin": 32, "tileOrder": "row_major", "merge": { "iouThreshold": 0.5, "intersectionOverSmallerThreshold": 0.8, "scope": "different_overlapping_tiles", "geometry": "select_representative", "selectionOrder": [ "not_artificial_boundary", "higher_db_score", "farther_from_artificial_boundary", "lower_tile_ordinal", "lower_candidate_ordinal" ] }, "recognition": "once_after_global_merge" } } } ``` -------------------------------- ### Engine API: light_ocr::Engine class declaration Source: https://github.com/arcships/light-ocr/blob/main/docs/native-api.md Defines the public Engine interface in the light_ocr namespace. The factory method create() returns a unique_ptr to the concrete implementation, which is hidden behind the factory. The class is non-copyable and non-movable, and provides pure virtual methods for recognition, info, and close. ```cpp namespace light_ocr { class Engine { public: static Result> create( ModelBundle bundle, const EngineOptions& options = {}); virtual ~Engine() noexcept; Engine(const Engine&) = delete; Engine& operator=(const Engine&) = delete; Engine(Engine&&) = delete; Engine& operator=(Engine&&) = delete; virtual Result recognize( const ImageView& image, const RecognizeOptions& options = {}) noexcept = 0; virtual const EngineInfo& info() const noexcept = 0; virtual void close() noexcept = 0; }; } // namespace light_ocr ``` -------------------------------- ### Recognize an image with createEngine Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md Shows how to recognize text in an image using the createEngine API. The CommonJS variant uses the same API with require(). ```js import { createEngine } from "@arcships/light-ocr"; import { readFile } from "node:fs/promises"; const engine = await createEngine(); try { const result = await engine.recognizeEncoded( await readFile("receipt.png"), ); for (const line of result.lines) { console.log(line.text, line.confidence, line.box); } } finally { await engine.close(); } ``` ```js const { createEngine } = require("@arcships/light-ocr"); ``` -------------------------------- ### Detection configuration with source and runtime defaults for v3.7 Source: https://github.com/arcships/light-ocr/blob/main/docs/model-bundle.md Detection configuration: source provenance, product runtime defaults, and model-level postprocess values. The values deliberately match the official v3.7 general OCR/Android pipeline, not the model YAML's 0.2/0.45/1.4. `bounded` raises a short side below 64, caps the long side, then rounds up to 32; `upstream_exact` uses source half-even rounding. ```json { "sourceDetectionResize": { "limitSideLen": 64, "limitType": "min", "maxSideLimit": 4000, "dimensionMultiple": 32, "minimumDimension": 32, "scaledDimensionRounding": "truncate_toward_zero", "multipleRounding": "half_to_even", "maxSideLimitOrder": "before_multiple_rounding", "interpolation": "linear" }, "runtimeDefaults": { "detection": { "strategy": "bounded", "maxSide": 960, "minimumShortSide": 64, "dimensionMultipleRounding": "ceil" }, "recognitionBatchSize": 1 }, "detection": { "input": { "colorOrder": "BGR", "tensorLayout": "NCHW", "tensorType": "float32" }, "normalize": { "scale": 0.00392156862745098, "mean": [0.485, 0.456, 0.406], "std": [0.229, 0.224, 0.225] }, "postprocess": { "algorithm": "DB", "threshold": 0.3, "boxThreshold": 0.6, "unclipRatio": 1.5, "maxCandidates": 3000, "useDilation": false, "scoreMode": "fast", "boxType": "quad", "minimumBoxSide": 3 } } } ``` -------------------------------- ### Create OCR engine with @arcships/light-ocr-tiny Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr-tiny/README.md Initializes the OCR engine using the tiny package. The engine is created asynchronously and can be used for OCR operations. ```javascript const { createEngine } = require('@arcships/light-ocr-tiny'); const engine = await createEngine(); ``` -------------------------------- ### C++ public types for tiled detection (DetectionStrategy, TiledDetectionInfo, EngineInfo) Source: https://github.com/arcships/light-ocr/blob/main/docs/tiled-design-and-acceptance.md Additive C++ public types for tiled detection. `EngineOptions::detection.strategy=tiled` is the only entry point; `DetectionOptions::max_side` and `RecognizeOptions::detection_max_side` are illegal under tiled. `EngineInfo::detection_max_side` is the tensor side (1280), not the image max side; image limits remain `limits.max_width`, `max_height`, `max_pixels`. `normalized_config_schema_version` reports "1.2"; `capabilities.tiled_detection` is true only when the bundle declares and passes `tiled-v1` validation, and only tiled engines have `info.tiled_detection` set. ```cpp enum class DetectionStrategy { bounded, tiled, upstream_exact, }; struct ResourceLimits { // existing fields... std::uint32_t max_detection_tiles = 100; }; struct TiledDetectionInfo { std::string contract_version; // "tiled-v1" std::uint32_t tile_side = 1280; std::uint32_t minimum_overlap = 128; std::uint32_t artificial_boundary_margin = 32; float merge_iou_threshold = 0.50f; float merge_ios_threshold = 0.80f; }; struct Capabilities { bool detection = true; bool recognition = true; bool textline_orientation = false; bool tiled_detection = false; }; struct EngineInfo { // existing fields... std::string normalized_config_schema_version; // "1.2" DetectionStrategy detection_strategy = DetectionStrategy::bounded; std::uint32_t detection_max_side = 960; std::optional tiled_detection; }; ``` -------------------------------- ### ModelBundle input structure Source: https://github.com/arcships/light-ocr/blob/main/docs/native-api.md Defines the immutable in-memory bundle input. Paths must be forward-slash relative to the bundle root; duplicate, absolute, parent-traversal, empty, or non-normalized paths are rejected. create validates schema, hashes, required files, configuration, and model identities, and the bundle retains shared ownership of required byte buffers. ```cpp namespace light_ocr { using SharedBytes = std::shared_ptr>; struct BundleFile { std::string path; SharedBytes bytes; }; class ModelBundle { public: static Result create(std::vector files); ModelBundle(ModelBundle&&) noexcept; ModelBundle& operator=(ModelBundle&&) noexcept; ~ModelBundle(); ModelBundle(const ModelBundle&) = delete; ModelBundle& operator=(const ModelBundle&) = delete; const std::string& id() const noexcept; const std::string& schema_version() const noexcept; }; } // namespace light_ocr ``` -------------------------------- ### Run Node addon tests Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Run the Node addon test suite with concurrency disabled to avoid interference. Executes all .test.cjs files under bindings/node/test. ```bash node --test --test-concurrency=1 bindings/node/test/*.test.cjs ``` -------------------------------- ### Core configuration contract (DetectionStrategy, DetectionOptions, EngineOptions) Source: https://github.com/arcships/light-ocr/blob/main/docs/memory-optimization.md Public contract for the first phase: DetectionStrategy enum, DetectionOptions, and EngineOptions with recognition_batch_size defaulting to 1. ```cpp enum class DetectionStrategy { bounded, upstream_exact, }; struct DetectionOptions { std::optional strategy; std::optional max_side; }; struct EngineOptions { // Existing thread and threshold fields remain. DetectionOptions detection; std::optional recognition_batch_size; // effective default: 1 }; ``` -------------------------------- ### Run light-ocr doctor --json Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md Run the CLI diagnostic command to output environment information in JSON format. ```bash light-ocr doctor --json ``` -------------------------------- ### Async pagination with recognizeDocument Source: https://github.com/arcships/light-ocr/blob/main/docs/roadmap.md Asynchronous pagination interface for the Document layer. Iterates over pages from recognizeDocument, allowing one page to be consumed or persisted at a time. Supports JPEG, PNG, PDF files/bytes, page range, raster DPI or target long edge, JSON/JSONL/text/Markdown output, and resource limits such as maxFileBytes, maxPages, maxPagePixels, and maxTotalPixels. ```ts for await (const page of recognizeDocument(source, options)) { // consume or persist one page at a time } ``` -------------------------------- ### Check PDF support and model profile Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md Check PDF support and model profile using the package's exported functions. ```javascript import { hasPdfSupport, modelProfile } from "@arcships/light-ocr"; console.log(hasPdfSupport()); console.log(modelProfile); ``` -------------------------------- ### recognizeDocument(source, options?) Source: https://github.com/arcships/light-ocr/blob/main/packages/light-ocr/README.md Streams PDF or image pages with automatic cleanup, applying configurable resource limits. ```APIDOC ## recognizeDocument(source, options?) ### Description Streams PDF or image pages with automatic cleanup. This function handles the entire document recognition process, including resource limits and cleanup. ### Method recognizeDocument ### Parameters #### source - **source** (string | Buffer | Stream) - Required - The input document (PDF or image). #### Options (optional) - **dpi** (number) - Optional - Rendering DPI, default 150. - **maxFileBytes** (number) - Optional - Maximum input file size, default 100 MiB. - **maxPages** (number) - Optional - Maximum number of pages, default 100. - **maxPagePixels** (object) - Optional - Maximum page dimensions, default 4096 × 4096. - **maxTotalPixels** (number) - Optional - Maximum total pixels, default 100 Mi pixels. ### Returns - **result** (object) - The recognition result with lines and page metadata. ### Example ```js const result = await recognizeDocument('document.pdf', { dpi: 200 }); ``` ``` -------------------------------- ### Batch OCR via shell loop Source: https://github.com/arcships/light-ocr/blob/main/bindings/node/README.md Batch processes all PNG files in the current directory, outputting JSONL for each. ```bash for f in *.png; do light-ocr recognize "$f" --format jsonl; done ``` -------------------------------- ### Public header files Source: https://github.com/arcships/light-ocr/blob/main/docs/native-api.md Lists the public headers exposed by the Core milestone. These headers use only the C++ standard library. ```text include/light_ocr/error.hpp include/light_ocr/types.hpp include/light_ocr/core.hpp ``` -------------------------------- ### Expected Core-owned recognition memory Source: https://github.com/arcships/light-ocr/blob/main/docs/memory-optimization.md Expected Core-owned recognition memory after streaming is implemented: one batch's crops, input, ORT output, and decode state, not the sum over all text lines. ```text one batch crops + one batch input + one ORT output + one batch decode state ```