[Feat] Add PP-OCRv6 iOS Demo (#17933)

* Update for paddleocr 3.5

* Fix doc

* Add doc to nav

* Refine docs

* Fix PaddleOCR-VL doc

* Polish PaddleOCR-VL docs

* Polish docs

* Add notice

* Polish doc

* docs: initialize project

* Init

* feat(02-02): port Clipper polygon offset algorithm to pure Swift

- Implement ClipperOffset class with addPath/execute API
- Support JT_ROUND + ET_CLOSEDPOLYGON for DB postprocessing
- Add static offsetPolygon() convenience for DBPostProcess
- Arc tolerance calculation matches pyclipper's Clipper 6.x
- Pure Swift, no external dependencies

* feat(02-01): add Yams dependency and InferenceConfig YAML parser

- Add Yams ~> 5.0 pod to Podfile for inference.yml parsing
- Create InferenceConfig.swift with typed parsing of inference.yml
- Support TransformOp enum: DetResizeForTest, NormalizeImage, ToCHWImage, RecResizeImg
- PostProcessConfig handles both det (DBPostProcess) and rec (CTCLabelDecode) configs
- Python-style scale string '1./255.' parsed via string splitting (not eval)
- Register InferenceConfig.swift in Xcode project

* feat(02-01): implement pure-Swift detection preprocessing operators

- Create Preprocessing.swift with DetPreprocessor and PreprocessResult
- Port DetResizeForTest: resize longest side to resize_long, ceil to 128 stride
- Port NormalizeImage: config-driven scale/mean/std normalization
- Port ToCHWImage: HWC-to-CHW layout conversion producing [1,3,H,W] tensor
- Image padding for tiny images (h+w < 64) matching Python reference
- Pure Swift using CoreGraphics + Accelerate (no OpenCV dependency)
- All transform parameters read from InferenceConfig (zero hardcoded values)
- Register Preprocessing.swift in Xcode project

* feat(02-02): implement DB text detection postprocessing pipeline

- Add DBPostProcessor with full pipeline: threshold -> contours -> minAreaRect -> score -> expand -> scale
- Implement Suzuki-Abe contour finding with CHAIN_APPROX_SIMPLE compression
- Implement rotating calipers minAreaRect + convex hull (Andrew's monotone chain)
- Add scanline polygon fill for box_score_fast computation
- Integrate ClipperOffset for polygon expansion (unclip)
- All parameters configurable via DBPostProcessConfigurable protocol
- Pure Swift, no OpenCV dependency

* docs(02-02): create SUMMARY.md for ClipperOffset + DBPostProcess plan

* feat(02-03): expose runDetection method on ORTSessionManager

- Add runDetection(inputData:shape:) for real inference with preprocessed data
- Returns output tensors as [String: (data: [Float], shape: [Int])] dictionary
- Includes NaN validation on output tensors
- All existing methods (loadModels, validateDetModel, validateRecModel) preserved unchanged

* feat(02-03): create DetectionEngine orchestrating full detection pipeline

- DetectionEngine wires DetPreprocessor -> ORTSessionManager.runDetection -> DBPostProcessor
- DetectionResult struct with boxes and per-stage timing metrics (preprocess/inference/postprocess)
- All parameters loaded from inference.yml via InferenceConfig.load()
- PostProcessConfig conforms to DBPostProcessConfigurable for type-safe init bridging
- DetectionEngineError for noOutputTensor and unexpectedOutputShape cases
- Registered in Xcode project pbxproj

* docs(02-03): complete detection engine integration plan

- SUMMARY.md documenting DetectionEngine pipeline integration
- STATE.md updated with position, decisions, metrics
- REQUIREMENTS.md: POST-01, POST-02 marked complete

* docs(phase-02): verification complete — human_needed for runtime numerical exactness

* docs(phase-02): complete phase execution

* docs(phase-02): evolve PROJECT.md after phase completion

* feat(03-01): add runRecognition to ORTSessionManager with shared inference method

- Extract private runInference() from runDetection to eliminate code duplication
- Add public runRecognition() method that uses recSession for recognition model inference
- Both runDetection and runRecognition guard their respective sessions and delegate to runInference
- Recognition model supports dynamic-width input tensors [1, 3, 48, W]

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(03-01): create RecPreprocessor implementing OCRResizeNormImg

- Implement OCRResizeNormImg algorithm matching PaddleX text_recognition/processors.py
- Read imgC/imgH/imgW from inference.yml RecResizeImg.image_shape (config-driven, not hardcoded)
- Aspect-ratio-aware resize with ceil() width computation matching Python math.ceil()
- Recognition normalization: pixel/127.5 - 1.0 mapping [0,255] to [-1,1] (not ImageNet mean/std)
- HWC-to-CHW transpose and right-pad with zeros to target width
- Bilinear interpolation via CGContext (pure Swift, no OpenCV)
- Register RecPreprocessor.swift in Xcode project (PBXBuildFile, PBXFileReference, PBXGroup, Sources)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(03-01): complete recognition preprocessing & inference plan

- Create 03-01-SUMMARY.md documenting plan execution
- Update STATE.md: advance to Phase 3 Plan 1 complete, add decisions
- Update ROADMAP.md: Phase 3 progress 1/2
- Update REQUIREMENTS.md: mark PREP-04 and PREP-05 as complete

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(03-02): create CTCDecoder implementing CTC label decode with character dictionary

- CTCDecoder struct ported from ppocr/postprocess/rec_postprocess.py CTCLabelDecode
- Reads character_dict from inference.yml PostProcess config
- Prepends blank token at index 0 (CTC convention)
- Decoding: argmax + consecutive duplicate removal + blank filtering + char mapping
- Confidence: mean probability of selected timesteps
- Registered in Xcode project (Engine group)

* feat(03-02): create RecognitionEngine orchestrating full recognition pipeline

- RecognitionEngine class mirrors DetectionEngine pattern
- Composes RecPreprocessor + ORTSessionManager.runRecognition + CTCDecoder
- Returns RecognitionEngineResult with text, confidence, and per-stage timing
- Config-driven: reads inference.yml for preprocessing dims and character dictionary
- Registered in Xcode project (Engine group)

* docs(03-02): complete CTC decoding and recognition engine integration plan

- 03-02-SUMMARY.md with frontmatter, accomplishments, and self-check
- STATE.md updated with position, decisions, metrics
- ROADMAP.md Phase 3 marked 2/2 complete
- REQUIREMENTS.md POST-03, POST-04 marked complete

* docs(03): create gap closure plan for CTCDecoder missing space character

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(03-03): append ASCII space to CTCDecoder dictionary for 18,385-element parity

- Add chars.append(" ") after dict chars to match PaddleX use_space_char=True default
- Update doc comments to document full 18,385-element character list layout
- Fixes model output class index 18384 being silently dropped during decode

* docs(03-03): complete CTC decoder space character fix plan

- Created 03-03-SUMMARY.md with execution results
- Updated STATE.md with plan completion and metrics
- Updated ROADMAP.md with plan 03-03 completion status

* merge: integrate phase 03-03 gap closure from worktree

* docs(phase-03): complete phase execution — 7/7 must-haves verified

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(phase-03): evolve PROJECT.md after phase completion

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(04): create phase plan for Pipeline Orchestration & Validation

3 plans in 2 waves:
- Plan 01 (Wave 1): BoxSorter + PerspectiveCrop algorithms
- Plan 02 (Wave 1): Python validation scripts (generate_reference.py + validate.py)
- Plan 03 (Wave 2): OCREngine orchestrator + ValidationExport JSON serializer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(04-02): add PaddleX reference output generator for iOS validation

- generate_reference.py runs PaddleOCR on test images, exports per-image
  JSON with polygon coordinates, text, and confidence scores
- Creates test_images/ directory with .gitkeep for developer-provided images
- .gitignore excludes generated reference/ directory from version control
- Supports PP-OCRv5 mobile det/rec models with all optional processors disabled

* feat(04-01): implement BoxSorter reading-order sort

- Port PaddleX SortQuadBoxes algorithm to Swift
- Two-phase sort: initial y/x sort + backward insertion for same-line reorder
- yThreshold=10 matching PaddleX hardcoded value
- Consumes DetectionBox type from DBPostProcess.swift

* feat(04-02): add iOS vs reference validation script and README

- validate.py compares iOS JSON output against PaddleX reference JSON
  with exact polygon/text match and 1e-4 confidence tolerance
- Prints per-image PASS/FAIL and overall summary with box match counts
- Exit codes: 0=pass, 1=fail, 2=missing files (CI-friendly)
- README.md documents complete validation workflow (generate -> export -> validate)

* feat(04-01): implement PerspectiveCrop with DLT warp and tall-narrow rotation

- Port PaddleX get_rotate_crop_image algorithm to pure Swift
- DLT perspective matrix solve via 8x8 Gaussian elimination
- Backward-mapping bilinear warp with BORDER_REPLICATE clamping
- 90-degree CCW rotation when height/width >= 1.5
- Float64 precision for matrix computation, Float for pixel sampling
- CoreGraphics-only: no OpenCV dependency

* docs(04-02): complete validation scripts plan

- SUMMARY.md documenting plan execution (2 tasks, 5 files, 4min)
- STATE.md updated with position, decisions, metrics
- ROADMAP.md updated with Phase 04 progress (1/3 plans)
- REQUIREMENTS.md marks VALID-01, VALID-02, PIPE-05 complete

* docs(04-01): complete pipeline bridge algorithms plan

- SUMMARY.md with BoxSorter and PerspectiveCrop execution results
- STATE.md updated with Phase 04 position and decisions
- ROADMAP.md updated with plan progress (1/3)
- REQUIREMENTS.md marked PIPE-02, PIPE-03 complete

* feat(04-03): add OCREngine pipeline orchestrator with per-stage timing

- Composes DetectionEngine, BoxSorter, PerspectiveCrop, RecognitionEngine
- Async run() method: detect -> sort -> crop -> recognize flow
- OCRResult and OCRPipelineResult types with per-stage timing breakdown
- Zero hardcoded params; all config-driven via inference.yml

* feat(04-03): add ValidationExport JSON serializer for pipeline output

- Serializes OCRPipelineResult to JSON matching Python validation schema
- Schema: {image, box_count, boxes: [{polygon, text, confidence}]}
- writeJSON writes to Documents/validation_output/ for device extraction
- Sorted keys for deterministic output diffs

* docs(04-03): complete pipeline orchestration plan

- OCREngine + ValidationExport implemented and committed
- STATE.md, ROADMAP.md, REQUIREMENTS.md updated
- PIPE-01, PIPE-04, CONF-02, CONF-03, CONF-04, CONF-05 marked complete

* docs(phase-04): complete phase execution — 10/10 must-haves verified

* docs(phase-04): evolve PROJECT.md after phase completion

* docs(05-user-interface): create phase plan

Two plans for Phase 5 UI: Plan 01 (wave 1) establishes OCRViewModel
state machine, PhotosPicker integration, sample images, and ContentView
coordinator. Plan 02 (wave 2) adds ResultImageView with Canvas polygon
overlay, TimingView, ResultsListView with clipboard copy, ErrorView,
and a human verification checkpoint.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(05-01): create OCRViewModel with full lifecycle state machine

- Add AppState enum with 5 states: loadingModels, ready, processing, results, error
- Add AppError enum with modelLoadFailed, inferenceFailed, imageLoadFailed cases
- Add OCRViewModel @MainActor class managing full app lifecycle via single @Published state
- Implement loadModels, processImage, selectSampleImage, copyResultsToClipboard, retry, reset
- Add normalizeOrientation helper for EXIF rotation flattening
- Fix missing pbxproj entries for OCREngine, BoxSorter, PerspectiveCrop, ValidationExport (Rule 3)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(05-01): create ImagePickerSection and bundle sample images

- Add ImagePickerSection.swift with PhotosPicker + sample thumbnail row
- Bundle 3 sample images: English (book.jpg), Chinese (PP-OCRv3-pic001), multiline (table.jpg)
- Add SampleImages as folder reference in Xcode project Resources build phase
- Add Views group and Resources group to Xcode project structure

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(05-01): rewrite ContentView as state coordinator, retire AppViewModel

- Rewrite ContentView to use OCRViewModel with state-driven rendering
- Add NavigationStack with inline title "PaddleOCR Demo"
- Implement 5 state views: loadingModels, ready, processing, results, error
- Wire PhotosPicker via onChange binding with Data loadTransferable
- Integrate ImagePickerSection in ready, results, and non-model-error states
- Show processing overlay spinner on selected image
- Add placeholder results view with text list and timing (Plan 02 replaces)
- Error view with context-specific heading and Retry button
- Replace AppViewModel.swift contents with empty stub comment

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(05-01): complete view model + image selection plan

- Create 05-01-SUMMARY.md with execution results and self-check
- Update STATE.md: Phase 5 Plan 1 complete, add decisions
- Update ROADMAP.md: Phase 5 progress (1/2 plans)
- Mark requirements UI-01, UI-02, UI-07, UI-08 as complete

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* merge: resolve STATE.md conflict after 05-01 execution

* feat(05-02): add ResultImageView with Canvas polygon overlay and TimingView

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(05-02): add ResultsListView, ErrorView, and wire all views into ContentView

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update docs

* update

* update

* Fix and update

* update speed data

* Optimize UI

* add warning

* update warning

* update warning

* update warning

* update warning

* update

* update

* Remove cached inference.yml files

* Fix bugs

* Update API docs

* Update API docs

* Fix

* Update

* Update git ignore

* Update docs

* Refactor and align with Python

* Fix config settting

* Optimize code

* Allow engine selection

* Restructure folders

* Support batch inference

* update pp_structure_v3 case

* update

* Init validation toolkit

* Hack paddleocr

* Allow specifying URLs for pdx and ppocr version

* docs: release-review fixes for 3.5 docs

Addresses issues surfaced during release-time review of #17820,
covering broken rendering, broken cross-language and anchor links,
expression and consistency nits, and the strict-mode docs-anchor CI.

Rendering fixes:
- Restore truncated/duplicated parameter-table rows in OCR.en.md,
  PP-DocTranslation.en.md, PP-StructureV3.en.md, and
  doc_understanding.en.md
- Fix mis-indented kwarg in the PP-DocTranslation.en.md transformers
  example (would SyntaxError on copy-paste)
- Fix 4-backtick closing fence and over-wide rowspan in
  chart_parsing.{en,zh}.md
- Fill in empty enable_hpi default (None) in PaddleOCR-VL.en.md

Link fixes:
- Point module_usage .en.md files at ../inference_engine.en.md
  instead of the Chinese ../inference_engine.md (11 files)
- Replace Chinese anchor #五推理引擎 with #5-inference-engine in
  eight module_usage .en.md files, and normalize the corresponding
  heading from "## V. Inference Engine" to "## 5. Inference Engine"
  in textline_orientation_classification.en.md
- Correct mislabeled PaddleX weight-conversion link text in
  text_detection.en.md and table_structure_recognition.en.md
- Align broken cross-file link in inference_engine.md with the
  actual slug (#3-paddlex) so it stops conflicting with
  high_performance_inference.md and serving.md

Chinese anchor resolution (CI fix):
- Attach explicit {#anchor} (attr_list) attributes to the zh
  headings for "推理引擎", "权重转换", and "流程导览" so the
  existing in-page Chinese anchors resolve under the default
  mkdocs slugify. Build now clean under `mkdocs-ci.yml` strict mode.

Expression and consistency:
- Drop duplicated "and vLLM" phrase in NVIDIA Blackwell WARNING
- Restore Chinese key "驾驶室准乘人数" in PP-ChatOCRv4.en.md
  transformers example (rest of the doc keeps it)
- Normalize "Paddle framework" to "PaddlePaddle framework" and
  align link text with target file title across affected docs
- Fix plural/singular mismatch ("examples"/"them" -> "example"/"it")
  in module_usage .en.md quick-start intros that show one command
- Add missing comma after hardware names in five hardware EN tutorials
- Add spacing in "PaddleX 产线 Python 脚本使用说明" link text in
  inference_engine.md
- Use uppercase CPU/GPU in paddlepaddle_installation.md comments

Navigation:
- Add missing English nav_translations entries so the English
  sidebar no longer shows raw Chinese labels:
    PP-DocTranslation产线 -> PP-DocTranslation Pipeline
    推理引擎与配置说明     -> Inference Engine and Configuration

Signed-off-by: Bvicii <yizhanhuang2002@gmail.com>

* docs: clarify that engine=None preserves legacy PaddleOCR behavior

Addresses PR #17820 review feedback: the engine-parameter row lists
`paddle`, `paddle_static`, `paddle_dynamic`, and `transformers` as
supported values but doesn't mention that `None` is also valid (and
is the default). Add a short user-facing clarification to every engine
row's Description so readers who see `default=None` understand what
that means:

- EN: "If left as `None` (the default), PaddleOCR preserves the
  behavior of earlier versions, which in most configurations is
  equivalent to `paddle`."
- ZH: "保持为默认值 None 时,PaddleOCR 保留旧版本的行为,在大多数配置下
  等价于 paddle。"

48 files, 66 engine rows updated (33 EN + 33 ZH). No changes to
engine_config rows, which use a different description.

Signed-off-by: Bvicii <yizhanhuang2002@gmail.com>

* Remove planning files

* Fix code style

* Optimize docs

* Update docs

* docs: align CUDA 12.6 Docker driver version with pip section

Per review feedback from changdazhou on PR #17820 (L26), update the
CUDA 12.6 Docker GPU line to require driver >= 550.54.14, matching
the pip section already at L61 (both ZH and EN).

Signed-off-by: Bvicii <yizhanhuang2002@gmail.com>

* docs: include None in engine supported-values list

Per follow-up review on PR #17820: from a completeness standpoint,
None belongs in the "Supports ..." enumeration rather than only in
the trailing clarification sentence. Move None into the list as the
default value and tighten the follow-on sentence accordingly.

- EN: "Supports None (the default), paddle, paddle_static,
  paddle_dynamic, and transformers. When left as None, PaddleOCR
  preserves the behavior of earlier versions..."
- ZH: "支持 None(默认值)、paddle、paddle_static、paddle_dynamic、
  transformers。保持为默认值 None 时..."

Applied to all three supported-value variants across the module_usage
and pipeline_usage pages — same 48 files / 66 rows as the previous
clarification commit.

Signed-off-by: Bvicii <yizhanhuang2002@gmail.com>

* Fix benchmark

* Add icon and fix validation

* ci,docs: align PaddleX install branch and document py3.8 extras boundary (#17954) (#17961)

* ci,docs: align PaddleX install branch and document py3.8 extras boundary

- CI: derive the PaddleX install branch from the paddlex constraint in
  pyproject.toml (release/X.Y) so PR/GPU tests stay in sync as the
  paddleocr series advances; apply to both tests.yml and test_gpu.yml
- CI: install only paddleocr[doc2md] on py3.8 since several paddlex
  transitive deps require py3.9+; add a py38_incompatible pytest marker
  and gate affected tests behind it
- CI: pin paddlepaddle==3.0.0 on py3.8 / 3.1.0 on py3.9+ (match GPU CI)
- CI: standardize workflow filenames (.yaml -> .yml, dashes -> underscores)
- deps: pin lmdb<1.5 on py3.8 (newer lmdb wheels reference Py_SET_REFCNT,
  a py3.9 stdlib C API)
- docs: note Python 3.8+ for base paddleocr/doc2md; py3.9+ for
  doc-parser/ie/trans/all extras (safetensors>=0.7 dropped py3.8)
- docs: update PaddleOCR-VL manual-install Python range to 3.9-3.13
  across all hardware variants (VL pipelines use doc-parser)
- tests: tag tests that require py3.9+ extras/deps with py38_incompatible



* ci: mark /workspace as git safe.directory in GPU runner

setuptools_scm runs git to derive the package version during
pip install -e .; inside the GPU CI container /workspace is owned
by the host user, which trips git's dubious-ownership check and
aborts the paddleocr install.



---------


(cherry picked from commit 09e8700fe6)

Signed-off-by: Bvicii <yizhanhuang2002@gmail.com>

* Add quantization

* docs(ios_demo): add build_onnx_calib_npy.py and README for static calib .npy

Made-with: Cursor

* Enhance quantization and support ort format

* Fix skills

* Fix installation docs

* Enhance benchmark

* Use release config

* By default use CPU

* Support setting session options

* Enhance UI

* Update benchmark docs

* Fix wrong updates

* reset skill updates

* Update .gitignore

* Add chinese docs

* Support PP-OCRv5_mobile

* Remove on-device deployment

* Fix anchor:

---------

Signed-off-by: Bvicii <yizhanhuang2002@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: zhangyue66 <zhangyue66@baidu.com>
Co-authored-by: Bvicii <yizhanhuang2002@gmail.com>
Co-authored-by: Bvicii <98971614+scyyh11@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-06-11 12:48:03 +08:00
1 parent 30c312b906
commit 6a8b8f1e32
100 files changed
+17146 -971

No files matched your search

+194
View File
@@ -0,0 +1,194 @@
# PaddleOCR Release SOP
[中文](./RELEASING_cn.md)
## Scope
This document describes the standard release process for PaddleOCR.
## Release Types
The current process supports the following two release types:
- `bump patch`: for example, `3.4.0 -> 3.4.1`
- `bump minor`: for example, `3.4.x -> 3.5.0`
For `bump major`:
- The current process does not directly support this scenario
- A major release process should be discussed and designed separately, for example by introducing an additional branch or a new preparation flow
## Release Principles
- Daily development happens on `main`
- Official releases are made only from `release/X.Y`
- Official tags must use `vX.Y.Z`
- Do not create official release tags on `main`
## Standard Release Process
### 1. Confirm the release target
First confirm which release line this release belongs to and what the target version is.
Examples:
- Release `3.4.1` on `release/3.4`
- Release `3.5.0` on `release/3.5`
### 2. Create or switch to the release branch
If the release line does not exist yet, create the corresponding `release/X.Y` branch from `main`.
If it already exists, switch to that branch and continue release preparation there.
Requirements:
- One minor release line corresponds to one fixed `release/X.Y` branch
- That branch should contain only the release content and patch fixes for that line
### 3. Pick release content from main
Based on the release scope, `cherry-pick` the required commits from `main` into `release/X.Y` until the release content is ready.
Requirements:
- Only pick what is needed for the current release
- Avoid bringing unrelated new features into the release branch
- If there are release-specific fixes on the release branch, keep them limited to the current release scope
### 4. Complete pre-release checks
Complete pre-release checks on `release/X.Y`.
At minimum, this should include:
- The current branch is correct
- The working tree is clean
- The version is as expected
- Key functionality is verified
- Required tests, builds, packaging, and regression checks have passed
- Release notes are ready
### 5. Create the official tag
Once the release is ready, create the official tag on `release/X.Y`:
- The tag format must be `vX.Y.Z`
Examples:
- `v3.4.1`
- `v3.5.0`
Requirements:
- The tag must be created on the release branch for the current official release
- Do not use development tags as official release tags
### 6. Publish the GitHub Release
Create a GitHub Release based on the official tag for this release.
### 7. Update dependency constraints and release notes
If this release is the first release of a new minor line, or if it changes PaddleX dependency requirements, update the related release materials before or after the official tag is published.
At minimum, this should include:
- Checking whether the `paddlex` dependency constraints in `pyproject.toml` match the target release
- Checking whether installation docs, upgrade notes, and release notes are aligned with the release version
Completion criteria:
- The `paddlex` dependency constraints match the target release
- The version information in the documentation matches the released version
### 8. Sync the release branch lineage back to main
After the first official release of a new `release/X.Y` line is completed, sync the lineage of that `release/X.Y` branch back to `main`.
This is a fixed step in the current workflow and should be done at least once for each new minor release line.
Purpose:
- Ensure `main` correctly reflects that the release line has produced an official version
- Keep subsequent development and release cadence aligned
Requirements:
- Perform this once after the first official release of each new `release/X.Y`
- For later patch releases on the same `release/X.Y`, it is usually not necessary to repeat it
### 9. Move on to the next development cycle or patch release
After the release:
- `main` continues with ongoing development
- `release/X.Y` continues to maintain that release line
If more patch releases are needed later on the same line:
- Continue preparing patches on `release/X.Y`
- `cherry-pick` from `main` as needed
- Repeat the relevant steps in this SOP
## How to Handle Different Bump Types
### Patch Release
Applicable scenarios:
- Fixing production issues
- Small compatibility fixes
- Documentation, dependency, or stability patches
How to handle it:
- Continue preparing changes on the existing `release/X.Y`
- Create the next patch tag, for example `v3.4.2`
### Minor Release
Applicable scenarios:
- Starting a new release line
- Releasing the next stable version, for example `3.5.0`
How to handle it:
- Create a new `release/X.Y` from `main`
- Prepare the release following the standard process
- Create the first official tag, for example `v3.5.0`
- Update `paddlex` dependency constraints if needed
- Sync the lineage of that release branch back to `main` after the release
### Major Release
Current conclusion:
- It is not included in this SOP for now
- A separate process needs to be discussed and designed later
Before a dedicated solution is defined, do not directly reuse the current minor/patch process for a major release.
## Release Checklist
Before each release, confirm the following:
- The target version and corresponding release branch have been confirmed
- The content on the release branch is ready
- The release scope has been finalized
- Key tests and regression checks have passed
- Release notes are ready
- The official tag uses the `vX.Y.Z` format
- The GitHub Release has been created
- If this is the first official release on `release/X.Y`, its lineage has been synced back to `main`
## Daily Maintenance Recommendations
- New features should go to `main` first
- Official releases should always be performed through `release/X.Y`
- Patch releases should always be maintained on the corresponding `release/X.Y`
- For each new `release/X.Y`, sync its lineage once after the first official release
If the current process changes, this document should be updated accordingly.
+194
View File
@@ -0,0 +1,194 @@
# PaddleOCR Release SOP
[English](./RELEASING.md)
## 适用范围
本文档用于说明 PaddleOCR 的标准发版流程。
## 版本类型
当前流程支持以下两类发布:
- `bump patch`:例如 `3.4.0 -> 3.4.1`
- `bump minor`:例如 `3.4.x -> 3.5.0`
对于 `bump major`:
- 当前流程暂不支持直接覆盖这类场景
- 如需发布大版本,需要单独讨论并设计额外流程,例如引入额外分支或新的版本准备方式
## 发版原则
- 日常开发在 `main` 分支进行
- 正式发布只在 `release/X.Y` 分支进行
- 正式标签只使用 `vX.Y.Z`
- 不在 `main` 分支打正式发布标签
## 标准发版流程
### 1. 确认发布目标
先确认本次发布属于哪一条版本线,以及目标版本号。
示例:
- 发布 `3.4.1`,对应分支为 `release/3.4`
- 发布 `3.5.0`,对应分支为 `release/3.5`
### 2. 创建或切换到 release 分支
如果该版本线尚未建立,则从 `main` 创建对应的 `release/X.Y` 分支。
如果该版本线已存在,则直接切换到该分支继续发版准备。
要求:
- 一个 minor 版本线对应一个固定的 `release/X.Y` 分支
- 该分支只承载该版本线的发布内容和补丁修复
### 3. 从 main 挑选发布内容
根据本次发布范围,从 `main` 将需要发布的提交按需 `cherry-pick` 到 `release/X.Y`,直到版本内容 ready。
要求:
- 只挑选本次发布需要的内容
- 避免把与本次发布无关的新功能带入 release 分支
- 如果 release 分支上出现专门的发布修复,也应仅限于本次发布范围
### 4. 完成发布前检查
在 `release/X.Y` 上完成发布前检查。
至少应包括:
- 当前分支正确
- 工作区干净
- 版本号符合预期
- 关键功能验证通过
- 必要的测试、构建、打包和回归通过
- 发布说明已经准备好
### 5. 打正式标签
确认版本 ready 后,在 `release/X.Y` 分支上打正式标签:
- 标签格式必须为 `vX.Y.Z`
示例:
- `v3.4.1`
- `v3.5.0`
要求:
- 标签必须打在本次正式发布对应的 release 分支上
- 不使用开发态标签作为正式发布标签
### 6. 发布 GitHub Release
在 GitHub 上基于本次正式标签创建 Release。
### 7. 更新依赖约束与发布说明
如果本次发布是新的 minor 版本首发,或本次发布涉及 PaddleX 依赖变化,则在正式标签发布前后同步完成相关更新。
至少应包括:
- 检查 `pyproject.toml` 中 `paddlex` 相关依赖约束是否与本次发布版本匹配
- 检查安装说明、升级说明和发布说明中的版本信息是否与本次发布一致
完成要求:
- `paddlex` 相关依赖约束与本次发布目标一致
- 文档中的版本信息与本次发布版本一致
### 8. 将 release 分支的 lineage 同步回 main
当一条新的 `release/X.Y` 发布线完成首个正式版本发布后,需要将该 `release/X.Y` 的 lineage 同步回 `main`。
这一步是当前流程中的固定步骤,每条新的 minor 发布线至少执行一次。
目的:
- 让 `main` 正确感知该发布线已经完成的正式版本
- 保持后续开发与发布节奏一致
要求:
- 每条新的 `release/X.Y` 在首个正式版本发布后执行一次
- 同一条 `release/X.Y` 后续如果继续发布补丁版本,通常不要求重复执行
### 9. 进入下一轮开发或补丁发布
发布完成后:
- `main` 继续进行后续开发
- `release/X.Y` 继续维护该版本线
如果后续还要发布该版本线的补丁版本:
- 继续在 `release/X.Y` 上准备补丁
- 从 `main` 按需 `cherry-pick`
- 重复执行本 SOP 中的发布步骤
## 不同 bump 类型的处理方式
### Patch 发布
适用场景:
- 修复线上问题
- 小范围兼容性修复
- 文档、依赖或稳定性补丁
处理方式:
- 在现有 `release/X.Y` 分支上继续准备内容
- 打下一个 patch 标签,例如 `v3.4.2`
### Minor 发布
适用场景:
- 开启一条新的发布线
- 发布下一阶段稳定版本,例如 `3.5.0`
处理方式:
- 从 `main` 建立新的 `release/X.Y`
- 按标准流程准备版本内容
- 打首个正式标签,例如 `v3.5.0`
- 如有需要,同步更新 `paddlex` 相关依赖约束
- 发布后将该 release 分支的 lineage 同步回 `main`
### Major 发布
当前结论:
- 暂不纳入本 SOP
- 后续需要单独讨论并设计流程
在新的方案明确之前,不建议直接套用当前 minor/patch 的做法处理 major 发布。
## 发布检查清单
每次发版前,请确认以下事项:
- 已确认目标版本号和对应 release 分支
- release 分支中的内容已经 ready
- 发布范围已经收敛
- 关键测试和回归已通过
- 发布说明已准备完成
- 正式标签格式为 `vX.Y.Z`
- GitHub Release 已创建
- 如本次是该 `release/X.Y` 的首个正式版本,发布完成后已将 lineage 同步回 `main`
## 日常维护建议
- 新功能优先进入 `main`
- 正式发布始终通过 `release/X.Y` 执行
- 补丁版本始终在对应的 `release/X.Y` 上维护
- 每条新的 `release/X.Y` 在首个正式版本发布后执行一次 lineage 同步
如当前流程发生调整,应同步更新本文档。
+21
View File
@@ -0,0 +1,21 @@
# CocoaPods
Pods/
# Xcode
PaddleOCRDemo.xcworkspace/xcuserdata/
PaddleOCRDemo.xcodeproj/xcuserdata/
PaddleOCRDemo.xcodeproj/project.xcworkspace/xcuserdata/
*.xcuserstate
DerivedData/
build/
# fetch_ios_demo_models.sh download cache
.fetch_ios_demo_models_work/
# Models — ignore all files under Models/; track only `.gitkeep` so det/, rec/, … stay in the tree
PaddleOCRDemo/Models/**
!PaddleOCRDemo/Models/*/
!PaddleOCRDemo/Models/*/.gitkeep
# Local validation reports
out/
+25
View File
@@ -0,0 +1,25 @@
PaddleOCR iOS demo — third-party notices
===============================================================================
This demo application is part of the PaddleOCR project (Apache License 2.0).
It may bundle or link third-party components in addition to the PaddleOCR
repository LICENSE. The following components are included in **source** form
in this tree:
Clipper / polyclipping (polygon clipping and offsetting)
--------------------------------------------------------------------------------------------
• Upstream: polyclipping clipper 6.4.2 (Angus Johnson)
• Bundled: `PaddleOCRDemo/ThirdParty/Clipper1/` (clipper.cpp, clipper.hpp)
• SPDX: BSL-1.0 (Boost Software License 1.0)
• Full text: `PaddleOCRDemo/ThirdParty/Clipper1/LICENSE`
CocoaPods dependencies (onnxruntime-objc, OpenCV, Yams, etc.)
-------------------------------------------------------------
• Versions and upstream packages are recorded in `Podfile.lock` after
`pod install`. Each pod is subject to its own license as published by
the respective project; consult the Pods project and upstream repos
for notices required by those licenses.
If you distribute binaries built from this demo, ensure your product’s
open-source / third-party attribution (e.g. in-app “Licenses” or
distribution packaging) satisfies your legal and policy requirements.
@@ -0,0 +1,822 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 56;
objects = {
/* Begin PBXBuildFile section */
6F50EE661821421A98371746 /* Pods_PaddleOCRDemoTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0A24555277519FE15EF10A5D /* Pods_PaddleOCRDemoTests.framework */; };
A1000001 /* PaddleOCRDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000001 /* PaddleOCRDemoApp.swift */; };
A1000002 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000002 /* ContentView.swift */; };
A1000003 /* Models in Resources */ = {isa = PBXBuildFile; fileRef = A2000006 /* Models */; };
A1000004 /* ModelConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000011 /* ModelConfig.swift */; };
A1000005 /* ORTSessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000012 /* ORTSessionManager.swift */; };
A10000F0 /* ORTProfilingBridge.mm in Sources */ = {isa = PBXBuildFile; fileRef = A20000F1 /* ORTProfilingBridge.mm */; };
A1000007 /* InferenceConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000015 /* InferenceConfig.swift */; };
A1000008 /* Preprocessing.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000016 /* Preprocessing.swift */; };
A1000011 /* ORTSessionManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000014 /* ORTSessionManagerTests.swift */; };
A1000021 /* DBPostProcess.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000021 /* DBPostProcess.swift */; };
A1000022 /* OpenCVDBBridge.mm in Sources */ = {isa = PBXBuildFile; fileRef = A2000023 /* OpenCVDBBridge.mm */; };
A1000023 /* OpenCVImageBridge.mm in Sources */ = {isa = PBXBuildFile; fileRef = A2000025 /* OpenCVImageBridge.mm */; };
A10000E1 /* clipper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A20000E1 /* clipper.cpp */; };
A10000E2 /* PDBPolygonOffsetBridge.mm in Sources */ = {isa = PBXBuildFile; fileRef = A20000E2 /* PDBPolygonOffsetBridge.mm */; };
A10000C0 /* DemoSectionChrome.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000C0 /* DemoSectionChrome.swift */; };
A1000030 /* DetectionEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000030 /* DetectionEngine.swift */; };
A1000040 /* RecPreprocessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000040 /* RecPreprocessor.swift */; };
A1000050 /* CTCDecoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000050 /* CTCDecoder.swift */; };
A1000060 /* RecognitionEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000060 /* RecognitionEngine.swift */; };
A1000070 /* OCREngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000070 /* OCREngine.swift */; };
A1000071 /* BoxSorter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000071 /* BoxSorter.swift */; };
A1000072 /* QuadTextCrop.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000072 /* QuadTextCrop.swift */; };
A1000074 /* EncodedImageCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000074 /* EncodedImageCodec.swift */; };
A1000080 /* OCRViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000080 /* OCRViewModel.swift */; };
A1000090 /* ImagePickerSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000090 /* ImagePickerSection.swift */; };
A1000091 /* SampleImages in Resources */ = {isa = PBXBuildFile; fileRef = A2000091 /* SampleImages */; };
A10000A0 /* ResultImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000A0 /* ResultImageView.swift */; };
A10000A1 /* TimingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000A1 /* TimingView.swift */; };
A10000A2 /* ResultsListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000A2 /* ResultsListView.swift */; };
A10000A3 /* ErrorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000A3 /* ErrorView.swift */; };
A10000A4 /* OCRParametersPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000A4 /* OCRParametersPanel.swift */; };
A10000A5 /* OnnxRuntimeSettingsPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000A5 /* OnnxRuntimeSettingsPanel.swift */; };
A10000A6 /* EngineSettingsSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000A6 /* EngineSettingsSheet.swift */; };
A10000B3 /* OCRParameterResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000B3 /* OCRParameterResolverTests.swift */; };
A10000C5 /* OCRBenchmarkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000C5 /* OCRBenchmarkTests.swift */; };
A10000C6 /* BenchmarkPayloads.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000C6 /* BenchmarkPayloads.swift */; };
A10000D3 /* BenchmarkFixtures.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000D3 /* BenchmarkFixtures.swift */; };
A10000C7 /* Fixtures in Resources */ = {isa = PBXBuildFile; fileRef = A20000C7 /* Fixtures */; };
A10000B1 /* OCRParameterResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000B1 /* OCRParameterResolver.swift */; };
A10000D0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A20000D0 /* Assets.xcassets */; };
A10000D1 /* Bundle+BundledImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000D1 /* Bundle+BundledImage.swift */; };
A10000D2 /* DemoAssets.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20000D2 /* DemoAssets.swift */; };
F9888FA77A2AF8AF45B50193 /* Pods_PaddleOCRDemo.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3D0FFA11A4E43E5BD0F80219 /* Pods_PaddleOCRDemo.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
A5000001 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = A3000001 /* Project object */;
proxyType = 1;
remoteGlobalIDString = A4000001;
remoteInfo = PaddleOCRDemo;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
0A24555277519FE15EF10A5D /* Pods_PaddleOCRDemoTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PaddleOCRDemoTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
3D0FFA11A4E43E5BD0F80219 /* Pods_PaddleOCRDemo.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PaddleOCRDemo.framework; sourceTree = BUILT_PRODUCTS_DIR; };
49C7CEE60686CC98BE2EEE45 /* Pods-PaddleOCRDemoTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PaddleOCRDemoTests.release.xcconfig"; path = "Target Support Files/Pods-PaddleOCRDemoTests/Pods-PaddleOCRDemoTests.release.xcconfig"; sourceTree = "<group>"; };
520BC3C496ED955BBB302DC4 /* Pods-PaddleOCRDemo.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PaddleOCRDemo.debug.xcconfig"; path = "Target Support Files/Pods-PaddleOCRDemo/Pods-PaddleOCRDemo.debug.xcconfig"; sourceTree = "<group>"; };
54F64B7C830508805D832F8A /* Pods-PaddleOCRDemo.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PaddleOCRDemo.release.xcconfig"; path = "Target Support Files/Pods-PaddleOCRDemo/Pods-PaddleOCRDemo.release.xcconfig"; sourceTree = "<group>"; };
72FF5C269BF861629F89D6B5 /* Pods-PaddleOCRDemoTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PaddleOCRDemoTests.debug.xcconfig"; path = "Target Support Files/Pods-PaddleOCRDemoTests/Pods-PaddleOCRDemoTests.debug.xcconfig"; sourceTree = "<group>"; };
A2000001 /* PaddleOCRDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PaddleOCRDemoApp.swift; sourceTree = "<group>"; };
A2000002 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
A2000003 /* PaddleOCRDemo-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "PaddleOCRDemo-Bridging-Header.h"; sourceTree = "<group>"; };
A2000004 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A2000005 /* PaddleOCRDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PaddleOCRDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
A2000006 /* Models */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models; sourceTree = "<group>"; };
A2000009 /* PaddleOCRDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PaddleOCRDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
A2000011 /* ModelConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelConfig.swift; sourceTree = "<group>"; };
A2000012 /* ORTSessionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ORTSessionManager.swift; sourceTree = "<group>"; };
A20000F0 /* ORTProfilingBridge.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ORTProfilingBridge.h; sourceTree = "<group>"; };
A20000F1 /* ORTProfilingBridge.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = ORTProfilingBridge.mm; sourceTree = "<group>"; };
A2000014 /* ORTSessionManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ORTSessionManagerTests.swift; sourceTree = "<group>"; };
A2000015 /* InferenceConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InferenceConfig.swift; sourceTree = "<group>"; };
A2000016 /* Preprocessing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Preprocessing.swift; sourceTree = "<group>"; };
A2000021 /* DBPostProcess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DBPostProcess.swift; sourceTree = "<group>"; };
A2000022 /* OpenCVDBBridge.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OpenCVDBBridge.h; sourceTree = "<group>"; };
A2000023 /* OpenCVDBBridge.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = OpenCVDBBridge.mm; sourceTree = "<group>"; };
A2000024 /* OpenCVImageBridge.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OpenCVImageBridge.h; sourceTree = "<group>"; };
A2000025 /* OpenCVImageBridge.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = OpenCVImageBridge.mm; sourceTree = "<group>"; };
A20000E1 /* clipper.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = clipper.cpp; sourceTree = "<group>"; };
A20000E2 /* PDBPolygonOffsetBridge.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = PDBPolygonOffsetBridge.mm; sourceTree = "<group>"; };
A20000E3 /* PDBPolygonOffsetBridge.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PDBPolygonOffsetBridge.h; sourceTree = "<group>"; };
A2000030 /* DetectionEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetectionEngine.swift; sourceTree = "<group>"; };
A2000040 /* RecPreprocessor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecPreprocessor.swift; sourceTree = "<group>"; };
A2000050 /* CTCDecoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CTCDecoder.swift; sourceTree = "<group>"; };
A2000060 /* RecognitionEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecognitionEngine.swift; sourceTree = "<group>"; };
A2000070 /* OCREngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OCREngine.swift; sourceTree = "<group>"; };
A2000071 /* BoxSorter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoxSorter.swift; sourceTree = "<group>"; };
A2000072 /* QuadTextCrop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuadTextCrop.swift; sourceTree = "<group>"; };
A2000074 /* EncodedImageCodec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EncodedImageCodec.swift; sourceTree = "<group>"; };
A2000080 /* OCRViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OCRViewModel.swift; sourceTree = "<group>"; };
A2000090 /* ImagePickerSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImagePickerSection.swift; sourceTree = "<group>"; };
A2000091 /* SampleImages */ = {isa = PBXFileReference; lastKnownFileType = folder; path = SampleImages; sourceTree = "<group>"; };
A20000A0 /* ResultImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResultImageView.swift; sourceTree = "<group>"; };
A20000A1 /* TimingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimingView.swift; sourceTree = "<group>"; };
A20000A2 /* ResultsListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResultsListView.swift; sourceTree = "<group>"; };
A20000A3 /* ErrorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ErrorView.swift; sourceTree = "<group>"; };
A20000A4 /* OCRParametersPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OCRParametersPanel.swift; sourceTree = "<group>"; };
A20000A5 /* OnnxRuntimeSettingsPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnnxRuntimeSettingsPanel.swift; sourceTree = "<group>"; };
A20000A6 /* EngineSettingsSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EngineSettingsSheet.swift; sourceTree = "<group>"; };
A20000B3 /* OCRParameterResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OCRParameterResolverTests.swift; sourceTree = "<group>"; };
A20000C5 /* OCRBenchmarkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OCRBenchmarkTests.swift; sourceTree = "<group>"; };
A20000C6 /* BenchmarkPayloads.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BenchmarkPayloads.swift; sourceTree = "<group>"; };
A20000D3 /* BenchmarkFixtures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BenchmarkFixtures.swift; sourceTree = "<group>"; };
A20000C7 /* Fixtures */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Fixtures; sourceTree = "<group>"; };
A20000B1 /* OCRParameterResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OCRParameterResolver.swift; sourceTree = "<group>"; };
A20000C0 /* DemoSectionChrome.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoSectionChrome.swift; sourceTree = "<group>"; };
A20000D0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
A20000D1 /* Bundle+BundledImage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Bundle+BundledImage.swift"; sourceTree = "<group>"; };
A20000D2 /* DemoAssets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoAssets.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A6000001 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
F9888FA77A2AF8AF45B50193 /* Pods_PaddleOCRDemo.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A6000002 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
6F50EE661821421A98371746 /* Pods_PaddleOCRDemoTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
2D2CDE3432BBDFC183DD82E7 /* Frameworks */ = {
isa = PBXGroup;
children = (
3D0FFA11A4E43E5BD0F80219 /* Pods_PaddleOCRDemo.framework */,
0A24555277519FE15EF10A5D /* Pods_PaddleOCRDemoTests.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
3E7A5973A61F2EB2D5542DE3 /* Pods */ = {
isa = PBXGroup;
children = (
520BC3C496ED955BBB302DC4 /* Pods-PaddleOCRDemo.debug.xcconfig */,
54F64B7C830508805D832F8A /* Pods-PaddleOCRDemo.release.xcconfig */,
72FF5C269BF861629F89D6B5 /* Pods-PaddleOCRDemoTests.debug.xcconfig */,
49C7CEE60686CC98BE2EEE45 /* Pods-PaddleOCRDemoTests.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
A7000001 = {
isa = PBXGroup;
children = (
A7000002 /* PaddleOCRDemo */,
A7000005 /* PaddleOCRDemoTests */,
A7000003 /* Products */,
3E7A5973A61F2EB2D5542DE3 /* Pods */,
2D2CDE3432BBDFC183DD82E7 /* Frameworks */,
);
sourceTree = "<group>";
};
A7000002 /* PaddleOCRDemo */ = {
isa = PBXGroup;
children = (
A7000004 /* App */,
A7000007 /* Engine */,
A7000008 /* ViewModels */,
A7000009 /* Views */,
A7000006 /* Supporting */,
A7000010 /* Resources */,
A700000D /* ThirdParty */,
A2000006 /* Models */,
);
path = PaddleOCRDemo;
sourceTree = "<group>";
};
A7000003 /* Products */ = {
isa = PBXGroup;
children = (
A2000005 /* PaddleOCRDemo.app */,
A2000009 /* PaddleOCRDemoTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
A7000004 /* App */ = {
isa = PBXGroup;
children = (
A20000D1 /* Bundle+BundledImage.swift */,
A20000D2 /* DemoAssets.swift */,
A2000001 /* PaddleOCRDemoApp.swift */,
A2000002 /* ContentView.swift */,
A20000C0 /* DemoSectionChrome.swift */,
);
path = App;
sourceTree = "<group>";
};
A7000005 /* PaddleOCRDemoTests */ = {
isa = PBXGroup;
children = (
A2000014 /* ORTSessionManagerTests.swift */,
A20000B3 /* OCRParameterResolverTests.swift */,
A20000C5 /* OCRBenchmarkTests.swift */,
A20000C6 /* BenchmarkPayloads.swift */,
A20000D3 /* BenchmarkFixtures.swift */,
A20000C7 /* Fixtures */,
);
path = PaddleOCRDemoTests;
sourceTree = "<group>";
};
A7000006 /* Supporting */ = {
isa = PBXGroup;
children = (
A2000003 /* PaddleOCRDemo-Bridging-Header.h */,
A2000004 /* Info.plist */,
);
path = Supporting;
sourceTree = "<group>";
};
A7000007 /* Engine */ = {
isa = PBXGroup;
children = (
A2000071 /* BoxSorter.swift */,
A2000050 /* CTCDecoder.swift */,
A2000021 /* DBPostProcess.swift */,
A2000022 /* OpenCVDBBridge.h */,
A2000023 /* OpenCVDBBridge.mm */,
A2000024 /* OpenCVImageBridge.h */,
A2000025 /* OpenCVImageBridge.mm */,
A20000E2 /* PDBPolygonOffsetBridge.mm */,
A20000E3 /* PDBPolygonOffsetBridge.h */,
A2000030 /* DetectionEngine.swift */,
A2000015 /* InferenceConfig.swift */,
A20000B1 /* OCRParameterResolver.swift */,
A2000011 /* ModelConfig.swift */,
A2000070 /* OCREngine.swift */,
A2000012 /* ORTSessionManager.swift */,
A20000F0 /* ORTProfilingBridge.h */,
A20000F1 /* ORTProfilingBridge.mm */,
A2000072 /* QuadTextCrop.swift */,
A2000074 /* EncodedImageCodec.swift */,
A2000016 /* Preprocessing.swift */,
A2000040 /* RecPreprocessor.swift */,
A2000060 /* RecognitionEngine.swift */,
);
path = Engine;
sourceTree = "<group>";
};
A7000008 /* ViewModels */ = {
isa = PBXGroup;
children = (
A2000080 /* OCRViewModel.swift */,
);
path = ViewModels;
sourceTree = "<group>";
};
A7000009 /* Views */ = {
isa = PBXGroup;
children = (
A20000A3 /* ErrorView.swift */,
A2000090 /* ImagePickerSection.swift */,
A20000A5 /* OnnxRuntimeSettingsPanel.swift */,
A20000A4 /* OCRParametersPanel.swift */,
A20000A6 /* EngineSettingsSheet.swift */,
A20000A0 /* ResultImageView.swift */,
A20000A2 /* ResultsListView.swift */,
A20000A1 /* TimingView.swift */,
);
path = Views;
sourceTree = "<group>";
};
A700000D /* ThirdParty */ = {
isa = PBXGroup;
children = (
A700000E /* Clipper1 */,
);
path = ThirdParty;
sourceTree = "<group>";
};
A700000E /* Clipper1 */ = {
isa = PBXGroup;
children = (
A20000E1 /* clipper.cpp */,
);
path = Clipper1;
sourceTree = "<group>";
};
A7000010 /* Resources */ = {
isa = PBXGroup;
children = (
A20000D0 /* Assets.xcassets */,
A2000091 /* SampleImages */,
);
path = Resources;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
A4000001 /* PaddleOCRDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = A9000003 /* Build configuration list for PBXNativeTarget "PaddleOCRDemo" */;
buildPhases = (
A9D5C3BAF4FDCBE19D45BCA7 /* [CP] Check Pods Manifest.lock */,
A8000001 /* Sources */,
A6000001 /* Frameworks */,
A8000003 /* Resources */,
6530B8008C9EFD4F162C3E86 /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = PaddleOCRDemo;
productName = PaddleOCRDemo;
productReference = A2000005 /* PaddleOCRDemo.app */;
productType = "com.apple.product-type.application";
};
A4000002 /* PaddleOCRDemoTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = A9000006 /* Build configuration list for PBXNativeTarget "PaddleOCRDemoTests" */;
buildPhases = (
9FD4B8CB3C3E1C27991BDE0B /* [CP] Check Pods Manifest.lock */,
A8000002 /* Sources */,
A6000002 /* Frameworks */,
A8000004 /* Resources */,
);
buildRules = (
);
dependencies = (
A5000002 /* PBXTargetDependency */,
);
name = PaddleOCRDemoTests;
productName = PaddleOCRDemoTests;
productReference = A2000009 /* PaddleOCRDemoTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A3000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1540;
LastUpgradeCheck = 2640;
TargetAttributes = {
A4000001 = {
CreatedOnToolsVersion = 15.4;
};
A4000002 = {
CreatedOnToolsVersion = 15.4;
TestTargetID = A4000001;
};
};
};
buildConfigurationList = A9000001 /* Build configuration list for PBXProject "PaddleOCRDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = A7000001;
productRefGroup = A7000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A4000001 /* PaddleOCRDemo */,
A4000002 /* PaddleOCRDemoTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
A8000003 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A10000D0 /* Assets.xcassets in Resources */,
A1000003 /* Models in Resources */,
A1000091 /* SampleImages in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A8000004 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A10000C7 /* Fixtures in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
6530B8008C9EFD4F162C3E86 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-PaddleOCRDemo/Pods-PaddleOCRDemo-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-PaddleOCRDemo/Pods-PaddleOCRDemo-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-PaddleOCRDemo/Pods-PaddleOCRDemo-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
9FD4B8CB3C3E1C27991BDE0B /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-PaddleOCRDemoTests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
A9D5C3BAF4FDCBE19D45BCA7 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-PaddleOCRDemo-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
A8000001 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A1000001 /* PaddleOCRDemoApp.swift in Sources */,
A10000D1 /* Bundle+BundledImage.swift in Sources */,
A10000D2 /* DemoAssets.swift in Sources */,
A1000002 /* ContentView.swift in Sources */,
A10000C0 /* DemoSectionChrome.swift in Sources */,
A1000021 /* DBPostProcess.swift in Sources */,
A1000022 /* OpenCVDBBridge.mm in Sources */,
A1000023 /* OpenCVImageBridge.mm in Sources */,
A10000E1 /* clipper.cpp in Sources */,
A10000E2 /* PDBPolygonOffsetBridge.mm in Sources */,
A1000030 /* DetectionEngine.swift in Sources */,
A1000004 /* ModelConfig.swift in Sources */,
A1000005 /* ORTSessionManager.swift in Sources */,
A10000F0 /* ORTProfilingBridge.mm in Sources */,
A1000007 /* InferenceConfig.swift in Sources */,
A10000B1 /* OCRParameterResolver.swift in Sources */,
A1000008 /* Preprocessing.swift in Sources */,
A1000040 /* RecPreprocessor.swift in Sources */,
A1000050 /* CTCDecoder.swift in Sources */,
A1000060 /* RecognitionEngine.swift in Sources */,
A1000070 /* OCREngine.swift in Sources */,
A1000071 /* BoxSorter.swift in Sources */,
A1000072 /* QuadTextCrop.swift in Sources */,
A1000074 /* EncodedImageCodec.swift in Sources */,
A1000080 /* OCRViewModel.swift in Sources */,
A1000090 /* ImagePickerSection.swift in Sources */,
A10000A0 /* ResultImageView.swift in Sources */,
A10000A1 /* TimingView.swift in Sources */,
A10000A2 /* ResultsListView.swift in Sources */,
A10000A3 /* ErrorView.swift in Sources */,
A10000A5 /* OnnxRuntimeSettingsPanel.swift in Sources */,
A10000A6 /* EngineSettingsSheet.swift in Sources */,
A10000A4 /* OCRParametersPanel.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A8000002 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A1000011 /* ORTSessionManagerTests.swift in Sources */,
A10000B3 /* OCRParameterResolverTests.swift in Sources */,
A10000C5 /* OCRBenchmarkTests.swift in Sources */,
A10000C6 /* BenchmarkPayloads.swift in Sources */,
A10000D3 /* BenchmarkFixtures.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
A5000002 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = A4000001 /* PaddleOCRDemo */;
targetProxy = A5000001 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
AA000001 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
AA000002 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
AA000003 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 520BC3C496ED955BBB302DC4 /* Pods-PaddleOCRDemo.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 76MLN428C9;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = PaddleOCRDemo/Supporting/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "PaddleOCR";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-Wl,-no_warn_duplicate_libraries",
);
PRODUCT_BUNDLE_IDENTIFIER = com.paddleocr.demo;
PRODUCT_NAME = "$(TARGET_NAME)";
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO;
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OBJC_BRIDGING_HEADER = "PaddleOCRDemo/Supporting/PaddleOCRDemo-Bridging-Header.h";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
USER_HEADER_SEARCH_PATHS = (
"$(inherited)",
"$(SRCROOT)/PaddleOCRDemo/Engine",
"$(SRCROOT)/PaddleOCRDemo/ThirdParty/Clipper1",
"$(PODS_ROOT)/onnxruntime-objc/objectivec",
"$(PODS_ROOT)/onnxruntime-objc/objectivec/include",
);
};
name = Debug;
};
AA000004 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 54F64B7C830508805D832F8A /* Pods-PaddleOCRDemo.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 76MLN428C9;
ENABLE_TESTABILITY = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = PaddleOCRDemo/Supporting/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "PaddleOCR";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-Wl,-no_warn_duplicate_libraries",
);
PRODUCT_BUNDLE_IDENTIFIER = com.paddleocr.demo;
PRODUCT_NAME = "$(TARGET_NAME)";
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO;
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OBJC_BRIDGING_HEADER = "PaddleOCRDemo/Supporting/PaddleOCRDemo-Bridging-Header.h";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
USER_HEADER_SEARCH_PATHS = (
"$(inherited)",
"$(SRCROOT)/PaddleOCRDemo/Engine",
"$(SRCROOT)/PaddleOCRDemo/ThirdParty/Clipper1",
"$(PODS_ROOT)/onnxruntime-objc/objectivec",
"$(PODS_ROOT)/onnxruntime-objc/objectivec/include",
);
};
name = Release;
};
AA000005 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 72FF5C269BF861629F89D6B5 /* Pods-PaddleOCRDemoTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 76MLN428C9;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.paddleocr.demo.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/PaddleOCRDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/PaddleOCRDemo";
};
name = Debug;
};
AA000006 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 49C7CEE60686CC98BE2EEE45 /* Pods-PaddleOCRDemoTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 76MLN428C9;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.paddleocr.demo.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/PaddleOCRDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/PaddleOCRDemo";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A9000001 /* Build configuration list for PBXProject "PaddleOCRDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
AA000001 /* Debug */,
AA000002 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A9000003 /* Build configuration list for PBXNativeTarget "PaddleOCRDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
AA000003 /* Debug */,
AA000004 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A9000006 /* Build configuration list for PBXNativeTarget "PaddleOCRDemoTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
AA000005 /* Debug */,
AA000006 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = A3000001 /* Project object */;
}
@@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2640"
version = "1.8">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A4000001"
BuildableName = "PaddleOCRDemo.app"
BlueprintName = "PaddleOCRDemo"
ReferencedContainer = "container:PaddleOCRDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A4000002"
BuildableName = "PaddleOCRDemoTests.xctest"
BlueprintName = "PaddleOCRDemoTests"
ReferencedContainer = "container:PaddleOCRDemo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = ""
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
reuseRunningArtifactsWhenBuildingTests = "YES"
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A4000001"
BuildableName = "PaddleOCRDemo.app"
BlueprintName = "PaddleOCRDemo"
ReferencedContainer = "container:PaddleOCRDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
reuseRunningArtifactsWhenBuildingTests = "YES"
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A4000001"
BuildableName = "PaddleOCRDemo.app"
BlueprintName = "PaddleOCRDemo"
ReferencedContainer = "container:PaddleOCRDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:PaddleOCRDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,48 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
extension Bundle {
/// Raster extensions tried when resolving a bundled image by stem, or after an explicit extension misses.
static let bundledRasterImageExtensions: [String] = [
"jpg", "jpeg", "png", "heic", "heif", "webp", "tiff", "tif", "bmp", "gif",
]
/// Resolves a filesystem path for an image under `subdirectory`.
///
/// `name` may be a resource stem (e.g. `photo`) or include a suffix (e.g. `photo.jpg`).
/// Extensions are matched case-insensitively when provided; otherwise each entry in
/// ``bundledRasterImageExtensions`` is tried in order.
func path(forBundledImageNamed name: String, subdirectory: String) -> String? {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
let ns = trimmed as NSString
let extGiven = ns.pathExtension.lowercased()
let stem = ns.deletingPathExtension
let resourceStem = stem.isEmpty ? trimmed : stem
if !extGiven.isEmpty {
if let path = path(forResource: resourceStem, ofType: extGiven, inDirectory: subdirectory) {
return path
}
}
for ext in Self.bundledRasterImageExtensions where ext != extGiven {
if let path = path(forResource: resourceStem, ofType: ext, inDirectory: subdirectory) {
return path
}
}
return nil
}
}
@@ -0,0 +1,321 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import PhotosUI
import SwiftUI
/// Root view: routes `AppState` and lays out **input (photo/sample)** vs **output (preview + text)**; engine tuning lives in ``EngineSettingsSheet``.
struct ContentView: View {
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
@StateObject private var viewModel = OCRViewModel()
@State private var selectedItem: PhotosPickerItem?
@State private var showEngineSettings = false
private var navigationTitleDisplayMode: NavigationBarItem.TitleDisplayMode {
switch viewModel.state {
case .ready: return .large
case .error(let err) where !err.isModelError: return .large
default: return .inline
}
}
private var showsAdvancedToolbarItem: Bool {
switch viewModel.state {
case .loadingModels, .processing: return false
case .ready, .results, .error: return true
}
}
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 0) {
contentForState
}
.padding(.horizontal, 20)
.padding(.vertical, 20)
}
.background(Color(.systemGroupedBackground))
.navigationTitle("PaddleOCR Demo")
.navigationBarTitleDisplayMode(navigationTitleDisplayMode)
.toolbar {
if showsAdvancedToolbarItem {
ToolbarItem(placement: .topBarTrailing) {
Button {
showEngineSettings = true
} label: {
Image(systemName: "slider.horizontal.3")
}
.accessibilityLabel("Advanced settings")
}
}
}
}
.sheet(isPresented: $showEngineSettings) {
EngineSettingsSheet(viewModel: viewModel)
}
.task {
await viewModel.loadModels()
}
.onChange(of: selectedItem) { newItem in
guard let item = newItem else { return }
Task {
guard let data = try? await item.loadTransferable(type: Data.self),
let uiImage = UIImage(data: data) else {
viewModel.reportImageLoadFailed()
return
}
selectedItem = nil
await viewModel.processImage(uiImage)
}
}
}
private func imageInputSection(title: String, subtitle: String) -> some View {
VStack(alignment: .leading, spacing: 10) {
DemoSectionHeader(title: title, subtitle: subtitle)
ImagePickerSection(
selectedItem: $selectedItem,
sampleImageNames: viewModel.sampleImageNames,
onSampleSelected: { name in
Task { await viewModel.selectSampleImage(named: name) }
}
)
}
}
// MARK: - State Router
@ViewBuilder
private var contentForState: some View {
switch viewModel.state {
case .loadingModels:
loadingModelsView
case .ready:
readyView
case .processing(let image):
processingView(image: image)
case .results(let result, let image, _):
resultsView(result: result, image: image)
case .error(let error):
errorView(error: error)
}
}
// MARK: - Loading Models
private var loadingModelsView: some View {
VStack(spacing: 16) {
ProgressView()
.scaleEffect(1.3)
.tint(.accentColor)
Text("Loading models")
.font(.title3.weight(.semibold))
Text("Preparing detection and recognition…")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
.frame(maxWidth: .infinity)
.padding(.top, 72)
.padding(.bottom, 40)
}
// MARK: - Ready
private var readyView: some View {
VStack(spacing: 22) {
statusPill(icon: "checkmark.circle.fill", tint: .green) {
VStack(alignment: .leading, spacing: 4) {
Text("Ready")
.font(.title3.weight(.semibold))
Text("Choose a photo or open a sample. Engine and OCR tuning are under Advanced in the toolbar.")
.font(.subheadline)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
imageInputSection(
title: "Image",
subtitle: "Choose from your library or a bundled sample."
)
}
}
// MARK: - Processing
private func processingView(image: UIImage) -> some View {
VStack(alignment: .leading, spacing: 16) {
Text("Running OCR")
.font(.title3.weight(.semibold))
Text("Hold on — detection and recognition are in progress.")
.font(.subheadline)
.foregroundStyle(.secondary)
ZStack {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxHeight: 360)
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(.ultraThinMaterial)
VStack(spacing: 10) {
ProgressView()
.scaleEffect(1.25)
.tint(.accentColor)
Text("Working…")
.font(.headline)
}
}
.frame(maxWidth: .infinity)
}
}
// MARK: - Results
private func resultsView(result: OCRRunResult, image: UIImage) -> some View {
// Only use two columns when explicitly regular (e.g. iPad); treat nil as compact.
let isCompact = horizontalSizeClass != .regular
return VStack(spacing: 22) {
if isCompact {
previewBlock(result: result, image: image)
TimingView(result: result)
.padding(.vertical, 4)
} else {
TimingView(result: result)
.padding(.vertical, 4)
HStack(alignment: .top, spacing: 16) {
previewBlock(result: result, image: image)
.frame(maxWidth: .infinity)
.layoutPriority(1)
resultsListBlock(result: result)
.frame(minWidth: 280, maxWidth: .infinity)
}
}
if isCompact {
resultsListBlock(result: result)
}
imageInputSection(
title: "New image",
subtitle: "Choose another photo or sample. Re-run uses the current image and OCR parameters."
)
rerunOCRButton()
}
}
@ViewBuilder
private func rerunOCRButton() -> some View {
if viewModel.hasPendingOcrChanges {
Button {
Task { await viewModel.rerunOCR() }
} label: {
Label("Re-run OCR on this image", systemImage: "arrow.clockwise.circle.fill")
.frame(maxWidth: .infinity)
.padding(.vertical, 4)
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
} else {
Button {
Task { await viewModel.rerunOCR() }
} label: {
Label("Re-run OCR on this image", systemImage: "arrow.clockwise.circle.fill")
.frame(maxWidth: .infinity)
.padding(.vertical, 4)
}
.buttonStyle(.bordered)
.controlSize(.large)
}
}
private func previewBlock(result: OCRRunResult, image: UIImage) -> some View {
VStack(alignment: .leading, spacing: 10) {
DemoSectionHeader(
title: "Preview",
subtitle: "Accent overlay shows each detected text region."
)
DemoCard {
ResultImageView(image: image, results: result.results)
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
}
}
}
private func resultsListBlock(result: OCRRunResult) -> some View {
VStack(alignment: .leading, spacing: 10) {
DemoSectionHeader(title: "Results", subtitle: nil)
DemoCard {
ResultsListView(
results: result.results,
copiedFeedback: viewModel.copiedFeedback,
onCopy: { viewModel.copyResultsToClipboard() }
)
}
}
}
// MARK: - Error
private func errorView(error: AppError) -> some View {
VStack(spacing: 22) {
ErrorView(error: error, onRetry: {
Task { await viewModel.retry() }
})
if !error.isModelError {
VStack(alignment: .leading, spacing: 10) {
DemoSectionHeader(title: "Try another image", subtitle: nil)
ImagePickerSection(
selectedItem: $selectedItem,
sampleImageNames: viewModel.sampleImageNames,
onSampleSelected: { name in
Task { await viewModel.selectSampleImage(named: name) }
}
)
}
}
}
.padding(.top, 24)
}
// MARK: - Small chrome
private func statusPill<Content: View>(icon: String, tint: Color, @ViewBuilder content: () -> Content) -> some View {
HStack(alignment: .top, spacing: 14) {
Image(systemName: icon)
.font(.system(size: 28))
.foregroundStyle(tint)
.symbolRenderingMode(.hierarchical)
content()
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(16)
.frame(maxWidth: .infinity, alignment: .leading)
.background {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(Color(.secondarySystemGroupedBackground))
}
.overlay {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(Color(.separator).opacity(0.35), lineWidth: 0.5)
}
}
}
@@ -0,0 +1,21 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Built-in demo images (bundle resource stems).
enum DemoAssets {
/// Default bundled sample for the image picker.
static let defaultSampleImageStem: String = "general_ocr_002"
}
@@ -0,0 +1,62 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
// MARK: - Section chrome (shared by ContentView + panels)
/// Vertical section title + optional subtitle for scan-friendly hierarchy.
struct DemoSectionHeader: View {
let title: String
var subtitle: String?
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(title)
.font(.footnote.weight(.semibold))
.foregroundStyle(.secondary)
.textCase(.uppercase)
.tracking(0.4)
if let subtitle {
Text(subtitle)
.font(.subheadline)
.foregroundStyle(.secondary)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
/// Grouped card matching system settings style.
struct DemoCard<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
.padding(16)
.frame(maxWidth: .infinity, alignment: .leading)
.background {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(Color(.secondarySystemGroupedBackground))
}
.overlay {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(Color(.separator).opacity(0.35), lineWidth: 0.5)
}
}
}
@@ -0,0 +1,24 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
@main
struct PaddleOCRDemoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
@@ -0,0 +1,72 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
// MARK: - BoxSorter
/// Sorts detection boxes in natural reading order: top-to-bottom, then
/// left-to-right within the same text line.
///
/// Two-pass: sort by top-left (y then x), then swap same-line neighbors when
/// the y-gap is below `yThreshold` but x is out of order.
struct BoxSorter {
/// Y-coordinate threshold for same-line detection. Boxes whose top-left y
/// coordinates differ by less than this value are considered on the same line
/// and sorted left-to-right. Default: 10 pixels.
static let yThreshold: Int32 = 10
/// Sort detection boxes in reading order: top-to-bottom, then left-to-right
/// within the same line (defined by yThreshold).
///
/// Algorithm:
/// 1. Sort all boxes by top-left corner: first by y, then by x.
/// 2. Insertion-sort pass: for each box, walk backward and swap with the
/// previous box if they are on the same line (y-difference < 10) and
/// the current box's x is smaller.
///
/// - Parameter boxes: Unordered detection boxes from DBPostProcessor.
/// - Returns: Boxes sorted in reading order.
static func sortInReadingOrder(_ boxes: [DetectionBox]) -> [DetectionBox] {
guard boxes.count > 1 else { return boxes }
// Step 1: Sort by top-left point -- first by y, then by x
var sorted = boxes.sorted { a, b in
let ay = a.points[0][1], ax = a.points[0][0]
let by = b.points[0][1], bx = b.points[0][0]
if ay != by { return ay < by }
return ax < bx
}
// Step 2: Backward insertion sort for same-line boxes
for i in 0..<(sorted.count - 1) {
var j = i
while j >= 0 {
let nextY = sorted[j + 1].points[0][1]
let currY = sorted[j].points[0][1]
let nextX = sorted[j + 1].points[0][0]
let currX = sorted[j].points[0][0]
if abs(nextY - currY) < yThreshold && nextX < currX {
sorted.swapAt(j, j + 1)
j -= 1
} else {
break
}
}
}
return sorted
}
}
@@ -0,0 +1,199 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
// MARK: - Errors
enum CTCDecoderError: LocalizedError {
case emptyDictionary
case invalidOutputShape([Int])
var errorDescription: String? {
switch self {
case .emptyDictionary:
return "Character dictionary is empty"
case .invalidOutputShape(let shape):
return "Invalid recognition output shape: \(shape), expected [1, T, C]"
}
}
}
// MARK: - Recognition Result
/// A single text recognition result from CTC decoding.
struct RecognitionResult {
/// The decoded text string.
let text: String
/// Average confidence across all decoded characters (0.0 to 1.0).
let confidence: Float
}
// MARK: - CTCDecoder
/// CTC label decoding for recognition output
///
/// Greedy CTC decoding with blank index 0 and duplicate collapse.
/// Per timestep: take the best class and its score, then merge duplicates and drop blanks,
/// then average the kept scores. Logits need not be softmax probabilities;
/// `max` over the class dimension is used for confidence on exported logits.
///
/// The CTC (Connectionist Temporal Classification) decoding algorithm:
/// 1. Argmax across the class dimension to get per-timestep predicted indices
/// 2. Max across the class dimension to get per-timestep prediction probabilities
/// 3. Remove consecutive duplicate indices (CTC merge rule)
/// 4. Remove blank tokens (index 0)
/// 5. Map remaining indices to characters via the dictionary
/// 6. Confidence = mean of probabilities at selected positions
///
struct CTCDecoder {
private let characters: [String]
/// The blank token index (always 0 for CTC).
private let blankIndex: Int = 0
/// Creates a CTCDecoder from a recognition model's InferenceConfig.
///
/// Reads `character_dict` from the model config file and prepends the blank token.
///
/// - Parameter config: A parsed InferenceConfig from the recognition model's config file.
/// - Throws: `CTCDecoderError.emptyDictionary` if no character dict is found.
init(config: InferenceConfig) throws {
guard let dict = config.postProcess.characterDict, !dict.isEmpty else {
throw CTCDecoderError.emptyDictionary
}
// Build character list: dict from config, trailing space (default-on), blank at index 0.
var chars = ["blank"]
chars.append(contentsOf: dict)
chars.append(" ")
self.characters = chars
}
/// Decodes the raw recognition model output into text with confidence.
///
/// The output tensor has shape `[1, T, C]` where:
/// - T = number of timesteps (sequence length)
/// - C = number of classes (character vocabulary size + 1 for blank)
///
/// - Parameters:
/// - outputData: Flat float32 array of the model output.
/// - outputShape: Shape of the output tensor, expected `[1, T, C]`.
/// - Returns: A `RecognitionResult` with decoded text and confidence score.
func decode(outputData: [Float], outputShape: [Int]) throws -> RecognitionResult {
guard outputShape.count == 3, outputShape[0] == 1 else {
throw CTCDecoderError.invalidOutputShape(outputShape)
}
let timesteps = outputShape[1]
let numClasses = outputShape[2]
// Step 1 & 2: Argmax and max across the class dimension for each timestep
var predIndices = [Int](repeating: 0, count: timesteps)
var predProbs = [Float](repeating: 0, count: timesteps)
for t in 0..<timesteps {
let offset = t * numClasses
var maxVal: Float = outputData[offset]
var maxIdx = 0
for c in 1..<numClasses {
let val = outputData[offset + c]
if val > maxVal {
maxVal = val
maxIdx = c
}
}
predIndices[t] = maxIdx
predProbs[t] = maxVal
}
// Step 3: Build selection mask
// - Remove consecutive duplicates (keep first of each run)
// - Remove blank tokens (index 0)
//
// Drop consecutive duplicate indices, then drop blank (0).
var selection = [Bool](repeating: true, count: timesteps)
// Remove consecutive duplicates
for t in 1..<timesteps {
if predIndices[t] == predIndices[t - 1] {
selection[t] = false
}
}
// Remove blank tokens
for t in 0..<timesteps {
if predIndices[t] == blankIndex {
selection[t] = false
}
}
// Step 4: Collect selected characters and their probabilities
var charList: [String] = []
var confList: [Float] = []
for t in 0..<timesteps {
if selection[t] {
let idx = predIndices[t]
if idx < characters.count {
charList.append(characters[idx])
}
confList.append(predProbs[t])
}
}
// Step 5: Join characters into text
let text = charList.joined()
// Step 6: Compute mean confidence
// Mean probability over kept timesteps; 0 if none kept.
let confidence: Float
if confList.isEmpty {
confidence = 0
} else {
confidence = confList.reduce(0, +) / Float(confList.count)
}
return RecognitionResult(text: text, confidence: confidence)
}
/// Decodes a batched output tensor with shape `[N, T, C]`.
func decodeBatch(outputData: [Float], outputShape: [Int]) throws -> [RecognitionResult] {
guard outputShape.count == 3 else {
throw CTCDecoderError.invalidOutputShape(outputShape)
}
let batchCount = outputShape[0]
let timesteps = outputShape[1]
let numClasses = outputShape[2]
guard batchCount >= 1, timesteps >= 1, numClasses >= 1 else {
throw CTCDecoderError.invalidOutputShape(outputShape)
}
let rowElements = timesteps * numClasses
let expected = batchCount * rowElements
guard outputData.count == expected else {
throw CTCDecoderError.invalidOutputShape(outputShape)
}
var results: [RecognitionResult] = []
results.reserveCapacity(batchCount)
for b in 0..<batchCount {
let start = b * rowElements
let slice = Array(outputData[start..<(start + rowElements)])
let one = try decode(outputData: slice, outputShape: [1, timesteps, numClasses])
results.append(one)
}
return results
}
}
@@ -0,0 +1,250 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import CoreGraphics
// MARK: - Detection Result
/// A detected text region with its bounding quadrilateral and confidence score.
struct DetectionBox {
/// Four corner points of the bounding quadrilateral, each as [x, y].
/// Order: top-left, top-right, bottom-right, bottom-left (`getMiniBoxes` / min-area rect).
let points: [[Int32]]
/// Confidence score from `boxScoreFast` (mean probability in the box region).
let score: Float
}
// MARK: - DBPostProcessor
/// DB (Differentiable Binarization) text detection postprocessor.
///
/// Maps raw model output probability map to
/// bounding polygons (threshold → contours → min-area quads → score filter → unclip → scale).
///
/// Steps: threshold → contours → min-area quads → box score → polygon offset (unclip) → scale to original size.
///
struct DBPostProcessor {
/// Binary threshold for the probability map (pixels above this are foreground).
let thresh: Float
/// Minimum box confidence score to keep a detection.
let boxThresh: Float
/// Maximum number of contours to evaluate.
let maxCandidates: Int
/// Expansion ratio for polygon offset (unclip step).
let unclipRatio: Float
/// Minimum side length of a bounding box to be kept (pixels in probability map space).
let minSize: Float = 3.0
/// Score mode: only `"fast"` is implemented (`"slow"` is not supported).
let scoreMode: String = "fast"
// MARK: - Initializers
/// Initialize with explicit parameters.
init(thresh: Float = 0.3, boxThresh: Float = 0.6, maxCandidates: Int = 1000, unclipRatio: Float = 1.5) {
self.thresh = thresh
self.boxThresh = boxThresh
self.maxCandidates = maxCandidates
self.unclipRatio = unclipRatio
}
/// Initialize from a parsed ``PostProcessConfig`.
init(config: PostProcessConfig) {
self.thresh = config.thresh
self.boxThresh = config.boxThresh
self.maxCandidates = config.maxCandidates
self.unclipRatio = config.unclipRatio
}
// MARK: - Public API
/// Process raw ORT detection output into bounding polygons.
///
/// - Parameters:
/// - outputTensor: Raw float output from ONNX Runtime, shape [1, 1, H, W].
/// - tensorHeight: Height of the output tensor (H).
/// - tensorWidth: Width of the output tensor (W).
/// - originalWidth: Width of the original input image.
/// - originalHeight: Height of the original input image.
/// - Returns: Array of detected text boxes with confidence scores.
func process(
outputTensor: [Float],
tensorHeight: Int,
tensorWidth: Int,
originalWidth: Int,
originalHeight: Int
) -> [DetectionBox] {
// 1. Extract probability map: pred[0, 0, :, :] from shape [1, 1, H, W]
let mapSize = tensorHeight * tensorWidth
let pred: [Float]
if outputTensor.count >= mapSize {
pred = Array(outputTensor.prefix(mapSize))
} else {
return []
}
// 2. Binary threshold: create mask where prob > thresh
var binaryMask = [UInt8](repeating: 0, count: mapSize)
for i in 0..<mapSize {
binaryMask[i] = pred[i] > thresh ? 1 : 0
}
// 3. Find contours on the binary mask
let contours = findContours(
binaryMask: binaryMask,
width: tensorWidth,
height: tensorHeight
)
// 4. Process each contour
let numContours = min(contours.count, maxCandidates)
var results: [DetectionBox] = []
for i in 0..<numContours {
let contour = contours[i]
// 4a. Get minimum area bounding rectangle
guard let (miniBox, sside) = getMiniBoxes(contour: contour) else {
continue
}
if sside < minSize {
continue
}
// 4b. Score the box using fast mode
let points = miniBox.map { [$0.x, $0.y] }
let score = boxScoreFast(
pred: pred,
predWidth: tensorWidth,
predHeight: tensorHeight,
box: points
)
if boxThresh > score {
continue
}
// 4c. Expand polygon (unclip) via integer-grid offset.
let nsMini = miniBox.map { NSValue(cgPoint: CGPoint(x: CGFloat($0.x), y: CGFloat($0.y))) }
let area = Double(PDBOpenCVDBBridge.contourArea(fromPoints: nsMini))
let length = Double(PDBOpenCVDBBridge.arcLength(fromPoints: nsMini, closed: true))
guard length > 0 else { continue }
let distance = area * Double(unclipRatio) / length
let rings = PDBPolygonOffsetBridge.inflateClosedPolygon(with: nsMini, distance: distance) as [[NSValue]]
guard rings.count == 1 else {
continue
}
let firstRing = rings[0]
// 4d. Second getMiniBoxes on the expanded polygon
let expandedFloats = firstRing.map { FloatPoint(x: Float($0.cgPointValue.x), y: Float($0.cgPointValue.y)) }
guard let (finalBox, finalSside) = getMiniBoxes(contour: expandedFloats) else {
continue
}
if finalSside < minSize + 2 {
continue
}
// 4e. Scale to original image dimensions
let w = Float(tensorWidth)
let h = Float(tensorHeight)
let dw = Float(originalWidth)
let dh = Float(originalHeight)
var scaledPoints: [[Int32]] = []
for pt in finalBox {
let sx = Int32(min(max((pt.x / w * dw).rounded(), 0), dw))
let sy = Int32(min(max((pt.y / h * dh).rounded(), 0), dh))
scaledPoints.append([sx, sy])
}
results.append(DetectionBox(points: scaledPoints, score: score))
}
return results
}
}
// MARK: - Internal Point Type
/// Float 2D point for `DBPostProcessor` geometry helpers.
internal struct FloatPoint {
var x: Float
var y: Float
}
// MARK: - OpenCV (CocoaPods OpenCV 4.3.x)
extension DBPostProcessor {
/// Foreground pixels as 255 on an 8-bit mask; runs `findContours` with `RETR_LIST` and `CHAIN_APPROX_SIMPLE`.
func findContours(binaryMask: [UInt8], width: Int, height: Int) -> [[FloatPoint]] {
let data = Data(binaryMask)
let raw = PDBOpenCVDBBridge.findContours(
binaryMask: data,
width: width,
height: height,
maxCandidates: maxCandidates
)
return raw.map { contour in
contour.map { v in
let p = v.cgPointValue
return FloatPoint(x: Float(p.x), y: Float(p.y))
}
}
}
/// Minimum-area rectangle: `minAreaRect` on contour points, `boxPoints` for corners, then TL/TR/BR/BL ordering.
func getMiniBoxes(contour: [FloatPoint]) -> (box: [FloatPoint], minSide: Float)? {
guard contour.count >= 2 else { return nil }
let values = contour.map { NSValue(cgPoint: CGPoint(x: CGFloat($0.x), y: CGFloat($0.y))) }
guard let result = PDBOpenCVDBBridge.miniBox(fromPoints: values) else { return nil }
let corners = result.corners.map { v in
let p = v.cgPointValue
return FloatPoint(x: Float(p.x), y: Float(p.y))
}
return (corners, result.minSide)
}
}
// MARK: - Box Scoring
extension DBPostProcessor {
/// Compute the mean probability score within a box region of the probability map.
///
/// Mean probability inside the quad: `fillPoly` mask on the score map, then `mean` over the masked region.
func boxScoreFast(
pred: [Float],
predWidth: Int,
predHeight: Int,
box: [[Float]]
) -> Float {
let predData = pred.withUnsafeBufferPointer { Data(buffer: $0) }
let boxNS: [[NSNumber]] = box.map { [NSNumber(value: $0[0]), NSNumber(value: $0[1])] }
return PDBOpenCVImageBridge.meanPredInQuad(
predData,
width: predWidth,
height: predHeight,
box: boxNS
)
}
}
@@ -0,0 +1,168 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CoreGraphics
import Foundation
// MARK: - Detection Result
/// The result of running text detection on an image.
///
/// Contains the detected text boxes and per-stage timing metrics for performance analysis.
struct DetectionResult {
/// Detected text region bounding polygons with confidence scores.
let boxes: [DetectionBox]
/// Seconds spent in preprocessing (resize, normalize, HWC-to-CHW).
let preprocessTime: TimeInterval
/// Seconds spent in ONNX Runtime inference.
let inferenceTime: TimeInterval
/// Seconds spent in DB postprocessing (threshold, contours, polygon offset / unclip).
let postprocessTime: TimeInterval
/// Total detection time (preprocess + inference + postprocess).
let totalTime: TimeInterval
/// Detection model input tensor shape, e.g. [1, 3, H, W].
let inputTensorShape: [Int]
}
// MARK: - Detection Engine Errors
enum DetectionEngineError: LocalizedError {
case noOutputTensor
case unexpectedOutputShape([Int])
var errorDescription: String? {
switch self {
case .noOutputTensor:
return "Detection model produced no output tensor"
case .unexpectedOutputShape(let shape):
return "Unexpected detection output shape: \(shape), expected [1, 1, H, W]"
}
}
}
// MARK: - DetectionEngine
/// Orchestrates text detection: CGImage → preprocess → ORT inference → postprocess.
///
/// This is the integration layer that composes `DetPreprocessor`, `ORTSessionManager`, and
/// `DBPostProcessor` into a single callable unit.
///
/// Usage:
/// ```swift
/// let engine = try DetectionEngine(sessionManager: manager)
/// let result = try await engine.detect(cgImage)
/// print("Found \(result.boxes.count) text regions in \(result.totalTime)s")
/// ```
class DetectionEngine {
private let sessionManager: ORTSessionManager
private let preprocessor: DetPreprocessor
private(set) var modelConfig: InferenceConfig
/// Initialize with an existing ORTSessionManager (models must already be loaded).
///
/// Loads the detection model config file from the bundle to configure
/// the preprocessor and postprocessor.
///
/// - Parameter sessionManager: A loaded ORTSessionManager with detection model ready.
/// - Throws: If the model config cannot be loaded or required fields are missing.
init(sessionManager: ORTSessionManager) throws {
self.sessionManager = sessionManager
// Load detection model config
let detPaths = try ModelConfig.detection()
let cfg = try InferenceConfig.load(from: detPaths.configPath)
self.modelConfig = cfg
self.preprocessor = try DetPreprocessor(config: cfg)
}
private func makePostProcessor(effective: EffectiveOCRParams) -> DBPostProcessor {
DBPostProcessor(
thresh: effective.detThresh,
boxThresh: effective.detBoxThresh,
maxCandidates: modelConfig.postProcess.maxCandidates,
unclipRatio: effective.detUnclipRatio
)
}
/// Run detection on a CGImage, returning bounding polygons with confidence scores.
///
/// Steps: DetResizeForTest → NormalizeImage → ToCHW → ORT inference → DBPostProcess
///
/// - Parameters:
/// - image: The input image to detect text regions in.
/// - runtimeParams: Detection postprocess / resize overrides (see ``OCRRuntimeParams``).
/// - Returns: A `DetectionResult` with boxes and per-stage timing metrics.
func detect(_ image: CGImage, runtimeParams: OCRRuntimeParams = .noOverrides) async throws -> DetectionResult {
let eff = OCRParameterResolver.effective(modelConfig: modelConfig, runtime: runtimeParams)
return try await detect(effective: eff) {
try preprocessor.preprocess(image, detResize: eff.detResize)
}
}
private func detect(
effective: EffectiveOCRParams,
preprocess: () throws -> PreprocessResult
) async throws -> DetectionResult {
let postprocessor = makePostProcessor(effective: effective)
// Step 1: Preprocess
let preprocessStart = CFAbsoluteTimeGetCurrent()
let preprocessed = try preprocess()
let preprocessTime = CFAbsoluteTimeGetCurrent() - preprocessStart
// Step 2: Run ORT inference
let inferenceStart = CFAbsoluteTimeGetCurrent()
let outputs = try await sessionManager.runDetection(
inputData: preprocessed.tensorData,
shape: preprocessed.tensorShape
)
let inferenceTime = CFAbsoluteTimeGetCurrent() - inferenceStart
// Step 3: Extract the probability map from ORT output
// The det model outputs a single tensor with shape [1, 1, H, W]
guard let firstOutput = outputs.values.first else {
throw DetectionEngineError.noOutputTensor
}
let outputData = firstOutput.data
let outputShape = firstOutput.shape
// Output shape should be [1, 1, H, W]
guard outputShape.count == 4 else {
throw DetectionEngineError.unexpectedOutputShape(outputShape)
}
let tensorHeight = outputShape[2]
let tensorWidth = outputShape[3]
// Step 4: Postprocess
let postprocessStart = CFAbsoluteTimeGetCurrent()
let boxes = postprocessor.process(
outputTensor: outputData,
tensorHeight: tensorHeight,
tensorWidth: tensorWidth,
originalWidth: preprocessed.originalSize.width,
originalHeight: preprocessed.originalSize.height
)
let postprocessTime = CFAbsoluteTimeGetCurrent() - postprocessStart
let totalTime = preprocessTime + inferenceTime + postprocessTime
return DetectionResult(
boxes: boxes,
preprocessTime: preprocessTime,
inferenceTime: inferenceTime,
postprocessTime: postprocessTime,
totalTime: totalTime,
inputTensorShape: preprocessed.tensorShape
)
}
}
@@ -0,0 +1,51 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CoreGraphics
import Foundation
import ImageIO
enum EncodedImageCodecError: LocalizedError {
case emptyData
case createImageSourceFailed
case createImageFailed
var errorDescription: String? {
switch self {
case .emptyData:
return "Image data is empty"
case .createImageSourceFailed:
return "Could not create image source from data"
case .createImageFailed:
return "Could not decode image from data"
}
}
}
/// Decodes PNG/JPEG/WebP and other formats supported by Image I/O into a ``CGImage``.
enum EncodedImageCodec {
static func cgImage(fromEncodedData data: Data) throws -> CGImage {
guard !data.isEmpty else {
throw EncodedImageCodecError.emptyData
}
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
throw EncodedImageCodecError.createImageSourceFailed
}
let options: [CFString: Any] = [kCGImageSourceShouldCache: true]
guard let cgImage = CGImageSourceCreateImageAtIndex(source, 0, options as CFDictionary) else {
throw EncodedImageCodecError.createImageFailed
}
return cgImage
}
}
@@ -0,0 +1,322 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Yams
// MARK: - Errors
enum InferenceConfigError: LocalizedError {
case fileNotFound(String)
case parseError(String)
case missingField(String)
var errorDescription: String? {
switch self {
case .fileNotFound(let path):
return "Model config file not found: \(path)"
case .parseError(let detail):
return "Failed to parse model config: \(detail)"
case .missingField(let field):
return "Missing required field in model config: \(field)"
}
}
}
// MARK: - Transform Operations
/// Channel order implied by `DecodeImage` in the model config file (`img_mode`: BGR or RGB).
/// When `DecodeImage` is absent, defaults to **BGR** (typical decode path for three-channel inputs).
enum InferenceImageChannelOrder: Equatable, Sendable {
case bgr
case rgb
/// Parses `DecodeImage.img_mode`; empty/missing defaults to **BGR**.
static func fromDecodeImage(imgMode: String?) -> InferenceImageChannelOrder {
guard let raw = imgMode?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty else {
return .bgr
}
switch raw.lowercased() {
case "rgb": return .rgb
case "bgr": return .bgr
default:
return .bgr
}
}
}
/// Parameters for `DetResizeForTest` from the model config file.
struct DetResizeParams: Equatable {
var limitSideLen: Int
var limitType: String
var maxSideLimit: Int
}
/// Represents a single preprocessing transform operation parsed from the model config file.
/// Each case carries associated parameters read from the model config file.
enum TransformOp {
/// `DecodeImage` in the model config file — selects BGR vs RGB for decoded pixels.
case decodeImage(channelOrder: InferenceImageChannelOrder)
case detResizeForTest(DetResizeParams)
case normalizeImage(scale: Float, mean: [Float], std: [Float], order: String)
case toCHWImage
case recResizeImg(imageShape: [Int])
case unknown(name: String)
}
// MARK: - Config Structures
struct PreProcessConfig {
let transformOps: [TransformOp]
}
struct PostProcessConfig {
let name: String
let thresh: Float
let boxThresh: Float
let maxCandidates: Int
let unclipRatio: Float
let characterDict: [String]?
}
struct InferenceConfig {
let modelName: String
let preProcess: PreProcessConfig
let postProcess: PostProcessConfig
// MARK: - Loading
/// Loads and parses a model config file into a typed `InferenceConfig`.
///
/// - Parameter path: Absolute filesystem path to the model config file.
/// - Returns: A fully parsed `InferenceConfig` with typed transform operations.
static func load(from path: String) throws -> InferenceConfig {
guard FileManager.default.fileExists(atPath: path) else {
throw InferenceConfigError.fileNotFound(path)
}
let configFileText: String
do {
configFileText = try String(contentsOfFile: path, encoding: .utf8)
} catch {
throw InferenceConfigError.parseError("Cannot read file: \(error.localizedDescription)")
}
guard let root = try Yams.load(yaml: configFileText) as? [String: Any] else {
throw InferenceConfigError.parseError("Root element is not a dictionary")
}
// Parse Global.model_name
guard let global = root["Global"] as? [String: Any],
let modelName = global["model_name"] as? String else {
throw InferenceConfigError.missingField("Global.model_name")
}
// Parse PreProcess
guard let preProcessDict = root["PreProcess"] as? [String: Any],
let transformOpsRaw = preProcessDict["transform_ops"] as? [[String: Any?]] else {
throw InferenceConfigError.missingField("PreProcess.transform_ops")
}
let transformOps = transformOpsRaw.map { parseTransformOp($0) }
let preProcess = PreProcessConfig(transformOps: transformOps)
// Parse PostProcess
guard let postProcessDict = root["PostProcess"] as? [String: Any] else {
throw InferenceConfigError.missingField("PostProcess")
}
let postProcess = parsePostProcess(postProcessDict)
return InferenceConfig(
modelName: modelName,
preProcess: preProcess,
postProcess: postProcess
)
}
}
extension InferenceConfig {
// MARK: - Private Parsing Helpers
private enum ParseDefaults {
static let postThresh: Float = 0.3
static let postBoxThresh: Float = 0.6
static let postMaxCandidates: Int = 1000
static let postUnclipRatio: Float = 2.0
static let detResizeLimitSideLen: Int = 960
static let detResizeLimitType: String = "max"
static let detResizeMaxSideLimit: Int = 4000
}
private static let defaultDetResizeParams = DetResizeParams(
limitSideLen: ParseDefaults.detResizeLimitSideLen,
limitType: ParseDefaults.detResizeLimitType,
maxSideLimit: ParseDefaults.detResizeMaxSideLimit
)
/// Parses a single transform operation dictionary (one key = op name, value = params or null).
private static func parseTransformOp(_ dict: [String: Any?]) -> TransformOp {
guard let opName = dict.keys.first else {
return .unknown(name: "empty")
}
switch opName {
case "DecodeImage":
let params = dict[opName] as? [String: Any] ?? [:]
let imgMode = params["img_mode"] as? String
return .decodeImage(channelOrder: InferenceImageChannelOrder.fromDecodeImage(imgMode: imgMode))
case "DetResizeForTest":
let params = dict[opName] as? [String: Any] ?? [:]
let limitSideLen =
optionalIntValue(params["resize_long"])
?? optionalIntValue(params["limit_side_len"])
?? ParseDefaults.detResizeLimitSideLen
let limitType = params["limit_type"] as? String ?? ParseDefaults.detResizeLimitType
let maxSideLimit =
intValueForKeyIfPresent(params, key: "max_side_limit")
?? ParseDefaults.detResizeMaxSideLimit
return .detResizeForTest(
DetResizeParams(
limitSideLen: limitSideLen,
limitType: limitType,
maxSideLimit: maxSideLimit
)
)
case "NormalizeImage":
let params = dict[opName] as? [String: Any] ?? [:]
let scale = parseScale(params["scale"])
let mean = parseFloatArray(params["mean"]) ?? [0.485, 0.456, 0.406]
let std = parseFloatArray(params["std"]) ?? [0.229, 0.224, 0.225]
let order = params["order"] as? String ?? "hwc"
return .normalizeImage(scale: scale, mean: mean, std: std, order: order)
case "ToCHWImage":
return .toCHWImage
case "RecResizeImg":
let params = dict[opName] as? [String: Any] ?? [:]
let imageShape = (params["image_shape"] as? [Any])?.compactMap { toInt($0) } ?? [3, 48, 320]
return .recResizeImg(imageShape: imageShape)
default:
return .unknown(name: opName)
}
}
/// Parses the `scale` field which may be a numeric value or a fraction string like `"1./255."`.
/// Handles string division expressions by splitting on "/" and computing the result.
private static func parseScale(_ value: Any?) -> Float {
if let floatVal = value as? Double {
return Float(floatVal)
}
if let stringVal = value as? String {
return parseScaleString(stringVal)
}
// Default scale: 1/255
return 1.0 / 255.0
}
/// Evaluates a fraction string by splitting on `"/"` and dividing numerator by denominator.
private static func parseScaleString(_ s: String) -> Float {
if s.contains("/") {
let parts = s.split(separator: "/")
if parts.count == 2,
let numerator = Double(parts[0].trimmingCharacters(in: .init(charactersIn: "."))),
let denominator = Double(parts[1].trimmingCharacters(in: .init(charactersIn: "."))) {
return Float(numerator / denominator)
}
let rawParts = s.split(separator: "/")
if rawParts.count == 2,
let num = Double(rawParts[0]),
let den = Double(rawParts[1]) {
return Float(num / den)
}
}
if let val = Double(s) {
return Float(val)
}
return 1.0 / 255.0
}
private static func parseFloatArray(_ value: Any?) -> [Float]? {
guard let array = value as? [Any] else { return nil }
return array.compactMap { element -> Float? in
if let d = element as? Double { return Float(d) }
if let i = element as? Int { return Float(i) }
return nil
}
}
private static func parsePostProcess(_ dict: [String: Any]) -> PostProcessConfig {
let name = dict["name"] as? String ?? "Unknown"
let thresh = (dict["thresh"] as? Double).map { Float($0) } ?? ParseDefaults.postThresh
let boxThresh = (dict["box_thresh"] as? Double).map { Float($0) } ?? ParseDefaults.postBoxThresh
let maxCandidates = dict["max_candidates"] as? Int ?? ParseDefaults.postMaxCandidates
let unclipRatio = (dict["unclip_ratio"] as? Double).map { Float($0) } ?? ParseDefaults.postUnclipRatio
let characterDict = (dict["character_dict"] as? [Any])?.compactMap { $0 as? String }
return PostProcessConfig(
name: name,
thresh: thresh,
boxThresh: boxThresh,
maxCandidates: maxCandidates,
unclipRatio: unclipRatio,
characterDict: characterDict
)
}
private static func toInt(_ value: Any) -> Int? {
if let i = value as? Int { return i }
if let d = value as? Double { return Int(d) }
return nil
}
private static func optionalIntValue(_ value: Any?) -> Int? {
guard let value else { return nil }
return toInt(value)
}
/// Only returns a value when the key exists in `params` (a missing key yields `nil`).
private static func stringValueForKeyIfPresent(_ params: [String: Any], key: String) -> String? {
guard params.keys.contains(key) else { return nil }
return params[key] as? String
}
private static func intValueForKeyIfPresent(_ params: [String: Any], key: String) -> Int? {
guard params.keys.contains(key) else { return nil }
return optionalIntValue(params[key])
}
/// First `DetResizeForTest` block in the model config file next to the ONNX weights, if present.
var detResizeFromModel: DetResizeParams? {
for op in preProcess.transformOps {
if case .detResizeForTest(let p) = op { return p }
}
return nil
}
var detResizeForMerge: DetResizeParams {
detResizeFromModel ?? Self.defaultDetResizeParams
}
/// First `DecodeImage` entry in `transform_ops` and its `img_mode` (BGR or RGB). If absent, **BGR**.
var decodeImageChannelOrder: InferenceImageChannelOrder {
for op in preProcess.transformOps {
if case .decodeImage(let order) = op { return order }
}
return .bgr
}
}
@@ -0,0 +1,107 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Resolves exported ONNX or ORT-format models and their **model config files** in the app bundle (`Models/det`, `Models/rec`).
/// Resource lookup uses the conventional shared basename for the weight file and the model config file in each folder.
/// Weights: prefers `inference*.ort` in the model directory (see ``bundledOrtPath``), otherwise `inference.onnx`.
struct ModelConfig {
let modelPath: String
let configPath: String
/// From `Global.model_name` in the model config file (same directory as the ONNX weights).
let name: String
/// Human-readable label from `Global.model_name` in the model config file; `fallback` if the file cannot be read.
private static func displayName(fromModelConfigPath configPath: String, fallback: String) -> String {
guard let cfg = try? InferenceConfig.load(from: configPath) else {
return fallback
}
return cfg.modelName
}
/// Bundled model weights: any `inference*.ort` in the subdirectory (``ortBundledFileMatchOrder``), else `inference.onnx`.
///
/// ONNX Runtime’s `convert_onnx_models_to_ort` may emit `inference.with_runtime_opt.ort` instead of `inference.ort`
/// when using Runtime optimization style; the bundle cannot resolve that with `forResource: "inference"`.
private static let ortResourceStems: [String] = [
"inference",
"inference.with_runtime_opt",
]
private static func bundledOrtPath(inDirectory directory: String) -> String? {
for stem in ortResourceStems {
if let p = Bundle.main.path(forResource: stem, ofType: "ort", inDirectory: directory) {
return p
}
}
// Other ORT export suffixes (e.g. non-default optim levels): one `inference*.ort` in the folder.
guard let urls = Bundle.main.urls(forResourcesWithExtension: "ort", subdirectory: directory) else {
return nil
}
let matches = urls.filter { url in
let c = url.lastPathComponent
return c.hasPrefix("inference") && c.hasSuffix(".ort")
}
guard !matches.isEmpty else { return nil }
if matches.count == 1 { return matches[0].path }
// If multiple, prefer lexicographic first (deterministic); avoid shipping several exports in one dir.
return matches.sorted { $0.lastPathComponent < $1.lastPathComponent }.first?.path
}
private static func bundledWeightsPath(inDirectory directory: String, notFoundMessage: String) throws -> String {
if let ort = bundledOrtPath(inDirectory: directory) {
return ort
}
if let onnx = Bundle.main.path(forResource: "inference", ofType: "onnx", inDirectory: directory) {
return onnx
}
throw ModelConfigError.modelNotFound(notFoundMessage)
}
static func detection() throws -> ModelConfig {
let modelPath = try Self.bundledWeightsPath(
inDirectory: "Models/det",
notFoundMessage: "det/inference.ort or det/inference.onnx"
)
guard let configPath = Bundle.main.path(forResource: "inference", ofType: "yml", inDirectory: "Models/det") else {
throw ModelConfigError.modelNotFound("det model config file")
}
let name = displayName(fromModelConfigPath: configPath, fallback: "text_detection")
return ModelConfig(modelPath: modelPath, configPath: configPath, name: name)
}
static func recognition() throws -> ModelConfig {
let modelPath = try Self.bundledWeightsPath(
inDirectory: "Models/rec",
notFoundMessage: "rec/inference.ort or rec/inference.onnx"
)
guard let configPath = Bundle.main.path(forResource: "inference", ofType: "yml", inDirectory: "Models/rec") else {
throw ModelConfigError.modelNotFound("rec model config file")
}
let name = displayName(fromModelConfigPath: configPath, fallback: "text_recognition")
return ModelConfig(modelPath: modelPath, configPath: configPath, name: name)
}
}
enum ModelConfigError: LocalizedError {
case modelNotFound(String)
var errorDescription: String? {
switch self {
case .modelNotFound(let path):
return "Model file not found in bundle: \(path)"
}
}
}
@@ -0,0 +1,293 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CoreGraphics
import Foundation
// MARK: - OCR run result types
/// A single OCR result: one detected text region with its recognized text.
struct OCRResult {
/// Four corner points of the bounding polygon [x, y] in original image coordinates.
/// Order: top-left, top-right, bottom-right, bottom-left.
let polygon: [[Int32]]
/// The recognized text string from CTC decoding.
let text: String
/// Recognition confidence score (0.0 to 1.0).
let confidence: Float
}
/// Result of one full OCR run on an image, with per-stage timing.
struct OCRRunResult {
/// All detected and recognized text regions, in reading order.
let results: [OCRResult]
/// Total time spent in the detection stage (preprocess + inference + postprocess).
let detectionTime: TimeInterval
/// Seconds in detection preprocessing (resize, normalize, HWC-to-CHW).
let detectionPreprocessTime: TimeInterval
/// Seconds in detection ONNX inference.
let detectionInferenceTime: TimeInterval
/// Seconds in detection postprocessing (DB map, contours, polygons).
let detectionPostprocessTime: TimeInterval
/// Total time spent recognizing all text regions (sum of per-line totals).
let recognitionTime: TimeInterval
/// Sum of recognition preprocess time across all lines (batched work split per line).
let recognitionPreprocessTime: TimeInterval
/// Sum of recognition inference time across all lines.
let recognitionInferenceTime: TimeInterval
/// Sum of recognition postprocess (CTC decode) time across all lines.
let recognitionPostprocessTime: TimeInterval
/// Wall-clock time for the entire run (detect + sort + crop + recognize).
let totalTime: TimeInterval
/// Time not attributed to detection or recognition totals.
let pipelineOverheadTime: TimeInterval
/// Number of text lines from detection sent through recognition.
let recognitionLineCount: Int
/// Detection model input tensor shape for this OCR run, e.g. [1, 3, H, W].
let detectionInputTensorShape: [Int]
/// Recognition model input tensor shapes for each non-empty recognition batch.
let recognitionInputTensorShapes: [[Int]]
/// Per-line recognition ONNX inference times in **seconds**.
let lineRecognitionInferenceTimes: [TimeInterval]
/// Per-line recognition preprocess times in **seconds**.
let lineRecognitionPreprocessTimes: [TimeInterval]
/// Per-line recognition postprocess times in **seconds**.
let lineRecognitionPostprocessTimes: [TimeInterval]
}
// MARK: - OCR Engine Errors
enum OCREngineError: LocalizedError {
case quadTextCropFailed(boxIndex: Int, underlying: Error)
case recognitionBatchSizeMismatch(expected: Int, actual: Int)
var errorDescription: String? {
switch self {
case .quadTextCropFailed(let idx, let err):
return "Quad text crop failed for box \(idx): \(err.localizedDescription)"
case .recognitionBatchSizeMismatch(let expected, let actual):
return "Recognition returned \(actual) results but \(expected) crops were sent"
}
}
}
// MARK: - OCREngine
/// End-to-end OCR: detect → sort → crop → recognize.
///
/// Composes `DetectionEngine`, `BoxSorter`, `QuadTextCrop`, and `RecognitionEngine`
/// into a single `run(CGImage)` call.
///
/// Runs entirely via async/await. Since `DetectionEngine` and
/// `RecognitionEngine` delegate to `ORTSessionManager` (a Swift actor), all ORT
/// calls are off the main thread.
///
/// Usage:
/// ```swift
/// let manager = ORTSessionManager()
/// try await manager.loadModels()
/// let engine = try OCREngine(sessionManager: manager)
/// let result = try await engine.run(cgImage, params: .noOverrides)
/// for item in result.results {
/// print("\(item.text) (\(item.confidence))")
/// }
/// ```
class OCREngine {
private let detectionEngine: DetectionEngine
private let recognitionEngine: RecognitionEngine
/// Initialize with an existing ORTSessionManager (models must already be loaded).
///
/// Creates both DetectionEngine and RecognitionEngine.
///
/// - Parameter sessionManager: A loaded ORTSessionManager.
/// - Throws: If either engine's model config cannot be loaded.
init(sessionManager: ORTSessionManager) throws {
self.detectionEngine = try DetectionEngine(sessionManager: sessionManager)
self.recognitionEngine = try RecognitionEngine(sessionManager: sessionManager)
}
func baselineRuntimeDefaults() -> ResolvedOCRRuntimeParams {
ResolvedOCRRuntimeParams.fromModelConfig(detectionEngine.modelConfig)
}
/// Run full OCR on an image.
///
/// End-to-end OCR flow (detect → sort → crop → recognize):
/// 1. **Detect**: Run detection to get bounding polygons
/// 2. **Sort**: Sort boxes in reading order (top-to-bottom, left-to-right)
/// 3. **Crop + Recognize**: Crop each region, order crops by ascending width/height for batched
/// recognition, then map results back to reading order
///
/// - Parameters:
/// - image: The input `CGImage` to process.
/// - params: Optional runtime parameter overrides (see ``OCRRuntimeParams``).
/// - Returns: `OCRRunResult` with all line results and timing.
func run(_ image: CGImage, params: OCRRuntimeParams = .noOverrides) async throws -> OCRRunResult {
let runStart = CFAbsoluteTimeGetCurrent()
let resolved = params.resolved(detectionEngine.modelConfig)
let detResult = try await detectionEngine.detect(image, runtimeParams: params)
let sortedBoxes = BoxSorter.sortInReadingOrder(detResult.boxes)
let (ocrResults, recTiming, perLine) = try await recognizeSortedBoxes(
sortedBoxes,
sourceImage: image,
resolved: resolved
)
let totalTime = CFAbsoluteTimeGetCurrent() - runStart
let overhead = totalTime - detResult.totalTime - recTiming.total
return OCRRunResult(
results: ocrResults,
detectionTime: detResult.totalTime,
detectionPreprocessTime: detResult.preprocessTime,
detectionInferenceTime: detResult.inferenceTime,
detectionPostprocessTime: detResult.postprocessTime,
recognitionTime: recTiming.total,
recognitionPreprocessTime: recTiming.preprocess,
recognitionInferenceTime: recTiming.inference,
recognitionPostprocessTime: recTiming.postprocess,
totalTime: totalTime,
pipelineOverheadTime: max(0, overhead),
recognitionLineCount: perLine.count,
detectionInputTensorShape: detResult.inputTensorShape,
recognitionInputTensorShapes: perLine.inputTensorShapes,
lineRecognitionInferenceTimes: perLine.inference,
lineRecognitionPreprocessTimes: perLine.preprocess,
lineRecognitionPostprocessTimes: perLine.postprocess
)
}
/// Aggregated recognition timing across all lines (sums of per-line split batch times).
private struct RecognitionTimingAggregate {
let preprocess: TimeInterval
let inference: TimeInterval
let postprocess: TimeInterval
let total: TimeInterval
}
/// Per-line rec timings
private struct PerLineRecognitionTimes {
let count: Int
let inputTensorShapes: [[Int]]
let inference: [TimeInterval]
let preprocess: [TimeInterval]
let postprocess: [TimeInterval]
}
private func recognizeSortedBoxes(
_ sortedBoxes: [DetectionBox],
sourceImage: CGImage,
resolved: ResolvedOCRRuntimeParams
) async throws -> ([OCRResult], RecognitionTimingAggregate, PerLineRecognitionTimes) {
struct LineCrop {
let lineIndex: Int
let aspectRatio: Float
let crop: CGImage
let polygon: [[Int32]]
}
var lines: [LineCrop] = []
lines.reserveCapacity(sortedBoxes.count)
for (index, box) in sortedBoxes.enumerated() {
let croppedImage: CGImage
do {
croppedImage = try QuadTextCrop.crop(sourceImage, polygon: box.points)
} catch {
throw OCREngineError.quadTextCropFailed(boxIndex: index, underlying: error)
}
let h = max(croppedImage.height, 1)
let aspect = Float(croppedImage.width) / Float(h)
lines.append(LineCrop(lineIndex: index, aspectRatio: aspect, crop: croppedImage, polygon: box.points))
}
let sortedForInference = lines.sorted { a, b in
if a.aspectRatio != b.aspectRatio {
return a.aspectRatio < b.aspectRatio
}
return a.lineIndex < b.lineIndex
}
let batchSize = max(1, resolved.textRecBatchSize)
var perLine: [RecognitionEngineResult?] = Array(repeating: nil, count: lines.count)
var batchInputShapes: [[Int]] = []
var chunkStart = 0
while chunkStart < sortedForInference.count {
let chunkEnd = min(chunkStart + batchSize, sortedForInference.count)
let chunk = Array(sortedForInference[chunkStart..<chunkEnd])
let crops = chunk.map(\.crop)
let recBatch = try await recognitionEngine.recognizeBatch(crops)
guard recBatch.count == chunk.count else {
throw OCREngineError.recognitionBatchSizeMismatch(expected: chunk.count, actual: recBatch.count)
}
if let first = recBatch.first {
batchInputShapes.append(first.inputTensorShape)
}
for (i, item) in chunk.enumerated() {
perLine[item.lineIndex] = recBatch[i]
}
chunkStart = chunkEnd
}
var ocrResults: [OCRResult] = []
var totalRecTime: TimeInterval = 0
var totalRecPre: TimeInterval = 0
var totalRecInf: TimeInterval = 0
var totalRecPost: TimeInterval = 0
var lineInf: [TimeInterval] = []
var linePre: [TimeInterval] = []
var linePost: [TimeInterval] = []
lineInf.reserveCapacity(lines.count)
linePre.reserveCapacity(lines.count)
linePost.reserveCapacity(lines.count)
for line in lines {
guard let recResult = perLine[line.lineIndex] else { continue }
linePre.append(recResult.preprocessTime)
lineInf.append(recResult.inferenceTime)
linePost.append(recResult.postprocessTime)
totalRecTime += recResult.totalTime
totalRecPre += recResult.preprocessTime
totalRecInf += recResult.inferenceTime
totalRecPost += recResult.postprocessTime
if recResult.confidence < resolved.textRecScoreThresh {
continue
}
ocrResults.append(OCRResult(
polygon: line.polygon,
text: recResult.text,
confidence: recResult.confidence
))
}
let aggregate = RecognitionTimingAggregate(
preprocess: totalRecPre,
inference: totalRecInf,
postprocess: totalRecPost,
total: totalRecTime
)
let perLineOut = PerLineRecognitionTimes(
count: lines.count,
inputTensorShapes: batchInputShapes,
inference: lineInf,
preprocess: linePre,
postprocess: linePost
)
return (ocrResults, aggregate, perLineOut)
}
}
@@ -0,0 +1,238 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
// MARK: - Runtime (UI) parameters
struct OCRRuntimeParams: Equatable, Sendable {
// Detection — preprocess
var textDetLimitSideLen: Int?
var textDetLimitType: String?
var textDetMaxSideLimit: Int?
// Detection — postprocess
var textDetThresh: Float?
var textDetBoxThresh: Float?
var textDetUnclipRatio: Float?
// Recognition
var textRecBatchSize: Int?
var textRecScoreThresh: Float?
static let noOverrides = OCRRuntimeParams(
textDetLimitSideLen: nil,
textDetLimitType: nil,
textDetMaxSideLimit: nil,
textDetThresh: nil,
textDetBoxThresh: nil,
textDetUnclipRatio: nil,
textRecBatchSize: nil,
textRecScoreThresh: nil
)
}
// MARK: - Resolved parameters (for UI baseline & filtering)
struct ResolvedOCRRuntimeParams: Equatable, Sendable {
// Detection — preprocess
var textDetLimitSideLen: Int
var textDetLimitType: String
var textDetMaxSideLimit: Int
// Detection — postprocess
var textDetThresh: Float
var textDetBoxThresh: Float
var textDetUnclipRatio: Float
// Recognition
var textRecBatchSize: Int
var textRecScoreThresh: Float
init(
textDetLimitSideLen: Int,
textDetLimitType: String,
textDetMaxSideLimit: Int,
textDetThresh: Float,
textDetBoxThresh: Float,
textDetUnclipRatio: Float,
textRecBatchSize: Int,
textRecScoreThresh: Float,
) {
self.textDetLimitSideLen = textDetLimitSideLen
self.textDetLimitType = textDetLimitType
self.textDetMaxSideLimit = textDetMaxSideLimit
self.textDetThresh = textDetThresh
self.textDetBoxThresh = textDetBoxThresh
self.textDetUnclipRatio = textDetUnclipRatio
self.textRecBatchSize = textRecBatchSize
self.textRecScoreThresh = textRecScoreThresh
}
static let fallbackForUI = ResolvedOCRRuntimeParams(
textDetLimitSideLen: OCRParameterResolver.textDetLimitSideLenAppDefault,
textDetLimitType: OCRParameterResolver.textDetLimitTypeAppDefault,
textDetMaxSideLimit: OCRParameterResolver.textDetMaxSideLimitAppDefault,
textDetThresh: OCRParameterResolver.textDetThreshAppDefault,
textDetBoxThresh: OCRParameterResolver.textDetBoxThreshAppDefault,
textDetUnclipRatio: OCRParameterResolver.textDetUnclipRatioAppDefault,
textRecBatchSize: OCRParameterResolver.textRecBatchSizeAppDefault,
textRecScoreThresh: OCRParameterResolver.textRecScoreThreshAppDefault
)
}
extension OCRRuntimeParams {
func resolved(_ modelConfig: InferenceConfig) -> ResolvedOCRRuntimeParams {
let base = ResolvedOCRRuntimeParams.fromModelConfig(modelConfig)
return ResolvedOCRRuntimeParams(
textDetLimitSideLen: textDetLimitSideLen ?? base.textDetLimitSideLen,
textDetLimitType: textDetLimitType ?? base.textDetLimitType,
textDetMaxSideLimit: textDetMaxSideLimit ?? base.textDetMaxSideLimit,
textDetThresh: textDetThresh ?? base.textDetThresh,
textDetBoxThresh: textDetBoxThresh ?? base.textDetBoxThresh,
textDetUnclipRatio: textDetUnclipRatio ?? base.textDetUnclipRatio,
textRecBatchSize: textRecBatchSize ?? base.textRecBatchSize,
textRecScoreThresh: textRecScoreThresh ?? base.textRecScoreThresh
)
}
}
extension ResolvedOCRRuntimeParams {
/// Baseline with no UI overrides, using ``OCRParameterResolver`` app-tier defaults.
static func fromModelConfig(_ modelConfig: InferenceConfig) -> ResolvedOCRRuntimeParams {
let o = OCRParameterResolver.effective(modelConfig: modelConfig, runtime: .noOverrides)
return ResolvedOCRRuntimeParams(
textDetLimitSideLen: o.mergedLimitSideLen,
textDetLimitType: o.mergedLimitType,
textDetMaxSideLimit: o.mergedMaxSideLimit,
textDetThresh: o.detThresh,
textDetBoxThresh: o.detBoxThresh,
textDetUnclipRatio: o.detUnclipRatio,
textRecBatchSize: o.textRecBatchSize,
textRecScoreThresh: o.recScoreThresh
)
}
}
// MARK: - Effective parameters (single merge pass)
struct EffectiveOCRParams: Equatable, Sendable {
// Detection — preprocess
var detResize: DetResizeParams
var mergedLimitSideLen: Int
var mergedLimitType: String
var mergedMaxSideLimit: Int
// Detection — postprocess
var detThresh: Float
var detBoxThresh: Float
var detUnclipRatio: Float
// Recognition
var textRecBatchSize: Int
var recScoreThresh: Float
}
// MARK: - Resolver
enum OCRParameterResolver {
// MARK: App tier
// Detection — preprocess
static let textDetLimitSideLenAppDefault: Int = 64
static let textDetLimitTypeAppDefault: String = "min"
static let textDetMaxSideLimitAppDefault: Int = 4000
// Detection — postprocess
static let textDetThreshAppDefault: Float = 0.3
static let textDetBoxThreshAppDefault: Float = 0.6
static let textDetUnclipRatioAppDefault: Float = 1.5
// Recognition
static let textRecBatchSizeAppDefault: Int = 1
static let textRecScoreThreshAppDefault: Float = 0.0
// MARK: Merge helpers
/// UI override if set; otherwise the app-tier default.
private static func mergeFloat(ui: Float?, app: Float) -> Float {
ui ?? app
}
private static func mergeInt(ui: Int?, app: Int) -> Int {
ui ?? app
}
private static func mergeString(ui: String?, app: String) -> String {
ui ?? app
}
private static func mergedLimitSideFields(runtime: OCRRuntimeParams) -> (
sideLen: Int, limitType: String, maxSide: Int
) {
let sideLen = mergeInt(
ui: runtime.textDetLimitSideLen,
app: Self.textDetLimitSideLenAppDefault
)
let limitType = mergeString(
ui: runtime.textDetLimitType,
app: Self.textDetLimitTypeAppDefault
)
let maxSide = mergeInt(
ui: runtime.textDetMaxSideLimit,
app: Self.textDetMaxSideLimitAppDefault
)
return (sideLen, limitType, maxSide)
}
private static func limitSideParams(runtime: OCRRuntimeParams) -> DetResizeParams {
let m = mergedLimitSideFields(runtime: runtime)
return DetResizeParams(
limitSideLen: m.sideLen,
limitType: m.limitType,
maxSideLimit: m.maxSide
)
}
/// Merges ``OCRRuntimeParams`` with app-tier defaults (UI → app). The `modelConfig` argument is
/// unused at this moment.
static func effective(modelConfig _: InferenceConfig, runtime: OCRRuntimeParams) -> EffectiveOCRParams {
let detResize = limitSideParams(runtime: runtime)
let merged = mergedLimitSideFields(runtime: runtime)
let detThresh = mergeFloat(
ui: runtime.textDetThresh,
app: Self.textDetThreshAppDefault
)
let detBoxThresh = mergeFloat(
ui: runtime.textDetBoxThresh,
app: Self.textDetBoxThreshAppDefault
)
let detUnclipRatio = mergeFloat(
ui: runtime.textDetUnclipRatio,
app: Self.textDetUnclipRatioAppDefault
)
let textRecBatchSize = mergeInt(
ui: runtime.textRecBatchSize,
app: Self.textRecBatchSizeAppDefault
)
let recScoreThresh = runtime.textRecScoreThresh ?? Self.textRecScoreThreshAppDefault
return EffectiveOCRParams(
detResize: detResize,
mergedLimitSideLen: merged.sideLen,
mergedLimitType: merged.limitType,
mergedMaxSideLimit: merged.maxSide,
detThresh: detThresh,
detBoxThresh: detBoxThresh,
detUnclipRatio: detUnclipRatio,
textRecBatchSize: textRecBatchSize,
recScoreThresh: recScoreThresh
)
}
}
@@ -0,0 +1,45 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <Foundation/Foundation.h>
@class ORTSession;
@class ORTSessionOptions;
NS_ASSUME_NONNULL_BEGIN
/// Bridges ONNX Runtime C++ profiling APIs that are not exposed on
/// `onnxruntime-objc`'s public surface.
///
/// - Warning: `endProfilingOnSession` reads the private `_session` ivar on
/// `ORTSession` (layout depends on the
/// installed `onnxruntime-objc` version). Re-verify after pod upgrades.
@interface ORTProfilingBridge : NSObject
+ (BOOL)enableProfilingOnSessionOptions:(ORTSessionOptions *)options
pathPrefix:(NSString *)pathPrefix
error:(NSError *_Nullable __autoreleasing *)
error
NS_SWIFT_NAME(enableProfiling(sessionOptions:pathPrefix:));
/// Ends profiling and returns the path to the written JSON (see ORT
/// `Session::EndProfilingAllocated`).
+ (nullable NSString *)
endProfilingOnSession:(ORTSession *)session
error:(NSError *_Nullable __autoreleasing *)error
NS_SWIFT_NAME(endProfiling(session:));
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,72 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import "ORTProfilingBridge.h"
#import "ort_session_internal.h"
#import "cxx_api.h"
#import "error_utils.h"
#import <objc/runtime.h>
#include <optional>
@implementation ORTProfilingBridge
+ (BOOL)enableProfilingOnSessionOptions:(ORTSessionOptions *)options
pathPrefix:(NSString *)pathPrefix
error:(NSError **)error {
if (options == nil || pathPrefix.length == 0) {
ORTSaveCodeAndDescriptionToError(ORT_INVALID_ARGUMENT, @"ORTProfilingBridge: options and non-empty pathPrefix required", error);
return NO;
}
try {
[options CXXAPIOrtSessionOptions].EnableProfiling(pathPrefix.fileSystemRepresentation);
return YES;
}
ORT_OBJC_API_IMPL_CATCH_RETURNING_BOOL(error);
}
+ (NSString *)endProfilingOnSession:(ORTSession *)session error:(NSError **)error {
if (session == nil) {
ORTSaveCodeAndDescriptionToError(ORT_INVALID_ARGUMENT, @"ORTProfilingBridge: session is nil", error);
return nil;
}
try {
Ivar ivar = class_getInstanceVariable([ORTSession class], "_session");
if (ivar == nullptr) {
ORTSaveCodeAndDescriptionToError(ORT_FAIL,
@"ORTProfilingBridge: ORTSession has no _session ivar — onnxruntime-objc mismatch?",
error);
return nil;
}
uintptr_t base = reinterpret_cast<uintptr_t>(session);
auto *opt = reinterpret_cast<std::optional<Ort::Session> *>(base + ivar_getOffset(ivar));
if (opt == nullptr || !opt->has_value()) {
ORTSaveCodeAndDescriptionToError(ORT_FAIL, @"ORTProfilingBridge: ORTSession is not ready", error);
return nil;
}
Ort::AllocatorWithDefaultOptions allocator;
Ort::AllocatedStringPtr path = opt->value().EndProfilingAllocated(allocator);
const char *cstr = path.get();
if (cstr == nullptr) {
return nil;
}
return [NSString stringWithUTF8String:cstr];
}
ORT_OBJC_API_IMPL_CATCH_RETURNING_NULLABLE(error);
}
@end
@@ -0,0 +1,338 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Preset for which ONNX Runtime execution provider is registered first on the session chain in this demo.
enum ORTPrimaryExecutionProvider: String, CaseIterable, Identifiable, Sendable {
/// Default CPU execution. Default for this demo.
case cpu = "cpu"
/// Registers the XNNPACK EP; nodes it cannot run still use the CPU EP.
case xnnpack = "xnnpack"
/// Registers the Core ML EP; remaining subgraphs use other registered EPs (commonly CPU).
case coreML = "core_ml"
var id: String { rawValue }
var displayTitle: String {
switch self {
case .cpu: return "CPU"
case .xnnpack: return "XNNPACK"
case .coreML: return "Core ML"
}
}
}
enum ORTCoreMLProviderOption: String, CaseIterable, Identifiable, Sendable {
case enableOnSubgraphs
case createMLProgram
case staticInputShapes
case cpuOnly
case cpuAndGPU
case aneOnly
var id: String { rawValue }
var displayTitle: String {
switch self {
case .enableOnSubgraphs: return "Enable on subgraphs"
case .createMLProgram: return "Use ML program"
case .staticInputShapes: return "Fixed tensor shapes only"
case .cpuOnly: return "Core ML CPU only"
case .cpuAndGPU: return "Core ML CPU and GPU"
case .aneOnly: return "Only on devices with ANE"
}
}
var detailCaption: String {
switch self {
case .enableOnSubgraphs: return "Compile subgraphs independently for Core ML."
case .createMLProgram: return "Prefer MLProgram over NeuralNetwork (when supported)."
case .staticInputShapes:
return "Core ML tries to run only ops whose input tensors have fixed shapes at inference time; parts with varying dimensions typically stay on the CPU EP instead."
case .cpuOnly: return "Forces Core ML compute on CPU. Mutually exclusive with CPU and GPU."
case .cpuAndGPU: return "Allows Core ML to use CPU and GPU. Mutually exclusive with CPU only."
case .aneOnly: return "Only enable Core ML EP on devices that have Apple Neural Engine hardware."
}
}
}
enum ORTSessionManagerError: LocalizedError {
case modelNotFound(String)
case sessionCreationFailed(String)
case inferenceFailed(String)
case inputTensorElementCountMismatch(expected: Int, actual: Int, modelName: String)
case outputContainsNaN(String)
case ortProfilingFailed(String)
var errorDescription: String? {
switch self {
case .modelNotFound(let name): return "Model not found: \(name)"
case .sessionCreationFailed(let detail): return "Session creation failed: \(detail)"
case .inferenceFailed(let detail): return "Inference failed: \(detail)"
case .inputTensorElementCountMismatch(let expected, let actual, let modelName):
return "\(modelName): input tensor size mismatch (expected \(expected) floats, got \(actual))"
case .outputContainsNaN(let name): return "Output tensor '\(name)' contains NaN values"
case .ortProfilingFailed(let detail): return "ONNX Runtime profiling: \(detail)"
}
}
}
/// File URLs of ONNX Runtime JSON profiles after ``ORTSessionManager/finalizeORTProfiling()`` (separate file per sub-model).
struct ORTProfilingOutput: Sendable {
var detectionProfileJSON: URL
var recognitionProfileJSON: URL
}
/// Tuning options for ORT session creation.
struct ORTSessionTuningOptions: Sendable {
/// Session-level intra-op thread count. 0 = ORT default.
var intraOpThreads: Int = 0
/// XNNPACK EP thread count. 0 = ORT default.
var xnnpackThreads: Int = 0
/// CoreML EP flags: enableOnSubgraphs, createMLProgram, staticInputShapes, cpuOnly, cpuAndGPU, aneOnly.
var coreMLFlags: Set<String> = []
static let `default` = ORTSessionTuningOptions()
}
extension ORTSessionTuningOptions: Equatable {}
/// At most one placement-related Core ML EP option is applied. Priority matches
/// ``OnnxRuntimeSettingsPanel`` when several keys appear (e.g. benchmark env / JSON).
private func applyCoreMLPlacementFlags(from flags: Set<String>, to coreml: ORTCoreMLExecutionProviderOptions) {
if flags.contains(ORTCoreMLProviderOption.cpuOnly.rawValue) {
coreml.useCPUOnly = true
} else if flags.contains(ORTCoreMLProviderOption.cpuAndGPU.rawValue) {
coreml.useCPUAndGPU = true
} else if flags.contains(ORTCoreMLProviderOption.aneOnly.rawValue) {
coreml.onlyEnableForDevicesWithANE = true
}
}
actor ORTSessionManager {
private struct SessionIONames {
let inputName: String
let outputNames: Set<String>
}
private var env: ORTEnv?
private var detSession: ORTSession?
private var recSession: ORTSession?
private var detIO: SessionIONames?
private var recIO: SessionIONames?
private var ortProfilingPendingFinalize: Bool = false
/// Load both models. Creates one ORTEnv (per ORT docs: one per process),
/// configures execution providers per ``ORTPrimaryExecutionProvider``,
/// and creates sessions for detection and recognition models.
///
/// - Parameter ortProfiling: When `true`, enables ONNX Runtime session profiling (written as JSON on finalize).
/// Profiling adds overhead; do not treat wall-clock times from the same run as a clean latency benchmark.
/// - Parameter tuning: Session tuning options (threads, EP flags). Default reads from environment.
func loadModels(executionProvider: ORTPrimaryExecutionProvider = .cpu, ortProfiling: Bool = false, tuning: ORTSessionTuningOptions = .default) async throws {
let env = try ORTEnv(loggingLevel: .warning)
self.env = env
ortProfilingPendingFinalize = ortProfiling
let detConfig = try ModelConfig.detection()
let recConfig = try ModelConfig.recognition()
if ortProfiling {
let baseDir = try ortProfilingDirectoryURL()
let detPrefix = baseDir.appendingPathComponent("paddle_ort_det", isDirectory: false).path
let recPrefix = baseDir.appendingPathComponent("paddle_ort_rec", isDirectory: false).path
let detOptions = try makeSessionOptions(executionProvider: executionProvider, ortProfilePathPrefix: detPrefix, tuning: tuning)
let recOptions = try makeSessionOptions(executionProvider: executionProvider, ortProfilePathPrefix: recPrefix, tuning: tuning)
detSession = try ORTSession(env: env, modelPath: detConfig.modelPath, sessionOptions: detOptions)
recSession = try ORTSession(env: env, modelPath: recConfig.modelPath, sessionOptions: recOptions)
} else {
let options = try makeSessionOptions(executionProvider: executionProvider, ortProfilePathPrefix: nil, tuning: tuning)
detSession = try ORTSession(env: env, modelPath: detConfig.modelPath, sessionOptions: options)
recSession = try ORTSession(env: env, modelPath: recConfig.modelPath, sessionOptions: options)
}
if let detSession {
detIO = try makeSessionIONames(session: detSession, modelName: "det")
}
if let recSession {
recIO = try makeSessionIONames(session: recSession, modelName: "rec")
}
}
/// Flushes ORT profiling and returns the JSON file paths. Call once after the last inference when
/// ``loadModels(ortProfiling:)`` was `true`. Safe to call when profiling was disabled (returns `nil`).
func finalizeORTProfiling() throws -> ORTProfilingOutput? {
guard ortProfilingPendingFinalize else { return nil }
ortProfilingPendingFinalize = false
guard let det = detSession, let rec = recSession else {
throw ORTSessionManagerError.sessionCreationFailed("Cannot finalize ORT profiling: session missing")
}
let detPath = try ORTProfilingBridge.endProfiling(session: det)
let recPath = try ORTProfilingBridge.endProfiling(session: rec)
if detPath.isEmpty || recPath.isEmpty {
throw ORTSessionManagerError.ortProfilingFailed("EndProfiling returned an empty path")
}
return ORTProfilingOutput(
detectionProfileJSON: URL(fileURLWithPath: detPath),
recognitionProfileJSON: URL(fileURLWithPath: recPath)
)
}
private func ortProfilingDirectoryURL() throws -> URL {
let base = try FileManager.default.url(
for: .cachesDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
let dir = base.appendingPathComponent("PaddleOCRORTProfiling", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir
}
private func makeSessionOptions(executionProvider: ORTPrimaryExecutionProvider, ortProfilePathPrefix: String?, tuning: ORTSessionTuningOptions) throws -> ORTSessionOptions {
let options = try ORTSessionOptions()
try options.setGraphOptimizationLevel(.all)
if tuning.intraOpThreads > 0 {
try options.setIntraOpNumThreads(Int32(tuning.intraOpThreads))
}
if let prefix = ortProfilePathPrefix {
try ORTProfilingBridge.enableProfiling(sessionOptions: options, pathPrefix: prefix)
}
switch executionProvider {
case .cpu:
break
case .xnnpack:
let xnnpackOptions = ORTXnnpackExecutionProviderOptions()
if tuning.xnnpackThreads > 0 {
xnnpackOptions.intra_op_num_threads = Int32(tuning.xnnpackThreads)
}
try options.appendXnnpackExecutionProvider(with: xnnpackOptions)
case .coreML:
let coremlOptions = ORTCoreMLExecutionProviderOptions()
let flags = tuning.coreMLFlags
if flags.contains("enableOnSubgraphs") { coremlOptions.enableOnSubgraphs = true }
if flags.contains("createMLProgram") { coremlOptions.createMLProgram = true }
if flags.contains("staticInputShapes") { coremlOptions.onlyAllowStaticInputShapes = true }
applyCoreMLPlacementFlags(from: flags, to: coremlOptions)
try options.appendCoreMLExecutionProvider(with: coremlOptions)
}
return options
}
private func makeSessionIONames(session: ORTSession, modelName: String) throws -> SessionIONames {
let inputNames = try session.inputNames()
let outputNamesList = try session.outputNames()
guard let firstInputName = inputNames.first else {
throw ORTSessionManagerError.inferenceFailed("\(modelName): no input names found")
}
return SessionIONames(inputName: firstInputName, outputNames: Set(outputNamesList))
}
/// Run detection inference with real preprocessed input data.
///
/// - Parameters:
/// - inputData: Float32 array in CHW layout; length must equal the product of `shape`.
/// - shape: Tensor shape, e.g. [1, 3, 896, 960].
/// - Returns: Dictionary mapping output name to (data as [Float], shape as [Int]).
func runDetection(inputData: [Float], shape: [Int]) async throws -> [String: (data: [Float], shape: [Int])] {
guard let session = detSession else {
throw ORTSessionManagerError.sessionCreationFailed("Detection session not loaded")
}
guard let io = detIO else {
throw ORTSessionManagerError.sessionCreationFailed("Detection session IO names not loaded")
}
return try runInference(session: session, io: io, modelName: "det", inputData: inputData, shape: shape)
}
/// Run recognition inference with preprocessed input data.
///
/// The recognition model accepts dynamic batch and width: shape `[N, 3, H, W]` with `N ≥ 1`,
/// fixed `H` (e.g. 48), and `W` shared after padding within each batch. A single line uses `N = 1`.
///
/// - Parameters:
/// - inputData: Float32 row-major tensor; length must equal the product of `shape`.
/// - shape: e.g. `[1, 3, 48, 320]` or `[6, 3, 48, 640]` for a batch of six lines.
/// - Returns: Dictionary mapping output name to (data as [Float], shape as [Int]).
func runRecognition(inputData: [Float], shape: [Int]) async throws -> [String: (data: [Float], shape: [Int])] {
guard let session = recSession else {
throw ORTSessionManagerError.sessionCreationFailed("Recognition session not loaded")
}
guard let io = recIO else {
throw ORTSessionManagerError.sessionCreationFailed("Recognition session IO names not loaded")
}
return try runInference(session: session, io: io, modelName: "rec", inputData: inputData, shape: shape)
}
/// Shared inference logic used by both detection and recognition.
///
/// Discovers input/output names at runtime, creates a float32 tensor from the
/// provided data and shape, runs the session, extracts output arrays, and
/// validates that no output contains NaN values.
private func runInference(
session: ORTSession,
io: SessionIONames,
modelName: String,
inputData: [Float],
shape: [Int]
) throws -> [String: (data: [Float], shape: [Int])] {
let expectedElements = shape.reduce(1, *)
guard expectedElements == inputData.count else {
throw ORTSessionManagerError.inputTensorElementCountMismatch(
expected: expectedElements,
actual: inputData.count,
modelName: modelName
)
}
// Create ORT tensor from input data
let nsShape = shape.map { NSNumber(value: $0) }
var data = inputData
let tensorData = NSMutableData(
bytes: &data,
length: inputData.count * MemoryLayout<Float>.stride
)
let inputTensor = try ORTValue(
tensorData: tensorData,
elementType: .float,
shape: nsShape
)
let inputs: [String: ORTValue] = [io.inputName: inputTensor]
let outputs = try session.run(
withInputs: inputs,
outputNames: io.outputNames,
runOptions: nil
)
// Extract output tensors as Float arrays
var result: [String: (data: [Float], shape: [Int])] = [:]
for (name, value) in outputs {
let info = try value.tensorTypeAndShapeInfo()
let outputShape = info.shape.map { $0.intValue }
let outputData = try value.tensorData() as Data
let floats: [Float] = outputData.withUnsafeBytes { buffer in
Array(buffer.bindMemory(to: Float.self))
}
if floats.contains(where: \.isNaN) {
throw ORTSessionManagerError.outputContainsNaN(name)
}
result[name] = (data: floats, shape: outputShape)
}
return result
}
}
@@ -0,0 +1,45 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PDBMiniBoxResult : NSObject
@property(nonatomic) NSArray<NSValue *> *corners;
@property(nonatomic) float minSide;
@end
@interface PDBOpenCVDBBridge : NSObject
+ (NSArray<NSArray<NSValue *> *> *)findContoursWithBinaryMask:(NSData *)data
width:(NSInteger)width
height:(NSInteger)height
maxCandidates:
(NSInteger)maxCandidates
NS_SWIFT_NAME(findContours(binaryMask:width:height:maxCandidates:));
+ (nullable PDBMiniBoxResult *)miniBoxFromPoints:(NSArray<NSValue *> *)points
NS_SWIFT_NAME(miniBox(fromPoints:));
+ (float)contourAreaFromPoints:(NSArray<NSValue *> *)points
NS_SWIFT_NAME(contourArea(fromPoints:));
+ (float)arcLengthFromPoints:(NSArray<NSValue *> *)points
closed:(BOOL)closed
NS_SWIFT_NAME(arcLength(fromPoints:closed:));
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,147 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import "OpenCVDBBridge.h"
// Include imgproc before UIKit: Objective-C's `NO` macro breaks OpenCV enums named `NO` in opencv.hpp.
#import <opencv2/core.hpp>
#import <opencv2/imgproc.hpp>
#import <UIKit/UIKit.h>
#include <algorithm>
@implementation PDBMiniBoxResult
@end
@implementation PDBOpenCVDBBridge
+ (NSArray<NSArray<NSValue *> *> *)findContoursWithBinaryMask:(NSData *)data
width:(NSInteger)width
height:(NSInteger)height
maxCandidates:(NSInteger)maxCandidates {
if (width <= 0 || height <= 0 || data.length < (NSUInteger)(width * height)) {
return @[];
}
const uint8_t *src = static_cast<const uint8_t *>(data.bytes);
cv::Mat mat((int)height, (int)width, CV_8UC1);
for (int y = 0; y < (int)height; y++) {
uint8_t *row = mat.ptr<uint8_t>(y);
for (int x = 0; x < (int)width; x++) {
row[x] = src[y * (int)width + x] ? 255 : 0;
}
}
std::vector<std::vector<cv::Point>> contours;
cv::findContours(mat, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
const NSInteger n = std::min((NSInteger)contours.size(), maxCandidates);
NSMutableArray *out = [NSMutableArray arrayWithCapacity:(NSUInteger)n];
for (NSInteger i = 0; i < n; i++) {
const auto &c = contours[(size_t)i];
NSMutableArray *pts = [NSMutableArray arrayWithCapacity:c.size()];
for (const auto &pt : c) {
[pts addObject:[NSValue valueWithCGPoint:CGPointMake(pt.x, pt.y)]];
}
[out addObject:pts];
}
return out;
}
+ (nullable PDBMiniBoxResult *)miniBoxFromPoints:(NSArray<NSValue *> *)points {
if (points.count < 2) {
return nil;
}
std::vector<cv::Point2f> pts;
pts.reserve(points.count);
for (NSValue *v in points) {
CGPoint p = v.CGPointValue;
pts.emplace_back((float)p.x, (float)p.y);
}
cv::RotatedRect rr = cv::minAreaRect(pts);
float w = rr.size.width;
float h = rr.size.height;
if (w <= 0 && h <= 0) {
return nil;
}
cv::Point2f cvPts[4];
rr.points(cvPts);
// Stable sort by x only (min-area box corner order).
int ord[4] = {0, 1, 2, 3};
std::stable_sort(ord, ord + 4, [&](int a, int b) { return cvPts[a].x < cvPts[b].x; });
cv::Point2f sortedPts[4];
for (int i = 0; i < 4; i++) {
sortedPts[i] = cvPts[ord[i]];
}
NSInteger index1, index2, index3, index4;
cv::Point2f p0 = sortedPts[0];
cv::Point2f p1 = sortedPts[1];
if (p1.y > p0.y) {
index1 = 0;
index4 = 1;
} else {
index1 = 1;
index4 = 0;
}
cv::Point2f p2 = sortedPts[2];
cv::Point2f p3 = sortedPts[3];
if (p3.y > p2.y) {
index2 = 2;
index3 = 3;
} else {
index2 = 3;
index3 = 2;
}
PDBMiniBoxResult *res = [[PDBMiniBoxResult alloc] init];
res.corners = @[
[NSValue valueWithCGPoint:CGPointMake(sortedPts[index1].x, sortedPts[index1].y)],
[NSValue valueWithCGPoint:CGPointMake(sortedPts[index2].x, sortedPts[index2].y)],
[NSValue valueWithCGPoint:CGPointMake(sortedPts[index3].x, sortedPts[index3].y)],
[NSValue valueWithCGPoint:CGPointMake(sortedPts[index4].x, sortedPts[index4].y)],
];
res.minSide = std::min(w, h);
return res;
}
+ (float)contourAreaFromPoints:(NSArray<NSValue *> *)points {
if (points.count < 2) {
return 0;
}
std::vector<cv::Point2f> pts;
pts.reserve(points.count);
for (NSValue *v in points) {
CGPoint p = v.CGPointValue;
pts.emplace_back((float)p.x, (float)p.y);
}
return cv::contourArea(pts);
}
+ (float)arcLengthFromPoints:(NSArray<NSValue *> *)points closed:(BOOL)closed {
if (points.count < 2) {
return 0;
}
std::vector<cv::Point2f> pts;
pts.reserve(points.count);
for (NSValue *v in points) {
CGPoint p = v.CGPointValue;
pts.emplace_back((float)p.x, (float)p.y);
}
return (float)cv::arcLength(pts, closed);
}
@end
@@ -0,0 +1,63 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PDBPerspectiveCropOutput : NSObject
@property(nonatomic) NSData *rgbData;
@property(nonatomic) NSInteger width;
@property(nonatomic) NSInteger height;
@end
@interface PDBOpenCVImageBridge : NSObject
/// `cv::resize(..., INTER_LINEAR)` on 8-bit **3-channel** row-major data
/// (`CV_8UC3`; stores BGR channel order for OpenCV).
+ (NSData *)resizeRGBU8:(NSData *)data
srcWidth:(NSInteger)srcWidth
srcHeight:(NSInteger)srcHeight
dstWidth:(NSInteger)dstWidth
dstHeight:(NSInteger)dstHeight NS_SWIFT_NAME(resizeRGBU8(_:srcWidth:srcHeight:dstWidth:dstHeight:));
/// Pad RGB image to `padWidth` x `padHeight` with zeros on bottom/right.
+ (NSData *)padRGBU8:(NSData *)data
width:(NSInteger)width
height:(NSInteger)height
padWidth:(NSInteger)padWidth
padHeight:(NSInteger)padHeight
NS_SWIFT_NAME(padRGBU8(_:width:height:padWidth:padHeight:));
/// Minimum-area rectangle, corner ordering, perspective warp (`INTER_CUBIC`,
/// `BORDER_REPLICATE`), then 90° CCW rotation when height/width ≥ 1.5. Input
/// buffer is row-major **BGR**.
+ (nullable PDBPerspectiveCropOutput *)
quadTextLineCropBGR:(NSData *)src
srcWidth:(NSInteger)srcWidth
srcHeight:(NSInteger)srcHeight
quad:(NSArray<NSValue *> *)quad
NS_SWIFT_NAME(quadTextLineCropBGR(_:srcWidth:srcHeight:quad:));
/// Mean of the float probability map inside the quadrilateral: `fillPoly` mask
/// then `cv::mean`.
+ (float)meanPredInQuad:(NSData *)pred
width:(NSInteger)width
height:(NSInteger)height
box:(NSArray<NSArray<NSNumber *> *> *)box
NS_SWIFT_NAME(meanPredInQuad(_:width:height:box:));
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,205 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import "OpenCVImageBridge.h"
#import <algorithm>
#import <cfloat>
#import <cmath>
#import <opencv2/core.hpp>
#import <opencv2/imgproc.hpp>
#import <UIKit/UIKit.h>
@implementation PDBPerspectiveCropOutput
@end
@implementation PDBOpenCVImageBridge
+ (NSData *)resizeRGBU8:(NSData *)data
srcWidth:(NSInteger)srcWidth
srcHeight:(NSInteger)srcHeight
dstWidth:(NSInteger)dstWidth
dstHeight:(NSInteger)dstHeight {
if (srcWidth <= 0 || srcHeight <= 0 || dstWidth <= 0 || dstHeight <= 0) {
return [NSData data];
}
if (data.length < (NSUInteger)(srcWidth * srcHeight * 3)) {
return [NSData data];
}
cv::Mat src((int)srcHeight, (int)srcWidth, CV_8UC3, (void *)data.bytes);
cv::Mat dst;
cv::resize(src, dst, cv::Size((int)dstWidth, (int)dstHeight), 0, 0, cv::INTER_LINEAR);
return [NSData dataWithBytes:dst.data length:(NSUInteger)(dst.rows * dst.cols * 3)];
}
+ (NSData *)padRGBU8:(NSData *)data
width:(NSInteger)width
height:(NSInteger)height
padWidth:(NSInteger)padWidth
padHeight:(NSInteger)padHeight {
if (width <= 0 || height <= 0 || padWidth < width || padHeight < height) {
return data ?: [NSData data];
}
if (data.length < (NSUInteger)(width * height * 3)) {
return [NSData data];
}
cv::Mat src((int)height, (int)width, CV_8UC3, (void *)data.bytes);
int bot = (int)(padHeight - height);
int right = (int)(padWidth - width);
cv::Mat dst;
cv::copyMakeBorder(src, dst, 0, bot, 0, right, cv::BORDER_CONSTANT, cv::Scalar(0, 0, 0));
return [NSData dataWithBytes:dst.data length:(NSUInteger)(dst.rows * dst.cols * 3)];
}
+ (nullable PDBPerspectiveCropOutput *)quadTextLineCropBGR:(NSData *)src
srcWidth:(NSInteger)srcWidth
srcHeight:(NSInteger)srcHeight
quad:(NSArray<NSValue *> *)quad {
if (srcWidth <= 0 || srcHeight <= 0) {
return nil;
}
if (quad.count != 4 || src.length < (NSUInteger)(srcWidth * srcHeight * 3)) {
return nil;
}
cv::Mat im((int)srcHeight, (int)srcWidth, CV_8UC3, (void *)src.bytes);
std::vector<cv::Point2f> raw(4);
for (int i = 0; i < 4; i++) {
CGPoint p = [quad[i] CGPointValue];
raw[i] = cv::Point2f((float)(int32_t)p.x, (float)(int32_t)p.y);
}
cv::RotatedRect rr = cv::minAreaRect(raw);
cv::Point2f boxPts[4];
rr.points(boxPts);
std::vector<cv::Point2f> sorted(boxPts, boxPts + 4);
std::sort(sorted.begin(), sorted.end(),
[](const cv::Point2f &a, const cv::Point2f &b) { return a.x < b.x; });
int index_a, index_b, index_c, index_d;
if (sorted[1].y > sorted[0].y) {
index_a = 0;
index_d = 1;
} else {
index_a = 1;
index_d = 0;
}
if (sorted[3].y > sorted[2].y) {
index_b = 2;
index_c = 3;
} else {
index_b = 3;
index_c = 2;
}
cv::Point2f srcPts[4] = {sorted[index_a], sorted[index_b], sorted[index_c], sorted[index_d]};
double w1 = cv::norm(srcPts[0] - srcPts[1]);
double w2 = cv::norm(srcPts[2] - srcPts[3]);
double h1 = cv::norm(srcPts[0] - srcPts[3]);
double h2 = cv::norm(srcPts[1] - srcPts[2]);
int img_crop_width = (int)std::max(w1, w2);
int img_crop_height = (int)std::max(h1, h2);
if (img_crop_width <= 0 || img_crop_height <= 0) {
return nil;
}
cv::Point2f dstPts[4] = {
cv::Point2f(0, 0),
cv::Point2f((float)img_crop_width, 0),
cv::Point2f((float)img_crop_width, (float)img_crop_height),
cv::Point2f(0, (float)img_crop_height),
};
cv::Mat M = cv::getPerspectiveTransform(srcPts, dstPts);
cv::Mat warped;
cv::warpPerspective(im, warped, M, cv::Size(img_crop_width, img_crop_height), cv::INTER_CUBIC,
cv::BORDER_REPLICATE);
cv::Mat outMat;
double ratio = (double)warped.rows / (double)warped.cols;
if (ratio >= 1.5) {
cv::rotate(warped, outMat, cv::ROTATE_90_COUNTERCLOCKWISE);
} else {
outMat = warped;
}
PDBPerspectiveCropOutput *result = [[PDBPerspectiveCropOutput alloc] init];
result.rgbData = [NSData dataWithBytes:outMat.data length:(NSUInteger)(outMat.rows * outMat.cols * 3)];
result.width = outMat.cols;
result.height = outMat.rows;
return result;
}
+ (float)meanPredInQuad:(NSData *)pred
width:(NSInteger)width
height:(NSInteger)height
box:(NSArray<NSArray<NSNumber *> *> *)box {
if (width <= 0 || height <= 0 || box.count != 4) {
return 0;
}
size_t need = (size_t)(width * height) * sizeof(float);
if (pred.length < need) {
return 0;
}
float xminF = FLT_MAX, xmaxF = -FLT_MAX, yminF = FLT_MAX, ymaxF = -FLT_MAX;
for (NSArray<NSNumber *> *pt in box) {
if (pt.count < 2) {
return 0;
}
float x = [pt[0] floatValue];
float y = [pt[1] floatValue];
xminF = std::min(xminF, x);
xmaxF = std::max(xmaxF, x);
yminF = std::min(yminF, y);
ymaxF = std::max(ymaxF, y);
}
int w = (int)width;
int h = (int)height;
// Clamp ROI to bitmap bounds before masking and mean (avoids out-of-range reads).
int xmin = std::max(0, std::min((int)std::floor(xminF), w - 1));
int xmax = std::max(0, std::min((int)std::ceil(xmaxF), w - 1));
int ymin = std::max(0, std::min((int)std::floor(yminF), h - 1));
int ymax = std::max(0, std::min((int)std::ceil(ymaxF), h - 1));
if (xmax < xmin || ymax < ymin) {
return 0;
}
const float *p = (const float *)pred.bytes;
cv::Mat bitmap(h, w, CV_32FC1, (void *)const_cast<float *>(p));
cv::Rect roi(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1);
cv::Mat crop = bitmap(roi);
cv::Mat mask = cv::Mat::zeros(crop.rows, crop.cols, CV_8UC1);
std::vector<cv::Point> pts;
pts.reserve(4);
for (NSArray<NSNumber *> *pt in box) {
float fx = [pt[0] floatValue] - static_cast<float>(xmin);
float fy = [pt[1] floatValue] - static_cast<float>(ymin);
int px = static_cast<int>(fx);
int py = static_cast<int>(fy);
pts.push_back(cv::Point(px, py));
}
std::vector<std::vector<cv::Point>> contours;
contours.push_back(pts);
cv::fillPoly(mask, contours, cv::Scalar(1));
cv::Scalar m = cv::mean(crop, mask);
return (float)m[0];
}
@end
@@ -0,0 +1,29 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// Polygon inflate (unclip) via Clipper 6.x (`ClipperLib`) for closed paths.
@interface PDBPolygonOffsetBridge : NSObject
+ (NSArray<NSArray<NSValue *> *> *)inflateClosedPolygonWith:
(NSArray<NSValue *> *)points
distance:(double)distance
NS_SWIFT_NAME(inflateClosedPolygon(with:distance:));
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,49 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import "PDBPolygonOffsetBridge.h"
#import <UIKit/UIKit.h>
#include <cmath>
#include "clipper.hpp"
@implementation PDBPolygonOffsetBridge
+ (NSArray<NSArray<NSValue *> *> *)inflateClosedPolygonWith:(NSArray<NSValue *> *)points
distance:(double)distance {
if (points.count < 2) {
return @[];
}
using namespace ClipperLib;
// Default miter limit and arc tolerance for ClipperOffset (round join).
ClipperOffset co(2.0, 0.25);
Path path;
path.reserve(points.count);
for (NSValue *v in points) {
CGPoint p = v.CGPointValue;
cInt ix = static_cast<cInt>(std::lround((double)p.x));
cInt iy = static_cast<cInt>(std::lround((double)p.y));
path.push_back(IntPoint(ix, iy));
}
co.AddPath(path, jtRound, etClosedPolygon);
Paths solution;
co.Execute(solution, distance);
if (solution.empty()) {
return @[];
}
const Path &out = solution[0];
NSMutableArray *ring = [NSMutableArray arrayWithCapacity:out.size()];
for (const IntPoint &pt : out) {
[ring addObject:[NSValue valueWithCGPoint:CGPointMake((CGFloat)pt.X, (CGFloat)pt.Y)]];
}
return @[ ring ];
}
@end
@@ -0,0 +1,386 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CoreGraphics
import Foundation
// MARK: - Errors
enum DetPreprocessorError: LocalizedError {
case invalidImage
case configMissing(String)
case pixelExtractionFailed
var errorDescription: String? {
switch self {
case .invalidImage:
return "Invalid input image: width or height is zero"
case .configMissing(let detail):
return "Required preprocessing config missing: \(detail)"
case .pixelExtractionFailed:
return "Failed to extract pixel data from image"
}
}
}
// MARK: - Preprocessing Result
/// The output of detection preprocessing: a float32 tensor and metadata needed for postprocessing.
struct PreprocessResult {
/// Flat CHW array of shape [1, 3, resizedH, resizedW].
let tensorData: [Float]
/// Tensor dimensions: [1, 3, resizedH, resizedW].
let tensorShape: [Int]
/// Original image dimensions before any resizing.
let originalSize: (width: Int, height: Int)
/// Image dimensions after resize and padding to stride multiples.
let resizedSize: (width: Int, height: Int)
/// Vertical resize ratio: resizedH / originalH.
let ratioH: Float
/// Horizontal resize ratio: resizedW / originalW.
let ratioW: Float
}
// MARK: - DetPreprocessor
/// Implements detection preprocessing: **DetResizeForTest** →
/// **NormalizeImage** (from the model config file) -> **ToCHWImage**.
///
/// Rasterization uses CoreGraphics; resize/pad use OpenCV (`INTER_LINEAR`, `copyMakeBorder`).
/// HWC channel order follows `DecodeImage.img_mode` (`InferenceConfig.decodeImageChannelOrder`).
struct DetPreprocessor {
private enum ResizeRule {
case limitSide(len: Int, limitType: String, maxSideLimit: Int)
case longEdge(resizeLong: Int)
}
private let scale: Float
private let mean: [Float]
private let std: [Float]
private let channelOrder: InferenceImageChannelOrder
init(config: InferenceConfig) throws {
var foundScale: Float?
var foundMean: [Float]?
var foundStd: [Float]?
for op in config.preProcess.transformOps {
switch op {
case .decodeImage:
break
case .detResizeForTest(_):
break
case .normalizeImage(let s, let m, let st, _):
foundScale = s
foundMean = m
foundStd = st
case .toCHWImage, .recResizeImg, .unknown:
break
}
}
guard let scale = foundScale, let mean = foundMean, let std = foundStd else {
throw DetPreprocessorError.configMissing("NormalizeImage with scale, mean, std")
}
guard mean.count == 3, std.count == 3 else {
throw DetPreprocessorError.configMissing("NormalizeImage mean/std must have exactly 3 values")
}
self.scale = scale
self.mean = mean
self.std = std
self.channelOrder = config.decodeImageChannelOrder
}
private static func resizeRule(from params: DetResizeParams) throws -> ResizeRule {
.limitSide(
len: params.limitSideLen,
limitType: params.limitType,
maxSideLimit: params.maxSideLimit
)
}
/// Rasterizes ``CGImage`` to HWC uint8 (`BGR` or `RGB` per `DecodeImage.img_mode`).
func preprocess(_ image: CGImage, detResize: DetResizeParams) throws -> PreprocessResult {
let originalW = image.width
let originalH = image.height
guard originalW > 0, originalH > 0 else {
throw DetPreprocessorError.invalidImage
}
let pixelBytes = try rasterizeImageIntoHWCBuffer(
from: image, width: originalW, height: originalH, order: channelOrder
)
return try preprocessFromHWCPixelBuffer(
pixelBytes: pixelBytes,
originalWidth: originalW,
originalHeight: originalH,
detResize: detResize
)
}
private func preprocessFromHWCPixelBuffer(
pixelBytes initialPixels: [UInt8],
originalWidth: Int,
originalHeight: Int,
detResize: DetResizeParams
) throws -> PreprocessResult {
let resizeRule = try Self.resizeRule(from: detResize)
var pixelBytes = initialPixels
var currentW = originalWidth
var currentH = originalHeight
if currentH + currentW < 64 {
let paddedH = max(32, currentH)
let paddedW = max(32, currentW)
pixelBytes = padImage(pixelBytes, fromW: currentW, fromH: currentH, toW: paddedW, toH: paddedH)
currentW = paddedW
currentH = paddedH
}
let (resizeW, resizeH, ratioW, ratioH): (Int, Int, Float, Float)
switch resizeRule {
case .limitSide(let len, let limitType, let maxSideLimit):
(resizeW, resizeH, ratioW, ratioH) = computeResizeLimitSide(
srcW: currentW,
srcH: currentH,
limitSideLen: len,
limitType: limitType,
maxSideLimit: maxSideLimit
)
case .longEdge(let resizeLong):
(resizeW, resizeH, ratioW, ratioH) = computeResizeLongEdge(
srcW: currentW,
srcH: currentH,
resizeLong: resizeLong
)
}
let resizedPixels = resizeImageBuffer(
pixelBytes, srcW: currentW, srcH: currentH, dstW: resizeW, dstH: resizeH
)
let normalizedHWC = normalizePixels(resizedPixels, width: resizeW, height: resizeH)
let chwData = hwcToCHW(normalizedHWC, width: resizeW, height: resizeH)
return PreprocessResult(
tensorData: chwData,
tensorShape: [1, 3, resizeH, resizeW],
originalSize: (width: originalWidth, height: originalHeight),
resizedSize: (width: resizeW, height: resizeH),
ratioH: ratioH,
ratioW: ratioW
)
}
// MARK: - Rasterization
/// Row-major HWC uint8: **BGR** or **RGB** per `DecodeImage.img_mode` in the model config file.
private func rasterizeImageIntoHWCBuffer(
from image: CGImage,
width: Int,
height: Int,
order: InferenceImageChannelOrder
) throws -> [UInt8] {
let bytesPerPixel = 4
let bytesPerRow = width * bytesPerPixel
var rgbaData = [UInt8](repeating: 0, count: height * bytesPerRow)
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
let context = CGContext(
data: &rgbaData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
) else {
throw DetPreprocessorError.pixelExtractionFailed
}
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
var out = [UInt8](repeating: 0, count: height * width * 3)
for i in 0..<(height * width) {
let r = rgbaData[i * 4]
let g = rgbaData[i * 4 + 1]
let b = rgbaData[i * 4 + 2]
switch order {
case .bgr:
out[i * 3] = b
out[i * 3 + 1] = g
out[i * 3 + 2] = r
case .rgb:
out[i * 3] = r
out[i * 3 + 1] = g
out[i * 3 + 2] = b
}
}
return out
}
private func padImage(_ pixels: [UInt8], fromW: Int, fromH: Int, toW: Int, toH: Int) -> [UInt8] {
if fromW == toW && fromH == toH {
return pixels
}
let out = PDBOpenCVImageBridge.padRGBU8(
Data(pixels), width: fromW, height: fromH, padWidth: toW, padHeight: toH
)
let expected = toW * toH * 3
guard out.count == expected else {
return [UInt8](repeating: 0, count: expected)
}
return [UInt8](out)
}
// MARK: - Resize geometry
/// Limit-side resize with multiple-of-32 dimensions, optional cap on the larger side.
private func computeResizeLimitSide(
srcW: Int,
srcH: Int,
limitSideLen: Int,
limitType: String,
maxSideLimit: Int
) -> (width: Int, height: Int, ratioW: Float, ratioH: Float) {
let h = Float(srcH)
let w = Float(srcW)
let ratio: Float
switch limitType {
case "max":
if max(srcH, srcW) > limitSideLen {
if srcH > srcW {
ratio = Float(limitSideLen) / h
} else {
ratio = Float(limitSideLen) / w
}
} else {
ratio = 1.0
}
case "min":
if min(srcH, srcW) < limitSideLen {
if srcH < srcW {
ratio = Float(limitSideLen) / h
} else {
ratio = Float(limitSideLen) / w
}
} else {
ratio = 1.0
}
case "resize_long":
ratio = Float(limitSideLen) / Float(max(srcH, srcW))
default:
ratio = 1.0
}
var resizeH = Int(Float(srcH) * ratio)
var resizeW = Int(Float(srcW) * ratio)
if max(resizeH, resizeW) > maxSideLimit {
let shrink = Float(maxSideLimit) / Float(max(resizeH, resizeW))
resizeH = Int(Float(resizeH) * shrink)
resizeW = Int(Float(resizeW) * shrink)
}
resizeH = max(Int((Double(resizeH) / 32.0).rounded(.toNearestOrEven)) * 32, 32)
resizeW = max(Int((Double(resizeW) / 32.0).rounded(.toNearestOrEven)) * 32, 32)
if resizeH == srcH && resizeW == srcW {
return (srcW, srcH, 1.0, 1.0)
}
let ratioH = Float(resizeH) / Float(srcH)
let ratioW = Float(resizeW) / Float(srcW)
return (resizeW, resizeH, ratioW, ratioH)
}
/// Long-edge resize with stride 128 on both sides.
private func computeResizeLongEdge(
srcW: Int,
srcH: Int,
resizeLong: Int
) -> (width: Int, height: Int, ratioW: Float, ratioH: Float) {
let ratio: Float
if srcH > srcW {
ratio = Float(resizeLong) / Float(srcH)
} else {
ratio = Float(resizeLong) / Float(srcW)
}
var resizeH = Int(Float(srcH) * ratio)
var resizeW = Int(Float(srcW) * ratio)
let stride = 128
resizeH = ((resizeH + stride - 1) / stride) * stride
resizeW = ((resizeW + stride - 1) / stride) * stride
let ratioH = Float(resizeH) / Float(srcH)
let ratioW = Float(resizeW) / Float(srcW)
return (resizeW, resizeH, ratioW, ratioH)
}
private func resizeImageBuffer(
_ pixels: [UInt8], srcW: Int, srcH: Int, dstW: Int, dstH: Int
) -> [UInt8] {
if srcW == dstW && srcH == dstH {
return pixels
}
let out = PDBOpenCVImageBridge.resizeRGBU8(
Data(pixels), srcWidth: srcW, srcHeight: srcH, dstWidth: dstW, dstHeight: dstH
)
let expected = dstW * dstH * 3
guard out.count == expected else {
return [UInt8](repeating: 0, count: expected)
}
return [UInt8](out)
}
// MARK: - NormalizeImage
private func normalizePixels(_ pixels: [UInt8], width: Int, height: Int) -> [Float] {
let pixelCount = width * height
var result = [Float](repeating: 0, count: pixelCount * 3)
let scaleOverStd = [scale / std[0], scale / std[1], scale / std[2]]
let meanOverStd = [mean[0] / std[0], mean[1] / std[1], mean[2] / std[2]]
for i in 0..<pixelCount {
let baseIdx = i * 3
result[baseIdx] = Float(pixels[baseIdx]) * scaleOverStd[0] - meanOverStd[0]
result[baseIdx + 1] = Float(pixels[baseIdx + 1]) * scaleOverStd[1] - meanOverStd[1]
result[baseIdx + 2] = Float(pixels[baseIdx + 2]) * scaleOverStd[2] - meanOverStd[2]
}
return result
}
private func hwcToCHW(_ hwcData: [Float], width: Int, height: Int) -> [Float] {
let channelSize = height * width
var chwData = [Float](repeating: 0, count: 3 * channelSize)
for y in 0..<height {
for x in 0..<width {
let hwcIdx = (y * width + x) * 3
let pixelOffset = y * width + x
chwData[0 * channelSize + pixelOffset] = hwcData[hwcIdx]
chwData[1 * channelSize + pixelOffset] = hwcData[hwcIdx + 1]
chwData[2 * channelSize + pixelOffset] = hwcData[hwcIdx + 2]
}
}
return chwData
}
}
@@ -0,0 +1,152 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CoreGraphics
import Foundation
// MARK: - BGR ↔ CGImage
/// Builds a ``CGImage`` from row-major BGR uint8 (8-bit three-channel).
enum BGRImageCodec {
static func makeCGImageFromBGR(pixels: [UInt8], width: Int, height: Int) throws -> CGImage {
let bytesPerPixel = 4
let bytesPerRow = width * bytesPerPixel
let pixelCount = width * height
guard pixels.count == pixelCount * 3 else {
throw QuadTextCropError.imageCreationFailed
}
var rgbaData = [UInt8](repeating: 255, count: pixelCount * bytesPerPixel)
for i in 0..<pixelCount {
let b = pixels[i * 3]
let g = pixels[i * 3 + 1]
let r = pixels[i * 3 + 2]
rgbaData[i * 4] = r
rgbaData[i * 4 + 1] = g
rgbaData[i * 4 + 2] = b
}
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
let context = CGContext(
data: &rgbaData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
),
let cgImage = context.makeImage() else {
throw QuadTextCropError.imageCreationFailed
}
return cgImage
}
}
// MARK: - Errors
enum QuadTextCropError: LocalizedError {
case invalidPolygon(String)
case imageCreationFailed
case openCVFailed
var errorDescription: String? {
switch self {
case .invalidPolygon(let detail):
return "Invalid polygon for quad text crop: \(detail)"
case .imageCreationFailed:
return "Failed to create output CGImage"
case .openCVFailed:
return "OpenCV quad text-line crop failed"
}
}
}
// MARK: - QuadTextCrop
/// Minimum-area quadrilateral, corner ordering, perspective warp, then optional 90° CCW rotation when height/width ≥ 1.5.
struct QuadTextCrop {
/// Crop a text region from the source image using the detector quadrilateral.
static func crop(_ image: CGImage, polygon: [[Int32]]) throws -> CGImage {
guard polygon.count == 4, polygon.allSatisfy({ $0.count == 2 }) else {
throw QuadTextCropError.invalidPolygon(
"Expected 4 points with 2 coordinates each, got \(polygon.count) points"
)
}
let srcPixels = try extractBGRPixels(from: image)
let srcW = image.width
let srcH = image.height
let polyValues: [NSValue] = polygon.map {
NSValue(cgPoint: CGPoint(x: CGFloat($0[0]), y: CGFloat($0[1])))
}
guard let out = PDBOpenCVImageBridge.quadTextLineCropBGR(
Data(srcPixels),
srcWidth: srcW,
srcHeight: srcH,
quad: polyValues
) else {
throw QuadTextCropError.openCVFailed
}
let bytes = [UInt8](out.rgbData)
return try BGRImageCodec.makeCGImageFromBGR(pixels: bytes, width: Int(out.width), height: Int(out.height))
}
}
// MARK: - Pixel Extraction & Image Creation
private extension QuadTextCrop {
/// Row-major HWC **BGR**
static func extractBGRPixels(from image: CGImage) throws -> [UInt8] {
let width = image.width
let height = image.height
let bytesPerPixel = 4
let bytesPerRow = width * bytesPerPixel
var rgbaData = [UInt8](repeating: 0, count: height * bytesPerRow)
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
let context = CGContext(
data: &rgbaData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
) else {
throw QuadTextCropError.imageCreationFailed
}
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
let pixelCount = width * height
var bgrData = [UInt8](repeating: 0, count: pixelCount * 3)
for i in 0..<pixelCount {
let r = rgbaData[i * 4]
let g = rgbaData[i * 4 + 1]
let b = rgbaData[i * 4 + 2]
bgrData[i * 3] = b
bgrData[i * 3 + 1] = g
bgrData[i * 3 + 2] = r
}
return bgrData
}
}
@@ -0,0 +1,380 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CoreGraphics
import Foundation
// MARK: - Errors
enum RecPreprocessorError: LocalizedError {
case invalidImage
case configMissing(String)
case pixelExtractionFailed
var errorDescription: String? {
switch self {
case .invalidImage:
return "Invalid input image: width or height is zero"
case .configMissing(let detail):
return "Required recognition preprocessing config missing: \(detail)"
case .pixelExtractionFailed:
return "Failed to extract pixel data from image"
}
}
}
// MARK: - Preprocessing Result
/// The output of recognition preprocessing: a float32 tensor and metadata.
struct RecPreprocessResult {
/// Flat CHW array of shape [1, imgC, imgH, targetW].
let tensorData: [Float]
/// Tensor dimensions: [1, imgC, imgH, targetW].
let tensorShape: [Int]
/// Original image dimensions before any resizing.
let originalSize: (width: Int, height: Int)
/// Actual content width before zero-padding (the resized image width).
let resizedWidth: Int
}
/// Batched recognition input: N × C × H × W with a common width after padding.
struct RecBatchPreprocessResult {
let tensorData: [Float]
let tensorShape: [Int]
}
// MARK: - RecPreprocessor
/// Recognition resize + normalize + pad: dynamic width, fixed height, scale to [-1, 1],
/// CHW layout, right-pad to target width.
///
/// Recognition resize, per-channel normalization, HWC→CHW, and width padding.
/// `DecodeImage.img_mode` is applied via `InferenceConfig.decodeImageChannelOrder`. Resize uses OpenCV `INTER_LINEAR`.
///
/// Set environment variable `PADDLEOCR_REC_ALIGN_WIDTH_TO_8` to `1`, `true`, or `yes` to round the
/// canvas width up to a multiple of 8 (off by default).
struct RecPreprocessor {
/// Channel count from `RecResizeImg.image_shape` (3).
private let imgC: Int
/// Target height from config RecResizeImg.image_shape (e.g., 48).
private let imgH: Int
/// Default width from config RecResizeImg.image_shape (e.g., 320).
private let imgW: Int
/// Absolute maximum width cap to prevent excessive memory usage.
private let maxImgW: Int = 3200
/// Channel order from `DecodeImage.img_mode` in the model config file.
private let channelOrder: InferenceImageChannelOrder
/// Creates a RecPreprocessor by extracting image_shape from the RecResizeImg transform op.
///
/// - Parameter config: A parsed InferenceConfig from the recognition model's config file.
/// - Throws: `RecPreprocessorError.configMissing` if RecResizeImg with image_shape is absent.
init(config: InferenceConfig) throws {
var foundImageShape: [Int]?
for op in config.preProcess.transformOps {
switch op {
case .decodeImage, .detResizeForTest, .normalizeImage, .toCHWImage, .unknown:
break
case .recResizeImg(let imageShape):
foundImageShape = imageShape
}
}
guard let imageShape = foundImageShape, imageShape.count >= 3 else {
throw RecPreprocessorError.configMissing("RecResizeImg with image_shape")
}
self.imgC = imageShape[0]
self.imgH = imageShape[1]
self.imgW = imageShape[2]
self.channelOrder = config.decodeImageChannelOrder
}
/// Runs recognition preprocessing on a `CGImage`.
///
/// Steps: extract pixels → compute dimensions → resize → normalize → HWC-to-CHW → pad
///
/// - Parameter image: The input image (typically a cropped text region).
/// - Returns: A `RecPreprocessResult` with the float32 CHW tensor and metadata.
func preprocess(_ image: CGImage) throws -> RecPreprocessResult {
let originalW = image.width
let originalH = image.height
guard originalW > 0, originalH > 0 else {
throw RecPreprocessorError.invalidImage
}
let pixelBytes = try extractHWCPixels(from: image, width: originalW, height: originalH, order: channelOrder)
let (paddedData, canvasW, resizedW) = try lineResizeNormalizeCHW(
pixelBytes: pixelBytes,
originalW: originalW,
originalH: originalH,
alignCanvasTo8: Self.isRecognitionCanvasWidthAlignedTo8Enabled()
)
return RecPreprocessResult(
tensorData: paddedData,
tensorShape: [1, imgC, imgH, canvasW],
originalSize: (width: originalW, height: originalH),
resizedWidth: resizedW
)
}
/// Builds a batched tensor: each line is resized and padded to its canvas width, then all rows
/// are padded on the right to the maximum canvas width in the batch (shape `[N, C, H, W]`).
func preprocessBatch(_ images: [CGImage]) throws -> RecBatchPreprocessResult {
guard !images.isEmpty else {
throw RecPreprocessorError.invalidImage
}
let align8 = Self.isRecognitionCanvasWidthAlignedTo8Enabled()
var rowCHW: [[Float]] = []
var canvasWidths: [Int] = []
for image in images {
let originalW = image.width
let originalH = image.height
guard originalW > 0, originalH > 0 else {
throw RecPreprocessorError.invalidImage
}
let pixelBytes = try extractHWCPixels(from: image, width: originalW, height: originalH, order: channelOrder)
let (chw, canvasW, _) = try lineResizeNormalizeCHW(
pixelBytes: pixelBytes,
originalW: originalW,
originalH: originalH,
alignCanvasTo8: align8
)
rowCHW.append(chw)
canvasWidths.append(canvasW)
}
guard let maxCanvasW = canvasWidths.max() else {
throw RecPreprocessorError.invalidImage
}
let n = rowCHW.count
let channelSize = imgH * maxCanvasW
var flat = [Float](repeating: 0, count: n * imgC * channelSize)
for (b, row) in rowCHW.enumerated() {
let w = canvasWidths[b]
let paddedRow: [Float]
if w == maxCanvasW {
paddedRow = row
} else {
let contentW = w
paddedRow = padToTargetWidth(
row,
contentWidth: contentW,
targetWidth: maxCanvasW,
height: imgH,
channels: imgC
)
}
let batchOffset = b * imgC * channelSize
for i in 0..<paddedRow.count {
flat[batchOffset + i] = paddedRow[i]
}
}
return RecBatchPreprocessResult(
tensorData: flat,
tensorShape: [n, imgC, imgH, maxCanvasW]
)
}
/// When `PADDLEOCR_REC_ALIGN_WIDTH_TO_8` is set to a truthy value, the canvas width is rounded up to a multiple of 8.
private static func isRecognitionCanvasWidthAlignedTo8Enabled() -> Bool {
let v = ProcessInfo.processInfo.environment["PADDLEOCR_REC_ALIGN_WIDTH_TO_8"]?.lowercased()
return v == "1" || v == "true" || v == "yes"
}
/// One text line: HWC uint8 → resize → normalize → CHW, padded to the computed canvas width.
private func lineResizeNormalizeCHW(
pixelBytes: [UInt8],
originalW: Int,
originalH: Int,
alignCanvasTo8: Bool
) throws -> (chw: [Float], canvasW: Int, resizedW: Int) {
let w = originalW
let h = originalH
let whRatio = Float(w) / Float(h)
let defaultRatio = Float(imgW) / Float(imgH)
let maxWhRatio = max(defaultRatio, whRatio)
var canvasW = Int(Float(imgH) * maxWhRatio)
let resizedW: Int
if canvasW > maxImgW {
canvasW = maxImgW
resizedW = maxImgW
} else {
let ratio = Float(w) / Float(h)
if Int(ceil(Float(imgH) * ratio)) > canvasW {
resizedW = canvasW
} else {
resizedW = Int(ceil(Float(imgH) * ratio))
}
}
if alignCanvasTo8 {
canvasW = min(max(roundUpToMultipleOf(canvasW, 8), resizedW), maxImgW)
}
let resizedPixels = resizeWithOpenCV(pixelBytes, srcW: w, srcH: h, dstW: resizedW, dstH: imgH)
let normalizedHWC = normalizePixels(resizedPixels, width: resizedW, height: imgH)
let chwData = hwcToCHW(normalizedHWC, width: resizedW, height: imgH)
let paddedData = padToTargetWidth(
chwData,
contentWidth: resizedW,
targetWidth: canvasW,
height: imgH,
channels: imgC
)
return (paddedData, canvasW, resizedW)
}
// MARK: - Step 0: Pixel extraction (BGR / RGB)
private func extractHWCPixels(
from image: CGImage,
width: Int,
height: Int,
order: InferenceImageChannelOrder
) throws -> [UInt8] {
let bytesPerPixel = 4
let bytesPerRow = width * bytesPerPixel
var rgbaData = [UInt8](repeating: 0, count: height * bytesPerRow)
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
let context = CGContext(
data: &rgbaData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
) else {
throw RecPreprocessorError.pixelExtractionFailed
}
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
var out = [UInt8](repeating: 0, count: height * width * 3)
for i in 0..<(height * width) {
let r = rgbaData[i * 4]
let g = rgbaData[i * 4 + 1]
let b = rgbaData[i * 4 + 2]
switch order {
case .bgr:
out[i * 3] = b
out[i * 3 + 1] = g
out[i * 3 + 2] = r
case .rgb:
out[i * 3] = r
out[i * 3 + 1] = g
out[i * 3 + 2] = b
}
}
return out
}
// MARK: - Resize (OpenCV)
private func resizeWithOpenCV(
_ pixels: [UInt8], srcW: Int, srcH: Int, dstW: Int, dstH: Int
) -> [UInt8] {
if srcW == dstW && srcH == dstH {
return pixels
}
let out = PDBOpenCVImageBridge.resizeRGBU8(
Data(pixels), srcWidth: srcW, srcHeight: srcH, dstWidth: dstW, dstHeight: dstH
)
let expected = dstW * dstH * 3
guard out.count == expected else {
return [UInt8](repeating: 0, count: expected)
}
return [UInt8](out)
}
// MARK: - Normalize (recognition)
/// Maps pixel values from [0, 255] to [-1, 1] via `pixel / 127.5 - 1.0`.
private func normalizePixels(_ pixels: [UInt8], width: Int, height: Int) -> [Float] {
let count = width * height * 3
var result = [Float](repeating: 0, count: count)
for i in 0..<count {
result[i] = Float(pixels[i]) / 127.5 - 1.0
}
return result
}
// MARK: - HWC → CHW
private func hwcToCHW(_ hwcData: [Float], width: Int, height: Int) -> [Float] {
let channelSize = height * width
var chwData = [Float](repeating: 0, count: 3 * channelSize)
for y in 0..<height {
for x in 0..<width {
let hwcIdx = (y * width + x) * 3
let pixelOffset = y * width + x
chwData[0 * channelSize + pixelOffset] = hwcData[hwcIdx]
chwData[1 * channelSize + pixelOffset] = hwcData[hwcIdx + 1]
chwData[2 * channelSize + pixelOffset] = hwcData[hwcIdx + 2]
}
}
return chwData
}
// MARK: - Zero-Padding
/// Right-pads a CHW tensor from contentWidth to targetWidth with zeros.
private func padToTargetWidth(
_ chwData: [Float],
contentWidth: Int,
targetWidth: Int,
height: Int,
channels: Int
) -> [Float] {
if contentWidth == targetWidth {
return chwData
}
let targetChannelSize = height * targetWidth
let sourceChannelSize = height * contentWidth
var padded = [Float](repeating: 0, count: channels * targetChannelSize)
for c in 0..<channels {
for y in 0..<height {
let srcOffset = c * sourceChannelSize + y * contentWidth
let dstOffset = c * targetChannelSize + y * targetWidth
for x in 0..<contentWidth {
padded[dstOffset + x] = chwData[srcOffset + x]
}
}
}
return padded
}
}
private func roundUpToMultipleOf(_ value: Int, _ multiple: Int) -> Int {
guard multiple > 0 else { return value }
return (value + multiple - 1) / multiple * multiple
}
@@ -0,0 +1,165 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CoreGraphics
import Foundation
// MARK: - Recognition Engine Result
/// The result of running text recognition on a cropped text image.
///
/// Contains the decoded text, confidence score, and per-stage timing metrics.
struct RecognitionEngineResult {
/// The decoded text string from CTC decoding.
let text: String
/// Average confidence across all decoded characters (0.0 to 1.0).
let confidence: Float
/// Seconds spent in preprocessing (resize, normalize, HWC-to-CHW, pad).
let preprocessTime: TimeInterval
/// Seconds spent in ONNX Runtime inference.
let inferenceTime: TimeInterval
/// Seconds spent in CTC decoding (best-class pick, dedup, char mapping).
let postprocessTime: TimeInterval
/// Total recognition time (preprocess + inference + postprocess).
let totalTime: TimeInterval
/// Recognition model input tensor shape for the batch this line belonged to.
let inputTensorShape: [Int]
}
// MARK: - Recognition Engine Errors
enum RecognitionEngineError: LocalizedError {
case noOutputTensor
case unexpectedOutputShape([Int])
case batchOutputCountMismatch(expectedBatch: Int, shape: [Int])
var errorDescription: String? {
switch self {
case .noOutputTensor:
return "Recognition model produced no output tensor"
case .unexpectedOutputShape(let shape):
return "Unexpected recognition output shape: \(shape), expected [1, T, C] or [N, T, C]"
case .batchOutputCountMismatch(let expectedBatch, let shape):
return "Recognition batch size mismatch: expected batch dimension \(expectedBatch), got shape \(shape)"
}
}
}
// MARK: - RecognitionEngine
/// Orchestrates text recognition:
/// CGImage → RecPreprocessor → ORT inference → CTCDecoder.
///
/// This is the integration layer that composes `RecPreprocessor`, `ORTSessionManager`,
/// and `CTCDecoder` into a single callable unit. All preprocessing parameters are read
/// from the recognition model config file at initialization time.
///
/// Usage:
/// ```swift
/// let engine = try RecognitionEngine(sessionManager: manager)
/// let result = try await engine.recognize(croppedTextImage)
/// print("Text: \(result.text) (confidence: \(result.confidence))")
/// ```
class RecognitionEngine {
private let sessionManager: ORTSessionManager
private let preprocessor: RecPreprocessor
private let decoder: CTCDecoder
private(set) var modelConfig: InferenceConfig
/// Initialize with an existing ORTSessionManager (models must already be loaded).
///
/// Loads the recognition model config file from the bundle to configure
/// the preprocessor and CTC decoder.
///
/// - Parameter sessionManager: A loaded ORTSessionManager with recognition model ready.
/// - Throws: If the model config cannot be loaded or required fields are missing.
init(sessionManager: ORTSessionManager) throws {
self.sessionManager = sessionManager
let recPaths = try ModelConfig.recognition()
let cfg = try InferenceConfig.load(from: recPaths.configPath)
self.modelConfig = cfg
self.preprocessor = try RecPreprocessor(config: cfg)
self.decoder = try CTCDecoder(config: cfg)
}
/// Run recognition on a cropped text region CGImage, returning decoded text with confidence.
///
/// Steps: RecPreprocessor → ORT inference → CTCDecoder
///
/// - Parameter image: A cropped text region image.
/// - Returns: A `RecognitionEngineResult` with text, confidence, and per-stage timing.
func recognize(_ image: CGImage) async throws -> RecognitionEngineResult {
let batch = try await recognizeBatch([image])
guard let first = batch.first else {
throw RecognitionEngineError.noOutputTensor
}
return first
}
/// Runs recognition on multiple cropped lines in one batched inference call.
///
/// - Parameter images: Cropped text regions in inference order (caller controls ordering).
/// - Returns: One result per input image, same order.
func recognizeBatch(_ images: [CGImage]) async throws -> [RecognitionEngineResult] {
guard !images.isEmpty else { return [] }
let preprocessStart = CFAbsoluteTimeGetCurrent()
let batchPreprocessed = try preprocessor.preprocessBatch(images)
let preprocessTime = CFAbsoluteTimeGetCurrent() - preprocessStart
let inferenceStart = CFAbsoluteTimeGetCurrent()
let outputs = try await sessionManager.runRecognition(
inputData: batchPreprocessed.tensorData,
shape: batchPreprocessed.tensorShape
)
let inferenceTime = CFAbsoluteTimeGetCurrent() - inferenceStart
guard let firstOutput = outputs.values.first else {
throw RecognitionEngineError.noOutputTensor
}
let outputData = firstOutput.data
let outputShape = firstOutput.shape
guard outputShape.count == 3, outputShape[0] == images.count else {
if outputShape.count == 3 {
throw RecognitionEngineError.batchOutputCountMismatch(expectedBatch: images.count, shape: outputShape)
}
throw RecognitionEngineError.unexpectedOutputShape(outputShape)
}
let postprocessStart = CFAbsoluteTimeGetCurrent()
let decoded = try decoder.decodeBatch(outputData: outputData, outputShape: outputShape)
let postprocessTime = CFAbsoluteTimeGetCurrent() - postprocessStart
let n = Double(images.count)
let preprocessPer = preprocessTime / n
let inferencePer = inferenceTime / n
let postPer = postprocessTime / n
let totalPer = (preprocessTime + inferenceTime + postprocessTime) / n
return decoded.map { d in
RecognitionEngineResult(
text: d.text,
confidence: d.confidence,
preprocessTime: preprocessPer,
inferenceTime: inferencePer,
postprocessTime: postPer,
totalTime: totalPer,
inputTensorShape: batchPreprocessed.tensorShape
)
}
}
}
@@ -0,0 +1,20 @@
{
"colors" : [
{
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0.753",
"green" : "0.396",
"red" : "0.082"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,62 @@
{
"images": [
{
"filename": "Icon-20@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "20x20"
},
{
"filename": "Icon-20@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "20x20"
},
{
"filename": "Icon-29@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "29x29"
},
{
"filename": "Icon-29@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "29x29"
},
{
"filename": "Icon-40@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "40x40"
},
{
"filename": "Icon-40@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "40x40"
},
{
"filename": "Icon-60@2x.png",
"idiom": "iphone",
"scale": "2x",
"size": "60x60"
},
{
"filename": "Icon-60@3x.png",
"idiom": "iphone",
"scale": "3x",
"size": "60x60"
},
{
"filename": "Icon-1024.png",
"idiom": "universal",
"platform": "ios",
"size": "1024x1024"
}
],
"info": {
"author": "xcode",
"version": 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleDisplayName</key>
<string>PaddleOCR</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
</dict>
</plist>
@@ -0,0 +1,24 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef BridgingHeader_h
#define BridgingHeader_h
#import "ORTProfilingBridge.h"
#import "OpenCVDBBridge.h"
#import "OpenCVImageBridge.h"
#import "PDBPolygonOffsetBridge.h"
#import <onnxruntime.h>
#endif
@@ -0,0 +1,23 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,419 @@
/*******************************************************************************
* *
* Author : Angus Johnson * Version : 6.4.2 * Date : 27 February
*2017 * Website :
*http://www.angusj.com * Copyright :
*Angus Johnson 2010-2017 *
* *
* License: * Use, modification & distribution is subject to Boost Software
*License Ver 1. * http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: * The code in this library is an extension of Bala Vatti's
*clipping algorithm: * "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms * By
*Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: * "Polygon Offsetting by Computing Winding Numbers" * Paper no.
*DETC2005-85513 pp. 565-575 * ASME 2005
*International Design Engineering Technical Conferences * and
*Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************/
#ifndef clipper_hpp
#define clipper_hpp
#define CLIPPER_VERSION "6.4.2"
// use_int32: When enabled 32bit ints are used instead of 64bit ints. This
// improve performance but coordinate values are limited to the range +/- 46340
// #define use_int32
// use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance.
// #define use_xyz
// use_lines: Enables line clipping. Adds a very minor cost to performance.
#define use_lines
// use_deprecated: Enables temporary support for the obsolete functions
// #define use_deprecated
#include <cstdlib>
#include <cstring>
#include <functional>
#include <list>
#include <ostream>
#include <queue>
#include <set>
#include <stdexcept>
#include <vector>
namespace ClipperLib {
enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
enum PolyType { ptSubject, ptClip };
// By far the most widely used winding rules for polygon filling are
// EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
// Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
// see http://glprogramming.com/red/chapter11.html
enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
#ifdef use_int32
typedef int cInt;
static cInt const loRange = 0x7FFF;
static cInt const hiRange = 0x7FFF;
#else
typedef signed long long cInt;
static cInt const loRange = 0x3FFFFFFF;
static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
typedef signed long long long64; // used by Int128 class
typedef unsigned long long ulong64;
#endif
struct IntPoint {
cInt X;
cInt Y;
#ifdef use_xyz
cInt Z;
IntPoint(cInt x = 0, cInt y = 0, cInt z = 0) : X(x), Y(y), Z(z){};
#else
IntPoint(cInt x = 0, cInt y = 0) : X(x), Y(y){};
#endif
friend inline bool operator==(const IntPoint &a, const IntPoint &b) {
return a.X == b.X && a.Y == b.Y;
}
friend inline bool operator!=(const IntPoint &a, const IntPoint &b) {
return a.X != b.X || a.Y != b.Y;
}
};
//------------------------------------------------------------------------------
typedef std::vector<IntPoint> Path;
typedef std::vector<Path> Paths;
inline Path &operator<<(Path &poly, const IntPoint &p) {
poly.push_back(p);
return poly;
}
inline Paths &operator<<(Paths &polys, const Path &p) {
polys.push_back(p);
return polys;
}
std::ostream &operator<<(std::ostream &s, const IntPoint &p);
std::ostream &operator<<(std::ostream &s, const Path &p);
std::ostream &operator<<(std::ostream &s, const Paths &p);
struct DoublePoint {
double X;
double Y;
DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
};
//------------------------------------------------------------------------------
#ifdef use_xyz
typedef void (*ZFillCallback)(IntPoint &e1bot, IntPoint &e1top, IntPoint &e2bot,
IntPoint &e2top, IntPoint &pt);
#endif
enum InitOptions {
ioReverseSolution = 1,
ioStrictlySimple = 2,
ioPreserveCollinear = 4
};
enum JoinType { jtSquare, jtRound, jtMiter };
enum EndType {
etClosedPolygon,
etClosedLine,
etOpenButt,
etOpenSquare,
etOpenRound
};
class PolyNode;
typedef std::vector<PolyNode *> PolyNodes;
class PolyNode {
public:
PolyNode();
virtual ~PolyNode(){};
Path Contour;
PolyNodes Childs;
PolyNode *Parent;
PolyNode *GetNext() const;
bool IsHole() const;
bool IsOpen() const;
int ChildCount() const;
private:
// PolyNode& operator =(PolyNode& other);
unsigned Index; // node index in Parent.Childs
bool m_IsOpen;
JoinType m_jointype;
EndType m_endtype;
PolyNode *GetNextSiblingUp() const;
void AddChild(PolyNode &child);
friend class Clipper; // to access Index
friend class ClipperOffset;
};
class PolyTree : public PolyNode {
public:
~PolyTree() { Clear(); };
PolyNode *GetFirst() const;
void Clear();
int Total() const;
private:
// PolyTree& operator =(PolyTree& other);
PolyNodes AllNodes;
friend class Clipper; // to access AllNodes
};
bool Orientation(const Path &poly);
double Area(const Path &poly);
int PointInPolygon(const IntPoint &pt, const Path &path);
void SimplifyPolygon(const Path &in_poly, Paths &out_polys,
PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys,
PolyFillType fillType = pftEvenOdd);
void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
void CleanPolygon(const Path &in_poly, Path &out_poly, double distance = 1.415);
void CleanPolygon(Path &poly, double distance = 1.415);
void CleanPolygons(const Paths &in_polys, Paths &out_polys,
double distance = 1.415);
void CleanPolygons(Paths &polys, double distance = 1.415);
void MinkowskiSum(const Path &pattern, const Path &path, Paths &solution,
bool pathIsClosed);
void MinkowskiSum(const Path &pattern, const Paths &paths, Paths &solution,
bool pathIsClosed);
void MinkowskiDiff(const Path &poly1, const Path &poly2, Paths &solution);
void PolyTreeToPaths(const PolyTree &polytree, Paths &paths);
void ClosedPathsFromPolyTree(const PolyTree &polytree, Paths &paths);
void OpenPathsFromPolyTree(PolyTree &polytree, Paths &paths);
void ReversePath(Path &p);
void ReversePaths(Paths &p);
struct IntRect {
cInt left;
cInt top;
cInt right;
cInt bottom;
};
// enums that are used internally ...
enum EdgeSide { esLeft = 1, esRight = 2 };
// forward declarations (for stuff used internally) ...
struct TEdge;
struct IntersectNode;
struct LocalMinimum;
struct OutPt;
struct OutRec;
struct Join;
typedef std::vector<OutRec *> PolyOutList;
typedef std::vector<TEdge *> EdgeList;
typedef std::vector<Join *> JoinList;
typedef std::vector<IntersectNode *> IntersectList;
//------------------------------------------------------------------------------
// ClipperBase is the ancestor to the Clipper class. It should not be
// instantiated directly. This class simply abstracts the conversion of sets of
// polygon coordinates into edge objects that are stored in a LocalMinima list.
class ClipperBase {
public:
ClipperBase();
virtual ~ClipperBase();
virtual bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
virtual void Clear();
IntRect GetBounds();
bool PreserveCollinear() { return m_PreserveCollinear; };
void PreserveCollinear(bool value) { m_PreserveCollinear = value; };
protected:
void DisposeLocalMinimaList();
TEdge *AddBoundsToLML(TEdge *e, bool IsClosed);
virtual void Reset();
TEdge *ProcessBound(TEdge *E, bool IsClockwise);
void InsertScanbeam(const cInt Y);
bool PopScanbeam(cInt &Y);
bool LocalMinimaPending();
bool PopLocalMinima(cInt Y, const LocalMinimum *&locMin);
OutRec *CreateOutRec();
void DisposeAllOutRecs();
void DisposeOutRec(PolyOutList::size_type index);
void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
void DeleteFromAEL(TEdge *e);
void UpdateEdgeIntoAEL(TEdge *&e);
typedef std::vector<LocalMinimum> MinimaList;
MinimaList::iterator m_CurrentLM;
MinimaList m_MinimaList;
bool m_UseFullRange;
EdgeList m_edges;
bool m_PreserveCollinear;
bool m_HasOpenPaths;
PolyOutList m_PolyOuts;
TEdge *m_ActiveEdges;
typedef std::priority_queue<cInt> ScanbeamList;
ScanbeamList m_Scanbeam;
};
//------------------------------------------------------------------------------
class Clipper : public virtual ClipperBase {
public:
Clipper(int initOptions = 0);
bool Execute(ClipType clipType, Paths &solution,
PolyFillType fillType = pftEvenOdd);
bool Execute(ClipType clipType, Paths &solution, PolyFillType subjFillType,
PolyFillType clipFillType);
bool Execute(ClipType clipType, PolyTree &polytree,
PolyFillType fillType = pftEvenOdd);
bool Execute(ClipType clipType, PolyTree &polytree, PolyFillType subjFillType,
PolyFillType clipFillType);
bool ReverseSolution() { return m_ReverseOutput; };
void ReverseSolution(bool value) { m_ReverseOutput = value; };
bool StrictlySimple() { return m_StrictSimple; };
void StrictlySimple(bool value) { m_StrictSimple = value; };
// set the callback function for z value filling on intersections (otherwise
// Z is 0)
#ifdef use_xyz
void ZFillFunction(ZFillCallback zFillFunc);
#endif
protected:
virtual bool ExecuteInternal();
private:
JoinList m_Joins;
JoinList m_GhostJoins;
IntersectList m_IntersectList;
ClipType m_ClipType;
typedef std::list<cInt> MaximaList;
MaximaList m_Maxima;
TEdge *m_SortedEdges;
bool m_ExecuteLocked;
PolyFillType m_ClipFillType;
PolyFillType m_SubjFillType;
bool m_ReverseOutput;
bool m_UsingPolyTree;
bool m_StrictSimple;
#ifdef use_xyz
ZFillCallback m_ZFill; // custom callback
#endif
void SetWindingCount(TEdge &edge);
bool IsEvenOddFillType(const TEdge &edge) const;
bool IsEvenOddAltFillType(const TEdge &edge) const;
void InsertLocalMinimaIntoAEL(const cInt botY);
void InsertEdgeIntoAEL(TEdge *edge, TEdge *startEdge);
void AddEdgeToSEL(TEdge *edge);
bool PopEdgeFromSEL(TEdge *&edge);
void CopyAELToSEL();
void DeleteFromSEL(TEdge *e);
void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
bool IsContributing(const TEdge &edge) const;
bool IsTopHorz(const cInt XPos);
void DoMaxima(TEdge *e);
void ProcessHorizontals();
void ProcessHorizontal(TEdge *horzEdge);
void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutPt *AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
OutRec *GetOutRec(int idx);
void AppendPolygon(TEdge *e1, TEdge *e2);
void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
OutPt *AddOutPt(TEdge *e, const IntPoint &pt);
OutPt *GetLastOutPt(TEdge *e);
bool ProcessIntersections(const cInt topY);
void BuildIntersectList(const cInt topY);
void ProcessIntersectList();
void ProcessEdgesAtTopOfScanbeam(const cInt topY);
void BuildResult(Paths &polys);
void BuildResult2(PolyTree &polytree);
void SetHoleState(TEdge *e, OutRec *outrec);
void DisposeIntersectNodes();
bool FixupIntersectionOrder();
void FixupOutPolygon(OutRec &outrec);
void FixupOutPolyline(OutRec &outrec);
bool IsHole(TEdge *e);
bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
void FixHoleLinkage(OutRec &outrec);
void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
void ClearJoins();
void ClearGhostJoins();
void AddGhostJoin(OutPt *op, const IntPoint offPt);
bool JoinPoints(Join *j, OutRec *outRec1, OutRec *outRec2);
void JoinCommonEdges();
void DoSimplePolygons();
void FixupFirstLefts1(OutRec *OldOutRec, OutRec *NewOutRec);
void FixupFirstLefts2(OutRec *InnerOutRec, OutRec *OuterOutRec);
void FixupFirstLefts3(OutRec *OldOutRec, OutRec *NewOutRec);
#ifdef use_xyz
void SetZ(IntPoint &pt, TEdge &e1, TEdge &e2);
#endif
};
//------------------------------------------------------------------------------
class ClipperOffset {
public:
ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
~ClipperOffset();
void AddPath(const Path &path, JoinType joinType, EndType endType);
void AddPaths(const Paths &paths, JoinType joinType, EndType endType);
void Execute(Paths &solution, double delta);
void Execute(PolyTree &solution, double delta);
void Clear();
double MiterLimit;
double ArcTolerance;
private:
Paths m_destPolys;
Path m_srcPoly;
Path m_destPoly;
std::vector<DoublePoint> m_normals;
double m_delta, m_sinA, m_sin, m_cos;
double m_miterLim, m_StepsPerRad;
IntPoint m_lowest;
PolyNode m_polyNodes;
void FixOrientations();
void DoOffset(double delta);
void OffsetPoint(int j, int &k, JoinType jointype);
void DoSquare(int j, int k);
void DoMiter(int j, int k, double r);
void DoRound(int j, int k);
};
//------------------------------------------------------------------------------
class clipperException : public std::exception {
public:
clipperException(const char *description) : m_descr(description) {}
virtual ~clipperException() throw() {}
virtual const char *what() const throw() { return m_descr.c_str(); }
private:
std::string m_descr;
};
//------------------------------------------------------------------------------
} // namespace ClipperLib
#endif // clipper_hpp
@@ -0,0 +1,275 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import UIKit
// MARK: - App State
/// The complete set of states the app can be in.
/// Drives all UI rendering via a single `@Published` property on `OCRViewModel`.
enum AppState: Equatable {
/// Models are being loaded from the bundle.
case loadingModels
/// Models are loaded and ready; waiting for the user to select an image.
case ready
/// An image is being processed by OCR.
case processing(UIImage)
/// OCR completed successfully with results and the processed image.
/// `runId` distinguishes successive successful runs for ``Equatable`` without requiring ``OCRRunResult`` to conform.
case results(OCRRunResult, UIImage, runId: UUID)
/// An error occurred during model loading or inference.
case error(AppError)
static func == (lhs: AppState, rhs: AppState) -> Bool {
switch (lhs, rhs) {
case (.loadingModels, .loadingModels): return true
case (.ready, .ready): return true
case (.processing, .processing): return true
case (.results(_, _, let runIdL), .results(_, _, let runIdR)): return runIdL == runIdR
case (.error(let a), .error(let b)): return a == b
default: return false
}
}
}
// MARK: - App Error
/// User-facing errors with recovery guidance.
enum AppError: Equatable, LocalizedError {
case modelLoadFailed(String)
case inferenceFailed(String)
case imageLoadFailed
var errorDescription: String? {
switch self {
case .modelLoadFailed(let msg): return msg
case .inferenceFailed(let msg): return msg
case .imageLoadFailed: return "Could not load the selected image. Try a different one."
}
}
/// Whether this error is recoverable by retrying model load (vs just selecting a new image).
var isModelError: Bool {
if case .modelLoadFailed = self { return true }
return false
}
}
// MARK: - OCRViewModel
/// Central view model that manages the complete app lifecycle.
///
/// State transitions:
/// ```
/// loadingModels --> ready --> processing --> results
/// | ^ | |
/// v | v v
/// error ----retry----> error ready (reset)
/// ```
///
/// All state mutations happen on `@MainActor` through the single
/// `@Published var state` property, giving SwiftUI a single source of truth.
@MainActor
class OCRViewModel: ObservableObject {
@Published var state: AppState = .loadingModels
@Published var copiedFeedback: Bool = false
@Published var runtimeParams = OCRRuntimeParams.noOverrides
/// ONNX Runtime presets and tuning shown in UI (draft). Use **Apply & reload** in Advanced settings to reload sessions (`loadModels()`).
@Published var ortPrimaryExecutionProvider: ORTPrimaryExecutionProvider = .cpu
@Published var ortSessionTuning = ORTSessionTuningOptions.default
/// Snapshot of Ort settings actually used by the loaded ``ocrEngine``.
private var ortLoadedPrimaryExecutionProvider: ORTPrimaryExecutionProvider = .cpu
private var ortLoadedSessionTuning: ORTSessionTuningOptions = .default
@Published private(set) var resolvedRuntimeBaseline: ResolvedOCRRuntimeParams?
private var sessionManager: ORTSessionManager?
private var ocrEngine: OCREngine?
/// Last image run through OCR (normalized orientation), for **Re-run OCR** without re-picking.
private var lastNormalizedImage: UIImage?
/// OCR runtime parameters used for the last successful run (drives ``hasPendingOcrChanges``).
private var lastRunRuntimeParams: OCRRuntimeParams?
/// Bundled sample resource names (stem or `stem.ext`) for ``selectSampleImage(named:)``.
let sampleImageNames: [String] = [DemoAssets.defaultSampleImageStem]
/// Draft Ort settings differ from the configuration used by loaded sessions.
var hasUnappliedOrtSettings: Bool {
ortPrimaryExecutionProvider != ortLoadedPrimaryExecutionProvider
|| ortSessionTuning != ortLoadedSessionTuning
}
/// `runtimeParams` differs from the last successful OCR run (only meaningful in ``AppState/results``).
var hasPendingOcrChanges: Bool {
guard case .results = state else { return false }
guard let last = lastRunRuntimeParams else { return false }
return runtimeParams != last
}
/// When `false`, disable Apply/Revert (reload would conflict with loading or OCR in flight).
var allowsOrtApplyControls: Bool {
switch state {
case .loadingModels, .processing: return false
case .ready, .results, .error: return true
}
}
/// Restores ONNX Runtime controls to match the currently loaded sessions.
func revertOrtDraftToLoaded() {
ortPrimaryExecutionProvider = ortLoadedPrimaryExecutionProvider
ortSessionTuning = ortLoadedSessionTuning
}
/// Photo picker or file load produced unusable image data.
func reportImageLoadFailed() {
state = .error(.imageLoadFailed)
}
// MARK: - Lifecycle
/// Load ORT models from the app bundle.
///
/// Creates an `ORTSessionManager`, loads both detection and recognition models,
/// then creates the `OCREngine` for end-to-end OCR.
func loadModels() async {
state = .loadingModels
do {
let manager = ORTSessionManager()
try await manager.loadModels(executionProvider: ortPrimaryExecutionProvider, tuning: ortSessionTuning)
let engine = try OCREngine(sessionManager: manager)
self.sessionManager = manager
self.ocrEngine = engine
self.resolvedRuntimeBaseline = engine.baselineRuntimeDefaults()
ortLoadedPrimaryExecutionProvider = ortPrimaryExecutionProvider
ortLoadedSessionTuning = ortSessionTuning
state = .ready
} catch {
state = .error(.modelLoadFailed(error.localizedDescription))
}
}
// MARK: - Image Processing
/// Run full OCR on a user-selected image.
///
/// Normalizes orientation first (camera photos often have EXIF rotation),
/// then delegates to `OCREngine.run(_:)`.
func processImage(_ uiImage: UIImage) async {
let normalized = normalizeOrientation(uiImage)
lastNormalizedImage = normalized
state = .processing(normalized)
guard let cgImage = normalized.cgImage else {
state = .error(.imageLoadFailed)
return
}
guard let engine = ocrEngine else {
state = .error(.modelLoadFailed("OCR engine is not ready."))
return
}
do {
let result = try await engine.run(cgImage, params: runtimeParams)
lastRunRuntimeParams = runtimeParams
state = .results(result, normalized, runId: UUID())
} catch {
lastNormalizedImage = nil
state = .error(.inferenceFailed(error.localizedDescription))
}
}
/// Runs OCR again on the **last image** using the current `runtimeParams` (e.g. after tuning sliders).
func rerunOCR() async {
guard let image = lastNormalizedImage else { return }
await processImage(image)
}
/// Load a bundled sample image by name and run OCR on it.
func selectSampleImage(named name: String) async {
guard let path = Bundle.main.path(forBundledImageNamed: name, subdirectory: "SampleImages") else {
state = .error(.imageLoadFailed)
return
}
do {
guard let uiFromFile = UIImage(contentsOfFile: path) else {
state = .error(.imageLoadFailed)
return
}
let normalized = normalizeOrientation(uiFromFile)
lastNormalizedImage = normalized
state = .processing(normalized)
guard let cgImage = normalized.cgImage else {
state = .error(.imageLoadFailed)
return
}
guard let engine = ocrEngine else {
state = .error(.modelLoadFailed("OCR engine is not ready."))
return
}
let result = try await engine.run(cgImage, params: runtimeParams)
lastRunRuntimeParams = runtimeParams
state = .results(result, normalized, runId: UUID())
} catch {
lastNormalizedImage = nil
state = .error(.inferenceFailed(error.localizedDescription))
}
}
// MARK: - Result Actions
/// Copy all recognized text to the system clipboard, with brief visual feedback.
func copyResultsToClipboard() {
guard case .results(let result, _, _) = state else { return }
let allText = result.results.map(\.text).joined(separator: "\n")
UIPasteboard.general.string = allText
copiedFeedback = true
Task {
try? await Task.sleep(nanoseconds: 2_000_000_000)
copiedFeedback = false
}
}
// MARK: - Error Recovery
/// Retry after an error. Model errors reload models; other errors return to ready state.
func retry() async {
guard case .error(let error) = state else { return }
if error.isModelError {
await loadModels()
} else {
state = .ready
}
}
/// Return to the ready state (e.g. after viewing results, user wants to pick a new image).
func reset() {
lastNormalizedImage = nil
lastRunRuntimeParams = nil
state = .ready
}
}
// MARK: - Image Orientation
/// Normalize EXIF orientation by redrawing the image in `.up` orientation.
///
/// Camera photos from the photo picker often carry non-`.up` orientation metadata.
/// CoreGraphics ignores EXIF orientation, so we must flatten it before OCR processing.
private func normalizeOrientation(_ image: UIImage) -> UIImage {
guard image.imageOrientation != .up else { return image }
let format = UIGraphicsImageRendererFormat()
format.scale = image.scale
let renderer = UIGraphicsImageRenderer(size: image.size, format: format)
return renderer.image { _ in
image.draw(in: CGRect(origin: .zero, size: image.size))
}
}
@@ -0,0 +1,106 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
/// Advanced ONNX Runtime and OCR parameters, presented as a sheet from the main screen toolbar.
struct EngineSettingsSheet: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var viewModel: OCRViewModel
@State private var ortSessionReloadConfirmed = false
var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
DemoSectionHeader(
title: "ONNX Runtime",
subtitle: "Choose execution provider and options, then reload to apply."
)
DemoCard {
OnnxRuntimeSettingsPanel(
primaryExecutionProvider: $viewModel.ortPrimaryExecutionProvider,
tuning: $viewModel.ortSessionTuning
)
}
DemoSectionHeader(
title: "OCR parameters",
subtitle: "These apply to the next OCR run."
)
DemoCard {
OCRParametersPanel(
params: $viewModel.runtimeParams,
resolvedBaseline: viewModel.resolvedRuntimeBaseline ?? .fallbackForUI
)
}
}
.padding(20)
.padding(.bottom, viewModel.hasUnappliedOrtSettings ? 120 : 24)
}
.background(Color(.systemGroupedBackground))
.navigationTitle("Engine & parameters")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") {
dismiss()
}
}
}
.safeAreaInset(edge: .bottom, spacing: 0) {
if viewModel.hasUnappliedOrtSettings {
VStack(alignment: .leading, spacing: 12) {
Divider()
Text("Sessions still use the previous ONNX Runtime choices until you reload.")
.font(.footnote)
.foregroundStyle(Color.orange.opacity(0.95))
.fixedSize(horizontal: false, vertical: true)
HStack(spacing: 12) {
Button("Revert draft") {
viewModel.revertOrtDraftToLoaded()
}
.disabled(!viewModel.allowsOrtApplyControls || !viewModel.hasUnappliedOrtSettings)
Button {
ortSessionReloadConfirmed = true
} label: {
Label("Apply & reload", systemImage: "arrow.clockwise.circle")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.disabled(!viewModel.allowsOrtApplyControls || !viewModel.hasUnappliedOrtSettings)
}
}
.padding(.horizontal, 20)
.padding(.vertical, 12)
.background(.ultraThinMaterial)
}
}
}
.confirmationDialog(
"Rebuild ONNX Runtime sessions?",
isPresented: $ortSessionReloadConfirmed,
titleVisibility: .visible
) {
Button("Reload models") {
Task { await viewModel.loadModels() }
}
Button("Cancel", role: .cancel) {}
} message: {
Text("Sessions are recreated from the bundle. Expect a short pause.")
}
}
}
@@ -0,0 +1,60 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
/// Displays an error state with icon, message, and retry button.
struct ErrorView: View {
let error: AppError
let onRetry: () -> Void
var body: some View {
VStack(spacing: 8) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 48))
.symbolRenderingMode(.hierarchical)
.foregroundStyle(errorSeverityColor)
Text(errorTitle)
.font(.title2)
.fontWeight(.semibold)
Text(error.localizedDescription)
.font(.body)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
Button(action: onRetry) {
Label("Retry", systemImage: "arrow.clockwise")
}
.buttonStyle(.borderedProminent)
.padding(.top, 8)
}
}
private var errorTitle: String {
switch error {
case .modelLoadFailed: return "Model Loading Failed"
case .inferenceFailed: return "OCR Failed"
case .imageLoadFailed: return "Image Error"
}
}
private var errorSeverityColor: Color {
switch error {
case .imageLoadFailed: return Color(.systemOrange)
case .modelLoadFailed, .inferenceFailed: return Color(.systemRed)
}
}
}
@@ -0,0 +1,83 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import PhotosUI
import SwiftUI
/// Image selection UI: a prominent "Choose Photo" button backed by PhotosPicker,
/// plus a row of sample image thumbnails for quick demo access.
struct ImagePickerSection: View {
@Binding var selectedItem: PhotosPickerItem?
let sampleImageNames: [String]
let onSampleSelected: (String) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
// Primary CTA: system photo picker
PhotosPicker(
selection: $selectedItem,
matching: .images,
photoLibrary: .shared()
) {
Label("Choose Photo", systemImage: "photo.on.rectangle")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
// Sample images row
if !sampleImageNames.isEmpty {
VStack(alignment: .leading, spacing: 8) {
Text("Or try a sample:")
.font(.subheadline)
.foregroundStyle(.secondary)
HStack(spacing: 8) {
ForEach(sampleImageNames, id: \.self) { name in
Button {
onSampleSelected(name)
} label: {
sampleThumbnail(named: name)
}
.buttonStyle(.plain)
.frame(minWidth: 44, minHeight: 44)
.contentShape(Rectangle())
.accessibilityLabel("Sample image: \(name)")
}
}
}
}
}
}
@ViewBuilder
private func sampleThumbnail(named name: String) -> some View {
if let path = Bundle.main.path(forBundledImageNamed: name, subdirectory: "SampleImages"),
let uiImage = UIImage(contentsOfFile: path) {
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 60, height: 60)
.clipShape(RoundedRectangle(cornerRadius: 8))
} else {
// Fallback for when image can't be loaded
RoundedRectangle(cornerRadius: 8)
.fill(Color(.tertiarySystemFill))
.frame(width: 60, height: 60)
.overlay(
Image(systemName: "photo")
.foregroundStyle(.secondary)
)
}
}
}
@@ -0,0 +1,226 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
/// Sliders for detection / recognition runtime parameters (content only; wrap with `DemoCard` in parent).
struct OCRParametersPanel: View {
@Binding var params: OCRRuntimeParams
let resolvedBaseline: ResolvedOCRRuntimeParams
var body: some View {
VStack(alignment: .leading, spacing: 0) {
groupTitle("Detection preprocess")
intParamRow(
title: "Limit side length",
caption: "Side length limit for detection resize",
range: 32...2048,
value: intOverrideBinding(\.textDetLimitSideLen, fallback: resolvedBaseline.textDetLimitSideLen)
)
limitTypeRow(
selection: stringOverrideBinding(\.textDetLimitType, fallback: resolvedBaseline.textDetLimitType)
)
intParamRow(
title: "Max side length cap",
caption: "After limit-side resize, caps the longer side if it is still above this",
range: 500...8000,
value: intOverrideBinding(\.textDetMaxSideLimit, fallback: resolvedBaseline.textDetMaxSideLimit)
)
groupTitle("Detection postprocess")
paramRow(
title: "Map threshold",
caption: "Binarization on the detector heatmap",
range: 0.05...0.95,
value: floatOverrideBinding(\.textDetThresh, fallback: resolvedBaseline.textDetThresh)
)
paramRow(
title: "Box score threshold",
caption: "Minimum score to keep a box",
range: 0.1...0.95,
value: floatOverrideBinding(\.textDetBoxThresh, fallback: resolvedBaseline.textDetBoxThresh)
)
paramRow(
title: "Unclip ratio",
caption: "Expand recovered polygons",
range: 0.5...3.0,
value: floatOverrideBinding(\.textDetUnclipRatio, fallback: resolvedBaseline.textDetUnclipRatio)
)
Divider()
.padding(.vertical, 12)
groupTitle("Recognition")
intParamRow(
title: "Recognition batch size",
caption: "Number of text lines per recognition run",
range: 1...32,
value: intOverrideBinding(\.textRecBatchSize, fallback: resolvedBaseline.textRecBatchSize)
)
paramRow(
title: "Line confidence",
caption: "Discard lines below this score",
range: 0...1,
value: floatOverrideBinding(\.textRecScoreThresh, fallback: resolvedBaseline.textRecScoreThresh)
)
HStack {
Spacer()
Button("Reset to defaults") {
params = .noOverrides
}
.font(.subheadline.weight(.medium))
}
.padding(.top, 4)
}
}
private func floatOverrideBinding(
_ keyPath: WritableKeyPath<OCRRuntimeParams, Float?>,
fallback: Float
) -> Binding<Float> {
Binding(
get: { params[keyPath: keyPath] ?? fallback },
set: { newValue in
var next = params
next[keyPath: keyPath] = newValue
params = next
}
)
}
private func intOverrideBinding(
_ keyPath: WritableKeyPath<OCRRuntimeParams, Int?>,
fallback: Int
) -> Binding<Int> {
Binding(
get: { params[keyPath: keyPath] ?? fallback },
set: { newValue in
var next = params
next[keyPath: keyPath] = newValue
params = next
}
)
}
private func stringOverrideBinding(
_ keyPath: WritableKeyPath<OCRRuntimeParams, String?>,
fallback: String
) -> Binding<String> {
Binding(
get: { params[keyPath: keyPath] ?? fallback },
set: { newValue in
var next = params
next[keyPath: keyPath] = newValue
params = next
}
)
}
private func groupTitle(_ text: String) -> some View {
Text(text)
.font(.subheadline.weight(.semibold))
.foregroundStyle(.primary)
.padding(.bottom, 8)
}
private func paramRow(
title: String,
caption: String,
range: ClosedRange<Float>,
value: Binding<Float>
) -> some View {
VStack(alignment: .leading, spacing: 6) {
HStack(alignment: .firstTextBaseline) {
VStack(alignment: .leading, spacing: 2) {
Text(title)
.font(.subheadline)
Text(caption)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
Text(String(format: "%.3f", value.wrappedValue))
.font(.caption.monospacedDigit())
.foregroundStyle(.secondary)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Color(.tertiarySystemFill), in: Capsule())
}
Slider(
value: Binding(
get: { Double(value.wrappedValue) },
set: { value.wrappedValue = Float($0) }
),
in: Double(range.lowerBound)...Double(range.upperBound)
)
.tint(Color.accentColor)
}
.padding(.bottom, 14)
}
private func intParamRow(
title: String,
caption: String,
range: ClosedRange<Int>,
value: Binding<Int>
) -> some View {
VStack(alignment: .leading, spacing: 6) {
HStack(alignment: .firstTextBaseline) {
VStack(alignment: .leading, spacing: 2) {
Text(title)
.font(.subheadline)
Text(caption)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
Text("\(value.wrappedValue)")
.font(.caption.monospacedDigit())
.foregroundStyle(.secondary)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Color(.tertiarySystemFill), in: Capsule())
}
Slider(
value: Binding(
get: { Double(value.wrappedValue) },
set: { value.wrappedValue = Int($0.rounded()) }
),
in: Double(range.lowerBound)...Double(range.upperBound),
step: 1
)
.tint(Color.accentColor)
}
.padding(.bottom, 14)
}
private func limitTypeRow(selection: Binding<String>) -> some View {
VStack(alignment: .leading, spacing: 6) {
VStack(alignment: .leading, spacing: 2) {
Text("Limit type")
.font(.subheadline)
Text("min: shortest side ≥ limit length; max: longest side ≤ limit length")
.font(.caption)
.foregroundStyle(.secondary)
}
Picker("Limit type", selection: selection) {
Text("min").tag("min")
Text("max").tag("max")
}
.pickerStyle(.segmented)
}
.padding(.bottom, 14)
}
}
@@ -0,0 +1,225 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
private enum CoreMLComputeMode: String, CaseIterable, Identifiable {
case automatic
case cpuOnly
case cpuAndGPU
case devicesWithANE
var id: String { rawValue }
var segmentLabel: String {
switch self {
case .automatic: return "Auto"
case .cpuOnly: return "CPU"
case .cpuAndGPU: return "CPU+GPU"
case .devicesWithANE: return "ANE"
}
}
static func from(flags: Set<String>) -> CoreMLComputeMode {
let cpuOnly = ORTCoreMLProviderOption.cpuOnly.rawValue
let cpuAndGPU = ORTCoreMLProviderOption.cpuAndGPU.rawValue
let aneOnly = ORTCoreMLProviderOption.aneOnly.rawValue
if flags.contains(cpuOnly) { return .cpuOnly }
if flags.contains(cpuAndGPU) { return .cpuAndGPU }
if flags.contains(aneOnly) { return .devicesWithANE }
return .automatic
}
func merge(into flags: inout Set<String>) {
let cpuOnly = ORTCoreMLProviderOption.cpuOnly.rawValue
let cpuAndGPU = ORTCoreMLProviderOption.cpuAndGPU.rawValue
let aneOnly = ORTCoreMLProviderOption.aneOnly.rawValue
flags.remove(cpuOnly)
flags.remove(cpuAndGPU)
flags.remove(aneOnly)
switch self {
case .automatic: break
case .cpuOnly: flags.insert(cpuOnly)
case .cpuAndGPU: flags.insert(cpuAndGPU)
case .devicesWithANE: flags.insert(aneOnly)
}
}
}
/// ONNX Runtime: preferred execution provider (EP) preset plus session tuning. Card content only.
struct OnnxRuntimeSettingsPanel: View {
private static let coreMLExtraToggleOptions: [ORTCoreMLProviderOption] =
[.enableOnSubgraphs, .createMLProgram, .staticInputShapes]
@Binding var primaryExecutionProvider: ORTPrimaryExecutionProvider
@Binding var tuning: ORTSessionTuningOptions
var body: some View {
VStack(alignment: .leading, spacing: 14) {
Text("All inference uses ONNX Runtime. Choose which EP is preferred first for this demo preset; unsupported operators still run on the CPU EP.")
.font(.caption)
.foregroundStyle(.secondary)
Picker("Execution provider", selection: $primaryExecutionProvider) {
ForEach(ORTPrimaryExecutionProvider.allCases) { provider in
Text(provider.displayTitle).tag(provider)
}
}
.pickerStyle(.segmented)
Divider()
.padding(.vertical, 2)
Text("Session options")
.font(.subheadline.weight(.semibold))
labeledStepper(
title: "Intra-op threads",
caption: "Session-wide CPU parallelism. Use 0 to leave ONNX Runtime’s default (no explicit limit).",
value: intraOpThreadsBinding,
range: 0...8
)
if primaryExecutionProvider == .xnnpack {
labeledStepper(
title: "XNNPACK intra-op threads",
caption: "0 leaves the XNNPACK EP default.",
value: xnnpackThreadsBinding,
range: 0...8
)
}
if primaryExecutionProvider == .coreML {
VStack(alignment: .leading, spacing: 10) {
Text("Core ML EP options")
.font(.subheadline.weight(.semibold))
.padding(.top, 4)
VStack(alignment: .leading, spacing: 6) {
Text("Core ML placement")
.font(.body)
Picker("Core ML placement", selection: coreMLComputeModeBinding) {
ForEach(CoreMLComputeMode.allCases) { mode in
Text(mode.segmentLabel).tag(mode)
}
}
.pickerStyle(.segmented)
Text(coreMLComputeModeCaption)
.font(.caption)
.foregroundStyle(.secondary)
}
ForEach(Self.coreMLExtraToggleOptions) { option in
Toggle(isOn: coreMLFlagBinding(option)) {
VStack(alignment: .leading, spacing: 2) {
Text(option.displayTitle)
Text(option.detailCaption)
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
}
}
HStack {
Spacer()
Button("Reset session options") {
tuning = .default
}
.font(.subheadline.weight(.medium))
}
.padding(.top, 4)
}
}
private var coreMLComputeModeCaption: String {
switch CoreMLComputeMode.from(flags: tuning.coreMLFlags) {
case .automatic:
return "ORT defaults — no cpuOnly/cpuAndGPU/device ANE restriction."
case .cpuOnly:
return "useCPUOnly — Core ML constrained to CPU."
case .cpuAndGPU:
return "useCPUAndGPU — CPU and GPU paths; excludes ANE in Core ML."
case .devicesWithANE:
return "Only enable Core ML EP on devices that have a Neural Engine."
}
}
private var intraOpThreadsBinding: Binding<Int> {
Binding(
get: { tuning.intraOpThreads },
set: { newValue in
var next = tuning
next.intraOpThreads = newValue
tuning = next
}
)
}
private var xnnpackThreadsBinding: Binding<Int> {
Binding(
get: { tuning.xnnpackThreads },
set: { newValue in
var next = tuning
next.xnnpackThreads = newValue
tuning = next
}
)
}
private var coreMLComputeModeBinding: Binding<CoreMLComputeMode> {
Binding(
get: { CoreMLComputeMode.from(flags: tuning.coreMLFlags) },
set: { mode in
var next = tuning
mode.merge(into: &next.coreMLFlags)
tuning = next
}
)
}
private func coreMLFlagBinding(_ option: ORTCoreMLProviderOption) -> Binding<Bool> {
let key = option.rawValue
return Binding(
get: { tuning.coreMLFlags.contains(key) },
set: { on in
var next = tuning
if on {
next.coreMLFlags.insert(key)
} else {
next.coreMLFlags.remove(key)
}
tuning = next
}
)
}
private func labeledStepper(title: String, caption: String, value: Binding<Int>, range: ClosedRange<Int>) -> some View {
VStack(alignment: .leading, spacing: 6) {
HStack(alignment: .firstTextBaseline) {
Text(title)
Spacer()
Stepper(value: value, in: range) {
Text("\(value.wrappedValue)")
.font(.body.monospacedDigit())
.frame(minWidth: 24, alignment: .trailing)
}
}
Text(caption)
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
@@ -0,0 +1,79 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
/// Displays the source image with bounding box polygon overlays drawn on a Canvas.
///
/// Polygon coordinates from `OCRResult.polygon` are in original image pixel space.
/// This view computes the scale factor and offset to map them to the displayed
/// image area, accounting for `.aspectFit` rendering within the available frame.
struct ResultImageView: View {
let image: UIImage
let results: [OCRResult]
var body: some View {
GeometryReader { geo in
let imageSize = image.size
let imageAspect = imageSize.width / imageSize.height
let viewAspect = geo.size.width / geo.size.height
// Compute the actual rendered image rect within the GeometryReader frame
let fitSize: CGSize = imageAspect > viewAspect
? CGSize(width: geo.size.width, height: geo.size.width / imageAspect)
: CGSize(width: geo.size.height * imageAspect, height: geo.size.height)
let offset = CGPoint(
x: (geo.size.width - fitSize.width) / 2,
y: (geo.size.height - fitSize.height) / 2
)
let scale = fitSize.width / imageSize.width
ZStack {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
Canvas { context, size in
for result in results {
let points = result.polygon.compactMap { coords -> CGPoint? in
guard coords.count >= 2 else { return nil }
return CGPoint(
x: CGFloat(coords[0]) * scale + offset.x,
y: CGFloat(coords[1]) * scale + offset.y
)
}
guard points.count >= 4 else { continue }
var path = Path()
path.move(to: points[0])
for pt in points.dropFirst() {
path.addLine(to: pt)
}
path.closeSubpath()
let strokeColor = Color.accentColor.opacity(0.9)
let fillColor = Color.accentColor.opacity(0.12)
context.stroke(path, with: .color(strokeColor), lineWidth: 2)
context.fill(path, with: .color(fillColor))
}
}
}
.frame(width: geo.size.width, height: geo.size.height)
}
.aspectRatio(image.size.width / image.size.height, contentMode: .fit)
.frame(maxHeight: 400)
.accessibilityElement(children: .combine)
.accessibilityLabel("Image preview with \(results.count) detected text regions")
}
}
@@ -0,0 +1,98 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
/// Recognized lines + copy action (intended to sit inside `DemoCard` from the parent).
struct ResultsListView: View {
let results: [OCRResult]
let copiedFeedback: Bool
let onCopy: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack(alignment: .firstTextBaseline) {
Text("Recognized text")
.font(.headline)
Spacer()
Button(action: onCopy) {
Label(
copiedFeedback ? "Copied" : "Copy all",
systemImage: copiedFeedback ? "checkmark.circle.fill" : "doc.on.doc"
)
.labelStyle(.titleAndIcon)
}
.font(.subheadline.weight(.medium))
.buttonStyle(.bordered)
.controlSize(.small)
.disabled(results.isEmpty)
}
.padding(.bottom, 12)
if results.isEmpty {
emptyState
} else {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(results.enumerated()), id: \.offset) { index, result in
resultRow(index: index, result: result)
if index < results.count - 1 {
Divider()
.padding(.vertical, 10)
}
}
}
}
}
}
private var emptyState: some View {
VStack(spacing: 12) {
Image(systemName: "text.magnifyingglass")
.font(.system(size: 32))
.foregroundStyle(.secondary)
.symbolRenderingMode(.hierarchical)
Text("No text to show")
.font(.subheadline.weight(.semibold))
Text("Try lowering thresholds or use an image with clearer text.")
.font(.caption)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 20)
}
private func resultRow(index: Int, result: OCRResult) -> some View {
HStack(alignment: .top, spacing: 12) {
Text("\(index + 1)")
.font(.caption.weight(.bold))
.foregroundStyle(.secondary)
.frame(width: 22, height: 22)
.background(Color(.tertiarySystemFill), in: Circle())
Text(result.text)
.font(.body)
.foregroundStyle(.primary)
.frame(maxWidth: .infinity, alignment: .leading)
.lineLimit(5)
Text(String(format: "%.0f%%", result.confidence * 100))
.font(.caption.monospacedDigit())
.foregroundStyle(.secondary)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(Color(.tertiarySystemFill), in: Capsule())
}
}
}
@@ -0,0 +1,54 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
/// Compact per-stage timing chips (fits the “output” section below the preview).
struct TimingView: View {
let result: OCRRunResult
var body: some View {
HStack(spacing: 10) {
chip(title: "Detect", ms: result.detectionTime)
chip(title: "Recognize", ms: result.recognitionTime)
chip(title: "Total", ms: result.totalTime, emphasized: true)
}
.frame(maxWidth: .infinity)
}
private func chip(title: String, ms: TimeInterval, emphasized: Bool = false) -> some View {
VStack(spacing: 6) {
Text(title)
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
Text(String(format: "%.0f", ms * 1000))
.font(.system(.body, design: .rounded).weight(emphasized ? .semibold : .regular))
.monospacedDigit()
Text("ms")
.font(.caption2)
.foregroundStyle(.tertiary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 12)
.padding(.horizontal, 8)
.background {
RoundedRectangle(cornerRadius: 12, style: .continuous)
.fill(emphasized ? Color.accentColor.opacity(0.12) : Color(.tertiarySystemFill))
}
.overlay {
RoundedRectangle(cornerRadius: 12, style: .continuous)
.strokeBorder(Color(.separator).opacity(0.25), lineWidth: 0.5)
}
}
}
@@ -0,0 +1,25 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Default bundled image file names for benchmark tests.
enum BenchmarkFixtures {
static let defaultReferenceImageStem: String = "ios_ocr_benchmark_reference"
static let defaultReferenceImageFileExtension: String = "jpg"
static var defaultReferenceImageFileName: String {
"\(defaultReferenceImageStem).\(defaultReferenceImageFileExtension)"
}
}
@@ -0,0 +1,95 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import Foundation
@testable import PaddleOCRDemo
/// Names for JSON written as `XCTAttachment`s; keep in sync with whatever exports attachments from test results.
enum BenchmarkArtifact: String {
case iOSExport = "ios-ocr-export.json"
case onDevicePerformance = "on-device-performance.json"
}
// MARK: - Accuracy export payload
struct OCRExportPayload: Codable {
var schemaVersion: Int = 1
var source: String
var items: [OCRExportItem]
}
struct OCRExportItem: Codable {
var polygon: [[Int]]
var text: String
var score: Double?
}
// MARK: - On-device performance payload
struct TimingSummary: Codable {
var mean: Double
var stdev: Double
var p90: Double
}
/// Pooled: one sample per det line per measured run (all lines concatenated, ms).
struct RecognitionPerLinePooledMs: Codable {
var count: Int
var inferenceMs: TimingSummary
var preprocessMs: TimingSummary
var postprocessMs: TimingSummary
var totalMs: TimingSummary
}
struct RecognitionPerLineBlock: Codable {
var pooled: RecognitionPerLinePooledMs
}
struct BenchmarkTensorShapeSample: Codable {
var shape: [Int]
var count: Int
}
struct BenchmarkInputShapeDistribution: Codable {
var detection: [BenchmarkTensorShapeSample]
var recognition: [BenchmarkTensorShapeSample]
}
struct OCRDeviceBenchmarkPayload: Codable {
var schemaVersion: Int = 1
var buildConfiguration: String
var deviceModel: String
var osVersion: String
var isSimulator: Bool
var ortExecutionProvider: String
var ortProfilingEnabled: Bool
var warmupIterations: Int
var measuredIterations: Int
var inputShapeDistribution: BenchmarkInputShapeDistribution
var firstMeasuredLineCount: Int
var coldLoadTimeMs: Double
var totalTimeMs: TimingSummary
var detectionTimeMs: TimingSummary
var detectionPreprocessTimeMs: TimingSummary
var detectionInferenceTimeMs: TimingSummary
var detectionPostprocessTimeMs: TimingSummary
var recognitionTimeMs: TimingSummary
var recognitionPreprocessTimeMs: TimingSummary
var recognitionInferenceTimeMs: TimingSummary
var recognitionPostprocessTimeMs: TimingSummary
var recognitionPerLine: RecognitionPerLineBlock?
var pipelineOverheadTimeMs: TimingSummary
var memoryFootprintBeforeLoadBytes: UInt64?
var memoryFootprintAfterLoadBytes: UInt64
var thermalState: String?
}
@@ -0,0 +1,2 @@
# Ad-hoc copies from ./scripts/run_validation.sh --image (local-*); not committed.
local-*
Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

@@ -0,0 +1,562 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Darwin
import Foundation
import XCTest
@testable import PaddleOCRDemo
import UIKit
// MARK: - Tests
final class OCRBenchmarkTests: XCTestCase {
/// `PADDLEOCR_BENCHMARK_IMAGE_NAME`: bundled image stem or `stem.ext` (optional).
private static let imageNameEnvKey = "PADDLEOCR_BENCHMARK_IMAGE_NAME"
/// Optional non-negative int; default `3`. Used only by `testOnDevicePerformanceMetrics`.
private static let warmupIterationsEnvKey = "PADDLEOCR_BENCHMARK_WARMUP_ITERATIONS"
/// Optional non-negative int; default `10`. Used only by `testOnDevicePerformanceMetrics`.
private static let measuredIterationsEnvKey = "PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS"
/// `CPU` (default), `XNNPACK`, or `CORE_ML` — ONNX Runtime execution provider preset for benchmarks.
private static let ortExecutionProviderEnvKey = "PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER"
/// `1` / `true` / `yes` / `on` enables ONNX Runtime JSON profiling (see ``ORTSessionManager/finalizeORTProfiling()``).
/// When set, on-device performance timings are not representative of a clean latency benchmark.
private static let ortProfilingEnvKey = "PADDLEOCR_BENCHMARK_ORT_PROFILING"
private static let buildConfigurationEnvKey = "PADDLEOCR_BENCHMARK_BUILD_CONFIGURATION"
private static let intraOpThreadsEnvKey = "PADDLEOCR_BENCHMARK_INTRA_OP_THREADS"
private static let xnnpackThreadsEnvKey = "PADDLEOCR_BENCHMARK_XNNPACK_THREADS"
private static let coremlOptionsEnvKey = "PADDLEOCR_BENCHMARK_COREML_OPTIONS"
private static let recBatchSizeEnvKey = "PADDLEOCR_BENCHMARK_REC_BATCH_SIZE"
func testOCRExportJSONSchema() async throws {
let cgImage = try resolveBenchmarkImage()
let executionProvider = try resolveBenchmarkExecutionProvider()
let manager = ORTSessionManager()
try await manager.loadModels(executionProvider: executionProvider, ortProfiling: resolveORTProfilingEnabled(), tuning: resolveSessionTuningOptions())
let engine = try OCREngine(sessionManager: manager)
let run = try await engine.run(cgImage, params: .noOverrides)
let payload = OCRExportPayload(
source: "ios_ocr_demo",
items: run.results.map { r in
OCRExportItem(
polygon: r.polygon.map { $0.map { Int($0) } },
text: r.text,
score: Double(r.confidence)
)
}
)
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
let data = try encoder.encode(payload)
_ = try JSONDecoder().decode(OCRExportPayload.self, from: data)
attachJSON(data, artifact: .iOSExport)
if resolveORTProfilingEnabled(), let out = try await manager.finalizeORTProfiling() {
attachProfileFile(out.detectionProfileJSON, name: "ort_profile_detection")
attachProfileFile(out.recognitionProfileJSON, name: "ort_profile_recognition")
}
}
func testOnDeviceLatencyBenchmark() async throws {
let executionProvider = try resolveBenchmarkExecutionProvider()
let ortProfiling = resolveORTProfilingEnabled()
let context = try await makeBenchmarkContext(executionProvider: executionProvider, ortProfiling: ortProfiling)
let warmup = try parseNonNegativeIntEnv(Self.warmupIterationsEnvKey, defaultValue: 3)
let iterations = max(try parseNonNegativeIntEnv(Self.measuredIterationsEnvKey, defaultValue: 10), 1)
try await runWarmup(engine: context.engine, image: context.cgImage, iterations: warmup)
var totals: [Double] = []
var dets: [Double] = []
var detPre: [Double] = []
var detInf: [Double] = []
var detPost: [Double] = []
var recs: [Double] = []
var recPre: [Double] = []
var recInf: [Double] = []
var recPost: [Double] = []
var overheads: [Double] = []
totals.reserveCapacity(iterations)
dets.reserveCapacity(iterations)
detPre.reserveCapacity(iterations)
detInf.reserveCapacity(iterations)
detPost.reserveCapacity(iterations)
recs.reserveCapacity(iterations)
recPre.reserveCapacity(iterations)
recInf.reserveCapacity(iterations)
recPost.reserveCapacity(iterations)
overheads.reserveCapacity(iterations)
var lineInferenceMsPooled: [Double] = []
var linePreprocessMsPooled: [Double] = []
var linePostprocessMsPooled: [Double] = []
var lineTotalMsPooled: [Double] = []
var firstMeasuredLineCount = 0
var detectionInputShapes: [[Int]] = []
var recognitionInputShapes: [[Int]] = []
let benchmarkParams = resolveBenchmarkRuntimeParams()
for index in 0..<iterations {
let run = try await context.engine.run(context.cgImage, params: benchmarkParams)
if index == 0 {
firstMeasuredLineCount = run.recognitionLineCount
}
detectionInputShapes.append(run.detectionInputTensorShape)
recognitionInputShapes.append(contentsOf: run.recognitionInputTensorShapes)
appendRun(
run,
totals: &totals,
dets: &dets,
detPre: &detPre,
detInf: &detInf,
detPost: &detPost,
recs: &recs,
recPre: &recPre,
recInf: &recInf,
recPost: &recPost,
overheads: &overheads,
lineInferenceMsPooled: &lineInferenceMsPooled,
linePreprocessMsPooled: &linePreprocessMsPooled,
linePostprocessMsPooled: &linePostprocessMsPooled,
lineTotalMsPooled: &lineTotalMsPooled
)
}
let perLine: RecognitionPerLineBlock? = lineInferenceMsPooled.isEmpty
? nil
: RecognitionPerLineBlock(
pooled: RecognitionPerLinePooledMs(
count: lineInferenceMsPooled.count,
inferenceMs: summarizeMs(lineInferenceMsPooled),
preprocessMs: summarizeMs(linePreprocessMsPooled),
postprocessMs: summarizeMs(linePostprocessMsPooled),
totalMs: summarizeMs(lineTotalMsPooled)
)
)
let stats = OCRDeviceBenchmarkPayload(
schemaVersion: 1,
buildConfiguration: resolveBuildConfiguration(),
deviceModel: deviceModelName(),
osVersion: ProcessInfo.processInfo.operatingSystemVersionString,
isSimulator: isRunningOnSimulator(),
ortExecutionProvider: executionProvider.rawValue,
ortProfilingEnabled: ortProfiling,
warmupIterations: warmup,
measuredIterations: iterations,
inputShapeDistribution: BenchmarkInputShapeDistribution(
detection: summarizeShapes(detectionInputShapes),
recognition: summarizeShapes(recognitionInputShapes)
),
firstMeasuredLineCount: firstMeasuredLineCount,
coldLoadTimeMs: context.coldLoadTime * 1000,
totalTimeMs: summarizeMs(totals),
detectionTimeMs: summarizeMs(dets),
detectionPreprocessTimeMs: summarizeMs(detPre),
detectionInferenceTimeMs: summarizeMs(detInf),
detectionPostprocessTimeMs: summarizeMs(detPost),
recognitionTimeMs: summarizeMs(recs),
recognitionPreprocessTimeMs: summarizeMs(recPre),
recognitionInferenceTimeMs: summarizeMs(recInf),
recognitionPostprocessTimeMs: summarizeMs(recPost),
recognitionPerLine: perLine,
pipelineOverheadTimeMs: summarizeMs(overheads),
memoryFootprintBeforeLoadBytes: context.memoryBeforeLoad,
memoryFootprintAfterLoadBytes: context.memoryAfterLoad,
thermalState: String(describing: ProcessInfo.processInfo.thermalState)
)
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
let encoded = try encoder.encode(stats)
let json = String(data: encoded, encoding: .utf8) ?? ""
XCTAssertFalse(json.isEmpty, "on-device performance stats should encode")
attachJSON(encoded, artifact: .onDevicePerformance)
if ortProfiling, let out = try await context.manager.finalizeORTProfiling() {
attachProfileFile(out.detectionProfileJSON, name: "ort_profile_detection")
attachProfileFile(out.recognitionProfileJSON, name: "ort_profile_recognition")
}
}
func testOnDeviceMemoryBenchmark() async throws {
let executionProvider = try resolveBenchmarkExecutionProvider()
let context = try await makeBenchmarkContext(executionProvider: executionProvider, ortProfiling: false)
let warmup = try parseNonNegativeIntEnv(Self.warmupIterationsEnvKey, defaultValue: 3)
let iterations = max(try parseNonNegativeIntEnv(Self.measuredIterationsEnvKey, defaultValue: 10), 1)
try await runWarmup(engine: context.engine, image: context.cgImage, iterations: warmup)
var measuredError: Error?
let options = XCTMeasureOptions()
options.iterationCount = iterations
measure(metrics: [XCTMemoryMetric()], options: options) {
guard measuredError == nil else { return }
do {
_ = try waitForAsync {
try await context.engine.run(context.cgImage, params: self.resolveBenchmarkRuntimeParams())
}
} catch {
measuredError = error
}
}
if let measuredError {
throw measuredError
}
}
// MARK: - Helpers
private struct BenchmarkContext {
let cgImage: CGImage
let manager: ORTSessionManager
let engine: OCREngine
let memoryBeforeLoad: UInt64
let memoryAfterLoad: UInt64
let coldLoadTime: TimeInterval
}
private func makeBenchmarkContext(executionProvider: ORTPrimaryExecutionProvider, ortProfiling: Bool) async throws -> BenchmarkContext {
let cgImage = try resolveBenchmarkImage()
let memoryBeforeLoad = physicalFootprintBytes()
let manager = ORTSessionManager()
let loadStart = CFAbsoluteTimeGetCurrent()
try await manager.loadModels(executionProvider: executionProvider, ortProfiling: ortProfiling, tuning: resolveSessionTuningOptions())
let coldLoadTime = CFAbsoluteTimeGetCurrent() - loadStart
let memoryAfterLoad = physicalFootprintBytes()
let engine = try OCREngine(sessionManager: manager)
return BenchmarkContext(
cgImage: cgImage,
manager: manager,
engine: engine,
memoryBeforeLoad: memoryBeforeLoad,
memoryAfterLoad: memoryAfterLoad,
coldLoadTime: coldLoadTime
)
}
private func summarizeShapes(_ shapes: [[Int]]) -> [BenchmarkTensorShapeSample] {
let counts = shapes.reduce(into: [[Int]: Int]()) { partial, shape in
partial[shape, default: 0] += 1
}
return counts
.map { BenchmarkTensorShapeSample(shape: $0.key, count: $0.value) }
.sorted { lhs, rhs in
if lhs.shape != rhs.shape {
return lhs.shape.lexicographicallyPrecedes(rhs.shape)
}
return lhs.count > rhs.count
}
}
private func runWarmup(engine: OCREngine, image: CGImage, iterations: Int) async throws {
let params = resolveBenchmarkRuntimeParams()
for _ in 0..<iterations {
_ = try await engine.run(image, params: params)
}
}
private func appendRun(
_ run: OCRRunResult,
totals: inout [Double],
dets: inout [Double],
detPre: inout [Double],
detInf: inout [Double],
detPost: inout [Double],
recs: inout [Double],
recPre: inout [Double],
recInf: inout [Double],
recPost: inout [Double],
overheads: inout [Double],
lineInferenceMsPooled: inout [Double],
linePreprocessMsPooled: inout [Double],
linePostprocessMsPooled: inout [Double],
lineTotalMsPooled: inout [Double]
) {
totals.append(run.totalTime * 1000)
dets.append(run.detectionTime * 1000)
detPre.append(run.detectionPreprocessTime * 1000)
detInf.append(run.detectionInferenceTime * 1000)
detPost.append(run.detectionPostprocessTime * 1000)
recs.append(run.recognitionTime * 1000)
recPre.append(run.recognitionPreprocessTime * 1000)
recInf.append(run.recognitionInferenceTime * 1000)
recPost.append(run.recognitionPostprocessTime * 1000)
overheads.append(run.pipelineOverheadTime * 1000)
let n = run.recognitionLineCount
if n > 0 {
let infMs = run.lineRecognitionInferenceTimes.map { $0 * 1000.0 }
let preMs = run.lineRecognitionPreprocessTimes.map { $0 * 1000.0 }
let postMs = run.lineRecognitionPostprocessTimes.map { $0 * 1000.0 }
lineInferenceMsPooled.append(contentsOf: infMs)
linePreprocessMsPooled.append(contentsOf: preMs)
linePostprocessMsPooled.append(contentsOf: postMs)
for i in 0..<n {
lineTotalMsPooled.append(preMs[i] + infMs[i] + postMs[i])
}
}
}
private func resolveBuildConfiguration() -> String {
let raw =
ProcessInfo.processInfo.environment[Self.buildConfigurationEnvKey]?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return raw.isEmpty ? "Release" : raw
}
private func isRunningOnSimulator() -> Bool {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}
private func deviceModelName() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let mirror = Mirror(reflecting: systemInfo.machine)
return mirror.children.reduce(into: "") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return }
identifier.append(String(UnicodeScalar(UInt8(value))))
}
}
private func resolveORTProfilingEnabled() -> Bool {
let raw =
ProcessInfo.processInfo.environment[Self.ortProfilingEnvKey]?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if raw.isEmpty { return false }
switch raw.lowercased() {
case "1", "true", "yes", "on":
return true
default:
return false
}
}
private func resolveSessionTuningOptions() -> ORTSessionTuningOptions {
let env = ProcessInfo.processInfo.environment
var opts = ORTSessionTuningOptions()
if let v = env[Self.intraOpThreadsEnvKey], let n = Int(v), n > 0 {
opts.intraOpThreads = n
}
if let v = env[Self.xnnpackThreadsEnvKey], let n = Int(v), n > 0 {
opts.xnnpackThreads = n
}
if let v = env[Self.coremlOptionsEnvKey], !v.isEmpty {
opts.coreMLFlags = Set(v.split(separator: ",").map { String($0).trimmingCharacters(in: .whitespaces) })
}
return opts
}
private func attachProfileFile(_ url: URL, name: String) {
let attachment = XCTAttachment(contentsOfFile: url)
attachment.name = name
attachment.lifetime = XCTAttachment.Lifetime.keepAlways
add(attachment)
}
private func resolveBenchmarkExecutionProvider() throws -> ORTPrimaryExecutionProvider {
let raw =
ProcessInfo.processInfo.environment[Self.ortExecutionProviderEnvKey]?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if raw.isEmpty {
return .cpu
}
if let exact = ORTPrimaryExecutionProvider(rawValue: raw) {
return exact
}
switch raw.lowercased() {
case "core_ml":
return .coreML
case "xnnpack":
return .xnnpack
case "cpu":
return .cpu
default:
throw NSError(
domain: "OCRBenchmarkTests",
code: 5,
userInfo: [
NSLocalizedDescriptionKey:
"Invalid \(Self.ortExecutionProviderEnvKey): \"\(raw)\". "
+ "Use CPU (default), XNNPACK, CORE_ML, or Swift raw values "
+ "\(ORTPrimaryExecutionProvider.cpu.rawValue) / "
+ "\(ORTPrimaryExecutionProvider.xnnpack.rawValue) / "
+ "\(ORTPrimaryExecutionProvider.coreML.rawValue).",
]
)
}
}
private func resolveBenchmarkImage() throws -> CGImage {
let envRaw =
ProcessInfo.processInfo.environment[Self.imageNameEnvKey]?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let raw = envRaw.isEmpty ? BenchmarkFixtures.defaultReferenceImageStem : envRaw
let bundle = Bundle(for: Self.self)
guard let path = bundle.path(forBundledImageNamed: raw, subdirectory: "Fixtures") else {
throw NSError(
domain: "OCRBenchmarkTests",
code: 3,
userInfo: [
NSLocalizedDescriptionKey:
"Image \"\(raw)\" not found in the test bundle. Check the name and that the file is included in the test target resources (e.g. \"\(BenchmarkFixtures.defaultReferenceImageStem)\").",
]
)
}
let url = URL(fileURLWithPath: path)
guard let ui = UIImage(contentsOfFile: url.path),
let cg = normalizeOrientation(ui).cgImage
else {
throw NSError(
domain: "OCRBenchmarkTests",
code: 4,
userInfo: [NSLocalizedDescriptionKey: "Could not decode image at \(url.path)."]
)
}
return cg
}
private func attachJSON(_ data: Data, artifact: BenchmarkArtifact) {
let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json")
attachment.name = artifact.rawValue
attachment.lifetime = .keepAlways
add(attachment)
}
private func waitForAsync<T>(_ operation: @escaping () async throws -> T) throws -> T {
let semaphore = DispatchSemaphore(value: 0)
let lock = NSLock()
var capturedResult: Result<T, Error>?
Task {
do {
let value = try await operation()
lock.lock()
capturedResult = .success(value)
lock.unlock()
} catch {
lock.lock()
capturedResult = .failure(error)
lock.unlock()
}
semaphore.signal()
}
semaphore.wait()
lock.lock()
let result = capturedResult
lock.unlock()
switch result {
case .success(let value):
return value
case .failure(let error):
throw error
case .none:
throw NSError(
domain: "OCRBenchmarkTests",
code: 6,
userInfo: [NSLocalizedDescriptionKey: "Async operation completed without a result."]
)
}
}
/// Parses a non-negative integer from the environment, or returns `defaultValue` when unset/blank.
private func parseNonNegativeIntEnv(_ key: String, defaultValue: Int) throws -> Int {
let raw =
ProcessInfo.processInfo.environment[key]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if raw.isEmpty {
return defaultValue
}
guard let n = Int(raw), n >= 0 else {
throw NSError(
domain: "OCRBenchmarkTests",
code: 3,
userInfo: [
NSLocalizedDescriptionKey:
"Invalid \(key): expected a non-negative integer (default \(defaultValue) if unset), got \(raw).",
]
)
}
return n
}
private func resolveBenchmarkRuntimeParams() -> OCRRuntimeParams {
let env = ProcessInfo.processInfo.environment
if let v = env[Self.recBatchSizeEnvKey], let n = Int(v), n >= 1 {
return OCRRuntimeParams(
textDetLimitSideLen: nil,
textDetLimitType: nil,
textDetMaxSideLimit: nil,
textDetThresh: nil,
textDetBoxThresh: nil,
textDetUnclipRatio: nil,
textRecBatchSize: n,
textRecScoreThresh: nil
)
}
return .noOverrides
}
/// Physical memory footprint (bytes) — matches Xcode Memory gauge more closely than RSS alone.
/// Uses `task_vm_info_data_t.phys_footprint` via `task_info(TASK_VM_INFO, ...)`.
private func physicalFootprintBytes() -> UInt64 {
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
let kerr = withUnsafeMutablePointer(to: &info) { p in
p.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
}
}
guard kerr == KERN_SUCCESS else { return 0 }
return UInt64(info.phys_footprint)
}
private func summarizeMs(_ samples: [Double]) -> TimingSummary {
let sorted = samples.sorted()
let mean = samples.reduce(0, +) / Double(max(samples.count, 1))
let variance =
samples.isEmpty
? 0
: samples.map { pow($0 - mean, 2) }.reduce(0, +) / Double(samples.count)
let stdev = sqrt(variance)
let p90Idx = max(0, min(sorted.count - 1, Int(floor(0.9 * Double(max(sorted.count - 1, 0))))))
let p90 = sorted.isEmpty ? 0 : sorted[p90Idx]
return TimingSummary(mean: mean, stdev: stdev, p90: p90)
}
}
// MARK: - Orientation (match OCRViewModel)
private func normalizeOrientation(_ image: UIImage) -> UIImage {
guard image.imageOrientation != .up else { return image }
let format = UIGraphicsImageRendererFormat()
format.scale = image.scale
let renderer = UIGraphicsImageRenderer(size: image.size, format: format)
return renderer.image { _ in
image.draw(in: CGRect(origin: .zero, size: image.size))
}
}
@@ -0,0 +1,118 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import PaddleOCRDemo
/// Verifies ``OCRParameterResolver``
final class OCRParameterResolverTests: XCTestCase {
func testDetResizeMergePrefersAppDefaultsOverModelWhenUINil() throws {
let dir = FileManager.default.temporaryDirectory
let url = dir.appendingPathComponent("merge_test_det_\(UUID().uuidString).yaml")
let yaml = """
Global:
model_name: PP-OCRv5_mobile_det
PreProcess:
transform_ops:
- DetResizeForTest:
resize_long: 960
PostProcess:
name: DBPostProcess
"""
try yaml.write(to: url, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: url) }
let det = try InferenceConfig.load(from: url.path)
let m = det.detResizeFromModel
XCTAssertNotNil(m)
XCTAssertEqual(m?.limitSideLen, 960)
let eff = OCRParameterResolver.effective(modelConfig: det, runtime: .noOverrides)
let app = OCRParameterResolver.textDetLimitSideLenAppDefault
XCTAssertEqual(eff.detResize.limitSideLen, app)
XCTAssertEqual(eff.mergedLimitSideLen, app)
}
func testEffectiveDetPostprocessMergesThresholdsOnly() throws {
let dir = FileManager.default.temporaryDirectory
let url = dir.appendingPathComponent("merge_test_post_\(UUID().uuidString).yaml")
let yaml = """
Global:
model_name: PP-OCRv5_mobile_det
PreProcess:
transform_ops:
- DetResizeForTest:
resize_long: 960
PostProcess:
name: DBPostProcess
thresh: 0.99
box_thresh: 0.99
unclip_ratio: 9.9
max_candidates: 7
"""
try yaml.write(to: url, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: url) }
let det = try InferenceConfig.load(from: url.path)
let post = OCRParameterResolver.effective(modelConfig: det, runtime: .noOverrides)
XCTAssertEqual(post.detThresh, 0.3, accuracy: 0.0001)
XCTAssertEqual(post.detBoxThresh, 0.6, accuracy: 0.0001)
XCTAssertEqual(post.detUnclipRatio, 1.5, accuracy: 0.0001)
XCTAssertEqual(det.postProcess.maxCandidates, 7)
}
func testDecodeImageImgModeParsedAsRGB() throws {
let dir = FileManager.default.temporaryDirectory
let url = dir.appendingPathComponent("decode_rgb_\(UUID().uuidString).yaml")
let yaml = """
Global:
model_name: PP-OCRv5_mobile_det
PreProcess:
transform_ops:
- DecodeImage:
channel_first: false
img_mode: RGB
- DetResizeForTest:
resize_long: 960
PostProcess:
name: DBPostProcess
"""
try yaml.write(to: url, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: url) }
let cfg = try InferenceConfig.load(from: url.path)
XCTAssertEqual(cfg.decodeImageChannelOrder, .rgb)
}
func testDecodeImageMissingDefaultsToBGR() throws {
let dir = FileManager.default.temporaryDirectory
let url = dir.appendingPathComponent("decode_default_bgr_\(UUID().uuidString).yaml")
let yaml = """
Global:
model_name: PP-OCRv5_mobile_det
PreProcess:
transform_ops:
- DetResizeForTest:
resize_long: 960
PostProcess:
name: DBPostProcess
"""
try yaml.write(to: url, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: url) }
let cfg = try InferenceConfig.load(from: url.path)
XCTAssertEqual(cfg.decodeImageChannelOrder, .bgr)
}
}
@@ -0,0 +1,55 @@
// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import PaddleOCRDemo
final class ORTSessionManagerTests: XCTestCase {
func testLoadModels() async throws {
let manager = ORTSessionManager()
try await manager.loadModels(executionProvider: .coreML)
}
func testLoadModelsCPU() async throws {
let manager = ORTSessionManager()
try await manager.loadModels(executionProvider: .cpu)
}
func testModelConfigResolution() throws {
do {
let detConfig = try ModelConfig.detection()
XCTAssertFalse(detConfig.modelPath.isEmpty, "Det model path should not be empty")
let expected = try InferenceConfig.load(from: detConfig.configPath).modelName
XCTAssertEqual(detConfig.name, expected, "Display name should equal Global.model_name in the det model config")
} catch let error as ModelConfigError {
switch error {
case .modelNotFound(let path):
XCTAssertTrue(path.contains("det"), "Error should reference det model path")
}
}
do {
let recConfig = try ModelConfig.recognition()
XCTAssertFalse(recConfig.modelPath.isEmpty, "Rec model path should not be empty")
let expected = try InferenceConfig.load(from: recConfig.configPath).modelName
XCTAssertEqual(recConfig.name, expected, "Display name should equal Global.model_name in the rec model config")
} catch let error as ModelConfigError {
switch error {
case .modelNotFound(let path):
XCTAssertTrue(path.contains("rec"), "Error should reference rec model path")
}
}
}
}
+30
View File
@@ -0,0 +1,30 @@
platform :ios, '16.0'
target 'PaddleOCRDemo' do
use_frameworks!
# ONNX Runtime with ObjC API — includes Core ML EP + XNNPACK EP pre-built
pod 'onnxruntime-objc', '~> 1.24'
# YAML parsing for model config files
pod 'Yams', '~> 5.0'
# OpenCV (imgproc): preprocessing resize/pad, recognition resize, quad crop, DB contours — see OpenCV*Bridge.
pod 'OpenCV', '~> 4.3.0'
# Unit tests `@testable import PaddleOCRDemo` need the same Swift / header search paths
# as the app without duplicating pod linkage.
target 'PaddleOCRDemoTests' do
inherit! :search_paths
end
end
# onnxruntime-objc ships headers that use #include "..." inside framework headers; newer Xcode
# treats that as an error (CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER). Allow Pods to build.
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER'] = 'NO'
end
end
end
+30
View File
@@ -0,0 +1,30 @@
PODS:
- onnxruntime-c (1.24.3)
- onnxruntime-objc (1.24.3):
- onnxruntime-objc/Core (= 1.24.3)
- onnxruntime-objc/Core (1.24.3):
- onnxruntime-c (= 1.24.3)
- OpenCV (4.3.0)
- Yams (5.0.6)
DEPENDENCIES:
- onnxruntime-objc (~> 1.24)
- OpenCV (~> 4.3.0)
- Yams (~> 5.0)
SPEC REPOS:
trunk:
- onnxruntime-c
- onnxruntime-objc
- OpenCV
- Yams
SPEC CHECKSUMS:
onnxruntime-c: 4a1a1a81da2087869dc9b6357f182952db2df29c
onnxruntime-objc: f9310465f0a284682811d071b7eb8e93f10517b8
OpenCV: 681e0451c1e54c5930a8922277f817ed5d5ab459
Yams: e10dae147f517ed57ecae37c5e8681bdf8fcab65
PODFILE CHECKSUM: 24111b5e94db1b6a72362b62148f587abc1a06be
COCOAPODS: 1.16.2
+4 -2
View File
@@ -1,3 +1,5 @@
# ios Demo
# PaddleOCR iOS Demo
参考 https://github.com/PaddlePaddle/Paddle-Lite-Demo/blob/develop/ocr/ios/ppocr_demo/ppocr_demo/README.md
中文 | [English](./README_en.md)
请查看 [文档](../../docs/version3.x/inference_deployment/cross_platform/ios_deployment.md)。
+5
View File
@@ -0,0 +1,5 @@
# PaddleOCR iOS Demo
[中文](./README.md) | English
Please refer to the [documentation](../../docs/version3.x/inference_deployment/cross_platform/ios_deployment.en.md).
@@ -0,0 +1,2 @@
PyYAML>=6.0
shapely>=2.0
@@ -0,0 +1,4 @@
numpy
paddlex>=3.5,<3.6
onnxruntime>=1.18
opencv-contrib-python>=4.5
@@ -0,0 +1,3 @@
numpy>=1.20
onnx>=1.16,<1.21
onnxruntime>=1.18
@@ -0,0 +1,5 @@
# Keep onnx and onnxruntime within a range that works together (avoids IR / schema skew on older CPU wheels).
# For best parity with the app, install a onnxruntime major version close to onnxruntime-objc in the Podfile.
numpy>=1.20
onnx>=1.16,<1.21
onnxruntime>=1.18
+397
View File
@@ -0,0 +1,397 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Build float32 NCHW ``.npy`` tensors for static ONNX quantization.
Note:
Uses undocumented PaddleX predictor internals (e.g. ``pre_tfs``). May break when
upgrading PaddleX.
Examples:
# Detection model
python3 scripts/build_onnx_calib_npy.py --task det \\
--model-dir PaddleOCRDemo/Models/det --image-dir /path/to/images --output-dir calib_det
# Recognition model (one tensor per full image)
python3 scripts/build_onnx_calib_npy.py --task rec \\
--model-dir PaddleOCRDemo/Models/rec --image-dir /path/to/images --output-dir calib_rec
# Recognition: full-page images — run det to crop line boxes, one tensor per crop
python3 scripts/build_onnx_calib_npy.py --task rec \\
--model-dir PaddleOCRDemo/Models/rec --det-model-dir PaddleOCRDemo/Models/det \\
--image-dir /path/to/pages --output-dir calib_rec_crops
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
from typing import Any, Iterator
import cv2
import numpy as np
from paddlex import create_predictor
_script_dir = Path(__file__).resolve().parent
if str(_script_dir) not in sys.path:
sys.path.insert(0, str(_script_dir))
from utils import die
def _read_model_name(model_dir: Path) -> str:
try:
import yaml
except ImportError as e:
die(f"PyYAML is required: {e}")
p = model_dir / "inference.yml"
if not p.is_file():
die(f"missing {p}")
with p.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f)
name = (data or {}).get("Global", {}).get("model_name")
if not name:
die("Global.model_name not found in inference.yml")
return str(name)
def _collect_images(image_dir: Path) -> list[Path]:
exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif", ".tiff"}
out: list[Path] = []
for p in sorted(image_dir.iterdir()):
if p.is_file() and p.suffix.lower() in exts:
out.append(p)
if not out:
die(f"no images found under {image_dir}")
return out
def _safe_stem(p: Path, idx: int) -> str:
s = p.stem
s = re.sub(r"[^\w\-.]+", "_", s)[:80]
return f"{idx:04d}_{s}" if s else f"{idx:04d}"
def _iter_text_boxes(dt_polys: Any) -> Iterator[np.ndarray]:
"""Turn ``dt_polys`` from a TextDetResult into a sequence of (N,2) point arrays."""
if dt_polys is None:
return
if isinstance(dt_polys, np.ndarray):
if dt_polys.size == 0:
return
if dt_polys.ndim == 2 and dt_polys.shape[0] >= 3:
yield np.array(dt_polys, dtype=np.float32, copy=True)
elif dt_polys.ndim == 3:
for i in range(dt_polys.shape[0]):
box = np.array(dt_polys[i], dtype=np.float32, copy=True)
if box.shape[0] >= 3:
yield box
return
for box in dt_polys:
b = np.array(box, dtype=np.float32, copy=True)
if b.size >= 6 and b.ndim == 2 and b.shape[0] >= 3:
yield b
def _minarea_rect_rotate_crop(img: np.ndarray, points: np.ndarray) -> np.ndarray:
"""
Min-area rect crop aligned with PP-OCR (see PaddleX CropByPolys, quad).
*img* is RGB (same as TextDet Read output).
"""
tmp_box = np.array(points, dtype=np.float32, copy=True)
bounding_box = cv2.minAreaRect(tmp_box.astype(np.int32))
pts = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
if pts[1][1] > pts[0][1]:
index_a, index_d = 0, 1
else:
index_a, index_d = 1, 0
if pts[3][1] > pts[2][1]:
index_b, index_c = 2, 3
else:
index_b, index_c = 3, 2
box = [pts[index_a], pts[index_b], pts[index_c], pts[index_d]]
pts4 = [np.array(p, dtype=np.float32) for p in box]
assert len(pts4) == 4, "shape of points must be 4*2"
img_crop_width = int(
max(
np.linalg.norm(pts4[0] - pts4[1]),
np.linalg.norm(pts4[2] - pts4[3]),
)
)
img_crop_height = int(
max(
np.linalg.norm(pts4[0] - pts4[3]),
np.linalg.norm(pts4[1] - pts4[2]),
)
)
if img_crop_width < 1 or img_crop_height < 1:
raise ValueError("degenerate text crop (zero width/height)")
pts_std = np.float32(
[
[0, 0],
[img_crop_width, 0],
[img_crop_width, img_crop_height],
[0, img_crop_height],
]
)
pstack = np.stack(pts4, axis=0)
m = cv2.getPerspectiveTransform(pstack, pts_std)
dst = cv2.warpPerspective(
img,
m,
(img_crop_width, img_crop_height),
borderMode=cv2.BORDER_REPLICATE,
flags=cv2.INTER_CUBIC,
)
dh, dw = dst.shape[0:2]
if dh * 1.0 / max(dw, 1) >= 1.5:
dst = np.rot90(dst)
return dst
def _tensor_det(pred, image_path: str) -> np.ndarray:
"""Mirror TextDetRunnerPredictor.process() preprocess, return (1,C,H,W) float32."""
batches = list(pred.batch_sampler([image_path]))
b = batches[0]
batch_raw_imgs = pred.pre_tfs["Read"](imgs=b.instances)
batch_imgs, _ = pred.pre_tfs["Resize"](
imgs=batch_raw_imgs,
limit_side_len=pred.limit_side_len,
limit_type=pred.limit_type,
max_side_limit=pred.max_side_limit,
)
batch_imgs = pred.pre_tfs["Normalize"](imgs=batch_imgs)
batch_imgs = pred.pre_tfs["ToCHW"](imgs=batch_imgs)
x = pred.pre_tfs["ToBatch"](imgs=batch_imgs)
if not x:
die("ToBatch returned empty (det)")
return np.ascontiguousarray(x[0], dtype=np.float32)
def _tensor_rec(pred, image_path: str) -> np.ndarray:
from paddlex.inference.models.text_recognition.processors import (
validate_text_rec_image_array,
)
batches = list(pred.batch_sampler([image_path]))
b = batches[0]
batch_raw_imgs = pred.pre_tfs["Read"](imgs=b.instances)
for i, img in enumerate(batch_raw_imgs):
validate_text_rec_image_array(img, index=i)
batch_imgs = pred.pre_tfs["ReisizeNorm"](imgs=batch_raw_imgs)
x = pred.pre_tfs["ToBatch"](imgs=batch_imgs)
if not x:
die("ToBatch returned empty (rec)")
return np.ascontiguousarray(x[0], dtype=np.float32)
def _tensor_rec_from_rgb_ndarray(rec_pred, img_rgb: np.ndarray) -> np.ndarray:
"""Same preprocessing as *path* input, for an RGB array (e.g. det crop on full page)."""
from paddlex.inference.models.text_recognition.processors import (
validate_text_rec_image_array,
)
bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
batch_raw_imgs = rec_pred.pre_tfs["Read"](imgs=[bgr])
for i, img in enumerate(batch_raw_imgs):
validate_text_rec_image_array(img, index=i)
batch_imgs = rec_pred.pre_tfs["ReisizeNorm"](imgs=batch_raw_imgs)
x = rec_pred.pre_tfs["ToBatch"](imgs=batch_imgs)
if not x:
die("ToBatch returned empty (rec, ndarray)")
return np.ascontiguousarray(x[0], dtype=np.float32)
def main() -> None:
ap = argparse.ArgumentParser(
description="Build float32 NCHW .npy files for static ONNX quantize."
)
ap.add_argument(
"--image-dir",
type=Path,
required=True,
help="Directory of input images.",
)
ap.add_argument(
"--output-dir",
type=Path,
required=True,
help="Output directory for .npy files (created if missing).",
)
ap.add_argument(
"--model-dir",
type=Path,
required=True,
help="Model directory.",
)
ap.add_argument(
"--task",
choices=("det", "rec"),
required=True,
help="Model role: det = text detection, rec = text recognition.",
)
ap.add_argument(
"--det-model-dir",
type=Path,
default=None,
help=(
"For --task rec only: text-detection model directory. "
"When set, each full image is run through det; each text box is cropped and one "
"rec calibration tensor is written per crop (instead of one tensor per file)."
),
)
ap.add_argument(
"--max-crops-per-image",
type=int,
default=0,
help="With --det-model-dir, cap how many box crops to use per input image (0 = no cap).",
)
ap.add_argument("--device", default="cpu", help="Device string, e.g. cpu or gpu:0.")
args = ap.parse_args()
if not args.image_dir.is_dir():
die(f"not a directory: {args.image_dir}")
if not (args.model_dir / "inference.onnx").is_file():
die(f"missing {args.model_dir / 'inference.onnx'}")
if args.det_model_dir is not None:
if args.task != "rec":
die("--det-model-dir is only valid with --task rec")
if not (args.det_model_dir / "inference.onnx").is_file():
die(f"missing {args.det_model_dir / 'inference.onnx'}")
model_name = _read_model_name(args.model_dir)
if args.task == "det" and "_rec" in model_name and "_det" not in model_name:
print(
"warning: --task det but model_name looks like recognition; check --model-dir",
file=sys.stderr,
)
if args.task == "rec" and "_det" in model_name and "_rec" not in model_name:
print(
"warning: --task rec but model_name looks like detection; check --model-dir",
file=sys.stderr,
)
try:
pred = create_predictor(
model_name,
model_dir=str(args.model_dir.resolve()),
device=args.device,
engine="onnxruntime",
batch_size=1,
)
except Exception as e:
die(f"create_predictor failed: {e}")
det_pred = None
det_name = None
if args.det_model_dir is not None:
det_name = _read_model_name(args.det_model_dir)
if "_rec" in det_name and "_det" not in det_name:
print(
"warning: --det-model-dir model_name looks like recognition; check path",
file=sys.stderr,
)
try:
det_pred = create_predictor(
det_name,
model_dir=str(args.det_model_dir.resolve()),
device=args.device,
engine="onnxruntime",
batch_size=1,
)
except Exception as e:
die(f"create_predictor (det) failed: {e}")
out_dir = args.output_dir
out_dir.mkdir(parents=True, exist_ok=True)
images = _collect_images(args.image_dir)
written = 0
for idx, path in enumerate(images):
pstr = str(path.resolve())
if args.task == "det":
try:
arr = _tensor_det(pred, pstr)
except Exception as e:
die(f"preprocess failed for {path}: {e}")
if arr.dtype != np.float32:
arr = arr.astype(np.float32)
name = _safe_stem(path, idx) + ".npy"
out_path = out_dir / name
np.save(str(out_path), arr)
print(f"wrote {out_path} shape={arr.shape} dtype={arr.dtype}")
written += 1
continue
# rec
if det_pred is None:
try:
arr = _tensor_rec(pred, pstr)
except Exception as e:
die(f"preprocess failed for {path}: {e}")
if arr.dtype != np.float32:
arr = arr.astype(np.float32)
out_path = out_dir / (_safe_stem(path, idx) + ".npy")
np.save(str(out_path), arr)
print(f"wrote {out_path} shape={arr.shape} dtype={arr.dtype}")
written += 1
continue
# rec + det: crops from full page
try:
det_res = next(det_pred(pstr)) # type: ignore[union-attr]
except Exception as e:
die(f"detection failed for {path}: {e}")
polys = list(_iter_text_boxes(det_res["dt_polys"]))
if not polys:
print(
f"warning: no text boxes for {path}; skipping (no .npy written)",
file=sys.stderr,
)
continue
if args.max_crops_per_image > 0:
polys = polys[: args.max_crops_per_image]
full_rgb = det_res["input_img"]
if isinstance(full_rgb, (list, tuple)) and len(full_rgb) == 1:
full_rgb = full_rgb[0]
for box_i, quad in enumerate(polys):
try:
line_rgb = _minarea_rect_rotate_crop(full_rgb, quad)
except Exception as e:
print(
f"warning: skip box {box_i} in {path}: {e}",
file=sys.stderr,
)
continue
try:
arr = _tensor_rec_from_rgb_ndarray(pred, line_rgb)
except Exception as e:
die(f"rec preprocess failed for {path} box {box_i}: {e}")
if arr.dtype != np.float32:
arr = arr.astype(np.float32)
out_path = out_dir / (f"{_safe_stem(path, idx)}_box{box_i:03d}.npy")
np.save(str(out_path), arr)
print(f"wrote {out_path} shape={arr.shape} dtype={arr.dtype}")
written += 1
print(f"done. {written} .npy file(s) -> {out_dir}")
if __name__ == "__main__":
main()
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Compare two OCR JSON files (reference vs device) using polygon IoU + CER.
Default thresholds (see argparse defaults) target a stricter CI gate than a loose
0.5 IoU baseline: tighter box alignment, ~95% char-level headroom on mean CER,
and limited reference-side misses.
Example:
python compare_ocr_json.py ref.json ios.json \\
--iou-threshold 0.65 --cer-threshold 0.05 --max-unmatched-ratio 0.1
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Sequence, Tuple
def _levenshtein(a: str, b: str) -> int:
if a == b:
return 0
if not a:
return len(b)
if not b:
return len(a)
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
ins = cur[j - 1] + 1
delete = prev[j] + 1
sub = prev[j - 1] + (ca != cb)
cur.append(min(ins, delete, sub))
prev = cur
return prev[-1]
def _cer(ref: str, hyp: str) -> float:
if not ref and not hyp:
return 0.0
if not ref:
return 1.0
return _levenshtein(ref, hyp) / max(len(ref), 1)
def _polygon_iou(
poly_a: Sequence[Sequence[float]], poly_b: Sequence[Sequence[float]]
) -> float:
try:
from shapely.geometry import Polygon
except ImportError as exc:
raise RuntimeError(
"compare_ocr_json.py requires `pip install shapely`"
) from exc
def _to_poly(p: Sequence[Sequence[float]]) -> Polygon:
pts = [(float(x), float(y)) for x, y in p]
if len(pts) < 3:
return Polygon()
if pts[0] != pts[-1]:
pts = pts + [pts[0]]
return Polygon(pts)
p1 = _to_poly(poly_a)
p2 = _to_poly(poly_b)
if p1.is_empty or p2.is_empty or not p1.is_valid or not p2.is_valid:
return 0.0
inter = p1.intersection(p2).area
union = p1.union(p2).area
if union <= 0:
return 0.0
return float(inter / union)
def _load_items(path: Path) -> List[Dict[str, Any]]:
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
items = data.get("items")
if not isinstance(items, list):
raise ValueError(f"{path}: missing 'items' array")
return items
def _greedy_match(
ref_items: List[Dict[str, Any]],
hyp_items: List[Dict[str, Any]],
iou_threshold: float,
) -> Tuple[List[Tuple[int, int, float]], List[int], List[int]]:
"""Return (pairs as ref_idx, hyp_idx, iou), unmatched_ref, unmatched_hyp."""
candidates: List[Tuple[float, int, int]] = []
for i, ri in enumerate(ref_items):
ra = ri.get("polygon")
if not isinstance(ra, list):
continue
for j, hj in enumerate(hyp_items):
ha = hj.get("polygon")
if not isinstance(ha, list):
continue
iou = _polygon_iou(ra, ha)
candidates.append((iou, i, j))
candidates.sort(key=lambda t: t[0], reverse=True)
used_r = set()
used_h = set()
pairs: List[Tuple[int, int, float]] = []
for iou, i, j in candidates:
if iou < iou_threshold:
break
if i in used_r or j in used_h:
continue
used_r.add(i)
used_h.add(j)
pairs.append((i, j, iou))
unmatched_r = [i for i in range(len(ref_items)) if i not in used_r]
unmatched_h = [j for j in range(len(hyp_items)) if j not in used_h]
return pairs, unmatched_r, unmatched_h
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Compare OCR JSON outputs")
parser.add_argument(
"reference", type=Path, help="Reference JSON (e.g. paddleocr_reference)"
)
parser.add_argument("hypothesis", type=Path, help="Device / second JSON")
parser.add_argument(
"--iou-threshold",
type=float,
default=0.65,
help="Min IoU to pair quadrilateral boxes (stricter than common 0.5 VOC-style cutoff)",
)
parser.add_argument(
"--cer-threshold",
type=float,
default=0.05,
help="Fail if mean CER on matched pairs exceeds this (e.g. 0.05 ≈ 95%% char accuracy headroom)",
)
parser.add_argument(
"--max-unmatched-ratio",
type=float,
default=0.1,
help="Fail if unmatched ref lines / len(ref) exceeds this",
)
parser.add_argument(
"--json-summary-out",
type=Path,
default=None,
help="Write the same JSON as stdout to this path (PASS or FAIL) for generate_benchmark_report.py",
)
args = parser.parse_args(list(argv) if argv is not None else None)
ref_items = _load_items(args.reference)
hyp_items = _load_items(args.hypothesis)
pairs, unmatched_r, unmatched_h = _greedy_match(
ref_items, hyp_items, args.iou_threshold
)
cers: List[float] = []
for ri, hj, _ in pairs:
rt = str(ref_items[ri].get("text", ""))
ht = str(hyp_items[hj].get("text", ""))
cers.append(_cer(rt, ht))
mean_cer = sum(cers) / len(cers) if cers else 0.0
nref = max(len(ref_items), 1)
unmatched_ratio = len(unmatched_r) / nref
report = {
"matched_pairs": len(pairs),
"reference_count": len(ref_items),
"hypothesis_count": len(hyp_items),
"unmatched_reference": len(unmatched_r),
"unmatched_hypothesis": len(unmatched_h),
"unmatched_reference_ratio": unmatched_ratio,
"mean_cer_matched": mean_cer,
"iou_threshold": args.iou_threshold,
"cer_threshold": args.cer_threshold,
"max_unmatched_ratio": args.max_unmatched_ratio,
}
failed = False
if mean_cer > args.cer_threshold:
print(f"FAIL: mean CER {mean_cer:.4f} > {args.cer_threshold}", file=sys.stderr)
failed = True
if unmatched_ratio > args.max_unmatched_ratio:
print(
f"FAIL: unmatched ref ratio {unmatched_ratio:.4f} > {args.max_unmatched_ratio}",
file=sys.stderr,
)
failed = True
report["pass"] = not failed
out_txt = json.dumps(report, indent=2, ensure_ascii=False)
print(out_txt)
if args.json_summary_out is not None:
args.json_summary_out.parent.mkdir(parents=True, exist_ok=True)
args.json_summary_out.write_text(out_txt + "\n", encoding="utf-8")
if not failed:
print("PASS", file=sys.stderr)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env bash
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Convert ONNX models to ORT format for ONNX Runtime.
# See: https://onnxruntime.ai/docs/performance/model-optimizations/ort-format-models.html
#
# Requires: python3
#
# Usage:
# ./scripts/convert_onnx_to_ort.sh
# ./scripts/convert_onnx_to_ort.sh --output-dir ./out/ort_bundles
# ./scripts/convert_onnx_to_ort.sh --input-dir /path/to/models --output-dir /tmp/ort
# ./scripts/convert_onnx_to_ort.sh --optimization-style Runtime
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IOS_DEMO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DEFAULT_INPUT_DIR="${IOS_DEMO_ROOT}/PaddleOCRDemo/Models"
INPUT_DIR="${DEFAULT_INPUT_DIR}"
ORT_OUTPUT_DIR=""
KEEP_OPERATOR_CONFIG=false
EXPLICIT_OPTIMIZATION_STYLE=false
OPTIMIZATION_STYLE_VALUES=()
usage() {
cat <<EOF
Usage: ./scripts/convert_onnx_to_ort.sh [OPTIONS] [ORT_CONVERTER_ARGS...]
Options:
--input-dir <dir> Root directory to scan for *.onnx (recursive). Default: PaddleOCRDemo/Models.
--output-dir <dir> If set, write .ort files under this directory, mirroring relative paths from
the input tree; also copies inference.yml beside each converted bundle (same
layout as under --input-dir) so you can swap in the whole output folder. If
omitted, write next to each .onnx in-place.
--keep-operator-config
Keep required_operators*.config files emitted by the ORT converter (for
minimal ORT builds). By default these are removed after a successful run.
--optimization-style <style>...
ORT conversion style(s): Fixed and/or Runtime (forwarded as Python
--optimization_style). One or more values after the flag, e.g.
--optimization-style Runtime or --optimization-style Fixed Runtime
The flag may appear more than once; values accumulate.
Alias: --optimization_style
Default when omitted: Fixed (single .ort per ONNX; upstream defaults to both).
-h, --help Show this help
ORT_CONVERTER_ARGS are forwarded to:
python3 -m onnxruntime.tools.convert_onnx_models_to_ort
(documentation: https://onnxruntime.ai/ — place this script’s options first, e.g. --output-dir
before other converter flags such as --enable_type_reduction.)
Examples:
./scripts/convert_onnx_to_ort.sh
./scripts/convert_onnx_to_ort.sh --output-dir ./out/ort_only
./scripts/convert_onnx_to_ort.sh --input-dir ./PaddleOCRDemo/Models --output-dir ./out/ort_bundles
./scripts/convert_onnx_to_ort.sh --output-dir /tmp/ort --optimization-style Runtime
./scripts/convert_onnx_to_ort.sh --optimization-style Fixed Runtime --output-dir ./out/both
./scripts/convert_onnx_to_ort.sh --output-dir ./out/ort_only --keep-operator-config
EOF
}
die() {
echo "error: $*" >&2
exit 1
}
# Remove ORT converter operator-config files.
prune_operator_config_files() {
local root="$1"
local n=0
while IFS= read -r -d '' f; do
rm -f "${f}"
n=$((n + 1))
done < <(find "${root}" -name 'required_operators*.config' -type f -print0 2>/dev/null || true)
if [[ "$n" -gt 0 ]]; then
echo "Removed ${n} required_operators*.config file(s) (minimal-build manifests; use --keep-operator-config to retain)."
fi
}
copy_inference_yml_mirrored() {
local src_root="$1"
local dst_root="$2"
local yml
local n=0
while IFS= read -r -d '' yml; do
local rel="${yml#"${src_root}/"}"
local dest="${dst_root}/${rel}"
mkdir -p "$(dirname "${dest}")"
cp -f "${yml}" "${dest}"
n=$((n + 1))
done < <(find "${src_root}" -name 'inference.yml' -type f -print0)
echo "Copied ${n} inference.yml into --output-dir (same relative paths as under --input-dir)."
}
while [[ $# -gt 0 ]]; do
case "$1" in
--input-dir)
[[ -n "${2:-}" ]] || die "--input-dir requires a directory"
INPUT_DIR="$2"
shift 2
;;
--output-dir)
[[ -n "${2:-}" ]] || die "--output-dir requires a directory"
ORT_OUTPUT_DIR="$2"
shift 2
;;
--keep-operator-config)
KEEP_OPERATOR_CONFIG=true
shift
;;
--optimization-style|--optimization_style)
shift
EXPLICIT_OPTIMIZATION_STYLE=true
chunk=()
while [[ $# -gt 0 ]]; do
case "$1" in
Fixed|Runtime)
chunk+=("$1")
shift
;;
*)
break
;;
esac
done
[[ ${#chunk[@]} -gt 0 ]] || die "--optimization-style requires one or more of: Fixed Runtime"
OPTIMIZATION_STYLE_VALUES+=("${chunk[@]}")
;;
-h | --help)
usage
exit 0
;;
*)
break
;;
esac
done
CONVERTER_EXTRA=("$@")
if [[ "$EXPLICIT_OPTIMIZATION_STYLE" == false ]]; then
OPTIMIZATION_STYLE_VALUES=(Fixed)
fi
ORT_OPTIMIZATION_ARGS=(--optimization_style "${OPTIMIZATION_STYLE_VALUES[@]}")
command -v python3 >/dev/null || die "python3 is required"
[[ -d "${INPUT_DIR}" ]] || die "input directory not found: ${INPUT_DIR}"
INPUT_ABS="$(cd "${INPUT_DIR}" && pwd)"
if [[ -n "${ORT_OUTPUT_DIR}" ]]; then
mkdir -p "${ORT_OUTPUT_DIR}" || die "cannot create --output-dir: ${ORT_OUTPUT_DIR}"
ORT_OUT_ABS="$(cd "${ORT_OUTPUT_DIR}" && pwd)"
echo "Converting .onnx -> .ort: --input-dir ${INPUT_ABS} -> --output-dir ${ORT_OUT_ABS} ..."
python3 -m onnxruntime.tools.convert_onnx_models_to_ort \
--output_dir "${ORT_OUT_ABS}" \
"${ORT_OPTIMIZATION_ARGS[@]}" \
"${CONVERTER_EXTRA[@]}" \
-- \
"${INPUT_ABS}"
copy_inference_yml_mirrored "${INPUT_ABS}" "${ORT_OUT_ABS}"
if [[ "$KEEP_OPERATOR_CONFIG" == false ]]; then
prune_operator_config_files "${ORT_OUT_ABS}"
fi
else
echo "Converting .onnx -> .ort in-place under ${INPUT_ABS} ..."
python3 -m onnxruntime.tools.convert_onnx_models_to_ort \
"${ORT_OPTIMIZATION_ARGS[@]}" \
"${CONVERTER_EXTRA[@]}" \
-- \
"${INPUT_ABS}"
if [[ "$KEEP_OPERATOR_CONFIG" == false ]]; then
prune_operator_config_files "${INPUT_ABS}"
fi
fi
echo "Done."
+321
View File
@@ -0,0 +1,321 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""QDQ quantization debug: align with ONNX Runtime ``qdq_loss_debug`` (official example flow).
This mirrors the *Debugging* section of:
https://github.com/microsoft/onnxruntime-inference-examples/blob/main/quantization/image_classification/cpu/ReadMe.md
Workflow:
1. Augment float32 and QDQ models to expose intermediate tensors
(``modify_model_output_intermediate_tensors``).
2. Run both with the same calibration ``.npy`` inputs
(``collect_activations``), matching ``quantize_onnx_model`` / ``build_onnx_calib_npy`` data.
3. ``create_activation_matching`` + SQNR; ``create_weight_matching`` + per-weight SQNR.
4. Print a report and optionally write JSON (scalar metrics only).
*float* should be the **same** float graph you quantized (ideally the ORT
``quant_pre_process`` output if you used ``--ort-preprocess`` in ``quantize_onnx_model.py``),
or the graph is unlikely to line-tensor match the QDQ model.
Example:
python3 scripts/debug_onnx_qdq.py \\
--float-model /path/to/float_infer.onnx \\
--qdq-model /path/to/inference_int8.onnx \\
--calib-data-dir /path/to/calib_npy \\
--max-samples 3 \\
--json-report qdq_debug.json
"""
from __future__ import annotations
import argparse
import json
import logging
import sys
import tempfile
from pathlib import Path
from typing import Any
_script_dir = Path(__file__).resolve().parent
if str(_script_dir) not in sys.path:
sys.path.insert(0, str(_script_dir))
from utils import build_npy_dir_reader, die
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def _parse_op_types(s: str | None) -> list[str] | None:
if not s or not s.strip():
return None
return [t.strip() for t in s.split(",") if t.strip()]
def _safe_compute_weight_error(
wmatch: dict[str, dict[str, Any]],
err_func: Any,
) -> dict[str, float]:
"""Like ORT ``compute_weight_error``, but coerce scalars to 0-d arrays.
``create_weight_matching`` can set ``dequantized`` to a bare ``numpy.float32``; ORT
``compute_signal_to_quantization_noice_ratio`` then does ``len(ylist)`` on that scalar
and raises ``TypeError``.
"""
import numpy as np
out: dict[str, float] = {}
for name, m in wmatch.items():
try:
xf = np.asarray(m["float"])
yd = np.asarray(m["dequantized"])
except (KeyError, TypeError, ValueError) as e:
logger.warning("weight SQNR skip %r: %s", name, e)
continue
if xf.size == 0 and yd.size == 0:
continue
if xf.size != yd.size:
logger.warning(
"weight SQNR skip %r: size mismatch %s vs %s",
name,
getattr(xf, "shape", xf),
getattr(yd, "shape", yd),
)
continue
try:
out[name] = float(err_func(xf, yd))
except (TypeError, ValueError, RuntimeError) as e:
logger.warning("weight SQNR skip %r: %s", name, e)
return out
def _safe_compute_activation_error(
match: dict[str, dict[str, Any]],
err_func: Any,
) -> dict[str, dict[str, float]]:
"""Like ORT ``compute_activation_error``, but skip missing *float* entries (avoids KeyError)."""
result: dict[str, dict[str, float]] = {}
for name, m in match.items():
e: dict[str, float] = {
"qdq_err": float(err_func(m["pre_qdq"], m["post_qdq"])),
}
if m.get("float"):
e["xmodel_err"] = float(err_func(m["float"], m["post_qdq"]))
result[name] = e
return result
def _sqnr_key(entry: dict[str, float], prefer_xmodel: bool) -> float:
if prefer_xmodel and "xmodel_err" in entry:
return entry["xmodel_err"]
return entry.get("qdq_err", float("nan"))
def _run(
float_model: Path,
qdq_model: Path,
calib: Path,
max_samples: int,
op_types: list[str] | None,
json_report: Path | None,
top_n: int,
skip_weights: bool,
skip_activations: bool,
) -> None:
from onnxruntime.quantization.qdq_loss_debug import (
collect_activations,
compute_signal_to_quantization_noice_ratio,
create_activation_matching,
create_weight_matching,
modify_model_output_intermediate_tensors,
)
if not float_model.is_file():
die(f"not a file: {float_model}")
if not qdq_model.is_file():
die(f"not a file: {qdq_model}")
if not skip_activations:
if not calib.is_dir():
die(f"not a directory: {calib}")
out_weights: dict[str, float] = {}
out_act: dict[str, dict[str, float]] = {}
if not skip_weights:
logger.info("weight matching (no inference run)…")
try:
wmatch = create_weight_matching(str(float_model), str(qdq_model))
except Exception as e:
die(f"create_weight_matching failed: {e}")
out_weights = _safe_compute_weight_error(
wmatch, compute_signal_to_quantization_noice_ratio
)
print("\n--- Weight SQNR (dB, higher is better) ---\n")
for name in sorted(out_weights, key=lambda x: out_weights[x]):
print(f" {name}: {out_weights[name]:.4f}")
if not skip_activations:
with tempfile.TemporaryDirectory(prefix="ort.qdq.debug.") as td:
tmp = Path(td)
aug_f = tmp / "augmented_float.onnx"
aug_q = tmp / "augmented_qdq.onnx"
op_arg = op_types if op_types is not None else []
logger.info("augmenting float model → %s", aug_f)
try:
modify_model_output_intermediate_tensors(
str(float_model), str(aug_f), op_types_for_saving=op_arg
)
except Exception as e:
die(f"modify_model_output_intermediate_tensors (float) failed: {e}")
logger.info("augmenting QDQ model → %s", aug_q)
try:
modify_model_output_intermediate_tensors(
str(qdq_model), str(aug_q), op_types_for_saving=op_arg
)
except Exception as e:
die(f"modify_model_output_intermediate_tensors (qdq) failed: {e}")
r_float = build_npy_dir_reader(float_model, calib, max_samples=max_samples)
r_qdq = build_npy_dir_reader(qdq_model, calib, max_samples=max_samples)
try:
logger.info("collect_activations (float)…")
act_f = collect_activations(str(aug_f), r_float)
logger.info("collect_activations (QDQ)…")
act_q = collect_activations(str(aug_q), r_qdq)
except Exception as e:
die(f"collect_activations failed: {e}")
match = create_activation_matching(act_q, act_f)
if not match:
print(
"\nwarning: empty activation match — is the quantized model QDQ (not QOperator)?",
file=sys.stderr,
)
out_act = _safe_compute_activation_error(
match, compute_signal_to_quantization_noice_ratio
)
has_xm = any("xmodel_err" in v for v in out_act.values())
scored = sorted(
out_act.items(),
key=lambda kv: _sqnr_key(kv[1], prefer_xmodel=has_xm),
)[: top_n if top_n > 0 else len(out_act)]
which = "xmodel_err (float vs post_qdq)" if has_xm else "qdq_err (q dq pair)"
print(
f"\n--- Top activation SQNR (dB, {which}; lower = worse) — showing "
f"{len(scored)} of {len(out_act)} —\n"
)
for name, m in scored:
if has_xm and "xmodel_err" in m:
print(
f" {name}: pre/post_qdq {m['qdq_err']:.4f} "
f"float vs post_qdq {m['xmodel_err']:.4f}"
)
else:
print(f" {name}: pre/post_qdq {m['qdq_err']:.4f}")
if json_report is not None:
payload: dict[str, Any] = {
"weight_sqnr_db": out_weights,
"activation_sqnr_db": out_act,
}
json_report = json_report.resolve()
json_report.parent.mkdir(parents=True, exist_ok=True)
with json_report.open("w", encoding="utf-8") as f:
json.dump(payload, f, indent=2, sort_keys=True)
print(f"\nwrote {json_report}")
def main() -> None:
ap = argparse.ArgumentParser(
description="ORT-style QDQ debug: float vs QDQ activations/weights (same .npy calib as quantize).",
)
ap.add_argument(
"--float-model",
type=Path,
required=True,
help="Float32 ONNX (same topology as the graph you quantized; use ORT preprocessed model if you used it before quantize).",
)
ap.add_argument(
"--qdq-model",
type=Path,
required=True,
help="Statically quantized (QDQ) ONNX model, e.g. from quantize_onnx_model.py.",
)
ap.add_argument(
"--calib-data-dir",
type=Path,
default=None,
help="Directory of float32 .npy used for calibration (required unless --skip-activations).",
)
ap.add_argument(
"--max-samples",
type=int,
default=5,
help="Max number of .npy files to use (default 5; full runs can be slow and memory-heavy).",
)
ap.add_argument(
"--op-types",
type=str,
default="",
help="Comma-separated op types to save intermediates for (e.g. Conv,Add). Empty = all float tensors (very slow and large).",
)
ap.add_argument(
"--json-report",
type=Path,
default=None,
help="Write metrics-only JSON to this path.",
)
ap.add_argument(
"--top",
type=int,
default=40,
help="How many activations to print (sorted worst-first by SQNR). 0 = print all.",
)
ap.add_argument(
"--skip-weights",
action="store_true",
help="Only run activation path (faster if you only care about activations).",
)
ap.add_argument(
"--skip-activations",
action="store_true",
help="Only run weight matching (no collect_activations; ignores calib).",
)
args = ap.parse_args()
if args.skip_weights and args.skip_activations:
die("cannot set both --skip-weights and --skip-activations")
if not args.skip_activations:
if args.calib_data_dir is None:
die("activation path requires --calib-data-dir")
if args.max_samples < 1:
die("--max-samples must be >= 1 for activation path")
_run(
float_model=args.float_model,
qdq_model=args.qdq_model,
calib=args.calib_data_dir or Path(),
max_samples=args.max_samples,
op_types=_parse_op_types(args.op_types),
json_report=args.json_report,
top_n=args.top,
skip_weights=args.skip_weights,
skip_activations=args.skip_activations,
)
if __name__ == "__main__":
main()
+380
View File
@@ -0,0 +1,380 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Extract named XCTAttachments from an .xcresult bundle into files.
Uses `xcrun xcresulttool` only. Prerequisites are probed against the **currently
selected** Xcode (`xcode-select`): see `_check_xcresulttool_capability`.
**Discovery (documented CLI behavior)**
- ``xcresulttool get test-results tests`` — “Get all tests from test report.”
(``xcrun xcresulttool help get test-results tests``). We walk Test Case nodes
and read each ``nodeIdentifierURL`` as ``--test-id``.
- ``xcresulttool get test-results activities`` — “Get the activity trees for the
specified test.” (``help get test-results activities``). Attachment records
(``name``, ``payloadId``) are taken from activity trees under ``testRuns``.
- ``xcresulttool export attachments`` — “An additional manifest.json file will be
generated… contains a list of attachment details for each test.”
(``help export attachments``). We resolve on-disk filenames via
``exportedFileName`` / ``suggestedHumanReadableName`` in that manifest when
present.
**Logical filename matching (repo heuristic, not from Apple help)**
We match ``--name`` to each activities record’s ``name`` by **exact string**, or
by **stem + underscore-suffixed** basename before the extension. Adjust
``_matches_wanted_attachment`` if your tests use different attachment titles.
If ``activities`` yields no attachments, we fall back to walking the ``tests``
JSON for ``attachments`` on nodes (empty after the activities pass in some
bundles).
"""
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any, List, Optional, Set, Tuple
AttachmentRow = Tuple[str, str, str] # stored_name, test_id_url, payload_id
def _die(what: str, where: str, next_step: str, code: int = 1) -> int:
sys.stderr.write(
f"[extract_xcresult_attachments] FAIL: {what}\n Where: {where}\n Next: {next_step}\n"
)
return code
def _run(cmd: List[str]) -> subprocess.CompletedProcess:
return subprocess.run(cmd, capture_output=True, check=False)
def _check_xcresulttool_capability() -> None:
"""Require `xcrun xcresulttool help get` to list `test-results` (command exists)."""
r = _run(["xcrun", "xcresulttool", "help", "get"])
text = (r.stdout + r.stderr).decode(errors="replace")
if "test-results" not in text:
raise SystemExit(
_die(
"`xcrun xcresulttool help get` has no `test-results` subcommand in this Xcode.",
"xcrun xcresulttool help get",
"Install a newer Xcode or `xcode-select` a toolchain that ships this subcommand.",
)
)
def _load_tests_json(result_path: Path) -> dict:
r = _run(
[
"xcrun",
"xcresulttool",
"get",
"test-results",
"tests",
"--path",
str(result_path),
"--format",
"json",
]
)
if r.returncode != 0:
raise SystemExit(
_die(
f"xcresulttool get test-results failed with exit {r.returncode}.",
str(result_path),
"Confirm the .xcresult was produced by a completed `xcodebuild test`.",
)
)
try:
return json.loads(r.stdout or b"{}")
except json.JSONDecodeError as e:
raise SystemExit(
_die(
f"Could not parse xcresulttool JSON: {e}.",
str(result_path),
"Re-run xcodebuild test to regenerate the .xcresult.",
)
)
def _collect_test_case_urls(node: dict) -> List[str]:
urls: List[str] = []
if node.get("nodeType") == "Test Case":
u = node.get("nodeIdentifierURL")
if isinstance(u, str) and u.startswith("test://"):
urls.append(u)
for ch in node.get("children") or []:
urls.extend(_collect_test_case_urls(ch))
return urls
def _walk_activity_tree(act: dict, acc: List[AttachmentRow], test_url: str) -> None:
for att in act.get("attachments") or []:
name = att.get("name")
pid = att.get("payloadId")
if isinstance(name, str) and isinstance(pid, str):
acc.append((name, test_url, pid))
for ch in act.get("childActivities") or []:
_walk_activity_tree(ch, acc, test_url)
def _attachments_from_activities(
result_path: Path, test_url: str
) -> List[AttachmentRow]:
r = _run(
[
"xcrun",
"xcresulttool",
"get",
"test-results",
"activities",
"--path",
str(result_path),
"--test-id",
test_url,
"--format",
"json",
]
)
if r.returncode != 0:
return []
try:
parsed = json.loads(r.stdout or b"{}")
except json.JSONDecodeError:
return []
acc: List[AttachmentRow] = []
for tr in parsed.get("testRuns") or []:
for act in tr.get("activities") or []:
_walk_activity_tree(act, acc, test_url)
return acc
def _walk_attachments_legacy(node: dict, acc: List[AttachmentRow]) -> None:
"""Fallback: walk ``tests`` JSON for ``attachments`` on nodes (used if activities path is empty)."""
identifier = node.get("identifier") or node.get("nodeIdentifierURL") or ""
for att in node.get("attachments") or []:
name = att.get("name")
pid = att.get("payloadId")
if isinstance(name, str) and isinstance(pid, str):
acc.append((name, str(identifier), pid))
for child in node.get("children") or []:
_walk_attachments_legacy(child, acc)
def _enumerate(result_path: Path) -> List[AttachmentRow]:
parsed = _load_tests_json(result_path)
acc: List[AttachmentRow] = []
urls: List[str] = []
for top in parsed.get("testNodes") or []:
urls.extend(_collect_test_case_urls(top))
for url in urls:
acc.extend(_attachments_from_activities(result_path, url))
if acc:
return acc
for top in parsed.get("testNodes") or []:
_walk_attachments_legacy(top, acc)
return acc
def _matches_wanted_attachment(stored: str, wanted: str) -> bool:
if stored == wanted:
return True
stem = Path(wanted).stem
suffix = Path(wanted).suffix if Path(wanted).suffix else ".json"
return stored.startswith(stem + "_") and stored.endswith(suffix)
def _pick_exported_file(
td_path: Path, wanted_out_name: str, stored_name: str
) -> Optional[Path]:
"""Pick the exported file using ``manifest.json`` when `xcresulttool export` writes it (see ``help export``)."""
manifest_path = td_path / "manifest.json"
if manifest_path.is_file():
try:
raw: Any = json.loads(manifest_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
raw = []
blocks: List[dict] = raw if isinstance(raw, list) else []
for block in blocks:
for att in block.get("attachments") or []:
if not isinstance(att, dict):
continue
sug = att.get("suggestedHumanReadableName") or ""
fn = att.get("exportedFileName")
if not isinstance(fn, str):
continue
candidate = td_path / fn
if not candidate.is_file():
continue
if sug == stored_name or _matches_wanted_attachment(
sug, wanted_out_name
):
return candidate
direct = td_path / stored_name
if direct.is_file():
return direct
for p in sorted(td_path.iterdir()):
if not p.is_file() or p.name == "manifest.json":
continue
if _matches_wanted_attachment(p.name, wanted_out_name):
return p
orphans = [
p
for p in td_path.iterdir()
if p.is_file() and p.suffix == ".json" and p.name != "manifest.json"
]
if len(orphans) == 1:
return orphans[0]
return None
def _export_one(
result_path: Path,
test_identifier: str,
wanted_out_name: str,
stored_name: str,
out_path: Path,
) -> None:
with tempfile.TemporaryDirectory() as td:
r = _run(
[
"xcrun",
"xcresulttool",
"export",
"attachments",
"--path",
str(result_path),
"--test-id",
test_identifier,
"--output-path",
td,
]
)
if r.returncode != 0:
raise SystemExit(
_die(
f"xcresulttool export attachments failed with exit {r.returncode}.",
f"test-id={test_identifier}",
"Inspect stderr above.",
)
)
td_path = Path(td)
src = _pick_exported_file(td_path, wanted_out_name, stored_name)
if src is None or not src.is_file():
raise SystemExit(
_die(
f"Could not resolve exported file (wanted {wanted_out_name!r}, stored {stored_name!r}).",
f"export dir: {td}",
"Check `manifest.json` and `xcresulttool export attachments` stderr.",
)
)
out_path.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(src), str(out_path))
def main(argv: List[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--result", required=True, type=Path, help="Path to .xcresult bundle."
)
parser.add_argument(
"--output-dir",
required=True,
type=Path,
help="Directory to write exported attachments into.",
)
parser.add_argument(
"--name",
action="append",
default=[],
help="Attachment name to extract (may be repeated). Fails the run if missing.",
)
parser.add_argument(
"--optional-name",
action="append",
default=[],
dest="optional_name",
help="Like --name, but a missing attachment is skipped with a message (exit still 0).",
)
args = parser.parse_args(argv)
if not args.name and not args.optional_name:
parser.error("at least one of --name or --optional-name is required")
_check_xcresulttool_capability()
if not args.result.exists():
return _die(
".xcresult bundle does not exist.",
str(args.result),
"Run `xcodebuild test -resultBundlePath <path>` first.",
)
attachments = _enumerate(args.result)
errors = 0
def _extract_wanted(wanted: str, optional: bool) -> None:
nonlocal errors
hits = [
(tid, sn)
for sn, tid, _pid in attachments
if _matches_wanted_attachment(sn, wanted)
]
uniq: Set[Tuple[str, str]] = set(hits)
if len(uniq) == 0:
if optional:
sys.stderr.write(
f"[extract_xcresult_attachments] optional attachment not found, skipping: {wanted!r}\n"
)
return
errors += _die(
f"Attachment not found: {wanted}.",
str(args.result),
"Confirm the test run attached JSON and inspect `get test-results activities` / `export attachments` for this bundle.",
)
return
if len(uniq) > 1:
errors += _die(
f"Attachment name collision: {wanted} matches {len(uniq)} exports.",
str(args.result),
"Ensure attachment base names are unique across tests.",
)
return
test_id, stored = next(iter(uniq))
_export_one(args.result, test_id, wanted, stored, args.out_dir / wanted)
for wanted in args.name:
_extract_wanted(wanted, optional=False)
for wanted in args.optional_name:
_extract_wanted(wanted, optional=True)
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Export XCTest performance metrics from an xcresult bundle."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence
def _die(message: str, code: int = 1) -> int:
sys.stderr.write(f"[extract_xctest_metrics] {message}\n")
return code
def _metric_summary(values: List[float]) -> Dict[str, float]:
if not values:
return {}
return {
"count": len(values),
"min": min(values),
"max": max(values),
"mean": sum(values) / len(values),
}
def export_metrics(result: Path) -> Dict[str, Any]:
proc = subprocess.run(
[
"xcrun",
"xcresulttool",
"get",
"test-results",
"metrics",
"--path",
str(result),
"--compact",
],
text=True,
capture_output=True,
check=False,
)
if proc.returncode != 0:
raise RuntimeError(proc.stderr.strip() or "xcresulttool metrics export failed")
raw = json.loads(proc.stdout or "[]")
tests = raw if isinstance(raw, list) else []
memory_metrics: List[Dict[str, Any]] = []
for test in tests:
if not isinstance(test, dict):
continue
for run in test.get("testRuns") or []:
if not isinstance(run, dict):
continue
device = run.get("device") if isinstance(run.get("device"), dict) else {}
config = (
run.get("testPlanConfiguration")
if isinstance(run.get("testPlanConfiguration"), dict)
else {}
)
for metric in run.get("metrics") or []:
if not isinstance(metric, dict):
continue
display_name = str(metric.get("displayName") or "")
identifier = str(metric.get("identifier") or "")
unit = str(metric.get("unitOfMeasurement") or "")
haystack = f"{display_name} {identifier} {unit}".lower()
if "memory" not in haystack:
continue
values = [
float(v)
for v in metric.get("measurements") or []
if isinstance(v, (int, float))
]
memory_metrics.append(
{
"testIdentifier": test.get("testIdentifier"),
"testIdentifierURL": test.get("testIdentifierURL"),
"device": device,
"configuration": config,
"displayName": display_name,
"identifier": identifier or None,
"unitOfMeasurement": unit,
"measurements": values,
"summary": _metric_summary(values),
}
)
return {
"schemaVersion": 1,
"source": "xcresulttool get test-results metrics",
"metrics": memory_metrics,
}
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--result", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args(list(argv) if argv is not None else None)
try:
doc = export_metrics(args.result)
except (OSError, RuntimeError, json.JSONDecodeError) as exc:
return _die(str(exc))
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(doc, indent=2, ensure_ascii=False), encoding="utf-8"
)
print(f"Wrote {args.output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env bash
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Fetch ONNX detection + recognition model bundles for the iOS demo.
#
# Requires: bash, curl, tar
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IOS_DEMO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
BASE_URL="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0"
ALLOWED_PRESETS=(PP-OCRv6_small PP-OCRv6_tiny PP-OCRv5_mobile)
DEFAULT_PRESET="PP-OCRv6_small"
DEST_DET="${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/det"
DEST_REC="${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/rec"
WORKDIR="${IOS_DEMO_ROOT}/.fetch_ios_demo_models_work"
usage() {
cat <<EOF
Usage: ./scripts/fetch_ios_demo_models.sh [-h|--help] [preset]
Downloads ONNX bundles into:
${DEST_DET}
${DEST_REC}
Options:
-h, --help Show this help
Positional:
preset Model preset; one of: ${ALLOWED_PRESETS[*]} (default: ${DEFAULT_PRESET})
EOF
}
preset="${DEFAULT_PRESET}"
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
usage
exit 0
;;
-*)
echo "error: unknown option: $1" >&2
exit 1
;;
*)
break
;;
esac
done
args=()
while [[ $# -gt 0 ]]; do
args+=("$1")
shift
done
if [[ ${#args[@]} -gt 1 ]]; then
echo "error: at most one model preset argument is allowed" >&2
exit 1
fi
if [[ ${#args[@]} -eq 1 ]]; then
preset="${args[0]}"
fi
die() {
echo "error: $*" >&2
exit 1
}
preset_allowed() {
local v="$1"
local x
for x in "${ALLOWED_PRESETS[@]}"; do
if [[ "$x" == "$v" ]]; then
return 0
fi
done
return 1
}
command -v curl >/dev/null || die "curl is required"
command -v tar >/dev/null || die "tar is required"
if ! preset_allowed "${preset}"; then
die "unsupported model preset: ${preset} (allowed: ${ALLOWED_PRESETS[*]})"
fi
DET_TAR="${preset}_det_onnx_infer.tar"
REC_TAR="${preset}_rec_onnx_infer.tar"
mkdir -p "${WORKDIR}"
fetch() {
local name="$1"
local url="${BASE_URL}/${name}"
local out="${WORKDIR}/${name}"
if [[ -f "${out}" ]]; then
echo "Using cached ${out}"
else
echo "Downloading ${url}"
curl -fL --retry 3 --retry-delay 2 -o "${out}" "${url}"
fi
}
extract() {
local tar_path="$1"
tar -xf "${tar_path}" -C "${WORKDIR}"
}
install_extracted_dir() {
local src_dir="$1"
local dest_dir="$2"
local label="$3"
[[ -d "${src_dir}" ]] || die "expected directory ${src_dir} (${label})"
mkdir -p "$(dirname "${dest_dir}")"
rm -rf "${dest_dir}"
mv "${src_dir}" "${dest_dir}"
}
echo "=== ONNX models (preset: ${preset}) ==="
echo "Work directory: ${WORKDIR}"
fetch "${DET_TAR}"
fetch "${REC_TAR}"
extract "${WORKDIR}/${DET_TAR}"
extract "${WORKDIR}/${REC_TAR}"
DET_SRC="${WORKDIR}/$(basename "${DET_TAR}" .tar)"
REC_SRC="${WORKDIR}/$(basename "${REC_TAR}" .tar)"
install_extracted_dir "${DET_SRC}" "${DEST_DET}" "det"
install_extracted_dir "${REC_SRC}" "${DEST_REC}" "rec"
echo "Installed:"
echo " ${DEST_DET}"
echo " ${DEST_REC}"
+697
View File
@@ -0,0 +1,697 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Merge optional benchmark JSONs into a local Markdown report.
Inputs:
--accuracy-summary Optional JSON from compare_ocr_json.py
--on-device-performance-json JSON attachment "on-device-performance.json"
--run-status JSON from run_benchmark.sh
--xctest-metrics-json JSON from extract_xctest_metrics.py
All inputs are optional; missing sections render placeholders.
"""
from __future__ import annotations
import argparse
import json
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence
def _run_text(cmd: List[str]) -> Optional[str]:
try:
return subprocess.check_output(
cmd, stderr=subprocess.DEVNULL, text=True
).strip()
except (OSError, subprocess.CalledProcessError):
return None
def _git_short() -> Optional[str]:
return _run_text(["git", "rev-parse", "--short", "HEAD"])
def _xcode_version() -> Optional[str]:
return _run_text(["xcodebuild", "-version"])
def _sw_vers() -> Optional[str]:
return _run_text(["sw_vers", "-productVersion"])
def _load_json(path: Path) -> Dict[str, Any]:
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
def _fmt_bytes(n: Optional[int]) -> str:
if n is None:
return "— (path missing)"
if n < 1024:
return f"{n} B"
if n < 1024 * 1024:
return f"{n / 1024:.1f} KiB"
return f"{n / (1024 * 1024):.2f} MiB"
def _fmt_duration_ms(raw: Any) -> str:
if raw is None:
return "—"
try:
ms = float(raw)
except (TypeError, ValueError):
return "—"
if ms < 1000:
return f"{ms:.0f} ms"
return f"{ms / 1000:.2f} s"
def _fmt_ms(raw: Any) -> str:
try:
return f"{float(raw):.4f} ms"
except (TypeError, ValueError):
return "—"
def _fmt_shape(raw: Any) -> str:
if isinstance(raw, list) and raw:
return "`[" + ", ".join(str(x) for x in raw) + "]`"
return "—"
def _truthy(value: Any) -> bool:
if isinstance(value, bool):
return value
if value is None:
return False
return str(value).strip().lower() in {"1", "true", "yes", "on"}
def _benchmark_value(
status: Dict[str, Any],
perf_data: Optional[Dict[str, Any]],
key: str,
) -> Any:
benchmark = (
status.get("benchmark") if isinstance(status.get("benchmark"), dict) else {}
)
if key in benchmark:
return benchmark.get(key)
if isinstance(perf_data, dict):
return perf_data.get(key)
return None
def _benchmark_warnings(
status: Dict[str, Any],
perf_data: Optional[Dict[str, Any]],
) -> List[str]:
warnings: List[str] = []
build = _benchmark_value(status, perf_data, "buildConfiguration")
is_sim = _benchmark_value(status, perf_data, "isSimulator")
profiling = _benchmark_value(status, perf_data, "ortProfilingEnabled")
if build and str(build) != "Release":
warnings.append(f"build configuration is `{build}`, not `Release`")
if _truthy(is_sim):
warnings.append("destination is simulator")
if _truthy(profiling):
warnings.append("ORT profiling is enabled")
return warnings
def _benchmark_metadata_markdown(
status: Dict[str, Any],
perf_data: Optional[Dict[str, Any]],
) -> str:
rows: List[str] = ["| Metric | Value |", "|--------|-------|"]
ep = _benchmark_value(status, perf_data, "ortExecutionProvider")
if ep is not None:
rows.append(f"| ORT execution provider | `{ep}` |")
for key, label in [
("buildConfiguration", "Build configuration"),
("deviceModel", "Device model"),
("osVersion", "OS version"),
("isSimulator", "Simulator"),
("modelPreset", "Model preset"),
("ortProfilingEnabled", "ORT profiling"),
]:
value = _benchmark_value(status, perf_data, key)
if value is None:
continue
rows.append(f"| {label} | `{value}` |")
warnings = _benchmark_warnings(status, perf_data)
if warnings:
rows.append("")
rows.append(
"> Not publishable: "
+ "; ".join(warnings)
+ ". Only Release runs on a real device with ORT profiling disabled should be used as publishable latency numbers."
)
else:
rows.append("")
rows.append(
"> Publishable baseline: Release run on a real device with ORT profiling disabled."
)
return "\n".join(rows)
def _model_artifacts_markdown(status: Dict[str, Any]) -> str:
benchmark = (
status.get("benchmark") if isinstance(status.get("benchmark"), dict) else {}
)
model_files = (
benchmark.get("modelFiles")
if isinstance(benchmark.get("modelFiles"), dict)
else {}
)
det = (
model_files.get("detection")
if isinstance(model_files.get("detection"), dict)
else {}
)
rec = (
model_files.get("recognition")
if isinstance(model_files.get("recognition"), dict)
else {}
)
rows = ["| Artifact | Format | Size |", "|----------|--------|------|"]
rows.append(
f"| Detection model | `{det.get('format') or '—'}` | {_fmt_bytes(det.get('sizeBytes'))} |"
)
rows.append(
f"| Recognition model | `{rec.get('format') or '—'}` | {_fmt_bytes(rec.get('sizeBytes'))} |"
)
rows.append(
f"| Total model weights | — | {_fmt_bytes(model_files.get('totalSizeBytes'))} |"
)
rows.append(
f"| App executable | — | {_fmt_bytes(benchmark.get('appBinarySizeBytes'))} |"
)
return "\n".join(rows)
# ---------- run-status ----------
def _run_status_section(status: Dict[str, Any]) -> str:
lines: List[str] = ["## Run status", ""]
lines.append(f"- **Exit code:** `{status.get('exitCode', '—')}`")
image = status.get("image") or {}
if image:
lines.append(
f"- **Image:** `{image.get('name', '—')}` ({image.get('source', '—')})"
)
dest = status.get("destination")
if dest:
lines.append(f"- **Destination:** `{dest}`")
benchmark = (
status.get("benchmark") if isinstance(status.get("benchmark"), dict) else {}
)
if benchmark:
if build := benchmark.get("buildConfiguration"):
lines.append(f"- **Build configuration:** `{build}`")
ep = benchmark.get("ortExecutionProvider")
if ep:
lines.append(f"- **ORT execution provider:** `{ep}`")
if scope := benchmark.get("testingScope"):
lines.append(f"- **Testing scope:** `{scope}`")
started = status.get("runStartedAt")
finished = status.get("runFinishedAt")
if started and finished:
lines.append(f"- **Run window:** {started} → {finished}")
lines.append("")
lines.append("| Step | Status | Duration | Notes |")
lines.append("|------|--------|----------|-------|")
for step in status.get("steps") or []:
name = step.get("name", "?")
st = (step.get("status") or "?").upper()
dur = _fmt_duration_ms(step.get("durationMs"))
note = step.get("reason") or ""
if step.get("logPath"):
note = (note + " · " if note else "") + f"see `{step['logPath']}`"
if step.get("exitCode") not in (None, 0):
note = (note + " · " if note else "") + f"exit {step['exitCode']}"
lines.append(f"| {name} | {st} | {dur} | {note} |")
return "\n".join(lines)
def _stale_data_banner(overall: str) -> str:
return (
f"> This run ended with status **{overall}**; the numbers below may be partial or stale. "
"Do not use them as a baseline.\n"
)
def _performance_section_banner(overall: Optional[str]) -> str:
if overall and overall != "COMPLETED":
return _stale_data_banner(overall)
return ""
# ---------- timing + memory (on-device performance) ----------
def _timing_markdown(data: Dict[str, Any]) -> str:
lines = ["| Metric | mean | stdev | p90 |", "|--------|------|-------|-----|"]
for key, label in [
("totalTimeMs", "Full OCR latency (ms)"),
("detectionTimeMs", "Detection stage latency (ms)"),
("detectionPreprocessTimeMs", "Detection preprocess latency (ms)"),
("detectionInferenceTimeMs", "Detection inference segment latency (ms)"),
("detectionPostprocessTimeMs", "Detection postprocess latency (ms)"),
("recognitionTimeMs", "Recognition stage latency (ms)"),
("recognitionPreprocessTimeMs", "Recognition preprocess latency (ms)"),
("recognitionInferenceTimeMs", "Recognition inference segment latency (ms)"),
("recognitionPostprocessTimeMs", "Recognition postprocess latency (ms)"),
]:
block = data.get(key)
if not isinstance(block, dict):
continue
lines.append(
"| {label} | {mean:.4f} | {stdev:.4f} | {p90:.4f} |".format(
label=label,
mean=float(block.get("mean", 0)),
stdev=float(block.get("stdev", 0)),
p90=float(block.get("p90", 0)),
)
)
ovh = data.get("pipelineOverheadTimeMs")
if isinstance(ovh, dict):
lines.append(
"| Pipeline overhead latency (ms) | {mean:.4f} | {stdev:.4f} | {p90:.4f} |".format(
mean=float(ovh.get("mean", 0)),
stdev=float(ovh.get("stdev", 0)),
p90=float(ovh.get("p90", 0)),
)
)
w = data.get("warmupIterations")
m = data.get("measuredIterations")
if w is not None or m is not None:
lines.append("")
lines.append(f"Warmup iterations: `{w}` · Measured iterations: `{m}`")
lines.append("")
lines.append(
"*Inference segment latency includes the tensor input/output handling required by the ORT wrapper, "
"`session.run`, output reads, and validation. It is not pure kernel latency or isolated `session.run` latency.*"
)
per_line_extra = _recognition_per_line_markdown(data)
if per_line_extra:
lines.append("")
lines.append(per_line_extra)
return "\n".join(lines)
def _input_profile_markdown(data: Dict[str, Any]) -> str:
dist = (
data.get("inputShapeDistribution")
if isinstance(data.get("inputShapeDistribution"), dict)
else {}
)
rows = [
"| Model | Input tensor shape | Count |",
"|-------|--------------------|-------|",
]
for model_key, label in [
("detection", "Detection"),
("recognition", "Recognition"),
]:
samples = dist.get(model_key)
if not isinstance(samples, list) or not samples:
rows.append(f"| {label} | — | `0` |")
continue
for sample in samples:
if not isinstance(sample, dict):
continue
rows.append(
f"| {label} | {_fmt_shape(sample.get('shape'))} | `{sample.get('count', '—')}` |"
)
rows.append("")
rows.append("| Metric | Value |")
rows.append("|--------|-------|")
rows.append(
f"| First measured run line count | `{data.get('firstMeasuredLineCount', '—')}` |"
)
rows.append(f"| Cold model load time | {_fmt_ms(data.get('coldLoadTimeMs'))} |")
rows.append("")
rows.append(
"*Input tensor shape counts are counted per model invocation in the measured loop.*"
)
return "\n".join(rows)
def _recognition_per_line_markdown(data: Dict[str, Any]) -> str:
"""Renders pooled `recognitionPerLine` samples."""
pl = data.get("recognitionPerLine")
if not isinstance(pl, dict):
return ""
out: List[str] = []
pooled = pl.get("pooled")
any_pooled = False
pooled_lines: List[str] = [
"| Pooled (all lines × measured runs) | count | mean | stdev | p90 |",
"|------------------------------------|------|------|-------|-----|",
]
for key, label in [
("preprocessMs", "Per-line recognition preprocess pooled (ms)"),
("inferenceMs", "Per-line recognition inference segment pooled (ms)"),
("postprocessMs", "Per-line recognition postprocess pooled (ms)"),
("totalMs", "Per-line recognition total pooled (ms)"),
]:
if not isinstance(pooled, dict):
break
b = pooled.get(key)
if not isinstance(b, dict):
continue
c = pooled.get("count") or b.get("count")
if c is None or c == 0:
continue
any_pooled = True
pooled_lines.append(
"| {label} | {c} | {me:.4f} | {sd:.4f} | {p90:.4f} |".format(
label=label,
c=int(c),
me=float(b.get("mean", 0)),
sd=float(b.get("stdev", 0)),
p90=float(b.get("p90", 0)),
)
)
if any_pooled:
out.append("#### Per-line Recognition Latency (ms)")
out.append("")
out.append(
"*Pooled* merges every detected line from every measured full-image run."
)
out.append("")
out.extend(pooled_lines)
return "\n".join(out) if out else ""
def _fmt_metric_number(value: Any, unit: str) -> str:
try:
number = float(value)
except (TypeError, ValueError):
return "—"
if unit.lower() == "kb":
return f"{number / 1024:.2f} MB"
if "byte" in unit.lower():
return _fmt_bytes(int(number))
if abs(number) >= 1000:
text = f"{number:.0f}"
else:
text = f"{number:.4f}".rstrip("0").rstrip(".")
return f"{text} {unit}".rstrip()
def _xctest_memory_rows(xctest_metrics: Optional[Dict[str, Any]]) -> List[str]:
rows: List[str] = []
metrics = (
xctest_metrics.get("metrics") if isinstance(xctest_metrics, dict) else None
)
if not isinstance(metrics, list) or not metrics:
rows.append("| XCTest memory metric | `not available` |")
return rows
for metric in metrics:
if not isinstance(metric, dict):
continue
summary = (
metric.get("summary") if isinstance(metric.get("summary"), dict) else {}
)
unit = str(metric.get("unitOfMeasurement") or "")
raw_label = str(
metric.get("displayName") or metric.get("identifier") or "memory"
)
label = {
"Memory Physical": "physical memory delta",
"Memory Peak Physical": "physical memory peak",
}.get(raw_label, raw_label)
test_id = metric.get("testIdentifier")
prefix = f"XCTest {label}"
if test_id:
prefix += f" ({test_id})"
rows.append(f"| {prefix} count | `{int(summary.get('count', 0))}` |")
rows.append(
f"| {prefix} min | {_fmt_metric_number(summary.get('min'), unit)} |"
)
rows.append(
f"| {prefix} max | {_fmt_metric_number(summary.get('max'), unit)} |"
)
rows.append(
f"| {prefix} mean | {_fmt_metric_number(summary.get('mean'), unit)} |"
)
return rows
def _memory_markdown(
data: Dict[str, Any],
xctest_metrics: Optional[Dict[str, Any]],
) -> str:
if data.get("memoryFootprintAfterLoadBytes") is None and xctest_metrics is None:
return ""
rows = [
"| Metric | Value |",
"|--------|-------|",
]
rows.extend(_xctest_memory_rows(xctest_metrics))
before = data.get("memoryFootprintBeforeLoadBytes")
if before is not None:
rows.append(f"| Footprint before load | {_fmt_bytes(int(before))} |")
after = data.get("memoryFootprintAfterLoadBytes")
if after is not None:
rows.append(f"| Footprint after model load | {_fmt_bytes(int(after))} |")
ts = data.get("thermalState")
if ts is not None:
rows.append(f"| Thermal state | `{ts}` |")
rows.append("")
rows.append(
"`physical memory delta` is a per-iteration net change, so negative values mean memory was released during that measured block. "
"`task_vm_info.phys_footprint` rows are diagnostic snapshots before and after model loading, not continuous peak measurements.*"
)
return "\n".join(rows)
def _on_device_section(
data: Dict[str, Any],
xctest_metrics: Optional[Dict[str, Any]],
status: Optional[Dict[str, Any]] = None,
) -> str:
parts: List[str] = []
ver = data.get("schemaVersion")
if ver is not None:
parts.append(f"Schema version: `{ver}`")
parts.append("")
parts.append("### Benchmark metadata")
parts.append("")
parts.append(_benchmark_metadata_markdown(status or {}, data))
parts.append("")
parts.append(
"*Latency and memory are both runtime performance attributes, but they are sampled by separate benchmark paths.*"
)
parts.append("")
parts.append("### Model and app artifacts")
parts.append("")
parts.append(_model_artifacts_markdown(status or {}))
parts.append("")
parts.append("### Input profile")
parts.append("")
parts.append(_input_profile_markdown(data))
parts.append("")
parts.append("### Latency")
parts.append("")
parts.append(_timing_markdown(data))
mem = _memory_markdown(data, xctest_metrics)
if mem:
parts.append("")
parts.append("### Memory (resource footprint)")
parts.append("")
parts.append(mem)
return "\n".join(parts)
# ---------- accuracy ----------
def _compare_section(data: Dict[str, Any]) -> str:
passed = data.get("pass")
status = "**PASS**" if passed is True else ("**FAIL**" if passed is False else "—")
return "\n".join(
[
f"Status: {status}",
"",
"```json",
json.dumps(data, indent=2, ensure_ascii=False),
"```",
]
)
def _accuracy_section(
summary_data: Optional[Dict[str, Any]],
run_status: Dict[str, Any],
) -> str:
accuracy = (
run_status.get("accuracy")
if isinstance(run_status.get("accuracy"), dict)
else {}
)
enabled = bool(accuracy.get("enabled")) or summary_data is not None
if not enabled:
return ""
parts: List[str] = ["## Accuracy check", ""]
status = str(accuracy.get("status") or "").upper()
reason = accuracy.get("reason")
if status:
parts.append(f"Precheck status: **{status}**")
if reason:
parts.append("")
parts.append(f"> {reason}")
parts.append("")
parts.append("")
if summary_data is not None:
parts.append(_compare_section(summary_data))
elif enabled:
parts.append("*No accuracy summary JSON was produced.*")
return "\n".join(parts)
# ---------- driver ----------
def _placeholder_from_status(status: Dict[str, Any], for_step: str) -> str:
for step in status.get("steps") or []:
if step.get("status") in ("fail", "skipped"):
reason = step.get("reason") or ""
if step.get("name") == for_step or reason:
return (
f"*Unavailable — step `{step.get('name', '?')}` ended in "
f"`{step.get('status')}`"
+ (f"; reason: {reason}" if reason else "")
+ ".*"
)
return "*Unavailable — no artifact and no run-status reason.*"
def generate_report(
*,
out_path: Path,
on_device_performance_json: Optional[Path],
accuracy_summary: Optional[Path],
run_status: Optional[Path],
xctest_metrics_json: Optional[Path],
) -> None:
status: Dict[str, Any] = {}
if run_status and run_status.is_file():
status = _load_json(run_status)
overall = (status.get("overall") or "").upper() or None
accuracy_data = (
_load_json(accuracy_summary)
if accuracy_summary and accuracy_summary.is_file()
else None
)
perf_data = (
_load_json(on_device_performance_json)
if on_device_performance_json and on_device_performance_json.is_file()
else None
)
xctest_metrics_data = (
_load_json(xctest_metrics_json)
if xctest_metrics_json and xctest_metrics_json.is_file()
else None
)
head_lines: List[str] = ["# iOS demo — benchmark report", ""]
if overall:
head_lines.append(f"**Overall:** {overall}")
head_lines.append("")
parts: List[str] = ["\n".join(head_lines)]
if status:
parts.append(_run_status_section(status))
parts.append("")
perf_banner = _performance_section_banner(overall)
accuracy_section = _accuracy_section(accuracy_data, status)
if accuracy_section:
parts.append(accuracy_section)
parts.append("")
parts.append("## On-device runtime performance")
parts.append("")
if perf_banner:
parts.append(perf_banner)
if perf_data is not None:
parts.append(_on_device_section(perf_data, xctest_metrics_data, status))
else:
parts.append(
_placeholder_from_status(status, "extract-artifacts")
if status
else "*No performance JSON provided.*"
)
parts.append("")
parts.append("## Metadata")
parts.append("")
parts.append(
f"- **Generated:** {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}"
)
if v := _sw_vers():
parts.append(f"- **macOS:** {v}")
if v := _xcode_version():
parts.append("- **Xcode:**\n```\n" + v + "\n```")
if g := _git_short():
parts.append(f"- **Git (short):** `{g}`")
parts.append("")
parts.append("*Generated by `scripts/generate_benchmark_report.py`.*")
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text("\n".join(parts), encoding="utf-8")
print(f"Wrote {out_path}")
def main(argv: Optional[Sequence[str]] = None) -> int:
root = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--output", type=Path, default=root / "out" / "benchmark-report.md"
)
parser.add_argument("--on-device-performance-json", type=Path, default=None)
parser.add_argument("--accuracy-summary", type=Path, default=None)
parser.add_argument("--run-status", type=Path, default=None)
parser.add_argument("--xctest-metrics-json", type=Path, default=None)
args = parser.parse_args(list(argv) if argv is not None else None)
generate_report(
out_path=args.output.resolve(),
on_device_performance_json=args.on_device_performance_json,
accuracy_summary=args.accuracy_summary,
run_status=args.run_status,
xctest_metrics_json=args.xctest_metrics_json,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+213
View File
@@ -0,0 +1,213 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate a JSON reference OCR result for comparison with the iOS demo.
Uses ``PaddleOCR`` with ``engine="onnxruntime"`` and no doc-orientation /
unwarping / textline-orientation modules.
Examples:
python ocr_reference_run.py --image a.png --output ref.json \\
--device cpu --align-ios-defaults
# Explicit models path
python ocr_reference_run.py --image a.png --output ref.json \\
--ios-models-root /path/to/PaddleOCRDemo/Models --device cpu --align-ios-defaults
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Sequence
def _paddleocr_package_root() -> Path:
return Path(__file__).resolve().parents[3]
def _default_ios_models_root() -> Path:
return Path(__file__).resolve().parent.parent / "PaddleOCRDemo" / "Models"
def _load_yaml_model_name(path: Path) -> str:
try:
import yaml
except ImportError as exc:
raise RuntimeError("PyYAML is required to read inference.yml") from exc
with path.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f)
return data["Global"]["model_name"]
def _numpy_to_python(obj: Any) -> Any:
if obj is None:
return None
if hasattr(obj, "tolist"):
return obj.tolist()
if isinstance(obj, (list, tuple)):
return [_numpy_to_python(x) for x in obj]
if isinstance(obj, dict):
return {k: _numpy_to_python(v) for k, v in obj.items()}
elif isinstance(obj, (str, int, float, bool)):
return obj
return str(obj)
def _extract_items(result_obj: Any) -> List[Dict[str, Any]]:
"""Build a list of {polygon, text, score} from an OCR pipeline result."""
if isinstance(result_obj, dict):
res = result_obj
elif hasattr(result_obj, "__getitem__"):
res = dict(result_obj)
else:
raise TypeError(f"Unsupported result type: {type(result_obj)}")
return _extract_items_from_res_dict(res)
def _extract_items_from_res_dict(res: Dict[str, Any]) -> List[Dict[str, Any]]:
texts = res.get("rec_texts") or []
scores = res.get("rec_scores")
polys = res.get("rec_polys") or res.get("dt_polys") or []
if hasattr(scores, "tolist"):
scores = scores.tolist()
items: List[Dict[str, Any]] = []
n = min(len(texts), len(polys))
for i in range(n):
poly = polys[i]
if hasattr(poly, "tolist"):
poly = poly.tolist()
score = float(scores[i]) if scores is not None and i < len(scores) else None
items.append(
{
"polygon": _numpy_to_python(poly),
"text": str(texts[i]),
"score": score,
}
)
return items
def _build_ocr(
*,
device: str,
text_detection_model_name: str | None,
text_recognition_model_name: str | None,
text_detection_model_dir: str | None,
text_recognition_model_dir: str | None,
) -> Any:
from paddleocr import PaddleOCR
kwargs: Dict[str, Any] = dict(
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
device=device,
engine="onnxruntime",
)
if text_detection_model_name:
kwargs["text_detection_model_name"] = text_detection_model_name
if text_recognition_model_name:
kwargs["text_recognition_model_name"] = text_recognition_model_name
if text_detection_model_dir:
kwargs["text_detection_model_dir"] = text_detection_model_dir
if text_recognition_model_dir:
kwargs["text_recognition_model_dir"] = text_recognition_model_dir
return PaddleOCR(**kwargs)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="OCR reference JSON for iOS demo comparison"
)
parser.add_argument("--image", required=True, help="Input image path")
parser.add_argument("--output", required=True, help="Output JSON path")
parser.add_argument("--device", default="cpu", help="Device, e.g. cpu or gpu:0")
parser.add_argument(
"--ios-models-root",
type=Path,
default=_default_ios_models_root(),
help="Path to models directory",
)
parser.add_argument(
"--align-ios-defaults",
action="store_true",
help="Match OCRParameterResolver app-tier defaults (Swift demo)",
)
args = parser.parse_args(list(argv) if argv is not None else None)
image_path = Path(args.image).resolve()
if not image_path.is_file():
print(f"error: image not found: {image_path}", file=sys.stderr)
return 2
root = Path(args.ios_models_root).resolve()
det_yml = root / "det" / "inference.yml"
rec_yml = root / "rec" / "inference.yml"
if not det_yml.is_file() or not rec_yml.is_file():
print(f"error: expected {det_yml} and {rec_yml}", file=sys.stderr)
return 2
text_detection_model_name = _load_yaml_model_name(det_yml)
text_recognition_model_name = _load_yaml_model_name(rec_yml)
text_detection_model_dir = str(root / "det")
text_recognition_model_dir = str(root / "rec")
ocr = _build_ocr(
device=args.device,
text_detection_model_name=text_detection_model_name,
text_recognition_model_name=text_recognition_model_name,
text_detection_model_dir=text_detection_model_dir,
text_recognition_model_dir=text_recognition_model_dir,
)
predict_kwargs: Dict[str, Any] = {}
if args.align_ios_defaults:
predict_kwargs.update(
text_det_limit_side_len=64,
text_det_limit_type="min",
text_det_thresh=0.3,
text_det_box_thresh=0.6,
text_det_unclip_ratio=1.5,
text_rec_score_thresh=0.0,
)
results = ocr.predict(str(image_path), **predict_kwargs)
if not results:
print("error: empty predict() result", file=sys.stderr)
return 3
items = _extract_items(results[0])
payload: Dict[str, Any] = {
"schema_version": 1,
"source": "paddleocr_reference",
"engine": "onnxruntime",
"image": str(image_path),
"items": items,
}
out_path = Path(args.output).resolve()
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
print(f"Wrote {len(items)} lines to {out_path}")
return 0
if __name__ == "__main__":
sys.path.insert(0, str(_paddleocr_package_root()))
raise SystemExit(main())
+385
View File
@@ -0,0 +1,385 @@
#!/usr/bin/env python3
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Quantize a bundled PaddleOCR ONNX model.
Reads ``inference.onnx`` from ``--input-model-dir``, writes quantized ``inference.onnx`` to
``--output-model-dir``. When input and output directories differ, copies ``inference.yml`` from
source to destination after a successful quantize. In-place mode (same directory) only
replaces ``inference.onnx``.
Examples:
# Dynamic (weights int8); no calibration data
python quantize_onnx_model.py --input-model-dir ./PaddleOCRDemo/Models/det \\
--output-model-dir ./out/det_q --mode dynamic
# Static; one .npy file per calibration sample (float32, model input shape)
python quantize_onnx_model.py --input-model-dir ./Models/rec \\
--output-model-dir ./Models/rec_int8 --mode static \\
--calib-data-dir ./my_calib_npy
"""
from __future__ import annotations
import argparse
import os
import shutil
import sys
import tempfile
from pathlib import Path
from typing import Any
_script_dir = Path(__file__).resolve().parent
if str(_script_dir) not in sys.path:
sys.path.insert(0, str(_script_dir))
from utils import build_npy_dir_reader, die
def _same_file(a: Path, b: Path) -> bool:
try:
return a.resolve() == b.resolve()
except OSError:
return False
def _run_ort_quant_pre_process(src_onnx: Path, work_dir: Path) -> Path:
"""Run ORT *quant_pre_process*; write a new ONNX with ``onnx.quant.pre_process`` metadata.
Tries, in order: default → ``skip_symbolic_shape`` (some det/NMS graphs fail symbolic infer)
→ also ``skip_optimization`` (last resort). Removes any failed output before retrying.
"""
try:
from onnxruntime.quantization import quant_pre_process
except ImportError as e:
die(
f"onnxruntime.quantization.quant_pre_process is required for --ort-preprocess: {e}"
)
fd, raw = tempfile.mkstemp(
suffix=".pre.onnx",
prefix="inference.ort_",
dir=str(work_dir),
)
os.close(fd)
out = Path(raw)
attempts: list[tuple[str, dict[str, bool]]] = [
(
"(full symbolic + ORT optimize)",
{"skip_symbolic_shape": False, "skip_optimization": False},
),
(
"(skip symbolic shape, keep ORT optimize)",
{"skip_symbolic_shape": True, "skip_optimization": False},
),
(
"(skip symbolic shape, skip ORT graph optimization)",
{"skip_symbolic_shape": True, "skip_optimization": True},
),
]
last_err: Exception | None = None
for label, kwargs in attempts:
out.unlink(missing_ok=True)
try:
quant_pre_process(
input_model=str(src_onnx),
output_model_path=str(out),
**kwargs,
)
except Exception as e:
last_err = e
continue
if label != attempts[0][0]:
print(
f"warning: ORT quant_pre_process succeeded with {label}.",
file=sys.stderr,
)
return out
out.unlink(missing_ok=True)
die(
f"ORT quant_pre_process failed after {len(attempts)} attempt(s). Last error: {last_err!r}. "
"You can try again with --no-ort-preprocess to quantize the original model only."
)
def _quantize_dynamic(src_onnx: Path, dst_onnx: Path, per_channel: bool) -> None:
from onnxruntime.quantization import QuantType, quantize_dynamic
quantize_dynamic(
model_input=str(src_onnx),
model_output=str(dst_onnx),
weight_type=QuantType.QInt8,
per_channel=per_channel,
)
def _quantize_static(
src_onnx: Path,
dst_onnx: Path,
calib_dir: Path,
per_channel: bool,
calibrate_method_name: str,
) -> None:
from onnxruntime.quantization import (
CalibrationMethod,
QuantFormat,
QuantType,
quantize_static,
)
reader = build_npy_dir_reader(src_onnx, calib_dir)
try:
method = getattr(CalibrationMethod, calibrate_method_name)
except AttributeError:
die(
f"unknown calibration method {calibrate_method_name!r}; "
f"valid names: {', '.join(CalibrationMethod.__members__)}"
)
quantize_static(
model_input=str(src_onnx),
model_output=str(dst_onnx),
calibration_data_reader=reader,
quant_format=QuantFormat.QDQ,
activation_type=QuantType.QUInt8,
weight_type=QuantType.QInt8,
per_channel=per_channel,
calibrate_method=method,
)
def _default_domain_onnx_opset(m: Any) -> int:
"""Max declared opset for default / ``ai.onnx`` imports."""
v = 0
for oi in m.opset_import:
dom = oi.domain or ""
if dom in ("", "ai.onnx"):
v = max(v, int(oi.version))
return v
def _try_onnx_opset_via_version_converter(path: Path, target_opset: int) -> str:
import onnx
from onnx import version_converter
m = onnx.load(str(path), load_external_data=True)
cur = _default_domain_onnx_opset(m)
if cur >= target_opset:
return "skipped_already_ge_target"
try:
m2 = version_converter.convert_version(m, target_opset)
except Exception as e:
print(
f"warning: onnx.version_converter.convert_version(..., {target_opset}) failed: {e!r}. "
"Full checker may still fail. Try a newer `onnx`, or use --no-verify if ORT loads the model.",
file=sys.stderr,
)
return "convert_failed"
try:
onnx.save(m2, str(path))
except Exception as e:
die(f"failed to write ONNX after version conversion: {e}")
return "converted"
def _verify_onnx_file(path: Path) -> None:
"""Validate the output with the ONNX checker (avoids ORT IR / build skew in the host venv)."""
import onnx
m = onnx.load(str(path), load_external_data=True)
try:
onnx.checker.check_model(m, full_check=True)
except Exception as e:
die(f"output model failed ONNX checker validation: {e}")
def _atomic_replace(src: Path, dst: Path) -> None:
os.replace(str(src), str(dst))
def main() -> None:
p = argparse.ArgumentParser(description="Quantize PaddleOCR ONNX model.")
p.add_argument(
"--input-model-dir",
required=True,
type=Path,
help="Input model directory",
)
p.add_argument(
"--output-model-dir",
required=True,
type=Path,
help="Output model directory",
)
p.add_argument(
"--mode",
required=True,
choices=("dynamic", "static"),
help="dynamic: weight-only (quantize_dynamic). static: QDQ (quantize_static, needs --calib-data-dir).",
)
p.add_argument(
"--calib-data-dir",
type=Path,
default=None,
help="Directory of float32 .npy calibration samples (static mode only; one tensor per file).",
)
p.add_argument(
"--per-channel",
action=argparse.BooleanOptionalAction,
default=True,
help="Per-channel weight quantization (default: true).",
)
p.add_argument(
"--calibration-method",
default="MinMax",
help="ORT CalibrationMethod name (e.g. MinMax, Entropy, Percentile).",
)
p.add_argument(
"--no-verify",
action="store_true",
help="Skip ONNX checker validation of the output model after quantization.",
)
p.add_argument(
"--ort-preprocess",
action=argparse.BooleanOptionalAction,
default=True,
help=(
"Before quantize_static / quantize_dynamic, run ORT quant_pre_process (shape infer + "
"optional graph optimization) and attach onnx.quant metadata."
),
)
p.add_argument(
"--onnx-opset-convert",
action=argparse.BooleanOptionalAction,
default=True,
help=(
"After ORT writes the output, run onnx.version_converter when the graph's declared "
"default-domain opset is below --onnx-target-opset. Use --no-onnx-opset-convert to keep "
"raw ORT output."
),
)
p.add_argument(
"--onnx-target-opset",
type=int,
default=13,
metavar="N",
help=(
"Target ONNX opset for --onnx-opset-convert (default: 13). Ignored when conversion is off."
),
)
args = p.parse_args()
if args.mode == "static" and args.calib_data_dir is None:
die("static mode requires --calib-data-dir")
if args.mode == "dynamic" and args.calib_data_dir is not None:
print("warning: --calib-data-dir is ignored for dynamic mode", file=sys.stderr)
if args.onnx_target_opset < 1:
die("--onnx-target-opset must be >= 1")
input_model_dir: Path = args.input_model_dir
output_model_dir: Path = args.output_model_dir
if not input_model_dir.is_dir():
die(f"input directory does not exist: {input_model_dir}")
src_onnx = input_model_dir / "inference.onnx"
src_yml = input_model_dir / "inference.yml"
if not src_onnx.is_file():
die(f"missing {src_onnx}")
if not src_yml.is_file():
die(f"missing {src_yml} (expected alongside inference.onnx)")
out_onnx = output_model_dir / "inference.onnx"
in_place = _same_file(input_model_dir, output_model_dir)
if not in_place:
output_model_dir.mkdir(parents=True, exist_ok=True)
pre_onnx: Path | None = None
if args.ort_preprocess:
pre_onnx = _run_ort_quant_pre_process(src_onnx, input_model_dir)
quant_src = pre_onnx if pre_onnx is not None else src_onnx
try:
if in_place:
fd, tmp_name = tempfile.mkstemp(
prefix="inference.onnx.",
suffix=".tmp",
dir=str(input_model_dir),
)
os.close(fd)
tmp_path = Path(tmp_name)
try:
if args.mode == "dynamic":
_quantize_dynamic(quant_src, tmp_path, per_channel=args.per_channel)
else:
assert args.calib_data_dir is not None
_quantize_static(
quant_src,
tmp_path,
args.calib_data_dir,
per_channel=args.per_channel,
calibrate_method_name=args.calibration_method,
)
_atomic_replace(tmp_path, out_onnx)
finally:
if tmp_path.is_file() and not _same_file(tmp_path, out_onnx):
try:
tmp_path.unlink()
except OSError:
pass
else:
try:
if args.mode == "dynamic":
_quantize_dynamic(quant_src, out_onnx, per_channel=args.per_channel)
else:
assert args.calib_data_dir is not None
_quantize_static(
quant_src,
out_onnx,
args.calib_data_dir,
per_channel=args.per_channel,
calibrate_method_name=args.calibration_method,
)
shutil.copy2(src_yml, output_model_dir / "inference.yml")
except Exception:
if out_onnx.is_file():
try:
out_onnx.unlink()
except OSError:
pass
raise
finally:
if pre_onnx is not None and pre_onnx.is_file():
try:
pre_onnx.unlink()
except OSError:
pass
if args.onnx_opset_convert:
st = _try_onnx_opset_via_version_converter(out_onnx, args.onnx_target_opset)
if st == "converted":
print(
f"note: applied onnx.version_converter to opset {args.onnx_target_opset}.",
file=sys.stderr,
)
if not args.no_verify:
_verify_onnx_file(out_onnx)
extra = f" and copied inference.yml" if not in_place else ""
print(f"Wrote {out_onnx}{extra}")
if __name__ == "__main__":
main()
+896
View File
@@ -0,0 +1,896 @@
#!/usr/bin/env bash
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# End-to-end benchmark runner for the iOS demo.
#
# Pipeline: preflight → resolve-image → resolve-destination →
# optional accuracy-precheck → benchmark xcodebuild-test → extract-artifacts → report
#
# Requires: bash 3.2+, xcodebuild, xcrun, python3.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IOS_DEMO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
# Fixtures/: images shipped for benchmark runs; `local-*` entries come from --image; auto-pick ignores `local-*`.
FIXTURES_DIR="${IOS_DEMO_ROOT}/PaddleOCRDemoTests/Fixtures"
DEFAULT_SIMULATOR="iPhone 16"
BUILD_CONFIGURATION="Release"
# Comma-separated xcodebuild -only-testing targets.
TESTING_SCOPE="${PADDLEOCR_BENCHMARK_ONLY_TESTING_SCOPE:-PaddleOCRDemoTests/OCRBenchmarkTests/testOnDeviceLatencyBenchmark,PaddleOCRDemoTests/OCRBenchmarkTests/testOnDeviceMemoryBenchmark}"
XCODE_TEST_SINGLE_RUN_FLAGS=(
-parallel-testing-enabled NO
-collect-test-diagnostics never
)
UDID=""
SIMULATOR=""
IMAGE=""
FIXTURE_ARG=""
WARMUP_CLI=""
MEASURED_CLI=""
ORT_EP_CLI=""
THREADS_CLI=""
XNNPACK_THREADS_CLI=""
REC_BATCH_SIZE_CLI=""
COREML_OPTIONS_CLI=""
ORT_PROFILING_CLI=0
ACCURACY_CHECK=0
ACCURACY_STOP_ON_FAILURE=0
ACCURACY_REFERENCE_JSON=""
OUT_DIR="${IOS_DEMO_ROOT}/out"
CLEAN=0
usage() {
cat <<EOF
Usage: ./scripts/run_benchmark.sh [OPTIONS]
Options:
--udid <id> Real-device UDID (preferred real-device path)
--simulator <name> Simulator name (default: ${DEFAULT_SIMULATOR})
--image <path> Ad-hoc benchmark image; copied as Fixtures/local-<basename>.
Without --image/--fixture, see image selection below.
--fixture <name> Use a file already under PaddleOCRDemoTests/Fixtures/ (stem or
file name, e.g. ios_ocr_benchmark_reference or .jpg). Useful when
several fixtures exist.
--warmup <n> Benchmark warmup iterations (non-negative int).
--measured-iterations <n> Timed benchmark iterations.
--ort-execution-provider <NAME> Preferred ONNX Runtime EP preset for tests:
CPU, XNNPACK, or CORE_ML.
--threads <n> Session-level intra-op thread count (positive int).
--xnnpack-threads <n> XNNPACK EP thread count (positive int).
--rec-batch-size <n> Recognition batch size override (positive int).
--coreml-options <flags> Comma-separated CoreML EP flags: enableOnSubgraphs,
createMLProgram, staticInputShapes, cpuOnly, cpuAndGPU, aneOnly.
--ort-profiling Enable ONNX Runtime session profiling.
--accuracy-check Run an accuracy precheck before benchmark tests.
--stop-on-accuracy-failure
With --accuracy-check, treat accuracy FAIL as blocking.
--accuracy-reference-json <path>
Existing OCR reference JSON for --accuracy-check. If omitted,
the script generates accuracy-reference.json under --output-dir.
--output-dir <dir> Output directory (default: out/)
--clean Delete Fixtures/local-* and prior non-log artifacts under <output-dir>
before running.
-h, --help Show help
Environment (optional; CLI wins when both are set):
PADDLEOCR_BENCHMARK_IMAGE_NAME Select which bundled fixture to use (same as --fixture)
PADDLEOCR_BENCHMARK_WARMUP_ITERATIONS
PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS
PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER CPU, XNNPACK, or CORE_ML
PADDLEOCR_BENCHMARK_INTRA_OP_THREADS Session-level thread count
PADDLEOCR_BENCHMARK_XNNPACK_THREADS XNNPACK EP thread count
PADDLEOCR_BENCHMARK_REC_BATCH_SIZE Recognition batch size
PADDLEOCR_BENCHMARK_COREML_OPTIONS Comma-separated CoreML EP flags
PADDLEOCR_BENCHMARK_ORT_PROFILING Set to 1/true/yes/on to emit ORT JSON profiles
PADDLEOCR_BENCHMARK_ONLY_TESTING_SCOPE Optional comma-separated xcodebuild -only-testing scopes.
Image selection when --image is not used:
1) --fixture <name>, if given, else PADDLEOCR_BENCHMARK_IMAGE_NAME, if set
2) otherwise exactly one non-local-* file in Fixtures/
EOF
}
die() {
printf "[run_benchmark] ERROR: %s\n" "$1" >&2
printf " Where: %s\n" "$2" >&2
printf " Next: %s\n" "$3" >&2
exit 1
}
while [[ $# -gt 0 ]]; do
case "$1" in
--udid) UDID="$2"; shift 2 ;;
--simulator) SIMULATOR="$2"; shift 2 ;;
--image) IMAGE="$2"; shift 2 ;;
--fixture) FIXTURE_ARG="$2"; shift 2 ;;
--warmup) WARMUP_CLI="$2"; shift 2 ;;
--measured-iterations) MEASURED_CLI="$2"; shift 2 ;;
--ort-execution-provider) ORT_EP_CLI="$2"; shift 2 ;;
--threads) THREADS_CLI="$2"; shift 2 ;;
--xnnpack-threads) XNNPACK_THREADS_CLI="$2"; shift 2 ;;
--rec-batch-size) REC_BATCH_SIZE_CLI="$2"; shift 2 ;;
--coreml-options) COREML_OPTIONS_CLI="$2"; shift 2 ;;
--ort-profiling) ORT_PROFILING_CLI=1; shift ;;
--accuracy-check) ACCURACY_CHECK=1; shift ;;
--stop-on-accuracy-failure) ACCURACY_STOP_ON_FAILURE=1; shift ;;
--accuracy-reference-json) ACCURACY_REFERENCE_JSON="$2"; shift 2 ;;
--output-dir) OUT_DIR="$2"; shift 2 ;;
--clean) CLEAN=1; shift ;;
-h|--help) usage; exit 0 ;;
*) die "Unknown option: $1" "argument parsing" "See --help." ;;
esac
done
if [[ "${ACCURACY_STOP_ON_FAILURE}" -eq 1 ]]; then
[[ "${ACCURACY_CHECK}" -eq 1 ]] \
|| die "--stop-on-accuracy-failure requires --accuracy-check" "argument parsing" "Add --accuracy-check, or remove --stop-on-accuracy-failure."
fi
if [[ -n "${ACCURACY_REFERENCE_JSON}" ]]; then
[[ "${ACCURACY_CHECK}" -eq 1 ]] \
|| die "--accuracy-reference-json requires --accuracy-check" "argument parsing" "Add --accuracy-check, or remove --accuracy-reference-json."
[[ -f "${ACCURACY_REFERENCE_JSON}" ]] \
|| die "Accuracy reference JSON not found: ${ACCURACY_REFERENCE_JSON}" "argument parsing" "Pass an existing OCR JSON reference file."
fi
# Fixture label: --fixture overrides PADDLEOCR_BENCHMARK_IMAGE_NAME.
EXPLICIT_FIXTURE="${FIXTURE_ARG:-${PADDLEOCR_BENCHMARK_IMAGE_NAME:-}}"
# Warmup / measured: CLI over env; forward to xcodebuild only when non-empty.
WARMUP_MERGED="${WARMUP_CLI:-${PADDLEOCR_BENCHMARK_WARMUP_ITERATIONS:-}}"
MEASURED_MERGED="${MEASURED_CLI:-${PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS:-}}"
if [[ -n "${WARMUP_MERGED}" ]]; then
[[ "${WARMUP_MERGED}" =~ ^[0-9]+$ ]] \
|| die "Invalid --warmup / PADDLEOCR_BENCHMARK_WARMUP_ITERATIONS: ${WARMUP_MERGED}" "argument parsing" "Use a non-negative integer."
fi
if [[ -n "${MEASURED_MERGED}" ]]; then
[[ "${MEASURED_MERGED}" =~ ^[0-9]+$ ]] \
|| die "Invalid --measured-iterations / PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS: ${MEASURED_MERGED}" "argument parsing" "Use a non-negative integer."
fi
# ORT execution provider preset: CPU, XNNPACK, or CORE_ML; forward when set (flag or env).
ORT_EP_MERGED="${ORT_EP_CLI:-${PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER:-}}"
ORT_EP_CANON=""
if [[ -n "${ORT_EP_MERGED}" ]]; then
_ort_ep_lc="$(printf '%s' "${ORT_EP_MERGED}" | tr '[:upper:]' '[:lower:]')"
case "${_ort_ep_lc}" in
core_ml) ORT_EP_CANON="CORE_ML" ;;
xnnpack) ORT_EP_CANON="XNNPACK" ;;
cpu) ORT_EP_CANON="CPU" ;;
*)
die "Invalid --ort-execution-provider / PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER: ${ORT_EP_MERGED}" "argument parsing" "Use CPU, XNNPACK, or CORE_ML."
;;
esac
fi
# Tuning parameters.
THREADS_MERGED="${THREADS_CLI:-${PADDLEOCR_BENCHMARK_INTRA_OP_THREADS:-}}"
XNNPACK_THREADS_MERGED="${XNNPACK_THREADS_CLI:-${PADDLEOCR_BENCHMARK_XNNPACK_THREADS:-}}"
REC_BATCH_SIZE_MERGED="${REC_BATCH_SIZE_CLI:-${PADDLEOCR_BENCHMARK_REC_BATCH_SIZE:-}}"
COREML_OPTIONS_MERGED="${COREML_OPTIONS_CLI:-${PADDLEOCR_BENCHMARK_COREML_OPTIONS:-}}"
if [[ -n "${THREADS_MERGED}" ]]; then
[[ "${THREADS_MERGED}" =~ ^[0-9]+$ && "${THREADS_MERGED}" -gt 0 ]] \
|| die "Invalid --threads: ${THREADS_MERGED}" "argument parsing" "Use a positive integer."
fi
if [[ -n "${XNNPACK_THREADS_MERGED}" ]]; then
[[ "${XNNPACK_THREADS_MERGED}" =~ ^[0-9]+$ && "${XNNPACK_THREADS_MERGED}" -gt 0 ]] \
|| die "Invalid --xnnpack-threads: ${XNNPACK_THREADS_MERGED}" "argument parsing" "Use a positive integer."
fi
if [[ -n "${REC_BATCH_SIZE_MERGED}" ]]; then
[[ "${REC_BATCH_SIZE_MERGED}" =~ ^[0-9]+$ && "${REC_BATCH_SIZE_MERGED}" -gt 0 ]] \
|| die "Invalid --rec-batch-size: ${REC_BATCH_SIZE_MERGED}" "argument parsing" "Use a positive integer."
fi
if [[ "${ORT_PROFILING_CLI}" -eq 1 ]]; then
ORT_PROFILING_MERGED="1"
else
ORT_PROFILING_MERGED="${PADDLEOCR_BENCHMARK_ORT_PROFILING:-}"
fi
LOGS_DIR="${OUT_DIR}/logs"
STATUS_PATH="${OUT_DIR}/run-status.json"
REPORT_PATH="${OUT_DIR}/benchmark-report.md"
XCTEST_METRICS_PATH="${OUT_DIR}/xctest-memory-metrics.json"
ACCURACY_RESULT_PATH="${OUT_DIR}/accuracy-result.xcresult"
LATENCY_RESULT_PATH="${OUT_DIR}/latency-result.xcresult"
MEMORY_RESULT_PATH="${OUT_DIR}/memory-result.xcresult"
ACCURACY_REFERENCE_OUT="${OUT_DIR}/accuracy-reference.json"
ACCURACY_IOS_EXPORT_PATH="${OUT_DIR}/ios-ocr-export.json"
ACCURACY_SUMMARY_PATH="${OUT_DIR}/accuracy-summary.json"
mkdir -p "${OUT_DIR}" "${LOGS_DIR}"
if [[ "${CLEAN}" -eq 1 ]]; then
rm -f "${FIXTURES_DIR}"/local-*
find "${OUT_DIR}" -mindepth 1 -not -path "${LOGS_DIR}" -not -path "${LOGS_DIR}/*" -exec rm -rf {} + 2>/dev/null || true
mkdir -p "${LOGS_DIR}"
fi
# ---------- Step state (parallel indexed arrays) ----------
STEP_NAMES=(preflight resolve-image resolve-destination accuracy-precheck xcodebuild-test extract-artifacts report)
STEP_STATUS=()
STEP_DURATION_MS=()
STEP_EXIT=()
STEP_REASON=()
STEP_LOG=()
for i in "${!STEP_NAMES[@]}"; do
STEP_STATUS[$i]=pending
STEP_DURATION_MS[$i]=""
STEP_EXIT[$i]=""
STEP_REASON[$i]=""
STEP_LOG[$i]=""
done
step_index() {
local want=$1 i
for i in "${!STEP_NAMES[@]}"; do
[[ "${STEP_NAMES[$i]}" == "$want" ]] && { echo "$i"; return 0; }
done
return 1
}
step_status_set() { local i; i=$(step_index "$1") || return 1; STEP_STATUS[$i]="$2"; }
step_status_get() { local i; i=$(step_index "$1") || return 1; echo "${STEP_STATUS[$i]}"; }
step_duration_set() { local i; i=$(step_index "$1") || return 1; STEP_DURATION_MS[$i]="$2"; }
step_exit_set() { local i; i=$(step_index "$1") || return 1; STEP_EXIT[$i]="$2"; }
step_reason_set() { local i; i=$(step_index "$1") || return 1; STEP_REASON[$i]="$2"; }
step_log_set() { local i; i=$(step_index "$1") || return 1; STEP_LOG[$i]="$2"; }
HALTED=0
HALT_REASON=""
CURRENT_STEP_NAME=""
CURRENT_STEP_START_MS=""
ACTIVE_CHILD_PID=""
ACTIVE_CHILD_LABEL=""
IMAGE_NAME=""
IMAGE_SRC=""
IMAGE_SOURCE=""
DEST=""
IS_SIMULATOR=1
RUN_STARTED="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
ACCURACY_STATUS="SKIPPED"
ACCURACY_REFERENCE_USED=""
ACCURACY_SUMMARY_USED=""
ACCURACY_REASON=""
MODEL_PRESET="unknown"
DET_MODEL_PATH=""
DET_MODEL_FORMAT=""
DET_MODEL_SIZE_BYTES=""
REC_MODEL_PATH=""
REC_MODEL_FORMAT=""
REC_MODEL_SIZE_BYTES=""
TOTAL_MODEL_SIZE_BYTES=""
APP_BINARY_SIZE_BYTES=""
now_ms() {
python3 -c 'import time; print(int(time.time()*1000))'
}
file_size_bytes() {
[[ -f "$1" ]] || { echo ""; return 0; }
stat -f%z "$1" 2>/dev/null || echo ""
}
first_model_file() {
local dir="$1" f matches
for f in "${dir}/inference.ort" "${dir}/inference.with_runtime_opt.ort"; do
[[ -f "$f" ]] && { echo "$f"; return 0; }
done
matches=("${dir}"/inference*.ort)
if [[ -f "${matches[0]:-}" ]]; then
printf "%s\n" "${matches[@]}" | sort | head -n 1
return 0
fi
[[ -f "${dir}/inference.onnx" ]] && { echo "${dir}/inference.onnx"; return 0; }
echo ""
}
yml_model_name() {
local path="$1"
python3 - "$path" <<'PY'
import re
import sys
from pathlib import Path
path = Path(sys.argv[1])
if not path.is_file():
print("")
raise SystemExit(0)
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
m = re.match(r"\s*model_name:\s*['\"]?([^'\"]+?)['\"]?\s*$", line)
if m:
print(m.group(1).strip())
break
else:
print("")
PY
}
infer_model_preset() {
local det_name="$1" rec_name="$2" joined
joined="$(printf "%s %s" "$det_name" "$rec_name" | tr '[:upper:]' '[:lower:]')"
case "$joined" in
*small*) echo "PP-OCRv6_small" ;;
*tiny*) echo "PP-OCRv6_tiny" ;;
*mobile*) echo "PP-OCRv5_mobile" ;;
*) echo "unknown" ;;
esac
}
collect_model_metadata() {
local det_name rec_name
DET_MODEL_PATH="$(first_model_file "${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/det")"
REC_MODEL_PATH="$(first_model_file "${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/rec")"
DET_MODEL_FORMAT="${DET_MODEL_PATH##*.}"
REC_MODEL_FORMAT="${REC_MODEL_PATH##*.}"
DET_MODEL_SIZE_BYTES="$(file_size_bytes "$DET_MODEL_PATH")"
REC_MODEL_SIZE_BYTES="$(file_size_bytes "$REC_MODEL_PATH")"
if [[ -n "$DET_MODEL_SIZE_BYTES" && -n "$REC_MODEL_SIZE_BYTES" ]]; then
TOTAL_MODEL_SIZE_BYTES=$((DET_MODEL_SIZE_BYTES + REC_MODEL_SIZE_BYTES))
fi
det_name="$(yml_model_name "${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/det/inference.yml")"
rec_name="$(yml_model_name "${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/rec/inference.yml")"
MODEL_PRESET="$(infer_model_preset "$det_name" "$rec_name")"
}
collect_app_binary_size() {
local settings target_build_dir executable_path app_binary
settings="$(xcodebuild -showBuildSettings -workspace "${IOS_DEMO_ROOT}/PaddleOCRDemo.xcworkspace" -scheme PaddleOCRDemo -configuration "${BUILD_CONFIGURATION}" -destination "${DEST}" 2>/dev/null || true)"
target_build_dir="$(printf "%s\n" "$settings" | awk -F'= ' '/ TARGET_BUILD_DIR = / {print $2; exit}')"
executable_path="$(printf "%s\n" "$settings" | awk -F'= ' '/ EXECUTABLE_PATH = / {print $2; exit}')"
if [[ -n "$target_build_dir" && -n "$executable_path" ]]; then
app_binary="${target_build_dir}/${executable_path}"
APP_BINARY_SIZE_BYTES="$(file_size_bytes "$app_binary")"
fi
}
record_step_ok() {
local name="$1" duration="$2"
step_status_set "$name" ok
step_duration_set "$name" "$duration"
step_exit_set "$name" 0
printf " -> OK (%sms)\n" "$duration"
}
record_step_fail() {
local name="$1" duration="$2" rc="$3" reason="$4"
step_status_set "$name" fail
step_duration_set "$name" "$duration"
step_exit_set "$name" "$rc"
step_reason_set "$name" "$reason"
step_log_set "$name" "logs/${name}.log"
HALTED=1
HALT_REASON="$reason"
printf " -> ERROR (%sms, exit %s): %s\n" "$duration" "$rc" "$reason" >&2
}
terminate_process_tree() {
local pid="$1" sig="$2" child
while IFS= read -r child; do
[[ -n "$child" ]] && terminate_process_tree "$child" "$sig"
done < <(pgrep -P "$pid" 2>/dev/null || true)
kill "-${sig}" "$pid" 2>/dev/null || true
}
handle_signal() {
local sig="$1" rc=130 reason end duration
[[ "$sig" == "TERM" ]] && rc=143
trap - INT TERM
reason="interrupted by SIG${sig}"
printf "\n[run_benchmark] %s\n" "$reason" >&2
if [[ -n "${ACTIVE_CHILD_PID}" ]] && kill -0 "${ACTIVE_CHILD_PID}" 2>/dev/null; then
printf "[run_benchmark] stopping %s (pid %s)\n" "${ACTIVE_CHILD_LABEL:-active child}" "${ACTIVE_CHILD_PID}" >&2
terminate_process_tree "${ACTIVE_CHILD_PID}" "$sig"
sleep 1
if kill -0 "${ACTIVE_CHILD_PID}" 2>/dev/null; then
terminate_process_tree "${ACTIVE_CHILD_PID}" TERM
fi
fi
if [[ -n "${CURRENT_STEP_NAME}" ]]; then
end="$(now_ms)"; duration=$((end - CURRENT_STEP_START_MS))
record_step_fail "${CURRENT_STEP_NAME}" "$duration" "$rc" "$reason"
mark_remaining_skipped "$reason"
else
HALTED=1
HALT_REASON="$reason"
fi
exit "$rc"
}
mark_remaining_skipped() {
local reason="$1" skipped=0 i st
for i in "${!STEP_NAMES[@]}"; do
st="${STEP_STATUS[$i]}"
if [[ "$st" == "pending" || "$st" == "running" ]]; then
if [[ "${STEP_NAMES[$i]}" != "report" ]]; then
STEP_STATUS[$i]="skipped"
STEP_REASON[$i]="$reason"
skipped=1
fi
fi
done
[[ $skipped -eq 1 ]] && echo " (remaining steps marked skipped)" >&2 || true
}
write_status_json() {
local overall="$1" exit_code="$2"
local finished
finished="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
python3 - "$STATUS_PATH" "$overall" "$exit_code" "$RUN_STARTED" "$finished" \
"$IMAGE_NAME" "$IMAGE_SOURCE" "$DEST" "$BUILD_CONFIGURATION" "$TESTING_SCOPE" \
"$IS_SIMULATOR" "${ORT_EP_CANON:-CPU}" "${WARMUP_MERGED:-}" "${MEASURED_MERGED:-}" \
"$MODEL_PRESET" "$DET_MODEL_FORMAT" "$DET_MODEL_SIZE_BYTES" "$REC_MODEL_FORMAT" "$REC_MODEL_SIZE_BYTES" "$TOTAL_MODEL_SIZE_BYTES" "$APP_BINARY_SIZE_BYTES" \
"${ORT_PROFILING_MERGED:-}" "$ACCURACY_CHECK" "$ACCURACY_STATUS" \
"$ACCURACY_STOP_ON_FAILURE" "$ACCURACY_REFERENCE_USED" "$ACCURACY_IOS_EXPORT_PATH" "$ACCURACY_SUMMARY_USED" "$ACCURACY_REASON" \
"${#STEP_NAMES[@]}" \
"${STEP_NAMES[@]}" \
"${STEP_STATUS[@]}" \
"${STEP_DURATION_MS[@]}" \
"${STEP_EXIT[@]}" \
"${STEP_REASON[@]}" \
"${STEP_LOG[@]}" <<'PY'
import json
import sys
args = sys.argv[1:]
(
path,
overall,
exit_code,
started,
finished,
image_name,
image_source,
destination,
build_configuration,
testing_scope,
is_simulator,
ort_ep_preset,
warmup_iterations,
measured_iterations,
model_preset,
det_model_format,
det_model_size_bytes,
rec_model_format,
rec_model_size_bytes,
total_model_size_bytes,
app_binary_size_bytes,
ort_profiling,
accuracy_enabled,
accuracy_status,
accuracy_stop_on_failure,
accuracy_reference,
accuracy_ios_export,
accuracy_summary,
accuracy_reason,
) = args[:29]
n = int(args[29])
base = 30
names = args[base + 0 * n : base + 1 * n]
status = args[base + 1 * n : base + 2 * n]
dur = args[base + 2 * n : base + 3 * n]
exitc = args[base + 3 * n : base + 4 * n]
reason = args[base + 4 * n : base + 5 * n]
logp = args[base + 5 * n : base + 6 * n]
steps = []
for i in range(n):
row = {"name": names[i], "status": status[i] or "pending"}
if dur[i]:
row["durationMs"] = int(dur[i])
if exitc[i]:
row["exitCode"] = int(exitc[i])
if reason[i]:
row["reason"] = reason[i]
if logp[i]:
row["logPath"] = logp[i]
steps.append(row)
doc = {
"schemaVersion": 1,
"overall": overall,
"exitCode": int(exit_code),
"image": {"name": image_name, "source": image_source},
"destination": destination,
"benchmark": {
"buildConfiguration": build_configuration,
"testingScope": testing_scope,
"isSimulator": is_simulator == "1",
"ortExecutionProvider": ort_ep_preset,
"warmupIterations": int(warmup_iterations) if warmup_iterations else None,
"measuredIterations": int(measured_iterations) if measured_iterations else None,
"modelPreset": model_preset or "unknown",
"modelFiles": {
"detection": {
"format": det_model_format or None,
"sizeBytes": int(det_model_size_bytes) if det_model_size_bytes else None,
},
"recognition": {
"format": rec_model_format or None,
"sizeBytes": int(rec_model_size_bytes) if rec_model_size_bytes else None,
},
"totalSizeBytes": int(total_model_size_bytes) if total_model_size_bytes else None,
},
"appBinarySizeBytes": int(app_binary_size_bytes) if app_binary_size_bytes else None,
"ortProfilingEnabled": ort_profiling.lower() in ("1", "true", "yes", "on"),
},
"accuracy": {
"enabled": accuracy_enabled == "1",
"status": accuracy_status,
"stopOnFailure": accuracy_stop_on_failure == "1",
"referenceJson": accuracy_reference or None,
"iosExportJson": accuracy_ios_export if accuracy_enabled == "1" else None,
"summaryJson": accuracy_summary or None,
"reason": accuracy_reason or None,
},
"runStartedAt": started,
"runFinishedAt": finished,
"steps": steps,
}
with open(path, "w", encoding="utf-8") as f:
json.dump(doc, f, indent=2)
PY
}
finish() {
local exit_code=$?
local overall
if [[ "${HALTED}" -eq 1 ]]; then
overall="ERROR"
else
overall="COMPLETED"
exit_code=0
fi
printf "\n===== SUMMARY =====\n"
printf "Overall: %s\n" "${overall}"
printf "Exit code: %s\n" "${exit_code}"
if [[ "${overall}" == "COMPLETED" ]]; then
printf "Status: %s\n" "${STATUS_PATH}"
printf "Report: %s\n" "${REPORT_PATH}"
else
printf "ERROR: See full logs in %s\n" "${LOGS_DIR}"
fi
exit "${exit_code}"
}
trap finish EXIT
trap 'handle_signal INT' INT
trap 'handle_signal TERM' TERM
run_xcodebuild() {
local rc
ACTIVE_CHILD_LABEL="$*"
"$@" &
ACTIVE_CHILD_PID=$!
set +e
wait "${ACTIVE_CHILD_PID}"
rc=$?
set -e
ACTIVE_CHILD_PID=""
ACTIVE_CHILD_LABEL=""
return "$rc"
}
run_step() {
local name="$1"; shift
local log="${LOGS_DIR}/${name}.log"
local start end duration rc tail
printf "\n===== [%s] step %s: %s =====\n" "$(date +%H:%M:%S)" "$name" "$*"
step_status_set "$name" running
start="$(now_ms)"
CURRENT_STEP_NAME="$name"
CURRENT_STEP_START_MS="$start"
if "$@" >"$log" 2>&1 </dev/null; then
CURRENT_STEP_NAME=""
CURRENT_STEP_START_MS=""
end="$(now_ms)"; duration=$((end - start))
record_step_ok "$name" "$duration"
return 0
else
rc=$?
CURRENT_STEP_NAME=""
CURRENT_STEP_START_MS=""
end="$(now_ms)"; duration=$((end - start))
tail="$(tail -n 5 "$log" | head -n 1 || true)"
record_step_fail "$name" "$duration" "$rc" "${tail:-step failed}"
return "$rc"
fi
}
generate_report_impl() {
python3 "${SCRIPT_DIR}/generate_benchmark_report.py" \
--accuracy-summary "${ACCURACY_SUMMARY_PATH}" \
--on-device-performance-json "${OUT_DIR}/on-device-performance.json" \
--run-status "${STATUS_PATH}" \
--xctest-metrics-json "${XCTEST_METRICS_PATH}" \
--output "${REPORT_PATH}"
}
# ---------- Step: preflight ----------
preflight_impl() {
[[ -f "${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/det/inference.yml" ]] \
|| { echo "Models/det/inference.yml missing; run ./scripts/fetch_ios_demo_models.sh" >&2; return 1; }
[[ -f "${IOS_DEMO_ROOT}/PaddleOCRDemo/Models/rec/inference.yml" ]] \
|| { echo "Models/rec/inference.yml missing; run ./scripts/fetch_ios_demo_models.sh" >&2; return 1; }
command -v xcodebuild >/dev/null || { echo "xcodebuild not in PATH" >&2; return 1; }
command -v xcrun >/dev/null || { echo "xcrun not in PATH" >&2; return 1; }
command -v python3 >/dev/null || { echo "python3 not in PATH" >&2; return 1; }
[[ -d "${FIXTURES_DIR}" ]] || { echo "Fixtures/ directory missing" >&2; return 1; }
collect_model_metadata
}
run_step preflight preflight_impl || { mark_remaining_skipped "preflight failed: ${HALT_REASON}"; exit 1; }
# ---------- Step: resolve-image ----------
resolve_image_impl() {
if [[ -n "$IMAGE" ]]; then
[[ -f "$IMAGE" ]] || { echo "--image file not found: $IMAGE" >&2; return 1; }
local base sanitized
base="$(basename "$IMAGE")"
sanitized="$(echo "$base" | tr -c 'A-Za-z0-9._-' '_')"
IMAGE_NAME="local-${sanitized}"
IMAGE_SRC="$IMAGE"
IMAGE_SOURCE="override"
cp -f "$IMAGE" "${FIXTURES_DIR}/${IMAGE_NAME}"
echo "Copied override image to ${FIXTURES_DIR}/${IMAGE_NAME}"
return 0
fi
if [[ -n "${EXPLICIT_FIXTURE}" ]]; then
local name cand
name="${EXPLICIT_FIXTURE}"
cand=""
if [[ -f "${FIXTURES_DIR}/${name}" ]]; then
cand="${FIXTURES_DIR}/${name}"
else
# stem without extension: try common image extensions
if [[ "$name" != *.* ]]; then
for ext in jpg jpeg png heic webp; do
if [[ -f "${FIXTURES_DIR}/${name}.${ext}" ]]; then
cand="${FIXTURES_DIR}/${name}.${ext}"
break
fi
done
fi
fi
[[ -n "$cand" ]] || { echo "Fixture not found for --fixture / PADDLEOCR_BENCHMARK_IMAGE_NAME: ${name}" >&2; return 1; }
IMAGE_NAME="$(basename "$cand")"
IMAGE_SRC="$cand"
IMAGE_SOURCE="fixture"
echo "Using fixture (explicit): ${IMAGE_NAME}"
return 0
fi
local found=()
while IFS= read -r -d '' f; do
local b; b="$(basename "$f")"
case "$b" in
local-*|.gitignore|.*) continue ;;
*) found+=("$b") ;;
esac
done < <(find "${FIXTURES_DIR}" -mindepth 1 -maxdepth 1 -type f -print0)
if [[ ${#found[@]} -eq 0 ]]; then
echo "No fixture in ${FIXTURES_DIR}/ and no --image provided." >&2
echo "Put exactly one fixture image in PaddleOCRDemoTests/Fixtures/, or pass --image <path>." >&2
return 1
fi
if [[ ${#found[@]} -gt 1 ]]; then
echo "Multiple fixtures in ${FIXTURES_DIR}/: ${found[*]}" >&2
echo "Pass --image <path> to select one explicitly." >&2
return 1
fi
IMAGE_NAME="${found[0]}"
IMAGE_SRC="${FIXTURES_DIR}/${IMAGE_NAME}"
IMAGE_SOURCE="fixture"
echo "Using fixture: ${IMAGE_NAME}"
}
run_step resolve-image resolve_image_impl || { mark_remaining_skipped "resolve-image failed: ${HALT_REASON}"; exit 1; }
# ---------- Step: resolve-destination ----------
resolve_destination_impl() {
if [[ -n "${UDID}" ]]; then
DEST="platform=iOS,id=${UDID}"
IS_SIMULATOR=0
elif [[ -n "${SIMULATOR}" ]]; then
DEST="platform=iOS Simulator,name=${SIMULATOR}"
IS_SIMULATOR=1
else
DEST="platform=iOS Simulator,name=${DEFAULT_SIMULATOR}"
IS_SIMULATOR=1
fi
echo "Destination: ${DEST}"
}
run_step resolve-destination resolve_destination_impl || { mark_remaining_skipped "resolve-destination failed: ${HALT_REASON}"; exit 1; }
# ---------- Step: accuracy-precheck (skipped unless --accuracy-check is set) ----------
accuracy_precheck_impl() {
ACCURACY_STATUS="ERROR"
ACCURACY_REASON=""
ACCURACY_SUMMARY_USED="${ACCURACY_SUMMARY_PATH}"
rm -rf "${ACCURACY_RESULT_PATH}"
rm -f "${ACCURACY_IOS_EXPORT_PATH}" "${ACCURACY_SUMMARY_PATH}"
if [[ -n "${ACCURACY_REFERENCE_JSON}" ]]; then
ACCURACY_REFERENCE_USED="${ACCURACY_REFERENCE_JSON}"
else
ACCURACY_REFERENCE_USED="${ACCURACY_REFERENCE_OUT}"
if ! python3 "${SCRIPT_DIR}/ocr_reference_run.py" \
--image "${IMAGE_SRC}" \
--output "${ACCURACY_REFERENCE_OUT}" \
--device cpu \
--align-ios-defaults; then
ACCURACY_STATUS="ERROR"
ACCURACY_REASON="reference generation failed"
echo "Accuracy precheck: ${ACCURACY_STATUS} (${ACCURACY_REASON})" >&2
return 1
fi
fi
local runenv=(
env "TEST_RUNNER_PADDLEOCR_BENCHMARK_IMAGE_NAME=${IMAGE_NAME}"
"TEST_RUNNER_PADDLEOCR_BENCHMARK_BUILD_CONFIGURATION=${BUILD_CONFIGURATION}"
)
if [[ -n "${ORT_EP_CANON}" ]]; then
runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER=${ORT_EP_CANON}")
fi
if ! run_xcodebuild "${runenv[@]}" xcodebuild test \
-workspace "${IOS_DEMO_ROOT}/PaddleOCRDemo.xcworkspace" \
-scheme PaddleOCRDemo \
-configuration "${BUILD_CONFIGURATION}" \
-destination "${DEST}" \
-resultBundlePath "${ACCURACY_RESULT_PATH}" \
"${XCODE_TEST_SINGLE_RUN_FLAGS[@]}" \
-only-testing:PaddleOCRDemoTests/OCRBenchmarkTests/testOCRExportJSONSchema; then
ACCURACY_STATUS="ERROR"
ACCURACY_REASON="accuracy XCTest export failed"
echo "Accuracy precheck: ${ACCURACY_STATUS} (${ACCURACY_REASON})" >&2
return 1
fi
if ! python3 "${SCRIPT_DIR}/extract_xcresult_attachments.py" \
--result "${ACCURACY_RESULT_PATH}" \
--output-dir "${OUT_DIR}" \
--name ios-ocr-export.json; then
ACCURACY_STATUS="ERROR"
ACCURACY_REASON="accuracy attachment extraction failed"
echo "Accuracy precheck: ${ACCURACY_STATUS} (${ACCURACY_REASON})" >&2
return 1
fi
set +e
python3 "${SCRIPT_DIR}/compare_ocr_json.py" \
"${ACCURACY_REFERENCE_USED}" \
"${ACCURACY_IOS_EXPORT_PATH}" \
--json-summary-out "${ACCURACY_SUMMARY_PATH}"
local compare_rc=$?
set -e
if [[ "${compare_rc}" -eq 0 ]]; then
ACCURACY_STATUS="PASS"
elif [[ -f "${ACCURACY_SUMMARY_PATH}" ]]; then
ACCURACY_STATUS="FAIL"
ACCURACY_REASON="accuracy thresholds were not met"
else
ACCURACY_STATUS="ERROR"
ACCURACY_REASON="accuracy comparison failed"
fi
echo "Accuracy precheck: ${ACCURACY_STATUS}${ACCURACY_REASON:+ (${ACCURACY_REASON})}"
[[ "${ACCURACY_STATUS}" != "ERROR" ]]
}
if [[ "${ACCURACY_CHECK}" -eq 1 ]]; then
if ! run_step accuracy-precheck accuracy_precheck_impl; then
HALT_REASON="accuracy precheck error: ${ACCURACY_REASON:-${HALT_REASON}}"
step_reason_set accuracy-precheck "${HALT_REASON}"
mark_remaining_skipped "${HALT_REASON}"
write_status_json "ERROR" 1
generate_report_impl || true
exit 1
fi
if [[ "${ACCURACY_STATUS}" == "FAIL" ]]; then
printf "Accuracy precheck: %s (%s)\n" "${ACCURACY_STATUS}" "${ACCURACY_REASON:-accuracy thresholds were not met}"
fi
if [[ "${ACCURACY_STOP_ON_FAILURE}" -eq 1 && "${ACCURACY_STATUS}" == "FAIL" ]]; then
HALTED=1
HALT_REASON="accuracy precheck did not pass: ${ACCURACY_STATUS}"
step_status_set accuracy-precheck fail
step_exit_set accuracy-precheck 1
step_reason_set accuracy-precheck "${HALT_REASON}"
mark_remaining_skipped "${HALT_REASON}"
write_status_json "ERROR" 1
generate_report_impl || true
exit 1
fi
else
step_status_set accuracy-precheck skipped
step_reason_set accuracy-precheck "accuracy precheck not requested"
ACCURACY_STATUS="SKIPPED"
fi
# ---------- Step: xcodebuild-test ----------
xcodebuild_test_impl() {
rm -rf "${LATENCY_RESULT_PATH}"
rm -rf "${MEMORY_RESULT_PATH}"
rm -f "${XCTEST_METRICS_PATH}"
echo "xcodebuild: configuration=${BUILD_CONFIGURATION} benchmark image name=${IMAGE_NAME} warmup=${WARMUP_MERGED:-} measured=${MEASURED_MERGED:-} ort_ep=${ORT_EP_CANON:-default} ort_profiling=${ORT_PROFILING_MERGED:+on} scope=${TESTING_SCOPE}"
local runenv=(
env "TEST_RUNNER_PADDLEOCR_BENCHMARK_IMAGE_NAME=${IMAGE_NAME}"
"TEST_RUNNER_PADDLEOCR_BENCHMARK_BUILD_CONFIGURATION=${BUILD_CONFIGURATION}"
)
[[ -n "${WARMUP_MERGED}" ]] && runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_WARMUP_ITERATIONS=${WARMUP_MERGED}")
[[ -n "${MEASURED_MERGED}" ]] && runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS=${MEASURED_MERGED}")
if [[ -n "${ORT_EP_CANON}" ]]; then
runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER=${ORT_EP_CANON}")
fi
[[ -n "${ORT_PROFILING_MERGED:-}" ]] && runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_ORT_PROFILING=${ORT_PROFILING_MERGED}")
[[ -n "${THREADS_MERGED}" ]] && runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_INTRA_OP_THREADS=${THREADS_MERGED}")
[[ -n "${XNNPACK_THREADS_MERGED}" ]] && runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_XNNPACK_THREADS=${XNNPACK_THREADS_MERGED}")
[[ -n "${REC_BATCH_SIZE_MERGED}" ]] && runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_REC_BATCH_SIZE=${REC_BATCH_SIZE_MERGED}")
[[ -n "${COREML_OPTIONS_MERGED}" ]] && runenv+=("TEST_RUNNER_PADDLEOCR_BENCHMARK_COREML_OPTIONS=${COREML_OPTIONS_MERGED}")
local scopes=() scope result_path
IFS=',' read -r -a scopes <<< "${TESTING_SCOPE}"
for scope in "${scopes[@]}"; do
scope="$(printf '%s' "$scope" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
[[ -n "$scope" ]] || continue
result_path="${LATENCY_RESULT_PATH}"
if [[ "${scope}" == *"/testOnDeviceMemoryBenchmark" ]]; then
result_path="${MEMORY_RESULT_PATH}"
fi
rm -rf "${result_path}"
echo "xcodebuild: running scope=${scope} result=${result_path}"
if ! run_xcodebuild "${runenv[@]}" xcodebuild test \
-workspace "${IOS_DEMO_ROOT}/PaddleOCRDemo.xcworkspace" \
-scheme PaddleOCRDemo \
-configuration "${BUILD_CONFIGURATION}" \
-destination "${DEST}" \
-resultBundlePath "${result_path}" \
"${XCODE_TEST_SINGLE_RUN_FLAGS[@]}" \
-only-testing:"${scope}"; then
return 1
fi
done
collect_app_binary_size
}
run_step xcodebuild-test xcodebuild_test_impl || { mark_remaining_skipped "xcodebuild-test failed: ${HALT_REASON}"; exit 1; }
# ---------- Step: extract-artifacts ----------
extract_artifacts_impl() {
local metrics_result="${MEMORY_RESULT_PATH}"
[[ -d "${metrics_result}" ]] || metrics_result="${LATENCY_RESULT_PATH}"
python3 "${SCRIPT_DIR}/extract_xcresult_attachments.py" \
--result "${LATENCY_RESULT_PATH}" \
--output-dir "${OUT_DIR}" \
--name on-device-performance.json \
--optional-name ios-ocr-export.json \
--optional-name ort_profile_detection \
--optional-name ort_profile_recognition
python3 "${SCRIPT_DIR}/extract_xctest_metrics.py" \
--result "${metrics_result}" \
--output "${XCTEST_METRICS_PATH}"
}
run_step extract-artifacts extract_artifacts_impl || { mark_remaining_skipped "extract-artifacts failed: ${HALT_REASON}"; exit 1; }
# ---------- Step: report ----------
# First pass captures report step timing; write_status_json persists final step state;
# second pass refreshes the Markdown so **Overall** and the step table match this run.
report_impl() {
generate_report_impl
}
report_refresh() {
generate_report_impl
}
run_step report report_impl || { write_status_json "ERROR" 1; exit 1; }
write_status_json "COMPLETED" 0
report_refresh || true
exit 0
+89
View File
@@ -0,0 +1,89 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Shared helpers (calibration I/O) for ``quantize_onnx_model`` / ``debug_onnx_qdq`` / ``build_onnx_calib_npy``.
Entry scripts prepend this file's directory to ``sys.path`` before ``from utils import ...`` so
``import utils`` does not depend on the process working directory. The top-level name ``utils`` is
generic; the scripts resolve ``utils.py`` in this same ``scripts/`` directory first.
"""
from __future__ import annotations
import sys
from pathlib import Path
from typing import Any
__all__ = [
"die",
"user_input_names",
"build_npy_dir_reader",
]
def die(msg: str) -> None:
print(f"error: {msg}", file=sys.stderr)
raise SystemExit(1)
def user_input_names(model_path: Path) -> list[str]:
"""Return non-initializer graph input names (user-visible inputs)."""
import onnx
m = onnx.load(str(model_path), load_external_data=True)
init = {t.name for t in m.graph.initializer}
return [i.name for i in m.graph.input if i.name not in init]
def build_npy_dir_reader(
model_path: Path, data_dir: Path, *, max_samples: int | None = None
) -> Any:
"""ONNX Runtime ``CalibrationDataReader``: one float32 ``(NCHW)`` ``.npy`` per sample; sorted by filename.
*model_path* is used to discover the single graph input name (``user_input_names``); it may be
the original or an augmented model as long as the first user input is unchanged.
"""
from onnxruntime.quantization import CalibrationDataReader
class NpyDirectoryDataReader(CalibrationDataReader):
def __init__(self) -> None:
names = user_input_names(model_path)
if len(names) != 1:
die(
"expected exactly one non-initializer graph input; "
f"found {len(names)}: {names}"
)
self._input_name = names[0]
files = sorted(data_dir.glob("*.npy"))
if not files:
die(f"no .npy files under {data_dir}")
if max_samples is not None:
files = files[: max(0, max_samples)]
self._it = iter(files)
def get_next(self) -> Any:
import numpy as np
try:
path = next(self._it)
except StopIteration:
return None
arr = np.load(str(path))
if not isinstance(arr, np.ndarray):
die(f"expected ndarray in {path}, got {type(arr)}")
if arr.dtype != np.float32:
arr = arr.astype(np.float32, copy=False)
return {self._input_name: arr}
return NpyDirectoryDataReader()
@@ -0,0 +1,171 @@
---
comments: true
---
# iOS Deployment
PaddleOCR ships an iOS OCR sample app under [`deploy/ios_demo`](https://github.com/PaddlePaddle/PaddleOCR/tree/{{PADDLEOCR_GITHUB_REF}}/deploy/ios_demo). The **SwiftUI** demo runs exported **ONNX** models on device using the [ONNX Runtime Objective-C API](https://onnxruntime.ai/docs/tutorials/mobile/) for detection and recognition.
This guide covers environment requirements, model asset setup, building and running in Xcode, and optional ORT format conversion and benchmarking.
## Project layout
App sources, bundled resources, and third-party **source** vendored for this demo live under **`PaddleOCRDemo/`**. Unit tests are in **`PaddleOCRDemoTests/`** next to the Xcode project. The project root also contains `Podfile`, **`scripts/`**, `README.md`, and `NOTICE`.
## Prerequisites
- **macOS** with **Xcode 16.0+** (deployment target **iOS 16+**)
- **CocoaPods** (`gem install cocoapods` or Homebrew)
- `curl`, `tar`
## Supported model presets
`scripts/fetch_ios_demo_models.sh` downloads ONNX bundles into **`PaddleOCRDemo/Models/`**. Supported presets:
- **`PP-OCRv6_small`** (default)
- **`PP-OCRv6_tiny`**
- **`PP-OCRv5_mobile`**
## Quick start
From the **project root** (`deploy/ios_demo`):
```bash
pod install
./scripts/fetch_ios_demo_models.sh
```
Optionally pass the **model preset** (bundle name such as `PP-OCRv6_small`) as a positional argument:
```bash
./scripts/fetch_ios_demo_models.sh PP-OCRv6_small
```
Intermediate `.tar` caches are stored under **`.fetch_ios_demo_models_work/`** at the project root.
After `pod install`, open the workspace:
```bash
open PaddleOCRDemo.xcworkspace
```
Build the **PaddleOCRDemo** scheme. Ensure **`PaddleOCRDemo/Models/`** and **`PaddleOCRDemo/Resources/SampleImages/`** are included in the app target via folder references / **Copy Bundle Resources**, and **`PaddleOCRDemoTests/Fixtures/`** in the test target (as in the checked-in project). The built-in picker sample is **`general_ocr_002.jpg`**.
### ONNX Runtime execution providers (EPs)
The **CPU** / **XNNPACK** / **Core ML** segmented control chooses which ONNX Runtime EP is preferred first when creating the session. ONNX Runtime may still execute some operators on the default **CPU** EP when another EP lacks an implementation. Selecting **CPU** does not register the XNNPACK or Core ML EPs.
## Convert to ORT model format (optional)
To produce [ORT format](https://onnxruntime.ai/docs/performance/model-optimizations/ort-format-models.html) weights:
```bash
python3 -m pip install -r requirements-onnx-convert-ort.txt
./scripts/convert_onnx_to_ort.sh
```
By default, conversion writes `inference*.ort` next to each `inference.onnx` under `PaddleOCRDemo/Models/`. The demo loads `inference*.ort` when present, so you do not need to ship ONNX in the bundle. To keep only one weight file in the app, delete the `inference.onnx` files manually, or use **`--output-dir`** and replace files under `PaddleOCRDemo/Models/`. Use **`--input-dir`** to point at any ONNX tree on the host; it defaults to `PaddleOCRDemo/Models` when omitted.
By default the script uses **`--optimization-style Fixed`** (one `.ort` per ONNX file). The raw Python tool defaults to both Fixed and Runtime (`*.ort` and `*.with_runtime_opt.ort`). For Runtime-style ORT files (e.g. Core ML–oriented exports), pass **`--optimization-style Runtime`** (alias: `--optimization_style`). You can pass both: **`--optimization-style Fixed Runtime`**.
The converter emits **`required_operators*.config`** for minimal ORT builds; **by default the shell script deletes them** after a successful run. Pass **`--keep-operator-config`** to retain them. They are **not** read at inference time. The iOS demo loads only **`.ort`** (or `.onnx`) weights.
Example (Runtime conversion to a separate folder):
```bash
./scripts/convert_onnx_to_ort.sh --output-dir ./out/ort_bundles --optimization-style Runtime
```
## Benchmark
This demo provides a benchmark pipeline for measuring on-device OCR latency and memory.
### Prerequisites
Complete [Quick start](#quick-start) first. For benchmark runs on a **physical device** you also need:
- **Code signing (real device only):** `xcodebuild` requires a valid Apple Development certificate and provisioning profile. Open `PaddleOCRDemo.xcworkspace` in Xcode once, select your Development Team under *Signing & Capabilities*, and let Xcode manage provisioning; later `run_benchmark.sh` invocations reuse the cached profile. On first deploy, trust the developer certificate on the device under **Settings → General → VPN & Device Management** (one-time per device). Simulator runs do not require signing.
- Optional accuracy precheck: PaddleOCR (ONNX Runtime engine) on the host for reference generation, and `python3 -m pip install -r requirements-accuracy.txt`.
### Full pipeline
From the project root, use **`./scripts/run_benchmark.sh`**. The script resolves the input image, optionally runs an accuracy precheck, runs the XCTest benchmark on a simulator or device, extracts artifacts, and writes the Markdown report. It always invokes `xcodebuild test` with `-configuration Release`.
Prefer script flags. `--image` copies an arbitrary image into test fixtures for this run. `--fixture` selects an existing file under `PaddleOCRDemoTests/Fixtures/`. If neither is set, the script requires exactly one non-`local-*` image under `Fixtures/` (e.g. `ios_ocr_benchmark_reference.jpg`).
| Intent | Flags |
| --- | --- |
| Destination | `--udid <id>` for a real device, or `--simulator <name>` |
| Image from an arbitrary path | `--image <path>` |
| Image already under `Fixtures/` | `--fixture <name>` |
| Benchmark intensity | `--warmup <n>`, `--measured-iterations <n>` |
| Preferred ONNX Runtime EP | `--ort-execution-provider CPU`, `XNNPACK`, or `CORE_ML` |
| ONNX Runtime profiling JSON | `--ort-profiling` |
| Optional accuracy precheck | `--accuracy-check`, optionally `--accuracy-reference-json <path>` |
| Gate benchmark on accuracy `FAIL` | `--accuracy-check --stop-on-accuracy-failure` |
| Output directory | `--output-dir <dir>` (default: `out/`) |
| Clean previous artifacts | `--clean` |
```bash
./scripts/run_benchmark.sh --udid <device-udid> --warmup 5 --measured-iterations 30
./scripts/run_benchmark.sh --udid <udid> --image /path/to/photo.png --ort-execution-provider CPU
./scripts/run_benchmark.sh --fixture ios_ocr_benchmark_reference --warmup 2 --measured-iterations 20
./scripts/run_benchmark.sh
PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS=30 ./scripts/run_benchmark.sh --warmup 0
PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER=XNNPACK ./scripts/run_benchmark.sh --fixture ios_ocr_benchmark_reference --warmup 1
./scripts/run_benchmark.sh --accuracy-check --udid <device-udid> --measured-iterations 30
./scripts/run_benchmark.sh --accuracy-check --stop-on-accuracy-failure --udid <device-udid>
./scripts/run_benchmark.sh --output-dir ./benchmark-out --measured-iterations 30
./scripts/run_benchmark.sh --udid <device-udid> --ort-profiling
```
`--accuracy-check` runs before the benchmark in a separate XCTest invocation. Results are `PASS`, `FAIL`, or `ERROR`. By default, `FAIL` records a mismatch but continues; `ERROR` stops the pipeline. `--stop-on-accuracy-failure` also skips the benchmark on `FAIL`.
**ORT session profiling** (attachments `ort_profile_detection`, `ort_profile_recognition`): use `--ort-profiling`. Run profiling in a **separate** run from clean latency measurements.
After the benchmark **completes**, the script overwrites `run-status.json`, `on-device-performance.json`, `xctest-memory-metrics.json`, and `benchmark-report.md` under the output directory (`out/` by default). On **ERROR**, those files may be missing or partial.
The report includes model input tensor shape distributions, first measured run line count, inferred model preset, actual model format (`onnx` or `ort`), det/rec/total weight sizes, app executable size when resolvable, cold model load time, measured latency, memory, etc.
| Artifact | Producer | Purpose |
|---|---|---|
| `accuracy-reference.json` | `ocr_reference_run.py` | Optional reference JSON |
| `accuracy-result.xcresult` | `xcodebuild test` | Optional accuracy precheck |
| `ios-ocr-export.json` | `extract_xcresult_attachments.py` | Optional iOS accuracy payload |
| `accuracy-summary.json` | `compare_ocr_json.py` | Optional accuracy summary |
| `latency-result.xcresult` | `xcodebuild test` | Latency benchmark |
| `memory-result.xcresult` | `xcodebuild test` | Memory benchmark |
| `on-device-performance.json` | `extract_xcresult_attachments.py` | Latency stats from `latency-result.xcresult` |
| `ort_profile_detection`, `ort_profile_recognition` | `extract_xcresult_attachments.py` | Optional ORT profiling JSON |
| `xctest-memory-metrics.json` | `extract_xctest_metrics.py` | XCTest memory metrics |
| `logs/*.log` | `run_benchmark.sh` | Per-step logs |
| `run-status.json` | `run_benchmark.sh` | Step outcomes and metadata |
| `benchmark-report.md` | `generate_benchmark_report.py` | Human-readable report |
Exit **`0`** when the pipeline reaches **`COMPLETED`**; non-zero on **`ERROR`**. Accuracy `FAIL` changes the exit code only with `--stop-on-accuracy-failure`; `ERROR` always stops the pipeline.
### Advanced: XCTest environment
Most users should use `run_benchmark.sh` flags instead of setting XCTest environment variables directly. This section is for debugging the `PaddleOCRDemoTests` target from Xcode or a custom `xcodebuild test` command.
Benchmark tests read **`PADDLEOCR_BENCHMARK_*`** variables on the XCTest runner process.
| How you launch tests | What to configure |
| --- | --- |
| **Xcode** | Scheme **PaddleOCRDemo** → **Test** → **Arguments** → **Environment Variables** (`PADDLEOCR_BENCHMARK_…` as-is). |
| **Custom `xcodebuild test`** | **`TEST_RUNNER_` + variable name** (e.g. `TEST_RUNNER_PADDLEOCR_BENCHMARK_IMAGE_NAME=…`). |
| Variable | If unset | Role |
| --- | --- | --- |
| `PADDLEOCR_BENCHMARK_IMAGE_NAME` | **`ios_ocr_benchmark_reference`** | Bundled test image under **`Fixtures/`**. |
| `PADDLEOCR_BENCHMARK_WARMUP_ITERATIONS` | **3** | Untimed full OCR runs before timing. |
| `PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS` | **10** | Timed runs. |
| `PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER` | **CPU** | **`CPU`**, **`XNNPACK`**, or **`CORE_ML`**. |
| `PADDLEOCR_BENCHMARK_ORT_PROFILING` | (unset) | Enable ORT session profiling (`1` / `true` / `yes` / `on`). |
| `PADDLEOCR_BENCHMARK_ONLY_TESTING_SCOPE` | latency + memory benchmark tests | `run_benchmark.sh` only: comma-separated `-only-testing` scope. |
Non-negative integers for the two iteration variables.
## Third-party licenses
Bundled **Clipper** (polyclipping 6.4.2) is under the [Boost Software License 1.0](https://www.boost.org/LICENSE_1_0.txt); see `NOTICE` and `PaddleOCRDemo/ThirdParty/Clipper1/LICENSE`. CocoaPods pods are governed by their respective licenses (see `Podfile.lock` after `pod install`).
@@ -0,0 +1,171 @@
---
comments: true
---
# iOS 部署
PaddleOCR 在 [`deploy/ios_demo`](https://github.com/PaddlePaddle/PaddleOCR/tree/{{PADDLEOCR_GITHUB_REF}}/deploy/ios_demo) 提供基于 **SwiftUI** 的 iOS OCR 示例应用。应用在设备上使用导出的 **ONNX** 模型,通过 [ONNX Runtime Objective-C API](https://onnxruntime.ai/docs/tutorials/mobile/) 完成检测与识别推理。
本指南介绍该 Demo 的环境要求、模型资源准备、在 Xcode 中构建运行,以及可选的 ORT 格式转换与基准测试流程。
## 工程结构
应用源码、打包资源及为本 Demo 引入的第三方**源码**均位于 **`PaddleOCRDemo/`** 下。单元测试位于与 Xcode 工程同级的 **`PaddleOCRDemoTests/`**。工程根目录还包含 `Podfile`、`scripts/`、`README.md` 与 `NOTICE`。
## 环境要求
- 搭载 **macOS** 的开发机,**Xcode 16.0+**(部署目标 **iOS 16+**)
- **CocoaPods**(`gem install cocoapods` 或 Homebrew)
- `curl`、`tar`
## 支持的模型预设
`scripts/fetch_ios_demo_models.sh` 会将 ONNX 模型包下载到 **`PaddleOCRDemo/Models/`**。当前支持的预设为:
- **`PP-OCRv6_small`**(默认)
- **`PP-OCRv6_tiny`**
- **`PP-OCRv5_mobile`**
## 快速开始 {#快速开始}
在 **工程根目录**(`deploy/ios_demo`)执行:
```bash
pod install
./scripts/fetch_ios_demo_models.sh
```
可选:通过位置参数指定模型预设(即 bundle 名称,如 `PP-OCRv6_small`):
```bash
./scripts/fetch_ios_demo_models.sh PP-OCRv6_small
```
中间 `.tar` 缓存目录为工程根下的 **`.fetch_ios_demo_models_work/`**。
使用 CocoaPods 时,需先执行 `pod install` 再打开工作区:
```bash
open PaddleOCRDemo.xcworkspace
```
构建 **PaddleOCRDemo** scheme。请确认 **`PaddleOCRDemo/Models/`** 与 **`PaddleOCRDemo/Resources/SampleImages/`** 已通过文件夹引用 / **Copy Bundle Resources** 加入 App target;**`PaddleOCRDemoTests/Fixtures/`** 已加入测试 target(与仓库中工程配置一致)。内置样例图为 **`general_ocr_002.jpg`**。
### ONNX Runtime 执行提供程序(EP)
界面上的 **CPU** / **XNNPACK** / **Core ML** 分段控件用于在创建 Session 时指定优先使用的 EP。当某一 EP 无法覆盖部分算子时,ONNX Runtime 仍可能回退到默认 **CPU** EP。选择 **CPU** 时不会注册 XNNPACK 或 Core ML EP。
## 转换为 ORT 模型格式(可选)
生成 [ORT 格式](https://onnxruntime.ai/docs/performance/model-optimizations/ort-format-models.html) 权重:
```bash
python3 -m pip install -r requirements-onnx-convert-ort.txt
./scripts/convert_onnx_to_ort.sh
```
默认在 `PaddleOCRDemo/Models/` 下每个 `inference.onnx` 旁生成 `inference*.ort`;Demo 在存在 `.ort` 时会优先加载,因此可不将 ONNX 打入 App 包。若只希望保留一种权重文件,可手动删除 `inference.onnx`,或用 **`--output-dir`** 将 `.ort` 输出到单独目录后再替换 `PaddleOCRDemo/Models/` 中的文件。省略 **`--input-dir`** 时默认输入目录为 `PaddleOCRDemo/Models`。
默认使用 **`--optimization-style Fixed`**(每个 ONNX 对应一个 `.ort`)。底层 Python 工具若未指定,会同时生成 Fixed 与 Runtime 两种(`*.ort` 与 `*.with_runtime_opt.ort`)。需要 Runtime 风格(如面向 Core ML 的导出)时,传入 **`--optimization-style Runtime`**(别名 `--optimization_style`);可同时传入 **`--optimization-style Fixed Runtime`**。
转换会生成 **`required_operators*.config`**(用于裁剪最小 ORT 构建);**默认在脚本成功结束后删除**。使用 **`--keep-operator-config`** 可保留。这些文件**不参与** Demo 推理,仅加载 **`.ort`**(或 `.onnx`)权重。
示例(Runtime,输出到独立目录):
```bash
./scripts/convert_onnx_to_ort.sh --output-dir ./out/ort_bundles --optimization-style Runtime
```
## 基准测试(Benchmark)
Demo 提供在真机或模拟器上测量 OCR 时延与内存的流水线。
### 前置条件
先完成 [快速开始](#快速开始) 中的资源准备。真机基准测试还需要:
- **代码签名(仅真机)**:`xcodebuild` 部署到物理设备需要有效的 Apple Development 证书与描述文件。建议在 Xcode 中打开 `PaddleOCRDemo.xcworkspace`,在 *Signing & Capabilities* 中选择 Development Team 并启用自动管理;之后 `run_benchmark.sh` 等命令可复用已缓存的配置。首次在设备上启动时,须在 **设置 → 通用 → VPN 与设备管理** 中信任开发者证书(每台设备一次)。模拟器无需签名。
- 可选精度预检:主机安装 PaddleOCR(ONNX Runtime 引擎)用于生成参考结果,并执行 `python3 -m pip install -r requirements-accuracy.txt`。
### 完整流水线
在工程根目录执行 **`./scripts/run_benchmark.sh`**。脚本会解析输入图像、可选执行精度预检、在模拟器或真机上运行 XCTest 基准、提取产物并生成 Markdown 报告。始终以 **Release** 配置调用 `xcodebuild test`。
**配置方式**:优先使用脚本参数。`--image` 将任意路径图像复制到本次运行的 `Fixtures/local-*`;`--fixture` 选择 `PaddleOCRDemoTests/Fixtures/` 下已有文件。若两者均未指定,则要求 `Fixtures/` 下恰好有一张非 `local-*` 的图像(常见为 `ios_ocr_benchmark_reference.jpg`)。
| 用途 | 参数 |
| --- | --- |
| 运行目标 | `--udid <id>`(真机)或 `--simulator <name>` |
| 任意路径图像 | `--image <path>` |
| 已有 Fixture | `--fixture <name>`(stem 或 `stem.ext`) |
| 强度 | `--warmup <n>`、`--measured-iterations <n>` |
| 优先 ORT EP | `--ort-execution-provider CPU`、`XNNPACK` 或 `CORE_ML` |
| ORT profiling JSON | `--ort-profiling` |
| 可选精度预检 | `--accuracy-check`,可选 `--accuracy-reference-json <path>` |
| 精度 FAIL 时中止 | `--accuracy-check --stop-on-accuracy-failure` |
| 输出目录 | `--output-dir <dir>`(默认 `out/`) |
| 清理旧产物 | `--clean` |
```bash
./scripts/run_benchmark.sh --udid <device-udid> --warmup 5 --measured-iterations 30
./scripts/run_benchmark.sh --udid <udid> --image /path/to/photo.png --ort-execution-provider CPU
./scripts/run_benchmark.sh --fixture ios_ocr_benchmark_reference --warmup 2 --measured-iterations 20
./scripts/run_benchmark.sh
PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS=30 ./scripts/run_benchmark.sh --warmup 0
PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER=XNNPACK ./scripts/run_benchmark.sh --fixture ios_ocr_benchmark_reference --warmup 1
./scripts/run_benchmark.sh --accuracy-check --udid <device-udid> --measured-iterations 30
./scripts/run_benchmark.sh --accuracy-check --stop-on-accuracy-failure --udid <device-udid>
./scripts/run_benchmark.sh --output-dir ./benchmark-out --measured-iterations 30
./scripts/run_benchmark.sh --udid <device-udid> --ort-profiling
```
`--accuracy-check` 在基准测试前以独立 XCTest 运行。结果为 `PASS`、`FAIL` 或 `ERROR`。默认 `FAIL` 仅记录并继续基准;`ERROR` 会中止流水线。`--stop-on-accuracy-failure` 会在 `FAIL` 时跳过基准并返回非零退出码。
**ORT Session profiling**(附件 `ort_profile_detection`、`ort_profile_recognition`):使用 `--ort-profiling`。Profiling 会改变运行时行为,应与干净时延测量**分开**运行。
基准**成功完成**后,脚本会在输出目录(默认 `out/`)覆盖写入 `run-status.json`、`on-device-performance.json`、`xctest-memory-metrics.json`、`benchmark-report.md`。若流水线提前 **ERROR**,这些文件可能缺失或不完整。
报告内容包括模型输入张量形状分布、首次测量运行的行数、推断的模型预设、实际模型格式(`onnx` 或 `ort`)、det/rec/总权重大小、在可解析时的 App 可执行文件大小、冷启动模型加载时间、测量时延与内存等。形状统计在测量循环内按模型调用计数:每次完整 OCR 检测贡献 1 次,识别按 batch 各贡献 1 次。
| 产物 | 来源 | 用途 |
|---|---|---|
| `accuracy-reference.json` | `ocr_reference_run.py` | 可选参考 JSON(除非提供 `--accuracy-reference-json`) |
| `accuracy-result.xcresult` | `xcodebuild test` | 可选精度预检 |
| `ios-ocr-export.json` | `extract_xcresult_attachments.py` | 从精度预检提取的 iOS 精度 payload |
| `accuracy-summary.json` | `compare_ocr_json.py` | 精度预检摘要 |
| `latency-result.xcresult` | `xcodebuild test` | 时延基准 |
| `memory-result.xcresult` | `xcodebuild test` | 内存基准 |
| `on-device-performance.json` | `extract_xcresult_attachments.py` | 从 `latency-result.xcresult` 提取的时延统计 |
| `ort_profile_detection`、`ort_profile_recognition` | `extract_xcresult_attachments.py` | 可选 ORT profiling JSON |
| `xctest-memory-metrics.json` | `extract_xctest_metrics.py` | XCTest 内存指标 |
| `logs/*.log` | `run_benchmark.sh` | 各步骤日志 |
| `run-status.json` | `run_benchmark.sh` | 步骤状态与元数据 |
| `benchmark-report.md` | `generate_benchmark_report.py` | 可读报告 |
流水线状态为 **`COMPLETED`** 时退出码 **`0`**;**`ERROR`** 时非零。精度预检 `FAIL` 仅在使用 `--stop-on-accuracy-failure` 时改变退出码;`ERROR` 始终中止。
### 进阶:XCTest 环境变量
多数场景应使用 `run_benchmark.sh` 参数,而非直接设置环境变量。本节适用于在 Xcode 或自定义 `xcodebuild test` 中调试 **PaddleOCRDemoTests**。
基准测试通过 **`PADDLEOCR_BENCHMARK_*`** 读取配置(作用于 XCTest runner,不会自动传入交互式 shell)。
| 启动方式 | 配置方法 |
| --- | --- |
| **Xcode** | Scheme **PaddleOCRDemo** → **Test** → **Arguments** → **Environment Variables**,变量名如下。 |
| **自定义 `xcodebuild test`** | 使用 **`TEST_RUNNER_` + 变量名**(如 `TEST_RUNNER_PADDLEOCR_BENCHMARK_IMAGE_NAME=…`)。 |
| 变量 | 未设置时 | 作用 |
| --- | --- | --- |
| `PADDLEOCR_BENCHMARK_IMAGE_NAME` | **`ios_ocr_benchmark_reference`** | `Fixtures/` 下 bundled 图像(stem 或 `stem.ext`)。 |
| `PADDLEOCR_BENCHMARK_WARMUP_ITERATIONS` | **3** | 计时时前的预热完整 OCR 次数。 |
| `PADDLEOCR_BENCHMARK_MEASURED_ITERATIONS` | **10** | 计时迭代次数。 |
| `PADDLEOCR_BENCHMARK_ORT_EXECUTION_PROVIDER` | **CPU** | **`CPU`**、**`XNNPACK`** 或 **`CORE_ML`**。 |
| `PADDLEOCR_BENCHMARK_ORT_PROFILING` | (未设置) | 启用 ORT session profiling(`1` / `true` / `yes` / `on`)。 |
| `PADDLEOCR_BENCHMARK_ONLY_TESTING_SCOPE` | latency + memory 基准测试 | 仅 `run_benchmark.sh`:传给多次 `xcodebuild -only-testing` 的逗号分隔列表。 |
两个迭代相关变量须为非负整数。
## 第三方许可
随 Demo 打包的 **Clipper**(polyclipping 6.4.2)采用 [Boost Software License 1.0](https://www.boost.org/LICENSE_1_0.txt);详见 `NOTICE` 与 `PaddleOCRDemo/ThirdParty/Clipper1/LICENSE`。CocoaPods 依赖的许可以 `pod install` 后的 `Podfile.lock` 及各自仓库为准。
@@ -1,479 +0,0 @@
---
comments: true
---
# OCR On-Device Deployment Demo Usage Guide
- [Quick Start](#quick-start)
- [Environment Preparation](#environment-preparation)
- [Deployment Steps](#deployment-steps)
- [Code Introduction](#code-introduction)
- [Project Explanation](#engineering-details)
- [Advanced Usage](#advanced-usage)
- [Update Prediction Library](#updating-the-prediction-library)
- [Convert NB Model](#converting-nb-models)
- [Update Model, Label File, and Prediction Image](#updating-models-label-files-and-prediction-images)
- [Update Model](#updating-models)
- [Update Label File](#updating-label-files)
- [Update Prediction Image](#updating-prediction-images)
- [Update Input/Output Preprocessing](#updating-inputoutput-preprocessing)
This guide mainly introduces how to run the PaddleX on-device deployment demo for OCR text recognition on an Android shell.
The following OCR models are supported in this guide:
- PP-OCRv3_mobile (cpu)
- PP-OCRv4_mobile (cpu)
- PP-OCRv5_mobile (cpu)
## Quick Start
### Environment Preparation
1. Install the CMAKE compilation tool in your local environment and download an NDK package for your current system from the [Android NDK official website](https://developer.android.google.cn/ndk/downloads). For example, if developing on a Mac, download the NDK package for the Mac platform from the Android NDK official website.
**Environment Requirements**
- `CMake >= 3.10` (the minimum version has not been verified; 3.20 or above is recommended)
- `Android NDK >= r17c` (the minimum version has not been verified; r20b or above is recommended)
**Test Environment Used in This Guide**:
- `cmake == 3.20.0`
- `android-ndk == r20b`
2. Prepare an Android phone and enable USB debugging mode. Method: `Phone Settings -> Find Developer Options -> Enable Developer Options and USB Debugging Mode`
3. Install the ADB tool on your computer for debugging. The installation methods for ADB are as follows:
3.1. Install ADB on a Mac:
```shell
brew cask install android-platform-tools
```
3.2. Install ADB on Linux:
```shell
sudo apt update
sudo apt install -y wget adb
```
3.3. Install ADB on Windows:
For installation on Windows, download and install the ADB software package from Google's Android platform: [Link](https://developer.android.com/studio)
Open a terminal, connect your phone to the computer, and enter the following command in the terminal:
```shell
adb devices
```
If there is a `device` output, the installation is successful.
```shell
List of devices attached
744be294 device
```
### Material Preparation
1. Clone the `feature/paddle-x` branch of the `Paddle-Lite-Demo` repository to the `PaddleX-Lite-Deploy` directory.
```shell
git clone -b feature/paddle-x https://github.com/PaddlePaddle/Paddle-Lite-Demo.git PaddleX-Lite-Deploy
```
2. Fill out the [questionnaire](https://paddle.wjx.cn/vm/eaaBo0H.aspx#) to download the compressed package. Place the compressed package in the specified extraction directory, switch to the specified extraction directory, and execute the extraction command.
```shell
# 1. Switch to the specified extraction directory
cd PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo
# 2. Execute the extraction command
unzip ocr.zip
```
### Deployment Steps
1. Switch the working directory to `PaddleX-Lite-Deploy/libs` and run the `download.sh` script to download the required Paddle Lite prediction library. This step only needs to be executed once to support each demo.
2. Switch the working directory to `PaddleX-Lite-Deploy/ocr/assets` and run the `download.sh` script to download the [paddle_lite_opt tool](https://www.paddlepaddle.org.cn/lite/v2.10/user_guides/model_optimize_tool.html)-optimized NB model file, prediction images, dictionary files, and other materials.
3. Switch the working directory to `PaddleX-Lite-Deploy/ocr/android/shell/cxx/ppocr_demo` and run the `build.sh` script to complete the compilation of the executable file.
4. Switch the working directory to `PaddleX-Lite-Deploy/ocr/android/shell/cxx/ppocr_demo` and run the `run.sh` script to complete the on-device prediction.
**Notes**:
- Before running the `build.sh` script, change the path specified by `NDK_ROOT` to the actual installation path of NDK.
- On Windows systems, you can use Git Bash to execute the deployment steps.
- If compiling on a Windows system, set `CMAKE_SYSTEM_NAME` to `windows` in `CMakeLists.txt`.
- If compiling on a Mac system, set `CMAKE_SYSTEM_NAME` to `darwin` in `CMakeLists.txt`.
- Keep the ADB connection active when running the `run.sh` script.
- The `download.sh` and `run.sh` scripts support passing parameters to specify the model. If no model is specified, the `PP-OCRv5_mobile` model is used by default. The following models are currently supported:
- `PP-OCRv3_mobile`
- `PP-OCRv4_mobile`
- `PP-OCRv5_mobile`
Here is an example of the actual operation:
```shell
# 1. Download the required Paddle Lite prediction library
cd PaddleX-Lite-Deploy/libs
sh download.sh
# 2. Download the paddle_lite_opt tool-optimized NB model file, prediction images, dictionary files, and other materials
cd ../ocr/assets
sh download.sh PP-OCRv5_mobile
# 3. Complete the compilation of the executable file
cd ../android/shell/ppocr_demo
sh build.sh
# 4. Prediction
sh run.sh PP-OCRv5_mobile
```
The output is as follows:
```text
The detection visualized image saved in ./test_img_result.jpg
0 纯臻营养护发素 0.998541
1 产品信息/参数 0.999094
2 (45元/每公斤,100公斤起订) 0.948841
3 每瓶22元,1000瓶起订) 0.961245
4 【品牌】:代加工方式/OEMODM 0.970401
5 【品名】:纯臻营养护发素 0.977496
6 ODMOEM 0.955396
7 【产品编号】:YM-X-3011 0.977864
8 【净含量】:220ml 0.970538
9 【适用人群】:适合所有肤质 0.995907
10 【主要成分】:鲸蜡硬脂醇、燕麦β-葡聚 0.975813
11 糖、椰油酰胺丙基甜菜碱、泛醌 0.964397
12 (成品包材) 0.97298
13 【主要功能】:可紧致头发磷层,从而达到 0.989097
14 即时持久改善头发光泽的效果,给干燥的头 0.990088
15 发足够的滋养 0.998037
```
![Prediction Result](https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/pipeline_deploy/edge_PP-OCRv5_mobile.jpg)
## Code Introduction
```
.
├── ...
├── ocr
│ ├── ...
│ ├── android
│ │ ├── ...
│ │ └── shell
│ │ └── ppocr_demo
│ │ ├── src # Contains prediction code
│ │ | ├── cls_process.cc # Full inference process for orientation classifier, including preprocessing, prediction, and postprocessing
│ │ | ├── rec_process.cc # Full inference process for recognition model CRNN, including preprocessing, prediction, and postprocessing
│ │ | ├── det_process.cc # Full inference process for detection model CRNN, including preprocessing, prediction, and postprocessing
│ │ | ├── det_post_process.cc # Postprocessing file for detection model DB
│ │ | ├── pipeline.cc # Full inference process code for OCR text recognition demo
│ │ | └── MakeFile # MakeFile file for prediction code
│ │ |
│ │ ├── CMakeLists.txt # CMake file that defines the compilation method for the executable
│ │ ├── README.md
│ │ ├── build.sh # Used for compiling the executable
│ │ └── run.sh # Used for prediction
│ └── assets # Stores models, test images, label files, and config files
│ ├── images # Stores test images
│ ├── labels # Stores dictionary files (see remarks below for details)
│ ├── models # Stores nb models
│ ├── config.txt
│ └── download.sh # Download script for paddle_lite_opt tool-optimized models
└── libs # Stores prediction libraries and OpenCV libraries for different platforms.
├── ...
└── download.sh # Download script for Paddle Lite prediction libraries and OpenCV libraries
```
**Remarks**:
- The `PaddleX-Lite-Deploy/ocr/assets/labels/` directory contains the dictionary files `ppocr_keys_v1.txt` for PP-OCRv3 and PP-OCRv4 models, and `ppocr_keys_ocrv5.txt` for the PP-OCRv5 model. The appropriate dictionary file is automatically selected during inference based on the model name, so no manual intervention is required.
- If you are using an English/numeric or other language model, you need to replace it with the corresponding language dictionary. The PaddleOCR repository provides [some dictionary files](../../../ppocr/utils).
```shell
# Parameters of the executable in run.sh script:
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
First parameter: ppocr_demo executable
Second parameter: ./models/${MODEL_NAME}_det.nb Detection model .nb file
Third parameter: ./models/${MODEL_NAME}_rec.nb Recognition model .nb file
Fourth parameter: ./models/${CLS_MODEL_FILE} Text line orientation classification model .nb file (automatically selected based on model name by default)
Fifth parameter: ./images/test.jpg Test image
Sixth parameter: ./test_img_result.jpg Result save file
Seventh parameter: ./labels/${LABEL_FILE} Label file (automatically selected based on model name by default)
Eighth parameter: ./config.txt Configuration file containing hyperparameters for the detection and classification models
```
```shell
# List of Specific Parameters in config.txt:
max_side_len 960 # When the width or height of the input image is greater than 960, the image is scaled proportionally so that the longest side of the image is 960.
det_db_thresh 0.3 # Used to filter the binarized images predicted by DB; setting it to 0.3 has no significant impact on the results.
det_db_box_thresh 0.5 # Threshold for filtering boxes in the DB post-processing; if there are missing boxes in detection, you may reduce this value.
det_db_unclip_ratio 1.6 # Represents the compactness of the text box; the smaller the value, the closer the text box is to the text.
use_direction_classify 0 # Whether to use a direction classifier: 0 means not using it, 1 means using it.
```
## Engineering Details
The OCR text recognition demo accomplishes the OCR text recognition function using three models collaboratively. First, the input image undergoes detection processing via the `${MODEL_NAME}_det.nb` model, followed by text direction classification using the `ch_ppocr_mobile_v2.0_cls_slim_opt.nb` model, and finally, text recognition with the `${MODEL_NAME}_rec.nb` model.
1. `pipeline.cc`: Full-process prediction code for the OCR text recognition demo
This file handles the entire process control for serial inference of the three models, including scheduling for the entire processing flow.
- The `Pipeline::Pipeline(...)` method initializes the three model class constructors, accomplishes model loading, thread count, core binding, and predictor creation.
- The `Pipeline::Process(...)` method manages the entire process control for serial inference of the three models.
2. `cls_process.cc`: Prediction file for the direction classifier
This file handles the preprocessing, prediction, and postprocessing for the direction classifier.
- The `ClsPredictor::ClsPredictor()` method initializes model loading, thread count, core binding, and predictor creation.
- The `ClsPredictor::Preprocess()` method handles model preprocessing.
- The `ClsPredictor::Postprocess()` method handles model postprocessing.
3. `rec_process.cc`: Prediction file for the CRNN recognition model
This file handles the preprocessing, prediction, and postprocessing for the CRNN recognition model.
- The `RecPredictor::RecPredictor()` method initializes model loading, thread count, core binding, and predictor creation.
- The `RecPredictor::Preprocess()` method handles model preprocessing.
- The `RecPredictor::Postprocess()` method handles model postprocessing.
4. `det_process.cc`: Prediction file for the DB detection model
This file handles the preprocessing, prediction, and postprocessing for the DB detection model.
- The `DetPredictor::DetPredictor()` method initializes model loading, thread count, core binding, and predictor creation.
- The `DetPredictor::Preprocess()` method handles model preprocessing.
- The `DetPredictor::Postprocess()` method handles model postprocessing.
5. `db_post_process`: Postprocessing functions for the DB detection model, including calls to the clipper library
This file implements third-party library calls and other postprocessing methods for the DB detection model.
- The `std::vector<std::vector<std::vector<int>>> BoxesFromBitmap(...)` method retrieves detection boxes from a Bitmap.
- The `std::vector<std::vector<std::vector<int>>> FilterTagDetRes(...)` method retrieves target box positions based on recognition results.
## Advanced Usage
If the quick start section does not meet your needs, refer to this section for custom modifications to the demo.
This section mainly includes four parts:
- Updating the prediction library;
- Converting `.nb` models;
- Updating models, label files, and prediction images;
- Updating input/output preprocessing.
### Updating the Prediction Library
The prediction library used in this guide is the latest version (214rc), and manual updates are not recommended.
If you need to use a different version, follow these steps to update the prediction library:
* Paddle Lite project: https://github.com/PaddlePaddle/Paddle-Lite
* Refer to the [Paddle Lite Source Code Compilation Documentation](https://www.paddlepaddle.org.cn/lite/develop/source_compile/compile_env.html) to compile the Android prediction library.
* The final compilation output is located in `build.lite.xxx.xxx.xxx` under `inference_lite_lib.xxx.xxx`.
* Replace the C++ library:
* Header files:
Replace the `PaddleX-Lite-Deploy/libs/android/cxx/include` folder in the demo with the generated `build.lite.android.xxx.gcc/inference_lite_lib.android.xxx/cxx/include` folder.
* armeabi-v7a:
Replace the `PaddleX-Lite-Deploy/libs/android/cxx/libs/armeabi-v7a/libpaddle_lite_api_shared.so` library in the demo with the generated `build.lite.android.armv7.gcc/inference_lite_lib.android.armv7/cxx/libs/libpaddle_lite_api_shared.so` library.
* arm64-v8a:
Replace the `PaddleX-Lite-Deploy/libs/android/cxx/libs/arm64-v8a/libpaddle_lite_api_shared.so` library in the demo with the generated `build.lite.android.armv8.gcc/inference_lite_lib.android.armv8/cxx/libs/libpaddle_lite_api_shared.so` library.
### Converting .nb Models
If you want to use your own trained models, follow the process below to obtain `.nb` models.
#### Terminal Command Method (Supports Mac/Ubuntu)
1. Navigate to the [release interface](https://github.com/PaddlePaddle/Paddle-Lite/releases) of the Paddle-Lite GitHub repository and download the corresponding conversion tool, opt, for the desired version (the latest version is recommended).
2. After downloading the opt tool, execute the following command (using the 2.14rc version of the linux_x86 opt tool to convert the PP-OCRv5_mobile_det model as an example):
```bash
./opt_linux_x86 \
--model_file=PP-OCRv5_mobile_det/inference.pdmodel \
--param_file=PP-OCRv5_mobile_det/inference.pdiparams \
--optimize_out=PP-OCRv5_mobile_det \
--valid_targets=arm
```
For detailed instructions on converting `.nb` models using the terminal command method, refer to the [Using the Executable opt](https://www.paddlepaddle.org.cn/lite/v2.12/user_guides/opt/opt_bin.html) section in the Paddle-Lite repository.
#### Python Script Method (Supports Windows/Mac/Ubuntu)
1. Install the latest version of the paddlelite wheel package.
```bash
pip install --pre paddlelite
```
2. Use the Python script to convert the model. Below is an example code snippet for converting the PP-OCRv5_mobile_det model:
```python
from paddlelite.lite import Opt
# 1. Create an Opt instance
opt = Opt()
# 2. Specify the input model paths
opt.set_model_file("./PP-OCRv5_mobile_det/inference.pdmodel")
opt.set_param_file("./PP-OCRv5_mobile_det/inference.pdiparams")
# 3. Specify the target platform for optimization
opt.set_valid_places("arm")
# 4. Specify the output path for the optimized model
opt.set_optimize_out("./PP-OCRv5_mobile_det")
# 5. Execute model optimization
opt.run()
```
For detailed instructions on converting `.nb` models using the Python script method, refer to the [Python Script opt Usage](https://www.paddlepaddle.org.cn/lite/v2.12/api_reference/python_api/opt.html) section in the Paddle-Lite repository.
**Notes**
- For detailed information about the model optimization tool `opt`, refer to Paddle-Lite's [Model Optimization Tool opt](https://www.paddlepaddle.org.cn/lite/v2.12/user_guides/model_optimize_tool.html).
- Currently, only static graph models in `.pdmodel` format can be converted to `.nb` format. In PaddlePaddle version 3.0 and above, the default exported model format is `.json`. If you want to export the model in `.pdmodel` format, simply add `-o Global.export_with_pir=False` during export.
### Updating Models, Label Files, and Prediction Images
#### Updating Models
This guide has only validated the `PP-OCRv3_mobile`, `PP-OCRv4_mobile`, and `PP-OCRv5_mobile` models. Other models may not be compatible.
If you fine-tune the `PP-OCRv5_mobile` model and generate a new model named `PP-OCRv5_mobile_ft`, follow these steps to replace the original model with your fine-tuned model:
1. Place the `.nb` models of `PP-OCRv5_mobile_ft` into the directory `PaddleX-Lite-Deploy/ocr/assets/models/`. The resulting file structure should be:
```text
.
├── ocr
│ ├── ...
│ └── assets
│ ├── models
│ │ ├── ...
│ │ ├── PP-OCRv5_mobile_ft_det.nb
│ │ └── PP-OCRv5_mobile_ft_rec.nb
│ └── ...
└── ...
```
2. Add the model name to the `MODEL_LIST` in the `run.sh` script.
```shell
MODEL_LIST="PP-OCRv3_mobile PP-OCRv4_mobile PP-OCRv5_mobile PP-OCRv5_mobile_ft" # Models are separated by spaces
```
3. Specify the model directory name when running the `run.sh` script.
```shell
sh run.sh PP-OCRv5_mobile_ft
```
**Notes**:
- If the input Tensor, Shape, or Dtype of the model is updated:
- For the text direction classifier model, update the `ClsPredictor::Preprocess` function in `ppocr_demo/src/cls_process.cc`.
- For the detection model, update the `DetPredictor::Preprocess` function in `ppocr_demo/src/det_process.cc`.
- For the recognition model, update the `RecPredictor::Preprocess` function in `ppocr_demo/src/rec_process.cc`.
- If the output Tensor or Dtype of the model is updated:
- For the text direction classifier model, update the `ClsPredictor::Postprocess` function in `ppocr_demo/src/cls_process.cc`.
- For the detection model, update the `DetPredictor::Postprocess` function in `ppocr_demo/src/det_process.cc`.
- For the recognition model, update the `RecPredictor::Postprocess` function in `ppocr_demo/src/rec_process.cc`.
#### Updating Label Files
To update the label file, place the new label file in the directory `PaddleX-Lite-Deploy/ocr/assets/labels/` and update the execution command in `PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo/run.sh` following the model update method.
For example, to update to `new_labels.txt`:
```shell
# File: `PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo/run.sh`
# Original command
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
# Updated command
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/new_labels.txt \
./config.txt"
```
#### Updating Prediction Images
If you need to update the prediction images, place the updated images in the `PaddleX-Lite-Deploy/ocr/assets/images/` directory and update the execution command in the `PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo/run.sh` file.
Here is an example of updating to `new_pics.jpg`:
```shell
# File: `PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo/run.sh`
## Original command
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
# Updated command
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/new_pics.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
```
### Updating Input/Output Preprocessing
- Updating Input Preprocessing
- For the text direction classifier model, update the `ClsPredictor::Preprocess` function in `ppocr_demo/src/cls_process.cc`.
- For the detection model, update the `DetPredictor::Preprocess` function in `ppocr_demo/src/det_process.cc`.
- For the recognition model, update the `RecPredictor::Preprocess` function in `ppocr_demo/src/rec_process.cc`.
- Updating Output Preprocessing
- For the text direction classifier model, update the `ClsPredictor::Postprocess` function in `ppocr_demo/src/cls_process.cc`.
- For the detection model, update the `DetPredictor::Postprocess` function in `ppocr_demo/src/det_process.cc`.
- For the recognition model, update the `RecPredictor::Postprocess` function in `ppocr_demo/src/rec_process.cc`.
@@ -1,479 +0,0 @@
---
comments: true
---
# OCR 端侧部署 demo 使用指南
- [快速开始](#_1)
- [环境准备](#_2)
- [部署步骤](#_4)
- [代码介绍](#_5)
- [工程详解](#_6)
- [进阶使用](#_7)
- [更新预测库](#_8)
- [转换 nb 模型](#nb)
- [更新模型、标签文件和预测图片](#_9)
- [更新模型](#_10)
- [更新标签文件](#_11)
- [更新预测图片](#_12)
- [更新输入/输出预处理](#_13)
本指南主要介绍 PaddleX 端侧部署——OCR文字识别 demo 在 Android shell 上的运行方法。
本指南适配了以下 OCR 模型:
- PP-OCRv3_mobile(cpu)
- PP-OCRv4_mobile(cpu)
- PP-OCRv5_mobile(cpu)
## 快速开始
### 环境准备
1. 在本地环境安装好 CMAKE 编译工具,并在 [Android NDK 官网](https://developer.android.google.cn/ndk/downloads)下载当前系统的某个版本的 NDK 软件包。例如,在 Mac 上开发,需要在 Android NDK 官网下载 Mac 平台的 NDK 软件包
**环境要求**
- `CMake >= 3.10`(最低版本未经验证,推荐 3.20 及以上)
- `Android NDK >= r17c`(最低版本未经验证,推荐 r20b 及以上)
**本指南所使用的测试环境:**
- `cmake == 3.20.0`
- `android-ndk == r20b`
2. 准备一部 Android 手机,并开启 USB 调试模式。开启方法: `手机设置 -> 查找开发者选项 -> 打开开发者选项和 USB 调试模式`
3. 电脑上安装 ADB 工具,用于调试。ADB 安装方式如下:
3.1. Mac 电脑安装 ADB:
```shell
brew cask install android-platform-tools
```
3.2. Linux 安装 ADB
```shell
sudo apt update
sudo apt install -y wget adb
```
3.3. Windows 安装 ADB
win 上安装需要去谷歌的安卓平台下载 ADB 软件包进行安装:[链接](https://developer.android.com/studio)
打开终端,手机连接电脑,在终端中输入
```shell
adb devices
```
如果有 device 输出,则表示安装成功。
```shell
List of devices attached
744be294 device
```
### 物料准备
1. 克隆 `Paddle-Lite-Demo` 仓库的 `feature/paddle-x` 分支到 `PaddleX-Lite-Deploy` 目录。
```shell
git clone -b feature/paddle-x https://github.com/PaddlePaddle/Paddle-Lite-Demo.git PaddleX-Lite-Deploy
```
2. 填写 [问卷](https://paddle.wjx.cn/vm/eaaBo0H.aspx#) 下载压缩包,将压缩包放到指定解压目录,切换到指定解压目录后执行解压命令。
```shell
# 1. 切换到指定解压目录
cd PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo
# 2. 执行解压命令
unzip ocr.zip
```
### 部署步骤
1. 将工作目录切换到 `PaddleX-Lite-Deploy/libs` 目录,运行 `download.sh` 脚本,下载需要的 Paddle Lite 预测库。此步骤只需执行一次,即可支持每个 demo 使用。
2. 将工作目录切换到 `PaddleX-Lite-Deploy/ocr/assets` 目录,运行 `download.sh` 脚本,下载 [paddle_lite_opt 工具](https://www.paddlepaddle.org.cn/lite/v2.10/user_guides/model_optimize_tool.html) 优化后的 nb 模型文件及预测图片、字典文件等物料。
3. 将工作目录切换到 `PaddleX-Lite-Deploy/ocr/android/shell/cxx/ppocr_demo` 目录,运行 `build.sh` 脚本,完成可执行文件的编译。
4. 将工作目录切换到 `PaddleX-Lite-Deploy/ocr/android/shell/cxx/ppocr_demo`,运行 `run.sh` 脚本,完成在端侧的预测。
**注意事项:**
- 在运行 `build.sh` 脚本前,需要更改 `NDK_ROOT` 指定的路径为实际安装的 NDK 路径。
- 在 Windows 系统上可以使用 Git Bash 执行部署步骤。
- 若在 Windows 系统上编译,需要将 `CMakeLists.txt` 中的 `CMAKE_SYSTEM_NAME` 设置为 `windows`。
- 若在 Mac 系统上编译,需要将 `CMakeLists.txt` 中的 `CMAKE_SYSTEM_NAME` 设置为 `darwin`。
- 在运行 `run.sh` 脚本时需保持 ADB 连接。
- `download.sh` 和 `run.sh` 支持传入参数来指定模型,若不指定则默认使用 `PP-OCRv5_mobile` 模型。目前适配了以下模型:
- `PP-OCRv3_mobile`
- `PP-OCRv4_mobile`
- `PP-OCRv5_mobile`
以下为实际操作时的示例:
```shell
# 1. 下载需要的 Paddle Lite 预测库
cd PaddleX-Lite-Deploy/libs
sh download.sh
# 2. 下载 paddle_lite_opt 工具优化后的 nb 模型文件及预测图片、字典文件等物料
cd ../ocr/assets
sh download.sh PP-OCRv5_mobile
# 3. 完成可执行文件的编译
cd ../android/shell/ppocr_demo
sh build.sh
# 4. 预测
sh run.sh PP-OCRv5_mobile
```
运行结果如下所示:
```text
The detection visualized image saved in ./test_img_result.jpg
0 纯臻营养护发素 0.998541
1 产品信息/参数 0.999094
2 (45元/每公斤,100公斤起订) 0.948841
3 每瓶22元,1000瓶起订) 0.961245
4 【品牌】:代加工方式/OEMODM 0.970401
5 【品名】:纯臻营养护发素 0.977496
6 ODMOEM 0.955396
7 【产品编号】:YM-X-3011 0.977864
8 【净含量】:220ml 0.970538
9 【适用人群】:适合所有肤质 0.995907
10 【主要成分】:鲸蜡硬脂醇、燕麦β-葡聚 0.975813
11 糖、椰油酰胺丙基甜菜碱、泛醌 0.964397
12 (成品包材) 0.97298
13 【主要功能】:可紧致头发磷层,从而达到 0.989097
14 即时持久改善头发光泽的效果,给干燥的头 0.990088
15 发足够的滋养 0.998037
```
![预测结果](https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/pipeline_deploy/edge_PP-OCRv5_mobile.jpg)
## 代码介绍
```
.
├── ...
├── ocr
│ ├── ...
│ ├── android
│ │ ├── ...
│ │ └── shell
│ │ └── ppocr_demo
│ │ ├── src # 存放预测代码
│ │ | ├── cls_process.cc # 方向分类器的推理全流程,包含预处理、预测和后处理三部分
│ │ | ├── rec_process.cc # 识别模型 CRNN 的推理全流程,包含预处理、预测和后处理三部分
│ │ | ├── det_process.cc # 检测模型 CRNN 的推理全流程,包含预处理、预测和后处理三部分
│ │ | ├── det_post_process.cc # 检测模型 DB 的后处理文件
│ │ | ├── pipeline.cc # OCR 文字识别 demo 推理全流程代码
│ │ | └── MakeFile # 预测代码的 MakeFile 文件
│ │ |
│ │ ├── CMakeLists.txt # CMake 文件,约束可执行文件的编译方法
│ │ ├── README.md
│ │ ├── build.sh # 用于可执行文件的编译
│ │ └── run.sh # 用于预测
│ └── assets # 存放模型、测试图片、标签文件、config 文件
│ ├── images # 存放测试图片
│ ├── labels # 存放字典文件,更多详情可参考下文备注
│ ├── models # 存放 nb 模型
│ ├── config.txt
│ └── download.sh # 下载脚本,用于下载 paddle_lite_opt 工具优化后的模型
└── libs # 存放不同端的预测库和 OpenCV 库。
├── ...
└── download.sh # 下载脚本,用于下载 Paddle Lite 预测库和 OpenCV 库
```
**备注:**
- `PaddleX-Lite-Deploy/ocr/assets/labels/` 目录下存放了 PP-OCRv3、PP-OCRv4 模型的字典文件 `ppocr_keys_v1.txt` 以及 PP-OCRv5 模型的字典文件 `ppocr_keys_ocrv5.txt`。在实际推理过程中,会根据模型名称自动选择相应的字典文件,因此无需手动干预。
- 如果使用的 nb 模型是英文数字或其他语言的模型,需要更换为对应语言的字典。PaddleOCR 仓库提供了[部分字典文件](../../../ppocr/utils)。
```shell
# run.sh 脚本中可执行文件的参数含义:
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
第一个参数:ppocr_demo 可执行文件
第二个参数:./models/${MODEL_NAME}_det.nb 检测模型的.nb文件
第三个参数:./models/${MODEL_NAME}_rec.nb 识别模型的.nb文件
第四个参数:./models/${CLS_MODEL_FILE} 文本行方向分类模型的.nb文件,默认根据模型名自动选择
第五个参数:./images/test.jpg 测试图片
第六个参数:./test_img_result.jpg 结果保存文件
第七个参数:./labels/${LABEL_FILE} label 文件,默认根据模型名自动选择
第八个参数:./config.txt 配置文件,模型的超参数配置文件,包含了检测器、分类器的超参数
```
```shell
# config.txt 具体参数 List:
max_side_len 960 # 输入图像长宽大于 960 时,等比例缩放图像,使得图像最长边为 960
det_db_thresh 0.3 # 用于过滤 DB 预测的二值化图像,设置为 0.3 对结果影响不明显
det_db_box_thresh 0.5 # DB 后处理过滤 box 的阈值,如果检测存在漏框情况,可酌情减小
det_db_unclip_ratio 1.6 # 表示文本框的紧致程度,越小则文本框更靠近文本
use_direction_classify 0 # 是否使用方向分类器,0 表示不使用,1 表示使用
```
## 工程详解
OCR 文字识别 demo 由三个模型一起完成 OCR 文字识别功能,对输入图片先通过 `${MODEL_NAME}_det.nb` 模型做检测处理,然后通过 `ch_ppocr_mobile_v2.0_cls_slim_opt.nb` 模型做文字方向分类处理,最后通过 `${MODEL_NAME}_rec.nb` 模型完成文字识别处理。
1. `pipeline.cc` : OCR 文字识别 demo 预测全流程代码
该文件完成了三个模型串行推理的全流程控制处理,包含整个处理过程的调度处理。
- `Pipeline::Pipeline(...)` 方法完成调用三个模型类构造函数,完成模型加载和线程数、绑核处理及 predictor 创建处理
- `Pipeline::Process(...)` 方法用于完成这三个模型串行推理的全流程控制处理
2. `cls_process.cc` 方向分类器的预测文件
该文件完成了方向分类器的预处理、预测和后处理过程
- `ClsPredictor::ClsPredictor()` 方法用于完成模型加载和线程数、绑核处理及 predictor 创建处理
- `ClsPredictor::Preprocess()` 方法用于模型的预处理
- `ClsPredictor::Postprocess()` 方法用于模型的后处理
3. `rec_process.cc` 识别模型 CRNN 的预测文件
该文件完成了识别模型 CRNN 的预处理、预测和后处理过程
- `RecPredictor::RecPredictor()` 方法用于完成模型加载和线程数、绑核处理及 predictor 创建处理
- `RecPredictor::Preprocess()` 方法用于模型的预处理
- `RecPredictor::Postprocess()` 方法用于模型的后处理
4. `det_process.cc` 检测模型 DB 的预测文件
该文件完成了检测模型 DB 的预处理、预测和后处理过程
- `DetPredictor::DetPredictor()` 方法用于完成模型加载和线程数、绑核处理及 predictor 创建处理
- `DetPredictor::Preprocess()` 方法用于模型的预处理
- `DetPredictor::Postprocess()` 方法用于模型的后处理
5. `db_post_process` 检测模型 DB 的后处理函数,包含 clipper 库的调用
该文件完成了检测模型 DB 的第三方库调用和其他后处理方法实现
- `std::vector<std::vector<std::vector<int>>> BoxesFromBitmap(...)` 方法从 Bitmap 图中获取检测框
- `std::vector<std::vector<std::vector<int>>> FilterTagDetRes(...)` 方法根据识别结果获取目标框位置
## 进阶使用
如果快速开始部分无法满足你的需求,可以参考本节对 demo 进行自定义修改。
本节主要包含四部分:
- 更新预测库;
- 转换 `.nb` 模型;
- 更新模型、标签文件和预测图片;
- 更新输入/输出预处理。
### 更新预测库
本指南所使用的预测库为最新版本(214rc),不推荐自行更新预测库。
若有使用其他版本的需求,可参考如下步骤更新预测库:
* Paddle Lite 项目:https://github.com/PaddlePaddle/Paddle-Lite
* 参考 [Paddle Lite 源码编译文档](https://www.paddlepaddle.org.cn/lite/develop/source_compile/compile_env.html),编译 Android 预测库
* 编译最终产物位于 `build.lite.xxx.xxx.xxx` 下的 `inference_lite_lib.xxx.xxx`
* 替换 c++ 库
* 头文件
将生成的 `build.lite.android.xxx.gcc/inference_lite_lib.android.xxx/cxx/include` 文件夹替换 demo 中的 `PaddleX-Lite-Deploy/libs/android/cxx/include`
* armeabi-v7a
将生成的 `build.lite.android.armv7.gcc/inference_lite_lib.android.armv7/cxx/libs/libpaddle_lite_api_shared.so` 库替换 demo 中的 `PaddleX-Lite-Deploy/libs/android/cxx/libs/armeabi-v7a/libpaddle_lite_api_shared.so`
* arm64-v8a
将生成的 `build.lite.android.armv8.gcc/inference_lite_lib.android.armv8/cxx/libs/libpaddle_lite_api_shared.so` 库替换 demo 中的 `PaddleX-Lite-Deploy/libs/android/cxx/libs/arm64-v8a/libpaddle_lite_api_shared.so`
### 转换 .nb 模型
若想使用自己训练的模型,可先参考以下流程得到 `.nb` 模型。
#### 终端命令方法(支持Mac/Ubuntu)
1. 进入Paddle-Lite Github仓库的[release界面](https://github.com/PaddlePaddle/Paddle-Lite/releases),选择所需版本下载对应的转化工具opt(推荐使用最新版本)。
2. 下载 opt 工具后,执行以下命令(此处以 2.14rc 版本的 linux_x86 opt 工具转换 PP-OCRv5_mobile_det 模型为例):
```bash
./opt_linux_x86 \
--model_file=PP-OCRv5_mobile_det/inference.pdmodel \
--param_file=PP-OCRv5_mobile_det/inference.pdiparams \
--optimize_out=PP-OCRv5_mobile_det \
--valid_targets=arm
```
有关使用终端命令方法转换 `.nb` 模型的详细介绍,可参考 Paddle-Lite 仓库的[使用可执行文件 opt](https://www.paddlepaddle.org.cn/lite/v2.12/user_guides/opt/opt_bin.html)。
#### python 脚本方法(支持Windows/Mac/Ubuntu)
1. 安装最新版本的 paddlelite wheel 包。
```bash
pip install --pre paddlelite
```
2. 使用 python 脚本进行模型转换。以下为转换 PP-OCRv5_mobile_det 模型的示例代码:
```python
from paddlelite.lite import Opt
# 1. 创建opt实例
opt = Opt()
# 2. 指定输入模型地址
opt.set_model_file("./PP-OCRv5_mobile_det/inference.pdmodel")
opt.set_param_file("./PP-OCRv5_mobile_det/inference.pdiparams")
# 3. 指定转化类型
opt.set_valid_places("arm")
# 4. 指定输出模型地址
opt.set_optimize_out("./PP-OCRv5_mobile_det")
# 5. 执行模型优化
opt.run()
```
有关使用 python 脚本方法转换 `.nb` 模型的详细介绍,可参考 Paddle-Lite 仓库的[使用 Python 脚本 opt](https://www.paddlepaddle.org.cn/lite/v2.12/api_reference/python_api/opt.html)。
**注意**
- 有关模型优化工具 opt 的详细介绍,可参考 Paddle-Lite 仓库的[模型优化工具 opt](https://www.paddlepaddle.org.cn/lite/v2.12/user_guides/model_optimize_tool.html)
- 目前仅支持将 `.pdmodel` 格式的静态图模型转换为 `.nb` 格式。在 PaddlePaddle 3.0 以上的版本,默认导出为 `.json` 的模型,如果希望导出为 `.pdmodel` 格式的模型,导出时加上 `-o Global.export_with_pir=False` 即可。
### 更新模型、标签文件和预测图片
#### 更新模型
本指南只对 `PP-OCRv3_mobile`、`PP-OCRv4_mobile`、`PP-OCRv5_mobile` 模型进行了验证,其他模型不保证适用性。
如果你对 `PP-OCRv5_mobile` 模型进行了微调,并生成了一个名为 `PP-OCRv5_mobile_ft` 的新模型,可以按照以下步骤将原有模型替换为你的微调模型:
1. 将 `PP-OCRv5_mobile_ft` 的 nb 模型存放到目录 `PaddleX-Lite-Deploy/ocr/assets/models/` 下,最终得到的文件结构如下:
```text
.
├── ocr
│ ├── ...
│ └── assets
│ ├── models
│ │ ├── ...
│ │ ├── PP-OCRv5_mobile_ft_det.nb
│ │ └── PP-OCRv5_mobile_ft_rec.nb
│ └── ...
└── ...
```
2. 将模型名加入到 `run.sh` 脚本中的 `MODEL_LIST`。
```shell
MODEL_LIST="PP-OCRv3_mobile PP-OCRv4_mobile PP-OCRv5_mobile PP-OCRv5_mobile_ft" # 模型之间以单个空格为间隔
```
3. 运行 `run.sh` 脚本时使用模型目录名。
```shell
sh run.sh PP-OCRv5_mobile_ft
```
**注意:**
- 如果更新模型中的输入 Tensor、Shape、和 Dtype 发生更新:
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/cls_process.cc` 中 `ClsPredictor::Preprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/det_process.cc` 中 `DetPredictor::Preprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/rec_process.cc` 中 `RecPredictor::Preprocss` 函数
- 如果更新模型中的输出 Tensor 和 Dtype 发生更新:
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/cls_process.cc` 中 `ClsPredictor::Postprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/det_process.cc` 中 `DetPredictor::Postprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/rec_process.cc` 中 `RecPredictor::Postprocss` 函数
#### 更新标签文件
如果需要更新标签文件,则需要将新的标签文件存放在目录 `PaddleX-Lite-Deploy/ocr/assets/labels/` 下,并参考模型更新方法更新 `PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo/run.sh` 中执行命令;
以更新 `new_labels.txt` 为例:
```shell
# 代码文件 `PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo/run.sh`
# old
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
# update
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/new_labels.txt \
./config.txt"
```
#### 更新预测图片
如果需要更新预测图片,将更新的图片存放在 `PaddleX-Lite-Deploy/ocr/assets/images/` 下,更新文件 `PaddleX-Lite-Deploy/ocr/android/shell/ppocr_demo/rush.sh` 中执行命令;
以更新 `new_pics.jpg` 为例:
```shell
# 代码文件 `PaddleX-Lite-Deploy/ocr/assets/images/run.sh`
## old
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"./models/${MODEL_NAME}_rec.nb\" \
./models/${CLS_MODEL_FILE} \
./images/test.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
# update
adb shell "cd ${ppocr_demo_path} \
&& chmod +x ./ppocr_demo \
&& export LD_LIBRARY_PATH=${ppocr_demo_path}:${LD_LIBRARY_PATH} \
&& ./ppocr_demo \
\"./models/${MODEL_NAME}_det.nb\" \
\"\"./models/${MODEL_NAME}_rec.nb\"\" \
./models/${CLS_MODEL_FILE} \
./images/new_pics.jpg \
./test_img_result.jpg \
./labels/${LABEL_FILE} \
./config.txt"
```
### 更新输入/输出预处理
- 更新输入预处理
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/cls_process.cc` 中 `ClsPredictor::Preprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/det_process.cc` 中 `DetPredictor::Preprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/rec_process.cc` 中 `RecPredictor::Preprocss` 函数
- 更新输出预处理
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/cls_process.cc` 中 `ClsPredictor::Postprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/det_process.cc` 中 `DetPredictor::Postprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/rec_process.cc` 中 `RecPredictor::Postprocss` 函数
@@ -60,6 +60,10 @@ The following table describes the methods and parameters related to pipeline inf
Create a `test_infer.py` script:
```python
import os
os.environ["PADDLE_PDX_PIPELINE_BENCHMARK"] = "True"
from paddleocr import PaddleOCR, benchmark
pipeline = PaddleOCR()
@@ -80,7 +84,7 @@ benchmark.save_pipeline_data("./benchmark") # Save benchmark data to the benchma
Execute the script:
```bash
PADDLE_PDX_PIPELINE_BENCHMARK=True python test_infer.py
python test_infer.py
```
The benchmark results obtained from running the example program are as follows:
@@ -60,6 +60,10 @@ Benchmark 功能会统计产线在端到端推理过程中,所有操作的平
创建 `test_infer.py` 脚本:
```python
import os
os.environ["PADDLE_PDX_PIPELINE_BENCHMARK"] = "True"
from paddleocr import PaddleOCR, benchmark
pipeline = PaddleOCR()
@@ -80,7 +84,7 @@ benchmark.save_pipeline_data("./benchmark") # 将benchmark数据保存至benchma
执行脚本:
```bash
PADDLE_PDX_PIPELINE_BENCHMARK=True python test_infer.py
python test_infer.py
```
运行示例程序所得到的 benchmark 结果如下:
+1 -1
View File
@@ -8,7 +8,7 @@ comments: true
This section explains how to install, as needed, the `paddleocr` distribution package, optional dependency groups by capability domain, and the inference engine. This path covers running pretrained pipelines for inference locally, as well as auxiliary features such as document format conversion. **Model training and model export** are covered in Section 2 and are independent of the installation path above.
**Python version requirement**: `paddleocr` itself and the `doc2md` dependency group support Python 3.8 and later. The other optional dependency groups (`doc-parser`, `ie`, `trans`, `all`) require Python 3.9 or later due to upstream dependencies.
**Python version requirement**: `paddleocr` itself and the `doc2md` dependency group support Python 3.8 and later. The other optional dependency groups (`doc-parser`, `ie`, `trans`, `all`, etc.) require Python 3.9 or later due to upstream dependencies.
### 1.1 Install paddleocr
+1 -1
View File
@@ -8,7 +8,7 @@ comments: true
本节说明如何按需安装`paddleocr` 分发包,按能力域启用的可选依赖组,以及安装推理引擎。这条路径适用于在本地调用预训练产线完成推理,或是使用文档格式转换等辅助功能。**模型训练与模型导出**见第 2 节,与上述安装路径相互独立。
**Python 版本要求**:`paddleocr` 本体与 `doc2md` 依赖组支持 Python 3.8 及以上;其他可选依赖组(`doc-parser`、`ie`、`trans`、`all`)受上游依赖限制,需要 Python 3.9 及以上。
**Python 版本要求**:`paddleocr` 本体与 `doc2md` 依赖组支持 Python 3.8 及以上;其他可选依赖组(`doc-parser`、`ie`、`trans`、`all` 等)受上游依赖限制,需要 Python 3.9 及以上。
### 1.1 安装 `paddleocr` {#install-paddleocr}
@@ -19,8 +19,6 @@ PaddleOCR provides a lightweight [Model Context Protocol (MCP)](https://modelcon
| `PP-StructureV3` | `pp_structurev3` | Identifies and extracts text blocks, titles, paragraphs, images, tables, and other layout elements from images or PDF files, converting the input into Markdown documents. |
| `PaddleOCR-VL Series` | `paddleocr_vl` | Performs layout parsing with a VLM-based approach and converts the input into Markdown documents. Includes versions: PaddleOCR-VL, PaddleOCR-VL-1.5, and PaddleOCR-VL-1.6. |
> Each MCP server instance exposes exactly one MCP tool.
- **Supported Inference Methods**
- **Local Inference**: Runs PaddleOCR pipelines directly on the local machine. This method has certain requirements for the local environment and hardware performance, and is suitable for offline use and scenarios with strict data privacy requirements.
- **Official API**: Invokes the PaddleOCR Official API. This method is suitable for quickly trying out features, validating solutions, and other no-code development scenarios.
@@ -19,8 +19,6 @@ PaddleOCR 提供轻量级的 [Model Context Protocol(MCP)](https://modelcont
| `PP-StructureV3` | `pp_structurev3` | 从图像或 PDF 文件中识别和提取文本块、标题、段落、图片、表格以及其他版面元素,将输入转换为 Markdown 文档。 |
| `PaddleOCR-VL 系列` | `paddleocr_vl` | 使用基于多模态大模型的方案进行版面解析,将输入转换为 Markdown 文档。包含版本:PaddleOCR-VL、PaddleOCR-VL-1.5、PaddleOCR-VL-1.6。 |
> 每个 MCP 服务器实例对外只暴露一个 MCP 工具。
- **支持的推理方式**
- **本地推理**:在本机直接运行 PaddleOCR 产线。此方式对本地环境与计算机性能有一定要求,适用于需要离线使用、对数据隐私有严格要求的场景。
- **官方 API**:调用 PaddleOCR 官方提供的 API。此方式适合快速体验功能、快速验证方案等,也适用于零代码开发场景。
+2 -3
View File
@@ -138,8 +138,8 @@ plugins:
高性能推理: High-Performance Inference
打包 PaddleOCR 项目: Package PaddleOCR Projects
获取ONNX模型: Obtaining ONNX Models
端侧部署: On-Device Deployment
Android 部署: Android Deployment
iOS 部署: iOS Deployment
服务化部署: Serving
浏览器端部署: Browser Deployment
模块列表: Module List
@@ -195,7 +195,6 @@ plugins:
基于C++预测引擎推理: CPP Inference
Visual Studio 2019 Community CMake 编译指南: Visual Studio 2019 Community CMake Compilation Guide
服务化部署: Server Deployment
端侧部署: On-Device Deployment
Android部署: Android Deployment
Paddle2ONNX模型转化与预测: Paddle2ONNX
云上飞桨部署工具: Paddle Cloud
@@ -362,8 +361,8 @@ nav:
- Go SDK: version3.x/inference_deployment/serving/paddleocr_official_api/go.md
- CLI: version3.x/inference_deployment/serving/paddleocr_official_api/cli.md
- 跨端部署:
- 端侧部署: version3.x/inference_deployment/cross_platform/on_device_deployment.md
- Android 部署: version3.x/inference_deployment/cross_platform/android_deployment.md
- iOS 部署: version3.x/inference_deployment/cross_platform/ios_deployment.md
- 浏览器端部署: version3.x/inference_deployment/cross_platform/browser.md
- 其它:
- 获取ONNX模型: version3.x/inference_deployment/others/obtaining_onnx_models.md
+1
View File
@@ -31,6 +31,7 @@ SUPPORTED_INFERENCE_ENGINE_LIST = [
"paddle_static",
"paddle_dynamic",
"transformers",
"onnxruntime",
]