Download src/document_processing/chunker.py from Estarcode/campusdesk-ai: direct link, hf CLI and curl.
- Browser
- Download file 4.7 kB
-
https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/document_processing/chunker.py
- Command line
-
hf download hf://Estarcode/campusdesk-ai/src/document_processing/chunker.py
-
curl -L -o chunker.py https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/document_processing/chunker.py
4.7 kB
| """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 | |