/** * Invoice extraction using Qwen3-VL 8B Vision (Direct) * * Single-step pipeline: PDF → Images → Qwen3-VL → JSON * Uses /no_think to disable reasoning mode for fast, direct responses. * * Qwen3-VL outperforms PaddleOCR-VL on certain invoice formats. */ 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 { ensureMiniCpm } from './helpers/docker.js'; const OLLAMA_URL = 'http://localhost:11434'; const VISION_MODEL = 'qwen3-vl:8b'; interface IInvoice { invoice_number: string; invoice_date: string; vendor_name: string; currency: string; net_amount: number; vat_amount: number; total_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 { // 150 DPI is sufficient for invoice extraction, reduces context size execSync( `convert -density 150 -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 }); } } /** * Query Qwen3-VL for a single field * Uses simple prompts to minimize thinking tokens */ async function queryField(images: string[], question: string): Promise { 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: `/no_think\n${question} Reply with just the value, nothing else.`, images: images, }], stream: false, think: false, options: { num_predict: 500, temperature: 0.1, }, }), }); if (!response.ok) { throw new Error(`Ollama API error: ${response.status}`); } const data = await response.json(); return (data.message?.content || '').trim(); } /** * Extract invoice data using multiple simple queries * Each query asks for 1-2 fields to minimize thinking tokens * (Qwen3's thinking mode uses all tokens on complex prompts) */ async function extractInvoiceFromImages(images: string[]): Promise { console.log(` [Vision] Processing ${images.length} page(s) with Qwen3-VL (multi-query)`); // Query each field separately to avoid excessive thinking tokens const [invoiceNum, invoiceDate, vendor, currency, amounts] = await Promise.all([ queryField(images, 'What is the invoice number on this document?'), queryField(images, 'What is the invoice date? Format as YYYY-MM-DD.'), queryField(images, 'What company issued this invoice?'), queryField(images, 'What currency is used? Answer EUR, USD, or GBP.'), queryField(images, 'What are the net amount, VAT amount, and total amount? Format: net,vat,total'), ]); console.log(` [Vision] Got: ${invoiceNum} | ${invoiceDate} | ${vendor} | ${currency}`); // Parse amounts (format: "net,vat,total" or similar) const amountMatch = amounts.match(/([\d.,]+)/g) || []; const parseAmount = (s: string): number => { if (!s) return 0; // Handle European format: 1.234,56 → 1234.56 const normalized = s.includes(',') && s.indexOf(',') > s.lastIndexOf('.') ? s.replace(/\./g, '').replace(',', '.') : s.replace(/,/g, ''); return parseFloat(normalized) || 0; }; return { invoice_number: invoiceNum || '', invoice_date: invoiceDate || '', vendor_name: vendor || '', currency: (currency || 'EUR').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 3) || 'EUR', net_amount: parseAmount(amountMatch[0] || ''), vat_amount: parseAmount(amountMatch[1] || ''), total_amount: parseAmount(amountMatch[2] || amountMatch[0] || ''), }; } /** * Normalize date to YYYY-MM-DD */ function normalizeDate(dateStr: string | null): string { if (!dateStr) return ''; if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return dateStr; const monthMap: Record = { JAN: '01', FEB: '02', MAR: '03', APR: '04', MAY: '05', JUN: '06', JUL: '07', AUG: '08', SEP: '09', OCT: '10', NOV: '11', DEC: '12', }; let match = dateStr.match(/^(\d{1,2})-([A-Z]{3})-(\d{4})$/i); if (match) { return `${match[3]}-${monthMap[match[2].toUpperCase()] || '01'}-${match[1].padStart(2, '0')}`; } 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 vs expected */ function compareInvoice(extracted: IInvoice, expected: IInvoice): { match: boolean; errors: string[] } { const errors: string[] = []; const extNum = extracted.invoice_number?.replace(/\s/g, '').toLowerCase() || ''; const expNum = expected.invoice_number?.replace(/\s/g, '').toLowerCase() || ''; if (extNum !== expNum) { errors.push(`invoice_number: expected "${expected.invoice_number}", got "${extracted.invoice_number}"`); } if (normalizeDate(extracted.invoice_date) !== normalizeDate(expected.invoice_date)) { errors.push(`invoice_date: expected "${expected.invoice_date}", got "${extracted.invoice_date}"`); } if (Math.abs(extracted.total_amount - expected.total_amount) > 0.02) { errors.push(`total_amount: expected ${expected.total_amount}, got ${extracted.total_amount}`); } if (extracted.currency?.toUpperCase() !== expected.currency?.toUpperCase()) { errors.push(`currency: expected "${expected.currency}", got "${extracted.currency}"`); } return { match: errors.length === 0, errors }; } /** * Find test cases */ function findTestCases(): Array<{ name: string; pdfPath: string; jsonPath: string }> { const testDir = path.join(process.cwd(), '.nogit/invoices'); 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)) { testCases.push({ name: baseName, pdfPath: path.join(testDir, pdf), jsonPath: path.join(testDir, jsonFile), }); } } return testCases.sort((a, b) => a.name.localeCompare(b.name)); } /** * Ensure Qwen3-VL 8B model is available */ async function ensureQwen3Vl(): Promise { try { const response = await fetch(`${OLLAMA_URL}/api/tags`); if (response.ok) { const data = await response.json(); const models = data.models || []; if (models.some((m: { name: string }) => m.name === VISION_MODEL)) { console.log(`[Ollama] Model already available: ${VISION_MODEL}`); return true; } } } catch { console.log('[Ollama] Cannot check models'); return false; } console.log(`[Ollama] Pulling model: ${VISION_MODEL}...`); const pullResponse = await fetch(`${OLLAMA_URL}/api/pull`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: VISION_MODEL, stream: false }), }); return pullResponse.ok; } // Tests tap.test('setup: ensure Qwen3-VL is running', async () => { console.log('\n[Setup] Checking Qwen3-VL 8B...\n'); // Ensure Ollama service is running const ollamaOk = await ensureMiniCpm(); expect(ollamaOk).toBeTrue(); // Ensure Qwen3-VL 8B model const visionOk = await ensureQwen3Vl(); expect(visionOk).toBeTrue(); console.log('\n[Setup] Ready!\n'); }); const testCases = findTestCases(); console.log(`\nFound ${testCases.length} invoice test cases (Qwen3-VL Vision)\n`); let passedCount = 0; let failedCount = 0; const times: number[] = []; for (const testCase of testCases) { tap.test(`should extract invoice: ${testCase.name}`, async () => { const expected: IInvoice = JSON.parse(fs.readFileSync(testCase.jsonPath, 'utf-8')); console.log(`\n=== ${testCase.name} ===`); console.log(`Expected: ${expected.invoice_number} | ${expected.invoice_date} | ${expected.total_amount} ${expected.currency}`); const start = Date.now(); const images = convertPdfToImages(testCase.pdfPath); console.log(` Pages: ${images.length}`); const extracted = await extractInvoiceFromImages(images); console.log(` Extracted: ${extracted.invoice_number} | ${extracted.invoice_date} | ${extracted.total_amount} ${extracted.currency}`); const elapsed = Date.now() - start; times.push(elapsed); const result = compareInvoice(extracted, expected); if (result.match) { passedCount++; console.log(` Result: MATCH (${(elapsed / 1000).toFixed(1)}s)`); } else { failedCount++; console.log(` Result: MISMATCH (${(elapsed / 1000).toFixed(1)}s)`); result.errors.forEach((e) => console.log(` - ${e}`)); } expect(result.match).toBeTrue(); }); } tap.test('summary', async () => { const total = testCases.length; const accuracy = total > 0 ? (passedCount / total) * 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(` Invoice Extraction Summary (Qwen3-VL Vision)`); console.log(`======================================================`); console.log(` Method: Qwen3-VL 8B Direct Vision (/no_think)`); console.log(` Passed: ${passedCount}/${total}`); console.log(` Failed: ${failedCount}/${total}`); console.log(` Accuracy: ${accuracy.toFixed(1)}%`); console.log(`------------------------------------------------------`); console.log(` Total time: ${totalTime.toFixed(1)}s`); console.log(` Avg per inv: ${avgTime.toFixed(1)}s`); console.log(`======================================================\n`); }); export default tap.start();