feat(录单识别): 手写送货单数量单位语义校验与纠正
- 打印/手写/混排分流提示词,手写不按印刷表头硬套 - 单位列数字与数量列斤/9/5语义交换,单位9/5按斤 - 3行以上5/9触发纠正重识别,异常转人工提示 - 右栏/页边商品独立成行,品名不粘数量 - 保留原7字段接口
This commit is contained in:
@@ -210,10 +210,13 @@ spec 最长 20 字,无法判断就填空字符串。`,
|
||||
wired: true,
|
||||
systemTemplate: [
|
||||
'你是生鲜送货单/采购单看图解析助手。输入是照片,请看图直接出商品 JSON。',
|
||||
'【版式】先看整张再逐行。印刷或表格一行左右两栏各一个商品(一行两品)时,右半幅也要输出,禁止只认左栏。',
|
||||
'手写「斤」就是单位「斤」,禁止认成数字 5;连笔、看不清的字按生鲜采购常识判断,看不清数量或单位的行跳过,不要猜。',
|
||||
'【表格】常见列是品名 / 数量 / 单位 / 备注;备注列和数量后面的尾说明(放红烧、洗干净、打皮、去壳)写入第5字段。',
|
||||
'【忽略】表头(品名、数量、单位)、日期、客户、电话、合计/总计、页码、划掉或涂黑的行。',
|
||||
'【先判断单据类型】机器打印明细:字体一致、行列规整,可按表头列名取值。手写明细:即使表头是印刷的,只要商品名/数字是手写,就按手写单处理,表头只当列名提示,不按列位置硬套。打印行与手写行混排:逐行判断。',
|
||||
'【版式/完整扫描】先看整张再逐行。印刷或表格一行左右两栏各一个商品(一行两品)时,右半幅也要输出;左栏、右栏、单价/金额旁、页边、末尾追加的「品名+数量+单位」都算商品,禁止只认左栏。右侧单独写的商品不能当金额、单价或备注,必须拆成独立商品行。输出前先数一遍图中商品,核对条数不要漏行。',
|
||||
'【表格】常见列是品名 / 数量 / 单位 / 备注;备注列和数量后面的尾说明(放红烧、洗干净、打皮、去壳)写入第5字段。忽略表头(品名、数量、单位)、日期、客户、电话、合计/总计、页码、划掉或涂黑的行;单价/金额/合计列的数字不是数量。',
|
||||
'【手写数量/单位】手写单可能把数字填在「单位」列、把「斤」填在「数量」列。纯数字(35、25、30)是数量,斤/公斤/千克/kg/袋/件/箱/把/盒/瓶/个/只等是单位;发现填反按语义交换,输出数量=数字、单位=单位。单位列出现 9(或 5)按手写「斤」处理,绝不能当数量。',
|
||||
'【手写斤】手写「斤」容易被识别成 5 或 9,禁止直接当数量;逐行读取每行自己的数量,禁止整列复制同一个 5/9。如果输出后 3 行以上数量为 5 或 9(尤其连续/大量相同的 9),必须重新检查原图;仍不能确定的行降低 confidence 或跳过,交人工核对。',
|
||||
'【单位列/数量列填反】这类手写送货单常见:印刷表头是「单位」「数量」,但手写时把数量写进单位列、把「斤」写进数量列。若单位列是 27/25/30 等纯数字、数量列是 9/5/斤,则数字是数量、9/5/斤是单位「斤」;必须逐行读取该行单位列的数字,绝不能把 9 当成所有行的数量,也不能整列抄 9。',
|
||||
'【品名不要粘数量】品名第1字段只写商品名;不得把该行数量粘在品名末尾(例如图片写「洋葱」、单位列 4、数量列「斤」,应输出「洋葱」+数量4+单位斤,不能输出「洋葱4」)。',
|
||||
'同名多行不要合并。不要先把全文抄成 OCR 再解释。',
|
||||
ORDER_PARSE_SHARED_RULES,
|
||||
].join('\n'),
|
||||
|
||||
@@ -426,6 +426,76 @@ function normalizeUnit(value: unknown, processingMethod?: string): string {
|
||||
return unit;
|
||||
}
|
||||
|
||||
|
||||
const ORDER_UNIT_WORDS = new Set([
|
||||
'斤', '公斤', '千克', 'kg', '袋', '件', '箱', '把', '盒', '瓶', '个', '只', '包', '桶', '罐', '提', '扎', '份', '板', '条',
|
||||
]);
|
||||
|
||||
function parseOrderNumericToken(value: unknown): number | null {
|
||||
const text = String(value ?? '').replace(/,/g, '').trim();
|
||||
if (!/^\d+(?:\.\d+)?$/.test(text)) return null;
|
||||
const n = Number(text);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
function isOrderUnitToken(value: unknown): boolean {
|
||||
const text = String(value ?? '').trim().toLowerCase();
|
||||
return ORDER_UNIT_WORDS.has(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 送货单「录单」数量/单位归一(与库存入库识别分开,各自 prompt/字段不同):
|
||||
* - 手写数字填在单位列、手写「斤」填在数量列 → 语义交换;
|
||||
* - 单位列 9/5 是手写「斤」,绝不能当数量;
|
||||
* - 数量字段写成「35斤」时拆出数字。
|
||||
*/
|
||||
export function normalizeOrderQtyUnit(
|
||||
rawQty: unknown,
|
||||
rawUnit: unknown
|
||||
): { quantity: number | null; unit: string } {
|
||||
let qtyText = String(rawQty ?? '').trim();
|
||||
let unitText = String(rawUnit ?? '').trim();
|
||||
let qty = parseOrderNumericToken(qtyText);
|
||||
const unitNum = parseOrderNumericToken(unitText);
|
||||
|
||||
const embedded = qtyText.match(/^(\d+(?:\.\d+)?)\s*([^\d\s]+)$/);
|
||||
if (embedded) {
|
||||
qty = Number(embedded[1]);
|
||||
qtyText = embedded[1];
|
||||
unitText = embedded[2] || unitText;
|
||||
}
|
||||
|
||||
if (isOrderUnitToken(qtyText) && unitNum !== null) {
|
||||
qty = unitNum;
|
||||
unitText = qtyText;
|
||||
}
|
||||
|
||||
if (unitText && (parseOrderNumericToken(unitText) === 9 || parseOrderNumericToken(unitText) === 5)) {
|
||||
unitText = '斤';
|
||||
} else if (unitText && parseOrderNumericToken(unitText) !== null && qty !== null) {
|
||||
// 单位列是数字、数量列已有数字:单位列按手写「斤」;不把数字当单位
|
||||
unitText = '斤';
|
||||
}
|
||||
|
||||
return { quantity: qty, unit: qty === null ? '' : unitText };
|
||||
}
|
||||
|
||||
/** 3 行以上数量全是 5 或 9:手写「斤」被误识别为数字的典型特征。 */
|
||||
export function hasSuspiciousOrderAllFiveNine(items: ExtractedItem[]): boolean {
|
||||
const rows = items.filter((item) => Number.isFinite(Number(item.quantity)));
|
||||
if (rows.length < 3) return false;
|
||||
// 手写「斤」被误读时往往不是“所有行”,而是连续多行都变成同一个 5/9;
|
||||
// 只要有 3 行以上落在 {5,9} 就触发纠正,避免漏掉混有 4/80 等正常数量的整单。
|
||||
const suspicious = rows.filter((item) => Number(item.quantity) === 5 || Number(item.quantity) === 9);
|
||||
return suspicious.length >= 3;
|
||||
}
|
||||
|
||||
const ORDER_HANDWRITE_CORRECTION_INSTRUCTION = `【强制纠错重识别】
|
||||
上一轮结果中 3 行以上数量都是 5 或 9,疑似把手写「斤」识别成了数量。
|
||||
请重新看原图:按「数字=数量、斤/公斤/袋/件=单位」逐行判断;单位列的数字是数量,数量列的「斤」是单位;单位列 9/5 按「斤」处理。
|
||||
必须输出每一行自己的数量,禁止整列复制同一个 5/9;同时完整扫描左栏、右栏、单价/金额旁和页边追加商品,输出前核对商品条数。
|
||||
仍不能确定的商品降低 confidence 或跳过,不要编造。`;
|
||||
|
||||
/**
|
||||
* 模型原始输出(6 或 7 元组 / 对象)→ 抽取项。
|
||||
*
|
||||
@@ -448,8 +518,12 @@ export function mapRawItemToExtracted(item: any): ExtractedItem | null {
|
||||
if (!rawName || isPromptTemplateItem(String(rawName))) return null;
|
||||
const normalized = normalizeExtractedName(String(rawName));
|
||||
const unitPeeled = peelRemarkFromUnitField(isArrayItem ? item[2] : item.unit || item.单位);
|
||||
const rawUnit = unitPeeled.unit;
|
||||
const rawQty = isArrayItem ? item[1] : item.quantity ?? item.qty ?? item.数量;
|
||||
const normalizedQtyUnit = normalizeOrderQtyUnit(
|
||||
isArrayItem ? item[1] : item.quantity ?? item.qty ?? item.数量,
|
||||
unitPeeled.unit
|
||||
);
|
||||
const rawUnit = normalizedQtyUnit.unit || unitPeeled.unit;
|
||||
const rawQty = normalizedQtyUnit.quantity ?? (isArrayItem ? item[1] : item.quantity ?? item.qty ?? item.数量);
|
||||
const rawProcessingText = String(
|
||||
(isArrayItem ? item[3] : item.processingMethod) ||
|
||||
item.processing_method ||
|
||||
@@ -902,7 +976,7 @@ async function extractItemsWithLLM(
|
||||
async function extractItemsFromImage(
|
||||
imageBase64: string,
|
||||
options?: ParseExtractOptions
|
||||
): Promise<{ items: ExtractedItem[]; ocrText: string }> {
|
||||
): Promise<{ items: ExtractedItem[]; ocrText: string; warning?: string }> {
|
||||
const systemPrompt = await resolveParseItemsPrompt('order.parse.image', options);
|
||||
console.info('Order image parse prompt:', {
|
||||
featureKey: 'order.parse.image',
|
||||
@@ -915,8 +989,29 @@ async function extractItemsFromImage(
|
||||
return { items: [], ocrText: '' };
|
||||
}
|
||||
console.info('Vision parse content length:', content.length);
|
||||
const items = parseItemsFromModelContent(content, 'image');
|
||||
return { items, ocrText: content };
|
||||
let items = parseItemsFromModelContent(content, 'image');
|
||||
let warning: string | undefined;
|
||||
if (hasSuspiciousOrderAllFiveNine(items)) {
|
||||
try {
|
||||
const retryContent =
|
||||
(await callArkWithImage(
|
||||
`${systemPrompt}\n\n${ORDER_HANDWRITE_CORRECTION_INSTRUCTION}`,
|
||||
imageBase64,
|
||||
options
|
||||
)) || '';
|
||||
const retryItems = parseItemsFromModelContent(retryContent, 'image-retry');
|
||||
if (retryItems.length && !hasSuspiciousOrderAllFiveNine(retryItems)) {
|
||||
items = retryItems;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Order image handwriting correction retry failed:', error);
|
||||
}
|
||||
if (hasSuspiciousOrderAllFiveNine(items)) {
|
||||
warning =
|
||||
'识别数量疑似异常(多行数量为 5 或 9,手写“斤”可能被误读),已尝试纠正重识别,请人工核对原图数量与单位列';
|
||||
}
|
||||
}
|
||||
return { items, ocrText: content, ...(warning ? { warning } : {}) };
|
||||
}
|
||||
|
||||
async function extractItemsFromAudio(
|
||||
@@ -947,12 +1042,13 @@ async function extractItemsFromImageParallel(
|
||||
): Promise<{
|
||||
items: ExtractedItem[];
|
||||
ocrText: string;
|
||||
warning?: string;
|
||||
mode: 'multimodal';
|
||||
parallelCount: number;
|
||||
requestItemCounts: number[];
|
||||
}> {
|
||||
const startedAt = Date.now();
|
||||
const { items, ocrText } = await extractItemsFromImage(imageBase64, options);
|
||||
const { items, ocrText, warning } = await extractItemsFromImage(imageBase64, options);
|
||||
console.info('Order image multimodal parse complete:', {
|
||||
itemCount: items.length,
|
||||
ocrTextLen: ocrText.length,
|
||||
@@ -961,6 +1057,7 @@ async function extractItemsFromImageParallel(
|
||||
return {
|
||||
items,
|
||||
ocrText,
|
||||
...(warning ? { warning } : {}),
|
||||
mode: 'multimodal',
|
||||
parallelCount: 1,
|
||||
requestItemCounts: [items.length],
|
||||
@@ -1901,6 +1998,7 @@ export async function parseOrderThreeLayer(body: {
|
||||
itemCount: extractedItems.length,
|
||||
elapsedMs: Date.now() - modelStartedAt,
|
||||
});
|
||||
if (imageParse.warning) message = imageParse.warning;
|
||||
if (!extractedItems.length) {
|
||||
demoMode = true;
|
||||
message = !arkConfigured
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import {
|
||||
hasSuspiciousOrderAllFiveNine,
|
||||
mapRawItemToExtracted,
|
||||
normalizeOrderQtyUnit,
|
||||
type ExtractedItem,
|
||||
} from '../src/services/orderParseService';
|
||||
|
||||
/** 手写送货单样例:单位列 35/25/30、数量列「斤」;另有单位列 9;共 17 个商品。 */
|
||||
function sample17(): any[][] {
|
||||
return [
|
||||
['草鱼', '斤', '35'],
|
||||
['二刀肉', '斤', '25'],
|
||||
['腿子牛肉', '斤', '30'],
|
||||
['蒜苔', '12', '9'],
|
||||
['小青椒', '18', '斤'],
|
||||
['青黄瓜', '20', '斤'],
|
||||
['空心菜', '22', '斤'],
|
||||
['酸菜', '10', '袋'],
|
||||
['夹子肉', '7', '斤'],
|
||||
['水面', '斤', '26'],
|
||||
['米块', '9', '斤'],
|
||||
['圣女果', '15', '斤'],
|
||||
['米糯玉米棒', '13', '斤'],
|
||||
['鲜海带丝', '斤', '28'],
|
||||
['苹果', '斤', '32'],
|
||||
['抄手皮', '8', '袋'],
|
||||
['精瘦肉', '斤', '19'],
|
||||
];
|
||||
}
|
||||
|
||||
describe('送货单图片录单 · 手写单数量/单位', () => {
|
||||
it('17 个商品:单位列 35/25/30、数量列「斤」交换,单位 9 按斤,数量均为数字', () => {
|
||||
const items = sample17()
|
||||
.map((row) => mapRawItemToExtracted(row))
|
||||
.filter(Boolean) as ExtractedItem[];
|
||||
expect(items).toHaveLength(17);
|
||||
expect(items[0]).toMatchObject({ originalName: '草鱼', quantity: 35, unit: '斤' });
|
||||
expect(items[1]).toMatchObject({ originalName: '二刀肉', quantity: 25, unit: '斤' });
|
||||
expect(items[2]).toMatchObject({ originalName: '腿子牛肉', quantity: 30, unit: '斤' });
|
||||
expect(items[3]).toMatchObject({ originalName: '蒜苔', quantity: 12, unit: '斤' });
|
||||
expect(items[9]).toMatchObject({ originalName: '水面', quantity: 26, unit: '斤' });
|
||||
for (const item of items) {
|
||||
expect(typeof item.quantity).toBe('number');
|
||||
expect(String(item.unit)).not.toMatch(/^\d+$/);
|
||||
}
|
||||
});
|
||||
|
||||
it('数量字段「35斤」拆为数量35/单位斤', () => {
|
||||
expect(normalizeOrderQtyUnit('35斤', '')).toEqual({ quantity: 35, unit: '斤' });
|
||||
expect(normalizeOrderQtyUnit('斤', '35')).toEqual({ quantity: 35, unit: '斤' });
|
||||
expect(normalizeOrderQtyUnit('12', '9')).toEqual({ quantity: 12, unit: '斤' });
|
||||
});
|
||||
|
||||
it('3 行以上数量全为 5/9 标记为可疑,供纠正重识别/人工', () => {
|
||||
const rows = [5, 9, 5].map((quantity) => ({ originalName: `品${quantity}`, quantity, unit: '斤' })) as ExtractedItem[];
|
||||
expect(hasSuspiciousOrderAllFiveNine(rows)).toBe(true);
|
||||
expect(hasSuspiciousOrderAllFiveNine([...rows.slice(0, 2), { ...rows[2], quantity: 7 }])).toBe(false);
|
||||
});
|
||||
|
||||
it('order.parse.image 提示词包含手写分流/完整扫描/3行5/9/数量单位规则,且保留7字段', () => {
|
||||
const source = readFileSync(new URL('../src/prompts/defaults.ts', import.meta.url), 'utf8');
|
||||
for (const text of [
|
||||
'先判断单据类型',
|
||||
'手写明细',
|
||||
'右半幅',
|
||||
'页边',
|
||||
'3 行以上数量为 5 或 9',
|
||||
'数量=数字、单位=单位',
|
||||
'单位列出现 9',
|
||||
'第7规格',
|
||||
]) {
|
||||
expect(source).toContain(text);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user