finish docscrawler

This commit is contained in:
Test 2024-08-22 18:53:04 -07:00
parent b9b58e23fc
commit 4edae01a90
6 changed files with 270 additions and 250 deletions

View file

@ -27,7 +27,7 @@ import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { streamDiffLines } from "./util/verticalEdit";
import { verifyOrInstallChromium } from "./indexing/docs/crawl";
import DocsCrawler from "./indexing/docs/DocsCrawler";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -169,7 +169,7 @@ export class Core {
);
try {
verifyOrInstallChromium();
DocsCrawler.verifyOrInstallChromium();
} catch (err) {
console.debug(`Failed to install Chromium: ${err}`);
}

View file

@ -1,4 +1,4 @@
import { crawl, PageData } from "./crawl";
import DocsCrawler, { type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
// Temporary workaround until we have better caching of Chromium
@ -15,8 +15,11 @@ describe.skip("crawl", () => {
let crawlResults: PageData[];
beforeAll(async () => {
const docsCrawler = new DocsCrawler(new URL(repoUrl));
crawlResults = [];
for await (const page of crawl(new URL(repoUrl))) {
for await (const page of docsCrawler.crawl()) {
crawlResults.push(page);
}
}, TIMEOUT);
@ -65,8 +68,12 @@ describe.skip("crawl", () => {
for (const site of TEST_SITES) {
const crawlResults: PageData[] = [];
const docsCrawler = new DocsCrawler(
new URL(site),
NUM_PAGES_TO_CRAWL,
);
for await (const page of crawl(new URL(site), NUM_PAGES_TO_CRAWL)) {
for await (const page of docsCrawler.crawl()) {
crawlResults.push(page);
}
@ -94,7 +101,9 @@ describe.skip("crawl", () => {
let pageFound = false;
try {
for await (const page of crawl(new URL(url), 1)) {
const docsCrawler = new DocsCrawler(new URL(url), 1);
for await (const page of docsCrawler.crawl()) {
if (page.url === url) {
pageFound = true;
break;

View file

@ -0,0 +1,249 @@
import { Octokit } from "@octokit/rest";
import { URL } from "node:url";
import { getChromiumPath, getContinueUtilsPath } from "../../util/paths";
import { Page } from "puppeteer";
// @ts-ignore
import PCR from "puppeteer-chromium-resolver";
import * as fs from "fs";
export type PageData = {
url: string;
path: string;
content: string;
};
export default class DocsCrawler {
LINK_GROUP_SIZE = 2; // Controls parallelization of crawler
GITHUB_HOST = "github.com";
MAX_REQUESTS_PER_CRAWL = 1000;
markdownRegex = new RegExp(/\.(md|mdx)$/);
octokit = new Octokit({
auth: undefined,
});
static PCR_CONFIG = {
downloadPath: getContinueUtilsPath(),
};
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
) {}
static verifyOrInstallChromium() {
if (!fs.existsSync(getChromiumPath())) {
PCR(DocsCrawler.PCR_CONFIG);
}
}
async *crawl(): AsyncGenerator<PageData> {
if (this.startUrl.host === this.GITHUB_HOST) {
yield* this.crawlGithubRepo();
} else {
yield* this.crawlSite();
}
}
private async getGithubRepoDefaultBranch(
owner: string,
repo: string,
): Promise<string> {
const repoInfo = await this.octokit.repos.get({
owner,
repo,
});
return repoInfo.data.default_branch;
}
private async getGitHubRepoPaths(
owner: string,
repo: string,
branch: string,
) {
const tree = await this.octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
},
);
const paths = tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
return paths;
}
private async getGithubRepoFileContent(
path: string,
owner: string,
repo: string,
) {
try {
const response = await this.octokit.repos.getContent({
owner,
repo,
path,
headers: {
Accept: "application/vnd.github.raw+json",
},
});
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
private async *crawlGithubRepo() {
console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`);
const urlStr = this.startUrl.toString();
const [_, owner, repo] = this.startUrl.pathname.split("/");
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
for await (const path of paths) {
const content = await this.getGithubRepoFileContent(path, owner, repo);
yield {
path,
url: urlStr,
content: content ?? "",
};
}
}
private stripHashFromUrl(urlStr: string) {
try {
let url = new URL(urlStr);
url.hash = "";
return url;
} catch (err) {
console.debug(`Failed to create URL: ${err}`);
return null;
}
}
private isValidHostAndPath(newUrl: URL, curUrl: URL) {
return (
newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host
);
}
private async getLinksFromPage(page: Page, curUrl: URL) {
const links = await page.$$eval("a", (links) => links.map((a) => a.href));
// This additional step is due to issues getting the URL module to work
// in an $$eval command
const cleanedLinks = links
.map(this.stripHashFromUrl)
.filter(
(newUrl) =>
newUrl !== null &&
this.isValidHostAndPath(newUrl, curUrl) &&
newUrl !== curUrl,
)
.map((newUrl) => (newUrl as URL).href);
const dedupedLinks = Array.from(new Set(cleanedLinks));
return dedupedLinks;
}
private async getLinkGroupsFromPage(page: Page, curUrl: URL) {
const links = await this.getLinksFromPage(page, curUrl);
const groups = links.reduce((acc, link, i) => {
const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE);
if (!acc[groupIndex]) {
acc.push([]);
}
acc[groupIndex].push(link);
return acc;
}, [] as string[][]);
return groups;
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
curRequestCount: number = 0,
): AsyncGenerator<PageData> {
if (curRequestCount >= this.maxRequestsPerCrawl) {
console.warn("Max requests per crawl reached. Stopping crawler.");
return;
}
if (visitedLinks.has(curUrl.toString())) {
console.warn("Already visited, skipping: ", curUrl.toString());
return;
}
console.debug(`Crawling page: ${curUrl.toString()}`);
await page.goto(curUrl.toString());
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
const requestCount = curRequestCount + 1;
visitedLinks.add(curUrl.toString());
yield {
path: curUrl.pathname,
url: curUrl.toString(),
content: htmlContent,
};
for (const linkGroup of linkGroups) {
for (const link of linkGroup) {
yield* this.crawlSitePages(
page,
new URL(link),
visitedLinks,
requestCount,
);
}
}
}
private async *crawlSite(): AsyncGenerator<PageData> {
console.debug(`Crawling site repo: ${this.startUrl}`);
const stats = await PCR(DocsCrawler.PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
],
executablePath: stats.executablePath,
});
const page = await browser.newPage();
try {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
} finally {
await browser.close();
}
}
}

View file

@ -22,7 +22,7 @@ import {
import { Telemetry } from "../../util/posthog";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider";
import { Article, chunkArticle, pageToArticle } from "./article";
import { crawl } from "./crawl";
import DocsCrawler from "./DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import {
downloadFromS3,
@ -172,7 +172,7 @@ export default class DocsService {
siteIndexingConfig: SiteIndexingConfig,
reIndex: boolean = false,
): AsyncGenerator<IndexingProgressUpdate> {
const { startUrl } = siteIndexingConfig;
const { startUrl, rootUrl } = siteIndexingConfig;
const embeddingsProvider = await this.getEmbeddingsProvider();
if (this.docsIndexingQueue.has(startUrl)) {
@ -202,8 +202,10 @@ export default class DocsService {
let processedPages = 0;
let maxKnownPages = 1;
const docsCrawler = new DocsCrawler(new URL(startUrl));
// Crawl pages and retrieve info as articles
for await (const page of crawl(new URL(startUrl))) {
for await (const page of docsCrawler.crawl()) {
processedPages++;
const article = pageToArticle(page);

View file

@ -2,7 +2,7 @@ import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { Chunk } from "../../";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
import { PageData } from "./crawl";
import { PageData } from "./DocsCrawler";
export type ArticleComponent = {
title: string;

View file

@ -1,240 +0,0 @@
import { Octokit } from "@octokit/rest";
import { URL } from "node:url";
import { EventEmitter } from "events";
import { getChromiumPath, getContinueUtilsPath } from "../../util/paths";
import { executablePath, Page } from "puppeteer";
// @ts-ignore
import PCR from "puppeteer-chromium-resolver";
import * as fs from "fs";
export type PageData = {
url: string;
path: string;
content: string;
};
const MAX_TIME_TO_CRAWL = 1000 * 5;
const LINK_GROUP_SIZE = 2; // Controls parallelization of crawler
const GITHUB_HOST = "github.com";
const MAX_REQUESTS_PER_CRAWL = 1000;
const markdownRegex = new RegExp(/\.(md|mdx)$/);
const octokit = new Octokit({
auth: undefined,
});
const PCR_CONFIG = {
downloadPath: getContinueUtilsPath(),
};
export function verifyOrInstallChromium() {
if (!fs.existsSync(getChromiumPath())) {
PCR(PCR_CONFIG);
}
}
async function getGithubRepoDefaultBranch(
owner: string,
repo: string,
): Promise<string> {
const repoInfo = await octokit.repos.get({
owner,
repo,
});
return repoInfo.data.default_branch;
}
async function getGitHubRepoPaths(owner: string, repo: string, branch: string) {
const tree = await octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
},
);
const paths = tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
return paths;
}
async function getGithubRepoFileContent(
path: string,
owner: string,
repo: string,
) {
try {
const response = await octokit.repos.getContent({
owner,
repo,
path,
headers: {
Accept: "application/vnd.github.raw+json",
},
});
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
async function* crawlGithubRepo(url: URL) {
const urlStr = url.toString();
const [_, owner, repo] = url.pathname.split("/");
const branch = await getGithubRepoDefaultBranch(owner, repo);
const paths = await getGitHubRepoPaths(owner, repo, branch);
for await (const path of paths) {
const content = await getGithubRepoFileContent(path, owner, repo);
yield {
path,
url: urlStr,
content: content ?? "",
};
}
}
async function getLinksFromPage(page: Page) {
// The URL lib is not available by default in the page scope,
// so we need to expose it to the page through this fn.
await page.exposeFunction(
"getCleanedUrlFromAnchorTag",
(a: HTMLAnchorElement) => {
let url = new URL(a.href);
url.hash = "";
return url.href;
},
);
const links: string[] = await page.$$eval("a", (links) =>
links.map((a) => (window as any).getCleanedUrlFromAnchorTag),
);
return links;
}
async function getLinkGroups(page: Page) {
const links = await getLinksFromPage(page);
const groups = links.reduce((acc, link, i) => {
const groupIndex = Math.floor(i / LINK_GROUP_SIZE);
if (!acc[groupIndex]) {
acc.push([]);
}
acc[groupIndex].push(link);
return acc;
}, [] as string[][]);
return groups;
}
function shouldSkipPage(url: URL, rootUrl: URL, visitedLinks: Set<string>) {
const hasVisitedLink = visitedLinks.has(url.toString());
const isInvalidHostOrPath =
!url.pathname.startsWith(rootUrl.pathname) || rootUrl.host !== url.host;
return hasVisitedLink || isInvalidHostOrPath;
}
async function* crawlSitePages(
page: Page,
url: URL,
rootUrl: URL,
maxRequestsPerCrawl: number,
visitedLinks: Set<string> = new Set(),
currentRequests: number = 0,
): AsyncGenerator<any> {
if (currentRequests >= maxRequestsPerCrawl) {
console.warn("Max requests per crawl reached. Stopping crawler.");
return;
}
if (shouldSkipPage(url, rootUrl, visitedLinks)) {
console.warn("Skipping ", url.toString());
return;
}
await page.goto(url.toString());
const htmlContent = await page.content();
const linkGroups = await getLinkGroups(page);
const requestCount = currentRequests + 1;
visitedLinks.add(url.toString());
yield {
path: url.pathname,
url: url.toString(),
content: htmlContent,
};
for (const linkGroup of linkGroups) {
for (const link of linkGroup) {
yield* crawlSitePages(
page,
new URL(link),
rootUrl,
maxRequestsPerCrawl,
visitedLinks,
requestCount,
);
}
}
}
async function* crawlSite(
startUrl: URL,
rootUrl: URL,
maxRequestsPerCrawl: number,
): AsyncGenerator<PageData> {
const stats = await PCR(PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
],
executablePath: stats.executablePath,
// From the docs: https://pptr.dev/guides/headless-modes
// If the performance is more important for your use case, switch to chrome-headless-shell as following:
// { headless: "shell" }
headless: "shell",
});
const page = await browser.newPage();
try {
yield* crawlSitePages(page, startUrl, rootUrl, maxRequestsPerCrawl);
} catch (e) {
console.debug("Error getting links: ", e);
} finally {
await browser.close();
}
}
export async function* crawl(
url: URL,
maxRequestsPerCrawl: number = MAX_REQUESTS_PER_CRAWL,
): AsyncGenerator<PageData> {
if (url.host === GITHUB_HOST) {
yield* crawlGithubRepo(url);
} else {
// TODO: Why both
yield* crawlSite(url, url, maxRequestsPerCrawl);
}
}