A fast, helpful, and open-source document parser
chore: update bench provider code
Logan Markewich89d42df0f791
diff --git a/dataset_eval_utils/README.md b/dataset_eval_utils/README.mdindex d876412..ace9fae 100644--- a/dataset_eval_utils/README.md+++ b/dataset_eval_utils/README.md@@ -69,15 +69,33 @@ Outputs:Measures parse latency and memory usage across providers.```bash-lp-benchmark document.pdf --providers pymupdf liteparse --runs 20+lp-benchmark ./documents --providers pymupdf liteparse --warmup-runs 0```+Takes a **directory** of PDFs (searched recursively), not a single file.+Options:- `--providers` — Providers to benchmark (default: all local providers)-- `--runs` — Number of benchmark runs per provider (default: 10)-- `--warmup` — Number of warmup runs (default: 1)+- `--warmup-runs` — Full passes over the corpus before timing starts (default: 5).+ Each warmup run parses **every** document, so on a large corpus this dominates+ wall time; use `0` for a quick measurement.- `--output` — Path to save JSON results+Reports per-document latency plus TOTAL / AVG-per-doc / MS-per-page rows.++#### Parity with the published speed benchmarks++The providers are configured to match the run recorded in `../SPEED_BENCHMARKS.md`:+OCR is off in every parser that has it, and each tool keeps its own layout engine+(notably pymupdf4llm keeps the PyMuPDF layout model it enables by default). On a+shared sample the two harnesses agree on total time to within ~10% — inside normal+run-to-run variance — and produce byte-identical text for every parser except+`pypdf`, which differs only by one newline per page boundary.++`opendataloader` needs **Java 11+**; the provider locates one via `JAVA_HOME` or the+usual install paths and raises a clear error if only Java 8 is present (its jar+otherwise fails on every document with `UnsupportedClassVersionError`).+## Parser Providers| Provider | Library | Notes |diff --git a/dataset_eval_utils/src/liteparse_eval/benchmark.py b/dataset_eval_utils/src/liteparse_eval/benchmark.pyindex 392d3d8..3df7631 100644--- a/dataset_eval_utils/src/liteparse_eval/benchmark.py+++ b/dataset_eval_utils/src/liteparse_eval/benchmark.py@@ -7,6 +7,7 @@ latency and an aggregate summary table.import argparseimport json+import reimport timefrom pathlib import Pathfrom typing import Optional@@ -50,8 +51,12 @@ PROVIDER_MAP = {def find_pdfs(directory: Path) -> list[Path]:- """Find all PDF files in a directory (non-recursive)."""- return sorted(directory.glob("*.pdf"))+ """Find all PDF files in a directory, recursively.++ Recursive so nested corpora (ParseBench, olmOCR-bench) can be pointed at+ directly; a flat directory behaves exactly as before.+ """+ return sorted(directory.rglob("*.pdf"))def count_pages(file_path: Path) -> Optional[int]:@@ -64,19 +69,33 @@ def count_pages(file_path: Path) -> Optional[int]:return None-def time_extraction(provider: ParserProvider, file_path: Path) -> tuple[float, int]:- """Time a single extraction, returning (seconds, text_length)."""+_FENCE = re.compile(r"^\s*```[a-zA-Z]*\s*$", re.M)+++def content_length(text: str) -> int:+ """Characters of actual content, ignoring structural boilerplate.++ A raw ``len(text)`` overstates coverage: some parsers emit an empty code fence+ or page separators for a page they could not read, which is non-empty output+ carrying no content. Stripping fences and whitespace makes "produced nothing"+ comparable across parsers.+ """+ return len(re.sub(r"\s+", "", _FENCE.sub("", text).replace("-----", "")))+++def time_extraction(provider: ParserProvider, file_path: Path) -> tuple[float, int, int]:+ """Time a single extraction, returning (seconds, text_length, content_length)."""start = time.perf_counter()text = provider.extract_text(file_path)elapsed = time.perf_counter() - start- return elapsed, len(text)+ return elapsed, len(text), content_length(text)def format_table(providers: list[str],doc_names: list[str],- # results[provider_name][doc_name] = (seconds, chars) | None (error)- results: dict[str, dict[str, tuple[float, int] | None]],+ # results[provider_name][doc_name] = (seconds, chars, content_chars) | None+ results: dict[str, dict[str, tuple[float, int, int] | None]],page_counts: dict[str, Optional[int]] | None = None,) -> str:"""Build a formatted table string."""@@ -179,8 +198,16 @@ def run_benchmark(print(f"No PDF files found in {input_dir}")return {}- doc_names = [f.name for f in pdf_files]- page_counts = {f.name: count_pages(f) for f in pdf_files}+ # Key results by path RELATIVE to input_dir, not by basename. The search is+ # recursive, and corpora do contain the same filename in different+ # subdirectories (ParseBench has 37 such collisions); keying by basename+ # silently collapses those documents into one entry, dropping their+ # measurements and under-reporting the corpus size.+ def key_of(f: Path) -> str:+ return str(f.relative_to(input_dir))++ doc_names = [key_of(f) for f in pdf_files]+ page_counts = {key_of(f): count_pages(f) for f in pdf_files}total_pages = sum(p for p in page_counts.values() if p)print(f"Found {len(pdf_files)} documents ({total_pages} pages) in {input_dir}")@@ -188,38 +215,45 @@ def run_benchmark(print()# results[provider][doc_name] = (seconds, chars) | None- results: dict[str, dict[str, tuple[float, int] | None]] = {+ results: dict[str, dict[str, tuple[float, int, int] | None]] = {p: {} for p in providers}+ init_seconds: dict[str, float] = {}for provider_name in providers:print(f"[{provider_name}]")try:+ _t0 = time.perf_counter()provider = PROVIDER_MAP[provider_name]()+ init_seconds[provider_name] = time.perf_counter() - _t0except Exception as e:print(f" Failed to initialize: {e}\n")for f in pdf_files:- results[provider_name][f.name] = None+ results[provider_name][key_of(f)] = Nonecontinue- # Warmup runs+ # Warmup: repeat ONE document, not the whole corpus. The point is to pay+ # lazy imports, JIT and first-call setup once before timing starts; doing a+ # full pass per warmup run multiplies the benchmark's wall time by+ # warmup_runs and warms the OS page cache for every file, which flatters+ # the timings that follow.if warmup_runs > 0:- print(f" Warming up ({warmup_runs} runs)...")+ warmup_doc = pdf_files[0]+ print(f" Warming up ({warmup_runs} runs on {warmup_doc.name})...")for _ in range(warmup_runs):- for pdf_path in pdf_files:- try:- provider.extract_text(pdf_path)- except Exception:- pass+ try:+ provider.extract_text(warmup_doc)+ except Exception:+ passfor pdf_path in pdf_files:try:- elapsed, text_len = time_extraction(provider, pdf_path)- results[provider_name][pdf_path.name] = (elapsed, text_len)- print(f" {pdf_path.name}: {elapsed:.3f}s ({text_len:,} chars)")+ elapsed, text_len, content_len = time_extraction(provider, pdf_path)+ results[provider_name][key_of(pdf_path)] = (elapsed, text_len, content_len)+ print(f" {key_of(pdf_path)}: {elapsed:.3f}s ({text_len:,} chars)")except Exception as e:- results[provider_name][pdf_path.name] = None- print(f" {pdf_path.name}: ERROR - {e}")+ results[provider_name][key_of(pdf_path)] = None+ print(f" {key_of(pdf_path)}: ERROR - {e}")print()# Print table@@ -245,6 +279,7 @@ def run_benchmark(provider_results[doc] = {"seconds": round(entry[0], 4),"text_length": entry[1],+ "content_length": entry[2],"ms_per_page": round(entry[0] / pc * 1000, 3) if pc else None,}times = [results[p][d][0] for d in doc_names if results[p].get(d) is not None]@@ -260,6 +295,7 @@ def run_benchmark(if results[p].get(d) is not None and page_counts.get(d))output["providers"][p] = {+ "init_seconds": round(init_seconds.get(p, 0.0), 4),"per_document": provider_results,"total_seconds": round(sum(times), 4) if times else None,"avg_seconds": round(sum(times) / len(times), 4) if times else None,diff --git a/dataset_eval_utils/src/liteparse_eval/providers/parsers/liteparse.py b/dataset_eval_utils/src/liteparse_eval/providers/parsers/liteparse.pyindex 89c1557..b722b8c 100644--- a/dataset_eval_utils/src/liteparse_eval/providers/parsers/liteparse.py+++ b/dataset_eval_utils/src/liteparse_eval/providers/parsers/liteparse.py@@ -17,10 +17,12 @@ class LiteparseProvider(ParserProvider):self,ocr_enabled: bool = False,ocr_server_url: Optional[str] = None,- ocr_language: str = "en",+ ocr_language: str = "eng",max_pages: int = 1000,dpi: int = 150,preserve_very_small_text: bool = False,+ image_mode: str = "off",+ extract_links: bool = False,):"""Initialize the liteparse provider.@@ -28,11 +30,15 @@ class LiteparseProvider(ParserProvider):Args:ocr_enabled: Whether to enable OCR for scanned documentsocr_server_url: URL of HTTP OCR server (uses Tesseract if not provided)- ocr_language: Language code for OCR (e.g., "en", "fr", "de")+ ocr_language: Tesseract language code for OCR (e.g. "eng", "fra", "deu")max_pages: Maximum number of pages to parsedpi: DPI for rendering (affects OCR quality)preserve_very_small_text: Whether to preserve very small text- cli_path: Custom path to liteparse CLI (auto-detected if not provided)+ image_mode: Image placeholder handling. Defaults to "off" so output is plain+ text, matching the ground truth the benchmarks score against.+ extract_links: Whether to emit [text](url) markdown links. Defaults to False+ for the same reason -- benchmark ground truth carries no link syntax, so+ leaving this on (the library default) scores spurious mismatches."""self.parser = LiteParse(ocr_enabled=ocr_enabled,@@ -41,6 +47,8 @@ class LiteparseProvider(ParserProvider):max_pages=max_pages,dpi=dpi,preserve_very_small_text=preserve_very_small_text,+ image_mode=image_mode,+ extract_links=extract_links,output_format="markdown",quiet=True,)diff --git a/dataset_eval_utils/src/liteparse_eval/providers/parsers/opendataloader.py b/dataset_eval_utils/src/liteparse_eval/providers/parsers/opendataloader.pyindex cf47c51..30a52c9 100644--- a/dataset_eval_utils/src/liteparse_eval/providers/parsers/opendataloader.py+++ b/dataset_eval_utils/src/liteparse_eval/providers/parsers/opendataloader.py@@ -1,3 +1,7 @@+import os+import re+import shutil+import subprocessimport tempfilefrom pathlib import Path@@ -6,6 +10,56 @@ import opendataloader_pdffrom .base import ParserProvider+def _java_major(java_bin: str) -> int:+ """Major version of a java binary, or 0 if it cannot be determined."""+ try:+ out = subprocess.run([java_bin, "-version"], capture_output=True, text=True,+ timeout=30).stderr+ except Exception:+ return 0+ m = re.search(r'version "(?:1\.)?(\d+)', out)+ return int(m.group(1)) if m else 0+++def ensure_java_11() -> str:+ """Put a Java 11+ runtime on PATH for opendataloader-pdf, and return its version.++ opendataloader-pdf shells out to whatever `java` is first on PATH. Its jar is+ compiled for Java 11+, so on a machine whose default is Java 8 every document+ fails with UnsupportedClassVersionError -- which surfaces as a row of ERRORs+ rather than as an obvious "wrong Java" message. Prefer JAVA_HOME, then the+ usual JDK install locations, and fail with an actionable message if none works.+ """+ candidates = []+ if os.environ.get("JAVA_HOME"):+ candidates.append(os.path.join(os.environ["JAVA_HOME"], "bin", "java"))+ current = shutil.which("java")+ if current:+ candidates.append(current)+ candidates += [+ "/opt/homebrew/opt/openjdk@11/bin/java", # Homebrew (Apple silicon)+ "/opt/homebrew/opt/openjdk/bin/java",+ "/usr/local/opt/openjdk@11/bin/java", # Homebrew (Intel)+ "/usr/local/opt/openjdk/bin/java",+ "/usr/lib/jvm/default-java/bin/java", # Debian/Ubuntu+ ]+ for java_bin in candidates:+ if not java_bin or not os.path.exists(java_bin):+ continue+ version = _java_major(java_bin)+ if version >= 11:+ bin_dir = os.path.dirname(java_bin)+ if shutil.which("java") != java_bin:+ os.environ["PATH"] = bin_dir + os.pathsep + os.environ.get("PATH", "")+ return f"java {version}"+ found = _java_major(current) if current else 0+ raise RuntimeError(+ "opendataloader-pdf needs Java 11+, but the java on PATH is "+ + (f"Java {found}." if found else "missing.")+ + " Install one (macOS: `brew install openjdk@11`) or point JAVA_HOME at it."+ )++class OpenDataLoaderProvider(ParserProvider):"""Parse provider using OpenDataLoader PDF.@@ -15,8 +69,8 @@ class OpenDataLoaderProvider(ParserProvider):"""def __init__(self):- """Initialize the parse provider."""- pass+ """Initialize the parse provider, ensuring a usable Java is on PATH."""+ self.java_version = ensure_java_11()def extract_text(self, file_path: Path) -> str:"""Extract markdown from a document using OpenDataLoader PDF."""@@ -25,6 +79,15 @@ class OpenDataLoaderProvider(ParserProvider):input_path=[str(file_path)],output_dir=tmp_dir,format="markdown",+ # image_output defaults to "external", which renders and writes an image+ # file per figure -- real work unrelated to text extraction that inflates+ # the timings. "cluster" tables and "xycut" reading order are what the+ # benchmarks score; hybrid="off" (already the default) keeps the+ # docling-fast ML backend out of the pipeline.+ image_output="off",+ table_method="cluster",+ reading_order="xycut",+ hybrid="off",quiet=True,)# Read the output markdown file