跳到主要内容

平台服务(OCR / 文件)


平台服务:OCR 与文件

client.services 是 @lovrabet/sdk v1.4.3+ 提供的平台服务命名空间,统一暴露不绑定数据集或 BFF 的通用平台能力。目前包含 OCR 识别文件上传 / 访问 URL 两项服务。

版本要求:SDK v1.4.3+ | 导入:createClient, OcrType, OCR_TYPES

client.services.ocr    // OCR 识别
client.services.file // 文件上传与访问 URL 查询

🧭 认证模式与路由

OCR 与文件服务都authMode 自动选择服务端路由

authModeOCR 路由文件路由说明
cookieGET /api/ocr/recognize-text/api/common/uploadFile/api/common/queryFileUrlWebAPI,携带用户 Cookie
client-akPOST /client/ocr/client/uploadFile/client/queryFileUrlClient API,携带 X-User-AK
openapi❌ 抛 OCR_AUTH_MODE_UNSUPPORTED❌ 抛 FILE_AUTH_MODE_UNSUPPORTED当前无对应契约

💡 两种可用模式都使用 runtimeDomain,认证模式只决定路由前缀与请求头。OpenAPI(数据集签名)模式不支持这两项服务。


🔍 OCR 识别:client.services.ocr.recognize()

API 签名

client.services.ocr.recognize(request: OcrRecognizeRequest): Promise<OcrRecognizeResponse>
interface OcrRecognizeRequest {
url: string; // 公网可访问的图片 / 文件 URL(必填)
type: OcrType; // OCR 识别类型(必填)
options?: ServiceRequestOptions; // 可选 fetch 设置(method/body 由 SDK 控制)
}

支持的识别类型

通过 OcrType 枚举引用,避免手写字符串;OCR_TYPES 是只读数组,可直接用于下拉框或能力发现。

OcrType说明
General通用文字识别
Invoice增值税发票
Advanced高精度全文识别
AdvancedCoordinate高精度(含坐标)
AdvancedGeneral高精度通用
IdCard身份证
BankCard银行卡
BusinessLicense营业执照
DrivingLicense驾驶证
CarNumber车牌
Table表格
import { createClient, OcrType, OCR_TYPES } from "@lovrabet/sdk";

const client = createClient({
appCode: "your-app-code",
authMode: "cookie",
// 浏览器会自动携带 Cookie;Node.js 可在此传入 cookie 字段
});

const result = await client.services.ocr.recognize({
url: "https://example.com/invoice.png",
type: OcrType.Invoice,
});

console.log(result.text); // 全文文本
console.log(result.kvData); // 结构化键值(发票号、金额等)
console.log(OCR_TYPES); // ['General', 'Invoice', ...] 用于下拉框

示例:Client AK 场景(服务端)

import { createClient, OcrType } from "@lovrabet/sdk";

const client = createClient({
appCode: "your-app-code",
authMode: "client-ak",
accessKey: process.env.LOVRABET_ACCESS_KEY!,
});

const result = await client.services.ocr.recognize({
url: "https://example.com/license.png",
type: OcrType.BusinessLicense,
});

返回值

interface OcrRecognizeResponse {
requestId?: string;
type?: OcrType;
text?: string; // 全文文本
lines?: string[]; // 按行拆分
kvData?: Record<string, string>; // 结构化键值
width?: number;
height?: number;
pageNo?: number | null;
// ...其余字段随识别类型变化,均为可选
}

⚠️ 当前 OCR 接口只接收 URL,不负责本地文件上传。如需识别本地文件,先用 client.services.file.upload() 上传拿到可访问 URL,再传入 recognize()


📎 文件服务:client.services.file

上传:upload()

client.services.file.upload(request: FileUploadRequest): Promise<FileUploadResponse>
interface FileUploadRequest {
file: Blob; // 浏览器 File 或标准 Blob(必填)
fileName?: string; // 可选文件名;Blob 无 name 时必填,否则回退为 upload.bin
options?: ServiceRequestOptions;
}

浏览器上传input.files[0] 是标准 File):

const client = createClient({ appCode: "your-app-code", authMode: "cookie" });

const uploaded = await client.services.file.upload({ file: input.files[0] });
console.log(uploaded.filePath); // 持久引用,建议保存到业务字段

Node.js 上传(传标准 Blob,显式指定文件名):

const uploaded = await client.services.file.upload({
file: new Blob([buffer], { type: "application/pdf" }),
fileName: "invoice.pdf",
});

返回值:

interface FileUploadResponse {
fileName?: string | null;
filePath?: string | null; // ⭐ 持久引用,适合长期保存
fileUrl?: string | null; // 临时访问 URL
downloadFlag?: boolean;
fileType?: string | null;
size?: number | null;
sourceDir?: string | null;
}

查询访问 URL:queryUrl()

client.services.file.queryUrl(request: FileQueryUrlRequest): Promise<FileUrlResponse>
interface FileQueryUrlRequest {
filePath: string; // upload() 返回的 filePath(必填)
download?: boolean; // true 返回下载 URL,默认 false(预览 URL)
longTerm?: boolean; // 是否申请长期 URL,默认 false
options?: ServiceRequestOptions;
}
const access = await client.services.file.queryUrl({
filePath: uploaded.filePath!,
});
console.log(access.fileUrl);

// 需要下载链接
const dl = await client.services.file.queryUrl({
filePath: uploaded.filePath!,
download: true,
});

filePath vs fileUrl:什么时候用什么

字段用途时效
filePath存入业务字段的稳定引用,后续随时换 URL长期
fileUrl临时预览、OCR 输入、短时间消费短期
longTerm: true仅当内容需要 URL-only 长期展示时申请长期

💡 推荐做法:业务表只存 filePath;需要展示或下载时再调 queryUrl() 换取临时 URL。


🛡️ 错误处理

服务在校验失败或认证模式不支持时抛 LovrabetError,错误 codedescription 可直接用于定位:

code触发条件description 关键字段
OCR_URL_REQUIREDurl 为空field: "url"
OCR_TYPE_UNSUPPORTEDtype 不在 OCR_TYPESsupportedTypes
OCR_AUTH_MODE_UNSUPPORTEDOpenAPI 模式调用 OCRsupportedAuthModes: ["cookie","client-ak"]
FILE_REQUIREDfile 不是 Blob/Filefield: "file"
FILE_PATH_REQUIREDqueryUrlfilePath 为空field: "filePath"
FILE_AUTH_MODE_UNSUPPORTEDOpenAPI 模式调用文件服务supportedAuthModes: ["cookie","client-ak"]
import { LovrabetError } from "@lovrabet/sdk";

try {
await client.services.ocr.recognize({ url: "", type: OcrType.Invoice });
} catch (e) {
if (e instanceof LovrabetError) {
console.log(e.code); // 'OCR_URL_REQUIRED'
console.log(e.description); // { field: 'url', suggestion: '...' }
}
}

📖 下一步

  • 认证配置 — Client AK / OpenAPI / Cookie 四种模式的配置
  • API 使用指南 — 数据集 CRUD 与批量操作
  • API 参考ServicesNamespace / OcrClient / FileClient 完整签名