feat(summary): send complete articles within user budget (#39)
This commit is contained in:
@ -7,23 +7,18 @@ const CONCURRENCY = 2
|
||||
const ARTICLE_TIMEOUT_MS = 30000
|
||||
const TOTAL_TIMEOUT_MS = 90000
|
||||
|
||||
function truncateUTF8 (value, maximum) {
|
||||
const buffer = Buffer.from(value, 'utf8')
|
||||
if (buffer.length <= maximum) return value
|
||||
let end = maximum
|
||||
while (end > 0 && (buffer[end] & 0xc0) === 0x80) end--
|
||||
return buffer.subarray(0, end).toString('utf8')
|
||||
}
|
||||
function extractArticle (html, articleURL) {
|
||||
const empty = { content: '', published_at: null, content_truncated: false }
|
||||
const empty = { content: '', published_at: null, content_truncated: false, content_state: 'unavailable' }
|
||||
if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES) return empty
|
||||
const $ = cheerio.load(html)
|
||||
const roots = $('article.articleLayout_basic__gcpQk div.body-content, article div.FeatureContent_body__NTf8M')
|
||||
const root = roots.length === 1 ? roots.first() : $()
|
||||
const paragraphs = []
|
||||
root.find('p.ArticleBodyText_articleBodyContent__17wqE, p.typography_articleBody___5jDr').each((_, node) => {
|
||||
root.find('p.ArticleBodyText_articleBodyContent__17wqE, p.typography_articleBody___5jDr, h1, h2, h3, h4, h5, h6, li, blockquote, pre, figcaption, tr').each((_, node) => {
|
||||
const excluded = 'script, style, noscript, nav, aside, footer, button, form, svg, [hidden], [aria-hidden="true"], .placeholder, .disclaimer, [data-component="placeholder"], [data-component="disclaimer"], [data-component="related-stories"]'
|
||||
if ($(node).parentsUntil(root).addBack().is(excluded)) return
|
||||
// A nested paragraph is already represented by its enclosing editorial block.
|
||||
if ($(node).parentsUntil(root, 'li, blockquote, pre, figcaption, tr').length) return
|
||||
const p = $(node).clone()
|
||||
if (p.is('[hidden], [aria-hidden="true"], .disclaimer, [data-component="disclaimer"], [data-component="related-stories"]')) return
|
||||
p.find(excluded).remove()
|
||||
@ -32,7 +27,10 @@ function extractArticle (html, articleURL) {
|
||||
if (text) paragraphs.push(text)
|
||||
})
|
||||
const full = paragraphs.join('\n\n')
|
||||
return { content: truncateUTF8(full, MAX_CONTENT_BYTES), published_at: extractPublicationDate(html, articleURL), content_truncated: Buffer.byteLength(full) > MAX_CONTENT_BYTES }
|
||||
// Keep the full editorial extraction; resource limits reject an extraction
|
||||
// rather than turning a prefix into a supposedly complete article.
|
||||
const blocked = $('[class*="paywall"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-truncated="true"]').length > 0
|
||||
return { content: full, published_at: extractPublicationDate(html, articleURL), content_truncated: false, content_state: full ? (blocked ? 'incomplete' : 'complete') : 'unavailable' }
|
||||
}
|
||||
function canonicalURL (value) {
|
||||
try {
|
||||
@ -48,7 +46,7 @@ async function enrichArticles (urls, loadHtml, options = {}) {
|
||||
const articleTimeoutMs = options.articleTimeoutMs ?? ARTICLE_TIMEOUT_MS
|
||||
const totalTimeoutMs = options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS
|
||||
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > CONCURRENCY || !(articleTimeoutMs > 0 && articleTimeoutMs <= ARTICLE_TIMEOUT_MS) || !(totalTimeoutMs > 0 && totalTimeoutMs <= TOTAL_TIMEOUT_MS)) throw new Error('invalid enrichment budget')
|
||||
const empty = () => ({ content: '', published_at: null, content_truncated: false })
|
||||
const empty = () => ({ content: '', published_at: null, content_truncated: false, content_state: 'unavailable' })
|
||||
const keys = urls.map(canonicalURL)
|
||||
const unique = [...new Set(keys.filter(Boolean))]
|
||||
const results = new Map()
|
||||
|
||||
@ -15,13 +15,14 @@ test('no broad article/main or JSON-LD content fallback; paragraph normalization
|
||||
assert.equal(extractArticle('<script type="application/ld+json">{"@type":"NewsArticle","articleBody":"excluded"}</script>').content, '')
|
||||
assert.equal(extractArticle(basic('one two<script>excluded</script>') .replace('</div></article>', `<p class="${paragraph}"> three\n four </p></div></article>`)).content, 'one two\n\nthree four')
|
||||
})
|
||||
test('oversized non-ASCII content is deterministically bounded on UTF-8 boundaries', () => {
|
||||
test('large non-ASCII editorial content remains complete without truncation', () => {
|
||||
const html = basic('é漢🙂'.repeat(MAX_CONTENT_BYTES))
|
||||
const first = extractArticle(html)
|
||||
assert.equal(first.content, extractArticle(html).content)
|
||||
assert.ok(Buffer.byteLength(first.content) <= MAX_CONTENT_BYTES)
|
||||
assert.equal(first.content, 'é漢🙂'.repeat(MAX_CONTENT_BYTES))
|
||||
assert.ok(!first.content.includes('\ufffd'))
|
||||
assert.equal(first.content_truncated, true)
|
||||
assert.equal(first.content_truncated, false)
|
||||
assert.equal(first.content_state, 'complete')
|
||||
})
|
||||
test('enrichment deduplicates loads, bounds concurrency and preserves input order', async () => {
|
||||
const urls = ['a', 'b', 'a', 'c'].map(id => `https://www.bloomberg.com/news/articles/${id}`)
|
||||
@ -90,3 +91,9 @@ test('editorial descendants preserve document order and exclude non-editorial an
|
||||
const html = `<article><div class="FeatureContent_body__NTf8M"><div><section><p class="${paragraph}">one</p></section></div><aside><div><p class="${paragraph}">excluded</p></div></aside><div hidden><p class="${paragraph}">excluded</p></div><div data-component="related-stories"><p class="${paragraph}">excluded</p></div><div><div><p class="${paragraph}">two</p></div></div></div></article>`
|
||||
assert.equal(extractArticle(html).content,'one\n\ntwo')
|
||||
})
|
||||
|
||||
test('full editorial extraction preserves headings, list items and quotations', () => {
|
||||
const html = basic('First paragraph.').replace('</div></article>', '<h2>Editorial heading</h2><ul><li>Editorial list item</li></ul><blockquote>Editorial quotation</blockquote></div></article>')
|
||||
const result = extractArticle(html)
|
||||
for (const text of ['First paragraph.', 'Editorial heading', 'Editorial list item', 'Editorial quotation']) assert.ok(result.content.includes(text))
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user