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
6 changes: 4 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +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/processing/`: cleaning, chunking, and the process run
- `src/swellsense/db/`: local Postgres connection and schema
- `src/swellsense/spots/`: spot profiles and the registry that loads them
- `src/swellsense/tides/`: LINZ Tauranga predictions and tide state at a time
Expand All @@ -76,6 +76,7 @@ code, with short docstrings explaining why.
- Verify changes: `bash scripts/check.sh` (lint, format check, then tests; stops at the first failure)
- Apply lint and format fixes: `uv run ruff check --fix && uv run ruff format`
- Download sources: `uv run swellsense ingest` (or `--source ID` for one)
- Process raw pages: `uv run swellsense process` (reads `data/raw/`, embeds via the configured provider, upserts into local Postgres)
- Tauranga tides: `uv run swellsense tides` (or `--date YYYY-MM-DD`)
- Spot forecast: `uv run swellsense forecast SPOT` (or `--hours N`, default 12)
- Conditions check: `uv run swellsense check SPOT` (or `--hours N`, default 12); `uv run swellsense check --all` ranks every spot, with ties shown as ties; `--skill LEVEL` lists harder spots separately
Expand All @@ -85,7 +86,7 @@ code, with short docstrings explaining why.
## Roadmap
1. [x] Foundations: provider-agnostic LLM client, structured extraction
2. [x] Knowledge ingestion: source registry, fetching, raw storage
3. [ ] Processing: cleaning, chunking, local embeddings, Postgres + pgvector (in progress)
3. [x] Processing: cleaning, chunking, local embeddings, Postgres + pgvector
4. [ ] Grounded chat: retrieval with citations
5. [ ] Live conditions: forecast, tides, classifiers, an explainable conditions check and a ranking are in. The chatbot answers a spot check or "where should I go" from those tools. Other answers are not grounded in sources yet.
6. [ ] Spots and maps: spot data and profiles, "where to surf" recommendations
Expand Down Expand Up @@ -118,4 +119,5 @@ Work on the current roadmap stage unless asked otherwise. Don't build ahead.
- Use `uv` for Python 3.13 (`.python-version`). The image's system Python may be older; `uv sync --locked` installs the pinned interpreter.
- Checks: `bash scripts/check.sh`. Tests must not call the network or the LLM.
- There is no dev server. `uv run swellsense ingest` downloads every source into `data/raw/` and writes `data/raw/_last_run.json`. `uv run swellsense ingest --source ID` downloads one source. `uv run swellsense tides` prints Tauranga high and low waters for today and caches the LINZ CSV under `data/cache/`. `uv run swellsense forecast SPOT` prints an Open-Meteo swell and wind table and caches it under `data/cache/forecast/` for one hour. `uv run swellsense check SPOT` rates the next 12 hours and `uv run swellsense check --all` ranks every spot (ties share a rank; `--skill LEVEL` lists harder spots as above your level); both use those caches. Loading `data/sources.yaml` with `swellsense.ingest.registry.load_sources` and parsing board dimensions with `swellsense.extraction.units.parse_dimension` exercises the current product path.
- `uv run swellsense process` reads `data/raw/`, embeds via the configured provider, and upserts into local Postgres (same Ollama embeddings endpoint as the LLM). Postgres is not started in Cloud; tests mock the database and embedder.
- `uv run python -m swellsense.chatbot` expects a local OpenAI-compatible server (default `http://localhost:11434/v1`, see `.env.example`). The environment does not start that server. A conditions question also fetches the Open-Meteo forecast and LINZ tides; tests mock both.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Early development. What works today:

- **Terminal chat** with a local model through Ollama. Conditions questions ("is it worth surfing?", "where should I go?") are answered from the conditions check. The model chooses the tool and phrases the result; the score is computed in code. Other answers are not grounded in sources yet, so treat those with caution.
- **Knowledge ingestion**: downloads surf knowledge from Wikipedia into local storage, keeping the source URL, license and attribution on every document.
- **Processing**: cleans and chunks ingested pages, embeds new or changed chunks via the configured provider, and stores them in local Postgres for retrieval.
- **Tauranga tides**: prints LINZ high and low waters for a day, with the required acknowledgement.
- **Spot forecast**: hourly swell, wind waves and wind for a Bay of Plenty spot, from Open-Meteo.
- **Conditions check**: rates the next few hours at a spot from that forecast, the tide and the spot profile, or ranks every spot by its best hour. Tied scores share a rank, and a skill level leaves harder spots on a separate list.
Expand Down Expand Up @@ -56,6 +57,7 @@ In `.env`, set `HTTP_USER_AGENT` to identify the project to source sites, for ex
| `uv run python -m swellsense.chatbot` | Chat in the terminal (needs Ollama). Conditions questions use the live check |
| `uv run swellsense ingest` | Download all sources into `data/raw/` |
| `uv run swellsense ingest --source wikipedia` | Download a single source |
| `uv run swellsense process` | Clean, chunk and embed `data/raw/` into Postgres |
| `uv run swellsense tides` | Print today's Tauranga highs and lows |
| `uv run swellsense tides --date 2026-01-15` | Print one day's Tauranga tides |
| `uv run swellsense forecast mount-main-beach` | Print 12 hours of swell and wind for a spot |
Expand Down Expand Up @@ -84,7 +86,7 @@ src/swellsense/
llm/ the only code that talks to the LLM
extraction/ structured extraction (board specs, unit parsing)
ingest/ source registry, fetchers, storage, ingest runs
processing/ cleaning and chunking raw documents
processing/ cleaning, chunking, and the process run
db/ local Postgres connection and schema
spots/ spot profiles
tides/ LINZ tide predictions and tide state
Expand All @@ -102,7 +104,7 @@ scripts/check.sh the single check command

- [x] Foundations: provider-agnostic LLM client, structured extraction
- [x] Knowledge ingestion: source registry, fetching, raw storage
- [ ] Processing: cleaning, chunking, embeddings, Postgres with pgvector
- [x] Processing: cleaning, chunking, embeddings, Postgres with pgvector
- [ ] Grounded chat: retrieval with citations
- [ ] Live conditions: forecast, tides, classifiers, an explainable conditions check and a ranking are in. The chatbot answers a spot check or "where should I go" from those tools. Other answers are not grounded in sources yet.
- [ ] Spots and maps: spot profiles and "where to surf" recommendations
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 @@ -16,7 +16,7 @@
- [x] Slice 4: Local Postgres, schema and `swellsense db init`
- [x] Slice 7: Postgres service container in CI
- [x] Slice 5: Chunk store (upsert, prune, nearest)
- [ ] Slice 6: `swellsense process` end to end
- [x] Slice 6: `swellsense process` end to end

Slices are run one at a time, in the order above.

Expand Down
43 changes: 43 additions & 0 deletions src/swellsense/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
``check`` rates a spot, or ranks every spot by its best hour. Ties share a
rank. ``--skill`` keeps harder spots in a separate list.
``db init`` creates the local Postgres schema (pgvector, documents, chunks).
``process`` cleans, chunks and embeds raw pages into Postgres.
"""

import argparse
import sys
from datetime import date, datetime, timedelta

import httpx
import openai
import psycopg

from swellsense.conditions.rating import HourRating
Expand All @@ -28,6 +30,9 @@
from swellsense.ingest.fetchers.mediawiki import make_client
from swellsense.ingest.registry import load_sources
from swellsense.ingest.run import SourceReport, ingest
from swellsense.ingest.store import load_all
from swellsense.llm.embeddings import embed
from swellsense.processing.run import PostgresChunkStore, ProcessReport, process
from swellsense.spots.models import Spot
from swellsense.spots.registry import get_spot, load_spots
from swellsense.tides.linz import (
Expand Down Expand Up @@ -55,6 +60,11 @@ def _main(argv: list[str] | None = None) -> int:
"--source", metavar="ID", help="Download only this source"
)

subparsers.add_parser(
"process",
help="Clean, chunk and embed data/raw into Postgres",
)

tides_parser = subparsers.add_parser(
"tides", help="Print Tauranga high and low waters for one day"
)
Expand Down Expand Up @@ -114,6 +124,8 @@ def _main(argv: list[str] | None = None) -> int:
args = parser.parse_args(argv)
if args.command == "ingest":
return _ingest(args.source)
if args.command == "process":
return _process()
if args.command == "tides":
return _tides(args.date)
if args.command == "forecast":
Expand All @@ -140,6 +152,29 @@ def _db_init() -> int:
return 0


def _process() -> int:
try:
docs = load_all()
conn = connect()
try:
report = process(
docs,
lambda texts: embed(texts, "document"),
PostgresChunkStore(conn),
)
conn.commit()
finally:
conn.close()
except (psycopg.Error, openai.APIError) as exc:
print(str(exc), file=sys.stderr)
return 1

print(_process_summary(report))
if report.failed:
return 1
return 0


def _ingest(source_id: str | None) -> int:
sources = load_sources()
if source_id is not None:
Expand Down Expand Up @@ -439,6 +474,14 @@ def _print_tides(day: date, events: list[TideEvent]) -> None:
print(LINZ_ATTRIBUTION)


def _process_summary(report: ProcessReport) -> str:
return (
f"process: {report.documents} documents, {report.embedded} embedded, "
f"{report.unchanged} unchanged, {report.removed} removed, "
f"{len(report.failed)} failed"
)


def _summary(source_id: str, report: SourceReport) -> str:
line = (
f"{source_id}: {report.saved} saved, {report.unchanged} unchanged, "
Expand Down
135 changes: 135 additions & 0 deletions src/swellsense/processing/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""Clean, chunk, embed and store raw documents.

One bad document is recorded and the rest still process, mirroring ingest runs.
"""

from __future__ import annotations

from collections.abc import Callable
from typing import Protocol

import openai
import psycopg
from pydantic import BaseModel, Field

from swellsense.config import get_settings
from swellsense.ingest.models import RawDocument
from swellsense.processing.chunk import chunk_document
from swellsense.processing.models import Chunk


class ChunkStore(Protocol):
"""Persistence for documents and chunk rows; no commit (caller's job)."""

def upsert_document(self, doc: RawDocument) -> None: ...

def existing_hashes(self, document_id: str) -> dict[str, tuple[str, str]]: ...

def upsert_chunks(
self, chunks: list[Chunk], embeddings: list[list[float]], model: str
) -> None: ...

def delete_chunks_except(self, document_id: str, keep_ids: list[str]) -> None: ...


class ProcessReport(BaseModel):
"""Counts from one process run over a set of raw documents."""

documents: int
embedded: int = 0
unchanged: int = 0
removed: int = 0
failed: list[dict[str, str]] = Field(default_factory=list)


class PostgresChunkStore:
"""Forwards chunk store operations to ``swellsense.db.chunks``."""

def __init__(self, conn: psycopg.Connection) -> None:
self._conn = conn

def upsert_document(self, doc: RawDocument) -> None:
from swellsense.db.chunks import upsert_document

upsert_document(self._conn, doc)

def existing_hashes(self, document_id: str) -> dict[str, tuple[str, str]]:
from swellsense.db.chunks import existing_hashes

return existing_hashes(self._conn, document_id)

def upsert_chunks(
self, chunks: list[Chunk], embeddings: list[list[float]], model: str
) -> None:
from swellsense.db.chunks import upsert_chunks

upsert_chunks(self._conn, chunks, embeddings, model)

def delete_chunks_except(self, document_id: str, keep_ids: list[str]) -> None:
from swellsense.db.chunks import delete_chunks_except

delete_chunks_except(self._conn, document_id, keep_ids)


def process(
docs: list[RawDocument],
embed_fn: Callable[[list[str]], list[list[float]]],
store: ChunkStore,
) -> ProcessReport:
"""Chunk each document, embed only new or changed chunks, upsert and prune."""
settings = get_settings()
report = ProcessReport(documents=len(docs))

for doc in docs:
try:
embedded, unchanged, removed = _process_document(
doc,
embed_fn,
store,
settings.chunk_words,
settings.chunk_overlap_words,
settings.embedding_model,
)
except (openai.APIError, psycopg.Error):
raise
except Exception as exc: # noqa: BLE001
report.failed.append({"id": doc.id, "error": str(exc)})
continue
report.embedded += embedded
report.unchanged += unchanged
report.removed += removed

return report


def _process_document(
doc: RawDocument,
embed_fn: Callable[[list[str]], list[list[float]]],
store: ChunkStore,
chunk_words: int,
chunk_overlap_words: int,
embedding_model: str,
) -> tuple[int, int, int]:
chunks = chunk_document(doc, chunk_words, chunk_overlap_words)
store.upsert_document(doc)
existing = store.existing_hashes(doc.id)
keep_ids = {chunk.id for chunk in chunks}

to_embed: list[Chunk] = []
for chunk in chunks:
prior = existing.get(chunk.id)
if prior == (chunk.content_hash, embedding_model):
continue
to_embed.append(chunk)

unchanged = len(chunks) - len(to_embed)
embedded = 0
if to_embed:
texts = [chunk.text for chunk in to_embed]
embeddings = embed_fn(texts)
store.upsert_chunks(to_embed, embeddings, embedding_model)
embedded = len(to_embed)

removed = sum(1 for chunk_id in existing if chunk_id not in keep_ids)
store.delete_chunks_except(doc.id, [chunk.id for chunk in chunks])
return embedded, unchanged, removed
Loading
Loading