Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(api): PDF shadow comparison for Rust (#2955)
Abimael Martelld1d72638b902
diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex 88c5e5dcf..697f95858 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -158,6 +158,7 @@ const configSchema = z.object({// PDF Rust Extraction (pdf-inspector)PDF_RUST_EXTRACT_ENABLE: z.stringbool().optional(),+ PDF_SHADOW_COMPARISON_ENABLE: z.stringbool().optional(),// WebhooksSELF_HOSTED_WEBHOOK_URL: z.string().optional(),diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/shadowComparison.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/shadowComparison.test.tsnew file mode 100644index 000000000..c9cb17e95--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/shadowComparison.test.ts@@ -0,0 +1,140 @@+import {+ comparePdfOutputs,+ extractNumbers,+ countTables,+} from "../shadowComparison";++describe("extractNumbers", () => {+ it("extracts integers and decimals", () => {+ const nums = extractNumbers("There are 123 items at $45.67 each");+ expect(nums).toEqual(new Set(["123", "45.67"]));+ });++ it("returns empty set for no numbers", () => {+ expect(extractNumbers("no numbers here")).toEqual(new Set());+ });+});++describe("countTables", () => {+ it("counts markdown table separator rows", () => {+ const md = `+| Col A | Col B |+| --- | --- |+| 1 | 2 |++Some text++| X | Y | Z |+| --- | --- | --- |+| a | b | c |+`;+ expect(countTables(md)).toBe(2);+ });++ it("returns 0 when no tables", () => {+ expect(countTables("just some text")).toBe(0);+ });+});++describe("comparePdfOutputs", () => {+ it("identical markdown returns good verdict with ratios of 1", () => {+ const md = "Hello world 123 456";+ const result = comparePdfOutputs(md, md);+ expect(result.overall.lenRatio).toBe(1);+ expect(result.overall.numberPreservationRatio).toBe(1);+ expect(result.overall.overallMatch).toBe("good");+ });++ it("shorter Rust markdown produces correct lenRatio", () => {+ const rustMd = "short";+ const muMd = "this is much longer text";+ const result = comparePdfOutputs(rustMd, muMd);+ expect(result.overall.rustLen).toBe(5);+ expect(result.overall.muLen).toBe(24);+ expect(result.overall.lenRatio).toBeCloseTo(5 / 24, 2);+ });++ it("computes number preservation ratio correctly", () => {+ const muMd = "Values: 123, 456, 789";+ const rustMd = "Values: 123, 789";+ const result = comparePdfOutputs(rustMd, muMd);+ expect(result.overall.muNumberCount).toBe(3);+ expect(result.overall.rustNumberCount).toBe(2);+ expect(result.overall.numberPreservationRatio).toBeCloseTo(2 / 3, 2);+ });++ it("detects table count differences", () => {+ const muMd = `+| A | B |+| --- | --- |+| 1 | 2 |++| C | D |+| --- | --- |+| 3 | 4 |+`;+ const rustMd = `+| A | B |+| --- | --- |+| 1 | 2 |+`;+ const result = comparePdfOutputs(rustMd, muMd);+ expect(result.overall.rustTableCount).toBe(1);+ expect(result.overall.muTableCount).toBe(2);+ });++ it("handles empty inputs", () => {+ const result = comparePdfOutputs("", "");+ expect(result.overall.rustLen).toBe(0);+ expect(result.overall.muLen).toBe(0);+ expect(result.overall.lenRatio).toBe(1);+ expect(result.overall.numberPreservationRatio).toBe(1);+ expect(result.overall.overallMatch).toBe("good");+ });++ it("handles empty Rust with non-empty MU", () => {+ const result = comparePdfOutputs("", "some content 123");+ expect(result.overall.lenRatio).toBe(0);+ expect(result.overall.numberPreservationRatio).toBe(0);+ expect(result.overall.overallMatch).toBe("poor");+ });++ it("returns acceptable verdict at threshold", () => {+ // Target: lenRatio in [0.5, 0.8), numberPreservation in [0.7, 0.9)+ // MU: 20 chars, 10 numbers. Rust: 10 chars (ratio 0.5), 8 of 10 numbers (ratio 0.8)+ const muMd = "aaaaaaaaaa 1 2 3 4 5 6 7 8 9 10";+ const rustMd = "aaaaa 1 2 3 4 5 6 7 8";+ const result = comparePdfOutputs(rustMd, muMd);+ expect(result.overall.lenRatio).toBeGreaterThanOrEqual(0.5);+ expect(result.overall.lenRatio).toBeLessThan(0.8);+ expect(result.overall.numberPreservationRatio).toBeGreaterThanOrEqual(0.7);+ expect(result.overall.numberPreservationRatio).toBeLessThan(0.9);+ expect(result.overall.overallMatch).toBe("acceptable");+ });++ it("returns good when lenRatio >= 0.8 and numberPreservation >= 0.9", () => {+ const muMd = "Numbers: 1 2 3 4 5 6 7 8 9 10 end";+ const rustMd = "Numbers: 1 2 3 4 5 6 7 8 9 10 end";+ const result = comparePdfOutputs(rustMd, muMd);+ expect(result.overall.overallMatch).toBe("good");+ });++ it("returns acceptable when lenRatio >= 0.5 and numberPreservation >= 0.7", () => {+ // 10 numbers in MU, 7 preserved in Rust (ratio = 0.7)+ const muMd = "aaaaaaaaaa 1 2 3 4 5 6 7 8 9 10";+ const rustMd = "aaaaaa 1 2 3 4 5 6 7";+ const result = comparePdfOutputs(rustMd, muMd);+ expect(result.overall.numberPreservationRatio).toBeGreaterThanOrEqual(0.7);+ expect(result.overall.lenRatio).toBeGreaterThanOrEqual(0.5);+ // But not both meeting good thresholds+ expect(result.overall.lenRatio).toBeLessThan(0.8);+ expect(result.overall.overallMatch).toBe("acceptable");+ });++ it("returns poor when below acceptable thresholds", () => {+ const muMd = "a]".repeat(100) + " 1 2 3 4 5 6 7 8 9 10";+ const rustMd = "b 1";+ const result = comparePdfOutputs(rustMd, muMd);+ expect(result.overall.overallMatch).toBe("poor");+ });+});diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/index.tsindex a256ac067..4eb788503 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts@@ -27,6 +27,7 @@ import { scrapePDFWithRunPodMU } from "./runpodMU";import { scrapePDFWithParsePDF } from "./pdfParse";import { captureExceptionWithZdrCheck } from "../../../../services/sentry";import { isPdfBuffer, PDF_SNIFF_WINDOW } from "./pdfUtils";+import { comparePdfOutputs } from "./shadowComparison";/** Check if the PDF is eligible for Rust extraction, returning a rejection reason or null. */function getIneligibleReason(@@ -140,6 +141,7 @@ export async function scrapePDF(meta: Meta): Promise<EngineScrapeResult> {let result: PDFProcessorResult | null = null;let effectivePageCount: number = 0;let metadataTitle: string | undefined;+ let rustMarkdownForShadow: string | undefined;const rustEnabled = !!config.PDF_RUST_EXTRACT_ENABLE;const logger = meta.logger.child({ method: "scrapePDF/processPdf" });@@ -217,6 +219,11 @@ export async function scrapePDF(meta: Meta): Promise<EngineScrapeResult> {mode,});+ rustMarkdownForShadow =+ !eligible && pdfResult.markdown && config.PDF_SHADOW_COMPARISON_ENABLE+ ? pdfResult.markdown+ : undefined;+// In fast mode, if the PDF requires OCR, fail immediately with a// clear error instead of returning empty content.if (@@ -299,6 +306,27 @@ export async function scrapePDF(meta: Meta): Promise<EngineScrapeResult> {pages: effectivePageCount,success: true,});++ if (rustMarkdownForShadow && result?.markdown && config.PDF_SHADOW_COMPARISON_ENABLE) {+ const shadowRust = rustMarkdownForShadow;+ const shadowMu = result.markdown;+ const shadowLogger = meta.logger.child({ method: "scrapePDF/shadowComparison" });+ const isZdr = !!meta.internalOptions.zeroDataRetention;++ (async () => {+ try {+ const metrics = comparePdfOutputs(shadowRust, shadowMu);+ shadowLogger.info("shadow comparison complete", {+ scrapeId: meta.id,+ url: isZdr ? undefined : (meta.rewrittenUrl ?? meta.url),+ pageCount: effectivePageCount,+ ...metrics.overall,+ });+ } catch (error) {+ shadowLogger.warn("shadow comparison failed", { error });+ }+ })();+ }} catch (error) {if (error instanceof RemoveFeatureError ||diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/shadowComparison.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/shadowComparison.tsnew file mode 100644index 000000000..7a9a13a71--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/shadowComparison.ts@@ -0,0 +1,77 @@+export interface ComparisonResult {+ overall: {+ rustLen: number;+ muLen: number;+ lenRatio: number;+ rustNumberCount: number;+ muNumberCount: number;+ numberPreservationRatio: number;+ rustTableCount: number;+ muTableCount: number;+ overallMatch: "good" | "acceptable" | "poor";+ };+}++/** Extract all numbers (integers and decimals) from text as a Set of strings. */+export function extractNumbers(text: string): Set<string> {+ const matches = text.match(/\d+(?:\.\d+)?/g);+ return new Set(matches ?? []);+}++/** Count markdown tables by matching full header-separator rows. */+export function countTables(md: string): number {+ const matches = md.match(/^\s*(?:\|\s*:?-+:?\s*)+\|\s*$/gm);+ return matches?.length ?? 0;+}++export function comparePdfOutputs(+ rustMd: string,+ muMd: string,+): ComparisonResult {+ const rustLen = rustMd.length;+ const muLen = muMd.length;+ const lenRatio = muLen > 0 ? rustLen / muLen : rustLen > 0 ? 0 : 1;++ const rustNumbers = extractNumbers(rustMd);+ const muNumbers = extractNumbers(muMd);+ const rustNumberCount = rustNumbers.size;+ const muNumberCount = muNumbers.size;++ let numberPreservationRatio: number;+ if (muNumberCount === 0) {+ numberPreservationRatio = rustNumberCount === 0 ? 1 : 0;+ } else {+ let preserved = 0;+ for (const n of muNumbers) {+ if (rustNumbers.has(n)) preserved++;+ }+ numberPreservationRatio = preserved / muNumberCount;+ }++ const rustTableCount = countTables(rustMd);+ const muTableCount = countTables(muMd);++ let overallMatch: "good" | "acceptable" | "poor";+ if (lenRatio >= 0.8 && numberPreservationRatio >= 0.9) {+ overallMatch = "good";+ } else if (lenRatio >= 0.5 && numberPreservationRatio >= 0.7) {+ overallMatch = "acceptable";+ } else {+ overallMatch = "poor";+ }++ return {+ overall: {+ rustLen,+ muLen,+ lenRatio: Math.round(lenRatio * 1000) / 1000,+ rustNumberCount,+ muNumberCount,+ numberPreservationRatio:+ Math.round(numberPreservationRatio * 1000) / 1000,+ rustTableCount,+ muTableCount,+ overallMatch,+ },+ };+}