mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 新增mac ocr转文字,增加到问一问微信 图片索引优化速度
- 图片文字索引性能与进度诚实化 - 问问微信:证据卡区分「消息类型」与「派生来源」,派生命中内容自报来源 - 问问微信:回答规则禁止未真实执行的多轮承诺 - 本地图片文字识别:支持 macOS 系统 OCR(Apple Vision)
This commit is contained in:
1 parent
b8f08d54c8
commit
1337bcb7de
53 files changed
+4985
-624
No files matched your search
+146
-15
@@ -11,24 +11,62 @@
|
||||
* 2. `ImageOcrBinding` —— 「某个会话里的某条图片消息 → 某个 artifact」的绑定,保证去重不丢来源。
|
||||
*/
|
||||
|
||||
/** 派生文本的引擎标识;与 System OCR 的引擎常量保持一致。 */
|
||||
export const IMAGE_TEXT_INDEX_ENGINE = 'windows-system-ocr'
|
||||
/**
|
||||
* 派生文本的引擎标识**不在这里定义**:它是 System OCR 运行时按平台决定的
|
||||
* (`resolveSystemOcrEngine`),并随 `ImageOcrProvenance` 一起进入 artifact 指纹。
|
||||
* 本模块只消费该值,不再持有任何单一平台的引擎常量。
|
||||
*/
|
||||
|
||||
/** 派生库自身的 schema 版本(与 Knowledge 的 schema 相互独立)。 */
|
||||
export const IMAGE_TEXT_INDEX_SCHEMA_VERSION = 1
|
||||
|
||||
/**
|
||||
* OCR 并发上限。
|
||||
*
|
||||
* 当前实现**严格串行**(循环体内只有一次 await,无 Promise.all 扇出),等价于 1。
|
||||
* 这个常量是后续调高的唯一入口:Windows OCR 是进程内 WinRT 调用,实测单张
|
||||
* 20–40ms,串行已足够;调高只会和 Query Agent 抢 CPU。
|
||||
*/
|
||||
export const DEFAULT_IMAGE_TEXT_OCR_CONCURRENCY = 1
|
||||
|
||||
/** 每个批次的图片条数;批间让出 event loop,保证 UI / 查询不被卡住。 */
|
||||
export const IMAGE_TEXT_INDEX_BATCH_SIZE = 12
|
||||
|
||||
/**
|
||||
* 正常运行态下,向 Renderer 推送进度的最小间隔。
|
||||
*
|
||||
* 后台仍然按 `IMAGE_TEXT_INDEX_BATCH_SIZE` 推进(batch / checkpoint / 并发都不受影响),
|
||||
* 但**UI 不该感知 batch 大小** —— 每批都推会让计数以「+12」的粒度跳动。
|
||||
* 所以这里只节流**通知**:状态变化(开始/暂停/继续/取消/失败/完成/清理)一律立即推送。
|
||||
*/
|
||||
export const IMAGE_TEXT_INDEX_PROGRESS_INTERVAL_MS = 5000
|
||||
|
||||
/** 速度统计窗口:取最近这段时间的增量,而不是整个任务的平均。 */
|
||||
export const IMAGE_TEXT_INDEX_RATE_WINDOW_MS = 60_000
|
||||
|
||||
/** 窗口内至少要有这么长的跨度才给出速度,否则显示「计算中」。 */
|
||||
export const IMAGE_TEXT_INDEX_RATE_MIN_SPAN_MS = 20_000
|
||||
|
||||
/**
|
||||
* OCR 并发度**硬上限**。
|
||||
*
|
||||
* `@napi-rs/system-ocr` 的 `recognize()` 是 napi AsyncTask,实际执行会占用
|
||||
* libuv **共享**线程池(fs / zlib / dns 等 native 异步工作也在用同一个池)。
|
||||
* 开得太高不会让单个识别更快,只会挤占同一进程里其它 native 异步工作。
|
||||
*/
|
||||
export const MAX_IMAGE_TEXT_OCR_CONCURRENCY = 4
|
||||
|
||||
/**
|
||||
* 默认 OCR 并发度(生产值)。
|
||||
*
|
||||
* 取值规则:在"吞吐明显更高、且 CPU / UI 交互代价可接受"的前提下取**最低**并发。
|
||||
* 超过 2 之后单次识别耗时会明显劣化(多个识别互相争抢 CPU),
|
||||
* 属于"多出来的并发全花在争抢上"。
|
||||
*
|
||||
* **这个值是待复测的**:原取舍依据来自一次现已修复的固定开销存在时的对照,
|
||||
* 而那个开销不随并发变化、会压扁并发收益。需要重新做锁定输入的对照后再决定;
|
||||
* 在那之前保持 2,不要按"池子多大就用多大"去推。
|
||||
*/
|
||||
export const DEFAULT_IMAGE_TEXT_OCR_CONCURRENCY = 2
|
||||
|
||||
/** 解析并发度:只接受 1..MAX 的整数,其余一律回落到默认值。 */
|
||||
export function resolveImageTextOcrConcurrency(raw?: string | number | null): number {
|
||||
const value = typeof raw === 'number' ? raw : Number.parseInt(String(raw ?? ''), 10)
|
||||
if (!Number.isFinite(value) || value < 1) return DEFAULT_IMAGE_TEXT_OCR_CONCURRENCY
|
||||
return Math.min(MAX_IMAGE_TEXT_OCR_CONCURRENCY, Math.floor(value))
|
||||
}
|
||||
|
||||
/** 已完成一批之后、回到会话循环前的让出时间。 */
|
||||
export const IMAGE_TEXT_INDEX_YIELD_MS = 0
|
||||
|
||||
@@ -222,6 +260,15 @@ export interface ImageTextIndexProgress {
|
||||
cancellable: boolean
|
||||
paused: boolean
|
||||
lastError?: string
|
||||
/**
|
||||
* 最近窗口(`IMAGE_TEXT_INDEX_RATE_WINDOW_MS`)的实测速度,单位 张/秒。
|
||||
*
|
||||
* 刻意用**滑动窗口**而不是整个任务的平均:全量回填要跑几小时,
|
||||
* 历史平均会把"现在到底快不快"完全糊掉。样本跨度不足时为 null(UI 显示"计算中")。
|
||||
*/
|
||||
speedPerSec?: number | null
|
||||
/** 按当前窗口速度估算的剩余时间(毫秒);速度不可用或分母不可信时为 null。 */
|
||||
etaMs?: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -278,9 +325,8 @@ export function imageTextCoverageState(coverage: ImageTextIndexCoverage): ImageT
|
||||
/**
|
||||
* 处理进度百分比。
|
||||
*
|
||||
* 保留 1 位小数,且**未完成时封顶 99.9%**:
|
||||
* `Math.round(45479 / 45707 * 100)` 会得到 `100`,于是出现了"已建立 · 仅完成 100%"
|
||||
* 这种自相矛盾的显示。进度条可以近似,结论句不行。
|
||||
* 保留 1 位小数,且**未完成时封顶 99.9%**:直接四舍五入会把 99.5% 显示成 100%,
|
||||
* 于是出现"已建立 · 仅完成 100%"这种自相矛盾的显示。进度条可以近似,结论句不行。
|
||||
*/
|
||||
export function imageTextProcessedPercent(processed: number, total: number): number {
|
||||
if (!(total > 0)) return 0
|
||||
@@ -324,7 +370,7 @@ export interface ImageTextIndexCountResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个会话的图片消息计数探针。
|
||||
* 单个会话的图片消息计数结果。
|
||||
*
|
||||
* `count: null` = **统计失败**,不等于 0 张。调用方必须区分处理。
|
||||
*/
|
||||
@@ -417,6 +463,89 @@ export interface ImageTextIndexStartOptions {
|
||||
sinceMs?: number
|
||||
}
|
||||
|
||||
/** 单个阶段的耗时聚合。**只含性能数字**,不含任何图片内容 / 路径 / 标识。 */
|
||||
export interface ImageTextIndexStageStat {
|
||||
count: number
|
||||
mean: number
|
||||
p50: number
|
||||
p95: number
|
||||
max: number
|
||||
}
|
||||
|
||||
/**
|
||||
* backfill 的**只读性能画像**,用来回答"时间花在哪一段"。
|
||||
*
|
||||
* 只写性能数字,不含图片内容 / 路径 / 会话标识;UI 不渲染,仅落到 app log。
|
||||
* 刻意不暴露单张图片的耗时序列:那会把"哪张图慢"变成可推断的信息。
|
||||
*/
|
||||
export interface ImageTextIndexStageTimings {
|
||||
/** 本遍累计计数(与 UI 进度同源)。让这一行日志自洽,不必再去别处对数。 */
|
||||
counters: {
|
||||
processed: number
|
||||
indexed: number
|
||||
empty: number
|
||||
missing: number
|
||||
failed: number
|
||||
}
|
||||
/** 最近窗口的实测速度(张/秒);样本不足或分母不可信时为 null。 */
|
||||
ratePerSec: number | null
|
||||
/** 本遍实际执行过的 OCR 次数(命中已有 artifact 而跳过的不计)。 */
|
||||
ocrExecutions: number
|
||||
/** 本遍生效的 OCR 并发度。 */
|
||||
ocrConcurrency: number
|
||||
/** 找图片文件(同步,占主线程)。 */
|
||||
locate: ImageTextIndexStageStat
|
||||
/** 解密(同步 + CPU,占主线程)。 */
|
||||
decrypt: ImageTextIndexStageStat
|
||||
/** 构造可识别输入(base64 编码;Windows 还包含转 PNG)。 */
|
||||
normalize: ImageTextIndexStageStat
|
||||
/** 识别(异步)。 */
|
||||
ocr: ImageTextIndexStageStat
|
||||
/** 写 artifact + binding(SQLite,单 writer)。 */
|
||||
persist: ImageTextIndexStageStat
|
||||
/**
|
||||
* 单张图片在流水线里的净耗时。
|
||||
*
|
||||
* 分母只含真正进入流水线的图片,所以这个值可以直接与上面五段之和对照;
|
||||
* **不要用"整遍耗时 ÷ 处理张数"**,那会把 `preLoop` 的一次性成本摊进每张图片。
|
||||
*/
|
||||
perImageMs: number
|
||||
/**
|
||||
* 本遍因为"没有可搜索内容变化"而**跳过** Knowledge 重建的会话数。
|
||||
*
|
||||
* 与 `preLoop.onConversationIndexedMs` 配套看:跳过越多、那段时间越小,
|
||||
* 说明门控在起作用。它同时是"到底有没有白做"的直接证据。
|
||||
*/
|
||||
knowledgeIndexSkipped: number
|
||||
/** 进入流水线**之前**的一次性成本(不按图片数摊)。 */
|
||||
preLoop: ImageTextIndexPreLoopCost
|
||||
}
|
||||
|
||||
/**
|
||||
* 流水线**之外**的成本(单位毫秒),用来解释"单张成本很低、整遍却很慢"。
|
||||
*
|
||||
* 这个结构的每一个字段都是"有理由不属于单张成本"的量:
|
||||
* 一次性的、每会话一次的、以及**别的模块**的。它们必须单独可见 ——
|
||||
* 否则 `perImageMs` 会看起来很好,而墙钟吞吐差好几倍,且无从归因。
|
||||
*/
|
||||
export interface ImageTextIndexPreLoopCost {
|
||||
/** 一遍 pass 开始前的一次性成本(能力探测 + 全账号图片统计 + 会话列表)。 */
|
||||
startupMs: number
|
||||
/** └ 其中:统计图片消息总数(遍历全部会话的 SQL)。 */
|
||||
countImageMessagesMs: number
|
||||
/** 每个会话进入流水线前的准备累计(水位 / 计数 / `listMessages`)。 */
|
||||
conversationSetupMs: number
|
||||
/** └ 其中:读取并格式化会话消息累计。**已知的大头之一**。 */
|
||||
listMessagesMs: number
|
||||
/**
|
||||
* 会话完成后等待 Knowledge 重建(`onConversationIndexed`)的累计。
|
||||
*
|
||||
* 这是**别的模块**的成本:Knowledge 侧会对同一个会话再全量读一遍消息并整篇写索引,
|
||||
* 而且如果此时有索引在跑还会先等它。它不在 batch 循环里,所以 `perImageMs` 看不到它。
|
||||
*/
|
||||
onConversationIndexedMs: number
|
||||
}
|
||||
|
||||
/** 对外状态快照(问问微信卡片 / 设置清理页共用同一份)。 */
|
||||
export interface ImageTextIndexStatus {
|
||||
progress: ImageTextIndexProgress
|
||||
@@ -424,4 +553,6 @@ export interface ImageTextIndexStatus {
|
||||
storage: ImageTextIndexStorageStats
|
||||
/** 正在做「检测到多少条图片消息」的 SQL 统计。 */
|
||||
counting: boolean
|
||||
/** 各阶段耗时画像(可选的附加诊断字段,UI 不渲染)。 */
|
||||
stageTimings?: ImageTextIndexStageTimings
|
||||
}
|
||||
+10
-1
@@ -229,10 +229,19 @@ export interface KnowledgeEvidence {
|
||||
* 有值 = 这条结果依赖本地派生内容才能命中(而不是原始消息本身的文字)。
|
||||
* 与 `sourceKind` 正交:`sourceKind` 说的是原始消息是什么,这里说的是"靠什么搜到的"。
|
||||
*/
|
||||
derivedSource?: 'image_ocr'
|
||||
derivedSource?: KnowledgeDerivedSource
|
||||
score?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 派生来源的种类。
|
||||
*
|
||||
* 用 union 而不是 `isOcr: boolean`:以后接视频字幕 / 文件解析时只需要加一个成员,
|
||||
* 不必给每个消费方再添一个布尔字段。UI 侧的展示文案集中在
|
||||
* `renderer/src/components/search/evidenceSourceLabels.ts`,不在这里。
|
||||
*/
|
||||
export type KnowledgeDerivedSource = 'image_ocr' | 'voice_transcript'
|
||||
|
||||
/**
|
||||
* 证据文本面向用户 / 模型时的可读化处理。
|
||||
*
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { KnowledgeEvidence, KnowledgeVoiceCoverage } from './knowledge'
|
||||
import type { KnowledgeDerivedSource, KnowledgeEvidence, KnowledgeVoiceCoverage } from './knowledge'
|
||||
|
||||
export type QueryDirection = 'any' | 'from_target' | 'to_target'
|
||||
export type QueryOrder = 'asc' | 'desc'
|
||||
@@ -119,7 +119,7 @@ export interface QueryEvidenceItem
|
||||
* 让用户知道这段内容来自**图片里的文字**,而不是群友真的发了一条文字消息。
|
||||
* authoritative source 仍然是原始图片消息,`messageRef` 也仍然指向原图。
|
||||
*/
|
||||
derivedSource?: 'image_ocr'
|
||||
derivedSource?: KnowledgeDerivedSource
|
||||
/**
|
||||
* 「从图片里读出来的文字」片段,只用作命中解释。
|
||||
*
|
||||
@@ -242,7 +242,7 @@ export interface QueryMessage {
|
||||
*/
|
||||
imageOcrText?: string
|
||||
/** 派生来源语义:`image_ocr` = 这段文字来自图片识别,而不是原始文字消息。 */
|
||||
derivedSource?: 'image_ocr'
|
||||
derivedSource?: KnowledgeDerivedSource
|
||||
/**
|
||||
* 这条图片消息在本地图片文字索引里的状态。
|
||||
*
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AiSearchPipelineRequest, AiSearchPipelineResult } from './ai-search'
|
||||
import type { KnowledgeDerivedSource } from './knowledge'
|
||||
import type { QueryCorpusScope } from './local-query-api'
|
||||
|
||||
/**
|
||||
@@ -36,10 +37,11 @@ export interface AskWechatEvidenceItem {
|
||||
/**
|
||||
* 命中所依赖的派生来源(与 `messageType` 正交)。
|
||||
*
|
||||
* `image_ocr` = 这条结果靠**图片里的文字**命中,而不是群友真的发了一条文字消息。
|
||||
* Evidence UI 会据此显示轻量来源标记。authoritative source 仍是原始图片消息。
|
||||
* 有值 = 这条结果靠**本地派生内容**命中,而不是原始消息本身的文字
|
||||
* (`image_ocr` = 图片里的文字,`voice_transcript` = 语音转写)。
|
||||
* Evidence UI 会据此多挂一个来源标记;authoritative source 仍是原始消息。
|
||||
*/
|
||||
derivedSource?: 'image_ocr'
|
||||
derivedSource?: KnowledgeDerivedSource
|
||||
/** 「从图片里读出来的文字」片段,只作命中解释(普通文字消息不会有)。 */
|
||||
imageOcrText?: string
|
||||
attachment?: { kind?: string; name?: string; url?: string; sizeBytes?: number }
|
||||
|
||||
+137
-25
@@ -7,15 +7,38 @@
|
||||
// 它不占用 AIVisionRuntimeConfig.source,也不产生任何网络请求。
|
||||
// - 能力边界:只把图片里的文字读出来。它不等于「理解人物 / 理解场景 /
|
||||
// 描述照片 / 理解表情包语义 / 视觉推理」——那些仍然属于 Vision Model。
|
||||
// - Windows 后端为 Windows.Media.Ocr.OcrEngine(经 @napi-rs/system-ocr 调用)。
|
||||
// macOS 本轮只保留架构位置,未实现;Linux 不支持。
|
||||
// - 后端按平台选择(统一经 @napi-rs/system-ocr 调用):
|
||||
// Windows → Windows.Media.Ocr.OcrEngine
|
||||
// macOS → Apple Vision(VNRecognizeTextRequest / RecognizeDocumentsRequest)
|
||||
// Linux 不支持。
|
||||
// - 引擎标识会进入 artifact 指纹与缓存 key,两个平台的结果**不得互相复用**。
|
||||
//
|
||||
// 数据边界(本轮不做):
|
||||
// - 不做历史图片全量 OCR、不做 Knowledge 回填、不把 OCR 文字伪装成原始聊天文字。
|
||||
// 原始消息始终是权威来源,OCR 文字只是派生内容(本轮仅存在于内存)。
|
||||
// 数据边界:
|
||||
// - OCR 文字始终是**派生内容**,会把原图定位回去(artifact + binding),
|
||||
// 但绝不写回 WCDB、也绝不伪装成原始聊天文字;原始消息始终是权威来源。
|
||||
// - 历史图片回填与 Knowledge 回填由 image-text-index 负责,本模块只提供识别能力。
|
||||
|
||||
/** Windows 引擎标识(Windows.Media.Ocr.OcrEngine)。 */
|
||||
export const SYSTEM_OCR_ENGINE_WINDOWS = 'windows-system-ocr'
|
||||
|
||||
/** macOS 引擎标识(Apple Vision)。 */
|
||||
export const SYSTEM_OCR_ENGINE_MACOS = 'macos-system-ocr'
|
||||
|
||||
/** System OCR 引擎标识。这是本地 Runtime,不是 provider id。 */
|
||||
export const SYSTEM_OCR_ENGINE = 'windows-system-ocr'
|
||||
export type SystemOcrEngine = typeof SYSTEM_OCR_ENGINE_WINDOWS | typeof SYSTEM_OCR_ENGINE_MACOS
|
||||
|
||||
/** 支持 System OCR 的平台。Linux 明确不支持。 */
|
||||
export const isSystemOcrPlatform = (platform: string): boolean =>
|
||||
platform === 'win32' || platform === 'darwin'
|
||||
|
||||
/**
|
||||
* 平台 → 引擎标识。
|
||||
*
|
||||
* 不要把引擎串硬编码成某一个平台:它同时是 artifact 指纹的一部分,
|
||||
* 一旦写死,跨平台结果就会互相复用。
|
||||
*/
|
||||
export const resolveSystemOcrEngine = (platform: string): SystemOcrEngine =>
|
||||
platform === 'darwin' ? SYSTEM_OCR_ENGINE_MACOS : SYSTEM_OCR_ENGINE_WINDOWS
|
||||
|
||||
/** 本地 OCR 结果在内存中的缓存时长。 */
|
||||
export const SYSTEM_OCR_CACHE_TTL_MS = 10 * 60 * 1000
|
||||
@@ -27,13 +50,13 @@ export const SYSTEM_OCR_CACHE_TTL_MS = 10 * 60 * 1000
|
||||
export type SystemOcrErrorCode =
|
||||
/** 运行时不可用(native binding 缺失 / 加载失败) */
|
||||
| 'SYSTEM_OCR_UNAVAILABLE'
|
||||
/** 当前平台不支持(Linux,或非 Windows 平台) */
|
||||
/** 当前平台不支持(Linux,或非 Windows / macOS 平台) */
|
||||
| 'UNSUPPORTED_PLATFORM'
|
||||
/** 图片格式不在支持范围内 */
|
||||
| 'UNSUPPORTED_IMAGE'
|
||||
/** 图片解码失败(格式可识别但内容损坏或无法转成 PNG) */
|
||||
/** 图片解码失败(格式可识别但内容损坏或无法转成可识别图像) */
|
||||
| 'IMAGE_DECODE_FAILED'
|
||||
/** 当前 Windows 未安装对应的 OCR 语言支持 */
|
||||
/** 当前 Windows 未安装对应的 OCR 语言支持(macOS 由 Vision 自行决定,不会出现) */
|
||||
| 'OCR_LANGUAGE_UNAVAILABLE'
|
||||
/** 引擎执行失败 */
|
||||
| 'OCR_FAILED'
|
||||
@@ -49,12 +72,17 @@ export type SystemOcrUnavailableReason =
|
||||
export interface SystemOcrCapability {
|
||||
/** 本机当前是否真的可以识别图片文字 */
|
||||
available: boolean
|
||||
engine: typeof SYSTEM_OCR_ENGINE
|
||||
engine: SystemOcrEngine
|
||||
platform: NodeJS.Platform
|
||||
arch: string
|
||||
/** @napi-rs/system-ocr 运行时版本;无法读取时为 null */
|
||||
runtimeVersion: string | null
|
||||
/** 实际可用的 OCR 语言标签(对应 Windows 语言包);null 表示走系统用户语言 */
|
||||
/**
|
||||
* 实际使用的 OCR 语言标签。
|
||||
*
|
||||
* Windows 为系统语言包对应的标签(如 zh-Hans-CN);macOS 由 Vision 自行决定识别语言,
|
||||
* 这里恒为 null(对应 UI 的「跟随系统语言」)。null 也表示走系统语言。
|
||||
*/
|
||||
language: string | null
|
||||
reason?: SystemOcrUnavailableReason
|
||||
/** 面向用户的中文说明,可直接展示 */
|
||||
@@ -71,20 +99,20 @@ export interface SystemOcrBoundingBox {
|
||||
|
||||
export interface SystemOcrLine {
|
||||
text: string
|
||||
/** Windows 恒为 1.0 */
|
||||
/** Windows 恒为 1.0;macOS 为 Vision 返回的逐行平均置信度 */
|
||||
confidence: number
|
||||
boundingBox: SystemOcrBoundingBox
|
||||
}
|
||||
|
||||
/** 本地 OCR 结果。不包含任何 Windows handle / native 内部对象。 */
|
||||
/** 本地 OCR 结果。不包含任何平台 handle / native 内部对象。 */
|
||||
export interface SystemOcrResult {
|
||||
success: boolean
|
||||
/** 归一化后的文本(去掉 CJK 字符之间的引擎伪空格) */
|
||||
text: string
|
||||
lines: SystemOcrLine[]
|
||||
/** 实际使用的 OCR 语言标签;null 表示由系统用户语言决定 */
|
||||
/** 实际使用的 OCR 语言标签;null 表示由系统决定识别语言 */
|
||||
language: string | null
|
||||
engine: typeof SYSTEM_OCR_ENGINE
|
||||
engine: SystemOcrEngine
|
||||
durationMs: number
|
||||
/** 命中内存缓存时为 true */
|
||||
fromCache?: boolean
|
||||
@@ -104,21 +132,24 @@ export interface SystemOcrRequest {
|
||||
/**
|
||||
* 缓存 key 组合。刻意与 ImageInsight 的 `imageHash` 保持不同的键空间,
|
||||
* 保证远端 Vision 的旧结果永远不会被当成"本地 OCR 结果"复用,
|
||||
* 也保证 System OCR 运行时升级后不会永远命中旧结果。
|
||||
* 也保证 System OCR 运行时升级 / 切换平台后不会永远命中旧结果。
|
||||
*/
|
||||
export const buildSystemOcrCacheKey = (input: {
|
||||
imageHash: string
|
||||
language: string | null
|
||||
runtimeVersion: string | null
|
||||
platform?: string
|
||||
}): string =>
|
||||
[
|
||||
engine?: SystemOcrEngine
|
||||
}): string => {
|
||||
const platform = input.platform ?? 'unknown'
|
||||
return [
|
||||
input.imageHash,
|
||||
SYSTEM_OCR_ENGINE,
|
||||
input.platform ?? 'unknown',
|
||||
input.engine ?? resolveSystemOcrEngine(platform),
|
||||
platform,
|
||||
input.language ?? 'auto',
|
||||
input.runtimeVersion ?? 'unknown'
|
||||
].join('|')
|
||||
}
|
||||
|
||||
const CJK_CHAR =
|
||||
/[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef\uac00-\ud7af]/
|
||||
@@ -126,6 +157,9 @@ const CJK_CHAR =
|
||||
/**
|
||||
* Windows OCR 会在每个 CJK 字符之间插入空格("本 地 图 片")。
|
||||
* 这里只删除 **两侧都是 CJK** 的空格,保留 "TraceMemo 本地图片文字识别" 里的真实分隔。
|
||||
*
|
||||
* macOS(Vision)本就输出连续中文,这条规则对它恒等;保留是为了两个平台共用一条
|
||||
* 归一化路径,而不是给 macOS 加特例。
|
||||
*/
|
||||
export const normalizeSystemOcrText = (value: string): string => {
|
||||
const source = String(value ?? '')
|
||||
@@ -149,8 +183,11 @@ export const normalizeSystemOcrText = (value: string): string => {
|
||||
return result.trim()
|
||||
}
|
||||
|
||||
/** 把系统 locale(如 zh-CN / en-US)映射成 Windows OCR 语言标签。 */
|
||||
const LANGUAGE_TAG_BY_LOCALE: Record<string, string> = {
|
||||
/**
|
||||
* 把系统 locale(如 zh-CN / en-US)映射成 **Windows OCR 语言标签**
|
||||
* (即 Windows 语言包里注册的 BCP-47 标签,中文带 region 子标签)。
|
||||
*/
|
||||
const WINDOWS_LANGUAGE_TAG_BY_LOCALE: Record<string, string> = {
|
||||
zh: 'zh-Hans-CN',
|
||||
'zh-cn': 'zh-Hans-CN',
|
||||
'zh-hans': 'zh-Hans-CN',
|
||||
@@ -186,7 +223,51 @@ const LANGUAGE_TAG_BY_LOCALE: Record<string, string> = {
|
||||
'ru-ru': 'ru-RU'
|
||||
}
|
||||
|
||||
export const resolveSystemOcrLanguageTag = (
|
||||
/**
|
||||
* 把系统 locale 映射成 **Apple Vision 语言标签**。
|
||||
*
|
||||
* 与 Windows 表刻意分开:Vision 只认脚本级子标签(`zh-Hans` / `zh-Hant`),
|
||||
* 不认 `zh-Hans-CN` 这类 region 组合;港台繁体统一收敛到 `zh-Hant`。
|
||||
*/
|
||||
const MACOS_LANGUAGE_TAG_BY_LOCALE: Record<string, string> = {
|
||||
zh: 'zh-Hans',
|
||||
'zh-cn': 'zh-Hans',
|
||||
'zh-sg': 'zh-Hans',
|
||||
'zh-hans': 'zh-Hans',
|
||||
'zh-hans-cn': 'zh-Hans',
|
||||
'zh-hans-sg': 'zh-Hans',
|
||||
'zh-tw': 'zh-Hant',
|
||||
'zh-hk': 'zh-Hant',
|
||||
'zh-mo': 'zh-Hant',
|
||||
'zh-hant': 'zh-Hant',
|
||||
'zh-hant-tw': 'zh-Hant',
|
||||
'zh-hant-hk': 'zh-Hant',
|
||||
'zh-hant-mo': 'zh-Hant',
|
||||
en: 'en-US',
|
||||
'en-us': 'en-US',
|
||||
'en-gb': 'en-GB',
|
||||
'en-au': 'en-AU',
|
||||
'en-ca': 'en-CA',
|
||||
ja: 'ja-JP',
|
||||
'ja-jp': 'ja-JP',
|
||||
ko: 'ko-KR',
|
||||
'ko-kr': 'ko-KR',
|
||||
fr: 'fr-FR',
|
||||
'fr-fr': 'fr-FR',
|
||||
de: 'de-DE',
|
||||
'de-de': 'de-DE',
|
||||
es: 'es-ES',
|
||||
'es-es': 'es-ES',
|
||||
it: 'it-IT',
|
||||
'it-it': 'it-IT',
|
||||
pt: 'pt-BR',
|
||||
'pt-br': 'pt-BR',
|
||||
ru: 'ru-RU',
|
||||
'ru-ru': 'ru-RU'
|
||||
}
|
||||
|
||||
const lookupLanguageTag = (
|
||||
table: Record<string, string>,
|
||||
locale: string | null | undefined
|
||||
): string | null => {
|
||||
const normalized = String(locale ?? '')
|
||||
@@ -194,11 +275,26 @@ export const resolveSystemOcrLanguageTag = (
|
||||
.toLowerCase()
|
||||
.replace(/_/g, '-')
|
||||
if (!normalized) return null
|
||||
if (LANGUAGE_TAG_BY_LOCALE[normalized]) return LANGUAGE_TAG_BY_LOCALE[normalized]
|
||||
if (table[normalized]) return table[normalized]
|
||||
const primary = normalized.split('-')[0]
|
||||
return LANGUAGE_TAG_BY_LOCALE[primary] ?? null
|
||||
return table[primary] ?? null
|
||||
}
|
||||
|
||||
/** 系统 locale → Windows OCR 语言标签。 */
|
||||
export const resolveWindowsOcrLanguageTag = (locale: string | null | undefined): string | null =>
|
||||
lookupLanguageTag(WINDOWS_LANGUAGE_TAG_BY_LOCALE, locale)
|
||||
|
||||
/** 系统 locale → Apple Vision 语言标签。 */
|
||||
export const resolveMacOcrLanguageTag = (locale: string | null | undefined): string | null =>
|
||||
lookupLanguageTag(MACOS_LANGUAGE_TAG_BY_LOCALE, locale)
|
||||
|
||||
/** 按平台把系统 locale 映射成该平台 OCR 引擎接受的语言标签。 */
|
||||
export const resolveSystemOcrLanguageTag = (
|
||||
locale: string | null | undefined,
|
||||
platform: string = 'win32'
|
||||
): string | null =>
|
||||
platform === 'darwin' ? resolveMacOcrLanguageTag(locale) : resolveWindowsOcrLanguageTag(locale)
|
||||
|
||||
/**
|
||||
* 把 native 错误映射成产品级错误码。
|
||||
*
|
||||
@@ -206,6 +302,16 @@ export const resolveSystemOcrLanguageTag = (
|
||||
* - 语言包缺失 / 引擎无法创建:`Windows error 操作成功完成。 (0x00000000)`
|
||||
* —— TryCreateFromLanguage 返回 null 引擎但 HRESULT 是 S_OK,非常容易误判。
|
||||
* - 送给解码器的字节不是可识别的图片:`Windows error Could not recognize file (0x80070005)`
|
||||
*
|
||||
* 已确认的 macOS 行为(1.2.0 / Vision):
|
||||
* - 图片无法解码成 CGImage(截断、伪造魔数、维度非法):
|
||||
* `CRImage Reader Detector was given zero-dimensioned image (0 x 0)`
|
||||
* - 图片任一边不超过 2px:`The image is too small in at least one dimension 2 x 2 ...`
|
||||
* - **图片没有文字时是抛错而不是返回空文本**:`No text recognized`
|
||||
* —— 它必须映射成 `OCR_EMPTY_RESULT`(正常终态)。映射成失败会让表情包 /
|
||||
* 风景图 / 头像全部变成"可重试失败",既污染派生库也会被反复重试。
|
||||
* - macOS 没有"语言包缺失"这个概念(Vision 自行决定识别语言),
|
||||
* 所以这里不会映射出 OCR_LANGUAGE_UNAVAILABLE。
|
||||
*/
|
||||
export const mapSystemOcrNativeError = (message: string): SystemOcrErrorCode => {
|
||||
const detail = String(message ?? '')
|
||||
@@ -216,6 +322,12 @@ export const mapSystemOcrNativeError = (message: string): SystemOcrErrorCode =>
|
||||
if (/\(0x00000000\)/.test(detail)) return 'OCR_LANGUAGE_UNAVAILABLE'
|
||||
if (/Could not recognize file/i.test(detail)) return 'IMAGE_DECODE_FAILED'
|
||||
if (/Could not open file/i.test(detail)) return 'IMAGE_DECODE_FAILED'
|
||||
// macOS Vision / CoreImage 解码失败。
|
||||
if (/zero-dimensioned image/i.test(detail)) return 'IMAGE_DECODE_FAILED'
|
||||
if (/The image is too small/i.test(detail)) return 'IMAGE_DECODE_FAILED'
|
||||
if (/CRImage|CIImage|CGImage/i.test(detail)) return 'IMAGE_DECODE_FAILED'
|
||||
// macOS Vision 的"图里没有文字":正常终态,不是失败。
|
||||
if (/No text recognized/i.test(detail)) return 'OCR_EMPTY_RESULT'
|
||||
return 'OCR_FAILED'
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user