RapidOCR Local Model Adapter
For cached in-process ONNX inference, use the RapidOCR Native DLL Adapter with HPDFCreateRapidOCRDLLOCREngine and THPDFRapidOCRDLLOptions
The native adapter provides THPDFRapidOCRDLLOptions.ForLanguage presets for simplified and traditional Chinese, English, Latin languages, Japanese, Korean, Cyrillic languages including Russian, Arabic languages, and Devanagari languages
HPDFRapidOCRRecognition provides a Windows process adapter implementing IHPDFOCREngine in Delphi, C++Builder, and FPC/Lazarus Win32 and Win64 builds
Provision Python with rapidocr and onnxruntime, the supplied tools/OCR/rapidocr_tsv.py bridge, and compatible local ONNX models; the adapter does not install packages or download models, dictionaries, or fonts
Python runs in a separate hidden process, so its architecture can differ from the calling application; its ONNX Runtime package must match its own Python architecture
Factory overloads
function HPDFCreateRapidOCREngine(const PythonExecutable, BridgeScript,
ModelDirectory: string; TimeoutMilliseconds: Cardinal = 60000): IHPDFOCREngine; overload;
function HPDFCreateRapidOCREngine(const PythonExecutable, BridgeScript,
ModelDirectory: string; const Options: THPDFRapidOCROptions): IHPDFOCREngine; overload;
The original timeout overload remains compatible with the existing bridge protocol and uses the three default PP-OCRv4 model filenames; it checks executable, script, and directory paths at construction and checks model availability in the worker
The options overload checks every required model, an optional dictionary, and the local font before returning the adapter; missing files or invalid options raise EArgumentException before recognition starts
Relative model, dictionary, and font paths resolve against ModelDirectory; absolute paths can point to separately provisioned files
Use models compatible with RapidOCR's detection, classification, and CTC recognition pipeline; a model from another OCR pipeline may require different preprocessing and cannot be selected solely because it uses the ONNX format
Language-specific model selection
The Python process adapter continues to use explicit THPDFRapidOCROptions paths; ForLanguage belongs to the native DLL options record and is not a Python adapter method
Provision local language models and dictionaries with tools/Install-RapidOCRModels.ps1 -Destination C:/OCR/models -Language ch,cyrillic, or select -Language All for all nine language profiles
The helper checks pinned SHA256 hashes and places each recognizer at <profile>/recognition.onnx with its matching <profile>/dictionary.txt; runtime recognition remains offline without automatic downloads
For Russian, use cyrillic/recognition.onnx and cyrillic/dictionary.txt; simplified Chinese uses the ch profile and traditional Chinese uses chinese_cht
Models := THPDFRapidOCROptions.Default;
Models.DetectionModel := 'ch_PP-OCRv3_det_infer.onnx';
Models.RecognitionModel := 'cyrillic/recognition.onnx';
Models.CharacterDictionary := 'cyrillic/dictionary.txt';
Models.ClassificationModel := 'ch_ppocr_mobile_v2.0_cls_infer.onnx';
The detector and classifier root filenames above match the provisioning helper's shared models; supply the matching recognition model and dictionary together, and choose a separate engine for pages or regions that need another script
Options and defaults
THPDFRapidOCROptions = record
DetectionModel: string;
RecognitionModel: string;
ClassificationModel: string;
CharacterDictionary: string;
FontPath: string;
UseAngleClassifier: Boolean;
IntraOpThreads: Integer;
InterOpThreads: Integer;
MaxPixels: Integer;
TimeoutMilliseconds: Cardinal;
class function Default: THPDFRapidOCROptions; static;
end;
Initialize the record with THPDFRapidOCROptions.Default before overriding fields
| Field | Default | Meaning |
|---|---|---|
DetectionModel | ch_PP-OCRv4_det_mobile.onnx | Local detection model |
RecognitionModel | ch_PP-OCRv4_rec_mobile.onnx | Local recognition model |
ClassificationModel | ch_ppocr_mobile_v2.0_cls_mobile.onnx | Required only when angle classification is enabled |
CharacterDictionary | Empty | Use the recognition model's embedded character metadata; supply a local dictionary when the model lacks that metadata |
FontPath | Empty | Resolve to %WINDIR%\Fonts\arial.ttf for RapidOCR's result container |
UseAngleClassifier | True | Enable text angle classification; when disabled, no classification model is required or passed |
IntraOpThreads | 1 | ONNX intra-operation threads, from 1 through 64, capped at the worker's logical CPU count |
InterOpThreads | 1 | ONNX inter-operation threads with the same limits |
MaxPixels | 16777216 | Input pixel budget, from 1 through 67,108,864 |
TimeoutMilliseconds | 60000 | Total request deadline, from 1 through 3,600,000 milliseconds |
The bridge explicitly selects the ONNX Runtime CPU backend for all stages and disables automatic downloads; a missing embedded character dictionary requires a provisioned local CharacterDictionary
Example with explicitly selected models
uses SysUtils, HPDFDoc, HPDFRapidOCRRecognition;
procedure AddLocalRapidOCRText(PDF: THotPDF);
var
Engine: IHPDFOCREngine;
Models: THPDFRapidOCROptions;
Layer: THPDFOCRTextLayerOptions;
Info: THPDFOCRTextLayerInfo;
begin
Models := THPDFRapidOCROptions.Default;
Models.DetectionModel := 'PP-OCRv6_det_small.onnx';
Models.RecognitionModel := 'PP-OCRv6_rec_small.onnx';
Models.UseAngleClassifier := False;
Engine := HPDFCreateRapidOCREngine(
'C:\OCR\Python\python.exe',
'C:\HotPDF\tools\OCR\rapidocr_tsv.py',
'C:\OCR\models', Models);
Layer := THPDFOCRTextLayerOptions.Default;
if not PDF.ApplyLoadedOCRTextLayer([0], Engine, Layer, Info) then
raise Exception.Create('Local RapidOCR text layer was not added');
end;
Results, budgets, and cancellation
Each request serializes the borrowed bitmap into a private temporary directory, starts a local Python worker, and cleans up its process handles and temporary files when the request finishes
The options overload checks MaxPixels before bitmap serialization; the worker also checks input dimensions before loading the models and receives the request's MaxWords and MaxTextCodeUnits limits
The bridge requests character coordinates and validates every character's geometry, confidence, and text coverage, then emits each complete recognized line with its original internal spaces and punctuation, the enclosing bounds in original image pixels, and mean confidence in the range 0 through 1
Each emitted line consumes one MaxWords slot; internal spaces count toward MaxTextCodeUnits, and publishing a whole line prevents the text layer from mistaking letter spacing for word spacing
Spacing is preserved from the recognizer's line text; text that detection splits into separate boxes still depends on spatial word-gap inference, and external PDF readers may reconstruct or collapse repeated spaces during extraction
Supplementary characters consume two UTF-16 units; invalid coordinates, confidence, control characters, or exhausted budgets fail recognition and clear partial results
An empty page succeeds with an empty word array; no native baseline is supplied, so the text layer uses its existing geometry fallback
Cancellation, timeout, and output sizes are polled every 25 milliseconds; a Windows job contains the worker and any interpreter child processes, and termination waits up to five additional seconds for process cleanup
ApplyLoadedOCRTextLayer publishes all selected pages atomically after recognition succeeds
TSV output is limited to 64 MiB and diagnostic output to 1 MiB; input and output budgets do not impose a hard cap on ONNX model or inference memory use
Model initialization occurs in a new Python process for each request and is included in the deadline
Validation
The shared Delphi and FPC adapter runners cover model preflight, custom paths, optional classification, Unicode, budgets, worker failure, cancellation, and timeout; their optional RapidOCR parameters enable real recognition and searchable PDF round-trip checks
Use Tests/Delphi/Run-TesseractRecognitionTests.ps1 or Tests/Delphi/Run-TesseractFPCRecognitionTests.ps1 with -RapidOCRPython, -RapidOCRModelDirectory, -RapidOCRDetectionModel, and -RapidOCRRecognitionModel
See Searchable OCR Text Layers for rendering options, Unicode PDF text mapping, optional-content grouping, and conformance limits