Python
Two functions: extract for text, extract_document for structure.
pip install khmerpdf
import khpdf
text = khpdf.extract("report.pdf") # plain text
md = khpdf.extract("report.pdf", format="markdown") # headings, lists, tables
doc = khpdf.extract_document("report.pdf") # dictextract
khpdf.extract(source, *, format="text", pages=None, page_markers=False) -> str
| Argument | |
|---|---|
source | A file path (str or pathlib.Path) or the PDF's bytes. |
format | "text" (default), "markdown" or "json". |
pages | 1-based page numbers to keep, e.g. [1, 2] or range(1, 4). All pages by default. |
page_markers | Mark where each page starts. |
extract_document
khpdf.extract_document(source, *, pages=None, words=False) -> dict
Returns the JSON output as a Python dict: pages with their blocks, fonts, OCR flag and warnings. With words=True, each page also lists every word with its box (Word positions). See The output for the fields.
doc = khpdf.extract_document("report.pdf")
for page in doc["pages"]:
if page["needs_ocr"]:
print("page", page["number"], "is a scan")
for block in page["blocks"]:
if block["type"] == "table":
print(block["headers"])Errors
FileNotFoundErrorwhen the path doesn't exist.ValueErrorwhen the data isn't a readable PDF, or for an unknownformat.
A folder of PDFs
from pathlib import Path
import khpdf
for pdf in Path("documents").glob("*.pdf"):
Path("converted", pdf.stem + ".txt").write_text(khpdf.extract(pdf), encoding="utf-8")khpdf releases Python's interpreter lock while it works, so a thread pool converts several PDFs in parallel.
The command
The package also installs the khpdf command, the same tool described in Command line. python -m khpdf runs it too.
With Neam
To find people, organizations and places in the text, pass it to Neam:
import khpdf
from neam import Neam
ner = Neam.from_pretrained("MoriartyPuth/neam")
text = khpdf.extract("report.pdf")
for entity in ner.predict(text)["entities"]:
print(entity["label"], entity["text"])