{"slug": "show-hn-offline-python-table-extractor-for-digital-and-scanned-pdfs", "title": "Show HN: Offline Python table extractor for digital and scanned PDFs", "summary": "A developer released an open-source Python tool that extracts tables from digital and scanned PDFs entirely on-device, combining a native OpenCV multi-table detector, a PDFium native text fast path via pypdfium2, and RapidOCR running on ONNX Runtime, with no cloud services, API keys, or telemetry. The tool's native text-layer path is claimed to be 40×–80× faster than OCR, processing a 16-page warn_report.pdf in 0.95 seconds with zero OCR typos, and it groups tables with matching columns into separate schema-matched CSV files or Python data structures. It accepts PDFs, single images, image folders, and in-memory bytes or PIL images, and supports CPU, NVIDIA CUDA, and AMD ROCm acceleration.", "body_md": "**100% local, private, zero-config** table extraction powered by a **native OpenCV multi-table engine + PDFium native text fast path + RapidOCR** — extracts **all tables from PDFs, single/multiple images, or folders of images** and automatically groups tables with matching columns into **separate, schema-matched CSV files** or Pythonic data structures, with automatic native-text vs. OCR routing, multi-core CPU parallelism, pluggable/installable RapidOCR language packs, repeated-header & headerless-continuation merging, stacked header flattening, implicit sub-row splitting, headless visual debugging, and **CPU / NVIDIA CUDA / AMD ROCm** acceleration.\n\n**100% Local & Private:** Everything runs entirely on your own machine — no cloud services, no external API keys, no telemetry, and no documents ever leave your environment. Once language models are cached (or pre-installed via `pdf2csv-tables languages install`), extraction works completely **offline / air-gapped**.\n\n- **100% local & offline-ready engine (`OpenCV + RapidOCR`):** Runs completely on-device via ONNX Runtime (or local PyTorch GPU) — no cloud APIs, no API keys, no external OS binaries, and zero network calls during extraction once models are cached.\n- **Unified PDF & image inputs (CLI and Python library):**  - Accepts **PDFs** (`--pdf-mode render` default via`pypdfium2` , or`--pdf-mode embedded` raw scan extraction with automatic logo filtering & render fallback on hybrid PDFs),\n  - **Single images** (`.png` ,`.jpg` ,`.jpeg` ,`.webp` ,`.tif` ,`.tiff` ,`.bmp` , including multi-frame TIFFs and automatic EXIF orientation),\n  - **Multiple images** or a**folder of images** (naturally sorted`page_1.png, page_2.png, ..., page_10.png` and processed seamlessly like pages of a multi-page PDF),\n  - **In-memory inputs** in Python (`bytes` for PDFs or images,`PIL.Image.Image` , or sequences of images/paths).\n- Accepts \n- **Native OpenCV multi-table & borderless detector + fast native PDF text layer:**  - Connected-component morphological grid & joint detector finds **all** bordered tables on every page while ignoring prose, diagrams, and decorative page frames.\n  - **Automatic native PDF text-layer fast path (`--text-source auto`, default):** extracts exact word coordinates directly via` pypdfium2` on digital PDFs (**40×–80× faster** ,**0.95 s** for 16-page`warn_report.pdf` , zero OCR typos) and automatically falls back to**RapidOCR** on image-only scans, raster images, or broken font maps. Override anytime with`--text-source ocr` or`--text-source native` .\n  - Auto-deskews tilted scans (`--deskew` ) while skipping redundant deskew on straight digital PDFs.\n  - Splits tall unruled data bands (e.g., 5-row visual grouping blocks) into individual rows while preserving wrapped multi-line prose cells.\n  - Detects horizontally merged cells from missing vertical dividers and extracts whitespace-aligned borderless tables (`--borderless` ).\n  - Paired with tuned single-pass **RapidOCR** (`onnxruntime` ) with table-ROI cropping on prose-heavy scans (`--no-borderless` ) and configurable multi-core CPU parallelism (`--workers` /`-j` /`PDF2CSV_WORKERS` ).\n- Connected-component morphological grid & joint detector finds \n- **Smart column detection, repeated headers & headerless continuations:**  - Handles multi-page tables **with repeated headers on every page** ,**without repeated headers** (headerless continuations), or**mixed** (headers repeated on some pages and omitted on others).\n  - Deduplicates repeated single-row, 2-row stacked/spanning, and mid-table headers automatically (or keep them via `--keep-repeated-headers` ).\n  - Promotes full-width banner titles into `manifest.json` (`schema.title` ) and flattens stacked 2-row spanning headers into clean column names.\n  - Fuzzy-matches column headers across pages (Unicode-safe for Latin, Cyrillic, Hebrew, Arabic, CJK; absorbs OCR typos like `Descriptlon` ↔`Description` ).\n  - Matches headerless continuations via column count, normalized/table-relative column spans (even on margin-shifted duplex scans), and column data-type profiles.\n  - Keeps tables with different headers in **separate CSV files** — even when they share the same column count.\n- Handles multi-page tables \n- **Pluggable & user-installable RapidOCR language packs:**  - Built-in support for English, European Latin (`de` ,`fr` ,`es` ,`it` ,`pt` ,`nl` ,`pl` ,`sv` ,`da` ,`fi` ,`no` ,`cs` ,`hu` ,`ro` ,`tr` ,`vi` , ...), Cyrillic (`ru` ,`uk` ,`bg` ,`sr` ,`be` ), Arabic (`ar` ,`fa` ,`ur` ), Chinese (`zh` ,`zh_tw` ), Japanese (`ja` ), Korean (`ko` ), Devanagari (`hi` ), Thai (`th` ), Greek (`el` ), Tamil (`ta` ), Telugu (`te` ), and Kannada (`ka` ).\n  - Manage offline/cached models (`languages list` ,`languages install` ,`languages remove` ), add custom ONNX recognition models + character dictionaries (`languages add` ,`.zip` /folder packs), or plug in Python packages via`entry_points` (`pdf_table_extractor.languages` ).\n- Built-in support for English, European Latin (\n- **Hardware acceleration:** Automatic`--device auto|cpu|cuda|rocm` routing,`pdf2csv-tables doctor` diagnostics, and multi-target Docker images (`cpu` ,`cuda` ,`rocm` ).\n\n| Capability | `pdf-to-csv-table-extractor` | Camelot | Tabula-py | pdfplumber | Docling | \n|---|---|---|---|---|---|\n| **Zero external OS binaries***(no Java / Ghostscript / Tesseract / Poppler)* | **Yes** | No *(Ghostscript)* | No *(Java JVM)* | **Yes** | **Yes** | \n| **Digital PDFs (fast native text layer)** | **Yes***(0.95 s / 16p)* | Yes | Yes | Yes | Yes | \n| **Scanned PDFs, tilted scans & image folders** | **Yes***(auto-deskew + RapidOCR)* | No | No | No | Yes *(heavier DL models)* | \n| **Stamped / hybrid scans***(vector text + tilted scan)* | **Yes***(automatic fallback)* | No | No | No | Yes | \n| **Multi-page schema-matched CSV merging***(repeated + headerless)* | **Yes***(automatic)* | Manual | Manual | Manual | Manual | \n| **Lightweight install & CPU / CUDA / ROCm** | **Yes***(ONNX Runtime / PyTorch)* | CPU | CPU | CPU | PyTorch / heavy | \n| **Outputs** | CSV, ZIP, JSON, Markdown, DataFrame, Polars | CSV, JSON, DataFrame | CSV, JSON, DataFrame | Lists / dicts | Markdown, JSON, DocTags | \n\n```\n  Input: PDF / Image(s) / Folder / bytes\n                   │\n                   ▼\n   1. Document Loader (pypdfium2 raster + native text boxes / PIL, EXIF, lazy --pages)\n                   │\n                   ▼   [Multi-core CPU worker pool via --workers / -j / PDF2CSV_WORKERS]\n   2. Preprocessing (auto-deskew on scans; skipped on straight digital PDFs)\n                   │\n                   ▼\n   3. Native OpenCV Grid Detector (bordered grids, horizontal merges, sub-rows & borderless)\n                   │\n          ┌────────┴────────────────────────────┐\n          ▼ (--text-source auto: digital PDF)   ▼ (scanned PDF / images / --text-source ocr)\n   3a. Native PDF Text Layer             3b. Tuned RapidOCR (table-ROI crop on prose scans)\n       (exact PDFium word boxes,             ◄── Pluggable Language Packs (ONNX / plugins)\n        ~11 ms/page, zero OCR typos)         ◄── Accelerator (CPU / NVIDIA CUDA / AMD ROCm)\n          └────────┬────────────────────────────┘\n                   ▼\n   4. Column & Schema Engine (repeated & headerless merging,\n                              banner strip, stacked header flatten)\n                   │\n                   ▼\n   5. Per-Schema CSVs / Pythonic API + manifest.json + debug overlays\n```\n\nRequires **Python 3.11 – 3.14** (Linux, macOS, Windows).\n\n```\n# With pip (100% local, CPU-ready, zero external OS binaries)\npip install pdf-to-csv-table-extractor\n\n# Optional Arabic / Persian / Urdu RTL support (installs python-bidi)\npip install \"pdf-to-csv-table-extractor[rtl]\"\n\n# Or with uv\nuv add pdf-to-csv-table-extractor\n\n# Or run one-shot via uvx without creating a virtualenv\nuvx --from pdf-to-csv-table-extractor pdf2csv-tables extract document.pdf -o output/\n\n# Optional NVIDIA CUDA ONNX Runtime acceleration (swap CPU onnxruntime AFTER install)\npip install pdf-to-csv-table-extractor\npip uninstall -y onnxruntime && pip install \"onnxruntime-gpu>=1.18.0\"\n```\n\n## Install from a local git checkout\n\n```\ngit clone https://github.com/vitali84/pdf-to-csv-table-extactor.git\ncd pdf-to-csv-table-extactor\nuv sync   # or: pip install .\n```\n\n*Note:* The example PDFs under `samples/` are available in the [GitHub repository](https://github.com/vitali84/pdf-to-csv-table-extactor/tree/master/samples) (excluded from the PyPI wheel to keep installs lean). Substitute any local PDF, image, or folder of images.\n\n```\npdf2csv-tables extract samples/warn_report.pdf --pages 1 -o output/ --debug-dir debug_out/\n```\n\nIgnores the agency logo, title block, and publication note, detects the 7-column header and all **36 data rows**, and writes a schema-named CSV alongside its manifest:\n\n| Notice Date | Effective | Received | Company | City | No. Of | Layoff/Closure | \n|---|---|---|---|---|---|---|\n| 06/22/2015 | 03/25/2016 | 07/01/2015 | Maxim Integrated Product | San Jose | 150 | Closure Permanent | \n| 06/30/2015 | 08/29/2015 | 07/01/2015 | McGraw-Hill Education | Monterey | 137 | Layoff Unknown at this time | \n| 06/30/2015 | 08/30/2015 | 07/01/2015 | Long Beach Memorial Medical Center | Long Beach | 90 | Layoff Permanent | \n| 07/01/2015 | 09/02/2015 | 07/01/2015 | Leidos | El Segundo | 72 | Layoff Permanent | \n| 07/01/2015 | 09/30/2016 | 07/01/2015 | Bosch Healthcare Systems, Inc. | Palo Alto | 55 | Closure Permanent | \n\n<sub>Showing the first 5 of 36 extracted rows from `samples/warn_report.pdf` (page 1). Omit `--pages 1` to extract and merge all 16 pages (643 rows) in under 1 second via the automatic native PDF text fast path.</sub>\n\n## View output files & raw CSV excerpt\n\n```\noutput/\n├── warn_report_table_01_notice_date_effective_received.csv   # 36 rows x 7 columns\n└── warn_report_manifest.json\nNotice Date,Effective,Received,Company,City,No. Of,Layoff/Closure\n06/22/2015,03/25/2016,07/01/2015,Maxim Integrated Product,San Jose,150,Closure Permanent\n06/30/2015,08/29/2015,07/01/2015,McGraw-Hill Education,Monterey,137,Layoff Unknown at this time\n06/30/2015,08/30/2015,07/01/2015,Long Beach Memorial Medical Center,Long Beach,90,Layoff Permanent\n07/01/2015,09/02/2015,07/01/2015,Leidos,El Segundo,72,Layoff Permanent\n07/01/2015,09/30/2016,07/01/2015,\"Bosch Healthcare Systems, Inc.\",Palo Alto,55,Closure Permanent\n```\n\n*Headless debug overlay (`--debug-dir`): amber highlights the detected header row; blue outlines every extracted cell.*\n\nImages work the **exact same way** as PDFs — including auto-deskewing, multi-table detection, repeated-header deduplication, and headerless cross-page continuation merging:\n\n```\n# Single image (.png, .jpg, .jpeg, .webp, .tif, .tiff, .bmp)\npdf2csv-tables extract scan_page1.png -o output/\n\n# Folder of images (sorted naturally: page_1.png, page_2.png, ..., page_10.png -> merged CSVs)\npdf2csv-tables extract ./monthly_scans/ -o output/ --zip\n\n# Multiple image files merged as pages of one document\npdf2csv-tables extract page_1.png page_2.png page_3.png -o output/\n\n# Or treat each image argument as an independent document\npdf2csv-tables extract invoice_a.png invoice_b.png --separate-images -o output/\npdf2csv-tables extract samples/multiple_tables.pdf -o output/ --debug-dir debug_out/\n```\n\nIgnores the prose paragraph between the two tables and writes **two separate CSV files** (`G1` blue 4-column table and `G2` green 3-column table):\n\n```\noutput/\n├── multiple_tables_table_01_4cols.csv   # 7 rows x 4 columns\n├── multiple_tables_table_02_3cols.csv   # 3 rows x 3 columns\n└── multiple_tables_manifest.json\n```\n\n*Two distinct tables on the same page (`G1` blue 4-column, `G2` green 3-column) with surrounding prose ignored.*\n\n```\npdf2csv-tables extract samples/foo_scanned.pdf \\\n  --pdf-mode embedded \\\n  --deskew \\\n  -o output/ \\\n  --debug-dir debug_out/\n```\n\nOn [samples/foo_scanned.pdf](https://github.com/vitali84/pdf-to-csv-table-extactor/blob/master/samples/foo_scanned.pdf) (zero PDF text layer, tilted ~1.8°, warm paper gradient, noise, and JPEG artifacts), the pipeline automatically deskews the page (`-1.74°`), ignores headings and numbered lists, detects the horizontally merged `Percent Fuel Savings` header span, and outputs `output/foo_scanned_table_01_cycle_name_ki_1_km_distance_mi.csv`:\n\n```\nCycle Name,KI (1/km),Distance (mi),Percent Fuel Savings - Improved Speed,Percent Fuel Savings - Decreased Accel,Percent Fuel Savings - Eliminate Stops,Percent Fuel Savings - Decreased Idle\n2012_2,3.30,1.3,5.9%,9.5%,29.2%,17.4%\n2145_1,0.68,11.2,2.4%,0.1%,9.5%,2.7%\n4234_1,0.59,58.7,8.5%,1.3%,8.5%,3.3%\n2032_2,0.17,57.8,21.7%,0.3%,2.7%,1.2%\n4171_1,0.07,173.9,58.1%,1.6%,2.1%,0.5%\n```\n\n*Tilted JPEG scan auto-deskewed (`-1.74°`) with stacked `Percent Fuel Savings` spanning header detected.*\n\nWhen a multi-page PDF (or folder of scanned images) mixes cover prose, multiple distinct tables per page, **repeated headers on some pages**, **no headers on continuation pages**, blank dividers, tilted scans, and borderless tables:\n\n```\npdf2csv-tables extract quarterly_report.pdf -o output/ --merge schema --zip --utf8-bom\n```\n\nTables with matching column schemas are automatically merged across pages into one CSV per schema (deduplicating repeated headers while keeping all continuation rows), while different tables stay in separate CSVs:\n\n```\noutput/\n├── quarterly_report_table_01_date_merchant_category.csv   # Pages 2, 3 (continuation), 5 (dedup header)\n├── quarterly_report_table_02_metric_value.csv             # Pages 2, 5 (dedup header)\n├── quarterly_report_table_03_sku_product_qty.csv          # Page 3\n├── quarterly_report_table_04_employee_department_ext.csv  # Page 6 (borderless)\n├── quarterly_report_manifest.json\n└── quarterly_report_tables.zip\n```\n\nUseful grouping flags:\n\n- `--merge schema`*(default)* — group by column headers & continuations into separate CSVs\n- `--merge none` — emit one CSV per individual table without cross-page merging\n- `--merge all` — concatenate all detected tables into a single CSV\n- `--deduplicate-headers`*(default)* /`--keep-repeated-headers` — control whether repeated header rows on subsequent pages are removed or kept\n\n``` php\n# Multi-page report with headerless continuations across all 16 pages -> 643 rows in <1s (auto native text + parallel workers)\npdf2csv-tables extract samples/warn_report.pdf --no-borderless -o output/\n\n# Force RapidOCR even on digital PDFs (e.g. broken font encodings) with 4 parallel CPU workers\npdf2csv-tables extract samples/warn_report.pdf --pages 1-3 --no-borderless --text-source ocr -j 4 -o output/\n\n# Strict native PDF text only (never invokes OCR; skips image-only pages)\npdf2csv-tables extract samples/background_checks.pdf --no-borderless --text-source native -o output/\n\n# Two complex tables with banner title & wrapped paragraph cells -> banner promoted to schema.title\npdf2csv-tables extract samples/twotables_1.pdf -o output/\n```\n\nKey extraction & performance flags:\n\n- `--text-source auto|ocr|native`*(default: `auto`)* — use fast native PDF text boxes on digital PDFs with automatic RapidOCR fallback on scans/images/garbled fonts;`ocr` forces RapidOCR on every page;`native` uses only the PDF text layer.\n- `--workers / -j <N>` or`PDF2CSV_WORKERS=<N>`*(default: `0` = auto)* — parallel CPU page workers (`0` auto-scales up to 8 workers for native-text grids and up to 4 workers for CPU OCR;`1` runs sequentially; GPU OCR stays single-worker to avoid VRAM contention).\n- `--min-confidence <0-100>`*(default: `40`)* — minimum OCR token confidence threshold.\n- `--implicit-rows / --no-implicit-rows`*(default: enabled)* — split tall unruled visual bands into individual rows.\n- `--fallback-render / --no-fallback-render`*(default: enabled)* — fall back to page rendering when`--pdf-mode embedded` encounters vector pages.\n\nDefaults to English (`en`) with zero configuration. RapidOCR's built-in language models download on demand or can be explicitly pre-installed, removed, or extended with **custom ONNX recognition models + character dictionaries**:\n\n```\n# List built-in, cached/installed, custom, and plugin language packs\npdf2csv-tables languages\n\n# Pre-download built-in RapidOCR models for offline / Docker use\npdf2csv-tables languages install de ru ja\n\n# Use any built-in or installed language (or set PDF2CSV_LANG once)\npdf2csv-tables extract rechnung.pdf --lang de\nexport PDF2CSV_LANG=ru\npdf2csv-tables extract report.pdf\n\n# Add a custom RapidOCR / PaddleOCR ONNX recognition model + character dict (e.g. Armenian or custom font)\npdf2csv-tables languages add hy \\\n  --model ./armenian_rec.onnx \\\n  --dict ./armenian_keys.txt \\\n  --name \"Armenian\" \\\n  --aliases hye,armenian\n\n# Or install a portable folder / .zip language pack containing `language.json` + model + dict\npdf2csv-tables languages install ./armenian_pack.zip\n\n# Remove a custom language pack or cached model\npdf2csv-tables languages remove hy\n```\n\nStore language packs in a custom directory via `--lang-dir /path/to/langs` or `export PDF2CSV_LANG_DIR=/path/to/langs` (defaults to `~/.local/share/pdf-to-csv-table-extractor/languages`). For right-to-left Arabic, Persian, or Urdu (`--lang ar|fa|ur`), install the optional RTL extra: `pip install \"pdf-to-csv-table-extractor[rtl]\"`.\n\nThird-party Python packages can also register language packs automatically via standard entry points in their `pyproject.toml`:\n\n```\n[project.entry-points.\"pdf_table_extractor.languages\"]\narmenian = \"my_armenian_pack:get_language_pack\"\n```\n\nUse `extract_tables` (or `extract_pdf_tables`) directly from Python with **PDF paths, image paths, folders of images, lists of images, `PIL.Image.Image`, or raw `bytes`**, and consume results as native Python dicts/lists, JSON, Markdown, `pandas.DataFrame`, `polars.DataFrame`, or CSVs:\n\n``` python\nfrom pathlib import Path\nfrom pdf_table_extractor import (\n    ExtractionConfig,\n    LanguagePack,\n    extract_tables,\n    install_language,\n    register_language,\n)\n\n# 1. Works identically on a PDF, single image, list of images, folder of images, PIL.Image, or bytes\nresult = extract_tables(\"samples/foo.pdf\")\n# result = extract_tables(\"scan_page1.png\")\n# result = extract_tables(\"./monthly_scans/\")\n# result = extract_tables([\"page_1.png\", \"page_2.png\", \"page_3.png\"])\n# result = extract_tables(Path(\"samples/foo.pdf\").read_bytes())\n\nprint(len(result))  # number of distinct logical tables\nprint(f\"native={result.native_text_pages}p, ocr={result.ocr_pages}p\")\n\nfor table in result:  # iterate directly over logical tables\n    print(table.slug, table.headers, f\"rows={len(table)}\", f\"pages={table.page_numbers}\")\n\n    # Native Python formats (zero extra dependencies)\n    records = table.to_records()  # list[dict[str, str]]  (like csv.DictReader)\n    columns = table.to_columns()  # dict[str, list[str]]  (column-oriented)\n    rows = table.to_rows()  # list[list[str]]\n    csv_str = table.to_csv_string()  # in-memory CSV string\n    md = table.to_markdown()  # GitHub-Flavored Markdown (great for LLM/RAG)\n    js = table.to_json()  # JSON array of row objects\n\n    # Optional DataFrame conversions (lazy import if pandas / polars is installed)\n    # df = table.to_dataframe()\n    # pl_df = table.to_polars()\n\n# Access by index, slice, or slug, or convert the entire document at once\nfirst_table = result[0]\nfirst_two = result[:2]\nall_records = result.to_records()  # {slug: list[dict[str, str]]}\nfull_dict = result.to_dict()  # metadata + all tables & records\nfull_json = result.to_json()  # complete JSON string\nall_md = result.to_markdown()  # all tables as Markdown sections\n\n# 2. Pre-install a built-in RapidOCR language or register a custom ONNX language pack in Python\ninstall_language(\"de\")\nregister_language(\n    LanguagePack(\n        code=\"custom_font\",\n        name=\"Custom Font\",\n        model_path=Path(\"./custom_rec.onnx\"),\n        keys_path=Path(\"./custom_keys.txt\"),\n    )\n)\n\n# 3. Custom config + file export\ncfg = ExtractionConfig(\n    pdf_mode=\"embedded\",  # extracts raw PDF scans, auto-falls back to render on vector pages\n    text_source=\"auto\",  # \"auto\" (native PDF text + OCR fallback) | \"ocr\" | \"native\"\n    workers=0,  # 0 = auto multi-core CPU parallelism, 1 = sequential, N = explicit workers\n    pages=\"1-5\",\n    ocr_lang=\"de\",\n    merge=\"schema\",  # \"schema\" | \"none\" | \"all\"\n    deduplicate_headers=True,\n    device=\"auto\",  # \"auto\" | \"cpu\" | \"cuda\" | \"rocm\"\n    debug_dir=Path(\"debug_out\"),\n)\nres = extract_tables(\"./scanned_folder/\", cfg)\nres.export_csvs(\"output/\", write_manifest=True, utf8_bom=True)\nres.export_zip(\"output/all_tables.zip\")\n```\n\nDigital PDFs with embedded text extract in milliseconds on CPU via the native text fast path. For **scanned PDFs, image folders, and `--text-source ocr` workloads**, RapidOCR accounts for **85%–97%** of runtime — running on a GPU delivers **3×–6.6× faster** single-stream throughput (while multi-core CPUs also accelerate multi-page scans via `--workers`). By default, `--device auto` automatically uses an available GPU and falls back cleanly to CPU when none is installed.\n\n```\npdf2csv-tables doctor\n```\n\nLook for `Recommended --device: cuda` (NVIDIA) or `Recommended --device: rocm` (AMD) in the output.\n\n`onnxruntime` (CPU) and `onnxruntime-gpu` share the same Python package namespace and must not be co-installed. Install the package first, then swap `onnxruntime` for `onnxruntime-gpu`:\n\n```\n# With pip\npip install pdf-to-csv-table-extractor\npip uninstall -y onnxruntime && pip install \"onnxruntime-gpu>=1.18.0\"\n\n# Or with uv (inside a uv-managed repo venv, run with `uv run --no-sync` afterwards)\nuv pip uninstall onnxruntime\nuv pip install \"onnxruntime-gpu>=1.18.0\"\n```\n\nMake sure your user belongs to the `render` and `video` groups (`sudo usermod -aG render,video \"$USER\"` and re-login) so `/dev/kfd` and `/dev/dri` are accessible. Two runtimes are supported:\n\n```\n# Option A (Recommended — self-contained wheel; activates RapidOCR's PyTorch HIP engine)\n# Replace rocm7.1 with your installed ROCm series (e.g. rocm6.2, rocm6.4, rocm7.1):\npip install torch --index-url https://download.pytorch.org/whl/rocm7.1\n# Or with uv:\nuv pip install torch --index-url https://download.pytorch.org/whl/rocm7.1\n\n# Option B (ONNX Runtime MIGraphX — requires host MIGraphX matching your ROCm release)\npip uninstall -y onnxruntime\npip install onnxruntime-migraphx\n```\n\n**Note for AMD ROCm (MIOpen warmup):** On the very first run on a fresh AMD GPU, MIOpen compiles and caches convolution kernels on disk (`~/.config/miopen/`), which takes ~15–20 s once per new image shape. Every subsequent run reuses the cache at full GPU speed.\n\n```\n# Auto-detect GPU (default)\npdf2csv-tables extract samples/warn_report.pdf -o output/\n\n# Explicitly target NVIDIA CUDA or AMD ROCm\npdf2csv-tables extract samples/warn_report.pdf --device cuda -o output/\npdf2csv-tables extract samples/warn_report.pdf --device rocm -o output/\n\n# Multi-GPU selection + fail fast if GPU is unavailable (recommended in CI / production)\npdf2csv-tables extract samples/warn_report.pdf --device cuda --gpu-id 1 --strict-device -o output/\n\n# Force CPU even when a GPU is installed (optionally tune multi-core workers via -j / --workers / PDF2CSV_WORKERS)\npdf2csv-tables extract samples/warn_report.pdf --device cpu -j 4 -o output/\n\n# Control text strategy: auto (default: native PDF text + OCR fallback), ocr (always OCR), or native\npdf2csv-tables extract samples/warn_report.pdf --text-source ocr --workers 4 -o output/\n```\n\n*(If you installed GPU wheels manually into a `uv` environment with `uv pip install`, invoke the CLI via `uv run --no-sync pdf2csv-tables ...` so `uv` does not re-sync back to CPU-only packages from `uv.lock`.)*\n\n``` python\nfrom pdf_table_extractor import ExtractionConfig, extract_tables, probe_hardware\n\nhw = probe_hardware()\nprint(\"Recommended device:\", hw.recommended_device)  # \"cuda\" | \"rocm\" | \"cpu\"\n\nresult = extract_tables(\n    \"samples/warn_report.pdf\",\n    ExtractionConfig(\n        device=\"auto\",  # \"auto\" | \"cpu\" | \"cuda\" | \"rocm\"\n        gpu_id=0,  # GPU index on multi-GPU machines\n        strict_device=True,  # raise RuntimeError instead of silently falling back to CPU\n        text_source=\"auto\",  # \"auto\" (native PDF text + OCR fallback) | \"ocr\" | \"native\"\n        workers=0,  # 0 = auto multi-core CPU parallelism, 1 = sequential, N = explicit workers\n    ),\n)\nprint(f\"Ran on: {result.resolved_device} ({result.execution_provider})\")\n```\n\nThe multi-target [Dockerfile](https://github.com/vitali84/pdf-to-csv-table-extactor/blob/master/Dockerfile) builds ready-to-run CLI images for `cpu` *(default)*, `cuda`, and `rocm` — no local GPU Python setup required:\n\n```\n# Build CPU image and run one-shot extraction on PDFs or image folders\ndocker build --target cpu -t pdf2csv-tables:cpu .\ndocker run --rm -v \"$PWD:/data\" pdf2csv-tables:cpu extract /data/samples/warn_report.pdf -o /data/out\n\n# Or run via Docker Compose profiles (place PDFs or images under ./data)\ndocker compose --profile cpu run --rm cpu extract /data/report.pdf -o /data/out\ndocker compose --profile cuda run --rm cuda extract /data/report.pdf -o /data/out --device cuda\ndocker compose --profile rocm run --rm rocm extract /data/report.pdf -o /data/out --device rocm\n```\n\nMeasured on `Intel Core Ultra 7 270K Plus`, Python 3.14, ONNX Runtime `1.32.0`, default 250 DPI:\n\n| Sample | Pages | Rows | Default ( `--text-source auto` ) | Tuned CPU OCR ( `--text-source ocr` ) | Notes | \n|---|---|---|---|---|---|\n| `multiple_tables.pdf` (2 tables + prose) | 1 | 10 | **0.05 s** | 0.84 s | Digital PDF (native text) | \n| `foo.pdf` (prose + 7-col table) | 1 | 5 | **0.08 s** | 1.49 s | Digital PDF (native text) | \n| `twotables_1.pdf` (2 tables + paragraphs) | 1 | 5 | **0.09 s** | 1.62 s | Digital PDF (native text) | \n| `background_checks.pdf` (dense 56×25) | 1 | 56 | **0.12 s** | 5.72 s | Digital PDF (native text) | \n| `warn_report.pdf` (all 16 pages) | 16 | 643 | **0.95 s***(16.8 p/s, auto workers)* | **17.91 s***(auto workers)* | Digital PDF (native text) | \n| `foo_scanned.pdf` (tilted JPEG scan) | 1 | 5 | **0.55 s***(`--no-borderless`)* / 1.47 s | 0.55 s / 1.47 s | Image-only scan (auto → RapidOCR + ROI crop) | \n\n**Multi-Core CPU Scaling (`samples/warn_report.pdf`, all 16 pages / 643 rows):**\n\n- Default (\n`--text-source auto`): `workers=1` **1.14 s** → `workers=0` (auto) **0.95 s** (**58× faster** than single-stream OCR).- Forced OCR (\n`--text-source ocr`): `workers=1` **29.26 s** → `workers=0` (auto, 4 workers) **17.91 s** (**3.1× faster** than untuned sequential OCR).\n\nMeasured head-to-head on **CPU** (`Intel Core Ultra 7 270K Plus`, ONNX Runtime `1.32.0` `CPUExecutionProvider`) vs. **GPU** (` AMD Radeon RX 9070 XT` `gfx1201`, ROCm `7.1`, PyTorch `2.13.0+rocm7.1` HIP via RapidOCR's Torch engine), default 250 DPI, warm steady-state (pure OCR workload):\n\n| Sample | Pages | Rows (CPU / GPU) | CPU Total | GPU Total (RX 9070 XT) | Total Speedup | CPU OCR | GPU OCR | OCR Speedup | \n|---|---|---|---|---|---|---|---|---|\n| `multiple_tables.pdf` (2 tables + prose) | 1 | 10 / 10 | 1.90 s | **0.50 s** | **3.78×** | 1,758 ms | **380 ms** | **4.62×** | \n| `twotables_1.pdf` (2 tables + paragraphs) | 1 | 5 / 5 | 3.31 s | **1.01 s** | **3.28×** | 2,946 ms | **800 ms** | **3.68×** | \n| `foo.pdf` (prose + 7-col table) | 1 | 5 / 5 | 2.92 s | **0.95 s** | **3.08×** | 2,632 ms | **734 ms** | **3.59×** | \n| `foo_scanned.pdf` (tilted JPEG scan) | 1 | 5 / 5 | 2.60 s | **0.86 s** | **3.03×** | 2,395 ms | **644 ms** | **3.72×** | \n| `background_checks.pdf` (dense 56×25) | 1 | 56 / 56 | 9.47 s | **3.30 s** | **2.87×** | 9,192 ms | **3,029 ms** | **3.03×** | \n| `warn_report.pdf` (all 16 pages) | 16 | 643 / 643 | 55.47 s | **19.79 s** | **2.80×** | 50,383 ms | **15,191 ms** | **3.32×** | \n\n```\n# Default auto mode (uses native PDF text on digital PDFs, RapidOCR on scans)\nuv run python benchmarks/benchmark.py --device cpu --text-source auto\n\n# Pure OCR benchmark on CPU or GPU\nuv run python benchmarks/benchmark.py --device cpu --text-source ocr --json bench_cpu.json\nuv run --no-sync python benchmarks/benchmark.py --device auto --text-source ocr --json bench_gpu.json\nuv sync --extra dev\nuv run pytest\nuv run ruff check .\nuv run ruff format --check .\nuv run mypy --strict src\nuv run mypy tests\n```\n\n*Vitali Mogilevsky*\n\nMIT License — see [LICENSE](https://github.com/vitali84/pdf-to-csv-table-extactor/blob/master/LICENSE) for details.", "url": "https://wpnews.pro/news/show-hn-offline-python-table-extractor-for-digital-and-scanned-pdfs", "canonical_source": "https://github.com/vitali84/pdf-to-csv-table-extactor", "published_at": "2026-11-28 11:12:16+00:00", "updated_at": "2026-11-28 11:42:23.090017+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "computer-vision", "ai-infrastructure"], "entities": ["OpenCV", "RapidOCR", "PDFium", "pypdfium2", "ONNX Runtime", "NVIDIA CUDA", "AMD ROCm", "Python"], "also_reported_by": [], "takeaway": "Route digital PDFs through the pypdfium2 native text layer (--text-source auto) instead of OCR: the tool reports 0.95 s for a 16-page warn_report.pdf, 40×–80× faster than OCR with zero OCR typos, falling back to RapidOCR only on scans or broken font maps.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/show-hn-offline-python-table-extractor-for-digital-and-scanned-pdfs", "markdown": "https://wpnews.pro/news/show-hn-offline-python-table-extractor-for-digital-and-scanned-pdfs.md", "text": "https://wpnews.pro/news/show-hn-offline-python-table-extractor-for-digital-and-scanned-pdfs.txt", "jsonld": "https://wpnews.pro/news/show-hn-offline-python-table-extractor-for-digital-and-scanned-pdfs.jsonld"}}