Polish lemmas from sjp.pl, a per-language analyzer registry, a legal thesaurus, partial matches, serve the old index during rebuilds, and per-source cron schedules
- app/integrations/analysis.py: one tokeniser, languages registered by ISO code; sjp.pl inflection list (CC BY 4.0) built into an mmap lexicon at image build, plstem as the fallback for unknown words. Morfeusz2 documented as an option. - thesaurus/pl.tsv: query-side, reviewed, variants weighted 0.5. - Partial matches (60% of content words) only when nothing matches fully, flagged. - textindex FORMAT 3; a format-2 index keeps answering until the rebuild swaps in. - croniter schedules per source, Europe/Warsaw, validated at startup; the *_INTERVAL_HOURS settings and the SAOS dump window are replaced. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+25
-9
@@ -115,34 +115,50 @@ INSIDER_CACHE_PURGE_SECONDS=3600
|
||||
INSIDER_INDEX_ENABLED=false
|
||||
# Where the indexes live; empty = <DATA_DIR>/index. Disposable: rebuilt from Postgres when missing.
|
||||
INSIDER_INDEX_DIR=
|
||||
# ── When each dataset updates: cron (min hour day month weekday), several joined by ";", read in
|
||||
# INSIDER_SCHEDULE_TZ. Every one is validated at startup — an invalid one refuses to start, naming
|
||||
# its variable. A run missed while the box was down happens once at the next tick.
|
||||
# The zone every schedule (and the SAOS first-import window) is read in; DST-aware.
|
||||
INSIDER_SCHEDULE_TZ=Europe/Warsaw
|
||||
# dziennik-ustaw-md: its bot commits ~05:00 UTC (07:00 Warsaw in summer) — 05:00 would be a day behind.
|
||||
INSIDER_DZU_MD_SCHEDULE="15 7 * * *"
|
||||
# ELI in-force acts: daily (one listing; only acts whose changeDate moved are fetched).
|
||||
INSIDER_ELI_INFORCE_SCHEDULE="0 5 * * *"
|
||||
# CELLAR acts: the daily delta (works CELLAR modified since the last pass).
|
||||
INSIDER_CELLAR_SCHEDULE="0 5 * * *"
|
||||
# CELLAR: the full listing pass (finds acts that left force) — Sundays.
|
||||
INSIDER_CELLAR_FULL_SCHEDULE="0 5 * * 0"
|
||||
# CELLAR CJEU case law (when INSIDER_CELLAR_CASELAW is on): the daily delta.
|
||||
INSIDER_CELLAR_CASELAW_SCHEDULE="0 5 * * *"
|
||||
# SAOS dump: the daily delta, once the first full import is done.
|
||||
INSIDER_SAOS_DUMP_SCHEDULE="0 5 * * *"
|
||||
# SAOS dump: the FIRST full import (several nights) runs only inside this window.
|
||||
INSIDER_SAOS_DUMP_FIRST_WINDOW=23:00-05:00
|
||||
# An index built another way (a deploy changed its format/analysis) is rebuilt then; the old one answers meanwhile. A missing one builds at once.
|
||||
INSIDER_INDEX_REBUILD_SCHEDULE="0 5 * * *"
|
||||
# dziennik-ustaw-md (CC0): Dz.U. 2025+ and older PDF-only acts as Markdown. One ~1 KB request per
|
||||
# check; a new commit fetches index.csv + the changed files (first sync ~7.2k files, ~30 min).
|
||||
INSIDER_DZU_MD_SYNC=true
|
||||
INSIDER_DZU_MD_SYNC_INTERVAL_HOURS=6
|
||||
INSIDER_DZU_MD_RATE=4
|
||||
INSIDER_DZU_MD_STALE_HOURS=72
|
||||
# The acts IN FORCE with their current consolidated text from ELI, where no CC0 mirror has it (the
|
||||
# codes and the major acts). Base acts of these ELI types; amending acts are skipped.
|
||||
INSIDER_ELI_INFORCE_SYNC=true
|
||||
INSIDER_ELI_INFORCE_INTERVAL_HOURS=24
|
||||
INSIDER_ELI_INFORCE_RATE=2
|
||||
INSIDER_ELI_INFORCE_TYPES=Ustawa,Konstytucja
|
||||
# SAOS's DUMP API — only this ingestor uses it, never a search. A UTC window (off-peak), one
|
||||
# request in flight, a pause between pages; resumable. The first full import takes days.
|
||||
# SAOS's DUMP API — only this ingestor uses it, never a search. One request in flight, a pause
|
||||
# between pages; resumable. The first full import takes days (INSIDER_SAOS_DUMP_FIRST_WINDOW).
|
||||
INSIDER_SAOS_DUMP_SYNC=true
|
||||
INSIDER_SAOS_DUMP_WINDOW=23:00-05:00
|
||||
INSIDER_SAOS_DUMP_PAGE_SIZE=100
|
||||
INSIDER_SAOS_DUMP_PAUSE_SECONDS=5
|
||||
INSIDER_SAOS_DUMP_INTERVAL_HOURS=20
|
||||
INSIDER_SAOS_INDEX_STALE_HOURS=96
|
||||
# CELLAR (EU law, anonymous — no EU Login account): every regulation, directive and decision IN
|
||||
# FORCE with the text of its newest consolidated version (Polish, else English), from the
|
||||
# Publications Office's SPARQL endpoint + the 303 text fetch. A full listing pass weekly, a delta
|
||||
# (CELLAR's modification dates) every interval; one request in flight, every redirect hop counted
|
||||
# Publications Office's SPARQL endpoint + the 303 text fetch. A full listing pass and a daily delta
|
||||
# (CELLAR's modification dates) on the schedules above; one request in flight, every redirect hop counted
|
||||
# against the rate (≤ 2). First import ~35k acts ≈ 20 h at 1 req/s; ~1 GB Postgres + ~0.3 GB index.
|
||||
# (Replaces INSIDER_EURLEX_DUMP_SYNC, which is gone; a leftover value is ignored.)
|
||||
INSIDER_CELLAR_SYNC=true
|
||||
INSIDER_CELLAR_INTERVAL_HOURS=24
|
||||
INSIDER_CELLAR_RATE=1
|
||||
INSIDER_CELLAR_STALE_HOURS=96
|
||||
# CJEU judgments (Court of Justice + General Court) from this date on — off by default
|
||||
|
||||
@@ -13,3 +13,5 @@ build/
|
||||
data/
|
||||
.DS_Store
|
||||
certs/
|
||||
# the language lexicons are BUILT (backend/scripts/build_lexicon.py), never committed
|
||||
backend/lexicon/
|
||||
|
||||
@@ -143,7 +143,7 @@ backend/app/
|
||||
· cursor (HMAC) · citations (regexes) · cache (LRU + source_cache, single-flight)
|
||||
· doctext (doc_text + ocr_job queue) · htmltext (sanitise, chunk) · runtime (singleton)
|
||||
· indexing (importers: dzu_md, eli_inforce, saos_dump, cellar ×2; run_loop)
|
||||
· indexstore (Pg + Memory; run lock) · textindex (tantivy) · window (UTC window)
|
||||
· indexstore (Pg + Memory; run lock) · textindex (tantivy) · window (a daily window) · schedule (cron)
|
||||
ocr/ engines (text layer, PaddleOCR, PaddleOCR-VL, Tesseract — import-guarded)
|
||||
· pipeline (tier selection, per-page escalation) · worker (queue; in-process or
|
||||
`python -m app.ocr.worker`)
|
||||
@@ -234,9 +234,31 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca
|
||||
alternations (sygnaliści/sygnalista, studenci, autorzy, prawnicy, biolodzy, sędzia/sędziów) are
|
||||
deliberately narrow — `tests/test_plstem.py` pins the look-alikes that must not merge (części,
|
||||
granicy, młodzy, narzędzi, lekarzy, żołnierzy).
|
||||
- **Language analysis goes through the analyzer registry** (`integrations/analysis.py`): `words()`
|
||||
is the ONE tokeniser; each language's `Analyzer` = a dictionary `Lemmatizer` (today
|
||||
`lexicon.Lexicon` over sjp.pl's inflection list, **CC BY 4.0** — never GPL/LGPL/MPL data) with the
|
||||
rule-based stemmer as the fallback (plstem for `pl`), chosen per document (`row["lang"]`,
|
||||
`TextIndex(langs=…)`). **Adding a language = a `DataPackage` in `analysis.PACKAGES` + a
|
||||
`register()` call** (+ optionally `thesaurus/<lang>.tsv`) — never a change to `textindex` or the
|
||||
importers. The lexicon is BUILT by `scripts/build_lexicon.py` in the Dockerfile (best effort; never
|
||||
committed — `backend/lexicon/` is ignored); tests build `tests/fixtures/odm_fixture.txt` in
|
||||
conftest, offline. An ambiguous form is ONE token (`mama|miec`, `lexicon.SEP`), so the text fields
|
||||
use tantivy's `whitespace` tokenizer. The thesaurus is query-side, hand-reviewed, lemmatised by the
|
||||
same analyzer; a variant weighs `EXPANSION_BOOST`. Partial matches (`PARTIAL_SHARE` of the words)
|
||||
answer only when no part holds every word, flagged `partial` + the `partial_matches` notice.
|
||||
`analysis.ident()` (stemmer version + lexicon build) is recorded in `index.json`.
|
||||
- **The previous index serves until its rebuild is swapped in.** `ready()` = can answer (a format in
|
||||
`READABLE`, today's `plstem.VERSION`); `current()` = built exactly as today's code builds it;
|
||||
`rebuild_pending()` = ready and not current. The rebuild goes into `<name>.new` and is renamed in,
|
||||
while searches read the old index with the schema and analysis of its own format (format 2 =
|
||||
plstem only). Between the two renames `_live()` serves `<name>.old`; a worker whose directory
|
||||
vanished under a search reopens and asks again. Importers write only into a `current()` index
|
||||
(`update()` refuses to mix analyses). Keep a format in `READABLE` until no box can still hold it.
|
||||
- **`textindex.FORMAT` guards what a document holds** the way `plstem.VERSION` guards the stems:
|
||||
bump it with any change to the fields or their analysis (an index of another format is not
|
||||
`ready()`, and `ensure_index` rebuilds it from Postgres). Format 2 (2026-10-21): the title is the
|
||||
`current()`, and `ensure_index` rebuilds it from Postgres while the old one still answers if its
|
||||
format is in `READABLE`). Format 3 (2026-10-21): analysis terms (lemmas, `a|b` ambiguity tokens),
|
||||
the `whitespace` tokenizer, each row in its own language. Format 2 (2026-10-21): the title is the
|
||||
act's NAME (`dzu_md.search_title`, no notice boilerplate), plus `head` (a carried chapter heading)
|
||||
and `lead` (the first sentence) fields, the body keeps function words (positions for the exact
|
||||
phrase; a query never MATCHES on them), and a stored `prior` (`dzu_md.act_prior`: codes up;
|
||||
@@ -247,6 +269,18 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca
|
||||
rebuilds it from hand-downloaded files) — run `python tests/search_eval.py` for the top-3 table
|
||||
after any ranking change. `plstem.STOPWORDS` are true function words only; `eurlex.FTS_COMMON`
|
||||
("umowa", "prawo"…) is CELLAR SPARQL's list and never the local index's.
|
||||
- **Every dataset has its OWN cron variable; there is no interval and no shared default**
|
||||
(`services/schedule.py`, croniter MIT + tzdata Apache-2.0): `INSIDER_DZU_MD_SCHEDULE`,
|
||||
`_ELI_INFORCE_`, `_CELLAR_`, `_CELLAR_FULL_`, `_CELLAR_CASELAW_`, `_SAOS_DUMP_`, `_INDEX_REBUILD_`
|
||||
`SCHEDULE`, plus `INSIDER_SAOS_DUMP_FIRST_WINDOW`, all read in `INSIDER_SCHEDULE_TZ`
|
||||
(Europe/Warsaw). `config.py` validates every one at startup and names the variable. Due = the
|
||||
last fire time is after the last start (`attempted_at`), so a missed run happens ONCE. Croniter
|
||||
steps through naive wall time and only then is a fire placed in the zone (its own tz arithmetic
|
||||
slipped an hour across DST — `tests/test_schedule.py` pins both changes). dzu_md runs at 07:15,
|
||||
not 05:00: its upstream bot commits ~05:00 UTC. A delta only `update()`s the changed groups; a
|
||||
rebuild for another format / analysis waits for `INSIDER_INDEX_REBUILD_SCHEDULE` (the old index
|
||||
answers; imports write Postgres only meanwhile, `index_writable()`), a missing index builds at
|
||||
once. Outage notices (`legal.outage_notices`) only when a local source truly cannot serve.
|
||||
- **An interrupted import resumes in minutes, not an interval later** (`indexing.unfinished`,
|
||||
`RESUME_AFTER`): the box's first `eli_inforce` pass stopped at 57 of 2 411 acts on a deploy and
|
||||
`due()` waited 24 h. `eli_inforce` also waits for `dzu_md`'s FIRST full pass (`after=`) and is due
|
||||
|
||||
@@ -47,6 +47,12 @@ Deliberately **not** used: Surya (GPL + restricted weights), MinerU (AGPL), mark
|
||||
| SAOS (`saos.org.pl`) | its robots.txt disallows `/api/` — used only for user-initiated live queries (README, "SAOS") | "Źródło: SAOS — System Analizy Orzeczeń Sądowych" |
|
||||
| EUR-Lex / CELLAR (`publications.europa.eu`) | Commission Decision 2011/833/EU: commercial and non-commercial reuse; metadata CC0, consolidated texts CC BY 4.0 | "© European Union, https://eur-lex.europa.eu …", plus a note on every EU text that Insider converted it to plain text (CC BY 4.0 asks that changes be indicated) |
|
||||
|
||||
## Language data
|
||||
|
||||
| Data | Licence | What Insider does with it |
|
||||
|---|---|---|
|
||||
| [Słownik SJP.PL — lista słów z odmianami](https://sjp.pl/sl/odmiany/) (sjp.pl) | offered under GPL 2, LGPL 2.1, **CC BY 4.0** or Apache 2.0; Insider uses it under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | downloaded while the image is built (`backend/scripts/build_lexicon.py`) and **changed**: proper names, multi-word entries and negated "nie…" forms under a positive headword dropped; forms lower-cased and diacritic-folded; a headword whose whole paradigm sits inside another's keeps its own lemma; stored as a binary form → lemma(s) table. Only an 80-line verbatim subset is committed, as a test fixture (`backend/tests/fixtures/odm_fixture.txt`) |
|
||||
|
||||
## Patterns borrowed (no code, no dependency)
|
||||
|
||||
| Project | License | What |
|
||||
|
||||
@@ -73,19 +73,43 @@ ELI and EUR-Lex search only **titles**, SAOS searches **full text** — so witho
|
||||
query ("najem okazjonalny", "przekroczenie prędkości") finds judgments and no act at all. INDEXED mode
|
||||
fixes that with local datasets in Postgres and an embedded full-text index, **tantivy** (`tantivy`
|
||||
0.26.2 on PyPI, MIT; no server, no JVM), on disk under `INSIDER_INDEX_DIR` (default
|
||||
`<DATA_DIR>/index`). Text is stemmed in Python by the in-house `plstem` (folded diacritics, one
|
||||
ending off; a query word with a mobile e also matches its e-less form: *najem* ↔ *najmu*), one index
|
||||
document per **article** (acts) or per **section** (judgments), hits grouped per act / judgment, the
|
||||
`<DATA_DIR>/index`). Text is analysed in Python per language (see *Language analysis* below:
|
||||
dictionary lemmas from sjp.pl first, the in-house `plstem` stemmer for words the dictionary does
|
||||
not know), one index document per **article** (acts) or per **section** (judgments), hits grouped per act / judgment, the
|
||||
act's title weighted ×3 and the query words side by side ×2.
|
||||
|
||||
| Dataset | What | How |
|
||||
|---|---|---|
|
||||
| `dzu_md` | [`PolskiAgentW/dziennik-ustaw-md`](https://github.com/PolskiAgentW/dziennik-ustaw-md) (CC0 data, `eli2md` MIT): Dz.U. from 2025, PDF-only older acts, and **~4,900 consolidated texts (t.j.) 2012–26** | every `INSIDER_DZU_MD_SYNC_INTERVAL_HOURS` (6): one ~1 KB request for the branch head; a new commit fetches `index.csv` and only the acts whose PDF checksum / converter / conversion time changed, pinned to that commit, ≤ `INSIDER_DZU_MD_RATE` req/s, one at a time |
|
||||
| `dzu_md` | [`PolskiAgentW/dziennik-ustaw-md`](https://github.com/PolskiAgentW/dziennik-ustaw-md) (CC0 data, `eli2md` MIT): Dz.U. from 2025, PDF-only older acts, and **~4,900 consolidated texts (t.j.) 2012–26** | on `INSIDER_DZU_MD_SCHEDULE` (07:15 Warsaw — after the upstream bot's ~05:00 UTC commit): one ~1 KB request for the branch head; a new commit fetches `index.csv` and only the acts whose PDF checksum / converter / conversion time changed, pinned to that commit, ≤ `INSIDER_DZU_MD_RATE` req/s, one at a time |
|
||||
| `eli_inforce` | every act **in force** (`inForce=1`, types `INSIDER_ELI_INFORCE_TYPES`, base acts only) with its **current** consolidated text | daily: ELI's listing, then per act whose `changeDate` moved one metadata request; the text (`text.html`, else the PDF's text layer) only when no dataset has it yet. Older t.j. are flagged **superseded** — kept, never searched (for every act held in several texts, whichever dataset holds them). Waits for `dzu_md`'s first full pass, then starts; an interrupted pass resumes ~10 min later |
|
||||
| `saos_dump` | SAOS's **dump API** (`/api/dump/judgments`) — metadata + sanitised text in sections | only in the off-peak UTC window `INSIDER_SAOS_DUMP_WINDOW` (23:00–05:00), one request in flight, `INSIDER_SAOS_DUMP_PAUSE_SECONDS` between pages, resumable from the stored cursor; the next pass asks `sinceModificationDate` = when the previous one started |
|
||||
| `cellar` | EU **regulations, directives and decisions in force** (CELEX sector 3, `resource_legal_in-force`), each with the text of its **newest consolidated version** (`0…-YYYYMMDD`), Polish — English when there is no Polish text, the language recorded | the Publications Office's anonymous CELLAR (no EU Login account — it replaced the planned EUR-Lex dump): SPARQL keyset-paged listing, the 303 → `resource/cellar` text fetch, one request in flight at `INSIDER_CELLAR_RATE` (≤ 2/s, every hop counted). A **full** pass weekly (acts it no longer lists are marked out of force — kept, never searched), a **delta** daily (works whose CELLAR `lastModificationDate`, or a consolidated version's, moved since the last pass). Cursor saved after every page |
|
||||
| `saos_dump` | SAOS's **dump API** (`/api/dump/judgments`) — metadata + sanitised text in sections | the first full import only inside `INSIDER_SAOS_DUMP_FIRST_WINDOW` (23:00–05:00 Warsaw, several nights), then a daily delta on `INSIDER_SAOS_DUMP_SCHEDULE`; one request in flight, `INSIDER_SAOS_DUMP_PAUSE_SECONDS` between pages, resumable from the stored cursor; the next pass asks `sinceModificationDate` = when the previous one started |
|
||||
| `cellar` | EU **regulations, directives and decisions in force** (CELEX sector 3, `resource_legal_in-force`), each with the text of its **newest consolidated version** (`0…-YYYYMMDD`), Polish — English when there is no Polish text, the language recorded | the Publications Office's anonymous CELLAR (no EU Login account — it replaced the planned EUR-Lex dump): SPARQL keyset-paged listing, the 303 → `resource/cellar` text fetch, one request in flight at `INSIDER_CELLAR_RATE` (≤ 2/s, every hop counted). A **full** pass on `INSIDER_CELLAR_FULL_SCHEDULE` (Sundays; acts it no longer lists are marked out of force — kept, never searched), a **delta** on `INSIDER_CELLAR_SCHEDULE` (daily) (works whose CELLAR `lastModificationDate`, or a consolidated version's, moved since the last pass). Cursor saved after every page |
|
||||
| `cellar_caselaw` | CJEU judgments (CJ, TJ) dated from `INSIDER_CELLAR_CASELAW_FROM` — **off by default** (`INSIDER_CELLAR_CASELAW`) | the same channel and cadence; cut into ~12k-character pieces |
|
||||
|
||||
**When it updates.** Every dataset has its own cron variable, read in `INSIDER_SCHEDULE_TZ`
|
||||
(default `Europe/Warsaw`, DST-aware); several expressions may be joined by `;`; an invalid one
|
||||
refuses to start, naming the variable; a run missed while the box was down happens once at the next
|
||||
tick. Everything updates once a day at 05:00 Polish time, except dziennik-ustaw-md at 07:15 (its bot
|
||||
commits around 05:00 UTC, so 05:00 Warsaw would always fetch the day before):
|
||||
|
||||
| Variable | Default | What |
|
||||
|---|---|---|
|
||||
| `INSIDER_SCHEDULE_TZ` | `Europe/Warsaw` | the zone of every schedule and of the SAOS first-import window |
|
||||
| `INSIDER_DZU_MD_SCHEDULE` | `15 7 * * *` | dziennik-ustaw-md: the branch head, then only what changed |
|
||||
| `INSIDER_ELI_INFORCE_SCHEDULE` | `0 5 * * *` | ELI in-force acts: the listing, then only acts whose `changeDate` moved |
|
||||
| `INSIDER_CELLAR_SCHEDULE` | `0 5 * * *` | CELLAR acts: the delta |
|
||||
| `INSIDER_CELLAR_FULL_SCHEDULE` | `0 5 * * 0` | CELLAR: the full listing pass (finds acts that left force) |
|
||||
| `INSIDER_CELLAR_CASELAW_SCHEDULE` | `0 5 * * *` | CJEU case law (when on): the delta |
|
||||
| `INSIDER_SAOS_DUMP_SCHEDULE` | `0 5 * * *` | SAOS: the daily delta, after the first full import |
|
||||
| `INSIDER_SAOS_DUMP_FIRST_WINDOW` | `23:00-05:00` | SAOS: the first full import runs only in this window |
|
||||
| `INSIDER_INDEX_REBUILD_SCHEDULE` | `0 5 * * *` | rebuilding an index of another format / analysis (the old one answers meanwhile); a missing index builds at once |
|
||||
|
||||
A delta writes only the changed documents into the index (delete by group, add, commit) — never a
|
||||
full rebuild. The Źródła page shows each dataset's last and next run. A notice ("Indeks aktów:
|
||||
aktualizacja w toku — wyniki z wyszukiwania na żywo", "… dane z dnia X …") appears only when a local
|
||||
source truly cannot serve (no index yet, a first import running, or data past its staleness
|
||||
threshold) — never during a delta or a rebuild, when the previous index answers.
|
||||
|
||||
**How search uses it.** A local source answers only when its index is built and its dataset has
|
||||
finished a first full import and synced within the staleness threshold (`INSIDER_DZU_MD_STALE_HOURS`,
|
||||
`INSIDER_SAOS_INDEX_STALE_HOURS`); otherwise its status line says `skipped` with the reason, and the
|
||||
@@ -134,6 +158,60 @@ consolidated version) → ~76k requests ≈ 21 h at 1 req/s (≈ 11 h at 2); mea
|
||||
(GDPR, DSA, AI Act…) 1.16 M characters → 0.9 MB of Postgres and 0.39 MB of index, so ≈ 0.6–1 GB +
|
||||
0.2–0.4 GB for the whole set. Case law since 2000: ~25.5k CJ/TJ judgments with a Polish version.
|
||||
|
||||
### Language analysis — lemmas, a legal thesaurus, partial matches
|
||||
|
||||
Every word reaches the index through `integrations/analysis.py`: one `Analyzer` per language in a
|
||||
registry keyed by ISO code and chosen **per document** (acts and SAOS judgments are `pl`; a CELLAR
|
||||
text records its language, so an English fallback text gets `en`). A Polish word goes to its
|
||||
**lemma** through a dictionary — *spółki*, *spółce*, *spółek* → `spolka`; *sądzie* → `sad`;
|
||||
*dzieci*, *dziećmi* → `dziecko`; *najmu* → `najem`; *szedł*, *idzie* → `isc` — and a word the
|
||||
dictionary does not know falls back to `plstem`. Diacritics are folded on both sides, as before, so
|
||||
"spolki" still finds "spółce".
|
||||
|
||||
* **The dictionary** is sjp.pl's inflection list ("Lista słów z odmianami",
|
||||
<https://sjp.pl/sl/odmiany/>), which sjp.pl offers under a choice of GPL 2, LGPL 2.1, **CC BY 4.0**
|
||||
or Apache 2.0 — Insider takes it under **CC BY 4.0** (credit in [`CREDITS.md`](CREDITS.md)). It is
|
||||
never committed: the image build downloads the current archive (two requests) and
|
||||
`scripts/build_lexicon.py` turns it into `lexicon/pl.lex`, a 60 MB sorted form → lemma file read
|
||||
through mmap (≈7 MB of heap, ~25 µs per uncached lookup, cached after). **Changes made to the
|
||||
data:** proper names and multi-word entries dropped; negated "nie…" forms under a positive headword
|
||||
dropped (they keep plstem's stem, so *niewykonanie* never meets *wykonanie*); lower-cased and
|
||||
diacritic-folded; where a headword's whole paradigm is listed inside another's (the verbal noun
|
||||
*wypowiedzenie* inside the verb *wypowiedzieć*), its forms keep their own lemma. Without network
|
||||
at build time the image still builds and search falls back to plstem.
|
||||
* **Ambiguity:** a form with several lemmas is indexed as one token naming them all
|
||||
(`mam` → `mam|mama|mamic|miec`, at most 4) at its own position — phrase and proximity are
|
||||
unchanged — and a query word asks for each of its lemmas OR every such token that names one.
|
||||
* **A legal thesaurus** (`app/integrations/thesaurus/pl.tsv`, query-side only, lemmatised through the
|
||||
same analyzer): everyday words → the words statutes use (*parkowanie* → *postój*, *zatrzymanie
|
||||
pojazdu*; *niedozwolony* ↔ *zabroniony*; *rozwód* ↔ *rozwiązanie małżeństwa*; *mandat* →
|
||||
*grzywna* …). A variant of the query weighs half the words as typed. Small and reviewed by hand —
|
||||
the file's header says how to add a line; no mined synonyms.
|
||||
* **Partial matches:** every content word must match. Only when nothing does, the index answers
|
||||
with parts holding at least 60 % of them — each result says `extra.partial`, and the answer
|
||||
carries the notice "Wyniki częściowe — nie wszystkie słowa zapytania występują w tekście".
|
||||
Never mixed silently with full matches.
|
||||
* **A deploy that changes the analysis** (`textindex.FORMAT`, the lexicon) keeps the previous index
|
||||
answering — read with the analysis it was built with — until the rebuild is swapped in; the status
|
||||
line says "indeks przebudowywany — odpowiada poprzedni" and Źródła "tak (przebudowa w toku)".
|
||||
|
||||
**Adding a language** = a `DataPackage` in `analysis.PACKAGES` (source page, archive name, licence
|
||||
and the phrase its README must contain, parser) + `analysis.register("xx", …)` (fallback stemmer,
|
||||
stopwords, normalisation) + optionally `thesaurus/xx.tsv`. Nothing in the indexing code changes.
|
||||
|
||||
**Alternative backends** — optional, not implemented, nothing of them bundled. Each would be one
|
||||
more `Lemmatizer` (`ident`, `lookup()`, `groups`) behind the same interface, and only under a
|
||||
permissive licence (MIT, BSD, Apache-2.0, ISC, 0BSD, PSF, CC0, CC BY — never GPL/LGPL/AGPL/SSPL,
|
||||
CC BY-SA or NC, for code, data and transitive dependencies alike):
|
||||
* **Morfeusz 2** (IPI PAN) — the best morphological analysis of Polish. The engine is declared
|
||||
BSD-2-Clause; its dictionaries (SGJP, PoliMorf) are published separately with their own terms,
|
||||
which must be verified at the source before any use; no aarch64 wheel on PyPI (the box would build
|
||||
it). Usable only if engine AND dictionary are permissive.
|
||||
* **Hunspell** — a native engine, tri-licensed MPL 1.1 / GPL 2 / LGPL 2.1 (copyleft: not usable
|
||||
under the permissive-only rule), affix-rule stemming, slower per word; its pl_PL dictionary
|
||||
comes from sjp.pl itself, so it adds nothing the inflection list does not already give.
|
||||
* **MySpell** — obsolete, superseded by Hunspell; not an option.
|
||||
|
||||
### SAOS: user-initiated live queries only
|
||||
|
||||
SAOS's `robots.txt` **disallows `/api/`**. Insider therefore uses SAOS **only for queries a person
|
||||
|
||||
@@ -8,3 +8,5 @@ __pycache__/
|
||||
.coverage
|
||||
.env
|
||||
.env.*
|
||||
# a lexicon built on this machine: the image builds its own (scripts/build_lexicon.py)
|
||||
lexicon/
|
||||
|
||||
@@ -46,6 +46,13 @@ COPY . .
|
||||
COPY --from=frontend . /frontend
|
||||
ENV INSIDER_FRONTEND_DIR=/frontend
|
||||
|
||||
# The language lexicons (app/integrations/analysis.PACKAGES — today Polish: sjp.pl's inflection
|
||||
# list, CC BY 4.0), downloaded from their source and built into lexicon/<lang>.lex here, never
|
||||
# committed (the raw list is ~70 MB and its archive is renamed every release). Two requests per
|
||||
# package. Best effort: without network the image still builds, the analyzers fall back to their
|
||||
# stemmers (plstem) and a later build with the lexicon rebuilds the indexes on their own.
|
||||
RUN python scripts/build_lexicon.py --best-effort
|
||||
|
||||
RUN useradd -m app && mkdir -p /data && chown -R app /data /app
|
||||
ENV DATA_DIR=/data
|
||||
USER app
|
||||
|
||||
+44
-12
@@ -138,8 +138,25 @@ class Settings(BaseSettings):
|
||||
insider_index_dir: str = ""
|
||||
# dziennik-ustaw-md (CC0, GitHub): Dz.U. acts as Markdown, article-level. The check is ONE ~1 KB
|
||||
# request (the branch head); only a changed head fetches index.csv and the changed files.
|
||||
# ── When each dataset updates: cron expressions (";" separates several), read in
|
||||
# INSIDER_SCHEDULE_TZ, every one validated at startup. A run missed while the box was down
|
||||
# happens once at the next tick. Everything updates once a day at 05:00 Polish time, except
|
||||
# dziennik-ustaw-md, whose upstream bot commits around 05:00 UTC (07:00 in a Polish summer):
|
||||
# 05:00 Warsaw would always fetch the day before's commit.
|
||||
insider_schedule_tz: str = "Europe/Warsaw"
|
||||
insider_dzu_md_schedule: str = "15 7 * * *"
|
||||
insider_eli_inforce_schedule: str = "0 5 * * *"
|
||||
insider_cellar_schedule: str = "0 5 * * *" # the delta (modified works)
|
||||
insider_cellar_full_schedule: str = "0 5 * * 0" # the full pass (finds acts out of force)
|
||||
insider_cellar_caselaw_schedule: str = "0 5 * * *"
|
||||
insider_saos_dump_schedule: str = "0 5 * * *" # the daily delta, once the first import is done
|
||||
# SAOS's FIRST full import (several nights) runs only inside this window, in INSIDER_SCHEDULE_TZ
|
||||
insider_saos_dump_first_window: str = "23:00-05:00"
|
||||
# An index built another way (a deploy changed its format or analysis) is rebuilt at the next
|
||||
# fire — the previous one answers meanwhile; a MISSING index is built at once.
|
||||
insider_index_rebuild_schedule: str = "0 5 * * *"
|
||||
|
||||
insider_dzu_md_sync: bool = True
|
||||
insider_dzu_md_sync_interval_hours: float = Field(default=6.0, ge=0.25, le=168)
|
||||
insider_dzu_md_rate: float = Field(default=4.0, gt=0, le=8)
|
||||
# How old the last successful sync may be before search stops trusting the index (→ ELI only).
|
||||
insider_dzu_md_stale_hours: float = Field(default=72.0, ge=1)
|
||||
@@ -148,25 +165,19 @@ class Settings(BaseSettings):
|
||||
# acts, whose current t.j. ELI publishes as HTML. Per changed act one metadata request plus, only
|
||||
# when no local dataset holds the text, one text request; `INSIDER_ELI_INFORCE_RATE` req/s.
|
||||
insider_eli_inforce_sync: bool = True
|
||||
insider_eli_inforce_interval_hours: float = Field(default=24.0, ge=1, le=720)
|
||||
insider_eli_inforce_rate: float = Field(default=2.0, gt=0, le=4)
|
||||
insider_eli_inforce_types: str = "Ustawa,Konstytucja"
|
||||
# The SAOS DUMP API (/api/dump/judgments) — ONLY the scheduled ingestor uses it, never a search.
|
||||
# Runs inside the UTC window below (off-peak by default: 23:00–05:00 UTC ≈ 01:00–07:00 in
|
||||
# Poland), one request in flight, a pause between pages, resumable from the stored cursor.
|
||||
# One request in flight, a pause between pages, resumable from the stored cursor.
|
||||
insider_saos_dump_sync: bool = True
|
||||
insider_saos_dump_window: str = "23:00-05:00"
|
||||
insider_saos_dump_page_size: int = Field(default=100, ge=10, le=100)
|
||||
insider_saos_dump_pause_seconds: float = Field(default=5.0, ge=1, le=600)
|
||||
# An incremental pass (sinceModificationDate) is due this long after the previous one finished.
|
||||
insider_saos_dump_interval_hours: float = Field(default=20.0, ge=1, le=720)
|
||||
insider_saos_index_stale_hours: float = Field(default=96.0, ge=1)
|
||||
# CELLAR (EU law, no account — it replaced the EUR-Lex dump seam, which needed EU Login): the
|
||||
# regulations, directives and decisions IN FORCE with their newest consolidated text (Polish,
|
||||
# else English), from the Publications Office's SPARQL endpoint + 303 text fetch. A full pass
|
||||
# weekly, a delta (CELLAR's modification dates) every interval; one request in flight.
|
||||
# else English), from the Publications Office's SPARQL endpoint + 303 text fetch. A full pass on
|
||||
# INSIDER_CELLAR_FULL_SCHEDULE, a delta (CELLAR's modification dates) on INSIDER_CELLAR_SCHEDULE.
|
||||
insider_cellar_sync: bool = True
|
||||
insider_cellar_interval_hours: float = Field(default=24.0, ge=1, le=720)
|
||||
# requests per second, every redirect hop counted (a text = 2): ≤ 2 by the owner's rule
|
||||
insider_cellar_rate: float = Field(default=1.0, gt=0, le=2)
|
||||
# How old the last pass may be before search stops trusting the EU index (→ live CELLAR).
|
||||
@@ -192,13 +203,34 @@ class Settings(BaseSettings):
|
||||
_dt.date.fromisoformat(v.strip()) # raises ValueError with the reason
|
||||
return v.strip()
|
||||
|
||||
@field_validator("insider_saos_dump_window")
|
||||
@field_validator("insider_saos_dump_first_window")
|
||||
@classmethod
|
||||
def _a_utc_window(cls, v: str) -> str:
|
||||
def _a_window(cls, v: str) -> str:
|
||||
from .services.window import parse_window
|
||||
parse_window(v) # raises ValueError with the reason
|
||||
return v.strip()
|
||||
|
||||
@field_validator("insider_schedule_tz")
|
||||
@classmethod
|
||||
def _a_zone(cls, v: str) -> str:
|
||||
from .services.schedule import zone
|
||||
zone(v.strip()) # raises ValueError naming the zone
|
||||
return v.strip()
|
||||
|
||||
@field_validator("insider_dzu_md_schedule", "insider_eli_inforce_schedule",
|
||||
"insider_cellar_schedule", "insider_cellar_full_schedule",
|
||||
"insider_cellar_caselaw_schedule", "insider_saos_dump_schedule",
|
||||
"insider_index_rebuild_schedule")
|
||||
@classmethod
|
||||
def _a_schedule(cls, v: str, info) -> str:
|
||||
from .services.schedule import parse
|
||||
try:
|
||||
if not parse(v):
|
||||
raise ValueError("empty: every dataset needs its own schedule")
|
||||
except ValueError as exc: # refuses to start, naming the variable
|
||||
raise ValueError(f"INSIDER_{info.field_name[8:].upper()}: {exc}") from exc
|
||||
return v.strip()
|
||||
|
||||
@field_validator("ocr_engine")
|
||||
@classmethod
|
||||
def _known_engine(cls, v: str) -> str:
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Language analysis for the full-text index and the title filters: one `Analyzer` per language.
|
||||
|
||||
Every word that reaches an index or a title filter goes through here: `words()` splits text (the
|
||||
ONE tokeniser), and the language's `Analyzer` turns a word into its index term — a dictionary
|
||||
lemma first (`Lemmatizer`, e.g. `lexicon.Lexicon`), the rule-based stemmer as the fallback (plstem
|
||||
for Polish). The registry is keyed by ISO 639-1 code and chosen per document: Polish acts and SAOS
|
||||
judgments are "pl"; a CELLAR text records its language, so an English fallback text gets "en".
|
||||
|
||||
**Adding a language = a data package + a registration**, nothing in the indexing code:
|
||||
1. a `DataPackage` in `PACKAGES` (where the source lives, its licence, how to parse it) — built
|
||||
into `lexicon/<lang>.lex` by `scripts/build_lexicon.py` while the image is built;
|
||||
2. `register("xx", lambda lex: Analyzer("xx", stem=..., ...))` — its rule-based fallback,
|
||||
stopwords and normalisation. An analyzer without a data package simply has no lemmatiser.
|
||||
Another backend (Morfeusz2, Hunspell — see README "Language analysis") would be one more class with
|
||||
`ident` + `lookup(key) -> token | None` + `groups`, passed as `lemmatizer`; nothing else changes.
|
||||
|
||||
`ident(langs)` names the analysis an index is built with (the stemmer version and each lexicon's
|
||||
build): `textindex` records it and rebuilds an index made with another one.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass, replace
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
from . import lexicon as lexicon_mod
|
||||
from . import plstem
|
||||
|
||||
WORD = re.compile(r"[0-9a-ząćęłńóśźż]+", re.IGNORECASE)
|
||||
SEP = lexicon_mod.SEP
|
||||
#: the built lexicons (`lexicon/<lang>.lex`); INSIDER_LEXICON_DIR overrides (tests: the fixture)
|
||||
LEXICON_DIR = Path(os.environ.get("INSIDER_LEXICON_DIR")
|
||||
or Path(__file__).resolve().parents[2] / "lexicon")
|
||||
#: how many index terms one query word may ask for (its lemmas + their ambiguity tokens)
|
||||
MAX_ALTERNATIVES = 16
|
||||
|
||||
|
||||
def words(text: str) -> list[str]:
|
||||
return WORD.findall(text or "")
|
||||
|
||||
|
||||
class Lemmatizer(Protocol):
|
||||
"""A dictionary backend: `lookup(normalised form)` → its index token (a lemma, or lemmas joined
|
||||
by `SEP` when ambiguous) or None; `groups[lemma]` = the ambiguity tokens naming that lemma."""
|
||||
ident: str
|
||||
groups: dict[str, tuple[str, ...]]
|
||||
|
||||
def lookup(self, key: str) -> str | None: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Analyzer:
|
||||
lang: str
|
||||
#: the rule-based fallback: a word → its stem
|
||||
stem: Callable[[str], str]
|
||||
#: the query-side stems of a word the lemmatiser does not know (plstem: + the mobile-e form)
|
||||
widen: Callable[[str], list[str]]
|
||||
normalise: Callable[[str], str]
|
||||
stopwords: frozenset[str] = frozenset()
|
||||
version: str = "1"
|
||||
lemmatizer: Lemmatizer | None = None
|
||||
|
||||
@property
|
||||
def ident(self) -> str:
|
||||
return f"{self.lang}:{self.version}:{self.lemmatizer.ident if self.lemmatizer else 'none'}"
|
||||
|
||||
def plain(self) -> Analyzer:
|
||||
"""The same analyzer without its dictionary (what format-2 indexes were built with)."""
|
||||
return replace(self, lemmatizer=None)
|
||||
|
||||
def is_stopword(self, word: str) -> bool:
|
||||
return word.lower() in self.stopwords
|
||||
|
||||
def term(self, word: str) -> str:
|
||||
"""The index term of one word: its lemma token when the dictionary knows it, else its stem."""
|
||||
return _term(self, word)
|
||||
|
||||
def lemmas(self, word: str) -> tuple[str, ...]:
|
||||
"""The word's lemmas (normalised), () when the dictionary does not know it."""
|
||||
t = _lookup(self, word)
|
||||
return tuple(t.split(SEP)) if t else ()
|
||||
|
||||
def alternatives(self, word: str) -> list[str]:
|
||||
"""The index terms a query word may match: its own term, each of its lemmas and every
|
||||
ambiguity token naming one ("mam" → mam|… , mama, miec, mama|miec…); for an unknown word
|
||||
its stem(s)."""
|
||||
tok = _lookup(self, word)
|
||||
if tok is None:
|
||||
return self.widen(word)
|
||||
out = [tok]
|
||||
for lemma in tok.split(SEP):
|
||||
out += [lemma, *self.lemmatizer.groups.get(lemma, ())]
|
||||
return list(dict.fromkeys(out))[:MAX_ALTERNATIVES]
|
||||
|
||||
def analyze(self, text: str, *, keep_stopwords: bool = False) -> list[str]:
|
||||
"""The terms of `text` in order — a term's position is its index in the list."""
|
||||
return [self.term(w) for w in words(text) if keep_stopwords or not self.is_stopword(w)]
|
||||
|
||||
|
||||
@lru_cache(maxsize=200_000)
|
||||
def _lookup(an: Analyzer, word: str) -> str | None:
|
||||
if an.lemmatizer is None or word.isdigit():
|
||||
return None
|
||||
return an.lemmatizer.lookup(an.normalise(word))
|
||||
|
||||
|
||||
@lru_cache(maxsize=200_000)
|
||||
def _term(an: Analyzer, word: str) -> str:
|
||||
return _lookup(an, word) or an.stem(word)
|
||||
|
||||
|
||||
# ── data packages ───────────────────────────────────────────────────────────────────────────────────
|
||||
@dataclass(frozen=True)
|
||||
class DataPackage:
|
||||
"""A language's dictionary: where it comes from, under which licence, how it is parsed."""
|
||||
lang: str
|
||||
page: str # the source's download page (the licence is stated there)
|
||||
archive: re.Pattern # the archive's name on that page (it changes with every release)
|
||||
member: str # the file inside the archive
|
||||
licence: str # the licence Insider takes it under
|
||||
licence_evidence: str # a phrase the archive's README must contain, or the build refuses
|
||||
parse: Callable[[Iterable[str], Callable[[str], str]], dict[str, list[str]]]
|
||||
credit: str
|
||||
|
||||
|
||||
PACKAGES: dict[str, DataPackage] = {
|
||||
"pl": DataPackage(
|
||||
lang="pl", page="https://sjp.pl/sl/odmiany/",
|
||||
archive=re.compile(r'href="(sjp-odm-\d{8}\.zip)"'), member="odm.txt",
|
||||
licence="CC BY 4.0", licence_evidence="Creative Commons Attribution 4.0",
|
||||
parse=lexicon_mod.parse_sjp,
|
||||
credit="Słownik SJP.PL — lista słów z odmianami (https://sjp.pl), CC BY 4.0"),
|
||||
}
|
||||
|
||||
|
||||
# ── the registry ────────────────────────────────────────────────────────────────────────────────────
|
||||
_FACTORIES: dict[str, Callable[[Lemmatizer | None], Analyzer]] = {}
|
||||
_cache: dict[str, Analyzer] = {}
|
||||
DEFAULT = "pl"
|
||||
|
||||
|
||||
def register(lang: str, factory: Callable[[Lemmatizer | None], Analyzer]) -> None:
|
||||
"""`factory(lemmatizer or None)` → the language's Analyzer (the lexicon is loaded here)."""
|
||||
_FACTORIES[lang] = factory
|
||||
_cache.pop(lang, None)
|
||||
|
||||
|
||||
def _load_lexicon(lang: str) -> Lemmatizer | None:
|
||||
path = LEXICON_DIR / f"{lang}.lex"
|
||||
try:
|
||||
return lexicon_mod.Lexicon(path) if path.is_file() else None
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def get(lang: str | None = None) -> Analyzer:
|
||||
"""The analyzer for `lang` (unknown or None → `DEFAULT`)."""
|
||||
lang = lang if lang in _FACTORIES else DEFAULT
|
||||
if lang not in _cache:
|
||||
_cache[lang] = _FACTORIES[lang](_load_lexicon(lang))
|
||||
return _cache[lang]
|
||||
|
||||
|
||||
def configure(lexicon_dir: str | Path | None) -> None:
|
||||
"""Point the registry at another lexicon directory (tests: the fixture; None: no lexicon)."""
|
||||
global LEXICON_DIR
|
||||
LEXICON_DIR = Path(lexicon_dir) if lexicon_dir else Path("/nonexistent-lexicon-dir")
|
||||
_cache.clear()
|
||||
_thesauri.clear()
|
||||
_lookup.cache_clear()
|
||||
_term.cache_clear()
|
||||
|
||||
|
||||
def ident(langs: Iterable[str]) -> str:
|
||||
return ";".join(get(lang).ident for lang in langs)
|
||||
|
||||
|
||||
register("pl", lambda lex: Analyzer(
|
||||
"pl", stem=plstem.stem, widen=plstem.alternatives, normalise=plstem.fold,
|
||||
stopwords=plstem.STOPWORDS, version=str(plstem.VERSION), lemmatizer=lex))
|
||||
|
||||
_EN_STOP = frozenset("a an and are as at be by for from in is it of on or that the to with".split())
|
||||
|
||||
|
||||
def _en_stem(word: str) -> str:
|
||||
"""A deliberately light English fallback: lower-case, a plural -s off."""
|
||||
w = word.lower()
|
||||
if len(w) > 4 and w.endswith("ies"):
|
||||
return w[:-3] + "y"
|
||||
if len(w) > 3 and w.endswith("s") and not w.endswith("ss"):
|
||||
return w[:-1]
|
||||
return w
|
||||
|
||||
|
||||
register("en", lambda lex: Analyzer(
|
||||
"en", stem=_en_stem, widen=lambda w: [_en_stem(w)], normalise=str.lower, stopwords=_EN_STOP,
|
||||
lemmatizer=lex))
|
||||
|
||||
|
||||
# ── text-level helpers (queries, title filters, snippets) ──────────────────────────────────────────
|
||||
def analyse(text: str, lang: str | None = None, *, keep_stopwords: bool = False,
|
||||
plain: bool = False) -> str:
|
||||
"""`text` as the space-separated terms the index stores (function words kept where an
|
||||
exact-phrase check needs their positions — the body; a query never MATCHES on them)."""
|
||||
an = get(lang)
|
||||
return " ".join((an.plain() if plain else an).analyze(text, keep_stopwords=keep_stopwords))
|
||||
|
||||
|
||||
def query_terms(q: str, langs: Iterable[str] = (DEFAULT,), *, plain: bool = False) -> list[list[str]]:
|
||||
"""Per distinct content word of the query, the index terms it may match (the union over the
|
||||
index's languages; the first is the word's own term in the first language)."""
|
||||
ans = [get(lang).plain() if plain else get(lang) for lang in langs]
|
||||
out: list[list[str]] = []
|
||||
seen: set[str] = set()
|
||||
for w in words(q):
|
||||
if ans[0].is_stopword(w):
|
||||
continue
|
||||
alts = list(dict.fromkeys(a for an in ans for a in an.alternatives(w)))
|
||||
if alts and alts[0] and alts[0] not in seen:
|
||||
seen.add(alts[0])
|
||||
out.append(alts)
|
||||
return out
|
||||
|
||||
|
||||
def query_keys(q: str) -> list[str]:
|
||||
"""Every lemma and stem a query's content words stand for — what a snippet looks for."""
|
||||
an = get(DEFAULT)
|
||||
keys: list[str] = []
|
||||
for w in words(q):
|
||||
if not an.is_stopword(w):
|
||||
keys += [an.stem(w), *an.lemmas(w)]
|
||||
return list(dict.fromkeys(k for k in keys if k))
|
||||
|
||||
|
||||
def word_matches(word: str, keys: Iterable[str]) -> bool:
|
||||
"""`word` (as written) stands for one of `keys`: its stem starts with one, or it is a form of
|
||||
a lemma among them."""
|
||||
an = get(DEFAULT)
|
||||
have = [an.stem(word), *an.lemmas(word)]
|
||||
return any(h.startswith(k) for h in have for k in keys)
|
||||
|
||||
|
||||
def longest_word(q: str) -> str | None:
|
||||
an = get(DEFAULT)
|
||||
ws = [w for w in words(q) if not an.is_stopword(w) and not w.isdigit()]
|
||||
return max(ws, key=len) if ws else None
|
||||
|
||||
|
||||
def title_matches(title: str, q: str) -> bool:
|
||||
"""True when every content word of the query starts a word of the (folded) title — by its stem,
|
||||
or by one of its lemmas: the client-side filter that makes ELI's substring title search
|
||||
inflection-aware ("spółki" matches a title with "spółce")."""
|
||||
an = get(DEFAULT)
|
||||
have = [form for w in words(title) for form in (an.normalise(w), an.stem(w), *an.lemmas(w))]
|
||||
for w in words(q):
|
||||
if an.is_stopword(w):
|
||||
continue
|
||||
want = [an.stem(w), *an.lemmas(w)]
|
||||
if not any(h.startswith(s) for s in want if s for h in have):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# ── the thesaurus (query-side expansion) ────────────────────────────────────────────────────────────
|
||||
#: `thesaurus/<lang>.tsv` — everyday words → the statutes' words; format in the file's header
|
||||
THESAURUS_DIR = Path(__file__).with_name("thesaurus")
|
||||
MAX_EXPANSIONS = 12
|
||||
_thesauri: dict[str, tuple] = {}
|
||||
|
||||
|
||||
def _keys(an: Analyzer, word: str) -> frozenset[str]:
|
||||
"""What a word stands for when phrases are compared: its lemmas, else its stem."""
|
||||
return frozenset(an.lemmas(word)) or frozenset([an.stem(word)])
|
||||
|
||||
|
||||
def _phrase(an: Analyzer, text: str) -> tuple[frozenset[str], ...]:
|
||||
return tuple(_keys(an, w) for w in words(text) if not an.is_stopword(w))
|
||||
|
||||
|
||||
def thesaurus(lang: str = DEFAULT) -> tuple[tuple[tuple[frozenset[str], ...], str], ...]:
|
||||
"""The language's rules, (source phrase as keys, target phrase as written), lemmatised
|
||||
through its analyzer — loaded once per lexicon (`configure` forgets them)."""
|
||||
if lang not in _thesauri:
|
||||
an = get(lang)
|
||||
rules = []
|
||||
path = THESAURUS_DIR / f"{lang}.tsv"
|
||||
lines = path.read_text(encoding="utf-8").splitlines() if path.is_file() else []
|
||||
for line in lines:
|
||||
if not line.strip() or line.startswith("#"):
|
||||
continue
|
||||
one_way = line.startswith(">")
|
||||
cols = [c.strip() for c in line.lstrip(">").split(" ") if c.strip()]
|
||||
sources = cols[:1] if one_way else cols
|
||||
rules += [(_phrase(an, a), b) for a in sources for b in cols if b != a]
|
||||
_thesauri[lang] = tuple(r for r in rules if r[0])
|
||||
return _thesauri[lang]
|
||||
|
||||
|
||||
def expansions(q: str, lang: str = DEFAULT) -> list[str]:
|
||||
"""The thesaurus variants of a query (its content words with a matched phrase replaced),
|
||||
without the query itself: "parkowanie w miejscu niedozwolonym" → "postój miejscu zabroniony",
|
||||
"postój miejscu zakazany", … (at most `MAX_EXPANSIONS`)."""
|
||||
an = get(lang)
|
||||
content = [w for w in words(q) if not an.is_stopword(w)]
|
||||
keys = [_keys(an, w) for w in content]
|
||||
subs: dict[int, list[tuple[int, str]]] = {}
|
||||
for src, tgt in thesaurus(lang):
|
||||
n = len(src)
|
||||
for i in range(len(keys) - n + 1):
|
||||
if all(keys[i + j] & src[j] for j in range(n)):
|
||||
subs.setdefault(i, []).append((i + n, tgt))
|
||||
if not subs:
|
||||
return []
|
||||
variants: list[tuple[int, list[str]]] = [(0, [])]
|
||||
done: list[str] = []
|
||||
while variants and len(done) <= MAX_EXPANSIONS:
|
||||
nxt = []
|
||||
for pos, acc in variants:
|
||||
if pos == len(content):
|
||||
done.append(" ".join(acc))
|
||||
continue
|
||||
nxt.append((pos + 1, acc + [content[pos]]))
|
||||
nxt += [(end, acc + [tgt]) for end, tgt in subs.get(pos, ())]
|
||||
variants = nxt
|
||||
plain = " ".join(content)
|
||||
return [v for v in dict.fromkeys(done) if v != plain][:MAX_EXPANSIONS]
|
||||
@@ -29,7 +29,7 @@ import asyncio
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from . import plstem
|
||||
from . import analysis
|
||||
from .base import ACT, EU_COURTS, JUDGMENT, LegalDoc, Query, SearchPage, SourceNotFound, Translation
|
||||
from .cellar_builder.structure import Part, split_html
|
||||
from .eurlex import (
|
||||
@@ -155,7 +155,8 @@ def doc_rows(doc: dict, parts: list[dict]) -> list[dict]:
|
||||
if not doc.get("in_force", True):
|
||||
tags.append("nf")
|
||||
return [{"group": doc["celex"], "ord": p["ord"], "title": doc.get("title") or "",
|
||||
"text": p["text"], "date": doc.get("date"), "tags": tags} for p in parts]
|
||||
"text": p["text"], "date": doc.get("date"), "tags": tags,
|
||||
"lang": doc.get("language") or "pl"} for p in parts]
|
||||
|
||||
|
||||
# ── the answer ─────────────────────────────────────────────────────────────────────────────────────
|
||||
@@ -259,7 +260,7 @@ class CellarIndexAdapter(LocalAdapter):
|
||||
def covered_kinds(self, query: Query) -> frozenset[str]:
|
||||
"""The kinds of THIS query the index answers in full (the live source keeps the others)."""
|
||||
if not self.applies_to(query) or query.act_ref is not None or query.celex \
|
||||
or query.case_number or not plstem.query_stems(query.q):
|
||||
or query.case_number or not analysis.query_keys(query.q):
|
||||
return frozenset()
|
||||
out = set()
|
||||
for k in self._wanted(query):
|
||||
@@ -269,10 +270,16 @@ class CellarIndexAdapter(LocalAdapter):
|
||||
out.add(k)
|
||||
return frozenset(out)
|
||||
|
||||
def outage(self, query: Query) -> dict | None:
|
||||
if not self._wanted(query) or not analysis.query_keys(query.q) or query.celex \
|
||||
or query.case_number:
|
||||
return None # not a query this index would answer anyway
|
||||
return super().outage(query)
|
||||
|
||||
def skip_reason(self, query: Query) -> str | None:
|
||||
if self.covered_kinds(query):
|
||||
return None
|
||||
if not plstem.query_stems(query.q) or query.celex or query.case_number:
|
||||
if not analysis.query_keys(query.q) or query.celex or query.case_number:
|
||||
return "no words to look up (a CELEX or case lookup is live)"
|
||||
reasons = {k: self._kind_ready(k) for k in sorted(self._wanted(query))}
|
||||
return "; ".join(f"{k}: {r}" for k, r in reasons.items() if r) or "not an EU query"
|
||||
@@ -293,7 +300,7 @@ class CellarIndexAdapter(LocalAdapter):
|
||||
date_from=query.date_from, date_to=query.date_to,
|
||||
tags=tags, exclude_tags=("nf",))
|
||||
found = self.store.get_eu_docs([g["group"] for g in groups])
|
||||
stems = plstem.query_stems(query.q)
|
||||
stems = analysis.query_keys(query.q)
|
||||
from .dzu_md import make_snippet
|
||||
docs = []
|
||||
for g in groups:
|
||||
@@ -308,6 +315,8 @@ class CellarIndexAdapter(LocalAdapter):
|
||||
snippet = ((f"{hits[0]['label']}: " if hits[0]["label"] else "") + hits[0]["snippet"]
|
||||
if hits else "")
|
||||
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
|
||||
return SearchPage(docs, total, offset + len(groups) >= total)
|
||||
|
||||
async def fetch(self, native_id: str) -> LegalDoc:
|
||||
|
||||
@@ -31,7 +31,7 @@ from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
from urllib.parse import quote
|
||||
|
||||
from . import plstem
|
||||
from . import analysis, plstem
|
||||
from .base import ACT, LegalDoc, Query, SearchPage, SourceError, SourceNotFound, Translation
|
||||
from .eli import ELI_ID, PUBLISHERS
|
||||
from .eli import official_url as eli_official_url
|
||||
@@ -293,7 +293,7 @@ def act_name(title: str) -> str:
|
||||
|
||||
def act_key(title: str) -> str:
|
||||
"""`act_name` folded to its words — the key under which every text of ONE act meets."""
|
||||
return " ".join(plstem.fold(w) for w in plstem.words(act_name(title)))
|
||||
return " ".join(plstem.fold(w) for w in analysis.words(act_name(title)))
|
||||
|
||||
|
||||
def search_title(title: str) -> str:
|
||||
@@ -438,13 +438,14 @@ def _eli_doc(act: dict, ln: dict, snippet: str, hits: list[dict] | None) -> Lega
|
||||
|
||||
|
||||
def make_snippet(text: str, stems: list[str], limit: int = 280) -> str:
|
||||
"""A plain-text window around the first word matching a query stem (headings' `#` dropped)."""
|
||||
"""A plain-text window around the first word matching a query key — a stem or a lemma,
|
||||
`analysis.query_keys` (headings' `#` dropped)."""
|
||||
plain = re.sub(r"^#+\s*", "", text, flags=re.M)
|
||||
plain = re.sub(r"[*_`]+", "", plain)
|
||||
plain = re.sub(r"\s+", " ", plain).strip()
|
||||
pos = 0
|
||||
for m in re.finditer(r"[0-9A-Za-zĄĆĘŁŃÓŚŹŻąćęłńóśźż]+", plain):
|
||||
if any(plstem.stem(m.group(0)).startswith(s) for s in stems):
|
||||
if analysis.word_matches(m.group(0), stems):
|
||||
pos = m.start()
|
||||
break
|
||||
start = max(0, pos - limit // 3)
|
||||
@@ -518,7 +519,7 @@ class DzuMdAdapter(LocalAdapter):
|
||||
return Translation({}, skip=True)
|
||||
return Translation({"eli": query.act_ref.eli}, unsupported,
|
||||
skip=self.unavailable() is not None)
|
||||
if not plstem.query_stems(query.q):
|
||||
if not analysis.query_keys(query.q):
|
||||
# a filter-only query (dates) is ELI's job: it lists, this source searches text
|
||||
return Translation({}, unsupported, skip=True)
|
||||
return Translation({"q": query.q}, unsupported, skip=self.unavailable() is not None)
|
||||
@@ -536,7 +537,7 @@ class DzuMdAdapter(LocalAdapter):
|
||||
groups, total = self.index.search(t.params["q"], offset=offset, limit=limit,
|
||||
date_from=query.date_from, date_to=query.date_to)
|
||||
acts = self.store.get_acts([g["group"] for g in groups])
|
||||
stems = plstem.query_stems(query.q)
|
||||
stems = analysis.query_keys(query.q)
|
||||
docs = []
|
||||
names: set[str] = set()
|
||||
for g in groups:
|
||||
@@ -561,6 +562,8 @@ class DzuMdAdapter(LocalAdapter):
|
||||
snippet = ((f"Art. {hits[0]['num']}: " if hits[0]["num"] else "") + hits[0]["snippet"]
|
||||
if hits else "")
|
||||
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
|
||||
return SearchPage(docs, total, offset + len(groups) >= total)
|
||||
|
||||
async def fetch(self, native_id: str) -> LegalDoc:
|
||||
|
||||
@@ -16,7 +16,7 @@ from __future__ import annotations
|
||||
import re
|
||||
from urllib.parse import quote
|
||||
|
||||
from . import plstem
|
||||
from . import analysis, plstem
|
||||
from .base import ACT, LegalDoc, Query, SearchPage, SourceAdapter, SourceError, Translation
|
||||
|
||||
BASE_URL = "https://api.sejm.gov.pl/eli/"
|
||||
@@ -35,7 +35,7 @@ SEARCH_ORDER = {"sortBy": "change", "sortDir": "desc"}
|
||||
#: query typed in one grammatical case ("ochrona danych osobowych") misses titles in another
|
||||
#: ("o ochronie danych osobowych"). Insider therefore sends the light stem of the LONGEST word
|
||||
#: (`osobow`), reads a wide window of `TITLE_SCAN` titles, and keeps those containing the stems of
|
||||
#: ALL the query words (`plstem.title_matches`). Offsets are then counted in ELI's own rows
|
||||
#: ALL the query words (`analysis.title_matches`). Offsets are then counted in ELI's own rows
|
||||
#: (`SearchPage.next_offset`), so the next page continues the scan where this one stopped.
|
||||
TITLE_SCAN = 500
|
||||
|
||||
@@ -89,7 +89,7 @@ class EliAdapter(SourceAdapter):
|
||||
params: dict = {}
|
||||
unsupported: list[str] = []
|
||||
if query.q:
|
||||
longest = plstem.longest_word(query.q)
|
||||
longest = analysis.longest_word(query.q)
|
||||
if longest:
|
||||
params["title"] = plstem.light_stem(longest)
|
||||
params["_match"] = query.q # filtered client-side, never sent
|
||||
@@ -144,7 +144,7 @@ class EliAdapter(SourceAdapter):
|
||||
items = [i for i in items if isinstance(i, dict)]
|
||||
exhausted = len(items) < window or (isinstance(total, int) and offset + len(items) >= total)
|
||||
if match:
|
||||
kept = [i for i in items if plstem.title_matches(str(i.get("title") or ""), match)]
|
||||
kept = [i for i in items if analysis.title_matches(str(i.get("title") or ""), match)]
|
||||
# `total` would count the stem's matches, not the query's: unknown after filtering
|
||||
return SearchPage([self.to_doc(i) for i in kept], len(kept) if exhausted and offset == 0 else None,
|
||||
exhausted, next_offset=offset + len(items))
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"""A dictionary lemmatiser: a compact form → lemma(s) file, built once per language data package.
|
||||
|
||||
Language-neutral: `analysis` owns which language uses which file and how a word is normalised
|
||||
(Polish: lower-cased and diacritic-folded, like `plstem`); this module only builds and reads the
|
||||
file. The one source format parsed today is sjp.pl's inflection list (`parse_sjp`: "lemma, form,
|
||||
form…" per line) — another language adds its parser next to it and a `DataPackage` in `analysis`.
|
||||
|
||||
**Ambiguity.** A form with several lemmas ("mam" → mama | mieć) is indexed as ONE token naming them
|
||||
all, sorted and joined by `SEP` (`mama|miec`, at most `MAX_LEMMAS`): tantivy-py cannot put two
|
||||
tokens at one position, and one token keeps phrase and proximity positions where they were. A query
|
||||
word asks for each of its lemmas OR every ambiguity token naming one (`Lexicon.groups`), so "mama"
|
||||
finds "mam", and "mam" finds both. Hence the index's text fields use tantivy's `whitespace`
|
||||
tokenizer (the default one would split at "|").
|
||||
|
||||
**File** (`MAGIC`, little-endian, read through mmap — the heap holds only the ambiguity table):
|
||||
a header of counts, the build's ident, the sorted forms (offsets + one blob), a value id per form,
|
||||
and the values (offsets + one blob; the ambiguous ones first). A lookup is a binary search
|
||||
(~25 µs warm; `analysis` caches the words it has seen).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import mmap
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
from collections.abc import Callable, Iterable
|
||||
from pathlib import Path
|
||||
|
||||
MAGIC = b"PLLEX02\n"
|
||||
MAX_LEMMAS = 4
|
||||
SEP = "|"
|
||||
_HEAD = struct.Struct("<8s6I") # magic, forms, values, ambiguous values, forms blob, values blob, ident
|
||||
_PL_WORD = re.compile(r"^[a-ząćęłńóśźż]+$")
|
||||
|
||||
|
||||
# ── building ────────────────────────────────────────────────────────────────────────────────────────
|
||||
def parse_sjp(lines: Iterable[str], normalise: Callable[[str], str]) -> dict[str, list[str]]:
|
||||
"""sjp.pl `odm.txt` → {normalised form: [normalised lemmas]}. The changes made to the source
|
||||
(CC BY 4.0 asks that they be indicated; README "Credits" repeats them):
|
||||
* proper names (capitalised headwords) and entries that are not one plain word are dropped;
|
||||
* negated forms ("nie…" under a headword that is not "nie…") are dropped — they keep plstem's
|
||||
stem, so "niewykonanie" never meets "wykonanie";
|
||||
* forms and lemmas are normalised (Polish: lower-cased, diacritics folded);
|
||||
* a lemma whose whole paradigm (2+ forms) is listed inside another's wins its forms: the verb
|
||||
line of "wypowiedzieć" lists the verbal noun "wypowiedzenie", which is also a headword — its
|
||||
forms stay `wypowiedzenie`, so a verbal noun and its verb remain two words, as under plstem.
|
||||
"""
|
||||
entries: list[tuple[str, set[str]]] = []
|
||||
for line in lines:
|
||||
parts = [p.strip() for p in line.rstrip("\r\n").split(",")]
|
||||
head = parts[0]
|
||||
if not head or head[0].isupper() or not _PL_WORD.match(head):
|
||||
continue
|
||||
neg = head.startswith("nie")
|
||||
forms = {p.lower() for p in parts if p and _PL_WORD.match(p.lower())
|
||||
and (neg or not p.lower().startswith("nie"))} | {head}
|
||||
entries.append((normalise(head), {normalise(f) for f in forms}))
|
||||
lemmas_of: dict[str, set[str]] = {}
|
||||
paradigm: dict[str, set[str]] = {}
|
||||
for lemma, forms in entries:
|
||||
paradigm.setdefault(lemma, set()).update(forms)
|
||||
for f in forms:
|
||||
lemmas_of.setdefault(f, set()).add(lemma)
|
||||
del entries
|
||||
# dominated[b] = the lemmas whose paradigm contains b's whole paradigm (b is derived from them)
|
||||
dominated: dict[str, set[str]] = {}
|
||||
for a, forms in paradigm.items():
|
||||
for b in forms:
|
||||
if b != a and b in paradigm and len(paradigm[b]) > 1 and paradigm[b] <= forms:
|
||||
dominated.setdefault(b, set()).add(a)
|
||||
out: dict[str, list[str]] = {}
|
||||
for form, cands in lemmas_of.items():
|
||||
if len(cands) > 1:
|
||||
cands = {a for a in cands
|
||||
if not any(a in dominated.get(b, ()) for b in cands if b != a)} or cands
|
||||
out[form] = sorted(cands)[:MAX_LEMMAS]
|
||||
return out
|
||||
|
||||
|
||||
def write(mapping: dict[str, list[str]], path: Path, ident: str) -> None:
|
||||
tokens = {SEP.join(v) for v in mapping.values()}
|
||||
vals = sorted(t for t in tokens if SEP in t) + sorted(t for t in tokens if SEP not in t)
|
||||
n_amb = sum(SEP in t for t in vals)
|
||||
index = {v: i for i, v in enumerate(vals)}
|
||||
forms = sorted(mapping, key=lambda f: f.encode("utf-8"))
|
||||
ids = [index[SEP.join(mapping[f])] for f in forms]
|
||||
|
||||
def blob(items):
|
||||
offs, parts, pos = [0], [], 0
|
||||
for s in items:
|
||||
b = s.encode("utf-8")
|
||||
parts.append(b)
|
||||
pos += len(b)
|
||||
offs.append(pos)
|
||||
return b"".join(parts), struct.pack(f"<{len(offs)}I", *offs)
|
||||
|
||||
fb, fo = blob(forms)
|
||||
vb, vo = blob(vals)
|
||||
idb = ident.encode("utf-8")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_name(path.name + ".tmp")
|
||||
with open(tmp, "wb") as fh:
|
||||
fh.write(_HEAD.pack(MAGIC, len(forms), len(vals), n_amb, len(fb), len(vb), len(idb)))
|
||||
for part in (idb, fo, struct.pack(f"<{len(ids)}I", *ids), fb, vo, vb):
|
||||
fh.write(part)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
# ── reading ─────────────────────────────────────────────────────────────────────────────────────────
|
||||
class Lexicon:
|
||||
"""`analysis.Lemmatizer` over a built file: `lookup()` + `groups`."""
|
||||
|
||||
def __init__(self, path: str | Path) -> None:
|
||||
with open(path, "rb") as fh:
|
||||
self._mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
|
||||
magic, nf, nv, na, lf, _lv, li = _HEAD.unpack_from(self._mm, 0)
|
||||
if magic != MAGIC or sys.byteorder != "little":
|
||||
raise ValueError(f"{path} is not a {MAGIC!r} lexicon")
|
||||
p = _HEAD.size
|
||||
self.ident = self._mm[p:p + li].decode("utf-8")
|
||||
p += li
|
||||
mv = memoryview(self._mm)
|
||||
self._fo = mv[p:p + 4 * (nf + 1)].cast("I")
|
||||
p += 4 * (nf + 1)
|
||||
self._ids = mv[p:p + 4 * nf].cast("I")
|
||||
p += 4 * nf
|
||||
self._fb = p
|
||||
p += lf
|
||||
self._vo = mv[p:p + 4 * (nv + 1)].cast("I")
|
||||
self._vb = p + 4 * (nv + 1)
|
||||
self.n_forms = nf
|
||||
#: lemma → the ambiguity tokens naming it (only the first `na` values hold a SEP)
|
||||
acc: dict[str, list[str]] = {}
|
||||
for i in range(na):
|
||||
v = self._value(i)
|
||||
for lemma in v.split(SEP):
|
||||
acc.setdefault(lemma, []).append(v)
|
||||
self.groups: dict[str, tuple[str, ...]] = {k: tuple(v) for k, v in acc.items()}
|
||||
|
||||
def _form(self, i: int) -> bytes:
|
||||
return self._mm[self._fb + self._fo[i]: self._fb + self._fo[i + 1]]
|
||||
|
||||
def _value(self, i: int) -> str:
|
||||
return self._mm[self._vb + self._vo[i]: self._vb + self._vo[i + 1]].decode("utf-8")
|
||||
|
||||
def lookup(self, key: str) -> str | None:
|
||||
"""The index token of a normalised form (a lemma, or "a|b" when ambiguous), or None."""
|
||||
k = key.encode("utf-8")
|
||||
lo, hi = 0, self.n_forms
|
||||
while lo < hi:
|
||||
mid = (lo + hi) // 2
|
||||
if self._form(mid) < k:
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid
|
||||
if lo < self.n_forms and self._form(lo) == k:
|
||||
return self._value(self._ids[lo])
|
||||
return None
|
||||
@@ -76,6 +76,31 @@ class LocalAdapter(SourceAdapter):
|
||||
return f"stale ({age_h:.0f} h since the last sync)"
|
||||
return None
|
||||
|
||||
def outage(self, query: Query) -> dict | None:
|
||||
"""When this source truly cannot serve `query` — never during a delta or a rebuild swap,
|
||||
when the previous index answers: `{"state": "updating"}` (no index yet, or no first full
|
||||
import) or `{"state": "stale", "synced_at": …}` (past `stale_hours`). None = it serves."""
|
||||
if self.index is None or not self.applies_to(query):
|
||||
return None
|
||||
if not self.index.ready():
|
||||
return {"state": "updating"}
|
||||
states = self.states()
|
||||
if not states or any(self._why_not(st) is None for st in states.values()):
|
||||
return None
|
||||
if any(st.get("completed_at") is None or not st.get("doc_count")
|
||||
for st in states.values()):
|
||||
return {"state": "updating"}
|
||||
synced = max((st["synced_at"] for st in states.values() if st.get("synced_at")),
|
||||
default=None)
|
||||
return {"state": "stale", "synced_at": synced}
|
||||
|
||||
def index_note(self) -> str | None:
|
||||
"""Said on an answer while the index it came from is rebuilt in the background (a deploy
|
||||
changed the analysis): the previous index answers until the new one is swapped in."""
|
||||
if self.index is not None and self.index.rebuild_pending():
|
||||
return "the index is being rebuilt; the previous one answers until then"
|
||||
return None
|
||||
|
||||
def unavailable(self) -> str | None:
|
||||
"""Why this source cannot answer at all right now (→ the live source), or None."""
|
||||
if self.index is None or not self.index.ready():
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
"""A conservative, light Polish suffix stemmer — in-house, Apache-2.0 like the rest of Insider.
|
||||
|
||||
Since 2026-10-21 it is the FALLBACK of the Polish analyzer (`analysis`): a word the sjp.pl lexicon
|
||||
knows is indexed as its lemma; a word it does not know, as its plstem stem. Word level only — the
|
||||
tokenising and the text-level helpers (query terms, title filter) live in `analysis`.
|
||||
|
||||
Why in-house: the candidates were checked on 2026-10-21 and none is both permissive and plainly
|
||||
licensed for code AND data. `pystempel` declares "Other/Proprietary License — see documentation" on
|
||||
PyPI (its Stempel tables descend from Lucene's, but the package itself is not declared permissive);
|
||||
@@ -31,7 +35,6 @@ MIN_STEM = 3
|
||||
#: bumped when `stem()` changes its output: every tantivy index is rebuilt from Postgres
|
||||
VERSION = 2
|
||||
_FOLD = str.maketrans("ąćęłńóśźż", "acelnoszz")
|
||||
_WORD = re.compile(r"[0-9a-ząćęłńóśźż]+", re.IGNORECASE)
|
||||
|
||||
#: case endings (nouns, adjectives, pronouns) — what `light_stem` removes
|
||||
_INFLECTION = sorted({
|
||||
@@ -109,65 +112,17 @@ def stem(word: str) -> str:
|
||||
return fold(s)
|
||||
|
||||
|
||||
def words(text: str) -> list[str]:
|
||||
return _WORD.findall(text or "")
|
||||
|
||||
|
||||
def stems(text: str, *, keep_stopwords: bool = False) -> list[str]:
|
||||
"""The stems of every word of `text`, in order (stop words dropped unless asked)."""
|
||||
return [stem(w) for w in words(text)
|
||||
if keep_stopwords or w.lower() not in STOPWORDS]
|
||||
|
||||
|
||||
def analyse(text: str, *, keep_stopwords: bool = False) -> str:
|
||||
"""`text` as the space-separated stems the full-text index stores (function words kept where
|
||||
an exact-phrase check needs their positions — the body; a query never MATCHES on them)."""
|
||||
return " ".join(stems(text, keep_stopwords=keep_stopwords))
|
||||
|
||||
|
||||
_MOBILE_E = re.compile(r"^(.*[^aeiouyąęó])e([^aeiouyąęó])$")
|
||||
|
||||
|
||||
def query_terms(q: str) -> list[list[str]]:
|
||||
"""Per distinct query word, the stems it may match in the index: its own, plus — for a word
|
||||
with a mobile e — the stem of the e-less form ("najem" → `naj`, and `najm` for najmu, najmem).
|
||||
The index keeps plain `stem()`s; only the query side widens."""
|
||||
out: list[list[str]] = []
|
||||
seen: set[str] = set()
|
||||
for w in words(q):
|
||||
if w.lower() in STOPWORDS:
|
||||
continue
|
||||
alts = [stem(w)]
|
||||
m = _MOBILE_E.match(w.lower())
|
||||
if m and len(w) >= 4:
|
||||
alt = stem(m.group(1) + m.group(2))
|
||||
if alt not in alts:
|
||||
alts.append(alt)
|
||||
if alts[0] and alts[0] not in seen:
|
||||
seen.add(alts[0])
|
||||
out.append(alts)
|
||||
return out
|
||||
|
||||
|
||||
def query_stems(q: str) -> list[str]:
|
||||
"""The distinct stems of a query, in order — what every match must contain."""
|
||||
seen: list[str] = []
|
||||
for s in stems(q):
|
||||
if s and s not in seen:
|
||||
seen.append(s)
|
||||
return seen
|
||||
|
||||
|
||||
def longest_word(q: str) -> str | None:
|
||||
ws = [w for w in words(q) if w.lower() not in STOPWORDS and not w.isdigit()]
|
||||
return max(ws, key=len) if ws else None
|
||||
|
||||
|
||||
def title_matches(title: str, q: str) -> bool:
|
||||
"""True when every query stem starts a word of the (folded) title — the client-side filter
|
||||
that makes ELI's substring title search inflection-aware."""
|
||||
want = query_stems(q)
|
||||
# the folded word itself, and its stem (a normalised alternation — `prawnic` for "prawnik" —
|
||||
# is not a prefix of the word as written)
|
||||
have = [form for w in words(title) for form in (fold(w), stem(w))]
|
||||
return all(any(h.startswith(s) for h in have) for s in want)
|
||||
def alternatives(word: str) -> list[str]:
|
||||
"""The stems a query word may match in the index: its own, plus — for a word with a mobile e —
|
||||
the stem of the e-less form ("najem" → `naj`, and `najm` for najmu, najmem). The index keeps
|
||||
plain `stem()`s; only the query side widens (`analysis.Analyzer.alternatives`)."""
|
||||
alts = [stem(word)]
|
||||
m = _MOBILE_E.match(word.lower())
|
||||
if m and len(word) >= 4:
|
||||
alt = stem(m.group(1) + m.group(2))
|
||||
if alt not in alts:
|
||||
alts.append(alt)
|
||||
return alts
|
||||
|
||||
@@ -31,7 +31,7 @@ import re
|
||||
from dataclasses import dataclass, field
|
||||
from urllib.parse import parse_qsl, urlsplit
|
||||
|
||||
from . import plstem
|
||||
from . import analysis
|
||||
from .base import (
|
||||
EU_COURTS,
|
||||
JUDGMENT,
|
||||
@@ -244,7 +244,7 @@ class SaosIndexAdapter(LocalAdapter):
|
||||
return "an EU court"
|
||||
if self._court_type(query) is False:
|
||||
return "a court's name (the dump carries court types, not names)"
|
||||
if not plstem.query_stems(query.q) and not query.case_number:
|
||||
if not analysis.query_keys(query.q) and not query.case_number:
|
||||
return "no words or case number to look up"
|
||||
return self.unavailable()
|
||||
|
||||
@@ -271,7 +271,7 @@ class SaosIndexAdapter(LocalAdapter):
|
||||
date_from=query.date_from, date_to=query.date_to,
|
||||
tags=tags)
|
||||
found = self.store.get_judgments([int(g["group"]) for g in groups])
|
||||
stems = plstem.query_stems(query.q)
|
||||
stems = analysis.query_keys(query.q)
|
||||
from .dzu_md import make_snippet
|
||||
docs = []
|
||||
for g in groups:
|
||||
@@ -284,6 +284,8 @@ class SaosIndexAdapter(LocalAdapter):
|
||||
"snippet": make_snippet(secs[h["ord"]]["text"], stems)}
|
||||
for h in g["hits"] if h["ord"] in secs]
|
||||
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
|
||||
return SearchPage(docs, total, offset + len(groups) >= total)
|
||||
|
||||
async def fetch(self, native_id: str) -> LegalDoc:
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Polish legal thesaurus: everyday words -> the words statutes use. QUERY-SIDE ONLY (the index is
|
||||
# never touched), loaded by `analysis` and lemmatised through the same analyzer, so any form of an
|
||||
# entry matches ("parkowania", "zabronione"). A variant of the query weighs EXPANSION_BOOST (less than
|
||||
# the words as typed); a phrase must occur in the query as a whole (function words ignored).
|
||||
#
|
||||
# a<TAB>b<TAB>c one group of equivalents: each expands to every other (both ways)
|
||||
# >a<TAB>b<TAB>c one way: a expands to b and to c, never back
|
||||
#
|
||||
# Keep it small and reviewed: one line per equivalence a lawyer would sign; no mined synonyms.
|
||||
# Add a line, run `pytest tests/test_analysis.py tests/test_search_quality.py` and
|
||||
# `python tests/search_eval.py` (no previously passing query may get worse).
|
||||
parkowanie postój zatrzymanie pojazdu
|
||||
>parkować postój zatrzymanie pojazdu pozostawienie pojazdu
|
||||
>parkowanie pozostawienie pojazdu
|
||||
niedozwolony zabroniony zakazany
|
||||
wypadek drogowy zdarzenie drogowe
|
||||
pracodawca zakład pracy
|
||||
>zwolnienie z pracy rozwiązanie umowy o pracę wypowiedzenie umowy o pracę
|
||||
>mandat grzywna kara grzywny
|
||||
spadek dziedziczenie
|
||||
alimenty obowiązek alimentacyjny
|
||||
rozwód rozwiązanie małżeństwa
|
||||
najem wynajem
|
||||
>pensja wynagrodzenie
|
||||
>wypłata wynagrodzenie
|
||||
>samochód pojazd
|
||||
>mieszkanie lokal mieszkalny
|
||||
>zwolnienie lekarskie niezdolność do pracy
|
||||
|
Can't render this file because it contains an unexpected character in line 3 and column 18.
|
@@ -40,6 +40,8 @@ class SourceStatus:
|
||||
served_by: str | None = None
|
||||
#: a local source's dataset state: last sync, commit or cursor, document count
|
||||
freshness: dict | None = None
|
||||
#: a local source answering from its previous index while the new one is built
|
||||
index_note: str | None = None
|
||||
|
||||
|
||||
def dedup_key(doc: LegalDoc) -> str:
|
||||
@@ -153,6 +155,11 @@ def _freshness(adapter) -> dict | None:
|
||||
return adapter.freshness() if getattr(adapter, "local", False) else None
|
||||
|
||||
|
||||
def _index_note(adapter) -> str | None:
|
||||
note = getattr(adapter, "index_note", None)
|
||||
return note() if note is not None else None
|
||||
|
||||
|
||||
def _skip_detail(adapter, query: Query) -> str | None:
|
||||
reason = getattr(adapter, "skip_reason", None)
|
||||
return reason(query) if reason is not None else None
|
||||
@@ -233,7 +240,8 @@ async def search(registry, cache: SourceCache, codec: CursorCodec, query: Query,
|
||||
"index answers the rest")
|
||||
if name in narrowed else None,
|
||||
served_by=_served(registry.get(name)),
|
||||
freshness=_freshness(registry.get(name)))
|
||||
freshness=_freshness(registry.get(name)),
|
||||
index_note=_index_note(registry.get(name)))
|
||||
next_offsets[name] = (None if page.get("exhausted")
|
||||
else page.get("next_offset") or offset + limit)
|
||||
continue
|
||||
|
||||
@@ -37,6 +37,7 @@ from ..integrations import dzu_md as dzu
|
||||
from ..integrations import saos_dump
|
||||
from ..integrations.base import ACT, SourceError
|
||||
from ..integrations.cellar_builder import queries as cellar_q
|
||||
from . import schedule as sched
|
||||
from .htmltext import html_to_text
|
||||
from .indexstore import utcnow
|
||||
from .window import in_window
|
||||
@@ -54,6 +55,8 @@ SAVE_EVERY = 50
|
||||
#: `interval` later, which is how the box's first `eli_inforce` pass stopped at 57 of 2 411 acts
|
||||
#: and would have waited a day (2026-10-21)
|
||||
RESUME_AFTER = dt.timedelta(minutes=10)
|
||||
#: the zone the schedules are read in (INSIDER_SCHEDULE_TZ)
|
||||
DEFAULT_TZ = "Europe/Warsaw"
|
||||
|
||||
|
||||
def unfinished(st: dict) -> bool:
|
||||
@@ -93,12 +96,36 @@ class _Base:
|
||||
#: what `status()` says when the switch is off
|
||||
off_reason = ""
|
||||
|
||||
def __init__(self, store, index, *, on: bool, clock=utcnow) -> None:
|
||||
def __init__(self, store, index, *, on: bool, schedule: str = "", tz: str = DEFAULT_TZ,
|
||||
rebuild_schedule: str = "", clock=utcnow) -> None:
|
||||
self.store = store
|
||||
self.index = index
|
||||
self.on = on
|
||||
#: INSIDER_<DATASET>_SCHEDULE: cron expression(s), ";"-separated, in `tz`
|
||||
self.schedule = schedule
|
||||
self.tz = tz
|
||||
#: INSIDER_INDEX_REBUILD_SCHEDULE: when an index of another format / analysis is rebuilt
|
||||
self.rebuild_schedule = rebuild_schedule
|
||||
#: when this process first saw the index wanting a rebuild (`ensure_index`)
|
||||
self.rebuild_seen: dt.datetime | None = None
|
||||
self._clock = clock
|
||||
|
||||
def scheduled(self, now: dt.datetime, last_start: dt.datetime | None,
|
||||
spec: str | None = None) -> bool:
|
||||
"""A fire time of the schedule has passed since `last_start` — a run missed while the box
|
||||
was down happens once, at the next tick."""
|
||||
return sched.due(self.schedule if spec is None else spec, now, last_start, self.tz)
|
||||
|
||||
def next_run(self) -> str | None:
|
||||
nxt = sched.next_fire(self.schedule, self._clock(), self.tz) if self.schedule else None
|
||||
return _iso(nxt)
|
||||
|
||||
def index_writable(self) -> bool:
|
||||
"""False while the index waits for its scheduled rebuild (another format or analysis: the
|
||||
previous index answers): an import then only writes Postgres, and the rebuild brings
|
||||
everything in. A missing index is created by `update()` / rebuilt at once."""
|
||||
return self.index is None or not self.index.rebuild_pending()
|
||||
|
||||
def enabled(self) -> bool:
|
||||
return self.on
|
||||
|
||||
@@ -124,7 +151,9 @@ class _Base:
|
||||
"cursor": st.get("cursor"), "documents": st.get("doc_count") or 0,
|
||||
"parts": st.get("part_count") or 0, "changed": st.get("changed") or 0,
|
||||
"progress": st.get("progress"), "error": st.get("error"),
|
||||
"schedule": self.schedule, "next_run": self.next_run() if self.enabled() else None,
|
||||
"index": {"ready": bool(self.index and self.index.ready()),
|
||||
"rebuild_pending": bool(self.index and self.index.rebuild_pending()),
|
||||
"size_bytes": self.index.size_bytes() if self.index else 0,
|
||||
"built_at": (self.index.meta().get("built_at") if self.index else None)}}
|
||||
|
||||
@@ -153,16 +182,14 @@ class DzuMdImporter(_Base):
|
||||
label = "Dziennik Ustaw (dziennik-ustaw-md, CC0)"
|
||||
off_reason = "INSIDER_DZU_MD_SYNC=false"
|
||||
|
||||
def __init__(self, store, index, upstream, *, on: bool, interval_hours: float,
|
||||
clock=utcnow) -> None:
|
||||
super().__init__(store, index, on=on, clock=clock)
|
||||
def __init__(self, store, index, upstream, *, on: bool, clock=utcnow, **sched_kw) -> None:
|
||||
super().__init__(store, index, on=on, clock=clock, **sched_kw)
|
||||
self.upstream = upstream
|
||||
self.interval = dt.timedelta(hours=interval_hours)
|
||||
|
||||
def due(self, now: dt.datetime) -> bool:
|
||||
st = self.state()
|
||||
last = st.get("attempted_at")
|
||||
if last is None or now - last >= self.interval:
|
||||
if self.scheduled(now, last):
|
||||
return True
|
||||
if unfinished(st) and now - last >= RESUME_AFTER:
|
||||
return True
|
||||
@@ -176,7 +203,7 @@ class DzuMdImporter(_Base):
|
||||
index_ok = self.index.ready()
|
||||
if head == st.get("commit_sha") and not failed_before and index_ok:
|
||||
flags = await asyncio.to_thread(reconcile_superseded, self.store)
|
||||
if flags:
|
||||
if flags and self.index_writable():
|
||||
await asyncio.to_thread(
|
||||
lambda: self.index.update(self.store.iter_dzu_rows(flags), flags, head))
|
||||
await self._save_async(synced_at=self._clock(), error=None, changed=len(flags))
|
||||
@@ -211,11 +238,12 @@ class DzuMdImporter(_Base):
|
||||
flags = await asyncio.to_thread(reconcile_superseded, self.store)
|
||||
redo = sorted(set(done) | set(flags))
|
||||
|
||||
# the index: a full rebuild when there is none, else only what changed
|
||||
# the index: a full rebuild when there is none, else only what changed (nothing while it
|
||||
# waits for its scheduled rebuild — that brings these rows in)
|
||||
await self._save_async(heartbeat_at=self._clock(), progress={"phase": "index"})
|
||||
if not index_ok:
|
||||
await asyncio.to_thread(self.index.rebuild, self.store.iter_dzu_rows(), head)
|
||||
elif redo or removed:
|
||||
elif (redo or removed) and self.index_writable():
|
||||
await asyncio.to_thread(
|
||||
lambda: self.index.update(self.store.iter_dzu_rows(redo), [*redo, *removed], head))
|
||||
acts, arts = await asyncio.to_thread(self.store.dzu_counts)
|
||||
@@ -245,27 +273,33 @@ class SaosDumpImporter(_Base):
|
||||
label = "SAOS — orzeczenia (API pobierania danych)"
|
||||
off_reason = "INSIDER_SAOS_DUMP_SYNC=false"
|
||||
|
||||
def __init__(self, store, index, upstream, *, on: bool, window: str, page_size: int,
|
||||
pause: float, interval_hours: float, max_pages: int | None = None,
|
||||
sleep=asyncio.sleep, clock=utcnow) -> None:
|
||||
super().__init__(store, index, on=on, clock=clock)
|
||||
def __init__(self, store, index, upstream, *, on: bool, first_window: str, page_size: int,
|
||||
pause: float, max_pages: int | None = None, sleep=asyncio.sleep, clock=utcnow,
|
||||
**sched_kw) -> None:
|
||||
super().__init__(store, index, on=on, clock=clock, **sched_kw)
|
||||
self.upstream = upstream
|
||||
self.window = window
|
||||
#: INSIDER_SAOS_DUMP_FIRST_WINDOW: the FIRST full import (hundreds of thousands of
|
||||
#: judgments, several nights) runs only inside it; afterwards the daily delta, on schedule
|
||||
self.first_window = first_window
|
||||
self.page_size = page_size
|
||||
self.pause = pause
|
||||
self.interval = dt.timedelta(hours=interval_hours)
|
||||
self.max_pages = max_pages
|
||||
self._sleep = sleep
|
||||
|
||||
def _first_pass(self) -> bool:
|
||||
return self.state().get("completed_at") is None
|
||||
|
||||
def _may_run(self, now: dt.datetime) -> bool:
|
||||
return not self._first_pass() or in_window(self.first_window, now, self.tz)
|
||||
|
||||
def due(self, now: dt.datetime) -> bool:
|
||||
if not in_window(self.window, now):
|
||||
if not self._may_run(now):
|
||||
return False
|
||||
st = self.state()
|
||||
cur = st.get("cursor") or {}
|
||||
if cur.get("page") is not None: # a pass in progress: carry on
|
||||
return True
|
||||
last = st.get("synced_at")
|
||||
return last is None or now - last >= self.interval
|
||||
if cur.get("page") is not None or st.get("completed_at") is None:
|
||||
return True # a pass in progress / the first import
|
||||
return self.scheduled(now, st.get("attempted_at"))
|
||||
|
||||
async def run_once(self, stop: asyncio.Event | None = None) -> dict:
|
||||
st = self.state()
|
||||
@@ -279,7 +313,7 @@ class SaosDumpImporter(_Base):
|
||||
while True:
|
||||
if stop is not None and stop.is_set():
|
||||
break
|
||||
if not in_window(self.window, self._clock()):
|
||||
if not self._may_run(self._clock()):
|
||||
break
|
||||
if self.max_pages is not None and pages >= self.max_pages:
|
||||
break
|
||||
@@ -296,7 +330,7 @@ class SaosDumpImporter(_Base):
|
||||
log.warning("saos dump: skipped an item: %s", exc)
|
||||
await asyncio.to_thread(self.store.upsert_judgments, recs)
|
||||
ids = [r.id for r in recs]
|
||||
if ids:
|
||||
if ids and self.index_writable():
|
||||
await asyncio.to_thread(lambda ids=ids: self.index.update(
|
||||
self.store.iter_saos_rows(ids), ids, {"since": cur["since"]}))
|
||||
stored += len(recs)
|
||||
@@ -357,12 +391,12 @@ class EliInForceImporter(_Base):
|
||||
label = "Akty obowiązujące — teksty jednolite (API ELI)"
|
||||
off_reason = "INSIDER_ELI_INFORCE_SYNC=false"
|
||||
|
||||
def __init__(self, store, index, client, *, on: bool, interval_hours: float, types: list[str],
|
||||
max_acts: int | None = None, after: str | None = None, clock=utcnow) -> None:
|
||||
super().__init__(store, index, on=on, clock=clock)
|
||||
def __init__(self, store, index, client, *, on: bool, types: list[str],
|
||||
max_acts: int | None = None, after: str | None = None, clock=utcnow,
|
||||
**sched_kw) -> None:
|
||||
super().__init__(store, index, on=on, clock=clock, **sched_kw)
|
||||
self.client = client
|
||||
self.upstream = client # closed with the other upstreams
|
||||
self.interval = dt.timedelta(hours=interval_hours)
|
||||
self.types = types
|
||||
self.max_acts = max_acts
|
||||
#: the dataset whose FIRST full import this one waits for (`dzu_md`, when its sync is on):
|
||||
@@ -375,7 +409,7 @@ class EliInForceImporter(_Base):
|
||||
return False
|
||||
st = self.state()
|
||||
last = st.get("attempted_at")
|
||||
if last is None or now - last >= self.interval:
|
||||
if self.scheduled(now, last):
|
||||
return True
|
||||
# an interrupted pass (a deploy mid-run) carries on soon: its `seen` cursor keeps the acts
|
||||
# already done, so the rest is what is fetched
|
||||
@@ -495,7 +529,7 @@ class EliInForceImporter(_Base):
|
||||
await self._save_async(heartbeat_at=self._clock(), progress={"phase": "index"})
|
||||
if not self.index.ready():
|
||||
await asyncio.to_thread(self.index.rebuild, self.store.iter_dzu_rows(), None)
|
||||
elif redo:
|
||||
elif redo and self.index_writable():
|
||||
await asyncio.to_thread(
|
||||
lambda: self.index.update(self.store.iter_dzu_rows(redo), redo, None))
|
||||
count = len(await asyncio.to_thread(self.store.dzu_fingerprints, "eli"))
|
||||
@@ -516,9 +550,6 @@ class EliInForceImporter(_Base):
|
||||
|
||||
|
||||
# ── CELLAR (EU acts in force; CJEU case law) ───────────────────────────────────────────────────────
|
||||
#: a full listing pass (which also finds acts that left force) at least this often; daily passes
|
||||
#: in between are DELTAS (works CELLAR modified since the last pass)
|
||||
FULL_EVERY = dt.timedelta(days=7)
|
||||
|
||||
|
||||
def _ts(t: dt.datetime) -> str:
|
||||
@@ -541,25 +572,26 @@ class CellarImporter(_Base):
|
||||
* `judgment` (`cellar_caselaw`, off by default): CJ/TJ judgments from `date_from` on.
|
||||
|
||||
A pass is FULL (the whole listing, keyset-paged by CELEX; acts the listing no longer returns are
|
||||
marked out of force) on the first run and every `FULL_EVERY`, otherwise a DELTA (the works whose
|
||||
marked out of force) on the first run and on `full_schedule` (INSIDER_CELLAR_FULL_SCHEDULE),
|
||||
otherwise a DELTA (the works whose
|
||||
— or whose consolidated versions' — `cmr:lastModificationDate` moved since the previous pass
|
||||
STARTED, minus a margin; one detail query per 100 of them; acts now out of force are marked).
|
||||
Only a work whose fingerprint (text CELEX | modification date) changed is fetched. The cursor
|
||||
is saved after every page, so a restart resumes where it stopped; one request in flight at the
|
||||
client's rate (`INSIDER_CELLAR_RATE`, ≤ 2 req/s, every redirect hop counted)."""
|
||||
|
||||
def __init__(self, store, index, upstream, *, kind: str, on: bool, interval_hours: float,
|
||||
def __init__(self, store, index, upstream, *, kind: str, on: bool, full_schedule: str = "",
|
||||
date_from: str = "2000-01-01", max_docs: int | None = None,
|
||||
clock=utcnow) -> None:
|
||||
clock=utcnow, **sched_kw) -> None:
|
||||
self.kind = kind
|
||||
self.name = cellar_mod.DATASET if kind == ACT else cellar_mod.CASELAW
|
||||
self.label = ("EUR-Lex — akty obowiązujące (CELLAR, teksty skonsolidowane)" if kind == ACT
|
||||
else f"EUR-Lex — orzecznictwo TSUE od {date_from[:4]} (CELLAR)")
|
||||
self.off_reason = ("INSIDER_CELLAR_SYNC=false" if kind == ACT
|
||||
else "INSIDER_CELLAR_CASELAW=false")
|
||||
super().__init__(store, index, on=on, clock=clock)
|
||||
super().__init__(store, index, on=on, clock=clock, **sched_kw)
|
||||
self.upstream = upstream
|
||||
self.interval = dt.timedelta(hours=interval_hours)
|
||||
self.full_schedule = full_schedule
|
||||
self.date_from = date_from
|
||||
self.max_docs = max_docs
|
||||
|
||||
@@ -567,8 +599,8 @@ class CellarImporter(_Base):
|
||||
st = self.state()
|
||||
if (st.get("cursor") or {}).get("mode"): # a pass in progress: carry on
|
||||
return True
|
||||
last = st.get("synced_at")
|
||||
return last is None or now - last >= self.interval
|
||||
last = st.get("attempted_at")
|
||||
return self.scheduled(now, last) or self.scheduled(now, last, self.full_schedule)
|
||||
|
||||
# ── upstream steps ──
|
||||
def _parse(self, row: dict):
|
||||
@@ -660,7 +692,7 @@ class CellarImporter(_Base):
|
||||
return list(dict.fromkeys(changed)), interrupted
|
||||
|
||||
async def _reindex(self, celexes: list[str], marker) -> None:
|
||||
if celexes:
|
||||
if celexes and self.index_writable():
|
||||
await asyncio.to_thread(lambda: self.index.update(
|
||||
self.store.iter_eu_rows(celexes), celexes, marker))
|
||||
|
||||
@@ -671,7 +703,7 @@ class CellarImporter(_Base):
|
||||
if not cur.get("mode"): # a new pass
|
||||
last_full = _parse_ts(cur.get("full_at"))
|
||||
full = (st.get("completed_at") is None or not cur.get("next_since")
|
||||
or last_full is None or now - last_full >= FULL_EVERY)
|
||||
or last_full is None or self.scheduled(now, last_full, self.full_schedule))
|
||||
cur = {"mode": "full" if full else "delta", "after": None,
|
||||
"since": cur.get("next_since"), "pass_started": _ts(now - SINCE_MARGIN),
|
||||
"pass_id": _ts(now), "full_at": cur.get("full_at"),
|
||||
@@ -763,12 +795,21 @@ async def run_loop(importer, stop: asyncio.Event, *, tick: float = TICK,
|
||||
|
||||
|
||||
async def ensure_index(importer) -> None:
|
||||
"""Rebuild a dataset's index from Postgres when it is missing (a fresh volume, a deleted
|
||||
directory) or was built with another stemmer (`plstem.VERSION` — a deploy that changes the
|
||||
stems rebuilds every index on the next tick, without downloading anything) while rows exist —
|
||||
the index is disposable, the rows are not."""
|
||||
if importer.index is None or not importer.index.available or importer.index.ready():
|
||||
"""Rebuild a dataset's index from Postgres (no download) while rows exist — the index is
|
||||
disposable, the rows are not:
|
||||
* at once when it cannot answer (missing: a fresh volume, a deleted directory; or a format /
|
||||
stemmer today's code cannot read) — the source is skipped until then;
|
||||
* at the next fire of INSIDER_INDEX_REBUILD_SCHEDULE when it still answers but was built
|
||||
another way (`rebuild_pending`: a deploy changed `FORMAT` or the analysis) — the previous
|
||||
index serves until the new one is swapped in (`TextIndex.rebuild`)."""
|
||||
if importer.index is None or not importer.index.available or importer.index.current():
|
||||
importer.rebuild_seen = None
|
||||
return
|
||||
if importer.index.ready():
|
||||
now = utcnow()
|
||||
importer.rebuild_seen = importer.rebuild_seen or now
|
||||
if not sched.due(importer.rebuild_schedule, now, importer.rebuild_seen, importer.tz):
|
||||
return
|
||||
st = await asyncio.to_thread(importer.store.sync_state, importer.name)
|
||||
if not st or not st.get("doc_count"):
|
||||
return
|
||||
@@ -786,6 +827,7 @@ async def ensure_index(importer) -> None:
|
||||
# the flags first, so the rebuilt index never holds an older t.j. as searchable
|
||||
await asyncio.to_thread(reconcile_superseded, importer.store)
|
||||
n = await asyncio.to_thread(importer.index.rebuild, rows, st.get("commit_sha"))
|
||||
importer.rebuild_seen = None
|
||||
log.info("%s index rebuilt from Postgres: %d parts", importer.name, n)
|
||||
finally:
|
||||
await asyncio.to_thread(importer.store.release, handle)
|
||||
@@ -835,11 +877,10 @@ def build_indexing(settings, store, *, transport=None, clock=utcnow, **client_kw
|
||||
root = settings.index_dir
|
||||
dzu_index = TextIndex(root / dzu.DATASET)
|
||||
saos_index = TextIndex(root / saos_dump.DATASET)
|
||||
eu_index = TextIndex(root / cellar_mod.INDEX_DIR)
|
||||
eu_index = TextIndex(root / cellar_mod.INDEX_DIR, langs=("pl", "en"))
|
||||
adapters = {
|
||||
dzu.DATASET: dzu.DzuMdAdapter(store, dzu_index,
|
||||
stale_hours=max(settings.insider_dzu_md_stale_hours,
|
||||
2 * settings.insider_eli_inforce_interval_hours),
|
||||
stale_hours=settings.insider_dzu_md_stale_hours,
|
||||
clock=clock),
|
||||
"saos_index": saos_dump.SaosIndexAdapter(
|
||||
store, saos_index, stale_hours=settings.insider_saos_index_stale_hours, clock=clock),
|
||||
@@ -858,21 +899,24 @@ def build_indexing(settings, store, *, transport=None, clock=utcnow, **client_kw
|
||||
saos_up = saos_dump.SaosDumpUpstream(client(
|
||||
"saos_dump", saos_dump.DUMP_URL, 1.0, retries=1,
|
||||
timeout=httpx.Timeout(connect=5.0, read=90.0, write=10.0, pool=5.0)))
|
||||
def sched_kw(spec: str) -> dict:
|
||||
return {"schedule": spec, "tz": settings.insider_schedule_tz,
|
||||
"rebuild_schedule": settings.insider_index_rebuild_schedule}
|
||||
|
||||
importers = [
|
||||
DzuMdImporter(store, dzu_index, dzu_up, on=settings.insider_dzu_md_sync,
|
||||
interval_hours=settings.insider_dzu_md_sync_interval_hours, clock=clock),
|
||||
DzuMdImporter(store, dzu_index, dzu_up, on=settings.insider_dzu_md_sync, clock=clock,
|
||||
**sched_kw(settings.insider_dzu_md_schedule)),
|
||||
SaosDumpImporter(store, saos_index, saos_up, on=settings.insider_saos_dump_sync,
|
||||
window=settings.insider_saos_dump_window,
|
||||
first_window=settings.insider_saos_dump_first_window,
|
||||
page_size=settings.insider_saos_dump_page_size,
|
||||
pause=settings.insider_saos_dump_pause_seconds,
|
||||
interval_hours=settings.insider_saos_dump_interval_hours, clock=clock),
|
||||
pause=settings.insider_saos_dump_pause_seconds, clock=clock,
|
||||
**sched_kw(settings.insider_saos_dump_schedule)),
|
||||
EliInForceImporter(store, dzu_index, client(
|
||||
"eli_inforce", eli_mod.BASE_URL, settings.insider_eli_inforce_rate,
|
||||
timeout=httpx.Timeout(connect=5.0, read=60.0, write=10.0, pool=5.0)),
|
||||
on=settings.insider_eli_inforce_sync,
|
||||
interval_hours=settings.insider_eli_inforce_interval_hours,
|
||||
types=settings.eli_inforce_types,
|
||||
after=dzu.DATASET if settings.insider_dzu_md_sync else None, clock=clock),
|
||||
on=settings.insider_eli_inforce_sync, types=settings.eli_inforce_types,
|
||||
after=dzu.DATASET if settings.insider_dzu_md_sync else None, clock=clock,
|
||||
**sched_kw(settings.insider_eli_inforce_schedule)),
|
||||
]
|
||||
# CELLAR: one client (one in flight, the importer's rate; redirects only to its own host)
|
||||
# shared by the two kinds, which never run at once (one lock key, one index writer)
|
||||
@@ -883,10 +927,12 @@ def build_indexing(settings, store, *, transport=None, clock=utcnow, **client_kw
|
||||
timeout=httpx.Timeout(connect=5.0, read=90.0, write=10.0, pool=5.0)))
|
||||
importers += [
|
||||
CellarImporter(store, eu_index, cellar_up, kind=ACT, on=settings.insider_cellar_sync,
|
||||
interval_hours=settings.insider_cellar_interval_hours, clock=clock),
|
||||
full_schedule=settings.insider_cellar_full_schedule, clock=clock,
|
||||
**sched_kw(settings.insider_cellar_schedule)),
|
||||
CellarImporter(store, eu_index, _Shared(cellar_up), kind="judgment",
|
||||
on=settings.insider_cellar_caselaw,
|
||||
interval_hours=settings.insider_cellar_interval_hours,
|
||||
date_from=settings.insider_cellar_caselaw_from, clock=clock),
|
||||
full_schedule=settings.insider_cellar_full_schedule,
|
||||
date_from=settings.insider_cellar_caselaw_from, clock=clock,
|
||||
**sched_kw(settings.insider_cellar_caselaw_schedule)),
|
||||
]
|
||||
return Indexing(store, adapters, importers)
|
||||
|
||||
@@ -610,7 +610,7 @@ class PgIndexStore:
|
||||
|
||||
from ..models import EuDoc, EuPart
|
||||
stmt = (select(EuDoc.celex, EuDoc.kind, EuDoc.type, EuDoc.title, EuDoc.date,
|
||||
EuDoc.in_force, EuPart.ord, EuPart.text)
|
||||
EuDoc.in_force, EuDoc.language, EuPart.ord, EuPart.text)
|
||||
.join(EuPart, EuPart.celex == EuDoc.celex)
|
||||
.order_by(EuDoc.celex, EuPart.ord))
|
||||
if celexes is not None:
|
||||
@@ -618,8 +618,8 @@ class PgIndexStore:
|
||||
return
|
||||
stmt = stmt.where(EuDoc.celex.in_(celexes))
|
||||
with self._factory() as db:
|
||||
for c, k, t, title, date, force, o, text in db.execute(stmt.execution_options(
|
||||
for c, k, t, title, date, force, lang, o, text in db.execute(stmt.execution_options(
|
||||
yield_per=1000)):
|
||||
yield from doc_rows({"celex": c, "kind": k, "type": t, "title": title,
|
||||
"date": date, "in_force": force},
|
||||
"date": date, "in_force": force, "language": lang},
|
||||
[{"ord": o, "text": text}])
|
||||
|
||||
@@ -11,6 +11,7 @@ answered with the official URL and the source's attribution.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
|
||||
from ..errors import NotFoundError, SourceDisabledError, UpstreamError, ValidationError
|
||||
from ..integrations import eli as eli_mod
|
||||
@@ -37,6 +38,48 @@ MAX_LIMIT = 50
|
||||
#: SAOS's Supreme Court collection ends in June 2016 (the newest SUPREME judgment is III KK 195/16;
|
||||
#: "III CZP 25/22" and "III CZP 11/20" are simply not there — checked 2026-10-21). Common courts are
|
||||
#: current. Said wherever a search or citation reaches for the Supreme Court through SAOS.
|
||||
#: a local index answered with PARTIAL matches (`textindex.search`): no part held every word
|
||||
PARTIAL_NOTICE = {
|
||||
"code": "partial_matches",
|
||||
"message": "Wyniki częściowe — nie wszystkie słowa zapytania występują w tekście",
|
||||
"message_en": "Partial results — not every word of the query occurs in the text",
|
||||
}
|
||||
|
||||
|
||||
def _with_partial(notices: list[dict], *groups: list[dict]) -> list[dict]:
|
||||
if any((d.get("extra") or {}).get("partial") for docs in groups for d in docs):
|
||||
return notices + [dict(PARTIAL_NOTICE)]
|
||||
return notices
|
||||
|
||||
|
||||
#: what an outage notice calls each local source
|
||||
INDEX_LABEL = {"dzu_md": "Indeks aktów", "saos_index": "Indeks orzeczeń", "cellar": "Indeks prawa UE"}
|
||||
|
||||
|
||||
def outage_notices(registry, query: Query, sources: list[dict]) -> list[dict]:
|
||||
"""A notice per local source that was SKIPPED because it truly cannot serve (no index yet, a
|
||||
first import running, or stale data) — never during a delta or a rebuild, when the previous
|
||||
index answers and nothing needs saying."""
|
||||
out = []
|
||||
for s in sources:
|
||||
adapter = registry.get(s["name"])
|
||||
if s.get("status") != "skipped" or not getattr(adapter, "local", False):
|
||||
continue
|
||||
o = adapter.outage(query)
|
||||
if o is None:
|
||||
continue
|
||||
label = INDEX_LABEL.get(s["name"], s["name"])
|
||||
if o["state"] == "updating":
|
||||
msg = f"{label}: aktualizacja w toku — wyniki z wyszukiwania na żywo"
|
||||
en = f"{label}: being updated — results from live search"
|
||||
else:
|
||||
day = o["synced_at"].astimezone(dt.UTC).date().isoformat() if o.get("synced_at") else "—"
|
||||
msg = f"{label}: dane z dnia {day} — wyniki z wyszukiwania na żywo"
|
||||
en = f"{label}: data as of {day} — results from live search"
|
||||
out.append({"code": f"index_{o['state']}:{s['name']}", "message": msg, "message_en": en})
|
||||
return out
|
||||
|
||||
|
||||
SN_NOTICE = {
|
||||
"code": "sn_not_in_saos",
|
||||
"message": "Orzeczenia Sądu Najwyższego po 2016 r. nie są dostępne w SAOS — szukaj na sn.pl",
|
||||
@@ -131,7 +174,8 @@ class Legal:
|
||||
tickets.append(entry)
|
||||
out["pending"] = tickets
|
||||
await self._eli_overlay(out["acts"])
|
||||
out["notices"] = self.notices(query)
|
||||
out["notices"] = _with_partial(self.notices(query), out["acts"], out["judgments"]) \
|
||||
+ outage_notices(self.registry, query, out["sources"])
|
||||
out["query"] = {k: v for k, v in query.__dict__.items() if v not in (None, "", "all")
|
||||
and k != "act_ref"} | ({"eli": query.act_ref.eli} if query.act_ref else {})
|
||||
# which result kind each set filter narrowed — the other kind is never filtered by it
|
||||
@@ -191,11 +235,11 @@ class Legal:
|
||||
raise NotFoundError(f"Unknown source '{name}'.")
|
||||
page = await asyncio.shield(self._start_slow(name, query, offset, limit))
|
||||
docs = federation.dedup([LegalDoc.from_dict(d) for d in page["docs"]])
|
||||
return {"source": name,
|
||||
"acts": [d.to_dict() for d in federation.by_date([d for d in docs if d.kind == ACT])],
|
||||
"judgments": [d.to_dict() for d in federation.by_date(
|
||||
[d for d in docs if d.kind == JUDGMENT])],
|
||||
"sources": [page["status"]], "notices": self.notices(query)}
|
||||
acts = [d.to_dict() for d in federation.by_date([d for d in docs if d.kind == ACT])]
|
||||
judgments = [d.to_dict() for d in federation.by_date([d for d in docs if d.kind == JUDGMENT])]
|
||||
return {"source": name, "acts": acts, "judgments": judgments,
|
||||
"sources": [page["status"]],
|
||||
"notices": _with_partial(self.notices(query), acts, judgments)}
|
||||
|
||||
# ── acts ─────────────────────────────────────────────────────────────────
|
||||
async def act(self, eli: str) -> LegalDoc:
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Cron schedules for the importers: `INSIDER_<DATASET>_SCHEDULE`, evaluated in INSIDER_SCHEDULE_TZ.
|
||||
|
||||
A schedule is one or more cron expressions separated by ";" ("15 7 * * *;0 13 * * 1-5"), parsed
|
||||
by croniter (MIT) in a time zone (default Europe/Warsaw, DST-aware through zoneinfo + tzdata). It
|
||||
is DUE when its most recent fire time is later than the importer's last start — so a run missed
|
||||
while the box was down happens once at the next tick, never once per missed fire.
|
||||
|
||||
Its own module, with no imports from the app, because `config.py` validates every expression at
|
||||
startup with it (an invalid one refuses to start, naming the variable).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from croniter import croniter
|
||||
|
||||
|
||||
def zone(name: str) -> ZoneInfo:
|
||||
try:
|
||||
return ZoneInfo(name)
|
||||
except Exception as exc: # noqa: BLE001 — ZoneInfoNotFoundError, ValueError on a bad key
|
||||
raise ValueError(f"not an IANA time zone: {name!r}") from exc
|
||||
|
||||
|
||||
def parse(spec: str) -> list[str]:
|
||||
"""The expressions of a schedule; ValueError naming the bad one. Empty = no schedule."""
|
||||
exprs = [e.strip() for e in (spec or "").split(";") if e.strip()]
|
||||
for e in exprs:
|
||||
if len(e.split()) != 5 or not croniter.is_valid(e):
|
||||
raise ValueError(f"not a 5-field cron expression: {e!r}")
|
||||
return exprs
|
||||
|
||||
|
||||
def _wall(now: dt.datetime, tz: str) -> dt.datetime:
|
||||
"""`now` as naive wall-clock time in `tz` — croniter steps through wall time, and only then is
|
||||
a fire time placed in the zone (croniter's own tz arithmetic slips an hour across a DST change)."""
|
||||
return now.astimezone(zone(tz)).replace(tzinfo=None)
|
||||
|
||||
|
||||
def _utc(wall: dt.datetime, tz: str) -> dt.datetime:
|
||||
return wall.replace(tzinfo=zone(tz)).astimezone(dt.UTC)
|
||||
|
||||
|
||||
def last_fire(spec: str, now: dt.datetime, tz: str) -> dt.datetime | None:
|
||||
"""The most recent fire time at or before `now` (UTC), or None for an empty schedule."""
|
||||
wall = _wall(now, tz) + dt.timedelta(seconds=1)
|
||||
fires = [_utc(croniter(e, wall).get_prev(dt.datetime), tz) for e in parse(spec)]
|
||||
return max(fires) if fires else None
|
||||
|
||||
|
||||
def next_fire(spec: str, now: dt.datetime, tz: str) -> dt.datetime | None:
|
||||
wall = _wall(now, tz)
|
||||
fires = [_utc(croniter(e, wall).get_next(dt.datetime), tz) for e in parse(spec)]
|
||||
return min(fires) if fires else None
|
||||
|
||||
|
||||
def due(spec: str, now: dt.datetime, last_start: dt.datetime | None, tz: str) -> bool:
|
||||
"""A fire time has passed since the last start (never started = due)."""
|
||||
if last_start is None:
|
||||
return True
|
||||
fire = last_fire(spec, now, tz)
|
||||
return fire is not None and fire > last_start
|
||||
@@ -1,4 +1,5 @@
|
||||
"""A full-text index on disk: tantivy (MIT), Polish-stemmed in Python, grouped by document.
|
||||
"""A full-text index on disk: tantivy (MIT), analysed in Python (`integrations/analysis`: lemmas,
|
||||
plstem as the fallback, a query-side thesaurus), grouped by document.
|
||||
|
||||
Engine: **tantivy-py** (`tantivy` on PyPI, MIT; wheels for manylinux x86_64/aarch64 and win_amd64),
|
||||
pinned in `requirements.txt`. An embedded Lucene-class engine with BM25 — no server, no JVM. Its
|
||||
@@ -32,6 +33,7 @@ exists, has documents and matches today's stemmer. Without `tantivy` installed
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import itertools
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
@@ -41,7 +43,7 @@ import threading
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
from ..integrations import plstem
|
||||
from ..integrations import analysis, plstem
|
||||
|
||||
log = logging.getLogger("insider.textindex")
|
||||
|
||||
@@ -53,7 +55,10 @@ except ImportError: # pragma: no cover — exercised only wh
|
||||
META = "index.json"
|
||||
#: bumped when what a document holds changes (fields, analysis); an index of another format is
|
||||
#: not `ready()` and `indexing.ensure_index` rebuilds it from Postgres — like `plstem.VERSION`
|
||||
FORMAT = 2
|
||||
FORMAT = 3
|
||||
#: the formats today's code can still QUERY: an index in one of them keeps answering (as "ready,
|
||||
#: rebuild pending") until its rebuild is swapped in — format 2 = plstem stems, default tokenizer
|
||||
READABLE = (2, 3)
|
||||
TITLE_BOOST = 3.0
|
||||
HEAD_BOOST = 4.0
|
||||
LEAD_BOOST = 1.5
|
||||
@@ -62,6 +67,12 @@ FIELDS = (("body", 1.0), ("lead", LEAD_BOOST), ("head", HEAD_BOOST), ("title", T
|
||||
#: deals with a subject throughout over the one with a single article on it
|
||||
BREADTH = 0.05
|
||||
PHRASE_BOOST = 3.0
|
||||
#: a thesaurus variant of the query ("parkowanie" → "postój") weighs less than the words as typed
|
||||
EXPANSION_BOOST = 0.5
|
||||
#: when no part holds every content word: the share of them a PARTIAL match needs (at least one),
|
||||
#: and how many word subsets that may take
|
||||
PARTIAL_SHARE = 0.6
|
||||
PARTIAL_COMBOS = 20
|
||||
PAIR_BOOST = 1.0
|
||||
EXACT_BOOST = 4.0
|
||||
SLOP = 2
|
||||
@@ -97,15 +108,18 @@ def split_lead(text: str) -> tuple[str, str]:
|
||||
return heading, (rest[: end.start()] if end else rest)
|
||||
|
||||
|
||||
def _schema():
|
||||
def _schema(fmt: int = FORMAT):
|
||||
"""Format 3 stores analysis terms that may hold `analysis.SEP` ("mama|miec"), so its text
|
||||
fields split on whitespace only; format 2's used tantivy's default tokenizer."""
|
||||
tok = "whitespace" if fmt >= 3 else "default"
|
||||
sb = tantivy.SchemaBuilder()
|
||||
sb.add_text_field("key", stored=True, tokenizer_name="raw")
|
||||
sb.add_text_field("group", stored=False, tokenizer_name="raw")
|
||||
sb.add_text_field("tag", stored=False, tokenizer_name="raw")
|
||||
sb.add_text_field("title", stored=False)
|
||||
sb.add_text_field("head", stored=False)
|
||||
sb.add_text_field("lead", stored=False)
|
||||
sb.add_text_field("body", stored=False)
|
||||
sb.add_text_field("title", stored=False, tokenizer_name=tok)
|
||||
sb.add_text_field("head", stored=False, tokenizer_name=tok)
|
||||
sb.add_text_field("lead", stored=False, tokenizer_name=tok)
|
||||
sb.add_text_field("body", stored=False, tokenizer_name=tok)
|
||||
sb.add_integer_field("day", stored=False, indexed=True, fast=True)
|
||||
sb.add_float_field("prior", stored=True)
|
||||
return sb.build()
|
||||
@@ -114,34 +128,54 @@ def _schema():
|
||||
class TextIndex:
|
||||
available = tantivy is not None
|
||||
|
||||
def __init__(self, path: str | Path) -> None:
|
||||
def __init__(self, path: str | Path, langs: tuple[str, ...] = (analysis.DEFAULT,)) -> None:
|
||||
self.path = Path(path)
|
||||
#: the languages its documents may be in (a row's `lang`); queries ask in all of them
|
||||
self.langs = langs
|
||||
self._lock = threading.RLock()
|
||||
self._index = None
|
||||
self._opened_at: str | None = None
|
||||
self._opened_format = FORMAT
|
||||
self._schema = _schema() if tantivy is not None else None
|
||||
|
||||
# ── state ──
|
||||
def _live(self) -> Path:
|
||||
"""The directory serving now: the index, or — in the instant of a swap, between the two
|
||||
renames — the previous one, so a search in another worker never finds nothing."""
|
||||
if (self.path / META).exists():
|
||||
return self.path
|
||||
old = self.path.with_name(self.path.name + ".old")
|
||||
return old if (old / META).exists() else self.path
|
||||
|
||||
def meta(self) -> dict:
|
||||
try:
|
||||
return json.loads((self.path / META).read_text(encoding="utf-8"))
|
||||
return json.loads((self._live() / META).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
def ready(self) -> bool:
|
||||
"""Built, not empty, and built with TODAY's stemmer: an index from another `plstem.VERSION`
|
||||
holds stems no query produces any more, so it is not ready — `indexing.ensure_index`
|
||||
rebuilds it from Postgres (no download)."""
|
||||
"""Can ANSWER: built, not empty, with today's stemmer and in a format today's code can
|
||||
query (`READABLE`). An older format or another analysis still answers — "ready, rebuild
|
||||
pending" (`current()` is False) — until `indexing.ensure_index` swaps the rebuild in, so a
|
||||
deploy that bumps `FORMAT` never leaves the source skipped for the length of a rebuild.
|
||||
Another `plstem.VERSION` holds stems no query produces any more: not ready."""
|
||||
meta = self.meta()
|
||||
return self.available and bool(meta.get("docs")) and \
|
||||
meta.get("stemmer") == plstem.VERSION and meta.get("format") == FORMAT
|
||||
meta.get("stemmer") == plstem.VERSION and meta.get("format") in READABLE
|
||||
|
||||
def current(self) -> bool:
|
||||
"""Ready AND built exactly as today's code builds it (`FORMAT`, `analysis.ident`)."""
|
||||
meta = self.meta()
|
||||
return self.ready() and meta.get("format") == FORMAT and \
|
||||
meta.get("analysis") == analysis.ident(self.langs)
|
||||
|
||||
def rebuild_pending(self) -> bool:
|
||||
return self.ready() and not self.current()
|
||||
|
||||
def stale_stemmer(self) -> bool:
|
||||
"""An index exists but was built with another `plstem.VERSION` or document `FORMAT` (or
|
||||
before they were recorded): its terms must never be mixed with today's."""
|
||||
meta = self.meta()
|
||||
return bool(meta) and (meta.get("stemmer") != plstem.VERSION
|
||||
or meta.get("format") != FORMAT)
|
||||
"""An index exists but was not built as today's code builds it (another `plstem.VERSION`,
|
||||
`FORMAT` or analysis): its terms must never be mixed with today's."""
|
||||
return bool(self.meta()) and not self.current()
|
||||
|
||||
def size_bytes(self) -> int:
|
||||
try:
|
||||
@@ -150,31 +184,37 @@ class TextIndex:
|
||||
return 0
|
||||
|
||||
def _open(self):
|
||||
"""The index, reopened when another process (or a rebuild) replaced it."""
|
||||
built = self.meta().get("built_at")
|
||||
"""(the index, its format), reopened when another process (or a rebuild) replaced it —
|
||||
with the schema of the format it was BUILT in, so an older one keeps answering."""
|
||||
meta = self.meta()
|
||||
built = meta.get("built_at")
|
||||
with self._lock:
|
||||
if self._index is None or built != self._opened_at:
|
||||
self._index = tantivy.Index(self._schema, path=str(self.path))
|
||||
self._opened_at = built
|
||||
return self._index
|
||||
fmt = meta.get("format", FORMAT)
|
||||
self._index = tantivy.Index(_schema(fmt), path=str(self._live()))
|
||||
self._opened_at, self._opened_format = built, fmt
|
||||
return self._index, self._opened_format
|
||||
|
||||
def _write_meta(self, path: Path, marker, docs: int) -> None:
|
||||
(path / META).write_text(json.dumps({
|
||||
"marker": marker, "docs": docs, "stemmer": plstem.VERSION, "format": FORMAT,
|
||||
"analysis": analysis.ident(self.langs),
|
||||
"built_at": dt.datetime.now(dt.UTC).isoformat(timespec="microseconds")}),
|
||||
encoding="utf-8")
|
||||
|
||||
@staticmethod
|
||||
def _doc(row: dict):
|
||||
def _doc(self, row: dict):
|
||||
text = row.get("text") or ""
|
||||
heading, first = split_lead(text)
|
||||
# the text in its own language (a CELLAR row records it); the title in the index's first
|
||||
lang = row.get("lang") if row.get("lang") in self.langs else self.langs[0]
|
||||
an = analysis.analyse
|
||||
return tantivy.Document(key=f"{row['group']}#{row['ord']}", group=str(row["group"]),
|
||||
tag=list(row.get("tags") or []),
|
||||
title=plstem.analyse(row.get("title") or "", keep_stopwords=True),
|
||||
head=plstem.analyse(heading), lead=plstem.analyse(first),
|
||||
title=an(row.get("title") or "", self.langs[0], keep_stopwords=True),
|
||||
head=an(heading, lang), lead=an(first, lang),
|
||||
# function words stay in the body: the exact-phrase check needs
|
||||
# their positions ("umowa o pracę"); matching never asks for them
|
||||
body=plstem.analyse(text, keep_stopwords=True),
|
||||
body=an(text, lang, keep_stopwords=True),
|
||||
day=day(row.get("date")), prior=float(row.get("prior") or 1.0))
|
||||
|
||||
# ── building ──
|
||||
@@ -241,48 +281,41 @@ class TextIndex:
|
||||
def search(self, q: str, *, offset: int = 0, limit: int = 20, date_from: str | None = None,
|
||||
date_to: str | None = None, tags: Iterable[str] = (),
|
||||
exclude_tags: Iterable[str] = ("sup",)) -> tuple[list[dict], int]:
|
||||
"""Groups ranked by their best part: `[{group, score, n, hits: [{ord, score}]}]`, total.
|
||||
`tags` must ALL be on a part (exact filters). With no query stems but a tag, every part
|
||||
"""Groups ranked by their best part: `[{group, score, n, partial, hits: [{ord, score}]}]`,
|
||||
total. Every content word must match (or the whole of a thesaurus variant of the query,
|
||||
weighted `EXPANSION_BOOST`); only when nothing does, the PARTIAL query answers — at
|
||||
least `PARTIAL_SHARE` of the words — and every group it returns says `partial: True`.
|
||||
`tags` must ALL be on a part (exact filters). With no query terms but a tag, every part
|
||||
carrying the tags matches (a case-number lookup)."""
|
||||
terms = plstem.query_terms(q)
|
||||
stems = [t[0] for t in terms]
|
||||
tags = [t for t in tags if t]
|
||||
if (not stems and not tags) or not self.ready():
|
||||
if not self.ready():
|
||||
return [], 0
|
||||
T = tantivy
|
||||
s = self._schema
|
||||
musts = []
|
||||
for term in terms:
|
||||
# per field the BEST of the word's stems ("zachowek" | "zachowk": one word, counted
|
||||
# once), then the fields add up
|
||||
fields = []
|
||||
for field, boost in FIELDS:
|
||||
one = [T.Query.term_query(s, field, v) for v in term]
|
||||
q_ = one[0] if len(one) == 1 else T.Query.disjunction_max_query(one)
|
||||
fields.append((T.Occur.Should, q_ if boost == 1.0 else T.Query.boost_query(q_, boost)))
|
||||
musts.append((T.Occur.Must, T.Query.boolean_query(fields)))
|
||||
musts += [(T.Occur.Should, q_) for q_ in self._proximity(q, terms)]
|
||||
for tag in tags:
|
||||
musts.append((T.Occur.Must, T.Query.term_query(s, "tag", tag)))
|
||||
for tag in exclude_tags: # "sup" = a consolidated text a newer one replaced
|
||||
musts.append((T.Occur.MustNot, T.Query.term_query(s, "tag", tag)))
|
||||
if date_from or date_to:
|
||||
musts.append((T.Occur.Must, T.Query.range_query(
|
||||
s, "day", T.FieldType.Integer, day(date_from) or 0, day(date_to) or 99991231)))
|
||||
with self._lock:
|
||||
index = self._open()
|
||||
index.reload()
|
||||
searcher = index.searcher()
|
||||
result = searcher.search(T.Query.boolean_query(musts), TOP_PARTS)
|
||||
found = []
|
||||
for score, addr in result.hits:
|
||||
doc = searcher.doc(addr)
|
||||
found.append((score, doc["key"][0], (doc.get_all("prior") or [1.0])[0]))
|
||||
index, fmt = self._open()
|
||||
plain = fmt < 3 # a format-2 index: plstem stems, no thesaurus
|
||||
langs = self.langs[:1] if plain else self.langs
|
||||
terms = analysis.query_terms(q, langs, plain=plain)
|
||||
if not terms and not tags:
|
||||
return [], 0
|
||||
variants = [terms] + ([] if plain else [
|
||||
analysis.query_terms(e, langs) for e in analysis.expansions(q, langs[0])])
|
||||
s = _schema(fmt)
|
||||
filters = self._filters(s, tags, exclude_tags, date_from, date_to)
|
||||
prox = self._proximity(q, terms, s, plain)
|
||||
match = self._match(s, variants, None) if terms else None
|
||||
found = self._run(index, fmt, match, prox, filters)
|
||||
partial = False
|
||||
need = max(1, math.ceil(PARTIAL_SHARE * len(terms)))
|
||||
if found == [] and need < len(terms):
|
||||
found = self._run(index, fmt, self._match(s, variants, need), prox, filters)
|
||||
partial = bool(found)
|
||||
if found is None: # the index was swapped to another format under us
|
||||
return self.search(q, offset=offset, limit=limit, date_from=date_from,
|
||||
date_to=date_to, tags=tags, exclude_tags=exclude_tags)
|
||||
groups: dict[str, dict] = {}
|
||||
for score, key, prior in found:
|
||||
g, _, o = key.rpartition("#")
|
||||
grp = groups.setdefault(g, {"group": g, "score": 0.0, "n": 0, "hits": [],
|
||||
"prior": prior})
|
||||
"prior": prior, "partial": partial})
|
||||
grp["n"] += 1
|
||||
grp["score"] = max(grp["score"], score)
|
||||
if len(grp["hits"]) < HITS_PER_GROUP:
|
||||
@@ -293,12 +326,75 @@ class TextIndex:
|
||||
reverse=True)
|
||||
return ranked[offset:offset + limit], len(ranked)
|
||||
|
||||
def _proximity(self, q: str, terms: list[list[str]]) -> list:
|
||||
@staticmethod
|
||||
def _word(s, term: list[str]):
|
||||
"""One query word: per field the BEST of its terms ("zachowek" | "zachowk": one word,
|
||||
counted once), then the fields add up."""
|
||||
T = tantivy
|
||||
fields = []
|
||||
for field, boost in FIELDS:
|
||||
one = [T.Query.term_query(s, field, v) for v in term]
|
||||
q_ = one[0] if len(one) == 1 else T.Query.disjunction_max_query(one)
|
||||
fields.append((T.Occur.Should, q_ if boost == 1.0 else T.Query.boost_query(q_, boost)))
|
||||
return T.Query.boolean_query(fields)
|
||||
|
||||
def _match(self, s, variants: list[list[list[str]]], need: int | None):
|
||||
"""What a part must match: every word of the query (`need` None) or `need` of them — of the
|
||||
query as typed, or of one of its thesaurus variants (weighted lower)."""
|
||||
T = tantivy
|
||||
alts = []
|
||||
for i, words in enumerate(variants):
|
||||
clauses = [self._word(s, t) for t in words]
|
||||
if need is None or need >= len(clauses):
|
||||
sets = [clauses]
|
||||
else:
|
||||
sets = [list(c) for c in 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))
|
||||
return alts[0] if len(alts) == 1 else T.Query.boolean_query([(T.Occur.Should, a) for a in alts])
|
||||
|
||||
@staticmethod
|
||||
def _filters(s, tags, exclude_tags, date_from, date_to) -> list:
|
||||
T = tantivy
|
||||
out = [(T.Occur.Must, T.Query.term_query(s, "tag", tag)) for tag in tags]
|
||||
# "sup" = a consolidated text a newer one replaced
|
||||
out += [(T.Occur.MustNot, T.Query.term_query(s, "tag", tag)) for tag in exclude_tags]
|
||||
if date_from or date_to:
|
||||
out.append((T.Occur.Must, T.Query.range_query(
|
||||
s, "day", T.FieldType.Integer, day(date_from) or 0, day(date_to) or 99991231)))
|
||||
return out
|
||||
|
||||
def _run(self, index, fmt: int, match, prox: list, filters: list):
|
||||
"""(score, key, prior) of the top parts; None when the index changed format under us."""
|
||||
T = tantivy
|
||||
query = T.Query.boolean_query(([(T.Occur.Must, match)] if match is not None else [])
|
||||
+ [(T.Occur.Should, p) for p in prox] + filters)
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
with self._lock:
|
||||
index.reload()
|
||||
searcher = index.searcher()
|
||||
result = searcher.search(query, TOP_PARTS)
|
||||
return [(score, doc["key"][0], (doc.get_all("prior") or [1.0])[0])
|
||||
for score, addr in result.hits for doc in [searcher.doc(addr)]]
|
||||
except (ValueError, OSError):
|
||||
# another worker swapped a rebuild in under us (our directory is gone): the
|
||||
# query was built for the format we opened, so reopen and ask once more
|
||||
if attempt == 2:
|
||||
raise
|
||||
with self._lock:
|
||||
self._index = None
|
||||
index, fmt2 = self._open()
|
||||
if fmt2 != fmt:
|
||||
return None
|
||||
return []
|
||||
|
||||
def _proximity(self, q: str, terms: list[list[str]], s, plain: bool) -> list:
|
||||
"""The SHOULD clauses that reward words found together: the content stems as a phrase
|
||||
(slop `SLOP`, in the body and the title), each adjacent pair of them, and the whole query
|
||||
as typed — function words included — word for word in the body."""
|
||||
T = tantivy
|
||||
s = self._schema
|
||||
out = []
|
||||
if len(terms) > 1:
|
||||
# every combination of the words' alternatives ("najem" → naj | najm), capped
|
||||
@@ -314,7 +410,7 @@ class TextIndex:
|
||||
for a, b in zip(terms, terms[1:], strict=False):
|
||||
out.append(T.Query.boost_query(
|
||||
T.Query.phrase_query(s, "body", [a[0], b[0]], SLOP), PAIR_BOOST))
|
||||
exact = plstem.stems(q, keep_stopwords=True)
|
||||
exact = analysis.analyse(q, self.langs[0], keep_stopwords=True, plain=plain).split()
|
||||
if len(exact) > len(terms) and len(exact) > 1:
|
||||
out.append(T.Query.boost_query(T.Query.phrase_query(s, "body", exact), EXACT_BOOST))
|
||||
return out
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
"""A daily UTC time window (`"23:00-05:00"`), for the off-peak SAOS dump ingestor.
|
||||
"""A daily time window (`"23:00-05:00"`), for the SAOS dump's first full import.
|
||||
|
||||
Its own module, with no imports from the app, because `config.py` validates the setting with it.
|
||||
UTC, not Europe/Warsaw, on purpose: a slim image need not carry a time-zone database, and an
|
||||
off-peak window an hour off in summer is still off-peak.
|
||||
Read in INSIDER_SCHEDULE_TZ (Europe/Warsaw by default, DST-aware — the image carries `tzdata`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -20,17 +19,18 @@ def _minutes(hm: str) -> int:
|
||||
|
||||
|
||||
def parse_window(spec: str) -> tuple[int, int]:
|
||||
"""`"23:00-05:00"` → (1380, 300) minutes after midnight UTC. `"00:00-24:00"`-style "always" is
|
||||
"""`"23:00-05:00"` → (1380, 300) minutes after midnight. `"00:00-24:00"`-style "always" is
|
||||
written `"00:00-00:00"` (start == end = the whole day)."""
|
||||
start, sep, end = (spec or "").partition("-")
|
||||
if not sep:
|
||||
raise ValueError("a window is HH:MM-HH:MM (UTC), e.g. 23:00-05:00")
|
||||
raise ValueError("a window is HH:MM-HH:MM, e.g. 23:00-05:00")
|
||||
return _minutes(start), _minutes(end)
|
||||
|
||||
|
||||
def in_window(spec: str, now: dt.datetime) -> bool:
|
||||
def in_window(spec: str, now: dt.datetime, tz: str = "UTC") -> bool:
|
||||
from zoneinfo import ZoneInfo
|
||||
start, end = parse_window(spec)
|
||||
t = now.astimezone(dt.UTC)
|
||||
t = now.astimezone(ZoneInfo(tz))
|
||||
m = t.hour * 60 + t.minute
|
||||
if start == end:
|
||||
return True
|
||||
|
||||
@@ -57,10 +57,15 @@ sse-starlette==2.2.1 # BSD-3-Clause — mcp's dependency, pinned to a s
|
||||
pypdfium2==4.30.0 # Apache-2.0 OR BSD-3-Clause (PDFium: BSD-3-Clause + permissive third-party)
|
||||
|
||||
# INDEXED mode's full-text engine — embedded (no server, no JVM), BM25; wheels for manylinux
|
||||
# x86_64/aarch64 and win_amd64. Polish stemming happens in Python (app/integrations/plstem.py).
|
||||
# x86_64/aarch64 and win_amd64. Language analysis happens in Python (app/integrations/analysis.py:
|
||||
# the sjp.pl lexicon built into the image, plstem as the fallback) — no dependency.
|
||||
# Only imported when INSIDER_INDEX_ENABLED (import-guarded in app/services/textindex.py).
|
||||
tantivy==0.26.2 # MIT
|
||||
|
||||
# Import schedules: INSIDER_*_SCHEDULE cron expressions, evaluated in INSIDER_SCHEDULE_TZ.
|
||||
croniter==6.0.0 # MIT (pulls python-dateutil Apache-2.0/BSD-3, pytz MIT, six MIT)
|
||||
tzdata==2026.5 # Apache-2.0 — IANA zones for zoneinfo; a slim image ships none
|
||||
|
||||
# Outbound HTTP — the ONE client, used only from app/integrations/.
|
||||
httpx==0.28.1 # BSD-3-Clause
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Build the language lexicons (`lexicon/<lang>.lex`) from their data packages — run by the Dockerfile.
|
||||
|
||||
python scripts/build_lexicon.py # every package in analysis.PACKAGES, downloaded
|
||||
python scripts/build_lexicon.py --zip odm.zip # from an archive already on disk (offline)
|
||||
python scripts/build_lexicon.py --best-effort # a failure leaves no lexicon instead of failing
|
||||
|
||||
Polite: per package one request for the download page (the archive's name changes with every
|
||||
release, and old releases are removed — a pinned URL would break the build within a month) and one
|
||||
for the archive. The archive's own README must state the licence Insider takes it under
|
||||
(`DataPackage.licence_evidence`), or nothing is built. The lexicon records the archive's name and
|
||||
SHA-256 (its `ident`): an index built with another lexicon is rebuilt from Postgres.
|
||||
|
||||
Without a lexicon the analyzer falls back to its rule-based stemmer (plstem for Polish).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import sys
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from app.integrations import analysis, lexicon # noqa: E402
|
||||
|
||||
UA = "Insider-lexicon-build/1 (self-hosted legal search; one download per image build)"
|
||||
TIMEOUT = 120
|
||||
|
||||
|
||||
def _get(url: str) -> bytes:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r: # noqa: S310 — a fixed https URL
|
||||
return r.read()
|
||||
|
||||
|
||||
def fetch(pkg: analysis.DataPackage) -> tuple[str, bytes]:
|
||||
page = _get(pkg.page).decode("utf-8", "replace")
|
||||
m = pkg.archive.search(page)
|
||||
if not m:
|
||||
raise RuntimeError(f"{pkg.page}: no archive matching {pkg.archive.pattern}")
|
||||
name = m.group(1)
|
||||
return name, _get(pkg.page.rstrip("/") + "/" + name)
|
||||
|
||||
|
||||
def build(pkg: analysis.DataPackage, name: str, data: bytes, out: Path) -> Path:
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||||
readme = next((n for n in z.namelist() if n.lower().startswith("readme")), None)
|
||||
text = z.read(readme).decode("utf-8", "replace") if readme else ""
|
||||
if pkg.licence_evidence not in text:
|
||||
raise RuntimeError(f"{name}: its README does not offer {pkg.licence} "
|
||||
f"(no {pkg.licence_evidence!r}) — refusing to build")
|
||||
with z.open(pkg.member) as fh:
|
||||
mapping = pkg.parse(io.TextIOWrapper(fh, encoding="utf-8"), analysis.get(pkg.lang).normalise)
|
||||
path = out / f"{pkg.lang}.lex"
|
||||
lexicon.write(mapping, path, f"{name} sha256:{digest[:16]}")
|
||||
print(f"{pkg.lang}: {name} sha256 {digest} -> {path} ({len(mapping)} forms, "
|
||||
f"{path.stat().st_size // 1_000_000} MB)")
|
||||
return path
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("--out", type=Path, default=analysis.LEXICON_DIR)
|
||||
ap.add_argument("--lang", action="append", help="only these languages (default: every package)")
|
||||
ap.add_argument("--zip", type=Path, help="the archive on disk instead of a download (one --lang)")
|
||||
ap.add_argument("--best-effort", action="store_true",
|
||||
help="report a failure and exit 0: the analyzers fall back to their stemmers")
|
||||
a = ap.parse_args()
|
||||
langs = a.lang or list(analysis.PACKAGES)
|
||||
failed = 0
|
||||
for lang in langs:
|
||||
pkg = analysis.PACKAGES[lang]
|
||||
try:
|
||||
if a.zip:
|
||||
name, data = a.zip.name, a.zip.read_bytes()
|
||||
else:
|
||||
name, data = fetch(pkg)
|
||||
build(pkg, name, data, a.out)
|
||||
except Exception as exc: # noqa: BLE001 — reported, and fatal unless --best-effort
|
||||
failed += 1
|
||||
print(f"{lang}: lexicon NOT built: {type(exc).__name__}: {exc}", file=sys.stderr)
|
||||
return 0 if a.best_effort or not failed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -29,8 +29,8 @@ sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from search_eval import FIXTURE, REGRESSION # noqa: E402
|
||||
|
||||
from app.integrations import analysis # noqa: E402
|
||||
from app.integrations import dzu_md as dzu # noqa: E402
|
||||
from app.integrations import plstem # noqa: E402
|
||||
from app.services.htmltext import html_to_text # noqa: E402
|
||||
|
||||
#: current t.j. the queries must find, older t.j. of the same acts, and the past wrong winners
|
||||
@@ -50,9 +50,9 @@ MUST = {"DU/2023/725": {"19a"}, "DU/2026/1245": {"22", "25", "29", "30", "52"},
|
||||
def _wanted(num: str | None, text: str, eli: str, ordinal: int) -> bool:
|
||||
if ordinal <= FIRST or (num and dzu.art_label(num) in MUST.get(eli, ())):
|
||||
return True
|
||||
have = set(plstem.stems(text))
|
||||
have = set(analysis.analyse(text).split())
|
||||
for q, *_ in REGRESSION:
|
||||
want = [t[0] for t in plstem.query_terms(q)]
|
||||
want = [t[0] for t in analysis.query_terms(q)]
|
||||
# every stem of a multi-word query (prefix match: "najm" for najem), or a one-word query
|
||||
if want and all(any(h.startswith(w) for h in have) for w in want):
|
||||
return True
|
||||
|
||||
@@ -157,6 +157,13 @@ for header in ("X-Content-Type-Options", "X-Frame-Options", "Content-Security-Po
|
||||
check(header in edge_py, f"app/edge.py does not set {header}")
|
||||
check("--no-server-header" in dockerfile, "uvicorn announces itself (no --no-server-header)",
|
||||
"uvicorn runs with --no-server-header")
|
||||
# the language lexicons are BUILT into the image (never committed), before the drop to USER app
|
||||
_lexicon_run = dockerfile.find("scripts/build_lexicon.py")
|
||||
check(_lexicon_run != -1 and _lexicon_run < dockerfile.find("USER app"),
|
||||
"the Dockerfile does not build the language lexicons (scripts/build_lexicon.py before USER)",
|
||||
"the image builds the language lexicons (sjp.pl, CC BY 4.0)")
|
||||
check("lexicon/" in read("backend/.dockerignore") and "backend/lexicon/" in read(".gitignore"),
|
||||
"a locally built lexicon could reach git or the build context (.gitignore / .dockerignore)")
|
||||
|
||||
# ── secrets and least privilege ───────────────────────────────────────────────
|
||||
check("app" in roles_sh and "migrator" in roles_sh,
|
||||
|
||||
@@ -9,12 +9,31 @@ from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import tempfile
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
RUN_INTEGRATION = os.environ.get("INSIDER_RUN_INTEGRATION") == "1"
|
||||
|
||||
# The language analysis uses the TEST lexicon — a small committed subset of sjp.pl's inflection list
|
||||
# (`fixtures/odm_fixture.txt`, CC BY 4.0) built here, offline — never a lexicon on the machine.
|
||||
LEXICON_FIXTURE = Path(__file__).parent / "fixtures" / "odm_fixture.txt"
|
||||
|
||||
|
||||
def _test_lexicon() -> Path:
|
||||
from app.integrations import analysis, lexicon
|
||||
out = Path(tempfile.mkdtemp(prefix="insider-lexicon-"))
|
||||
with open(LEXICON_FIXTURE, encoding="utf-8") as fh:
|
||||
mapping = lexicon.parse_sjp(fh, analysis.get("pl").normalise)
|
||||
lexicon.write(mapping, out / "pl.lex", "odm_fixture.txt")
|
||||
analysis.configure(out)
|
||||
return out
|
||||
|
||||
|
||||
TEST_LEXICON_DIR = _test_lexicon()
|
||||
|
||||
integration = pytest.mark.skipif(
|
||||
not RUN_INTEGRATION,
|
||||
reason="set INSIDER_RUN_INTEGRATION=1 with a migrated Postgres to run these",
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
# A subset of the sjp.pl inflection list ("Lista słów z odmianami", sjp-odm-20260901.zip,
|
||||
# https://sjp.pl/sl/odmiany/), CC BY 4.0 — the test vocabulary only, lines verbatim.
|
||||
alkohol, alkoholach, alkoholami, alkohole, alkoholem, alkoholi, alkoholom, alkoholowi, alkoholów, alkoholu
|
||||
bez, beze
|
||||
bez, bzach, bzami, bzem, bzie, bzom, bzowi, bzów, bzu, bzy
|
||||
cywilny, cywilna, cywilną, cywilne, cywilnego, cywilnej, cywilnemu, cywilni, cywilnie, cywilnych, cywilnym, cywilnymi, niecywilna, niecywilną, niecywilne, niecywilnego, niecywilnej, niecywilnemu, niecywilni, niecywilnie, niecywilny, niecywilnych, niecywilnym, niecywilnymi
|
||||
dane, danych, danym, danymi
|
||||
dany, dana, daną, dane, danego, danej, danemu, dani, danych, danym, danymi, niedana, niedaną, niedane, niedanego, niedanej, niedanemu, niedani, niedany, niedanych, niedanym, niedanymi
|
||||
dziecię, dzieciąt, dziecięcia, dziecięciem, dziecięciu, dziecięta, dzieciętach, dzieciętami, dzieciętom
|
||||
dziecko, dzieci, dzieciach, dzieciom, dziecka, dzieckiem, dziecku, dziećmi
|
||||
id, idach, idami, idem, idom, idowi, idów, idu, idy, idzie
|
||||
iścić, iszczą, iszcząc, iszcząca, iszczącą, iszczące, iszczącego, iszczącej, iszczącemu, iszczący, iszczących, iszczącym, iszczącymi, iszczeni, iszczenia, iszczeniach, iszczeniami, iszczenie, iszczeniem, iszczeniom, iszczeniu, iszczeń, iszczę, iszczona, iszczoną, iszczone, iszczonego, iszczonej, iszczonemu, iszczono, iszczony, iszczonych, iszczonym, iszczonymi, iści, iścicie, iścili, iściliby, iścilibyście, iścilibyśmy, iściliście, iściliśmy, iścił, iściła, iściłaby, iściłabym, iściłabyś, iściłam, iściłaś, iściłby, iściłbym, iściłbyś, iściłem, iściłeś, iściło, iściłoby, iściły, iściłyby, iściłybyście, iściłybyśmy, iściłyście, iściłyśmy, iścimy, iścisz, iść, iśćcie, iśćcież, iśćmy, iśćmyż, iśćże, nieiszcząca, nieiszczącą, nieiszczące, nieiszczącego, nieiszczącej, nieiszczącemu, nieiszczący, nieiszczących, nieiszczącym, nieiszczącymi, nieiszczeni, nieiszczenia, nieiszczeniach, nieiszczeniami, nieiszczenie, nieiszczeniem, nieiszczeniom, nieiszczeniu, nieiszczeń, nieiszczona, nieiszczoną, nieiszczone, nieiszczonego, nieiszczonej, nieiszczonemu, nieiszczony, nieiszczonych, nieiszczonym, nieiszczonymi
|
||||
iść, idą, idąc, idąca, idącą, idące, idącego, idącej, idącemu, idący, idących, idącym, idącymi, idę, idzie, idziecie, idziemy, idziesz, idź, idźcie, idźcież, idźmy, idźmyż, idźże, nieidąca, nieidącą, nieidące, nieidącego, nieidącej, nieidącemu, nieidący, nieidących, nieidącym, nieidącymi, szedł, szedłby, szedłbym, szedłbyś, szedłem, szedłeś, szli, szliby, szlibyście, szlibyśmy, szliście, szliśmy, szła, szłaby, szłabym, szłabyś, szłam, szłaś, szło, szłoby, szły, szłyby, szłybyście, szłybyśmy, szłyście, szłyśmy
|
||||
jazda
|
||||
jazda, jazd, jazdach, jazdami, jazdą, jazdę, jazdo, jazdom, jazdy, jeździe
|
||||
kodeks, kodeksach, kodeksami, kodeksem, kodeksie, kodeksom, kodeksowi, kodeksów, kodeksu, kodeksy
|
||||
konkurencja, konkurencjach, konkurencjami, konkurencją, konkurencje, konkurencję, konkurencji, konkurencjo, konkurencjom, konkurencyj
|
||||
konsument, konsumenci, konsumencie, konsumenta, konsumentach, konsumentami, konsumentem, konsumentom, konsumentowi, konsumentów, konsumenty
|
||||
mam
|
||||
mama, mam, mamach, mamami, mamą, mamę, mamie, mamo, mamom, mamy
|
||||
mamić, mam, mamcie, mamcież, mami, mamią, mamiąc, mamiąca, mamiącą, mamiące, mamiącego, mamiącej, mamiącemu, mamiący, mamiących, mamiącym, mamiącymi, mamicie, mamieni, mamienia, mamieniach, mamieniami, mamienie, mamieniem, mamieniom, mamieniu, mamień, mamię, mamili, mamiliby, mamilibyście, mamilibyśmy, mamiliście, mamiliśmy, mamił, mamiła, mamiłaby, mamiłabym, mamiłabyś, mamiłam, mamiłaś, mamiłby, mamiłbym, mamiłbyś, mamiłem, mamiłeś, mamiło, mamiłoby, mamiły, mamiłyby, mamiłybyście, mamiłybyśmy, mamiłyście, mamiłyśmy, mamimy, mamiona, mamioną, mamione, mamionego, mamionej, mamionemu, mamiono, mamiony, mamionych, mamionym, mamionymi, mamisz, mammy, mammyż, mamże, niemamiąca, niemamiącą, niemamiące, niemamiącego, niemamiącej, niemamiącemu, niemamiący, niemamiących, niemamiącym, niemamiącymi, niemamieni, niemamienia, niemamieniach, niemamieniami, niemamienie, niemamieniem, niemamieniom, niemamieniu, niemamień, niemamiona, niemamioną, niemamione, niemamionego, niemamionej, niemamionemu, niemamiony, niemamionych, niemamionym, niemamionymi
|
||||
mieć, ma, macie, mają, mając, mająca, mającą, mające, mającego, mającej, mającemu, mający, mających, mającym, mającymi, mam, mamy, masz, miał, miała, miałaby, miałabym, miałabyś, miałam, miałaś, miałby, miałbym, miałbyś, miałem, miałeś, miało, miałoby, miały, miałyby, miałybyście, miałybyśmy, miałyście, miałyśmy, miana, mianą, miane, mianego, mianej, mianemu, miani, miano, miany, mianych, mianym, mianymi, miej, miejcie, miejcież, miejmy, miejmyż, miejże, mieli, mieliby, mielibyście, mielibyśmy, mieliście, mieliśmy, mienia, mieniach, mieniami, mienie, mieniem, mieniom, mieniu, mień, niemająca, niemającą, niemające, niemającego, niemającej, niemającemu, niemający, niemających, niemającym, niemającymi, niemiana, niemianą, niemiane, niemianego, niemianej, niemianemu, niemiani, niemiany, niemianych, niemianym, niemianymi, niemienia, niemieniach, niemieniami, niemienie, niemieniem, niemieniom, niemieniu, niemień
|
||||
mieść, mieceni, miecenia, mieceniach, mieceniami, miecenie, mieceniem, mieceniom, mieceniu, mieceń, miecie, mieciecie, mieciemy, mieciesz, mieciona, miecioną, miecione, miecionego, miecionej, miecionemu, mieciono, mieciony, miecionych, miecionym, miecionymi, mieć, miećcie, miećcież, miećmy, miećmyż, miećże, mietli, mietliby, mietlibyście, mietlibyśmy, mietliście, mietliśmy, miotą, miotąc, miotąca, miotącą, miotące, miotącego, miotącej, miotącemu, miotący, miotących, miotącym, miotącymi, miotę, miotła, miotłaby, miotłabym, miotłabyś, miotłam, miotłaś, miotłem, miotłeś, miotło, miotłoby, miotły, miotłyby, miotłybyście, miotłybyśmy, miotłyście, miotłyśmy, miótł, miótłby, miótłbym, miótłbyś, niemieceni, niemiecenia, niemieceniach, niemieceniami, niemiecenie, niemieceniem, niemieceniom, niemieceniu, niemieceń, niemieciona, niemiecioną, niemiecione, niemiecionego, niemiecionej, niemiecionemu, niemieciony, niemiecionych, niemiecionym, niemiecionymi, niemiotąca, niemiotącą, niemiotące, niemiotącego, niemiotącej, niemiotącemu, niemiotący, niemiotących, niemiotącym, niemiotącymi
|
||||
najem, najmach, najmami, najmem, najmie, najmom, najmowi, najmów, najmu, najmy
|
||||
najeść, najadł, najadła, najadłaby, najadłabym, najadłabyś, najadłam, najadłaś, najadłby, najadłbym, najadłbyś, najadłem, najadłeś, najadło, najadłoby, najadłszy, najadły, najadłyby, najadłybyście, najadłybyśmy, najadłyście, najadłyśmy, naje, najecie, najedli, najedliby, najedlibyście, najedlibyśmy, najedliście, najedliśmy, najedz, najedzą, najedzcie, najedzcież, najedzenia, najedzeniach, najedzeniami, najedzenie, najedzeniem, najedzeniom, najedzeniu, najedzeń, najedzmy, najedzmyż, najedzono, najedzże, najem, najemy, najesz, nienajedzenia, nienajedzeniach, nienajedzeniami, nienajedzenie, nienajedzeniem, nienajedzeniom, nienajedzeniu, nienajedzeń
|
||||
najmowy, najmowa, najmową, najmowe, najmowego, najmowej, najmowemu, najmowi, najmowych, najmowym, najmowymi, nienajmowa, nienajmową, nienajmowe, nienajmowego, nienajmowej, nienajmowemu, nienajmowi, nienajmowy, nienajmowych, nienajmowym, nienajmowymi
|
||||
ochrona, ochron, ochronach, ochronami, ochroną, ochronę, ochronie, ochrono, ochronom, ochrony
|
||||
ochronić, nieochronieni, nieochronienia, nieochronieniach, nieochronieniami, nieochronienie, nieochronieniem, nieochronieniom, nieochronieniu, nieochronień, nieochroniona, nieochronioną, nieochronione, nieochronionego, nieochronionej, nieochronionemu, nieochroniony, nieochronionych, nieochronionym, nieochronionymi, ochroni, ochronią, ochronicie, ochronieni, ochronienia, ochronieniach, ochronieniami, ochronienie, ochronieniem, ochronieniom, ochronieniu, ochronień, ochronię, ochronili, ochroniliby, ochronilibyście, ochronilibyśmy, ochroniliście, ochroniliśmy, ochronił, ochroniła, ochroniłaby, ochroniłabym, ochroniłabyś, ochroniłam, ochroniłaś, ochroniłby, ochroniłbym, ochroniłbyś, ochroniłem, ochroniłeś, ochroniło, ochroniłoby, ochroniły, ochroniłyby, ochroniłybyście, ochroniłybyśmy, ochroniłyście, ochroniłyśmy, ochronimy, ochroniona, ochronioną, ochronione, ochronionego, ochronionej, ochronionemu, ochroniono, ochroniony, ochronionych, ochronionym, ochronionymi, ochronisz, ochroniwszy, ochroń, ochrońcie, ochrońcież, ochrońmy, ochrońmyż, ochrońże
|
||||
okazjonalny, nieokazjonalna, nieokazjonalną, nieokazjonalne, nieokazjonalnego, nieokazjonalnej, nieokazjonalnemu, nieokazjonalni, nieokazjonalnie, nieokazjonalny, nieokazjonalnych, nieokazjonalnym, nieokazjonalnymi, okazjonalna, okazjonalną, okazjonalne, okazjonalnego, okazjonalnej, okazjonalnemu, okazjonalni, okazjonalnie, okazjonalnych, okazjonalnym, okazjonalnymi
|
||||
osobowy, nieosobowa, nieosobową, nieosobowe, nieosobowego, nieosobowej, nieosobowemu, nieosobowi, nieosobowo, nieosobowy, nieosobowych, nieosobowym, nieosobowymi, osobowa, osobową, osobowe, osobowego, osobowej, osobowemu, osobowi, osobowo, osobowych, osobowym, osobowymi
|
||||
osobowy, osobowe, osobowego, osobowemu, osobowych, osobowym, osobowymi
|
||||
praca, prac, pracach, pracami, pracą, prace, pracę, praco, pracom, pracy
|
||||
pracować, niepracowania, niepracowaniach, niepracowaniami, niepracowanie, niepracowaniem, niepracowaniom, niepracowaniu, niepracowań, niepracująca, niepracującą, niepracujące, niepracującego, niepracującej, niepracującemu, niepracujący, niepracujących, niepracującym, niepracującymi, pracowali, pracowaliby, pracowalibyście, pracowalibyśmy, pracowaliście, pracowaliśmy, pracował, pracowała, pracowałaby, pracowałabym, pracowałabyś, pracowałam, pracowałaś, pracowałby, pracowałbym, pracowałbyś, pracowałem, pracowałeś, pracowało, pracowałoby, pracowały, pracowałyby, pracowałybyście, pracowałybyśmy, pracowałyście, pracowałyśmy, pracowania, pracowaniach, pracowaniami, pracowanie, pracowaniem, pracowaniom, pracowaniu, pracowano, pracowań, pracuj, pracują, pracując, pracująca, pracującą, pracujące, pracującego, pracującej, pracującemu, pracujący, pracujących, pracującym, pracującymi, pracujcie, pracujcież, pracuje, pracujecie, pracujemy, pracujesz, pracuję, pracujmy, pracujmyż, pracujże
|
||||
pracownica, pracownic, pracownicach, pracownicami, pracownicą, pracownice, pracownicę, pracownico, pracownicom, pracownicy
|
||||
pracownik, pracownicy, pracownika, pracownikach, pracownikami, pracowniki, pracownikiem, pracownikom, pracownikowi, pracowników, pracowniku
|
||||
prawo
|
||||
prawo, praw, prawa, prawach, prawami, prawem, prawie, prawom, prawu
|
||||
prędkość, prędkości, prędkościach, prędkościami, prędkością, prędkościom
|
||||
przedawnienie, przedawnienia, przedawnieniach, przedawnieniami, przedawnieniem, przedawnieniom, przedawnieniu, przedawnień
|
||||
przekroczenie, przekroczenia, przekroczeniach, przekroczeniami, przekroczeniem, przekroczeniom, przekroczeniu, przekroczeń
|
||||
przekroczyć, nieprzekroczeni, nieprzekroczenia, nieprzekroczeniach, nieprzekroczeniami, nieprzekroczenie, nieprzekroczeniem, nieprzekroczeniom, nieprzekroczeniu, nieprzekroczeń, nieprzekroczona, nieprzekroczoną, nieprzekroczone, nieprzekroczonego, nieprzekroczonej, nieprzekroczonemu, nieprzekroczony, nieprzekroczonych, nieprzekroczonym, nieprzekroczonymi, przekrocz, przekroczą, przekroczcie, przekroczcież, przekroczeni, przekroczenia, przekroczeniach, przekroczeniami, przekroczenie, przekroczeniem, przekroczeniom, przekroczeniu, przekroczeń, przekroczę, przekroczmy, przekroczmyż, przekroczona, przekroczoną, przekroczone, przekroczonego, przekroczonej, przekroczonemu, przekroczono, przekroczony, przekroczonych, przekroczonym, przekroczonymi, przekroczy, przekroczycie, przekroczyli, przekroczyliby, przekroczylibyście, przekroczylibyśmy, przekroczyliście, przekroczyliśmy, przekroczył, przekroczyła, przekroczyłaby, przekroczyłabym, przekroczyłabyś, przekroczyłam, przekroczyłaś, przekroczyłby, przekroczyłbym, przekroczyłbyś, przekroczyłem, przekroczyłeś, przekroczyło, przekroczyłoby, przekroczyły, przekroczyłyby, przekroczyłybyście, przekroczyłybyśmy, przekroczyłyście, przekroczyłyśmy, przekroczymy, przekroczysz, przekroczywszy, przekroczże
|
||||
roszczenie, roszczenia, roszczeniach, roszczeniami, roszczeniem, roszczeniom, roszczeniu, roszczeń
|
||||
rozwiązać, nierozwiązana, nierozwiązaną, nierozwiązane, nierozwiązanego, nierozwiązanej, nierozwiązanemu, nierozwiązani, nierozwiązania, nierozwiązaniach, nierozwiązaniami, nierozwiązanie, nierozwiązaniem, nierozwiązaniom, nierozwiązaniu, nierozwiązany, nierozwiązanych, nierozwiązanym, nierozwiązanymi, nierozwiązań, rozwiązali, rozwiązaliby, rozwiązalibyście, rozwiązalibyśmy, rozwiązaliście, rozwiązaliśmy, rozwiązał, rozwiązała, rozwiązałaby, rozwiązałabym, rozwiązałabyś, rozwiązałam, rozwiązałaś, rozwiązałby, rozwiązałbym, rozwiązałbyś, rozwiązałem, rozwiązałeś, rozwiązało, rozwiązałoby, rozwiązały, rozwiązałyby, rozwiązałybyście, rozwiązałybyśmy, rozwiązałyście, rozwiązałyśmy, rozwiązana, rozwiązaną, rozwiązane, rozwiązanego, rozwiązanej, rozwiązanemu, rozwiązani, rozwiązania, rozwiązaniach, rozwiązaniami, rozwiązanie, rozwiązaniem, rozwiązaniom, rozwiązaniu, rozwiązano, rozwiązany, rozwiązanych, rozwiązanym, rozwiązanymi, rozwiązań, rozwiązawszy, rozwiąż, rozwiążą, rozwiążcie, rozwiążcież, rozwiąże, rozwiążecie, rozwiążemy, rozwiążesz, rozwiążę, rozwiążmy, rozwiążmyż, rozwiążże
|
||||
rozwiązanie, rozwiązania, rozwiązaniach, rozwiązaniami, rozwiązaniem, rozwiązaniom, rozwiązaniu, rozwiązań
|
||||
sadz, sadza, sadzach, sadzami, sadze, sadzem, sadzom, sadzowi, sadzów, sadzu
|
||||
sadza, sadz, sadzach, sadzami, sadzą, sadze, sadzę, sadzo, sadzom, sadzy
|
||||
sąd, sądach, sądami, sądem, sądom, sądowi, sądów, sądu, sądy, sądzie
|
||||
sądowy, niesądowa, niesądową, niesądowe, niesądowego, niesądowej, niesądowemu, niesądowi, niesądowo, niesądowy, niesądowych, niesądowym, niesądowymi, sądowa, sądową, sądowe, sądowego, sądowej, sądowemu, sądowi, sądowo, sądowych, sądowym, sądowymi
|
||||
spółka, spółce, spółek, spółkach, spółkami, spółką, spółkę, spółki, spółko, spółkom
|
||||
sygnalista, sygnalistach, sygnalistami, sygnalistą, sygnalistę, sygnalisto, sygnalistom, sygnalistów, sygnalisty, sygnaliści, sygnaliście
|
||||
szla, szlach, szlami, szlą, szle, szlę, szli, szlo, szlom
|
||||
umowa, umowach, umowami, umową, umowę, umowie, umowo, umowom, umowy, umów
|
||||
umówić, nieumówieni, nieumówienia, nieumówieniach, nieumówieniami, nieumówienie, nieumówieniem, nieumówieniom, nieumówieniu, nieumówień, nieumówiona, nieumówioną, nieumówione, nieumówionego, nieumówionej, nieumówionemu, nieumówiony, nieumówionych, nieumówionym, nieumówionymi, umów, umówcie, umówcież, umówi, umówią, umówicie, umówieni, umówienia, umówieniach, umówieniami, umówienie, umówieniem, umówieniom, umówieniu, umówień, umówię, umówili, umówiliby, umówilibyście, umówilibyśmy, umówiliście, umówiliśmy, umówił, umówiła, umówiłaby, umówiłabym, umówiłabyś, umówiłam, umówiłaś, umówiłby, umówiłbym, umówiłbyś, umówiłem, umówiłeś, umówiło, umówiłoby, umówiły, umówiłyby, umówiłybyście, umówiłybyśmy, umówiłyście, umówiłyśmy, umówimy, umówiona, umówioną, umówione, umówionego, umówionej, umówionemu, umówiono, umówiony, umówionych, umówionym, umówionymi, umówisz, umówiwszy, umówmy, umówmyż, umówże
|
||||
wykonać, niewykonana, niewykonaną, niewykonane, niewykonanego, niewykonanej, niewykonanemu, niewykonani, niewykonania, niewykonaniach, niewykonaniami, niewykonanie, niewykonaniem, niewykonaniom, niewykonaniu, niewykonany, niewykonanych, niewykonanym, niewykonanymi, niewykonań, wykona, wykonacie, wykonaj, wykonają, wykonajcie, wykonajcież, wykonajmy, wykonajmyż, wykonajże, wykonali, wykonaliby, wykonalibyście, wykonalibyśmy, wykonaliście, wykonaliśmy, wykonał, wykonała, wykonałaby, wykonałabym, wykonałabyś, wykonałam, wykonałaś, wykonałby, wykonałbym, wykonałbyś, wykonałem, wykonałeś, wykonało, wykonałoby, wykonały, wykonałyby, wykonałybyście, wykonałybyśmy, wykonałyście, wykonałyśmy, wykonam, wykonamy, wykonana, wykonaną, wykonane, wykonanego, wykonanej, wykonanemu, wykonani, wykonania, wykonaniach, wykonaniami, wykonanie, wykonaniem, wykonaniom, wykonaniu, wykonano, wykonany, wykonanych, wykonanym, wykonanymi, wykonań, wykonasz, wykonawszy
|
||||
wykonanie, wykonania, wykonaniach, wykonaniami, wykonaniem, wykonaniom, wykonaniu, wykonań
|
||||
wypowiedzenie, wypowiedzenia, wypowiedzeniach, wypowiedzeniami, wypowiedzeniem, wypowiedzeniom, wypowiedzeniu, wypowiedzeń
|
||||
wypowiedzieć, niewypowiedzenia, niewypowiedzeniach, niewypowiedzeniami, niewypowiedzenie, niewypowiedzeniem, niewypowiedzeniom, niewypowiedzeniu, niewypowiedzeń, niewypowiedziana, niewypowiedzianą, niewypowiedziane, niewypowiedzianego, niewypowiedzianej, niewypowiedzianemu, niewypowiedziani, niewypowiedziany, niewypowiedzianych, niewypowiedzianym, niewypowiedzianymi, wypowie, wypowiecie, wypowiedz, wypowiedzą, wypowiedzcie, wypowiedzcież, wypowiedzenia, wypowiedzeniach, wypowiedzeniami, wypowiedzenie, wypowiedzeniem, wypowiedzeniom, wypowiedzeniu, wypowiedzeń, wypowiedział, wypowiedziała, wypowiedziałaby, wypowiedziałabym, wypowiedziałabyś, wypowiedziałam, wypowiedziałaś, wypowiedziałby, wypowiedziałbym, wypowiedziałbyś, wypowiedziałem, wypowiedziałeś, wypowiedziało, wypowiedziałoby, wypowiedziały, wypowiedziałyby, wypowiedziałybyście, wypowiedziałybyśmy, wypowiedziałyście, wypowiedziałyśmy, wypowiedziana, wypowiedzianą, wypowiedziane, wypowiedzianego, wypowiedzianej, wypowiedzianemu, wypowiedziani, wypowiedziano, wypowiedziany, wypowiedzianych, wypowiedzianym, wypowiedzianymi, wypowiedziawszy, wypowiedzieli, wypowiedzieliby, wypowiedzielibyście, wypowiedzielibyśmy, wypowiedzieliście, wypowiedzieliśmy, wypowiedzmy, wypowiedzmyż, wypowiedzże, wypowiem, wypowiemy, wypowiesz
|
||||
wypowiedź, wypowiedzi, wypowiedziach, wypowiedziami, wypowiedzią, wypowiedziom
|
||||
zachować, niezachowana, niezachowaną, niezachowane, niezachowanego, niezachowanej, niezachowanemu, niezachowani, niezachowania, niezachowaniach, niezachowaniami, niezachowanie, niezachowaniem, niezachowaniom, niezachowaniu, niezachowany, niezachowanych, niezachowanym, niezachowanymi, niezachowań, zachowa, zachowacie, zachowaj, zachowają, zachowajcie, zachowajcież, zachowajmy, zachowajmyż, zachowajże, zachowali, zachowaliby, zachowalibyście, zachowalibyśmy, zachowaliście, zachowaliśmy, zachował, zachowała, zachowałaby, zachowałabym, zachowałabyś, zachowałam, zachowałaś, zachowałby, zachowałbym, zachowałbyś, zachowałem, zachowałeś, zachowało, zachowałoby, zachowały, zachowałyby, zachowałybyście, zachowałybyśmy, zachowałyście, zachowałyśmy, zachowam, zachowamy, zachowana, zachowaną, zachowane, zachowanego, zachowanej, zachowanemu, zachowani, zachowania, zachowaniach, zachowaniami, zachowanie, zachowaniem, zachowaniom, zachowaniu, zachowano, zachowany, zachowanych, zachowanym, zachowanymi, zachowań, zachowasz, zachowawszy
|
||||
zachowek, zachowka, zachowkach, zachowkami, zachowki, zachowkiem, zachowkom, zachowkowi, zachowków, zachowku
|
||||
alimenty, alimenta, alimentach, alimentami, alimentom, alimentów
|
||||
drogowy, drogowa, drogową, drogowe, drogowego, drogowej, drogowemu, drogowi, drogowych, drogowym, drogowymi, niedrogowa, niedrogową, niedrogowe, niedrogowego, niedrogowej, niedrogowemu, niedrogowi, niedrogowy, niedrogowych, niedrogowym, niedrogowymi
|
||||
grzywna, grzywien, grzywnach, grzywnami, grzywną, grzywnę, grzywnie, grzywno, grzywnom, grzywny
|
||||
małżeństwo, małżeństw, małżeństwa, małżeństwach, małżeństwami, małżeństwem, małżeństwie, małżeństwom, małżeństwu
|
||||
mandat, mandacie, mandatach, mandatami, mandatem, mandatom, mandatowi, mandatów, mandatu, mandaty
|
||||
miejsce, miejsc, miejsca, miejscach, miejscami, miejscem, miejscom, miejscu
|
||||
parkować, nieparkowana, nieparkowaną, nieparkowane, nieparkowanego, nieparkowanej, nieparkowanemu, nieparkowani, nieparkowania, nieparkowaniach, nieparkowaniami, nieparkowanie, nieparkowaniem, nieparkowaniom, nieparkowaniu, nieparkowany, nieparkowanych, nieparkowanym, nieparkowanymi, nieparkowań, nieparkująca, nieparkującą, nieparkujące, nieparkującego, nieparkującej, nieparkującemu, nieparkujący, nieparkujących, nieparkującym, nieparkującymi, parkowali, parkowaliby, parkowalibyście, parkowalibyśmy, parkowaliście, parkowaliśmy, parkował, parkowała, parkowałaby, parkowałabym, parkowałabyś, parkowałam, parkowałaś, parkowałby, parkowałbym, parkowałbyś, parkowałem, parkowałeś, parkowało, parkowałoby, parkowały, parkowałyby, parkowałybyście, parkowałybyśmy, parkowałyście, parkowałyśmy, parkowana, parkowaną, parkowane, parkowanego, parkowanej, parkowanemu, parkowani, parkowania, parkowaniach, parkowaniami, parkowanie, parkowaniem, parkowaniom, parkowaniu, parkowano, parkowany, parkowanych, parkowanym, parkowanymi, parkowań, parkuj, parkują, parkując, parkująca, parkującą, parkujące, parkującego, parkującej, parkującemu, parkujący, parkujących, parkującym, parkującymi, parkujcie, parkujcież, parkuje, parkujecie, parkujemy, parkujesz, parkuję, parkujmy, parkujmyż, parkujże
|
||||
pojazd, pojazdach, pojazdami, pojazdem, pojazdom, pojazdowi, pojazdów, pojazdu, pojazdy, pojeździe
|
||||
postój, postoi, postojach, postojami, postoje, postojem, postojom, postojowi, postojów, postoju
|
||||
pozostawić, niepozostawieni, niepozostawienia, niepozostawieniach, niepozostawieniami, niepozostawienie, niepozostawieniem, niepozostawieniom, niepozostawieniu, niepozostawień, niepozostawiona, niepozostawioną, niepozostawione, niepozostawionego, niepozostawionej, niepozostawionemu, niepozostawiony, niepozostawionych, niepozostawionym, niepozostawionymi, pozostaw, pozostawcie, pozostawcież, pozostawi, pozostawią, pozostawicie, pozostawieni, pozostawienia, pozostawieniach, pozostawieniami, pozostawienie, pozostawieniem, pozostawieniom, pozostawieniu, pozostawień, pozostawię, pozostawili, pozostawiliby, pozostawilibyście, pozostawilibyśmy, pozostawiliście, pozostawiliśmy, pozostawił, pozostawiła, pozostawiłaby, pozostawiłabym, pozostawiłabyś, pozostawiłam, pozostawiłaś, pozostawiłby, pozostawiłbym, pozostawiłbyś, pozostawiłem, pozostawiłeś, pozostawiło, pozostawiłoby, pozostawiły, pozostawiłyby, pozostawiłybyście, pozostawiłybyśmy, pozostawiłyście, pozostawiłyśmy, pozostawimy, pozostawiona, pozostawioną, pozostawione, pozostawionego, pozostawionej, pozostawionemu, pozostawiono, pozostawiony, pozostawionych, pozostawionym, pozostawionymi, pozostawisz, pozostawiwszy, pozostawmy, pozostawmyż, pozostawże
|
||||
pracodawca, pracodawcach, pracodawcami, pracodawcą, pracodawce, pracodawcę, pracodawco, pracodawcom, pracodawców, pracodawcy
|
||||
rozwód, rozwodach, rozwodami, rozwodem, rozwodom, rozwodowi, rozwodów, rozwodu, rozwody, rozwodzie
|
||||
spadek, spadkach, spadkami, spadki, spadkiem, spadkom, spadkowi, spadków, spadku
|
||||
wynajem, wynajmach, wynajmami, wynajmem, wynajmie, wynajmom, wynajmowi, wynajmów, wynajmu, wynajmy
|
||||
wypadek, wypadkach, wypadkami, wypadki, wypadkiem, wypadkom, wypadkowi, wypadków, wypadku
|
||||
zabraniać, niezabraniająca, niezabraniającą, niezabraniające, niezabraniającego, niezabraniającej, niezabraniającemu, niezabraniający, niezabraniających, niezabraniającym, niezabraniającymi, niezabraniana, niezabranianą, niezabraniane, niezabranianego, niezabranianej, niezabranianemu, niezabraniani, niezabraniania, niezabranianiach, niezabranianiami, niezabranianie, niezabranianiem, niezabranianiom, niezabranianiu, niezabraniany, niezabranianych, niezabranianym, niezabranianymi, niezabraniań, zabrania, zabraniacie, zabraniaj, zabraniają, zabraniając, zabraniająca, zabraniającą, zabraniające, zabraniającego, zabraniającej, zabraniającemu, zabraniający, zabraniających, zabraniającym, zabraniającymi, zabraniajcie, zabraniajcież, zabraniajmy, zabraniajmyż, zabraniajże, zabraniali, zabranialiby, zabranialibyście, zabranialibyśmy, zabranialiście, zabranialiśmy, zabraniał, zabraniała, zabraniałaby, zabraniałabym, zabraniałabyś, zabraniałam, zabraniałaś, zabraniałby, zabraniałbym, zabraniałbyś, zabraniałem, zabraniałeś, zabraniało, zabraniałoby, zabraniały, zabraniałyby, zabraniałybyście, zabraniałybyśmy, zabraniałyście, zabraniałyśmy, zabraniam, zabraniamy, zabraniana, zabranianą, zabraniane, zabranianego, zabranianej, zabranianemu, zabraniani, zabraniania, zabranianiach, zabranianiami, zabranianie, zabranianiem, zabranianiom, zabranianiu, zabraniano, zabraniany, zabranianych, zabranianym, zabranianymi, zabraniań, zabraniasz
|
||||
zabronić, niezabronieni, niezabronienia, niezabronieniach, niezabronieniami, niezabronienie, niezabronieniem, niezabronieniom, niezabronieniu, niezabronień, niezabroniona, niezabronioną, niezabronione, niezabronionego, niezabronionej, niezabronionemu, niezabroniony, niezabronionych, niezabronionym, niezabronionymi, zabroni, zabronią, zabronicie, zabronieni, zabronienia, zabronieniach, zabronieniami, zabronienie, zabronieniem, zabronieniom, zabronieniu, zabronień, zabronię, zabronili, zabroniliby, zabronilibyście, zabronilibyśmy, zabroniliście, zabroniliśmy, zabronił, zabroniła, zabroniłaby, zabroniłabym, zabroniłabyś, zabroniłam, zabroniłaś, zabroniłby, zabroniłbym, zabroniłbyś, zabroniłem, zabroniłeś, zabroniło, zabroniłoby, zabroniły, zabroniłyby, zabroniłybyście, zabroniłybyśmy, zabroniłyście, zabroniłyśmy, zabronimy, zabroniona, zabronioną, zabronione, zabronionego, zabronionej, zabronionemu, zabroniono, zabroniony, zabronionych, zabronionym, zabronionymi, zabronisz, zabroniwszy, zabroń, zabrońcie, zabrońcież, zabrońmy, zabrońmyż, zabrońże
|
||||
zakazany, niezakazana, niezakazaną, niezakazane, niezakazanego, niezakazanej, niezakazanemu, niezakazani, niezakazany, niezakazanych, niezakazanym, niezakazanymi, zakazana, zakazaną, zakazane, zakazanego, zakazanej, zakazanemu, zakazani, zakazanych, zakazanym, zakazanymi
|
||||
zakład, zakładach, zakładami, zakładem, zakładom, zakładowi, zakładów, zakładu, zakłady, zakładzie
|
||||
zatrzymać, niezatrzymana, niezatrzymaną, niezatrzymane, niezatrzymanego, niezatrzymanej, niezatrzymanemu, niezatrzymani, niezatrzymania, niezatrzymaniach, niezatrzymaniami, niezatrzymanie, niezatrzymaniem, niezatrzymaniom, niezatrzymaniu, niezatrzymany, niezatrzymanych, niezatrzymanym, niezatrzymanymi, niezatrzymań, zatrzyma, zatrzymacie, zatrzymaj, zatrzymają, zatrzymajcie, zatrzymajcież, zatrzymajmy, zatrzymajmyż, zatrzymajże, zatrzymali, zatrzymaliby, zatrzymalibyście, zatrzymalibyśmy, zatrzymaliście, zatrzymaliśmy, zatrzymał, zatrzymała, zatrzymałaby, zatrzymałabym, zatrzymałabyś, zatrzymałam, zatrzymałaś, zatrzymałby, zatrzymałbym, zatrzymałbyś, zatrzymałem, zatrzymałeś, zatrzymało, zatrzymałoby, zatrzymały, zatrzymałyby, zatrzymałybyście, zatrzymałybyśmy, zatrzymałyście, zatrzymałyśmy, zatrzymam, zatrzymamy, zatrzymana, zatrzymaną, zatrzymane, zatrzymanego, zatrzymanej, zatrzymanemu, zatrzymani, zatrzymania, zatrzymaniach, zatrzymaniami, zatrzymanie, zatrzymaniem, zatrzymaniom, zatrzymaniu, zatrzymano, zatrzymany, zatrzymanych, zatrzymanym, zatrzymanymi, zatrzymań, zatrzymasz, zatrzymawszy
|
||||
zdarzenie, zdarzenia, zdarzeniach, zdarzeniami, zdarzeniem, zdarzeniom, zdarzeniu, zdarzeń
|
||||
zwolnienie, zwolnienia, zwolnieniach, zwolnieniami, zwolnieniem, zwolnieniom, zwolnieniu, zwolnień
|
||||
@@ -38,6 +38,16 @@ REGRESSION: list[tuple[str, str, int, tuple[str, ...]]] = [
|
||||
("przedawnienie roszczeń", "DU/2026/795", 1, ("117",)),
|
||||
("jazda po alkoholu", "Kodeks (karny|wykroczeń)", 3, ()),
|
||||
("ochrona konsumenta", "konsument", 3, ()),
|
||||
# statutes say "postój" / "zatrzymanie" and "w miejscu, gdzie jest to zabronione": the thesaurus
|
||||
# and the partial match (2026-10-21; the fixture slice holds art. 130a, not 46/47/49)
|
||||
("parkowanie w miejscu niedozwolonym", "DU/2024/1251", 3, ()),
|
||||
]
|
||||
|
||||
#: recall that only lemmas give (2026-10-21): the query word never occurs in these acts as typed —
|
||||
#: "spółki" must find "spółce" (k↔c) and "spółek" (a fleeting e), "dzieci" must find "dziecko"
|
||||
RECALL: list[tuple[str, tuple[str, ...]]] = [
|
||||
("spółki", ("DU/2026/1342", "DU/2023/725")),
|
||||
("dzieci", ("DU/2026/1245",)),
|
||||
]
|
||||
|
||||
|
||||
@@ -92,9 +102,19 @@ def table(adapter) -> str:
|
||||
cells = [f"{_short(r['title'])} ({r['eli']}) art. {', '.join(str(a) for a in r['articles'][:3])}"
|
||||
for r in rows] + [""] * (3 - len(rows))
|
||||
lines.append(f"| {q} | " + " | ".join(cells) + f" | {'yes' if passed(rows, want, depth, arts) else 'NO'} |")
|
||||
lines += ["", "| query (recall) | must be found (top 10) | found | ok |", "|---|---|---|---|"]
|
||||
for q, want in RECALL:
|
||||
got = [r["eli"] for r in top(adapter, q, 10)]
|
||||
lines.append(f"| {q} | {', '.join(want)} | {', '.join(got)} | "
|
||||
f"{'yes' if recalled(adapter, q, want) else 'NO'} |")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def recalled(adapter, q: str, want: tuple[str, ...]) -> bool:
|
||||
got = {r["eli"] for r in top(adapter, q, 10)}
|
||||
return all(w in got for w in want)
|
||||
|
||||
|
||||
def passed(rows: list[dict], want: str, depth: int, arts: tuple[str, ...]) -> bool:
|
||||
hit = next((r for r in rows[:depth] if matches(r, want)), None)
|
||||
if hit is None:
|
||||
@@ -113,5 +133,14 @@ def _short(title: str) -> str:
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import os
|
||||
if "--full-lexicon" not in sys.argv: # the committed test lexicon, like the suite
|
||||
import conftest # noqa: F401
|
||||
elif not os.environ.get("INSIDER_LEXICON_DIR"):
|
||||
sys.exit("--full-lexicon: set INSIDER_LEXICON_DIR to a built lexicon directory")
|
||||
if "--no-lexicon" in sys.argv: # plstem only: the table before lemmas
|
||||
from app.integrations import analysis
|
||||
analysis.configure(None)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
print(table(build(Path(d))))
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Language analysis: the per-language registry, the dictionary lemmatiser (sjp.pl, the committed
|
||||
test subset `fixtures/odm_fixture.txt`, built offline by conftest) and plstem as its fallback. DB-free."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from conftest import TEST_LEXICON_DIR
|
||||
|
||||
from app.integrations import analysis, lexicon
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pl():
|
||||
return analysis.get("pl")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lemma,forms", [
|
||||
("spolka", ["spółka", "spółki", "spółce", "spółek", "spółkę", "spółką", "spółkom", "spółkami",
|
||||
"spółkach", "spolki"]),
|
||||
("sad", ["sąd", "sądu", "sądowi", "sądem", "sądzie", "sądy", "sądów"]),
|
||||
("dziecko", ["dziecko", "dziecka", "dziecku", "dzieckiem", "dzieci", "dzieciom", "dziećmi"]),
|
||||
("najem", ["najem", "najmu", "najmem", "najmie", "najmy", "najmów"]),
|
||||
("isc", ["iść", "idę", "idzie", "idziemy", "szedł", "szła", "szli"]),
|
||||
("umowa", ["umowa", "umowy", "umowie", "umowę", "umową", "umów", "umowami"]),
|
||||
("pracownik", ["pracownik", "pracownika", "pracownikowi", "pracownicy", "pracowników"]),
|
||||
("wypowiedzenie", ["wypowiedzenie", "wypowiedzenia", "wypowiedzeniu", "wypowiedzeniem",
|
||||
"wypowiedzeń"]),
|
||||
])
|
||||
def test_every_form_names_its_lemma(pl, lemma, forms):
|
||||
"""Each form's index term names the lemma (alone, or in an ambiguity token: "sądzie" is also a
|
||||
form of `sadz` once diacritics are folded), and a query for any form asks for it."""
|
||||
for f in forms:
|
||||
assert lemma in pl.lemmas(f), f
|
||||
assert lemma in pl.alternatives(f), f
|
||||
|
||||
|
||||
def test_one_query_form_finds_every_other(pl):
|
||||
"""What the index stores for any form is among what any other form's query asks for."""
|
||||
for forms in (["spółki", "spółce", "spółek"], ["dzieci", "dziecko"], ["sąd", "sądzie"],
|
||||
["najem", "najmu"], ["iść", "szedł", "idzie"]):
|
||||
for q in forms:
|
||||
for text in forms:
|
||||
assert pl.term(text) in pl.alternatives(q), (q, text)
|
||||
|
||||
|
||||
def test_ambiguity_is_one_token_and_an_or_on_the_query(pl):
|
||||
assert pl.term("mam") == "mam|mama|mamic|miec" # one position, every lemma
|
||||
assert pl.term("mama") == "mama"
|
||||
assert "mam|mama|mamic|miec" in pl.alternatives("mama") # "mama" finds the text's "mam"
|
||||
assert {"mama", "miec"} <= set(pl.alternatives("mam")) # "mam" asks for both
|
||||
assert len(pl.alternatives("mam")) <= analysis.MAX_ALTERNATIVES
|
||||
|
||||
|
||||
def test_derived_lemmas_and_negation_stay_apart(pl):
|
||||
"""The verbal noun keeps its own lemma (the verb's line lists it too); a negated form under a
|
||||
positive headword is not in the lexicon — it falls back to plstem."""
|
||||
assert pl.lemmas("wypowiedzenie") == ("wypowiedzenie",)
|
||||
assert pl.lemmas("wypowiedzieć") == ("wypowiedziec",)
|
||||
assert pl.lemmas("niewykonanie") == () and pl.term("niewykonanie") == "niewykonan"
|
||||
|
||||
|
||||
def test_unknown_words_fall_back_to_plstem(pl):
|
||||
from app.integrations import plstem
|
||||
for w in ("lokatorów", "nieodpłatnej", "2024", "zzyzx"):
|
||||
assert pl.lemmas(w) == () and pl.term(w) == plstem.stem(w)
|
||||
assert pl.alternatives("zamek") == plstem.alternatives("zamek") == ["zamek", "zamk"]
|
||||
|
||||
|
||||
def test_without_a_lexicon_the_analysis_is_plstem():
|
||||
from app.integrations import plstem
|
||||
analysis.configure(None)
|
||||
try:
|
||||
an = analysis.get("pl")
|
||||
assert an.lemmatizer is None and an.ident.endswith(":none")
|
||||
assert an.analyze("Umowa spółki") == [plstem.stem("Umowa"), plstem.stem("spółki")]
|
||||
finally:
|
||||
analysis.configure(TEST_LEXICON_DIR)
|
||||
assert analysis.get("pl").lemmatizer is not None
|
||||
|
||||
|
||||
def test_the_fixture_lexicon_loads_offline():
|
||||
lx = lexicon.Lexicon(TEST_LEXICON_DIR / "pl.lex")
|
||||
assert lx.ident == "odm_fixture.txt" and lx.n_forms > 500
|
||||
assert lx.lookup("spolce") == "spolka" and lx.lookup("nieznane") is None
|
||||
assert analysis.ident(["pl"]) == "pl:2:odm_fixture.txt"
|
||||
|
||||
|
||||
def test_lexicon_roundtrip(tmp_path):
|
||||
lines = ["kot, kota, kotem, kocie, koty", "kocić, kocie, kocisz", "Kraków, Krakowa",
|
||||
"kotka, kotce, kotek, kotki"]
|
||||
m = lexicon.parse_sjp(lines, analysis.get("pl").normalise)
|
||||
assert "krakow" not in m # proper names dropped
|
||||
lexicon.write(m, tmp_path / "x.lex", "t")
|
||||
lx = lexicon.Lexicon(tmp_path / "x.lex")
|
||||
assert lx.lookup("kocie") == "kocic|kot" and lx.lookup("kotce") == "kotka"
|
||||
assert lx.groups == {"kocic": ("kocic|kot",), "kot": ("kocic|kot",)}
|
||||
|
||||
|
||||
def test_title_filter_through_lemmas():
|
||||
assert analysis.title_matches("Ustawa o spółce komandytowej", "spółki")
|
||||
assert analysis.title_matches("Rozporządzenie w sprawie najmu lokali", "najem")
|
||||
assert not analysis.title_matches("Ustawa o ochronie roślin", "spółki")
|
||||
|
||||
|
||||
def test_snippet_keys_reach_a_lemma():
|
||||
keys = analysis.query_keys("spółki")
|
||||
assert analysis.word_matches("spółce", keys) and not analysis.word_matches("ustawa", keys)
|
||||
|
||||
|
||||
def test_the_registry_chooses_per_language():
|
||||
en = analysis.get("en")
|
||||
assert en.lang == "en" and en.term("Contracts") == "contract" and en.is_stopword("the")
|
||||
assert analysis.get(None).lang == analysis.get("xx").lang == "pl" # unknown → default
|
||||
|
||||
|
||||
def test_a_backend_is_anything_with_lookup_and_groups():
|
||||
"""Morfeusz2 or Hunspell would plug in the same way (README "Language analysis")."""
|
||||
class Double:
|
||||
ident = "double-1"
|
||||
groups = {"byc": ("byc|bywac",)}
|
||||
|
||||
def lookup(self, key):
|
||||
return {"jest": "byc", "bywa": "byc|bywac"}.get(key)
|
||||
|
||||
analysis.register("xx", lambda _lex: analysis.Analyzer(
|
||||
"xx", stem=str.lower, widen=lambda w: [w.lower()], normalise=str.lower, lemmatizer=Double()))
|
||||
try:
|
||||
xx = analysis.get("xx")
|
||||
assert xx.analyze("Jest bywa inne") == ["byc", "byc|bywac", "inne"]
|
||||
assert xx.alternatives("jest") == ["byc", "byc|bywac"]
|
||||
assert xx.ident == "xx:1:double-1"
|
||||
finally:
|
||||
analysis._FACTORIES.pop("xx")
|
||||
analysis._cache.pop("xx", None)
|
||||
|
||||
|
||||
def test_eu_index_reads_each_text_in_its_language(tmp_path):
|
||||
from app.services.textindex import TextIndex
|
||||
if not TextIndex.available:
|
||||
pytest.skip("tantivy is not installed")
|
||||
ix = TextIndex(tmp_path / "eu", langs=("pl", "en"))
|
||||
ix.rebuild([{"group": "A", "ord": 0, "title": "Umowa spółki", "text": "The contracts.",
|
||||
"lang": "en"},
|
||||
{"group": "B", "ord": 0, "title": "Inny", "text": "W spółce.", "lang": "pl"}])
|
||||
assert [g["group"] for g in ix.search("contract")[0]] == ["A"] # English: plural off
|
||||
assert sorted(g["group"] for g in ix.search("spółki")[0]) == ["A", "B"]
|
||||
|
||||
|
||||
# ── the thesaurus ──────────────────────────────────────────────────────────────────────────────────
|
||||
def test_thesaurus_entries_are_lemmatised_and_whole_phrases():
|
||||
ex = analysis.expansions("parkowanie w miejscu niedozwolonym")
|
||||
assert "postój miejscu zabroniony" in ex and "zatrzymanie pojazdu miejscu zakazany" in ex
|
||||
assert analysis.expansions("parkowania") and analysis.expansions("postoju") # any form
|
||||
assert analysis.expansions("rozwód") == ["rozwiązanie małżeństwa"]
|
||||
assert "rozwód" in analysis.expansions("rozwiązanie małżeństwa") # both ways
|
||||
assert analysis.expansions("grzywna") == [] # ">" is one way
|
||||
# a phrase only as a whole: "zwolnienie" alone is not "zwolnienie z pracy"
|
||||
assert analysis.expansions("zwolnienie z podatku") == []
|
||||
assert analysis.expansions("zwolnienie z pracy")[0] == "rozwiązanie umowy o pracę"
|
||||
assert analysis.expansions("umowa o pracę") == []
|
||||
assert len(analysis.expansions("parkowanie w miejscu niedozwolonym")) <= analysis.MAX_EXPANSIONS
|
||||
|
||||
|
||||
def test_thesaurus_variants_weigh_less_and_partial_matches_are_flagged(tmp_path):
|
||||
from app.services.textindex import TextIndex
|
||||
if not TextIndex.available:
|
||||
pytest.skip("tantivy is not installed")
|
||||
ix = TextIndex(tmp_path / "ix")
|
||||
ix.rebuild([
|
||||
{"group": "P", "ord": 0, "title": "Prawo", "text": "Postój pojazdu w miejscu zabronionym."},
|
||||
{"group": "Q", "ord": 0, "title": "Inne", "text": "Parkowanie w miejscu niedozwolonym."},
|
||||
{"group": "R", "ord": 0, "title": "Trzecie", "text": "Pojazd w miejscu zabronionym."},
|
||||
])
|
||||
groups, _ = ix.search("parkowanie w miejscu niedozwolonym")
|
||||
assert [g["group"] for g in groups] == ["Q", "P"] # as typed first, then the variant
|
||||
assert not any(g["partial"] for g in groups)
|
||||
groups, _ = ix.search("hulajnoga w miejscu zabronionym") # no part holds "hulajnoga"
|
||||
# 2 of 3 words — Q through the thesaurus (zabroniony ↔ niedozwolony)
|
||||
assert {g["group"] for g in groups} == {"P", "Q", "R"} and all(g["partial"] for g in groups)
|
||||
assert ix.search("hulajnoga")[0] == [] # one word: nothing to relax
|
||||
|
||||
|
||||
def test_partial_results_carry_a_notice_and_a_rebuild_a_note():
|
||||
from app.services import federation, legal
|
||||
full = [{"extra": {}}]
|
||||
assert legal._with_partial([], full, []) == []
|
||||
notes = legal._with_partial([], full + [{"extra": {"partial": True}}], [])
|
||||
assert [n["code"] for n in notes] == ["partial_matches"]
|
||||
|
||||
class Ix:
|
||||
def rebuild_pending(self):
|
||||
return True
|
||||
|
||||
from app.integrations.local import LocalAdapter
|
||||
|
||||
class Adapter:
|
||||
index = Ix()
|
||||
index_note = LocalAdapter.index_note
|
||||
|
||||
assert "previous one answers" in federation._index_note(Adapter())
|
||||
@@ -196,15 +196,17 @@ class FakeCellar:
|
||||
|
||||
def ix_settings(tmp_path, **over):
|
||||
base = dict(index_dir=tmp_path / "index", insider_contact="ops@example.test",
|
||||
insider_dzu_md_stale_hours=72, insider_eli_inforce_interval_hours=24,
|
||||
insider_dzu_md_stale_hours=72, insider_eli_inforce_schedule="0 5 * * *",
|
||||
insider_saos_index_stale_hours=96, insider_dzu_md_rate=1000.0,
|
||||
insider_dzu_md_sync=False, insider_dzu_md_sync_interval_hours=6,
|
||||
insider_saos_dump_sync=False, insider_saos_dump_window="23:00-05:00",
|
||||
insider_dzu_md_sync=False, insider_dzu_md_schedule="15 7 * * *",
|
||||
insider_saos_dump_sync=False, insider_saos_dump_first_window="23:00-05:00",
|
||||
insider_saos_dump_page_size=10, insider_saos_dump_pause_seconds=5,
|
||||
insider_saos_dump_interval_hours=20, insider_eli_inforce_rate=1000.0,
|
||||
insider_saos_dump_schedule="0 5 * * *", insider_eli_inforce_rate=1000.0,
|
||||
insider_eli_inforce_sync=False, eli_inforce_types=["Ustawa"],
|
||||
insider_cellar_sync=True, insider_cellar_caselaw=False,
|
||||
insider_cellar_interval_hours=24, insider_cellar_rate=1000.0,
|
||||
insider_cellar_schedule="0 5 * * *", insider_cellar_full_schedule="0 5 * * 0",
|
||||
insider_cellar_caselaw_schedule="0 5 * * *", insider_schedule_tz="Europe/Warsaw",
|
||||
insider_index_rebuild_schedule="0 5 * * *", insider_cellar_rate=1000.0,
|
||||
insider_cellar_stale_hours=96, insider_cellar_caselaw_from="2000-01-01")
|
||||
base.update(over)
|
||||
return SimpleNamespace(**base)
|
||||
@@ -278,7 +280,9 @@ class TestImporter:
|
||||
ix = build(tmp_path, up, clock=lambda: clock["t"])
|
||||
imp = acts_importer(ix)
|
||||
asyncio.run(imp.locked_run())
|
||||
assert not imp.due(NOW + dt.timedelta(hours=23)) and imp.due(later)
|
||||
# 04:00 Warsaw now; the next fire of "0 5 * * *" is 05:00 Warsaw (03:00 UTC)
|
||||
assert not imp.due(NOW + dt.timedelta(minutes=59)) and imp.due(NOW + dt.timedelta(hours=1))
|
||||
assert imp.due(later)
|
||||
# a new consolidated version of the GDPR; the directive left force
|
||||
fc.text("02016R0679-20240101", "pl", OJ_XHTML.replace("Przedmiot", "Nowy przedmiot"))
|
||||
fc.acts["32016R0679"] |= {"cons": "02016R0679-20240101", "consmod": "2026-10-21T10:00:00"}
|
||||
|
||||
@@ -131,15 +131,17 @@ def dataset(up: FakeUpstream, head: str, acts: dict[str, tuple[str, str]], shas=
|
||||
|
||||
def settings(tmp_path, **over):
|
||||
base = dict(index_dir=tmp_path / "index", insider_contact="ops@example.test",
|
||||
insider_dzu_md_stale_hours=72, insider_eli_inforce_interval_hours=24,
|
||||
insider_dzu_md_stale_hours=72, insider_eli_inforce_schedule="0 5 * * *",
|
||||
insider_saos_index_stale_hours=96, insider_dzu_md_rate=1000.0,
|
||||
insider_dzu_md_sync=True, insider_dzu_md_sync_interval_hours=6,
|
||||
insider_saos_dump_sync=True, insider_saos_dump_window="23:00-05:00",
|
||||
insider_dzu_md_sync=True, insider_dzu_md_schedule="15 7 * * *",
|
||||
insider_saos_dump_sync=True, insider_saos_dump_first_window="23:00-05:00",
|
||||
insider_saos_dump_page_size=10, insider_saos_dump_pause_seconds=5,
|
||||
insider_saos_dump_interval_hours=20, insider_eli_inforce_rate=1000.0,
|
||||
insider_saos_dump_schedule="0 5 * * *", insider_eli_inforce_rate=1000.0,
|
||||
insider_eli_inforce_sync=True, eli_inforce_types=["Ustawa"],
|
||||
insider_cellar_sync=False, insider_cellar_caselaw=False,
|
||||
insider_cellar_interval_hours=24, insider_cellar_rate=1000.0,
|
||||
insider_cellar_schedule="0 5 * * *", insider_cellar_full_schedule="0 5 * * 0",
|
||||
insider_cellar_caselaw_schedule="0 5 * * *", insider_schedule_tz="Europe/Warsaw",
|
||||
insider_index_rebuild_schedule="0 5 * * *", insider_cellar_rate=1000.0,
|
||||
insider_cellar_stale_hours=96, insider_cellar_caselaw_from="2000-01-01")
|
||||
base.update(over)
|
||||
return SimpleNamespace(**base)
|
||||
@@ -347,14 +349,20 @@ class TestSaosImporter:
|
||||
asyncio.run(imp.locked_run())
|
||||
assert seen[-1]["sinceModificationDate"] == "2026-10-21T01:00:00.000"
|
||||
|
||||
def test_off_peak_window_and_interval(self, tmp_path):
|
||||
def test_first_import_in_its_window_then_the_daily_schedule(self, tmp_path):
|
||||
ix = build(tmp_path, FakeUpstream())
|
||||
imp = importer(ix, "saos_dump")
|
||||
# the FIRST full import: only inside 23:00-05:00 Warsaw (NOW = 04:00 Warsaw)
|
||||
assert imp.due(NOW) and not imp.due(NOW.replace(hour=12))
|
||||
ix.store.set_state("saos_dump", synced_at=NOW, cursor={"next_since": "x"})
|
||||
assert not imp.due(NOW + dt.timedelta(hours=2))
|
||||
ix.store.set_state("saos_dump", cursor={"page": 4, "since": None})
|
||||
assert imp.due(NOW + dt.timedelta(hours=2)) # a pass in progress carries on
|
||||
assert imp.due(NOW) and not imp.due(NOW.replace(hour=12)) # resumes, still in the window
|
||||
# done: the daily delta at 05:00 Warsaw (03:00 UTC), the window no longer applies
|
||||
ix.store.set_state("saos_dump", synced_at=NOW, attempted_at=NOW, completed_at=NOW,
|
||||
cursor={"next_since": "x"})
|
||||
assert not imp.due(NOW + dt.timedelta(minutes=30))
|
||||
assert imp.due(NOW + dt.timedelta(hours=1)) and imp.due(NOW.replace(hour=12))
|
||||
ix.store.set_state("saos_dump", cursor={"page": 4, "since": "x"})
|
||||
assert imp.due(NOW + dt.timedelta(minutes=30)) # a pass in progress carries on
|
||||
|
||||
def test_the_dump_client_only_reaches_the_dump(self):
|
||||
from app.integrations.http import SourceClient
|
||||
@@ -393,7 +401,13 @@ class TestTextIndex:
|
||||
assert [g["group"] for g in ix.search("ochrona danych osobowych")[0]] == ["A"]
|
||||
|
||||
def test_query_terms(self):
|
||||
assert plstem.query_terms("najem okazjonalny") == [["naj", "najm"], ["okazjonaln"]]
|
||||
from app.integrations import analysis
|
||||
# without a dictionary: plstem, the mobile e widened on the query side
|
||||
assert analysis.query_terms("najem okazjonalny", plain=True) == [["naj", "najm"],
|
||||
["okazjonaln"]]
|
||||
# with one: lemmas (najem is also a form of najeść — one ambiguity token naming both)
|
||||
terms = analysis.query_terms("najem okazjonalny")
|
||||
assert "najem" in terms[0] and terms[1] == ["okazjonalny"]
|
||||
assert plstem.stem("przekroczenie") == plstem.stem("przekroczenia") == plstem.stem(
|
||||
"przekroczeniu")
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.integrations import plstem
|
||||
from app.integrations import analysis, plstem
|
||||
|
||||
|
||||
@pytest.mark.parametrize("forms,stem", [
|
||||
@@ -31,15 +31,15 @@ def test_short_words_and_numbers_are_left_alone():
|
||||
|
||||
def test_title_filter():
|
||||
title = "Ustawa z dnia 10 maja 2018 r. o ochronie danych osobowych"
|
||||
assert plstem.title_matches(title, "ochrona danych osobowych")
|
||||
assert plstem.title_matches(title, "Ochrona Danych")
|
||||
assert not plstem.title_matches(title, "ochrona środowiska")
|
||||
assert not plstem.title_matches("Ustawa o ochronie roślin", "ochrona danych osobowych")
|
||||
assert analysis.title_matches(title, "ochrona danych osobowych")
|
||||
assert analysis.title_matches(title, "Ochrona Danych")
|
||||
assert not analysis.title_matches(title, "ochrona środowiska")
|
||||
assert not analysis.title_matches("Ustawa o ochronie roślin", "ochrona danych osobowych")
|
||||
|
||||
|
||||
def test_longest_word_skips_stop_words():
|
||||
assert plstem.longest_word("o ochronie danych osobowych") == "osobowych"
|
||||
assert plstem.longest_word("o w z") is None
|
||||
assert analysis.longest_word("o ochronie danych osobowych") == "osobowych"
|
||||
assert analysis.longest_word("o w z") is None
|
||||
|
||||
|
||||
# ── consonant alternations (2026-10-21): masculine-personal plurals meet their singular ─────────────
|
||||
@@ -83,9 +83,9 @@ def test_distinct_words_stay_apart():
|
||||
|
||||
|
||||
def test_title_filter_with_a_normalised_stem():
|
||||
assert plstem.title_matches("Ustawa o ochronie sygnalistów", "sygnaliści")
|
||||
assert plstem.title_matches("Rozporządzenie w sprawie załącznika", "załącznik")
|
||||
assert plstem.title_matches("Ustawa o rzeczniku praw pacjenta", "rzecznik")
|
||||
assert analysis.title_matches("Ustawa o ochronie sygnalistów", "sygnaliści")
|
||||
assert analysis.title_matches("Rozporządzenie w sprawie załącznika", "załącznik")
|
||||
assert analysis.title_matches("Ustawa o rzeczniku praw pacjenta", "rzecznik")
|
||||
|
||||
|
||||
def test_the_index_records_the_stemmer_version(tmp_path):
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"""The importers' cron schedules (INSIDER_*_SCHEDULE in INSIDER_SCHEDULE_TZ), the scheduled index
|
||||
rebuild, incremental index updates and the outage notices. DB-free, no network."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services import indexing
|
||||
from app.services import schedule as sched
|
||||
from app.services.indexstore import MemoryIndexStore
|
||||
|
||||
UTC = dt.UTC
|
||||
W = "Europe/Warsaw"
|
||||
|
||||
|
||||
def t(s: str) -> dt.datetime:
|
||||
return dt.datetime.fromisoformat(s).replace(tzinfo=UTC)
|
||||
|
||||
|
||||
# ── parsing ─────────────────────────────────────────────────────────────────────────────────────────
|
||||
def test_parse_several_expressions_and_refuse_bad_ones():
|
||||
assert sched.parse("15 7 * * *; 0 11 * * 1-5") == ["15 7 * * *", "0 11 * * 1-5"]
|
||||
assert sched.parse("") == []
|
||||
for bad in ("0 5 * *", "61 5 * * *", "every day", "0 5 * * * *"):
|
||||
with pytest.raises(ValueError):
|
||||
sched.parse(bad)
|
||||
|
||||
|
||||
def test_an_invalid_schedule_refuses_to_start_naming_the_variable(monkeypatch):
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.config import Settings
|
||||
monkeypatch.setenv("INSIDER_CELLAR_FULL_SCHEDULE", "0 5 * *")
|
||||
with pytest.raises(ValidationError, match="INSIDER_CELLAR_FULL_SCHEDULE"):
|
||||
Settings(_env_file=None)
|
||||
monkeypatch.setenv("INSIDER_CELLAR_FULL_SCHEDULE", "0 5 * * 0")
|
||||
monkeypatch.setenv("INSIDER_SCHEDULE_TZ", "Mars/Olympus")
|
||||
with pytest.raises(ValidationError, match="time zone"):
|
||||
Settings(_env_file=None)
|
||||
|
||||
|
||||
def test_the_defaults():
|
||||
from app.config import Settings
|
||||
s = Settings(_env_file=None)
|
||||
assert s.insider_schedule_tz == W and s.insider_dzu_md_schedule == "15 7 * * *"
|
||||
assert {s.insider_eli_inforce_schedule, s.insider_cellar_schedule,
|
||||
s.insider_cellar_caselaw_schedule, s.insider_saos_dump_schedule,
|
||||
s.insider_index_rebuild_schedule} == {"0 5 * * *"}
|
||||
assert s.insider_cellar_full_schedule == "0 5 * * 0"
|
||||
assert s.insider_saos_dump_first_window == "23:00-05:00"
|
||||
assert not hasattr(s, "insider_cellar_interval_hours") # one way to say it
|
||||
|
||||
|
||||
# ── time zone and DST ───────────────────────────────────────────────────────────────────────────────
|
||||
@pytest.mark.parametrize("now,fire", [
|
||||
("2026-10-21T12:00", "2026-10-21T03:00"), # CEST: 05:00 Warsaw = 03:00 UTC
|
||||
("2026-10-25T12:00", "2026-10-25T04:00"), # the day summer time ends: CET, 04:00 UTC
|
||||
("2026-03-29T12:00", "2026-03-29T03:00"), # the day it begins: CEST again
|
||||
("2026-03-28T12:00", "2026-03-28T04:00"),
|
||||
])
|
||||
def test_five_in_warsaw_across_dst(now, fire):
|
||||
assert sched.last_fire("0 5 * * *", t(now), W) == t(fire)
|
||||
|
||||
|
||||
def test_next_fire_across_the_autumn_change():
|
||||
assert sched.next_fire("0 5 * * *", t("2026-10-24T12:00"), W) == t("2026-10-25T04:00")
|
||||
assert sched.next_fire("15 7 * * *", t("2026-10-21T06:00"), W) == t("2026-10-22T05:15")
|
||||
|
||||
|
||||
def test_due_once_per_fire_and_a_missed_run_catches_up_once():
|
||||
spec = "0 5 * * *"
|
||||
assert sched.due(spec, t("2026-10-21T02:00"), None, W) # never ran
|
||||
assert not sched.due(spec, t("2026-10-21T02:59"), t("2026-10-20T03:01"), W)
|
||||
assert sched.due(spec, t("2026-10-21T03:00"), t("2026-10-20T03:01"), W)
|
||||
# the box was down for three days: ONE run at the next tick, then nothing until the next fire
|
||||
last = t("2026-10-17T03:01")
|
||||
assert sched.due(spec, t("2026-10-21T09:00"), last, W)
|
||||
assert not sched.due(spec, t("2026-10-21T09:05"), t("2026-10-21T09:00"), W)
|
||||
|
||||
|
||||
def test_several_expressions_take_the_latest_fire():
|
||||
spec = "15 7 * * *;0 13 * * *" # 05:15 and 11:00 UTC
|
||||
assert sched.last_fire(spec, t("2026-10-21T12:00"), W) == t("2026-10-21T11:00")
|
||||
assert sched.due(spec, t("2026-10-21T12:00"), t("2026-10-21T06:00"), W)
|
||||
|
||||
|
||||
# ── the importers ───────────────────────────────────────────────────────────────────────────────────
|
||||
def test_importers_follow_their_own_schedule_and_report_the_next_run():
|
||||
store = MemoryIndexStore()
|
||||
clock = {"t": t("2026-10-21T04:00")} # 06:00 Warsaw
|
||||
imp = indexing.DzuMdImporter(store, None, None, on=True, schedule="15 7 * * *", tz=W,
|
||||
clock=lambda: clock["t"])
|
||||
assert imp.due(clock["t"]) # never ran
|
||||
store.set_state("dzu_md", attempted_at=clock["t"], synced_at=clock["t"])
|
||||
assert not imp.due(t("2026-10-21T05:14")) and imp.due(t("2026-10-21T05:15"))
|
||||
assert imp.status()["next_run"] == "2026-10-21T05:15:00+00:00"
|
||||
assert imp.status()["schedule"] == "15 7 * * *"
|
||||
|
||||
|
||||
def test_cellar_full_pass_on_its_own_schedule():
|
||||
store = MemoryIndexStore()
|
||||
imp = indexing.CellarImporter(store, None, None, kind="act", on=True, schedule="0 5 * * *",
|
||||
full_schedule="0 5 * * 0", tz=W)
|
||||
sunday, monday = t("2026-10-25T04:30"), t("2026-10-26T04:30") # after 05:00 CET
|
||||
store.set_state("cellar", attempted_at=t("2026-10-24T05:00"))
|
||||
assert imp.scheduled(sunday, t("2026-10-24T05:00"), imp.full_schedule)
|
||||
assert not imp.scheduled(monday, t("2026-10-25T04:30"), imp.full_schedule)
|
||||
assert imp.due(monday) # the daily delta
|
||||
|
||||
|
||||
# ── the scheduled rebuild; incremental updates ─────────────────────────────────────────────────────
|
||||
def _rows(n=2, text="Umowa spółki"):
|
||||
return [{"group": f"G{i}", "ord": 0, "title": "t", "text": text} for i in range(n)]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ix(tmp_path):
|
||||
from app.services.textindex import TextIndex
|
||||
if not TextIndex.available:
|
||||
pytest.skip("tantivy is not installed")
|
||||
return TextIndex(tmp_path / "dzu_md")
|
||||
|
||||
|
||||
def test_a_missing_index_builds_at_once_a_stale_one_at_the_rebuild_schedule(ix, monkeypatch):
|
||||
import json
|
||||
store = MemoryIndexStore()
|
||||
store.set_state("saos_dump", doc_count=2)
|
||||
store.iter_saos_rows = lambda ids=None: iter(_rows())
|
||||
imp = indexing.SaosDumpImporter(store, ix, None, on=True, first_window="23:00-05:00",
|
||||
page_size=10, pause=1, rebuild_schedule="0 5 * * *", tz=W)
|
||||
clock = {"t": t("2026-10-21T10:00")}
|
||||
monkeypatch.setattr(indexing, "utcnow", lambda: clock["t"])
|
||||
asyncio.run(indexing.ensure_index(imp))
|
||||
assert ix.current() # missing → built now
|
||||
meta = ix.meta()
|
||||
(ix.path / "index.json").write_text(json.dumps(meta | {"analysis": "pl:2:older"}),
|
||||
encoding="utf-8")
|
||||
assert ix.rebuild_pending()
|
||||
asyncio.run(indexing.ensure_index(imp))
|
||||
assert ix.rebuild_pending() # waits for 05:00, the old one answers
|
||||
clock["t"] = t("2026-10-22T02:59")
|
||||
asyncio.run(indexing.ensure_index(imp))
|
||||
assert ix.rebuild_pending()
|
||||
clock["t"] = t("2026-10-22T03:00") # 05:00 Warsaw
|
||||
asyncio.run(indexing.ensure_index(imp))
|
||||
assert ix.current() and imp.rebuild_seen is None
|
||||
|
||||
|
||||
def test_a_delta_adds_replaces_and_deletes_only_its_documents(ix):
|
||||
ix.rebuild(_rows(3), "m")
|
||||
built = ix.meta()["built_at"]
|
||||
ix.update([{"group": "G1", "ord": 0, "title": "t", "text": "Najem lokalu"},
|
||||
{"group": "G9", "ord": 0, "title": "t", "text": "Najem okazjonalny"}],
|
||||
["G1", "G2", "G9"], "m2")
|
||||
assert sorted(g["group"] for g in ix.search("najem")[0]) == ["G1", "G9"] # replaced + added
|
||||
assert [g["group"] for g in ix.search("spółka")[0]] == ["G0"] # G2 deleted
|
||||
assert ix.meta()["docs"] == 3 and ix.meta()["built_at"] != built
|
||||
|
||||
|
||||
def test_an_import_does_not_write_into_an_index_awaiting_its_rebuild(ix):
|
||||
import json
|
||||
ix.rebuild(_rows(1), "m")
|
||||
(ix.path / "index.json").write_text(json.dumps(ix.meta() | {"analysis": "x"}), encoding="utf-8")
|
||||
imp = indexing.DzuMdImporter(MemoryIndexStore(), ix, None, on=True, schedule="15 7 * * *")
|
||||
assert not imp.index_writable() # Postgres only; the rebuild brings it in
|
||||
|
||||
|
||||
# ── notices ─────────────────────────────────────────────────────────────────────────────────────────
|
||||
def test_outage_notices_only_when_a_source_cannot_serve(ix):
|
||||
from app.integrations import dzu_md
|
||||
from app.integrations.base import Query
|
||||
from app.services.legal import outage_notices
|
||||
store = MemoryIndexStore()
|
||||
now = t("2026-10-21T12:00")
|
||||
ad = dzu_md.DzuMdAdapter(store, ix, stale_hours=72, clock=lambda: now)
|
||||
|
||||
class Reg:
|
||||
def get(self, name):
|
||||
return ad
|
||||
|
||||
q = Query(q="najem", kind="act")
|
||||
skipped = [{"name": "dzu_md", "status": "skipped"}]
|
||||
[n] = outage_notices(Reg(), q, skipped) # no index yet
|
||||
assert n["message"] == "Indeks aktów: aktualizacja w toku — wyniki z wyszukiwania na żywo"
|
||||
ix.rebuild(_rows(1), "m")
|
||||
for d in ("dzu_md", "eli_inforce"):
|
||||
store.set_state(d, doc_count=1, completed_at=now, synced_at=now - dt.timedelta(days=5))
|
||||
[n] = outage_notices(Reg(), q, skipped)
|
||||
assert n["message"] == "Indeks aktów: dane z dnia 2026-10-16 — wyniki z wyszukiwania na żywo"
|
||||
store.set_state("dzu_md", synced_at=now)
|
||||
assert outage_notices(Reg(), q, skipped) == [] # it serves: nothing to say
|
||||
assert outage_notices(Reg(), q, [{"name": "dzu_md", "status": "ok"}]) == []
|
||||
assert outage_notices(Reg(), Query(q="x", kind="judgment"), skipped) == []
|
||||
@@ -8,13 +8,14 @@ consolidated texts of it), "sygnaliści" found the free-legal-aid act. Nothing h
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import search_eval as se
|
||||
|
||||
from app.integrations import analysis
|
||||
from app.integrations import dzu_md as dzu
|
||||
from app.integrations import plstem
|
||||
from app.integrations.base import ACT, LegalDoc
|
||||
from app.services import federation, indexing, textindex
|
||||
from app.services.indexstore import MemoryIndexStore
|
||||
@@ -39,6 +40,11 @@ def test_regression_query(adapter, q, want, depth, arts):
|
||||
assert se.passed(rows, want, depth, arts), se.table(adapter)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("q", "want"), se.RECALL, ids=[r[0] for r in se.RECALL])
|
||||
def test_recall_through_lemmas(adapter, q, want):
|
||||
assert se.recalled(adapter, q, want), se.table(adapter)
|
||||
|
||||
|
||||
def test_one_answer_per_act(adapter):
|
||||
"""Thirteen texts of the Labour Code, three of the tenants' act: each answers ONCE, as its newest."""
|
||||
for q, *_ in se.REGRESSION:
|
||||
@@ -119,8 +125,10 @@ def test_reconcile_flags_and_unflags():
|
||||
def test_function_words_never_match_but_content_words_do():
|
||||
""""umowa" is a content word here (the EUR-Lex SPARQL list of common words is NOT the local
|
||||
index's stoplist); "o" is a function word: never required, but kept for the exact phrase."""
|
||||
assert [t[0] for t in plstem.query_terms("umowa o pracę")] == ["umow", "prac"]
|
||||
assert plstem.stems("umowa o pracę", keep_stopwords=True) == ["umow", "o", "prac"]
|
||||
assert [t[0] for t in analysis.query_terms("umowa o pracę", plain=True)] == ["umow", "prac"]
|
||||
assert analysis.analyse("umowa o pracę", keep_stopwords=True, plain=True) == "umow o prac"
|
||||
assert [t[0] for t in analysis.query_terms("umowa o pracę")] == ["umowa", "praca"]
|
||||
assert analysis.analyse("umowa o pracę", keep_stopwords=True) == "umowa o praca"
|
||||
|
||||
|
||||
def _ix(tmp_path, rows):
|
||||
@@ -166,10 +174,59 @@ def test_format_bump_makes_an_index_stale(tmp_path):
|
||||
assert ix.ready() and ix.meta()["format"] == textindex.FORMAT
|
||||
meta_path = ix.path / textindex.META
|
||||
import json
|
||||
meta_path.write_text(json.dumps(ix.meta() | {"format": textindex.FORMAT - 1}), encoding="utf-8")
|
||||
meta = ix.meta()
|
||||
# another analysis (a new lexicon): still answers, a rebuild is pending
|
||||
meta_path.write_text(json.dumps(meta | {"analysis": "pl:2:older"}), encoding="utf-8")
|
||||
assert ix.ready() and not ix.current() and ix.rebuild_pending() and ix.stale_stemmer()
|
||||
# a format today's code cannot read: not ready at all
|
||||
meta_path.write_text(json.dumps(meta | {"format": 1}), encoding="utf-8")
|
||||
assert not ix.ready() and ix.stale_stemmer() # → `ensure_index` rebuilds it
|
||||
|
||||
|
||||
def test_the_previous_index_serves_until_the_rebuild_is_swapped_in(tmp_path, monkeypatch):
|
||||
"""A deploy that bumps FORMAT (2 → 3: plstem stems → lemmas): the format-2 index keeps
|
||||
answering — with the analysis it was built with — through the whole rebuild, in this worker
|
||||
and in another one, and the rebuilt one answers from the moment it is swapped in."""
|
||||
from conftest import TEST_LEXICON_DIR
|
||||
|
||||
from app.integrations import analysis as an
|
||||
rows = [{"group": "A", "ord": 0, "title": "Ustawa", "text": "Umowa zawarta w spółce."}]
|
||||
with monkeypatch.context() as m: # yesterday's code: format 2, no lexicon
|
||||
m.setattr(textindex, "FORMAT", 2)
|
||||
an.configure(None)
|
||||
old = TextIndex(tmp_path / "ix")
|
||||
old._schema = textindex._schema(2)
|
||||
old.rebuild(rows, "m")
|
||||
an.configure(TEST_LEXICON_DIR)
|
||||
ix, other = TextIndex(tmp_path / "ix"), TextIndex(tmp_path / "ix") # two workers
|
||||
assert ix.meta()["format"] == 2 and ix.ready() and ix.rebuild_pending()
|
||||
assert [g["group"] for g in other.search("umowa")[0]] == ["A"] # opened before the swap
|
||||
assert ix.search("spółki")[0] == [] # plstem: spolk ≠ spolc — the old analysis answers
|
||||
|
||||
seen = []
|
||||
|
||||
def during():
|
||||
yield from rows
|
||||
seen.append(([g["group"] for g in ix.search("umowa")[0]],
|
||||
[g["group"] for g in other.search("umowa")[0]], ix.ready()))
|
||||
if os.name == "nt": # Linux renames a directory with open files in it,
|
||||
other._index = None # Windows refuses: there the other worker lets go
|
||||
import gc
|
||||
gc.collect()
|
||||
ix.rebuild(during(), "m2")
|
||||
assert seen == [(["A"], ["A"], True)] # mid-rebuild: served by the previous index
|
||||
assert ix.current() and other.current() and ix.meta()["format"] == 3
|
||||
assert [g["group"] for g in ix.search("spółki")[0]] == ["A"] # the lemmas now
|
||||
assert [g["group"] for g in other.search("spółki")[0]] == ["A"] # the other worker too
|
||||
|
||||
|
||||
def test_the_swap_window_serves_the_previous_directory(tmp_path):
|
||||
"""Between the two renames of a swap the index directory is briefly absent: `.old` answers."""
|
||||
ix = _ix(tmp_path, [{"group": "g", "ord": 0, "title": "t", "text": "sygnaliści"}])
|
||||
ix.path.rename(ix.path.with_name(ix.path.name + ".old"))
|
||||
assert ix.ready() and [g["group"] for g in ix.search("sygnalista")[0]] == ["g"]
|
||||
|
||||
|
||||
def test_federation_drops_the_live_twin_of_an_indexed_act():
|
||||
local = LegalDoc(id="dzu_md:DU/2023/725", source="dzu_md", kind=ACT,
|
||||
title="Ustawa o ochronie praw lokatorów (tekst jednolity)",
|
||||
@@ -193,7 +250,7 @@ T0 = dt.datetime(2026, 10, 21, 12, 0, tzinfo=dt.UTC)
|
||||
|
||||
|
||||
def _eli_importer(store, after="dzu_md"):
|
||||
return indexing.EliInForceImporter(store, None, None, on=True, interval_hours=24,
|
||||
return indexing.EliInForceImporter(store, None, None, on=True, schedule="0 5 * * *",
|
||||
types=["Ustawa"], after=after, clock=lambda: T0)
|
||||
|
||||
|
||||
@@ -221,7 +278,8 @@ def test_an_interrupted_pass_resumes_soon_not_a_day_later():
|
||||
|
||||
def test_dzu_md_resumes_an_interrupted_run():
|
||||
store = MemoryIndexStore()
|
||||
imp = indexing.DzuMdImporter(store, None, None, on=True, interval_hours=6, clock=lambda: T0)
|
||||
imp = indexing.DzuMdImporter(store, None, None, on=True, schedule="15 7 * * *",
|
||||
clock=lambda: T0)
|
||||
store.set_state("dzu_md", attempted_at=T0, synced_at=T0 - dt.timedelta(hours=7))
|
||||
assert imp.due(T0 + indexing.RESUME_AFTER)
|
||||
store.set_state("dzu_md", synced_at=T0 + dt.timedelta(minutes=1))
|
||||
|
||||
+10
-2
@@ -261,12 +261,17 @@ const I18N = {
|
||||
'Wersja / kursor': 'Version / cursor',
|
||||
'Dokumenty': 'Documents',
|
||||
'Indeks gotowy': 'Index ready',
|
||||
'Następne uruchomienie': 'Next run',
|
||||
'trwa': 'running',
|
||||
'bezczynny': 'idle',
|
||||
'wyłączony': 'off',
|
||||
'Artykuły': 'Articles',
|
||||
'brak wyników': 'no results',
|
||||
'Orzeczenia Sądu Najwyższego po 2016 r. nie są dostępne w SAOS — szukaj na sn.pl': 'Supreme Court rulings after 2016 are not available in SAOS — search sn.pl',
|
||||
'Wyniki częściowe — nie wszystkie słowa zapytania występują w tekście': 'Partial results — not every word of the query occurs in the text',
|
||||
'Wynik częściowy — nie wszystkie słowa zapytania': 'Partial match — not every word of the query',
|
||||
'tak (przebudowa w toku)': 'yes (rebuild in progress)',
|
||||
'indeks przebudowywany — odpowiada poprzedni': 'index being rebuilt — the previous one answers',
|
||||
'Orzecznictwo SN': 'Supreme Court case law',
|
||||
'Każdy publikator': 'Any publisher',
|
||||
'Dziennik Urzędowy UE': 'Official Journal of the EU',
|
||||
@@ -892,6 +897,7 @@ function renderSourceLine(sources) {
|
||||
return `<span class="s pending"><span class="spin" aria-hidden="true"></span><b>${esc(PENDING_LABEL[s.name] || s.name)}</b></span>`;
|
||||
}
|
||||
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>`;
|
||||
}).join('');
|
||||
@@ -905,6 +911,7 @@ function hitHtml(d, i, q) {
|
||||
<div class="t">${hl(d.title, q)}</div>
|
||||
<div class="m">${meta.map((m) => `<span>${esc(m)}</span>`).join('')}</div>
|
||||
${d.snippet ? `<div class="sn">${hl(d.snippet, q)}</div>` : ''}
|
||||
${d.extra && d.extra.partial ? '<div class="faint tiny">Wynik częściowy — nie wszystkie słowa zapytania</div>' : ''}
|
||||
${d.extra && d.extra.disclaimer ? `<div class="faint tiny">${esc(d.extra.disclaimer)}</div>` : ''}</button>`;
|
||||
}
|
||||
|
||||
@@ -1082,14 +1089,15 @@ function datasetsCard(ds) {
|
||||
: st === 'idle' ? '<span class="chip ok">bezczynny</span>' : '<span class="chip">wyłączony</span>');
|
||||
const ver = (d) => (d.commit ? String(d.commit).slice(0, 10) : d.cursor ? JSON.stringify(d.cursor).slice(0, 80) : '—');
|
||||
return `<div class="card" id="datasets"><h3>Zbiory danych (tryb INDEXED)</h3><div class="tablewrap"><table class="rt"><thead><tr>
|
||||
<th>Zbiór</th><th>Stan</th><th>Ostatnia synchronizacja</th><th>Wersja / kursor</th><th>Dokumenty</th><th>Indeks gotowy</th></tr></thead><tbody>
|
||||
<th>Zbiór</th><th>Stan</th><th>Ostatnia synchronizacja</th><th>Następne uruchomienie</th><th>Wersja / kursor</th><th>Dokumenty</th><th>Indeks gotowy</th></tr></thead><tbody>
|
||||
${(ds.datasets || []).map((d) => `<tr>
|
||||
<td><b>${esc(d.label || d.name)}</b>${d.error ? `<div class="tiny" style="color:var(--at-danger)">${esc(d.error)}</div>` : ''}${d.off_reason ? `<div class="faint tiny">${esc(d.off_reason)}</div>` : ''}</td>
|
||||
<td${lbl('Stan')}>${chip(d.state)}</td>
|
||||
<td class="tiny"${lbl('Ostatnia synchronizacja')}>${esc(d.synced_at ? fmtDate(d.synced_at) : '—')}</td>
|
||||
<td class="tiny"${lbl('Następne uruchomienie')} title="${esc(d.schedule || '')}">${esc(d.next_run ? fmtDateTime(d.next_run) : '—')}</td>
|
||||
<td class="tiny mono"${lbl('Wersja / kursor')}>${esc(ver(d))}</td>
|
||||
<td${lbl('Dokumenty')}>${esc(String(d.documents || 0))}</td>
|
||||
<td${lbl('Indeks gotowy')}>${d.index && d.index.ready ? 'tak' : 'nie'}</td></tr>`).join('')}
|
||||
<td${lbl('Indeks gotowy')}>${d.index && d.index.ready ? (d.index.rebuild_pending ? 'tak (przebudowa w toku)' : 'tak') : 'nie'}</td></tr>`).join('')}
|
||||
</tbody></table></div></div>`;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user