- Resources
Cookbooks
Sparse Table OCR — Net Income Analysis
Hands-on notebooks and guides for building with the Mistral API.
Sparse Table OCR — Net Income Analysis
This notebook reads the sparse income statement PDF, sends it through the Mistral OCR API, prints the markdown output, and reconstructs the net-income row while keeping empty cells as missing values.
The goal is to preserve the blank Q4 slot instead of letting later values shift left.
import importlib
import os
import ocr4_utils
from IPython.display import Markdown
import pandas as pd
import fitz # PyMuPDF
from IPython.display import Image, display
ocr4_utils = importlib.reload(ocr4_utils)
from ocr4_utils import extract_pdf_lines, ocr_request
from ocr4_utils import build_ocr_payload
from ocr4_utils import (
extract_net_income_values_from_pdf,
markdown_table_to_df,
)
PDF_PATH = os.path.join(
os.path.dirname(os.path.abspath('__file__')),
'samples',
'sparse_income_statement_with_net_income.pdf',
)
print(f'Reading sparse_income_statement_with_net_income.pdf, PDF size : {os.path.getsize(PDF_PATH):,} bytes')
# Open the PDF document
doc = fitz.open(PDF_PATH)
# Load the first page (0-indexed)
page = doc.load_page(0)
# Render the page to a PNG image byte array
pix = page.get_pixmap()
image_bytes = pix.tobytes("png")
# Display the image inside VS Code
display(Image(data=image_bytes))
payload = build_ocr_payload(
PDF_PATH,
include_blocks=True,
confidence_granularity='page',
extract_header=True,
extract_footer=True,
table_format='markdown',
)
response = ocr_request(payload)
pages = response.get('pages', [])
print(f'Pages processed: {len(pages)}')
all_tables = [
(table.get('content') or '').strip()
for page in pages
for table in page.get('tables', [])
if (table.get('content') or '').strip()
]
print(f'Tables found in OCR payload: {len(all_tables)}')
for index, table in enumerate(all_tables[:3], start=1):
print(f'\n--- table {index} snippet ---')
print(table[:2000])
pdf_lines = extract_pdf_lines(PDF_PATH)
print('\n--- PDF text fallback ---')
for line in pdf_lines:
print(line)
page0 = pages[0] if pages else {}
markdown_text = page0.get('markdown', '')
print(markdown_text[:4000])
Sparse-table parsing strategy
When a table has empty cells, the usual failure mode is that later values shift left. The safe approach is to:
1.
Read the raw OCR table content.2.
Split markdown rows.3.
Pad shorter rows to the header width.4.
Preserve empty cells as missing values.5.
Fall back to the source PDF text when OCR is ambiguous or sparse.
parsed_tables = [
markdown_table_to_df(table_markdown)
for table_markdown in all_tables
]
parsed_tables = [table for table in parsed_tables if not table.empty]
print(f'Parsed OCR tables: {len(parsed_tables)}')
for index, table in enumerate(parsed_tables[:3], start=1):
print(f'\n--- parsed table {index} ---')
display(table.head(10))
net_income_row = extract_net_income_values_from_pdf(pdf_lines)
print('\n--- net income row extracted from PDF text ---')
print(net_income_row)
# Rebuild the sparse row in a stable DataFrame while keeping the blank Q4 cell intact.
reconstructed_row = pd.DataFrame([
{
'Line Item': 'Net Income',
'Q1 Actual': net_income_row.get('Q1 Actual'),
'Q2 Forecast': net_income_row.get('Q2 Forecast'),
'Q3 Actual': net_income_row.get('Q3 Actual'),
'Q4 Projection': net_income_row.get('Q4 Projection'),
'Full Year Total': net_income_row.get('Full Year Total'),
}
])
print('Reconstructed sparse row:')
display(reconstructed_row)
numeric_values = [
float(v) for v in [
net_income_row.get('Q1 Actual'),
net_income_row.get('Q2 Forecast'),
net_income_row.get('Q3 Actual'),
net_income_row.get('Full Year Total'),
] if pd.notna(v)
]
print(f'Observed numeric values: {numeric_values}')
print(f'Total income across the row: ${sum(numeric_values):,.2f}')
# Final human-readable summary.
q1 = net_income_row.get('Q1 Actual')
q2 = net_income_row.get('Q2 Forecast')
q3 = net_income_row.get('Q3 Actual')
q4 = net_income_row.get('Q4 Projection')
full_total = net_income_row.get('Full Year Total')
display(Markdown(
"### Net income per quarter and total income\n\n"
f"- Q1 Actual: **${float(q1):,.2f}**\n"
f"- Q2 Forecast: **${float(q2):,.2f}**\n"
f"- Q3 Actual: **${float(q3):,.2f}**\n"
f"- Q4 Projection: **blank / missing**\n"
f"- Full Year Total: **${float(full_total):,.2f}**"
))
Interpretation
For this sparse income statement, the source PDF clearly shows:
- Q1 Actual = $40,300
- Q2 Forecast = $8,500
- Q3 Actual = $34,500
- Q4 Projection = blank / missing
- Full Year Total = $83,300
The blank Q4 cell is preserved as missing rather than shifted left, which keeps the table aligned correctly and prevents the rest of the row from being corrupted.