# lw-ppocr-vulkan-java **Repository Path**: wuyuan/lw-ppocr-vulkan-java ## Basic Information - **Project Name**: lw-ppocr-vulkan-java - **Description**: lw-ppocr-vulkan java操作库 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-10-08 - **Last Updated**: 2026-10-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # lw-ppocr-vulkan PPOCRv6 Java Interface Library based on Vulkan GPU Acceleration ## Project Introduction lw-ppocr-vulkan is a high-performance Java OCR (Optical Character Recognition) library, based on the PPOCRv6 model and utilizing Vulkan GPU for accelerated computing. This project provides a concise Java API, supporting multiple integration methods, including native Java calling, Spring Boot, and Solon framework integration. ## Main Features - **Vulkan GPU Acceleration**: Implements efficient GPU parallel computing using the Vulkan API - **Multi-Framework Support**: Supports native Java, Spring Boot, and Solon - **Connection Pool Support**: Built-in engine connection pool, supporting high-concurrency scenarios - **Rich Configuration Options**: Provides fine-grained OCR parameter configuration - **Multi-Language Support**: Supports text recognition in Chinese, English, and other languages ## Module Structure | Module | Description | |------|------| | lw-ppocr-vulkan-common | Core library, containing the OCR engine and all core classes | | lw-ppocr-vulkan-spring-boot-starter | Spring Boot auto-configuration starter | | lw-ppocr-vulkan-solon-plugin | Solon framework plugin | | samples/spring-boot-ocr-app | Spring Boot sample application | | samples/solon-ocr-app | Solon sample application | ## Quick Start ### Maven Dependency ```xml com.lw.ppocr lw-ppocr-vulkan-spring-boot-starter 1.0.0 ``` ### Basic Usage ```java // Create OCR engine LwPpocr ocr = LwPpocr.create("/path/to/ppocrv6-tiny"); // Recognize image OcrResult result = ocr.ocr(imageBytes); // Get recognition results for (OcrItem item : result.getItems()) { System.out.println("Text: " + item.getText()); System.out.println("Confidence: " + item.getScore()); } ``` ### Spring Boot Integration Configure in `application.yml`: ```yaml lw: ppocr: enabled: true model-root: ./models/ppocrv6-tiny device-index: 0 # Single engine + bounded queue (same model as the official HTTP service): 4 / 32 / 5000 by default workers: 4 max-queued: 32 engine-wait-timeout-ms: 5000 ``` Inject service: ```java @RestController public class OcrController { @Autowired private LwPpocrService ocrService; @PostMapping("/ocr") public OcrResult ocr(@RequestParam("file") MultipartFile file) throws IOException { return ocrService.ocr(file.getBytes()); } } ``` ## Configuration Options | Configuration Item | Type | Default Value | Description | |--------|------|--------|------| | model-root | String | - | Model file root directory (Required) | | device-index | int | 0 | GPU device index | | nativeLibrary | String | Auto-detect | Native library path | | nativeDir | String | Auto-detect | Native library directory | | workers | int | 4 | Worker threads (max concurrently executing tasks) | | max-queued | int | 32 | Pending queue cap; full → 429 | | engine-wait-timeout-ms | long | 5000 | Result wait budget; timeout → 503 | | enableClassifier | Boolean | null | Enable direction classifier | | useDilation | Boolean | null | Use dilation operation | | readingOrder | Boolean | null | Sort by reading order | | detLimitSide | Integer | null | Detection side length limit | | maxCandidates | Integer | null | Maximum number of candidates | | bitmapThreshold | Float | 0.3 | Binarization threshold | | boxThreshold | Float | 0.5 | Text box confidence threshold | | unclipRatio | Float | 1.5 | Text box expansion ratio | | clsThreshold | Float | 0.9 | Direction classification confidence threshold | ## API Reference ### LwPpocr (Core Engine) ```java // Create engine LwPpocr ocr = LwPpocr.create(modelRoot); // Or use custom options LwPpocrOptions options = LwPpocrOptions.builder(modelRoot) .deviceIndex(0) .enableClassifier(true) .build(); LwPpocr ocr = LwPpocr.create(options); // Recognize image OcrResult ocr(byte[] encodedImageBytes); OcrResult ocr(BgrImage image); OcrResult ocr(byte[] pixels, int width, int height, int stride); // Get device list List devices(); // Whether the engine has been closed (true after close()) boolean isClosed(); // Close engine ocr.close(); ``` > `version()` / `devices()` only read library-level state and never touch the engine handle, so they stay > usable after `close()`; the inference entry points (`ocr` / `recognizeLine`) throw > `IllegalStateException` once closed. ### LwPpocrQueue (Single Engine + Bounded Queue) Same concurrency model as the official `lw-ppocr-vulkan-http-service`: one engine, N workers pulling jobs, a capped pending queue. ```java // With defaults: 4 workers / queue 32 / 5000ms wait LwPpocrQueue queue = LwPpocrQueue.create(options); // Or wrap an existing engine LwPpocrQueue queue = LwPpocrQueue.of(LwPpocr.create(options)); // Submit and wait for the result String text = queue.submit(ocr -> ocr.ocr(imageBytes).text()); // Close queue.closeAndAwait(); ``` **Three overload conditions, three status codes** (same as the official service): | Condition | Exception | HTTP | |-----------|-----------|------| | Queue full | `LwPpocrQueueFullException` | **429** QUEUE_FULL | | Timed out waiting for a result | `LwPpocrEngineBusyException` | **503** ENGINE_WAIT_TIMEOUT | | Engine unavailable | `LwPpocrEngineUnavailableException` | **503** ENGINE_UNAVAILABLE | > **Queue full must fail immediately**: the queue — not the HTTP thread pool — is where requests line up. > Letting them pile up in the thread pool turns "we're full" into "the whole service is down". > > **An engine failure marks the whole queue unavailable**: when native returns non-OK (GPU lost, OOM) or > throws an `Error`, the queue is flagged `broken` once, pending jobs fail immediately, and every later > submit is rejected — instead of making each request burn a full timeout. Business errors (a bad image) > do not trigger this. Recovery means rebuilding the engine (restart the process). > > **Release before exit**: `close()` returns immediately; the last worker to exit destroys the engine once > the running task finishes. A container that exits right after leaks those handles (~60MiB of VRAM each). > Use `queue.closeAndAwait()` from container shutdown / `@PreDestroy` (waits up to 10s, see > `LwPpocrQueue.DEFAULT_DRAIN_TIMEOUT_MS`); the Spring queue bean already does. A Cleaner backstop destroys > handles once an instance becomes unreachable, but that is a fallback, not deterministic release. > > **Never submit from inside a task** (worker-thread re-entry): worker count is finite, so every worker > waiting on its own child job deadlocks. Re-entry throws `IllegalStateException` immediately. > > **Never `close()` the engine owned by the queue** (e.g. `service.nativeEngine().close()`): the handle is > already destroyed, so touching it again is use-after-free, and the queue flags the whole service > unavailable. > > Ops visibility: `GET /api/ocr/info` returns `workers` / `maxQueued` / `pending` / `active` / `broken`. > > **Why a single engine by default**: inference on one handle is serial, so throughput caps at > `1 / per-call time`. Measured here (640×320 image, ppocrv6-tiny): a GTX 1650 already used 83% of the GPU > with one instance (28.0 ms/op) — 2 instances reached 98% and +18% throughput, 4 hit the ceiling > (44.1 QPS); an Intel UHD 630 sat at 97–99% with a single instance, so extra instances added nothing. > Each extra instance also costs ~60MiB of weight VRAM. Measure single-instance GPU utilization with > `tools/gpubench` before scaling up. ### OcrResult (Recognition Result) ```java OcrResult result = ocr.ocr(imageBytes); // Get all text String fullText = result.text(); // Get line-by-line text List lines = result.lines(); // Get detailed information List items = result.getItems(); Timing timing = result.getTiming(); double elapsedMs = result.getElapsedMs(); ``` ## Performance Testing The project provides a GPU performance testing tool located in the `tools/gpubench` directory: ```bash cd tools/gpubench go run main.go -image ../test-images/sample.jpg -devices 0,1 ``` ## Model Files The project includes the PPOCRv6-tiny model, located in the `models/ppocrv6-tiny` directory: - `det.onnx` - Text detection model - `rec.onnx` - Text recognition model - `cls.onnx` - Direction classification model - `dictionary.txt` - Dictionary file ## System Requirements - Java 8 or higher - GPU driver supporting Vulkan 1.0+ - Windows or Linux operating system ## License This project is open sourced under the Apache License 2.0.