Compare commits
31
Commits
dated-act-case
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61c5d71d2c | ||
|
|
127e3a857e | ||
|
|
4853393865 | ||
|
|
086f45f48c | ||
|
|
3869992257 | ||
|
|
bb7c540259 | ||
|
|
c577b77de3 | ||
|
|
3039f1675c | ||
|
|
2d50403423 | ||
|
|
ed8a65ead5 | ||
|
|
c66216044a | ||
|
|
3f64fad643 | ||
|
|
ade4181d4a | ||
|
|
140ab3e5b9 | ||
|
|
811e24e46b | ||
|
|
d3c6d70561 | ||
|
|
87ff4b4290 | ||
|
|
495adbd6cc | ||
|
|
dcfb6c94de | ||
|
|
122432543f | ||
|
|
eccc067449 | ||
|
|
cee9c54c75 | ||
|
|
ef34fda6d9 | ||
|
|
16225b7f19 | ||
|
|
02ee3b7bef | ||
|
|
0a09650d2c | ||
|
|
1f517ec924 | ||
|
|
5bee0990bc | ||
|
|
be56dba0ff | ||
|
|
8daa937ec4 | ||
|
|
316f78c62e |
+16
-27
@@ -1,5 +1,20 @@
|
||||
name: CI
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
# main only: a branch is tested through its pull request (a push of many branches at once
|
||||
# must not flood the runners)
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch: # manual run: Actions -> CI -> Run workflow
|
||||
|
||||
# dredd-core is private on the Haski Gitea, and so is every repository this workflow may fetch.
|
||||
# All git traffic to the Gitea host (pip installing dredd-core from requirements, above all) goes
|
||||
# through the read-only bot haski-reader: its token is the Haski org secret DREDD_CORE_TOKEN,
|
||||
# which Gitea masks in logs. Docker builds get the same token as a BuildKit secret instead.
|
||||
env:
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: url.http://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@77.216.148.202:3000/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: http://77.216.148.202:3000/
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
@@ -45,17 +60,6 @@ jobs:
|
||||
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
SQL
|
||||
- name: Authenticate to dredd-core
|
||||
# dredd-core is a PRIVATE repo, so the `git+https://` requirement cannot be fetched
|
||||
# anonymously — without this step `pip install` fails with a git auth prompt/404.
|
||||
# The rewrite injects the token for that ONE repo URL; every other GitHub URL is untouched,
|
||||
# and the secret stays out of the requirements file and the pip log.
|
||||
# Add the secret under Settings → Secrets and variables → Actions → DREDD_CORE_TOKEN
|
||||
# (a fine-grained PAT with read-only Contents access on Alpaq92/dredd-core).
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -121,11 +125,6 @@ jobs:
|
||||
GRANT USAGE ON SCHEMA public TO app;
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
SQL
|
||||
- name: Authenticate to dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -190,11 +189,6 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Authenticate to dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -385,11 +379,6 @@ jobs:
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Let pip fetch the private dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install the OCR extras
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-ocr.txt pip-licenses==5.0.0
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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`,
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ── build stage: resolve dependencies, including the private one ─────────────
|
||||
# `dredd-core` is a private GitHub repository pinned by tag in requirements.txt, so installing it
|
||||
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
|
||||
# needs two things the runtime image should never have: `git`, and a credential.
|
||||
#
|
||||
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
|
||||
@@ -27,8 +27,8 @@ RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
test -s /run/secrets/dredd_core_token \
|
||||
|| { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
|
||||
GIT_CONFIG_COUNT=1 \
|
||||
GIT_CONFIG_KEY_0="url.https://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@github.com/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# ── runtime stage: no git, no credential, no compiler ────────────────────────
|
||||
|
||||
@@ -16,8 +16,8 @@ RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
test -s /run/secrets/dredd_core_token \
|
||||
|| { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
|
||||
GIT_CONFIG_COUNT=1 \
|
||||
GIT_CONFIG_KEY_0="url.https://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@github.com/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements-ocr.txt
|
||||
|
||||
FROM python:3.12-slim
|
||||
|
||||
@@ -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
|
||||
@@ -369,6 +369,7 @@ class CellarIndexAdapter(LocalAdapter):
|
||||
docs.append(to_doc(d, snippet=snippet, hits=hits))
|
||||
if g.get("partial"): # not every query word is in it: `textindex.search`
|
||||
docs[-1].extra["partial"] = True
|
||||
docs[-1].extra["relevance"] = round(g.get("score") or 0.0, 4) # `federation.merge_ranked`
|
||||
return SearchPage(docs, total, offset + len(groups) >= total)
|
||||
|
||||
async def fetch(self, native_id: str) -> LegalDoc:
|
||||
|
||||
@@ -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
|
||||
@@ -569,6 +583,7 @@ class DzuMdAdapter(LocalAdapter):
|
||||
docs.append(to_doc(act, snippet=snippet, hits=hits))
|
||||
if g.get("partial"): # not every query word is in it: `textindex.search`
|
||||
docs[-1].extra["partial"] = True
|
||||
docs[-1].extra["relevance"] = round(g.get("score") or 0.0, 4) # `federation.merge_ranked`
|
||||
if self.graph_counts:
|
||||
self._with_counts(docs)
|
||||
return SearchPage(docs, total, offset + len(groups) >= total)
|
||||
|
||||
@@ -286,6 +286,7 @@ class SaosIndexAdapter(LocalAdapter):
|
||||
docs.append(to_doc(j, snippet=hits[0]["snippet"] if hits else "", hits=hits))
|
||||
if g.get("partial"): # not every query word is in it: `textindex.search`
|
||||
docs[-1].extra["partial"] = True
|
||||
docs[-1].extra["relevance"] = round(g.get("score") or 0.0, 4) # `federation.merge_ranked`
|
||||
return SearchPage(docs, total, offset + len(groups) >= total)
|
||||
|
||||
async def fetch(self, native_id: str) -> LegalDoc:
|
||||
|
||||
+2
-2
@@ -23,7 +23,7 @@ from .errors import ProblemDetailErrorMiddleware, install_error_handlers
|
||||
from .logging_config import configure_logging
|
||||
from .mcp_server import McpEndpoint, get_session_manager, reset_session_manager
|
||||
from .observability import setup_observability
|
||||
from .routers import admin, auth, graph, health, legal, users
|
||||
from .routers import admin, auth, graph, health, legal, stats, users
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
@@ -182,7 +182,7 @@ if settings.cors_origins_list:
|
||||
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router,
|
||||
legal.router,
|
||||
legal.router, stats.router,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""The family's stats contract (dredd-core 0.23.0 `stats_contract`): Insider's current numbers for
|
||||
Panorama, asked with the acting person's own session. See `services/stats.py`."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core import stats_contract
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import get_current_user
|
||||
from ..models import AppUser
|
||||
from ..services import stats as stats_service
|
||||
|
||||
router = APIRouter(tags=["stats"])
|
||||
|
||||
|
||||
@router.get(stats_contract.PATH)
|
||||
def stats(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return stats_service.module_stats(db, user)
|
||||
@@ -60,9 +60,11 @@ def _identity_is_ours() -> None:
|
||||
|
||||
@router.get("/users", response_model=list[UserOut])
|
||||
def list_users(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""Every signed-in user may list users: the console needs names to render "assigned to"
|
||||
pickers, and an email address inside the instance is not the secret worth hiding here."""
|
||||
_: AppUser = Depends(require_moderator)) -> list[dict]:
|
||||
"""The roster is this module's administration screen, so it takes `require_moderator`. On the
|
||||
platform `list_users` reads the SHARED `app_user`: every account on the platform, including
|
||||
people who may not open this module, with their e-mail and tier. Insider has no "assigned to"
|
||||
picker that would need it for an ordinary user."""
|
||||
# One query for the whole page's tier column, not one per row: `moderator_ids` returns this
|
||||
# module's roster as a set, and standalone it returns an empty set without touching the database.
|
||||
moderators = moderation_service.moderator_ids(db)
|
||||
|
||||
@@ -11,6 +11,7 @@ cursor carrying each source's next offset (`services/cursor.py`).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import time
|
||||
from dataclasses import asdict, dataclass, field
|
||||
|
||||
@@ -77,6 +78,40 @@ def dedup(docs: list[LegalDoc]) -> list[LegalDoc]:
|
||||
return out
|
||||
|
||||
|
||||
#: a query that names EU law: then an EU act is weighed like a Polish one (`merge_ranked`)
|
||||
EU_QUERY = re.compile(r"\b(UE|WE|EWG|EWWiS|Euratom|unijn\w*|dyrektyw\w*|RODO|GDPR|CELEX)\b"
|
||||
r"|\b\d{4}/\d+/(UE|WE)\b|\b[1-9]\d{4}[A-Z]{1,2}\d{4}\b", re.I)
|
||||
#: an EU act's weight against a Polish one for a query that does not name EU law: the EU index
|
||||
#: scores a Polish legal word it barely holds (its IDF) far above the Polish index, so its raw
|
||||
#: score is never compared — and even normalised its best hit is usually a word-form accident
|
||||
EU_WEIGHT = 0.6
|
||||
|
||||
|
||||
def merge_ranked(by_source: dict[str, list[LegalDoc]], q: str) -> list[LegalDoc]:
|
||||
"""The local indexes' hits as ONE relevance order. Each index's scores come from its own
|
||||
corpus statistics, so each is normalised by its own best hit (1.0 = that index's top), then
|
||||
weighted: EU acts by `EU_WEIGHT` unless the query names EU law. A partial match (some query
|
||||
words missing, `textindex.search`) comes after every full one, whatever its score. Ties keep
|
||||
the registry's source order (Polish acts first). An index's OWN order is final — it re-ranks
|
||||
after scoring (the act the query names, the graph) — so a hit never outranks the one before
|
||||
it from the same index; the merge only interleaves. Before this the blocks followed whichever
|
||||
search FINISHED first."""
|
||||
eu = 1.0 if EU_QUERY.search(q or "") else EU_WEIGHT
|
||||
scored = []
|
||||
for s_i, (name, found) in enumerate(by_source.items()):
|
||||
rel = [float(d.extra.get("relevance") or 0.0) for d in found]
|
||||
top = max(rel, default=0.0)
|
||||
cap, partial = float("inf"), False
|
||||
for i, d in enumerate(found):
|
||||
v = rel[i] / top if top > 0 else 1.0 - i / max(1, len(found)) # no scores: its order
|
||||
if d.kind == ACT and d.source == "cellar":
|
||||
v *= eu
|
||||
v = cap = min(v, cap)
|
||||
partial = partial or bool(d.extra.get("partial"))
|
||||
scored.append((partial, -v, s_i, i, d))
|
||||
return [d for *_k, d in sorted(scored, key=lambda t: t[:4])]
|
||||
|
||||
|
||||
def by_date(docs: list[LegalDoc]) -> list[LegalDoc]:
|
||||
return sorted(docs, key=lambda d: (d.date is not None, d.date or ""), reverse=True)
|
||||
|
||||
@@ -213,7 +248,7 @@ async def search(registry, cache: SourceCache, codec: CursorCodec, query: Query,
|
||||
for p in deferred: # optimistic: a page past its end simply comes back empty
|
||||
next_offsets[p["source"]] = p["offset"] + limit
|
||||
docs: list[LegalDoc] = []
|
||||
ranked: list[LegalDoc] = [] # a local full-text source's hits, in relevance order
|
||||
ranked_by: dict[str, list[LegalDoc]] = {} # each local full-text source's hits, in its order
|
||||
if tasks:
|
||||
done, pending = await asyncio.wait(tasks, timeout=budget)
|
||||
for task in pending:
|
||||
@@ -235,7 +270,10 @@ async def search(registry, cache: SourceCache, codec: CursorCodec, query: Query,
|
||||
if exc is None:
|
||||
page = task.result()
|
||||
found = [LegalDoc.from_dict(d) for d in page["docs"]]
|
||||
(ranked if getattr(registry.get(name), "ranked", False) else docs).extend(found)
|
||||
if getattr(registry.get(name), "ranked", False):
|
||||
ranked_by[name] = found
|
||||
else:
|
||||
docs.extend(found)
|
||||
statuses[name] = SourceStatus(name, "ok", latency, page.get("total"), unsupported,
|
||||
detail=(f"only {narrowed[name].kind}s: the local "
|
||||
"index answers the rest")
|
||||
@@ -261,6 +299,7 @@ async def search(registry, cache: SourceCache, codec: CursorCodec, query: Query,
|
||||
# `rank` (`Legal._live_rank`): the live acts re-ordered by the naive prior (+ the graph's
|
||||
# when complete) — a STABLE sort, so equal priors stay newest first
|
||||
live = by_date(docs)
|
||||
ranked = merge_ranked({n: ranked_by[n] for n in registry.names() if n in ranked_by}, query.q)
|
||||
docs = dedup(ranked + (rank(live) if rank is not None else live))
|
||||
has_more = any(v is not None for v in next_offsets.values())
|
||||
return {
|
||||
|
||||
@@ -66,10 +66,12 @@ _ALIAS_COLS = ("key", "target", "kind", "label", "ord", "part", "offset", "excer
|
||||
_CASE_COLS = ("judgment_id", "section", "at", "kind", "confidence", "dst_eli", "dst_ord", "dst_num",
|
||||
"detail", "court_type", "court_tier", "judgment_date")
|
||||
#: `PgIndexStore.recount_case_refs`: per cited article, judgments, distinct courts, newest date
|
||||
#: (a date after today is a typo in the source — SAOS has judgments dated 3013 — and never the newest)
|
||||
_CASE_RECOUNT_SQL = """
|
||||
INSERT INTO case_ref_count (eli, ord, judgments, courts, latest)
|
||||
SELECT r.dst_eli, r.dst_ord, count(DISTINCT r.judgment_id),
|
||||
count(DISTINCT coalesce(j.meta ->> 'court_name', r.court_type, '')), max(r.judgment_date)
|
||||
count(DISTINCT coalesce(j.meta ->> 'court_name', r.court_type, '')),
|
||||
max(r.judgment_date) FILTER (WHERE r.judgment_date <= to_char(current_date, 'YYYY-MM-DD'))
|
||||
FROM case_ref r JOIN saos_judgment j ON j.id = r.judgment_id
|
||||
GROUP BY r.dst_eli, r.dst_ord
|
||||
"""
|
||||
@@ -608,13 +610,14 @@ class MemoryIndexStore:
|
||||
|
||||
def recount_case_refs(self) -> int:
|
||||
agg: dict = {}
|
||||
today = dt.date.today().isoformat()
|
||||
for r in self._case_table():
|
||||
a = agg.setdefault((r["dst_eli"], r["dst_ord"]), [set(), set(), None])
|
||||
a[0].add(r["judgment_id"])
|
||||
j = self.judgments.get(r["judgment_id"]) or {}
|
||||
a[1].add((j.get("meta") or {}).get("court_name") or r.get("court_type") or "")
|
||||
d = r.get("judgment_date")
|
||||
if d and (a[2] is None or d > a[2]):
|
||||
if d and d <= today and (a[2] is None or d > a[2]):
|
||||
a[2] = d
|
||||
self.case_count = {k: {"judgments": len(v[0]), "courts": len(v[1]), "latest": v[2]}
|
||||
for k, v in agg.items()}
|
||||
|
||||
@@ -534,7 +534,7 @@ class Legal:
|
||||
|
||||
async def act_text(self, eli: str, *, part: int = 1, max_chars: int = 20000) -> dict:
|
||||
doc, rec, extra = await self._act_text_record(eli)
|
||||
return {**_text_answer(doc, rec, part, max_chars), **extra}
|
||||
return {**await asyncio.to_thread(_text_answer, doc, rec, part, max_chars), **extra}
|
||||
|
||||
async def _act_text_record(self, eli: str) -> tuple[LegalDoc, TextRecord | None, dict]:
|
||||
"""The act and its text record — what `act_text` chunks and outlines, and what `resolve`
|
||||
@@ -551,7 +551,8 @@ class Legal:
|
||||
|
||||
async def fetch() -> dict:
|
||||
if doc.extra.get("has_html"):
|
||||
text = html_to_text(await adapter.text_html(doc.extra["eli"]))
|
||||
text = await asyncio.to_thread(html_to_text,
|
||||
await adapter.text_html(doc.extra["eli"]))
|
||||
if text:
|
||||
await self.texts.put(TextRecord(doc.id, version, "ready", text, "html", "pl"))
|
||||
return {"status": "ready"}
|
||||
@@ -600,7 +601,7 @@ class Legal:
|
||||
if large is not None:
|
||||
return await asyncio.to_thread(self._large_text_answer, *large, part, max_chars)
|
||||
doc, rec, extra = await self._eu_text_record(celex)
|
||||
return {**_text_answer(doc, rec, part, max_chars), **extra}
|
||||
return {**await asyncio.to_thread(_text_answer, doc, rec, part, max_chars), **extra}
|
||||
|
||||
async def _cellar_large(self, celex: str):
|
||||
"""(document, part sizes) when the local CELLAR index holds this text and it is too
|
||||
@@ -683,7 +684,7 @@ class Legal:
|
||||
# and remembered, so the next view does not download it again
|
||||
await self.texts.put(TextRecord(doc.id, "1", "failed", error=TOO_LARGE))
|
||||
return {"status": "failed"}
|
||||
text = html_to_text(html)
|
||||
text = await asyncio.to_thread(html_to_text, html) # up to MAX_TEXT_BYTES
|
||||
await self.texts.put(TextRecord(doc.id, "1", "ready" if text else "failed",
|
||||
text or None, "html", lang,
|
||||
error=None if text else "empty text"))
|
||||
@@ -716,7 +717,7 @@ class Legal:
|
||||
async def fetch() -> dict:
|
||||
doc, html = await adapter.fetch_full(jid)
|
||||
# SAOS text lives ONLY in this TTL entry (7 d) — never in doc_text.
|
||||
return {"doc": doc.to_dict(), "text": html_to_text(html)}
|
||||
return {"doc": doc.to_dict(), "text": await asyncio.to_thread(html_to_text, html)}
|
||||
return await self._cached(f"judgment:saos:{int(jid)}", TTL_JUDGMENT, fetch)
|
||||
|
||||
async def get_judgment(self, source: str, jid: str) -> dict:
|
||||
@@ -738,7 +739,7 @@ class Legal:
|
||||
doc = LegalDoc.from_dict(entry["doc"])
|
||||
rec = TextRecord(doc.id, "ttl", "ready" if entry["text"] else "failed",
|
||||
entry["text"] or None, "html", "pl")
|
||||
return _text_answer(doc, rec, part, max_chars)
|
||||
return await asyncio.to_thread(_text_answer, doc, rec, part, max_chars)
|
||||
if source == "eurlex":
|
||||
return await self.eu_text(jid, part=part, max_chars=max_chars)
|
||||
raise NotFoundError(f"Unknown judgment source '{source}'.")
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,23 @@
|
||||
"""`GET /stats`: dredd-core's stats contract (dredd-core 0.23.0 `stats_contract`), Panorama's tiles,
|
||||
asked with the acting person's own session.
|
||||
|
||||
Insider is a reference module: acts, judgments and the reference graph are the same for everybody,
|
||||
so they are not "what this person has" and are deliberately not tiles. The one list in the console
|
||||
that belongs to the caller is "Tokeny MCP" (`#/tokens`, `GET /me/tokens`), and its tile is counted by
|
||||
the very function that list calls. Nothing here re-implements access."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core import stats_contract
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import AppUser
|
||||
from . import auth as auth_service
|
||||
|
||||
|
||||
def module_stats(db: Session, user: AppUser) -> dict:
|
||||
tiles = [
|
||||
stats_contract.make_tile(key="mcp_tokens", label="Tokeny MCP",
|
||||
count=len(auth_service.list_app_tokens(db, user)), link="tokens"),
|
||||
]
|
||||
return stats_contract.make_response(get_settings().module_slug, tiles)
|
||||
@@ -402,7 +402,9 @@ class TextIndex:
|
||||
if need is None or need >= len(clauses):
|
||||
sets = [clauses]
|
||||
else:
|
||||
sets = [list(c) for c in itertools.combinations(clauses, need)][:PARTIAL_COMBOS]
|
||||
# islice, not list()[:N]: C(40, 24) is ~63 billion subsets, and building them all
|
||||
# took a ~40-word query past 16 GB before the cut (benchmark 2026-11-18).
|
||||
sets = [list(c) for c in itertools.islice(itertools.combinations(clauses, need), PARTIAL_COMBOS)]
|
||||
for subset in sets:
|
||||
q_ = T.Query.boolean_query([(T.Occur.Must, c) for c in subset])
|
||||
alts.append(q_ if i == 0 else T.Query.boost_query(q_, EXPANSION_BOOST))
|
||||
|
||||
@@ -23,9 +23,12 @@
|
||||
# nothing else.
|
||||
#
|
||||
# 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
|
||||
# local — a read-only Gitea access token in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the Haski org secret DREDD_CORE_TOKEN; see the workflow-level `env:` in .github/workflows/
|
||||
#
|
||||
# v0.23.0 brings `dredd_core.stats_contract` (the Compass split's M4): `GET /stats`, Panorama's tiles
|
||||
# (services/stats.py). 0.18.0-0.22.0 come along; their additions are opt-in (no table needed here).
|
||||
dredd-core @ git+http://77.216.148.202:3000/Haski/dredd-core.git@v0.23.0
|
||||
|
||||
# Web framework
|
||||
fastapi==0.161.0
|
||||
@@ -74,7 +77,7 @@ Jinja2==3.1.6 # BSD-3-Clause (pulls MarkupSafe, BSD-3-Clause)
|
||||
# Generators (Claude, Bielik, Mistral, Ollama…) are plain httpx calls, no vendor SDK.
|
||||
onnxruntime==1.31.0 # MIT (deps: numpy, protobuf BSD-3, flatbuffers Apache-2.0, packaging)
|
||||
tokenizers==0.23.3 # Apache-2.0 (pulls huggingface-hub Apache-2.0 → tqdm MPL-2.0 AND MIT)
|
||||
numpy==2.5.4 # BSD-3-Clause
|
||||
numpy==2.3.5 # BSD-3-Clause — held below 2.4: paddleocr 3.7 (paddlex 3.7.x, requirements-ocr.txt) needs numpy<2.4
|
||||
# the platform's provider-key cipher (AES-256-GCM), for INSIDER_GENERATOR=provider:…
|
||||
cryptography==50.0.2 # Apache-2.0 OR BSD-3-Clause
|
||||
|
||||
|
||||
@@ -126,8 +126,8 @@ check("USER app" in dockerfile, "container runs as root",
|
||||
|
||||
# ── the image can install the private core ────────────────────────────────────
|
||||
requirements = read("backend/requirements.txt")
|
||||
if "git+https://github.com/Alpaq92/dredd-core" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names github.com, so that could never fail.
|
||||
if "dredd-core @ git+" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names git in its URL rewrite, so that could never fail.
|
||||
# Look for git as a package of an apt/apk install (comments dropped, `\` continuations joined as
|
||||
# BuildKit joins them: whitespace may follow the backslash, and blank lines inside are skipped).
|
||||
run_text = re.sub(r"\\[ \t]*\n(?:[ \t]*\n)*", " ", re.sub(r"(?m)^\s*#.*\n", "", dockerfile))
|
||||
@@ -219,6 +219,9 @@ check(f"target: {CA_TARGET}" in override and "create_host_path: false" in overri
|
||||
check('MIGRATION_DATABASE_URL: ""' in service_block("backend"),
|
||||
"docker-compose.managed-db.yml leaves the migrator's URL in the long-running backend",
|
||||
"the managed-db override keeps migrator credentials out of the backend")
|
||||
check('MIGRATION_DATABASE_URL: ""' in service_block("ocr-worker"),
|
||||
"docker-compose.managed-db.yml leaves the migrator's URL in the long-running OCR worker",
|
||||
"the managed-db override keeps migrator credentials out of the OCR worker")
|
||||
|
||||
|
||||
def env_settings(text: str) -> dict[str, str]:
|
||||
|
||||
@@ -50,7 +50,7 @@ class Budgeted(httpx.AsyncBaseTransport):
|
||||
|
||||
def _settings() -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
insider_contact=os.environ.get("INSIDER_CONTACT", "https://github.com/Alpaq92/Insider"),
|
||||
insider_contact=os.environ.get("INSIDER_CONTACT", "http://77.216.148.202:3000/Haski/Insider"),
|
||||
insider_source_eli=True, insider_source_saos=True, insider_source_eurlex=True,
|
||||
insider_rate_eli=2.0, insider_concurrency_eli=2, insider_rate_saos=1.0,
|
||||
insider_concurrency_saos=1, insider_rate_eurlex=1.0, insider_concurrency_eurlex=1)
|
||||
|
||||
@@ -55,11 +55,19 @@ def rss() -> tuple[int, int]:
|
||||
if not k32.K32GetProcessMemoryInfo(k32.GetCurrentProcess(), ctypes.byref(c), c.cb):
|
||||
raise OSError("GetProcessMemoryInfo failed")
|
||||
return c.WorkingSetSize, c.PeakWorkingSetSize
|
||||
if os.path.exists("/proc/self/status"):
|
||||
# Linux: VmRSS / VmHWM belong to this process's own memory and start over at exec.
|
||||
# Not ru_maxrss: Linux carries it over from the parent across fork+exec, so under a
|
||||
# pytest process that has grown to ~340 MB the probe "peaked" at 340 MB before it began.
|
||||
fields = {}
|
||||
with open("/proc/self/status") as f:
|
||||
for line in f:
|
||||
key, _, value = line.partition(":")
|
||||
fields[key] = value
|
||||
return (int(fields["VmRSS"].split()[0]) * 1024, int(fields["VmHWM"].split()[0]) * 1024)
|
||||
import resource
|
||||
with open("/proc/self/statm") as f:
|
||||
cur = int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE")
|
||||
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024
|
||||
return cur, peak
|
||||
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # bytes on macOS
|
||||
return peak, peak
|
||||
|
||||
|
||||
ART = ('<div class="eli-subdivision"><p class="oj-ti-art">Artykuł {n}</p>'
|
||||
|
||||
@@ -179,6 +179,34 @@ def test_thesaurus_variants_weigh_less_and_partial_matches_are_flagged(tmp_path)
|
||||
assert ix.search("hulajnoga")[0] == [] # one word: nothing to relax
|
||||
|
||||
|
||||
def test_a_long_query_draws_only_the_capped_word_subsets(tmp_path, monkeypatch):
|
||||
"""A ~40-word query (the chat sends whole exam questions) relaxed to 60% of its words has
|
||||
C(40, 24) ~ 63 billion subsets; listing them all before the cut killed the process (OOM)."""
|
||||
import itertools
|
||||
|
||||
from app.services import textindex
|
||||
from app.services.textindex import PARTIAL_COMBOS, TextIndex
|
||||
if not TextIndex.available:
|
||||
pytest.skip("tantivy is not installed")
|
||||
words = ("sąd umowa najem lokal gmina czynsz kaucja wypowiedzenie termin pismo strona dłużnik "
|
||||
"wierzyciel odsetki szkoda kara grzywna wyrok apelacja skarga wniosek opłata podatek "
|
||||
"spadek darowizna testament małżonek dziecko alimenty rozwód majątek hipoteka księga "
|
||||
"służebność własność posiadanie zasiedzenie przedawnienie pełnomocnik prokura").split()
|
||||
assert len(set(words)) == 40
|
||||
combinations = itertools.combinations
|
||||
|
||||
def counted(pool, r):
|
||||
for drawn, c in enumerate(combinations(pool, r), 1):
|
||||
assert drawn <= PARTIAL_COMBOS, "the subsets must be cut while drawn, not after"
|
||||
yield c
|
||||
|
||||
monkeypatch.setattr(textindex.itertools, "combinations", counted)
|
||||
ix = TextIndex(tmp_path / "ix")
|
||||
ix.rebuild([{"group": "P", "ord": 0, "title": "Prawo", "text": " ".join(words[:-1]) + "."}])
|
||||
groups, _ = ix.search(" ".join(words[1:]) + " hulajnoga") # no part holds "hulajnoga"
|
||||
assert [g["group"] for g in groups] == ["P"] and groups[0]["partial"]
|
||||
|
||||
|
||||
def test_partial_results_carry_a_notice_and_a_rebuild_a_note():
|
||||
from app.services import federation, legal
|
||||
full = [{"extra": {}}]
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -158,6 +158,18 @@ def test_first_pass_counts_and_guard(acts):
|
||||
assert caselaw.cited(key) == 3
|
||||
|
||||
|
||||
def test_a_date_in_the_future_is_never_the_newest(acts):
|
||||
# SAOS has judgments dated 3013 (typos in the source); "latest" ignores them
|
||||
store = world(acts)
|
||||
store.upsert_judgments([judgment(1, "art. 415 k.c.", date="2024-06-01"),
|
||||
judgment(2, "art. 415 k.c.", date="3013-12-04")])
|
||||
store.set_state("legal_graph", completed_at=now())
|
||||
asyncio.run(case_job(store).run_once())
|
||||
key = (KC, lg.LabelCache(store)(KC)["415"])
|
||||
assert cl.CaseLaw(store).counts([key])[key] == {"judgments": 2, "courts": 1,
|
||||
"latest": "2024-06-01"}
|
||||
|
||||
|
||||
def test_incremental_by_updated_at(acts):
|
||||
store = world(acts)
|
||||
store.upsert_judgments([judgment(1, "art. 415 k.c."), judgment(2, "art. 22 k.p.")])
|
||||
|
||||
@@ -80,6 +80,8 @@ vm.runInContext(fs.readFileSync(process.argv[2], 'utf8') + `
|
||||
routes: [docRoute({id:'eli:DU/1997/939', kind:'act'}), docRoute({id:'saos:554187', kind:'judgment'}),
|
||||
docRoute({id:'eurlex:62018CJ0311', kind:'judgment'}), docRoute({id:'eurlex:32016R0679', kind:'act'})],
|
||||
apis: [routeApi(['act','DU','1997','939']), routeApi(['eu','32016R0679']), routeApi(['judgment','saos','1'])],
|
||||
apisExtra: [routeApi(['eu','32016R0679',"'-alert(1)-'"]), routeApi(['judgment','saos','1','x']),
|
||||
routeApi(['act','DU','1997','939','x']), routeApi(['eu'])],
|
||||
hash: routeHash(['judgment','saos','1']),
|
||||
hl: hl('<b>Kredyt</b> frankowy & bank', 'kredyt <b>'),
|
||||
cite: [citationOf({source:'eli', title:'Ustawa - Prawo bankowe', extra:{eli:'DU/1997/939'}}),
|
||||
@@ -129,6 +131,8 @@ def test_console_helpers_in_node(tmp_path):
|
||||
assert out["routes"] == [["act", "DU", "1997", "939"], ["judgment", "saos", "554187"],
|
||||
["judgment", "eurlex", "62018CJ0311"], ["eu", "32016R0679"]]
|
||||
assert out["apis"] == ["/acts/DU/1997/939", "/acts/eu/32016R0679", "/judgments/saos/1"]
|
||||
# a segment the API would ignore is refused: it would ride along in every link built from it
|
||||
assert out["apisExtra"] == [None, None, None, None]
|
||||
assert out["hash"] == "#/doc/judgment/saos/1"
|
||||
assert "<b>" not in out["hl"] and "<b>" in out["hl"] and "<mark>Kredyt</mark>" in out["hl"]
|
||||
assert out["cite"] == ["Ustawa - Prawo bankowe (Dz. U. z 1997 r. poz. 939)",
|
||||
@@ -166,6 +170,13 @@ def test_console_helpers_in_node(tmp_path):
|
||||
{"name": "saos", "status": "ok", "total": 3}]
|
||||
|
||||
|
||||
def test_no_inline_handler_carries_a_route():
|
||||
"""esc() is HTML escaping: inside onclick="…" the browser decodes ' back to ' before the
|
||||
JavaScript runs, so a hash-derived route there is script injection (the document pager was)."""
|
||||
for handler in re.findall(r'\bon[a-z]+="([^"]*)"', APP):
|
||||
assert "routeHash" not in handler and "location.hash" not in handler, handler
|
||||
|
||||
|
||||
def test_progressive_search_is_wired():
|
||||
assert "p.set('progressive', 'true')" in APP
|
||||
assert "/search/pending?ticket=" in APP and "encodeURIComponent(p.ticket)" in APP
|
||||
|
||||
@@ -105,8 +105,13 @@ def _probe(*args: str) -> dict:
|
||||
import subprocess
|
||||
import sys
|
||||
probe = os.path.join(os.path.dirname(__file__), "eu_stream_probe.py")
|
||||
# The probe measures this code's memory, not the harness's: no pytest-cov tracer in the child,
|
||||
# and one malloc arena, so glibc's per-core arenas (6 cores on the Gitea runner: ~120 MB
|
||||
# instead of ~62 MB) do not add their own retained pages to the peak.
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith(("COV_CORE_", "COVERAGE_"))}
|
||||
env["MALLOC_ARENA_MAX"] = "1"
|
||||
out = subprocess.run([sys.executable, probe, *args], capture_output=True, text=True,
|
||||
timeout=900, check=True)
|
||||
timeout=900, check=True, env=env)
|
||||
return json.loads(out.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
@@ -121,7 +126,8 @@ class TestBoundedMemory:
|
||||
assert big["parts"] > 15_000 and big["chars"] > 150 * 1024 * 1024 and not big["truncated"]
|
||||
# flat: ~40 MB either way (the runtime's own first allocations), never the document
|
||||
assert big["peak_mb"] < 96, big
|
||||
assert big["peak_mb"] - small["peak_mb"] < 16, (small, big)
|
||||
# measured on the Gitea runner: ~42 MB vs ~62 MB; the old whole-body path was ~700 MB
|
||||
assert big["peak_mb"] - small["peak_mb"] < 32, (small, big)
|
||||
|
||||
def test_the_valve_cuts_a_text_past_the_streaming_cap(self):
|
||||
out = _probe("--mb", "40", "--max-stream-mb", "8")
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""The facade never parses or chunks a whole text on the event loop.
|
||||
|
||||
`html_to_text` is a pure-Python HTMLParser and a live EU text may be up to `MAX_TEXT_BYTES`; run on the
|
||||
loop it froze every other request (REST, MCP, the console) for as long as it took. `_text_answer`
|
||||
chunks and outlines a whole stored text. Inside an `async def` both go through `asyncio.to_thread`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import pathlib
|
||||
|
||||
LEGAL = pathlib.Path(__file__).resolve().parents[1] / "app" / "services" / "legal.py"
|
||||
HEAVY = {"html_to_text", "_text_answer"}
|
||||
|
||||
|
||||
def _direct_calls(fn: ast.AsyncFunctionDef) -> list[str]:
|
||||
found = []
|
||||
for node in ast.walk(fn):
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in HEAVY:
|
||||
found.append(f"{fn.name}:{node.lineno}")
|
||||
return found
|
||||
|
||||
|
||||
def test_heavy_text_work_never_runs_on_the_event_loop():
|
||||
tree = ast.parse(LEGAL.read_text(encoding="utf-8"))
|
||||
offenders = [hit for node in ast.walk(tree) if isinstance(node, ast.AsyncFunctionDef)
|
||||
for hit in _direct_calls(node)]
|
||||
assert offenders == [], offenders
|
||||
|
||||
|
||||
def test_the_guard_sees_the_calls_it_is_about():
|
||||
src = LEGAL.read_text(encoding="utf-8")
|
||||
assert src.count("asyncio.to_thread(html_to_text") >= 3
|
||||
assert src.count("asyncio.to_thread(_text_answer") >= 3
|
||||
@@ -318,3 +318,38 @@ def test_supreme_court_case_numbers():
|
||||
from app.services.citations import is_supreme_court_case as sn
|
||||
assert all(sn(x) for x in ("III CZP 25/22", "V KK 12/21", "I CSKP 100/22", "II PSKP 1/22"))
|
||||
assert not any(sn(x) for x in ("III Ca 1127/26", "II SA/Wa 123/24", "I ACa 5/20", "KIO 1/24"))
|
||||
|
||||
|
||||
def _hit(source: str, n: str, score: float, *, partial: bool = False) -> LegalDoc:
|
||||
extra = {"relevance": score} | ({"partial": True} if partial else {})
|
||||
return LegalDoc(id=f"{source}:{n}", source=source, kind="act", title=n, extra=extra)
|
||||
|
||||
|
||||
def test_local_hits_merge_by_normalised_score_not_by_which_index_finished_first():
|
||||
from app.services.federation import merge_ranked
|
||||
# the EU index's raw scores are far higher (a Polish word is rare there): never compared raw
|
||||
pl = [_hit("dzu_md", "kc-991", 9.0), _hit("dzu_md", "kc-1000", 4.0)]
|
||||
eu = [_hit("cellar", "eu-a", 80.0), _hit("cellar", "eu-b", 70.0)]
|
||||
for order in ({"cellar": eu, "dzu_md": pl}, {"dzu_md": pl, "cellar": eu}):
|
||||
got = [d.title for d in merge_ranked(order, "zachowek")]
|
||||
assert got[0] == "kc-991" # each index's best is 1.0; EU's weighs 0.6
|
||||
assert got.index("eu-a") < got.index("kc-1000") # 0.6 beats 4/9: interleaved, not blocks
|
||||
|
||||
|
||||
def test_a_query_naming_eu_law_weighs_eu_acts_like_polish_ones():
|
||||
from app.services.federation import merge_ranked
|
||||
pl = [_hit("dzu_md", "ustawa-odo", 5.0)]
|
||||
eu = [_hit("cellar", "rodo", 50.0)]
|
||||
by = {"dzu_md": pl, "cellar": eu}
|
||||
assert [d.title for d in merge_ranked(by, "art. 6 RODO")] == ["ustawa-odo", "rodo"] # tie: PL first
|
||||
eu[0].extra["relevance"] = 60.0
|
||||
pl.append(_hit("dzu_md", "inna", 6.0)) # PL top is now 6.0: ustawa-odo 5/6 < rodo 1.0
|
||||
assert [d.title for d in merge_ranked(by, "dyrektywa 2016/680")][0] in ("inna", "rodo")
|
||||
assert [d.title for d in merge_ranked(by, "zachowek")][-1] == "rodo" # 0.6 under 5/6
|
||||
|
||||
|
||||
def test_a_partial_match_sits_under_the_full_ones():
|
||||
from app.services.federation import merge_ranked
|
||||
pl = [_hit("dzu_md", "full-low", 3.0), _hit("dzu_md", "partial-top", 9.0, partial=True)]
|
||||
got = [d.title for d in merge_ranked({"dzu_md": pl}, "kara umowna")]
|
||||
assert got == ["full-low", "partial-top"] # a tier of its own, not a weight
|
||||
|
||||
@@ -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"):
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -53,8 +53,9 @@ def test_anonymous_requests_are_refused():
|
||||
def test_the_admin_boundary(admin_client, make_user):
|
||||
bob = make_user("bob")
|
||||
h = bearer(bob["token"])
|
||||
# GET /users is the roster: on the platform every account there is, not only this module's
|
||||
for method, path in [("GET", "/api/v1/admin/audit"), ("GET", "/api/v1/admin/settings"),
|
||||
("PUT", "/api/v1/admin/settings")]:
|
||||
("PUT", "/api/v1/admin/settings"), ("GET", "/api/v1/users")]:
|
||||
r = admin_client.request(method, path, headers=h, json={"values": {"instance_name": "x"}})
|
||||
assert r.status_code == 403, (path, r.status_code)
|
||||
r = admin_client.post("/api/v1/users", headers=h, json={
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""`GET /stats` (dredd-core's stats contract, Panorama's tiles) - DB-free: the route exists behind
|
||||
the session, and the one tile is built from the very function the "Tokeny MCP" list calls."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from dredd_core import stats_contract
|
||||
|
||||
from app.services import stats
|
||||
|
||||
|
||||
def test_the_tile_comes_from_the_lists_own_function(monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def list_app_tokens(db, user):
|
||||
seen["tokens"] = user
|
||||
return [object()] * 3
|
||||
|
||||
monkeypatch.setattr(stats.auth_service, "list_app_tokens", list_app_tokens)
|
||||
person = SimpleNamespace(id="p")
|
||||
body = stats.module_stats(None, person)
|
||||
stats_contract.validate_response(body)
|
||||
assert body["module"] == "insider"
|
||||
assert [(t["key"], t["count"], t["link"]) for t in body["tiles"]] == [("mcp_tokens", 3, "tokens")]
|
||||
assert seen == {"tokens": person}
|
||||
|
||||
|
||||
def test_the_list_route_calls_the_same_function():
|
||||
from app.routers import users
|
||||
|
||||
assert users.auth_service is stats.auth_service
|
||||
|
||||
|
||||
def test_the_route_is_behind_the_session():
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
assert TestClient(app).get("/api/v1/stats").status_code == 401
|
||||
@@ -1,7 +1,7 @@
|
||||
# Insider on a managed PostgreSQL database (the family's shared one, or any Postgres 16/17 reached
|
||||
# over a network): an override for docker-compose.yml.
|
||||
#
|
||||
# DREDD_CORE_TOKEN=github_pat_... \
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> \
|
||||
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
|
||||
#
|
||||
# The database lives elsewhere — the family shares ONE managed database, and Insider has schema
|
||||
@@ -68,3 +68,15 @@ services:
|
||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-5}
|
||||
DB_MAX_OVERFLOW: ${DB_MAX_OVERFLOW:-10}
|
||||
volumes: *managed_db_ca
|
||||
ocr-worker:
|
||||
# The optional OCR worker (profile `ocr`) is long-running too, and it is the process that feeds
|
||||
# PDFs to native parsers (pdfium, Paddle/OpenCV, Tesseract): the same blanks as the backend, so a
|
||||
# compromised worker cannot log in as insider_migrator or as the local superuser. It needs only
|
||||
# DATABASE_URL (ocr_job, doc_text) and ELI.
|
||||
environment:
|
||||
MIGRATION_DATABASE_URL: ""
|
||||
DB_MIGRATOR_PASSWORD: ""
|
||||
DB_APP_PASSWORD: ""
|
||||
POSTGRES_PASSWORD: ""
|
||||
DB_APP_ROLE: ${DB_APP_ROLE:?set DB_APP_ROLE in .env to the runtime role, insider_app in the shared database}
|
||||
volumes: *managed_db_ca
|
||||
|
||||
+1
-1
@@ -86,6 +86,6 @@ secrets:
|
||||
# Used only by the build stage's one `pip install`; no running container gets it. Compose resolves
|
||||
# the variable from the shell OR the project .env (shell wins) — keep it in the shell, because every
|
||||
# service here also loads .env at runtime and would receive the token:
|
||||
# DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> docker compose up -d --build
|
||||
dredd_core_token:
|
||||
environment: DREDD_CORE_TOKEN
|
||||
|
||||
@@ -105,6 +105,8 @@ mark { background: var(--warn-bg); color: inherit; border-radius: 2px; padding:
|
||||
.outline a:hover { background: var(--at-hover); text-decoration: none; }
|
||||
.outline .l1 { padding-left: 14px; }
|
||||
.outline .l2 { padding-left: 26px; }
|
||||
.outline .art { color: var(--text); font-weight: 500; }
|
||||
.doctext .mdh { font-weight: 600; }
|
||||
.doctext { white-space: pre-wrap; font-size: 14px; line-height: 1.65; overflow-wrap: anywhere; }
|
||||
.doctext .anchor { scroll-margin-top: 16px; }
|
||||
.doctext .anchor.hit { background: var(--surface-2); font-weight: 600; }
|
||||
|
||||
+79
-27
@@ -59,7 +59,7 @@ async function api(method, path, body) {
|
||||
|
||||
function toast(msg) {
|
||||
const t = $('toast');
|
||||
t.innerHTML = `<div class="toast">${esc(msg)}</div>`;
|
||||
t.innerHTML = `<div class="toast">${esc(_tr(msg))}</div>`;
|
||||
setTimeout(() => { t.innerHTML = ''; }, 3000);
|
||||
}
|
||||
|
||||
@@ -184,6 +184,7 @@ const SRC_LANG = 'pl';
|
||||
const ALT_LANG = 'en';
|
||||
|
||||
const I18N = {
|
||||
'Przejdź do treści': 'Skip to content',
|
||||
'System zarządzania': 'Management console',
|
||||
'Zaloguj się': 'Sign in',
|
||||
'Wyloguj się': 'Sign out',
|
||||
@@ -200,6 +201,7 @@ const I18N = {
|
||||
'Język': 'Language',
|
||||
'Konto': 'Account',
|
||||
'Szukaj…': 'Search…',
|
||||
'Szukaj… (Ctrl+K)': 'Search… (Ctrl+K)',
|
||||
'Graf odesłań między przepisami — kto cytuje który artykuł i które akty łączą się najmocniej': 'The reference graph — which article cites which, and which acts are most closely linked',
|
||||
'art. 415 k.c., kc:415, Kodeks cywilny, k.c. albo słowa z tytułu aktu': 'art. 415 k.c., kc:415, Kodeks cywilny, k.c. or words from an act title',
|
||||
'Szukaj w grafie': 'Search the graph',
|
||||
@@ -376,6 +378,28 @@ const I18N = {
|
||||
'np. Claude Desktop': 'e.g. Claude Desktop',
|
||||
'Zwiń panel (Ctrl+B)': 'Collapse panel (Ctrl+B)',
|
||||
'Zwiń panel': 'Collapse panel',
|
||||
'akty i orzecznictwo': 'acts and case law',
|
||||
'Indeks EUR-Lex': 'EUR-Lex index',
|
||||
'Indeks…': 'Index…',
|
||||
'OCR w toku — ten akt jest opublikowany tylko jako PDF; tekst pojawi się po rozpoznaniu.': 'OCR in progress — this act is published only as a PDF; the text appears once it is recognised.',
|
||||
'Dokument jest zbyt duży, by pokazać go w podglądzie.': 'The document is too large to show in the preview.',
|
||||
'Tekst skrócony — dokument przekracza limit importu; pełna wersja w EUR-Lex.': 'Text shortened — the document exceeds the import limit; the full version is on EUR-Lex.',
|
||||
'narzędzia:': 'tools:',
|
||||
'zap./s': 'req/s',
|
||||
/* Fixed strings the server sends (attributions in backend/app/integrations, dataset labels in
|
||||
services/indexing.py): matched verbatim, so a reworded one there shows in Polish again. */
|
||||
'Źródło: Kancelaria Sejmu RP, API ELI (api.sejm.gov.pl)': 'Source: Chancellery of the Sejm, ELI API (api.sejm.gov.pl)',
|
||||
'Źródło: SAOS — System Analizy Orzeczeń Sądowych (saos.org.pl)': 'Source: SAOS — Court Judgment Analysis System (saos.org.pl)',
|
||||
'© European Union, https://eur-lex.europa.eu — ponowne wykorzystanie zgodnie z decyzją 2011/833/UE; metadane CC0, teksty skonsolidowane CC BY 4.0': '© European Union, https://eur-lex.europa.eu — reused under Decision 2011/833/EU; metadata CC0, consolidated texts CC BY 4.0',
|
||||
'Tekst: dziennik-ustaw-md (PolskiAgentW, CC0 1.0), konwersja eli2md (MIT) z PDF Dziennika Ustaw — nieoficjalna; metadane i status: Kancelaria Sejmu RP, API ELI': 'Text: dziennik-ustaw-md (PolskiAgentW, CC0 1.0), eli2md conversion (MIT) from the Journal of Laws PDF — unofficial; metadata and status: Chancellery of the Sejm, ELI API',
|
||||
'Źródło: Kancelaria Sejmu RP, API ELI (api.sejm.gov.pl) — tekst jednolity w lokalnym indeksie Insidera': 'Source: Chancellery of the Sejm, ELI API (api.sejm.gov.pl) — consolidated text in Insider\'s local index',
|
||||
'Źródło: SAOS — System Analizy Orzeczeń Sądowych (saos.org.pl), lokalna kopia z API pobierania danych (zrzut)': 'Source: SAOS — Court Judgment Analysis System (saos.org.pl), local copy from the data download API (dump)',
|
||||
'Dziennik Ustaw (dziennik-ustaw-md, CC0)': 'Journal of Laws (dziennik-ustaw-md, CC0)',
|
||||
'SAOS — orzeczenia (API pobierania danych)': 'SAOS — judgments (data download API)',
|
||||
'Akty obowiązujące — teksty jednolite (API ELI)': 'Acts in force — consolidated texts (ELI API)',
|
||||
'Graf odesłań między przepisami (z tekstów aktów)': 'Reference graph between provisions (from the acts\' texts)',
|
||||
'Aliasy przepisów i sygnatur (kc:483, rodo:6, sig:III CZP 12/20)': 'Provision and case-number aliases (kc:483, rodo:6, sig:III CZP 12/20)',
|
||||
'Orzecznictwo: przepisy cytowane w wyrokach (SAOS)': 'Case law: provisions cited in judgments (SAOS)',
|
||||
};
|
||||
|
||||
let LANG = (function () {
|
||||
@@ -459,12 +483,25 @@ function applyLang(lang) {
|
||||
document.documentElement.lang = LANG;
|
||||
document.querySelectorAll('#aLang,#btnLangLogin').forEach((b) => { b.textContent = LANG.toUpperCase(); });
|
||||
localize(document.body);
|
||||
localizeChrome();
|
||||
/* the framed graph page has its own dictionary (graph.js) */
|
||||
try { const f = $('gframe'); if (f && f.contentWindow && f.contentWindow.applyLang) f.contentWindow.applyLang(LANG); } catch { /* not loaded yet */ }
|
||||
if (state.user && _RERENDER_ON_LANG.has(parseHash().seg[0] || '') && !_hasEditedField($('content'))) router();
|
||||
return true;
|
||||
}
|
||||
window.applyLang = applyLang;
|
||||
/* <title> lives in <head>, outside localize()'s reach, and the language button is data-no-i18n
|
||||
(its PL / EN is a code, not a word) — so their text is set here, from the Polish source. */
|
||||
const _SRC_TITLE = document.title;
|
||||
function localizeChrome() {
|
||||
document.documentElement.lang = LANG;
|
||||
const [name, sub] = _SRC_TITLE.split(' — ');
|
||||
document.title = sub ? `${name} — ${_tr(sub)}` : _tr(name);
|
||||
document.querySelectorAll('#aLang,#btnLangLogin').forEach((b) => {
|
||||
b.title = _tr('Język');
|
||||
if (b.hasAttribute('aria-label')) b.setAttribute('aria-label', b.title);
|
||||
});
|
||||
}
|
||||
function cycleLang() { applyLang(LANG === SRC_LANG ? ALT_LANG : SRC_LANG); }
|
||||
|
||||
/* ── auth ─────────────────────────────────────────────────────────────────
|
||||
@@ -547,7 +584,6 @@ async function afterLogin() {
|
||||
b.textContent = LANG.toUpperCase();
|
||||
});
|
||||
$('aUser').textContent = initials(state.user.full_name || state.user.email);
|
||||
try { state.users = await api('GET', '/users'); } catch { state.users = []; }
|
||||
try { state.config = await api('GET', '/config'); } catch { state.config = {}; }
|
||||
if (!location.hash || location.hash === '#') location.hash = '#/';
|
||||
await router();
|
||||
@@ -593,10 +629,11 @@ function setCrumb(parts) {
|
||||
? `<a href="${esc(p.href)}">${esc(p.label)}</a>`
|
||||
: `<b>${esc(p.label)}</b>`);
|
||||
}).join(' ');
|
||||
localize($('crumb'));
|
||||
}
|
||||
|
||||
function pageHead(title, sub, actions) {
|
||||
return `<div class="page-head"><div><h2>${esc(title)}</h2>${sub ? `<div class="sub">${esc(sub)}</div>` : ''}</div>${actions ? `<div class="acts">${actions}</div>` : ''}</div>`;
|
||||
return `<div class="page-head"><div><h1>${esc(title)}</h1>${sub ? `<div class="sub">${esc(sub)}</div>` : ''}</div>${actions ? `<div class="acts">${actions}</div>` : ''}</div>`;
|
||||
}
|
||||
|
||||
function parseHash() {
|
||||
@@ -645,11 +682,13 @@ function docRoute(d) {
|
||||
return null;
|
||||
}
|
||||
function routeHash(r) { return '#/doc/' + r.map(encodeURIComponent).join('/'); }
|
||||
/* Exactly the segments each kind has: a route comes from the URL's hash, and a segment the API
|
||||
call ignores would still be carried into every link built from the route. */
|
||||
function routeApi(r) {
|
||||
const e = r.map(encodeURIComponent);
|
||||
if (r[0] === 'act') return '/acts/' + e.slice(1).join('/');
|
||||
if (r[0] === 'eu') return '/acts/eu/' + e[1];
|
||||
if (r[0] === 'judgment') return '/judgments/' + e[1] + '/' + e[2];
|
||||
if (r[0] === 'act' && r.length === 4) return '/acts/' + e.slice(1).join('/');
|
||||
if (r[0] === 'eu' && r.length === 2) return '/acts/eu/' + e[1];
|
||||
if (r[0] === 'judgment' && r.length === 3) return '/judgments/' + e[1] + '/' + e[2];
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -798,7 +837,7 @@ async function viewSearch(C, q) {
|
||||
<input type="date" id="qto" value="${esc(q.to || '')}" title="Do" aria-label="Do" />
|
||||
${kindFiltersHtml(q)}
|
||||
</div>
|
||||
${(state._cleared || []).length ? `<div class="faint tiny" id="qcleared">Wyczyszczono filtry dotyczące tylko jednego rodzaju wyników: ${esc(state._cleared.map((k) => FILTER_SCOPE_LABEL[k]).join(', '))}</div>` : ''}
|
||||
${(state._cleared || []).length ? `<div class="faint tiny" id="qcleared"><span>Wyczyszczono filtry dotyczące tylko jednego rodzaju wyników:</span> ${state._cleared.map((k) => `<span>${esc(FILTER_SCOPE_LABEL[k])}</span>`).join(', ')}</div>` : ''}
|
||||
<div class="srcline" id="srcline"></div>
|
||||
<div id="notices"></div>
|
||||
<div class="split2"><div id="results" aria-busy="false"></div><aside class="card preview" id="preview">
|
||||
@@ -972,7 +1011,7 @@ function renderSourceLine(sources) {
|
||||
const u = UNSUPPORTED[f];
|
||||
return typeof u === 'object' ? (u[s.name] || '') : (u || f);
|
||||
}).filter(Boolean);
|
||||
const bits = [SRC_STATUS[s.status] || s.status];
|
||||
const bits = [];
|
||||
if (s.latency_ms != null && s.status !== 'skipped') bits.push(s.latency_ms + ' ms');
|
||||
if (s.total != null) bits.push(String(s.total));
|
||||
if (s.status === 'pending') {
|
||||
@@ -981,7 +1020,7 @@ function renderSourceLine(sources) {
|
||||
const fresh = s.freshness ? Object.entries(s.freshness).map(([k, f]) => `${k}: ${f.synced_at ? fmtDate(f.synced_at) : '—'} · ${f.documents}`).join('; ') : '';
|
||||
if (s.index_note) notes.push('indeks przebudowywany — odpowiada poprzedni');
|
||||
const tip = [s.detail, fresh].filter(Boolean).join(' — ');
|
||||
return `<span class="s ${esc(s.status)}" title="${esc(tip)}"><span class="dot"></span><b>${esc(SOURCE_LABEL[s.name] || s.name)}</b> ${esc(bits.join(' · '))}${notes.length ? ` <span class="faint">(${esc(notes.join(', '))})</span>` : ''}</span>`;
|
||||
return `<span class="s ${esc(s.status)}" title="${esc(tip)}"><span class="dot"></span><b>${esc(SOURCE_LABEL[s.name] || s.name)}</b> <span>${esc(SRC_STATUS[s.status] || s.status)}</span>${bits.length ? ' · ' + esc(bits.join(' · ')) : ''}${notes.length ? ` <span class="faint">(${notes.map((n) => `<span>${esc(n)}</span>`).join(', ')})</span>` : ''}</span>`;
|
||||
}).join('');
|
||||
localize($('srcline'));
|
||||
}
|
||||
@@ -1099,19 +1138,25 @@ function previewHtml(d, text, i, route) {
|
||||
}
|
||||
|
||||
/* ── document ───────────────────────────────────────────────────────────── */
|
||||
const ACT_RE = [/^(DZIAŁ|Dział|ROZDZIAŁ|Rozdział|TYTUŁ|Tytuł|KSIĘGA|Księga)\s+\S+/, /^(Art\.|§)\s*\d+[a-z]*\.?/, /^\d+[a-z]?\.\s/, /^\d+[a-z]?\)\s/];
|
||||
const ACT_RE = [/^(DZIAŁ|Dział|ROZDZIAŁ|Rozdział|TYTUŁ|Tytuł|KSIĘGA|Księga|Oddział|ODDZIAŁ)\s+\S+/, /^Art\.\s*\d+[a-z]*[¹²³⁰-⁹]*\.?/, /^§\s*\d+[a-z]*\.?/, /^\d+[a-z]?\.\s/, /^\d+[a-z]?\)\s/];
|
||||
const RULING_RE = /^(WYROK|POSTANOWIENIE|UCHWAŁA|UZASADNIENIE|SENTENCJA|ZDANIE ODRĘBNE|W IMIENIU RZECZYPOSPOLITEJ POLSKIEJ|JUDGMENT|WYROK TRYBUNAŁU)\b/;
|
||||
/* dziennik-ustaw-md texts carry headings as Markdown ("##### Art. 227.", "### Rozdział XXVI"):
|
||||
the marks and emphasis go before a line is matched, and before it is shown. */
|
||||
const MD_MARKS = /^[#>*_\s]+/;
|
||||
function plainLine(ln) { return ln.trim().replace(MD_MARKS, ''); }
|
||||
|
||||
function outlineOf(lines, isAct) {
|
||||
const out = [];
|
||||
lines.forEach((ln, i) => {
|
||||
const t = ln.trim();
|
||||
const t = plainLine(ln);
|
||||
if (!t || out.length >= 600) return;
|
||||
if (isAct) {
|
||||
/* chapter, then its articles, then each article's § / ust. and pkt — indented in that order */
|
||||
if (ACT_RE[0].test(t)) out.push({ i, lvl: 0, label: t.slice(0, 60) });
|
||||
else if (ACT_RE[1].test(t)) out.push({ i, lvl: 0, label: t.match(ACT_RE[1])[0] });
|
||||
else if (ACT_RE[2].test(t)) out.push({ i, lvl: 1, label: 'ust. ' + t.match(/^\d+[a-z]?/)[0] });
|
||||
else if (ACT_RE[3].test(t)) out.push({ i, lvl: 2, label: 'pkt ' + t.match(/^\d+[a-z]?/)[0] });
|
||||
else if (ACT_RE[1].test(t)) out.push({ i, lvl: 0, art: true, label: t.match(ACT_RE[1])[0] });
|
||||
else if (ACT_RE[2].test(t)) out.push({ i, lvl: 1, label: t.match(ACT_RE[2])[0] });
|
||||
else if (ACT_RE[3].test(t)) out.push({ i, lvl: 1, label: 'ust. ' + t.match(/^\d+[a-z]?/)[0] });
|
||||
else if (ACT_RE[4].test(t)) out.push({ i, lvl: 2, label: 'pkt ' + t.match(/^\d+[a-z]?/)[0] });
|
||||
} else if (RULING_RE.test(t) || (t.length < 60 && t === t.toUpperCase() && /[A-ZĄĆĘŁŃÓŚŹŻ]{4}/.test(t))) {
|
||||
out.push({ i, lvl: 0, label: t.slice(0, 60) });
|
||||
}
|
||||
@@ -1126,9 +1171,7 @@ function articleLine(lines, art) {
|
||||
const key = String(art || '').replace(/\s+/g, '').toLowerCase();
|
||||
if (!key) return -1;
|
||||
return lines.findIndex((ln) => {
|
||||
/* dziennik-ustaw-md texts carry their article headings as Markdown ("##### Art. 52."), so the
|
||||
heading marks and emphasis are skipped before the label. */
|
||||
const m = ln.trim().replace(/^[#>*_\s]+/, '').match(/^(?:Art\.|Artyku[łl]|Article)\s*(\d+[a-z]?[¹²³⁰-⁹]*)/i);
|
||||
const m = plainLine(ln).match(/^(?:Art\.|Artyku[łl]|Article)\s*(\d+[a-z]?[¹²³⁰-⁹]*)/i);
|
||||
return !!m && m[1].toLowerCase() === key;
|
||||
});
|
||||
}
|
||||
@@ -1148,15 +1191,21 @@ async function viewDocument(C, route, q) {
|
||||
const anchors = new Set(outline.map((o) => o.i));
|
||||
const artLine = articleLine(lines, q.art);
|
||||
if (artLine >= 0) anchors.add(artLine);
|
||||
const body = lines.map((ln, i) => (anchors.has(i) ? `<span class="anchor${i === artLine ? ' hit' : ''}" id="ln${i}">${esc(ln)}</span>` : esc(ln))).join('\n');
|
||||
/* a Markdown heading line is shown as a heading, its "#####" dropped */
|
||||
const shown = (ln) => (/^\s*#{1,6}\s/.test(ln) ? `<span class="mdh">${esc(plainLine(ln))}</span>` : esc(ln));
|
||||
const body = lines.map((ln, i) => (anchors.has(i) ? `<span class="anchor${i === artLine ? ' hit' : ''}" id="ln${i}">${shown(ln)}</span>` : shown(ln))).join('\n');
|
||||
/* Plain links, never an inline handler: the route comes from the URL, and esc() is HTML
|
||||
escaping — the browser decodes it again before a handler's JavaScript runs. */
|
||||
const pageLink = (n, label, off) => (off ? `<button class="btn sm" disabled>${label}</button>`
|
||||
: `<a class="btn sm" href="${esc(routeHash(route))}?part=${n}">${label}</a>`);
|
||||
const pager = t.parts > 1 ? `<div class="row" style="gap:8px;margin:10px 0">
|
||||
<button class="btn sm" ${t.part <= 1 ? 'disabled' : ''} onclick="location.hash='${esc(routeHash(route))}?part=${t.part - 1}'">←</button>
|
||||
${pageLink(t.part - 1, '←', t.part <= 1)}
|
||||
<span class="faint tiny"><span>Część</span> ${esc(String(t.part))}/${esc(String(t.parts))}</span>
|
||||
<button class="btn sm" ${t.part >= t.parts ? 'disabled' : ''} onclick="location.hash='${esc(routeHash(route))}?part=${t.part + 1}'">→</button></div>` : '';
|
||||
${pageLink(t.part + 1, '→', t.part >= t.parts)}</div>` : '';
|
||||
let textBlock;
|
||||
if (t.text_status === 'ready' && t.text) {
|
||||
textBlock = `<div class="docgrid">
|
||||
<nav class="card outline" aria-label="Spis treści">${outline.length ? outline.map((o) => `<a class="l${o.lvl}" onclick="jumpTo(${o.i})">${esc(o.label)}</a>`).join('') : '<div class="faint tiny">—</div>'}</nav>
|
||||
<nav class="card outline" aria-label="Spis treści">${outline.length ? outline.map((o) => `<a class="l${o.lvl}${o.art ? ' art' : ''}" onclick="jumpTo(${o.i})">${esc(o.label)}</a>`).join('') : '<div class="faint tiny">—</div>'}</nav>
|
||||
<div class="card">${pager}<div class="doctext" data-no-i18n>${body}</div>${pager}</div></div>`;
|
||||
} else if (t.text_status === 'pending') {
|
||||
textBlock = `<div class="banner warn">OCR w toku — ten akt jest opublikowany tylko jako PDF; tekst pojawi się po rozpoznaniu.
|
||||
@@ -1166,7 +1215,7 @@ async function viewDocument(C, route, q) {
|
||||
textBlock = `<div class="banner warn">${esc(t.error || 'Dokument jest zbyt duży, by pokazać go w podglądzie.')}
|
||||
${t.text_url ? `<a class="btn sm" href="${esc(t.text_url)}" target="_blank" rel="noopener noreferrer">${svg(ICN.external)}EUR-Lex</a>` : ''}</div>`;
|
||||
} else {
|
||||
textBlock = `<div class="banner err">Tekst niedostępny${t.error ? ': ' + esc(t.error) : ''}.</div>`;
|
||||
textBlock = `<div class="banner err"><span>Tekst niedostępny</span>${t.error ? ': ' + esc(t.error) : ''}.</div>`;
|
||||
}
|
||||
if (t.truncated && t.text) {
|
||||
textBlock = `<div class="banner warn">Tekst skrócony — dokument przekracza limit importu; pełna wersja w EUR-Lex.
|
||||
@@ -1409,9 +1458,9 @@ async function viewSources(C) {
|
||||
${rows.map((s) => `<tr>
|
||||
<td><div><b>${esc(SOURCE_LABEL[s.name] || s.name)}</b>${s.attribution ? `<div class="faint tiny">${esc(s.attribution)}</div>` : ''}${s.capabilities && s.capabilities.policy ? `<div class="faint tiny">${esc(s.capabilities.policy)}</div>` : ''}</div></td>
|
||||
<td${lbl('Stan')}>${stateChip(s)}</td>
|
||||
<td class="tiny"${lbl('Zakres')}>${esc([s.jurisdiction && s.jurisdiction.toUpperCase(), (s.kinds || []).map((k) => KIND_LABEL[k]).join(', ')].filter(Boolean).join(' · ') || '—')}</td>
|
||||
<td class="tiny"${lbl('Zakres')}>${[s.jurisdiction && esc(s.jurisdiction.toUpperCase()), (s.kinds || []).map((k) => `<span>${esc(KIND_LABEL[k])}</span>`).join(', ')].filter(Boolean).join(' · ') || '—'}</td>
|
||||
<td${lbl('Pełny tekst')}>${s.capabilities ? (s.capabilities.full_text ? 'tak' : 'tylko tytuły') : '—'}</td>
|
||||
<td class="tiny"${lbl('Tempo')}>${s.rate_per_s ? esc(String(s.rate_per_s)) + ' zap./s' : '—'}</td>
|
||||
<td class="tiny"${lbl('Tempo')}>${s.rate_per_s ? esc(String(s.rate_per_s)) + ' <span>zap./s</span>' : '—'}</td>
|
||||
</tr>`).join('')}</tbody></table></div>
|
||||
<div class="faint tiny" style="padding:10px 2px 2px">Przełączniki źródeł ustawia się w konfiguracji wdrożenia (INSIDER_SOURCE_ELI / _SAOS / _EURLEX); tu są tylko do odczytu.</div></div>`
|
||||
+ datasetsCard(await api('GET', '/sources/datasets').catch(() => null));
|
||||
@@ -1466,7 +1515,7 @@ async function viewTokens(C) {
|
||||
<td class="acts-cell">${t.revoked_at ? '' : `<button class="btn sm danger" onclick="revokeToken('${esc(t.id)}')">${svg(ICN.trash)}Unieważnij</button>`}</td></tr>`).join('')}
|
||||
</tbody></table></div>` : '<div class="empty">Brak tokenów.</div>'}</div>`
|
||||
+ `<div class="card"><h3>Konfiguracja MCP</h3>
|
||||
<div class="tiny">Adres serwera: <span class="mono" data-no-i18n>${esc(mcpUrl())}</span> — narzędzia: search_acts, search_judgments, get_act, get_judgment, resolve_citation.</div>
|
||||
<div class="tiny">Adres serwera: <span class="mono" data-no-i18n>${esc(mcpUrl())}</span> — <span>narzędzia:</span> search_acts, search_judgments, get_act, get_judgment, resolve_citation.</div>
|
||||
${mcpConfigs('insider_pat_…')}</div>`;
|
||||
}
|
||||
|
||||
@@ -1508,6 +1557,8 @@ function confirmRevokeToken(id) {
|
||||
/* ── administration ─────────────────────────────────────────────────────── */
|
||||
async function viewAdmin(C) {
|
||||
setCrumb([{ label: 'Administracja' }]);
|
||||
/* the roster is a moderator's screen: fetched here, never at sign-in for everybody */
|
||||
state.users = await api('GET', '/users').catch(() => []);
|
||||
const audit = await api('GET', '/admin/audit?limit=50').catch(() => []);
|
||||
const ai = (await api('GET', '/admin/settings').catch(() => [])).filter((x) => x.key.startsWith('ai_'));
|
||||
const AI_LABEL = { ai_query_rewrite: 'Przepisywanie zapytań przez model', ai_answers: 'Odpowiedzi z cytatami',
|
||||
@@ -1595,8 +1646,8 @@ function closeModal() {
|
||||
|
||||
function modal(title, sub, bodyHtml, actionsHtml, opts) {
|
||||
$('modalRoot').innerHTML = `<div class="scrim" onclick="if(event.target===this)closeModal()">
|
||||
<div class="modal ${opts && opts.wide ? 'wide' : ''}" role="dialog" aria-modal="true">
|
||||
<h3>${esc(title)}</h3>${sub ? `<div class="msub">${esc(sub)}</div>` : ''}
|
||||
<div class="modal ${opts && opts.wide ? 'wide' : ''}" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
|
||||
<h3 id="modalTitle">${esc(title)}</h3>${sub ? `<div class="msub">${esc(sub)}</div>` : ''}
|
||||
<div id="modalBody">${bodyHtml}</div>
|
||||
<div class="acts">${actionsHtml}</div>
|
||||
</div></div>`;
|
||||
@@ -1711,5 +1762,6 @@ window.addEventListener('DOMContentLoaded', () => {
|
||||
});
|
||||
|
||||
localize(document.body);
|
||||
localizeChrome();
|
||||
restore();
|
||||
});
|
||||
|
||||
+10
-6
@@ -567,9 +567,12 @@
|
||||
});
|
||||
var shown = g.kind === 'structure' ? g.shown : g.nodes.length;
|
||||
var total = g.kind === 'structure' ? g.total : g.nodes.length;
|
||||
var note = el('div', 'g-3d-note', (g.truncated
|
||||
? 'pokazano ' + shown + (g.kind === 'structure' ? ' z ' + total : '') + ' węzłów (limit ' + g.cap + ')'
|
||||
: shown + ' węzłów') + ' · ' + g.edges.length + ' krawędzi');
|
||||
/* words and numbers in spans of their own (same order in both languages), so localize() reaches the words */
|
||||
var parts = g.truncated
|
||||
? ['pokazano', ' ' + shown + ' '].concat(g.kind === 'structure' ? ['z', ' ' + total + ' '] : [], ['węzłów', ' (limit ' + g.cap + ')'])
|
||||
: [shown + ' ', 'węzłów'];
|
||||
var note = el('div', 'g-3d-note');
|
||||
parts.concat([' · ' + g.edges.length + ' ', 'krawędzi']).forEach(function (p) { note.appendChild(el('span', null, p)); });
|
||||
w.appendChild(tools); w.appendChild(key); w.appendChild(note); w.appendChild(tip);
|
||||
var mx = 0, my = 0;
|
||||
function place() {
|
||||
@@ -586,8 +589,8 @@
|
||||
if (!n) { tip.hidden = true; return; }
|
||||
tip.textContent = '';
|
||||
tip.appendChild(el('b', null, n.title || n.label || n.id));
|
||||
var info = n.t === 'art' ? 'cytowany przez ' + (n.cited_by || 0) + ' · odwołania ' + (n.refs_out || 0)
|
||||
: n.t === 'unit' ? (n.arts || 0) + ' art.' : n.t === 'linked' ? n.weight + ' odesłań'
|
||||
var info = n.t === 'art' ? tr('cytowany przez') + ' ' + (n.cited_by || 0) + ' · ' + tr('odwołania') + ' ' + (n.refs_out || 0)
|
||||
: n.t === 'unit' ? (n.arts || 0) + ' art.' : n.t === 'linked' ? n.weight + ' ' + tr('odesłań')
|
||||
: n.w_in != null ? (n.w_in || 0) + ' ← · → ' + (n.w_out || 0) : '';
|
||||
if (info) tip.appendChild(el('div', 'faint', info));
|
||||
place();
|
||||
@@ -694,7 +697,8 @@
|
||||
'Nie udało się wczytać widoku 3D — zostaje widok 2D.': 'The 3D view could not be loaded — staying in 2D.',
|
||||
'akt': 'the act', 'działy i rozdziały': 'parts and chapters', 'artykuły (wielkość = cytowania)': 'articles (size = citations)',
|
||||
'akty powiązane': 'linked acts', 'orzeczenia cytujące': 'citing judgments', 'akty (wielkość = PageRank)': 'acts (size = PageRank)',
|
||||
'Struktura aktu w 3D': 'Act structure in 3D', 'Graf powiązań między aktami w 3D': 'Graph of links between acts in 3D'
|
||||
'Struktura aktu w 3D': 'Act structure in 3D', 'Graf powiązań między aktami w 3D': 'Graph of links between acts in 3D',
|
||||
'pokazano': 'showing', 'z': 'of', 'węzłów': 'nodes', 'krawędzi': 'edges', 'odesłań': 'references'
|
||||
};
|
||||
var LANG = 'pl';
|
||||
try { LANG = localStorage.getItem('insider_lang') === 'en' ? 'en' : 'pl'; } catch (e) { /* blocked */ }
|
||||
|
||||
+116
-48
@@ -108,17 +108,44 @@
|
||||
var data = prepare(g, p);
|
||||
SPHERE = SPHERE || new THREE.SphereGeometry(1, 14, 10);
|
||||
SPHERE_LO = SPHERE_LO || new THREE.SphereGeometry(1, 7, 5); /* the small majority: a fifth of the triangles */
|
||||
var mats = {}, hlMats = {};
|
||||
function mat(col, hl) {
|
||||
var cache = hl ? hlMats : mats;
|
||||
if (!cache[col]) {
|
||||
/* the colour pushed ABOVE 1.0: the excess is what the bloom turns into a corona — the
|
||||
"stars" look (legal-memory's NodeCloud boost); without bloom it just clamps to the hue */
|
||||
var c = new THREE.Color(col), br = (c.r + c.g + c.b) / 3;
|
||||
c.multiplyScalar((1.2 + br * 0.8) * (hl ? 1.5 : 1));
|
||||
cache[col] = new THREE.MeshBasicMaterial({ color: c, transparent: true, opacity: 1, toneMapped: false });
|
||||
}
|
||||
return cache[col];
|
||||
/* every sphere is an instance of ONE of two InstancedMeshes (big / small): two draw calls
|
||||
instead of one per node (2,500 at the cap). The per-node Group that 3d-force-graph places
|
||||
carries only what is rare — a label, a fallback halo — and our own raycast does the picking. */
|
||||
var glow = {};
|
||||
function glowColor(col) {
|
||||
/* the colour pushed ABOVE 1.0: the excess is what the bloom turns into a corona — the
|
||||
"stars" look (legal-memory's NodeCloud boost); without bloom it just clamps to the hue */
|
||||
if (!glow[col]) { var c = new THREE.Color(col), br = (c.r + c.g + c.b) / 3; glow[col] = c.multiplyScalar(1.2 + br * 0.8); }
|
||||
return glow[col];
|
||||
}
|
||||
var nodeMat = new THREE.MeshBasicMaterial({ color: 0xffffff, toneMapped: false });
|
||||
var inst = [SPHERE, SPHERE_LO].map(function (geo, k) {
|
||||
var list = data.nodes.filter(function (n) { return (n.r < 2.2) === (k === 1); });
|
||||
var m = new THREE.InstancedMesh(geo, nodeMat, Math.max(1, list.length));
|
||||
m.count = list.length; m.frustumCulled = false; m.userData.list = list;
|
||||
list.forEach(function (n, i) { n.__inst = m; n.__i = i; });
|
||||
return m;
|
||||
});
|
||||
var tmpM = new THREE.Matrix4(), tmpC = new THREE.Color();
|
||||
function syncNodes() {
|
||||
inst.forEach(function (m) {
|
||||
m.userData.list.forEach(function (n, i) {
|
||||
var r = n.r;
|
||||
tmpM.makeScale(r, r, r).setPosition(n.x || 0, n.y || 0, n.z || 0);
|
||||
m.setMatrixAt(i, tmpM);
|
||||
});
|
||||
m.instanceMatrix.needsUpdate = true;
|
||||
m.computeBoundingSphere();
|
||||
});
|
||||
}
|
||||
function paintNodes() { /* the hovered neighbourhood brighter, everything else dimmed */
|
||||
inst.forEach(function (m) {
|
||||
m.userData.list.forEach(function (n, i) {
|
||||
var k = !hover ? 1 : hoverNodes.has(n) ? 1.5 : 0.18;
|
||||
m.setColorAt(i, tmpC.copy(glowColor(n.col)).multiplyScalar(k));
|
||||
});
|
||||
if (m.instanceColor) m.instanceColor.needsUpdate = true;
|
||||
});
|
||||
}
|
||||
var haloMats = {};
|
||||
function haloMat(col) {
|
||||
@@ -135,8 +162,6 @@
|
||||
|
||||
function nodeObject(n) {
|
||||
var grp = new THREE.Group();
|
||||
var m = new THREE.Mesh(n.r < 2.2 ? SPHERE_LO : SPHERE, mat(n.col)); m.scale.setScalar(n.r);
|
||||
grp.add(m); n.__mesh = m;
|
||||
if (!hooks.Bloom && (haloSet[n.id] || n.t === 'act')) { /* the fallback glow */
|
||||
var h = new THREE.Sprite(haloMat(n.col)); h.scale.setScalar(n.r * 4.2); grp.add(h);
|
||||
}
|
||||
@@ -177,23 +202,14 @@
|
||||
.backgroundColor(p.bg)
|
||||
.showNavInfo(false)
|
||||
.nodeLabel(null).linkLabel(null)
|
||||
.enablePointerInteraction(false) /* its per-frame raycast over every node object: ours is below */
|
||||
.nodeId('id')
|
||||
.nodeThreeObject(nodeObject)
|
||||
.nodeThreeObjectExtend(false)
|
||||
.linkColor(function (l) {
|
||||
if (hover && hoverLinks.has(l)) return LC.hl;
|
||||
return LC[l.t] || LC.ref;
|
||||
})
|
||||
.linkWidth(function (l) { return hover && hoverLinks.has(l) ? 0.6 : (l.t === 'deleg' ? 0.5 : 0); })
|
||||
.linkOpacity(1)
|
||||
/* every edge is drawn by ONE merged LineSegments (below): 3d-force-graph would make one
|
||||
draw call per edge (5,500 at the cap). Its own link objects exist only for the hovered
|
||||
node's edges, which carry the highlight and the directional particles. */
|
||||
.linkVisibility(function (l) { return !!hover && hoverLinks.has(l); })
|
||||
.linkDirectionalParticles(function (l) { return !reduced && hover && hoverLinks.has(l) && l.t !== 'tree' ? 3 : 0; })
|
||||
.linkDirectionalParticleWidth(1.6)
|
||||
.linkDirectionalParticleSpeed(0.008)
|
||||
.linkDirectionalParticleColor(function () { return '#ffffff'; })
|
||||
/* every edge is drawn by ONE merged LineSegments, the hovered node's edges by a second small
|
||||
one (below). 3d-force-graph draws none: its link objects would be one draw call per edge
|
||||
(5,500 at the cap), and changing any link accessor on hover re-digests all of them. */
|
||||
.linkVisibility(false)
|
||||
.warmupTicks(g.kind === 'structure' ? 60 : 30)
|
||||
.cooldownTicks(reduced ? 80 : 220)
|
||||
.d3VelocityDecay(0.32)
|
||||
@@ -212,6 +228,8 @@
|
||||
|
||||
var scene = Graph.scene(), renderer = Graph.renderer(), controls = Graph.controls();
|
||||
scene.fog = new THREE.FogExp2(p.bg, 0.0011);
|
||||
inst.forEach(function (m) { scene.add(m); });
|
||||
paintNodes();
|
||||
var segPos = new Float32Array(data.links.length * 6), segCol = new Float32Array(data.links.length * 6);
|
||||
data.links.forEach(function (l, i) {
|
||||
var c = new THREE.Color(LC[l.t] || LC.ref);
|
||||
@@ -225,19 +243,45 @@
|
||||
var segs = new THREE.LineSegments(segGeo, segMat);
|
||||
segs.frustumCulled = false;
|
||||
scene.add(segs);
|
||||
function syncSegs() {
|
||||
data.links.forEach(function (l, i) {
|
||||
/* the hovered node's edges: their own segments, rebuilt on hover — never the whole link set */
|
||||
var hlGeo = new THREE.BufferGeometry(), hlList = [];
|
||||
var hlMat = new THREE.LineBasicMaterial({ color: new THREE.Color(LC.hl), transparent: true, depthWrite: false,
|
||||
blending: THREE.AdditiveBlending, toneMapped: false });
|
||||
var hlSegs = new THREE.LineSegments(hlGeo, hlMat);
|
||||
hlSegs.frustumCulled = false; hlSegs.renderOrder = 5;
|
||||
scene.add(hlSegs);
|
||||
function fill(pos, list) {
|
||||
list.forEach(function (l, i) {
|
||||
var a = l.source, b = l.target;
|
||||
if (typeof a !== 'object' || a.x === undefined) return;
|
||||
segPos[i * 6] = a.x; segPos[i * 6 + 1] = a.y; segPos[i * 6 + 2] = a.z;
|
||||
segPos[i * 6 + 3] = b.x; segPos[i * 6 + 4] = b.y; segPos[i * 6 + 5] = b.z;
|
||||
pos[i * 6] = a.x; pos[i * 6 + 1] = a.y; pos[i * 6 + 2] = a.z;
|
||||
pos[i * 6 + 3] = b.x; pos[i * 6 + 4] = b.y; pos[i * 6 + 5] = b.z;
|
||||
});
|
||||
segGeo.attributes.position.needsUpdate = true;
|
||||
}
|
||||
function syncHl() {
|
||||
if (!hlList.length) { hlSegs.visible = false; return; }
|
||||
var pos = new Float32Array(hlList.length * 6);
|
||||
fill(pos, hlList);
|
||||
hlGeo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
|
||||
hlSegs.visible = true;
|
||||
}
|
||||
function syncSegs() {
|
||||
fill(segPos, data.links);
|
||||
segGeo.attributes.position.needsUpdate = true;
|
||||
if (hlList.length) syncHl();
|
||||
}
|
||||
/* a 4K or hi-DPI screen would render (and bloom) up to 9x the pixels of a 1x one: 1.5x is sharp
|
||||
enough for points and lines, and the glow is a blur anyway, so it runs at half of that */
|
||||
var PR = Math.min(window.devicePixelRatio || 1, 1.5);
|
||||
renderer.setPixelRatio(PR);
|
||||
var bloom = null;
|
||||
if (hooks.Bloom) {
|
||||
bloom = new hooks.Bloom(new THREE.Vector2(box.clientWidth, box.clientHeight), 1.0, 0.55, 0.3);
|
||||
Graph.postProcessingComposer().addPass(bloom);
|
||||
var composer = Graph.postProcessingComposer();
|
||||
if (composer.setPixelRatio) composer.setPixelRatio(PR);
|
||||
bloom = new hooks.Bloom(new THREE.Vector2(box.clientWidth / 2, box.clientHeight / 2), 1.0, 0.55, 0.3);
|
||||
var bloomSize = bloom.setSize.bind(bloom);
|
||||
bloom.setSize = function (w, h) { bloomSize(Math.max(1, w / 2), Math.max(1, h / 2)); };
|
||||
composer.addPass(bloom);
|
||||
/* measured: through 3d-force-graph's composer the colours already arrive encoded, so an sRGB
|
||||
output here would encode them twice (the background turns slate grey) */
|
||||
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
|
||||
@@ -253,14 +297,14 @@
|
||||
waiting for its stop could leave the camera at its default distance) */
|
||||
var framed = false;
|
||||
Graph.onEngineTick(function () {
|
||||
syncSegs();
|
||||
syncSegs(); syncNodes();
|
||||
if (framed) return;
|
||||
var far = 0;
|
||||
data.nodes.forEach(function (n) { if (n.x !== undefined) far = Math.max(far, Math.hypot(n.x, n.y, n.z)); });
|
||||
if (far > 20) { framed = true; fit(0); patchLinks(); }
|
||||
});
|
||||
Graph.onEngineStop(function () {
|
||||
syncSegs();
|
||||
syncSegs(); syncNodes();
|
||||
patchLinks();
|
||||
if (!fitted) { fitted = true; fit(reduced ? 0 : 700); }
|
||||
var R = 1;
|
||||
@@ -270,36 +314,58 @@
|
||||
|
||||
function setHover(n) {
|
||||
if (hover === n) return;
|
||||
if (hover) { hoverNodes.forEach(function (x) { if (x.__mesh) x.__mesh.material = mat(x.col); hideLabel(x); }); }
|
||||
if (hover) { hoverNodes.forEach(function (x) { hideLabel(x); }); }
|
||||
hoverLinks = new Set(); hoverNodes = new Set();
|
||||
hover = n || null;
|
||||
Object.keys(mats).forEach(function (k) { mats[k].opacity = hover ? 0.18 : 1; });
|
||||
segMat.opacity = hover ? 0.25 : 1;
|
||||
if (hover) {
|
||||
hoverNodes.add(hover);
|
||||
data.links.forEach(function (l) {
|
||||
if (l.source === hover || l.target === hover) { hoverLinks.add(l); hoverNodes.add(l.source); hoverNodes.add(l.target); }
|
||||
});
|
||||
hoverNodes.forEach(function (x) { if (x.__mesh) x.__mesh.material = mat(x.col, true); });
|
||||
showLabel(hover);
|
||||
}
|
||||
Graph.linkVisibility(Graph.linkVisibility()).linkColor(Graph.linkColor()).linkWidth(Graph.linkWidth())
|
||||
.linkDirectionalParticles(Graph.linkDirectionalParticles());
|
||||
patchLinks();
|
||||
paintNodes();
|
||||
hlList = Array.from(hoverLinks);
|
||||
syncHl();
|
||||
box.style.cursor = hover ? 'pointer' : '';
|
||||
if (hooks.onHover) hooks.onHover(hover);
|
||||
}
|
||||
Graph.onNodeHover(function (n) { setHover(n); });
|
||||
/* picking: one raycast against the two instanced meshes, at most once per frame */
|
||||
var ray = new THREE.Raycaster(), ndc = new THREE.Vector2(), canvas = renderer.domElement, pending = null, down = null;
|
||||
function pick(e) {
|
||||
var b = canvas.getBoundingClientRect();
|
||||
ndc.set((e.clientX - b.left) / b.width * 2 - 1, -(e.clientY - b.top) / b.height * 2 + 1);
|
||||
ray.setFromCamera(ndc, Graph.camera());
|
||||
var hits = ray.intersectObjects(inst, false);
|
||||
return hits.length ? hits[0].object.userData.list[hits[0].instanceId] : null;
|
||||
}
|
||||
function onMove(e) {
|
||||
if (pending) { pending = e; return; }
|
||||
pending = e;
|
||||
requestAnimationFrame(function () { var ev = pending; pending = null; if (!down) setHover(pick(ev)); });
|
||||
}
|
||||
function onDown(e) { down = { x: e.clientX, y: e.clientY }; }
|
||||
function onUp(e) {
|
||||
var d = down; down = null;
|
||||
if (!d || Math.hypot(e.clientX - d.x, e.clientY - d.y) > 5) return; /* a drag turned the camera */
|
||||
var n = pick(e);
|
||||
if (n) nodeClick(n); else if (controls) controls.autoRotate = false;
|
||||
}
|
||||
function onLeave() { down = null; setHover(null); }
|
||||
canvas.addEventListener('pointermove', onMove);
|
||||
canvas.addEventListener('pointerdown', onDown);
|
||||
canvas.addEventListener('pointerup', onUp);
|
||||
canvas.addEventListener('pointerleave', onLeave);
|
||||
var lastClick = { id: null, at: 0 };
|
||||
Graph.onNodeClick(function (n) {
|
||||
function nodeClick(n) {
|
||||
if (controls) controls.autoRotate = false;
|
||||
var now = Date.now();
|
||||
if (lastClick.id === n.id && now - lastClick.at < 400) { focus(n); lastClick.id = null; return; }
|
||||
lastClick = { id: n.id, at: now };
|
||||
select(n.id);
|
||||
if (hooks.onSelect) hooks.onSelect(n);
|
||||
});
|
||||
Graph.onBackgroundClick(function () { if (controls) controls.autoRotate = false; });
|
||||
}
|
||||
|
||||
function focus(n) {
|
||||
var d = 40 + n.r * 6, len = Math.hypot(n.x, n.y, n.z) || 1, k = 1 + d / len;
|
||||
@@ -339,7 +405,10 @@
|
||||
if (ro) ro.observe(box);
|
||||
|
||||
function dispose() {
|
||||
segGeo.dispose(); segMat.dispose();
|
||||
segGeo.dispose(); segMat.dispose(); hlGeo.dispose(); hlMat.dispose();
|
||||
canvas.removeEventListener('pointermove', onMove); canvas.removeEventListener('pointerdown', onDown);
|
||||
canvas.removeEventListener('pointerup', onUp); canvas.removeEventListener('pointerleave', onLeave);
|
||||
inst.forEach(function (m) { m.dispose(); }); nodeMat.dispose();
|
||||
if (ro) ro.disconnect();
|
||||
try { Graph.pauseAnimation(); } catch (e) { /* already gone */ }
|
||||
try { Graph._destructor(); } catch (e) { /* older builds */ }
|
||||
@@ -347,7 +416,6 @@
|
||||
if (o.geometry && o.geometry !== SPHERE && o.geometry !== SPHERE_LO) o.geometry.dispose();
|
||||
if (o.material && o.material.map && o.material.map !== HALO) o.material.map.dispose();
|
||||
});
|
||||
Object.keys(mats).concat(Object.keys(hlMats)).forEach(function (k) { (mats[k] || hlMats[k]).dispose(); });
|
||||
Object.keys(haloMats).forEach(function (k) { haloMats[k].dispose(); });
|
||||
if (bloom) bloom.dispose();
|
||||
try { renderer.dispose(); renderer.forceContextLoss(); } catch (e) { /* lost already */ }
|
||||
|
||||
+11
-8
@@ -2,6 +2,8 @@
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#181818" media="(prefers-color-scheme: dark)" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Insider — akty i orzecznictwo</title>
|
||||
<meta name="description" content="Insider — akty prawne i orzecznictwo (PL, UE) wprost ze źródeł." />
|
||||
@@ -25,8 +27,8 @@
|
||||
submit anyway. -->
|
||||
<div id="login" class="hidden">
|
||||
<div class="login-tools">
|
||||
<button class="iconbtn txt" id="btnLangLogin" title="Język" data-no-i18n>PL</button>
|
||||
<button class="iconbtn js-theme" id="btnThemeLogin" title="Motyw"></button>
|
||||
<button class="iconbtn txt" id="btnLangLogin" title="Język" aria-label="Język" data-no-i18n>PL</button>
|
||||
<button class="iconbtn js-theme" id="btnThemeLogin" title="Motyw" aria-label="Motyw"></button>
|
||||
</div>
|
||||
<form class="login-card" id="loginForm">
|
||||
<svg class="logo" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="5" fill="#099268"/><g stroke="#e6fcf5" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" fill="none"><path d="M7 12.5l3.2 3.2L17 9"/></g></svg>
|
||||
@@ -64,6 +66,7 @@
|
||||
</div>
|
||||
|
||||
<div id="app" class="hidden">
|
||||
<a class="skip" href="#content" onclick="event.preventDefault();document.getElementById('content').focus()">Przejdź do treści</a>
|
||||
<aside class="sidebar" id="sidebar">
|
||||
<div class="brand">
|
||||
<svg class="logo" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="5" fill="#099268"/><g stroke="#e6fcf5" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" fill="none"><path d="M7 12.5l3.2 3.2L17 9"/></g></svg>
|
||||
@@ -71,28 +74,28 @@
|
||||
<button class="iconbtn" id="navCollapse" title="Zwiń panel (Ctrl+B)" aria-label="Zwiń panel" aria-pressed="false"></button>
|
||||
</div>
|
||||
<nav class="nav" id="nav"></nav>
|
||||
<div class="nav sidebar-foot"><div class="nav-item" id="navAdmin"></div></div>
|
||||
<div class="nav sidebar-foot" id="navAdmin"></div>
|
||||
</aside>
|
||||
<div id="navScrim"></div>
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<button class="iconbtn" id="navToggle" title="Menu"></button>
|
||||
<button class="iconbtn" id="navToggle" title="Menu" aria-label="Menu"></button>
|
||||
<div class="crumb" id="crumb"></div>
|
||||
<div class="spacer"></div>
|
||||
<button class="searchbar js-tool" id="aSearch" title="Szukaj… (Ctrl+K)">
|
||||
<span class="si"></span><span class="sp">Szukaj…</span><kbd>Ctrl K</kbd>
|
||||
</button>
|
||||
<span class="vdiv js-tool"></span>
|
||||
<button class="iconbtn js-theme js-tool" id="aTheme" title="Motyw"></button>
|
||||
<button class="iconbtn txt js-tool" id="aLang" title="Język" data-no-i18n>PL</button>
|
||||
<button class="iconbtn js-theme js-tool" id="aTheme" title="Motyw" aria-label="Motyw"></button>
|
||||
<button class="iconbtn txt js-tool" id="aLang" title="Język" aria-label="Język" data-no-i18n>PL</button>
|
||||
<button type="button" class="avatar" id="aUser" title="Konto" aria-label="Konto" aria-haspopup="dialog">?</button>
|
||||
</header>
|
||||
<main class="content" id="content"></main>
|
||||
<main class="content" id="content" tabindex="-1"></main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="modalRoot"></div>
|
||||
<div id="toast"></div>
|
||||
<div id="toast" role="status" aria-live="polite"></div>
|
||||
|
||||
<script src="app.js"></script>
|
||||
<script src="ui/v1/shell.js" defer></script>
|
||||
|
||||
@@ -91,7 +91,7 @@ a:hover { text-decoration: underline; }
|
||||
}
|
||||
.nav-item .cnt.hot { background: var(--at-danger-soft); color: var(--at-danger-text); }
|
||||
.nav-sep {
|
||||
font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: .12em;
|
||||
font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .12em;
|
||||
color: var(--at-text-muted); padding: 20px 12px 8px;
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
}
|
||||
@@ -525,3 +525,20 @@ td.mono { font-family: var(--at-font-mono); font-size: 12.5px; }
|
||||
table.rt td.nowrap { white-space: normal; }
|
||||
.card .tablewrap { margin: 0; }
|
||||
}
|
||||
|
||||
/* ── usability pass (Web Interface Guidelines) ───────────────────────────────
|
||||
The page title is the page's h1 (one per screen, so a screen reader can jump to it); a skip link
|
||||
past the sidebar; no double-tap zoom delay on controls; a scroll inside a dialog, the drawer or a
|
||||
menu never drags the page behind it; 44px targets wherever the pointer is a finger. */
|
||||
.page-head h1 { margin: 0; font-size: 30px; font-weight: 600; line-height: 1.2; letter-spacing: var(--at-tracking-title); }
|
||||
@media (max-width: 640px) { .page-head h1 { font-size: 24px; } }
|
||||
.skip {
|
||||
position: fixed; left: 12px; top: -60px; z-index: 100; padding: 8px 14px;
|
||||
border-radius: var(--at-radius-lg); border: 1px solid var(--at-border-strong);
|
||||
background: var(--at-surface); color: var(--at-text); font-size: 14px;
|
||||
}
|
||||
.skip:focus { top: 12px; text-decoration: none; }
|
||||
button, a, input, select, textarea, label, summary { touch-action: manipulation; }
|
||||
.modal, .search-modal, .search-results, .waffle, .sidebar { overscroll-behavior: contain; }
|
||||
@media (pointer: coarse) { .iconbtn, .btn.sm { min-width: 44px; min-height: 44px; } }
|
||||
#content:focus { outline: none; } /* the skip link lands here; the page itself needs no ring */
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
--at-text-content: #1a1c1f;
|
||||
--at-text-secondary: #52525a;
|
||||
--at-text-muted: #6c6c76;
|
||||
--at-text-faint: #8f8f98;
|
||||
--at-text-faint: #737380; /* 4.7:1 on white (WCAG AA); #8f8f98 was 3.2 */
|
||||
--at-text-placeholder: #75757e;
|
||||
--at-text-inverse: #ffffff;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user