A fast, helpful, and open-source document parser
make the docs example simple by adding a new helper
Logan Markewich3f0f762057f1
diff --git a/docs/src/content/docs/liteparse/guides/visual-citations.md b/docs/src/content/docs/liteparse/guides/visual-citations.mdindex 11e8f1f..3811c60 100644--- a/docs/src/content/docs/liteparse/guides/visual-citations.md+++ b/docs/src/content/docs/liteparse/guides/visual-citations.md@@ -72,12 +72,34 @@ function itemToPixels(item, dpi = 150) {For example, at the default 150 DPI the scale factor is `150 / 72 ≈ 2.08`, so a text item at `(72, 200)` maps to pixel `(150, 416)`.+## Searching for phrases with `searchItems`++A single text item often contains just one word or fragment. A phrase like `"0°C to 70°C"` may span several adjacent items. The `searchItems` utility handles this — it concatenates consecutive items, finds matches, and returns merged text items with combined bounding boxes:++```typescript+import { LiteParse, searchItems } from "@llamaindex/liteparse";++const parser = new LiteParse({ outputFormat: "json" });+const result = await parser.parse("report.pdf");++for (const page of result.json.pages) {+ const matches = searchItems(page.textItems, { phrase: "0°C to 70°C" });+ for (const match of matches) {+ console.log(`Found "${match.text}" at (${match.x}, ${match.y}) ${match.width}×${match.height}`);+ }+}+```++Each returned item has the same shape as a regular text item, with merged coordinates spanning all the items that contributed to the match.++For single-word searches, iterating `textItems` individually (as shown in the library usage section above) is simpler and works fine.+## Full example: highlighting citations with sharp-Here's a complete workflow that parses a PDF, searches for matching text, and draws yellow highlight boxes on the page screenshot:+Here's a complete workflow that parses a PDF, searches for a phrase, and draws yellow highlight boxes on the page screenshot:```typescript-import { LiteParse } from "@llamaindex/liteparse";+import { LiteParse, searchItems } from "@llamaindex/liteparse";import sharp from "sharp";const DPI = 150;@@ -86,40 +108,36 @@ const SCALE = DPI / 72;async function main() {const parser = new LiteParse({ outputFormat: "json", dpi: DPI });- const result = await parser.parse("report.pdf");- const screenshots = await parser.screenshot("report.pdf");+ const result = await parser.parse("manual.pdf");+ const screenshots = await parser.screenshot("manual.pdf");- // Search for text items containing a query, grouped by page- const query = "revenue";+ // Search for a phrase, grouped by page+ const query = "0°C to 70°C";const hitsByPage = new Map<number, Array<{ x: number; y: number; width: number; height: number }>>();for (const page of result.json?.pages || []) {- for (const item of page.textItems) {- if (item.text.toLowerCase().includes(query)) {- if (!hitsByPage.has(page.page)) hitsByPage.set(page.page, []);- hitsByPage.get(page.page)!.push(item);- }- }+ const matches = searchItems(page.textItems, { phrase: query });+ if (matches.length) hitsByPage.set(page.page, matches);}// Draw all highlights per page into a single image- for (const [pageNum, items] of hitsByPage) {+ for (const [pageNum, rects] of hitsByPage) {const shot = screenshots.find((s) => s.pageNum === pageNum);if (!shot) continue;const composites = await Promise.all(- items.map(async (item) => {- const rect = {- left: Math.round(item.x * SCALE),- top: Math.round(item.y * SCALE),- width: Math.round(item.width * SCALE),- height: Math.round(item.height * SCALE),+ rects.map(async (rect) => {+ const pixel = {+ left: Math.round(rect.x * SCALE),+ top: Math.round(rect.y * SCALE),+ width: Math.round(rect.width * SCALE),+ height: Math.round(rect.height * SCALE),};const overlay = await sharp({create: {- width: rect.width,- height: rect.height,+ width: pixel.width,+ height: pixel.height,channels: 4,background: { r: 255, g: 255, b: 0, alpha: 0.3 },},@@ -127,7 +145,7 @@ async function main() {.png().toBuffer();- return { input: overlay, left: rect.left, top: rect.top };+ return { input: overlay, left: pixel.left, top: pixel.top };}));@@ -137,13 +155,17 @@ async function main() {.toBuffer();await sharp(highlighted).toFile(`citation_page${pageNum}.png`);- console.log(`Saved citation_page${pageNum}.png (${items.length} highlights)`);+ console.log(`Saved citation_page${pageNum}.png (${rects.length} highlights)`);}}main().catch(console.error);```+Running this script on a PDF will produce new images with the search phrase highlighted, showing exactly where the information was found on the page.+++## CLI usageParse to JSON to get bounding boxes:diff --git a/docs/src/content/docs/liteparse/guides/visual_citation.png b/docs/src/content/docs/liteparse/guides/visual_citation.pngnew file mode 100644index 0000000..eaa6d97Binary files /dev/null and b/docs/src/content/docs/liteparse/guides/visual_citation.png differdiff --git a/src/core/types.ts b/src/core/types.tsindex 62a9bd0..cbd3db7 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -286,6 +286,34 @@ export interface ParsedPage {boundingBoxes?: BoundingBox[];}+/**+ * A text element from the JSON output with position, size, and font metadata.+ */+export interface JsonTextItem {+ /** The text content of this item. */+ text: string;+ /** X coordinate of the top-left corner, in PDF points. */+ x: number;+ /** Y coordinate of the top-left corner, in PDF points. */+ y: number;+ /** Width of the text item in PDF points. */+ width: number;+ /** Height of the text item in PDF points. */+ height: number;+ /** Font name. */+ fontName?: string;+ /** Font size in PDF points. */+ fontSize?: number;+}++/**+ * Options for {@link searchItems}.+ */+export interface SearchItemsOptions {+ /** Find text items containing this phrase (case-insensitive). Matches can span multiple adjacent items. */+ phrase: string;+}+/*** Structured JSON representation of parsed document data.* Returned when {@link LiteParseConfig.outputFormat} is `"json"`.@@ -302,15 +330,7 @@ export interface ParseResultJson {/** Full text content of the page. */text: string;/** Individual text elements with position and font metadata. */- textItems: Array<{- text: string;- x: number;- y: number;- width: number;- height: number;- fontName?: string;- fontSize?: number;- }>;+ textItems: JsonTextItem[];/*** @deprecated Use `textItems` coordinates instead. Will be removed in v2.0.*/diff --git a/src/lib.ts b/src/lib.tsindex 2484209..c82775c 100644--- a/src/lib.ts+++ b/src/lib.ts@@ -13,6 +13,7 @@* ```*/export { LiteParse } from "./core/parser.js";+export { searchItems } from "./processing/searchItems.js";export type {LiteParseConfig,LiteParseInput,@@ -22,6 +23,8 @@ export type {ParsedPage,BoundingBox,TextItem,+ JsonTextItem,+ SearchItemsOptions,ScreenshotResult,MarkupData,} from "./core/types.js";diff --git a/src/processing/searchItems.test.ts b/src/processing/searchItems.test.tsnew file mode 100644index 0000000..dc9960a--- /dev/null+++ b/src/processing/searchItems.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from "vitest";+import { searchItems } from "./searchItems";+import { JsonTextItem } from "../core/types";++function item(text: string, x: number, y: number, width: number, height = 12): JsonTextItem {+ return { text, x, y, width, height };+}++describe("searchItems", () => {+ it("matches a phrase within a single item", () => {+ const items = [item("hello world", 10, 20, 100)];+ const results = searchItems(items, { phrase: "hello world" });+ expect(results).toHaveLength(1);+ expect(results[0].text).toBe("hello world");+ expect(results[0].x).toBe(10);+ expect(results[0].width).toBe(100);+ });++ it("matches a phrase spanning multiple items", () => {+ const items = [+ item("0°C", 10, 50, 30),+ item("to", 45, 50, 15),+ item("70°C", 65, 50, 35),+ ];+ const results = searchItems(items, { phrase: "0°C to 70°C" });+ expect(results).toHaveLength(1);+ expect(results[0].text).toBe("0°C to 70°C");+ expect(results[0].x).toBe(10);+ expect(results[0].width).toBe(90); // 65 + 35 - 10+ });++ it("narrows match and does not include unrelated leading items", () => {+ const items = [+ item("Operating", 10, 50, 70),+ item("0°C to 70°C", 85, 50, 90),+ ];+ const results = searchItems(items, { phrase: "0°C to 70°C" });+ expect(results).toHaveLength(1);+ expect(results[0].x).toBe(85);+ expect(results[0].width).toBe(90);+ });++ it("is case-insensitive", () => {+ const items = [item("Revenue Grew", 10, 20, 100)];+ const results = searchItems(items, { phrase: "revenue grew" });+ expect(results).toHaveLength(1);+ expect(results[0].text).toBe("revenue grew");+ });++ it("returns empty array when no match", () => {+ const items = [item("hello", 10, 20, 50)];+ const results = searchItems(items, { phrase: "goodbye" });+ expect(results).toHaveLength(0);+ });++ it("merges bounding boxes vertically for wrapped phrases", () => {+ const items = [+ item("temperature", 10, 50, 80, 12),+ item("range", 10, 65, 40, 12),+ ];+ const results = searchItems(items, { phrase: "temperature range" });+ expect(results).toHaveLength(1);+ expect(results[0].y).toBe(50);+ expect(results[0].height).toBe(27); // 65 + 12 - 50+ });+});diff --git a/src/processing/searchItems.ts b/src/processing/searchItems.tsnew file mode 100644index 0000000..fce3884--- /dev/null+++ b/src/processing/searchItems.ts@@ -0,0 +1,82 @@+import { JsonTextItem, SearchItemsOptions } from "../core/types.js";++/**+ * Search text items for matches, returning synthetic merged items for each match.+ *+ * For phrase searches, consecutive text items are concatenated and searched.+ * When a phrase spans multiple items, the result is a single merged item with+ * combined bounding box and the matched text. Font metadata is taken from the+ * first matched item.+ *+ * @example+ * ```typescript+ * import { LiteParse, searchItems } from "@llamaindex/liteparse";+ *+ * const parser = new LiteParse({ outputFormat: "json" });+ * const result = await parser.parse("report.pdf");+ *+ * for (const page of result.json.pages) {+ * const matches = searchItems(page.textItems, { phrase: "0°C to 70°C" });+ * for (const match of matches) {+ * console.log(`Found "${match.text}" at (${match.x}, ${match.y})`);+ * }+ * }+ * ```+ */+export function searchItems(+ items: JsonTextItem[],+ options: SearchItemsOptions+): JsonTextItem[] {+ const results: JsonTextItem[] = [];+ const q = options.phrase.toLowerCase();++ let start = 0;+ while (start < items.length) {+ let combined = "";+ let found = false;+ for (let end = start; end < items.length; end++) {+ combined += (end > start ? " " : "") + items[end].text;+ if (combined.toLowerCase().includes(q)) {+ // Narrow from the left: drop leading items that aren't part of the match+ let narrowed = combined;+ let s = start;+ while (s < end) {+ const without = narrowed.slice(items[s].text.length + 1);+ if (without.toLowerCase().includes(q)) {+ narrowed = without;+ s++;+ } else {+ break;+ }+ }++ // Merge bounding boxes of the matched items+ const matched = items.slice(s, end + 1);+ const x = Math.min(...matched.map((m) => m.x));+ const y = Math.min(...matched.map((m) => m.y));+ const x2 = Math.max(...matched.map((m) => m.x + m.width));+ const y2 = Math.max(...matched.map((m) => m.y + m.height));++ results.push({+ text: options.phrase,+ x,+ y,+ width: x2 - x,+ height: y2 - y,+ fontName: matched[0].fontName,+ fontSize: matched[0].fontSize,+ });++ // Advance past the match to avoid duplicates+ start = end + 1;+ found = true;+ break;+ }+ // Stop expanding if the combined text is already much longer than the query+ if (combined.length > q.length * 2) break;+ }+ if (!found) start++;+ }++ return results;+}