3v324v23's picture
Initial clean code release
6b74974
Raw History Blame Contribute Delete
4.7 kB
import os
import re
from typing import List, Dict, Any, Tuple
import pdfplumber
import fitz # PyMuPDF
class FinancialDocumentParser:
"""
Advanced financial document parser utilizing PyMuPDF and pdfplumber
to accurately extract structured text, multi-header tables, spatial metadata,
and footnote linkages from SEC filings and credit documents.
"""
def __init__(self, filepath: str):
self.filepath = filepath
self.filename = os.path.basename(filepath)
def extract_full_document(self) -> Dict[str, Any]:
"""
Parses the complete PDF file page-by-page, returning structured pages
containing text blocks, tables formatted as Markdown, and footnote linkages.
"""
doc = fitz.open(self.filepath)
total_pages = len(doc)
pages_data = []
with pdfplumber.open(self.filepath) as plumber_pdf:
for page_num in range(total_pages):
page_obj = doc[page_num]
plumber_page = plumber_pdf.pages[page_num]
# Extract explicit tables with bounding boxes
tables_markdown, table_bbox_list = self._extract_tables(plumber_page)
# Extract text blocks outside tables
text_content = page_obj.get_text("text")
# Extract potential footnotes
footnotes = self._extract_footnotes(text_content)
# Combine text and table markdown representation
combined_content = text_content
if tables_markdown:
combined_content += "\n\n### FINANCIAL TABLES EXTRACTED:\n" + "\n\n".join(tables_markdown)
if footnotes:
combined_content += "\n\n### FOOTNOTES & ANNOTATIONS:\n" + "\n".join(footnotes)
pages_data.append({
"page_number": page_num + 1,
"text": text_content,
"tables_markdown": tables_markdown,
"footnotes": footnotes,
"combined_content": combined_content,
"char_count": len(combined_content)
})
doc.close()
return {
"filename": self.filename,
"total_pages": total_pages,
"pages": pages_data
}
def _extract_tables(self, plumber_page) -> Tuple[List[str], List[Any]]:
"""
Extracts structured tables from a pdfplumber page object,
formatting them as clean, human-readable Markdown tables.
"""
markdown_tables = []
bboxes = []
extracted_tables = plumber_page.extract_tables()
table_objects = plumber_page.find_tables()
for idx, table in enumerate(extracted_tables):
if not table or len(table) < 2:
continue
# Clean and sanitize table cells
cleaned_table = []
for row in table:
cleaned_row = [str(cell).strip().replace('\n', ' ') if cell is not None else "" for cell in row]
if any(cleaned_row):
cleaned_table.append(cleaned_row)
if len(cleaned_table) < 2:
continue
# Convert to Markdown Table format
header = cleaned_table[0]
divider = ["---"] * len(header)
md_lines = [" | ".join(header), " | ".join(divider)]
for row in cleaned_table[1:]:
# Ensure row length matches header
if len(row) < len(header):
row.extend([""] * (len(header) - len(row)))
elif len(row) > len(header):
row = row[:len(header)]
md_lines.append(" | ".join(row))
table_md = "\n".join(md_lines)
markdown_tables.append(table_md)
if idx < len(table_objects):
bboxes.append(table_objects[idx].bbox)
return markdown_tables, bboxes
def _extract_footnotes(self, text: str) -> List[str]:
"""
Identifies potential footnote pattern matches in text (e.g. '(1) Excludes non-recurring charges', '* Note 4:').
"""
footnote_pattern = re.compile(
r'^(?:\(\d+\)|\*\d*|\bNote\s+\d+:?|\b\[\d+\])\s+[A-Z0-9].*$',
re.MULTILINE
)
matches = footnote_pattern.findall(text)
return [m.strip() for m in matches]
def parse_pdf_file(filepath: str) -> Dict[str, Any]:
"""
Helper function to parse a PDF file and return full structured document data.
"""
parser = FinancialDocumentParser(filepath)
return parser.extract_full_document()