Skip to content

Commit 9e6588c

Browse files
committed
Improve code block extraction and normalization in website fetcher
- it's neem repported that code blocks on a website with such html [Pasted text] are ommited - it's been reported that code blocks on a website with such html are ommited [Pasted text] 
1 parent 5c94afd commit 9e6588c

1 file changed

Lines changed: 38 additions & 3 deletions

File tree

‎apps/editor/src/views/prompt/backend/utils/website-fetcher.ts‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,16 +46,14 @@ const create_turndown_service = () => {
4646
)
4747
}
4848
})
49-
// Convert math blocks to markdown
5049
turndown_service.addRule('multiplemath', {
5150
filter(node) {
5251
return (
5352
node.nodeName == 'SPAN' &&
5453
(node as HTMLElement).classList.contains('katex-display')
55-
) // Check if it's a display math block that centers equation
54+
)
5655
},
5756
replacement(_, node) {
58-
// "<annotation>" element holds expression string, right for markdown
5957
const annotation = (node as HTMLElement).querySelector(
6058
'annotation'
6159
)?.textContent
@@ -122,6 +120,43 @@ export const fetch_and_save_website = async (
122120
const dom = new JSDOM(clean_html, { url })
123121
const doc = dom.window.document
124122

123+
doc.querySelectorAll('pre').forEach((pre) => {
124+
const code = pre.querySelector('code')
125+
const language = (code?.className.match(/language-(\S+)/) ||
126+
pre.className.match(/language-(\S+)/) || [null, ''])[1]
127+
128+
let text = ''
129+
const lines = pre.querySelectorAll('.line')
130+
if (lines.length > 0) {
131+
text = Array.from(lines)
132+
.map((l) => l.textContent)
133+
.join('\n')
134+
} else {
135+
text = pre.textContent || ''
136+
}
137+
138+
pre.innerHTML = ''
139+
const new_code = doc.createElement('code')
140+
if (language) {
141+
new_code.className = `language-${language}`
142+
}
143+
new_code.textContent = text
144+
pre.appendChild(new_code)
145+
146+
let current: Element = pre
147+
while (
148+
current.parentElement &&
149+
current.parentElement.tagName == 'DIV' &&
150+
current.parentElement.textContent?.trim() == pre.textContent?.trim()
151+
) {
152+
current = current.parentElement
153+
}
154+
if (current !== pre && current.parentElement) {
155+
current.parentElement.insertBefore(pre, current)
156+
current.remove()
157+
}
158+
})
159+
125160
if (isProbablyReaderable(doc)) {
126161
const reader = new Readability(doc, { keepClasses: true })
127162
const article = reader.parse()

0 commit comments

Comments
 (0)