Answer the family search contract; strip control characters from act texts

- dredd-core v0.17.0. Every /search answer carries the contract's
  version/q/hits/truncated beside Insider's own keys (services/search_v1);
  format=v1 applies the contract's limit default and 2-character minimum
  and asks the fast sources only. Hit links are the console's own routes.
- PDF hyphenation left U+0002 inside words (art. 483 k.c.). The DzU
  splitters strip C0 controls (tab/newline/CR kept); 0013 cleans the 226
  articles already stored.

Requested by Tobiasz under Alpaq92/Atrium#17.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 15:21:44 +01:00
co-authored by Claude Opus 5.5
parent be56dba0ff
commit 5bee0990bc
10 changed files with 151 additions and 8 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ permissive (no copyleft).
The core is pinned by tag in `backend/requirements.txt`:
```
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.15.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.17.0
```
It is a **private** repository, so installing it needs a token — see `README.md` for the
+1 -1
View File
@@ -618,7 +618,7 @@ writer, the security primitives, the shared enums and error types, and the engin
factories all come from one installed package. `backend/requirements.txt` pins it by tag:
```
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.15.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.17.0
```
The app-side files that used to hold that code (`services/auth.py`, `models/__init__.py`,
@@ -0,0 +1,29 @@
"""Control characters out of the stored act texts (`dzu_md.strip_controls`).
A PDF's hyphenation reached some articles as U+0002 where a word broke over a line ("wykona" U+0002
"nia", art. 483 k.c.), which breaks a verbatim quote. The importer now strips C0 controls (tab,
newline and CR kept) and DEL before an act is split; this cleans the rows stored before it — 226
articles in 7 acts on the box (2026-10-28). EU parts, judgments and fetched texts had none.
Idempotent by construction: the WHERE matches nothing once it has run. No schema change, so no
runtime grants to re-apply.
"""
from __future__ import annotations
from alembic import op
revision = "0013"
down_revision = "0012"
branch_labels = None
depends_on = None
_CONTROLS = r"[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]"
def upgrade() -> None:
op.execute(f"UPDATE dzu_article SET text = regexp_replace(text, '{_CONTROLS}', '', 'g') "
f"WHERE text ~ '{_CONTROLS}'")
def downgrade() -> None:
pass # the removed characters were noise, never content
+16 -2
View File
@@ -128,8 +128,20 @@ class Article:
text: str # the chunk of Markdown, heading included
#: C0 control characters (tab, newline and CR kept) and DEL. A PDF's hyphenation reaches the text
#: as U+0002 where a word broke over a line (art. 483 k.c.; 7 acts, 226 articles on the box,
#: 2026-10-28): a quoted article must read as the act does, so the word is joined.
CONTROL = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
def strip_controls(text: str) -> str:
return CONTROL.sub("", text)
def split_articles(body: str) -> list[Article]:
"""The body cut at every `##### Art. N.` heading. Joining the texts gives the body back."""
"""The body cut at every `##### Art. N.` heading. Joining the texts gives the body back,
control characters removed (`strip_controls`)."""
body = strip_controls(body)
out: list[Article] = []
marks = list(_ART.finditer(body))
head = body[: marks[0].start()] if marks else body
@@ -148,7 +160,9 @@ _PLAIN_ART = re.compile(r"^Art\.\s*(\d+[a-z]{0,4}(?:[¹²³⁰-⁹]+[a-z]?)?)\."
def split_plain_articles(text: str) -> list[Article]:
"""Plain consolidated text cut before every article heading (ord = position, like Markdown)."""
"""Plain consolidated text cut before every article heading (ord = position, like Markdown),
control characters removed (`strip_controls`)."""
text = strip_controls(text)
out: list[Article] = []
marks = list(_PLAIN_ART.finditer(text))
head = text[: marks[0].start()] if marks else text
+14 -2
View File
@@ -9,12 +9,14 @@ from __future__ import annotations
import datetime as dt
from typing import Literal
from dredd_core import search_contract as sc
from fastapi import APIRouter, Depends, Path, Query
from ..deps import get_current_user
from ..integrations.base import Query as LegalQuery
from ..integrations.eurlex import CELEX_PATTERN # one allow-list: the route and valid_celex
from ..models import AppUser
from ..services import search_v1
from ..services.legal import Legal
from ..services.runtime import get_legal
@@ -42,21 +44,31 @@ async def search(
publisher: Literal["DU", "MP", "EU"] | None = Query(
None, description="Acts only: Dz.U. (DU), M.P. (MP) or the EU Official Journal (EU)."),
cursor: str | None = Query(None, max_length=2000),
limit: int = Query(20, ge=1, le=50),
limit: int | None = Query(None, ge=1, le=50, description="Default 20 (10 with format=v1)."),
progressive: bool = Query(False, description=(
"Answer with the fast sources at once; each slow source (SAOS, 22–30 s) is listed in "
"`pending` with a ticket for GET /search/pending.")),
fmt: Literal["v1"] | None = Query(None, alias="format", description=(
"v1 = the family's search contract (`version`, `q`, `hits`, `truncated` — on every "
"answer): its limit default, its 2-character minimum, and the fast sources only.")),
user: AppUser = Depends(get_current_user),
legal: Legal = Depends(get_legal),
) -> dict:
if fmt == "v1":
q = sc.normalize_query(q)
if not sc.is_searchable(q) and not (case_number or citation):
return sc.empty_response(q)
progressive = True
limit = limit or (sc.DEFAULT_LIMIT if fmt == "v1" else 20)
query = LegalQuery(q=q.strip(), kind=kind, jurisdiction=jurisdiction,
date_from=_iso(date_from), date_to=_iso(date_to),
court=(court or "").strip() or None,
case_number=(case_number or "").strip() or None, in_force=in_force,
publisher=publisher)
return await legal.search(query, limit=limit, cursor=cursor, citation=citation,
body = await legal.search(query, limit=limit, cursor=cursor, citation=citation,
progressive=progressive, user=str(user.id),
**await _ai(user, "ai_query_rewrite", "rewrite"))
return {**body, **search_v1.contract(body, query.q, limit)}
async def _ai(user: AppUser, flag: str, arg: str | None = None) -> dict:
+63
View File
@@ -0,0 +1,63 @@
"""The family's search contract (`dredd_core.search_contract`) on top of Insider's own search.
Atrium's Home, palette and chat ask every module `GET api/v1/search?q=&limit=&format=v1` and read
`{version, q, hits, truncated}`. Insider's own body has no `hits` key, so the contract keys ride
along on EVERY answer (the contract's rule for such a module); `format=v1` only changes how the
request is read — the contract's limit default, its 2-character minimum, and the fast sources only
(`progressive`), because Home asks while someone types and SAOS live takes 22-30 s. The local
indexes answer judgments and acts fast once they are built.
A hit's `link` is the console's own route (`frontend/app.js` `docRoute` / `routeHash`, without
`#/`): a document whose id names no route is dropped, never linked to nowhere. Acts and judgments
are interleaved, each list in Insider's own ranking order.
"""
from __future__ import annotations
from itertools import chain, zip_longest
from urllib.parse import quote
from dredd_core import search_contract as sc
KIND_LABEL = {"act": "Akt prawny", "judgment": "Orzeczenie"}
def route(doc: dict) -> list[str] | None:
"""The console route of a result (`docRoute` in `frontend/app.js` — keep the two in step)."""
src, _, native = str(doc.get("id") or "").partition(":")
if not native:
return None
if src in ("eli", "dzu_md"):
return ["act", *native.split("/")]
if src == "eurlex":
return ["judgment", "eurlex", native] if doc.get("kind") == "judgment" else ["eu", native]
if src == "saos":
return ["judgment", "saos", native]
return None
def link(doc: dict) -> str | None:
r = route(doc)
return "doc/" + "/".join(quote(p, safe="") for p in r) if r else None
def hit(doc: dict) -> sc.SearchHit | None:
to = link(doc)
title = (doc.get("title") or doc.get("signature") or "").strip()
if not to or not title:
return None
kind = doc.get("kind") if doc.get("kind") in KIND_LABEL else "act"
sub = " · ".join(str(x) for x in (doc.get("signature"), doc.get("court_or_publisher"),
doc.get("date")) if x)
return sc.make_hit(kind=kind, kind_label=KIND_LABEL[kind], title=title, subtitle=sub,
link=to, id=doc["id"])
def contract(body: dict, q: str, limit: int) -> dict:
"""The contract's keys for one legacy search body: `{version, q, hits, truncated}`."""
docs = [d for d in chain.from_iterable(zip_longest(body.get("acts") or [],
body.get("judgments") or []))
if d is not None]
hits = [h for h in map(hit, docs) if h is not None]
out = sc.make_response(q, hits, limit)
out["truncated"] = out["truncated"] or bool(body.get("next_cursor"))
return out
+1 -1
View File
@@ -25,7 +25,7 @@
# The repo is PRIVATE, so pip needs credentials to fetch it:
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.15.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.17.0
# Web framework
fastapi==0.161.0
+16
View File
@@ -94,6 +94,22 @@ class TestRest:
assert item["official_url"].startswith("https://") and item["source"]
assert len(item["snippet"]) <= 300
def test_search_answers_the_family_contract(self, api):
from dredd_core import search_contract as sc
body = api.get("/api/v1/search", params={"q": "bank", "limit": 5}).json()
sc.validate_response(body, limit=5) # on every answer, legacy keys beside it
assert body["acts"] and body["hits"]
v1 = api.get("/api/v1/search", params={"q": " bank ", "format": "v1"}).json()
sc.validate_response(v1, limit=sc.DEFAULT_LIMIT)
assert v1["q"] == "bank" and {h["kind"] for h in v1["hits"]} <= {"act", "judgment"}
assert all(h["link"].startswith("doc/") for h in v1["hits"])
# the console's own routes (`docRoute` in frontend/app.js), interleaved act, judgment, act
assert [(h["id"], h["link"]) for h in body["hits"]] == [
("eurlex:32016R0679", "doc/eu/32016R0679"), ("saos:554187", "doc/judgment/saos/554187"),
("eli:DU/1997/939", "doc/act/DU/1997/939")]
short = api.get("/api/v1/search", params={"q": "b", "format": "v1"})
assert short.status_code == 200 and short.json() == sc.empty_response("b")
def test_search_by_citation(self, api):
r = api.get("/api/v1/search", params={"citation": "Dz. U. z 1997 r. Nr 140, poz. 939"})
body = r.json()
+8
View File
@@ -195,6 +195,14 @@ class TestDzuParsing:
assert dzu.display_title(KP) == "Ustawa - Kodeks pracy (tekst jednolity)"
assert dzu.display_title("Ustawa o czymś") == "Ustawa o czymś"
def test_a_pdf_hyphenation_control_is_joined(self):
# U+0002 where a word broke over a line in the PDF (art. 483 k.c. on the box)
plain = dzu.split_plain_articles("Art. 483. § 1. Można zastrzec, że naprawienie szkody "
"wynikłej z niewykona\x02nia zobowiązania\x07.\n")
md = dzu.split_articles("##### Art. 483.\n\nniewykona\x02nia\tzobowiązania\n")
assert "niewykonania zobowiązania." in plain[0].text
assert md[0].text == "##### Art. 483.\n\nniewykonania\tzobowiązania\n" # tab, newline kept
class TestSaosParsing:
def page(self, n=2, nxt=True, host="https://www.saos.org.pl/api/dump/judgments"):
+2 -1
View File
@@ -32,7 +32,8 @@ SEARCHES = [
]
IDS = [f"{q}|{p.get('kind', 'all')}|{p.get('jurisdiction', 'all')}" for q, p in SEARCHES]
TOP_KEYS = {"acts", "judgments", "sources", "notices", "pending", "next_cursor", "query",
"rank_prior", "filter_scope"}
"rank_prior", "filter_scope",
"version", "q", "hits", "truncated"} # the family search contract
ITEM_KEYS = {"id", "source", "kind", "title", "official_url", "attribution", "snippet", "extra"}
SOURCE_KEYS = {"name", "status"}
LIVE = {"eli", "saos", "eurlex"}