BXUP Track progress & test yourself — free
Forward Deployed AI Engineer · Module · ~2 min read
FORWARD DEPLOYED AI ENGINEER · MODULE

Enterprise Data Plumbing: Ingesting Messy ERPs, Legacy SQL & Scanned PDFs

Production AI systems succeed or fail at the data ingestion layer. This module teaches the FDE how to parse scanned multi-column enterprise PDFs, clean corrupt legacy SQL schemas, enforce multi-tenant isolation, and redact PII before embeddings ever touch a database.

  1. 11:30 AM · TUESDAY

    An industrial manufacturing client hands you an S3 bucket containing 12,000 PDF files.

  2. THE DATA DISASTER

    Half of the documents are scanned equipment inspection sheets from 2014, rotated at 90 degrees, containing handwritten inspector signatures and multi-column tables.

  3. THE LEGACY DATABASE

    The other half is an Oracle export with 92 columns named COL_A1, DAT_REV_9, and sentinel null strings like '9999-12-31' and 'N/A'.

  4. THE NAIVE ATTEMPT

    A junior engineer ran standard LangChain DirectoryLoader with RecursiveCharacterTextSplitter. Tables were chopped in half, null dates were embedded as valid historical events, and queries for machine error codes returned zero matches.

  5. THE FDE FIX

    You stand up a layout-aware vision parser, build a Pydantic schema adapter, and implement an automated data quality gate.


1. The Realities of Enterprise Data

In academic benchmarks, datasets are clean CSVs or formatted Markdown. In enterprise client engagements:

  • 80% of data is unstructured
    Scanned PDFs, PowerPoint decks, invoices, emails, and call transcripts.
  • Tables are fatal to naive splitters
    A fixed 500-token chunker slices right through a balance sheet, putting the row labels in Chunk 1 and the revenue figures in Chunk 2.
  • Legacy ERP schemas are hostile
    Decades of patch jobs leave columns with conflicting meanings and sentinel null values.
┌────────────────────────────────────────────────────────────────────────┐
│               Enterprise Ingestion & Plumbing Architecture             │
└────────────────────────────────────────────────────────────────────────┘
                                    │
       ┌────────────────────────────┴────────────────────────────┐
       ▼                                                         ▼
[ Unstructured Documents ]                               [ Legacy Databases ]
 (Scanned PDFs, Invoices)                                 (Oracle, SAP, SQL)
       │                                                         │
       ▼                                                         ▼
[ Layout & Vision Parser ]                               [ Pydantic Schema Adapter ]
 • Layout-aware OCR                                       • Map acronyms to semantics
 • Detect table bounding boxes                           • Sanitize sentinel nulls
 • Serialize tables to Markdown                           • Validate strict types
       │                                                         │
       └────────────────────────────┬────────────────────────────┘
                                    │
                                    ▼
                      [ PII Redaction Gateway ]
                       • Presidio / Regex filters
                       • Mask Aadhaar, PAN, Credit Cards
                                    │
                                    ▼
                      [ Vector & Relational Store ]
                       • Multi-tenant RBAC metadata
                       • Parent-child hierarchical links

2. Parsing Scanned Documents & Complex Tables

When extracting tables from PDFs, the goal is to preserve horizontal and vertical cell associations.

Pattern: Table-Aware Markdown Serialization

Never allow raw OCR text from a table to be dumped as unformatted sentences. Instead, detect table structures and format them into clean GitHub-flavored Markdown:

# table_extractor.py - Production FDE table serializer
from pydantic import BaseModel, Field
from typing import List, Optional

class TableCell(BaseModel):
    row_idx: int
    col_idx: int
    text: str

class ExtractedTable(BaseModel):
    table_id: str
    headers: List[str]
    rows: List[List[str]]
    page_number: int

    def to_markdown(self) -> str:
        """Serializes table into self-contained Markdown with preserved headers."""
        header_line = "| " + " | ".join(self.headers) + " |"
        sep_line = "| " + " | ".join(["---"] * len(self.headers)) + " |"
        row_lines = ["| " + " | ".join(row) + " |" for row in self.rows]
        return "\n".join([header_line, sep_line] + row_lines)

By serializing tables into Markdown, both embedding models and LLM attention mechanisms can preserve tabular relationships without losing row-column associations.


3. Legacy Schema Adapters with Pydantic

When ingesting enterprise database records, an FDE writes explicit schema sanitizers to neutralize dirty data:

# legacy_adapter.py - Enterprise schema cleaner
from pydantic import BaseModel, field_validator
from typing import Optional
from datetime import date

class EnterpriseCustomerRecord(BaseModel):
    customer_id: str
    annual_spend_inr: float
    account_status: str
    last_review_date: Optional[date]

    @field_validator("annual_spend_inr", mode="before")
    def clean_currency(cls, v):
        if isinstance(v, str):
            # Clean currency symbols, commas, and negative parentheses
            clean = v.replace("INR", "").replace("₹", "").replace(",", "").strip()
            if clean.startswith("(") and clean.endswith(")"):
                clean = "-" + clean[1:-1]
            return float(clean) if clean and clean != "N/A" else 0.0
        return float(v or 0.0)

    @field_validator("last_review_date", mode="before")
    def clean_sentinel_dates(cls, v):
        # Catch common enterprise sentinel values used instead of NULL
        if v in ["9999-12-31", "1900-01-01", "0000-00-00", "", None]:
            return None
        return v

4. Multi-Tenant Vector RBAC & Partitioning

Never trust the prompt to enforce tenant data isolation. When indexing documents in vector databases (e.g. Qdrant, pgvector), attach immutable security metadata to every single chunk payload:

# vector_indexer.py - Enforcing cryptographic tenant RBAC
def build_vector_payload(chunk_text: str, tenant_id: str, allowed_roles: list[str], doc_id: str) -> dict:
    return {
        "text": chunk_text,
        "tenant_id": tenant_id,          # E.g. 'tenant_enterprise_hdfc'
        "allowed_roles": allowed_roles,  # E.g. ['claims_adjuster', 'auditor']
        "doc_id": doc_id,
        "indexed_at": "2026-09-08T10:00:00Z"
    }

# When querying: ALWAYS inject filters from verified JWT tokens
def query_with_rbac(client, query_vector, user_jwt_claims):
    tenant_id = user_jwt_claims["tenant_id"]
    user_role = user_jwt_claims["role"]

    search_filter = {
        "must": [
            {"key": "tenant_id", "match": {"value": tenant_id}},
            {"key": "allowed_roles", "match": {"value": user_role}}
        ]
    }
    return client.search(collection_name="enterprise_kb", query_vector=query_vector, query_filter=search_filter)

5. Automated PII Masking Gateway

Under the Indian Digital Personal Data Protection (DPDP) Act, sending raw Aadhaar, PAN, or phone numbers to third-party APIs risks severe regulatory penalties:

# pii_masker.py - Pre-flight privacy gateway
import re

PATTERNS = {
    "PAN": r"\b[A-Z]{5}[0-9]{4}[A-Z]{1}\b",
    "AADHAAR": r"\b[2-9]{1}[0-9]{3}\s[0-9]{4}\s[0-9]{4}\b",
    "PHONE": r"\b(?:\+91[\-\s]?)?[6-9]\d{9}\b",
    "EMAIL": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b"
}

def mask_pii(text: str) -> tuple[str, dict]:
    mapping = {}
    counter = {}
    
    def replacer(match, entity_type):
        val = match.group(0)
        idx = counter.get(entity_type, 1)
        token = f"<{entity_type}_{idx}>"
        mapping[token] = val
        counter[entity_type] = idx + 1
        return token

    masked = text
    for entity, pattern in PATTERNS.items():
        masked = re.sub(pattern, lambda m, e=entity: replacer(m, e), masked)
        
    return masked, mapping

6. Verification Checklist

  • Does your PDF extraction pipeline preserve multi-column tables as Markdown rather than mashed lines?
  • Are sentinel null values (9999-12-31, N/A) converted to None before vector embedding?
  • Are vector queries hardcoded to filter on authenticated tenant_id from JWT tokens?
  • Is PII masked before outbound LLM API dispatch and re-hydrated on the return path?
This is the free reading view. Open BXUP to track your progress, run the hands-on labs, and prove it with original, exam-pattern assessments.
© Anvi Innovate · BXUP — Be Exponentially Upskilled · BXUP is an independent learning platform, not affiliated with or endorsed by AWS, Microsoft, Google, NVIDIA, IBM, Salesforce, Databricks, Oracle or Anthropic. All trademarks belong to their respective owners. · bxup.in