Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ jobs:
python3 benchmark/eval/parser_improvements.py --output benchmark/eval/outputs/parser-020-ci/geometry-and-decoding
python3 benchmark/eval/section_hierarchy.py --output benchmark/eval/outputs/parser-020-ci/sections
python3 benchmark/eval/section_safety.py --output benchmark/eval/outputs/parser-020-ci/section-safety
python3 benchmark/eval/lzw_early_change.py --output benchmark/eval/outputs/parser-020-ci/lzw-early-change

- name: Upload adaptive provenance evidence
if: always()
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@

### Fixed

- LZW decoding honors `EarlyChange` values 0 and 1, defaults to 1, and rejects
invalid explicit values. Regression controls cover code-width transitions,
dictionary reset, predictor/filter composition and decoded-output limits.
- LZW parameters resolve indirect dictionaries, array entries and `EarlyChange`
values at the document boundary, including Form and font streams. Bounded
resolution rejects cycles and preserves referenced object-stream byte limits.
- The compiler-budget test records readiness before crossing its stop boundary,
avoiding a race between resource refusal and a subsequent diagnostic print.
- Python distribution and runtime metadata now use `0.4.0.dev0`, matching the
native `0.4.0-dev` build, with canonical repository links and installed-wheel
checks that compare package, native-library and manifest identities.

- Batch and streaming extraction share one bounded table-continuation policy.
Partial headers, missing evidence, page gaps, and intervening tables abstain.
- Native line grouping distinguishes opposite writing directions, including
Expand Down
16 changes: 16 additions & 0 deletions benchmark/eval/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ must finish within its timeout and retain the page's body text.
Run `node --test integrations/javascript/*.test.mjs` for strict batch/stream
consumer validation and actual CLI adapter roundtrips.

LZW controls exercise omitted/default and explicit `EarlyChange`, every
9-to-12-bit width transition, clear-code resets and composed predictors through
native text and both public JSONL formats:

```sh
python3 benchmark/eval/lzw_early_change.py --output benchmark/eval/outputs/lzw-run
```

The harness runs 45 CLI checks on fifteen generated inputs, including indirect
parameter values, dictionaries and filter-aligned arrays, plus a Form XObject.
Pass `--qpdf qpdf`
when that optional tool is installed to compare complete decoded stream bytes
independently. Zig unit checks also cover exact output caps, invalid parameter
values and allocation-failure cleanup. These controls do not establish general
PDF conformance.

The independent [table region development controls](table_regions/README.md)
check separated regions, persistent columns, exact source ownership, and prose
retention in both public JSONL formats. Their drawing truth is frozen before
Expand Down
174 changes: 174 additions & 0 deletions benchmark/eval/lzw_early_change.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
#!/usr/bin/env python3
"""Check LZW width transitions through native text and both public JSONL modes.

Literal-only streams use fixed width windows rather than a copy of the decoder
dictionary. An optional qpdf comparison checks the complete decoded bytes.
Generated PDFs and raw results stay in a fresh evidence directory.
"""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import subprocess

ROOT = Path(__file__).resolve().parents[2]


def literal_lzw(data, early_change, reset_at=None):
windows = (254, 766, 1790) if early_change else (255, 767, 1791)
bits = []

def emit(code, width):
bits.extend((code >> shift) & 1 for shift in range(width - 1, -1, -1))

def width(index):
return 9 + sum(index >= boundary for boundary in windows)

emit(256, 9)
count = 0
for index, byte in enumerate(data):
if index == reset_at:
emit(256, width(count))
count = 0
emit(byte, width(count))
count += 1
emit(257, width(count))
bits.extend([0] * (-len(bits) % 8))
return bytes(sum(bits[index + bit] << (7 - bit) for bit in range(8))
for index in range(0, len(bits), 8))


def make_pdf(payload, filters, params, extra_objects=(), form=False):
resources = b"/Font << /F1 4 0 R >>" + (b" /XObject << /Fm1 6 0 R >>" if form else b"")
stream = f"<< /Length {len(payload)} /Filter {filters} {params}".encode()
if form:
stream += b" /Type /XObject /Subtype /Form /BBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >>"
stream += b" >>\nstream\n" + payload + b"\nendstream"
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << " + resources + b" >> /Contents 5 0 R >>",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
b"<< /Length 8 >>\nstream\n/Fm1 Do\n\nendstream" if form else stream,
]
if form:
objects.append(stream)
objects.extend(extra_objects)
output, offsets = bytearray(b"%PDF-1.7\n"), []
for index, obj in enumerate(objects, 1):
offsets.append(len(output))
output.extend(f"{index} 0 obj\n".encode() + obj + b"\nendobj\n")
xref = len(output)
output.extend(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode())
for offset in offsets:
output.extend(f"{offset:010d} 00000 n \n".encode())
output.extend(f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
return output


def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cli", type=Path, default=ROOT / "zig-out/bin/pdf-parser")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--qpdf", help="optional independent decoded-byte oracle executable")
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=False)
report = {"cli_sha256": digest(args.cli), "harness_sha256": digest(Path(__file__)),
"decoder_sha256": digest(ROOT / "src/decompress.zig"),
"resolver_sha256": digest(ROOT / "src/pagetree.zig"), "runs": [], "oracles": []}
for name, early, chain, reset, entry, style in (
("default", 1, False, None, "", "direct"),
("null-default", 1, False, None, "/EarlyChange null", "direct"),
("early-one", 1, False, None, "/EarlyChange 1", "direct"),
("early-zero", 0, False, None, "/EarlyChange 0", "direct"),
("chain-predictor-one", 1, True, None, "/EarlyChange 1", "direct"),
("chain-predictor-zero", 0, True, None, "/EarlyChange 0", "direct"),
("reset-one", 1, False, 2100, "/EarlyChange 1", "direct"),
("reset-zero", 0, False, 2100, "/EarlyChange 0", "direct"),
("indirect-one", 1, False, None, "/EarlyChange 6 0 R", "entry"),
("indirect-zero", 0, False, None, "/EarlyChange 6 0 R", "entry"),
("indirect-null", 1, False, None, "/EarlyChange 6 0 R", "null-entry"),
("indirect-nested-zero", 0, False, None, "", "nested"),
("indirect-params-zero", 0, False, None, "", "params"),
("indirect-array-zero", 0, True, None, "", "array"),
("indirect-form-zero", 0, False, None, "/EarlyChange 7 0 R", "form"),
):
expected = f"LZW {name} source retained"
content = b"%" + b"p" * 3200 + f"\nBT /F1 12 Tf 40 700 Td ({expected}) Tj ET\n".encode()
source = content
if chain:
source = bytes([content[0]] + [(byte - content[index - 1]) % 256 for index, byte in enumerate(content) if index])
encoded = literal_lzw(source, early, reset)
filters = "/LZWDecode"
params = f"/DecodeParms << {entry} >>"
if chain:
encoded = encoded.hex().encode() + b">"
filters = "[/ASCIIHexDecode /LZWDecode]"
params = f"/DecodeParms [null << {entry} /Predictor 2 /Columns {len(content)} >>]"
extra = []
if style in ("entry", "form"):
extra = [str(early).encode()]
elif style == "null-entry":
extra = [b"null"]
elif style == "nested":
params = "/DecodeParms 6 0 R"
extra = [b"<< /EarlyChange 7 0 R >>", b"0"]
elif style == "params":
params = "/DecodeParms 6 0 R"
extra = [b"<< /EarlyChange 0 >>"]
elif style == "array":
params = "/DecodeParms 6 0 R"
extra = [b"[null 7 0 R]", f"<< /EarlyChange 8 0 R /Predictor 2 /Columns {len(content)} >>".encode(), b"0"]
path = args.output / f"{name}.pdf"
path.write_bytes(make_pdf(encoded, filters, params, extra, style == "form"))
if args.qpdf:
command = [args.qpdf, "--show-object=6" if style == "form" else "--show-object=5", "--filtered-stream-data", str(path)]
result = subprocess.run(command, capture_output=True, timeout=15)
(args.output / f"{name}.qpdf.bin").write_bytes(result.stdout)
(args.output / f"{name}.qpdf.stderr").write_bytes(result.stderr)
report["oracles"].append({"command": command, "exit_code": result.returncode,
"passed": result.returncode == 0 and result.stdout == content})
for fmt in ("native", "artifact-jsonl", "stream-jsonl"):
command = [str(args.cli.resolve()), "extract", "--fast", str(path)] if fmt == "native" else [
str(args.cli.resolve()), "extract-adaptive", "--input", str(path), "--no-ocr", "--format", fmt]
result = subprocess.run(command, capture_output=True, text=True, timeout=15)
stem = args.output / f"{name}.{fmt}"
stem.with_suffix(stem.suffix + ".stdout").write_text(result.stdout)
stem.with_suffix(stem.suffix + ".stderr").write_text(result.stderr)
failures = []
if result.returncode:
failures.append(f"exit {result.returncode}")
if fmt == "native":
if result.stdout.strip() != expected:
failures.append("native text mismatch")
else:
try:
records = [json.loads(line) for line in result.stdout.splitlines() if line.strip()]
spans = [r for r in records if r.get("record_type") == "span"]
if not records or records[0].get("record_type") != "document_manifest":
failures.append("missing manifest")
if " ".join(r.get("text", "") for r in spans) != expected or any(r.get("page_index") != 0 for r in spans):
failures.append("span text or page identity mismatch")
if any(r.get("errors") for r in records):
failures.append("artifact errors")
if fmt == "stream-jsonl" and (not records or records[-1].get("record_type") != "document_finished" or records[-1].get("status") != "completed"):
failures.append("missing completed stream")
except json.JSONDecodeError:
failures.append("invalid JSONL")
report["runs"].append({"case": name, "format": fmt, "command": command,
"input_sha256": digest(path), "exit_code": result.returncode, "failures": failures})
report["passed"] = all(not r["failures"] for r in report["runs"]) and all(r["passed"] for r in report["oracles"])
(args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({"passed": report["passed"], "runs": len(report["runs"]),
"oracles": len(report["oracles"]), "failures": [r for r in report["runs"] if r["failures"]]}))
return 0 if report["passed"] else 1


if __name__ == "__main__":
raise SystemExit(main())
24 changes: 22 additions & 2 deletions benchmark/eval/test_bounded_zig.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,12 @@ def test_limit_stops_owned_parent_and_child_but_not_unrelated_process(self):
f"subprocess.Popen([sys.executable,'-c',{sleeper!r}])\n"
f"ready=pathlib.Path({str(child_ready)!r})\n"
"while not ready.exists(): time.sleep(.01)\n"
# Once the write crosses the limit, the monitor may stop the group
# before the writer can print again. Log readiness before growing it.
"print('child group ready',flush=True)\n"
"p=pathlib.Path(os.environ['ZIG_GLOBAL_CACHE_DIR'])/'large'\n"
"with p.open('wb') as f:\n"
" f.write(b'x'*(2*1024*1024)); f.flush(); os.fsync(f.fileno())\n"
"print('allocated over budget',flush=True)\n"
"time.sleep(60)\n"
)
unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], start_new_session=True)
Expand All @@ -94,11 +96,29 @@ def test_limit_stops_owned_parent_and_child_but_not_unrelated_process(self):
self.assertEqual(child_stopped.read_text(), "terminated")
self.assertIsNone(unrelated.poll(), "runner killed an unrelated process")
self.assertTrue((self.cache / "global/large").exists())
self.assertIn(b"allocated over budget", self.log.read_bytes())
self.assertIn(b"child group ready", self.log.read_bytes())
finally:
unrelated.terminate()
unrelated.wait(timeout=5)

def test_budget_stop_does_not_require_output_after_allocation(self):
# Hold the writer after allocation so the monitor must stop it without
# relying on a later log line or successful command exit.
result = self.run_child(
"import os,pathlib,time\n"
"p=pathlib.Path(os.environ['ZIG_GLOBAL_CACHE_DIR'])/'large'\n"
"with p.open('wb') as f:\n"
" f.write(b'x'*(2*1024*1024)); f.flush(); os.fsync(f.fileno())\n"
"time.sleep(60)\n"
"print('must not reach this line',flush=True)\n"
)
receipt = self.read_receipt()
self.assertEqual(result, 124)
self.assertEqual(receipt["status"], "allocation_budget_exceeded")
self.assertNotEqual(receipt["command_exit_code"], 0)
self.assertGreater(receipt["observed_budget_overshoot_bytes"], 0)
self.assertEqual(self.log.read_bytes(), b"")

def test_preexisting_cache_over_budget_never_starts_command(self):
self.cache.mkdir()
cached = self.cache / "preexisting"
Expand Down
7 changes: 7 additions & 0 deletions docs/output-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,13 @@ allocator overhead, input mappings, or subprocess RSS. Intentional bounded
Type3 scratch-buffer exhaustion remains best-effort; an explicit stream cap
refusal propagates.

LZW decoding defaults to `EarlyChange=1` and accepts explicit integer 0 or 1.
For document streams, indirect decode-parameter dictionaries, aligned array
entries and `EarlyChange` values resolve before decoding. Reference chains and
nested object-stream parameter resolution have a 16-level bound; cyclic or
excessively deep resolution fails. Referenced object streams retain the same
decoded-byte cap. These controls change decoding behavior, not record fields.

### `debug_asset`

Reference to visual review and coordinate artifacts. Debug assets are always
Expand Down
5 changes: 5 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ Python bindings for the Zig pdf-parser library. The package is named
`pdf-parser`, while the import path remains `zpdf` for compatibility with the
inherited API.

The current development package is `0.4.0.dev0`, the Python packaging spelling
of the native parser's `0.4.0-dev` build. Adaptive output uses schema `0.20.0`;
its version is independent of the package version. This is a capable pre-1.0
parser; a development build is not a tagged release.

## Install

Published wheels are platform-specific. From a source checkout, build a wheel
Expand Down
12 changes: 6 additions & 6 deletions python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ build-backend = "setuptools.build_meta"

[project]
name = "pdf-parser"
version = "0.1.0"
description = "High-performance PDF text extraction powered by Zig"
version = "0.4.0.dev0"
description = "PDF text and artifact extraction powered by Zig"
readme = "README.md"
license = { text = "MIT" }
requires-python = ">=3.8"
dependencies = ["cffi>=1.15"]
authors = [{name = "Thomas Main"}]
keywords = ["pdf", "text-extraction", "parser", "zig"]
classifiers = [
"Development Status :: 3 - Alpha",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Text Processing",
"Programming Language :: Python :: 3",
Expand All @@ -26,9 +26,9 @@ classifiers = [
]

[project.urls]
Homepage = "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/thomasmain/pdf-parser"
Repository = "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/thomasmain/pdf-parser"
Issues = "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/thomasmain/pdf-parser/issues"
Homepage = "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/Tom-R-Main/pdf-parser"
Repository = "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/Tom-R-Main/pdf-parser"
Issues = "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/Tom-R-Main/pdf-parser/issues"

[project.optional-dependencies]
dev = ["pytest>=7.0"]
Expand Down
13 changes: 12 additions & 1 deletion python/tests/wheel_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

from __future__ import annotations

import json
import sys
import zipfile
from importlib import metadata
from pathlib import Path

import zpdf
Expand All @@ -24,6 +26,13 @@ def main() -> None:
assert selected_library.name == expected_library
assert "-none-any.whl" not in wheel.name

distribution = metadata.distribution("pdf-parser")
native_version = _ffi.ffi.string(_ffi.lib.pdf_parser_version()).decode("ascii")
package_version = (
native_version[:-4] + ".dev0" if native_version.endswith("-dev") else native_version
)
assert distribution.version == zpdf.__version__ == package_version

with zipfile.ZipFile(wheel) as archive:
native_members = [
name
Expand All @@ -41,7 +50,9 @@ def main() -> None:
source_id="wheel-smoke",
format="artifact-jsonl",
)
assert '"record_type":"document_manifest"' in artifacts.splitlines()[0]
manifest = json.loads(artifacts.splitlines()[0])
assert manifest["record_type"] == "document_manifest"
assert manifest["parser_version"] == native_version


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion python/zpdf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from ._ffi import ffi, lib
from .exceptions import ZpdfError, InvalidPdfError, PageNotFoundError, ExtractionError

__version__ = "0.1.0"
__version__ = "0.4.0.dev0"
__all__ = ["Document", "PageInfo", "TextSpan", "extract_adaptive", "ZpdfError", "InvalidPdfError", "PageNotFoundError", "ExtractionError"]


Expand Down
Loading
Loading