Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 386122c8c7 | |||
| 7c8f10497e | |||
| 9f9ec0a671 | |||
| 3780105c6f |
26
Dockerfile_qwen3vl
Normal file
26
Dockerfile_qwen3vl
Normal file
@@ -0,0 +1,26 @@
|
||||
# Qwen3-VL-30B-A3B Vision Language Model
|
||||
# Q4_K_M quantization (~20GB model)
|
||||
#
|
||||
# Most powerful Qwen vision model:
|
||||
# - 256K context (expandable to 1M)
|
||||
# - Visual agent capabilities
|
||||
# - Code generation from images
|
||||
#
|
||||
# Build: docker build -f Dockerfile_qwen3vl -t qwen3vl .
|
||||
# Run: docker run --gpus all -p 11434:11434 -v ht-ollama-models:/root/.ollama qwen3vl
|
||||
|
||||
FROM ollama/ollama:latest
|
||||
|
||||
# Pre-pull the model during build (optional - can also pull at runtime)
|
||||
# This makes the image larger but faster to start
|
||||
# RUN ollama serve & sleep 5 && ollama pull qwen3-vl:30b-a3b && pkill ollama
|
||||
|
||||
# Expose Ollama API port
|
||||
EXPOSE 11434
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||
CMD curl -f http://localhost:11434/api/tags || exit 1
|
||||
|
||||
# Start Ollama server
|
||||
CMD ["serve"]
|
||||
18
changelog.md
18
changelog.md
@@ -1,5 +1,23 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-01-18 - 1.10.1 - fix(tests)
|
||||
improve Qwen3-VL invoice extraction test by switching to non-stream API, adding model availability/pull checks, simplifying response parsing, and tightening model options
|
||||
|
||||
- Replaced streaming reader logic with direct JSON parsing of the /api/chat response
|
||||
- Added ensureQwen3Vl() to check and pull the Qwen3-VL:8b model from Ollama
|
||||
- Switched to ensureMiniCpm() to verify Ollama service is running before model checks
|
||||
- Use /no_think prompt for direct JSON output and set temperature to 0.0 and num_predict to 512
|
||||
- Removed retry loop and streaming parsing; improved error messages to include response body
|
||||
- Updated logging and test setup messages for clarity
|
||||
|
||||
## 2026-01-18 - 1.10.0 - feat(vision)
|
||||
add Qwen3-VL vision model support with Dockerfile and tests; improve invoice OCR conversion and prompts; simplify extraction flow by removing consensus voting
|
||||
|
||||
- Add Dockerfile_qwen3vl to provide an Ollama-based image for Qwen3-VL and expose the Ollama API on port 11434
|
||||
- Introduce test/test.invoices.qwen3vl.ts and ensureQwen3Vl() helper to pull and test qwen3-vl:8b
|
||||
- Improve PDF->PNG conversion and prompt in ministral3 tests (higher DPI, max quality, sharpen) and increase num_predict from 512 to 1024
|
||||
- Simplify extraction pipeline: remove consensus voting, log single-pass results, and simplify OCR HTML sanitization/truncation logic
|
||||
|
||||
## 2026-01-18 - 1.9.0 - feat(tests)
|
||||
add Ministral 3 vision tests and improve invoice extraction pipeline to use Ollama chat schema, sanitization, and multi-page support
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@host.today/ht-docker-ai",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.1",
|
||||
"type": "module",
|
||||
"private": false,
|
||||
"description": "Docker images for AI vision-language models including MiniCPM-V 4.5",
|
||||
|
||||
@@ -311,9 +311,8 @@ export async function ensureOllamaModel(modelName: string): Promise<boolean> {
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const models = data.models || [];
|
||||
const exists = models.some((m: { name: string }) =>
|
||||
m.name === modelName || m.name.startsWith(modelName.split(':')[0])
|
||||
);
|
||||
// Exact match required - don't match on prefix
|
||||
const exists = models.some((m: { name: string }) => m.name === modelName);
|
||||
|
||||
if (exists) {
|
||||
console.log(`[Ollama] Model already available: ${modelName}`);
|
||||
@@ -371,3 +370,16 @@ export async function ensureMinistral3(): Promise<boolean> {
|
||||
// Then ensure the Ministral 3 8B model is pulled
|
||||
return ensureOllamaModel('ministral-3:8b');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure Qwen3-VL 8B model is available (vision-language model)
|
||||
* Q4_K_M quantization (~5GB) - fits in 15GB VRAM with room to spare
|
||||
*/
|
||||
export async function ensureQwen3Vl(): Promise<boolean> {
|
||||
// First ensure the Ollama service is running
|
||||
const ollamaOk = await ensureMiniCpm();
|
||||
if (!ollamaOk) return false;
|
||||
|
||||
// Then ensure Qwen3-VL 8B is pulled
|
||||
return ensureOllamaModel('qwen3-vl:8b');
|
||||
}
|
||||
|
||||
@@ -36,8 +36,9 @@ function convertPdfToImages(pdfPath: string): string[] {
|
||||
const outputPattern = path.join(tempDir, 'page-%d.png');
|
||||
|
||||
try {
|
||||
// High quality conversion: 300 DPI, max quality, sharpen for better OCR
|
||||
execSync(
|
||||
`convert -density 200 -quality 90 "${pdfPath}" -background white -alpha remove "${outputPattern}"`,
|
||||
`convert -density 300 -quality 100 "${pdfPath}" -background white -alpha remove -sharpen 0x1 "${outputPattern}"`,
|
||||
{ stdio: 'pipe' }
|
||||
);
|
||||
|
||||
@@ -77,18 +78,35 @@ async function extractInvoiceFromImages(images: string[]): Promise<IInvoice> {
|
||||
required: ['invoice_number', 'invoice_date', 'vendor_name', 'currency', 'net_amount', 'vat_amount', 'total_amount'],
|
||||
};
|
||||
|
||||
const prompt = `Extract invoice data from this document image(s).
|
||||
const prompt = `You are an expert invoice data extraction system. Carefully analyze this invoice document and extract the following fields with high precision.
|
||||
|
||||
Find and return:
|
||||
- invoice_number: The invoice number/ID (look for "Invoice No", "Invoice #", "Rechnung Nr")
|
||||
- invoice_date: The invoice date in YYYY-MM-DD format
|
||||
- vendor_name: The company issuing the invoice (in letterhead)
|
||||
- currency: EUR, USD, or GBP
|
||||
- total_amount: The FINAL total amount due
|
||||
- net_amount: Amount before VAT/tax
|
||||
- vat_amount: VAT/tax amount
|
||||
INVOICE NUMBER:
|
||||
- Look for labels: "Invoice No", "Invoice #", "Invoice Number", "Rechnung Nr", "Rechnungsnummer", "Document No", "Bill No", "Reference"
|
||||
- Usually alphanumeric, often starts with letters (e.g., R0014359508, INV-2024-001)
|
||||
- Located near the top of the invoice
|
||||
|
||||
Return ONLY valid JSON.`;
|
||||
INVOICE DATE:
|
||||
- Look for labels: "Invoice Date", "Date", "Datum", "Rechnungsdatum", "Issue Date", "Bill Date"
|
||||
- Convert ANY date format to YYYY-MM-DD (e.g., 14/10/2021 → 2021-10-14, Oct 14, 2021 → 2021-10-14)
|
||||
- Usually near the invoice number
|
||||
|
||||
VENDOR NAME:
|
||||
- The company ISSUING the invoice (not the recipient)
|
||||
- Found in letterhead, logo area, or header - typically the largest/most prominent company name
|
||||
- Examples: "Hetzner Online GmbH", "Adobe Inc", "DigitalOcean LLC"
|
||||
|
||||
CURRENCY:
|
||||
- Detect from symbols: € = EUR, $ = USD, £ = GBP
|
||||
- Or from text: "EUR", "USD", "GBP"
|
||||
- Default to EUR if unclear
|
||||
|
||||
AMOUNTS (Critical - read carefully!):
|
||||
- total_amount: The FINAL amount due/payable - look for "Total", "Grand Total", "Amount Due", "Balance Due", "Gesamtbetrag", "Endbetrag"
|
||||
- net_amount: Subtotal BEFORE tax - look for "Subtotal", "Net", "Netto", "excl. VAT"
|
||||
- vat_amount: Tax amount - look for "VAT", "Tax", "MwSt", "USt", "19%", "20%"
|
||||
- For multi-page invoices: the FINAL totals are usually on the LAST page
|
||||
|
||||
Return ONLY valid JSON with the extracted values.`;
|
||||
|
||||
const response = await fetch(`${OLLAMA_URL}/api/chat`, {
|
||||
method: 'POST',
|
||||
@@ -105,7 +123,7 @@ Return ONLY valid JSON.`;
|
||||
format: invoiceSchema,
|
||||
stream: true,
|
||||
options: {
|
||||
num_predict: 512,
|
||||
num_predict: 1024,
|
||||
temperature: 0.0,
|
||||
},
|
||||
}),
|
||||
@@ -170,46 +188,6 @@ Return ONLY valid JSON.`;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract with consensus voting (2 agreeing passes)
|
||||
*/
|
||||
async function extractWithConsensus(images: string[], name: string, maxPasses: number = 3): Promise<IInvoice> {
|
||||
const results: Array<{ invoice: IInvoice; hash: string }> = [];
|
||||
const hashCounts: Map<string, number> = new Map();
|
||||
|
||||
for (let pass = 1; pass <= maxPasses; pass++) {
|
||||
try {
|
||||
const invoice = await extractInvoiceFromImages(images);
|
||||
const hash = `${invoice.invoice_number}|${invoice.invoice_date}|${invoice.total_amount?.toFixed(2)}`;
|
||||
results.push({ invoice, hash });
|
||||
hashCounts.set(hash, (hashCounts.get(hash) || 0) + 1);
|
||||
|
||||
console.log(` [Pass ${pass}] ${invoice.invoice_number} | ${invoice.invoice_date} | ${invoice.total_amount} ${invoice.currency}`);
|
||||
|
||||
if (hashCounts.get(hash)! >= 2) {
|
||||
console.log(` [Consensus] Reached after ${pass} passes`);
|
||||
return invoice;
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(` [Pass ${pass}] Error: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Return most common result
|
||||
let bestHash = '';
|
||||
let bestCount = 0;
|
||||
for (const [hash, count] of hashCounts) {
|
||||
if (count > bestCount) {
|
||||
bestCount = count;
|
||||
bestHash = hash;
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestHash) throw new Error(`No valid results for ${name}`);
|
||||
|
||||
console.log(` [No consensus] Using best result (${bestCount}/${maxPasses})`);
|
||||
return results.find((r) => r.hash === bestHash)!.invoice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize date to YYYY-MM-DD
|
||||
@@ -314,7 +292,8 @@ for (const testCase of testCases) {
|
||||
const images = convertPdfToImages(testCase.pdfPath);
|
||||
console.log(` Pages: ${images.length}`);
|
||||
|
||||
const extracted = await extractWithConsensus(images, testCase.name);
|
||||
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);
|
||||
|
||||
|
||||
@@ -89,25 +89,13 @@ async function parseDocument(imageBase64: string): Promise<string> {
|
||||
return data.result?.html || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 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> {
|
||||
const sanitized = sanitizeHtml(html);
|
||||
const truncated = sanitized.length > 32000 ? sanitized.slice(0, 32000) : sanitized;
|
||||
// OCR output is already good - just truncate if too long
|
||||
const truncated = html.length > 32000 ? html.slice(0, 32000) : html;
|
||||
console.log(` [Extract] ${truncated.length} chars of HTML`);
|
||||
|
||||
// JSON schema for structured output
|
||||
|
||||
311
test/test.invoices.qwen3vl.ts
Normal file
311
test/test.invoices.qwen3vl.ts
Normal file
@@ -0,0 +1,311 @@
|
||||
/**
|
||||
* 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 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract invoice data directly from images using Qwen3-VL Vision
|
||||
* Uses /no_think to disable reasoning mode for fast, direct JSON output
|
||||
*/
|
||||
async function extractInvoiceFromImages(images: string[]): Promise<IInvoice> {
|
||||
console.log(` [Vision] Processing ${images.length} page(s) with Qwen3-VL`);
|
||||
|
||||
// /no_think disables Qwen3's reasoning mode - crucial for getting direct output
|
||||
const prompt = `/no_think
|
||||
Look at this invoice and extract these fields. Reply with ONLY JSON, no explanation.
|
||||
|
||||
- invoice_number
|
||||
- invoice_date (format: YYYY-MM-DD)
|
||||
- vendor_name
|
||||
- currency (EUR, USD, or GBP)
|
||||
- net_amount
|
||||
- vat_amount
|
||||
- total_amount
|
||||
|
||||
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({
|
||||
model: VISION_MODEL,
|
||||
messages: [{
|
||||
role: 'user',
|
||||
content: prompt,
|
||||
images: images, // Pass all pages
|
||||
}],
|
||||
stream: false,
|
||||
options: {
|
||||
num_predict: 512,
|
||||
temperature: 0.0,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.text();
|
||||
throw new Error(`Ollama API error: ${response.status} - ${err}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
let content = data.message?.content || '';
|
||||
|
||||
console.log(` [Vision] Response (${content.length} chars): ${content.substring(0, 200)}...`);
|
||||
|
||||
// Parse JSON from response
|
||||
if (content.startsWith('```json')) content = content.slice(7);
|
||||
else if (content.startsWith('```')) content = content.slice(3);
|
||||
if (content.endsWith('```')) content = content.slice(0, -3);
|
||||
content = content.trim();
|
||||
|
||||
const startIdx = content.indexOf('{');
|
||||
const endIdx = content.lastIndexOf('}') + 1;
|
||||
|
||||
if (startIdx < 0 || endIdx <= startIdx) {
|
||||
throw new Error(`No JSON found: ${content.substring(0, 300)}`);
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(content.substring(startIdx, endIdx));
|
||||
|
||||
return {
|
||||
invoice_number: parsed.invoice_number || null,
|
||||
invoice_date: parsed.invoice_date || null,
|
||||
vendor_name: parsed.vendor_name || null,
|
||||
currency: parsed.currency || 'EUR',
|
||||
net_amount: parseFloat(parsed.net_amount) || 0,
|
||||
vat_amount: parseFloat(parsed.vat_amount) || 0,
|
||||
total_amount: parseFloat(parsed.total_amount) || 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<string, string> = {
|
||||
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<boolean> {
|
||||
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();
|
||||
Reference in New Issue
Block a user