Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/stage-3.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
1 change: 1 addition & 0 deletions src/swellsense/processing/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Turn raw ingested pages into sections and chunks for retrieval."""
77 changes: 77 additions & 0 deletions src/swellsense/processing/clean.py
Original file line number Diff line number Diff line change
@@ -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
89 changes: 89 additions & 0 deletions tests/test_clean.py
Original file line number Diff line number Diff line change
@@ -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."),
]
Loading