검색 본문 읽기: Readability 기반 본문 추출기(메뉴·푸터 제거, 인코딩 처리, 표 줄바꿈 보존, 메뉴목록 판별) 적용
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c1c2b096f0
commit
396eaea309
5 files changed
+362
-4
No files matched your search
Generated
+209
@@ -9,6 +9,7 @@
|
||||
"version": "4.5.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@xterm/addon-fit": "^0.10.0",
|
||||
"@xterm/addon-web-links": "^0.11.0",
|
||||
"@xterm/xterm": "^5.5.0",
|
||||
@@ -24,6 +25,7 @@
|
||||
"esptool-js": "^0.4.1",
|
||||
"express": "^5.2.1",
|
||||
"imapflow": "^1.3.3",
|
||||
"linkedom": "^0.18.13",
|
||||
"mailparser": "^3.9.8",
|
||||
"monaco-editor": "^0.52.0",
|
||||
"node-pty": "^1.1.0",
|
||||
@@ -510,6 +512,14 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@mozilla/readability": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz",
|
||||
"integrity": "sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ==",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@pinojs/redact": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
|
||||
@@ -1110,6 +1120,18 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/boolbase": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz",
|
||||
"integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
|
||||
@@ -1529,6 +1551,116 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/css-select": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz",
|
||||
"integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==",
|
||||
"dependencies": {
|
||||
"boolbase": "^2.0.0",
|
||||
"css-what": "^8.0.0",
|
||||
"domhandler": "^6.0.1",
|
||||
"domutils": "^4.0.2",
|
||||
"nth-check": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/css-select/node_modules/dom-serializer": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
|
||||
"integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
|
||||
"dependencies": {
|
||||
"domelementtype": "^3.0.0",
|
||||
"domhandler": "^6.0.0",
|
||||
"entities": "^8.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/css-select/node_modules/domelementtype": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
|
||||
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/css-select/node_modules/domhandler": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
|
||||
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
|
||||
"dependencies": {
|
||||
"domelementtype": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/css-select/node_modules/domutils": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
|
||||
"integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
|
||||
"dependencies": {
|
||||
"dom-serializer": "^3.0.0",
|
||||
"domelementtype": "^3.0.0",
|
||||
"domhandler": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/domutils?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/css-select/node_modules/entities": {
|
||||
"version": "8.1.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
|
||||
"integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/css-what": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz",
|
||||
"integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/cssom": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
|
||||
"integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw=="
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
@@ -2146,6 +2278,11 @@
|
||||
"he": "bin/he"
|
||||
}
|
||||
},
|
||||
"node_modules/html-escaper": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz",
|
||||
"integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ=="
|
||||
},
|
||||
"node_modules/html-to-text": {
|
||||
"version": "9.0.5",
|
||||
"resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz",
|
||||
@@ -2487,6 +2624,58 @@
|
||||
"immediate": "~3.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom": {
|
||||
"version": "0.18.13",
|
||||
"resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz",
|
||||
"integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==",
|
||||
"dependencies": {
|
||||
"css-select": "^7.0.0",
|
||||
"cssom": "^0.5.0",
|
||||
"html-escaper": "^3.0.3",
|
||||
"htmlparser2": "^10.1.0",
|
||||
"uhyphen": "^0.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"canvas": ">= 2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"canvas": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/entities": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
|
||||
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/htmlparser2": {
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
|
||||
"integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
|
||||
"funding": [
|
||||
"https://github.com/fb55/htmlparser2?sponsor=1",
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.2.2",
|
||||
"entities": "^7.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkify-it": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz",
|
||||
@@ -2756,6 +2945,21 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nth-check": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz",
|
||||
"integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==",
|
||||
"dependencies": {
|
||||
"boolbase": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/nth-check?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/object-assign": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||
@@ -3852,6 +4056,11 @@
|
||||
"resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz",
|
||||
"integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A=="
|
||||
},
|
||||
"node_modules/uhyphen": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz",
|
||||
"integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA=="
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "7.19.2",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@xterm/addon-fit": "^0.10.0",
|
||||
"@xterm/addon-web-links": "^0.11.0",
|
||||
"@xterm/xterm": "^5.5.0",
|
||||
@@ -52,6 +53,7 @@
|
||||
"esptool-js": "^0.4.1",
|
||||
"express": "^5.2.1",
|
||||
"imapflow": "^1.3.3",
|
||||
"linkedom": "^0.18.13",
|
||||
"mailparser": "^3.9.8",
|
||||
"monaco-editor": "^0.52.0",
|
||||
"node-pty": "^1.1.0",
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* web-extract.ts — 본문 추출기 (검색 결과 상위 페이지 읽기용)
|
||||
*
|
||||
* 기존 stripHtml은 태그만 걷어 내서 메뉴·사이드바·푸터 글자가 본문보다 앞에 붙는다(2026-10-17 실측:
|
||||
* GitHub 문서 페이지는 첫 800자가 "Skip to content / Navigation Menu / Sign in …"). 페이지당 2~3KB만
|
||||
* 모델에 주는 상황에서 그건 근거 자료의 절반을 버리는 것이다. 여기서는
|
||||
* 1) Mozilla Readability(Firefox 읽기 모드와 같은 알고리즘)로 본문 영역을 고르고
|
||||
* 2) 못 고르면(상품·목록 페이지) 메뉴/푸터를 걷어 낸 body 텍스트로 폴백하고
|
||||
* 3) 쿠키·로그인·저작권 같은 고정 문구 줄을 지우고 중복 줄을 합친다.
|
||||
* 인코딩도 처리한다(옛 한국 사이트의 euc-kr을 utf-8로 읽으면 깨진 글자가 본문이 된다).
|
||||
*/
|
||||
import { parseHTML } from 'linkedom';
|
||||
import { Readability } from '@mozilla/readability';
|
||||
|
||||
const BOILERPLATE_LINE = /(쿠키|cookie|로그인|회원가입|sign\s*in|log\s*in|subscribe|구독|공유하기|스크랩|댓글|무단\s*(전재|복제)|저작권|copyright|all rights reserved|개인정보|이용약관|광고문의|뉴스레터|skip to (main )?content|사이트맵|맨\s*위로|top\s*of\s*page)/i;
|
||||
|
||||
function decodeBody(buf: ArrayBuffer, contentType: string): string {
|
||||
const bytes = new Uint8Array(buf);
|
||||
let charset = /charset=([\w-]+)/i.exec(contentType)?.[1];
|
||||
if (!charset) {
|
||||
// <meta charset> / <meta http-equiv content="...charset=..."> — 앞부분 ASCII만 훑는다
|
||||
const head = new TextDecoder('latin1').decode(bytes.subarray(0, 4096));
|
||||
charset = /<meta[^>]+charset=["']?([\w-]+)/i.exec(head)?.[1];
|
||||
}
|
||||
try { return new TextDecoder((charset || 'utf-8').toLowerCase()).decode(bytes); }
|
||||
catch { return new TextDecoder('utf-8').decode(bytes); }
|
||||
}
|
||||
|
||||
|
||||
/** 메뉴 목록처럼 짧은 줄만 잔뜩이면 본문이 아니다(연합뉴스 404 페이지에서 Readability가 내비게이션을 본문으로 고른 실측). */
|
||||
function looksLikeMenu(text: string): boolean {
|
||||
const lines = text.split('\n').map(l => l.trim()).filter(Boolean);
|
||||
if (lines.length < 15) return false;
|
||||
const short = lines.filter(l => l.length < 12).length;
|
||||
return short / lines.length > 0.7;
|
||||
}
|
||||
|
||||
function normalize(text: string): string {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const raw of text.replace(/\r/g, '').split('\n')) {
|
||||
const line = raw.replace(/[ \t ]+/g, ' ').trim();
|
||||
if (!line) { if (out.length && out[out.length - 1] !== '') out.push(''); continue; }
|
||||
if (line.length < 60 && BOILERPLATE_LINE.test(line)) continue; // 짧은 고정 문구 줄만 (긴 줄은 본문일 수 있음)
|
||||
if (line.length < 40 && seen.has(line)) continue; // 반복되는 짧은 줄(메뉴 항목 등)
|
||||
seen.add(line);
|
||||
out.push(line);
|
||||
}
|
||||
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
/** HTML 문자열에서 본문 텍스트를 뽑는다. 아무것도 못 얻으면 빈 문자열. */
|
||||
export function extractMainText(html: string, url = ''): { title: string; text: string; method: 'readability' | 'fallback' } {
|
||||
let title = '';
|
||||
try {
|
||||
const { document } = parseHTML(html);
|
||||
title = String(document.title || '').trim();
|
||||
// Readability는 문서를 변형하므로 폴백용으로 복제본을 따로 쓴다.
|
||||
const fallbackDoc = parseHTML(html).document;
|
||||
try {
|
||||
const article = new Readability(document as any, { charThreshold: 300 }).parse();
|
||||
// textContent는 블록 사이 줄바꿈이 없어 표·정보상자가 한 줄로 붙는다 — content(HTML)를 다시 파싱해 블록 끝에 줄바꿈을 넣는다.
|
||||
let raw = article?.textContent || '';
|
||||
if (article?.content) {
|
||||
const adoc: any = parseHTML(`<!doctype html><html><body>${article.content}</body></html>`).document;
|
||||
adoc.querySelectorAll('p, div, li, tr, h1, h2, h3, h4, h5, h6, br, section, dt, dd, figcaption, blockquote, pre')
|
||||
.forEach((n: any) => n.append(adoc.createTextNode('\n')));
|
||||
adoc.querySelectorAll('td, th').forEach((n: any) => n.append(adoc.createTextNode(' | ')));
|
||||
raw = String(adoc.body?.textContent || raw);
|
||||
}
|
||||
const text = raw ? normalize(raw) : '';
|
||||
if (text.length >= 400 && !looksLikeMenu(text)) return { title: article?.title || title, text, method: 'readability' };
|
||||
} catch { /* 폴백으로 */ }
|
||||
for (const sel of ['script', 'style', 'noscript', 'svg', 'iframe', 'form', 'nav', 'header', 'footer', 'aside', 'button', 'select', 'template']) {
|
||||
fallbackDoc.querySelectorAll(sel).forEach((n: any) => n.remove());
|
||||
}
|
||||
const root: any = fallbackDoc.querySelector('main, article, [role="main"]') || fallbackDoc.body;
|
||||
// 블록 경계가 줄바꿈이 되도록 textContent 앞에 구분자를 넣는다
|
||||
root?.querySelectorAll?.('p, div, li, tr, h1, h2, h3, h4, h5, h6, br, section')
|
||||
.forEach((n: any) => n.append(fallbackDoc.createTextNode('\n')));
|
||||
const fb = normalize(String(root?.textContent || ''));
|
||||
return { title, text: looksLikeMenu(fb) ? '' : fb, method: 'fallback' };
|
||||
} catch {
|
||||
return { title, text: '', method: 'fallback' };
|
||||
}
|
||||
}
|
||||
|
||||
/** URL을 받아 본문 텍스트를 돌려준다. 실패·비HTML·너무 큰 페이지는 null. */
|
||||
export async function fetchMainText(url: string, opts: { maxChars?: number; timeoutMs?: number } = {}): Promise<{ title: string; text: string; method: string } | null> {
|
||||
const maxChars = opts.maxChars ?? 2500;
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmallClaw/1.0', 'Accept': 'text/html,application/xhtml+xml', 'Accept-Language': 'ko,en;q=0.8' },
|
||||
signal: AbortSignal.timeout(opts.timeoutMs ?? 6500),
|
||||
redirect: 'follow',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const ct = res.headers.get('content-type') || '';
|
||||
if (!/html|xml/i.test(ct)) return null;
|
||||
const buf = await res.arrayBuffer();
|
||||
if (buf.byteLength > 3_000_000) return null;
|
||||
const { title, text, method } = extractMainText(decodeBody(buf, ct), url);
|
||||
if (!text) return null;
|
||||
return { title, text: text.length > maxChars ? text.slice(0, maxChars).replace(/\s+\S*$/, '') + ' …' : text, method };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -2,6 +2,7 @@ import { ToolResult } from '../types.js';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { lookupGpuSpecs } from './gpu-specs.js';
|
||||
import { lookupDanawa } from './danawa.js';
|
||||
import { fetchMainText } from './web-extract.js';
|
||||
import { mergeSearchResults, renderMergedStdout, normalizePreferredProvider } from './search-merge.js';
|
||||
|
||||
type SearchResultItem = { title: string; url: string; snippet: string };
|
||||
@@ -1385,7 +1386,7 @@ function isDeepReadUrl(url: string): boolean {
|
||||
* Reading the pages in code is what lets the answer rest on the source instead of on a snippet.
|
||||
* Every page is best-effort: a walled, slow or JS-only page is dropped silently, never an error.
|
||||
*/
|
||||
async function deepReadResults(results: any[], maxPages = 3, perPageChars = 2200, budgetMs = 7000): Promise<Array<{ n: number; url: string; text: string }>> {
|
||||
async function deepReadResults(results: any[], maxPages = 3, perPageChars = 2500, budgetMs = 7000): Promise<Array<{ n: number; url: string; text: string }>> {
|
||||
const picks = (Array.isArray(results) ? results : [])
|
||||
.map((r, i) => ({ n: i + 1, url: String(r?.url || '').trim() }))
|
||||
.filter(x => isDeepReadUrl(x.url))
|
||||
@@ -1393,9 +1394,10 @@ async function deepReadResults(results: any[], maxPages = 3, perPageChars = 2200
|
||||
const timeout = new Promise<null>(resolve => setTimeout(() => resolve(null), budgetMs));
|
||||
const jobs = picks.map(async (x) => {
|
||||
try {
|
||||
const r = await Promise.race([executeWebFetch({ url: x.url, max_chars: perPageChars }), timeout]);
|
||||
if (!r || !r.success) return null;
|
||||
const text = String(r.stdout || '').replace(/\n{3,}/g, '\n\n').trim();
|
||||
// 본문 추출기(Readability + 폴백): 메뉴·푸터를 걷어 내고 인코딩을 맞춘다. web_fetch 자체의 동작은 그대로.
|
||||
const r = await Promise.race([fetchMainText(x.url, { maxChars: perPageChars, timeoutMs: budgetMs - 500 }), timeout]);
|
||||
if (!r) return null;
|
||||
const text = (r.title ? `${r.title}\n` : '') + String(r.text || '').replace(/\n{3,}/g, '\n\n').trim();
|
||||
// Short bodies are cookie walls, "enable JavaScript" stubs or redirects — not evidence.
|
||||
if (text.length < 400 || /enable javascript|자바스크립트를 (활성|사용)|access denied|captcha/i.test(text.slice(0, 600))) return null;
|
||||
return { n: x.n, url: x.url, text };
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* web-extract — 검색 결과 페이지 본문 추출
|
||||
* 표본: 2026-10-17 실측(GitHub/당근/연합뉴스 404 페이지에서 메뉴가 본문보다 앞서거나 본문으로 뽑힘).
|
||||
*/
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractMainText } from '../src/tools/web-extract';
|
||||
|
||||
const ARTICLE = `<html><head><title>HQ 카메라 리뷰 | 블로그</title></head><body>
|
||||
<header><nav><a>홈</a><a>로그인</a><a>회원가입</a></nav></header>
|
||||
<main><article><h1>HQ 카메라 리뷰</h1>
|
||||
<p>${'IMX477 센서는 4056×3040 해상도를 제공하며 C/CS 마운트 렌즈를 쓸 수 있다. '.repeat(8)}</p>
|
||||
<p>${'초점은 렌즈 경통으로 조절하고 조리개 잠금 나사로 고정한다. '.repeat(6)}</p></article></main>
|
||||
<footer><p>Copyright 2026 All rights reserved</p></footer></body></html>`;
|
||||
|
||||
describe('extractMainText', () => {
|
||||
test('메뉴·푸터를 빼고 본문만 남긴다', () => {
|
||||
const r = extractMainText(ARTICLE);
|
||||
assert.ok(r.text.includes('IMX477'));
|
||||
assert.ok(!r.text.includes('회원가입'));
|
||||
assert.ok(!/all rights reserved/i.test(r.text));
|
||||
assert.ok(r.text.length >= 400);
|
||||
});
|
||||
test('메뉴 목록뿐인 페이지는 본문으로 인정하지 않는다', () => {
|
||||
const menu = '<html><body><main>' + Array.from({ length: 60 }, (_, i) => `<div>메뉴${i}</div>`).join('') + '</main></body></html>';
|
||||
assert.equal(extractMainText(menu).text, '');
|
||||
});
|
||||
test('표 셀이 한 줄로 뭉치지 않는다(줄바꿈 보존)', () => {
|
||||
const html = `<html><body><article><p>${'설명 문장입니다. '.repeat(40)}</p><table><tr><td>가격</td><td>35달러</td></tr><tr><td>해상도</td><td>12MP</td></tr></table></article></body></html>`;
|
||||
const t = extractMainText(html).text;
|
||||
assert.ok(/가격[\s|]+35달러/.test(t));
|
||||
assert.ok(t.split('\n').some(l => l.includes('35달러') && !l.includes('12MP')));
|
||||
});
|
||||
test('깨진 HTML도 예외 없이 빈 문자열', () => {
|
||||
assert.equal(extractMainText('<<<>>>').text, '');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user