feat(tests): add Ministral 3 vision tests and improve invoice extraction pipeline to use Ollama chat schema, sanitization, and multi-page support

This commit is contained in:
2026-01-18 02:53:24 +00:00
parent b316d98f24
commit 7652a2df52
5 changed files with 824 additions and 57 deletions

View File

@@ -90,61 +90,71 @@ async function parseDocument(imageBase64: string): Promise<string> {
}
/**
* Extract invoice fields from structured HTML using Qwen2.5 (text-only model)
* Sanitize HTML to remove OCR artifacts that confuse the LLM
* Minimal cleaning - only remove truly problematic patterns
*/
function sanitizeHtml(html: string): string {
// Remove excessively repeated characters (OCR glitches)
let sanitized = html.replace(/(\d)\1{20,}/g, '$1...');
// Remove extremely long strings (corrupted data)
sanitized = sanitized.replace(/\b[A-Za-z0-9]{50,}\b/g, '[OCR_ARTIFACT]');
return sanitized;
}
/**
* Extract invoice fields using simple direct prompt
* The OCR output has clearly labeled fields - just ask the LLM to read them
*/
async function extractInvoiceFromHtml(html: string): Promise<IInvoice> {
// Truncate if too long (HTML is more valuable per byte, allow more)
const truncated = html.length > 16000 ? html.slice(0, 16000) : html;
console.log(` [Extract] Processing ${truncated.length} chars of HTML`);
const sanitized = sanitizeHtml(html);
const truncated = sanitized.length > 32000 ? sanitized.slice(0, 32000) : sanitized;
console.log(` [Extract] ${truncated.length} chars of HTML`);
const prompt = `You are an invoice data extractor. Extract the following fields from this HTML document (OCR output with semantic structure) and return ONLY a valid JSON object.
The HTML uses semantic tags:
- <table> with <thead>/<tbody> for structured tables (invoice line items, totals)
- <header> for document header (company info, invoice number)
- <footer> for document footer (payment terms, legal text)
- <section class="table-region"> for table regions
- data-type and data-y attributes indicate block type and vertical position
Required fields:
- invoice_number: The invoice/receipt/document number
- invoice_date: Date in YYYY-MM-DD format (convert from any format)
- vendor_name: Company that issued the invoice
- currency: EUR, USD, GBP, etc.
- net_amount: Amount before tax (number)
- vat_amount: Tax/VAT amount (number, use 0 if reverse charge or not shown)
- total_amount: Final total amount (number)
Example output format:
{"invoice_number":"INV-123","invoice_date":"2022-01-28","vendor_name":"Adobe","currency":"EUR","net_amount":24.99,"vat_amount":0,"total_amount":24.99}
Rules:
- Return ONLY the JSON object, no explanation or markdown
- Use null for missing string fields
- Use 0 for missing numeric fields
- Convert dates to YYYY-MM-DD format (e.g., "28-JAN-2022" becomes "2022-01-28")
- Extract numbers without currency symbols
- Look for totals in <table> sections, especially rows with "Total", "Amount Due", "Grand Total"
HTML Document:
${truncated}
JSON:`;
const payload = {
model: TEXT_MODEL,
prompt,
stream: true,
options: {
num_predict: 512,
temperature: 0.1,
// JSON schema for structured output
const invoiceSchema = {
type: 'object',
properties: {
invoice_number: { type: 'string' },
invoice_date: { type: 'string' },
vendor_name: { type: 'string' },
currency: { type: 'string' },
net_amount: { type: 'number' },
vat_amount: { type: 'number' },
total_amount: { type: 'number' },
},
required: ['invoice_number', 'invoice_date', 'vendor_name', 'currency', 'net_amount', 'vat_amount', 'total_amount'],
};
const response = await fetch(`${OLLAMA_URL}/api/generate`, {
// Simple, direct prompt - the OCR output already has labeled fields
const systemPrompt = `You read invoice HTML and extract labeled fields. Return JSON only.`;
const userPrompt = `Extract from this invoice HTML:
- invoice_number: Find "Invoice no.", "Invoice #", "Invoice", "Rechnung", "Document No" and extract the value
- invoice_date: Find "Invoice date", "Date", "Datum" and convert to YYYY-MM-DD format
- vendor_name: The company name issuing the invoice (in header/letterhead)
- currency: EUR, USD, or GBP (look for € $ £ symbols or text)
- total_amount: Find "Total", "Grand Total", "Amount Due", "Gesamtbetrag" - the FINAL total amount
- net_amount: Amount before VAT/tax (Subtotal, Net)
- vat_amount: VAT/tax amount
HTML:
${truncated}
Return ONLY valid JSON: {"invoice_number":"...", "invoice_date":"YYYY-MM-DD", "vendor_name":"...", "currency":"EUR", "net_amount":0, "vat_amount":0, "total_amount":0}`;
const response = await fetch(`${OLLAMA_URL}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
body: JSON.stringify({
model: TEXT_MODEL,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt },
],
format: invoiceSchema,
stream: true,
options: { num_predict: 512, temperature: 0.0 },
}),
});
if (!response.ok) {
@@ -169,7 +179,9 @@ JSON:`;
for (const line of lines) {
try {
const json = JSON.parse(line);
if (json.response) {
if (json.message?.content) {
fullText += json.message.content;
} else if (json.response) {
fullText += json.response;
}
} catch {
@@ -179,17 +191,37 @@ JSON:`;
}
// Extract JSON from response
const startIdx = fullText.indexOf('{');
const endIdx = fullText.lastIndexOf('}') + 1;
let jsonStr = fullText.trim();
// Remove markdown code block if present
if (jsonStr.startsWith('```json')) {
jsonStr = jsonStr.slice(7);
} else if (jsonStr.startsWith('```')) {
jsonStr = jsonStr.slice(3);
}
if (jsonStr.endsWith('```')) {
jsonStr = jsonStr.slice(0, -3);
}
jsonStr = jsonStr.trim();
// Find JSON object boundaries
const startIdx = jsonStr.indexOf('{');
const endIdx = jsonStr.lastIndexOf('}') + 1;
if (startIdx < 0 || endIdx <= startIdx) {
throw new Error(`No JSON object found in response: ${fullText.substring(0, 200)}`);
}
const jsonStr = fullText.substring(startIdx, endIdx);
const parsed = JSON.parse(jsonStr);
jsonStr = jsonStr.substring(startIdx, endIdx);
// Ensure numeric fields are actually numbers
let parsed;
try {
parsed = JSON.parse(jsonStr);
} catch (e) {
throw new Error(`Invalid JSON: ${jsonStr.substring(0, 200)}`);
}
// Normalize response to expected format
return {
invoice_number: parsed.invoice_number || null,
invoice_date: parsed.invoice_date || null,
@@ -203,14 +235,23 @@ JSON:`;
/**
* Single extraction pass: Parse with PaddleOCR-VL Full, extract with Qwen2.5 (text-only)
* Processes ALL pages and concatenates HTML for multi-page invoice support
*/
async function extractOnce(images: string[], passNum: number): Promise<IInvoice> {
// Parse document with full pipeline (PaddleOCR-VL) -> returns HTML
const html = await parseDocument(images[0]);
console.log(` [Parse] Got ${html.split('\n').length} lines of HTML`);
// Parse ALL pages and concatenate HTML with page markers
const htmlParts: string[] = [];
for (let i = 0; i < images.length; i++) {
const pageHtml = await parseDocument(images[i]);
// Add page marker for context
htmlParts.push(`<!-- Page ${i + 1} -->\n${pageHtml}`);
}
const fullHtml = htmlParts.join('\n\n');
console.log(` [Parse] Got ${fullHtml.split('\n').length} lines from ${images.length} page(s)`);
// Extract invoice fields from HTML using text-only model (no images)
return extractInvoiceFromHtml(html);
return extractInvoiceFromHtml(fullHtml);
}
/**