Intermediate12 min read

Find the policy that applied on a given date

Look up a table entry across archived PDF editions and check that removed entries do not reappear from an older source.

Put both editions in one folder

The fictional library issues a complete replacement schedule each time. A question for July needs the June policy. A question for November needs the November policy. Use the effective date printed in each source to pick the active schedule before looking up an equipment ID.

Use a Python virtual environment. Save policy_table.py in your working folder and put both PDFs in a policies subfolder.

Download policy_table.py
View policy_table.py
import argparse
from dataclasses import dataclass
from datetime import date
from hashlib import sha256
from io import BytesIO
from pathlib import Path
import re

import pdfplumber

HEADERS = ("Equipment ID", "Equipment", "Loan limit", "Conditions")


@dataclass(frozen=True)
class EquipmentRow:
    page: int
    table: int
    row: int
    cells: tuple[str, ...]


@dataclass(frozen=True)
class Edition:
    filename: str
    effective: date
    digest: str
    rows: dict[str, EquipmentRow]


def read_edition(path):
    data = path.read_bytes()
    rows = {}
    with pdfplumber.open(BytesIO(data)) as pdf:
        first_page = pdf.pages[0].extract_text() if pdf.pages else ""
        match = re.search(r"^Effective ([0-9]{4}-[0-9]{2}-[0-9]{2})$", first_page or "", re.M)
        if not match:
            raise ValueError(f"{path.name}: expected an effective date on page 1.")
        effective = date.fromisoformat(match[1])
        for page in pdf.pages:
            for table_number, table in enumerate(page.extract_tables(), start=1):
                headers = tuple(" ".join((cell or "").split()) for cell in table[0])
                if headers != HEADERS:
                    raise ValueError(f"{path.name}, page {page.page_number}: unexpected table headers.")
                for row_number, row in enumerate(table[1:], start=2):
                    cells = tuple(" ".join((cell or "").split()) for cell in row)
                    if len(cells) != len(HEADERS) or not all(cells):
                        raise ValueError(f"{path.name}, page {page.page_number}: incomplete row {row_number}.")
                    equipment_id = cells[0]
                    if equipment_id in rows:
                        raise ValueError(f"{path.name}: repeated ID {equipment_id}.")
                    rows[equipment_id] = EquipmentRow(page.page_number, table_number, row_number, cells)
    if not rows:
        raise ValueError(f"{path.name}: no equipment rows were extracted.")
    return Edition(path.name, effective, sha256(data).hexdigest(), rows)


def print_row(edition, row):
    print(f"{edition.filename} | effective {edition.effective} | page {row.page}, table {row.table}, row {row.row}")
    for column, value in zip(HEADERS, row.cells):
        print(f"  {column}: {value}")


def lookup(folder, equipment_id, as_of):
    paths = sorted(folder.glob("equipment-policy-*.pdf"))
    if not paths:
        raise ValueError(f"No equipment-policy PDFs found in {folder}.")
    editions = [read_edition(path) for path in paths]
    dates = {edition.effective for edition in editions}
    if len(dates) != len(editions):
        raise ValueError("More than one source has the same effective date. Review the editions.")
    active = max((edition for edition in editions if edition.effective <= as_of),
                 key=lambda edition: edition.effective, default=None)
    if active is None:
        print(f"No edition is effective on {as_of}.")
        return
    row = active.rows.get(equipment_id)
    if row is None:
        print(f"{equipment_id} is absent from {active.filename} (effective {active.effective}).")
        return
    print_row(active, row)
    print(f"  File SHA-256: {active.digest}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Inspect and search a fictional equipment policy.")
    commands = parser.add_subparsers(dest="command", required=True)
    inspect = commands.add_parser("inspect")
    inspect.add_argument("pdf", type=Path)
    find = commands.add_parser("find")
    find.add_argument("folder", type=Path)
    find.add_argument("equipment_id", type=str.upper)
    find.add_argument("--as-of", type=date.fromisoformat, required=True)
    args = parser.parse_args()

    try:
        if args.command == "inspect":
            edition = read_edition(args.pdf)
            for row in edition.rows.values():
                print_row(edition, row)
        else:
            lookup(args.folder, args.equipment_id, args.as_of)
    except (OSError, ValueError, pdfplumber.utils.exceptions.PdfminerException) as error:
        raise SystemExit(str(error)) from None
python -m pip install "pdfplumber==0.11.9"
python policy_table.py find policies EQ-314 --as-of 2026-07-15
python policy_table.py find policies EQ-314 --as-of 2026-11-14
You’re ready when

July returns 30 minutes and November returns 45 minutes. Both cite page 1, table 1, row 2. The filenames, effective dates, and file digests identify two different editions.

Check a removed entry

python policy_table.py find policies EQ-073 --as-of 2026-07-15
python policy_table.py find policies EQ-073 --as-of 2026-11-14
python policy_table.py find policies EQ-314 --as-of 2026-01-01

The slide viewer appears in July and is absent in November. January has no effective edition in this folder. A search over both editions without a date filter could still surface the slide viewer’s old row.

Keep the version with the answer

Use the source date for eligibility and the digest for identity. The digest changes if the file changes, even if it keeps the same filename. In a persistent index, filter by edition before ranking passages or sending them to a model. If a policy issues partial updates, record which rows each revision replaces before applying this approach.

Check your understanding

Why choose the edition before looking up the equipment ID?

Each edition replaces the complete schedule. Searching the ID first could carry a removed row forward from an older policy.

Sources

Search the guide