Skip to content

A fast, helpful, and open-source document parser

Fix cicd errors

Logan Markewicha95e7358387e
diff --git a/cli/parse.ts b/cli/parse.ts
index 3787212..dd695ee 100644
--- a/cli/parse.ts
+++ b/cli/parse.ts
@@ -6,6 +6,50 @@ import { LiteParse } from "../src/core/parser.js";
import { LiteParseConfig, OutputFormat } from "../src/core/types.js";
import { performance } from "perf_hooks";
+/** Options for the parse command */
+interface ParseCommandOptions {
+ output?: string;
+ format?: string;
+ ocrServerUrl?: string;
+ ocr?: boolean;
+ ocrLanguage?: string;
+ maxPages?: string;
+ targetPages?: string;
+ dpi?: string;
+ tables?: boolean;
+ preciseBbox?: boolean;
+ skipDiagonalText?: boolean;
+ preserveSmallText?: boolean;
+ config?: string;
+ quiet?: boolean;
+}
+
+/** Options for the screenshot command */
+interface ScreenshotCommandOptions {
+ outputDir?: string;
+ pages?: string;
+ dpi?: string;
+ format?: string;
+ config?: string;
+ quiet?: boolean;
+}
+
+/** Options for the batch-parse command */
+interface BatchParseCommandOptions {
+ format?: string;
+ ocrServerUrl?: string;
+ ocr?: boolean;
+ ocrLanguage?: string;
+ maxPages?: string;
+ dpi?: string;
+ tables?: boolean;
+ preciseBbox?: boolean;
+ recursive?: boolean;
+ extension?: string;
+ config?: string;
+ quiet?: boolean;
+}
+
const program = new Command();
program
@@ -30,7 +74,7 @@ program
.option("--preserve-small-text", "Preserve very small text")
.option("--config <file>", "Config file (JSON)")
.option("-q, --quiet", "Suppress progress output")
- .action(async (file: string, options: any) => {
+ .action(async (file: string, options: ParseCommandOptions) => {
try {
const quiet = options.quiet || false;
@@ -59,9 +103,9 @@ program
ocrEnabled: options.ocr !== false,
ocrServerUrl: options.ocrServerUrl,
ocrLanguage: options.ocrLanguage,
- maxPages: parseInt(options.maxPages),
+ maxPages: parseInt(options.maxPages || "1000"),
targetPages: options.targetPages,
- dpi: parseInt(options.dpi),
+ dpi: parseInt(options.dpi || "150"),
tableDetection: options.tables !== false,
preciseBoundingBox: options.preciseBbox !== false,
skipDiagonalText: options.skipDiagonalText || false,
@@ -96,10 +140,12 @@ program
// Output result to stdout (can be piped)
console.log(output);
}
- } catch (error: any) {
- console.error(`\nError: ${error.message}`);
- if (error.stack) {
- console.error(error.stack);
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ const stack = error instanceof Error ? error.stack : undefined;
+ console.error(`\nError: ${message}`);
+ if (stack) {
+ console.error(stack);
}
process.exit(1);
}
@@ -114,7 +160,7 @@ program
.option("--format <format>", "Image format: png|jpg", "png")
.option("--config <file>", "Config file (JSON)")
.option("-q, --quiet", "Suppress progress output")
- .action(async (file: string, options: any) => {
+ .action(async (file: string, options: ScreenshotCommandOptions) => {
try {
const quiet = options.quiet || false;
@@ -139,7 +185,7 @@ program
// Override with CLI options
config = {
...config,
- dpi: parseInt(options.dpi),
+ dpi: parseInt(options.dpi || "150"),
};
// Parse target pages
@@ -148,9 +194,11 @@ program
pageNumbers = parsePageNumbers(options.pages);
}
+ const outputDir = options.outputDir || "./screenshots";
+
// Create output directory
- if (!existsSync(options.outputDir)) {
- await fs.mkdir(options.outputDir, { recursive: true });
+ if (!existsSync(outputDir)) {
+ await fs.mkdir(outputDir, { recursive: true });
}
// Create parser
@@ -161,8 +209,8 @@ program
// Save screenshots
for (const result of results) {
- const filename = `page_${result.pageNum}.${options.format}`;
- const filepath = `${options.outputDir}/${filename}`;
+ const filename = `page_${result.pageNum}.${options.format || "png"}`;
+ const filepath = `${outputDir}/${filename}`;
await fs.writeFile(filepath, result.imageBuffer);
if (!quiet) {
console.error(`✓ ${filepath} (${result.width}x${result.height})`);
@@ -170,12 +218,14 @@ program
}
if (!quiet) {
- console.error(`\n✓ Generated ${results.length} screenshots → ${options.outputDir}`);
+ console.error(`\n✓ Generated ${results.length} screenshots → ${outputDir}`);
}
- } catch (error: any) {
- console.error(`\nError: ${error.message}`);
- if (error.stack) {
- console.error(error.stack);
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ const stack = error instanceof Error ? error.stack : undefined;
+ console.error(`\nError: ${message}`);
+ if (stack) {
+ console.error(stack);
}
process.exit(1);
}
@@ -238,7 +288,7 @@ program
.option("--extension <ext>", 'Only process files with this extension (e.g., ".pdf")')
.option("--config <file>", "Config file (JSON)")
.option("-q, --quiet", "Suppress progress output")
- .action(async (inputDir: string, outputDir: string, options: any) => {
+ .action(async (inputDir: string, outputDir: string, options: BatchParseCommandOptions) => {
try {
const quiet = options.quiet || false;
const startTime = performance.now();
@@ -261,7 +311,7 @@ program
}
// Find all files to process
- const files = findFiles(inputDir, options.recursive, options.extension);
+ const files = findFiles(inputDir, options.recursive || false, options.extension);
if (files.length === 0) {
console.error("No supported files found in input directory");
@@ -290,8 +340,8 @@ program
ocrEnabled: options.ocr !== false,
ocrServerUrl: options.ocrServerUrl,
ocrLanguage: options.ocrLanguage,
- maxPages: parseInt(options.maxPages),
- dpi: parseInt(options.dpi),
+ maxPages: parseInt(options.maxPages || "1000"),
+ dpi: parseInt(options.dpi || "150"),
tableDetection: options.tables !== false,
preciseBoundingBox: options.preciseBbox !== false,
};
@@ -336,10 +386,11 @@ program
`[${i + 1}/${files.length}] ✓ ${relativePath} (${result.pages.length} pages, ${fileTime}ms)`
);
}
- } catch (error: any) {
+ } catch (error: unknown) {
errorCount++;
if (!quiet) {
- console.error(`[${i + 1}/${files.length}] ✗ ${relativePath}: ${error.message}`);
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(`[${i + 1}/${files.length}] ✗ ${relativePath}: ${message}`);
}
}
}
@@ -358,10 +409,12 @@ program
if (errorCount > 0) {
process.exit(1);
}
- } catch (error: any) {
- console.error(`\nError: ${error.message}`);
- if (error.stack) {
- console.error(error.stack);
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ const stack = error instanceof Error ? error.stack : undefined;
+ console.error(`\nError: ${message}`);
+ if (stack) {
+ console.error(stack);
}
process.exit(1);
}
diff --git a/src/conversion/convertToPdf.ts b/src/conversion/convertToPdf.ts
index 36b90e0..852f789 100644
--- a/src/conversion/convertToPdf.ts
+++ b/src/conversion/convertToPdf.ts
@@ -289,13 +289,19 @@ async function convertImageToPdf(filePath: string, outputDir: string): Promise<s
if (errorMsg.includes("gs") && errorMsg.includes("command not found")) {
throw new Error(
`Ghostscript is required to convert ${ext.toUpperCase().slice(1)} files but is not installed. ` +
- "On macOS: brew install ghostscript, On Ubuntu: apt-get install ghostscript"
+ "On macOS: brew install ghostscript, On Ubuntu: apt-get install ghostscript",
+ {
+ cause: error,
+ }
);
}
if (errorMsg.includes("FailedToExecuteCommand") && errorMsg.includes("gs")) {
throw new Error(
`Ghostscript failed during ${ext.toUpperCase().slice(1)} conversion. ` +
- "Ensure Ghostscript is properly installed: brew install ghostscript"
+ "Ensure Ghostscript is properly installed: brew install ghostscript",
+ {
+ cause: error,
+ }
);
}
throw error;
diff --git a/src/core/parser.ts b/src/core/parser.ts
index b751eeb..f85d4d0 100644
--- a/src/core/parser.ts
+++ b/src/core/parser.ts
@@ -1,6 +1,6 @@
-import { LiteParseConfig, ParseResult, ScreenshotResult } from "./types.js";
+import { LiteParseConfig, ParseResult, ScreenshotResult, TextItem } from "./types.js";
import { mergeConfig } from "./config.js";
-import { PdfEngine } from "../engines/pdf/interface.js";
+import { PdfEngine, PdfDocument, PageData } from "../engines/pdf/interface.js";
import { PdfJsEngine } from "../engines/pdf/pdfjs.js";
import { PdfiumRenderer } from "../engines/pdf/pdfium-renderer.js";
import { OcrEngine } from "../engines/ocr/interface.js";
@@ -198,7 +198,11 @@ export class LiteParse {
/**
* Run OCR on pages that need it
*/
- private async runOCR(doc: any, pages: any[], log: (msg: string) => void): Promise<void> {
+ private async runOCR(
+ doc: PdfDocument,
+ pages: PageData[],
+ log: (msg: string) => void
+ ): Promise<void> {
if (!this.ocrEngine) return;
log("Running OCR on pages...");
@@ -208,7 +212,7 @@ export class LiteParse {
// Check if page has very little text (indicating need for OCR)
const textLength = page.textItems.reduce(
- (sum: number, item: any) => sum + item.str.length,
+ (sum: number, item: TextItem) => sum + item.str.length,
0
);
@@ -246,7 +250,7 @@ export class LiteParse {
.filter((s: string) => s.length > 0)
);
- const ocrTextItems = ocrResults
+ const ocrTextItems: TextItem[] = ocrResults
.filter((r) => r.confidence > 0.1) // Filter low confidence
.filter((r) => {
// Filter out OCR text that already exists in native PDF text
@@ -259,9 +263,10 @@ export class LiteParse {
y: r.bbox[1],
width: r.bbox[2] - r.bbox[0],
height: r.bbox[3] - r.bbox[1],
+ w: r.bbox[2] - r.bbox[0],
+ h: r.bbox[3] - r.bbox[1],
fontName: "OCR",
fontSize: r.bbox[3] - r.bbox[1],
- fromOcr: true,
}));
// Add OCR text items directly to page textItems
diff --git a/src/core/types.ts b/src/core/types.ts
index 4b174a5..ea752f3 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -115,10 +115,31 @@ export interface ParsedPage {
tables?: DetectedTable[];
}
+/** JSON output format for parsed document */
+export interface ParseResultJson {
+ pages: Array<{
+ page: number;
+ width: number;
+ height: number;
+ text: string;
+ textItems: Array<{
+ text: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ fontName?: string;
+ fontSize?: number;
+ }>;
+ boundingBoxes: BoundingBox[];
+ tables: DetectedTable[];
+ }>;
+}
+
export interface ParseResult {
pages: ParsedPage[];
text: string;
- json?: any;
+ json?: ParseResultJson;
}
export interface ScreenshotResult {
diff --git a/src/engines/ocr/http-simple.ts b/src/engines/ocr/http-simple.ts
index ee87ee8..b1a4b49 100644
--- a/src/engines/ocr/http-simple.ts
+++ b/src/engines/ocr/http-simple.ts
@@ -3,6 +3,13 @@ import FormData from "form-data";
import fs from "fs";
import { OcrEngine, OcrOptions, OcrResult } from "./interface.js";
+/** Response item from the HTTP OCR server */
+interface HttpOcrResponseItem {
+ text: string;
+ bbox: [number, number, number, number];
+ confidence: number;
+}
+
/**
* HTTP-based OCR engine that conforms to LiteParse OCR API specification.
*
@@ -46,9 +53,9 @@ export class HttpOcrEngine implements OcrEngine {
console.warn("Got OCR results from server");
- return results.map((item: any) => ({
+ return results.map((item: HttpOcrResponseItem) => ({
text: item.text,
- bbox: item.bbox as [number, number, number, number],
+ bbox: item.bbox,
confidence: item.confidence,
}));
} catch (error) {
diff --git a/src/engines/pdf/interface.ts b/src/engines/pdf/interface.ts
index d7d86cd..8d0b202 100644
--- a/src/engines/pdf/interface.ts
+++ b/src/engines/pdf/interface.ts
@@ -12,7 +12,7 @@ export interface PdfEngine {
export interface PdfDocument {
numPages: number;
data: Uint8Array;
- metadata?: any;
+ metadata?: unknown;
}
export interface PageData {
diff --git a/src/engines/pdf/pdfjs.ts b/src/engines/pdf/pdfjs.ts
index 16a3bf1..a2cab95 100644
--- a/src/engines/pdf/pdfjs.ts
+++ b/src/engines/pdf/pdfjs.ts
@@ -5,6 +5,47 @@ import { PdfEngine, PdfDocument, PageData, Path, Image, Annotation } from "./int
import { TextItem } from "../../core/types.js";
import { PdfiumRenderer } from "./pdfium-renderer.js";
+/** PDF.js internal document type - opaque to our code */
+interface PdfJsDocument {
+ numPages: number;
+ getPage(pageNum: number): Promise<PdfJsPage>;
+ getMetadata(): Promise<unknown>;
+ destroy(): Promise<void>;
+}
+
+/** PDF.js internal page type */
+interface PdfJsPage {
+ getViewport(params: { scale: number }): PdfJsViewport;
+ getTextContent(): Promise<PdfJsTextContent>;
+ cleanup(): Promise<void>;
+}
+
+/** PDF.js viewport type */
+interface PdfJsViewport {
+ width: number;
+ height: number;
+ transform: number[];
+}
+
+/** PDF.js text content type */
+interface PdfJsTextContent {
+ items: PdfJsTextItem[];
+}
+
+/** PDF.js text item type */
+interface PdfJsTextItem {
+ str: string;
+ transform: number[];
+ width: number;
+ height: number;
+ fontName?: string;
+}
+
+/** Extended PdfDocument with internal PDF.js document reference */
+interface PdfJsExtendedDocument extends PdfDocument {
+ _pdfDocument: PdfJsDocument;
+}
+
// Dynamic import of PDF.js
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -110,11 +151,11 @@ export class PdfJsEngine implements PdfEngine {
data,
metadata,
_pdfDocument: pdfDocument,
- } as PdfDocument & { _pdfDocument: any };
+ } as PdfJsExtendedDocument;
}
async extractPage(doc: PdfDocument, pageNum: number): Promise<PageData> {
- const pdfDocument = (doc as any)._pdfDocument;
+ const pdfDocument = (doc as PdfJsExtendedDocument)._pdfDocument;
const page = await pdfDocument.getPage(pageNum);
// Get viewport
@@ -127,7 +168,7 @@ export class PdfJsEngine implements PdfEngine {
const viewportTransform = viewport.transform;
const textItems: TextItem[] = [];
- for (const item of textContent.items as any[]) {
+ for (const item of textContent.items) {
// Skip items with zero dimensions
if (item.height === 0 || item.width === 0) continue;
@@ -262,7 +303,7 @@ export class PdfJsEngine implements PdfEngine {
}
async close(doc: PdfDocument): Promise<void> {
- const pdfDocument = (doc as any)._pdfDocument;
+ const pdfDocument = (doc as PdfJsExtendedDocument)._pdfDocument;
if (pdfDocument && pdfDocument.destroy) {
await pdfDocument.destroy();
}
diff --git a/src/output/json.ts b/src/output/json.ts
index 2ee156f..dde402c 100644
--- a/src/output/json.ts
+++ b/src/output/json.ts
@@ -1,9 +1,9 @@
-import { ParseResult, ParsedPage } from "../core/types.js";
+import { ParseResult, ParsedPage, ParseResultJson } from "../core/types.js";
/**
* Build JSON output from parsed pages
*/
-export function buildJSON(pages: ParsedPage[]): any {
+export function buildJSON(pages: ParsedPage[]): ParseResultJson {
return {
pages: pages.map((page) => ({
page: page.pageNum,
diff --git a/src/processing/gridProjection.ts b/src/processing/gridProjection.ts
index 51cda5d..041356f 100644
--- a/src/processing/gridProjection.ts
+++ b/src/processing/gridProjection.ts
@@ -1165,7 +1165,7 @@ export function projectToGrid(
if (!config.preserveLayoutAlignmentAcrossPages) {
const sizes = getMedianTextBoxSize(lines.slice(block.start, block.end).flat());
medianWidth = sizes.width;
-
+
// medianHeight updated but not currently used per-block - reserved for future use
void sizes.height;
}
diff --git a/src/processing/tables.ts b/src/processing/tables.ts
index ebd5bd0..7846ecb 100644
--- a/src/processing/tables.ts
+++ b/src/processing/tables.ts
@@ -310,10 +310,17 @@ export function detectTables(paths: Path[], textItems: TextItem[] = []): Detecte
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[]): any {
+export function extractTableStructure(table: DetectedTable, _paths: Path[]): TableStructure {
return {
rows: table.rows,
cols: table.cols,