html-get 2.26.13 → 2.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -97,4 +97,43 @@ export const ABORT_TYPES: string[]
97
97
  */
98
98
  export const PDF_SIZE_TRESHOLD: number
99
99
 
100
+ export interface PdfMeta {
101
+ title?: string | null
102
+ author?: string | null
103
+ authors?: string | null
104
+ description?: string | null
105
+ publisher?: string | null
106
+ date?: string | null
107
+ lang?: string | null
108
+ image?: string | null
109
+ logo?: string | null
110
+ }
111
+
112
+ /** Read title, author, date, and the rest from PDF bytes. */
113
+ export function extractPdf(input: {
114
+ url: string
115
+ pdf: ArrayBuffer | ArrayBufferView
116
+ maxPages?: number
117
+ }): Promise<PdfMeta>
118
+
119
+ /** `extractPdf` that returns undefined on a non-PDF or a parse error. */
120
+ export function extractPdfSafe(
121
+ input: ArrayBuffer | ArrayBufferView,
122
+ url: string,
123
+ opts?: { maxPages?: number }
124
+ ): Promise<PdfMeta | undefined>
125
+
126
+ /** `true` when the bytes start with `%PDF` (junk before the header is allowed). */
127
+ export function isPdf(input: ArrayBuffer | ArrayBufferView): boolean
128
+
129
+ /** `true` when `url` looks like a PDF link. */
130
+ export function isPdfLink(url?: string): boolean
131
+
132
+ /** Empty HTML document with PDF metadata stamped as meta tags. */
133
+ export function pdfToHtml(
134
+ input: ArrayBuffer | ArrayBufferView,
135
+ url: string,
136
+ opts?: { maxPages?: number }
137
+ ): Promise<string>
138
+
100
139
  export default htmlGet
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "html-get",
3
3
  "description": "Get the HTML from any website, fine-tuned for correction & speed",
4
4
  "homepage": "https://nicedoc.com/microlinkhq/html-get",
5
- "version": "2.26.13",
5
+ "version": "2.27.0",
6
6
  "types": "index.d.ts",
7
7
  "main": "src/index.js",
8
8
  "bin": {
@@ -63,7 +63,8 @@
63
63
  "p-cancelable": "~2.1.0",
64
64
  "p-retry": "~4.6.0",
65
65
  "tinyspawn": "~1.5.7",
66
- "top-sites": "~1.1.224"
66
+ "top-sites": "~1.1.224",
67
+ "unpdf": "~1.8.1"
67
68
  },
68
69
  "devDependencies": {
69
70
  "@browserless/test": "latest",
@@ -77,6 +78,17 @@
77
78
  "finepack": "latest",
78
79
  "git-authors-cli": "latest",
79
80
  "github-generate-release": "latest",
81
+ "metascraper": "~5.56.2",
82
+ "metascraper-author": "~5.56.2",
83
+ "metascraper-date": "~5.56.2",
84
+ "metascraper-description": "~5.56.2",
85
+ "metascraper-image": "~5.56.2",
86
+ "metascraper-lang": "~5.56.2",
87
+ "metascraper-logo": "~5.56.2",
88
+ "metascraper-manifest": "~5.56.2",
89
+ "metascraper-publisher": "~5.56.2",
90
+ "metascraper-title": "~5.56.2",
91
+ "metascraper-url": "~5.56.2",
80
92
  "nano-staged": "latest",
81
93
  "pretty": "latest",
82
94
  "puppeteer": "latest",
@@ -110,7 +122,9 @@
110
122
  "ava": {
111
123
  "files": [
112
124
  "test/**/*.js",
113
- "!test/helpers.js"
125
+ "!test/helpers.js",
126
+ "!test/pdf/helpers.js",
127
+ "!test/pdf/scrape.js"
114
128
  ],
115
129
  "timeout": "2m",
116
130
  "workerThreads": false
package/src/html.js CHANGED
@@ -19,19 +19,27 @@ const has = el => el.length !== 0
19
19
 
20
20
  const upsert = (el, collection, item) => !has(el) && collection.push(item)
21
21
 
22
- const addHead = ({ $, url, headers }) => {
22
+ const escapeAttr = value =>
23
+ String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
24
+
25
+ const metaTag = (key, value, attr = 'name') =>
26
+ `<meta ${attr}="${key}" content="${escapeAttr(value)}">`
27
+
28
+ const addHead = ({ $, url, headers, pdfMeta = {} }) => {
23
29
  const tags = []
24
30
  const charset = getCharset(headers)
25
31
  const { domain } = parseUrl(url)
26
32
  const head = $('head')
33
+ const title = pdfMeta.title || path.basename(url)
34
+ const siteName = pdfMeta.publisher || domain
27
35
 
28
- upsert(head.find('title'), tags, `<title>${path.basename(url)}</title>`)
36
+ upsert(head.find('title'), tags, `<title>${escapeAttr(title)}</title>`)
29
37
 
30
- if (domain) {
38
+ if (siteName) {
31
39
  upsert(
32
40
  head.find('meta[property="og:site_name"]'),
33
41
  tags,
34
- `<meta property="og:site_name" content="${domain}">`
42
+ metaTag('og:site_name', siteName, 'property')
35
43
  )
36
44
  }
37
45
 
@@ -41,6 +49,23 @@ const addHead = ({ $, url, headers }) => {
41
49
  upsert(head.find('meta[charset]'), tags, `<meta charset="${charset}">`)
42
50
  }
43
51
 
52
+ if (pdfMeta.title) tags.push(metaTag('og:title', pdfMeta.title, 'property'))
53
+ if (pdfMeta.author) tags.push(metaTag('author', pdfMeta.author))
54
+ if (pdfMeta.description) {
55
+ tags.push(metaTag('description', pdfMeta.description))
56
+ tags.push(metaTag('og:description', pdfMeta.description, 'property'))
57
+ }
58
+ if (pdfMeta.date) {
59
+ tags.push(metaTag('date', pdfMeta.date))
60
+ tags.push(metaTag('article:published_time', pdfMeta.date, 'property'))
61
+ }
62
+ if (pdfMeta.image) tags.push(metaTag('og:image', pdfMeta.image, 'property'))
63
+ if (pdfMeta.logo) tags.push(metaTag('og:logo', pdfMeta.logo, 'property'))
64
+ if (pdfMeta.lang) {
65
+ tags.push(metaTag('og:locale', pdfMeta.lang, 'property'))
66
+ $('html').attr('lang', pdfMeta.lang)
67
+ }
68
+
44
69
  tags.forEach(tag => head.append(tag))
45
70
  }
46
71
 
@@ -157,6 +182,7 @@ module.exports = ({
157
182
  html,
158
183
  url,
159
184
  headers = {},
185
+ pdfMeta,
160
186
  styles,
161
187
  hide,
162
188
  remove,
@@ -173,7 +199,7 @@ module.exports = ({
173
199
 
174
200
  if (rewriteHtml) rewriteMetaTags({ $, url })
175
201
 
176
- addHead({ $, url, headers })
202
+ addHead({ $, url, headers, pdfMeta })
177
203
 
178
204
  if (styles) injectStyle({ $, styles })
179
205
 
package/src/index.js CHANGED
@@ -16,6 +16,7 @@ const os = require('os')
16
16
 
17
17
  const { getContentLength, getContentType } = require('./util')
18
18
  const { getOfficeFormat, isOfficeUrl } = require('./office')
19
+ const { extractSafe } = require('./pdf')
19
20
  const autoDomains = require('./auto-domains')
20
21
  const addHtml = require('./html')
21
22
 
@@ -52,6 +53,7 @@ const fetch = PCancelable.fn(
52
53
  try {
53
54
  const res = await req
54
55
 
56
+ let pdfMeta
55
57
  const html = await (async () => {
56
58
  const contentType = getContentType(res.headers)
57
59
 
@@ -59,7 +61,9 @@ const fetch = PCancelable.fn(
59
61
 
60
62
  // a recognized office file never goes through mutool, even if the
61
63
  // response is mislabeled as application/pdf
62
- if (mutool && !officeFormat && contentType === 'application/pdf') {
64
+ if (!officeFormat && contentType === 'application/pdf') {
65
+ pdfMeta = await extractSafe(res.body, res.url)
66
+ if (!mutool) return ''
63
67
  const file = getTemporalFile(url, 'pdf')
64
68
  await writeFile(file.path, res.body)
65
69
  try {
@@ -106,6 +110,7 @@ const fetch = PCancelable.fn(
106
110
  return {
107
111
  headers: res.headers,
108
112
  html,
113
+ pdfMeta,
109
114
  mode: 'fetch',
110
115
  url: res.url,
111
116
  statusCode: res.statusCode,
@@ -350,14 +355,16 @@ const getContent = PCancelable.fn(
350
355
  onCancel(() => promise.cancel())
351
356
 
352
357
  return promise.then(content => {
358
+ const { pdfMeta, ...rest } = content
353
359
  const $ = addHtml({
354
- ...content,
360
+ ...rest,
361
+ pdfMeta,
355
362
  ...(isFetchMode ? puppeteerOpts : undefined),
356
363
  rewriteUrls,
357
364
  rewriteHtml
358
365
  })
359
366
 
360
- return { ...content, $ }
367
+ return { ...rest, $ }
361
368
  })
362
369
  }
363
370
  )
@@ -461,3 +468,16 @@ module.exports.defaultPandoc = defaultPandoc
461
468
  // the binary is not installed. Lazy: nothing runs until first call.
462
469
  module.exports.getPandocPath = () => whichSync('pandoc')
463
470
  module.exports.getMutoolPath = () => whichSync('mutool')
471
+ module.exports.extractPdf = require('./pdf').extract
472
+ module.exports.extractPdfSafe = extractSafe
473
+ module.exports.isPdf = require('./pdf').isPdf
474
+ module.exports.isPdfLink = require('./pdf').isPdfLink
475
+ module.exports.pdfToHtml = async (input, url, opts) => {
476
+ const pdfMeta = await extractSafe(input, url, opts)
477
+ return addHtml({
478
+ html: '',
479
+ url,
480
+ headers: { 'content-type': 'application/pdf' },
481
+ pdfMeta
482
+ }).html()
483
+ }
@@ -0,0 +1,142 @@
1
+ 'use strict'
2
+
3
+ const {
4
+ ORGANIZATION_WORDS,
5
+ PLACE_NAME,
6
+ flatten,
7
+ isBannerLine,
8
+ isInvertedName,
9
+ isPersonName,
10
+ splitNamePairs,
11
+ splitNames,
12
+ stripNoise,
13
+ tidy
14
+ } = require('./text')
15
+
16
+ const EDITOR_PREFIX =
17
+ /^(edited|reviewed|approved|submitted|received|accepted|published)\s+by\s*:?|^(editors?|reviewing editors?|action editors?)\s*:/i
18
+ const SECTION_WORDS =
19
+ /^(abstract|summary|introduction|contents|table of contents|keywords|index|preface|foreword|version|draft)\b/i
20
+
21
+ const AUTHOR_BLOCK_MARGIN = 4
22
+ const EDITOR_BLOCK_LINES = 4
23
+ const MAX_ORGANIZATION_WORDS = 4
24
+ const MAX_AUTHORS = 10
25
+ const NEIGHBOUR_OFFSETS = [1, 2, 3, 4]
26
+
27
+ const isCapitalizedWord = word => /^[\p{Lu}]/u.test(word)
28
+
29
+ const isOrganizationAuthor = text => {
30
+ if (/\S+@\S+/.test(text) || /\d/.test(text) || /^https?:/i.test(text)) {
31
+ return false
32
+ }
33
+ if (SECTION_WORDS.test(text) || PLACE_NAME.test(text)) return false
34
+ const words = text.split(/\s+/)
35
+ return words.length <= MAX_ORGANIZATION_WORDS && words.every(isCapitalizedWord)
36
+ }
37
+
38
+ const editorBlock = lines => {
39
+ const excluded = new Set()
40
+
41
+ for (const line of lines) {
42
+ if (!EDITOR_PREFIX.test(line.text)) continue
43
+ for (let offset = 0; offset <= EDITOR_BLOCK_LINES; offset++) {
44
+ excluded.add(line.index + offset)
45
+ }
46
+ }
47
+
48
+ return excluded
49
+ }
50
+
51
+ const toAuthor = (lines, indexes, options = {}) => {
52
+ const { organizationLimit = Infinity, allowOrganization = false } = options
53
+ const excluded = editorBlock(lines)
54
+ const usable = index => !excluded.has(index)
55
+
56
+ const names = indexes
57
+ .filter(usable)
58
+ .map(index => lines[index])
59
+ .filter(Boolean)
60
+ .map(line => line.text)
61
+ .filter(
62
+ text => !EDITOR_PREFIX.test(text) && !ORGANIZATION_WORDS.test(text) && !isBannerLine(text)
63
+ )
64
+ .flatMap(text => stripNoise(text).split(/;\s*/).flatMap(splitNames))
65
+ .map(tidy)
66
+ .filter(isPersonName)
67
+
68
+ const unique = [...new Set(names.map(flatten))].slice(0, MAX_AUTHORS)
69
+ if (unique.length > 1) return unique.join(', ')
70
+
71
+ const paired = indexes
72
+ .filter(usable)
73
+ .map(index => lines[index])
74
+ .filter(line => line && !ORGANIZATION_WORDS.test(line.text))
75
+ .flatMap(line => splitNamePairs(stripNoise(line.text)))
76
+ .filter(isPersonName)
77
+ if (paired.length > unique.length) {
78
+ return [...new Set(paired)].slice(0, MAX_AUTHORS).join(', ')
79
+ }
80
+ if (unique.length > 0) return unique.join(', ')
81
+
82
+ if (!allowOrganization) return null
83
+
84
+ const organization = indexes
85
+ .filter(index => index <= organizationLimit && usable(index))
86
+ .map(index => lines[index])
87
+ .filter(Boolean)
88
+ .map(line => flatten(stripNoise(line.text)))
89
+ .find(isOrganizationAuthor)
90
+
91
+ return organization || null
92
+ }
93
+
94
+ /**
95
+ * Bylines share a font size. Once one name is found, every line set in the same
96
+ * size around it belongs to the same block, which is what recovers the authors
97
+ * hidden between affiliation and email lines.
98
+ */
99
+ const expandAuthorLines = (lines, indexes, { titleIndexes = [] } = {}) => {
100
+ const excludedTitle = new Set(titleIndexes)
101
+ const usable = indexes.filter(index => !excludedTitle.has(index))
102
+ const named = usable
103
+ .map(index => lines[index])
104
+ .filter(line => line && isPersonName(stripNoise(line.text)))
105
+
106
+ if (named.length === 0) return usable
107
+
108
+ const sizes = new Set(named.map(line => line.size))
109
+ const first = Math.min(...named.map(line => line.index)) - AUTHOR_BLOCK_MARGIN
110
+ const last = Math.max(...named.map(line => line.index)) + AUTHOR_BLOCK_MARGIN
111
+
112
+ return lines
113
+ .filter(line => line.index >= first && line.index <= last && !excludedTitle.has(line.index))
114
+ .filter(line => sizes.has(line.size) && isPersonName(stripNoise(line.text)))
115
+ .map(line => line.index)
116
+ }
117
+
118
+ const nameCount = value => {
119
+ if (!value) return 0
120
+ return value.split(/\s*;\s*/).reduce((count, part) => {
121
+ const trimmed = part.trim()
122
+ if (!trimmed) return count
123
+ if (isInvertedName(trimmed)) return count + 1
124
+ return count + trimmed.split(/,|\s+and\s+/i).filter(Boolean).length
125
+ }, 0)
126
+ }
127
+
128
+ const getAuthor = (lines, { titleIndexes = [] } = {}) => {
129
+ const titleIndex = titleIndexes.length > 0 ? titleIndexes[titleIndexes.length - 1] : 0
130
+ const neighbours = NEIGHBOUR_OFFSETS.map(offset => titleIndex + offset)
131
+ const organization = {
132
+ allowOrganization: true,
133
+ organizationLimit: titleIndex + AUTHOR_BLOCK_MARGIN
134
+ }
135
+
136
+ return (
137
+ toAuthor(lines, expandAuthorLines(lines, neighbours, { titleIndexes })) ||
138
+ toAuthor(lines, neighbours, organization)
139
+ )
140
+ }
141
+
142
+ module.exports = { expandAuthorLines, getAuthor, nameCount, toAuthor }
@@ -0,0 +1,104 @@
1
+ 'use strict'
2
+
3
+ const YEAR = '((?:19|20)\\d{2})'
4
+ const MONTHS =
5
+ 'january|february|march|april|may|june|july|august|september|october|november|december|enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre'
6
+
7
+ const ARXIV_NEW = /arxiv\.org\/(?:abs|pdf)\/(\d{2})(\d{2})\.\d{4,5}|arxiv:(\d{2})(\d{2})\.\d{4,5}/i
8
+ const ARXIV_OLD =
9
+ /arxiv\.org\/(?:abs|pdf)\/[a-z-]+(?:\.[A-Z]{2})?\/(\d{2})(\d{2})\d{3}|arxiv:[a-z-]+(?:\.[A-Z]{2})?\/(\d{2})(\d{2})\d{3}/i
10
+ const PATH_YEAR = /(?:^|[/_-])((?:19|20)\d{2})(?:[/_-]|$)/
11
+
12
+ const MARKED_YEAR = [
13
+ new RegExp(
14
+ `\\b(?:published|accepted|issued|publicado|publication date)\\b[^\\n]{0,40}?${YEAR}`,
15
+ 'i'
16
+ ),
17
+ new RegExp(`(?:©|\\(c\\)|copyright)[^\\n]{0,40}?${YEAR}`, 'i'),
18
+ new RegExp(`\\barxiv:\\S+[^\\n]{0,30}?${YEAR}`, 'i'),
19
+ new RegExp(`\\b(?:vol\\.?|volume|núm\\.?|no\\.)[^\\n]{0,40}?${YEAR}\\b`, 'i'),
20
+ new RegExp(`\\b(?:${MONTHS})\\s+${YEAR}\\b`, 'i'),
21
+ new RegExp(
22
+ `\\b(?:cvpr|iccv|eccv|neurips|nips|icml|iclr|acl|emnlp|naacl|interspeech|aaai|ijcai)\\s*${YEAR}\\b`,
23
+ 'i'
24
+ ),
25
+ new RegExp(`${YEAR}\\s+(?:ieee|acm|international conference|conference on)`, 'i')
26
+ ]
27
+
28
+ const HEADER_LINES = 12
29
+ const FOOTER_LINES = 4
30
+ const BODY_LINE_WORDS = 18
31
+ const ARXIV_EPOCH = 1991
32
+
33
+ const toFullYear = shortYear => {
34
+ const year = Number(shortYear)
35
+ return year >= 91 ? 1900 + year : 2000 + year
36
+ }
37
+
38
+ const arxivStamp = source => {
39
+ const match = ARXIV_NEW.exec(source) || ARXIV_OLD.exec(source)
40
+ if (!match) return null
41
+ const [year, month] = match.slice(1).filter(Boolean)
42
+ return { year: toFullYear(year), month: Number(month) }
43
+ }
44
+
45
+ /**
46
+ * An arXiv id encodes the month it was announced, and proceedings hosts put the
47
+ * year in the path. Both beat the PDF creation date, which is the day the file
48
+ * was last built.
49
+ */
50
+ const identifierDate = (url, { text = '' } = {}) => {
51
+ const stamp = arxivStamp(url) || arxivStamp(text.slice(0, 400))
52
+ if (stamp && stamp.year >= ARXIV_EPOCH && stamp.month >= 1 && stamp.month <= 12) {
53
+ const month = String(stamp.month).padStart(2, '0')
54
+ return `${stamp.year}-${month}-01T00:00:00.000Z`
55
+ }
56
+
57
+ const { pathname } = new URL(url)
58
+ const match = PATH_YEAR.exec(pathname)
59
+ const year = match ? Number(match[1]) : 0
60
+ return year >= 1900 ? `${year}-01-01T00:00:00.000Z` : null
61
+ }
62
+
63
+ const headerAndFooter = lines => {
64
+ const header = []
65
+
66
+ for (const line of lines) {
67
+ if (header.length >= HEADER_LINES) break
68
+ header.push(line.text)
69
+ if (line.text.split(/\s+/).length >= BODY_LINE_WORDS && header.length > 1) {
70
+ break
71
+ }
72
+ }
73
+
74
+ return [...header, ...lines.slice(-FOOTER_LINES).map(line => line.text)].join('\n')
75
+ }
76
+
77
+ const firstMarkedYear = (text, currentYear) => {
78
+ for (const pattern of MARKED_YEAR) {
79
+ const match = pattern.exec(text)
80
+ const year = match ? Number(match[1]) : 0
81
+ if (year >= 1900 && year <= currentYear) return year
82
+ }
83
+ return null
84
+ }
85
+
86
+ const documentYear = (lines, { embedded = {}, now = new Date() } = {}) => {
87
+ const currentYear = now.getUTCFullYear()
88
+ const venue = [embedded.description, embedded.keywords, embedded.title].filter(Boolean).join('\n')
89
+ return firstMarkedYear(headerAndFooter(lines), currentYear) || firstMarkedYear(venue, currentYear)
90
+ }
91
+
92
+ const getDate = (url, { lines, text, embedded, rawEmbedded, now }) => {
93
+ const fromIdentifier = identifierDate(url, { text })
94
+ if (fromIdentifier) return fromIdentifier
95
+
96
+ const year = documentYear(lines, { embedded: rawEmbedded, now })
97
+ if (year == null) return embedded.date
98
+ if (embedded.date && new Date(embedded.date).getUTCFullYear() === year) {
99
+ return embedded.date
100
+ }
101
+ return `${year}-01-01T00:00:00.000Z`
102
+ }
103
+
104
+ module.exports = { documentYear, getDate, identifierDate }
@@ -0,0 +1,57 @@
1
+ 'use strict'
2
+
3
+ const ABSTRACT_HEADING = /(?:^|\n)\s*(?:abstract|summary|executive summary)\b[.:—-]?\s*/i
4
+ const NEXT_SECTION =
5
+ /(?:^|\n)\s*(?:(?:\d+|[ivxlc]+)\.?\s+)?(?:introduction|keywords|contents|table of contents|references|acknowledgements?)\b/i
6
+ const RUNNING_HEADER = /[|·•‖]|^\d+\s*$|\bdoi:/i
7
+ const SENTENCE_END = /(?<=[.!?])\s+/
8
+ const MAX_SUMMARY_LENGTH = 300
9
+ const MIN_SUMMARY_LENGTH = 40
10
+
11
+ const dehyphenate = text => text.replace(/(\p{Ll})-\s+(\p{Ll})/gu, '$1$2')
12
+
13
+ /** The size that carries most of the page is the body text, not the furniture. */
14
+ const dominantSize = lines => {
15
+ const weight = new Map()
16
+ for (const line of lines) {
17
+ weight.set(line.size, (weight.get(line.size) || 0) + line.text.length)
18
+ }
19
+ return [...weight.entries()].sort((left, right) => right[1] - left[1]).map(([size]) => size)[0]
20
+ }
21
+
22
+ const firstSentences = (text, maxLength) => {
23
+ const sentences = text.split(SENTENCE_END)
24
+ let summary = ''
25
+
26
+ for (const sentence of sentences) {
27
+ if (summary && `${summary} ${sentence}`.length > maxLength) break
28
+ summary = summary ? `${summary} ${sentence}` : sentence
29
+ if (summary.length >= maxLength) break
30
+ }
31
+
32
+ if (summary.length <= maxLength) return summary.trim()
33
+ const clipped = summary.slice(0, maxLength)
34
+ return `${clipped.slice(0, clipped.lastIndexOf(' ')).trim()}…`
35
+ }
36
+
37
+ /**
38
+ * The abstract, or the first real paragraph when the document has none.
39
+ */
40
+ const getDescription = (lines, { maxLength = MAX_SUMMARY_LENGTH } = {}) => {
41
+ const readable = lines.filter(line => !RUNNING_HEADER.test(line.text))
42
+ const text = dehyphenate(readable.map(line => line.text).join('\n'))
43
+ const abstract = ABSTRACT_HEADING.exec(text)
44
+
45
+ const bodySize = dominantSize(readable)
46
+ const body = abstract
47
+ ? text.slice(abstract.index + abstract[0].length).split(NEXT_SECTION)[0]
48
+ : readable
49
+ .filter(line => line.size === bodySize)
50
+ .map(line => line.text)
51
+ .join(' ')
52
+
53
+ const summary = firstSentences(dehyphenate(body).replace(/\s+/g, ' ').trim(), maxLength)
54
+ return summary.length >= MIN_SUMMARY_LENGTH ? summary : null
55
+ }
56
+
57
+ module.exports = { getDescription }
@@ -0,0 +1,92 @@
1
+ 'use strict'
2
+
3
+ const { extractImages, getDocumentProxy } = require('unpdf')
4
+
5
+ const SAME_LINE_TOLERANCE = 2
6
+ const MIN_LINE_LENGTH = 2
7
+ const WORD_GAP_RATIO = 0.08
8
+ const COLUMN_GAP_RATIO = 1.5
9
+ const DEFAULT_MAX_PAGES = 2
10
+
11
+ const normalizeSpaces = text =>
12
+ text
13
+ .replace(/[^\S ]+/g, ' ')
14
+ .replace(/ {3,}/g, ' ')
15
+ .trim()
16
+
17
+ const toLines = items => {
18
+ const lines = []
19
+
20
+ for (const item of items) {
21
+ if (!item.str.trim()) continue
22
+ const x = item.transform[4]
23
+ const y = item.transform[5]
24
+ const size = item.height || item.transform[0]
25
+ const previous = lines[lines.length - 1]
26
+
27
+ if (previous && Math.abs(previous.y - y) <= SAME_LINE_TOLERANCE) {
28
+ const gap = x - previous.endX
29
+ const separator = gap > size * COLUMN_GAP_RATIO ? ' ' : ' '
30
+ const needsSpace =
31
+ gap > size * WORD_GAP_RATIO && !/\s$/.test(previous.text) && !/^\s/.test(item.str)
32
+ previous.text += needsSpace ? `${separator}${item.str}` : item.str
33
+ previous.size = Math.max(previous.size, size)
34
+ previous.endX = x + item.width
35
+ } else {
36
+ lines.push({ y, size, text: item.str, endX: x + item.width })
37
+ }
38
+ }
39
+
40
+ return lines
41
+ .map(({ y, size, text }) => ({
42
+ y,
43
+ size: Number(size.toFixed(2)),
44
+ text: normalizeSpaces(text)
45
+ }))
46
+ .filter(line => line.text.length >= MIN_LINE_LENGTH)
47
+ }
48
+
49
+ const pageLines = async (pdf, pageNumber) => {
50
+ const page = await pdf.getPage(pageNumber)
51
+ const { items } = await page.getTextContent()
52
+ const height = page.view[3]
53
+ return toLines(items).map(line => ({ ...line, pageHeight: height }))
54
+ }
55
+
56
+ const readDocument = async (buffer, { maxPages = DEFAULT_MAX_PAGES } = {}) => {
57
+ const pdf = await getDocumentProxy(Uint8Array.from(buffer), {
58
+ isEvalSupported: false,
59
+ verbosity: 0
60
+ })
61
+
62
+ try {
63
+ const { info, metadata } = await pdf.getMetadata()
64
+ const pages = []
65
+
66
+ for (let pageNumber = 1; pageNumber <= Math.min(maxPages, pdf.numPages); pageNumber++) {
67
+ pages.push(await pageLines(pdf, pageNumber))
68
+ }
69
+
70
+ const lines = pages.flat()
71
+ let images = []
72
+ try {
73
+ images = await extractImages(pdf, 1)
74
+ } catch (_) {}
75
+
76
+ return {
77
+ info: info || {},
78
+ xmp: metadata?.getAll?.() || {},
79
+ pageCount: pdf.numPages,
80
+ firstPageLines: pages[0] || [],
81
+ lines,
82
+ images,
83
+ text: lines.map(line => line.text).join('\n')
84
+ }
85
+ } finally {
86
+ try {
87
+ await pdf.loadingTask.destroy()
88
+ } catch (_) {}
89
+ }
90
+ }
91
+
92
+ module.exports = { readDocument, toLines }