A fast, helpful, and open-source document parser
update projection
Logan Markewicha87d6700129c
diff --git a/src/processing/README.md b/src/processing/README.mdindex 162f02c..a5740d3 100644--- a/src/processing/README.md+++ b/src/processing/README.md@@ -101,16 +101,16 @@ When disabled, a zero-cost `NoopGridDebugLogger` singleton is used — no runtim---### gridVisualizer.ts-**PNG visualization of grid projection state.**+**PNG visualization of projected text output.**-Renders a page's projection as a PNG image using sharp with an SVG overlay. Text boxes are drawn as colored rectangles by snap type:+Renders the projected text as a monospace character grid image using sharp with an SVG overlay. Each character is drawn at its grid position, color-coded by snap type:- **Blue** — left snap- **Red** — right snap- **Green** — center snap- **Gray** — floating (unsnapped)- **Yellow** — flowing text-Also draws vertical dashed lines for anchor positions and block boundary outlines. Includes a color legend.+Text segments get colored background rectangles and colored text, making it easy to compare the projection output directly against the original PDF page screenshot. Includes a color legend.Called automatically when `debug.visualize` is enabled. Output files are named `page-{N}-grid.png` in the configured directory.diff --git a/src/processing/gridDebugLogger.ts b/src/processing/gridDebugLogger.tsindex 8cd0e73..a6520fe 100644--- a/src/processing/gridDebugLogger.ts+++ b/src/processing/gridDebugLogger.ts@@ -72,31 +72,22 @@ type LogEntry = {data?: Record<string, unknown>;};+/** A segment of rendered text placed into the output grid. */+export interface RenderedSegment {+ lineIndex: number;+ /** Character column where this segment starts in the output line. */+ gridCol: number;+ text: string;+ snap: "left" | "right" | "center" | "floating" | "flowing";+}+/** Captured data for a single page, used by the grid visualizer. */export interface VisualizerPageData {pageNum: number;- width: number;- height: number;- boxes: VisualizerBox[];- anchors: {- left: number[];- right: number[];- center: number[];- };- flowingLines: Set<number>;- blocks: Array<{ start: number; end: number; flowing: boolean }>;-}--export interface VisualizerBox {- text: string;- x: number;- y: number;- w: number;- h: number;- lineIndex: number;- snap?: "left" | "right" | "center";- isFlowing: boolean;- forceUnsnapped?: boolean;+ /** Rendered text segments with snap type for color coding. */+ segments: RenderedSegment[];+ /** Final projected text lines (the actual output). */+ rawLines: string[];}/**@@ -151,7 +142,7 @@ export class GridDebugLogger {return this.config;}- setPage(pageNum: number, width: number, height: number): void {+ setPage(pageNum: number, _width: number, _height: number): void {this.currentPage = pageNum;if (this.config.pageFilter && pageNum !== this.config.pageFilter) {return;@@ -161,12 +152,8 @@ export class GridDebugLogger {if (this.shouldVisualize) {this.currentVizPage = {pageNum,- width,- height,- boxes: [],- anchors: { left: [], right: [], center: [] },- flowingLines: new Set(),- blocks: [],+ segments: [],+ rawLines: [],};this.vizPages.push(this.currentVizPage);}@@ -220,17 +207,10 @@ export class GridDebugLogger {phase: "flowing",message: `Block lines ${start}-${end - 1} classified as flowing text`,});- if (this.currentVizPage) {- this.currentVizPage.blocks.push({ start, end, flowing: true });- }}- /** Log non-flowing block */- logStructuredBlock(start: number, end: number): void {- if (this.currentVizPage) {- this.currentVizPage.blocks.push({ start, end, flowing: false });- }- }+ /** Log non-flowing block (no-op, only used for symmetry with logFlowingBlock) */+ logStructuredBlock(_start: number, _end: number): void {}/** Log flowing line detection */logFlowingLine(lineIndex: number, reason: string): void {@@ -241,9 +221,6 @@ export class GridDebugLogger {lineIndex,message: `Line ${lineIndex} marked flowing: ${reason}`,});- if (this.currentVizPage) {- this.currentVizPage.flowingLines.add(lineIndex);- }}/** Log anchor extraction results for a block */@@ -263,13 +240,6 @@ export class GridDebugLogger {message: `Anchors: left=[${leftKeys.join(", ")}] right=[${rightKeys.join(", ")}] center=[${centerKeys.join(", ")}]`,});- // Capture for visualization- if (this.currentVizPage) {- this.currentVizPage.anchors.left.push(...leftKeys);- this.currentVizPage.anchors.right.push(...rightKeys);- this.currentVizPage.anchors.center.push(...centerKeys);- }-// Log which elements are in each anchor, but only if they match filtersfor (const key of leftKeys) {const items = anchorLeft[key];@@ -328,22 +298,24 @@ export class GridDebugLogger {});}- /** Capture all boxes on a line for visualization (called after snap assignment) */- captureLineBoxes(lineIndex: number, line: ProjectionTextBox[], isFlowing: boolean): void {+ /** Capture a rendered text segment for visualization. */+ captureRender(+ lineIndex: number,+ gridCol: number,+ text: string,+ snap: "left" | "right" | "center" | "floating" | "flowing"+ ): void {+ if (!this.currentVizPage) return;+ this.currentVizPage.segments.push({ lineIndex, gridCol, text, snap });+ }++ /** Capture the final raw lines after projection completes for this page. */+ captureRawLines(rawLines: string[]): void {if (!this.currentVizPage) return;- for (const bbox of line) {- this.currentVizPage.boxes.push({- text: bbox.str,- x: bbox.x,- y: bbox.y,- w: bbox.w,- h: bbox.h,- lineIndex,- snap: bbox.snap,- isFlowing,- forceUnsnapped: bbox.forceUnsnapped,- });- }+ this.currentVizPage.rawLines = Array.from(+ { length: rawLines.length },+ (_, i) => rawLines[i] ?? ""+ );}/** Log the rendering of a bbox to a target column position */@@ -476,7 +448,8 @@ class NoopGridDebugLogger extends GridDebugLogger {override logFlowingLine(): void {}override logAnchors(): void {}override logSnapAssignment(): void {}- override captureLineBoxes(): void {}+ override captureRender(): void {}+ override captureRawLines(): void {}override logRender(): void {}override logForwardAnchor(): void {}override logDuplicateResolution(): void {}diff --git a/src/processing/gridProjection.ts b/src/processing/gridProjection.tsindex 35cdc6f..8be1273 100644--- a/src/processing/gridProjection.ts+++ b/src/processing/gridProjection.ts@@ -1422,17 +1422,14 @@ export function projectToGrid(// render it simply and skip grid projectionif (isFlowingTextBlock(blockLines, anchorLeft, anchorRight, anchorCenter, page.width)) {logger.logFlowingBlock(block.start, block.end);- // Capture flowing lines for visualization- if (logger.shouldVisualize) {- for (let li = block.start; li < block.end; li++) {- logger.captureLineBoxes(li, lines[li], true);- }- }if (!config.preserveLayoutAlignmentAcrossPages) {const sizes = getMedianTextBoxSize(blockLines.flat());medianWidth = sizes.width;}renderFlowingBlock(lines, block, rawLines, medianWidth);+ for (let li = block.start; li < block.end; li++) {+ if (rawLines[li]) logger.captureRender(li, 0, rawLines[li], "flowing");+ }continue;}@@ -1576,6 +1573,7 @@ export function projectToGrid(rawLines[lineIndex] = renderLineAsFlowingText(line, blockMinX, medianWidth);flowingLines.add(lineIndex);logger.logFlowingLine(lineIndex, reason);+ logger.captureRender(lineIndex, 0, rawLines[lineIndex], "flowing");}// First pass: detect clearly flowing lines (wide, no column gaps, enough items)@@ -1617,13 +1615,6 @@ export function projectToGrid(}}- // Capture line boxes for visualization (after snap + flowing assignment)- if (logger.shouldVisualize) {- for (let li = block.start; li < block.end; li++) {- logger.captureLineBoxes(li, lines[li], flowingLines.has(li));- }- }-while (hasChanged || snapMaps.right.length || snapMaps.left.length || snapMaps.center.length) {hasChanged = false;@@ -1698,6 +1689,7 @@ export function projectToGrid(bbox.rendered = true;hasChanged = true;logger.logRender(bbox, lineIndex, targetX, "floating");+ logger.captureRender(lineIndex, targetX, bbox.str, "floating");let nextBbox: ProjectionTextBox | null = null;if (line.length > boxIndex + 1) {@@ -1784,6 +1776,7 @@ export function projectToGrid(rawLines[lineIndex] += currentLeftSnapBox.bbox.str;currentLeftSnapBox.bbox.rendered = true;logger.logRender(currentLeftSnapBox.bbox, lineIndex, targetX, "left-snap");+ logger.captureRender(lineIndex, targetX, currentLeftSnapBox.bbox.str, "left");let nextBbox: ProjectionTextBox | null = null;if (lines[lineIndex].length > currentLeftSnapBox.boxIndex + 1) {@@ -1876,6 +1869,12 @@ export function projectToGrid(rawLines[lineIndex] += currentRightSnapBox.bbox.str;currentRightSnapBox.bbox.rendered = true;logger.logRender(currentRightSnapBox.bbox, lineIndex, targetX, "right-snap");+ logger.captureRender(+ lineIndex,+ targetX - currentRightSnapBox.bbox.strLength,+ currentRightSnapBox.bbox.str,+ "right"+ );let nextBbox: ProjectionTextBox | null = null;if (lines[lineIndex].length > currentRightSnapBox.boxIndex + 1) {@@ -1973,6 +1972,12 @@ export function projectToGrid(targetX,"center-snap");+ logger.captureRender(+ currentCenterSnapBox.lineIndex,+ targetX - Math.round(currentCenterSnapBox.bbox.strLength / 2),+ currentCenterSnapBox.bbox.str,+ "center"+ );}snapMaps.center.shift();}@@ -1980,6 +1985,7 @@ export function projectToGrid(}fixSparseBlocks(blocks, rawLines);+ logger.captureRawLines(rawLines);const text = rawLines.join("\n");// OSS: Return text instead of mutating page objectdiff --git a/src/processing/gridVisualizer.ts b/src/processing/gridVisualizer.tsindex 1767a60..0594b2a 100644--- a/src/processing/gridVisualizer.ts+++ b/src/processing/gridVisualizer.ts@@ -1,21 +1,23 @@import sharp from "sharp";import { mkdirSync } from "fs";-import { VisualizerPageData } from "./gridDebugLogger.js";+import type { VisualizerPageData, RenderedSegment } from "./gridDebugLogger.js";-/** Maximum image dimension in pixels to prevent excessive memory usage. */-const MAX_IMAGE_DIM = 4000;--/** Padding around content bounding box in PDF points. */-const CROP_PADDING = 15;+/** Monospace character metrics in pixels. */+const CHAR_WIDTH = 7;+const CHAR_HEIGHT = 14;+const LINE_HEIGHT = 16;+const PADDING = 12;+const LEGEND_WIDTH = 140;+const LEGEND_HEIGHT = 100;/** Color scheme for snap types */-const COLORS = {- left: { fill: "rgba(59,130,246,0.15)", stroke: "#3b82f6", anchor: "#3b82f6" },- right: { fill: "rgba(239,68,68,0.15)", stroke: "#ef4444", anchor: "#ef4444" },- center: { fill: "rgba(34,197,94,0.15)", stroke: "#22c55e", anchor: "#22c55e" },- floating: { fill: "rgba(156,163,175,0.15)", stroke: "#9ca3af", anchor: "#9ca3af" },- flowing: { fill: "rgba(234,179,8,0.15)", stroke: "#eab308", anchor: "#eab308" },-} as const;+const COLORS: Record<RenderedSegment["snap"], { bg: string; text: string }> = {+ left: { bg: "rgba(59,130,246,0.18)", text: "#2563eb" },+ right: { bg: "rgba(239,68,68,0.18)", text: "#dc2626" },+ center: { bg: "rgba(34,197,94,0.18)", text: "#16a34a" },+ floating: { bg: "rgba(156,163,175,0.15)", text: "#4b5563" },+ flowing: { bg: "rgba(234,179,8,0.15)", text: "#a16207" },+};function escapeXml(s: string): string {return s@@ -27,188 +29,148 @@ function escapeXml(s: string): string {}/**- * Compute the bounding box of all content in PDF coordinates.- * Returns { x, y, w, h } clamped to page dimensions.- */-function getContentBounds(data: VisualizerPageData): {- x: number;- y: number;- w: number;- h: number;-} {- if (data.boxes.length === 0) {- return { x: 0, y: 0, w: data.width, h: data.height };- }-- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;-- for (const box of data.boxes) {- minX = Math.min(minX, box.x);- minY = Math.min(minY, box.y);- maxX = Math.max(maxX, box.x + box.w);- maxY = Math.max(maxY, box.y + box.h);- }-- // Also include anchor lines in the horizontal extent- for (const x of data.anchors.left) {- minX = Math.min(minX, x);- maxX = Math.max(maxX, x);- }- for (const x of data.anchors.right) {- minX = Math.min(minX, x);- maxX = Math.max(maxX, x);- }- for (const x of data.anchors.center) {- minX = Math.min(minX, x);- maxX = Math.max(maxX, x);- }-- // Add padding and clamp to page- minX = Math.max(0, minX - CROP_PADDING);- minY = Math.max(0, minY - CROP_PADDING);- maxX = Math.min(data.width, maxX + CROP_PADDING);- maxY = Math.min(data.height, maxY + CROP_PADDING);-- return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };-}--/**- * Render a grid visualization for a single page as a PNG.+ * Render the projected text output as a monospace grid image.*- * Draws text boxes as colored rectangles (by snap type), anchor positions- * as vertical lines, and text labels inside each box. Auto-crops to the- * content bounding box to avoid large empty regions.+ * Each character of the output text is rendered at its grid position.+ * Text segments are color-coded by snap type so you can visually compare+ * the projection against the original PDF page screenshot.*/export async function renderGridVisualization(data: VisualizerPageData,outputPath: string): Promise<void> {- // Compute content bounds for cropping- const bounds = getContentBounds(data);+ const { rawLines, segments } = data;+ if (!rawLines || rawLines.length === 0) return;- // Calculate scale to fit within MAX_IMAGE_DIM based on cropped size- const scale = Math.min(MAX_IMAGE_DIM / bounds.w, MAX_IMAGE_DIM / bounds.h, 2);- const imgWidth = Math.round(bounds.w * scale);- const imgHeight = Math.round(bounds.h * scale);-- // Offset: shift all coordinates so content starts at (0,0)- const ox = bounds.x;- const oy = bounds.y;+ // Trim trailing empty lines+ let lastNonEmpty = rawLines.length - 1;+ while (lastNonEmpty >= 0 && rawLines[lastNonEmpty].trimEnd().length === 0) {+ lastNonEmpty--;+ }+ const lines = rawLines.slice(0, lastNonEmpty + 1);+ if (lines.length === 0) return;++ const maxLineLen = Math.max(0, ...lines.map((l) => (l ?? "").length));+ if (maxLineLen === 0 || !Number.isFinite(maxLineLen)) return;++ // Image dimensions+ const contentWidth = maxLineLen * CHAR_WIDTH;+ const contentHeight = lines.length * LINE_HEIGHT;+ const imgWidth = Math.max(1, contentWidth + PADDING * 2 + LEGEND_WIDTH + PADDING);+ const imgHeight = Math.max(1, contentHeight + PADDING * 2);++ // Build segment lookup: for each (lineIndex, colRange) → snap type+ // Sort segments by line then column for efficient lookup+ const segmentsByLine = new Map<number, RenderedSegment[]>();+ for (const seg of segments) {+ if (!segmentsByLine.has(seg.lineIndex)) {+ segmentsByLine.set(seg.lineIndex, []);+ }+ segmentsByLine.get(seg.lineIndex)!.push(seg);+ }- // Build SVG overlayconst svgParts: string[] = [];svgParts.push(`<svg xmlns="http://www.w3.org/2000/svg" width="${imgWidth}" height="${imgHeight}" viewBox="0 0 ${imgWidth} ${imgHeight}">`);- // Font size scales with image- const fontSize = Math.max(6, Math.min(10, Math.round(8 * scale)));-- // Draw anchor lines (behind boxes)- const drawnAnchors = new Set<string>();-- for (const x of data.anchors.left) {- const key = `left-${x}`;- if (drawnAnchors.has(key)) continue;- drawnAnchors.add(key);- const sx = Math.round((x - ox) * scale);- svgParts.push(- `<line x1="${sx}" y1="0" x2="${sx}" y2="${imgHeight}" stroke="${COLORS.left.anchor}" stroke-width="1" stroke-dasharray="4,4" opacity="0.5"/>`- );- }- for (const x of data.anchors.right) {- const key = `right-${x}`;- if (drawnAnchors.has(key)) continue;- drawnAnchors.add(key);- const sx = Math.round((x - ox) * scale);- svgParts.push(- `<line x1="${sx}" y1="0" x2="${sx}" y2="${imgHeight}" stroke="${COLORS.right.anchor}" stroke-width="1" stroke-dasharray="4,4" opacity="0.5"/>`- );- }- for (const x of data.anchors.center) {- const key = `center-${x}`;- if (drawnAnchors.has(key)) continue;- drawnAnchors.add(key);- const sx = Math.round((x - ox) * scale);- svgParts.push(- `<line x1="${sx}" y1="0" x2="${sx}" y2="${imgHeight}" stroke="${COLORS.center.anchor}" stroke-width="1" stroke-dasharray="2,6" opacity="0.5"/>`- );- }-- // Draw block boundaries- for (const block of data.blocks) {- const blockBoxes = data.boxes.filter(- (b) => b.lineIndex >= block.start && b.lineIndex < block.end- );- if (blockBoxes.length === 0) continue;- const minY = Math.min(...blockBoxes.map((b) => b.y));- const maxY = Math.max(...blockBoxes.map((b) => b.y + b.h));- const sy = Math.round((minY - oy) * scale) - 2;- const ey = Math.round((maxY - oy) * scale) + 2;- const blockColor = block.flowing ? COLORS.flowing.stroke : "#6b7280";- svgParts.push(- `<rect x="0" y="${sy}" width="${imgWidth}" height="${ey - sy}" fill="none" stroke="${blockColor}" stroke-width="1" stroke-dasharray="6,3" opacity="0.3"/>`- );+ // Draw colored background rectangles for each segment+ for (const [lineIdx, lineSegments] of segmentsByLine) {+ if (lineIdx > lastNonEmpty) continue;+ for (const seg of lineSegments) {+ const color = COLORS[seg.snap];+ const x = PADDING + seg.gridCol * CHAR_WIDTH;+ const y = PADDING + lineIdx * LINE_HEIGHT;+ const w = seg.text.length * CHAR_WIDTH;+ svgParts.push(+ `<rect x="${x}" y="${y}" width="${w}" height="${LINE_HEIGHT}" fill="${color.bg}"/>`+ );+ }}- // Draw text boxes- for (const box of data.boxes) {- const sx = Math.round((box.x - ox) * scale);- const sy = Math.round((box.y - oy) * scale);- const sw = Math.max(Math.round(box.w * scale), 1);- const sh = Math.max(Math.round(box.h * scale), 1);-- let color: (typeof COLORS)[keyof typeof COLORS];- if (box.isFlowing) {- color = COLORS.flowing;- } else if (box.snap === "left") {- color = COLORS.left;- } else if (box.snap === "right") {- color = COLORS.right;- } else if (box.snap === "center") {- color = COLORS.center;- } else {- color = COLORS.floating;- }+ // Render text line by line using colored spans for segments+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {+ const line = lines[lineIdx] ?? "";+ if (line.length === 0) continue;- svgParts.push(- `<rect x="${sx}" y="${sy}" width="${sw}" height="${sh}" fill="${color.fill}" stroke="${color.stroke}" stroke-width="0.75"/>`- );+ const y = PADDING + lineIdx * LINE_HEIGHT + CHAR_HEIGHT;+ const lineSegs = segmentsByLine.get(lineIdx) ?? [];- // Text label (truncated to fit)- const maxChars = Math.max(1, Math.floor(sw / (fontSize * 0.55)));- const label =- box.text.length > maxChars ? box.text.substring(0, maxChars - 1) + "\u2026" : box.text;- if (label.length > 0 && sh >= fontSize) {+ if (lineSegs.length === 0) {+ // No segment data — render as plain gray textsvgParts.push(- `<text x="${sx + 2}" y="${sy + sh - 2}" font-family="monospace" font-size="${fontSize}" fill="${color.stroke}" clip-path="url(#clip-${sx}-${sy})">${escapeXml(label)}</text>`+ `<text x="${PADDING}" y="${y}" font-family="monospace" font-size="12" fill="#6b7280">${escapeXml(line)}</text>`);+ continue;}++ // Sort segments by column position+ lineSegs.sort((a, b) => a.gridCol - b.gridCol);++ // Build colored tspans for each segment, with gaps in default color+ let col = 0;+ const textParts: string[] = [];+ textParts.push(`<text y="${y}" font-family="monospace" font-size="12">`);++ for (const seg of lineSegs) {+ // Gap before this segment (whitespace or untracked text)+ if (seg.gridCol > col) {+ const gapText = line.substring(col, seg.gridCol);+ if (gapText.length > 0) {+ textParts.push(+ `<tspan x="${PADDING + col * CHAR_WIDTH}" fill="#9ca3af">${escapeXml(gapText)}</tspan>`+ );+ }+ col = seg.gridCol;+ }++ // Render the segment with its snap color+ const color = COLORS[seg.snap];+ const segText = line.substring(col, col + seg.text.length);+ if (segText.length > 0) {+ textParts.push(+ `<tspan x="${PADDING + col * CHAR_WIDTH}" fill="${color.text}">${escapeXml(segText)}</tspan>`+ );+ col += seg.text.length;+ }+ }++ // Trailing text after last segment+ if (col < line.length) {+ const trailing = line.substring(col);+ if (trailing.trimEnd().length > 0) {+ textParts.push(+ `<tspan x="${PADDING + col * CHAR_WIDTH}" fill="#9ca3af">${escapeXml(trailing)}</tspan>`+ );+ }+ }++ textParts.push("</text>");+ svgParts.push(textParts.join(""));}- // Legend (top-right corner of cropped image)- const legendY = 10;- const legendX = imgWidth - 200;+ // Legend+ const legendX = contentWidth + PADDING * 2;+ const legendY = PADDING;svgParts.push(- `<rect x="${legendX - 5}" y="${legendY - 5}" width="195" height="95" fill="white" stroke="#d1d5db" stroke-width="1" rx="3"/>`+ `<rect x="${legendX}" y="${legendY}" width="${LEGEND_WIDTH}" height="${LEGEND_HEIGHT}" fill="white" stroke="#d1d5db" stroke-width="1" rx="3"/>`);- const legendItems = [- { label: "Left snap", color: COLORS.left },- { label: "Right snap", color: COLORS.right },- { label: "Center snap", color: COLORS.center },- { label: "Floating", color: COLORS.floating },- { label: "Flowing text", color: COLORS.flowing },+ const legendItems: Array<{ label: string; snap: RenderedSegment["snap"] }> = [+ { label: "Left snap", snap: "left" },+ { label: "Right snap", snap: "right" },+ { label: "Center snap", snap: "center" },+ { label: "Floating", snap: "floating" },+ { label: "Flowing text", snap: "flowing" },];for (let i = 0; i < legendItems.length; i++) {- const ly = legendY + i * 17;+ const item = legendItems[i];+ const ly = legendY + 8 + i * 17;+ const color = COLORS[item.snap];svgParts.push(- `<rect x="${legendX}" y="${ly}" width="12" height="12" fill="${legendItems[i].color.fill}" stroke="${legendItems[i].color.stroke}" stroke-width="1"/>`+ `<rect x="${legendX + 8}" y="${ly}" width="12" height="12" fill="${color.bg}" stroke="${color.text}" stroke-width="1"/>`);svgParts.push(- `<text x="${legendX + 18}" y="${ly + 10}" font-family="sans-serif" font-size="11" fill="#374151">${legendItems[i].label}</text>`+ `<text x="${legendX + 26}" y="${ly + 10}" font-family="sans-serif" font-size="11" fill="#374151">${item.label}</text>`);}@@ -216,7 +178,6 @@ export async function renderGridVisualization(const svgBuffer = Buffer.from(svgParts.join("\n"));- // Create white background image and composite SVGawait sharp({create: {width: imgWidth,