feat(onebot): implement ocr_image via OIDB 0xE07_0

Server-side image OCR ported from Lagrange.Core ([Service]
"OidbSvcTrpcTcp.0xe07_0") cross-checked with NapCat's Oidb.0xE07 proto
(NapCat's transformer cmd 0xEB7 is a typo; the proto name + Lagrange + the
wire name all say 0xE07_0). New ImageOcr service + proto types, misc.ocrImage
api, and the ocr_image/.ocr_image action. The cmd takes an image URL, so the
action accepts an http(s) url or a cached image file_id (resolved via
getImageInfo); base64/local input is unsupported (NapCat's path is a
Windows-only kernel OCR, not portable). Wire round-trip + response-parse
tests lock the pb tags.
This commit is contained in:
DrSmoothl committed 2026-06-18 00:36:07 +08:00
1 parent f936515a59
commit e07090376a
8 files changed
+271 -3

No files matched your search

+5
View File
@@ -10,6 +10,7 @@ import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key';
import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr';
export class MiscApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -18,6 +19,10 @@ export class MiscApi {
return TranslateEnToZh.invoke(this.ctx, { words });
}
ocrImage(imageUrl: string): Promise<OcrResult> {
return ImageOcr.invoke(this.ctx, { imageUrl });
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
let appid = '1109937557'; // default: bilibili
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
+25 -3
View File
@@ -1248,12 +1248,34 @@ export const actions = [
},
}),
// ocr_image — 服务端 OCR via OIDB 0xE07_0(port 自 Lagrange/NapCat proto)。
// 该 cmd 接收图片 URL(服务端拉取),故 image 支持:http(s) URL 直用,或
// 已缓存图片的 file_id(经 getImageInfo 解析出 URL)。base64/本地文件需先
// 上传换 URL,本实现不覆盖(NapCat 走的是 Windows-only 内核 OCR,不可移植)。
defineAction({
name: ['ocr_image', '.ocr_image'],
summary: 'OCR 图片(未实现)',
summary: 'OCR 图片(服务端,需图片 URL 或已缓存的图片 file_id)',
readOnly: true,
params: {},
run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'),
params: { image: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
let url = /^https?:\/\//i.test(p.image) ? p.image : '';
if (!url) {
const info = await ctx.getImageInfo(p.image);
const resolved = info && typeof info.url === 'string' ? info.url : '';
if (resolved) url = resolved;
}
if (!url) {
return failedResponse(
RETCODE.ACTION_FAILED,
'ocr_image needs an http(s) image url or a cached image file_id; '
+ 'base64/local-file input is not supported',
);
}
const result = await ctx.bridge.apis.misc.ocrImage(url);
// OcrResult is plain JSON data; the interface just lacks an index
// signature, so coerce for the JsonValue-typed response.
return okResponse(result as unknown as JsonObject);
},
}),
groupAction({
@@ -751,3 +751,48 @@ describe('extended-actions / get_rkey_server', () => {
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
});
// ─── Wave 3: ocr_image / .ocr_image (OIDB 0xE07_0) ───
describe('extended-actions / ocr_image', () => {
const ocrResult = { texts: [{ text: 'hello', confidence: 99, coordinates: [{ x: 1, y: 2 }] }], language: 'en' };
it('OCRs an http(s) image URL directly', async () => {
const ocrImage = vi.fn(async () => ocrResult);
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', { image: 'https://x/a.jpg' });
expect(res).toMatchObject({ status: 'ok', data: ocrResult });
expect(ocrImage).toHaveBeenCalledWith('https://x/a.jpg');
});
it('resolves a cached image file_id to a url via getImageInfo', async () => {
const ocrImage = vi.fn(async () => ocrResult);
const getImageInfo = vi.fn(async () => ({ url: 'https://cdn/resolved.jpg' }));
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'abc.jpg' });
expect(res.status).toBe('ok');
expect(ocrImage).toHaveBeenCalledWith('https://cdn/resolved.jpg');
});
it('.ocr_image shares the same handler', async () => {
const ocrImage = vi.fn(async () => ocrResult);
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
const res = await makeHandler(fakeCtx(bridge)).handle('.ocr_image', { image: 'http://x/a.jpg' });
expect(res.status).toBe('ok');
});
it('fails when the id cannot be resolved to a url', async () => {
const ocrImage = vi.fn();
const getImageInfo = vi.fn(async () => null);
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'unknown' });
expect(res.status).toBe('failed');
expect(ocrImage).not.toHaveBeenCalled();
});
it('rejects missing image', async () => {
const bridge = fakeBridge({ apis: { misc: { ocrImage: vi.fn() } } });
const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', {});
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
});
});
+4
View File
@@ -70,6 +70,10 @@
"./oidb-actions/media": {
"types": "./src/oidb-actions/media.ts",
"default": "./src/oidb-actions/media.ts"
},
"./oidb-actions/ocr": {
"types": "./src/oidb-actions/ocr.ts",
"default": "./src/oidb-actions/ocr.ts"
}
},
"scripts": {
@@ -0,0 +1,50 @@
// OIDB 0xE07_0 — server-side image OCR. Field tags verified against
// NapCat's Oidb.0xE07 proto AND Lagrange.Core's OidbSvcTrpcTcp.0xE07_0
// (the two agree; NapCat's transformer builds with cmd 0xEB7, which is a
// typo — the proto name + Lagrange + the `OidbSvcTrpcTcp.0xe07_0` wire
// name are authoritative). Request takes an image URL (server fetches it).
import type { pb, pb_repeated, int_32, uint_32, bool } from '@snowluma/proton';
export interface OcrReqBody {
imageUrl?: pb<1, string>;
languageType?: pb<2, uint_32>;
scene?: pb<3, uint_32>;
originMd5?: pb<10, string>;
afterCompressMd5?: pb<11, string>;
afterCompressFileSize?: pb<12, string>;
afterCompressWeight?: pb<13, string>;
afterCompressHeight?: pb<14, string>;
isCut?: pb<15, bool>;
}
export interface ImageOcrReq {
version?: pb<1, uint_32>;
client?: pb<2, uint_32>;
entrance?: pb<3, uint_32>;
ocrReqBody?: pb<10, OcrReqBody>;
}
export interface OcrCoordinate {
x?: pb<1, int_32>;
y?: pb<2, int_32>;
}
export interface OcrPolygon {
coordinates?: pb_repeated<1, OcrCoordinate>;
}
export interface OcrTextDetection {
detectedText?: pb<1, string>;
confidence?: pb<2, uint_32>;
polygon?: pb<3, OcrPolygon>;
advancedInfo?: pb<4, string>;
}
export interface OcrRspBody {
textDetections?: pb_repeated<1, OcrTextDetection>;
language?: pb<2, string>;
requestId?: pb<3, string>;
}
export interface ImageOcrResp {
retCode?: pb<1, int_32>;
errMsg?: pb<2, string>;
wording?: pb<3, string>;
ocrRspBody?: pb<10, OcrRspBody>;
}
+4
View File
@@ -99,6 +99,10 @@
"types": "./src/oidb-services/misc/translate-en-to-zh.ts",
"default": "./src/oidb-services/misc/translate-en-to-zh.ts"
},
"./oidb-services/misc/image-ocr": {
"types": "./src/oidb-services/misc/image-ocr.ts",
"default": "./src/oidb-services/misc/image-ocr.ts"
},
"./oidb-services/misc/click-inline-keyboard-button": {
"types": "./src/oidb-services/misc/click-inline-keyboard-button.ts",
"default": "./src/oidb-services/misc/click-inline-keyboard-button.ts"
@@ -0,0 +1,65 @@
// 0xE07_0 — server-side image OCR. Sends an image URL; the server fetches
// it and returns detected text + bounding-box polygons. Cmd/sub verified
// against Lagrange.Core ([Service("OidbSvcTrpcTcp.0xe07_0")]) and NapCat's
// Oidb.0xE07 proto (NapCat's transformer cmd 0xEB7 is a typo). uinForm is
// false (NapCat build(..., false, false); Lagrange sends no uid).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { ensureRetCodeZero } from '../shared';
/** One detected text run with its bounding-box vertices. */
export interface OcrText {
text: string;
confidence: number;
coordinates: Array<{ x: number; y: number }>;
}
export interface OcrResult {
texts: OcrText[];
language: string;
}
export namespace ImageOcr {
export const command = 0xE07;
export const subCommand = 0;
export interface Params { imageUrl: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): ImageOcrReq => ({
version: 1,
client: 0,
entrance: 1,
ocrReqBody: {
imageUrl: p.imageUrl,
originMd5: '',
afterCompressMd5: '',
afterCompressFileSize: '',
afterCompressWeight: '',
afterCompressHeight: '',
isCut: false,
},
});
export const deserialize = (_ctx: Deps, body: ImageOcrResp): OcrResult => {
ensureRetCodeZero('image ocr', body.retCode, body.errMsg, body.wording);
const rsp = body.ocrRspBody;
const texts: OcrText[] = (rsp?.textDetections ?? []).map((d) => ({
text: d.detectedText ?? '',
confidence: d.confidence ?? 0,
coordinates: (d.polygon?.coordinates ?? []).map((c) => ({ x: c.x ?? 0, y: c.y ?? 0 })),
}));
return { texts, language: rsp?.language ?? '' };
};
export const encode = (env: OidbBase<ImageOcrReq>): Uint8Array =>
protobuf_encode<OidbBase<ImageOcrReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<ImageOcrResp> =>
protobuf_decode<OidbBase<ImageOcrResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<OcrResult> =>
invokeOidb(deps, ImageOcr, params);
}
@@ -0,0 +1,73 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { ImageOcr } from '../../../src/oidb-services/misc/image-ocr';
// A server OCR response: retCode 0, one text detection with a 2-vertex box.
function ocrResponse(): Buffer {
const env: OidbBase<ImageOcrResp> = {
command: 0xE07, subCommand: 0,
body: {
retCode: 0,
ocrRspBody: {
language: 'zh',
textDetections: [
{ detectedText: '你好', confidence: 95, polygon: { coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] } },
],
},
},
};
return Buffer.from(protobuf_encode<OidbBase<ImageOcrResp>>(env));
}
function makeSender(resp = ocrResponse()) {
const r: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: resp,
};
return { sendRawPacket: vi.fn(async () => r) };
}
describe('ImageOcr namespace', () => {
it('declares command 0xE07 sub 0 (no uin form)', () => {
expect(ImageOcr.command).toBe(0xE07);
expect(ImageOcr.subCommand).toBe(0);
expect(ImageOcr.uinForm).toBeUndefined(); // defaults to false in invokeOidb
});
it('serializes the image url into ocrReqBody with the fixed version/client/entrance header', () => {
const out = ImageOcr.serialize({} as any, { imageUrl: 'https://x/a.jpg' });
expect(out).toMatchObject({ version: 1, client: 0, entrance: 1 });
expect(out.ocrReqBody).toMatchObject({ imageUrl: 'https://x/a.jpg', isCut: false });
});
it('routes to OidbSvcTrpcTcp.0xe07_0 and round-trips the request body (locks pb tags)', async () => {
const sender = makeSender();
await ImageOcr.invoke(sender, { imageUrl: 'https://x/a.jpg' });
const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xe07_0');
const env = protobuf_decode<OidbBase<ImageOcrReq>>(bytes);
expect(env.command).toBe(0xE07);
// subCommand 0 is a protobuf default → omitted on the wire (decodes to
// null); the '0xe07_0' cmd string above already pins it. version/entrance
// are non-zero so survive; client=0 is likewise omitted (serialize test
// covers the pre-encode shape).
expect(env.body).toMatchObject({ version: 1, entrance: 1 });
expect(env.body.ocrReqBody?.imageUrl).toBe('https://x/a.jpg');
});
it('deserializes text detections + coordinates + language', async () => {
const result = await ImageOcr.invoke(makeSender(), { imageUrl: 'https://x/a.jpg' });
expect(result.language).toBe('zh');
expect(result.texts).toEqual([
{ text: '你好', confidence: 95, coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] },
]);
});
it('throws on a non-zero retCode', () => {
expect(() => ImageOcr.deserialize({} as any, { retCode: 5, errMsg: 'bad', wording: 'nope' }))
.toThrow();
});
});