Refactored web crawling code for document indexing. The updated code uses a breadth-first search, filters out specific paths, and ensures that websites are not downloaded twice.

This commit is contained in:
Jason Jacobs 2024-03-13 00:15:35 -07:00
parent 9c290e9db8
commit e8d126c6ee
6 changed files with 129 additions and 215 deletions

View file

@ -2,13 +2,14 @@ import { Readability } from "@mozilla/readability";
import { Chunk } from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
import { PageData } from "./crawl"
type ArticleComponent = {
export type ArticleComponent = {
title: string;
body: string;
};
type Article = {
export type Article = {
url: string;
subpath: string;
title: string;
@ -132,6 +133,7 @@ export async function stringToArticle(
}
let article_components = await extractTitlesAndBodies(article.content);
return {
url,
subpath,
@ -144,20 +146,11 @@ export async function stringToArticle(
}
}
export async function urlToArticle(
subpath: string,
baseUrl: URL,
export async function pageToArticle(
page: PageData
): Promise<Article | undefined> {
const url = new URL(subpath, baseUrl);
try {
const response = await fetch(url.toString());
if (!response.ok) {
return undefined;
}
const htmlContent = await response.text();
return stringToArticle(baseUrl.toString(), htmlContent, subpath);
return stringToArticle(page.url, page.html, page.path);
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;

View file

@ -1,13 +1,12 @@
import { Octokit } from "@octokit/rest";
import cheerio from "cheerio";
import fetch from "node-fetch";
// const HCCrawler = require("headless-chrome-crawler");
import { URL } from 'url';
const IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
// ReadTheDocs
"genindex",
"py-modindex",
"search.html",
@ -19,70 +18,6 @@ const IGNORE_PATHS_ENDING_IN = [
const GITHUB_PATHS_TO_TRAVERSE = ["/blob/", "/tree/"];
function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
if (pathname.includes("#")) {
pathname = pathname.slice(0, pathname.indexOf("#"));
}
if (pathname.endsWith("/")) {
pathname = pathname.slice(0, -1);
}
if (baseUrl.hostname === "github.com") {
if (
pathname.split("/").length > 3 &&
!GITHUB_PATHS_TO_TRAVERSE.some((path) => pathname.includes(path))
)
return true;
return false;
}
if (IGNORE_PATHS_ENDING_IN.some((path) => pathname.endsWith(path)))
return true;
return false;
}
async function* crawlLinks(
pathname: string,
baseUrl: URL,
visited: Set<string>,
): AsyncGenerator<number> {
if (visited.has(pathname) || shouldFilterPath(pathname, baseUrl)) {
return;
}
visited.add(pathname);
yield visited.size;
const response = await fetch(new URL(pathname, baseUrl));
const text = await response.text();
const $ = cheerio.load(text);
const children: string[] = [];
$("a").each((_, element) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, baseUrl);
if (
parsedUrl.hostname === baseUrl.hostname &&
!visited.has(parsedUrl.pathname)
// parsedUrl.pathname.startsWith(baseUrl.pathname)
) {
children.push(parsedUrl.pathname);
}
});
await Promise.all(
children.map(async (child) => {
for await (const _ of crawlLinks(child, baseUrl, visited)) {
}
}),
);
yield visited.size;
}
async function crawlGithubRepo(baseUrl: URL) {
const octokit = new Octokit({
auth: undefined,
@ -111,112 +46,115 @@ async function crawlGithubRepo(baseUrl: URL) {
const paths = tree.data.tree
.filter(
(file) => file.type === "blob" && file.path?.endsWith(".md"),
// ||
// file.path?.endsWith(".rst") ||
// file.path?.split("/").includes("documentation") ||
// file.path?.split("/").includes("docs") ||
// file.path?.split("/").includes("doc") ||
// file.path?.split("/").includes("examples") ||
// file.path?.split("/").includes("example")
)
.map((file) => baseUrl.pathname + "/tree/main/" + file.path);
return paths;
}
export async function* crawlSubpages(
baseUrl: URL,
): AsyncGenerator<number, string[]> {
// Special case for GitHub repos
if (baseUrl.hostname === "github.com") {
return crawlGithubRepo(baseUrl);
}
// First, check if the parent of the path redirects to the same page
if (baseUrl.pathname.endsWith("/")) {
baseUrl.pathname = baseUrl.pathname.slice(0, -1);
}
let realBaseUrl = new URL(baseUrl);
while (true) {
let parentUrl = new URL(realBaseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");
if (
parentUrl.pathname === realBaseUrl.pathname ||
parentUrl.pathname === ""
) {
break;
async function getLinksFromUrl(url: string, path: string) {
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
if (error instanceof Error && error.message.includes('maximum redirect')) {
console.error('Maximum redirect reached for: ', location.toString());
return {
html: '',
links: []
};
} else {
console.error(error);
return {
html: '',
links: []
};
}
}
const response = await fetch(parentUrl);
const redirected = response.url.toString() === baseUrl.toString() + "/";
if (!redirected) {
break;
}
realBaseUrl = parentUrl;
}
const visited = new Set<string>();
for await (const count of crawlLinks(
realBaseUrl.pathname || "/",
realBaseUrl,
visited,
)) {
yield count;
}
return [...visited];
const html = await response.text();
let links: string[] = [];
if (url.includes("github.com")) {
return {
html,
links
};
}
const $ = cheerio.load(html);
$('a').each((_, element) => {
const link = $(element).attr('href');
if (link) {
const fullUrl = new URL(link, url);
if (fullUrl.pathname.startsWith(path)) {
links.push(fullUrl.pathname);
}
}
});
links = [...new Set(links)].filter(link => {
return !link.includes('#') && !IGNORE_PATHS_ENDING_IN.some(ending => link.endsWith(ending));
});
return {
html,
links
};
}
// class NoEscapeTurndownService extends TurndownService {
// escape(str: string): string {
// return str;
// }
// }
function splitUrl(url: URL) {
const baseUrl = `${url.protocol}//${url.hostname}`;
const basePath = url.pathname;
return {
baseUrl,
basePath
};
}
// async function convertURLToMarkdown(url: string): Promise<string> {
// try {
// const response = await fetch(url);
// const htmlContent = await response.text();
// const turndown = new NoEscapeTurndownService({
// codeBlockStyle: "fenced",
// headingStyle: "atx",
// }).use([turndownPluginGfm.tables, turndownPluginGfm.strikethrough]);
// const markdown = turndown.turndown(htmlContent);
// return markdown;
// } catch (err) {
// console.error(err);
// throw new Error("Error converting URL to markdown");
// }
// }
export type PageData = {
url: string;
path: string;
html: string;
};
export async function* crawlPage(url: URL): AsyncGenerator<PageData> {
const { baseUrl, basePath } = splitUrl(url);
let paths: string[] = [basePath];
// convertURLToMarkdown("https://python-socketio.readthedocs.io/en/stable").then(
// (md) => {
// console.log(md);
// }
// );
if (url.hostname === "github.com") {
const githubLinks = await crawlGithubRepo(url);
paths = [...paths, ...githubLinks];
}
let visited = new Set<string>();
const url = new URL("https://python-socketio.readthedocs.io/en/stable");
const url2 = new URL("https://platform.openai.com/docs/api-reference");
// crawlLinks(url.pathname, url, visited).then(() => {
// console.log(visited);
// });
let index = 0;
// async function hcCrawlLinks() {
// const results: any[] = [];
// const crawler = await HCCrawler.launch({
// // Function to be evaluated in browsers
// evaluatePage: () => ({
// title: $("title").text(),
// }),
// // Function to be called with evaluated results from browsers
// onSuccess: (result: any) => {
// console.log(result);
// results.push(result.url);
// },
// });
// // Queue a request
// await crawler.queue(url.toString());
// await crawler.onIdle(); // Resolved when no queue is left
// await crawler.close(); // Close the crawler
while (index < paths.length) {
const promises = paths.slice(index, index + 50).map(path => getLinksFromUrl(baseUrl, path));
// return results;
// }
const results = await Promise.all(promises);
for (const {html, links} of results) {
if (html !== '') {
yield {
url: url.toString(),
path: paths[index],
html: html
};
}
for (let link of links) {
if (!paths.includes(link)) {
paths.push(link);
}
}
index++;
}
paths = paths.filter(path => results.some(result => result.html !== '' && result.links.includes(path)));
}
}

View file

@ -140,3 +140,13 @@ export async function listDocs(): Promise<
const docs = db.all(`SELECT title, baseUrl FROM docs`);
return docs;
}
export async function hasDoc(baseUrl: string) {
const db = await open({
filename: getDocsSqlitePath(),
driver: sqlite3.Database,
});
await createDocsTable(db);
const doc = await db.get(`SELECT title FROM docs WHERE baseUrl =?`, baseUrl);
return!!doc;
}

View file

@ -4,17 +4,16 @@ import {
IndexingProgressUpdate,
} from "../..";
import { crawlSubpages } from "./crawl";
import { addDocs, listDocs } from "./db";
import { urlToArticle, chunkArticle } from "./article";
import { crawlPage } from "./crawl";
import { addDocs, hasDoc } from "./db";
import { pageToArticle, chunkArticle, Article } from "./article";
export async function* indexDocs(
title: string,
baseUrl: URL,
embeddingsProvider: EmbeddingsProvider,
): AsyncGenerator<IndexingProgressUpdate> {
const existingDocs = await listDocs();
if (existingDocs.find((doc) => doc.baseUrl === baseUrl.toString())) {
if (await hasDoc(baseUrl.toString())) {
yield {
progress: 1,
desc: "Already indexed",
@ -27,36 +26,26 @@ export async function* indexDocs(
desc: "Finding subpages",
};
const subpathGenerator = crawlSubpages(baseUrl);
let { value, done } = await subpathGenerator.next();
while (true) {
if (done) {
break;
}
const articles: Article[] = [];
for await (const page of crawlPage(baseUrl)) {
const article = await pageToArticle(page);
if (!article) continue;
articles.push(article);
yield {
progress: 0,
desc: `Finding subpages (${value})`,
desc: `Finding subpages (${page.path})`,
};
const next = await subpathGenerator.next();
value = next.value;
done = next.done;
}
let subpaths = value as string[];
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
let articles = await Promise.all(
subpaths.map(subpath => urlToArticle(subpath, baseUrl)),
);
for (const article of articles) {
if (!article) continue;
yield {
progress: Math.max(1, Math.floor(100 / (subpaths.length + 1))),
progress: Math.max(1, Math.floor(100 / (articles.length + 1))),
desc: `${article.subpath}`,
};

11
core/package-lock.json generated
View file

@ -55,7 +55,6 @@
"@types/uuid": "^9.0.7",
"esbuild": "^0.19.11",
"jest": "^29.7.0",
"tree-sitter-cli": "^0.21.0",
"ts-jest": "^29.1.1"
}
},
@ -9575,16 +9574,6 @@
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
"node_modules/tree-sitter-cli": {
"version": "0.21.0",
"resolved": "https://registry.npmjs.org/tree-sitter-cli/-/tree-sitter-cli-0.21.0.tgz",
"integrity": "sha512-wA7wT5724fNQW82XDH6zT6ZcYonjrAKLCHHuhLsPcAKULrhp3rNuMvlgBdB5FUBvmjHNhtTZF/qpHenMoRJPBw==",
"dev": true,
"hasInstallScript": true,
"bin": {
"tree-sitter": "cli.js"
}
},
"node_modules/tree-sitter-wasms": {
"version": "0.1.6",
"license": "Unlicense"

View file

@ -5264,11 +5264,6 @@ tr46@~0.0.3:
resolved "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz"
integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==
tree-sitter-cli@^0.21.0:
version "0.21.0"
resolved "https://registry.npmjs.org/tree-sitter-cli/-/tree-sitter-cli-0.21.0.tgz"
integrity sha512-wA7wT5724fNQW82XDH6zT6ZcYonjrAKLCHHuhLsPcAKULrhp3rNuMvlgBdB5FUBvmjHNhtTZF/qpHenMoRJPBw==
tree-sitter-wasms@^0.1.6:
version "0.1.6"