mirror of
https://github.com/Stirling-Tools/Stirling-PDF.git
synced 2026-09-03 05:10:16 +03:00
## Overview Adds **AI document classification** and a **classification-aware Files sidebar**: uploaded documents are automatically tagged with document-type labels (Invoice, Contract, Lab report, …), and the sidebar groups files under editable parent categories so a large library stays navigable. > [!IMPORTANT] > **This feature only runs in the SaaS build.** Classification depends on the AI engine and team-scoped label storage, so it's gated to SaaS end-to-end: > - The sidebar grouping is a `saas/`-layer override of the `fileSidebarGrouping` seam; every other build (OSS core, self-hosted proprietary, desktop) gets the null stub and renders the **unchanged flat, recency-sorted list** — no categories, no "Other", no picker. > - The classify/labels backend endpoints are gated on `policies.enabled` (on in SaaS) and live in `app/proprietary`, so they're absent from pure OSS and dormant in self-hosted unless explicitly enabled. > - The Python classifier is reached only via that gated path. > > Shared-layer changes that do compile everywhere are inert without the engine (dormant schema/field additions) or intentional (`GetInfoOnPDF` surfacing custom metadata). ## What it does - **Classifier (engine):** reads the first/last two pages of a PDF and assigns document-type labels from an allowed vocabulary. Labels are deliberately document-*type* descriptors — no deep-content/PII detection, since only a page window is read. - **Team label vocabulary:** ~270 built-in defaults across ~15 families, seeded per team. Editable by team leaders/admins in the Classification policy settings (import/export/reset). Team-scoped and shared; **per-user personal labels are intentionally out of scope** — the vocabulary is team-level only. - **Sidebar categories:** files group under parent categories (Financial, Legal, Medical, …), busiest-first, collapsible, with a "Recent" group on top and an "Other" group for anything uncategorised. The category structure (names, icons, membership, custom categories) is **device-local and user-editable** via a "Customize" picker — the only per-user personalization; it never changes the team's label vocabulary. - Classification results are written to PDF metadata (`StirlingPDFClassification`), read back to keep files in their groups without re-parsing. ## Architecture Spans all three layers, mirroring the existing policy/source subsystem conventions: - **`frontend/editor`** — sidebar grouping seam + SaaS override, category manager, labels editor, icon palette, file grouping, tests, `en-US` i18n. - **`app/proprietary` + `app/common` + `app/core`** — `ClassifyLabelController`, team-scoped `ClassificationLabelStore` (Jpa + in-process impls, same shape as `PolicyStore`/`SourceStore`), metadata read/write. - **`engine`** — the document-classifier agent, contracts, routes, tests. ## Screenshots **Files sidebar — grouped by category (SaaS)** ### Loading view <img width="2056" height="1046" alt="Screenshot 2026-07-07 at 5 12 56 PM" src="https://github.com/user-attachments/assets/1d712da5-50ae-4349-b0cd-e62665c3ec0c" /> ### Organized in the sidebar <img width="2056" height="1045" alt="Screenshot 2026-07-07 at 5 14 05 PM" src="https://github.com/user-attachments/assets/3ea4fe21-da51-4cea-bc3a-18ce040d3d05" /> **Customize categories picker** ### Personal settings to change how labels are grouped in an individual users editor <img width="2056" height="1044" alt="Screenshot 2026-07-07 at 5 52 42 PM" src="https://github.com/user-attachments/assets/40be03ce-0f63-4d1e-b58b-cec045d01cb2" /> **Classification labels editor (team settings)** <img width="2056" height="1042" alt="Screenshot 2026-07-07 at 5 53 00 PM" src="https://github.com/user-attachments/assets/337b0739-15c9-4749-9c6b-22e3b20825b8" /> ## Testing - Frontend `task frontend:check` — green (editor + portal tests, typecheck across all flavors, lint, label-drift guard). - Backend `task backend:check` (proprietary) and `:saas:test` — green. - Engine `task engine:check` — green.
150 lines
5.3 KiB
Python
150 lines
5.3 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock
|
|
|
|
import pytest
|
|
|
|
from stirling.agents.document_classifier import (
|
|
MAX_ASSIGNED_LABELS,
|
|
DocumentClassifierAgent,
|
|
_ClassifierOutput,
|
|
render_labels,
|
|
select_window,
|
|
validate_labels,
|
|
)
|
|
from stirling.contracts import (
|
|
ClassifyDocumentRequest,
|
|
DocumentClassificationResponse,
|
|
LabelOption,
|
|
PageText,
|
|
)
|
|
from stirling.services.runtime import AppRuntime
|
|
|
|
|
|
def _page(number: int, text: str = "x") -> PageText:
|
|
return PageText(page_number=number, text=text)
|
|
|
|
|
|
def _slug(name: str) -> str:
|
|
return re.sub(r"^-+|-+$", "", re.sub(r"[^a-z0-9]+", "-", name.lower()))
|
|
|
|
|
|
def _opts(*names: str) -> list[LabelOption]:
|
|
"""Allowed vocabulary from names, with slug ids (mirrors the frontend)."""
|
|
return [LabelOption(id=_slug(name), name=name) for name in names]
|
|
|
|
|
|
# ── select_window ───────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_select_window_returns_short_documents_whole() -> None:
|
|
pages = [_page(1), _page(2), _page(3), _page(4)]
|
|
assert select_window(pages, window=2) == pages
|
|
|
|
|
|
def test_select_window_takes_both_ends_without_overlap() -> None:
|
|
pages = [_page(n) for n in range(1, 6)] # 5 pages
|
|
selected = select_window(pages, window=2)
|
|
assert [p.page_number for p in selected] == [1, 2, 4, 5]
|
|
|
|
|
|
def test_select_window_handles_empty() -> None:
|
|
assert select_window([], window=2) == []
|
|
|
|
|
|
def test_select_window_zero_returns_all() -> None:
|
|
pages = [_page(1), _page(2), _page(3)]
|
|
assert select_window(pages, window=0) == pages
|
|
|
|
|
|
# ── validate_labels ──────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_valid_labels_are_preserved_in_order() -> None:
|
|
# Model answers with names; the result is the matching label ids.
|
|
output = _ClassifierOutput(labels=["Invoice", "Receipt"])
|
|
result = validate_labels(output, _opts("Invoice", "Receipt", "Purchase order"))
|
|
assert isinstance(result, DocumentClassificationResponse)
|
|
assert result.labels == ["invoice", "receipt"]
|
|
|
|
|
|
def test_off_list_labels_are_dropped() -> None:
|
|
output = _ClassifierOutput(labels=["Invoice", "Warp core", "Receipt"])
|
|
result = validate_labels(output, _opts("Invoice", "Receipt"))
|
|
assert result.labels == ["invoice", "receipt"]
|
|
|
|
|
|
def test_matching_is_case_insensitive_and_returns_ids() -> None:
|
|
output = _ClassifierOutput(labels=["invoice", " CREDIT NOTE "])
|
|
result = validate_labels(output, _opts("Invoice", "Credit note"))
|
|
assert result.labels == ["invoice", "credit-note"]
|
|
|
|
|
|
def test_duplicates_collapse_to_first_occurrence() -> None:
|
|
output = _ClassifierOutput(labels=["Invoice", "invoice", "Receipt", "INVOICE"])
|
|
result = validate_labels(output, _opts("Invoice", "Receipt"))
|
|
assert result.labels == ["invoice", "receipt"]
|
|
|
|
|
|
def test_result_is_capped_at_max_assigned_labels() -> None:
|
|
allowed = _opts(*[f"Label {n}" for n in range(10)])
|
|
output = _ClassifierOutput(labels=[label.name for label in allowed])
|
|
result = validate_labels(output, allowed)
|
|
assert result.labels == [label.id for label in allowed[:MAX_ASSIGNED_LABELS]]
|
|
|
|
|
|
def test_empty_answer_is_valid() -> None:
|
|
result = validate_labels(_ClassifierOutput(labels=[]), _opts("Invoice"))
|
|
assert result.labels == []
|
|
|
|
|
|
def test_entirely_off_list_answer_yields_empty_result() -> None:
|
|
output = _ClassifierOutput(labels=["Spaceship", "Boarding pass"])
|
|
result = validate_labels(output, _opts("Invoice", "Receipt"))
|
|
assert result.labels == []
|
|
|
|
|
|
# ── render_labels ────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_render_labels_lists_the_vocabulary_names() -> None:
|
|
rendered = render_labels(_opts("Invoice", "Receipt"))
|
|
assert "Invoice" in rendered
|
|
assert "Receipt" in rendered
|
|
|
|
|
|
def test_render_labels_handles_empty_vocabulary() -> None:
|
|
assert "(none)" in render_labels([])
|
|
|
|
|
|
# ── DocumentClassifierAgent (inline page text) ───────────────────────────────
|
|
|
|
|
|
def _stub_model_answer(agent: DocumentClassifierAgent, labels: list[str]) -> AsyncMock:
|
|
mock = AsyncMock(return_value=SimpleNamespace(output=_ClassifierOutput(labels=labels)))
|
|
agent._agent.run = mock
|
|
return mock
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_classify_respects_request_supplied_vocabulary(runtime: AppRuntime) -> None:
|
|
agent = DocumentClassifierAgent(runtime)
|
|
run_mock = _stub_model_answer(agent, ["board minutes", "Invoice"])
|
|
|
|
result = await agent.classify(
|
|
ClassifyDocumentRequest(
|
|
file_name="minutes.pdf",
|
|
pages=[PageText(page_number=1, text="Minutes of the board meeting")],
|
|
labels=_opts("Board minutes", "Agenda"),
|
|
)
|
|
)
|
|
|
|
# "Invoice" is off this request's vocabulary even though the default knows it.
|
|
assert result.labels == ["board-minutes"]
|
|
assert run_mock.await_args is not None
|
|
prompt = run_mock.await_args.args[0]
|
|
assert "Board minutes" in prompt
|
|
assert "Agenda" in prompt
|