diff --git a/plugins/native-ocr/CHANGELOG.md b/plugins/native-ocr/CHANGELOG.md index 5ce41ece4..a6f3048bf 100644 --- a/plugins/native-ocr/CHANGELOG.md +++ b/plugins/native-ocr/CHANGELOG.md @@ -2,6 +2,36 @@ Native OCR 从官方 `wechat-ocr` 插件 fork 而来,作者署名 Samson。以下版本历史已按里程碑整合。 +## 1.2.0 - 2026-11-23 + +次要版本:**调整 Windows 的引擎组合**——移除系统 OCR,加回微信 OCR;同时修掉 ONNX 引擎「起不来又不说原因」的问题。macOS 的引擎组合不变(Vision / ONNX / 图文混排 / 公式 / 微信 OCR)。 + +### 变更(仅 Windows) + +- **移除系统 OCR(Windows.Media.Ocr / WinRT)**:识别质量明显弱于 PP-OCRv4 与微信 OCR,且强依赖系统中文语言包(英文版 Windows 上几乎不可用)。同步删除 `bin/ocr-winrt.ps1`、WinRT 能力探针与「Windows OCR」页签;Windows 上历史选择的该引擎自动迁移到 ONNX OCR。 +- **加回微信 OCR**:Windows 上复用**本机微信 4.x 自带的 `wxocr.dll`**,通过 PowerShell P/Invoke 直接调用(`wechat_ocr` / `stop_ocr`,`__cdecl`),**不需要 Python、不需要 node-gyp/MSVC 原生构建**,也不下载任何运行时。找不到微信时该页签置灰并在遮罩里给出具体原因(缺 `wxocr.dll` 还是缺安装目录),支持「重新检测」。 + - 之所以不是复用 macOS 那套运行时:官方 `@ztools-center/wechat-ocr-native` 只发布了一份 `wcocr_native.node`,实测是 Mach-O arm64,没有 Windows 构建。 + - 传输仍走 1.1.1 引入的 `NOCR1:` 信封,对控制台代码页免疫;微信返回的 JSON **不在 PowerShell 里解析**(形状随微信版本变化且无法单测),而是把原始字节带回 Node,由 `wechat-result.cjs` 容错解析。 + +### 修复 + +- **ONNX 服务启动失败时不再吞掉真实原因**:`onnx_ocr_server.mjs` 顶层是静态 `import 'onnxruntime-node'`,ESM 静态导入在模块求值前解析,原生模块加载失败会在任何 `try/catch` 之前杀掉进程 —— stdout 一个字节都没有,界面只能显示「服务启动失败」,真正的原因只留在被丢弃的 stderr 里。现在预加载脚本会把子进程 stderr 尾部与退出码拼进错误信息,并在 Windows 上识别 `LoadLibrary` 失败后检查 `System32` 下的 `vcruntime140.dll` / `vcruntime140_1.dll` / `msvcp140.dll`,缺哪个报哪个,并直接提示安装 VC++ 2015-2022 x64 运行库。 +- **新增平台二进制预检**:启动前检查 `node_modules/onnxruntime-node/bin/napi-v3//` 是否存在。宿主为 32 位 Electron 时包内没有对应二进制,此前表现为「引擎显示已安装但永远起不来」,现在直接报「缺少当前平台的二进制」。OCR / 公式识别 / 图文混排三个服务统一走这套报错。 + +### 工程 + +- 新增 `tests/onnx-diagnose.mjs`(16 项):把「进程崩溃时错误信息必须包含 stderr 原因」和「运行库齐全时不得误导用户去装」写成不变量断言。 +- 新增 `tests/wechat-result.mjs`(20 项):锁定微信返回值的容错范围(`results` / `ocr_result` / 根数组、多边形与 `x/y/w/h` 框、`Text` 大写键)、**原点左下的归一化坐标**、`errcode != 0` 必须报错而不是伪装成「图里没字」、以及 GBK 字节回退(UTF-8 严格解码失败后按 936 解)。 +- `winrt-payload.cjs` 更名为 `ps-ocr-payload.cjs`(它现在服务微信 OCR 通道,不再与 WinRT 绑定);`npm test` 现串联 8 个文件。 + +### 排查结论(真机已确认) + +Windows 虚拟机上复现并确认 ONNX 启动失败的根因:`onnxruntime.dll` 的导入表依赖 `VCRUNTIME140.dll` / `VCRUNTIME140_1.dll` / `MSVCP140.dll`,而干净的虚拟机镜像常缺 `VCRUNTIME140_1.dll`(VS2019 起才提供)。安装 VC++ 2015-2022 x64 运行库后,ONNX 引擎恢复正常,中文识别质量随之回到 PP-OCRv4 的水平。 + +### 已知限制 + +Windows 微信 OCR 的解析容错与 P/Invoke 链路**尚未在真机上跑通验证**(开发机为 macOS,无微信 4.x 也无 PowerShell)。代码把不确定性集中到了可单测的 `wechat-result.cjs`,但调用链本身需要一次真机验证;失败时错误信息会带出微信返回的原始片段,便于定位。 + ## 1.1.1 - 2026-11-03 基于 1.1.0 的补丁发布:修复 Windows 系统 OCR 的中文乱码。仅此一项功能变更,其余为配套的传输协议测试与脚本编码调整。 diff --git a/plugins/native-ocr/README.md b/plugins/native-ocr/README.md index a3ad4c002..176164a4a 100644 --- a/plugins/native-ocr/README.md +++ b/plugins/native-ocr/README.md @@ -1,6 +1,6 @@ # Native OCR -ZTools 本地多引擎 OCR 插件。支持 macOS Vision / Windows OCR(系统 WinRT)/ ONNX OCR(PP-OCR v4)/ 微信 OCR(macOS)/ 公式识别(LaTeX OCR)五类引擎,内置表格识别、PDF 多页识别、OCR 后翻译、识别历史。 +ZTools 本地多引擎 OCR 插件。macOS 支持 Vision / ONNX OCR(PP-OCR v4)/ 微信 OCR / 公式识别 / 图文混排;Windows 支持 ONNX OCR / 微信 OCR / 公式识别 / 图文混排。内置表格识别、PDF 多页识别、OCR 后翻译、识别历史。 **识别(含公式、图文混排、表格)全部在本地完成,图片不上传任何服务器**;唯二需要联网的是「首次下载模型」与「OCR 后翻译」,详见「[隐私与联网](#隐私与联网)」。 @@ -13,10 +13,10 @@ ZTools 本地多引擎 OCR 插件。支持 macOS Vision / Windows OCR(系统 W | ONNX OCR | ✅ | ✅(默认首选) | PP-OCR v4 模型,约 60MB 一次性下载,离线可用,支持表格识别,无需任何环境 | | 公式识别 | ✅ | ✅ | RapidLaTeXOCR 模型,约 171MB 一次性下载,把公式图片识别为 LaTeX 代码(依托 ONNX 引擎) | | 图文混排 | ✅ | ✅ | MFD 模型(pix2text-mfd-1.5.onnx,约 80MB)先定位公式区域,裁切后复用公式引擎识别,再与文本行按阅读顺序合并为 Markdown | -| 系统 OCR | macOS Vision | Windows OCR | 系统内置能力,零依赖;小图自动放大提升识别率 | -| 微信 OCR | ✅ | — | 复用微信自带离线 OCR 运行时(按需从 npmmirror 下载) | +| 系统 OCR | macOS Vision | — | 系统内置能力,零依赖;小图自动放大提升识别率 | +| 微信 OCR | ✅(下载运行时) | ✅(需微信 4.x) | macOS 下载微信离线 OCR 运行时;Windows 复用本机微信自带的 wxocr.dll(P/Invoke,无需 Python / 原生构建) | -Windows 平台默认展示 ONNX OCR,切换引擎后自动用新引擎重新识别当前图片。 +Windows 平台默认展示 ONNX OCR,切换引擎后自动用新引擎重新识别当前图片。**Windows 系统 OCR(WinRT)自 1.2.0 起移除**:识别质量明显弱于 ONNX / 微信 OCR,且依赖中文语言包。 ## 功能 @@ -34,9 +34,9 @@ Windows 平台默认展示 ONNX OCR,切换引擎后自动用新引擎重新识 | 能力 | 依赖 | | --- | --- | | 系统 OCR(macOS Vision) | 首次运行会用 `swiftc -O` 把 `bin/ocr-vision.swift` 编译成二进制(按脚本内容指纹缓存,脚本变更后自动重编;编译失败会回退用 `swift` 解释执行)。因此**需要安装 Xcode Command Line Tools**(`xcode-select --install`) | -| 系统 OCR(Windows OCR) | Win10/11 **桌面版**,依赖系统内置的 **Windows PowerShell**(当前实现调用 `powershell.exe`,未适配 PowerShell 7 / `pwsh`);基于 WinRT OCR,**识别中文需系统安装中文语言包**,在英文版 Windows 上可能不可用或识别质量很差 | +| 微信 OCR(Windows) | 需安装并登录**微信 4.x 桌面版**:插件直接调用微信自带的 `wxocr.dll`(位于 `%APPDATA%\Tencent\xwechat\XPlugin\plugins\WeChatOcr\<版本>\extracted`),不随插件分发。依赖系统内置的 **Windows PowerShell 5.1**(调用 `powershell.exe`,未适配 `pwsh`);找不到微信时该引擎置灰并给出原因 | | ONNX OCR / 公式识别 / 图文混排 | 无需额外环境(Electron 自带 Node 子进程);首次使用需联网下载模型 | -| 微信 OCR | 仅 macOS,复用微信自带离线 OCR 运行时(按需下载) | +| 微信 OCR(macOS) | 复用微信自带离线 OCR 运行时(按需下载) | | OCR 后翻译 | 需联网 | ## 运行时下载 @@ -47,6 +47,7 @@ ONNX OCR、公式识别、图文混排与微信 OCR 运行时不内置在插件 - 公式识别(RapidLaTeXOCR,约 171MB)→ `/native-ocr/onnx-runtime/assets/formula`(复用 ONNX 运行环境,需先装 ONNX 引擎),来源 `ghfast.top`(GitHub 加速) - 图文混排(MFD,约 80MB)→ `/native-ocr/onnx-runtime/assets/mfd`(复用 ONNX 运行环境与公式模型,需先装二者),来源 `hf-mirror.com` - 微信 OCR(macOS)→ `/native-ocr/ocr-runtime`(插件卸载时自动清理),来源 `registry.npmmirror.com` +- 微信 OCR(Windows)**不下载任何运行时**,直接使用本机微信的 `wxocr.dll` 插件页头提供两个资源管理入口:**「释放内存」**回收常驻的 ONNX 推理进程(下次识别自动重启);**「清理 ONNX 模型缓存」**删除已下载的 ONNX 运行环境与全部 ONNX 系模型(约 300MB+,微信 OCR 运行时不受影响),下次使用需重新下载。 diff --git a/plugins/native-ocr/bin/ocr-wechat-win.ps1 b/plugins/native-ocr/bin/ocr-wechat-win.ps1 new file mode 100644 index 000000000..6894d3ed9 --- /dev/null +++ b/plugins/native-ocr/bin/ocr-wechat-win.ps1 @@ -0,0 +1,310 @@ +# WeChat OCR for the native-ocr ZTools plugin (Windows only). +# +# WHY THIS EXISTS: on macOS the plugin downloads a bundled WeChat OCR runtime +# (libwxocr.dylib + models). No Windows build of that native addon is published, +# so on Windows we call the WeChat desktop client's own wxocr.dll directly via +# P/Invoke -- no node-gyp, no MSVC, no Python. +# +# REQUIREMENT: WeChat 4.x must be installed on this machine. wxocr.dll ships +# inside the WeChat plugin directory; we do not redistribute it. +# +# ABI (from the official addon source, Windows branch): +# bool __cdecl wechat_ocr(const wchar_t *ocrExe, const wchar_t *wechatDir, +# const char *imagePath, void(__cdecl *cb)(const char *)); +# void __cdecl stop_ocr(); +# +# OUTPUT CONTRACT (single line on stdout, ASCII only): +# NOCR1: +# probe: { "ok": true, "available": bool, "reason": str, "wxocrDll": str, "wechatDir": str } +# ocr: { "ok": true, "raw": "", "width": int, "height": int } +# fail: { "ok": false, "code": int, "message": str } +# +# The raw WeChat JSON is NOT parsed here: its shape varies between WeChat +# versions and PowerShell-side string handling cannot be unit tested. We only +# transport the bytes; public/wechat-result.cjs does the tolerant parsing. +# Base64 keeps the transport immune to the console code page (see the fix in +# 1.1.1 -- 936/950/932/1252 all produce identical bytes). +# This file is deliberately pure ASCII: PowerShell 5.1 reads BOM-less UTF-8 +# files using the system ANSI code page. +# +# Exit codes: 0 ok / 2 bad args / 3 image missing / 6 wechat not found +# 7 native load failed / 8 ocr call failed / 9 result too large + +param( + [string]$ImagePath = "", + [switch]$Probe +) + +$ErrorActionPreference = 'Stop' + +$scriptVersion = "1.0.0" + +try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {} +try { [Console]::ErrorEncoding = [System.Text.Encoding]::UTF8 } catch {} + +function Write-Payload($payload) { + $json = $payload | ConvertTo-Json -Compress -Depth 6 + $b64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($json)) + [Console]::Out.Write("NOCR1:$b64`r`n") + [Console]::Out.Flush() +} + +function Fail($code, $message) { + try { [Console]::Error.WriteLine("[wcocr-$scriptVersion] $message") } catch {} + try { Write-Payload @{ ok = $false; code = $code; message = $message } } catch {} + exit $code +} + +# --------------------------------------------------------------------------- +# Locate WeChat 4.x +# --------------------------------------------------------------------------- + +# wxocr.dll lives under the WeChat plugin data directory, one folder per build. +# Newest build wins; we never execute it, only LoadLibrary it. +function Find-WxOcrDll { + $roots = @() + if ($env:APPDATA) { $roots += $env:APPDATA } + if ($env:LOCALAPPDATA) { $roots += $env:LOCALAPPDATA } + foreach ($root in $roots) { + foreach ($plugin in @('Tencent\xwechat\XPlugin\plugins\WeChatOcr', 'Tencent\WeChat\XPlugin\plugins\WeChatOcr')) { + $base = Join-Path $root $plugin + if (-not (Test-Path -LiteralPath $base)) { continue } + $versions = Get-ChildItem -LiteralPath $base -Directory -ErrorAction SilentlyContinue | + Sort-Object -Property Name -Descending + foreach ($version in $versions) { + $dll = Join-Path $version.FullName 'extracted\wxocr.dll' + if (Test-Path -LiteralPath $dll) { return $dll } + } + } + } + return "" +} + +# wechat_ocr() also takes the client install directory (used by wxocr.dll to +# resolve its own dependencies), so we look for the client executable. +function Find-WeChatDir { + $roots = @() + if ($env:ProgramW6432) { $roots += $env:ProgramW6432 } + if ($env:ProgramFiles) { $roots += $env:ProgramFiles } + if (${env:ProgramFiles(x86)}) { $roots += ${env:ProgramFiles(x86)} } + foreach ($root in $roots) { + foreach ($name in @('Tencent\Weixin', 'Tencent\WeChat')) { + $base = Join-Path $root $name + if (-not (Test-Path -LiteralPath $base)) { continue } + foreach ($exe in @('Weixin.exe', 'WeChat.exe')) { + $found = Get-ChildItem -LiteralPath $base -Filter $exe -Recurse -Depth 3 -ErrorAction SilentlyContinue | + Sort-Object -Property FullName -Descending | + Select-Object -First 1 + if ($found) { return $found.DirectoryName } + } + } + } + return "" +} + +# --------------------------------------------------------------------------- +# P/Invoke bridge +# --------------------------------------------------------------------------- + +$nativeSource = @' +using System; +using System.Runtime.InteropServices; +using System.Text; + +public static class WcOcrNative +{ + [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern IntPtr LoadLibraryW(string fileName); + + [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)] + public static extern IntPtr GetProcAddress(IntPtr module, string procName); + + [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern bool SetDllDirectoryW(string path); + + [DllImport("kernel32", SetLastError = true)] + public static extern bool FreeLibrary(IntPtr module); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void ResultCallback(IntPtr text); + + // Static fields instead of script-scope variables: the callback may be invoked + // from a native worker thread, where PowerShell $script: scope is unreliable. + public static volatile bool CallbackInvoked; + public static byte[] ResultBytes; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate bool WechatOcrFn(IntPtr ocrExe, IntPtr wechatDir, IntPtr imagePath, IntPtr callback); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void StopOcrFn(); + + // Copy the NUL-terminated byte string out of unmanaged memory as raw bytes. + // The encoding is unknown (UTF-8 for newer builds, ANSI/GBK is possible), so + // we must not decode here -- Node decides with a UTF-8-strict-then-GBK rule. + public static byte[] BytesFromPtr(IntPtr ptr) + { + if (ptr == IntPtr.Zero) { return null; } + int length = 0; + while (Marshal.ReadByte(ptr, length) != 0) { length++; } + byte[] buffer = new byte[length]; + if (length > 0) { Marshal.Copy(ptr, buffer, 0, length); } + return buffer; + } + + public static IntPtr AllocUtf16(string value) + { + return Marshal.StringToHGlobalUni(value); + } + + public static IntPtr AllocUtf8(string value) + { + byte[] bytes = Encoding.UTF8.GetBytes(value); + IntPtr ptr = Marshal.AllocHGlobal(bytes.Length + 1); + Marshal.Copy(bytes, 0, ptr, bytes.Length); + Marshal.WriteByte(ptr, bytes.Length, 0); + return ptr; + } + + public static string LastError() + { + return Marshal.GetLastWin32Error().ToString(); + } +} +'@ + +function Get-WxOcrState { + $dll = Find-WxOcrDll + $dir = Find-WeChatDir + # Machine-readable reason code; the Chinese wording lives in preload.js so + # this file can stay pure ASCII (see the header note). + $reasonCode = "ok" + $detail = "" + if (-not $dll) { + $reasonCode = "wxocr-dll-missing" + $detail = "wxocr.dll not found under %APPDATA%\\Tencent\\xwechat\\XPlugin\\plugins\\WeChatOcr" + } elseif (-not $dir) { + $reasonCode = "wechat-dir-missing" + $detail = "Weixin.exe not found under Program Files\\Tencent" + } + return @{ + wxocrDll = $dll + wechatDir = $dir + available = [bool]($dll -and $dir) + reasonCode = $reasonCode + detail = $detail + } +} + +if ($Probe) { + $state = Get-WxOcrState + Write-Payload @{ + ok = $true + available = $state.available + reasonCode = $state.reasonCode + detail = $state.detail + wxocrDll = $state.wxocrDll + wechatDir = $state.wechatDir + } + exit 0 +} + +if (-not $ImagePath) { Fail 2 "ImagePath is required" } +if (-not (Test-Path -LiteralPath $ImagePath)) { Fail 3 "image not found: $ImagePath" } + +$state = Get-WxOcrState +if (-not $state.available) { Fail 6 ($state.reasonCode + ":" + $state.detail) } + +# Image size is needed to normalize the boxes; wxocr does not return it. +$width = 0 +$height = 0 +try { + Add-Type -AssemblyName System.Drawing -ErrorAction Stop + $image = [System.Drawing.Image]::FromFile((Resolve-Path -LiteralPath $ImagePath).Path) + try { + $width = [int]$image.Width + $height = [int]$image.Height + } finally { + $image.Dispose() + } +} catch { + # Non-fatal: the Node side falls back to deriving size from the boxes. +} + +try { + Add-Type -TypeDefinition $nativeSource -Language CSharp -ErrorAction Stop +} catch { + # Re-running in the same host can hit "type already exists"; that is fine. + if (-not ([System.Management.Automation.PSTypeName]'WcOcrNative').Type) { + Fail 7 ("failed to load P/Invoke bridge: " + $_.Exception.Message) + } +} + +# Make wxocr.dll's own dependencies resolvable before loading it. +try { [void][WcOcrNative]::SetDllDirectoryW($state.wechatDir) } catch {} + +$module = [WcOcrNative]::LoadLibraryW($state.wxocrDll) +if ($module -eq [IntPtr]::Zero) { + Fail 7 ("LoadLibraryW failed for wxocr.dll (win32 error " + [WcOcrNative]::LastError() + ")") +} + +$procOcr = [WcOcrNative]::GetProcAddress($module, "wechat_ocr") +$procStop = [WcOcrNative]::GetProcAddress($module, "stop_ocr") +if ($procOcr -eq [IntPtr]::Zero) { + Fail 7 "wxocr.dll does not export wechat_ocr (unsupported WeChat version)" +} + +# Callback captures raw bytes; script scope keeps the delegate alive so the GC +# cannot collect it while native code still holds the function pointer. +[WcOcrNative]::ResultBytes = $null +[WcOcrNative]::CallbackInvoked = $false +$resultCallback = [WcOcrNative+ResultCallback]{ + param([IntPtr]$text) + [WcOcrNative]::CallbackInvoked = $true + [WcOcrNative]::ResultBytes = [WcOcrNative]::BytesFromPtr($text) +} + +$wechatOcr = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer( + $procOcr, [WcOcrNative+WechatOcrFn]) + +$ptrOcrExe = [WcOcrNative]::AllocUtf16($state.wxocrDll) +$ptrWechatDir = [WcOcrNative]::AllocUtf16($state.wechatDir) +$ptrImage = [WcOcrNative]::AllocUtf8((Resolve-Path -LiteralPath $ImagePath).Path) + +try { + $called = $wechatOcr.Invoke($ptrOcrExe, $ptrWechatDir, $ptrImage, $resultCallback) + # The official addon reads the result right after the call, i.e. it is + # synchronous. Some builds hand the work to a worker thread, so give the + # callback a bounded window to arrive before declaring failure. + if (-not [WcOcrNative]::CallbackInvoked) { + $deadline = [DateTime]::UtcNow.AddSeconds(15) + while (-not [WcOcrNative]::CallbackInvoked -and [DateTime]::UtcNow -lt $deadline) { + Start-Sleep -Milliseconds 100 + } + } + [GC]::KeepAlive($resultCallback) + if (-not $called) { Fail 8 "wechat_ocr returned false" } + if (-not [WcOcrNative]::CallbackInvoked) { Fail 8 "wechat_ocr did not invoke the result callback within 15s" } + if ($null -eq [WcOcrNative]::ResultBytes -or [WcOcrNative]::ResultBytes.Length -eq 0) { + Fail 8 "wechat_ocr returned an empty result" + } + if ([WcOcrNative]::ResultBytes.Length -gt 8MB) { Fail 9 "result too large" } + + $rawB64 = [System.Convert]::ToBase64String([WcOcrNative]::ResultBytes) + Write-Payload @{ ok = $true; raw = $rawB64; width = $width; height = $height } + exit 0 +} catch { + Fail 8 "ocr failed: $($_.Exception.Message)" +} finally { + try { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptrOcrExe) } catch {} + try { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptrWechatDir) } catch {} + try { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptrImage) } catch {} + if ($procStop -ne [IntPtr]::Zero) { + try { + $stopOcr = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer( + $procStop, [WcOcrNative+StopOcrFn]) + $stopOcr.Invoke() + } catch {} + } + try { [void][WcOcrNative]::FreeLibrary($module) } catch {} +} diff --git a/plugins/native-ocr/bin/ocr-winrt.ps1 b/plugins/native-ocr/bin/ocr-winrt.ps1 deleted file mode 100644 index 64703bf2d..000000000 --- a/plugins/native-ocr/bin/ocr-winrt.ps1 +++ /dev/null @@ -1,181 +0,0 @@ -# Windows system OCR (WinRT Windows.Media.Ocr) for the native-ocr ZTools plugin. -# macOS equivalent of ocr-vision.swift. Runs on built-in PowerShell 5.1+ with -# zero dependencies. -# -# OUTPUT CONTRACT (single line on stdout): -# NOCR1: -# success: { "ok": true, "width": int, "height": int, -# "lines": [ { "text": str, "box": { "x","y","w","h" } } ] } -# failure: { "ok": false, "code": int, "message": str } -# -# WHY BASE64: stdout bytes are encoded by [Console]::OutputEncoding, which is -# silently ignored in some hosts (no real console + redirected pipe), falling -# back to the OEM code page (936/GBK on Chinese Windows). Node would then decode -# GBK bytes as UTF-8 and every Chinese line becomes mojibake. Base64 uses only -# [A-Za-z0-9+/=], so the bytes are identical under ANY code page. -# This file is deliberately pure ASCII: PowerShell 5.1 reads UTF-8 files WITHOUT -# a BOM using the system ANSI code page, which would corrupt non-ASCII comments. -# -# Box convention matches the macOS Vision engine: normalized to [0,1] with -# the origin at the image's lower-left corner (y measured from the bottom). -# Exit codes: 0 ok / 2 bad args / 3 image missing / 4 engine unavailable / 5 ocr failed - -param( - [Parameter(Mandatory = $true)][string]$ImagePath -) - -$ErrorActionPreference = 'Stop' - -$scriptVersion = "0.6.10" - -# Best effort only: keeps the human-readable stderr line from mojibake. -# The data channel does NOT depend on this succeeding (see Write-Payload). -try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {} -try { [Console]::ErrorEncoding = [System.Text.Encoding]::UTF8 } catch {} - -# Emit the payload as ASCII-only base64 so no console code page can alter it. -function Write-Payload($payload) { - $json = $payload | ConvertTo-Json -Compress -Depth 6 - $b64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($json)) - [Console]::Out.Write("NOCR1:$b64`r`n") - [Console]::Out.Flush() -} - -# Required for [System.WindowsRuntimeSystemExtensions] (AsTask reflection below). -# Some systems do not auto-load it when resolving WinRT types. -try { Add-Type -AssemblyName System.Runtime.WindowsRuntime } catch {} - -$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime] -$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime] -$null = [Windows.Storage.StorageFile, Windows.Foundation, ContentType = WindowsRuntime] -$null = [Windows.Globalization.Language, Windows.Foundation, ContentType = WindowsRuntime] -$null = [Windows.Security.Cryptography.CryptographicBuffer, Windows.Foundation, ContentType = WindowsRuntime] - -function Await($WinRtTask, $ResultType) { - $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | - Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0] - if (-not $asTaskGeneric) { - throw 'WinRT AsTask helper not found' - } - $asTask = $asTaskGeneric.MakeGenericMethod($ResultType) - $netTask = $asTask.Invoke($null, @($WinRtTask)) - $netTask.Wait(-1) | Out-Null - return $netTask.Result -} - -function Fail($code, $message) { - # stderr is for humans and may be re-encoded by the console code page; the - # authoritative text travels in the base64 envelope on stdout. - try { [Console]::Error.WriteLine("[winrt-$scriptVersion] $message") } catch {} - try { Write-Payload @{ ok = $false; code = $code; message = $message } } catch {} - exit $code -} - -if (-not (Test-Path -LiteralPath $ImagePath)) { - Fail 3 "image not found: $ImagePath" -} - -# Prefer Chinese, then any user-profile language. -$engine = $null -try { - $available = @([Windows.Media.Ocr.OcrEngine]::AvailableRecognizerLanguages) - $preferred = $available | Where-Object { $_.LanguageTag -like 'zh*' } | Select-Object -First 1 - if ($preferred) { - $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage($preferred) - } - if (-not $engine) { - $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages() - } -} catch { - Fail 4 "ocr engine init failed: $($_.Exception.Message)" -} -if (-not $engine) { - Fail 4 "ocr engine unavailable: install a language pack (Settings > Time & Language > Language)" -} - -try { - $file = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync((Resolve-Path -LiteralPath $ImagePath).Path)) ([Windows.Storage.StorageFile]) - $stream = Await ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream]) - $decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder]) - - # Accuracy boost: small images / small text hurt WinRT OCR badly, so upscale - # at decode time (max edge < 1200px gets 2x, capped at 4000px). Boxes are - # normalized afterwards, so coordinates stay consistent with the source. - $srcW = [uint32]$decoder.PixelWidth - $srcH = [uint32]$decoder.PixelHeight - $outW = $srcW - $outH = $srcH - $transform = New-Object Windows.Graphics.Imaging.BitmapTransform - $maxEdge = [Math]::Max($srcW, $srcH) - if ($maxEdge -gt 0 -and $maxEdge -lt 1200) { - $scale = [Math]::Min(4.0, 1200.0 / [double]$maxEdge) - $outW = [uint32][Math]::Min(4000, [Math]::Round([double]$srcW * $scale)) - $outH = [uint32][Math]::Min(4000, [Math]::Round([double]$srcH * $scale)) - $transform.ScaledWidth = $outW - $transform.ScaledHeight = $outH - } - $pixelData = Await ($decoder.GetPixelDataAsync( - [Windows.Graphics.Imaging.BitmapPixelFormat]::Bgra8, - [Windows.Graphics.Imaging.BitmapAlphaMode]::Premultiplied, - $transform, - [Windows.Graphics.Imaging.ExifOrientationMode]::IgnoreExifOrientation, - [Windows.Graphics.Imaging.ColorManagementMode]::DoNotColorManage)) ([Windows.Graphics.Imaging.PixelDataProvider]) - # PowerShell cannot bind byte[] to the IBuffer overload directly; convert it. - # Any failure falls back to the plain (no upscale) path so OCR keeps working. - $bitmap = $null - try { - $pixels = $pixelData.DetachPixelData() - $buffer = [Windows.Security.Cryptography.CryptographicBuffer]::CreateFromByteArray($pixels) - $bitmap = [Windows.Graphics.Imaging.SoftwareBitmap]::CreateCopyFromBuffer( - $buffer, - [Windows.Graphics.Imaging.BitmapPixelFormat]::Bgra8, - [int]$outW, - [int]$outH) - } catch { - $bitmap = $null - } - if (-not $bitmap) { - $bitmap = Await ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap]) - } - $result = Await ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult]) - - $width = [double]$srcW - $height = [double]$srcH - $lines = @() - foreach ($line in $result.Lines) { - $text = $line.Text - if ([string]::IsNullOrWhiteSpace($text)) { continue } - $rect = $null - foreach ($word in $line.Words) { - $r = $word.BoundingRect - if ($null -eq $rect) { - $rect = @{ - left = $r.X; top = $r.Y - right = ($r.X + $r.Width); bottom = ($r.Y + $r.Height) - } - } else { - $rect.left = [Math]::Min($rect.left, $r.X) - $rect.top = [Math]::Min($rect.top, $r.Y) - $rect.right = [Math]::Max($rect.right, $r.X + $r.Width) - $rect.bottom = [Math]::Max($rect.bottom, $r.Y + $r.Height) - } - } - if ($null -eq $rect) { - $rect = @{ left = 0; top = 0; right = $width; bottom = $height } - } - $lines += @{ - text = $text - box = @{ - x = [Math]::Max(0.0, [Math]::Min(1.0, $rect.left / $width)) - y = [Math]::Max(0.0, [Math]::Min(1.0, 1.0 - $rect.bottom / $height)) - w = [Math]::Max(0.0, [Math]::Min(1.0, ($rect.right - $rect.left) / $width)) - h = [Math]::Max(0.0, [Math]::Min(1.0, ($rect.bottom - $rect.top) / $height)) - } - } - } - - Write-Payload @{ ok = $true; width = $width; height = $height; lines = $lines } - exit 0 -} catch { - Fail 5 "ocr failed: $($_.Exception.Message)" -} diff --git a/plugins/native-ocr/package-lock.json b/plugins/native-ocr/package-lock.json index 986472fa4..627b9ef81 100644 --- a/plugins/native-ocr/package-lock.json +++ b/plugins/native-ocr/package-lock.json @@ -1,12 +1,12 @@ { "name": "native-ocr", - "version": "1.1.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "native-ocr", - "version": "1.1.1", + "version": "1.2.0", "dependencies": { "katex": "^0.16.11", "pdfjs-dist": "^6.3.289", diff --git a/plugins/native-ocr/package.json b/plugins/native-ocr/package.json index e20523a31..ba3570b6b 100644 --- a/plugins/native-ocr/package.json +++ b/plugins/native-ocr/package.json @@ -1,6 +1,6 @@ { "name": "native-ocr", - "version": "1.1.1", + "version": "1.2.0", "private": true, "type": "module", "description": "本地多引擎 OCR(微信 OCR / macOS Vision / ONNX / 公式识别)", @@ -11,7 +11,7 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "test": "node tests/run.mjs && node tests/mixed-layout.mjs && node tests/table.mjs && node tests/engine-rerun.mjs && node tests/winrt-payload.mjs && node tests/check-sfc.mjs" + "test": "node tests/run.mjs && node tests/mixed-layout.mjs && node tests/table.mjs && node tests/engine-rerun.mjs && node tests/ps-ocr-payload.mjs && node tests/wechat-result.mjs && node tests/onnx-diagnose.mjs && node tests/check-sfc.mjs" }, "dependencies": { "katex": "^0.16.11", diff --git a/plugins/native-ocr/public/onnx-diagnose.cjs b/plugins/native-ocr/public/onnx-diagnose.cjs new file mode 100644 index 000000000..c9949af78 --- /dev/null +++ b/plugins/native-ocr/public/onnx-diagnose.cjs @@ -0,0 +1,97 @@ +// ONNX 子进程启动失败的诊断辅助(纯 CJS,不依赖 electron)。 +// +// WHY THIS FILE: onnx_ocr_server.mjs 在模块顶层静态 import 'onnxruntime-node', +// ESM 的静态 import 在模块求值前解析,原生模块加载失败(.node / .dll 缺失、 +// VC++ 运行库缺失、架构不匹配)会在任何 try/catch 之前让进程直接退出 —— +// stdout 一个字节都没有,preload 只能报「服务启动失败」,真正的原因只留在 +// stderr 里并被丢弃。本模块把 stderr 尾部与常见失败模式翻译成可执行的提示。 +// +// 单独成模块是为了能在纯 Node 下单测:preload.js 顶层 require("electron")。 + +const path = require("node:path"); + +// onnxruntime-node 把平台二进制放在 bin/napi-v3/// 下, +// 安装时只保留当前平台那一份(见 preload.js 的 trimPlatformBin)。 +const NATIVE_BIN_SEGMENTS = ["node_modules", "onnxruntime-node", "bin", "napi-v3"]; + +// onnxruntime.dll 的导入表实测依赖这三个(MSVC 2015-2022 x64 运行库)。 +// 干净的系统/虚拟机镜像里 VCRUNTIME140_1.dll 经常缺失,表现为 LoadLibrary 失败。 +const VC_RUNTIME_DLLS = ["vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll"]; + +const VC_RUNTIME_HINT = "系统缺少 Microsoft Visual C++ 运行库(vc_redist.x64.exe)"; + +function nativeBinDir(runtimeDir, platform, arch) { + return path.join(runtimeDir, ...NATIVE_BIN_SEGMENTS, String(platform), String(arch)); +} + +// 返回缺失的运行库文件名;existsSync 由调用方注入,便于单测。 +function missingVcRuntimeDlls(systemRoot, existsSync) { + if (!systemRoot) return []; + return VC_RUNTIME_DLLS.filter((name) => { + try { + return !existsSync(path.join(systemRoot, "System32", name)); + } catch (_) { + return false; + } + }); +} + +function isNativeLoadFailure(text) { + return /ERR_DLOPEN_FAILED|The specified module could not be found|LoadLibrary|not a valid Win32 application|%1 is not a valid/i + .test(String(text || "")); +} + +// 取 stderr 有效尾部:去掉栈帧、Node 版本行等噪声,压缩成一行。 +function tailSnippet(text, maxLen = 300) { + const raw = String(text || ""); + if (!raw) return ""; + const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean); + const kept = lines.filter((line) => !/^at\s/.test(line) + && !/^Node\.js v/.test(line) + && !/^node:internal/.test(line)); + const text2 = (kept.length ? kept : lines).join(" "); + if (!text2) return ""; + return text2.length > maxLen ? `…${text2.slice(-maxLen)}` : text2; +} + +// 组装给用户看的启动失败信息: +// <兜底文案>(退出码 N)||<可执行建议> +function startupErrorDetail(options) { + const { + stderrTail = "", + exitCode = null, + signal = null, + platform = "", + systemRoot = "", + existsSync = null, + fallback = "ONNX OCR 服务启动失败", + } = options || {}; + + const parts = []; + if (exitCode !== null && exitCode !== undefined) parts.push(`退出码 ${exitCode}`); + if (signal) parts.push(`信号 ${signal}`); + + const snippet = tailSnippet(stderrTail); + if (snippet) parts.push(snippet); + + let message = parts.length ? `${fallback}(${parts.join("|")})` : fallback; + + // 只在原生模块确实加载失败、且确实是 Windows 时提示运行库,避免误导。 + if (platform === "win32" && isNativeLoadFailure(stderrTail) && typeof existsSync === "function") { + const missing = missingVcRuntimeDlls(systemRoot, existsSync); + if (missing.length) { + message += `|${VC_RUNTIME_HINT}:缺 ${missing.join(" / ")}`; + } + } + return message; +} + +module.exports = { + VC_RUNTIME_DLLS, + VC_RUNTIME_HINT, + nativeBinDir, + missingVcRuntimeDlls, + isNativeLoadFailure, + tailSnippet, + startupErrorDetail, +}; diff --git a/plugins/native-ocr/public/package.json b/plugins/native-ocr/public/package.json index 3886709e7..28852f626 100644 --- a/plugins/native-ocr/public/package.json +++ b/plugins/native-ocr/public/package.json @@ -1,4 +1,4 @@ { "type": "commonjs", - "version": "1.1.1" + "version": "1.2.0" } diff --git a/plugins/native-ocr/public/plugin.json b/plugins/native-ocr/public/plugin.json index 96f0c7122..1c933bcfc 100644 --- a/plugins/native-ocr/public/plugin.json +++ b/plugins/native-ocr/public/plugin.json @@ -2,7 +2,7 @@ "name": "native-ocr", "title": "Native OCR", "description": "本地多引擎 OCR(微信 OCR / macOS Vision / ONNX / 公式识别)", - "version": "1.1.1", + "version": "1.2.0", "author": "Samson", "platform": [ "darwin", diff --git a/plugins/native-ocr/public/preload.js b/plugins/native-ocr/public/preload.js index 9e11271e8..7a563b44b 100644 --- a/plugins/native-ocr/public/preload.js +++ b/plugins/native-ocr/public/preload.js @@ -7,14 +7,31 @@ const zlib = require("node:zlib"); const { clipboard } = require("electron"); const { execFile, spawn, spawnSync } = require("node:child_process"); -// Windows 系统 OCR 的 stdout 解码(ASCII base64 协议,见 public/winrt-payload.cjs)。 +// PowerShell OCR 子进程的 stdout 解码(ASCII base64 协议,见 public/ps-ocr-payload.cjs)。 // 单独成模块是为了能在纯 Node 下单测:preload.js 顶层 require("electron"),测试里跑不起来。 -// 缺该文件时不让整个 preload 崩掉 —— 只有 Windows 系统 OCR 这条路会报错。 -let winrtPayload = null; +// 缺该文件时不让整个 preload 崩掉 —— 只有 Windows 微信 OCR 这条路会报错。 +let psPayload = null; try { - winrtPayload = require("./winrt-payload.cjs"); + psPayload = require("./ps-ocr-payload.cjs"); } catch (_) { - winrtPayload = null; + psPayload = null; +} + +// 微信 OCR 原始返回的容错解析(返回值形状随微信版本变化,纯 Node 可测)。 +let wechatResult = null; +try { + wechatResult = require("./wechat-result.cjs"); +} catch (_) { + wechatResult = null; +} + +// ONNX 子进程启动失败的诊断(原生模块加载失败的原因只出现在 stderr 里)。 +// 同样单独成模块以便单测;缺失时退化为原有兜底文案。 +let onnxDiagnose = null; +try { + onnxDiagnose = require("./onnx-diagnose.cjs"); +} catch (_) { + onnxDiagnose = null; } const OCR_IMAGE_STORAGE_KEY = "native_ocr_image"; @@ -648,32 +665,52 @@ function runVisionScript(scriptPath, imagePath) { }); } -function runWinRtOcrScript(scriptPath, imagePath) { - const scriptReal = ensureRuntimeScript(scriptPath, "ztools-native-ocr-winrt.ps1"); +// --------------------------------------------------------------------------- +// PowerShell OCR 子进程(仅 Windows) +// 原「Windows 系统 OCR(WinRT)」已移除,这条通道现在只服务微信 OCR。 +// --------------------------------------------------------------------------- +const WECHAT_WIN_SCRIPT = "ocr-wechat-win.ps1"; + +// 微信 OCR 在 Windows 上复用本机微信自带的 wxocr.dll(不随插件分发), +// 因此目标机必须装微信 4.x。原因码 → 中文文案:脚本侧保持纯 ASCII +// (PowerShell 5.1 会用 ANSI 读取无 BOM 的 UTF-8 文件),文案统一放这里。 +const WECHAT_WIN_REASONS = { + "wxocr-dll-missing": "未找到微信 OCR 组件 wxocr.dll,请安装并登录微信 4.x 桌面版后重试", + "wechat-dir-missing": "未找到微信安装目录(Weixin.exe),请确认微信 4.x 已正确安装" +}; + +function localizeWeChatWinError(message) { + const text = String(message || ""); + for (const [code, zh] of Object.entries(WECHAT_WIN_REASONS)) { + if (text.startsWith(code)) return zh; + } + return text; +} + +function runPowerShellOcrScript(scriptName, args) { + const scriptReal = ensureRuntimeScript( + path.join(__dirname, "bin", scriptName), + `ztools-native-ocr-${scriptName}` + ); return new Promise((resolve, reject) => { execFile("powershell.exe", [ "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", - "-File", scriptReal, "-ImagePath", imagePath + "-File", scriptReal, ...args ], { timeout: 60000, maxBuffer: 8 * 1024 * 1024, windowsHide: true, - // 取原始字节,不让 Node 提前做有损解码。 - // 新协议是纯 ASCII base64(任何代码页字节相同);旧协议再按 utf8 解。 - // 若用默认 utf8,GBK 输出会先被解成 U+FFFD,后面任何补救都无效。 + // 取原始字节,不让 Node 提前做有损解码(协议是纯 ASCII base64)。 encoding: "latin1" }, (err, stdout, stderr) => { const outBuf = Buffer.from(String(stdout || ""), "latin1"); if (err) { - // 失败信息优先取 stdout 里的 base64 信封(不受本机代码页影响); - // stderr 先按字节还原成 utf8,若已是替换字符则不再把乱码抛给用户。 const stderrText = Buffer.from(String(stderr || ""), "latin1").toString("utf8"); - const fallbackMessage = err.message || "Windows OCR 识别失败"; - reject(new Error( - winrtPayload - ? winrtPayload.errorMessageFromOutput(outBuf, stderrText, fallbackMessage) - : fallbackMessage - )); + const fallbackMessage = err.message || "微信 OCR 识别失败"; + const raw = psPayload + ? psPayload.errorMessageFromOutput(outBuf, stderrText, fallbackMessage) + : fallbackMessage; + reject(new Error(localizeWeChatWinError(raw))); return; } resolve(outBuf); @@ -681,23 +718,90 @@ function runWinRtOcrScript(scriptPath, imagePath) { }); } -function parseWinRtOutput(raw) { - if (!winrtPayload) { - throw new Error("Windows OCR 解码模块缺失(winrt-payload.cjs),请重新安装插件"); +// 探测结果缓存:微信是否安装不会在会话中途变化,每次识别都跑一次 PowerShell 太贵。 +let wechatWinProbeCache = null; + +function probeWeChatWin(force = false) { + if (process.platform !== "win32") { + return { available: false, reasonCode: "unsupported-platform", detail: "not win32" }; } - const { text, lines } = winrtPayload.payloadToOcrResult(winrtPayload.decodeWinRtStdout(raw)); - return { engine: "vision", text, lines }; + if (!force && wechatWinProbeCache) return wechatWinProbeCache; + let probe; + try { + probe = spawnSync("powershell.exe", [ + "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", + "-File", ensureRuntimeScript(path.join(__dirname, "bin", WECHAT_WIN_SCRIPT), `ztools-native-ocr-${WECHAT_WIN_SCRIPT}`), + "-Probe" + ], { + timeout: 20000, + maxBuffer: 4 * 1024 * 1024, + windowsHide: true, + encoding: "latin1" + }); + } catch (error) { + return { available: false, reasonCode: "probe-failed", detail: error.message }; + } + const outBuf = Buffer.from(String((probe && probe.stdout) || ""), "latin1"); + let payload = null; + try { + payload = psPayload ? psPayload.decodeStdout(outBuf) : null; + } catch (_) { + payload = null; + } + if (!payload) { + const stderrText = Buffer.from(String((probe && probe.stderr) || ""), "latin1").toString("utf8").trim(); + return { + available: false, + reasonCode: "probe-failed", + detail: stderrText.slice(0, 300) || "探测脚本没有返回结果" + }; + } + const result = { + available: Boolean(payload.available), + reasonCode: String(payload.reasonCode || (payload.available ? "ok" : "unknown")), + detail: String(payload.detail || ""), + wxocrDll: String(payload.wxocrDll || ""), + wechatDir: String(payload.wechatDir || ""), + message: localizeWeChatWinError(String(payload.reasonCode || "")) + }; + wechatWinProbeCache = result; + return result; } -async function recognizeWinRtOcr(source) { +async function recognizeWeChatWin(source) { let tempFile = ""; try { const imagePath = typeof source === "string" && source.startsWith("data:image/") ? (tempFile = dataUrlToTempFile(source)) : assertImagePath(source); - const scriptPath = path.join(__dirname, "bin", "ocr-winrt.ps1"); - const stdout = await runWinRtOcrScript(scriptPath, imagePath); - return parseWinRtOutput(stdout); + const probe = probeWeChatWin(); + if (!probe.available) { + throw new Error(probe.message || localizeWeChatWinError(probe.reasonCode)); + } + const raw = await runPowerShellOcrScript(WECHAT_WIN_SCRIPT, ["-ImagePath", imagePath]); + if (!psPayload) { + throw new Error("PowerShell 传输解码模块缺失(ps-ocr-payload.cjs),请重新安装插件"); + } + const payload = psPayload.decodeStdout(raw); + if (!payload) throw new Error("微信 OCR 没有返回结果"); + if (payload.ok === false) { + throw new Error(localizeWeChatWinError(String(payload.message || "微信 OCR 识别失败"))); + } + if (!payload.raw) throw new Error("微信 OCR 返回结果为空"); + if (!wechatResult) { + throw new Error("微信 OCR 结果解析模块缺失(wechat-result.cjs),请重新安装插件"); + } + const bytes = Buffer.from(String(payload.raw), "base64"); + const parsed = wechatResult.parseWeChatResult(bytes, { + width: Number(payload.width) || 0, + height: Number(payload.height) || 0 + }); + return { + engine: "wechat", + text: parsed.lines.map((line) => line.text).join("\n"), + lines: parsed.lines, + raw: parsed + }; } finally { if (tempFile) { try { @@ -777,11 +881,10 @@ function parseVisionOutput(raw, engineName = "vision") { const output = String( } async function recognizeVision(source) { - if (process.platform === "win32") { - return recognizeWinRtOcr(source); - } + // Windows 系统 OCR(WinRT)已移除:识别质量明显弱于微信 OCR / ONNX, + // 且需要额外安装中文语言包。Windows 侧请使用微信 OCR 或 ONNX。 if (process.platform !== "darwin") { - throw new Error("系统 OCR 仅支持 macOS / Windows"); + throw new Error("系统 OCR 仅支持 macOS,Windows 请使用微信 OCR 或 ONNX OCR"); } let tempFile = ""; try { @@ -924,91 +1027,10 @@ async function translateSegments(segments, toLang) { return translated; } -// Windows 系统 OCR 走内置 PowerShell + WinRT,无 OCR 语言包时引擎不可用。 -// 只验证「powershell 能跑」会把英文版 Windows(或未装中文语言包)也判成可用, -// 实际识别中文会失败或极差,所以这里做一次真实探针,查 AvailableRecognizerLanguages。 -// 探针与 PS 版本检查合并成同一次调用(避免启动时多一次 powershell 冷启动), -// 输出只用 ASCII 标签,不受中文控制台的代码页影响。 -const WIN_VISION_PROBE_SCRIPT = [ - "$psv = $PSVersionTable.PSVersion.Major", - "$probe = 'ERR'", - "$langs = ''", - "try {", - " $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]", - " $langs = (@([Windows.Media.Ocr.OcrEngine]::AvailableRecognizerLanguages) | ForEach-Object { $_.LanguageTag }) -join ','", - " $probe = 'OK'", - "} catch { }", - "Write-Output ('PSV=' + $psv + ';PROBE=' + $probe + ';LANGS=' + $langs)" -].join("\n"); -const WIN_VISION_PROBE_TIMEOUT_MS = 8000; - -let lastWindowsVisionProbe = null; - -// 返回 { known, powershellAvailable, languages, chinese, message }。 -// known=false 表示探针本身没结论(异常 / 超时 / 输出不可解析 / WinRT 查询失败), -// 调用方必须退回旧的乐观判断,绝不能因此把可用环境判成不可用。 -function probeWindowsVision() { - let probe; - try { - probe = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WIN_VISION_PROBE_SCRIPT], { - encoding: "utf8", - timeout: WIN_VISION_PROBE_TIMEOUT_MS, - windowsHide: true - }); - } catch (_) { - return { - known: false, - powershellAvailable: true, - languages: [], - chinese: false, - message: "无法检测 Windows 系统 OCR,已按兼容策略视为可用" - }; - } - // 只有确定 powershell.exe 缺失(ENOENT)才算不可用;超时 / 被终止 / 非零退出 - // 都可能只是慢或被安全软件拦截,按旧判断乐观处理。 - const powershellAvailable = !(probe.error && probe.error.code === "ENOENT"); - const stdout = typeof probe.stdout === "string" ? probe.stdout : ""; - const versionMatch = /PSV=(\d+)/.exec(stdout); - const probeMatch = /PROBE=([A-Z]+)/.exec(stdout); - const langsMatch = /LANGS=([^\r\n]*)/.exec(stdout); - if (probe.status !== 0 || !versionMatch || !probeMatch || !langsMatch || probeMatch[1] !== "OK") { - return { - known: false, - powershellAvailable, - languages: [], - chinese: false, - message: "未能确认 Windows 系统 OCR 语言包,已按兼容策略视为可用" - }; - } - const languages = langsMatch[1].split(",").map((tag) => tag.trim()).filter(Boolean); - const chinese = languages.some((tag) => /^zh/i.test(tag)); - return { - known: true, - powershellAvailable: true, - languages, - chinese, - message: languages.length - ? (chinese ? "" : "Windows 系统 OCR 未安装中文识别语言包,请在「设置 > 时间和语言 > 语言」中添加中文并安装语言包") - : "Windows 系统 OCR 引擎不可用,请安装 OCR 语言包(设置 > 时间和语言 > 语言)" - }; -} - function isVisionAvailable() { - if (process.platform === "win32") { - const probe = probeWindowsVision(); - lastWindowsVisionProbe = probe; - // 探针没结论 → 退回旧的「powershell 能跑就算可用」,宁可乐观也不制造假阴性 - // (假阴性会让 UI 直接禁用系统 OCR 引擎)。 - if (!probe.known) return probe.powershellAvailable; - // 探到 WinRT OCR 但一个识别语言都没有,说明引擎确实不可用。 - if (!probe.languages.length) return false; - // 有 OCR 但缺中文语言包时仍返回 true(引擎可用,只是中文效果差), - // 提示信息放在 getVisionSupportDetail() 里,不改变本函数的布尔契约。 - return true; - } - if (process.platform !== "darwin") { - return false; - } + // Windows 系统 OCR(WinRT)已移除:识别质量明显弱于微信 OCR / ONNX,且依赖中文语言包。 + // Windows 侧的可选引擎为 ONNX OCR 与微信 OCR(见 probeWeChatWin)。 + if (process.platform !== "darwin") return false; try { const result = spawnSync("which", ["swift"], { encoding: "utf8", timeout: 5000 }); return result.status === 0 @@ -1019,28 +1041,9 @@ function isVisionAvailable() { } } -// 附件能力(不改变 isVisionAvailable 的布尔契约):UI 想提示「需安装中文语言包」 -// 时可读上一次探针细节;未探针过(非 Windows)返回 null。 +// 保留导出以维持 preload 契约:Windows 已无系统 OCR 探针,恒返回 null。 function getVisionSupportDetail() { - return lastWindowsVisionProbe ? { ...lastWindowsVisionProbe } : null; -} - -// --------------------------------------------------------------------------- -// Python 探测(仅供 Windows 微信 OCR 过渡链路使用;ONNX OCR / Vision 均无 Python) -// --------------------------------------------------------------------------- - -function pythonCandidates() { - if (process.platform === "win32") { - return ["python", "python3", "py"]; - } - // GUI 应用不继承 shell 的 PATH,需补充常见绝对路径 - return [ - "/opt/homebrew/bin/python3", - "/usr/local/bin/python3", - "/usr/bin/python3", - "python3", - "python" - ]; + return null; } // --------------------------------------------------------------------------- @@ -1248,6 +1251,22 @@ async function installOnnxRuntime(onProgress) { let onnxServerState = null; +// 服务进程已退出时组装报错:ESM 静态 import 的原生模块加载失败会直接杀掉进程、 +// stdout 无输出,原因只在 stderr 尾部。这里把它带进用户可见的错误里。 +function onnxStartupErrorMessage(state, fallback, exitCode, signal) { + if (state && state.fatalError) return state.fatalError; + if (!onnxDiagnose) return fallback; + return onnxDiagnose.startupErrorDetail({ + stderrTail: state ? state.stderrTail : "", + exitCode, + signal, + platform: process.platform, + systemRoot: process.env.SystemRoot || process.env.windir || "", + existsSync: fs.existsSync, + fallback + }); +} + // ONNX 依赖 ESM 原生模块,渲染进程 preload 的动态 import() 走浏览器解析 // (报 process is not defined),因此放在 Electron 自带 Node 的子进程里跑: // process.execPath + ELECTRON_RUN_AS_NODE=1,无需系统安装 Node。 @@ -1259,6 +1278,17 @@ function ensureOnnxServer() { if (!fs.existsSync(scriptPath)) { throw new Error("ONNX OCR 服务脚本缺失,请重新下载引擎"); } + // 平台二进制预检:安装时按 trimPlatformBin 只保留当前 platform/arch 那一份。 + // 若宿主 Electron 的架构在包内没有对应二进制(如 32 位 Electron),整个 bin + // 目录会被裁空,表现是「引擎显示已安装但永远起不来」且没有任何原因。 + if (onnxDiagnose) { + const binDir = onnxDiagnose.nativeBinDir(getOnnxRuntimeDir(), process.platform, process.arch); + if (!fs.existsSync(binDir)) { + throw new Error( + `ONNX 运行库缺少当前平台的二进制(${process.platform}/${process.arch}),请重置 ONNX 引擎后重试` + ); + } + } // 启动前同步最新服务脚本:识别逻辑修复不依赖模型重下载。 // 动态扫描 bin/*.mjs(避免新增模块后漏同步导致 import 失败),异常时回退静态列表。 try { @@ -1340,7 +1370,7 @@ function ensureOnnxServer() { onnxServerState = null; } }; - proc.on("exit", () => failAll(new Error(state.fatalError || "ONNX OCR 服务进程已退出"))); + proc.on("exit", (code, signal) => failAll(new Error(onnxStartupErrorMessage(state, "ONNX OCR 服务进程已退出", code, signal)))); proc.on("error", (error) => failAll(error)); onnxServerState = state; return state; @@ -1356,7 +1386,7 @@ function waitOnnxServerReady(state, timeoutMs = 90000) { return; } if (state.proc.exitCode !== null) { - reject(new Error(state.fatalError || "ONNX OCR 服务进程启动失败")); + reject(new Error(onnxStartupErrorMessage(state, "ONNX OCR 服务进程启动失败", state.proc.exitCode, null))); return; } if (state.fatalError) { @@ -1730,7 +1760,7 @@ function ensureOnnxFormulaServer() { onnxFormulaServerState = null; } }; - proc.on("exit", () => failAll(new Error(state.fatalError || "公式识别服务进程已退出"))); + proc.on("exit", (code, signal) => failAll(new Error(onnxStartupErrorMessage(state, "公式识别服务进程已退出", code, signal)))); proc.on("error", (error) => failAll(error)); onnxFormulaServerState = state; return state; @@ -1835,7 +1865,7 @@ function ensureOnnxMixedServer() { onnxMixedServerState = null; } }; - proc.on("exit", () => failAll(new Error(state.fatalError || "图文混排服务进程已退出"))); + proc.on("exit", (code, signal) => failAll(new Error(onnxStartupErrorMessage(state, "图文混排服务进程已退出", code, signal)))); proc.on("error", (error) => failAll(error)); onnxMixedServerState = state; return state; @@ -2215,6 +2245,14 @@ window.nativeOcr = { recognizeVision, isVisionAvailable, getVisionSupportDetail, + // Windows 微信 OCR(复用本机微信自带的 wxocr.dll) + recognizeWeChatWin, + isWeChatWinAvailable(force = false) { + return probeWeChatWin(force).available; + }, + getWeChatWinDetail(force = false) { + return { ...probeWeChatWin(force) }; + }, recognizeOnnxOcr, isOnnxOcrAvailable, installOnnxRuntime, diff --git a/plugins/native-ocr/public/winrt-payload.cjs b/plugins/native-ocr/public/ps-ocr-payload.cjs similarity index 85% rename from plugins/native-ocr/public/winrt-payload.cjs rename to plugins/native-ocr/public/ps-ocr-payload.cjs index daa2bbd0b..2dffa001b 100644 --- a/plugins/native-ocr/public/winrt-payload.cjs +++ b/plugins/native-ocr/public/ps-ocr-payload.cjs @@ -1,10 +1,10 @@ "use strict"; -// Windows 系统 OCR 的 stdout 传输协议(供 public/preload.js 与 tests/ 共用)。 +// PowerShell OCR 子进程的 stdout 传输协议(供 public/preload.js 与 tests/ 共用)。 // // 问题背景 // -------- -// `bin/ocr-winrt.ps1` 由 powershell.exe 执行,stdout 的字节由 +// Windows 侧的 OCR 脚本(微信 OCR:bin/ocr-wechat-win.ps1)由 powershell.exe 执行,stdout 的字节由 // `[Console]::OutputEncoding` 决定。该设置在「没有真实控制台 + stdout 被重定向 // 到管道」的宿主里可能被**静默忽略**(脚本里那两行 try/catch 会吞掉失败),于是 // 输出退回系统 OEM 代码页 —— 中文 Windows 是 936(GBK)。Node 侧若固定按 UTF-8 @@ -21,7 +21,7 @@ // NOCR1: // 成功:{ ok: true, width, height, lines: [{ text, box: { x, y, w, h } }] } // 失败:{ ok: false, code, message } -// 旧版脚本直接输出明文 JSON,本模块仍兼容(见 decodeWinRtStdout 的 legacy 分支)。 +// 旧版脚本直接输出明文 JSON,本模块仍兼容(见 decodeStdout 的 legacy 分支)。 const PROTOCOL_PREFIX = "NOCR1:"; @@ -33,7 +33,7 @@ function toBuffer(raw) { // 把脚本 stdout 解成 payload 对象;无法识别时返回 null。 // 传入 Buffer 最佳(字节精确);传入字符串时按 utf8 解释,仅用于旧调用点。 -function decodeWinRtStdout(raw) { +function decodeStdout(raw) { const buf = toBuffer(raw); if (!buf.length) return null; @@ -52,12 +52,12 @@ function decodeWinRtStdout(raw) { try { json = Buffer.from(b64, "base64").toString("utf8"); } catch (_) { - throw new Error("Windows OCR 返回内容无法解码(协议 NOCR1)"); + throw new Error("PowerShell OCR 返回内容无法解码(协议 NOCR1)"); } try { return JSON.parse(json); } catch (_) { - throw new Error("Windows OCR 返回内容不是合法 JSON(协议 NOCR1)"); + throw new Error("PowerShell OCR 返回内容不是合法 JSON(协议 NOCR1)"); } } @@ -69,7 +69,7 @@ function decodeWinRtStdout(raw) { try { return JSON.parse(text.slice(start)); } catch (_) { - throw new Error("Windows OCR 返回内容无法解析(legacy 协议)"); + throw new Error("PowerShell OCR 返回内容无法解析(legacy 协议)"); } } @@ -78,7 +78,7 @@ function decodeWinRtStdout(raw) { function payloadToOcrResult(payload) { if (!payload) return { text: "", lines: [] }; if (payload.ok === false || payload.error) { - throw new Error(String(payload.message || "Windows OCR 识别失败")); + throw new Error(String(payload.message || "OCR 识别失败")); } const items = Array.isArray(payload.lines) ? payload.lines @@ -100,19 +100,19 @@ function payloadToOcrResult(payload) { // 取不到才退回 stderr;stderr 若已被解成替换字符(U+FFFD) 就不要再把乱码抛给用户。 function errorMessageFromOutput(raw, stderrText, fallback) { try { - const payload = decodeWinRtStdout(raw); + const payload = decodeStdout(raw); if (payload && payload.message) return String(payload.message); } catch (_) { // 信封本身不可解析,继续走下面的兜底。 } const text = String(stderrText || "").trim(); if (text && !text.includes("\uFFFD")) return text; - return fallback || "Windows OCR 识别失败"; + return fallback || "OCR 识别失败"; } module.exports = { PROTOCOL_PREFIX, - decodeWinRtStdout, + decodeStdout, payloadToOcrResult, errorMessageFromOutput }; diff --git a/plugins/native-ocr/public/wechat-result.cjs b/plugins/native-ocr/public/wechat-result.cjs new file mode 100644 index 000000000..cb253c4ed --- /dev/null +++ b/plugins/native-ocr/public/wechat-result.cjs @@ -0,0 +1,200 @@ +// 微信 OCR(Windows)返回结果的解析与归一化(纯 CJS,不依赖 electron)。 +// +// WHY THIS FILE: Windows 上我们通过 PowerShell P/Invoke 调用本机微信自带的 +// wxocr.dll,回调给的是 `const char *`(一段 JSON 字符串)。这段 JSON 的确切 +// 结构由微信版本决定、没有公开契约,实测不同版本会出现在 `results` / +// `ocr_result` / `lines` 下的差异,框也可能是 4 点多边形或 x/y/w/h。 +// 与其在 PowerShell 里写脆弱的字符串处理(无法单测),不如: +// - ps1 只做「调用 + 把原始字节按 base64 输出 + 附带图片尺寸」 +// - 解析/归一化全部放在这里,用单测锁定容错行为 +// +// 坐标系:输入是像素、原点左上;输出统一为归一化 0..1、原点左下(与 macOS +// Vision / ONNX 两条链路一致,渲染层不再做引擎分支)。 + +const TEXT_KEYS = ["text", "Text", "content", "Content", "value", "Value"]; +const ARRAY_KEYS = ["results", "ocr_result", "ocrResult", "lines", "items", "data", "list"]; +const BOX_KEYS = ["box", "Box", "poly", "points", "boxPoints", "box_points", "rect"]; + +function decodeResultBytes(input) { + if (typeof input === "string") return input; + if (!input || typeof input.length !== "number") return ""; + const bytes = Buffer.isBuffer(input) ? input : Buffer.from(input); + if (!bytes.length) return ""; + // 微信输出的编码没有承诺:先按 UTF-8 严格解,失败再按 GBK(936)解。 + // 顺序不能反 —— GBK 几乎不会解码失败,反着用会把 UTF-8 中文解成乱码。 + try { + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch (_) { + try { + return new TextDecoder("gbk").decode(bytes); + } catch (_) { + return bytes.toString("latin1"); + } + } +} + +function pickFirst(object, keys) { + for (const key of keys) { + if (object && object[key] !== undefined && object[key] !== null) return object[key]; + } + return undefined; +} + +function isPolygon(value) { + if (!Array.isArray(value) || value.length < 3) return false; + return value.every((point) => Array.isArray(point) && point.length >= 2 + && Number.isFinite(Number(point[0])) && Number.isFinite(Number(point[1]))); +} + +// 统一成像素包围盒 {left, top, right, bottom};识别不出则返回 null。 +function toPixelBox(item) { + if (!item || typeof item !== "object") return null; + const raw = pickFirst(item, BOX_KEYS); + if (isPolygon(raw)) { + const xs = raw.map((point) => Number(point[0])); + const ys = raw.map((point) => Number(point[1])); + return { + left: Math.min(...xs), + top: Math.min(...ys), + right: Math.max(...xs), + bottom: Math.max(...ys), + }; + } + if (raw && typeof raw === "object" && !Array.isArray(raw)) { + // {x,y,w,h} 或 {left,top,right,bottom} + const x = Number(raw.x); + const y = Number(raw.y); + const w = Number(raw.w); + const h = Number(raw.h); + if ([x, y, w, h].every(Number.isFinite)) { + return { left: x, top: y, right: x + w, bottom: y + h }; + } + const left = Number(raw.left); + const top = Number(raw.top); + const right = Number(raw.right); + const bottom = Number(raw.bottom); + if ([left, top, right, bottom].every(Number.isFinite)) return { left, top, right, bottom }; + } + // 扁平的 x/y/w/h + const x = Number(item.x); + const y = Number(item.y); + const w = Number(item.w !== undefined ? item.w : item.width); + const h = Number(item.h !== undefined ? item.h : item.height); + if ([x, y, w, h].every(Number.isFinite)) { + return { left: x, top: y, right: x + w, bottom: y + h }; + } + return null; +} + +function findItems(root) { + if (Array.isArray(root)) return root; + if (!root || typeof root !== "object") return []; + for (const key of ARRAY_KEYS) { + if (Array.isArray(root[key])) return root[key]; + } + return []; +} + +// 微信可能同时返回一个非零 errcode:这类响应必须当失败处理,否则会被 +// 「解析出 0 行」伪装成「图里没有文字」。 +function assertNoError(root) { + if (!root || typeof root !== "object" || Array.isArray(root)) return; + const code = pickFirst(root, ["errcode", "errCode", "code"]); + if (code === undefined || code === null) return; + const numeric = Number(code); + if (Number.isFinite(numeric) && numeric !== 0) { + const message = pickFirst(root, ["errmsg", "errMsg", "message", "msg"]) || ""; + throw new Error(`微信 OCR 返回错误 ${numeric}${message ? `: ${message}` : ""}`); + } +} + +function clamp01(value) { + if (!Number.isFinite(value)) return 0; + return Math.max(0, Math.min(1, value)); +} + +function normalizeBox(box, width, height) { + const x = clamp01(box.left / width); + const w = clamp01((box.right - box.left) / width); + // 原点从左下:top/bottom 需要翻转 + const y = clamp01(1 - box.bottom / height); + const h = clamp01((box.bottom - box.top) / height); + return { x, y, w, h }; +} + +/** + * 解析微信 OCR 的原始返回。 + * @param {Buffer|Uint8Array|string} input 原始字节或已解码文本 + * @param {{width?: number, height?: number}} [sizeHint] 图片尺寸(ps1 侧读取) + * @returns {{width: number, height: number, lines: Array<{text: string, box?: object}>}} + */ +function parseWeChatResult(input, sizeHint = {}) { + const text = decodeResultBytes(input); + if (!text || !text.trim()) { + throw new Error("微信 OCR 没有返回任何内容(可能是微信版本不支持该图片)"); + } + let root; + try { + root = JSON.parse(text); + } catch (_) { + const snippet = text.replace(/\s+/g, " ").slice(0, 160); + throw new Error(`微信 OCR 返回值不是 JSON:${snippet}`); + } + assertNoError(root); + + const items = findItems(root); + const lines = []; + for (const item of items) { + if (typeof item === "string") { + const value = item.trim(); + if (value) lines.push({ text: value }); + continue; + } + if (!item || typeof item !== "object") continue; + const rawText = pickFirst(item, TEXT_KEYS); + const value = rawText === undefined || rawText === null ? "" : String(rawText).trim(); + if (!value) continue; + const pixelBox = toPixelBox(item); + lines.push(pixelBox ? { text: value, pixelBox } : { text: value }); + } + + // 尺寸优先级:调用方给的真实图片尺寸 > 返回值里自带的 > 用最大坐标兜底 + let width = Number(sizeHint.width); + let height = Number(sizeHint.height); + if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) { + const w = Number(pickFirst(root, ["width", "Width", "imageWidth", "imgWidth"])); + const h = Number(pickFirst(root, ["height", "Height", "imageHeight", "imgHeight"])); + width = Number.isFinite(w) && w > 0 ? w : 0; + height = Number.isFinite(h) && h > 0 ? h : 0; + } + if ((!width || !height) && lines.length) { + let maxX = 0; + let maxY = 0; + for (const line of lines) { + if (!line.pixelBox) continue; + maxX = Math.max(maxX, line.pixelBox.right); + maxY = Math.max(maxY, line.pixelBox.bottom); + } + if (!width && maxX > 0) width = maxX; + if (!height && maxY > 0) height = maxY; + } + if (!width || !height) { + // 没有尺寸就无法归一化:保留文本、丢掉坐标,总比整条失败好。 + return { width: 0, height: 0, lines: lines.map((line) => ({ text: line.text })) }; + } + + return { + width, + height, + lines: lines.map((line) => (line.pixelBox + ? { text: line.text, box: normalizeBox(line.pixelBox, width, height) } + : { text: line.text })), + }; +} + +module.exports = { + decodeResultBytes, + toPixelBox, + normalizeBox, + parseWeChatResult, +}; diff --git a/plugins/native-ocr/src/App.vue b/plugins/native-ocr/src/App.vue index b51889deb..7ef44fbb4 100644 --- a/plugins/native-ocr/src/App.vue +++ b/plugins/native-ocr/src/App.vue @@ -293,10 +293,21 @@ @click="startMfdDownload" >下载图文混排模型 (约 80MB) +
+
微信 OCR 不可用
+
+ {{ wechatWinDetail?.message || '需要在本机安装微信 4.x 桌面版,插件复用其自带的 wxocr.dll' }} +
+ +
{{ loadingMessage }} - 首次使用需要初始化 OCR 模型 + 首次使用需要初始化 OCR 模型
@@ -808,14 +819,20 @@ const runtimeProgress = ref({ downloaded: 0, total: 0 }) -const engine = ref(localStorage.getItem('native_ocr_engine') || 'wechat') +// 默认引擎:macOS 用微信 OCR(免下载、离线);Windows 用 ONNX(系统 OCR 已移除, +// 微信 OCR 依赖本机安装微信,不如 ONNX 稳定)。 +const initialPlatform = window.nativeOcr?.getPlatform?.() || 'darwin' +const engine = ref(localStorage.getItem('native_ocr_engine') || (initialPlatform === 'darwin' ? 'wechat' : 'rapidocr')) const lastRecognizedSource = ref('') // 切引擎时若识别在途,则登记一次待补跑的重识别(loading 结束后由 finally 消费)。 const pendingEngineRerun = ref(false) const visionAvailable = ref(false) -// Windows 视觉探针细节(非 Windows / 未探针恒为 null)。仅用于把「缺中文语言包」等解释性 -// 文案透出给用户;绝不参与启用/禁用决策,也绝不据此改变 visionAvailable 的布尔契约。 -const visionSupportDetail = ref(null) +// Windows 微信 OCR 能力:复用本机微信自带的 wxocr.dll,需装微信 4.x。 +// probed 区分「还没探过」与「探过但不可用」—— 探测要起一次 powershell 进程, +// 放在首帧之后做,未探测前不要因此把页签判成不可用。 +const wechatWinAvailable = ref(false) +const wechatWinProbed = ref(false) +const wechatWinDetail = ref(null) const onnxReady = ref(false) const onnxDownloading = ref(false) const onnxCacheClearing = ref(false) @@ -990,16 +1007,7 @@ const hasContent = computed(() => Boolean(previewSrc.value || rawResultText.valu const runtimeReady = computed(() => runtimeStatus.value === 'ready') const isMacPlatform = (window.nativeOcr?.getPlatform?.() || 'darwin') === 'darwin' const wechatReady = computed(() => runtimeReady.value) -const wechatSupported = computed(() => runtimeStatus.value !== 'unsupported') -// Windows 视觉探针的补充提示:仅当探针结论明确(known === true)且给出非空 message 时采用, -// 否则返回空串,由 engineTabs 回落到原有文案(探针无结论时不得改变任何措辞)。 -const visionDetailHint = computed(() => { - const detail = visionSupportDetail.value - if (!detail || detail.known !== true) return '' - const message = detail.message - return typeof message === 'string' && message.trim() !== '' ? message : '' -}) -// 引擎页签排序:Windows 上 ONNX OCR(识别率最优)排第一; +// 引擎页签排序:Windows 上 ONNX OCR(识别率最优)排第一,微信 OCR 复用本机微信; // macOS 保持 macOS Vision → ONNX OCR → 微信 OCR。 const engineTabs = computed(() => { const onnxTab = { @@ -1010,18 +1018,11 @@ const engineTabs = computed(() => { badge: onnxReady.value ? '' : '未下载', title: onnxReady.value ? '内置 ONNX 引擎(PP-OCR v4),支持表格识别' : '点击下载内置 ONNX 引擎(无需 Python)' } - const visionTab = isMacPlatform - ? { - id: 'vision', label: 'macOS Vision', pending: false, - disabled: !visionAvailable.value, badge: '', - title: visionAvailable.value ? '' : '需要 macOS 及 swift 命令' - } - : { - id: 'vision', label: 'Windows OCR', pending: false, - disabled: !visionAvailable.value, badge: '', - // 探针给出明确提示(如缺中文语言包)时优先展示;否则保持原有文案。 - title: visionDetailHint.value || (visionAvailable.value ? '' : '需要 Windows 10 及 PowerShell') - } + const visionTab = { + id: 'vision', label: 'macOS Vision', pending: false, + disabled: !visionAvailable.value, badge: '', + title: visionAvailable.value ? '' : '需要 macOS 及 swift 命令' + } const formulaTab = { id: 'formula', label: '公式识别', @@ -1046,7 +1047,18 @@ const engineTabs = computed(() => { : '点击下载图文混排模型(约 80MB,依赖 ONNX 引擎与公式模型)' } if (!isMacPlatform) { - return [onnxTab, mixedTab, formulaTab, visionTab] + // Windows:系统 OCR(WinRT)已移除,微信 OCR 改为复用本机微信的 wxocr.dll。 + // 未探测前不禁用(探测在首帧后异步进行),探测完不可用才置灰并给出原因。 + const wechatWinTab = { + id: 'wechat', label: '微信 OCR', + pending: false, + disabled: wechatWinProbed.value && !wechatWinAvailable.value, + badge: wechatWinAvailable.value || !wechatWinProbed.value ? '' : '不可用', + title: wechatWinAvailable.value + ? '调用本机微信自带的离线 OCR(需微信 4.x)' + : (wechatWinDetail.value?.message || '需要在本机安装微信 4.x 桌面版') + } + return [onnxTab, mixedTab, formulaTab, wechatWinTab] } const wechatTab = { id: 'wechat', label: '微信 OCR', @@ -1061,11 +1073,17 @@ const readyToRecognize = computed(() => { if (engine.value === 'rapidocr') return onnxReady.value if (engine.value === 'formula') return formulaReady.value if (engine.value === 'mixed') return mfdReady.value - return wechatReady.value + if (engine.value === 'wechat') { + return isMacPlatform ? wechatReady.value : (!wechatWinProbed.value || wechatWinAvailable.value) + } + return false }) const runtimeBusy = computed(() => ['checking', 'downloading', 'extracting'].includes(runtimeStatus.value)) const runtimeCanDownload = computed(() => ['missing', 'outdated', 'error'].includes(runtimeStatus.value)) const runtimeOverlayVisible = computed(() => engine.value === 'wechat' && isMacPlatform && !runtimeReady.value) +// Windows 微信 OCR 不可用时的说明遮罩(macOS 走上面的运行时下载遮罩)。 +const wechatWinOverlayVisible = computed(() => engine.value === 'wechat' && !isMacPlatform + && wechatWinProbed.value && !wechatWinAvailable.value) const runtimeProgressVisible = computed(() => ['downloading', 'extracting'].includes(runtimeStatus.value)) const tableCapable = computed(() => { if (engine.value === 'vision') return visionAvailable.value @@ -2117,6 +2135,8 @@ function recognizeWithEngine(source) { if (engine.value === 'vision') return window.nativeOcr.recognizeVision(source) if (engine.value === 'rapidocr') return window.nativeOcr.recognizeOnnxOcr(source) if (engine.value === 'formula') return window.nativeOcr.recognizeOnnxFormula(source) + // Windows 的微信 OCR 走本机 wxocr.dll(P/Invoke),与 macOS 的下载运行时是两条实现 + if (engine.value === 'wechat' && !isMacPlatform) return window.nativeOcr.recognizeWeChatWin(source) return window.nativeOcr.recognize(source) } @@ -2174,7 +2194,8 @@ async function recognizeSource(source, preview = '', force = false) { showToast('请先下载图文混排模型') return } - if (engine.value !== 'vision' && engine.value !== 'rapidocr' && engine.value !== 'formula' && engine.value !== 'mixed' && !runtimeReady.value) { + // 微信 OCR:macOS 需要下载运行时;Windows 复用本机微信,无运行时下载这一步。 + if (engine.value === 'wechat' && isMacPlatform && !runtimeReady.value) { pendingRecognition = { source, preview } try { previewSrc.value = preview || await previewForSource(source) @@ -2184,6 +2205,10 @@ async function recognizeSource(source, preview = '', force = false) { showToast('请先下载 OCR 运行时') return } + if (engine.value === 'wechat' && !isMacPlatform && wechatWinProbed.value && !wechatWinAvailable.value) { + showToast(wechatWinDetail.value?.message || '微信 OCR 不可用,请安装微信 4.x 桌面版') + return + } if (!force && source === lastSource && rawResultText.value) return // 仅新图(source 变化)清空手工排除状态与框 resize override;同一张图的滑块/切换重跑保留。 if (source !== lastSource) { @@ -3759,13 +3784,6 @@ onMounted(async () => { } catch (_) { // Ignore host API failures. } - // 探针细节只用于解释性文案:宿主未暴露该 API(旧版 ZTools)或调用失败时保持 null, - // 绝不因此影响启动或引擎可用性判断。 - try { - visionSupportDetail.value = await window.nativeOcr?.getVisionSupportDetail?.() || null - } catch (_) { - // Ignore host API failures. - } try { onnxReady.value = await window.nativeOcr?.isOnnxOcrAvailable?.() || false } catch (_) { @@ -3781,17 +3799,39 @@ onMounted(async () => { } catch (_) { // Ignore host API failures. } - // 微信 OCR 仅支持 macOS;Windows 上历史遗留的 wechat 引擎回退到本机 OCR - if (engine.value === 'wechat' && !isMacPlatform) { - engine.value = 'vision' + // Windows 系统 OCR(WinRT)已移除:历史选择的 vision 统一迁到 ONNX。 + if (!isMacPlatform && engine.value === 'vision') { + engine.value = 'rapidocr' } if (engine.value === 'vision' && !visionAvailable.value) { engine.value = 'rapidocr' } await refreshRuntimeStatus() + // 微信 OCR 在 Windows 上要起一次 powershell 探测微信安装情况:放到首帧之后, + // 避免冷启动(约数百毫秒)拖慢插件界面。探测完若不可用再把引擎迁走。 + if (!isMacPlatform) { + setTimeout(refreshWechatWinProbe, 0) + } await consumePendingImage() }) +// Windows 微信 OCR 能力探测 / 重新探测(「重新检测」按钮也走这里)。 +function refreshWechatWinProbe(force = false) { + if (isMacPlatform) return + let detail = null + try { + detail = window.nativeOcr?.getWeChatWinDetail?.(force) || null + } catch (_) { + detail = { available: false, message: '无法检测微信 OCR,请重试' } + } + wechatWinDetail.value = detail + wechatWinAvailable.value = Boolean(detail?.available) + wechatWinProbed.value = true + if (engine.value === 'wechat' && !wechatWinAvailable.value) { + engine.value = 'rapidocr' + } +} + onBeforeUnmount(() => { window.removeEventListener(OCR_IMAGE_EVENT, onOcrImageEvent) window.removeEventListener('keydown', onGlobalKeydown) diff --git a/plugins/native-ocr/tests/onnx-diagnose.mjs b/plugins/native-ocr/tests/onnx-diagnose.mjs new file mode 100644 index 000000000..7ba29ce94 --- /dev/null +++ b/plugins/native-ocr/tests/onnx-diagnose.mjs @@ -0,0 +1,173 @@ +// ONNX 子进程启动失败的诊断回归测试 —— node tests/onnx-diagnose.mjs +// +// 覆盖 public/onnx-diagnose.cjs。背景:onnx_ocr_server.mjs 顶层静态 import +// 'onnxruntime-node',原生模块加载失败会在任何 try/catch 之前杀掉进程,stdout +// 无输出,用户只看到「服务启动失败」。本测试锁定: +// 1. stderr 尾部必须被带进错误信息(否则永远查不出原因) +// 2. Windows 上缺 VC++ 运行库时,必须给出可执行提示而非原始英文报错 +// 3. 非 Windows / 非加载失败场景不得误报运行库问题 +// 4. 平台二进制目录按 /node_modules/onnxruntime-node/bin/napi-v3// 组装 +// +// 不依赖 Windows 或真实原生模块,纯字符串与路径测试(existsSync 注入)。 +import assert from 'node:assert/strict' +import path from 'node:path' +import { createRequire } from 'node:module' + +const require = createRequire(import.meta.url) +const { + VC_RUNTIME_DLLS, + nativeBinDir, + missingVcRuntimeDlls, + isNativeLoadFailure, + tailSnippet, + startupErrorDetail +} = require('../public/onnx-diagnose.cjs') + +let passed = 0 +let failed = 0 + +function test(name, fn) { + try { + fn() + passed += 1 + console.log(` ✓ ${name}`) + } catch (error) { + failed += 1 + console.error(` ✗ ${name}\n ${error.message}`) + } +} + +// 「所有运行库都在」与「一个都没有」两种环境 +const allPresent = () => true +const nonePresent = () => false + +// 真实的 Node 原生模块加载失败长这样(Node 打印的是英文原文) +const DLOPEN_ERR = [ + "node:internal/modules/cjs/loader:1386", + " throw err;", + "", + "Error: The specified module could not be found.", + "\\\\?\\C:\\Users\\u\\AppData\\Roaming\\ZTools\\plugins-data\\native-ocr\\onnx-runtime\\node_modules\\onnxruntime-node\\bin\\napi-v3\\win32\\x64\\onnxruntime_binding.node", + " at Module._extensions..node (node:internal/modules/cjs/loader:1396:18)", + " at Module.load (node:internal/modules/cjs/loader:1180:32)", + "Node.js v22.22.2" +].join("\n") + +test('平台二进制目录按 napi-v3// 组装', () => { + const dir = nativeBinDir('/rt', 'win32', 'x64') + assert.equal(dir, path.join('/rt', 'node_modules', 'onnxruntime-node', 'bin', 'napi-v3', 'win32', 'x64')) + assert.ok(dir.endsWith(path.join('napi-v3', 'win32', 'x64'))) +}) + +test('arm64 与 x64 的目录互不相同(架构裁剪不会串)', () => { + assert.notEqual(nativeBinDir('/rt', 'win32', 'x64'), nativeBinDir('/rt', 'win32', 'arm64')) +}) + +test('缺运行库时列出具体文件名', () => { + const missing = missingVcRuntimeDlls('C:\\Windows', nonePresent) + assert.deepEqual(missing, VC_RUNTIME_DLLS) +}) + +test('运行库齐全时不报缺失', () => { + assert.deepEqual(missingVcRuntimeDlls('C:\\Windows', allPresent), []) +}) + +test('systemRoot 为空时不误判(非 Windows 调用方)', () => { + assert.deepEqual(missingVcRuntimeDlls('', nonePresent), []) +}) + +test('识别原生模块加载失败', () => { + assert.equal(isNativeLoadFailure(DLOPEN_ERR), true) + assert.equal(isNativeLoadFailure('not a valid Win32 application'), true) + assert.equal(isNativeLoadFailure('ERR_DLOPEN_FAILED'), true) +}) + +test('普通业务错误不当作加载失败', () => { + assert.equal(isNativeLoadFailure('imagePath is required'), false) + assert.equal(isNativeLoadFailure('ONNX 引擎组件缺失或版本不兼容'), false) +}) + +test('stderr 尾部去掉栈帧与 Node 版本噪声', () => { + const s = tailSnippet(DLOPEN_ERR, 5000) + assert.ok(s.includes('The specified module could not be found')) + assert.ok(!s.includes('node:internal'), '不应保留 node:internal 行') + assert.ok(!s.includes('at Module.load'), '不应保留栈帧') + assert.ok(!s.includes('Node.js v'), '不应保留版本行') +}) + +test('stderr 尾部超长时保留末尾(原因通常在最后)', () => { + const long = `${'x'.repeat(400)}TAIL_MARK` + const s = tailSnippet(long, 50) + assert.ok(s.startsWith('…')) + assert.ok(s.endsWith('TAIL_MARK')) + assert.ok(s.length <= 51) +}) + +test('空 stderr 返回空串', () => { + assert.equal(tailSnippet(''), '') + assert.equal(tailSnippet(null), '') +}) + +test('★ 进程崩溃时错误信息必须包含 stderr 原因', () => { + const msg = startupErrorDetail({ + stderrTail: DLOPEN_ERR, + exitCode: 1, + platform: 'win32', + systemRoot: 'C:\\Windows', + existsSync: allPresent, + fallback: 'ONNX OCR 服务进程已退出' + }) + assert.ok(msg.includes('ONNX OCR 服务进程已退出')) + assert.ok(msg.includes('退出码 1')) + assert.ok(msg.includes('The specified module could not be found'), '必须带出真实原因') +}) + +test('★ Windows 缺 VC++ 运行库时给出可执行提示', () => { + const msg = startupErrorDetail({ + stderrTail: DLOPEN_ERR, + exitCode: 1, + platform: 'win32', + systemRoot: 'C:\\Windows', + existsSync: nonePresent, + fallback: 'ONNX OCR 服务进程已退出' + }) + assert.ok(msg.includes('vc_redist.x64.exe')) + assert.ok(msg.includes('vcruntime140.dll')) +}) + +test('运行库齐全时不再提示安装(避免误导)', () => { + const msg = startupErrorDetail({ + stderrTail: DLOPEN_ERR, + exitCode: 1, + platform: 'win32', + systemRoot: 'C:\\Windows', + existsSync: allPresent, + fallback: 'ONNX OCR 服务进程已退出' + }) + assert.ok(!msg.includes('vc_redist'), '不该让用户去装已经装过的运行库') +}) + +test('macOS 上不做 Windows 运行库推断', () => { + const msg = startupErrorDetail({ + stderrTail: DLOPEN_ERR, + exitCode: 1, + platform: 'darwin', + systemRoot: '', + existsSync: nonePresent, + fallback: 'ONNX OCR 服务进程已退出' + }) + assert.ok(!msg.includes('vc_redist')) +}) + +test('无 stderr 时保持简洁,不加空括号', () => { + const msg = startupErrorDetail({ stderrTail: '', exitCode: null, fallback: 'ONNX OCR 服务启动失败' }) + assert.equal(msg, 'ONNX OCR 服务启动失败') +}) + +test('信号退出(被杀)也能表达', () => { + const msg = startupErrorDetail({ stderrTail: '', exitCode: null, signal: 'SIGKILL', fallback: '服务已退出' }) + assert.ok(msg.includes('SIGKILL')) +}) + +console.log(`\n${passed} 通过 / ${failed} 失败`) +process.exitCode = failed ? 1 : 0 diff --git a/plugins/native-ocr/tests/winrt-payload.mjs b/plugins/native-ocr/tests/ps-ocr-payload.mjs similarity index 83% rename from plugins/native-ocr/tests/winrt-payload.mjs rename to plugins/native-ocr/tests/ps-ocr-payload.mjs index 9916cf1d4..a06d7b63c 100644 --- a/plugins/native-ocr/tests/winrt-payload.mjs +++ b/plugins/native-ocr/tests/ps-ocr-payload.mjs @@ -1,7 +1,7 @@ -// Windows 系统 OCR 的 stdout 传输协议回归测试 —— node tests/winrt-payload.mjs +// PowerShell OCR 子进程的 stdout 传输协议回归测试 —— node tests/ps-ocr-payload.mjs // -// 覆盖 public/winrt-payload.cjs: -// 1. 新协议 NOCR1: 的中文往返(这是「Windows OCR 中文乱码」的直接回归项) +// 覆盖 public/ps-ocr-payload.cjs: +// 1. 新协议 NOCR1: 的中文往返(这是「OCR 结果中文乱码」的直接回归项) // 2. **核心不变量**:线上字节必须全部 < 0x80 —— 只有这样,936/950/932/1252 // 任何代码页写出的字节才完全相同,编码问题才从根上消失 // 3. 旧协议(明文 JSON / 带 BOM / 前面有 PowerShell warning)仍可解析 @@ -15,10 +15,10 @@ import { createRequire } from 'node:module' const require = createRequire(import.meta.url) const { PROTOCOL_PREFIX, - decodeWinRtStdout, + decodeStdout, payloadToOcrResult, errorMessageFromOutput -} = require('../public/winrt-payload.cjs') +} = require('../public/ps-ocr-payload.cjs') let passed = 0 let failed = 0 @@ -34,7 +34,7 @@ function test(name, fn) { } } -// 复刻 ocr-winrt.ps1 的 Write-Payload:JSON → UTF-8 → Base64,再拼前缀。 +// 复刻 ocr-wechat-win.ps1 的 Write-Payload:JSON → UTF-8 → Base64,再拼前缀。 function wire(payload) { const json = JSON.stringify(payload) const b64 = Buffer.from(json, 'utf8').toString('base64') @@ -56,7 +56,7 @@ const SAMPLE = { // --------------------------------------------------------------------------- test('新协议:中文 / 混排 / emoji 往返完全一致', () => { - const payload = decodeWinRtStdout(wire(SAMPLE)) + const payload = decodeStdout(wire(SAMPLE)) const result = payloadToOcrResult(payload) assert.equal(result.lines.length, 2) assert.equal(result.lines[0].text, '第一行:中文识别') @@ -65,14 +65,14 @@ test('新协议:中文 / 混排 / emoji 往返完全一致', () => { }) test('新协议:box 被规范化为 number', () => { - const { lines } = payloadToOcrResult(decodeWinRtStdout(wire(SAMPLE))) + const { lines } = payloadToOcrResult(decodeStdout(wire(SAMPLE))) assert.deepEqual(lines[0].box, { x: 0.1, y: 0.8, w: 0.5, h: 0.1 }) assert.equal(typeof lines[0].box.x, 'number') }) test('新协议:非法 box 被忽略但文本保留', () => { const payload = { ok: true, lines: [{ text: '没有框' }, { text: '坏框', box: { x: 'NaN' } }] } - const { lines } = payloadToOcrResult(decodeWinRtStdout(wire(payload))) + const { lines } = payloadToOcrResult(decodeStdout(wire(payload))) assert.equal(lines.length, 2) assert.equal(lines[0].box, undefined) assert.equal(lines[1].box, undefined) @@ -90,9 +90,9 @@ test('线上字节全部 < 0x80(任何代码页写出的字节相同)', () = test('同一份线上字节,按 utf8 / latin1 / ascii 三种方式交给解码器,结果一致', () => { const buf = wire(SAMPLE) - const expected = JSON.stringify(payloadToOcrResult(decodeWinRtStdout(buf))) + const expected = JSON.stringify(payloadToOcrResult(decodeStdout(buf))) for (const enc of ['utf8', 'latin1', 'ascii']) { - const got = JSON.stringify(payloadToOcrResult(decodeWinRtStdout(buf.toString(enc)))) + const got = JSON.stringify(payloadToOcrResult(decodeStdout(buf.toString(enc)))) assert.equal(got, expected, `encoding=${enc} 结果不一致`) } }) @@ -113,7 +113,7 @@ test('模拟 4 种 Windows 代码页:ASCII payload 在各代码页下字节不 test('旧协议:明文 JSON(utf8)仍可解析', () => { const buf = Buffer.from(`{"width":10,"height":20,"lines":[{"text":"旧版中文"}]}`, 'utf8') - const { text } = payloadToOcrResult(decodeWinRtStdout(buf)) + const { text } = payloadToOcrResult(decodeStdout(buf)) assert.equal(text, '旧版中文') }) @@ -122,20 +122,20 @@ test('旧协议:带 UTF-8 BOM 仍可解析', () => { Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from('{"width":1,"height":1,"lines":[{"text":"BOM 之后"}]}', 'utf8') ]) - const { text } = payloadToOcrResult(decodeWinRtStdout(buf)) + const { text } = payloadToOcrResult(decodeStdout(buf)) assert.equal(text, 'BOM 之后') }) test('新协议:payload 前有 PowerShell warning 行仍能定位', () => { const body = wire(SAMPLE) const buf = Buffer.concat([Buffer.from('WARNING: something noisy\r\n', 'latin1'), body]) - const { text } = payloadToOcrResult(decodeWinRtStdout(buf)) + const { text } = payloadToOcrResult(decodeStdout(buf)) assert.equal(text, SAMPLE.lines.map((l) => l.text).join('\n')) }) test('新协议:PowerShell 把单元素 lines 折叠成对象时仍解析', () => { const payload = { ok: true, lines: { text: '只有一行', box: { x: 0, y: 0, w: 1, h: 1 } } } - const { lines, text } = payloadToOcrResult(decodeWinRtStdout(wire(payload))) + const { lines, text } = payloadToOcrResult(decodeStdout(wire(payload))) assert.equal(lines.length, 1) assert.equal(text, '只有一行') }) @@ -147,14 +147,14 @@ test('新协议:PowerShell 把单元素 lines 折叠成对象时仍解析', () test('failure 信封:ok:false 抛出原始 message(中文不乱码)', () => { const buf = wire({ ok: false, code: 4, message: 'ocr engine unavailable: 请安装语言包' }) assert.throws( - () => payloadToOcrResult(decodeWinRtStdout(buf)), + () => payloadToOcrResult(decodeStdout(buf)), /ocr engine unavailable: 请安装语言包/ ) }) test('空输出 → 空结果,不抛错', () => { - assert.deepEqual(payloadToOcrResult(decodeWinRtStdout(Buffer.alloc(0))), { text: '', lines: [] }) - assert.deepEqual(payloadToOcrResult(decodeWinRtStdout(Buffer.from(' \r\n '))), { text: '', lines: [] }) + assert.deepEqual(payloadToOcrResult(decodeStdout(Buffer.alloc(0))), { text: '', lines: [] }) + assert.deepEqual(payloadToOcrResult(decodeStdout(Buffer.from(' \r\n '))), { text: '', lines: [] }) }) test('失败时优先用信封里的 message,即使 stderr 已被代码页搞成乱码', () => { diff --git a/plugins/native-ocr/tests/wechat-result.mjs b/plugins/native-ocr/tests/wechat-result.mjs new file mode 100644 index 000000000..e959fe9ff --- /dev/null +++ b/plugins/native-ocr/tests/wechat-result.mjs @@ -0,0 +1,168 @@ +// 微信 OCR(Windows)返回值的解析回归测试 —— node tests/wechat-result.mjs +// +// 覆盖 public/wechat-result.cjs。微信 wxocr.dll 回调的 JSON 结构没有公开契约, +// 不同版本会出现在 results / ocr_result / lines 等不同键下,框也可能是多边形或 +// x/y/w/h。本测试锁定「容错范围」与「坐标系约定」,避免以后收窄到只认一种形状。 +// +// 不依赖微信、Windows 或真实图片,纯字符串/字节测试。 +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' + +const require = createRequire(import.meta.url) +const { + decodeResultBytes, + toPixelBox, + normalizeBox, + parseWeChatResult +} = require('../public/wechat-result.cjs') + +let passed = 0 +let failed = 0 + +function test(name, fn) { + try { + fn() + passed += 1 + console.log(` ✓ ${name}`) + } catch (error) { + failed += 1 + console.error(` ✗ ${name}\n ${error.message}`) + } +} + +// 「中」「文」的 GBK 编码,用来验证编码回退(Node 只有 GBK 解码能力,没有编码器) +const GBK_ZHONG = [0xd6, 0xd0] +const GBK_WEN = [0xce, 0xc4] + +test('results 形状 + 多边形框 → 归一化包围盒', () => { + const payload = { + results: [ + { text: '你好', box: [[100, 50], [300, 50], [300, 150], [100, 150]] } + ] + } + const out = parseWeChatResult(JSON.stringify(payload), { width: 1000, height: 500 }) + assert.equal(out.lines.length, 1) + assert.equal(out.lines[0].text, '你好') + assert.deepEqual(out.lines[0].box, { x: 0.1, y: 0.7, w: 0.2, h: 0.2 }) +}) + +test('ocr_result 形状 + {x,y,w,h} 框', () => { + const payload = { + ocr_result: [ + { text: 'A', box: { x: 200, y: 100, w: 100, h: 50 } } + ] + } + const out = parseWeChatResult(JSON.stringify(payload), { width: 1000, height: 500 }) + assert.deepEqual(out.lines[0].box, { x: 0.2, y: 0.7, w: 0.1, h: 0.1 }) +}) + +test('根直接是数组', () => { + const out = parseWeChatResult(JSON.stringify([{ text: 'x' }])) + assert.equal(out.lines.length, 1) + assert.equal(out.lines[0].text, 'x') +}) + +test('扁平 x/y/w/h 也能识别', () => { + const out = parseWeChatResult(JSON.stringify({ lines: [{ text: 't', x: 0, y: 0, w: 100, h: 50 }] }), { width: 100, height: 100 }) + assert.deepEqual(out.lines[0].box, { x: 0, y: 0.5, w: 1, h: 0.5 }) +}) + +test('大写的 Text 键也接受', () => { + const out = parseWeChatResult(JSON.stringify({ results: [{ Text: '大写' }] })) + assert.equal(out.lines[0].text, '大写') +}) + +test('无框时保留文本、不造坐标', () => { + const out = parseWeChatResult(JSON.stringify({ results: [{ text: 'only' }] }), { width: 10, height: 10 }) + assert.equal(out.lines[0].text, 'only') + assert.equal(out.lines[0].box, undefined) +}) + +test('空文本项被丢弃', () => { + const out = parseWeChatResult(JSON.stringify({ results: [{ text: ' ' }, { text: 'keep' }] })) + assert.equal(out.lines.length, 1) + assert.equal(out.lines[0].text, 'keep') +}) + +test('★ 坐标系为原点左下(y 由 bottom 翻转)', () => { + // 顶边 0、底边 50 的框在图片最上方 → 归一化 y 应接近 1 + const box = normalizeBox({ left: 0, top: 0, right: 10, bottom: 50 }, 10, 100) + assert.ok(Math.abs(box.y - 0.5) < 1e-9) + const top = normalizeBox({ left: 0, top: 0, right: 10, bottom: 10 }, 10, 100) + assert.ok(top.y > 0.8, `最上方的框 y 应接近 1,实际 ${top.y}`) +}) + +test('坐标越界会被夹到 0..1', () => { + const box = normalizeBox({ left: -50, top: -50, right: 200, bottom: 200 }, 100, 100) + assert.ok(box.x >= 0 && box.x <= 1) + assert.ok(box.w >= 0 && box.w <= 1) + assert.ok(box.y >= 0 && box.y <= 1) + assert.ok(box.h >= 0 && box.h <= 1) +}) + +test('errcode 非 0 必须抛错(不能伪装成「图里没字」)', () => { + assert.throws( + () => parseWeChatResult(JSON.stringify({ errcode: 3, errmsg: 'bad image' })), + /3.*bad image/ + ) +}) + +test('errcode 为 0 正常放行', () => { + const out = parseWeChatResult(JSON.stringify({ errcode: 0, results: [{ text: 'ok' }] })) + assert.equal(out.lines[0].text, 'ok') +}) + +test('非 JSON 返回带片段报错', () => { + assert.throws(() => parseWeChatResult('not json at all'), /不是 JSON/) +}) + +test('空返回报错', () => { + assert.throws(() => parseWeChatResult(''), /没有返回任何内容/) +}) + +test('★ GBK 字节回退(UTF-8 严格解失败后按 936 解)', () => { + const head = Buffer.from('{"results":[{"text":"', 'utf8') + const tail = Buffer.from('"}]}', 'utf8') + const bytes = Buffer.concat([head, Buffer.from([...GBK_ZHONG, ...GBK_WEN]), tail]) + const out = parseWeChatResult(bytes) + assert.equal(out.lines[0].text, '中文') +}) + +test('UTF-8 字节正常解,不被 GBK 抢走', () => { + const out = parseWeChatResult(Buffer.from(JSON.stringify({ results: [{ text: '中文' }] }), 'utf8')) + assert.equal(out.lines[0].text, '中文') +}) + +test('尺寸优先用调用方给的图片尺寸', () => { + const out = parseWeChatResult( + JSON.stringify({ width: 999, height: 999, results: [{ text: 't', x: 0, y: 0, w: 10, h: 10 }] }), + { width: 100, height: 100 } + ) + assert.equal(out.width, 100) + assert.equal(out.height, 100) +}) + +test('没有尺寸时用返回值自带的尺寸', () => { + const out = parseWeChatResult(JSON.stringify({ width: 200, height: 100, results: [{ text: 't', x: 0, y: 0, w: 20, h: 10 }] })) + assert.equal(out.width, 200) + assert.equal(out.height, 100) +}) + +test('完全没有尺寸时按最大坐标兜底', () => { + const out = parseWeChatResult(JSON.stringify({ results: [{ text: 't', x: 0, y: 0, w: 40, h: 20 }] })) + assert.equal(out.width, 40) + assert.equal(out.height, 20) +}) + +test('toPixelBox 对非法输入返回 null', () => { + assert.equal(toPixelBox(null), null) + assert.equal(toPixelBox({ text: 'no box' }), null) + assert.equal(toPixelBox({ box: [[1, 2]] }), null) +}) + +test('decodeResultBytes 接受字符串原样返回', () => { + assert.equal(decodeResultBytes('{"a":1}'), '{"a":1}') +}) + +console.log(`\n${passed} 通过 / ${failed} 失败`) +process.exitCode = failed ? 1 : 0