Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

Merge branch 'main' into feat/issue-266

Rafael Millerf9c7ca938823
diff --cc apps/api/src/__tests__/e2e_withAuth/index.test.ts
index 1e1d5e38d,780ad3992..9149c0122
--- a/apps/api/src/__tests__/e2e_withAuth/index.test.ts
+++ b/apps/api/src/__tests__/e2e_withAuth/index.test.ts
@@@ -139,10 -133,57 +139,59 @@@ describe("E2E Tests for API Routes", (
expect(response.body.data).toHaveProperty('content');
expect(response.body.data).toHaveProperty('metadata');
expect(response.body.data.content).toContain('We present spectrophotometric observations of the Broad Line Radio Galaxy');
+ expect(response.body.data.metadata.pageStatusCode).toBe(200);
+ expect(response.body.data.metadata.pageError).toBeUndefined();
}, 60000); // 60 seconds
+ it.concurrent('should return a successful response for a valid scrape with PDF file and parsePDF set to false', async () => {
+ const response = await request(TEST_URL)
+ .post('/v0/scrape')
+ .set('Authorization', `Bearer ${process.env.TEST_API_KEY}`)
+ .set('Content-Type', 'application/json')
+ .send({ url: 'https://arxiv.org/pdf/astro-ph/9301001.pdf', pageOptions: { parsePDF: false } });
+ await new Promise((r) => setTimeout(r, 6000));
+
+ expect(response.statusCode).toBe(200);
+ expect(response.body).toHaveProperty('data');
+ expect(response.body.data).toHaveProperty('content');
+ expect(response.body.data).toHaveProperty('metadata');
+ expect(response.body.data.content).toContain('/Title(arXiv:astro-ph/9301001v1 7 Jan 1993)>>endobj');
+ }, 60000); // 60 seconds
+
+ it.concurrent("should return a successful response with a valid API key with removeTags option", async () => {
+ const responseWithoutRemoveTags = await request(TEST_URL)
+ .post("/v0/scrape")
+ .set("Authorization", `Bearer ${process.env.TEST_API_KEY}`)
+ .set("Content-Type", "application/json")
+ .send({ url: "https://www.scrapethissite.com/" });
+ expect(responseWithoutRemoveTags.statusCode).toBe(200);
+ expect(responseWithoutRemoveTags.body).toHaveProperty("data");
+ expect(responseWithoutRemoveTags.body.data).toHaveProperty("content");
+ expect(responseWithoutRemoveTags.body.data).toHaveProperty("markdown");
+ expect(responseWithoutRemoveTags.body.data).toHaveProperty("metadata");
+ expect(responseWithoutRemoveTags.body.data).not.toHaveProperty("html");
+ expect(responseWithoutRemoveTags.body.data.content).toContain("Scrape This Site");
+ expect(responseWithoutRemoveTags.body.data.content).toContain("Lessons and Videos"); // #footer
+ expect(responseWithoutRemoveTags.body.data.content).toContain("[Sandbox]("); // .nav
+ expect(responseWithoutRemoveTags.body.data.content).toContain("web scraping"); // strong
+
+ const response = await request(TEST_URL)
+ .post("/v0/scrape")
+ .set("Authorization", `Bearer ${process.env.TEST_API_KEY}`)
+ .set("Content-Type", "application/json")
+ .send({ url: "https://www.scrapethissite.com/", pageOptions: { removeTags: ['.nav', '#footer', 'strong'] } });
+ expect(response.statusCode).toBe(200);
+ expect(response.body).toHaveProperty("data");
+ expect(response.body.data).toHaveProperty("content");
+ expect(response.body.data).toHaveProperty("markdown");
+ expect(response.body.data).toHaveProperty("metadata");
+ expect(response.body.data).not.toHaveProperty("html");
+ expect(response.body.data.content).toContain("Scrape This Site");
+ expect(response.body.data.content).not.toContain("Lessons and Videos"); // #footer
+ expect(response.body.data.content).not.toContain("[Sandbox]("); // .nav
+ expect(response.body.data.content).not.toContain("web scraping"); // strong
+ }, 30000); // 30 seconds timeout
+
// TODO: add this test back once we nail the waitFor option to be more deterministic
// it.concurrent("should return a successful response with a valid API key and waitFor option", async () => {
// const startTime = Date.now();
diff --cc apps/api/src/scraper/WebScraper/index.ts
index 0446ab7a9,36af58a7a..3fbc6d1e5
--- a/apps/api/src/scraper/WebScraper/index.ts
+++ b/apps/api/src/scraper/WebScraper/index.ts
@@@ -280,10 -280,10 +280,10 @@@ export class WebScraperDataProvider
private async fetchPdfDocuments(pdfLinks: string[]): Promise<Document[]> {
return Promise.all(
pdfLinks.map(async (pdfLink) => {
- const { content, pageStatusCode, pageError } = await fetchAndProcessPdf(pdfLink);
- const pdfContent = await fetchAndProcessPdf(pdfLink, this.pageOptions.parsePDF);
++ const { content, pageStatusCode, pageError } = await fetchAndProcessPdf(pdfLink, this.pageOptions.parsePDF);
return {
- content: pdfContent,
- metadata: { sourceURL: pdfLink },
+ content: content,
+ metadata: { sourceURL: pdfLink, pageStatusCode, pageError },
provider: "web-scraper",
};
})
diff --cc apps/api/src/scraper/WebScraper/single_url.ts
index 3f7e78951,4723a561e..1ba28323e
--- a/apps/api/src/scraper/WebScraper/single_url.ts
+++ b/apps/api/src/scraper/WebScraper/single_url.ts
@@@ -88,8 -88,7 +88,8 @@@ export async function scrapWithFireEngi
const contentType = response.headers["content-type"];
if (contentType && contentType.includes("application/pdf")) {
- const { content, pageStatusCode, pageError } = await fetchAndProcessPdf(url);
- return { html: await fetchAndProcessPdf(url, pageOptions?.parsePDF), screenshot: "" };
++ const { content, pageStatusCode, pageError } = await fetchAndProcessPdf(url, pageOptions?.parsePDF);
+ return { html: content, screenshot: "", pageStatusCode, pageError };
} else {
const data = response.data;
const html = data.content;
@@@ -109,8 -108,9 +109,9 @@@
export async function scrapWithScrapingBee(
url: string,
wait_browser: string = "domcontentloaded",
- timeout: number = universalTimeout
+ timeout: number = universalTimeout,
+ pageOptions: { parsePDF?: boolean } = { parsePDF: true }
-): Promise<string> {
+): Promise<{ content: string, pageStatusCode?: number, pageError?: string }> {
try {
const client = new ScrapingBeeClient(process.env.SCRAPING_BEE_API_KEY);
const clientParams = await generateRequestParams(
@@@ -129,16 -130,11 +130,17 @@@
const contentType = response.headers["content-type"];
if (contentType && contentType.includes("application/pdf")) {
- return await fetchAndProcessPdf(url);
- return fetchAndProcessPdf(url, pageOptions?.parsePDF);
++ return await fetchAndProcessPdf(url, pageOptions?.parsePDF);
++
} else {
- const decoder = new TextDecoder();
- const text = decoder.decode(response.data);
- return text;
+ let text = "";
+ try {
+ const decoder = new TextDecoder();
+ text = decoder.decode(response.data);
+ } catch (decodeError) {
+ console.error(`[ScrapingBee][c] Error decoding response data for url: ${url} -> ${decodeError}`);
+ }
+ return { content: text, pageStatusCode: response.status, pageError: response.statusText != "OK" ? response.statusText : undefined };
}
} catch (error) {
console.error(`[ScrapingBee][c] Error fetching url: ${url} -> ${error}`);
@@@ -149,8 -145,9 +151,9 @@@
export async function scrapWithPlaywright(
url: string,
waitFor: number = 0,
- headers?: Record<string, string>
+ headers?: Record<string, string>,
+ pageOptions: { parsePDF?: boolean } = { parsePDF: true }
-): Promise<string> {
+): Promise<{ content: string, pageStatusCode?: number, pageError?: string }> {
try {
const reqParams = await generateRequestParams(url);
// If the user has passed a wait parameter in the request, use that
@@@ -177,7 -174,7 +180,7 @@@
const contentType = response.headers["content-type"];
if (contentType && contentType.includes("application/pdf")) {
- return await fetchAndProcessPdf(url);
- return fetchAndProcessPdf(url, pageOptions?.parsePDF);
++ return await fetchAndProcessPdf(url, pageOptions?.parsePDF);
} else {
const textData = response.data;
try {
@@@ -199,7 -196,10 +202,10 @@@
}
}
- export async function scrapWithFetch(url: string): Promise<{ content: string, pageStatusCode?: number, pageError?: string }> {
+ export async function scrapWithFetch(
+ url: string,
+ pageOptions: { parsePDF?: boolean } = { parsePDF: true }
-): Promise<string> {
++): Promise<{ content: string, pageStatusCode?: number, pageError?: string }> {
try {
const response = await axios.get(url, {
headers: {
@@@ -218,10 -218,10 +224,10 @@@
const contentType = response.headers["content-type"];
if (contentType && contentType.includes("application/pdf")) {
- return await fetchAndProcessPdf(url);
- return fetchAndProcessPdf(url, pageOptions?.parsePDF);
++ return await fetchAndProcessPdf(url, pageOptions?.parsePDF);
} else {
const text = response.data;
- return text;
+ return { content: text, pageStatusCode: 200 };
}
} catch (error) {
if (error.code === 'ECONNABORTED') {
@@@ -390,8 -389,7 +409,8 @@@ export async function scrapSingleUrl
}
break;
case "pdf":
- const { content, pageStatusCode, pageError } = await fetchAndProcessPdf(customScraperResult.url);
- customScrapedContent = { html: await fetchAndProcessPdf(customScraperResult.url, pageOptions?.parsePDF), screenshot }
++ const { content, pageStatusCode, pageError } = await fetchAndProcessPdf(customScraperResult.url, pageOptions?.parsePDF);
+ customScrapedContent = { html: content, screenshot, pageStatusCode, pageError }
break;
}
}
diff --cc apps/api/src/scraper/WebScraper/utils/__tests__/pdfProcessor.test.ts
index 3438287d1,f4ed3c622..55930f28c
--- a/apps/api/src/scraper/WebScraper/utils/__tests__/pdfProcessor.test.ts
+++ b/apps/api/src/scraper/WebScraper/utils/__tests__/pdfProcessor.test.ts
@@@ -3,10 -3,8 +3,10 @@@ import * as pdfProcessor from '../pdfPr
describe('PDF Processing Module - Integration Test', () => {
it('should correctly process a simple PDF file without the LLAMAPARSE_API_KEY', async () => {
delete process.env.LLAMAPARSE_API_KEY;
- const { content, pageStatusCode, pageError } = await pdfProcessor.fetchAndProcessPdf('https://s3.us-east-1.amazonaws.com/storage.mendable.ai/rafa-testing/test%20%281%29.pdf');
- const pdfContent = await pdfProcessor.fetchAndProcessPdf('https://s3.us-east-1.amazonaws.com/storage.mendable.ai/rafa-testing/test%20%281%29.pdf', true);
- expect(pdfContent.trim()).toEqual("Dummy PDF file");
++ const { content, pageStatusCode, pageError } = await pdfProcessor.fetchAndProcessPdf('https://s3.us-east-1.amazonaws.com/storage.mendable.ai/rafa-testing/test%20%281%29.pdf', true);
+ expect(content.trim()).toEqual("Dummy PDF file");
+ expect(pageStatusCode).toEqual(200);
+ expect(pageError).toBeUndefined();
});
// We're hitting the LLAMAPARSE rate limit 🫠
diff --cc apps/api/src/scraper/WebScraper/utils/pdfProcessor.ts
index 715f30d5a,1f0d6e875..1a67d60b4
--- a/apps/api/src/scraper/WebScraper/utils/pdfProcessor.ts
+++ b/apps/api/src/scraper/WebScraper/utils/pdfProcessor.ts
@@@ -9,14 -9,14 +9,14 @@@ import os from "os"
dotenv.config();
- export async function fetchAndProcessPdf(url: string): Promise<{ content: string, pageStatusCode?: number, pageError?: string }> {
-export async function fetchAndProcessPdf(url: string, parsePDF: boolean): Promise<string> {
- const tempFilePath = await downloadPdf(url);
++export async function fetchAndProcessPdf(url: string, parsePDF: boolean): Promise<{ content: string, pageStatusCode?: number, pageError?: string }> {
+ const { tempFilePath, pageStatusCode, pageError } = await downloadPdf(url);
- const content = await processPdfToText(tempFilePath);
+ const content = await processPdfToText(tempFilePath, parsePDF);
fs.unlinkSync(tempFilePath); // Clean up the temporary file
- return content;
+ return { content, pageStatusCode, pageError };
}
-async function downloadPdf(url: string): Promise<string> {
+async function downloadPdf(url: string): Promise<{ tempFilePath: string, pageStatusCode?: number, pageError?: string }> {
const response = await axios({
url,
method: "GET",