Camelot PDF Table Extraction

repository·master·Indexed 26 days ago

https://github.com/camelot-dev/camelot

A Python library (camelot-py) for high-accuracy PDF table extraction. It supports ruled tables via the 'lattice' flavor and borderless tables via 'stream', 'network', and 'ml' flavors. Camelot provides a high-level API through `read_pdf()`, a command-line interface, and support for exporting data to CSV, JSON, Excel, HTML, Markdown, and SQLite. Advanced features include OCR for scanned PDFs, neural table extraction using Table Transformer, and visual debugging plots via matplotlib.

Tokens
14.6K
Snippets
42
Records
100
Agent score
81%

What's inside Camelot

  1. Understand the mypyc compilation plan for Camelot

    master

    Camelot plans to use mypyc to ship compiled hot-path modules (specifically camelot/utils.py) in pre-built wheels to improve performance.

    Key details of the implementation model:

    • Default Behavior: When installing via pip install camelot-py on supported platforms, you will receive a pre-built wheel containing the compiled utils.py (as .so or .pyd files) with no extra build dependencies.
    • Fallback: On exotic platforms where a pre-built wheel is unavailable, pip will install from the source distribution (sdist), which remains pure-Python and requires no build dependencies.
    • Performance Impact: Compiling camelot/utils.py is expected to provide a 2-3× speedup on stream/network parse paths compared to the pure-Python version.
    • Limitations: Core classes (like Table) and parsers are not compiled due to dynamic attribute usage and **kwargs constraints in mypyc.
  2. Compare Camelot with other PDF table extraction tools

    master

    Use the following comparison to decide if Camelot is the right tool for your PDF corpus based on specific requirements:

    CapabilityCamelotTabulapdfplumberPyMuPDFgmftunstructured.iotablers
    LicenseMITMITMITAGPL / commercialMITApache 2.0MIT
    Runtimepure PythonJava + wrapperpure PythonC bindingPyTorch modelPython + pluginsRust + Python
    Ruled-grid tables✓ (flavor='lattice')✓ (model-based)◐ (via backend)
    Borderless tables✓ (stream/network/hybrid; flavor='ml' for hardest)
    Per-page overrides✓ (per_page=)◐ (manual loop)
    Scanned PDFs✓ (flavor='ml' + [ocr] extra)◐ (via OCR plugin)✓ (vision model)✓ (Tesseract plugin)
    Neural structure✓ (optional flavor='ml')✓ (Table Transformer)◐ (via model backends)
    Confidence score✓ (Table.confidence)◐ (heuristic)
    In-memory input✗ (needs path)
    Multi-page stitching✓ (TableList.stack_contiguous)◐ (manual)✓ (model-aware)

    Note: ✓ = supported out of the box, ✗ = not supported, ◐ = partial/workaround required.

  3. Choose a table parsing method

    master

    Camelot provides several parsing methods (flavors) depending on the structure of your PDF tables:

    • Stream: Best for tables that use whitespace between cells to simulate structure (no visible lines).
    • Lattice: Best for tables with demarcated lines (borders) between cells. It is deterministic and can automatically parse multiple tables on a single page.
    • Network: A text-based parser that identifies patterns in text bounding boxes to find table structures. Useful for complex text alignments.
    • Hybrid: A combination of Network and Lattice. It uses Network to identify cells and Lattice to refine the precision of row/column boundaries using solid lines.
    • ML (Table Transformer): An optional neural backend designed for dense borderless tables or scanned/image-only PDFs. It uses a Table Transformer (TATR) model to detect structure while relying on the PDF's text layer (or OCR) for content to prevent hallucinations.
  4. Reduce memory usage for long PDFs

    master

    When processing long PDFs, RAM usage grows with the number of pages held in memory. To mitigate this, process the document in page-range chunks and export each chunk to disk. This allows Python to release the intermediate state (text objects, parser caches, and TableList) between calls to read_pdf.

    import camelot
    
    
    def extract_in_chunks(
        filepath,
        total_pages,
        chunk_size=50,
        export_dir=".",
        **read_pdf_kwargs,
    ):
        """Extract tables a chunk of pages at a time, freeing RAM between chunks.
    
        Parameters
        ----------
        filepath : str
            Path to the PDF file.
        total_pages : int
            Total page count of the PDF. Get it from any PDF tool, e.g. 
            ``len(playa.parse(open(filepath, "rb").read()).pages)``.
        chunk_size : int, optional (default: 50)
            How many pages to process per ``read_pdf`` call.
        export_dir : str, optional (default: ".")
            Directory in which per-chunk CSVs are written.
        **read_pdf_kwargs
            Any other keyword arguments are forwarded to
            :meth:`camelot.read_pdf` (e.g. ``flavor="stream"``, 
            ``table_areas=...``).
        """
        for start in range(1, total_pages + 1, chunk_size):
            end = min(start + chunk_size - 1, total_pages)
            tables = camelot.read_pdf(
                filepath, pages=f"{start}-{end}", **read_pdf_kwargs
            )
            tables.export(f"{export_dir}/tables_{start}-{end}.csv")
  5. Use the Network parser for text-alignment based tables

    master
    The Network parser is a text-based method that relies on the bounding boxes of text elements. It identifies common horizontal or vertical coordinate alignments to build a network of connected text elements, which are then used to 'grow' the table structure from a central seed.
  6. Detect small lines in Lattice mode with `line_scale`

    master

    In lattice mode, the smallest detectable line size is determined by the line_scale parameter (default is 40).

    • To detect smaller lines: Increase line_scale.
    • Warning: Setting line_scale too high (>150) may cause text to be incorrectly detected as lines.

    Increasing the scale allows Camelot to see smaller lines that might be separating headers or table sections.

  7. Install Ghostscript dependencies

    master

    Camelot uses image conversion backends. Since v1.0.0, pdfium is the default backend and is easier to install via pip. However, if you need to use Ghostscript, you must install it using your system's package manager or the official installer.

    OS-specific installation commands:

    • Ubuntu: Use apt.
    • MacOS: Use brew.
    • Windows: Download the installer from the official Ghostscript downloads page.
    # Ubuntu
    $ apt install ghostscript
    
    # MacOS
    $ brew install ghostscript
  8. Choose between Camelot and pdfplumber

    master

    Camelot and pdfplumber serve different primary purposes:

    • Choose pdfplumber if: You need fine-grained access to every layout primitive (characters, rects, curves) to perform complex layout analysis (e.g., finding paragraph headers adjacent to tables).
    • Choose Camelot if: You want higher out-of-the-box table-detection quality for typical PDF reports, per-table quality reports via parsing_report (including confidence), or the flavor='hybrid' parser which combines lattice and network signals. Camelot uses playa-pdf as a backend for speed and encrypted-PDF correctness.
  9. Process background lines in Lattice

    master

    If a table's lines are in the background rather than the foreground, use the process_background=True argument in read_pdf to ensure they are detected. This is common in certain PDF types where lines are not clearly foreground elements.

    >>> tables = camelot.read_pdf('background_lines.pdf', process_background=True)
    >>> tables[1].df
  10. Use the Hybrid parser for improved precision

    master
    The Hybrid parser combines the Network and Lattice parsers. It uses the Network parser to identify the table structure and the Lattice parser to provide precise coordinates for row and column boundaries based on detected solid lines. This is particularly effective when both parsers can identify table areas.
  11. Choose between Camelot and Tabula

    master

    Camelot and Tabula are direct peers, but they excel in different areas:

    • Choose Tabula if: You need strong auto-detection of stream-flavor (borderless) tables or want to use an interactive web UI for manually marking table regions. Note that Tabula requires a JRE (Java Runtime Environment) for deployment.
    • Choose Camelot if: You are dealing with complex table structures like multi-row column headers, merged spanning cells, or tables with italic/superscript decorations. Camelot also provides specific kwargs to fix extraction defects without leaving Python: copy_text, shift_text, flag_size, and replace_text.
    • Deployment: Camelot is pure Python and only requires opencv-python-headless and pdfium.