table-extraction
Table extraction from PDFs and images for RAG. Covers Camelot, Tabula, pdfplumber, TableTransformer (DETR), Amazon Textract Tables, Azure Document Intelligence. Conversion to markdown/CSV/JSON, merged-cell handling. USE WHEN: user mentions "table extraction", "PDF tables", "Camelot", "Tabula", "TableTransformer", "Textract tables", "Azure form recognizer tables", "markdown table for LLM" DO NOT USE FOR: general PDF text - use `pdf-extraction`; full OCR pipelines - use `ocr`
What this skill does
# Table Extraction
## Tool Comparison
| Tool | Input | Ruled Tables | Borderless | Merged Cells | Cost |
|------|-------|--------------|------------|--------------|------|
| Camelot (lattice) | Digital PDF | Excellent | Poor | Partial | Free |
| Camelot (stream) | Digital PDF | OK | OK | Poor | Free |
| Tabula | Digital PDF | Excellent | OK | Poor | Free |
| pdfplumber | Digital PDF | Very good | Good | Partial | Free |
| TableTransformer | Image/PDF | Excellent | Excellent | Good | GPU time |
| AWS Textract Tables | PDF/image | Excellent | Excellent | Yes | Per-page |
| Azure Doc Intelligence | PDF/image | Excellent | Excellent | Yes | Per-page |
## Camelot
```python
import camelot
# Lattice: ruled tables
tables = camelot.read_pdf(
"report.pdf",
pages="1-end",
flavor="lattice",
line_scale=40,
)
# Stream: whitespace-delimited
tables_stream = camelot.read_pdf(
"report.pdf",
pages="1-end",
flavor="stream",
edge_tol=500,
row_tol=10,
)
print(f"Found {tables.n} tables")
for i, t in enumerate(tables):
print(t.parsing_report) # accuracy, whitespace, order
df = t.df # pandas DataFrame
df.to_csv(f"table_{i}.csv", index=False)
```
## Tabula-py
```python
import tabula
dfs = tabula.read_pdf(
"report.pdf",
pages="all",
multiple_tables=True,
lattice=True,
pandas_options={"header": 0},
)
tabula.convert_into("report.pdf", "tables.csv", output_format="csv", pages="all")
```
## pdfplumber Tables
```python
import pdfplumber
with pdfplumber.open("report.pdf") as pdf:
for page_num, page in enumerate(pdf.pages):
settings = {
"vertical_strategy": "lines",
"horizontal_strategy": "lines",
"snap_tolerance": 3,
"join_tolerance": 3,
}
for table in page.extract_tables(table_settings=settings):
# table is list[list[str|None]]
cleaned = [[c or "" for c in row] for row in table]
print(f"Page {page_num+1}:", cleaned[0])
```
## TableTransformer (Microsoft, DETR-based)
```python
from transformers import AutoImageProcessor, TableTransformerForObjectDetection
from PIL import Image
import torch
processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection")
detector = TableTransformerForObjectDetection.from_pretrained("microsoft/table-transformer-detection")
structure = TableTransformerForObjectDetection.from_pretrained(
"microsoft/table-transformer-structure-recognition-v1.1-all"
)
image = Image.open("page.png").convert("RGB")
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = detector(**inputs)
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[0]
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
print(detector.config.id2label[label.item()], score.item(), box.tolist())
# Crop detected table and run structure model
x0, y0, x1, y1 = results["boxes"][0].tolist()
table_img = image.crop((x0, y0, x1, y1))
structure_inputs = processor(images=table_img, return_tensors="pt")
with torch.no_grad():
structure_out = structure(**structure_inputs)
```
## AWS Textract — Tables + Queries
```python
import boto3
client = boto3.client("textract", region_name="us-east-1")
with open("form.pdf", "rb") as f:
response = client.analyze_document(
Document={"Bytes": f.read()},
FeatureTypes=["TABLES", "FORMS"],
)
# Build cell grid
blocks = {b["Id"]: b for b in response["Blocks"]}
tables = [b for b in response["Blocks"] if b["BlockType"] == "TABLE"]
def cell_text(cell_block):
out = []
for rel in cell_block.get("Relationships", []):
if rel["Type"] == "CHILD":
for child_id in rel["Ids"]:
word = blocks[child_id]
if word["BlockType"] == "WORD":
out.append(word["Text"])
return " ".join(out)
for table in tables:
cells = []
for rel in table.get("Relationships", []):
if rel["Type"] == "CHILD":
for cid in rel["Ids"]:
cb = blocks[cid]
if cb["BlockType"] == "CELL":
cells.append({
"row": cb["RowIndex"],
"col": cb["ColumnIndex"],
"row_span": cb.get("RowSpan", 1),
"col_span": cb.get("ColumnSpan", 1),
"text": cell_text(cb),
})
print(cells[:5])
```
### Textract Queries (ask targeted questions)
```python
response = client.analyze_document(
Document={"Bytes": pdf_bytes},
FeatureTypes=["QUERIES"],
QueriesConfig={"Queries": [
{"Text": "What is the invoice total?", "Alias": "TOTAL"},
{"Text": "What is the due date?", "Alias": "DUE_DATE"},
]},
)
```
## Azure AI Document Intelligence
```python
from azure.ai.documentintelligence import DocumentIntelligenceClient
from azure.core.credentials import AzureKeyCredential
import os
client = DocumentIntelligenceClient(
endpoint=os.environ["AZURE_DOC_INTEL_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_DOC_INTEL_KEY"]),
)
with open("report.pdf", "rb") as f:
poller = client.begin_analyze_document(
model_id="prebuilt-layout",
body=f,
output_content_format="markdown",
)
result = poller.result()
for table in result.tables:
print(f"Rows: {table.row_count}, Cols: {table.column_count}")
for cell in table.cells:
print(cell.row_index, cell.column_index, cell.content,
"span=", cell.row_span, cell.column_span)
```
## Convert Table to Markdown (for LLM Context)
```python
import pandas as pd
def df_to_markdown(df: pd.DataFrame, caption: str | None = None) -> str:
df = df.fillna("").astype(str)
header = "| " + " | ".join(df.columns) + " |"
sep = "|" + "|".join(["---"] * len(df.columns)) + "|"
rows = ["| " + " | ".join(row) + " |" for row in df.values]
md = "\n".join([header, sep, *rows])
return f"**{caption}**\n\n{md}" if caption else md
```
### Handling Merged Cells (from grid with row/col span)
```python
def cells_to_markdown(cells: list[dict]) -> str:
rows = max(c["row"] for c in cells)
cols = max(c["col"] for c in cells)
grid = [["" for _ in range(cols)] for _ in range(rows)]
for c in cells:
for dr in range(c["row_span"]):
for dc in range(c["col_span"]):
r = c["row"] - 1 + dr
col = c["col"] - 1 + dc
if 0 <= r < rows and 0 <= col < cols and not grid[r][col]:
grid[r][col] = c["text"]
header = "| " + " | ".join(grid[0]) + " |"
sep = "|" + "|".join(["---"] * cols) + "|"
body = ["| " + " | ".join(r) + " |" for r in grid[1:]]
return "\n".join([header, sep, *body])
```
## Anti-Patterns
| Anti-Pattern | Fix |
|---|---|
| Passing raw CSV text to LLM | Convert to markdown; LLMs parse it better |
| Using Camelot on scanned PDFs | Scanned requires OCR + TableTransformer or Textract |
| Ignoring merged cells | Expand spans when building grid |
| Single flavor for all PDFs | Try `lattice` then fall back to `stream` |
| No accuracy check | Use `tables.parsing_report` and re-extract low-confidence |
| Losing table context | Prepend caption and page number to markdown |
## Production Checklist
- [ ] Fallback chain: pdfplumber -> Camelot lattice -> Camelot stream -> Textract
- [ ] Tables serialized as markdown with caption + page metadata
- [ ] Merged cells handled (row_span, col_span)
- [ ] Low-confidence tables flagged for human review
- [ ] Page images cached for image-based re-extraction
- [ ] Output schema validated (row/col counts non-zero)
- [ ] Rate limits + retries for Textract/Azure
- [ ] Cost tracking per-page for cloud OCR services
Related in Ads & Marketing
ads
IncludedMulti-platform paid advertising audit and optimization skill. Analyzes Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, and Apple Ads. 250+ checks with scoring, parallel agents, industry templates, and AI creative generation.
banana
IncludedAI image generation Creative Director powered by Google Gemini Nano Banana models. Use this skill for ANY request involving image creation, editing, visual asset production, or creative direction. Triggers on: generate an image, create a photo, edit this picture, design a logo, make a banner, visual for my anything, and all /banana commands. Handles text-to-image, image editing, multi-turn creative sessions, batch workflows, and brand presets.
rpg-migration-analyzer
IncludedAnalyzes legacy RPG (Report Program Generator) programs from AS/400 and IBM i systems for migration to modern Java applications. Extracts business logic from RPG III/IV/ILE source code, identifies data structures (D-specs), file operations (F-specs), program dependencies (CALLB/CALLP), and converts RPG constructs to Java equivalents. Generates migration reports, complexity estimates, and Java implementation strategies with POJO classes, JPA entities, and service methods. Use when modernizing AS/400 or IBM i legacy systems, analyzing RPG source files (.rpg, .rpgle, .RPGLE), converting RPG to Java, mapping data specifications to Java classes, planning legacy system migration, or when user mentions RPG analysis, Report Program Generator, RPG III/IV/ILE, AS/400 modernization, IBM i migration, packed decimal conversion, or mainframe application rewrite.
brand-library-architect
IncludedBuild a complete brand library for a product — visual asset render pipeline, brand documentation set (BRAND, COPY, MANIFESTO, BIOS, FAQ, GLOSSARY, TONE, PRICING), open-source convention files (README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT), and a self-contained press kit. This skill should be used when the user asks to "build a brand library / brand kit / press kit / brand assets" for a product, "set up a brand library workflow," "create a positioning manifesto plus visual identity," or any combination of brand documentation + visual asset pipeline. Apply phase-by-phase or run end-to-end. Templates are product-agnostic and use {{TOKEN}} placeholders the skill prompts the user to fill.
writing-tech-post
IncludedAuthors engineering blog posts end-to-end: launch deep-dives, incident postmortems, architecture migrations, performance case studies, tutorials, AI/agent system writeups, security disclosures, and research-to-product translations. Picks the correct archetype, plans the abstraction ladder, enforces an evidence cadence (diagrams, benchmarks, profiles, traces, code, ablations), tunes voice against publisher house styles (Datadog, Vercel, GitHub, AWS, Meta, Cloudflare, Jane Street), and runs a pre-publish gate for narrative momentum and disclosure ethics. Use when drafting a new engineering post, restructuring a draft that feels flat, deciding which evidence form belongs where, validating that depth and product context are balanced, or preparing a postmortem, migration, or performance narrative for external publication. Do not use for API reference documentation, README authoring, marketing copy, release notes, generic SEO content, ghost-written executive thought leadership, or non-engineering long-form essays.
blog-google
IncludedGoogle API integration for blog performance: PageSpeed Insights, CrUX Core Web Vitals with 25-week history, Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search for embedding, and Google Ads Keyword Planner. Progressive feature availability based on credential tier (API key, OAuth/service account, GA4, Ads). Shares config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user says "google data", "page speed", "core web vitals", "search console", "indexation", "GA4", "keyword research", "nlp entities", "blog performance", "youtube search", "google api setup".