2021-03-13 08:46:22 +01:00
|
|
|
import { toMatchFile } from 'jest-file-snapshot';
|
|
|
|
|
|
|
|
import * as pdfjs from 'pdfjs-dist/es5/build/pdf';
|
|
|
|
import * as fs from 'fs';
|
2021-03-22 09:03:26 +01:00
|
|
|
import * as path from 'path';
|
|
|
|
import * as http from 'http';
|
|
|
|
import * as https from 'https';
|
2021-03-13 08:46:22 +01:00
|
|
|
|
|
|
|
import PdfParser from 'src/PdfParser';
|
|
|
|
import PdfPipeline from 'src/PdfPipeline';
|
|
|
|
import { transformers } from 'src/index';
|
|
|
|
import Debugger from 'src/Debugger';
|
2024-03-25 23:36:58 +01:00
|
|
|
import Globals from 'src/Globals';
|
2021-03-13 08:46:22 +01:00
|
|
|
import Item from 'src/Item';
|
2024-03-25 23:36:58 +01:00
|
|
|
import { Change } from 'src/debug/ChangeIndex';
|
2021-03-22 09:03:26 +01:00
|
|
|
import StageResult from 'src/debug/StageResult';
|
2021-04-01 18:16:42 +02:00
|
|
|
import EvaluationIndex from 'src/debug/EvaluationIndex';
|
2024-03-25 23:36:58 +01:00
|
|
|
import RemoveRepetitiveItems from 'src/transformer/RemoveRepetitiveItems';
|
2021-04-25 08:13:13 +02:00
|
|
|
import DetectToc, { TOC_GLOBAL } from 'src/transformer/DetectToc';
|
2024-03-25 23:36:58 +01:00
|
|
|
import DetectHeaders from 'src/transformer/DetectHeaders';
|
2024-03-19 23:50:58 +01:00
|
|
|
import TOC from 'src/TOC';
|
|
|
|
import { getText } from 'src/support/items';
|
|
|
|
|
2021-07-18 22:13:38 +02:00
|
|
|
pdfjs.GlobalWorkerOptions.workerSrc = `pdfjs-dist/es5/build/pdf.worker.min.js`;
|
2021-03-13 08:46:22 +01:00
|
|
|
|
|
|
|
const parser = new PdfParser(pdfjs);
|
|
|
|
const pipeline = new PdfPipeline(parser, transformers);
|
|
|
|
|
2024-03-26 17:50:33 +01:00
|
|
|
const folder = './examples';
|
2021-03-13 08:46:22 +01:00
|
|
|
const files = fs.readdirSync(folder).filter((file) => file.endsWith('.pdf'));
|
2021-03-28 10:21:26 +02:00
|
|
|
const urls = [
|
|
|
|
'https://homepages.cwi.nl/~lex/files/dict.pdf',
|
|
|
|
'https://github.com/mozilla/pdf.js/raw/master/web/compressed.tracemonkey-pldi-09.pdf',
|
|
|
|
];
|
2021-03-22 09:03:26 +01:00
|
|
|
const downloadCache = 'node_modules/.cache/files';
|
2021-03-13 08:46:22 +01:00
|
|
|
|
|
|
|
expect.extend({ toMatchFile });
|
|
|
|
|
2021-03-22 09:03:26 +01:00
|
|
|
// Test is for debugging purpose
|
2024-03-25 23:36:58 +01:00
|
|
|
test('Debug', async () => {
|
|
|
|
// const data = fs.readFileSync(`${folder}/Adventures-Of-Sherlock-Holmes.pdf`);
|
|
|
|
const data = fs.readFileSync(`${folder}/ExamplePdf.pdf`);
|
|
|
|
await pipeline.parse(data, () => {});
|
2021-03-22 09:03:26 +01:00
|
|
|
});
|
|
|
|
|
2021-03-13 08:46:22 +01:00
|
|
|
describe.each(files)('Test %p', (file) => {
|
|
|
|
const data = fs.readFileSync(`${folder}/${file}`);
|
|
|
|
|
|
|
|
let debug: Debugger;
|
2024-03-20 16:07:48 +01:00
|
|
|
const printedGlobals = new Set<string>();
|
2024-03-25 23:36:58 +01:00
|
|
|
beforeAll(async () => (debug = await pipeline.parse(data, () => {}).then((pc) => pc.debug())));
|
2021-03-13 08:46:22 +01:00
|
|
|
|
2021-03-14 12:15:37 +01:00
|
|
|
test.each(transformers.map((t) => t.name).filter((name) => name !== 'Does nothing'))(
|
|
|
|
'stage %p',
|
|
|
|
(transformerName) => {
|
2021-03-22 09:03:26 +01:00
|
|
|
const stageResult = debug.stageResult(debug.stageNames.indexOf(transformerName));
|
2021-03-14 12:15:37 +01:00
|
|
|
const chunkedLines: string[][] = [[]];
|
|
|
|
let resultIndex = 0;
|
|
|
|
let collectedItems = 0;
|
2021-03-22 09:03:26 +01:00
|
|
|
stageResult.selectPages(true, true).forEach((page) => {
|
2021-03-14 12:15:37 +01:00
|
|
|
page.itemGroups.forEach((itemGroup) => {
|
2021-04-01 18:16:42 +02:00
|
|
|
const item = itemGroup.top;
|
|
|
|
const change = stageResult.changes.change(item);
|
2021-03-22 09:03:26 +01:00
|
|
|
if (change || stageResult.descriptor.debug?.showAll) {
|
2021-04-01 18:16:42 +02:00
|
|
|
chunkedLines[resultIndex].push(itemToString(debug.fontMap, item, change, stageResult.evaluations));
|
2021-03-14 12:15:37 +01:00
|
|
|
collectedItems++;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// we split results to multiple files to circumvent githubs 100MB limit
|
|
|
|
resultIndex = Math.floor(collectedItems / 450_000);
|
|
|
|
if (resultIndex === chunkedLines.length) {
|
|
|
|
chunkedLines.push([]);
|
2021-03-13 08:46:22 +01:00
|
|
|
}
|
|
|
|
});
|
2021-03-13 22:46:10 +01:00
|
|
|
|
2021-03-14 12:15:37 +01:00
|
|
|
// Global characteristics
|
2021-07-18 22:13:38 +02:00
|
|
|
chunkedLines[0].unshift(toHeader(stageResult, printedGlobals));
|
2021-03-14 12:15:37 +01:00
|
|
|
chunkedLines.forEach((lines, idx) => {
|
|
|
|
const transformerResultAsString = lines.join('\n') || '{}';
|
2021-03-22 09:03:26 +01:00
|
|
|
expect(transformerResultAsString).toMatchFile(matchFilePath(file, transformerName, chunkedLines.length, idx));
|
2021-03-14 12:15:37 +01:00
|
|
|
});
|
2021-07-18 22:13:38 +02:00
|
|
|
stageResult.globals.keys().forEach((globalKey) => {
|
|
|
|
printedGlobals.add(globalKey);
|
|
|
|
});
|
2021-03-14 12:15:37 +01:00
|
|
|
},
|
|
|
|
);
|
2021-03-13 08:46:22 +01:00
|
|
|
});
|
2021-03-13 19:38:47 +01:00
|
|
|
|
2021-03-22 09:03:26 +01:00
|
|
|
function matchFilePath(pdfFileName: string, transformerName: string, chunkCount = 1, chunkIndex = 0): string {
|
|
|
|
const pdfFileNameWithoutExtension = pdfFileName.substr(0, pdfFileName.length - 4);
|
|
|
|
const resultFileName = `${transformerName[0].toLowerCase() + transformerName.slice(1).replace(/\s/g, '')}`;
|
|
|
|
const fileIndex = chunkCount > 1 ? `.${chunkIndex}` : '';
|
|
|
|
return `${folder}/${pdfFileNameWithoutExtension}/${resultFileName}${fileIndex}.json`;
|
|
|
|
}
|
|
|
|
|
2021-04-18 09:41:37 +02:00
|
|
|
describe('Selective transforms on URL PDFs', () => {
|
2024-03-25 23:36:58 +01:00
|
|
|
const transformerNames = [new RemoveRepetitiveItems().name, new DetectToc().name, new DetectHeaders().name];
|
2021-03-22 09:03:26 +01:00
|
|
|
test.each(urls)('URL %p', async (url) => {
|
|
|
|
const { fileName, data } = download(url);
|
2024-03-25 23:36:58 +01:00
|
|
|
const debug = await pipeline.parse(data, () => {}).then((pc) => pc.debug());
|
2024-03-20 16:07:48 +01:00
|
|
|
const printedGlobals = new Set<string>();
|
2021-03-22 09:03:26 +01:00
|
|
|
|
2021-04-18 09:41:37 +02:00
|
|
|
transformerNames.forEach((transformerName) => {
|
|
|
|
const stageResult = debug.stageResult(debug.stageNames.indexOf(transformerName));
|
|
|
|
const pages = stageResult.selectPages(true, true);
|
|
|
|
|
|
|
|
const lines: string[] = [];
|
2021-07-18 22:13:38 +02:00
|
|
|
lines.push(toHeader(stageResult, printedGlobals));
|
2021-04-18 09:41:37 +02:00
|
|
|
|
|
|
|
pages.forEach((page) =>
|
|
|
|
page.itemGroups.forEach((itemGroup) => {
|
|
|
|
const item = itemGroup.top;
|
|
|
|
const change = stageResult.changes.change(item);
|
|
|
|
if (change) {
|
|
|
|
lines.push(itemToString(debug.fontMap, item, change, stageResult.evaluations));
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
|
|
|
const transformerResultAsString = lines.join('\n') || '{}';
|
|
|
|
expect(transformerResultAsString).toMatchFile(matchFilePath(fileName, transformerName));
|
2021-07-18 22:13:38 +02:00
|
|
|
|
|
|
|
stageResult.globals.keys().forEach((globalKey) => {
|
|
|
|
printedGlobals.add(globalKey);
|
|
|
|
});
|
2021-04-18 09:41:37 +02:00
|
|
|
});
|
2021-03-22 09:03:26 +01:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2021-07-18 22:13:38 +02:00
|
|
|
function toHeader(stageResult: StageResult, alreadyPrintedGlobals: Set<string>): string {
|
2024-03-20 16:07:48 +01:00
|
|
|
const groupedItemCount = stageResult
|
2021-03-22 09:03:26 +01:00
|
|
|
.selectPages(false, true)
|
|
|
|
.reduce((itemCount, page) => itemCount + page.itemGroups.length, 0);
|
2021-03-28 10:58:24 +02:00
|
|
|
|
2021-03-22 09:03:26 +01:00
|
|
|
return JSON.stringify(
|
|
|
|
{
|
|
|
|
pages: stageResult.pages.length,
|
|
|
|
items: stageResult.itemsUnpacked().length,
|
|
|
|
groupedItems: groupedItemCount,
|
|
|
|
changes: stageResult.changes.changeCount(),
|
|
|
|
schema: stageResult.schema,
|
2021-07-18 22:13:38 +02:00
|
|
|
globals: globalsToString(stageResult.globals, alreadyPrintedGlobals),
|
2021-03-22 09:03:26 +01:00
|
|
|
// messages: stageResults.messages,
|
|
|
|
},
|
|
|
|
null,
|
|
|
|
2,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-07-18 22:13:38 +02:00
|
|
|
function globalsToString(globals: Globals, alreadyPrintedGlobals: Set<string>): object {
|
|
|
|
return Array.from(globals.map)
|
2024-03-20 16:07:48 +01:00
|
|
|
.filter(([key]) => !alreadyPrintedGlobals.has(key))
|
2021-07-18 22:13:38 +02:00
|
|
|
.reduce((obj, [key, value]) => {
|
|
|
|
if (key === TOC_GLOBAL.key) {
|
2024-03-20 16:07:48 +01:00
|
|
|
const toc: TOC = value as TOC;
|
2021-07-18 22:13:38 +02:00
|
|
|
value = {
|
2021-07-19 18:15:59 +02:00
|
|
|
...toc,
|
|
|
|
tocHeadlineItems: toc.tocHeadlineItems.map((item) => ({
|
|
|
|
page: item.page,
|
|
|
|
text: getText(item),
|
|
|
|
})),
|
2021-07-18 22:13:38 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
obj[key] = value;
|
|
|
|
return obj;
|
|
|
|
}, {});
|
2021-03-28 10:58:24 +02:00
|
|
|
}
|
|
|
|
|
2021-04-01 18:16:42 +02:00
|
|
|
function itemToString(
|
|
|
|
fontMap: Map<string, object>,
|
|
|
|
item: Item,
|
|
|
|
change: Change | undefined,
|
|
|
|
evaluationIndex: EvaluationIndex,
|
|
|
|
): string {
|
2021-03-13 19:38:47 +01:00
|
|
|
const fontName: string | Array<string> = item.data['fontName'];
|
|
|
|
let newFontName: string | Array<string> | undefined = undefined;
|
|
|
|
if (fontName) {
|
|
|
|
if (typeof fontName === 'string') {
|
2024-03-19 23:50:58 +01:00
|
|
|
newFontName = fontMap.get(fontName)?.['name'];
|
2021-03-13 19:38:47 +01:00
|
|
|
} else {
|
|
|
|
newFontName = fontName.map((name) => fontMap.get(name)?.['name']);
|
|
|
|
}
|
|
|
|
}
|
2021-04-01 18:16:42 +02:00
|
|
|
const changeType = change?.constructor.name || 'none';
|
2021-03-13 22:46:10 +01:00
|
|
|
const transform: undefined | number[] = item.data['transform'];
|
2021-03-22 09:03:26 +01:00
|
|
|
let newTransform: undefined | string[];
|
2021-03-13 22:46:10 +01:00
|
|
|
if (transform) {
|
|
|
|
newTransform = transform.map((num) => num.toFixed(2));
|
|
|
|
}
|
2021-04-01 18:16:42 +02:00
|
|
|
|
|
|
|
const object = {
|
2021-03-13 19:38:47 +01:00
|
|
|
page: item.page,
|
|
|
|
change: changeType,
|
2021-04-01 18:16:42 +02:00
|
|
|
score: evaluationIndex.evaluationScore(item),
|
2021-07-18 22:25:55 +02:00
|
|
|
types: item.data['types'],
|
2021-03-13 22:46:10 +01:00
|
|
|
...item.data,
|
|
|
|
fontName: newFontName,
|
|
|
|
height: item.data['height'].toFixed(2),
|
|
|
|
width: item.data['width'].toFixed(2),
|
|
|
|
transform: newTransform,
|
2021-04-01 18:16:42 +02:00
|
|
|
};
|
|
|
|
if (!evaluationIndex.hasScores()) {
|
|
|
|
delete object.score;
|
|
|
|
}
|
|
|
|
return JSON.stringify(object);
|
2021-03-13 19:38:47 +01:00
|
|
|
}
|
2021-03-22 09:03:26 +01:00
|
|
|
|
|
|
|
function download(url: string): { fileName: string; data: Buffer } {
|
|
|
|
const fileName = path.basename(new URL(url).pathname);
|
|
|
|
const localFilePath = `${downloadCache}/${fileName}`;
|
|
|
|
if (!fs.existsSync(localFilePath)) {
|
|
|
|
fs.mkdirSync(downloadCache, { recursive: true });
|
|
|
|
downloadToFile(url, localFilePath);
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
fileName,
|
|
|
|
data: fs.readFileSync(localFilePath),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function downloadToFile(url: string, dest: string): Promise<void> {
|
|
|
|
const uri = new URL(url);
|
|
|
|
const pkg = url.toLowerCase().startsWith('https:') ? https : http;
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
pkg.get(uri.href).on('response', (res) => {
|
|
|
|
if (res.statusCode === 200) {
|
|
|
|
const file = fs.createWriteStream(dest, { flags: 'wx' });
|
|
|
|
res
|
|
|
|
.on('end', () => {
|
|
|
|
file.end();
|
|
|
|
resolve();
|
|
|
|
})
|
|
|
|
.on('error', (err) => {
|
|
|
|
file.destroy();
|
|
|
|
fs.unlink(dest, () => reject(err));
|
|
|
|
})
|
|
|
|
.pipe(file);
|
|
|
|
} else if (res.statusCode === 302 || res.statusCode === 301) {
|
|
|
|
// Recursively follow redirects, only a 200 will resolve.
|
2024-03-19 23:50:58 +01:00
|
|
|
if (res.headers.location) {
|
|
|
|
downloadToFile(res.headers.location, dest).then(() => resolve());
|
|
|
|
}
|
2021-03-22 09:03:26 +01:00
|
|
|
} else {
|
|
|
|
reject(new Error(`Download request failed, response status: ${res.statusCode} ${res.statusMessage}`));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|