A fast, helpful, and open-source document parser
remove unused code
Logan Markewiche0b591304683
diff --git a/AGENTS.md b/AGENTS.mdindex c23acba..f8d2734 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -38,7 +38,7 @@ liteparse/1. **Input**: File path received (any supported format)2. **Conversion** (if dependencies installed): Non-PDF formats converted to PDF via LibreOffice/ImageMagick-3. **PDF Loading**: PDF.js extracts text items, paths, images, metadata+3. **PDF Loading**: PDF.js extracts text items, images, metadata4. **OCR** (if enabled): Images rendered and OCR'd for text-sparse areas5. **Grid Projection**: Spatial reconstruction of text layout using anchor system6. **Post-processing**: Bounding boxes, text cleanupdiff --git a/src/engines/pdf/README.md b/src/engines/pdf/README.mdindex 1070b79..0916ad8 100644--- a/src/engines/pdf/README.md+++ b/src/engines/pdf/README.md@@ -21,8 +21,7 @@ interface PdfEngine {**Key Data Types:**- `PdfDocument` - Loaded document with `numPages`, `data` (Uint8Array), `metadata`-- `PageData` - Extracted page: `pageNum`, `width`, `height`, `textItems`, `paths`, `images`, `annotations`-- `Path` - Vector path: `type` ('rectangle'|'line'|'curve'), `points`, `color`, `width`+- `PageData` - Extracted page: `pageNum`, `width`, `height`, `textItems`, `images`, `annotations`- `Image` - Embedded image with position, dimensions, and optional OCR data- `Annotation` - PDF annotation (links, etc.)diff --git a/src/engines/pdf/interface.ts b/src/engines/pdf/interface.tsindex 8d0b202..7486582 100644--- a/src/engines/pdf/interface.ts+++ b/src/engines/pdf/interface.ts@@ -20,7 +20,6 @@ export interface PageData {width: number;height: number;textItems: TextItem[];- paths: Path[];images: Image[];annotations?: Annotation[];}diff --git a/src/engines/pdf/pdfjs.ts b/src/engines/pdf/pdfjs.tsindex a2cab95..7cf4a22 100644--- a/src/engines/pdf/pdfjs.ts+++ b/src/engines/pdf/pdfjs.ts@@ -1,7 +1,7 @@import fs from "node:fs/promises";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";-import { PdfEngine, PdfDocument, PageData, Path, Image, Annotation } from "./interface.js";+import { PdfEngine, PdfDocument, PageData, Image, Annotation } from "./interface.js";import { TextItem } from "../../core/types.js";import { PdfiumRenderer } from "./pdfium-renderer.js";@@ -240,8 +240,6 @@ export class PdfJsEngine implements PdfEngine {});}- // For now, paths and images are empty - we'll add extraction logic later- const paths: Path[] = [];const images: Image[] = [];// Skip annotation extraction - not currently used in processing pipeline@@ -255,7 +253,6 @@ export class PdfJsEngine implements PdfEngine {width: viewport.width,height: viewport.height,textItems,- paths,images,annotations,};diff --git a/src/processing/README.md b/src/processing/README.mdindex e5c7744..4186330 100644--- a/src/processing/README.md+++ b/src/processing/README.md@@ -50,7 +50,6 @@ This is the core algorithm that converts raw PDF text items into readable, prope**Design Decisions:**- **Anchor rounding**: Groups anchor x-coords by nearest 1/4 unit to handle slight variations- **Sparse block compression**: Reduces excessive whitespace in sparse layouts (>70% whitespace)-- **Vertical line anchoring**: Uses PDF path lines to establish column boundaries- **Small text filtering**: Lines with >50% small text can be filtered (configurable)---@@ -83,21 +82,6 @@ This is the core algorithm that converts raw PDF text items into readable, prope----### pathUtils.ts-**Extract lines from PDF vector paths.**--Provides input for layout analysis.--`getVerticalAndHorizontalLinesFromPagePaths(config, paths)`:-- Extracts vertical lines (x1 ≈ x2) from line paths-- Extracts horizontal lines (y1 ≈ y2) from line paths-- Extracts edges from rectangle paths-- Returns `{ verticalLines, horizontalLines }`--Used by `gridProjection.ts` to establish column anchors from visible lines.------### ocrUtils.ts**OCR result parsing and coordinate conversion.**diff --git a/src/processing/gridProjection.ts b/src/processing/gridProjection.tsindex b55117f..ab539a6 100644--- a/src/processing/gridProjection.ts+++ b/src/processing/gridProjection.ts@@ -4,7 +4,6 @@ import { cleanRawText } from "./cleanText.js";import { ProjectionTextBox, Coordinates, LiteParseConfig, ParsedPage } from "../core/types.js";import { PageData } from "../engines/pdf/interface.js";-import { getVerticalAndHorizontalLinesFromPagePaths, VerticalLine } from "./pathUtils.js";import { applyMarkupTags } from "./markupUtils.js";// Minimum spaces between unsnapped bboxes (likely justified text@@ -141,53 +140,13 @@ function fixSparseBlocks(blocks: LineRange[], rawLines: string[]) {}}-function extractAnchorsPointsFromLines(- lines: ProjectionTextBox[][],- page: PageData,- verticalLines: VerticalLine[]-): Anchors {+function extractAnchorsPointsFromLines(lines: ProjectionTextBox[][], page: PageData): Anchors {const pageHeight = page.height;const anchorLeft: Anchor = {};const anchorRight: Anchor = {};const anchorCenter: Anchor = {};- // Add anchors from vertical lines to ensure horizontal gaps- // This creates left and right anchors at vertical line positions- for (const vLine of verticalLines) {- const leftAnchor = roundAnchor(vLine.x);- const rightAnchor = roundAnchor(vLine.x + vLine.width);-- if (!anchorLeft[leftAnchor]) {- anchorLeft[leftAnchor] = [];- }- if (!anchorRight[rightAnchor]) {- anchorRight[rightAnchor] = [];- }-- // Create dummy bboxes spanning the vertical line height to establish the anchor- const dummyBboxLeft = {- x: vLine.x,- y: vLine.y1,- w: 0,- h: vLine.height,- str: "",- strLength: 0,- } as ProjectionTextBox;-- const dummyBboxRight = {- x: vLine.x + vLine.width,- y: vLine.y1,- w: 0,- h: vLine.height,- str: "",- strLength: 0,- } as ProjectionTextBox;-- anchorLeft[leftAnchor].push(dummyBboxLeft);- anchorRight[rightAnchor].push(dummyBboxRight);- }-for (const line of lines) {for (const bbox of line) {let anchor = roundAnchor(bbox.x);@@ -1042,13 +1001,6 @@ export function projectToGrid(let medianWidth = pageMedianSizes.width;const medianHeight = pageMedianSizes.height;- const { verticalLines: rawVerticalLines, horizontalLines: _horizontalLines } =- getVerticalAndHorizontalLinesFromPagePaths(config, page.paths);- // filter vertical and horizontal lines are less than 80% of page.width / height- const verticalLines = rawVerticalLines.filter((line) => line.height > page.height * 0.8);- // horizontalLines filtered but not currently used - reserved for future detection- void _horizontalLines.filter((line) => line.width > page.width * 0.8);-// Save original bboxes (including OCR) for text attributionconst attributionBboxes: ProjectionTextBox[] = [];for (const bbox of projectionBoxes as ProjectionTextBox[]) {@@ -1127,8 +1079,7 @@ export function projectToGrid(for (const block of blocks) {const { anchorLeft, anchorRight, anchorCenter } = extractAnchorsPointsFromLines(lines.slice(block.start, block.end),- page,- verticalLines+ page);const snapMaps: SnapMaps = {diff --git a/src/processing/markupUtils.ts b/src/processing/markupUtils.tsindex 94d91ab..718ff3e 100644--- a/src/processing/markupUtils.ts+++ b/src/processing/markupUtils.ts@@ -2,7 +2,7 @@ import { MarkupData } from "../core/types.js";/*** Apply markup tags to text based on markup data- * Returns text with inline markup tags that can be converted to markdown later+ * Returns text with inline markup tags that can be converted to other formats later*/export function applyMarkupTags(markup: MarkupData, text: string): string {let result = text;diff --git a/src/processing/pathUtils.ts b/src/processing/pathUtils.tsdeleted file mode 100644index 48f6eed..0000000--- a/src/processing/pathUtils.ts+++ /dev/null@@ -1,103 +0,0 @@-import { Path } from "../engines/pdf/interface.js";-import { LiteParseConfig } from "../core/types.js";--export interface Line {- x: number;- y1: number;- y2: number;- width: number;- height: number;-}--export type VerticalLine = Line;-export type HorizontalLine = Line;--/**- * Extract vertical and horizontal lines from PDF paths- */-export function getVerticalAndHorizontalLinesFromPagePaths(- _config: LiteParseConfig,- paths: Path[]-): { verticalLines: VerticalLine[]; horizontalLines: HorizontalLine[] } {- const verticalLines: VerticalLine[] = [];- const horizontalLines: HorizontalLine[] = [];-- // Simplified version - full implementation would analyze path types- // and extract line segments from rectangles and line paths-- for (const path of paths) {- if (path.type === "line" && path.points.length >= 2) {- const [start, end] = path.points;- const [x1, y1] = start;- const [x2, y2] = end;-- // Check if vertical (x coordinates similar)- if (Math.abs(x2 - x1) < 2) {- verticalLines.push({- x: (x1 + x2) / 2,- y1: Math.min(y1, y2),- y2: Math.max(y1, y2),- width: path.width || 1,- height: Math.abs(y2 - y1),- });- }- // Check if horizontal (y coordinates similar)- else if (Math.abs(y2 - y1) < 2) {- horizontalLines.push({- x: Math.min(x1, x2),- y1: (y1 + y2) / 2,- y2: (y1 + y2) / 2,- width: Math.abs(x2 - x1),- height: path.width || 1,- });- }- }- // Handle rectangles as potential borders- else if (path.type === "rectangle" && path.points.length >= 4) {- const xs = path.points.map((p) => p[0]);- const ys = path.points.map((p) => p[1]);- const minX = Math.min(...xs);- const maxX = Math.max(...xs);- const minY = Math.min(...ys);- const maxY = Math.max(...ys);-- // Add vertical edges- verticalLines.push(- {- x: minX,- y1: minY,- y2: maxY,- width: path.width || 1,- height: maxY - minY,- },- {- x: maxX,- y1: minY,- y2: maxY,- width: path.width || 1,- height: maxY - minY,- }- );-- // Add horizontal edges- horizontalLines.push(- {- x: minX,- y1: minY,- y2: minY,- width: maxX - minX,- height: path.width || 1,- },- {- x: minX,- y1: maxY,- y2: maxY,- width: maxX - minX,- height: path.width || 1,- }- );- }- }-- return { verticalLines, horizontalLines };-}diff --git a/src/processing/tables.ts b/src/processing/tables.tsdeleted file mode 100644index 7846ecb..0000000--- a/src/processing/tables.ts+++ /dev/null@@ -1,329 +0,0 @@-import { Path } from "../engines/pdf/interface.js";-import { TextItem } from "../core/types.js";--export interface DetectedTable {- x1: number;- y1: number;- x2: number;- y2: number;- rows: number;- cols: number;- cells?: TableCell[];-}--export interface TableCell {- x1: number;- y1: number;- x2: number;- y2: number;- text: string;- row: number;- col: number;-}--interface Line {- x1: number;- y1: number;- x2: number;- y2: number;- isHorizontal: boolean;-}--interface Intersection {- x: number;- y: number;-}--/**- * Extract horizontal and vertical lines from paths- */-function extractLines(paths: Path[]): { horizontal: Line[]; vertical: Line[] } {- const horizontal: Line[] = [];- const vertical: Line[] = [];- const tolerance = 2; // Tolerance for determining if a line is horizontal/vertical-- for (const path of paths) {- if (path.type === "line" && path.points.length >= 2) {- const [start, end] = path.points;- const [x1, y1] = start;- const [x2, y2] = end;-- const dx = Math.abs(x2 - x1);- const dy = Math.abs(y2 - y1);-- // Horizontal line- if (dy < tolerance && dx > 10) {- horizontal.push({- x1: Math.min(x1, x2),- y1: (y1 + y2) / 2,- x2: Math.max(x1, x2),- y2: (y1 + y2) / 2,- isHorizontal: true,- });- }- // Vertical line- else if (dx < tolerance && dy > 10) {- vertical.push({- x1: (x1 + x2) / 2,- y1: Math.min(y1, y2),- x2: (x1 + x2) / 2,- y2: Math.max(y1, y2),- isHorizontal: false,- });- }- }- // Extract lines from rectangles- else if (path.type === "rectangle" && path.points.length >= 4) {- const xs = path.points.map((p) => p[0]);- const ys = path.points.map((p) => p[1]);- const minX = Math.min(...xs);- const maxX = Math.max(...xs);- const minY = Math.min(...ys);- const maxY = Math.max(...ys);-- // Add edges as lines- horizontal.push(- { x1: minX, y1: minY, x2: maxX, y2: minY, isHorizontal: true },- { x1: minX, y1: maxY, x2: maxX, y2: maxY, isHorizontal: true }- );- vertical.push(- { x1: minX, y1: minY, x2: minX, y2: maxY, isHorizontal: false },- { x1: maxX, y1: minY, x2: maxX, y2: maxY, isHorizontal: false }- );- }- }-- return { horizontal, vertical };-}--/**- * Find intersections between horizontal and vertical lines- */-function findIntersections(- horizontal: Line[],- vertical: Line[],- tolerance: number = 3-): Intersection[] {- const intersections: Intersection[] = [];- const seen = new Set<string>();-- for (const h of horizontal) {- for (const v of vertical) {- // Check if lines intersect- const hY = h.y1;- const vX = v.x1;-- // Check if intersection is within line bounds- if (- vX >= h.x1 - tolerance &&- vX <= h.x2 + tolerance &&- hY >= v.y1 - tolerance &&- hY <= v.y2 + tolerance- ) {- const key = `${Math.round(vX)},${Math.round(hY)}`;- if (!seen.has(key)) {- intersections.push({ x: vX, y: hY });- seen.add(key);- }- }- }- }-- return intersections;-}--/**- * Cluster nearby lines together- */-function clusterLines(lines: Line[], isHorizontal: boolean): Line[] {- if (lines.length === 0) return [];-- // Sort lines by position- const sorted = [...lines].sort((a, b) => {- return isHorizontal ? a.y1 - b.y1 : a.x1 - b.x1;- });-- const clusters: Line[] = [];- let current = sorted[0];-- for (let i = 1; i < sorted.length; i++) {- const line = sorted[i];- const threshold = 5;-- // Check if lines are close enough to merge- const distance = isHorizontal ? Math.abs(line.y1 - current.y1) : Math.abs(line.x1 - current.x1);-- if (distance < threshold) {- // Merge lines- if (isHorizontal) {- current.x1 = Math.min(current.x1, line.x1);- current.x2 = Math.max(current.x2, line.x2);- current.y1 = (current.y1 + line.y1) / 2;- current.y2 = current.y1;- } else {- current.y1 = Math.min(current.y1, line.y1);- current.y2 = Math.max(current.y2, line.y2);- current.x1 = (current.x1 + line.x1) / 2;- current.x2 = current.x1;- }- } else {- clusters.push(current);- current = line;- }- }- clusters.push(current);-- return clusters;-}--/**- * Create cells from intersections- */-function createCellsFromIntersections(intersections: Intersection[]): TableCell[] {- if (intersections.length < 4) return [];-- // Sort intersections- const sorted = [...intersections].sort((a, b) => {- if (Math.abs(a.y - b.y) < 2) return a.x - b.x;- return a.y - b.y;- });-- // Find unique x and y coordinates- const xCoords = [...new Set(sorted.map((i) => Math.round(i.x)))].sort((a, b) => a - b);- const yCoords = [...new Set(sorted.map((i) => Math.round(i.y)))].sort((a, b) => a - b);-- const cells: TableCell[] = [];-- // Create cells from grid- for (let row = 0; row < yCoords.length - 1; row++) {- for (let col = 0; col < xCoords.length - 1; col++) {- cells.push({- x1: xCoords[col],- y1: yCoords[row],- x2: xCoords[col + 1],- y2: yCoords[row + 1],- text: "",- row,- col,- });- }- }-- return cells;-}--/**- * Assign text items to cells- */-function assignTextToCells(cells: TableCell[], textItems: TextItem[]): void {- for (const cell of cells) {- const cellText: string[] = [];-- for (const item of textItems) {- // Check if text item overlaps with cell- const itemCenterX = item.x + item.w / 2;- const itemCenterY = item.y + item.h / 2;-- if (- itemCenterX >= cell.x1 &&- itemCenterX <= cell.x2 &&- itemCenterY >= cell.y1 &&- itemCenterY <= cell.y2- ) {- cellText.push(item.str);- }- }-- cell.text = cellText.join(" ").trim();- }-}--/**- * Validate if detected structure is a valid table- */-function isValidTable(- cells: TableCell[],- minCells: number = 4,- minRows: number = 2,- minCols: number = 2-): boolean {- if (cells.length < minCells) return false;-- const rows = new Set(cells.map((c) => c.row)).size;- const cols = new Set(cells.map((c) => c.col)).size;-- return rows >= minRows && cols >= minCols;-}--/**- * Detect tables using heuristic methods (outlined paths)- * Uses line intersection detection to find table grid structures- */-export function detectTables(paths: Path[], textItems: TextItem[] = []): DetectedTable[] {- const tables: DetectedTable[] = [];-- // Extract lines from paths- const { horizontal, vertical } = extractLines(paths);-- if (horizontal.length < 2 || vertical.length < 2) {- return tables;- }-- // Cluster nearby lines to reduce noise- const clusteredH = clusterLines(horizontal, true);- const clusteredV = clusterLines(vertical, false);-- // Find intersections- const intersections = findIntersections(clusteredH, clusteredV);-- if (intersections.length < 4) {- return tables;- }-- // Create cells from intersections- const cells = createCellsFromIntersections(intersections);-- if (!isValidTable(cells)) {- return tables;- }-- // Assign text to cells- assignTextToCells(cells, textItems);-- // Calculate table bounds- const xCoords = cells.map((c) => c.x1).concat(cells.map((c) => c.x2));- const yCoords = cells.map((c) => c.y1).concat(cells.map((c) => c.y2));-- const rows = new Set(cells.map((c) => c.row)).size;- const cols = new Set(cells.map((c) => c.col)).size;-- tables.push({- x1: Math.min(...xCoords),- y1: Math.min(...yCoords),- x2: Math.max(...xCoords),- y2: Math.max(...yCoords),- rows,- cols,- cells,- });-- return tables;-}--/** Extracted table structure */-export interface TableStructure {- rows: number;- cols: number;- cells: TableCell[];-}--/**- * Extract table structure from detected table region- */-export function extractTableStructure(table: DetectedTable, _paths: Path[]): TableStructure {- return {- rows: table.rows,- cols: table.cols,- cells: table.cells || [],- };-}