-
Notifications
You must be signed in to change notification settings - Fork 34
feat: PDF ingestion via unpdf with page chunking #33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
RaviTharuma
wants to merge
2
commits into
AVIDS2:main
Choose a base branch
from
RaviTharuma:feature/memorix-nmi-pdf-ingestion
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| /** | ||
| * PDF Loader — unpdf Integration | ||
| * | ||
| * Extracts text from PDFs using unpdf (pure JS, optional dependency). | ||
| * Creates per-page observations for searchable memory storage. | ||
| */ | ||
|
|
||
| import type { ObservationType } from '../types.js'; | ||
|
|
||
| // ── Types ──────────────────────────────────────────────────────────── | ||
|
|
||
| export interface PdfInput { | ||
| base64: string; | ||
| filename?: string; | ||
| maxPages?: number; | ||
| } | ||
|
|
||
| export interface PdfPage { | ||
| pageNumber: number; | ||
| text: string; | ||
| charCount: number; | ||
| } | ||
|
|
||
| export interface PdfExtractionResult { | ||
| pages: PdfPage[]; | ||
| totalPages: number; | ||
| extractionMethod: 'unpdf'; | ||
| } | ||
|
|
||
| // ── Type shim for optional unpdf dependency ─────────────────────────── | ||
|
|
||
| interface UnpdfModule { | ||
| extractText: (data: Uint8Array, options?: { mergePages?: boolean }) => Promise<{ | ||
| totalPages: number; | ||
| text: string; | ||
| pages?: string[]; | ||
| }>; | ||
| } | ||
|
|
||
| async function tryLoadUnpdf(): Promise<UnpdfModule | null> { | ||
| try { | ||
| // unpdf is an optional peer dependency — TypeScript cannot resolve it at compile time. | ||
| // The runtime import is intentional; the catch handles the missing-module case. | ||
| // @ts-ignore | ||
| const mod = await import('unpdf') as unknown as UnpdfModule; | ||
| if (typeof mod?.extractText === 'function') { | ||
| return mod; | ||
| } | ||
| return null; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| // ── Core Functions ─────────────────────────────────────────────────── | ||
|
|
||
| /** | ||
| * Extract text from a PDF document page-by-page. | ||
| * | ||
| * @throws Error if unpdf is not installed (it's an optional dependency). | ||
| */ | ||
| export async function extractPdfText(input: PdfInput): Promise<PdfExtractionResult> { | ||
| const unpdf = await tryLoadUnpdf(); | ||
|
|
||
| if (!unpdf) { | ||
| throw new Error( | ||
| 'unpdf is not installed. To enable PDF ingestion, run:\n' + | ||
| ' npm install unpdf\n' + | ||
| 'or: bun add unpdf', | ||
| ); | ||
| } | ||
|
|
||
| const buffer = Buffer.from(input.base64, 'base64'); | ||
| const maxPages = input.maxPages ?? 100; | ||
|
|
||
| const result = await unpdf.extractText(new Uint8Array(buffer), { mergePages: false }); | ||
|
|
||
| // unpdf returns pages as array when mergePages: false | ||
| const rawPages = result.pages ?? result.text.split('\f'); | ||
|
|
||
| const pages: PdfPage[] = []; | ||
| const limit = Math.min(rawPages.length, maxPages); | ||
|
|
||
| for (let i = 0; i < limit; i++) { | ||
| const text = String(rawPages[i] ?? '').trim(); | ||
| if (text.length >= 10) { | ||
| pages.push({ | ||
| pageNumber: i + 1, | ||
| text, | ||
| charCount: text.length, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| pages, | ||
| totalPages: rawPages.length, | ||
| extractionMethod: 'unpdf', | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Extract PDF text and store each page as a Memorix observation. | ||
| */ | ||
| export async function ingestPdf( | ||
| input: PdfInput, | ||
| storeFn: (obs: { | ||
| entityName: string; | ||
| type: ObservationType; | ||
| title: string; | ||
| narrative: string; | ||
| concepts: string[]; | ||
| projectId: string; | ||
| }) => Promise<{ observation: { id: number }; upserted: boolean }>, | ||
| projectId: string, | ||
| ): Promise<{ observationIds: number[]; pagesProcessed: number; totalChars: number }> { | ||
| const extraction = await extractPdfText(input); | ||
|
|
||
| const entityName = input.filename | ||
| ? input.filename.replace(/\.[^.]+$/, '') | ||
| : `pdf-${Date.now()}`; | ||
|
|
||
| const observationIds: number[] = []; | ||
| let totalChars = 0; | ||
|
|
||
| for (const page of extraction.pages) { | ||
| const narrative = page.text.length > 5000 | ||
| ? page.text.slice(0, 5000) + '…' | ||
| : page.text; | ||
|
|
||
| const { observation } = await storeFn({ | ||
| entityName, | ||
| type: 'discovery' as ObservationType, | ||
| title: `${entityName} — Page ${page.pageNumber}`, | ||
| narrative, | ||
| concepts: ['pdf', 'document', entityName], | ||
| projectId, | ||
| }); | ||
|
|
||
| observationIds.push(observation.id); | ||
| totalChars += page.charCount; | ||
| } | ||
|
|
||
| return { | ||
| observationIds, | ||
| pagesProcessed: extraction.pages.length, | ||
| totalChars, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
| import { extractPdfText, ingestPdf } from '../../src/multimodal/pdf-loader.js'; | ||
|
|
||
| describe('pdf-loader', () => { | ||
| it('throws clear error when unpdf is not installed', async () => { | ||
| await expect( | ||
| extractPdfText({ base64: 'dGVzdA==' }), | ||
| ).rejects.toThrow('unpdf is not installed'); | ||
| }); | ||
|
|
||
| it('error message includes install instructions', async () => { | ||
| try { | ||
| await extractPdfText({ base64: 'dGVzdA==' }); | ||
| } catch (err) { | ||
| expect((err as Error).message).toContain('npm install unpdf'); | ||
| } | ||
| }); | ||
|
|
||
| it('ingestPdf propagates extractPdfText errors', async () => { | ||
| const storeFn = async (_obs: any) => ({ observation: { id: 1 }, upserted: false }); | ||
| await expect( | ||
| ingestPdf({ base64: 'dGVzdA==' }, storeFn as any, 'proj-1'), | ||
| ).rejects.toThrow('unpdf is not installed'); | ||
| }); | ||
|
|
||
| it('PdfInput interface accepts all expected fields', () => { | ||
| const input = { base64: 'test', filename: 'doc.pdf', maxPages: 5 }; | ||
| expect(input.base64).toBe('test'); | ||
| expect(input.filename).toBe('doc.pdf'); | ||
| expect(input.maxPages).toBe(5); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maxPagesis treated as an arbitrary number and used directly ini < limit, which causes fractional values to round up in practice (e.g.,maxPages=1.1processes pages 1 and 2). Negative values also silently result in zero ingestion. Because this tool parameter represents a page count, it should be validated/coerced to a positive integer before computing the loop bound.Useful? React with 👍 / 👎.