File size: 4,695 Bytes
2ab2b76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | """Section- and row-aware deterministic chunker producing immutable passage IDs."""
import re
from pathlib import Path
from typing import Dict, List
from src.config import PASSAGES_PATH, SOURCE_MANIFEST_PATH
from src.document_processing.extractors import (
extract_csv_rows,
extract_pdf_text,
load_manifest_rows,
)
from src.schemas import PassageRecord
SECTION_INTENT_HINTS: Dict[str, List[str]] = {
"N01-P01": ["deadlines"],
"N01-P02": ["required_documents"],
"N02-P01": ["deadlines", "required_documents"],
"N03-P01": ["eligibility"],
"N03-P02": ["eligibility", "fees"],
"N04-P01": ["eligibility"],
"N05-P01": ["fees", "required_documents"],
"N05-P02": ["deadlines", "fees"],
"N06-P01": ["required_documents", "eligibility"],
"N07-P01": ["required_documents", "deadlines"],
"N08-P01": ["eligibility", "required_documents"],
"N09-R01": ["fees"],
"N09-R02": ["fees", "required_documents"],
"N09-R03": ["fees", "required_documents"],
"N09-R04": ["fees", "deadlines"],
"N09-R05": ["fees", "eligibility"],
"N09-R06": ["fees", "eligibility"],
}
def chunk_pdf_notice(row: Dict[str, str], raw_text: str) -> List[PassageRecord]:
"""Split a PDF notice by explicit [Section N] markers into stable PassageRecords."""
pattern = re.compile(
r"\[Section\s+(\d+)\]\s*(.*?)(?=\[Section\s+\d+\]|Issued by:|\Z)",
re.DOTALL | re.IGNORECASE,
)
passages: List[PassageRecord] = []
for sec_num, sec_body in pattern.findall(raw_text):
clean_text = re.sub(r"\s+", " ", sec_body).strip()
passage_id = f"{row['document_id']}-P0{sec_num}"
passages.append(
PassageRecord(
passage_id=passage_id,
doc_id=row["document_id"],
title=row["title"],
format="pdf",
date=row["date"],
version=row["version"],
section_or_row=f"Section {sec_num}",
intent_hints=SECTION_INTENT_HINTS.get(passage_id, []),
amends_doc_id=row["amends_doc_id"].strip() or None,
amends_scope=row["amends_scope"].strip() or None,
text=clean_text,
)
)
return passages
def chunk_csv_schedule(row: Dict[str, str], csv_rows: List[Dict[str, str]]) -> List[PassageRecord]:
"""Convert each CSV schedule row into a stable PassageRecord."""
passages: List[PassageRecord] = []
for idx, item in enumerate(csv_rows):
passage_id = str(item["row_id"]).strip()
text = (
f"{item['item_name']} ({item['category']}): {item['amount_ngn']}. "
f"Applies to: {item['applies_to']}. Notes: {item['notes']} "
f"(Effective: {item['effective_date']})."
)
passages.append(
PassageRecord(
passage_id=passage_id,
doc_id=row["document_id"],
title=row["title"],
format="csv",
date=str(item["effective_date"]),
version=row["version"],
section_or_row=f"Row {idx + 1} ({passage_id})",
intent_hints=SECTION_INTENT_HINTS.get(passage_id, ["fees"]),
amends_doc_id=row["amends_doc_id"].strip() or None,
amends_scope=row["amends_scope"].strip() or None,
text=text,
)
)
return passages
def build_passages_from_sources(
manifest_path: Path = SOURCE_MANIFEST_PATH,
output_path: Path = PASSAGES_PATH,
) -> List[PassageRecord]:
"""Parse all sources in source_manifest.csv and persist processed passages.jsonl."""
passages: List[PassageRecord] = []
for row in load_manifest_rows(manifest_path):
fmt = row["format"].strip().lower()
if fmt == "pdf":
passages.extend(chunk_pdf_notice(row, extract_pdf_text(row["file_path"])))
elif fmt == "csv":
passages.extend(chunk_csv_schedule(row, extract_csv_rows(row["file_path"])))
else:
raise ValueError(f"Unsupported notice format: {fmt}")
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8") as out:
for p in passages:
out.write(p.model_dump_json() + "\n")
return passages
def load_passages(passages_path: Path = PASSAGES_PATH) -> List[PassageRecord]:
"""Load pre-chunked PassageRecords from JSONL."""
records: List[PassageRecord] = []
with passages_path.open("r", encoding="utf-8") as f:
for line in f:
if line.strip():
records.append(PassageRecord.model_validate_json(line))
return records
|