mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +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
@@ -24,6 +24,87 @@ import {
|
||||
type ContactSearchIndex
|
||||
} from '../../shared/contact-search'
|
||||
|
||||
/**
|
||||
* 谁在读消息。
|
||||
*
|
||||
* 只允许下面这几个固定标签 —— 日志里**不能**出现会话 md5 / session id / wxid /
|
||||
* 群名 / 联系人 / 路径,所以调用方身份只能靠标签表达。
|
||||
* 落在集合外的调用点一律记 `unknown`。
|
||||
*/
|
||||
export type ListMessagesCaller =
|
||||
| 'image-text-index'
|
||||
| 'group-monitor'
|
||||
| 'archive'
|
||||
| 'knowledge'
|
||||
| 'unknown'
|
||||
|
||||
/** 进程生命周期内单调递增的读取序号,用来把"同一段时间的几次调用"关联起来(不是稳定标识)。 */
|
||||
let listMessagesRequestSeq = 0
|
||||
|
||||
export function nextListMessagesRequestId(): string {
|
||||
listMessagesRequestSeq += 1
|
||||
return `request-${listMessagesRequestSeq}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次 `listMessages` 的性能拆解。
|
||||
*
|
||||
* 存在的意义:大会话的全量读取会把主进程卡住数秒,而原来只有一行 `totalMs`,
|
||||
* 无法判断时间花在 **WCDB 查询**、**JS 逐条格式化**,还是 **内容解析**上。
|
||||
*
|
||||
* 覆盖面:`totalMs` 是外层入口的整段耗时;`formatMs` 包含 `contentParseMs` 与
|
||||
* `dateFormatMs`(后两者是它的子集,不可与 `formatMs` 相加)。
|
||||
*/
|
||||
export interface ListMessagesPerf {
|
||||
caller: ListMessagesCaller
|
||||
requestId: string
|
||||
/** WCDB 返回的原始行数(异步路径里含原生查询时间)。 */
|
||||
rawRows: number
|
||||
formattedRows: number
|
||||
totalMs: number
|
||||
/** 取原始行:同步 `getUserMessages` 或 `await getUserMessagesAsync`。 */
|
||||
rawReadMs: number
|
||||
/** 逐条构造 `FormattedMessage`(整个 `map`)。 */
|
||||
formatMs: number
|
||||
/** └ 其中:日期格式化(`toLocaleString`)。 */
|
||||
dateFormatMs: number
|
||||
/** └ 其中:内容解析(`parseMessageContent` / `parseStickerMessageFromRow`)。 */
|
||||
contentParseMs: number
|
||||
/** 召回归档合并与排序。 */
|
||||
sortMs: number
|
||||
/** `totalMs` 减去上面已计部分。 */
|
||||
otherMs: number
|
||||
}
|
||||
|
||||
function emptyPerf(caller: ListMessagesCaller, requestId: string): ListMessagesPerf {
|
||||
return {
|
||||
caller,
|
||||
requestId,
|
||||
rawRows: 0,
|
||||
formattedRows: 0,
|
||||
totalMs: 0,
|
||||
rawReadMs: 0,
|
||||
formatMs: 0,
|
||||
dateFormatMs: 0,
|
||||
contentParseMs: 0,
|
||||
sortMs: 0,
|
||||
otherMs: 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只在**值得看**的时候打一行:大会话、或者总耗时已经明显影响交互。
|
||||
* 单行、可 grep、无任何会话标识。
|
||||
*/
|
||||
function logListMessagesPerf(perf: ListMessagesPerf): void {
|
||||
perf.otherMs = Math.max(0, perf.totalMs - perf.rawReadMs - perf.formatMs - perf.sortMs)
|
||||
const noteworthy = perf.formattedRows >= 20_000 || perf.totalMs >= 1_000
|
||||
if (!noteworthy) return
|
||||
console.log(
|
||||
`[ChatServicePerf] caller=${perf.caller} request=${perf.requestId} rows=${perf.formattedRows} rawRows=${perf.rawRows} totalMs=${perf.totalMs} rawReadMs=${perf.rawReadMs} formatMs=${perf.formatMs} dateFormatMs=${perf.dateFormatMs} contentParseMs=${perf.contentParseMs} sortMs=${perf.sortMs} otherMs=${perf.otherMs}`
|
||||
)
|
||||
}
|
||||
|
||||
export function getCurrentKey(): string {
|
||||
if (!dbRef) return ''
|
||||
try {
|
||||
@@ -199,7 +280,8 @@ export function isReady(): boolean {
|
||||
|
||||
/** Session 行的时间字段可能是秒,也可能是毫秒;1e11 以下按秒换算。 */
|
||||
function sessionTimeToEpochMs(value: unknown): number | null {
|
||||
const numeric = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN
|
||||
const numeric =
|
||||
typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN
|
||||
if (!Number.isFinite(numeric) || numeric <= 0) return null
|
||||
return Math.round(numeric < 1e11 ? numeric * 1000 : numeric)
|
||||
}
|
||||
@@ -379,28 +461,52 @@ function listSourceMessages(
|
||||
endTime?: number,
|
||||
options?: { limit?: number },
|
||||
rawMessagesOverride?: WechatMessage[],
|
||||
requestId = 'NO-REQUEST'
|
||||
requestId = 'NO-REQUEST',
|
||||
perf?: ListMessagesPerf
|
||||
): FormattedMessage[] {
|
||||
if (!dbRef) return []
|
||||
|
||||
const startedAt = Date.now()
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const username = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
const isGroupChat = Boolean(username?.endsWith('@chatroom'))
|
||||
wcdbDebugLog(
|
||||
`[${requestId}] ChatService listSourceMessages start md5=${userMd5} username=${username || ''} start=${startTime || 0} end=${endTime || 0} limit=${options?.limit || 0}`
|
||||
`[${requestId}] ChatService listSourceMessages start start=${startTime || 0} end=${endTime || 0} limit=${options?.limit || 0} hasOverride=${rawMessagesOverride ? 1 : 0}`
|
||||
)
|
||||
const rawReadStartedAt = Date.now()
|
||||
const rawMessages =
|
||||
rawMessagesOverride ?? dbRef.getUserMessages(userMd5, startTime, endTime, options)
|
||||
if (perf) {
|
||||
perf.rawReadMs += Date.now() - rawReadStartedAt
|
||||
perf.rawRows += rawMessages.length
|
||||
}
|
||||
wcdbDebugLog(
|
||||
`[${requestId}] ChatService raw snapshot ready raw=${rawMessages.length} cost=${Date.now() - startedAt}ms`
|
||||
`[${requestId}] ChatService raw snapshot ready raw=${rawMessages.length} cost=${Date.now() - rawReadStartedAt}ms`
|
||||
)
|
||||
|
||||
/** 把"内容解析"单独计时,才能区分"消息多"和"每条都在做解析"。 */
|
||||
const timedParse = <T>(fn: () => T): T => {
|
||||
if (!perf) return fn()
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
return fn()
|
||||
} finally {
|
||||
perf.contentParseMs += Date.now() - startedAt
|
||||
}
|
||||
}
|
||||
|
||||
const formatStartedAt = Date.now()
|
||||
const formatted = rawMessages.map((msg: WechatMessage) => {
|
||||
const rawMsgType = parseInt(msg.messageType)
|
||||
const msgType = normalizeMsgType(msg.messageType)
|
||||
const createTime = parseInt(msg.msgCreateTime)
|
||||
const date = new Date(createTime * 1000)
|
||||
/**
|
||||
* 逐条 `toLocaleString` 每次都会新建一个 ICU formatter —— 大会话里这是主要成本,
|
||||
* 所以单独计时,避免它被笼统算进"格式化耗时"。
|
||||
*/
|
||||
const dateFormatStartedAt = perf ? Date.now() : 0
|
||||
const datetimeText = date.toLocaleString('zh-CN', { hour12: false })
|
||||
if (perf) perf.dateFormatMs += Date.now() - dateFormatStartedAt
|
||||
const isMine = msg.mesDes !== 1
|
||||
const localId = parseInt(msg.mesLocalID) || 0
|
||||
|
||||
@@ -434,7 +540,7 @@ function listSourceMessages(
|
||||
/<patinfo\b|<type>\s*62\s*<\/type>/i.test(rawContent) ||
|
||||
([10000, 10002].includes(msgType) && /拍了拍/i.test(rawContent))
|
||||
if (isPatMessage) {
|
||||
const system = parseMessageContent(content, 10000)
|
||||
const system = timedParse(() => parseMessageContent(content, 10000))
|
||||
const patContent =
|
||||
system.type === 'system'
|
||||
? { ...system, pat: true }
|
||||
@@ -461,9 +567,9 @@ function listSourceMessages(
|
||||
/<(?:emoji|sticker|emoticon)\b/i.test(content) || /<type>\s*47\s*<\/type>/i.test(content)
|
||||
const rowSticker =
|
||||
inferredMsgType === 47 || (inferredMsgType === 49 && !isQuotePayload && hasStickerPayload)
|
||||
? parseStickerMessageFromRow(msg, content)
|
||||
? timedParse(() => parseStickerMessageFromRow(msg, content))
|
||||
: undefined
|
||||
const parsedContent = parseMessageContent(content, inferredMsgType)
|
||||
const parsedContent = timedParse(() => parseMessageContent(content, inferredMsgType))
|
||||
const rowStickerUrl = rowSticker?.type === 'sticker' ? String(rowSticker.url || '') : ''
|
||||
const parsedShareUrl = parsedContent.type === 'share' ? parsedContent.url : ''
|
||||
const redPacketUrl = rowStickerUrl || parsedShareUrl
|
||||
@@ -535,7 +641,7 @@ function listSourceMessages(
|
||||
}
|
||||
|
||||
if (!contentData && typeof content === 'string' && /^[0-9a-fA-F]{64,}$/.test(content.trim())) {
|
||||
const parsed = parseStickerMessageFromRow(msg, content)
|
||||
const parsed = timedParse(() => parseStickerMessageFromRow(msg, content))
|
||||
if (parsed.type === 'sticker') {
|
||||
if (!parsed.url && parsed.md5) {
|
||||
parsed.url = wcdb4Client.resolveEmoticonCdnUrl(parsed.md5)
|
||||
@@ -616,7 +722,7 @@ function listSourceMessages(
|
||||
from: contentData?.type === 'system' ? 'system' : isMine ? 'assistant' : 'user',
|
||||
isSender: isMine,
|
||||
type: displayType,
|
||||
datetime: date.toLocaleString('zh-CN', { hour12: false }),
|
||||
datetime: datetimeText,
|
||||
content,
|
||||
img,
|
||||
name,
|
||||
@@ -634,9 +740,10 @@ function listSourceMessages(
|
||||
}
|
||||
})
|
||||
|
||||
console.log(
|
||||
`[ChatService] listMessages end md5=${userMd5} formatted=${formatted.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
if (perf) {
|
||||
perf.formatMs += Date.now() - formatStartedAt
|
||||
perf.formattedRows += formatted.length
|
||||
}
|
||||
return formatted
|
||||
}
|
||||
|
||||
@@ -644,13 +751,38 @@ export function listMessages(
|
||||
userMd5: string,
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
options?: { limit?: number }
|
||||
options?: { limit?: number },
|
||||
caller: ListMessagesCaller = 'unknown'
|
||||
): FormattedMessage[] {
|
||||
const sourceMessages = listSourceMessages(userMd5, startTime, endTime, options)
|
||||
if (!dbRef) return sourceMessages
|
||||
const username = dbRef.getWcdb4Client().getUsernameByMd5(userMd5) || ''
|
||||
recordRecallArchiveMessages(userMd5, username, sourceMessages)
|
||||
return mergeRecallArchiveMessages(userMd5, sourceMessages, startTime, endTime, options?.limit)
|
||||
const perf = emptyPerf(caller, nextListMessagesRequestId())
|
||||
const totalStartedAt = Date.now()
|
||||
try {
|
||||
const sourceMessages = listSourceMessages(
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
options,
|
||||
undefined,
|
||||
perf.requestId,
|
||||
perf
|
||||
)
|
||||
if (!dbRef) return sourceMessages
|
||||
const username = dbRef.getWcdb4Client().getUsernameByMd5(userMd5) || ''
|
||||
const recallStartedAt = Date.now()
|
||||
recordRecallArchiveMessages(userMd5, username, sourceMessages)
|
||||
const result = mergeRecallArchiveMessages(
|
||||
userMd5,
|
||||
sourceMessages,
|
||||
startTime,
|
||||
endTime,
|
||||
options?.limit
|
||||
)
|
||||
perf.sortMs += Date.now() - recallStartedAt
|
||||
return result
|
||||
} finally {
|
||||
perf.totalMs = Date.now() - totalStartedAt
|
||||
logListMessagesPerf(perf)
|
||||
}
|
||||
}
|
||||
|
||||
export async function listMessagesAsync(
|
||||
@@ -658,42 +790,106 @@ export async function listMessagesAsync(
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
options?: { limit?: number },
|
||||
requestId = 'NO-REQUEST'
|
||||
requestId = '',
|
||||
caller: ListMessagesCaller = 'unknown'
|
||||
): Promise<FormattedMessage[]> {
|
||||
if (!dbRef) return []
|
||||
const startedAt = Date.now()
|
||||
wcdbDebugLog(`[${requestId}] ChatService listMessagesAsync start md5=${userMd5}`)
|
||||
const rawMessages = await dbRef.getUserMessagesAsync(
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
options,
|
||||
requestId
|
||||
)
|
||||
wcdbDebugLog(
|
||||
`[${requestId}] ChatService getUserMessagesAsync end raw=${rawMessages.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
const sourceMessages = listSourceMessages(
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
options,
|
||||
rawMessages,
|
||||
requestId
|
||||
)
|
||||
const username = dbRef.getWcdb4Client().getUsernameByMd5(userMd5) || ''
|
||||
recordRecallArchiveMessages(userMd5, username, sourceMessages)
|
||||
const result = mergeRecallArchiveMessages(
|
||||
userMd5,
|
||||
sourceMessages,
|
||||
startTime,
|
||||
endTime,
|
||||
options?.limit
|
||||
)
|
||||
wcdbDebugLog(
|
||||
`[${requestId}] ChatService listMessagesAsync end formatted=${result.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
return result
|
||||
const perf = emptyPerf(caller, requestId || nextListMessagesRequestId())
|
||||
const totalStartedAt = Date.now()
|
||||
try {
|
||||
wcdbDebugLog(`[${perf.requestId}] ChatService listMessagesAsync start`)
|
||||
const rawReadStartedAt = Date.now()
|
||||
const rawMessages = await dbRef.getUserMessagesAsync(
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
options,
|
||||
perf.requestId
|
||||
)
|
||||
perf.rawReadMs += Date.now() - rawReadStartedAt
|
||||
wcdbDebugLog(
|
||||
`[${perf.requestId}] ChatService getUserMessagesAsync end raw=${rawMessages.length} cost=${Date.now() - rawReadStartedAt}ms`
|
||||
)
|
||||
const sourceMessages = listSourceMessages(
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
options,
|
||||
rawMessages,
|
||||
perf.requestId,
|
||||
perf
|
||||
)
|
||||
const username = dbRef.getWcdb4Client().getUsernameByMd5(userMd5) || ''
|
||||
const recallStartedAt = Date.now()
|
||||
recordRecallArchiveMessages(userMd5, username, sourceMessages)
|
||||
const result = mergeRecallArchiveMessages(
|
||||
userMd5,
|
||||
sourceMessages,
|
||||
startTime,
|
||||
endTime,
|
||||
options?.limit
|
||||
)
|
||||
perf.sortMs += Date.now() - recallStartedAt
|
||||
wcdbDebugLog(
|
||||
`[${perf.requestId}] ChatService listMessagesAsync end formatted=${result.length} cost=${Date.now() - totalStartedAt}ms`
|
||||
)
|
||||
return result
|
||||
} finally {
|
||||
perf.totalMs = Date.now() - totalStartedAt
|
||||
logListMessagesPerf(perf)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只取**图片消息**(图片文字索引专用)。
|
||||
*
|
||||
* 与 `listMessagesAsync` 的唯一差别是"读哪些行":由 WCDB 在 SQL 层按消息类型过滤,
|
||||
* 而不是把整个会话读进来再在 JS 里筛。格式化和消息身份走的是**同一套代码**
|
||||
* (同一个 `listSourceMessages`),所以 `messageId` / `contentData` / 派生键完全不变。
|
||||
*
|
||||
* 存在的理由:大会话(十几万到二十几万条消息)全量读一次要 15s 以上,
|
||||
* 而图片索引只关心图片;这是数据边界错了,不是性能调优问题。
|
||||
*/
|
||||
export async function listImageMessagesAsync(
|
||||
userMd5: string,
|
||||
requestId = '',
|
||||
caller: ListMessagesCaller = 'unknown'
|
||||
): Promise<FormattedMessage[]> {
|
||||
if (!dbRef) return []
|
||||
const perf = emptyPerf(caller, requestId || nextListMessagesRequestId())
|
||||
const totalStartedAt = Date.now()
|
||||
try {
|
||||
const rawReadStartedAt = Date.now()
|
||||
const rawMessages = await dbRef
|
||||
.getWcdb4Client()
|
||||
.listImageMessagesAsync(userMd5, { requestId: perf.requestId })
|
||||
perf.rawReadMs += Date.now() - rawReadStartedAt
|
||||
const sourceMessages = listSourceMessages(
|
||||
userMd5,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
rawMessages,
|
||||
perf.requestId,
|
||||
perf
|
||||
)
|
||||
const username = dbRef.getWcdb4Client().getUsernameByMd5(userMd5) || ''
|
||||
const recallStartedAt = Date.now()
|
||||
recordRecallArchiveMessages(userMd5, username, sourceMessages)
|
||||
// 召回归档里可能还留着已被撤回的图片;跳过合并会漏索引,所以照旧合并。
|
||||
const result = mergeRecallArchiveMessages(
|
||||
userMd5,
|
||||
sourceMessages,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined
|
||||
)
|
||||
perf.sortMs += Date.now() - recallStartedAt
|
||||
return result
|
||||
} finally {
|
||||
perf.totalMs = Date.now() - totalStartedAt
|
||||
logListMessagesPerf(perf)
|
||||
}
|
||||
}
|
||||
|
||||
export async function listMessagesForExport(
|
||||
@@ -702,24 +898,35 @@ export async function listMessagesForExport(
|
||||
endTime?: number
|
||||
): Promise<FormattedMessage[]> {
|
||||
if (!dbRef) return []
|
||||
const rawMessages = await dbRef.getUserMessagesForExport(userMd5, startTime, endTime)
|
||||
const sourceMessages = listSourceMessages(userMd5, startTime, endTime, undefined, rawMessages)
|
||||
const username = dbRef.getWcdb4Client().getUsernameByMd5(userMd5) || ''
|
||||
recordRecallArchiveMessages(userMd5, username, sourceMessages)
|
||||
const mergedMessages = mergeRecallArchiveMessages(userMd5, sourceMessages, startTime, endTime)
|
||||
console.log(
|
||||
`[ChatService] listMessagesForExport end md5=${userMd5} source=${sourceMessages.length} merged=${mergedMessages.length}`
|
||||
)
|
||||
return mergedMessages
|
||||
const perf = emptyPerf('archive', nextListMessagesRequestId())
|
||||
const totalStartedAt = Date.now()
|
||||
try {
|
||||
const rawReadStartedAt = Date.now()
|
||||
const rawMessages = await dbRef.getUserMessagesForExport(userMd5, startTime, endTime)
|
||||
perf.rawReadMs += Date.now() - rawReadStartedAt
|
||||
const sourceMessages = listSourceMessages(
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
undefined,
|
||||
rawMessages,
|
||||
perf.requestId,
|
||||
perf
|
||||
)
|
||||
const username = dbRef.getWcdb4Client().getUsernameByMd5(userMd5) || ''
|
||||
const recallStartedAt = Date.now()
|
||||
recordRecallArchiveMessages(userMd5, username, sourceMessages)
|
||||
const mergedMessages = mergeRecallArchiveMessages(userMd5, sourceMessages, startTime, endTime)
|
||||
perf.sortMs += Date.now() - recallStartedAt
|
||||
return mergedMessages
|
||||
} finally {
|
||||
perf.totalMs = Date.now() - totalStartedAt
|
||||
logListMessagesPerf(perf)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count voice rows without hydrating message content. This is used by the
|
||||
* batch-selection view, where loading every conversation would make opening
|
||||
* Settings noticeably slow.
|
||||
*/
|
||||
/**
|
||||
* 图片消息计数探针(SQL 统计,不解密)。
|
||||
* 图片消息计数(SQL 统计,不解密)。
|
||||
*
|
||||
* 返回 `count: null` 表示**统计失败**,不是 0 张。调用方必须区分这两件事 ——
|
||||
* 否则"数不出来"会被显示成"账号里没有图片",用户会因此放弃建立索引。
|
||||
|
||||
@@ -322,16 +322,16 @@ class ImageInsightService {
|
||||
// 与 Vision 路径的关系:
|
||||
// ImageInsightService 是统一编排入口,下面挂两条互不干扰的运行时——
|
||||
// - Vision Model Runtime(AIProviderService,走 AI Provider,可能联网)
|
||||
// - Windows System OCR Runtime(SystemOcrService,纯本地,不联网)
|
||||
// - System OCR Runtime(SystemOcrService,纯本地,不联网)
|
||||
//
|
||||
// 边界与约束:
|
||||
// 1. 本地 OCR 结果属于 **派生内容**,原始消息始终是权威来源;
|
||||
// 本轮不落库、不写 Knowledge、不做历史图片 backfill。
|
||||
// 本服务只返回识别文本,不做持久化 —— 落库与 Knowledge 回填在图片文字索引侧。
|
||||
// 2. 本地 OCR 结果 **不会** 写入 image-insights.json——那是 Vision 结果的缓存,
|
||||
// 两者的缓存键空间也不同(见 buildSystemOcrCacheKey)。
|
||||
// 3. 这里不读取也绝不修改 AI Vision Provider / 模型配置。
|
||||
|
||||
/** 本机是否支持本地图片文字识别(Windows System OCR)。 */
|
||||
/** 本机是否支持本地图片文字识别(System OCR,引擎按平台决定)。 */
|
||||
getSystemOcrCapability(): Promise<SystemOcrCapability> {
|
||||
return systemOcrService.getCapability()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* 为什么单独一个库而不是往 knowledge.sqlite 里加表:
|
||||
* - 清理语义干净:整个能力 = 三个文件(.sqlite/-wal/-shm),删掉即可,不留残渣。
|
||||
* - 零迁移风险:不动已发布的 knowledge schema(§26 要求升级不破坏既有派生库)。
|
||||
* - 零迁移风险:不动已发布的 knowledge schema(升级不得破坏既有派生库)。
|
||||
* - 去重语义天然:artifact 按「图片内容 + OCR 运行时指纹」唯一,binding 承担多来源。
|
||||
*
|
||||
* 账号隔离与 Knowledge 一致:路径按 accountId 摘要分目录 + 库内 account_id 自证。
|
||||
@@ -345,6 +345,29 @@ export class ImageTextIndexStore {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描进度:所有会话累计「应扫多少张图片消息」与「实际扫过多少张」。
|
||||
*
|
||||
* 与上面的 `readCountedTotal()` 分工必须分清:
|
||||
* - `readCountedTotal()` 是 `countImageMessages()` 给出的**预估**分母(遍历消息表数出来的,
|
||||
* 会随新消息变动,且与「归档合并后流水线真正拿到的消息集合」并不完全一致);
|
||||
* - 这里是流水线**真实走过**的集合。
|
||||
*
|
||||
* 进度必须用后者。拿预估值当分母,进度会永远差最后几个百分点,
|
||||
* 让已经跑完的索引一直显示成"部分完成"。
|
||||
*/
|
||||
readScanProgress(): { total: number; processed: number } {
|
||||
const row = this.database
|
||||
.prepare(
|
||||
'SELECT SUM(image_total) AS total, SUM(image_processed) AS processed FROM image_ocr_scan_state'
|
||||
)
|
||||
.get() as Record<string, unknown> | undefined
|
||||
return {
|
||||
total: Number(row?.total ?? 0) || 0,
|
||||
processed: Number(row?.processed ?? 0) || 0
|
||||
}
|
||||
}
|
||||
|
||||
writeCountedTotal(input: { total: number; countedAt: number; complete: boolean }): void {
|
||||
this.writeMeta('total_image_messages', String(input.total))
|
||||
this.writeMeta('total_image_counted_at', String(input.countedAt))
|
||||
|
||||
@@ -109,10 +109,8 @@ export interface QueryAgentTraceItem {
|
||||
/**
|
||||
* 本次 Tool Result 里携带 OCR 派生文本的图片消息/证据条数(诊断用,不进模型上下文)。
|
||||
*
|
||||
* 存在的意义是让"图片已经识别出文字、但模型没拿到"这类**链路断点**可以被直接观测:
|
||||
* 真机上曾经出现过 `query_messages` 返回了图片消息却只带 `attachment`、
|
||||
* 模型因此回答"没有取得 OCR 文字"。当时从回答文本无法判断是"索引没建"还是"没接上",
|
||||
* 因为这两件事在日志里长得一模一样。有了这个数字就能一眼分开。
|
||||
* 用来区分"图片索引没建"与"索引建了但没接到 tool result 上"这两类链路断点 ——
|
||||
* 没有这个数字时,两者在回答文本里长得一样。
|
||||
*/
|
||||
imageOcrTextCount?: number
|
||||
/** 本次 Tool Result 里图片文字索引的覆盖度状态(`not_built` / `partial` / `complete` / `failed`)。 */
|
||||
@@ -213,6 +211,26 @@ export interface QueryAgentEvidenceItem {
|
||||
const MAX_EVIDENCE_ITEMS = 40
|
||||
|
||||
|
||||
/**
|
||||
* 回答格式与单轮语义的硬规则。
|
||||
*
|
||||
* 单独抽出来是为了让它可被测试直接断言 —— 这几条是产品契约,不是措辞偏好:
|
||||
* 换行、改写都可以,但三条实质约束不能丢。
|
||||
*/
|
||||
export const ANSWER_RULES = `
|
||||
回答结构(检索型结果):
|
||||
- **不要用 Markdown 表格**承载多条命中结果 —— 结果栏很窄,表格列宽会错位、长字段换行后难读。改用编号列表:先给一句结论,再逐条列出(发送者 / 时间 / 会话 / 类型 / 内容),最后按需说明与范围。
|
||||
- 逐条里的内容若来自本地派生(图片 OCR、语音转写),要写明它来自派生内容,不要说成群友发过的一条这样的文字消息。
|
||||
|
||||
单轮语义(重要):
|
||||
- 当前是**单次检索回答**:一次提问、一次检索、一次回答。没有自动连续的多轮工具执行。
|
||||
- **禁止**任何"下一步还能帮你继续"的邀约,包括但不限于:"如果你需要,我可以…""要不要我继续…""我还可以帮你进一步…""需要的话我再查…""我可以再帮你分析…"。除非该动作在**本轮已经真实执行过**。
|
||||
- 需要收口时,用陈述句说明范围(如"以上为当前检索范围内的结果"),或者直接结束。
|
||||
|
||||
事实与推断:
|
||||
- 没有内容哈希 / artifact 同一性这些直接证据时,不要写"就是同一张图转发了三次"这类确定说法,只能写"内容高度相似,可能是同一张或同系列"。
|
||||
- 范围说明只在确有必要时给:索引覆盖不完整、内容属于本地派生、时间或检索范围受限、有已知未覆盖数据。不要在每次回答末尾机械复读同一句。`
|
||||
|
||||
const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使用提供的四个 Query Tool 获取事实,最终回答只基于 Tool Result。
|
||||
|
||||
规划原则:
|
||||
@@ -250,7 +268,8 @@ const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使
|
||||
- not_indexed:这条图片还没进图片文字索引。**不许**把“还没索引”说成“图片里没有文字”;若 imageOcrCoverage 不是 complete,必须说明当前无法确认。
|
||||
- 图片文字索引状态一律以 Tool Result 的结构化字段为准。**不要**在回答里凭空建议“可以先建立图片文字索引再查”——只有 imageOcrCoverage.state 确实是 not_built 时才可以这么说。
|
||||
- 区分「图片里确实没有文字」(OCR 结果为空,属于已处理的正常终态)与「图片还没被索引」(覆盖缺口):前者是事实,后者不能当成事实。
|
||||
缺少必要信息时用自然语言澄清;超出工具能力时说明不能可靠完成,并给出当前工具可以执行的替代方向。`
|
||||
缺少必要信息时用自然语言澄清;超出工具能力时说明不能可靠完成,并给出当前工具可以执行的替代方向。
|
||||
${ANSWER_RULES}`
|
||||
|
||||
function toolDefinitions(): AIChatToolDefinition[] {
|
||||
return LOCAL_QUERY_TOOL_DEFINITIONS.map((tool) => ({
|
||||
@@ -707,13 +726,9 @@ function nextToolDefinitions(name: string, result: QueryAgentToolResult, state:
|
||||
/**
|
||||
* 这里**不能**因为"时间范围已经是全部"就关掉重试。
|
||||
*
|
||||
* 原实现是 `if (rangeWasAll && resultCount === 0) return []`,依据是"时间不能再放宽了、
|
||||
* 更窄只会更少"。但 0 结果的重试本来就不是为了改时间 —— 它是为了放宽
|
||||
* **direction / messageTypes**:「我给 X 发了什么图片」被错判成 `from_target` 时,
|
||||
* 换成 `to_target` 会从 0 条变成有结果。
|
||||
*
|
||||
* 这个守卫的后果正是真机那个回归:工具没发出去 → 第二次调用被
|
||||
* `tool_availability` 拒掉 → 模型想改向也调不动 → 只能回头问用户"是不是方向搞错了"。
|
||||
* 0 结果的重试不是为了让时间更宽 —— 它的作用是放宽 **direction / messageTypes**:
|
||||
* 「我给 X 发了什么图片」被判成 `from_target` 时,换成 `to_target` 会从 0 条变成有结果。
|
||||
* 一旦在这里关掉,模型想改向也调不动,只能回头问用户"是不是方向搞错了"。
|
||||
*
|
||||
* 时间范围不可变由 `constraint_time_range_immutable` 单独把关,
|
||||
* 完全相同的重试由 `duplicate_retry` 拦下,次数由 ZERO_RESULT_RETRY_LIMIT 限制,
|
||||
@@ -859,9 +874,12 @@ class EvidenceCollector {
|
||||
? { messageType: record.sourceKind }
|
||||
: {}),
|
||||
...(typeof record.text === 'string' && record.text ? { text: record.text } : {}),
|
||||
// 「靠图片里的文字命中」这个来源语义必须带到 UI:用户要能看出这条答案来自
|
||||
// 图片 OCR,而不是群友真发了一条文字消息。messageRef 仍然指向原始图片消息。
|
||||
...(record.derivedSource === 'image_ocr' ? { derivedSource: 'image_ocr' as const } : {}),
|
||||
// 派生来源原样透传到 UI(取值集合由 `KnowledgeDerivedSource` 约束):
|
||||
// 用户要能看出这条答案来自图片 OCR / 语音转写,而不是群友真发了一条文字消息。
|
||||
// messageRef 始终指向原始消息,authoritative source 不变。
|
||||
...(record.derivedSource === 'image_ocr' || record.derivedSource === 'voice_transcript'
|
||||
? { derivedSource: record.derivedSource }
|
||||
: {}),
|
||||
...(typeof record.imageOcrText === 'string' && record.imageOcrText
|
||||
? { imageOcrText: record.imageOcrText }
|
||||
: {}),
|
||||
|
||||
@@ -24,22 +24,34 @@
|
||||
// 抛出的错误是 `Windows error 操作成功完成。 (0x00000000)`(HRESULT 为 S_OK)。
|
||||
// - 空白图不会报错,返回空文本 → 映射成 OCR_EMPTY_RESULT。
|
||||
// - CJK 字符之间会被引擎插入空格,结果里做归一化。
|
||||
//
|
||||
// macOS 后端:Apple Vision(同一 native 包,darwin binding)。
|
||||
// 已实测的引擎行为(1.2.0 / macOS 15.7.7 / arm64):
|
||||
// - Buffer 输入 PNG / JPEG / WEBP / GIF / BMP / TIFF **全部直接可用**,
|
||||
// 所以 macOS 不做任何归一化,原始字节直通(不落盘、不起 ffmpeg 子进程)。
|
||||
// - preferredLangs 对识别结果没有可观测影响(Vision 自行决定识别语言),
|
||||
// 因此默认不传语言提示;显式指定 language 时仍然透传。
|
||||
// - 畸形图片抛普通 Error:`CRImage Reader Detector was given zero-dimensioned image (0 x 0)`;
|
||||
// 任一边 ≤2px 抛 `The image is too small in at least one dimension ...` → 都映射成 IMAGE_DECODE_FAILED。
|
||||
// - macOS 没有"语言包缺失"这一失败模式。
|
||||
|
||||
import crypto from 'node:crypto'
|
||||
import { spawn } from 'node:child_process'
|
||||
import {
|
||||
SYSTEM_OCR_CACHE_TTL_MS,
|
||||
SYSTEM_OCR_ENGINE,
|
||||
SYSTEM_OCR_PROBE_PNG_BASE64,
|
||||
buildSystemOcrCacheKey,
|
||||
detectSystemOcrImageFormat,
|
||||
isSystemOcrPlatform,
|
||||
mapSystemOcrNativeError,
|
||||
normalizeSystemOcrText,
|
||||
parseImageDataUrl,
|
||||
resolveSystemOcrEngine,
|
||||
resolveSystemOcrLanguageTag
|
||||
} from '../../shared/system-ocr'
|
||||
import type {
|
||||
SystemOcrCapability,
|
||||
SystemOcrEngine,
|
||||
SystemOcrErrorCode,
|
||||
SystemOcrImageFormat,
|
||||
SystemOcrLine,
|
||||
@@ -71,13 +83,18 @@ interface NativeRuntime {
|
||||
export interface SystemOcrServiceDeps {
|
||||
/** 加载 native 运行时;不可用时返回 null(不允许抛) */
|
||||
loadRuntime?: () => NativeRuntime | null
|
||||
/** 把输入图片转成 PNG 字节;失败返回 null */
|
||||
/**
|
||||
* 把输入图片转成引擎可接受的字节;失败返回 null。
|
||||
*
|
||||
* Windows 后端只吃 PNG,必须走这一步;macOS 的 Vision 直接接受
|
||||
* PNG / JPEG / WEBP / GIF / BMP / TIFF,默认实现直接透传原始字节。
|
||||
*/
|
||||
toPngBytes?: (input: {
|
||||
buffer: Buffer
|
||||
format: SystemOcrImageFormat
|
||||
}) => Promise<Buffer | null>
|
||||
/**
|
||||
* ffmpeg 可执行文件解析器。只用于 GIF/BMP/WebP/TIFF → PNG 的兜底归一化。
|
||||
* ffmpeg 可执行文件解析器。只用于 Windows 上 GIF/BMP/WebP/TIFF → PNG 的兜底归一化。
|
||||
* main/index.ts 会注入项目统一的解析逻辑(与图片解密共用一套候选路径)。
|
||||
*/
|
||||
resolveFfmpegExecutable?: () => string
|
||||
@@ -87,6 +104,22 @@ export interface SystemOcrServiceDeps {
|
||||
locale?: () => string
|
||||
}
|
||||
|
||||
const failure = (
|
||||
engine: SystemOcrEngine,
|
||||
errorCode: SystemOcrErrorCode,
|
||||
error: string,
|
||||
startedAt: number
|
||||
): SystemOcrResult => ({
|
||||
success: false,
|
||||
text: '',
|
||||
lines: [],
|
||||
language: null,
|
||||
engine,
|
||||
durationMs: Date.now() - startedAt,
|
||||
errorCode,
|
||||
error
|
||||
})
|
||||
|
||||
/** 未被显式注入时的兜底:环境变量 → 打包内 ffmpeg-static → PATH。 */
|
||||
const defaultResolveFfmpegExecutable = (): string => {
|
||||
const fromEnvironment = String(process.env['FFMPEG_BIN'] || '').trim()
|
||||
@@ -114,22 +147,7 @@ const toLines = (lines: NativeLine[] | undefined): SystemOcrLine[] =>
|
||||
}))
|
||||
: []
|
||||
|
||||
const failure = (
|
||||
errorCode: SystemOcrErrorCode,
|
||||
error: string,
|
||||
startedAt: number
|
||||
): SystemOcrResult => ({
|
||||
success: false,
|
||||
text: '',
|
||||
lines: [],
|
||||
language: null,
|
||||
engine: SYSTEM_OCR_ENGINE,
|
||||
durationMs: Date.now() - startedAt,
|
||||
errorCode,
|
||||
error
|
||||
})
|
||||
|
||||
/** 把任意容器(gif/bmp/webp/tiff)用 ffmpeg 走内存管道转成 PNG。不落盘。 */
|
||||
/** 把任意容器(gif/bmp/webp/tiff)用 ffmpeg 走内存管道转成 PNG。不落盘。仅 Windows 归一化路径会用到。 */
|
||||
const convertWithFfmpeg = (buffer: Buffer, executable: string): Promise<Buffer | null> =>
|
||||
new Promise((resolve) => {
|
||||
let settled = false
|
||||
@@ -222,6 +240,16 @@ class SystemOcrService {
|
||||
return this.deps.arch ?? process.arch
|
||||
}
|
||||
|
||||
/** 该平台对应的引擎标识。进 artifact 指纹与缓存 key,不要硬编码。 */
|
||||
private get engine(): SystemOcrEngine {
|
||||
return resolveSystemOcrEngine(this.platform)
|
||||
}
|
||||
|
||||
/** 本平台是否为 macOS 后端(决定是否跳过图片归一化)。 */
|
||||
private get isMacBackend(): boolean {
|
||||
return this.platform === 'darwin'
|
||||
}
|
||||
|
||||
private get locale(): string {
|
||||
if (this.deps.locale) {
|
||||
try {
|
||||
@@ -245,7 +273,7 @@ class SystemOcrService {
|
||||
this.runtime = this.deps.loadRuntime()
|
||||
return this.runtime
|
||||
}
|
||||
if (this.platform !== 'win32') {
|
||||
if (!isSystemOcrPlatform(this.platform)) {
|
||||
this.runtime = null
|
||||
return this.runtime
|
||||
}
|
||||
@@ -267,7 +295,7 @@ class SystemOcrService {
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[SystemOcrService] native runtime unavailable engine=%s platform=%s reason=%s',
|
||||
SYSTEM_OCR_ENGINE,
|
||||
this.engine,
|
||||
this.platform,
|
||||
error instanceof Error ? error.message.split('\n')[0] : String(error)
|
||||
)
|
||||
@@ -281,6 +309,11 @@ class SystemOcrService {
|
||||
format: SystemOcrImageFormat
|
||||
): Promise<Buffer | null> {
|
||||
if (this.deps.toPngBytes) return this.deps.toPngBytes({ buffer, format })
|
||||
/*
|
||||
* macOS:Vision 后端直接接受 PNG / JPEG / WEBP / GIF / BMP / TIFF(已实测),
|
||||
* 归一化没有收益,只会白白多一次转码或一个 ffmpeg 子进程 —— 原字节直通。
|
||||
*/
|
||||
if (this.isMacBackend) return buffer
|
||||
if (format === 'png') return buffer
|
||||
if (format === 'jpeg') {
|
||||
// 项目内已有的进程内解码能力,优先于 ffmpeg(更快、无子进程)。
|
||||
@@ -322,18 +355,18 @@ class SystemOcrService {
|
||||
SystemOcrCapability,
|
||||
'engine' | 'platform' | 'arch' | 'runtimeVersion' | 'language'
|
||||
> = {
|
||||
engine: SYSTEM_OCR_ENGINE,
|
||||
engine: this.engine,
|
||||
platform: this.platform,
|
||||
arch: this.arch,
|
||||
runtimeVersion: null,
|
||||
language: null
|
||||
}
|
||||
if (this.platform !== 'win32') {
|
||||
if (!isSystemOcrPlatform(this.platform)) {
|
||||
return {
|
||||
...base,
|
||||
available: false,
|
||||
reason: 'UNSUPPORTED_PLATFORM',
|
||||
message: '本地图片文字识别目前仅支持 Windows。'
|
||||
message: '本地图片文字识别目前支持 Windows 与 macOS。'
|
||||
}
|
||||
}
|
||||
const runtime = this.loadRuntime()
|
||||
@@ -355,20 +388,26 @@ class SystemOcrService {
|
||||
message: probed.message
|
||||
}
|
||||
}
|
||||
const engineLabel = this.isMacBackend ? 'macOS 系统 OCR' : 'Windows 系统 OCR'
|
||||
return {
|
||||
...base,
|
||||
runtimeVersion: runtime.version,
|
||||
available: true,
|
||||
language: probed.language,
|
||||
message: probed.language
|
||||
? `本地图片文字识别可用(Windows 系统 OCR,${probed.language})。`
|
||||
: '本地图片文字识别可用(Windows 系统 OCR,跟随系统语言)。'
|
||||
? `本地图片文字识别可用(${engineLabel},${probed.language})。`
|
||||
: `本地图片文字识别可用(${engineLabel},跟随系统语言)。`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用一个 64x32 纯白 PNG 探测语言可用性:引擎能创建即说明语言包可用。
|
||||
* 首选「系统 locale 推导出的标签」,失败再退回「系统用户语言配置」。
|
||||
* 用一个 64x32 纯白 PNG 探测引擎是否真的能跑。
|
||||
*
|
||||
* Windows:引擎创建依赖语言包,首选「系统 locale 推导出的标签」,
|
||||
* 失败再退回「系统用户语言配置」,并据此区分 LANGUAGE_UNAVAILABLE。
|
||||
*
|
||||
* macOS:Vision 自行决定识别语言,**没有语言包缺失这一失败模式**,
|
||||
* 所以不传语言提示,探测失败只可能是引擎本身起不来。
|
||||
*/
|
||||
private async probeLanguage(
|
||||
runtime: NativeRuntime
|
||||
@@ -377,7 +416,29 @@ class SystemOcrService {
|
||||
| { language: null; reason: 'LANGUAGE_UNAVAILABLE' | 'NATIVE_MODULE_MISSING'; message: string }
|
||||
> {
|
||||
const probeBuffer = Buffer.from(SYSTEM_OCR_PROBE_PNG_BASE64, 'base64')
|
||||
const preferred = resolveSystemOcrLanguageTag(this.locale)
|
||||
if (this.isMacBackend) {
|
||||
try {
|
||||
await runtime.recognize(probeBuffer, undefined, undefined)
|
||||
return { language: null }
|
||||
} catch (error) {
|
||||
/*
|
||||
* 探测图是纯白图。Vision 对"图里没有文字"是**抛错**(`No text recognized`),
|
||||
* 而抛这个错恰恰证明识别器跑通了 —— 不能当成引擎故障。
|
||||
*/
|
||||
if (
|
||||
mapSystemOcrNativeError(error instanceof Error ? error.message : String(error)) ===
|
||||
'OCR_EMPTY_RESULT'
|
||||
) {
|
||||
return { language: null }
|
||||
}
|
||||
return {
|
||||
language: null,
|
||||
reason: 'NATIVE_MODULE_MISSING',
|
||||
message: '本地文字识别引擎初始化失败,请重启 TraceMemo 或重新安装。'
|
||||
}
|
||||
}
|
||||
}
|
||||
const preferred = resolveSystemOcrLanguageTag(this.locale, this.platform)
|
||||
const candidates: Array<string | null> = preferred ? [preferred, null] : [null]
|
||||
let lastCode: SystemOcrErrorCode = 'OCR_FAILED'
|
||||
for (const candidate of candidates) {
|
||||
@@ -433,22 +494,28 @@ class SystemOcrService {
|
||||
*/
|
||||
async recognize(request: SystemOcrRequest): Promise<SystemOcrResult> {
|
||||
const startedAt = Date.now()
|
||||
const engine = this.engine
|
||||
const parsed = parseImageDataUrl(request.imageDataUrl)
|
||||
if (!parsed) {
|
||||
return failure('UNSUPPORTED_IMAGE', '仅支持 PNG、JPG、JPEG、WebP、GIF、BMP 图片。', startedAt)
|
||||
return failure(
|
||||
engine,
|
||||
'UNSUPPORTED_IMAGE',
|
||||
'仅支持 PNG、JPG、JPEG、WebP、GIF、BMP 图片。',
|
||||
startedAt
|
||||
)
|
||||
}
|
||||
let sourceBuffer: Buffer
|
||||
try {
|
||||
sourceBuffer = Buffer.from(parsed.base64, 'base64')
|
||||
} catch {
|
||||
return failure('IMAGE_DECODE_FAILED', '图片数据无法解码。', startedAt)
|
||||
return failure(engine, 'IMAGE_DECODE_FAILED', '图片数据无法解码。', startedAt)
|
||||
}
|
||||
if (sourceBuffer.length === 0) {
|
||||
return failure('IMAGE_DECODE_FAILED', '图片数据为空。', startedAt)
|
||||
return failure(engine, 'IMAGE_DECODE_FAILED', '图片数据为空。', startedAt)
|
||||
}
|
||||
const format = detectSystemOcrImageFormat(sourceBuffer)
|
||||
if (!format) {
|
||||
return failure('UNSUPPORTED_IMAGE', '无法识别的图片格式。', startedAt)
|
||||
return failure(engine, 'UNSUPPORTED_IMAGE', '无法识别的图片格式。', startedAt)
|
||||
}
|
||||
|
||||
const imageHash =
|
||||
@@ -464,7 +531,7 @@ class SystemOcrService {
|
||||
: capability.reason === 'LANGUAGE_UNAVAILABLE'
|
||||
? 'OCR_LANGUAGE_UNAVAILABLE'
|
||||
: 'SYSTEM_OCR_UNAVAILABLE'
|
||||
return failure(errorCode, capability.message, startedAt)
|
||||
return failure(engine, errorCode, capability.message, startedAt)
|
||||
}
|
||||
|
||||
const languageForCache = requestedLanguage ?? capability.language
|
||||
@@ -472,7 +539,8 @@ class SystemOcrService {
|
||||
imageHash,
|
||||
language: languageForCache,
|
||||
runtimeVersion: capability.runtimeVersion,
|
||||
platform: capability.platform
|
||||
platform: capability.platform,
|
||||
engine: capability.engine
|
||||
})
|
||||
if (requestedLanguage === null) {
|
||||
const cached = this.readCache(cacheKey, startedAt)
|
||||
@@ -481,12 +549,12 @@ class SystemOcrService {
|
||||
|
||||
const runtime = this.loadRuntime()
|
||||
if (!runtime) {
|
||||
return failure('SYSTEM_OCR_UNAVAILABLE', '本地文字识别组件不可用。', startedAt)
|
||||
return failure(engine, 'SYSTEM_OCR_UNAVAILABLE', '本地文字识别组件不可用。', startedAt)
|
||||
}
|
||||
|
||||
const png = await this.toPngBytes(sourceBuffer, format)
|
||||
if (!png || png.length === 0 || !detectSystemOcrImageFormat(png)) {
|
||||
return failure('IMAGE_DECODE_FAILED', '图片解码失败,无法读取这张图片。', startedAt)
|
||||
const prepared = await this.toPngBytes(sourceBuffer, format)
|
||||
if (!prepared || prepared.length === 0 || !detectSystemOcrImageFormat(prepared)) {
|
||||
return failure(engine, 'IMAGE_DECODE_FAILED', '图片解码失败,无法读取这张图片。', startedAt)
|
||||
}
|
||||
|
||||
const candidates: Array<string | null> = requestedLanguage
|
||||
@@ -499,8 +567,11 @@ class SystemOcrService {
|
||||
let usedLanguage: string | null = null
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
// accuracy 传 undefined = 用 native 默认值,而该默认是 `Accurate`
|
||||
// (见 @napi-rs/system-ocr 的 recognize 文档)。**不要改成 Fast**:
|
||||
// 低精度档在中文上会明显掉字。Windows 忽略该参数。
|
||||
const result = await runtime.recognize(
|
||||
png,
|
||||
prepared,
|
||||
undefined,
|
||||
candidate ? [candidate] : undefined
|
||||
)
|
||||
@@ -508,30 +579,37 @@ class SystemOcrService {
|
||||
const lines = toLines(result?.lines)
|
||||
usedLanguage = candidate
|
||||
if (!text) {
|
||||
return failure('OCR_EMPTY_RESULT', '没有在这张图片里识别到文字。', startedAt)
|
||||
return failure(engine, 'OCR_EMPTY_RESULT', '没有在这张图片里识别到文字。', startedAt)
|
||||
}
|
||||
const succeeded: SystemOcrResult = {
|
||||
success: true,
|
||||
text,
|
||||
lines,
|
||||
language: usedLanguage,
|
||||
engine: SYSTEM_OCR_ENGINE,
|
||||
engine,
|
||||
durationMs: Date.now() - startedAt
|
||||
}
|
||||
// 生产日志只记录 error code / engine / platform / duration,绝不记录识别正文。
|
||||
console.log(
|
||||
'[SystemOcrService] ok engine=%s platform=%s language=%s chars=%d durationMs=%d',
|
||||
SYSTEM_OCR_ENGINE,
|
||||
capability.platform,
|
||||
usedLanguage ?? 'system-default',
|
||||
text.length,
|
||||
succeeded.durationMs
|
||||
)
|
||||
/**
|
||||
* 成功路径**刻意不逐张打日志**。
|
||||
*
|
||||
* 后台回填会连续识别几万张图片,逐张一条成功日志既是没有信息量的噪声,
|
||||
* 又会把日志刷爆。逐张耗时由 `ImageTextIndexService` 的阶段画像低频汇总,
|
||||
* 单张的 `durationMs` / 字数依然在**返回值**里(设置页的单图诊断就是用它)。
|
||||
* 只有失败才值得在默认输出里留痕 —— 见下面的 `failed`。
|
||||
*/
|
||||
this.writeCache(cacheKey, succeeded)
|
||||
return succeeded
|
||||
} catch (error) {
|
||||
lastErrorMessage = error instanceof Error ? error.message : String(error)
|
||||
lastErrorCode = mapSystemOcrNativeError(lastErrorMessage)
|
||||
/*
|
||||
* macOS 的 Vision 在"图里没有文字"时是抛错(`No text recognized`)而不是返回空文本。
|
||||
* 它必须走 empty 语义:表情包 / 风景 / 头像都是**正常终态**,不是 OCR 失败 ——
|
||||
* 否则这些图片会落成可重试失败,被反复重算,覆盖率也会说谎。
|
||||
*/
|
||||
if (lastErrorCode === 'OCR_EMPTY_RESULT') {
|
||||
return failure(engine, 'OCR_EMPTY_RESULT', '没有在这张图片里识别到文字。', startedAt)
|
||||
}
|
||||
// 语言不可用才值得换下一个候选;其它错误直接结束,避免无意义重试。
|
||||
if (lastErrorCode !== 'OCR_LANGUAGE_UNAVAILABLE') break
|
||||
}
|
||||
@@ -539,12 +617,13 @@ class SystemOcrService {
|
||||
|
||||
console.warn(
|
||||
'[SystemOcrService] failed engine=%s platform=%s errorCode=%s durationMs=%d',
|
||||
SYSTEM_OCR_ENGINE,
|
||||
engine,
|
||||
capability.platform,
|
||||
lastErrorCode,
|
||||
Date.now() - startedAt
|
||||
)
|
||||
return failure(
|
||||
engine,
|
||||
lastErrorCode,
|
||||
lastErrorCode === 'OCR_LANGUAGE_UNAVAILABLE'
|
||||
? '当前 Windows 未安装可用的 OCR 语言支持。'
|
||||
|
||||
Reference in new issue
Block a user