diff --git a/package.json b/package.json index 00f9bb2..2866154 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,7 @@ "p-retry": "~4.6.0", "tinyspawn": "~1.5.7", "top-sites": "~1.1.224", - "unpdf": "~1.9.0" + "unpdf": "~2.1.0" }, "devDependencies": { "@browserless/test": "latest", @@ -99,7 +99,7 @@ "typescript": "latest" }, "engines": { - "node": ">= 22" + "node": ">= 24" }, "files": [ "bin", diff --git a/src/pdf/media.js b/src/pdf/media.js index 59bfa36..d402045 100644 --- a/src/pdf/media.js +++ b/src/pdf/media.js @@ -5,6 +5,11 @@ const { deflateSync } = require('node:zlib') const MIN_SIDE = 16 const MAX_PIXELS = 400 * 400 const MAX_LOGO_SIDE = 256 +const RGBA_CHANNELS = 4 +const PNG_COLOR_TYPE_RGBA = 6 +const PNG_BIT_DEPTH = 8 +const OPAQUE = 255 +const TRANSPARENT = 0 const crcTable = new Uint32Array(256) for (let n = 0; n < 256; n++) { @@ -30,10 +35,10 @@ const chunk = (type, data) => { return Buffer.concat([length, body, crc]) } -/** Encode raw RGB/RGBA from unpdf into a PNG data URI. node:zlib only. */ -const toPngDataUri = ({ width, height, channels, data }) => { +/** Encode the raw RGBA pixels unpdf extracts into a PNG data URI. node:zlib only. */ +const toPngDataUri = ({ width, height, data }) => { const source = Buffer.from(data.buffer, data.byteOffset, data.byteLength) - const stride = width * channels + const stride = width * RGBA_CHANNELS const raw = Buffer.alloc((stride + 1) * height) for (let y = 0; y < height; y++) { source.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride) @@ -41,8 +46,8 @@ const toPngDataUri = ({ width, height, channels, data }) => { const ihdr = Buffer.alloc(13) ihdr.writeUInt32BE(width, 0) ihdr.writeUInt32BE(height, 4) - ihdr[8] = 8 - ihdr[9] = channels === 4 ? 6 : 2 + ihdr[8] = PNG_BIT_DEPTH + ihdr[9] = PNG_COLOR_TYPE_RGBA const png = Buffer.concat([ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), @@ -52,6 +57,16 @@ const toPngDataUri = ({ width, height, channels, data }) => { return `data:image/png;base64,${png.toString('base64')}` } +/** An image mask has no color of its own: unpdf paints it opaque black on transparent. */ +const isStencil = ({ data }) => { + for (let offset = 0; offset < data.length; offset += RGBA_CHANNELS) { + if (data[offset] || data[offset + 1] || data[offset + 2]) return false + const alpha = data[offset + 3] + if (alpha !== OPAQUE && alpha !== TRANSPARENT) return false + } + return true +} + const usable = images => images.filter( img => @@ -60,7 +75,7 @@ const usable = images => img.width >= MIN_SIDE && img.height >= MIN_SIDE && img.width * img.height <= MAX_PIXELS && - (img.channels === 3 || img.channels === 4) + !isStencil(img) ) const isLogo = img => diff --git a/test/pdf/helpers.js b/test/pdf/helpers.js index dec1d45..b34634e 100644 --- a/test/pdf/helpers.js +++ b/test/pdf/helpers.js @@ -4,6 +4,8 @@ const PAGE_WIDTH = 612 const PAGE_HEIGHT = 792 const TOP_MARGIN = 72 const LEFT_MARGIN = 72 +const FIRST_IMAGE_OBJECT = 7 +const MASK_ROW_PATTERN = ['00', 'ff'] const escapeText = text => text.replace(/([\\()])/g, '\\$1') @@ -21,12 +23,46 @@ const toStream = lines => { return operations.join('\n') } +const toHex = byte => byte.toString(16).padStart(2, '0') + +const imageSamples = ({ width, height, color, mask }) => { + if (mask) { + const rowBytes = Math.ceil(width / 8) + return Array.from({ length: height }, (_, row) => + MASK_ROW_PATTERN[row % MASK_ROW_PATTERN.length].repeat(rowBytes) + ).join('') + } + return color + .map(toHex) + .join('') + .repeat(width * height) +} + +const imageObject = image => { + const samples = `${imageSamples(image)}>` + const format = image.mask + ? '/ImageMask true /BitsPerComponent 1' + : '/ColorSpace /DeviceRGB /BitsPerComponent 8' + return `<< /Type /XObject /Subtype /Image /Width ${image.width} /Height ${image.height} ${format} /Filter /ASCIIHexDecode /Length ${samples.length} >>\nstream\n${samples}\nendstream` +} + +const paintImages = images => + images.map( + ({ width, height }, index) => + `q ${width} 0 0 ${height} ${LEFT_MARGIN} ${TOP_MARGIN} cm /Im${index} Do Q` + ) + /** - * Builds a one page PDF out of `{ text, size }` lines, so tests exercise the - * real parser without committing binaries to the repository. + * Builds a one page PDF out of `{ text, size }` lines, plus optional + * `{ width, height, color: [r, g, b] }` images or `{ width, height, mask: true }` + * image masks, so tests exercise the real parser without committing binaries + * to the repository. */ -const createPdf = (lines, { info = {} } = {}) => { - const stream = toStream(lines) +const createPdf = (lines, { info = {}, images = [] } = {}) => { + const stream = [toStream(lines), ...paintImages(images)].join('\n') + const xobjects = images + .map((_, index) => `/Im${index} ${FIRST_IMAGE_OBJECT + index} 0 R`) + .join(' ') const infoEntries = Object.entries(info) .map(([key, value]) => `/${key} (${escapeText(String(value))})`) .join(' ') @@ -34,10 +70,11 @@ const createPdf = (lines, { info = {} } = {}) => { const objects = [ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', - `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PAGE_WIDTH} ${PAGE_HEIGHT}] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>`, + `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PAGE_WIDTH} ${PAGE_HEIGHT}] /Resources << /Font << /F1 5 0 R >> /XObject << ${xobjects} >> >> /Contents 4 0 R >>`, `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`, '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', - `<< ${infoEntries} >>` + `<< ${infoEntries} >>`, + ...images.map(imageObject) ] let pdf = '%PDF-1.4\n' diff --git a/test/pdf/index.js b/test/pdf/index.js index 44beacd..ca111ee 100644 --- a/test/pdf/index.js +++ b/test/pdf/index.js @@ -1,6 +1,8 @@ 'use strict' -const { extractPdfSafe, isPdf, isPdfLink, pdfToHtml } = require('../..') +const { inflateSync } = require('node:zlib') + +const { extractPdf, extractPdfSafe, isPdf, isPdfLink, pdfToHtml } = require('../..') const { runServer, test } = require('../helpers') const { createPdf } = require('./helpers') const { scrapePdf } = require('./scrape') @@ -54,6 +56,61 @@ const JOURNAL = createPdf([ } ]) +const JOURNAL_URL = 'https://journals.plos.org/plosone/article/file?id=10.1371/x&type=printable' +const FIGURE_SIDE = 32 +const FIGURE_COLOR = [200, 30, 60] +const PNG_COLOR_TYPE_RGBA = 6 + +const decodePng = dataUri => { + const png = Buffer.from(dataUri.replace('data:image/png;base64,', ''), 'base64') + const idatLength = png.readUInt32BE(33) + return { + width: png.readUInt32BE(16), + height: png.readUInt32BE(20), + colorType: png[25], + scanlines: inflateSync(png.subarray(41, 41 + idatLength)) + } +} + +const PNG_FILTER_NONE = 0 +const OPAQUE = 255 + +const solidScanlines = (side, color) => { + const row = [PNG_FILTER_NONE] + for (let column = 0; column < side; column++) row.push(...color, OPAQUE) + return Buffer.from(Array.from({ length: side }, () => row).flat()) +} + +const paperWith = image => + createPdf([{ text: 'Figures of a paper', size: 14 }], { + images: [{ width: FIGURE_SIDE, height: FIGURE_SIDE, ...image }] + }) + +test('a picture painted on the first page is the image and the logo, as RGBA', async t => { + const { image, logo } = await extractPdf({ + url: JOURNAL_URL, + pdf: paperWith({ color: FIGURE_COLOR }) + }) + + t.is(logo, image) + t.deepEqual(decodePng(image), { + width: FIGURE_SIDE, + height: FIGURE_SIDE, + colorType: PNG_COLOR_TYPE_RGBA, + scanlines: solidScanlines(FIGURE_SIDE, FIGURE_COLOR) + }) +}) + +test('an image mask is neither the image nor the logo', async t => { + const { image, logo } = await extractPdf({ url: JOURNAL_URL, pdf: paperWith({ mask: true }) }) + + t.is(image, null) + t.is( + logo, + `https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(JOURNAL_URL)}&sz=128` + ) +}) + test('isPdfLink only accepts a PDF url', t => { t.true(isPdfLink('https://arxiv.org/pdf/1706.03762v7')) t.true(isPdfLink('https://example.com/paper.pdf')) diff --git a/test/pdf/snapshots/fixtures.js.md b/test/pdf/snapshots/fixtures.js.md index b758aa5..d964b08 100644 --- a/test/pdf/snapshots/fixtures.js.md +++ b/test/pdf/snapshots/fixtures.js.md @@ -108,9 +108,9 @@ Generated by [AVA](https://avajs.dev). author: 'Giovanni Colavizza', date: '2020-04-21T03:37:32.000Z', description: 'Efforts to make research results open and reproducible are increasingly reflected by journal policies encouraging or mandating authors to provide data availability statements. As a consequence of this, there has been a strong uptake of data availability statements in recent literature.', - image: 'data:image/png;base64…1810', + image: 'data:image/png;base64…1914', lang: 'en', - logo: 'data:image/png;base64…1810', + logo: 'data:image/png;base64…1914', publisher: 'PLOS ONE', title: 'The citation advantage of linking publications to research data', url: 'https://journals.plos.org/plosone/article/file?id=10.1371/journal.pone.0230416&type=printable', @@ -220,9 +220,9 @@ Generated by [AVA](https://avajs.dev). author: 'Qiang Zhang', date: '2020-04-24T03:36:38.000Z', description: 'Background: Influenza is a severe respiratory illness that continually threatens global health. It has been widely known that gut microbiota modulates the host response to protect against influenza infection, but mechanistic details remain largely unknown.', - image: 'data:image/png;base64…15142', + image: 'data:image/png;base64…14822', lang: 'en', - logo: 'data:image/png;base64…342', + logo: 'data:image/png;base64…358', publisher: 'Springer', title: 'Influenza infection elicits an expansion of gut population of endogenous Bifidobacterium animalis which protects mice against infection', url: 'https://link.springer.com/content/pdf/10.1186/s13059-020-02007-1.pdf', @@ -300,9 +300,9 @@ Generated by [AVA](https://avajs.dev). author: 'Zayra Elisa Carvajal-Portuguez', date: '2013-01-01T00:00:00.000Z', description: 'Enseñanza del inglés en secundaria: una propuesta innovadora. Educación Carvajal-Portuguez, Zayra Elisa vol. 37, núm. 2, julio-diciembre, 2013, pp. 79-101 Universidad de Costa Rica San Pedro, Montes de Oca, Costa Rica', - image: 'data:image/png;base64…2574', + image: 'data:image/png;base64…2658', lang: 'es', - logo: 'data:image/png;base64…15010', + logo: 'data:image/png;base64…15278', publisher: 'Redalyc', title: 'Enseñanza del inglés en secundaria: una propuesta innovadora', url: 'https://www.redalyc.org/pdf/440/44029444004.pdf', @@ -364,9 +364,9 @@ Generated by [AVA](https://avajs.dev). author: 'Nathalie Percie du Sert', date: '2020-07-11T04:57:33.000Z', description: 'Reproducible science requires transparent reporting. The ARRIVE guidelines (Animal Research: Reporting of In Vivo Experiments) were originally developed in 2010 to improve the reporting of animal research.', - image: 'data:image/png;base64…1810', + image: 'data:image/png;base64…1914', lang: 'en', - logo: 'data:image/png;base64…1810', + logo: 'data:image/png;base64…1914', publisher: 'PLOS BIOLOGY', title: 'The ARRIVE guidelines 2.0: Updated guidelines for reporting animal research', url: 'https://journals.plos.org/plosbiology/article/file?id=10.1371/journal.pbio.3000410&type=printable', @@ -476,9 +476,9 @@ Generated by [AVA](https://avajs.dev). author: 'Nandan Thakur', date: '2021-04-01T00:00:00.000Z', description: 'Existing neural information retrieval (IR) models have often been studied in homogeneous and narrow settings, which has considerably limited insights into their out-of-distribution (OOD) generalization capabilities.', - image: 'data:image/png;base64…11398', + image: 'data:image/png;base64…11782', lang: 'en', - logo: 'data:image/png;base64…11398', + logo: 'data:image/png;base64…11782', publisher: 'arXiv', title: 'BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models', url: 'https://arxiv.org/pdf/2104.08663v4', @@ -636,9 +636,9 @@ Generated by [AVA](https://avajs.dev). author: 'Matthew J. Page', date: '2021-03-24T09:31:13.000Z', description: 'points complete, and accurate account of why the review was done, what they did, and what they found PLOS MEDICINE (UG1EY020522), National Institutes of Health, United States. LAM is supported by a National Institute for Health Research Doctoral Research Fellowship (DRF-2018-11-ST2-048).', - image: 'data:image/png;base64…1810', + image: 'data:image/png;base64…1914', lang: 'en', - logo: 'data:image/png;base64…1810', + logo: 'data:image/png;base64…1914', publisher: 'PLOS Medicine', title: 'The PRISMA 2020 statement: An updated guideline for reporting systematic reviews', url: 'https://journals.plos.org/plosmedicine/article/file?id=10.1371/journal.pmed.1003583&type=printable', @@ -652,9 +652,9 @@ Generated by [AVA](https://avajs.dev). author: 'Greg Wilson', date: '2017-06-21T09:08:26.000Z', description: 'Computers are now essential in all branches of science, but most researchers are never taught the equivalent of basic lab skills for research computing.', - image: 'data:image/png;base64…1070', + image: 'data:image/png;base64…1150', lang: 'en', - logo: 'data:image/png;base64…1070', + logo: 'data:image/png;base64…1150', publisher: 'PLOS Computational Biology', title: 'Good enough practices in scientific computing', url: 'https://journals.plos.org/ploscompbiol/article/file?id=10.1371/journal.pcbi.1005510&type=printable', @@ -684,7 +684,7 @@ Generated by [AVA](https://avajs.dev). author: 'Yu Xie', date: '2020-01-21T06:02:46.000Z', description: 'Networks, such as social networks, biochemical networks, and protein-protein interaction networks are ubiquitous in the real world.', - image: 'data:image/png;base64…1610', + image: 'data:image/png;base64…1978', lang: 'en', logo: 'https://www.google.com/s2/favicons?domain_url=https%3A%2F%2Fwww.frontiersin.org%2Farticles%2F10.3389%2Ffnins.2020.00001%2Fpdf&sz=128', publisher: 'Frontiers in Neuroscience', @@ -732,9 +732,9 @@ Generated by [AVA](https://avajs.dev). author: 'Helen Le Sueur', date: '2020-06-23T14:17:55.000Z', description: 'Background: Individual clinical trials and cohort studies are a useful source of data, often under-utilised once a study has ended.', - image: 'data:image/png;base64…22214', + image: 'data:image/png;base64…21578', lang: 'en', - logo: 'data:image/png;base64…302', + logo: 'data:image/png;base64…322', publisher: 'Springer', title: 'The challenges in data integration – heterogeneity and complexity in clinical trials and patient registries of Systemic Lupus Erythematosus', url: 'https://link.springer.com/content/pdf/10.1186/s12874-020-01057-0.pdf', @@ -748,9 +748,9 @@ Generated by [AVA](https://avajs.dev). author: 'Josef Zelinka', date: '2022-09-08T19:32:41.000Z', description: 'For autonomous robots operating in an unknown environment, it is important to assess the traversability of the surrounding terrain to improve path planning and decision-making on where to navigate next in a cost-efficient way.', - image: 'data:image/png;base64…1658', + image: 'data:image/png;base64…1934', lang: 'en', - logo: 'data:image/png;base64…26950', + logo: 'data:image/png;base64…27178', publisher: 'CEUR-WS', title: 'Deep Transfer Learning of Traversability Assessment for Heterogeneous Robots', url: 'https://ceur-ws.org/Vol-3226/paper1.pdf', @@ -764,9 +764,9 @@ Generated by [AVA](https://avajs.dev). author: 'Begoña Martínez Domínguez', date: '2009-01-01T00:00:00.000Z', description: 'UNA OPORTUNIDAD PARA QUE JÓVENES QUE FRACASAN EN LA ESCUELA PUEDAN SALIR DE LA ZONA DE RIESGO DE EXCLUSIÓN. LA EXPERIENCIA DE LOS CENTROS DE INICIACIÓN PROFESIONAL EN LA COMUNIDAD AUTÓNOMA VASCA. Profesorado. Revista de Currículum y Formación de Profesorado Martínez Domínguez, Begoña; Mendizábal Ituarte, Amaia; Sostoa Gaztelu-Urrutia, Virginia P. vol. 13, núm. 3, 2009, pp. 239-271 Universidad de Granada Granada, España', - image: 'data:image/png;base64…2574', + image: 'data:image/png;base64…2658', lang: 'es', - logo: 'data:image/png;base64…21742', + logo: 'data:image/png;base64…22014', publisher: 'Redalyc', title: 'UNA OPORTUNIDAD PARA QUE JÓVENES QUE FRACASAN EN LA ESCUELA PUEDAN SALIR DE LA ZONA DE RIESGO DE EXCLUSIÓN. LA EXPERIENCIA DE LOS CENTROS DE INICIACIÓN PROFESIONAL EN LA COMUNIDAD AUTÓNOMA VASCA', url: 'https://www.redalyc.org/pdf/567/56712871011.pdf', @@ -780,9 +780,9 @@ Generated by [AVA](https://avajs.dev). author: 'Lucile Mégret', date: '2020-02-24T02:45:03.000Z', description: 'Background: MicroRNA (miRNA) regulation is associated with several diseases, including neurodegenerative diseases. Several approaches can be used for modeling miRNA regulation. However, their precision may be limited for analyzing multidimensional data.', - image: 'data:image/png;base64…34334', + image: 'data:image/png;base64…33190', lang: 'en', - logo: 'data:image/png;base64…302', + logo: 'data:image/png;base64…322', publisher: 'BMC', title: 'Combining feature selection and shape analysis uncovers precise rules for miRNA regulation in Huntington’s disease mice', url: 'https://bmcbioinformatics.biomedcentral.com/counter/pdf/10.1186/s12859-020-3418-9.pdf', diff --git a/test/pdf/snapshots/fixtures.js.snap b/test/pdf/snapshots/fixtures.js.snap index aa2acfe..e001cf8 100644 Binary files a/test/pdf/snapshots/fixtures.js.snap and b/test/pdf/snapshots/fixtures.js.snap differ diff --git a/test/pdf/unit.js b/test/pdf/unit.js index ca3b671..36a7ed1 100644 --- a/test/pdf/unit.js +++ b/test/pdf/unit.js @@ -182,13 +182,22 @@ test('lang comes from the host or the words on the page', t => { ) }) +const rgbaImage = (side, pixelAt) => { + const data = Buffer.alloc(side * side * 4) + for (let index = 0; index < side * side; index++) data.set(pixelAt(index), index * 4) + return { width: side, height: side, data } +} + +const OPAQUE_BLACK = [0, 0, 0, 255] +const TRANSPARENT = [0, 0, 0, 0] +const SIDE = 16 +const URL = 'https://journals.plos.org/article.pdf' +const FAVICON = `https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(URL)}&sz=128` + test('a small square image is the logo; otherwise the host favicon', t => { - const pixels = Buffer.alloc(16 * 16 * 3, 80) - const { image, logo } = getMedia([{ width: 16, height: 16, channels: 3, data: pixels }], { - url: 'https://journals.plos.org/article.pdf' - }) + const { image, logo } = getMedia([rgbaImage(SIDE, () => [80, 80, 80, 255])], { url: URL }) t.true(image.startsWith('data:image/png;base64,')) - t.true(logo.startsWith('data:image/png;base64,')) + t.is(logo, image) const fallback = getMedia([], { url: 'https://arxiv.org/pdf/x' }) t.is(fallback.image, null) @@ -199,3 +208,27 @@ test('a small square image is the logo; otherwise the host favicon', t => { )}&sz=128` ) }) + +test('an image mask, opaque black on transparent, is not an image', t => { + const stencil = rgbaImage(SIDE, index => (index % 2 ? OPAQUE_BLACK : TRANSPARENT)) + t.deepEqual(getMedia([stencil], { url: URL }), { image: null, logo: FAVICON }) + + const painted = rgbaImage(SIDE, () => OPAQUE_BLACK) + t.deepEqual(getMedia([painted], { url: URL }), { image: null, logo: FAVICON }) +}) + +test('a black image that is not a stencil is an image', t => { + const siblings = { + 'black and white': index => (index % 2 ? OPAQUE_BLACK : [255, 255, 255, 255]), + 'antialiased black': index => (index % 2 ? OPAQUE_BLACK : [0, 0, 0, 128]), + 'red channel': index => (index % 2 ? OPAQUE_BLACK : [1, 0, 0, 255]), + 'green channel': index => (index % 2 ? OPAQUE_BLACK : [0, 1, 0, 255]), + 'blue channel': index => (index % 2 ? OPAQUE_BLACK : [0, 0, 1, 255]) + } + + for (const [name, pixelAt] of Object.entries(siblings)) { + const { image, logo } = getMedia([rgbaImage(SIDE, pixelAt)], { url: URL }) + t.true(image.startsWith('data:image/png;base64,'), name) + t.is(logo, image, name) + } +})