🩹 clean up markdown and crawling for Mintlify, ReadTheDocs

This commit is contained in:
Nate Sesti 2024-01-21 16:14:43 -08:00
parent 33eb24cb37
commit cfd5426e12
7 changed files with 151 additions and 56 deletions

View file

@ -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) => ({

View file

@ -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 {

View file

@ -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<string>) {
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<string>) {
}
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<string>();
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<string> {
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);

View file

@ -28,13 +28,14 @@ async function createDocsTable(db: Database<sqlite3.Database>) {
export async function retrieveDocs(
baseUrl: string,
vector: number[]
vector: number[],
nRetrieve: number
): Promise<Chunk[]> {
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();

View file

@ -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);

View file

@ -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. '<a href="#section-name" title="Link to this heading">#</a>')
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<string | undefined> {
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");
}
}

View file

@ -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