桌面端的中文票据识别一直不太行:tesseract 会把字距拆开,表格线和编号也常丢。鸿蒙设备上有一套离线、中文效果更好的 Core Vision Kit,但 Electron 过不去:上游没有 HarmonyOS 运行时,系统 OCR 又只对 ArkTS 开放。这个库绕开的办法是把图片用 hdc 送进设备上一个零权限 agent 的沙箱,让它在设备上识别,再把 JSON 拉回桌面;没有设备、或者设备识别失败,就退回本机 tesseract。桌面和设备的交界只有 job id、envelope 和一份
OcrResult。
仓库地址:https://atomgit.com/lqjmac/electron-ohos-ocr
版本地址:https://atomgit.com/CPF-Electron
三方库框架:https://atomgit.com/oh-tpc
0. 环境与实测设备
三方库适配信息:
| 三方库 | Electron 版本 | 鸿蒙化版本 | 仓库地址 | 社区 | 社区地址 |
|---|---|---|---|---|---|
| electron-ohos-ocr | v40.1.0 | 6.0.0(20) | https://atomgit.com/lqjmac/electron-ohos-ocr | CPF-Electron 鸿蒙社区 | https://atomgit.com/CPF-Electron |
实测环境:
| 项 | 版本/型号 |
|---|---|
| Electron | v40.1.0(peer 依赖 >= 20,库核心也支持纯 Node 18+) |
| Node.js | 18+ |
| DevEco Studio | 5.x+(自带 hdc 工具链与 hvigor;构建 agent HAP 用) |
| 实测设备 | HarmonyOS 2in1 模拟器(127.0.0.1:5555,3120×2080),OpenHarmony 7.0.0.105,API 26;414 ms 那次更早运行没有记录设备型号 |
| 设备能力基线 | Core Vision Kit textRecognition 自 API 12 可用;agent 工程 compatibleSdkVersion 5.0.5(17)、targetSdkVersion 6.0.0(20) |
| hdc | DevEco Studio SDK toolchains 自带;需支持 -b 沙箱传文件与 aa start --ps |
| local 后端 | tesseract.js(WASM,主进程运行;首次使用时下载语言数据) |
| 测试 | vitest 4 个文件 56 项全过(后端选择、hdc 协议解析、tesseract 映射、模型契约;子进程与 worker 全 mock,不需要真机) |
表里的测试数和构建输出来自仓库验证记录(2026-11-13)。那天的机器是 macOS arm64,Node 24.12.0、npm 11.12.1、TypeScript 5.9.3、Vitest 3.2.7;鸿蒙侧用 DevEco Studio 自带的 hvigor 和 API 26 SDK,hdc 连的是 127.0.0.1:5555 的 2in1 模拟器。下面的日志、错误码和命令输出都能在那份记录或源码里对上,没有补写“应该能跑”的结论。
1. 414 ms 那张图,和后来那个 1001400001

这张图拍的是设备代理页,桌面应用在另一头。414 ms 是设备上的读数,触发者却在桌面:窗口底部一行写着 Triggered from Electron via: hdc shell aa start --ps job <id>。标题栏 ElectronOcrAgent,副标题 vision-on-device · Core Vision Kit (API 12+),右上角 status installed、last job none;左边是刚被识别的整屏截图,右边第一行 55 blocks · 414 ms · 3120×2080 px,下面 55 条编号文本,连目录树里的 ✓C harmonyos、{} oh-package-lock.js、oh-package.json5 都抓出来了。按钮 Photo picker smoke test 旁边写着 done in 414 ms。识别由桌面应用通过 hdc 拉起 Ability 触发,设备上没有人去点按钮。
截图那次运行比 11 月 13 日的验证记录早。仓库当前版本的代理页已经换成中文界面(代理页截图),后来在 2in1 模拟器上,图能解码、Ability 能起、envelope 能写回来,recognizeText 却返回 1001400001。桌面 auto 回退本机 Tesseract,最终 tesseract-local、7 行、237 ms,状态栏写“设备已连接,但端侧识别失败,已回退本机”。协议没变,变的是设备镜像里有没有 OCR 模型。414 ms 那次每个环节都返回成功;1001400001 这一次,失败落在哪一段,得把探测和识别分开看。
2. 各个目录放什么

仓库顶层是 src/、test/、example/、ohos/ 和文档目录;ohos/library 是设备侧 HAR,ohos/example 是代理 HAP,test/ 是 56 项 vitest,example/ 是桌面“取字”工作台。
3. 从推图到收回 JSON,难的是边界
一次 device 识别的完整数据流都在这张图里(hdc 命令一览详见架构文档;图里的 …/files 指 ./data/storage/el2/base/haps/entry/files):
┌──────────────────── Electron 桌面应用(Main 进程) ────────────────────┐
│ OhosOcrEngine(prefer: 'auto') │
│ ├─ device 后端:spawn hdc(argv 数组,无 shell 插值) │
│ └─ local 后端:tesseract.js worker(主进程) │
└──────────────────────────────┬────────────────────────────────────────┘
│ USB / 网络
┌──────────────────────────────▼────────────────────────────────────────┐
│ 鸿蒙设备 / 模拟器(API 12+) com.ohos.electronocr.agent │
│ ① hdc file send -b <bundle> 本地.png …/files/ocr/in/<job>.png │
│ ② hdc shell aa start -b <bundle> -a OcrAgentAbility │
│ --ps job <id> --ps lang CHINESE │
│ └─ 设备侧:读图 → textRecognition.recognizeText │
│ → 写 ocr/out/<job>.json → 删图 → 自退出 │
│ ③ hdc file recv -b <bundle> …/ocr/out/<job>.json 本地.json(轮询) │
└────────────────────────────────────────────────────────────────────────┘
验证记录里的命令长这样:
hdc file send -b com.ohos.electronocr.agent \
image.png ./data/storage/el2/base/haps/entry/files/ocr/in/probe002.png
hdc shell aa start -b com.ohos.electronocr.agent -a OcrAgentAbility \
--ps job probe002 --ps lang CHINESE
hdc file recv -b com.ohos.electronocr.agent \
./data/storage/el2/base/haps/entry/files/ocr/out/probe002.json result.json
-b 把远端路径解释成 bundle 沙箱相对路径,不需要 run-as,也不需要设备 root。job id 由 crypto.randomUUID() 去掉横线后取前 16 位,既当文件名又当 --ps 参数;桌面端在 startAgent 里用 ^[0-9a-z-]{8,64}$ 校验一次,agent 拿到什么就用什么拼路径,不再校验第二遍。校验放在发起方,是因为 job id 只由库生成,agent 再多查一遍,反而要多维护一份正则。并发任务因此不会串台:轮询只认自己那个 <job>.json。
目录约定只有两级:filesDir/ocr/in/<job>.png 和 filesDir/ocr/out/<job>.json。桌面不拼绝对路径,只拼 ./data/storage/el2/base/haps/entry/files 这个沙箱相对前缀,剩下的交给 -b。默认值是 entry 模块的 filesDir;换成 HAR、feature 模块或别的 bundle 时它可能变,sandboxFilesDir 就是为这个留的覆盖项。job id 取代原文件名,有三个实际原因:同一张 receipt.png 可以连续识别多次,不会互相覆盖;--ps 只接受短字符串,16 位十六进制比中文文件名安全;原文件名只用于界面展示,设备端不需要知道它。
HdcRunner.run 用 spawn(hdcPath, argv),路径、bundle、job id 全是独立的 argv 元素。图片路径来自拖拽或文件选择,如果拼进 shell 字符串,一个带空格或分号的文件名就能多带一个参数。库内没有一处 exec 或 shell: true,-t <target> 也先在 buildArgs 里拼成数组再交给 spawn。硬超时到点直接 SIGKILL,避免一个挂死的 hdc 拖住主进程。
pushImage 并不只是给 file send 套个壳。agent 刚装上、一次都没跑过时,hdc file send -b 会失败,错误固定有两种:“Invalid bundle name”(hdc 还认不得这个 bundle)和“no such file or directory”(agent 创建的 ocr/in、ocr/out 还没出现)。两种都意味着沙箱是冷的,代码的处理是先做一次“报废的 aa start”把目录焐出来,再重试一次:
// src/backends/device-backend.ts · pushImage()
/** Step 1: `hdc file send -b` into the agent sandbox. */
async pushImage(localPath: string, jobId: string): Promise<void> {
const remote = this.remoteInPath(jobId);
const run = await this.guard('file send', () =>
this.runner.run(
['file', 'send', '-b', this.agentBundle, localPath, remote],
this.commandTimeoutMs,
),
);
if (run.code !== 0 || /fail|error/i.test(run.stdout + run.stderr)) {
if (isBundleMissing(run.stdout, run.stderr)) {
throw new OcrError(
'AGENT_NOT_INSTALLED',
`Agent "${this.agentBundle}" is not installed — build ohos/ in DevEco Studio and run: hdc install ohos/example/build/default/outputs/default/entry-default-signed.hap`,
);
}
if (isSandboxCold(run.stdout, run.stderr, this.sandboxFilesDir)) {
await this.warmupSandbox();
const retry = await this.guard('file send (retry)', () =>
this.runner.run(
['file', 'send', '-b', this.agentBundle, localPath, remote],
this.commandTimeoutMs,
),
);
if (retry.code === 0 && !/fail|error/i.test(retry.stdout + retry.stderr)) {
return;
}
throw new OcrError(
'BACKEND_FAILED',
`hdc file send failed (${retry.code}) after sandbox warmup: ${(retry.stderr || retry.stdout).trim()}`,
);
}
throw new OcrError(
'BACKEND_FAILED',
`hdc file send failed (${run.code}): ${(run.stderr || run.stdout).trim()}`,
);
}
}
isSandboxCold 只看两个特征,不猜别的错误:
// src/backends/device-backend.ts
/**
* True when a `hdc file send -b` failure means the agent sandbox is cold:
* hdc reports "Invalid bundle name" until the app has run at least once,
* and "no such file or directory" while the agent-created `ocr/in` and
* `ocr/out` directories do not exist yet. Both are fixable by one
* throwaway `aa start` (see {@link DeviceOcrBackend.warmupSandbox}).
*/
export function isSandboxCold(stdout: string, stderr: string, sandboxFilesDir: string): boolean {
const text = `${stdout}\n${stderr}`;
if (/invalid bundle name/i.test(text)) {
return true;
}
return /no such file or directory/i.test(text) && text.includes(sandboxFilesDir);
}
warmupSandbox 用 boot 加新 job id 起一次 Ability,然后在 15 秒内轮询 ocr/out/boot<id>.json。文件出现说明目录已经建好,信封内容直接忽略;aa start 自己失败或者轮询超时,它会清掉缓存的 promise、抛 BACKEND_FAILED,下一次识别重新焐,一次冷启动失败不会被记成永久状态。第一次识别和第一百次识别的用户路径因此一样,代价只是第一次多一次 Ability 启动。把“焐热”写进协议、不写进文档,是我在这条链路上做得最对的一个决定。
第三封信由 collectResult 负责:
// src/backends/device-backend.ts · collectResult()
/**
* Step 3: polls `hdc file recv -b` until the agent result file exists,
* then parses the envelope. Rejects with `AGENT_TIMEOUT` on deadline.
*/
async collectResult(jobId: string): Promise<AgentEnvelope> {
const remote = this.remoteOutPath(jobId);
const localPath = path.join(os.tmpdir(), `electron-ohos-ocr-${jobId}.json`);
const deadline = Date.now() + this.agentTimeoutMs;
let lastError = '';
for (;;) {
const run = await this.guard('file recv', () =>
this.runner.run(['file', 'recv', '-b', this.agentBundle, remote, localPath], 15000),
);
if (run.code === 0 && this.fileOps.existsSync(localPath)) {
break;
}
lastError = (run.stderr || run.stdout).trim();
if (Date.now() >= deadline) {
throw new OcrError(
'AGENT_TIMEOUT',
`Agent did not write ${remote} within ${this.agentTimeoutMs} ms (last hdc error: ${lastError})`,
);
}
await sleep(this.pollIntervalMs);
}
try {
const raw = this.fileOps.readFileSync(localPath);
return parseAgentEnvelope(raw, jobId);
} finally {
try {
this.fileOps.removeFileSync(localPath);
} catch {
// Best effort only.
}
}
}
轮询间隔 500 ms,总超时 60 秒,单条 file recv 自己还有 15 秒上限;命令超时和等待结果超时是两回事。前者是某条 hdc 卡住,抛 BACKEND_FAILED;后者是 agent 没写文件,抛 AGENT_TIMEOUT。前者通常重试命令能过,后者要去看 hilog 里 agent 有没有起来。只有 run.code === 0 且本地临时文件真的出现才跳出循环;否则到点抛 AGENT_TIMEOUT,message 里带上最后一次 hdc 的 stderr,排查时不用再猜是“文件没写”还是“路径不对”。解析出来的 envelope 无论成败都会在 finally 里删掉本地临时文件。file send 用 30 秒的默认上限,aa start 和 warmup 只给 15 秒。拉起 Ability 正常在一秒内返回,真卡住时多等 15 秒也不会好。
成功和失败各长这样:
{
"ok": true,
"job": "<job>",
"backend": "vision-kit",
"result": {
"id": "vision-on-device",
"source": "<job>.png",
"language": "CHINESE",
"blocks": [{ "text": "有光咖啡", "confidence": 0.0 }],
"durationMs": 142
}
}
{"ok":false,"job":"probe002","error":{"code":"OCR_VISION_ERROR","message":"Failed to run OCR, please try again. (code 1001400001)"}}
桌面侧把 source 覆盖成本地文件名,界面上不会出现 job id;durationMs 是设备端 recognizeText 的墙钟时间,不含 hdc 传输。device 结果的 confidence 恒为 0.0,因为 Core Vision Kit 不返回逐行置信度,库不编数字。parseAgentEnvelope 对 ok:false 保留 agent 给的 code,对非 JSON 直接抛 AGENT_ERROR;OCR_VISION_ERROR 在 recognizeFile 里映射成 VISION_ERROR,其它 agent 错误映射成 AGENT_ERROR。
4. 设备在,模型不在
1001400001 第一次露面时,看起来像 file send 没把图推进去。手动跑一遍 probe002,责任才分清:send、start、recv 都返回成功,file recv 也真的拿到了文件,内容就是前面那封带 1001400001 的失败信封。
设备侧 hilog 把链路切得更细:
VisionOcr: pixel map decoded 1000x760
VisionOcr: vision pipeline failed: code=1001400001 message=Failed to run OCR, please try again.
ElectronOcrAgent: job probe002 failed: ... (code 1001400001)
ElectronOcrAgent: ability destroyed
日志第三行是验证记录里原样抄过来的,中间的省略号在记录时就截断了,跟 agent 的输出无关。图解码成 1000×760 了,说明沙箱路径、-b、文件读取都没问题;失败发生在 recognizeText 里面。单独试 textRecognition.init(),模拟器返回的是另一段:
VisionOcr: textRecognition.init unavailable: Run timed out, please try again later. (code 200)
我一开始把 1001400001 当成权限问题:agent 装好后第一次 aa start 没有弹窗、也没有错误页,看着像被系统拦下了。翻 module.json5 才看到 requestPermissions 是空数组,它只读自己的沙箱,系统那里没有可授权的入口。图片那条误判也一样:file recv 拿到了 JSON,说明 hdc 链路是通的,可那封 JSON 是失败信封,里面没有识别结果。
hilog 的顺序比错误码更能说明问题。pixel map decoded 先出现、vision pipeline failed 后出现,说明图已经从沙箱读出来、解码也成功,失败落在识别引擎里;如果只有 job failed 而没有 pixel map decoded,要回头查沙箱路径和 file send;如果先出现的是 init unavailable,那通常是设备没有 Core Vision Kit 服务,连识别入口都没进去。1001400001 的 message 永远是那句“Failed to run OCR, please try again.”,能区分的只有数字本身。
到这里可以对上号了:2in1 模拟器镜像能解码图片,但没有 Core Vision Kit 的 OCR 模型。协议是通的,图片格式也正常。桌面侧第一次探测仍然会把 device 判成健康:hdc 在、设备在、agent 也装了,跑起来才失败。回退只能放在识别调用这一处,启动探测拦不住这种失败。
auto 的行为是:探测到 device 就先走 device;device 中途失败,且 prefer 不为 device,就再用 local 跑一次。验证记录里的最终结果是 tesseract-local、7 行、237 ms,状态栏原文是“设备已连接,但端侧识别失败,已回退本机”。验证主机上的 doctor 输出:
[OK] hdc executable (hdc)
[OK] connected targets: 127.0.0.1:5555
[--] agent "com.ohos.electronocr.agent" installed on device
[OK] sandbox dir used by file send/recv: ./data/storage/el2/base/haps/entry/files
[OK] local tesseract.js backend
Active backend (auto): local
换成测试 bundle 后 [--] 变 [OK],最后一行变成 Active backend (auto): device。[--] 只表示这一项没通过;探测不确定是另一档,doctor 打的是 [? ]。这两种符号分开,是为了不把“没装”和“问不出来”混成同一个状态。
后端选择本身写在 getBackendInfo 里:
// src/engine.ts · getBackendInfo()
/**
* Probes both backends and reports which one `auto` would pick. Use this
* for the "backend" indicator in your UI. Never throws.
*/
async getBackendInfo(): Promise<BackendInfo> {
const device: DeviceProbe = await this.device.probe();
let localAvailable = false;
try {
localAvailable = await this.local.isAvailable();
} catch {
localAvailable = false;
}
let active: OcrBackendKind | null = null;
if (this.prefer === 'local') {
active = localAvailable ? OcrBackendKind.Local : null;
} else if (this.prefer === 'device') {
active = this.deviceHealthy(device) ? OcrBackendKind.Device : null;
} else {
active = this.deviceHealthy(device)
? OcrBackendKind.Device
: localAvailable
? OcrBackendKind.Local
: null;
}
return {
active,
prefer: this.prefer,
device: {
hdcFound: device.hdcFound,
deviceConnected: device.deviceConnected,
targets: device.targets,
agentInstalled: device.agentInstalled,
error: device.error,
},
local: localAvailable,
};
}
探测顺序是 hdc list targets → 有目标 → hdc shell bm dump -n <agentBundle>。agentInstalled 有三态:true、false、null。null 表示 dump 既没输出“不存在”也没在文本里找到 bundle 名,这时 deviceHealthy 仍然放行:探测不确定不该直接掐掉 device,失败留给识别调用去暴露。prefer: 'device' 和 'local' 是严格模式,getBackendInfo 只报告,不偷偷换路。
两个后端的差别和选中条件:
| device 后端 | local 后端 | |
|---|---|---|
| 引擎 | Core Vision Kit(API 12+,端侧离线) | tesseract.js(WASM,主进程) |
| 置信度 | 不提供,固定 0.0 | 0~100 归一化到 0~1 |
| 前置条件 | hdc + 已连接设备 + 已装 agent | 首次下载语言数据 |
| 选中条件 | hdc + target + agent 已装 | auto 兜底;prefer: 'local' 强制 |
recognizeFile 的回退写在 recognizeFileWithFallback 里(recognizeBytes 另有一份等价分支):
// src/engine.ts · recognizeFileWithFallback()
/**
* Auto-fallback recognition: tries the preferred backend first; when the
* *device* backend fails mid-run (cable unplugged, agent crash) and the
* local backend is usable, the run is retried locally once.
*/
async recognizeFileWithFallback(
imagePath: string,
options: RecognizeOptions = {},
): Promise<OcrResult> {
const backend = await this.pickBackend();
try {
return await backend.recognizeFile(imagePath, options);
} catch (error) {
if (backend.kind === OcrBackendKind.Device && this.prefer !== 'device') {
const localOk = await this.local.isAvailable().catch(() => false);
if (localOk) {
try {
return await this.local.recognizeFile(imagePath, options);
} catch (fallbackError) {
throw decorate(OcrBackendKind.Local, fallbackError);
}
}
}
throw decorate(backend.kind, error);
}
}
重试要同时满足三个条件:失败的是 device 后端、prefer 不为 device、local 的 isAvailable() 为真。local 也失败时抛出的是 local 的错误:这时用户更需要知道本机也识别不了,设备那边失败过什么已经是次要信息。非 OcrError 的异常交给 decorate 包装,device 侧给 BACKEND_FAILED,local 侧给 VISION_ERROR,上层只需要看 code。
对应的测试不碰真机,device 和 local 都是 mock:
// test/engine.test.ts · describe('mid-run fallback')
describe('mid-run fallback', () => {
it('retries locally when the device backend fails mid-run', async () => {
deviceState.available = true;
deviceState.failWith = 'cable unplugged';
const engine = new OhosOcrEngine();
const result = await engine.recognizeFileWithFallback('a.png');
expect(result.id).toBe('tesseract-local');
});
it('does not fallback when prefer is device', async () => {
deviceState.available = true;
deviceState.failWith = 'agent crash';
const engine = new OhosOcrEngine({ prefer: 'device' });
await expect(engine.recognizeFileWithFallback('a.png')).rejects.toMatchObject({
code: 'BACKEND_FAILED',
});
});
it('surfaces the device error when local is unavailable', async () => {
deviceState.available = true;
deviceState.failWith = 'agent crash';
localState.available = false;
const engine = new OhosOcrEngine();
await expect(engine.recognizeFileWithFallback('a.png')).rejects.toMatchObject({
code: 'BACKEND_FAILED',
message: expect.stringContaining('agent crash'),
});
});
});
三项断言分别覆盖“device 失败后用 local”“prefer: 'device' 不降级”“local 也不可用时暴露 device 错误”。56 项测试里,device-backend 18 项、engine 12 项、models 7 项、tesseract-backend 19 项,全部在 mock 的子进程和 worker 上跑。这也是为什么协议能改得动:改 aa start 的参数顺序,先在 test/ 里那组 argv 断言上炸掉,不用等真机。
5. 设备侧:信封先落盘,异常后抛
代理 Ability 从 Want 里读 job 和 lang,onCreate 首启和 onNewWant 复用都接住了;窗口内容 ready 后跑 runJob,跑完 terminateSelf()。onCreate 先把参数存进 pendingJob,等 onWindowStageCreate 的 loadContent 回调到了再跑;onNewWant 到来时 Ability 已经在前台,直接复用实例跑新任务。没有 job 参数的启动停在 pages/Index,那是给人手动用相册做冒烟测试的入口。
干活的是 OcrAgent:
// ohos/example/src/main/ets/ocr/OcrAgent.ets · runJob()
/**
* Runs one job end to end. Always writes the result envelope, then either
* resolves (success) or rejects with the failure that was already written.
*/
static async runJob(
context: common.UIAbilityContext,
jobId: string,
language: OcrLanguage,
): Promise<void> {
const filesDir: string = context.filesDir;
const inDir: string = `${filesDir}/ocr/in`;
const outDir: string = `${filesDir}/ocr/out`;
const inPath: string = `${inDir}/${jobId}.png`;
const outPath: string = `${outDir}/${jobId}.json`;
hilog.info(DOMAIN, TAG, 'job %{public}s start, filesDir=%{public}s', jobId, filesDir);
await OcrAgent.ensureDir(inDir);
await OcrAgent.ensureDir(outDir);
OcrAgent.pruneOutputs(outDir).catch((): void => {});
let bytes: Uint8Array;
try {
bytes = OcrAgent.readImage(inPath);
} catch (error) {
const message: string =
`Input image not found or unreadable: ${inPath} (${visionErrorMessage(error as Object)})`;
hilog.error(DOMAIN, TAG, '%{public}s', message);
await OcrAgent.writeText(
outPath,
OcrAgent.errorEnvelope(jobId, 'AGENT_INPUT_MISSING', message),
);
throw new Error(message);
}
try {
const run: VisionRun = await VisionOcr.recognizeBytes(
bytes,
`${jobId}.png`,
language,
);
await OcrAgent.writeText(outPath, OcrAgent.okEnvelope(jobId, run.result));
hilog.info(
DOMAIN, TAG,
'job %{public}s done: %{public}d blocks in %{public}d ms',
jobId, run.result.blocks.length, run.elapsedMs,
);
} catch (error) {
const message: string = visionErrorMessage(error as Object);
const failed = error as BusinessError;
const code: number =
failed === null || failed === undefined ? -1 : failed.code;
hilog.error(
DOMAIN, TAG,
'job %{public}s failed: %{public}s (code %{public}d)', jobId, message, code,
);
await OcrAgent.writeText(
outPath,
OcrAgent.errorEnvelope(jobId, 'OCR_VISION_ERROR', message),
);
throw new Error(message);
} finally {
// The image is already in memory; do not leave a copy in the sandbox
// when recognition fails (failed jobs used to accumulate inputs).
await OcrAgent.removeFile(inPath);
}
}
ensureDir 要自己逐级 mkdir,因为 fileIo.mkdir 不递归。已存在的目录返回 13900015,不算错误;其它错误会先 stat 确认类型,确实没建成目录才抛。readImage 先看 stat.size,0 字节直接失败并写 AGENT_INPUT_MISSING 信封。识别成功写 ok 信封,失败写 OCR_VISION_ERROR 信封,成功和失败都以 writeText 落盘,然后 finally 删掉输入图。
注释里那句 the host never waits for a file that will never appear 是整个设计的出发点:如果失败时不写文件,桌面会一直轮询到 AGENT_TIMEOUT,错误原因(模型缺失、图片损坏、引擎失败)永远埋在设备里。写完信封再抛异常,代理状态页能显示错误,桌面拆开 JSON 也知道该报哪个码。输出文件不会马上删,下一次任务按 mtime 清掉一小时前的项,沙箱不会无限长。
设备侧识别在 HAR 里的 VisionOcr.recognizeBytes:image.createImageSource → createPixelMap → textRecognition.recognizeText,finally 里 release 掉 PixelMap 和 ImageSource。Core Vision Kit 不给逐行置信度,所以每个块固定 0.0;同一个文本出现两次会去重,因为 HAR 的 OcrResult 要求块文本唯一。这份实现是从 flutter_ohos_ocr 原样搬过来的,文件头注释里写了出处;模拟器上它停在前面那个 1001400001。
agent 的 module.json5 里 requestPermissions 是空数组,exported: true 只为了让 aa 工具能拉起它。图片进的是 agent 自己的沙箱,识别完删除,全程无网络。job id 在 agent 侧不校验,因为能执行 hdc shell 的人本来就能直接读写这个沙箱;真正的边界在 hdc 的访问控制,不在 id 的正则。桌面侧仍然校验,是因为库要保证自己生成的 id 在 --ps 里不会因为长度或字符出问题;图片路径也由宿主通过 -b 写进固定目录,agent 不接收任意绝对路径。
6. 桌面这边:白名单只有一个出口
preload.ts 只暴露四个方法,底层是四个固定的 ipcRenderer.invoke 通道。渲染进程拿不到 ipcRenderer、process 或 require:
// src/preload.ts · 白名单与唯一的 invoke 出口
/** Channel names the renderer is allowed to invoke — nothing else. */
const ALLOWED_CHANNELS: readonly string[] = [
OCR_IPC_CHANNELS.isAvailable,
OCR_IPC_CHANNELS.backendInfo,
OCR_IPC_CHANNELS.recognizeFile,
OCR_IPC_CHANNELS.recognizeBytes,
];
function assertChannel(channel: string): void {
if (!ALLOWED_CHANNELS.includes(channel)) {
throw new Error(`electron-ohos-ocr: channel "${channel}" is not whitelisted`);
}
}
/** Single invoke funnel with whitelist + argument validation. */
async function invoke(channel: string, ...args: unknown[]): Promise<unknown> {
assertChannel(channel);
if (channel === OCR_IPC_CHANNELS.recognizeFile) {
const [imagePath] = args;
if (typeof imagePath !== 'string' || imagePath.trim().length === 0) {
throw new Error('recognizeFile requires a non-empty image path string');
}
}
if (channel === OCR_IPC_CHANNELS.recognizeBytes) {
const [bytes] = args;
if (!(bytes instanceof Uint8Array) || bytes.length === 0) {
throw new Error('recognizeBytes requires non-empty Uint8Array bytes');
}
}
return ipcRenderer.invoke(channel, ...args);
}
const api: ElectronOhosOcrApi = {
isAvailable: () =>
invoke(OCR_IPC_CHANNELS.isAvailable).then((value) => value === true),
getBackendInfo: () =>
invoke(OCR_IPC_CHANNELS.backendInfo) as Promise<BackendInfo>,
recognizeFile: (imagePath: string, options: RecognizeOptions = {}) =>
invoke(OCR_IPC_CHANNELS.recognizeFile, imagePath, options) as Promise<OcrResult>,
recognizeBytes: (bytes: Uint8Array, options: RecognizeOptions = {}) =>
invoke(OCR_IPC_CHANNELS.recognizeBytes, bytes, options) as Promise<OcrResult>,
};
contextBridge.exposeInMainWorld('electronOhosOcr', api);
两道校验是有意重复的。preload 这一侧挡住的是渲染进程传错类型,主进程的 registerOcrIpcHandlers 挡的是绕过 preload 的其他调用方;两边都只收非空字符串和非空 Uint8Array。错误以 plain object 回到渲染进程,invoke 正常 reject,不会挂住。示例的 webPreferences 是 contextIsolation: true、nodeIntegration: false、sandbox: false;最后一项是为了让 preload 能 require 本库;要开 sandbox: true,就把 preload 改成纯 IPC 转发。这个取舍写在注释里,比藏在配置里好排查。
四个通道之外没有通用 invoke;页面即使被注入脚本,能调的也只有这四个方法,路径和字节还要再过一次校验。
主进程模块作用域建一个 OhosOcrEngine,registerOcrIpcHandlers(engine) 注册四个通道,will-quit 时 engine.dispose() 终止 tesseract worker。渲染进程只做两件事:拿 getBackendInfo().active 做后端徽标,调 recognizeFile 拿 OcrResult。切换后端时业务代码一行不改,因为两边返回的是同一份模型。
local 后端有一处和 device 不一样:tesseract 的中文模型常在汉字之间插空格,直接展示会变成“端 侧 文 字”。normalizeCjkSpacing 只折叠两个汉字之间的空格,汉字和拉丁字母、数字之间的空格保留,所以“项目 HarmonyOS OCR 接入”不会被粘成一串。collectTesseractBlocks 把 blocks → paragraphs → lines 展平、去重,再用页级文本按行兜底;置信度从 0…100 归一到 0…1。
local 后端的代价要提前算。第一次识别会创建 tesseract worker 并加载对应语言的 traineddata:chi_sim 和 eng 各一份,仓库的示例把 .traineddata.gz 放在 example/tessdata;没有这份数据时 tesseract.js 会尝试下载,下载失败或目录里缺文件,createWorker 直接报 VISION_ERROR,不会返回空结果。worker 按语言缓存在 Map 里,同一语言第二次识别不再加载模型。验证记录里另一次纯本机识别是 1000×760 文档、7 块、210 ms;回退那次是 237 ms,两个数都只算 worker.recognize 的墙钟,不含首次加载。机器冷启动、语言包很大或图片分辨率高时,第一次会明显慢于这个数。
7. npm run verify 与 HAP 打包输出
桌面侧:
npm install
npm run verify
最近一次输出:
Test Files 4 passed (4)
Tests 56 passed (56)
verify 依次跑 tsc --noEmit、vitest run、tsc -p tsconfig.json。四个测试文件分别 18、12、7、19 项,覆盖后端选择、hdc 输出解析与协议、tesseract 结果映射、模型校验;子进程和 worker 全部 mock。
示例应用单独构建:cd example && npm install && npm run build。本机 Tesseract 的语言数据不进 git,macOS 上先跑 npm run fetch:tessdata 把 chi_sim 和 eng 下到 example/tessdata,或者用 ELECTRON_OHOS_OCR_TESSDATA 指向已有目录;没有语言数据时 local 后端会在创建 worker 时失败,报 VISION_ERROR,不会静默返回空结果。
设备侧:
cd ohos/example && ohpm install
export DEVECO_SDK_HOME="<DevEco SDK 路径>"
export NODE_HOME="<DevEco Node 目录>"
hvigorw \
--mode module -p product=default -p module=library@default assembleHar --no-daemon
hvigorw \
--mode module -p product=default -p module=entry@default assembleHap --no-daemon
hdc install -r ohos/example/build/default/outputs/default/entry-default-signed.hap
产物是 library.har 17 KB、entry-default-unsigned.hap 130 KB,两次都是 BUILD SUCCESSFUL。仓库里 signingConfigs 是空占位,SignHap 会跳过;验证时装的是本机调试签名,测试包的 bundle 临时改成了签名 profile 的名字。HAP 的安装输出是 msg:install bundle successfully.。
自动探测可以单独跑:
npx electron-ohos-ocr-doctor [--hdc /path/to/hdc] [-t target] [-b bundle]
它逐项检查 hdc、目标、agent 和 tesseract,最后打印 auto 会选的后端。doctor 全绿也不代表识别一定成功:模拟器那轮就是全绿之后 recognizeText 才报 1001400001。
这一轮的验证集中在 2in1 模拟器的失败路径、HAR/HAP 编译和 56 项单测;414 ms 的成功读数是更早一次运行,不能算作这一轮的结论。
仓库里的文档各管一块:仓库说明写双后端、HAR/agent 结构、hdc 环境准备与已知限制;OpenHarmony 接入说明是中文鸿蒙侧说明,含 2in1 模拟器缺模型的记录;架构文档讲协议顺序、envelope、沙箱布局和失败矩阵;API 文档列完整签名、错误码和 HAR API;验证记录记 2026-11-13 的构建、56 项测试与模拟器日志。
8. 失败点与边界
这个库解决的是“桌面应用怎么借设备的 OCR”,不是“Electron 在鸿蒙上跑”。device 后端依赖 hdc、已连接设备和已安装的 agent;local 后端在纯 Node 里也能跑,但中文质量取决于 traineddata。两个后端之间不共享运行时,只共享一份 OcrResult 和同一套 OcrError.code;device 结果的置信度固定 0.0,local 的 0…1 只代表 tesseract 自己的把握,不代表正确率。
桥的边界可以按失败点分。设备不在线时,auto 不会进 device,getBackendInfo 里 deviceConnected 为 false,识别直接走 local;prefer: 'device' 是严格模式,pickBackend 找不到设备就抛 UNSUPPORTED,不换路。bundle 不存在时,file send 或 aa start 会抛 AGENT_NOT_INSTALLED,message 里带着安装命令;agent 装了但没写结果文件,60 秒后是 AGENT_TIMEOUT,message 里带最后一次 hdc 的 stderr;hdc 本身找不到是 HDC_NOT_FOUND;两个后端都不可用时,auto 也抛 UNSUPPORTED,这一情况与 prefer 无关。auto 下 bundle 缺失、agent 超时、hdc 报错这些 device 失败会再试一次 local;设备不在线则一开始就选 local。用户看到的是结果或一个错误码,失败原因留在各条命令的 stderr 和 getBackendInfo().device.error 里。
短期的清单上只有证据:把 sandboxFilesDir 从配置项改成从 agent 日志或 bm dump 自动读,省掉换工程形态时手改路径。1001400001 这类“设备在、模型不在”的失败,仍然会先落到 device,再回退 local;这条路径现在有测试、有日志、有界面提示。
3



被折叠的 条评论
为什么被折叠?



