From 831fbadabeb44aebae1af140fc21727b7945cb75 Mon Sep 17 00:00:00 2001 From: Zane Date: Wed, 28 Oct 2026 15:42:27 +1300 Subject: [PATCH] Add MediaWiki section cleaning for stage 3 slice 1. Split plain text on heading lines, drop boilerplate sections, and normalise whitespace so slice 2 can chunk citation-ready bodies. Co-authored-by: Cursor --- AGENTS.md | 1 + docs/plans/stage-3.md | 2 +- src/swellsense/processing/__init__.py | 1 + src/swellsense/processing/clean.py | 77 +++++++++++++++++++++++ tests/test_clean.py | 89 +++++++++++++++++++++++++++ 5 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 src/swellsense/processing/__init__.py create mode 100644 src/swellsense/processing/clean.py create mode 100644 tests/test_clean.py diff --git a/AGENTS.md b/AGENTS.md index 52b5425..d5b6a84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,6 +56,7 @@ code, with short docstrings explaining why. - `src/swellsense/llm/`: the only code that talks to the LLM API - `src/swellsense/extraction/`: structured extraction (boards, unit parsing) - `src/swellsense/ingest/`: source registry, fetchers, raw document storage, ingest runs +- `src/swellsense/processing/`: cleaning and chunking raw documents - `src/swellsense/spots/`: spot profiles and the registry that loads them - `src/swellsense/tides/`: LINZ Tauranga predictions and tide state at a time - `src/swellsense/forecast/`: Open-Meteo swell and wind for one spot diff --git a/docs/plans/stage-3.md b/docs/plans/stage-3.md index 6f3d00d..2b30edb 100644 --- a/docs/plans/stage-3.md +++ b/docs/plans/stage-3.md @@ -10,7 +10,7 @@ ## Progress (tick each box in the slice's own PR) -- [ ] Slice 1: Clean raw pages into sections +- [x] Slice 1: Clean raw pages into sections - [ ] Slice 2: Chunk a document with its citation metadata - [ ] Slice 3: Embedding function in `swellsense.llm` - [ ] Slice 4: Local Postgres, schema and `swellsense db init` diff --git a/src/swellsense/processing/__init__.py b/src/swellsense/processing/__init__.py new file mode 100644 index 0000000..0502533 --- /dev/null +++ b/src/swellsense/processing/__init__.py @@ -0,0 +1 @@ +"""Turn raw ingested pages into sections and chunks for retrieval.""" diff --git a/src/swellsense/processing/clean.py b/src/swellsense/processing/clean.py new file mode 100644 index 0000000..446af24 --- /dev/null +++ b/src/swellsense/processing/clean.py @@ -0,0 +1,77 @@ +"""Split MediaWiki plain text into content sections for chunking.""" + +from __future__ import annotations + +import re + +from pydantic import BaseModel + +# MediaWiki marks section levels with matching = runs on both sides. +_HEADING_RE = re.compile(r"^\s*(=+)\s*(.*?)\s*\1\s*$") + +# Boilerplate sections are dropped so chunks stay on surf-relevant prose. +_DROPPED_HEADINGS = frozenset( + { + "references", + "see also", + "external links", + "further reading", + "notes", + "bibliography", + } +) + + +class Section(BaseModel): + """One heading and its body after whitespace normalisation.""" + + heading: str + text: str + + +def _normalize_section_text(text: str) -> str: + """Strip line endings, collapse extra blank lines, trim the block.""" + lines = [line.rstrip() for line in text.splitlines()] + collapsed: list[str] = [] + blank_run = 0 + for line in lines: + if line == "": + blank_run += 1 + if blank_run == 1: + collapsed.append("") + else: + blank_run = 0 + collapsed.append(line) + return "\n".join(collapsed).strip() + + +def _drop_heading(heading: str) -> bool: + return heading.strip().casefold() in _DROPPED_HEADINGS + + +def clean_sections(text: str) -> list[Section]: + """Split plain MediaWiki text into sections, dropping boilerplate blocks.""" + if text == "": + return [] + + sections: list[Section] = [] + current_heading = "" + body_lines: list[str] = [] + + def flush() -> None: + nonlocal body_lines + body = _normalize_section_text("\n".join(body_lines)) + if not _drop_heading(current_heading) and body: + sections.append(Section(heading=current_heading, text=body)) + body_lines = [] + + for line in text.splitlines(): + match = _HEADING_RE.match(line) + if match: + flush() + current_heading = match.group(2).strip() + else: + body_lines.append(line) + + flush() + return sections diff --git a/tests/test_clean.py b/tests/test_clean.py new file mode 100644 index 0000000..0fee1c9 --- /dev/null +++ b/tests/test_clean.py @@ -0,0 +1,89 @@ +import pytest + +from swellsense.processing.clean import Section, clean_sections + + +def test_empty_input_returns_no_sections(): + assert clean_sections("") == [] + + +def test_no_headings_is_single_lead_section(): + text = "Opening paragraph only." + assert clean_sections(text) == [Section(heading="", text="Opening paragraph only.")] + + +def test_lead_section_before_first_heading(): + text = "Lead line.\n\n== First ==\nFirst body." + assert clean_sections(text) == [ + Section(heading="", text="Lead line."), + Section(heading="First", text="First body."), + ] + + +def test_lead_section_heading_is_empty_string(): + text = "Only lead." + result = clean_sections(text) + assert len(result) == 1 + assert result[0].heading == "" + + +def test_nested_headings_levels_two_three_four(): + text = ( + "Lead.\n" + "== Level two ==\n" + "Two body.\n" + "=== Level three ===\n" + "Three body.\n" + "==== Level four ====\n" + "Four body." + ) + assert clean_sections(text) == [ + Section(heading="", text="Lead."), + Section(heading="Level two", text="Two body."), + Section(heading="Level three", text="Three body."), + Section(heading="Level four", text="Four body."), + ] + + +@pytest.mark.parametrize( + "heading", + [ + "References", + "SEE ALSO", + " external links ", + "Further Reading", + "NOTES", + "bibliography", + ], +) +def test_dropped_boilerplate_headings_are_removed(heading: str): + text = ( + f"== Intro ==\nKeep this.\n== {heading} ==\nDrop this.\n== After ==\nKeep too." + ) + assert clean_sections(text) == [ + Section(heading="Intro", text="Keep this."), + Section(heading="After", text="Keep too."), + ] + + +def test_empty_section_after_normalisation_is_dropped(): + text = "== Intro ==\nText.\n== Empty ==\n \n\n \n== Next ==\nMore." + assert clean_sections(text) == [ + Section(heading="Intro", text="Text."), + Section(heading="Next", text="More."), + ] + + +def test_nested_heading_under_dropped_section_is_kept(): + text = "== References ==\nRef list.\n=== Detail ===\nStill useful." + assert clean_sections(text) == [ + Section(heading="Detail", text="Still useful."), + ] + + +def test_whitespace_normalisation(): + text = "Line one. \n\n\n\nLine two. \n== Section ==\nBody. " + assert clean_sections(text) == [ + Section(heading="", text="Line one.\n\nLine two."), + Section(heading="Section", text="Body."), + ]