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:
348
test/test.bankstatements.ministral3.ts
Normal file
348
test/test.bankstatements.ministral3.ts
Normal file
@@ -0,0 +1,348 @@
|
||||
/**
|
||||
* Bank Statement extraction using Ministral 3 Vision (Direct)
|
||||
*
|
||||
* NO OCR pipeline needed - Ministral 3 has built-in vision encoder:
|
||||
* 1. Convert PDF to images
|
||||
* 2. Send images directly to Ministral 3 via Ollama
|
||||
* 3. Extract transactions as structured JSON
|
||||
*/
|
||||
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { execSync } from 'child_process';
|
||||
import * as os from 'os';
|
||||
import { ensureMinistral3 } from './helpers/docker.js';
|
||||
|
||||
const OLLAMA_URL = 'http://localhost:11434';
|
||||
const VISION_MODEL = 'ministral-3:8b';
|
||||
|
||||
interface ITransaction {
|
||||
date: string;
|
||||
counterparty: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert PDF to PNG images using ImageMagick
|
||||
*/
|
||||
function convertPdfToImages(pdfPath: string): string[] {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pdf-convert-'));
|
||||
const outputPattern = path.join(tempDir, 'page-%d.png');
|
||||
|
||||
try {
|
||||
execSync(
|
||||
`convert -density 200 -quality 90 "${pdfPath}" -background white -alpha remove "${outputPattern}"`,
|
||||
{ stdio: 'pipe' }
|
||||
);
|
||||
|
||||
const files = fs.readdirSync(tempDir).filter((f) => f.endsWith('.png')).sort();
|
||||
const images: string[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
const imagePath = path.join(tempDir, file);
|
||||
const imageData = fs.readFileSync(imagePath);
|
||||
images.push(imageData.toString('base64'));
|
||||
}
|
||||
|
||||
return images;
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract transactions from a single page image using Ministral 3 Vision
|
||||
*/
|
||||
async function extractTransactionsFromPage(image: string, pageNum: number): Promise<ITransaction[]> {
|
||||
console.log(` [Vision] Processing page ${pageNum}`);
|
||||
|
||||
// JSON schema for array of transactions
|
||||
const transactionSchema = {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
date: { type: 'string', description: 'Transaction date in YYYY-MM-DD format' },
|
||||
counterparty: { type: 'string', description: 'Name of the other party' },
|
||||
amount: { type: 'number', description: 'Amount (negative for debits, positive for credits)' },
|
||||
},
|
||||
required: ['date', 'counterparty', 'amount'],
|
||||
},
|
||||
};
|
||||
|
||||
const prompt = `Extract ALL bank transactions from this bank statement page.
|
||||
|
||||
For each transaction, extract:
|
||||
- date: Transaction date in YYYY-MM-DD format
|
||||
- counterparty: The name/description of the other party (merchant, payee, etc.)
|
||||
- amount: The amount as a number (NEGATIVE for debits/expenses, POSITIVE for credits/income)
|
||||
|
||||
Return a JSON array of transactions. If no transactions visible, return empty array [].
|
||||
Example: [{"date":"2021-06-01","counterparty":"AMAZON","amount":-50.00}]`;
|
||||
|
||||
const response = await fetch(`${OLLAMA_URL}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: VISION_MODEL,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: prompt,
|
||||
images: [image],
|
||||
},
|
||||
],
|
||||
format: transactionSchema,
|
||||
stream: true,
|
||||
options: {
|
||||
num_predict: 4096, // Bank statements can have many transactions
|
||||
temperature: 0.0,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ollama API error: ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
throw new Error('No response body');
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
let fullText = '';
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true });
|
||||
const lines = chunk.split('\n').filter((l) => l.trim());
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const json = JSON.parse(line);
|
||||
if (json.message?.content) {
|
||||
fullText += json.message.content;
|
||||
}
|
||||
} catch {
|
||||
// Skip invalid JSON lines
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse JSON response
|
||||
let jsonStr = fullText.trim();
|
||||
|
||||
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 array boundaries
|
||||
const startIdx = jsonStr.indexOf('[');
|
||||
const endIdx = jsonStr.lastIndexOf(']') + 1;
|
||||
|
||||
if (startIdx < 0 || endIdx <= startIdx) {
|
||||
console.log(` [Page ${pageNum}] No transactions found`);
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(jsonStr.substring(startIdx, endIdx));
|
||||
console.log(` [Page ${pageNum}] Found ${parsed.length} transactions`);
|
||||
return parsed.map((t: { date?: string; counterparty?: string; amount?: number }) => ({
|
||||
date: t.date || '',
|
||||
counterparty: t.counterparty || '',
|
||||
amount: parseFloat(String(t.amount)) || 0,
|
||||
}));
|
||||
} catch (e) {
|
||||
console.log(` [Page ${pageNum}] Parse error: ${e}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract all transactions from all pages
|
||||
*/
|
||||
async function extractAllTransactions(images: string[]): Promise<ITransaction[]> {
|
||||
const allTransactions: ITransaction[] = [];
|
||||
|
||||
for (let i = 0; i < images.length; i++) {
|
||||
const pageTransactions = await extractTransactionsFromPage(images[i], i + 1);
|
||||
allTransactions.push(...pageTransactions);
|
||||
}
|
||||
|
||||
return allTransactions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize date to YYYY-MM-DD
|
||||
*/
|
||||
function normalizeDate(dateStr: string): string {
|
||||
if (!dateStr) return '';
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return dateStr;
|
||||
|
||||
// Handle DD/MM/YYYY or DD.MM.YYYY
|
||||
const match = dateStr.match(/^(\d{1,2})[\/.](\d{1,2})[\/.](\d{4})$/);
|
||||
if (match) {
|
||||
return `${match[3]}-${match[2].padStart(2, '0')}-${match[1].padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare extracted transactions vs expected
|
||||
*/
|
||||
function compareTransactions(
|
||||
extracted: ITransaction[],
|
||||
expected: ITransaction[]
|
||||
): { matchRate: number; matched: number; missed: number; extra: number; errors: string[] } {
|
||||
const errors: string[] = [];
|
||||
let matched = 0;
|
||||
|
||||
// Normalize all dates
|
||||
const normalizedExtracted = extracted.map((t) => ({
|
||||
...t,
|
||||
date: normalizeDate(t.date),
|
||||
counterparty: t.counterparty.toUpperCase().trim(),
|
||||
}));
|
||||
|
||||
const normalizedExpected = expected.map((t) => ({
|
||||
...t,
|
||||
date: normalizeDate(t.date),
|
||||
counterparty: t.counterparty.toUpperCase().trim(),
|
||||
}));
|
||||
|
||||
// Try to match each expected transaction
|
||||
const matchedIndices = new Set<number>();
|
||||
|
||||
for (const exp of normalizedExpected) {
|
||||
let found = false;
|
||||
|
||||
for (let i = 0; i < normalizedExtracted.length; i++) {
|
||||
if (matchedIndices.has(i)) continue;
|
||||
|
||||
const ext = normalizedExtracted[i];
|
||||
|
||||
// Match by date + amount (counterparty names can vary)
|
||||
if (ext.date === exp.date && Math.abs(ext.amount - exp.amount) < 0.02) {
|
||||
matched++;
|
||||
matchedIndices.add(i);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
errors.push(`Missing: ${exp.date} | ${exp.counterparty} | ${exp.amount}`);
|
||||
}
|
||||
}
|
||||
|
||||
const missed = expected.length - matched;
|
||||
const extra = extracted.length - matched;
|
||||
const matchRate = expected.length > 0 ? (matched / expected.length) * 100 : 0;
|
||||
|
||||
return { matchRate, matched, missed, extra, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Find test cases (PDF + JSON pairs in .nogit/)
|
||||
*/
|
||||
function findTestCases(): Array<{ name: string; pdfPath: string; jsonPath: string }> {
|
||||
const testDir = path.join(process.cwd(), '.nogit');
|
||||
if (!fs.existsSync(testDir)) return [];
|
||||
|
||||
const files = fs.readdirSync(testDir);
|
||||
const testCases: Array<{ name: string; pdfPath: string; jsonPath: string }> = [];
|
||||
|
||||
for (const pdf of files.filter((f) => f.endsWith('.pdf'))) {
|
||||
const baseName = pdf.replace('.pdf', '');
|
||||
const jsonFile = `${baseName}.json`;
|
||||
if (files.includes(jsonFile)) {
|
||||
// Skip invoice files - only bank statements
|
||||
if (!baseName.includes('invoice')) {
|
||||
testCases.push({
|
||||
name: baseName,
|
||||
pdfPath: path.join(testDir, pdf),
|
||||
jsonPath: path.join(testDir, jsonFile),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return testCases.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
// Tests
|
||||
|
||||
tap.test('setup: ensure Ministral 3 is running', async () => {
|
||||
console.log('\n[Setup] Checking Ministral 3...\n');
|
||||
const ok = await ensureMinistral3();
|
||||
expect(ok).toBeTrue();
|
||||
console.log('\n[Setup] Ready!\n');
|
||||
});
|
||||
|
||||
const testCases = findTestCases();
|
||||
console.log(`\nFound ${testCases.length} bank statement test cases (Ministral 3 Vision)\n`);
|
||||
|
||||
let totalMatched = 0;
|
||||
let totalExpected = 0;
|
||||
const times: number[] = [];
|
||||
|
||||
for (const testCase of testCases) {
|
||||
tap.test(`should extract bank statement: ${testCase.name}`, async () => {
|
||||
const expected: ITransaction[] = JSON.parse(fs.readFileSync(testCase.jsonPath, 'utf-8'));
|
||||
console.log(`\n=== ${testCase.name} ===`);
|
||||
console.log(`Expected: ${expected.length} transactions`);
|
||||
|
||||
const start = Date.now();
|
||||
const images = convertPdfToImages(testCase.pdfPath);
|
||||
console.log(` Pages: ${images.length}`);
|
||||
|
||||
const extracted = await extractAllTransactions(images);
|
||||
const elapsed = Date.now() - start;
|
||||
times.push(elapsed);
|
||||
|
||||
console.log(` Extracted: ${extracted.length} transactions`);
|
||||
|
||||
const result = compareTransactions(extracted, expected);
|
||||
totalMatched += result.matched;
|
||||
totalExpected += expected.length;
|
||||
|
||||
console.log(` Match rate: ${result.matchRate.toFixed(1)}% (${result.matched}/${expected.length})`);
|
||||
console.log(` Missed: ${result.missed}, Extra: ${result.extra}`);
|
||||
console.log(` Time: ${(elapsed / 1000).toFixed(1)}s`);
|
||||
|
||||
if (result.errors.length > 0 && result.errors.length <= 5) {
|
||||
result.errors.forEach((e) => console.log(` - ${e}`));
|
||||
} else if (result.errors.length > 5) {
|
||||
console.log(` (${result.errors.length} missing transactions)`);
|
||||
}
|
||||
|
||||
// Consider it a pass if we match at least 70% of transactions
|
||||
expect(result.matchRate).toBeGreaterThan(70);
|
||||
});
|
||||
}
|
||||
|
||||
tap.test('summary', async () => {
|
||||
const overallMatchRate = totalExpected > 0 ? (totalMatched / totalExpected) * 100 : 0;
|
||||
const totalTime = times.reduce((a, b) => a + b, 0) / 1000;
|
||||
const avgTime = times.length > 0 ? totalTime / times.length : 0;
|
||||
|
||||
console.log(`\n======================================================`);
|
||||
console.log(` Bank Statement Extraction Summary (Ministral 3)`);
|
||||
console.log(`======================================================`);
|
||||
console.log(` Method: Ministral 3 8B Vision (Direct)`);
|
||||
console.log(` Statements: ${testCases.length}`);
|
||||
console.log(` Matched: ${totalMatched}/${totalExpected} transactions`);
|
||||
console.log(` Match rate: ${overallMatchRate.toFixed(1)}%`);
|
||||
console.log(`------------------------------------------------------`);
|
||||
console.log(` Total time: ${totalTime.toFixed(1)}s`);
|
||||
console.log(` Avg per stmt: ${avgTime.toFixed(1)}s`);
|
||||
console.log(`======================================================\n`);
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
Reference in New Issue
Block a user