Skip to content

kb: native PDF support (FlateDecode + /ToUnicode) for ingest - #295

Merged
FMXExpress merged 2 commits into
mainfrom
claude/kb-pdf-support
Jun 16, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/kb-pdf-support

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Brings your pdftotext parser (https://github.com/FMXExpress/pdftotext) into PasClaw as PasClaw.KB.PDF so the KB ingest pipeline can index .pdf files directly. No external converter needed — pure-Pascal FlateDecode + per-font /ToUnicode CMap parsing under both FPC and Delphi.

  • Parser: src/pkg/kb/PasClaw.KB.PDF.Parser.pas (port of upstream pdftotext.PDFParser), src/pkg/kb/PasClaw.KB.PDF.Compat.pas (RegEx / TFile / InflateBytes shim — RegExpr + zstream on FPC, System.RegularExpressions + System.ZLib on Delphi). Thin PasClaw.KB.PDF wrapper exposes ExtractPDFText(Path, out Text, out Err): Boolean.
  • KB.Index wiring: .pdf added to KB_EXTENSIONS, KB_MAX_FILE_BYTES bumped 4 MB → 30 MB (admits textbooks), and IngestOne routes .pdf through 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 so kb sync doesn't re-attempt them every cycle.
  • Gateway + web UI: /v1/kb/upload accepts a new optional content_b64 field for binary uploads. The existing {name, content} text path is unchanged so old clients (and /v1/chat/completions) keep working. webui.html base64-encodes .pdf files, lifts the JS-side guard to 30 MB, and includes .pdf in <input accept="…">. Added Base64ToBytes to PasClaw.Crypto.HMAC for the decode path.
  • Tests: new src/tests/kb_pdf_extract_tests.pas builds a minimal uncompressed PDF (one Tj operator, Type1 font, /Title meta) in a temp file and asserts extracted text + Err strings on missing-file / non-PDF / empty-text cases. kb_index_tests flips its .pdf NOT supported assertion. New make test-kb-pdf target added to the aggregate make test list.
  • Docs: cleared the stale "PDFs are not supported — convert first" notes from docs/knowledgebase.md and pasclaw kb help.

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 supported assertion
  • make — full binary builds clean under FPC 3.2.2
  • End-to-end CLI smoke: PASCLAW_HOME=… pasclaw kb add /tmp/kb-dir/ indexes a hand-crafted PDF; pasclaw kb search "roundtrip" returns the chunk with «roundtrip» highlighted.
  • Delphi build (dcc32 / dcc64) — delphi_build_tests covers it; the parser uses the same TRegEx / TFile / System.ZLib surface the shim hides under FPC.
  • Web UI: pick a small .pdf, click Upload & index, confirm the toast says indexed 1 — 1 file(s), N chunk(s) and kb search finds the content.

License: brought in at your request as author of both projects — no separate vendor notice needed.


Generated by Claude Code

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/pkg/kb/PasClaw.KB.PDF.Parser.pas Outdated
begin
for ObjID in ContentIDs do
begin
ObjMarker := Format('%d 0 obj', [ObjID]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope font resources per page

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 👍 / 👎.

Comment thread src/pkg/kb/PasClaw.KB.PDF.Parser.pas Outdated
if ParenDepth = 0 then
begin
InParen := False;
Result := Result + DecodeStringBytes(CurrentStr, CurFont);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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").
@FMXExpress
FMXExpress merged commit 1c5a788 into main Jun 16, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants