"""pdf2csv.py: each table in a PDF to its own CSV file, with Docling. Free, and it runs on your computer.

Install: pip install docling
Run:     python pdf2csv.py statement.pdf [more.pdf ...]
It writes statement-table-1.csv, statement-table-2.csv, ... next to each PDF, and never overwrites a file.
Docling reads the text inside the PDF. A scan has none, so run `ocrmypdf scan.pdf ocr.pdf` first.
From https://brasspage.com/pdf-to-csv/
"""

import shlex
import sys
from pathlib import Path

if len(sys.argv) < 2:
    sys.exit(__doc__)

from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOption

opts = PdfPipelineOptions(do_ocr=False, do_table_structure=True)
conv = DocumentConverter(
    format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=opts)}
)

for name in sys.argv[1:]:
    pdf = Path(name)
    doc = conv.convert(pdf).document
    tables = []
    for table in doc.tables:
        df = table.export_to_dataframe(doc=doc)
        # No header row found: pandas would write a 0,1,2 line, so skip it.
        numbered = list(df.columns) == list(range(len(df.columns)))
        # A table shape with no text in it (a scan) is not a table.
        if not (df.empty and numbered):
            tables.append((df, numbered))
    if not doc.texts and not tables:
        print(f"{pdf}: no text. A scan? Run: ocrmypdf {shlex.quote(str(pdf))} ocr.pdf")
        continue
    if not tables:
        print(f"{pdf}: no table found")
    for i, (df, numbered) in enumerate(tables, 1):
        out = pdf.with_name(f"{pdf.stem}-table-{i}.csv")
        if out.exists():
            print(f"{out}: exists, skipped")
            continue
        df.to_csv(out, index=False, header=not numbered)
        print(out)
