From cfd5426e12c44101ea547da1e108b87672f11010 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 21 Jan 2024 16:14:43 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=A9=B9=20clean=20up=20markdown=20and=20cr?= =?UTF-8?q?awling=20for=20Mintlify,=20ReadTheDocs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/context/providers/DocsContextProvider.ts | 8 ++- core/indexing/chunk/markdown.ts | 33 ++++++---- core/indexing/docs/crawl.ts | 44 +++++++------ core/indexing/docs/db.ts | 5 +- core/indexing/docs/index.ts | 21 +++++-- core/indexing/docs/urlToMarkdown.ts | 61 +++++++++++++++++++ extensions/vscode/src/activation/activate.ts | 35 +++++------ 7 files changed, 151 insertions(+), 56 deletions(-) create mode 100644 core/indexing/docs/urlToMarkdown.ts diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index cf681a6c1..7422e1579 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -25,7 +25,13 @@ class DocsContextProvider extends BaseContextProvider { const embeddingsProvider = new TransformersJsEmbeddingsProvider(); const [vector] = await embeddingsProvider.embed([extras.fullInput]); - const chunks = await retrieveDocs(query, vector); + const chunks = await retrieveDocs( + query, + vector, + this.options?.nRetrieve || 15 + ); + + console.log(chunks); return [ ...chunks.map((chunk) => ({ diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index 78031196b..9a7becd3d 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -2,8 +2,11 @@ import { ChunkWithoutID } from "../.."; import { countTokens } from "../../llm/countTokens"; import { basicChunker } from "./basic"; -function cleanFragment(fragment: string): string { - let originalFragment = fragment; +function cleanFragment(fragment: string | undefined): string | undefined { + if (!fragment) { + return undefined; + } + // Remove leading and trailing whitespaces fragment = fragment.trim(); @@ -22,12 +25,14 @@ function cleanFragment(fragment: string): string { // Replace spaces with hyphens fragment = fragment.replace(/\s+/g, "-"); - console.log(`Fragment ${originalFragment} -> ${fragment}`); return fragment; } -function cleanHeader(header: string): string { - let originalHeader = header; +function cleanHeader(header: string | undefined): string | undefined { + if (!header) { + return undefined; + } + // Remove leading and trailing whitespaces header = header.trim(); @@ -40,10 +45,13 @@ function cleanHeader(header: string): string { // Remove all special characters except alphanumeric, hyphen, space, and underscore header = header.replace(/[^\w\d-\s]/g, "").trim(); - console.log(`Header ${originalHeader} -> ${header}`); return header; } +function findHeader(lines: string[]): string | undefined { + return lines.find((line) => line.startsWith("#"))?.split("# ")[1]; +} + export async function* markdownChunker( content: string, maxChunkSize: number, @@ -71,9 +79,10 @@ export async function* markdownChunker( for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith(h) || i === 0) { if (currentSection.length) { + const isHeader = currentSection[0].startsWith(h); sections.push({ - header: currentSection[0], - content: currentSection.slice(1).join("\n"), + header: isHeader ? currentSection[0] : findHeader(currentSection), + content: currentSection.slice(isHeader ? 1 : 0).join("\n"), startLine: currentSectionStartLine, endLine: currentSectionStartLine + currentSection.length, }); @@ -86,9 +95,10 @@ export async function* markdownChunker( } if (currentSection.length) { + const isHeader = currentSection[0].startsWith(h); sections.push({ - header: currentSection[0], - content: currentSection.slice(1).join("\n"), + header: isHeader ? currentSection[0] : findHeader(currentSection), + content: currentSection.slice(isHeader ? 1 : 0).join("\n"), startLine: currentSectionStartLine, endLine: currentSectionStartLine + currentSection.length, }); @@ -97,7 +107,8 @@ export async function* markdownChunker( for (const section of sections) { for await (const chunk of markdownChunker( section.content, - maxChunkSize - countTokens(section.header, "gpt-4"), + maxChunkSize - + (section.header ? countTokens(section.header, "gpt-4") : 0), hLevel + 1 )) { yield { diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts index 58fbfe09f..9570b86d0 100644 --- a/core/indexing/docs/crawl.ts +++ b/core/indexing/docs/crawl.ts @@ -1,19 +1,27 @@ import cheerio from "cheerio"; import fetch from "node-fetch"; -import { NodeHtmlMarkdown } from "node-html-markdown"; // const HCCrawler = require("headless-chrome-crawler"); const IGNORE_PATHS_ENDING_IN = [ "favicon.ico", "robots.txt", ".rst.txt", - // Sphinx documentation + "index.html", // So as not to duplicate with "/" + // ReadTheDocs "genindex", "py-modindex", - "/en/search", + "search.html", + "search", + "genindex.html", + "changelog", + "changelog.html", ]; function shouldFilterPath(pathname: string): boolean { + if (pathname.includes("#")) { + pathname = pathname.slice(0, pathname.indexOf("#")); + } + if (pathname.endsWith("/")) { pathname = pathname.slice(0, -1); } @@ -42,7 +50,8 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set) { const parsedUrl = new URL(href, baseUrl); if ( parsedUrl.hostname === baseUrl.hostname && - !visited.has(parsedUrl.pathname) + !visited.has(parsedUrl.pathname) && + parsedUrl.pathname.startsWith(baseUrl.pathname) ) { children.push(parsedUrl.pathname); } @@ -54,8 +63,19 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set) { } export async function crawlSubpages(baseUrl: URL) { + // First, check if the parent of the path redirects to the same page + const parentUrl = new URL(baseUrl); + parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/"); + const response = await fetch(parentUrl); + + let useParent = response.url === baseUrl.toString(); + const visited = new Set(); - await crawlLinks(baseUrl.pathname || "/", baseUrl, visited); + await crawlLinks( + (useParent ? parentUrl.pathname : baseUrl.pathname) || "/", + baseUrl, + visited + ); return [...visited]; } @@ -81,20 +101,6 @@ export async function crawlSubpages(baseUrl: URL) { // } // } -const nhm = new NodeHtmlMarkdown({}, undefined, undefined); - -export async function convertURLToMarkdown(url: URL): Promise { - try { - const response = await fetch(url); - const htmlContent = await response.text(); - const markdown = nhm.translate(htmlContent).trimEnd(); - return markdown; - } catch (err) { - console.error(err); - throw new Error("Error converting URL to markdown"); - } -} - // convertURLToMarkdown("https://python-socketio.readthedocs.io/en/stable").then( // (md) => { // console.log(md); diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts index 38751625d..760fc0f87 100644 --- a/core/indexing/docs/db.ts +++ b/core/indexing/docs/db.ts @@ -28,13 +28,14 @@ async function createDocsTable(db: Database) { export async function retrieveDocs( baseUrl: string, - vector: number[] + vector: number[], + nRetrieve: number ): Promise { const lance = await lancedb.connect(getLanceDbPath()); const table = await lance.openTable(DOCS_TABLE_NAME); const docs: LanceDbDocsRow[] = await table .search(vector) - .limit(20) + .limit(nRetrieve) .where(`baseUrl = '${baseUrl}'`) .execute(); diff --git a/core/indexing/docs/index.ts b/core/indexing/docs/index.ts index 076c42283..7b147dcdd 100644 --- a/core/indexing/docs/index.ts +++ b/core/indexing/docs/index.ts @@ -6,8 +6,9 @@ import { } from "../.."; import { MAX_CHUNK_SIZE } from "../../llm/constants"; import { markdownChunker } from "../chunk/markdown"; -import { convertURLToMarkdown, crawlSubpages } from "./crawl"; +import { crawlSubpages } from "./crawl"; import { addDocs, listDocs } from "./db"; +import { convertURLToMarkdown } from "./urlToMarkdown"; export async function* indexDocs( title: string, @@ -28,15 +29,27 @@ export async function* indexDocs( desc: "Finding subpages", }; - const subpaths = await crawlSubpages(baseUrl); + let subpaths = await crawlSubpages(baseUrl); console.log("Found subpaths", subpaths); const chunks: Chunk[] = []; const embeddings: number[][] = []; - const markdownForSubpaths = await Promise.all( + let markdownForSubpaths = await Promise.all( subpaths.map((subpath) => convertURLToMarkdown(new URL(subpath, baseUrl))) ); + // Filter out undefineds + let filteredSubpaths: string[] = []; + let filteredMarkdown: string[] = []; + for (let i = 0; i < subpaths.length; i++) { + if (markdownForSubpaths[i]) { + filteredSubpaths.push(subpaths[i]); + filteredMarkdown.push(markdownForSubpaths[i]!); + } + } + subpaths = filteredSubpaths; + markdownForSubpaths = filteredMarkdown; + for (let i = 0; i < subpaths.length; i++) { const subpath = subpaths[i]; yield { @@ -44,7 +57,7 @@ export async function* indexDocs( desc: `${subpath}`, }; - const markdown = markdownForSubpaths[i]; + const markdown = markdownForSubpaths[i]!; const markdownChunks: ChunkWithoutID[] = []; for await (const chunk of markdownChunker(markdown, MAX_CHUNK_SIZE, 0)) { markdownChunks.push(chunk); diff --git a/core/indexing/docs/urlToMarkdown.ts b/core/indexing/docs/urlToMarkdown.ts new file mode 100644 index 000000000..ca98bd873 --- /dev/null +++ b/core/indexing/docs/urlToMarkdown.ts @@ -0,0 +1,61 @@ +import { NodeHtmlMarkdown, PostProcessResult } from "node-html-markdown"; + +const nhm = new NodeHtmlMarkdown( + {}, + { + a: { + postprocess: (ctx) => { + if (ctx.node.tagName === "A") { + // Remove sections links (e.g. '#') + if (ctx.content.length <= 1) { + return PostProcessResult.RemoveNode; + } + } + return ctx.content; + }, + }, + }, + undefined +); + +const STRIP_BEFORE = ["\n# "]; +const STRIP_AFTER_AND_INCLUDING = ["Was this page helpful?"]; + +export async function convertURLToMarkdown( + url: URL +): Promise { + try { + const response = await fetch(url); + + if (!response.ok) { + return undefined; + } + + const htmlContent = await response.text(); + let markdown = nhm.translate(htmlContent).trimEnd(); + + // Check for 404 + if (markdown.includes("404 Not Found")) { + return undefined; + } + + // Strip above and below certain phrases + STRIP_BEFORE.forEach((phrase) => { + const index = markdown.indexOf(phrase); + if (index !== -1) { + markdown = markdown.slice(index); + } + }); + STRIP_AFTER_AND_INCLUDING.forEach((phrase) => { + const index = markdown.lastIndexOf(phrase); + if (index !== -1) { + markdown = markdown.slice(0, index); + } + }); + + return markdown; + } catch (err) { + console.error(err); + throw new Error("Error converting URL to markdown"); + } +} diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 8ea4e3207..d351601c6 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -1,4 +1,3 @@ -import { indexDocs } from "core/indexing/docs"; import { getTsConfigPath } from "core/util/paths"; import * as fs from "fs"; import path from "path"; @@ -7,10 +6,8 @@ import * as vscode from "vscode"; import { registerAllCommands } from "../commands"; import IdeProtocolClient from "../continueIdeClient"; import { ContinueGUIWebviewViewProvider } from "../debugPanel"; -import { VsCodeIde } from "../ideProtocol"; import registerQuickFixProvider from "../lang-server/codeActions"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; -import { configHandler } from "../loadConfig"; import { vsCodeIndexCodebase } from "../util/indexCodebase"; import { getExtensionUri } from "../util/vscode"; import { setupInlineTips } from "./inlineTips"; @@ -94,24 +91,24 @@ export async function activateExtension(context: vscode.ExtensionContext) { startProxy(); vsCodeIndexCodebase(ideProtocolClient.getWorkspaceDirectories()); - (async () => { - const defaultDocsPages = [ - ["Socket.IO", "https://python-socketio.readthedocs.io/en/stable"], - // ["Flask", "https://flask.palletsprojects.com/en/2.0.x/"], - ]; + // (async () => { + // const defaultDocsPages = [ + // ["Socket.IO", "https://python-socketio.readthedocs.io/en/stable"], + // // ["Flask", "https://flask.palletsprojects.com/en/2.0.x/"], + // ]; - const config = await configHandler.loadConfig(new VsCodeIde()); + // const config = await configHandler.loadConfig(new VsCodeIde()); - defaultDocsPages.forEach(async ([title, url]) => { - for await (const update of indexDocs( - title, - new URL(url), - config.embeddingsProvider - )) { - console.log(update.progress, update.desc); - } - }); - })(); + // defaultDocsPages.forEach(async ([title, url]) => { + // for await (const update of indexDocs( + // title, + // new URL(url), + // config.embeddingsProvider + // )) { + // console.log(update.progress, update.desc); + // } + // }); + // })(); try { // Add icon theme for .continueignore