extract-refdoc 0.0.0-stage → 0.2.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/README.md +172 -2
- package/bin/extract-refdoc.ts +134 -0
- package/dist/refdoc.css +3727 -0
- package/dist/refdoc.js +162 -0
- package/package.json +83 -3
- package/src/ai.ts +268 -0
- package/src/finish.ts +105 -0
- package/src/highlight.ts +125 -0
- package/src/html-to-paper.ts +400 -0
- package/src/html.ts +172 -0
- package/src/index.ts +78 -0
- package/src/markdown.ts +192 -0
- package/src/mdx.ts +182 -0
- package/src/pipeline.ts +61 -0
- package/src/reader-runtime.ts +166 -0
- package/src/refdoc-read.ts +96 -0
- package/src/refdoc.ts +250 -0
- package/src/server.ts +218 -0
- package/src/source.ts +156 -0
- package/src/types.ts +59 -0
- package/src/widget/PaperReader.tsx +41 -0
- package/src/widget/PaperToWeb.tsx +129 -0
- package/src/widget/index.ts +6 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Extracted reading-mode HTML (or plain text / markdown) →
|
|
3
|
+
* `Paper`.
|
|
4
|
+
*
|
|
5
|
+
* `extract-webpage` hands back basic HTML: headings, paragraphs, lists,
|
|
6
|
+
* figures. This splits it into sections at the heading level the document
|
|
7
|
+
* uses most for its top-level parts, pulls out the abstract and the
|
|
8
|
+
* reference list, strips section numbers from headings ("2. Original Sin",
|
|
9
|
+
* "II. Foo") so the MDX can number them itself, and rejoins paragraphs a PDF
|
|
10
|
+
* broke mid-sentence. Documents with no usable headings are cut into
|
|
11
|
+
* sections of a few paragraphs each.
|
|
12
|
+
*
|
|
13
|
+
* Summaries and underlining are left to `finishPaper` (offline) or the AI
|
|
14
|
+
* pass in `ai.ts`.
|
|
15
|
+
*
|
|
16
|
+
* @module html-to-paper
|
|
17
|
+
*/
|
|
18
|
+
import { parseHTML } from "linkedom"
|
|
19
|
+
import { collapseWhitespace, escapeMdxText, htmlInlineToMarkdown, markdownToPlainText } from "./markdown"
|
|
20
|
+
import type { Paper, PaperFigure, PaperSection } from "./types"
|
|
21
|
+
|
|
22
|
+
/** Metadata the extractor found, carried onto the paper. */
|
|
23
|
+
export interface PaperMeta {
|
|
24
|
+
title?: string
|
|
25
|
+
author?: string
|
|
26
|
+
date?: string
|
|
27
|
+
sourceUrl?: string
|
|
28
|
+
cite?: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One block in document order. */
|
|
32
|
+
type Block =
|
|
33
|
+
| { kind: "heading"; level: number; text: string }
|
|
34
|
+
| { kind: "paragraph"; markdown: string; listItem?: boolean }
|
|
35
|
+
| { kind: "figure"; figure: PaperFigure }
|
|
36
|
+
|
|
37
|
+
const REFERENCES_HEADING = /^(references|bibliography|works cited|literature cited|sources|citations|notes and references)$/i
|
|
38
|
+
const ABSTRACT_HEADING = /^(abstract|summary|executive summary)$/i
|
|
39
|
+
const SKIP_HEADING = /^(table of contents|contents|acknowledg(e)?ments?|footnotes|instructions for reporting errors|report (github )?issue|related articles|share this|comments?)$/i
|
|
40
|
+
|
|
41
|
+
/** Paragraphs per section when the document has no headings to split on. */
|
|
42
|
+
const PARAGRAPHS_PER_SECTION = 6
|
|
43
|
+
|
|
44
|
+
type El = {
|
|
45
|
+
nodeType: number
|
|
46
|
+
tagName: string
|
|
47
|
+
childNodes: ArrayLike<El>
|
|
48
|
+
children: ArrayLike<El>
|
|
49
|
+
textContent: string | null
|
|
50
|
+
getAttribute(name: string): string | null
|
|
51
|
+
querySelector(selector: string): El | null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** "2. Original Sin" / "II. Foo" / "2 Foo" / "Section 3: Bar" → the title alone. */
|
|
55
|
+
export function stripSectionNumber(heading: string): string {
|
|
56
|
+
return heading
|
|
57
|
+
.replace(/^\s*(?:section|chapter|part)\s+[\divxlc]+[.:)]?\s*/i, "")
|
|
58
|
+
.replace(/^\s*(?:\d+(?:\.\d+)*|[IVXLC]+|[A-Z])[.:)]\s+/, "")
|
|
59
|
+
.replace(/^\s*\d{1,2}(?:\.\d+)*\s+(?=[A-Z])/, "")
|
|
60
|
+
.trim()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function figureFrom(element: El): PaperFigure | null {
|
|
64
|
+
const img = element.tagName === "IMG" ? element : element.querySelector("img")
|
|
65
|
+
const src = img?.getAttribute("src") ?? ""
|
|
66
|
+
if (!/^(https?:)?\/\//.test(src) && !src.startsWith("data:image/")) return null
|
|
67
|
+
if (NOT_A_FIGURE.test(src)) return null
|
|
68
|
+
const width = Number(img?.getAttribute("width"))
|
|
69
|
+
if (width > 0 && width < 120) return null
|
|
70
|
+
const caption =
|
|
71
|
+
collapseWhitespace(element.querySelector("figcaption")?.textContent ?? "").trim() ||
|
|
72
|
+
collapseWhitespace(img?.getAttribute("alt") ?? img?.getAttribute("title") ?? "").trim()
|
|
73
|
+
return { src: src.startsWith("//") ? `https:${src}` : src, caption: caption.replace(/^(figure|fig\.)\s*\d+[a-z]?\s*[:.–—-]\s*/i, "") }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Block-level children that end a run of loose inline text. */
|
|
77
|
+
const BLOCK_TAGS = /^(P|DIV|H[1-6]|UL|OL|DL|FIGURE|TABLE|BLOCKQUOTE|SECTION|ARTICLE|PRE|HEADER|FOOTER|MAIN|NAV|ASIDE|DETAILS|PICTURE)$/
|
|
78
|
+
|
|
79
|
+
/** "Figure 3: caption" / "Fig. 3. caption". */
|
|
80
|
+
const FIGURE_CAPTION = /^(?:figure|fig\.)\s*\d+[a-z]?\s*[:.–—-]\s*(.*)$/i
|
|
81
|
+
|
|
82
|
+
/** Site chrome, icons and logos rather than figures. */
|
|
83
|
+
const NOT_A_FIGURE = /\.svg(\?|$)|\/(static|icons?|logos?|funders|badges?|avatars?)\/|logo|sprite|spacer|pixel/i
|
|
84
|
+
|
|
85
|
+
const CONTAINER_TAGS = new Set(["DIV", "SECTION", "ARTICLE", "MAIN", "HEADER", "FOOTER", "BODY", "SPAN", "CENTER", "ASIDE", "NAV", "FORM", "TBODY", "THEAD", "DETAILS"])
|
|
86
|
+
|
|
87
|
+
/** Walk the extracted HTML into blocks, in document order. */
|
|
88
|
+
function collectBlocks(root: El): Block[] {
|
|
89
|
+
const blocks: Block[] = []
|
|
90
|
+
const visit = (element: El) => {
|
|
91
|
+
const tag = element.tagName
|
|
92
|
+
const heading = /^H([1-6])$/.exec(tag)
|
|
93
|
+
if (heading) {
|
|
94
|
+
const text = collapseWhitespace(element.textContent ?? "").trim()
|
|
95
|
+
if (text) blocks.push({ kind: "heading", level: Number(heading[1]), text })
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (tag === "FIGURE" || tag === "IMG" || tag === "PICTURE") {
|
|
99
|
+
const figure = figureFrom(element)
|
|
100
|
+
if (figure) blocks.push({ kind: "figure", figure })
|
|
101
|
+
return
|
|
102
|
+
}
|
|
103
|
+
if ((tag === "UL" || tag === "OL") && !Array.from(element.children).some((child) => child.tagName === "LI")) {
|
|
104
|
+
// PDF output wraps loose lines in a list with no items.
|
|
105
|
+
pushParagraph(element)
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
if (tag === "UL" || tag === "OL") {
|
|
109
|
+
for (const item of Array.from(element.children)) {
|
|
110
|
+
if (item.tagName === "LI") pushParagraph(item, true)
|
|
111
|
+
}
|
|
112
|
+
return
|
|
113
|
+
}
|
|
114
|
+
if (tag === "P" || tag === "BLOCKQUOTE" || tag === "PRE" || tag === "DD" || tag === "DT" || tag === "LI") {
|
|
115
|
+
// A paragraph that is only an image is a figure.
|
|
116
|
+
if (element.querySelector("img") && !(element.textContent ?? "").trim()) {
|
|
117
|
+
const figure = figureFrom(element)
|
|
118
|
+
if (figure) blocks.push({ kind: "figure", figure })
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
pushParagraph(element)
|
|
122
|
+
return
|
|
123
|
+
}
|
|
124
|
+
if (tag === "TABLE" || tag === "SCRIPT" || tag === "STYLE" || tag === "NOSCRIPT" || tag === "SVG") return
|
|
125
|
+
if (CONTAINER_TAGS.has(tag) || element.children.length > 0) {
|
|
126
|
+
const hasBlockChild = Array.from(element.children).some((child) => BLOCK_TAGS.test(child.tagName))
|
|
127
|
+
if (!hasBlockChild) {
|
|
128
|
+
pushParagraph(element)
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
// Mixed content (common in extracted PDF and arXiv HTML): loose text and
|
|
132
|
+
// inline elements between block children are paragraphs of their own.
|
|
133
|
+
let run: El[] = []
|
|
134
|
+
const flush = () => {
|
|
135
|
+
const markdown = run.map((node) => htmlInlineToMarkdown(node as never)).join("").trim()
|
|
136
|
+
if (markdown) pushMarkdown(markdown)
|
|
137
|
+
run = []
|
|
138
|
+
}
|
|
139
|
+
for (const child of Array.from(element.childNodes)) {
|
|
140
|
+
if (child.nodeType === 1 && (BLOCK_TAGS.test(child.tagName) || child.tagName === "IMG")) {
|
|
141
|
+
flush()
|
|
142
|
+
visit(child)
|
|
143
|
+
} else {
|
|
144
|
+
run.push(child)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
flush()
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
pushParagraph(element)
|
|
151
|
+
}
|
|
152
|
+
const pushMarkdown = (markdown: string, listItem = false) => {
|
|
153
|
+
// A caption written as loose text right after its image: "Figure 1: …".
|
|
154
|
+
const caption = FIGURE_CAPTION.exec(markdownToPlainText(markdown))
|
|
155
|
+
const previous = blocks[blocks.length - 1]
|
|
156
|
+
if (caption && previous?.kind === "figure" && !previous.figure.caption) {
|
|
157
|
+
previous.figure.caption = caption[1].trim()
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
blocks.push({ kind: "paragraph", markdown, listItem })
|
|
161
|
+
}
|
|
162
|
+
const pushParagraph = (element: El, listItem = false) => {
|
|
163
|
+
const markdown = htmlInlineToMarkdown(element as never).trim()
|
|
164
|
+
if (markdown) pushMarkdown(markdown, listItem)
|
|
165
|
+
}
|
|
166
|
+
visit(root)
|
|
167
|
+
return blocks
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Page numbers, running headers, navigation links and other noise. */
|
|
171
|
+
export function isNoise(markdown: string): boolean {
|
|
172
|
+
const plain = markdownToPlainText(markdown)
|
|
173
|
+
if (plain.length < 3 || /^(page\s*)?\d+(\s*of\s*\d+)?$/i.test(plain) || !/[\p{L}]/u.test(plain)) return true
|
|
174
|
+
// Navigation: a paragraph that is nothing but links.
|
|
175
|
+
const withoutLinks = markdownToPlainText(markdown.replace(/!?\[[^\]]*\]\([^)]*\)/g, ""))
|
|
176
|
+
return /\]\(/.test(markdown) && withoutLinks.replace(/[\s·|•,;:–—-]/g, "").length < 3
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** "1. Introduction", "3.2 Results", "IV. CONCLUSION": a numbered heading line. */
|
|
180
|
+
const NUMBERED_HEADING = /^(?:(\d+(?:\.\d+)*)\.?|([IVXLC]+)\.)\s+([A-Z][^.!?]{1,70})$/
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* PDFs come out with no heading tags: section titles are short numbered
|
|
184
|
+
* lines ("1. Introduction"). Promote those to headings (sub-numbers one level
|
|
185
|
+
* deeper), and drop "headings" that are really math (no words).
|
|
186
|
+
*/
|
|
187
|
+
export function promotePseudoHeadings(blocks: Block[]): Block[] {
|
|
188
|
+
const hasRealHeadings = blocks.filter((b) => b.kind === "heading" && /\p{L}{3}/u.test(b.text)).length >= 2
|
|
189
|
+
const out: Block[] = []
|
|
190
|
+
for (const block of blocks) {
|
|
191
|
+
if (block.kind === "heading") {
|
|
192
|
+
if (/\p{L}/u.test(block.text)) out.push(block)
|
|
193
|
+
continue
|
|
194
|
+
}
|
|
195
|
+
if (!hasRealHeadings && block.kind === "paragraph") {
|
|
196
|
+
const plain = markdownToPlainText(block.markdown)
|
|
197
|
+
const match = NUMBERED_HEADING.exec(plain)
|
|
198
|
+
if (match && plain.split(/\s+/).length <= 10) {
|
|
199
|
+
const depth = match[1] ? match[1].split(".").length : 1
|
|
200
|
+
out.push({ kind: "heading", level: 1 + depth, text: plain })
|
|
201
|
+
continue
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
out.push(block)
|
|
205
|
+
}
|
|
206
|
+
return out
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Rejoin paragraphs a PDF broke mid-sentence. */
|
|
210
|
+
export function mergeBrokenParagraphs(paragraphs: string[]): string[] {
|
|
211
|
+
const merged: string[] = []
|
|
212
|
+
for (const paragraph of paragraphs) {
|
|
213
|
+
const previous = merged[merged.length - 1]
|
|
214
|
+
// Short lines (list items, labels) stay apart unless a word was hyphenated across them.
|
|
215
|
+
const longEnough = previous !== undefined && (previous.split(/\s+/).length >= 6 || previous.endsWith("-"))
|
|
216
|
+
if (previous !== undefined && longEnough && !/[.!?:"'”’)\]*]$/.test(previous.trim()) && /^[a-z(“"‘']/.test(paragraph.trim())) {
|
|
217
|
+
merged[merged.length - 1] = `${previous.replace(/-$/, "")}${previous.endsWith("-") ? "" : " "}${paragraph}`
|
|
218
|
+
} else {
|
|
219
|
+
merged.push(paragraph)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return merged
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Pick the heading level that marks top-level sections: the shallowest level used at least twice. */
|
|
226
|
+
function sectionLevel(blocks: Block[]): number | null {
|
|
227
|
+
const counts = new Map<number, number>()
|
|
228
|
+
for (const block of blocks) {
|
|
229
|
+
if (block.kind === "heading" && !REFERENCES_HEADING.test(block.text) && !ABSTRACT_HEADING.test(block.text)) {
|
|
230
|
+
counts.set(block.level, (counts.get(block.level) ?? 0) + 1)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const levels = [...counts.entries()].filter(([, count]) => count >= 2).map(([level]) => level)
|
|
234
|
+
if (levels.length > 0) return Math.min(...levels)
|
|
235
|
+
// One section only: the level below a lone title heading.
|
|
236
|
+
const used = [...counts.keys()].sort((a, b) => a - b)
|
|
237
|
+
if (used.length >= 2) return used[1]
|
|
238
|
+
// A lone <h1> is the title; a lone deeper heading opens the one section.
|
|
239
|
+
return used[0] !== undefined && used[0] > 1 ? used[0] : null
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function emptySection(title: string): PaperSection {
|
|
243
|
+
return { title, summary: [], paragraphs: [] }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Build a `Paper` from extracted reading-mode HTML. */
|
|
247
|
+
export function htmlToPaper(html: string, meta: PaperMeta = {}): Paper {
|
|
248
|
+
const { document } = parseHTML(`<!doctype html><html><body>${html}</body></html>`)
|
|
249
|
+
const blocks = promotePseudoHeadings(collectBlocks(document.body as unknown as El))
|
|
250
|
+
const level = sectionLevel(blocks)
|
|
251
|
+
|
|
252
|
+
let title = meta.title?.trim() ?? ""
|
|
253
|
+
// A lone heading above the section level is the paper's title.
|
|
254
|
+
const titleHeading = blocks.find((b) => b.kind === "heading" && (level === null || b.level < level))
|
|
255
|
+
if (!title && titleHeading?.kind === "heading") title = titleHeading.text
|
|
256
|
+
|
|
257
|
+
const intro: string[] = []
|
|
258
|
+
const abstract: string[] = []
|
|
259
|
+
const references: string[] = []
|
|
260
|
+
const sections: PaperSection[] = []
|
|
261
|
+
let figure: PaperFigure | undefined
|
|
262
|
+
let mode: "intro" | "abstract" | "references" | "skip" | "section" = "intro"
|
|
263
|
+
let current: PaperSection | null = null
|
|
264
|
+
|
|
265
|
+
// Everything above the title heading is page chrome (menus, banners, dialogs).
|
|
266
|
+
const start = titleHeading ? blocks.indexOf(titleHeading) : 0
|
|
267
|
+
for (const block of blocks.slice(start)) {
|
|
268
|
+
if (block.kind === "heading") {
|
|
269
|
+
const plain = stripSectionNumber(block.text).replace(/[.:]$/, "")
|
|
270
|
+
if (REFERENCES_HEADING.test(plain)) {
|
|
271
|
+
mode = "references"
|
|
272
|
+
current = null
|
|
273
|
+
continue
|
|
274
|
+
}
|
|
275
|
+
if (ABSTRACT_HEADING.test(plain)) {
|
|
276
|
+
// Between the title and the abstract is the byline (authors, affiliations, notes).
|
|
277
|
+
if (mode === "intro") intro.length = 0
|
|
278
|
+
mode = "abstract"
|
|
279
|
+
continue
|
|
280
|
+
}
|
|
281
|
+
if (block === titleHeading) continue
|
|
282
|
+
if (level !== null && block.level === level) {
|
|
283
|
+
if (SKIP_HEADING.test(plain)) {
|
|
284
|
+
mode = "skip"
|
|
285
|
+
current = null
|
|
286
|
+
continue
|
|
287
|
+
}
|
|
288
|
+
current = emptySection(plain || block.text)
|
|
289
|
+
sections.push(current)
|
|
290
|
+
mode = "section"
|
|
291
|
+
continue
|
|
292
|
+
}
|
|
293
|
+
if (level !== null && block.level < level) continue
|
|
294
|
+
// A deeper heading: kept as a `### ` subheading inside the section.
|
|
295
|
+
if (SKIP_HEADING.test(plain)) {
|
|
296
|
+
if (mode === "section") mode = "skip"
|
|
297
|
+
continue
|
|
298
|
+
}
|
|
299
|
+
if (mode === "skip" && current) mode = "section"
|
|
300
|
+
if (mode === "section" && current) current.paragraphs.push(`### ${escapeMdxText(block.text)}`)
|
|
301
|
+
continue
|
|
302
|
+
}
|
|
303
|
+
if (block.kind === "figure") {
|
|
304
|
+
if (mode === "section" && current && !current.figure) current.figure = block.figure
|
|
305
|
+
else if (mode === "section" && current) current.paragraphs.push(``)
|
|
306
|
+
else if (!figure) figure = block.figure
|
|
307
|
+
continue
|
|
308
|
+
}
|
|
309
|
+
if (isNoise(block.markdown)) continue
|
|
310
|
+
// Diagram labels and table scraps from PDFs: a few words, no sentence.
|
|
311
|
+
const words = markdownToPlainText(block.markdown).split(/\s+/).length
|
|
312
|
+
if (mode !== "references" && !block.listItem && words < 4 && !/[.!?:"”)]$/.test(markdownToPlainText(block.markdown))) continue
|
|
313
|
+
if (mode === "references") references.push(block.markdown)
|
|
314
|
+
else if (mode === "abstract") abstract.push(block.markdown)
|
|
315
|
+
else if (mode === "section" && current) current.paragraphs.push(block.markdown)
|
|
316
|
+
else if (mode === "intro") intro.push(block.markdown)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// An abstract written inline: "**Abstract.** In this paper…" or "Abstract: …".
|
|
320
|
+
const inlineAbstract = abstract.length === 0 ? intro.findIndex((p) => /^(\*\*)?abstract\b/i.test(p)) : -1
|
|
321
|
+
if (inlineAbstract >= 0) {
|
|
322
|
+
// With no title tag, the first short line above the abstract is the title.
|
|
323
|
+
const firstLine = inlineAbstract > 0 ? markdownToPlainText(intro[0]) : ""
|
|
324
|
+
if (!title && firstLine && firstLine.split(/\s+/).length <= 20) title = firstLine
|
|
325
|
+
abstract.push(intro[inlineAbstract].replace(/^(\*\*)?abstract[.:]?(\*\*)?[.:—–-]?\s*/i, ""))
|
|
326
|
+
// Above the abstract is the title block and byline.
|
|
327
|
+
intro.splice(0, inlineAbstract + 1)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (sections.length === 0) {
|
|
331
|
+
// No headings to split on: cut the body into runs of a few paragraphs.
|
|
332
|
+
const body = mergeBrokenParagraphs(intro.splice(0))
|
|
333
|
+
for (let i = 0; i < body.length; i += PARAGRAPHS_PER_SECTION) {
|
|
334
|
+
const chunk = body.slice(i, i + PARAGRAPHS_PER_SECTION)
|
|
335
|
+
sections.push({ ...emptySection(titleFromParagraph(chunk[0]) || `Part ${sections.length + 1}`), paragraphs: chunk })
|
|
336
|
+
}
|
|
337
|
+
} else if (intro.some((p) => markdownToPlainText(p).split(/\s+/).length >= 25)) {
|
|
338
|
+
// Real prose before the first heading; short lines there are a byline.
|
|
339
|
+
sections.unshift({ ...emptySection("Introduction"), paragraphs: intro })
|
|
340
|
+
}
|
|
341
|
+
for (const section of sections) section.paragraphs = mergeBrokenParagraphs(section.paragraphs)
|
|
342
|
+
|
|
343
|
+
return {
|
|
344
|
+
title: title || titleFromParagraph(sections[0]?.paragraphs[0] ?? "") || "Untitled paper",
|
|
345
|
+
author: meta.author,
|
|
346
|
+
date: meta.date,
|
|
347
|
+
sourceUrl: meta.sourceUrl,
|
|
348
|
+
cite: meta.cite,
|
|
349
|
+
abstract: abstract.length > 0 ? mergeBrokenParagraphs(abstract).join(" ") : undefined,
|
|
350
|
+
figure,
|
|
351
|
+
sections: sections.filter((section) => section.paragraphs.length > 0 || section.figure),
|
|
352
|
+
references: mergeBrokenParagraphs(references).map((ref) => ref.replace(/^\\?\[\d+\\?\]\s*|^\d+\.\s+/, "")),
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** A short title from a paragraph's opening words, for sections that had none. */
|
|
357
|
+
export function titleFromParagraph(markdown: string): string {
|
|
358
|
+
const plain = markdownToPlainText(markdown)
|
|
359
|
+
const words = plain.split(/\s+/).slice(0, 7).join(" ").replace(/[.,;:!?]+$/, "")
|
|
360
|
+
return words ? `${words}${plain.split(/\s+/).length > 7 ? "…" : ""}` : ""
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Plain text or markdown → `Paper`. Markdown headings (`#`, `##`) split
|
|
365
|
+
* sections; blank lines split paragraphs. Used for pasted text and `.md`/`.txt`
|
|
366
|
+
* files.
|
|
367
|
+
*/
|
|
368
|
+
export function textToPaper(text: string, meta: PaperMeta = {}): Paper {
|
|
369
|
+
const html = text
|
|
370
|
+
.replace(/\r\n?/g, "\n")
|
|
371
|
+
.split(/\n{2,}/)
|
|
372
|
+
.map((chunk) => {
|
|
373
|
+
const trimmed = chunk.trim()
|
|
374
|
+
const heading = /^(#{1,6})\s+(.+)$/.exec(trimmed)
|
|
375
|
+
if (heading) return `<h${heading[1].length}>${escapeForHtml(heading[2])}</h${heading[1].length}>`
|
|
376
|
+
if (/^[-*]\s+/.test(trimmed)) {
|
|
377
|
+
return `<ul>${trimmed
|
|
378
|
+
.split(/\n(?=[-*]\s+)/)
|
|
379
|
+
.map((item) => `<li>${inlineMarkdownToHtml(item.replace(/^[-*]\s+/, ""))}</li>`)
|
|
380
|
+
.join("")}</ul>`
|
|
381
|
+
}
|
|
382
|
+
return trimmed ? `<p>${inlineMarkdownToHtml(trimmed)}</p>` : ""
|
|
383
|
+
})
|
|
384
|
+
.join("\n")
|
|
385
|
+
return htmlToPaper(html, meta)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function escapeForHtml(text: string): string {
|
|
389
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Enough inline markdown → HTML for `textToPaper` to keep bold, italics, links and `==marks==`. */
|
|
393
|
+
function inlineMarkdownToHtml(text: string): string {
|
|
394
|
+
return escapeForHtml(text)
|
|
395
|
+
.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, '<img src="$2" alt="$1">')
|
|
396
|
+
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2">$1</a>')
|
|
397
|
+
.replace(/==([^=]+)==/g, "<mark>$1</mark>")
|
|
398
|
+
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
|
399
|
+
.replace(/(^|[^*\w])\*([^*\n]+)\*(?!\w)/g, "$1<em>$2</em>")
|
|
400
|
+
}
|
package/src/html.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview `Paper` → HTML, for the reader widget and the standalone
|
|
3
|
+
* export.
|
|
4
|
+
*
|
|
5
|
+
* - `renderPaperBody` is the paper itself: title block, abstract, then each
|
|
6
|
+
* section with its figure, a Section Summary `<details>` and its numbered
|
|
7
|
+
* paragraphs, `==text==` rendered as `<mark class="debate-hl">`.
|
|
8
|
+
* - `renderReaderToolbar` is the Reader mode / Underlining / Voice bar the
|
|
9
|
+
* runtime (`reader-runtime.ts`) wires up.
|
|
10
|
+
* - `paperToHtml` wraps both, the stylesheet and the inlined runtime into one
|
|
11
|
+
* self-contained page that works offline from a file.
|
|
12
|
+
*
|
|
13
|
+
* @module html
|
|
14
|
+
*/
|
|
15
|
+
import { escapeHtml, isSubheading, markdownInlineToHtml, markdownToPlainText } from "./markdown"
|
|
16
|
+
import { sectionSlug } from "./mdx"
|
|
17
|
+
import { READER_RUNTIME_SOURCE } from "./reader-runtime"
|
|
18
|
+
import type { Paper, PaperFigure } from "./types"
|
|
19
|
+
|
|
20
|
+
export function figureHtml(figure: PaperFigure, number: number): string {
|
|
21
|
+
const caption = escapeHtml(figure.caption)
|
|
22
|
+
const img = `<img src="${escapeHtml(figure.src)}" alt="${caption || `Figure ${number}`}" loading="lazy" />`
|
|
23
|
+
return `<figure>${img}${caption ? `<figcaption>Figure ${number}: ${caption}</figcaption>` : ""}</figure>`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Numbered paragraphs, split into lists around `### ` subheadings; numbering
|
|
28
|
+
* continues across them. With `headingId`, each subheading gets an `id`.
|
|
29
|
+
*/
|
|
30
|
+
export function paragraphsHtml(paragraphs: string[], headingId?: (text: string) => string): string {
|
|
31
|
+
const out: string[] = []
|
|
32
|
+
let items: string[] = []
|
|
33
|
+
let n = 0
|
|
34
|
+
const flush = () => {
|
|
35
|
+
if (items.length > 0) out.push(`<ol class="ptw-paragraphs" start="${n - items.length + 1}">${items.join("")}</ol>`)
|
|
36
|
+
items = []
|
|
37
|
+
}
|
|
38
|
+
for (const p of paragraphs) {
|
|
39
|
+
if (isSubheading(p)) {
|
|
40
|
+
flush()
|
|
41
|
+
const id = headingId ? ` id="${escapeHtml(headingId(markdownToPlainText(p.slice(4))))}"` : ""
|
|
42
|
+
out.push(`<h3${id}>${markdownInlineToHtml(p.slice(4))}</h3>`)
|
|
43
|
+
} else {
|
|
44
|
+
n += 1
|
|
45
|
+
items.push(`<li><p>${markdownInlineToHtml(p)}</p></li>`)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
flush()
|
|
49
|
+
return out.join("")
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The Reader mode / Underlining / Voice toolbar. */
|
|
53
|
+
export function renderReaderToolbar(): string {
|
|
54
|
+
return `<div class="ptw-toolbar" role="toolbar" aria-label="Reading options">
|
|
55
|
+
<button type="button" data-ptw="reader" aria-pressed="false"><span aria-hidden="true">📖</span> <span data-ptw-label>Reader mode off</span></button>
|
|
56
|
+
<button type="button" data-ptw="underline" aria-pressed="true"><span aria-hidden="true" class="ptw-u">U</span> <span data-ptw-label>Underlining on</span></button>
|
|
57
|
+
<button type="button" data-ptw="voice" aria-pressed="false"><span aria-hidden="true">🔊</span> <span data-ptw-label>Voice</span></button>
|
|
58
|
+
<label class="ptw-rate">Speed <select data-ptw="rate"><option value="1">1×</option><option value="1.2" selected>1.2×</option><option value="1.5">1.5×</option><option value="2">2×</option></select></label>
|
|
59
|
+
</div>`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The paper's content (see the module doc). */
|
|
63
|
+
export function renderPaperBody(paper: Paper): string {
|
|
64
|
+
const out: string[] = []
|
|
65
|
+
out.push(`<header class="ptw-header"><h1>${escapeHtml(paper.title)}</h1>`)
|
|
66
|
+
if (paper.description) out.push(`<p class="ptw-description">${markdownInlineToHtml(paper.description)}</p>`)
|
|
67
|
+
const byline = [paper.author, paper.date].filter(Boolean).map((part) => escapeHtml(part!))
|
|
68
|
+
if (paper.sourceUrl) {
|
|
69
|
+
byline.push(`<a href="${escapeHtml(paper.sourceUrl)}" target="_blank" rel="noopener noreferrer">${escapeHtml(paper.sourceUrl.replace(/^https?:\/\//, ""))}</a>`)
|
|
70
|
+
}
|
|
71
|
+
if (byline.length > 0) out.push(`<p class="ptw-byline">${byline.join(" · ")}</p>`)
|
|
72
|
+
out.push("</header>")
|
|
73
|
+
if (paper.figure) out.push(figureHtml(paper.figure, 1))
|
|
74
|
+
if (paper.abstract) out.push(`<p class="ptw-abstract"><strong>Abstract.</strong> ${markdownInlineToHtml(paper.abstract)}</p>`)
|
|
75
|
+
if (paper.keywords?.length) out.push(`<p class="ptw-keywords"><em><strong>Keywords</strong>: ${escapeHtml(paper.keywords.join(", "))}</em></p>`)
|
|
76
|
+
|
|
77
|
+
let figureNumber = paper.figure ? 1 : 0
|
|
78
|
+
paper.sections.forEach((section, i) => {
|
|
79
|
+
if (section.part) out.push(`<h2 class="ptw-part">${escapeHtml(section.part)}</h2>`)
|
|
80
|
+
out.push(`<section class="ptw-section" id="${sectionSlug(section, i)}">`)
|
|
81
|
+
out.push(`<h2>${i + 1}. ${escapeHtml(section.title)}</h2>`)
|
|
82
|
+
if (section.description) out.push(`<p class="ptw-description">${markdownInlineToHtml(section.description)}</p>`)
|
|
83
|
+
if (section.figure) {
|
|
84
|
+
figureNumber += 1
|
|
85
|
+
out.push(figureHtml(section.figure, figureNumber))
|
|
86
|
+
}
|
|
87
|
+
if (section.summary.length > 0) {
|
|
88
|
+
out.push(
|
|
89
|
+
`<details class="ptw-summary" open><summary>Section Summary</summary><ol>${section.summary
|
|
90
|
+
.map((point) => `<li><strong>${markdownInlineToHtml(point.label)}:</strong> ${markdownInlineToHtml(point.text)}</li>`)
|
|
91
|
+
.join("")}</ol></details>`,
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
if (section.paragraphs.length > 0) out.push(paragraphsHtml(section.paragraphs))
|
|
95
|
+
out.push("</section>")
|
|
96
|
+
})
|
|
97
|
+
if (paper.references.length > 0) {
|
|
98
|
+
out.push(`<section class="ptw-section ptw-references" id="references"><h2>References</h2><ol>${paper.references.map((ref) => `<li>${markdownInlineToHtml(ref)}</li>`).join("")}</ol></section>`)
|
|
99
|
+
}
|
|
100
|
+
return out.join("\n")
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The contents list (hidden in Reader mode). */
|
|
104
|
+
export function renderToc(paper: Paper): string {
|
|
105
|
+
const items = paper.sections.map((section, i) => `<li><a href="#${sectionSlug(section, i)}">${i + 1}. ${escapeHtml(section.title)}</a></li>`)
|
|
106
|
+
if (paper.references.length > 0) items.push('<li><a href="#references">References</a></li>')
|
|
107
|
+
return `<nav class="ptw-toc" aria-label="Contents"><strong>Contents</strong><ol>${items.join("")}</ol></nav>`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Styles for the reader; scoped to `.ptw-paper`, light and dark. */
|
|
111
|
+
export const PAPER_READER_CSS = `
|
|
112
|
+
.ptw-paper{--ptw-bg:#fff;--ptw-fg:#1c1917;--ptw-muted:#78716c;--ptw-border:#e7e5e4;--ptw-accent:#2563eb;--ptw-mark:#fef08a;--ptw-reader-bg:#fbf7ef;
|
|
113
|
+
color:var(--ptw-fg);background:var(--ptw-bg);font:16px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif;display:grid;grid-template-columns:minmax(0,14rem) minmax(0,1fr);gap:2rem;padding:1rem;}
|
|
114
|
+
@media (prefers-color-scheme:dark){.ptw-paper{--ptw-bg:#0c0a09;--ptw-fg:#e7e5e4;--ptw-muted:#a8a29e;--ptw-border:#292524;--ptw-accent:#60a5fa;--ptw-mark:#854d0e;--ptw-reader-bg:#1c1917;}}
|
|
115
|
+
.ptw-paper *{box-sizing:border-box}
|
|
116
|
+
.ptw-toolbar{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;position:sticky;top:0;z-index:2;padding:.5rem 0;background:var(--ptw-bg);border-bottom:1px solid var(--ptw-border)}
|
|
117
|
+
.ptw-toolbar button,.ptw-toolbar select{font:inherit;font-size:.875rem;color:inherit;background:transparent;border:1px solid var(--ptw-border);border-radius:.5rem;padding:.3rem .7rem;cursor:pointer}
|
|
118
|
+
.ptw-toolbar button[aria-pressed="true"]{background:color-mix(in srgb,var(--ptw-accent) 15%,transparent);border-color:var(--ptw-accent)}
|
|
119
|
+
.ptw-u{text-decoration:underline;font-weight:700}
|
|
120
|
+
.ptw-rate{font-size:.875rem;color:var(--ptw-muted)}
|
|
121
|
+
.ptw-toc{position:sticky;top:3.5rem;align-self:start;font-size:.875rem;max-height:calc(100vh - 5rem);overflow:auto}
|
|
122
|
+
.ptw-toc ol{padding-left:0;list-style:none}.ptw-toc li{margin:.2rem 0}.ptw-toc a{color:inherit;text-decoration:none}.ptw-toc a:hover{color:var(--ptw-accent)}
|
|
123
|
+
.ptw-content{min-width:0;max-width:52rem}
|
|
124
|
+
.ptw-content h1{font-size:2rem;line-height:1.2;margin:.5rem 0}
|
|
125
|
+
.ptw-content h2{font-size:1.4rem;margin:2.5rem 0 .5rem}
|
|
126
|
+
.ptw-part{text-transform:uppercase;letter-spacing:.06em;font-size:1rem!important;color:var(--ptw-muted)}
|
|
127
|
+
.ptw-description,.ptw-byline{color:var(--ptw-muted)}
|
|
128
|
+
.ptw-content a{color:var(--ptw-accent)}
|
|
129
|
+
.ptw-content figure{margin:1.5rem 0}.ptw-content img{max-width:100%;height:auto;border-radius:.5rem}
|
|
130
|
+
.ptw-content figcaption{font-style:italic;color:var(--ptw-muted);font-size:.9rem;margin-top:.4rem}
|
|
131
|
+
.ptw-summary{border:1px solid var(--ptw-border);border-radius:.75rem;padding:.5rem 1rem;margin:1rem 0}
|
|
132
|
+
.ptw-summary summary{cursor:pointer;font-weight:600}
|
|
133
|
+
.ptw-paragraphs>li{margin:.9rem 0}.ptw-paragraphs p{margin:0}
|
|
134
|
+
.ptw-paper mark.debate-hl{background:transparent;color:inherit}
|
|
135
|
+
.ptw-paper[data-underline="on"] mark.debate-hl{background:var(--ptw-mark);text-decoration:underline;text-decoration-thickness:2px;text-underline-offset:2px;font-weight:600}
|
|
136
|
+
.ptw-paper [data-voice-reading]{outline:2px solid var(--ptw-accent);outline-offset:4px;border-radius:4px}
|
|
137
|
+
.ptw-paper[data-reader="on"]{grid-template-columns:minmax(0,1fr);background:var(--ptw-reader-bg)}
|
|
138
|
+
.ptw-paper[data-reader="on"] .ptw-toolbar{background:var(--ptw-reader-bg)}
|
|
139
|
+
.ptw-paper[data-reader="on"] .ptw-toc{display:none}
|
|
140
|
+
.ptw-paper[data-reader="on"] .ptw-content{margin:0 auto;max-width:40rem;font:1.15rem/1.8 Georgia,"Iowan Old Style","Times New Roman",serif}
|
|
141
|
+
@media (max-width:760px){.ptw-paper{grid-template-columns:minmax(0,1fr)}.ptw-toc{display:none}}
|
|
142
|
+
`
|
|
143
|
+
|
|
144
|
+
/** The reader markup: toolbar, contents and paper inside one `.ptw-paper` root. */
|
|
145
|
+
export function renderPaperReader(paper: Paper): string {
|
|
146
|
+
return `<div class="ptw-paper" data-underline="on" data-reader="off">
|
|
147
|
+
${renderReaderToolbar()}
|
|
148
|
+
${renderToc(paper)}
|
|
149
|
+
<article class="ptw-content">
|
|
150
|
+
${renderPaperBody(paper)}
|
|
151
|
+
</article>
|
|
152
|
+
</div>`
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** One self-contained HTML page: reader, styles and runtime inlined. */
|
|
156
|
+
export function paperToHtml(paper: Paper): string {
|
|
157
|
+
return `<!doctype html>
|
|
158
|
+
<html lang="en">
|
|
159
|
+
<head>
|
|
160
|
+
<meta charset="utf-8" />
|
|
161
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
162
|
+
<title>${escapeHtml(paper.title)}</title>
|
|
163
|
+
${paper.description ? `<meta name="description" content="${escapeHtml(markdownToPlainText(paper.description))}" />` : ""}
|
|
164
|
+
<style>body{margin:0;background:#fff}@media (prefers-color-scheme:dark){body{background:#0c0a09}}${PAPER_READER_CSS}</style>
|
|
165
|
+
</head>
|
|
166
|
+
<body>
|
|
167
|
+
${renderPaperReader(paper)}
|
|
168
|
+
<script>(${READER_RUNTIME_SOURCE})(document.querySelector(".ptw-paper"));</script>
|
|
169
|
+
</body>
|
|
170
|
+
</html>
|
|
171
|
+
`
|
|
172
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview extract-refdoc (formerly paper-to-web / refdoc).
|
|
3
|
+
*
|
|
4
|
+
* The refdoc format: one `.refdoc.html` file holding the whole document,
|
|
5
|
+
* which opens as a Fumadocs docs site (sidebar, contents, search,
|
|
6
|
+
* references) from a CDN-hosted runtime — see `refdoc.ts`.
|
|
7
|
+
*
|
|
8
|
+
* Any PDF, research paper, archive link, DOI or text → the Synergy Slayer
|
|
9
|
+
* paper format: numbered section pages with Section Summaries and `==card
|
|
10
|
+
* underlining==`, read with Reader mode, Underlining on/off and Voice. Plus
|
|
11
|
+
* AI outlines in that format from anything. Standalone: nothing here is
|
|
12
|
+
* mounted by the debate-ai.com site.
|
|
13
|
+
*
|
|
14
|
+
* The React widget is at `extract-refdoc/widget` and the web app
|
|
15
|
+
* handler at `extract-refdoc/server`; the CLI is `extract-refdoc`.
|
|
16
|
+
*
|
|
17
|
+
* @module extract-refdoc
|
|
18
|
+
*/
|
|
19
|
+
export type { Paper, PaperFigure, PaperSection, SummaryPoint } from "./types"
|
|
20
|
+
export { convertToPaper, type ConvertMode, type ConvertOptions } from "./pipeline"
|
|
21
|
+
export {
|
|
22
|
+
loadPaper,
|
|
23
|
+
normalizeSourceUrl,
|
|
24
|
+
isLinkInput,
|
|
25
|
+
isPdfBuffer,
|
|
26
|
+
extractWithExtractWebpage,
|
|
27
|
+
type Extractor,
|
|
28
|
+
type ExtractedSource,
|
|
29
|
+
type LoadOptions,
|
|
30
|
+
} from "./source"
|
|
31
|
+
export { htmlToPaper, textToPaper, stripSectionNumber, mergeBrokenParagraphs, type PaperMeta } from "./html-to-paper"
|
|
32
|
+
export { finishPaper, readOnlyUnderlined, summarizeSection, describeSection } from "./finish"
|
|
33
|
+
export { applyUnderlines, autoUnderline, stripUnderlines, underlinedRuns, splitSentences } from "./highlight"
|
|
34
|
+
export {
|
|
35
|
+
paperToMdxFiles,
|
|
36
|
+
paperToSingleMdx,
|
|
37
|
+
sectionToMdx,
|
|
38
|
+
indexToMdx,
|
|
39
|
+
referencesToMdx,
|
|
40
|
+
paperMeta,
|
|
41
|
+
slugify,
|
|
42
|
+
sectionSlug,
|
|
43
|
+
type MdxOptions,
|
|
44
|
+
} from "./mdx"
|
|
45
|
+
export { paperToHtml, figureHtml, paragraphsHtml, renderPaperBody, renderPaperReader, renderReaderToolbar, PAPER_READER_CSS } from "./html"
|
|
46
|
+
export { mountPaperReader, READER_RUNTIME_SOURCE, type PaperReaderHandle, type PaperReaderRuntimeOptions } from "./reader-runtime"
|
|
47
|
+
export {
|
|
48
|
+
createAnthropicGenerator,
|
|
49
|
+
enhancePaperWithAi,
|
|
50
|
+
enhanceSectionWithAi,
|
|
51
|
+
generateOutline,
|
|
52
|
+
paperToPlainText,
|
|
53
|
+
parseJsonReply,
|
|
54
|
+
DEFAULT_MODEL,
|
|
55
|
+
type TextGenerator,
|
|
56
|
+
type AnthropicGeneratorOptions,
|
|
57
|
+
type OutlineOptions,
|
|
58
|
+
} from "./ai"
|
|
59
|
+
export { markdownInlineToHtml, markdownToPlainText, escapeMdxText } from "./markdown"
|
|
60
|
+
export {
|
|
61
|
+
paperToRefdoc,
|
|
62
|
+
paperToRefdocDocument,
|
|
63
|
+
renderRefdocHtml,
|
|
64
|
+
parseRefdoc,
|
|
65
|
+
readRefdocFromDocument,
|
|
66
|
+
linkCitations,
|
|
67
|
+
refdocFileName,
|
|
68
|
+
REFDOC_CDN,
|
|
69
|
+
REFDOC_VERSION,
|
|
70
|
+
REFDOC_PACKAGE_VERSION,
|
|
71
|
+
OVERVIEW_ID,
|
|
72
|
+
type RefdocDocument,
|
|
73
|
+
type RefdocMeta,
|
|
74
|
+
type RefdocPage,
|
|
75
|
+
type RefdocHeading,
|
|
76
|
+
type RefdocRuntime,
|
|
77
|
+
type RenderRefdocOptions,
|
|
78
|
+
} from "./refdoc"
|