Repository navigation
kb: native PDF support (FlateDecode + /ToUnicode) for ingest - #295
Conversation
Adds PasClaw.KB.PDF (+ .Parser, +.Compat) — a port of the upstream
pdftotext (github.com/FMXExpress/pdftotext) that gives the KB ingest
pipeline native PDF text extraction without an external dependency.
Handles /FlateDecode streams, per-font /ToUnicode CMaps (Type0/CID +
simple fonts, beginbfchar / beginbfrange), CP1252 fallback, PDF
string escapes, and /Title / /Author metadata.
KB.Index wiring:
* .pdf added to KB_EXTENSIONS
* KB_MAX_FILE_BYTES bumped 4 MB -> 30 MB (admits textbooks)
* IngestOne routes .pdf through ExtractPDFText, bypassing the
binary-sniff (PDFs always contain NUL bytes raw). Image-only
PDFs fall out with "no extractable text" so Sync doesn't
re-attempt them every cycle.
Gateway / web UI:
* /v1/kb/upload accepts a new optional content_b64 field for
binary uploads; existing {name, content} text path unchanged
so old clients keep working.
* webui.html base64-encodes .pdf files on upload and lifts the
JS-side size guard to 30 MB; <input accept="..."> now includes
.pdf so the file picker shows them.
Tests:
* src/tests/kb_pdf_extract_tests.pas — builds a minimal
uncompressed PDF (one Tj operator, Type1 font, /Title meta)
in a temp file, asserts extracted text + Err strings on
missing / non-PDF / empty-text cases.
* kb_index_tests: flip the ".pdf NOT supported" assertion.
* Makefile: new test-kb-pdf target, added to the aggregate
`make test` list.
Base64ToBytes added to PasClaw.Crypto.HMAC for the binary-upload
decode path.
Cleared a stale "PDFs are not supported" note from docs and
cmd_kb help.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 454f3bd076
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| begin | ||
| for ObjID in ContentIDs do | ||
| begin | ||
| ObjMarker := Format('%d 0 obj', [ObjID]); |
There was a problem hiding this comment.
Resolve content objects with their actual generation
For PDFs whose page dictionary references a nonzero-generation content stream (for example /Contents 12 1 R, which occurs in incrementally updated PDFs), GetPageContentStreamIDs still returns an ID so the fallback scanner is skipped, but this lookup only searches for 12 0 obj. The stream is never visited and the wrapper reports the valid text PDF as having no extractable text; use the object index or preserve the generation from the reference instead of hard-coding generation 0.
Useful? React with 👍 / 👎.
| if (ObjID >= 0) and Fonts.ContainsKey(ObjID) then | ||
| begin | ||
| Name := M.Groups[1].Value; | ||
| Result.AddOrSetValue(Name, ObjID); |
There was a problem hiding this comment.
PDF font resource names are local to a resource dictionary, but this builds one document-wide Name -> ObjID map and overwrites entries by name. In multi-page PDFs that reuse names such as /F1 for different subset fonts, text from pages using the other /F1 will be decoded with the wrong /ToUnicode map, corrupting the extracted KB text; build the map from the page/content stream's resources instead of scanning the whole file globally.
Useful? React with 👍 / 👎.
| if ParenDepth = 0 then | ||
| begin | ||
| InParen := False; | ||
| Result := Result + DecodeStringBytes(CurrentStr, CurFont); |
There was a problem hiding this comment.
Preserve separators between positioned text draws
When a BT block draws words with separate string operands and positions them with Td/Tm/T* (common in generated PDFs), this append path concatenates the decoded operands directly, so (Hello) Tj 40 0 Td (World) Tj becomes HelloWorld in the KB. The existing spacing logic only handles negative numbers inside TJ arrays, so positioned Tj sequences need spacing/newline handling before appending the next string.
Useful? React with 👍 / 👎.
PR #295 review feedback, two legit fixes + one deferred. * P2 #1 (generation-number): ExtractTextAndMetadata's primary path looked content streams up via Format('%d 0 obj', [ObjID]), hardcoding generation 0. An incrementally-updated PDF whose page /Contents references "12 1 R" would silently fall through to the empty-text branch. Switched to ObjIndex.TryGetValue, which the parser already builds via BuildObjectIndex and which records the position of every <id> <gen> obj regardless of gen. Stream-bounds check now uses 'endobj' (mirroring GetObjectStreamData) instead of the next 'obj' keyword. * P2 #3 (positioned-Tj spacing): "BT (Hello) Tj 50 0 Td (World) Tj ET" used to extract "HelloWorld". ParseTextOperators now detects Td/TD/Tm/T*/'/" position operators and flips a NeedSpaceBeforeNext flag; the next paren-close or hex-close emits via a local EmitWithSpacing helper that prepends a single space. The existing TJ-array negative-number spacing (>120 units = word boundary) is unchanged and still handles intra-TJ glyph runs. * P2 #2 (per-page font resource map): BuildResourceFontMap is still document-wide -- proper per-page maps would restructure GetPageContentStreamIDs to thread a TDictionary per content stream through ParseTextOperators, which is a bigger refactor than this PR warrants. Added a header comment explaining the known limitation: single-font and same-font-across-pages docs work, and the CP1252 fallback keeps ASCII readable when /ToUnicode misses on per-page-subset fonts (LaTeX output). New regression tests in src/tests/kb_pdf_extract_tests.pas: * TestPositionedTjSpacing -- "Foo Bar" via Td between Tj operands. * TestNonZeroGenerationContent -- "4 1 obj" content stream resolves. End-to-end smoke: `kb add` + `kb search "cross reference"` on a PDF with three position-separated Tj operands now returns "Cross reference Document" (was "CrossreferenceDocument").
The README + docs/changelog.md last entry was 2026-06-13 (FMXExpress#244). Five substantial PRs (FMXExpress#314 FMXExpress#315 FMXExpress#316 FMXExpress#317 FMXExpress#318) and ten more feature PRs between them and that entry shipped without changelog entries. This brings both files current through today. Twenty new entries (newest first, matching the existing style): 2026-06-21 FMXExpress#318 Relay pull-worker provider (queue + provider + /v1/relay/* HTTP) 2026-06-20 FMXExpress#317 pasclaw plan + build PLAN.md pickup + build --goal + cog mode FMXExpress#316 Cloudflare AI Gateway provider catalog rows FMXExpress#315 MCP progressive disclosure + tool_search FMXExpress#314 Stock defaults adopt lean-edit shape; fs_grep split-gate 2026-06-18 FMXExpress#312 Web UI workspace.zip export + import FMXExpress#310 Model-callable cron tool FMXExpress#309 FTS5 snippet window widened 24 -> 60 FMXExpress#307 Windows cmd.exe quoting fix 2026-06-17 FMXExpress#306 cog-build honours profile=security sandbox FMXExpress#304 cog-build default profile = max-build FMXExpress#303 cog-build list[Path] outputs + Secret inputs + -q 2026-06-16 FMXExpress#302 cog-build optional workspace_in FMXExpress#300 pasclaw build cmd + cog-build/ predictor (parent feature) FMXExpress#299 Checkpoints zpaq backend + /redo FMXExpress#298 AGENTS.md + pasclaw init + /init FMXExpress#297 tool_choice force-a-specific-tool form FMXExpress#296 Delphi ExtraEnv injection fix FMXExpress#295 KB native PDF ingest 2026-06-15 FMXExpress#292 pasclaw profile diff + bench Skipped per the changelog's stated convention ("Bug fixes and review follow-ups are in the full git log"): FMXExpress#293 cmd/profile dcc64 fix FMXExpress#294 skills_manage gemini empty-enum fix FMXExpress#301 cmd.build dcc64 fix FMXExpress#311 cron dcc64 fix Files updated identically (the docs/changelog.md note at the top says "This file mirrors the changelog section at the top of the root README.md"): M README.md 20 entries + 20 link refs added M docs/changelog.md same The link-ref block at the bottom of each file gained 20 [#NNN] entries keeping the existing one-per-line / sorted-numerically format.
Summary
Brings your
pdftotextparser (https://github.com/FMXExpress/pdftotext) into PasClaw asPasClaw.KB.PDFso the KB ingest pipeline can index.pdffiles directly. No external converter needed — pure-Pascal FlateDecode + per-font /ToUnicode CMap parsing under both FPC and Delphi.src/pkg/kb/PasClaw.KB.PDF.Parser.pas(port of upstreampdftotext.PDFParser),src/pkg/kb/PasClaw.KB.PDF.Compat.pas(RegEx / TFile / InflateBytes shim —RegExpr+zstreamon FPC,System.RegularExpressions+System.ZLibon Delphi). ThinPasClaw.KB.PDFwrapper exposesExtractPDFText(Path, out Text, out Err): Boolean..pdfadded toKB_EXTENSIONS,KB_MAX_FILE_BYTESbumped 4 MB → 30 MB (admits textbooks), andIngestOneroutes.pdfthrough the parser before the binary sniff (PDFs always have NUL bytes raw). Image-only PDFs fall out with a"no extractable text"warning and are recorded as skipped sokb syncdoesn't re-attempt them every cycle./v1/kb/uploadaccepts a new optionalcontent_b64field for binary uploads. The existing{name, content}text path is unchanged so old clients (and/v1/chat/completions) keep working.webui.htmlbase64-encodes.pdffiles, lifts the JS-side guard to 30 MB, and includes.pdfin<input accept="…">. AddedBase64ToBytestoPasClaw.Crypto.HMACfor the decode path.src/tests/kb_pdf_extract_tests.pasbuilds a minimal uncompressed PDF (one Tj operator, Type1 font,/Titlemeta) in a temp file and asserts extracted text +Errstrings on missing-file / non-PDF / empty-text cases.kb_index_testsflips its.pdf NOT supportedassertion. Newmake test-kb-pdftarget added to the aggregatemake testlist.docs/knowledgebase.mdandpasclaw kbhelp.Test plan
make test-kb-pdf— passes (missing file, non-PDF, minimal PDF roundtrip, image-only PDF rejection)make test-kb-index— passes after flipping the.pdf NOT supportedassertionmake— full binary builds clean under FPC 3.2.2PASCLAW_HOME=… pasclaw kb add /tmp/kb-dir/indexes a hand-crafted PDF;pasclaw kb search "roundtrip"returns the chunk with«roundtrip»highlighted.delphi_build_testscovers it; the parser uses the sameTRegEx/TFile/System.ZLibsurface the shim hides under FPC..pdf, click Upload & index, confirm the toast saysindexed 1 — 1 file(s), N chunk(s)andkb searchfinds the content.License: brought in at your request as author of both projects — no separate vendor notice needed.
Generated by Claude Code