fix(tests): stabilize OCR extraction tests and manage GPU containers

This commit is contained in:
2026-01-18 23:00:24 +00:00
parent 09ea7440e8
commit ae28a64902
4 changed files with 451 additions and 425 deletions

View File

@@ -1,19 +1,17 @@
/**
* Invoice extraction using Nanonets-OCR-s + Qwen3 (two-stage pipeline)
* Invoice extraction using Nanonets-OCR-s + Qwen3 (sequential two-stage pipeline)
*
* Stage 1: Nanonets-OCR-s converts document pages to markdown (its strength)
* Stage 2: Qwen3 extracts structured JSON from the combined markdown
* Stage 1: Nanonets-OCR-s converts ALL document pages to markdown (stop after completion)
* Stage 2: Qwen3 extracts structured JSON from saved markdown (after Nanonets stops)
*
* This leverages each model's strengths:
* - Nanonets: Document OCR with semantic tags
* - Qwen3: Text understanding and JSON extraction
* This approach avoids GPU contention by running services sequentially.
*/
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 { ensureNanonetsOcr, ensureMiniCpm } from './helpers/docker.js';
import { ensureNanonetsOcr, ensureMiniCpm, isContainerRunning } from './helpers/docker.js';
const NANONETS_URL = 'http://localhost:8000/v1';
const NANONETS_MODEL = 'nanonets/Nanonets-OCR-s';
@@ -21,6 +19,9 @@ const NANONETS_MODEL = 'nanonets/Nanonets-OCR-s';
const OLLAMA_URL = 'http://localhost:11434';
const QWEN_MODEL = 'qwen3:8b';
// Temp directory for storing markdown between stages
const TEMP_MD_DIR = path.join(os.tmpdir(), 'nanonets-invoices-markdown');
interface IInvoice {
invoice_number: string;
invoice_date: string;
@@ -31,6 +32,13 @@ interface IInvoice {
total_amount: number;
}
interface ITestCase {
name: string;
pdfPath: string;
jsonPath: string;
markdownPath?: string;
}
// Nanonets-specific prompt for document OCR to markdown
const NANONETS_OCR_PROMPT = `Extract the text from the above document as if you were reading it naturally.
Return the tables in html format.
@@ -66,14 +74,13 @@ INVOICE TEXT:
`;
/**
* Convert PDF to PNG images using ImageMagick
* Convert PDF to PNG images
*/
function convertPdfToImages(pdfPath: string): string[] {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pdf-convert-'));
const outputPattern = path.join(tempDir, 'page-%d.png');
try {
// Use 150 DPI to keep images within model's context length
execSync(
`convert -density 150 -quality 90 "${pdfPath}" -background white -alpha remove "${outputPattern}"`,
{ stdio: 'pipe' }
@@ -95,10 +102,9 @@ function convertPdfToImages(pdfPath: string): string[] {
}
/**
* Stage 1: Convert a single page to markdown using Nanonets-OCR-s
* Convert a single page to markdown using Nanonets-OCR-s
*/
async function convertPageToMarkdown(image: string, pageNum: number): Promise<string> {
console.log(` [Nanonets] Converting page ${pageNum} to markdown...`);
const startTime = Date.now();
const response = await fetch(`${NANONETS_URL}/chat/completions`, {
@@ -125,21 +131,20 @@ async function convertPageToMarkdown(image: string, pageNum: number): Promise<st
if (!response.ok) {
const errorText = await response.text();
console.log(` [Nanonets] ERROR page ${pageNum}: ${response.status} - ${errorText}`);
throw new Error(`Nanonets API error: ${response.status}`);
throw new Error(`Nanonets API error: ${response.status} - ${errorText}`);
}
const data = await response.json();
const content = (data.choices?.[0]?.message?.content || '').trim();
console.log(` [Nanonets] Page ${pageNum} converted (${elapsed}s, ${content.length} chars)`);
console.log(` Page ${pageNum}: ${content.length} chars (${elapsed}s)`);
return content;
}
/**
* Stage 1: Convert all pages to markdown using Nanonets-OCR-s
* Convert all pages of a document to markdown
*/
async function convertDocumentToMarkdown(images: string[]): Promise<string> {
console.log(` [Stage 1] Converting ${images.length} page(s) to markdown with Nanonets-OCR-s...`);
async function convertDocumentToMarkdown(images: string[], docName: string): Promise<string> {
console.log(` [${docName}] Converting ${images.length} page(s)...`);
const markdownPages: string[] = [];
@@ -149,10 +154,24 @@ async function convertDocumentToMarkdown(images: string[]): Promise<string> {
}
const fullMarkdown = markdownPages.join('\n\n');
console.log(` [Stage 1] Complete: ${fullMarkdown.length} chars total`);
console.log(` [${docName}] Complete: ${fullMarkdown.length} chars total`);
return fullMarkdown;
}
/**
* Stop Nanonets container
*/
function stopNanonets(): void {
console.log(' [Docker] Stopping Nanonets container...');
try {
execSync('docker stop nanonets-test 2>/dev/null || true', { stdio: 'pipe' });
execSync('sleep 5', { stdio: 'pipe' });
console.log(' [Docker] Nanonets stopped');
} catch {
console.log(' [Docker] Nanonets was not running');
}
}
/**
* Ensure Qwen3 model is available
*/
@@ -190,7 +209,6 @@ function parseAmount(s: string | number | undefined): number {
const match = s.match(/([\d.,]+)/);
if (!match) return 0;
const numStr = match[1];
// Handle European format: 1.234,56 -> 1234.56
const normalized = numStr.includes(',') && numStr.indexOf(',') > numStr.lastIndexOf('.')
? numStr.replace(/\./g, '').replace(',', '.')
: numStr.replace(/,/g, '');
@@ -204,10 +222,10 @@ function extractInvoiceNumber(s: string | undefined): string {
if (!s) return '';
let clean = s.replace(/\*\*/g, '').replace(/`/g, '').trim();
const patterns = [
/\b([A-Z]{2,3}\d{10,})\b/i, // IEE2022006460244
/\b([A-Z]\d{8,})\b/i, // R0014359508
/\b(INV[-\s]?\d{4}[-\s]?\d+)\b/i, // INV-2024-001
/\b(\d{7,})\b/, // 1579087430
/\b([A-Z]{2,3}\d{10,})\b/i,
/\b([A-Z]\d{8,})\b/i,
/\b(INV[-\s]?\d{4}[-\s]?\d+)\b/i,
/\b(\d{7,})\b/,
];
for (const pattern of patterns) {
const match = clean.match(pattern);
@@ -224,7 +242,6 @@ function extractDate(s: string | undefined): string {
let clean = s.replace(/\*\*/g, '').replace(/`/g, '').trim();
const isoMatch = clean.match(/(\d{4}-\d{2}-\d{2})/);
if (isoMatch) return isoMatch[1];
// Try DD/MM/YYYY or DD.MM.YYYY
const dmyMatch = clean.match(/(\d{1,2})[\/.](\d{1,2})[\/.](\d{4})/);
if (dmyMatch) {
return `${dmyMatch[3]}-${dmyMatch[2].padStart(2, '0')}-${dmyMatch[1].padStart(2, '0')}`;
@@ -245,20 +262,16 @@ function extractCurrency(s: string | undefined): string {
}
/**
* Extract JSON from response (handles markdown code blocks)
* Extract JSON from response
*/
function extractJsonFromResponse(response: string): Record<string, unknown> | null {
// Remove thinking tags if present (Qwen3 may include <think>...</think>)
let cleanResponse = response.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
// Try to find JSON in markdown code block
const codeBlockMatch = cleanResponse.match(/```(?:json)?\s*([\s\S]*?)```/);
const jsonStr = codeBlockMatch ? codeBlockMatch[1].trim() : cleanResponse;
try {
return JSON.parse(jsonStr);
} catch {
// Try to find JSON object pattern
const jsonMatch = jsonStr.match(/\{[\s\S]*\}/);
if (jsonMatch) {
try {
@@ -290,15 +303,16 @@ function parseJsonToInvoice(response: string): IInvoice | null {
}
/**
* Stage 2: Extract invoice from markdown using Qwen3
* Extract invoice from markdown using Qwen3
*/
async function extractInvoiceFromMarkdown(markdown: string, queryId: string): Promise<IInvoice | null> {
console.log(` [${queryId}] Sending markdown to ${QWEN_MODEL}...`);
console.log(` [${queryId}] Sending to ${QWEN_MODEL}...`);
const startTime = Date.now();
const response = await fetch(`${OLLAMA_URL}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(600000), // 10 minute timeout for large documents
body: JSON.stringify({
model: QWEN_MODEL,
messages: [{
@@ -322,13 +336,13 @@ async function extractInvoiceFromMarkdown(markdown: string, queryId: string): Pr
const data = await response.json();
const content = (data.message?.content || '').trim();
console.log(` [${queryId}] Response received (${elapsed}s, ${content.length} chars)`);
console.log(` [${queryId}] Response: ${content.length} chars (${elapsed}s)`);
return parseJsonToInvoice(content);
}
/**
* Compare two invoices for consensus (key fields must match)
* Compare two invoices for consensus
*/
function invoicesMatch(a: IInvoice, b: IInvoice): boolean {
const numMatch = a.invoice_number.toLowerCase() === b.invoice_number.toLowerCase();
@@ -338,45 +352,39 @@ function invoicesMatch(a: IInvoice, b: IInvoice): boolean {
}
/**
* Stage 2: Extract invoice using Qwen3 with consensus
* Extract with consensus
*/
async function extractWithConsensus(markdown: string): Promise<IInvoice> {
async function extractWithConsensus(markdown: string, docName: string): Promise<IInvoice> {
const MAX_ATTEMPTS = 3;
console.log(` [Stage 2] Extracting invoice with ${QWEN_MODEL} (consensus)...`);
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
console.log(`\n [Stage 2] --- Attempt ${attempt}/${MAX_ATTEMPTS} ---`);
console.log(` [${docName}] Attempt ${attempt}/${MAX_ATTEMPTS}`);
// Extract twice
const inv1 = await extractInvoiceFromMarkdown(markdown, `A${attempt}Q1`);
const inv2 = await extractInvoiceFromMarkdown(markdown, `A${attempt}Q2`);
const inv1 = await extractInvoiceFromMarkdown(markdown, `${docName}-A${attempt}Q1`);
const inv2 = await extractInvoiceFromMarkdown(markdown, `${docName}-A${attempt}Q2`);
if (!inv1 || !inv2) {
console.log(` [Stage 2] Parsing failed, retrying...`);
console.log(` [${docName}] Parsing failed, retrying...`);
continue;
}
console.log(` [Stage 2] Q1: ${inv1.invoice_number} | ${inv1.invoice_date} | ${inv1.total_amount} ${inv1.currency}`);
console.log(` [Stage 2] Q2: ${inv2.invoice_number} | ${inv2.invoice_date} | ${inv2.total_amount} ${inv2.currency}`);
console.log(` [${docName}] Q1: ${inv1.invoice_number} | ${inv1.invoice_date} | ${inv1.total_amount}`);
console.log(` [${docName}] Q2: ${inv2.invoice_number} | ${inv2.invoice_date} | ${inv2.total_amount}`);
if (invoicesMatch(inv1, inv2)) {
console.log(` [Stage 2] CONSENSUS REACHED`);
console.log(` [${docName}] CONSENSUS`);
return inv2;
}
console.log(` [Stage 2] NO CONSENSUS`);
console.log(` [${docName}] No consensus`);
}
// Fallback: use last response
console.log(`\n [Stage 2] === FALLBACK ===`);
const fallback = await extractInvoiceFromMarkdown(markdown, 'FALLBACK');
// Fallback
const fallback = await extractInvoiceFromMarkdown(markdown, `${docName}-FALLBACK`);
if (fallback) {
console.log(` [Stage 2] ~ FALLBACK: ${fallback.invoice_number} | ${fallback.invoice_date} | ${fallback.total_amount}`);
console.log(` [${docName}] FALLBACK: ${fallback.invoice_number} | ${fallback.invoice_date} | ${fallback.total_amount}`);
return fallback;
}
// Return empty invoice if all else fails
return {
invoice_number: '',
invoice_date: '',
@@ -388,19 +396,6 @@ async function extractWithConsensus(markdown: string): Promise<IInvoice> {
};
}
/**
* Full pipeline: PDF -> Images -> Markdown -> JSON
*/
async function extractInvoice(images: string[]): Promise<IInvoice> {
// Stage 1: Convert to markdown
const markdown = await convertDocumentToMarkdown(images);
// Stage 2: Extract invoice with consensus
const invoice = await extractWithConsensus(markdown);
return invoice;
}
/**
* Normalize date to YYYY-MM-DD
*/
@@ -435,45 +430,38 @@ function compareInvoice(
): { match: boolean; errors: string[] } {
const errors: string[] = [];
// Compare invoice number (normalize by removing spaces and case)
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}"`);
errors.push(`invoice_number: exp "${expected.invoice_number}", got "${extracted.invoice_number}"`);
}
// Compare date
if (normalizeDate(extracted.invoice_date) !== normalizeDate(expected.invoice_date)) {
errors.push(`invoice_date: expected "${expected.invoice_date}", got "${extracted.invoice_date}"`);
errors.push(`invoice_date: exp "${expected.invoice_date}", got "${extracted.invoice_date}"`);
}
// Compare total amount (with tolerance)
if (Math.abs(extracted.total_amount - expected.total_amount) > 0.02) {
errors.push(`total_amount: expected ${expected.total_amount}, got ${extracted.total_amount}`);
errors.push(`total_amount: exp ${expected.total_amount}, got ${extracted.total_amount}`);
}
// Compare currency
if (extracted.currency?.toUpperCase() !== expected.currency?.toUpperCase()) {
errors.push(`currency: expected "${expected.currency}", got "${extracted.currency}"`);
errors.push(`currency: exp "${expected.currency}", got "${extracted.currency}"`);
}
return { match: errors.length === 0, errors };
}
/**
* Find all test cases (PDF + JSON pairs) in .nogit/invoices/
* Find all test cases
*/
function findTestCases(): Array<{ name: string; pdfPath: string; jsonPath: string }> {
function findTestCases(): ITestCase[] {
const testDir = path.join(process.cwd(), '.nogit/invoices');
if (!fs.existsSync(testDir)) {
return [];
}
if (!fs.existsSync(testDir)) return [];
const files = fs.readdirSync(testDir);
const pdfFiles = files.filter((f) => f.endsWith('.pdf'));
const testCases: Array<{ name: string; pdfPath: string; jsonPath: string }> = [];
const testCases: ITestCase[] = [];
for (const pdf of pdfFiles) {
for (const pdf of files.filter((f) => f.endsWith('.pdf'))) {
const baseName = pdf.replace('.pdf', '');
const jsonFile = `${baseName}.json`;
if (files.includes(jsonFile)) {
@@ -485,90 +473,114 @@ function findTestCases(): Array<{ name: string; pdfPath: string; jsonPath: strin
}
}
testCases.sort((a, b) => a.name.localeCompare(b.name));
return testCases;
return testCases.sort((a, b) => a.name.localeCompare(b.name));
}
// Tests
// ============ TESTS ============
tap.test('setup: ensure containers are running', async () => {
console.log('\n[Setup] Checking Docker containers...\n');
const testCases = findTestCases();
console.log(`\nFound ${testCases.length} invoice test cases\n`);
// Nanonets for OCR
const nanonetsOk = await ensureNanonetsOcr();
expect(nanonetsOk).toBeTrue();
// Ensure temp directory exists
if (!fs.existsSync(TEMP_MD_DIR)) {
fs.mkdirSync(TEMP_MD_DIR, { recursive: true });
}
// -------- STAGE 1: OCR with Nanonets --------
tap.test('Stage 1: Setup Nanonets', async () => {
console.log('\n========== STAGE 1: Nanonets OCR ==========\n');
const ok = await ensureNanonetsOcr();
expect(ok).toBeTrue();
});
tap.test('Stage 1: Convert all invoices to markdown', async () => {
console.log('\n Converting all invoice PDFs to markdown with Nanonets-OCR-s...\n');
for (const tc of testCases) {
console.log(`\n === ${tc.name} ===`);
const images = convertPdfToImages(tc.pdfPath);
console.log(` Pages: ${images.length}`);
const markdown = await convertDocumentToMarkdown(images, tc.name);
const mdPath = path.join(TEMP_MD_DIR, `${tc.name}.md`);
fs.writeFileSync(mdPath, markdown);
tc.markdownPath = mdPath;
console.log(` Saved: ${mdPath}`);
}
console.log('\n Stage 1 complete: All invoices converted to markdown\n');
});
tap.test('Stage 1: Stop Nanonets', async () => {
stopNanonets();
await new Promise(resolve => setTimeout(resolve, 3000));
expect(isContainerRunning('nanonets-test')).toBeFalse();
});
// -------- STAGE 2: Extraction with Qwen3 --------
tap.test('Stage 2: Setup Ollama + Qwen3', async () => {
console.log('\n========== STAGE 2: Qwen3 Extraction ==========\n');
// Ollama for Qwen3
const ollamaOk = await ensureMiniCpm();
expect(ollamaOk).toBeTrue();
// Qwen3 model
const qwenOk = await ensureQwen3();
expect(qwenOk).toBeTrue();
console.log('\n[Setup] All containers ready!\n');
});
tap.test('should have models available', async () => {
// Check Nanonets
const nanonetsResp = await fetch(`${NANONETS_URL}/models`);
expect(nanonetsResp.ok).toBeTrue();
// Check Qwen3
const ollamaResp = await fetch(`${OLLAMA_URL}/api/tags`);
expect(ollamaResp.ok).toBeTrue();
const data = await ollamaResp.json();
const modelNames = data.models.map((m: { name: string }) => m.name);
expect(modelNames.some((name: string) => name.includes('qwen3'))).toBeTrue();
});
const testCases = findTestCases();
console.log(`\nFound ${testCases.length} invoice test cases (Nanonets + Qwen3)\n`);
let passedCount = 0;
let failedCount = 0;
const processingTimes: 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}`);
for (const tc of testCases) {
tap.test(`Stage 2: Extract ${tc.name}`, async () => {
const expected: IInvoice = JSON.parse(fs.readFileSync(tc.jsonPath, 'utf-8'));
console.log(`\n === ${tc.name} ===`);
console.log(` Expected: ${expected.invoice_number} | ${expected.invoice_date} | ${expected.total_amount} ${expected.currency}`);
const startTime = Date.now();
const images = convertPdfToImages(testCase.pdfPath);
console.log(` Pages: ${images.length}`);
const extracted = await extractInvoice(images);
console.log(` Extracted: ${extracted.invoice_number} | ${extracted.invoice_date} | ${extracted.total_amount} ${extracted.currency}`);
const mdPath = path.join(TEMP_MD_DIR, `${tc.name}.md`);
if (!fs.existsSync(mdPath)) {
throw new Error(`Markdown not found: ${mdPath}. Run Stage 1 first.`);
}
const markdown = fs.readFileSync(mdPath, 'utf-8');
console.log(` Markdown: ${markdown.length} chars`);
const extracted = await extractWithConsensus(markdown, tc.name);
const elapsedMs = Date.now() - startTime;
processingTimes.push(elapsedMs);
console.log(` Extracted: ${extracted.invoice_number} | ${extracted.invoice_date} | ${extracted.total_amount} ${extracted.currency}`);
const result = compareInvoice(extracted, expected);
if (result.match) {
passedCount++;
console.log(` Result: MATCH (${(elapsedMs / 1000).toFixed(1)}s)`);
console.log(` Result: MATCH (${(elapsedMs / 1000).toFixed(1)}s)`);
} else {
failedCount++;
console.log(` Result: MISMATCH (${(elapsedMs / 1000).toFixed(1)}s)`);
result.errors.forEach((e) => console.log(` - ${e}`));
console.log(` Result: MISMATCH (${(elapsedMs / 1000).toFixed(1)}s)`);
result.errors.forEach(e => console.log(` - ${e}`));
}
expect(result.match).toBeTrue();
});
}
tap.test('summary', async () => {
tap.test('Summary', async () => {
const totalInvoices = testCases.length;
const accuracy = totalInvoices > 0 ? (passedCount / totalInvoices) * 100 : 0;
const totalTimeMs = processingTimes.reduce((a, b) => a + b, 0);
const avgTimeSec = processingTimes.length > 0 ? totalTimeMs / processingTimes.length / 1000 : 0;
console.log(`\n========================================`);
console.log(` Invoice Extraction Summary`);
console.log(` (Nanonets + Qwen3 Pipeline)`);
console.log(` Invoice Summary (Nanonets + Qwen3)`);
console.log(`========================================`);
console.log(` Stage 1: Nanonets-OCR-s (doc -> md)`);
console.log(` Stage 2: Qwen3 8B (md -> JSON)`);
@@ -579,6 +591,14 @@ tap.test('summary', async () => {
console.log(` Total time: ${(totalTimeMs / 1000).toFixed(1)}s`);
console.log(` Avg per inv: ${avgTimeSec.toFixed(1)}s`);
console.log(`========================================\n`);
// Cleanup temp files
try {
fs.rmSync(TEMP_MD_DIR, { recursive: true, force: true });
console.log(` Cleaned up temp directory: ${TEMP_MD_DIR}\n`);
} catch {
// Ignore
}
});
export default tap.start();