endomorphosis commited on
Commit
1c25384
·
verified ·
1 Parent(s): 9bf0bb4

Incremental country-laws-ir GraphRAG release for justicedao/ipfs_libya_laws_ir

Browse files
Files changed (42) hide show
  1. README.md +14 -9
  2. country_laws_ir/__main__.py +134 -0
  3. country_laws_ir/citations.py +139 -0
  4. country_laws_ir/data/bluebook_t2.json +27 -0
  5. country_laws_ir/data/learned_line_patterns.json +3 -0
  6. country_laws_ir/duckdb_store.py +67 -0
  7. country_laws_ir/graph.py +4 -4
  8. country_laws_ir/normalize.py +172 -44
  9. country_laws_ir/normalize_loop.py +608 -0
  10. country_laws_ir/package.py +137 -74
  11. country_laws_ir/profiles.py +217 -10
  12. country_laws_ir/query.py +17 -0
  13. country_laws_ir/reconstruct.py +229 -0
  14. country_laws_ir/sparse.py +12 -5
  15. country_laws_ir/structure.py +1929 -108
  16. country_laws_ir/upload.py +87 -18
  17. country_laws_ir/verify.py +110 -1
  18. data/bm25/documents/part-000000.parquet +2 -2
  19. data/bm25/postings/part-000000.parquet +2 -2
  20. data/bm25/postings/part-000001.parquet +3 -0
  21. data/bm25/postings/part-000002.parquet +3 -0
  22. data/bm25/postings/part-000003.parquet +3 -0
  23. data/corpus/part-000000.parquet +2 -2
  24. data/graph/adjacency/in/part-000000.parquet +2 -2
  25. data/graph/adjacency/out/part-000000.parquet +2 -2
  26. data/graph/edges/part-000000.parquet +2 -2
  27. data/graph/edges/part-000001.parquet +2 -2
  28. data/graph/nodes/part-000000.parquet +2 -2
  29. data/vectors/part-000000.parquet +2 -2
  30. indexes/bm25_document_chunks.parquet +2 -2
  31. indexes/bm25_keyword_shards.parquet +2 -2
  32. indexes/corpus_chunks.parquet +1 -1
  33. indexes/graph_edge_chunks.parquet +2 -2
  34. indexes/graph_in_adjacency.parquet +2 -2
  35. indexes/graph_node_chunks.parquet +1 -1
  36. indexes/graph_out_adjacency.parquet +2 -2
  37. indexes/vector_chunks.parquet +2 -2
  38. manifest.json +131 -82
  39. normalization_report.json +72 -23
  40. normalize.py +172 -44
  41. query.py +17 -0
  42. reports/normalization.json +72 -23
README.md CHANGED
@@ -11,6 +11,8 @@ tags:
11
  - not-legal-advice
12
  - libya
13
  pretty_name: Libya laws IR (CID-keyed GraphRAG)
 
 
14
  configs:
15
  - config_name: corpus
16
  data_files:
@@ -47,11 +49,14 @@ configs:
47
  - config_name: graph_outgoing_adjacency
48
  data_files:
49
  - split: train
50
- path: data/graph/adjacency/outgoing/*.parquet
51
  - config_name: graph_incoming_adjacency
52
  data_files:
53
  - split: train
54
- path: data/graph/adjacency/incoming/*.parquet
 
 
 
55
  ---
56
 
57
  # Libya legislation IR (CID-keyed sparse GraphRAG)
@@ -72,14 +77,14 @@ Target Hub id (packaging metadata only): `justicedao/ipfs_libya_laws_ir`.
72
 
73
  | Field | Value |
74
  | --- | --- |
75
- | Laws (corpus units) | 0 |
76
  | Articles (corpus units) | 689 |
77
- | Canonical docs | 689 |
78
- | BM25 terms | 739 |
79
- | BM25 postings | 4645 |
80
- | Graph nodes | 822 |
81
- | Graph edges | 4823 |
82
- | Vectors | 689 × 384-d `thenlper/gte-small` (embedded) |
83
 
84
  ## Canonical fields
85
 
 
11
  - not-legal-advice
12
  - libya
13
  pretty_name: Libya laws IR (CID-keyed GraphRAG)
14
+ size_categories:
15
+ - n<1K
16
  configs:
17
  - config_name: corpus
18
  data_files:
 
49
  - config_name: graph_outgoing_adjacency
50
  data_files:
51
  - split: train
52
+ path: data/graph/adjacency/out/*.parquet
53
  - config_name: graph_incoming_adjacency
54
  data_files:
55
  - split: train
56
+ path: data/graph/adjacency/in/*.parquet
57
+ language:
58
+ - ar
59
+ - en
60
  ---
61
 
62
  # Libya legislation IR (CID-keyed sparse GraphRAG)
 
77
 
78
  | Field | Value |
79
  | --- | --- |
80
+ | Laws (corpus units) | 69 |
81
  | Articles (corpus units) | 689 |
82
+ | Canonical docs | 758 |
83
+ | BM25 terms | 15202 |
84
+ | BM25 postings | 33741 |
85
+ | Graph nodes | 975 |
86
+ | Graph edges | 5306 |
87
+ | Vectors | 758 × 384-d `thenlper/gte-small` (embedded) |
88
 
89
  ## Canonical fields
90
 
country_laws_ir/__main__.py CHANGED
@@ -83,6 +83,21 @@ def main(argv: list[str] | None = None) -> int:
83
  p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country")
84
  p_ver.add_argument("--limit", type=int, default=None)
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  p_raw = sub.add_parser("package-raw")
87
  p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
88
  p_raw.add_argument("--instruments-dir", default=None,
@@ -253,6 +268,125 @@ def main(argv: list[str] | None = None) -> int:
253
  )
254
  )
255
  return 1 if failed else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  if args.cmd == "package-raw":
257
  from .build import RELEASES
258
  from .raw_package import default_instruments_dir, package_instruments
 
83
  p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country")
84
  p_ver.add_argument("--limit", type=int, default=None)
85
 
86
+ p_loop = sub.add_parser(
87
+ "normalize-loop",
88
+ help="scan residuals, improve the normalizer script with llm_router, or apply that script",
89
+ )
90
+ p_loop.add_argument("stage", choices=["scan", "improve", "apply", "run"])
91
+ p_loop.add_argument("--cache", default=None)
92
+ p_loop.add_argument("--out", default=None)
93
+ p_loop.add_argument("--reports", default=None, help="Per-country residual JSON directory")
94
+ p_loop.add_argument("--slug", default=None, help="One country, for a subprocess")
95
+ p_loop.add_argument("--workers", type=int, default=None, help="Country processes (default: one per CPU)")
96
+ p_loop.add_argument("--limit", type=int, default=None)
97
+ p_loop.add_argument("--passes", type=int, default=40, help="Improve batches sent to llm_router")
98
+ p_loop.add_argument("--force", action="store_true", help="Redo finished countries and retry unresolved lines")
99
+ p_loop.add_argument("--progress", default=None, help="JSONL file appended as each country or improve pass finishes")
100
+
101
  p_raw = sub.add_parser("package-raw")
102
  p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
103
  p_raw.add_argument("--instruments-dir", default=None,
 
268
  )
269
  )
270
  return 1 if failed else 0
271
+ if args.cmd == "normalize-loop":
272
+ from .build import CACHE, ROOT
273
+ from .normalize_loop import (
274
+ _apply_job,
275
+ _scan_job,
276
+ append_progress,
277
+ apply_done,
278
+ cache_packs,
279
+ improve_from_reports,
280
+ load_generate_text,
281
+ run_parallel,
282
+ scan_done,
283
+ worker_count,
284
+ )
285
+
286
+ cache = Path(args.cache) if args.cache else CACHE
287
+ reports = Path(args.reports) if args.reports else ROOT / "reports" / "residuals"
288
+ out = Path(args.out) if args.out else ROOT / "llm-normalized"
289
+ packs = cache_packs(cache, slug=args.slug)
290
+ if args.limit:
291
+ packs = packs[: int(args.limit)]
292
+ workers = worker_count(args.workers)
293
+ progress = Path(args.progress) if args.progress else ROOT / "reports" / f"normalize_{args.stage}.jsonl"
294
+
295
+ def _pending(stage: str) -> tuple[list[tuple[str, str, str]], list[str]]:
296
+ jobs: list[tuple[str, str, str]] = []
297
+ skipped: list[str] = []
298
+ for slug, path in packs:
299
+ done = scan_done(reports, slug) if stage == "scan" else apply_done(out, slug)
300
+ if done and not args.force:
301
+ skipped.append(slug)
302
+ continue
303
+ dest = reports if stage == "scan" else out
304
+ jobs.append((slug, str(path), str(dest)))
305
+ return jobs, skipped
306
+
307
+ def _run(stage: str, worker) -> list[dict]:
308
+ jobs, skipped = _pending(stage)
309
+ total = len(jobs) + len(skipped)
310
+ done = len(skipped)
311
+ print(json.dumps({
312
+ "event": "start",
313
+ "stage": stage,
314
+ "workers": workers,
315
+ "done": done,
316
+ "pending": len(jobs),
317
+ "total": total,
318
+ "progress": str(progress),
319
+ }), flush=True)
320
+ state = {"done": done}
321
+
322
+ def _on_done(row: dict) -> None:
323
+ state["done"] += 1
324
+ print(json.dumps({
325
+ "event": stage,
326
+ "done": state["done"],
327
+ "total": total,
328
+ **row,
329
+ }), flush=True)
330
+
331
+ return run_parallel(jobs, worker, workers, progress_path=progress, on_done=_on_done)
332
+
333
+ if args.stage == "scan":
334
+ rows = _run("scan", _scan_job)
335
+ failed = [row for row in rows if row.get("error")]
336
+ print(json.dumps({"stage": "scan", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2))
337
+ return 1 if failed else 0
338
+ if args.stage == "apply":
339
+ rows = _run("apply", _apply_job)
340
+ failed = [row for row in rows if row.get("error")]
341
+ print(json.dumps({"stage": "apply", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2))
342
+ return 1 if failed else 0
343
+ def _on_pass(row: dict) -> None:
344
+ print(json.dumps({"event": "improve", **row}, ensure_ascii=False), flush=True)
345
+ append_progress(progress, {"event": "improve", **row})
346
+
347
+ def _improve():
348
+ print(json.dumps({
349
+ "event": "start",
350
+ "stage": "improve",
351
+ "passes": args.passes,
352
+ "reports": str(reports),
353
+ }), flush=True)
354
+ try:
355
+ generate = load_generate_text()
356
+ except Exception as exc:
357
+ print(json.dumps({"error": f"llm_router unavailable: {exc}"}), flush=True)
358
+ return None
359
+ return improve_from_reports(
360
+ reports,
361
+ generate,
362
+ max_passes=args.passes,
363
+ on_pass=_on_pass,
364
+ reset_unresolved=bool(args.force),
365
+ )
366
+
367
+ if args.stage == "improve":
368
+ result = _improve()
369
+ if result is None:
370
+ return 1
371
+ print(json.dumps({"stage": "improve", **result}, indent=2, ensure_ascii=False))
372
+ return 0
373
+ # run scans, then improves the script. Applying the script to every
374
+ # pack is the separate ``apply`` stage.
375
+ scan_rows = _run("scan", _scan_job)
376
+ failed = [row for row in scan_rows if row.get("error")]
377
+ if failed:
378
+ print(json.dumps({"stage": "run", "n_scanned": len(scan_rows), "n_failed": len(failed)}, indent=2))
379
+ return 1
380
+ improved = _improve()
381
+ if improved is None:
382
+ return 1
383
+ print(json.dumps(
384
+ {"stage": "run", "workers": workers, "improve": improved, "n_scanned": len(scan_rows)},
385
+ indent=2,
386
+ ensure_ascii=False,
387
+ default=str,
388
+ ))
389
+ return 0
390
  if args.cmd == "package-raw":
391
  from .build import RELEASES
392
  from .raw_package import default_instruments_dir, package_instruments
country_laws_ir/citations.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Official and Bluebook citations for country-law corpus rows.
2
+
3
+ Bluebook T2/T10 abbreviations are used only when this table has a row.
4
+ Unknown jurisdictions get ``official_citation`` only — never a invented
5
+ Bluebook form. Query keys are normalized so ``ORS 1.010`` and
6
+ ``Or. Rev. Stat. § 1.010`` can hit the same row later.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ import re
13
+ import unicodedata
14
+ from typing import Any
15
+
16
+ from pathlib import Path
17
+ import json as _json
18
+
19
+ _TABLE_PATH = Path(__file__).resolve().parent / "data" / "bluebook_t2.json"
20
+
21
+
22
+ def _load_t2() -> dict[str, dict[str, Any]]:
23
+ if not _TABLE_PATH.is_file():
24
+ return {}
25
+ payload = _json.loads(_TABLE_PATH.read_text(encoding="utf-8"))
26
+ return payload if isinstance(payload, dict) else {}
27
+
28
+
29
+ _BLUEBOOK_T2 = _load_t2()
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Citation:
34
+ official_citation: str
35
+ bluebook_citation: str
36
+ cite_key: str
37
+ citation_status: str # bluebook | official_only | unknown
38
+ pinpoint: str
39
+
40
+
41
+ def normalize_cite_key(value: str) -> str:
42
+ if not value:
43
+ return ""
44
+ text = unicodedata.normalize("NFKC", value).lower()
45
+ text = text.replace("§", " s ")
46
+ text = text.replace("¶", " ")
47
+ text = re.sub(r"\bart(?:icle|\.)?\b", "art", text)
48
+ text = re.sub(r"\bsec(?:tion|\.)?\b", "s", text)
49
+ text = re.sub(r"[^a-z0-9]+", " ", text)
50
+ return re.sub(r"\s+", " ", text).strip()
51
+
52
+
53
+ def _pinpoint(article_number: str, section_number: str, record_type: str) -> str:
54
+ if record_type == "section" and section_number:
55
+ return f"§ {section_number}"
56
+ if article_number:
57
+ return f"art. {article_number}"
58
+ if section_number:
59
+ return f"§ {section_number}"
60
+ return ""
61
+
62
+
63
+ def _t2_row(jurisdiction: str, country: str, slug: str = "") -> dict[str, Any]:
64
+ for key in (slug, country, jurisdiction):
65
+ hit = _BLUEBOOK_T2.get(str(key or "").strip().lower().replace("_", " "))
66
+ if isinstance(hit, dict):
67
+ return hit
68
+ return {}
69
+
70
+
71
+ def assign_citation(
72
+ *,
73
+ eli: str = "",
74
+ official_identifier: str = "",
75
+ identifier: str = "",
76
+ instrument_title: str = "",
77
+ article_number: str = "",
78
+ section_number: str = "",
79
+ record_type: str = "law",
80
+ jurisdiction: str = "",
81
+ country: str = "",
82
+ slug: str = "",
83
+ year: str = "",
84
+ ) -> Citation:
85
+ pinpoint = _pinpoint(article_number, section_number, record_type)
86
+ official = (
87
+ (eli or "").strip()
88
+ or (official_identifier or "").strip()
89
+ or (identifier or "").strip()
90
+ or (instrument_title or "").strip()
91
+ )
92
+ if official and pinpoint and pinpoint.lower() not in official.lower():
93
+ official_cite = f"{official}, {pinpoint}"
94
+ else:
95
+ official_cite = official
96
+
97
+ t2 = _t2_row(jurisdiction, country, slug)
98
+ abbrev = str(t2.get("abbrev") or "")
99
+ emit = str(t2.get("emit") or "official_only")
100
+ required = list(t2.get("required") or [])
101
+ have = {
102
+ "year": bool(year),
103
+ "section": bool(section_number or (record_type == "section" and article_number)),
104
+ "article": bool(article_number),
105
+ "title": bool(instrument_title),
106
+ }
107
+ missing = [k for k in required if not have.get(k)]
108
+ bluebook = ""
109
+ if emit == "bluebook" and abbrev and not missing:
110
+ if pinpoint:
111
+ bluebook = f"{abbrev} {pinpoint}" + (f" ({year})" if year else "")
112
+ elif have.get("section"):
113
+ bluebook = f"{abbrev} § {section_number}" + (f" ({year})" if year else "")
114
+
115
+ if bluebook:
116
+ status = "bluebook"
117
+ elif official_cite:
118
+ status = "official_only"
119
+ else:
120
+ status = "unknown"
121
+
122
+ key_src = bluebook or official_cite
123
+ return Citation(
124
+ official_citation=official_cite,
125
+ bluebook_citation=bluebook,
126
+ cite_key=normalize_cite_key(key_src),
127
+ citation_status=status,
128
+ pinpoint=pinpoint,
129
+ )
130
+
131
+
132
+ def citation_fields(cite: Citation) -> dict[str, Any]:
133
+ return {
134
+ "official_citation": cite.official_citation,
135
+ "bluebook_citation": cite.bluebook_citation,
136
+ "cite_key": cite.cite_key,
137
+ "citation_status": cite.citation_status,
138
+ "pinpoint": cite.pinpoint,
139
+ }
country_laws_ir/data/bluebook_t2.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "usa": {"abbrev": "U.S.C.", "emit": "bluebook", "required": ["title", "section"]},
3
+ "united states": {"abbrev": "U.S.C.", "emit": "bluebook", "required": ["title", "section"]},
4
+ "uk": {"abbrev": "U.K.", "emit": "official_only", "required": []},
5
+ "united kingdom": {"abbrev": "U.K.", "emit": "official_only", "required": []},
6
+ "australia": {"abbrev": "Cth", "emit": "official_only", "required": ["year"]},
7
+ "canada": {"abbrev": "S.C.", "emit": "official_only", "required": ["year"]},
8
+ "germany": {"abbrev": "BGBl.", "emit": "official_only", "required": []},
9
+ "france": {"abbrev": "J.O.", "emit": "official_only", "required": []},
10
+ "malta": {"abbrev": "Laws of Malta", "emit": "official_only", "required": []},
11
+ "ireland": {"abbrev": "Ir.", "emit": "official_only", "required": []},
12
+ "newzealand": {"abbrev": "N.Z.", "emit": "official_only", "required": []},
13
+ "new zealand": {"abbrev": "N.Z.", "emit": "official_only", "required": []},
14
+ "southafrica": {"abbrev": "S. Afr.", "emit": "official_only", "required": []},
15
+ "south africa": {"abbrev": "S. Afr.", "emit": "official_only", "required": []},
16
+ "india": {"abbrev": "India", "emit": "official_only", "required": []},
17
+ "japan": {"abbrev": "Japan", "emit": "official_only", "required": []},
18
+ "china": {"abbrev": "P.R.C.", "emit": "official_only", "required": []},
19
+ "netherlands": {"abbrev": "Stb.", "emit": "official_only", "required": []},
20
+ "austria": {"abbrev": "BGBl.", "emit": "official_only", "required": []},
21
+ "switzerland": {"abbrev": "AS", "emit": "official_only", "required": []},
22
+ "sweden": {"abbrev": "SFS", "emit": "official_only", "required": []},
23
+ "norway": {"abbrev": "Norsk Lovtidend", "emit": "official_only", "required": []},
24
+ "denmark": {"abbrev": "Lovtidende", "emit": "official_only", "required": []},
25
+ "finland": {"abbrev": "Finlex", "emit": "official_only", "required": []},
26
+ "eu": {"abbrev": "O.J.", "emit": "official_only", "required": []}
27
+ }
country_laws_ir/data/learned_line_patterns.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "patterns": []
3
+ }
country_laws_ir/duckdb_store.py CHANGED
@@ -151,6 +151,73 @@ def bm25_search(root: Path, query: str, top_k: int = 10) -> list[dict[str, Any]]
151
  con.close()
152
 
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  def graph_neighbors(
155
  root: Path,
156
  node_cid: str,
 
151
  con.close()
152
 
153
 
154
+ def cite_search(
155
+ root: Path,
156
+ citation: str,
157
+ *,
158
+ cite_format: str = "any",
159
+ limit: int = 25,
160
+ ) -> list[dict[str, Any]]:
161
+ """Look up corpus rows by Bluebook, official cite, or normalized cite_key."""
162
+ from .citations import normalize_cite_key
163
+
164
+ needle = (citation or "").strip()
165
+ if not needle:
166
+ return []
167
+ key = normalize_cite_key(needle)
168
+ con = connect_release(root)
169
+ try:
170
+ tables = {
171
+ r[0]
172
+ for r in con.execute(
173
+ "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
174
+ ).fetchall()
175
+ }
176
+ if "corpus" not in tables:
177
+ raise DuckDBStoreError("release is missing corpus parquet shards")
178
+ cols = [
179
+ r[1]
180
+ for r in con.execute(
181
+ "SELECT table_schema, column_name FROM information_schema.columns "
182
+ "WHERE table_schema = 'main' AND table_name = 'corpus'"
183
+ ).fetchall()
184
+ ]
185
+ wanted = [
186
+ "entry_cid",
187
+ "record_type",
188
+ "title",
189
+ "instrument_title",
190
+ "article_number",
191
+ "official_citation",
192
+ "bluebook_citation",
193
+ "cite_key",
194
+ "citation_status",
195
+ "source_url",
196
+ ]
197
+ select = ", ".join(c for c in wanted if c in cols) or "*"
198
+ clauses = []
199
+ params: list[Any] = []
200
+ fmt = (cite_format or "any").strip().lower()
201
+ if fmt in {"any", "bluebook"} and "bluebook_citation" in cols:
202
+ clauses.append("lower(coalesce(bluebook_citation, '')) = lower(?)")
203
+ params.append(needle)
204
+ if fmt in {"any", "official"} and "official_citation" in cols:
205
+ clauses.append("lower(coalesce(official_citation, '')) = lower(?)")
206
+ params.append(needle)
207
+ if "cite_key" in cols and key:
208
+ clauses.append("cite_key = ?")
209
+ params.append(key)
210
+ if not clauses:
211
+ return []
212
+ sql = f"SELECT {select} FROM corpus WHERE {' OR '.join(clauses)} LIMIT ?"
213
+ params.append(int(limit))
214
+ rows = con.execute(sql, params).fetchall()
215
+ names = [c for c in wanted if c in cols] if select != "*" else list(cols)
216
+ return [dict(zip(names, row)) for row in rows]
217
+ finally:
218
+ con.close()
219
+
220
+
221
  def graph_neighbors(
222
  root: Path,
223
  node_cid: str,
country_laws_ir/graph.py CHANGED
@@ -68,7 +68,7 @@ def build_graph(
68
  "node_cid": law_cid,
69
  "node_type": "law",
70
  "entry_cid": "",
71
- "label": getattr(rec, "instrument_title", None) or instrument_id,
72
  "properties_json": _json(
73
  {
74
  "instrument_id": instrument_id,
@@ -92,7 +92,7 @@ def build_graph(
92
  "node_cid": rec.entry_cid,
93
  "node_type": node_type,
94
  "entry_cid": rec.entry_cid,
95
- "label": title,
96
  "properties_json": _props_tuple(rec),
97
  "schema_version": SCHEMA_VERSION,
98
  }
@@ -112,7 +112,7 @@ def build_graph(
112
  "node_cid": fc,
113
  "node_type": f"facet_{kind}",
114
  "entry_cid": "",
115
- "label": f"{kind}:{value}",
116
  "properties_json": _json({"kind": kind, "value": value}),
117
  "schema_version": SCHEMA_VERSION,
118
  }
@@ -157,7 +157,7 @@ def build_graph(
157
 
158
  law_cid = str(row_map.get("law_cid") or "")
159
  instrument_id = str(row_map.get("instrument_id") or "")
160
- if rec.record_type == "article":
161
  parent = entry_by_instrument.get(instrument_id) or law_cid
162
  if parent and parent != rec.entry_cid:
163
  edges.append(
 
68
  "node_cid": law_cid,
69
  "node_type": "law",
70
  "entry_cid": "",
71
+ "label": str(getattr(rec, "instrument_title", None) or instrument_id).replace("\x00", ""),
72
  "properties_json": _json(
73
  {
74
  "instrument_id": instrument_id,
 
92
  "node_cid": rec.entry_cid,
93
  "node_type": node_type,
94
  "entry_cid": rec.entry_cid,
95
+ "label": str(title or "").replace("\x00", ""),
96
  "properties_json": _props_tuple(rec),
97
  "schema_version": SCHEMA_VERSION,
98
  }
 
112
  "node_cid": fc,
113
  "node_type": f"facet_{kind}",
114
  "entry_cid": "",
115
+ "label": f"{kind}:{value}".replace("\x00", ""),
116
  "properties_json": _json({"kind": kind, "value": value}),
117
  "schema_version": SCHEMA_VERSION,
118
  }
 
157
 
158
  law_cid = str(row_map.get("law_cid") or "")
159
  instrument_id = str(row_map.get("instrument_id") or "")
160
+ if rec.record_type in {"article", "section"}:
161
  parent = entry_by_instrument.get(instrument_id) or law_cid
162
  if parent and parent != rec.entry_cid:
163
  edges.append(
country_laws_ir/normalize.py CHANGED
@@ -24,6 +24,12 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
24
  from .auth import configure_hf, public_token
25
  from .cidutil import cid_of_json, sha256_file, sha256_hex
26
  from .schema import SchemaError, validate_articles, validate_laws
 
 
 
 
 
 
27
  from .structure import normalize_legal_text, split_structured_units
28
 
29
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
@@ -399,6 +405,34 @@ def _base_record(
399
  }
400
  if extra:
401
  rec.update(extra)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  rec["entry_cid"] = _entry_cid(rec)
403
  rec["title_length"] = len(title_for_bm25)
404
  rec["body_length"] = len(body)
@@ -455,16 +489,137 @@ def build_corpus(
455
  "schema_surprises": list(source_meta.get("schema_surprises") or []),
456
  "n_out": 0,
457
  "never_invented_legal_text": True,
 
 
 
 
458
  }
459
 
460
  entries: list[dict[str, Any]] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
 
462
  if sparse_fallback:
463
  report["schema_surprises"].append(
464
  f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
465
  )
466
 
467
- if use_articles:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  for _, row in articles.iterrows():
469
  source_id = _row_get(row, "id")
470
  instrument_id = _row_get(row, "law_id")
@@ -521,13 +676,10 @@ def build_corpus(
521
  },
522
  )
523
  )
524
- else:
525
  for instrument_id, parent in law_map.items():
526
  body = parent["body"]
527
  if not body:
528
- report["drops"]["empty_body"] += 1
529
- if len(report["drop_samples"]["empty_body"]) < 20:
530
- report["drop_samples"]["empty_body"].append(instrument_id)
531
  continue
532
  meta = parent["metadata"]
533
  units = split_structured_units(body, language=parent["language"])
@@ -572,49 +724,11 @@ def build_corpus(
572
  },
573
  )
574
  )
575
- continue
576
- entries.append(
577
- _base_record(
578
- record_type="law",
579
- source_dataset=source_dataset,
580
- source_revision=source_revision,
581
- instrument_id=instrument_id,
582
- instrument_title=parent["instrument_title"],
583
- law_cid=parent["law_cid"],
584
- article_number="",
585
- article_title="",
586
- body=body,
587
- jurisdiction=parent["jurisdiction"],
588
- language=parent["language"],
589
- source_url=parent["source_url"],
590
- snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
591
- coverage=_coverage_from(
592
- parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback
593
- ),
594
- license_expr=parent["license"],
595
- collector=_collector(meta, source_dataset),
596
- source_id=instrument_id,
597
- extra={
598
- "eli": parent["eli"],
599
- "identifier": parent["identifier"],
600
- "official_identifier": parent["official_identifier"],
601
- "source_type": parent["source_type"],
602
- "country": parent["country"],
603
- "law_status": parent["law_status"],
604
- "parent_law_id": "",
605
- "article_id": "",
606
- **_hierarchy_fields(
607
- parent["instrument_title"], body, "", language=parent["language"]
608
- ),
609
- },
610
- )
611
- )
612
 
613
  entries.sort(
614
  key=lambda r: (
615
  r["instrument_id"],
616
- r.get("article_number") or "",
617
- r["source_id"],
618
  )
619
  )
620
  n_before = len(entries)
@@ -639,6 +753,20 @@ def build_corpus(
639
  raise SchemaError("Duplicate entry_cid remained after dedupe")
640
  report["n_before_dedupe"] = n_before
641
  report["n_out"] = int(len(df))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  report["n_dropped_total"] = (
643
  report["drops"]["empty_body"]
644
  + report["drops"]["missing_instrument"]
 
24
  from .auth import configure_hf, public_token
25
  from .cidutil import cid_of_json, sha256_file, sha256_hex
26
  from .schema import SchemaError, validate_articles, validate_laws
27
+ from .reconstruct import (
28
+ article_sort_key,
29
+ parent_needs_reconstruct,
30
+ reconstruct_on,
31
+ reconstruct_parent,
32
+ )
33
  from .structure import normalize_legal_text, split_structured_units
34
 
35
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
 
405
  }
406
  if extra:
407
  rec.update(extra)
408
+ from .citations import assign_citation, citation_fields
409
+
410
+ slug = ""
411
+ if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
412
+ slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
413
+ year = ""
414
+ if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit():
415
+ year = snapshot_date[:4]
416
+ extra = extra or {}
417
+ rec.update(
418
+ citation_fields(
419
+ assign_citation(
420
+ eli=str(rec.get("eli") or extra.get("eli") or ""),
421
+ official_identifier=str(
422
+ rec.get("official_identifier") or extra.get("official_identifier") or ""
423
+ ),
424
+ identifier=str(rec.get("identifier") or extra.get("identifier") or ""),
425
+ instrument_title=instrument_title,
426
+ article_number=article_number,
427
+ section_number=str(extra.get("section_number") or ""),
428
+ record_type=record_type,
429
+ jurisdiction=jurisdiction,
430
+ country=str(extra.get("country") or ""),
431
+ slug=slug,
432
+ year=year,
433
+ )
434
+ )
435
+ )
436
  rec["entry_cid"] = _entry_cid(rec)
437
  rec["title_length"] = len(title_for_bm25)
438
  rec["body_length"] = len(body)
 
489
  "schema_surprises": list(source_meta.get("schema_surprises") or []),
490
  "n_out": 0,
491
  "never_invented_legal_text": True,
492
+ "n_reconstructed_parents": 0,
493
+ "n_reconstructed_truncated": 0,
494
+ "n_reconstructed_stubs": 0,
495
+ "n_empty_parents_with_articles_not_reconstructed": 0,
496
  }
497
 
498
  entries: list[dict[str, Any]] = []
499
+ slug = ""
500
+ if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
501
+ slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
502
+
503
+ children_by_law: dict[str, list[dict[str, Any]]] = {}
504
+ if not articles_empty:
505
+ for _, row in articles.iterrows():
506
+ lid = _row_get(row, "law_id")
507
+ if not lid:
508
+ continue
509
+ children_by_law.setdefault(lid, []).append(
510
+ {
511
+ "id": _row_get(row, "id"),
512
+ "title": _row_get(row, "title"),
513
+ "article_number": _row_get(row, "article_number"),
514
+ "body": _row_get(row, "text"),
515
+ "row": row,
516
+ }
517
+ )
518
+
519
+ reconstructed_ids: set[str] = set()
520
+ running_extra_bytes = 0
521
+
522
+ def _append_law_row(
523
+ instrument_id: str,
524
+ parent: dict[str, Any],
525
+ recon=None,
526
+ ) -> None:
527
+ body = parent["body"]
528
+ recon_extra: dict[str, Any] = {}
529
+ coverage = _coverage_from(
530
+ parent["row"],
531
+ parent["metadata"],
532
+ articles_empty=articles_empty,
533
+ sparse_fallback=sparse_fallback,
534
+ )
535
+ if recon is not None and recon.reconstructed_from_articles:
536
+ body = recon.body
537
+ recon_extra = recon.extra_fields()
538
+ coverage = f"{coverage}; reconstructed_from_articles"
539
+ if not body:
540
+ kids = children_by_law.get(instrument_id) or []
541
+ if kids:
542
+ report["n_empty_parents_with_articles_not_reconstructed"] += 1
543
+ report["drops"]["empty_body"] += 1
544
+ if len(report["drop_samples"]["empty_body"]) < 20:
545
+ report["drop_samples"]["empty_body"].append(instrument_id)
546
+ return
547
+ meta = parent["metadata"]
548
+ entries.append(
549
+ _base_record(
550
+ record_type="law",
551
+ source_dataset=source_dataset,
552
+ source_revision=source_revision,
553
+ instrument_id=instrument_id,
554
+ instrument_title=parent["instrument_title"],
555
+ law_cid=parent["law_cid"],
556
+ article_number="",
557
+ article_title="",
558
+ body=body,
559
+ jurisdiction=parent["jurisdiction"],
560
+ language=parent["language"],
561
+ source_url=parent["source_url"],
562
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
563
+ coverage=coverage,
564
+ license_expr=parent["license"],
565
+ collector=_collector(meta, source_dataset),
566
+ source_id=instrument_id,
567
+ extra={
568
+ "eli": parent["eli"],
569
+ "identifier": parent["identifier"],
570
+ "official_identifier": parent["official_identifier"],
571
+ "source_type": parent["source_type"],
572
+ "country": parent["country"],
573
+ "law_status": parent["law_status"],
574
+ "parent_law_id": "",
575
+ "article_id": "",
576
+ "reconstructed_from_articles": False,
577
+ **_hierarchy_fields(
578
+ parent["instrument_title"], body, "", language=parent["language"]
579
+ ),
580
+ **recon_extra,
581
+ },
582
+ )
583
+ )
584
 
585
  if sparse_fallback:
586
  report["schema_surprises"].append(
587
  f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
588
  )
589
 
590
+ for instrument_id, parent in law_map.items():
591
+ kids = children_by_law.get(instrument_id) or []
592
+ recon = None
593
+ if reconstruct_on() and parent_needs_reconstruct(parent["body"], len(kids)):
594
+ recon = reconstruct_parent(
595
+ slug=slug,
596
+ parent_body=parent["body"],
597
+ parent_title=parent["instrument_title"],
598
+ children=[
599
+ {
600
+ "id": k["id"],
601
+ "title": k["title"],
602
+ "article_number": k["article_number"],
603
+ "body": k["body"],
604
+ }
605
+ for k in kids
606
+ ],
607
+ running_extra_bytes=running_extra_bytes,
608
+ sha256_hex=sha256_hex,
609
+ )
610
+ running_extra_bytes += recon.extra_bytes
611
+ reconstructed_ids.add(instrument_id)
612
+ report["n_reconstructed_parents"] += 1
613
+ if recon.reconstruction_truncated:
614
+ report["n_reconstructed_truncated"] += 1
615
+ if recon.is_stub:
616
+ report["n_reconstructed_stubs"] += 1
617
+ _append_law_row(instrument_id, parent, recon)
618
+
619
+ emit_articles = use_articles or bool(reconstructed_ids)
620
+ skip_body_split = emit_articles
621
+
622
+ if emit_articles:
623
  for _, row in articles.iterrows():
624
  source_id = _row_get(row, "id")
625
  instrument_id = _row_get(row, "law_id")
 
676
  },
677
  )
678
  )
679
+ elif not skip_body_split:
680
  for instrument_id, parent in law_map.items():
681
  body = parent["body"]
682
  if not body:
 
 
 
683
  continue
684
  meta = parent["metadata"]
685
  units = split_structured_units(body, language=parent["language"])
 
724
  },
725
  )
726
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
727
 
728
  entries.sort(
729
  key=lambda r: (
730
  r["instrument_id"],
731
+ article_sort_key(r.get("article_number") or "", r["source_id"]),
 
732
  )
733
  )
734
  n_before = len(entries)
 
753
  raise SchemaError("Duplicate entry_cid remained after dedupe")
754
  report["n_before_dedupe"] = n_before
755
  report["n_out"] = int(len(df))
756
+ if not df.empty and "record_type" in df.columns:
757
+ n_law_rows = int((df["record_type"] == "law").sum())
758
+ n_child_rows = int(df["record_type"].isin(["article", "section"]).sum())
759
+ report["n_law_rows"] = n_law_rows
760
+ report["n_child_rows"] = n_child_rows
761
+ report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows
762
+ if n_law_rows and n_child_rows:
763
+ report["unit"] = (
764
+ "law+structured" if report.get("unit") == "structured" else "law+article"
765
+ )
766
+ elif n_law_rows:
767
+ report["unit"] = "law"
768
+ elif n_child_rows:
769
+ report["unit"] = "article"
770
  report["n_dropped_total"] = (
771
  report["drops"]["empty_body"]
772
  + report["drops"]["missing_instrument"]
country_laws_ir/normalize_loop.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Improve the row normalizer, then let that script normalize every row.
2
+
3
+ ``scan`` and ``apply`` only call ``normalize_legal_text``. They do not import
4
+ the LLM router, so one subprocess per country does not boot a model.
5
+
6
+ ``improve`` imports ``llm_router`` once. Each pass sends a short batch of
7
+ lines the current script still leaves in place. The model proposes whole-line
8
+ patterns. A pattern is stored only when it matches one of those lines, misses
9
+ every held-out legal sentence, and the script then actually drops the line.
10
+ Accepted patterns live in ``data/learned_line_patterns.json`` and are applied
11
+ by the same script that normalizes the rows. The model never rewrites a row.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import re
20
+ from collections import Counter
21
+ from concurrent.futures import ProcessPoolExecutor, as_completed
22
+ from pathlib import Path
23
+ from typing import Any, Callable, Sequence
24
+
25
+ from .catalog import EXCLUDED_SLUGS
26
+ from .structure import learned_patterns_path, normalize_legal_text
27
+
28
+ GenerateText = Callable[[str], str]
29
+
30
+ # Sentences the learned rules must not delete. Whole-line patterns that
31
+ # full-match any of these are discarded.
32
+ KEEP_LINES = (
33
+ "Article 1 The present Act applies throughout the territory and binds every person.",
34
+ "The court in Malawi shall apply the Public Roads Act throughout the territory.",
35
+ "2. Amendment of section 5 of Cap. 122A",
36
+ "publié au Journal Officiel et entre en vigueur sur tout le territoire.",
37
+ "10 dicembre 1948",
38
+ "Quarta-Feira de Cinzas continua a ser feriado nacional.",
39
+ "Phone: +1 202 555 0100 is the number appointed under this section.",
40
+ "Troubleshoot faulty system.",
41
+ "100 GENERAL PROVISIONS",
42
+ "applicable rule applies throughout the territory.",
43
+ "The register is published at www.example.com for public inspection under this Act.",
44
+ "بسم الله الرحمن الرحيم",
45
+ "Done at Brussels, 25 June 1999.",
46
+ "2",
47
+ "10",
48
+ "published in the Gazette.",
49
+ "Gazetted 1 October 2009",
50
+ "Lycée : séries ES, L et S",
51
+ "au Journal Officiel",
52
+ "Subs. ibid., for “local official Gazette”.",
53
+ "(a) books (excluding printed music and periodicals) ;",
54
+ "Act 19 Copyright and Neighbouring Rights Act 2006",
55
+ )
56
+
57
+ # One local-model window is 1024 tokens. Keep the prompt well under that.
58
+ PROMPT_CHAR_BUDGET = 1600
59
+ _PROMPT_PREFIX = (
60
+ "These lines survived legal-text normalization. "
61
+ 'Propose JSON only: {"line_patterns": ["^...$"]}. '
62
+ "Each pattern must match one whole chrome line (page header, site footer, "
63
+ "printer stamp) and must not match a legal sentence. Do not write legal text. "
64
+ 'If none are safe, return {"line_patterns": []}.\n'
65
+ )
66
+
67
+
68
+ def cache_packs(cache_dir: Path, slug: str | None = None) -> list[tuple[str, Path]]:
69
+ packs: list[tuple[str, Path]] = []
70
+ for path in sorted(cache_dir.glob("*_corpus.parquet")):
71
+ name = path.name[: -len("_corpus.parquet")]
72
+ if name in EXCLUDED_SLUGS or not name:
73
+ continue
74
+ if slug is not None and name != slug:
75
+ continue
76
+ packs.append((name, path))
77
+ return packs
78
+
79
+
80
+ _HEADING_LINE = re.compile(
81
+ r"(?i)^(article|art\.|section|chapter|part|subtopic|§)\b"
82
+ )
83
+ _CHROME_HINT = re.compile(
84
+ r"(?i)(translated|serial number|copyright|gazette|https?://|www\.|"
85
+ r"\bpage\b|printed|journal officiel|série|series\b)"
86
+ )
87
+ # Repeated lines that are still the law, not a banner. The router must not see them.
88
+ _PROVISION_LINE = re.compile(
89
+ r"(?i)(publi[eé]|lycée|lycee|newspaper|days after|série cei|série en |"
90
+ r"\bshall\b|\bmust\b|inserted sig|the gazette\.$|in the gazette\.$|"
91
+ r"\bgazetted\b|\bau journal officiel\b|subs\.\s*ibid|"
92
+ r"excluding printed|whether or not printed|neighbouring rights|"
93
+ r"série de classe|note de bas de page|communaut[eé]s europ)"
94
+ )
95
+
96
+
97
+ def scan_pack(path: Path, *, sample_lines: int = 40) -> dict[str, Any]:
98
+ """Count rows and keep the repeated short lines the script did not remove."""
99
+ import pyarrow.parquet as pq
100
+
101
+ pf = pq.ParquetFile(path)
102
+ if "body" not in set(pf.schema_arrow.names):
103
+ raise ValueError(f"{path.name} has no body column")
104
+ short: Counter[str] = Counter()
105
+ n = 0
106
+ n_changed = 0
107
+ n_unstable = 0
108
+ for batch in pf.iter_batches(batch_size=512, columns=["body"]):
109
+ for body in batch.column("body").to_pylist():
110
+ if body is None:
111
+ continue
112
+ original = body if isinstance(body, str) else str(body)
113
+ n += 1
114
+ normalized = normalize_legal_text(original)
115
+ if normalized != original:
116
+ n_changed += 1
117
+ if normalize_legal_text(normalized) != normalized:
118
+ n_unstable += 1
119
+ for line in normalized.splitlines():
120
+ stripped = line.strip()
121
+ if not stripped or len(stripped) > 60 or _HEADING_LINE.match(stripped):
122
+ continue
123
+ if not _CHROME_HINT.search(stripped):
124
+ continue
125
+ if stripped in short or len(short) < 20000:
126
+ short[stripped] += 1
127
+ leftovers = [
128
+ {"line": line, "count": count}
129
+ for line, count in short.most_common(sample_lines)
130
+ if count >= 3
131
+ ]
132
+ return {
133
+ "n": n,
134
+ "n_changed": n_changed,
135
+ "n_unstable": n_unstable,
136
+ "leftovers": leftovers,
137
+ }
138
+
139
+
140
+ def apply_pack(path: Path, out_path: Path) -> dict[str, Any]:
141
+ """Rewrite every body with the current script. No model is loaded."""
142
+ import pyarrow as pa
143
+ import pyarrow.parquet as pq
144
+
145
+ pf = pq.ParquetFile(path)
146
+ if "body" not in set(pf.schema_arrow.names):
147
+ raise ValueError(f"{path.name} has no body column")
148
+ out_path.parent.mkdir(parents=True, exist_ok=True)
149
+ tmp = out_path.with_suffix(out_path.suffix + ".partial")
150
+ writer = pq.ParquetWriter(tmp, pf.schema_arrow)
151
+ n = 0
152
+ n_changed = 0
153
+ try:
154
+ for batch in pf.iter_batches(batch_size=256):
155
+ bodies = batch.column("body").to_pylist()
156
+ rewritten: list[Any] = []
157
+ for body in bodies:
158
+ if body is None:
159
+ rewritten.append(None)
160
+ continue
161
+ original = body if isinstance(body, str) else str(body)
162
+ n += 1
163
+ normalized = normalize_legal_text(original)
164
+ if normalized != original:
165
+ n_changed += 1
166
+ rewritten.append(normalized)
167
+ index = batch.schema.get_field_index("body")
168
+ arrays = [batch.column(i) for i in range(batch.num_columns)]
169
+ arrays[index] = pa.array(rewritten, type=batch.schema.field("body").type)
170
+ writer.write_batch(pa.record_batch(arrays, schema=batch.schema))
171
+ except Exception:
172
+ writer.close()
173
+ tmp.unlink(missing_ok=True)
174
+ raise
175
+ writer.close()
176
+ tmp.replace(out_path)
177
+ return {"n": n, "n_changed": n_changed}
178
+
179
+
180
+ def _safe_pattern(pattern: str) -> bool:
181
+ if not isinstance(pattern, str) or not pattern.startswith("^") or not pattern.endswith("$"):
182
+ return False
183
+ if not 4 <= len(pattern) <= 180:
184
+ return False
185
+ if len(re.findall(r"\.\*|\.\+", pattern)) > 2:
186
+ return False
187
+ if re.search(r"\([^)]*[+*][^)]*\)[+*{]", pattern):
188
+ return False
189
+ try:
190
+ re.compile(pattern, re.IGNORECASE)
191
+ except re.error:
192
+ return False
193
+ return True
194
+
195
+
196
+ def _blocked_candidate(line: str) -> bool:
197
+ """Publication sentences, headings, and mid-sentence fragments stay in the row."""
198
+ if _PROVISION_LINE.search(line) or _HEADING_LINE.match(line):
199
+ return True
200
+ if len(line) <= 3:
201
+ return True
202
+ return line.endswith((",", ";", " or", " and"))
203
+
204
+
205
+ def accept_line_patterns(
206
+ proposals: Sequence[str],
207
+ leftovers: Sequence[str],
208
+ existing: Sequence[str] = (),
209
+ *,
210
+ must_hit: Sequence[str] | None = None,
211
+ ) -> list[str]:
212
+ """Keep a proposal only when it hits a leftover and misses every held-out sentence."""
213
+ accepted: list[str] = []
214
+ seen = set(existing)
215
+ pool = [line.strip() for line in leftovers if line and str(line).strip()]
216
+ required = pool if must_hit is None else [line.strip() for line in must_hit if line and str(line).strip()]
217
+ for pattern in proposals:
218
+ if pattern in seen or not _safe_pattern(pattern):
219
+ continue
220
+ compiled = re.compile(pattern, re.IGNORECASE)
221
+ if any(compiled.fullmatch(line.strip()) for line in KEEP_LINES):
222
+ continue
223
+ if compiled.fullmatch("2") or compiled.fullmatch("10"):
224
+ continue
225
+ hits = [line for line in pool if compiled.fullmatch(line)]
226
+ if not hits:
227
+ continue
228
+ if required and not any(compiled.fullmatch(line) for line in required):
229
+ continue
230
+ if any(_blocked_candidate(line) for line in hits):
231
+ continue
232
+ accepted.append(pattern)
233
+ seen.add(pattern)
234
+ return accepted
235
+
236
+
237
+ def line_still_present(line: str) -> bool:
238
+ """True when the current script still leaves this exact line in place."""
239
+ probe = (
240
+ line
241
+ + "\nArticle 1 The present Act applies throughout the territory and binds every person."
242
+ )
243
+ normalized = normalize_legal_text(probe)
244
+ return line in normalized.splitlines()
245
+
246
+
247
+ def router_candidates(
248
+ leftovers: Sequence[dict[str, Any]],
249
+ limit: int = 40,
250
+ *,
251
+ skip: set[str] | None = None,
252
+ presence: dict[str, bool] | None = None,
253
+ ) -> list[dict[str, Any]]:
254
+ """Banners the script still keeps, in leftover order, excluding provision lines."""
255
+ chosen: list[dict[str, Any]] = []
256
+ seen: set[str] = set()
257
+ held = skip or set()
258
+ known = presence if presence is not None else {}
259
+ for item in leftovers:
260
+ line = str(item.get("line") or "").strip()
261
+ if not line or line in seen or line in held:
262
+ continue
263
+ if line not in known:
264
+ known[line] = line_still_present(line)
265
+ if not known[line] or _blocked_candidate(line):
266
+ continue
267
+ seen.add(line)
268
+ chosen.append({"line": line, "count": int(item.get("count") or 0)})
269
+ if len(chosen) >= limit:
270
+ break
271
+ return chosen
272
+
273
+
274
+ def _cluster_key(line: str) -> str:
275
+ shape = re.sub(r"\d+", "0", line.casefold())
276
+ shape = re.sub(r"[^\w\s]+", " ", shape, flags=re.UNICODE)
277
+ shape = re.sub(r"\s+", " ", shape).strip()
278
+ return " ".join(shape.split()[:4])
279
+
280
+
281
+ def largest_cluster(candidates: Sequence[dict[str, Any]], limit: int) -> list[dict[str, Any]]:
282
+ """The repeated family with the highest total count, capped to one prompt."""
283
+ groups: dict[str, list[dict[str, Any]]] = {}
284
+ for item in candidates:
285
+ groups.setdefault(_cluster_key(str(item["line"])), []).append(item)
286
+ best = max(groups.values(), key=lambda group: sum(int(item["count"]) for item in group))
287
+ best.sort(key=lambda item: int(item["count"]), reverse=True)
288
+ return best[:limit]
289
+
290
+
291
+ def propose_line_patterns(
292
+ leftovers: Sequence[dict[str, Any]],
293
+ generate_text: GenerateText,
294
+ *,
295
+ char_budget: int = PROMPT_CHAR_BUDGET,
296
+ ) -> list[str]:
297
+ """One router call. The model proposes whole-line patterns, not statute text."""
298
+ if not leftovers:
299
+ return []
300
+ body: list[str] = []
301
+ used = len(_PROMPT_PREFIX)
302
+ for item in leftovers:
303
+ row = f"- {item['count']}× {item['line']}\n"
304
+ if used + len(row) > char_budget:
305
+ break
306
+ body.append(row)
307
+ used += len(row)
308
+ if not body:
309
+ room = max(0, char_budget - len(_PROMPT_PREFIX) - 16)
310
+ snippet = str(leftovers[0]["line"])[:room]
311
+ body.append(f"- {leftovers[0]['count']}× {snippet}\n")
312
+ raw = str(generate_text(_PROMPT_PREFIX + "".join(body)))
313
+ start, end = raw.find("{"), raw.rfind("}")
314
+ if start < 0 or end <= start:
315
+ return []
316
+ try:
317
+ payload = json.loads(raw[start : end + 1])
318
+ except json.JSONDecodeError:
319
+ return []
320
+ found = payload.get("line_patterns")
321
+ if not isinstance(found, list):
322
+ return []
323
+ return [item for item in found if isinstance(item, str)]
324
+
325
+
326
+ def load_learned_patterns() -> list[str]:
327
+ path = learned_patterns_path()
328
+ if not path.is_file():
329
+ return []
330
+ try:
331
+ payload = json.loads(path.read_text(encoding="utf-8"))
332
+ except (OSError, json.JSONDecodeError):
333
+ return []
334
+ return [item for item in payload.get("patterns") or [] if isinstance(item, str)]
335
+
336
+
337
+ def save_learned_patterns(patterns: Sequence[str]) -> None:
338
+ path = learned_patterns_path()
339
+ path.parent.mkdir(parents=True, exist_ok=True)
340
+ path.write_text(
341
+ json.dumps({"patterns": list(patterns)}, ensure_ascii=False, indent=2) + "\n",
342
+ encoding="utf-8",
343
+ )
344
+ # The structure cache keys on mtime; the write updates it.
345
+
346
+
347
+ def unresolved_path(report_dir: Path) -> Path:
348
+ return report_dir / "_unresolved.json"
349
+
350
+
351
+ def load_unresolved(report_dir: Path) -> set[str]:
352
+ path = unresolved_path(report_dir)
353
+ if not path.is_file():
354
+ return set()
355
+ try:
356
+ payload = json.loads(path.read_text(encoding="utf-8"))
357
+ except (OSError, json.JSONDecodeError):
358
+ return set()
359
+ return {item.strip() for item in payload.get("lines") or [] if isinstance(item, str) and item.strip()}
360
+
361
+
362
+ def save_unresolved(report_dir: Path, lines: set[str]) -> None:
363
+ path = unresolved_path(report_dir)
364
+ path.parent.mkdir(parents=True, exist_ok=True)
365
+ path.write_text(
366
+ json.dumps({"lines": sorted(lines)}, ensure_ascii=False, indent=2) + "\n",
367
+ encoding="utf-8",
368
+ )
369
+
370
+
371
+ def collect_leftovers(report_dir: Path) -> list[dict[str, Any]]:
372
+ """Merge per-country residual lines. Counts for the same line are summed."""
373
+ counts: Counter[str] = Counter()
374
+ if not report_dir.is_dir():
375
+ return []
376
+ for path in sorted(report_dir.glob("*.json")):
377
+ if path.name.startswith("_"):
378
+ continue
379
+ try:
380
+ payload = json.loads(path.read_text(encoding="utf-8"))
381
+ except (OSError, json.JSONDecodeError):
382
+ continue
383
+ for item in payload.get("leftovers") or []:
384
+ if isinstance(item, dict) and isinstance(item.get("line"), str):
385
+ line = item["line"].strip()
386
+ if line:
387
+ counts[line] += int(item.get("count") or 0)
388
+ return [{"line": line, "count": count} for line, count in counts.most_common()]
389
+
390
+
391
+ def improve_from_reports(
392
+ report_dir: Path,
393
+ generate_text: GenerateText,
394
+ *,
395
+ max_passes: int = 40,
396
+ batch_size: int = 12,
397
+ char_budget: int = PROMPT_CHAR_BUDGET,
398
+ on_pass: Callable[[dict[str, Any]], None] | None = None,
399
+ reset_unresolved: bool = False,
400
+ ) -> dict[str, Any]:
401
+ """Ask the router, one short batch at a time, for rules the script can apply.
402
+
403
+ A batch is one repeated family. Patterns that do not remove a line, or that
404
+ also match a publication sentence, are not stored. Families the model cannot
405
+ safely pattern are remembered so the next batch is a different family.
406
+ """
407
+ merged = collect_leftovers(report_dir)
408
+ pool_lines = [str(item["line"]) for item in merged]
409
+ presence: dict[str, bool] = {}
410
+ skip = set() if reset_unresolved else load_unresolved(report_dir)
411
+ existing = load_learned_patterns()
412
+ accepted_all: list[str] = []
413
+ removed_lines: list[str] = []
414
+ proposed = 0
415
+ passes = 0
416
+
417
+ def _emit(row: dict[str, Any]) -> None:
418
+ if on_pass is not None:
419
+ on_pass(row)
420
+
421
+ for pass_no in range(1, max(1, max_passes) + 1):
422
+ pending = router_candidates(merged, limit=100_000, skip=skip, presence=presence)
423
+ if not pending:
424
+ break
425
+ batch = largest_cluster(pending, batch_size)
426
+ cluster = _cluster_key(str(batch[0]["line"]))
427
+ _emit({
428
+ "event": "prompt",
429
+ "pass": pass_no,
430
+ "cluster": cluster,
431
+ "batch_id": hashlib.sha256(cluster.encode("utf-8")).hexdigest()[:8],
432
+ "candidates": len(batch),
433
+ "lines": [str(item["line"]) for item in batch],
434
+ })
435
+ try:
436
+ proposals = propose_line_patterns(batch, generate_text, char_budget=char_budget)
437
+ except Exception as exc:
438
+ passes += 1
439
+ _emit({"event": "pass", "pass": pass_no, "cluster": cluster, "error": str(exc)})
440
+ break
441
+ proposed += len(proposals)
442
+ accepted = accept_line_patterns(proposals, pool_lines, existing, must_hit=[str(item["line"]) for item in batch])
443
+ before = list(existing)
444
+ kept: list[str] = []
445
+ removed_now: list[str] = []
446
+ if accepted:
447
+ save_learned_patterns([*before, *accepted])
448
+ for pattern in accepted:
449
+ compiled = re.compile(pattern, re.IGNORECASE)
450
+ hits = [line for line in pool_lines if compiled.fullmatch(line)]
451
+ dropped = [line for line in hits if not line_still_present(line)]
452
+ if not dropped:
453
+ continue
454
+ kept.append(pattern)
455
+ removed_now.extend(dropped)
456
+ if kept != accepted:
457
+ save_learned_patterns([*before, *kept])
458
+ if not kept:
459
+ skip.update(str(item["line"]) for item in batch)
460
+ else:
461
+ for line in removed_now:
462
+ presence[line] = False
463
+ skip.discard(line)
464
+ if line not in removed_lines:
465
+ removed_lines.append(line)
466
+ existing = [*before, *kept]
467
+ accepted_all.extend(kept)
468
+ passes += 1
469
+ _emit({
470
+ "event": "pass",
471
+ "pass": pass_no,
472
+ "cluster": cluster,
473
+ "proposed": len(proposals),
474
+ "accepted": kept,
475
+ "removed": len(removed_now),
476
+ })
477
+
478
+ save_unresolved(report_dir, skip)
479
+ withheld = 0
480
+ for item in merged:
481
+ line = str(item["line"])
482
+ if line not in presence:
483
+ presence[line] = line_still_present(line)
484
+ if presence[line] and _blocked_candidate(line):
485
+ withheld += 1
486
+ remaining = router_candidates(merged, limit=100_000, skip=skip, presence=presence)
487
+ return {
488
+ "proposed": proposed,
489
+ "accepted": accepted_all,
490
+ "leftover_lines": len(merged),
491
+ "removed": len(removed_lines),
492
+ "removed_lines": removed_lines[:40],
493
+ "unresolved": len(skip),
494
+ "withheld": withheld,
495
+ "remaining": len(remaining),
496
+ "passes": passes,
497
+ }
498
+
499
+
500
+ def worker_count(requested: int | None) -> int:
501
+ if requested is not None:
502
+ return max(1, int(requested))
503
+ return max(1, os.cpu_count() or 1)
504
+
505
+
506
+ def _scan_job(job: tuple[str, str, str]) -> dict[str, Any]:
507
+ slug, path, report_dir = job
508
+ stats = scan_pack(Path(path))
509
+ write_scan(Path(report_dir), slug, stats)
510
+ return {"slug": slug, "n": stats["n"], "n_changed": stats["n_changed"], "n_unstable": stats["n_unstable"], "leftovers": len(stats["leftovers"])}
511
+
512
+
513
+ def _apply_job(job: tuple[str, str, str]) -> dict[str, Any]:
514
+ slug, path, out_dir = job
515
+ out_path = Path(out_dir) / Path(path).name
516
+ stats = apply_pack(Path(path), out_path)
517
+ return {"slug": slug, "out": str(out_path), **stats}
518
+
519
+
520
+ def run_parallel(
521
+ jobs: Sequence[tuple[str, str, str]],
522
+ worker,
523
+ workers: int | None,
524
+ *,
525
+ progress_path: Path | None = None,
526
+ on_done: Callable[[dict[str, Any]], None] | None = None,
527
+ ) -> list[dict[str, Any]]:
528
+ """One process per batch of countries. Each country writes its own file.
529
+
530
+ Progress is recorded in the parent as each country finishes, so a later
531
+ run can skip those slugs.
532
+ """
533
+ count = worker_count(workers)
534
+
535
+ def _finish(row: dict[str, Any]) -> dict[str, Any]:
536
+ if progress_path is not None:
537
+ append_progress(progress_path, row)
538
+ if on_done is not None:
539
+ on_done(row)
540
+ return row
541
+
542
+ if count == 1 or len(jobs) <= 1:
543
+ return [_finish(worker(job)) for job in jobs]
544
+ rows: list[dict[str, Any]] = []
545
+ with ProcessPoolExecutor(max_workers=min(count, len(jobs))) as pool:
546
+ futures = {pool.submit(worker, job): job[0] for job in jobs}
547
+ for future in as_completed(futures):
548
+ slug = futures[future]
549
+ try:
550
+ row = future.result()
551
+ except Exception as exc:
552
+ row = {"slug": slug, "error": str(exc)}
553
+ rows.append(_finish(row))
554
+ rows.sort(key=lambda row: str(row.get("slug") or ""))
555
+ return rows
556
+
557
+
558
+ def write_scan(report_dir: Path, slug: str, stats: dict[str, Any]) -> Path:
559
+ report_dir.mkdir(parents=True, exist_ok=True)
560
+ path = report_dir / f"{slug}.json"
561
+ tmp = path.with_suffix(".json.tmp")
562
+ tmp.write_text(json.dumps({"slug": slug, **stats}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
563
+ tmp.replace(path)
564
+ return path
565
+
566
+
567
+ def scan_done(report_dir: Path, slug: str) -> bool:
568
+ path = report_dir / f"{slug}.json"
569
+ if not path.is_file():
570
+ return False
571
+ try:
572
+ payload = json.loads(path.read_text(encoding="utf-8"))
573
+ except (OSError, json.JSONDecodeError):
574
+ return False
575
+ return isinstance(payload.get("n"), int)
576
+
577
+
578
+ def apply_done(out_dir: Path, slug: str) -> bool:
579
+ path = out_dir / f"{slug}_corpus.parquet"
580
+ if not path.is_file() or path.stat().st_size < 12:
581
+ return False
582
+ with path.open("rb") as handle:
583
+ if handle.read(4) != b"PAR1":
584
+ return False
585
+ handle.seek(-4, 2)
586
+ return handle.read(4) == b"PAR1"
587
+
588
+
589
+ def append_progress(path: Path, row: dict[str, Any]) -> None:
590
+ path.parent.mkdir(parents=True, exist_ok=True)
591
+ with path.open("a", encoding="utf-8") as handle:
592
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
593
+ handle.flush()
594
+
595
+
596
+ def load_generate_text() -> GenerateText:
597
+ """Import the router once per process. Scan and apply never call this."""
598
+ from ipfs_datasets_py.llm_router import generate_text
599
+
600
+ return generate_text
601
+
602
+
603
+ def default_paths(root: Path) -> dict[str, Path]:
604
+ return {
605
+ "cache": root / "cache",
606
+ "reports": root / "reports" / "residuals",
607
+ "out": root / "llm-normalized",
608
+ }
country_laws_ir/package.py CHANGED
@@ -253,7 +253,9 @@ def package_release(
253
  return file_descriptor(path, f"indexes/{name}")
254
 
255
  hub_id = target_repo(country["slug"])
256
- edge_types = graph["stats"].get("edge_types") or [
 
 
257
  "HAS_JURISDICTION",
258
  "HAS_LANGUAGE",
259
  "BELONGS_TO_LAW",
@@ -270,10 +272,20 @@ def package_release(
270
  "dataset_revision": source_meta["source_revision"],
271
  "country": country,
272
  "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
273
- "bm25": {k: bm25["stats"][k] for k in (
274
- "k1", "b", "title_weight", "body_weight", "average_document_length",
275
- "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
276
- )},
 
 
 
 
 
 
 
 
 
 
277
  "counts": counts,
278
  "parquet": {
279
  "compression": "zstd",
@@ -361,7 +373,17 @@ def package_release(
361
  if extra_manifest:
362
  manifest.update(extra_manifest)
363
  (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
364
- _write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
 
 
 
 
 
 
 
 
 
 
365
  _write_gitattributes(out)
366
  _write_dataset_configs(out)
367
  return manifest
@@ -395,6 +417,55 @@ def _write_gitattributes(out: Path) -> None:
395
  )
396
 
397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
  def _write_readme(
399
  out: Path,
400
  country: dict[str, Any],
@@ -404,67 +475,49 @@ def _write_readme(
404
  graph_stats: dict[str, Any],
405
  vector_stats: dict[str, Any],
406
  hub_id: str,
 
407
  ) -> None:
408
  slug = country["slug"]
409
- name = country["name"]
410
- src = source_meta["source_dataset"]
411
- rev = source_meta["source_revision"]
412
- vec_status = vector_stats.get("status", "embedded")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  text = f"""---
414
- license: other
415
- task_categories:
416
- - text-retrieval
417
- tags:
418
- - legal
419
- - law
420
- - graphrag
421
- - bm25
422
- - research
423
- - not-legal-advice
424
- - {slug}
425
- pretty_name: {name} laws IR (CID-keyed GraphRAG)
426
- configs:
427
- - config_name: corpus
428
- data_files:
429
- - split: train
430
- path: data/corpus/*.parquet
431
- - config_name: bm25_documents
432
- data_files:
433
- - split: train
434
- path: data/bm25/documents/*.parquet
435
- - config_name: bm25_postings
436
- data_files:
437
- - split: train
438
- path: data/bm25/postings/*.parquet
439
- - config_name: bm25_keyword_index
440
- data_files:
441
- - split: train
442
- path: indexes/bm25_keyword_shards.parquet
443
- - config_name: vectors
444
- data_files:
445
- - split: train
446
- path: data/vectors/*.parquet
447
- - config_name: vector_meta_index
448
- data_files:
449
- - split: train
450
- path: indexes/vector_chunks.parquet
451
- - config_name: graph_nodes
452
- data_files:
453
- - split: train
454
- path: data/graph/nodes/*.parquet
455
- - config_name: graph_edges
456
- data_files:
457
- - split: train
458
- path: data/graph/edges/*.parquet
459
- - config_name: graph_outgoing_adjacency
460
- data_files:
461
- - split: train
462
- path: data/graph/adjacency/outgoing/*.parquet
463
- - config_name: graph_incoming_adjacency
464
- data_files:
465
- - split: train
466
- path: data/graph/adjacency/incoming/*.parquet
467
- ---
468
 
469
  # {name} legislation IR (CID-keyed sparse GraphRAG)
470
 
@@ -484,14 +537,14 @@ Target Hub id (packaging metadata only): `{hub_id}`.
484
 
485
  | Field | Value |
486
  | --- | --- |
487
- | Laws (corpus units) | {counts['n_laws']} |
488
- | Articles (corpus units) | {counts['n_articles']} |
489
- | Canonical docs | {counts['corpus_rows']} |
490
- | BM25 terms | {counts['bm25_terms']} |
491
- | BM25 postings | {counts['bm25_postings']} |
492
- | Graph nodes | {counts['graph_nodes']} |
493
- | Graph edges | {counts['graph_edges']} |
494
- | Vectors | {counts['vector_rows']} × {vector_stats['dimension']}-d `{vector_stats['model_name']}` ({vec_status}) |
495
 
496
  ## Canonical fields
497
 
@@ -825,7 +878,7 @@ def package_release_sequential(
825
  "dataset_revision": source_meta["source_revision"],
826
  "country": country,
827
  "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
828
- "bm25": {k: bm25_stats[k] for k in (
829
  "k1", "b", "title_weight", "body_weight", "average_document_length",
830
  "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
831
  ) if k in bm25_stats},
@@ -900,7 +953,17 @@ def package_release_sequential(
900
  (out / "manifest.json").write_text(
901
  json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
902
  )
903
- _write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
 
 
 
 
 
 
 
 
 
 
904
  _write_gitattributes(out)
905
  _write_dataset_configs(out)
906
  checkpoint("package_seq_done")
 
253
  return file_descriptor(path, f"indexes/{name}")
254
 
255
  hub_id = target_repo(country["slug"])
256
+ bm25_stats = bm25.get("stats") if isinstance(bm25.get("stats"), dict) else {}
257
+ graph_stats = graph.get("stats") if isinstance(graph.get("stats"), dict) else {}
258
+ edge_types = graph_stats.get("edge_types") or [
259
  "HAS_JURISDICTION",
260
  "HAS_LANGUAGE",
261
  "BELONGS_TO_LAW",
 
272
  "dataset_revision": source_meta["source_revision"],
273
  "country": country,
274
  "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
275
+ "bm25": {
276
+ k: bm25_stats.get(k)
277
+ for k in (
278
+ "k1",
279
+ "b",
280
+ "title_weight",
281
+ "body_weight",
282
+ "average_document_length",
283
+ "tokenizer",
284
+ "max_query_terms",
285
+ "posting_rows_per_record",
286
+ "terms_per_shard",
287
+ )
288
+ },
289
  "counts": counts,
290
  "parquet": {
291
  "compression": "zstd",
 
373
  if extra_manifest:
374
  manifest.update(extra_manifest)
375
  (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
376
+ _write_readme(
377
+ out,
378
+ country,
379
+ source_meta,
380
+ counts,
381
+ bm25_stats,
382
+ graph_stats,
383
+ vectors.get("stats") if isinstance(vectors.get("stats"), dict) else {},
384
+ hub_id,
385
+ normalization_report=normalization_report,
386
+ )
387
  _write_gitattributes(out)
388
  _write_dataset_configs(out)
389
  return manifest
 
417
  )
418
 
419
 
420
+ def _size_category(n: int) -> str:
421
+ if n < 1000:
422
+ return "n<1K"
423
+ if n < 10_000:
424
+ return "1K<n<10K"
425
+ if n < 100_000:
426
+ return "10K<n<100K"
427
+ if n < 1_000_000:
428
+ return "100K<n<1M"
429
+ if n < 10_000_000:
430
+ return "1M<n<10M"
431
+ return "n>10M"
432
+
433
+
434
+ def _card_languages(normalization_report: dict[str, Any] | None) -> list[str]:
435
+ if not normalization_report:
436
+ return []
437
+ seen: list[str] = []
438
+ majority = str(normalization_report.get("document_language_majority") or "").strip()
439
+ breakdown = normalization_report.get("language_breakdown") or {}
440
+ ordered = []
441
+ if majority:
442
+ ordered.append(majority)
443
+ ordered.extend(
444
+ sorted(
445
+ (str(k) for k in breakdown if k),
446
+ key=lambda k: -int(breakdown.get(k) or 0),
447
+ )
448
+ )
449
+ for raw in ordered:
450
+ lang = str(raw).strip().lower().replace("_", "-").split("-")[0]
451
+ if lang and lang not in seen and lang not in {"und", "none", "null"}:
452
+ seen.append(lang)
453
+ if len(seen) >= 8:
454
+ break
455
+ return seen
456
+
457
+
458
+ def _adj_glob(out: Path, direction: str) -> str:
459
+ aliases = {
460
+ "out": ("out", "outgoing"),
461
+ "in": ("in", "incoming"),
462
+ }
463
+ for name in aliases.get(direction, (direction,)):
464
+ if (out / "data" / "graph" / "adjacency" / name).is_dir():
465
+ return f"data/graph/adjacency/{name}/*.parquet"
466
+ return f"data/graph/adjacency/{direction}/*.parquet"
467
+
468
+
469
  def _write_readme(
470
  out: Path,
471
  country: dict[str, Any],
 
475
  graph_stats: dict[str, Any],
476
  vector_stats: dict[str, Any],
477
  hub_id: str,
478
+ normalization_report: dict[str, Any] | None = None,
479
  ) -> None:
480
  slug = country["slug"]
481
+ name = country.get("name") or slug
482
+ src = source_meta.get("source_dataset") or ""
483
+ rev = source_meta.get("source_revision") or ""
484
+ vec_status = (vector_stats or {}).get("status", "embedded")
485
+ n_docs = int((counts or {}).get("corpus_rows") or 0)
486
+ languages = _card_languages(normalization_report)
487
+ import yaml
488
+
489
+ card = {
490
+ "license": "other",
491
+ "task_categories": ["text-retrieval"],
492
+ "tags": [
493
+ "legal",
494
+ "law",
495
+ "graphrag",
496
+ "bm25",
497
+ "research",
498
+ "not-legal-advice",
499
+ str(slug),
500
+ ],
501
+ "pretty_name": f"{name} laws IR (CID-keyed GraphRAG)",
502
+ "size_categories": [_size_category(n_docs)],
503
+ "configs": [
504
+ {"config_name": "corpus", "data_files": [{"split": "train", "path": "data/corpus/*.parquet"}]},
505
+ {"config_name": "bm25_documents", "data_files": [{"split": "train", "path": "data/bm25/documents/*.parquet"}]},
506
+ {"config_name": "bm25_postings", "data_files": [{"split": "train", "path": "data/bm25/postings/*.parquet"}]},
507
+ {"config_name": "bm25_keyword_index", "data_files": [{"split": "train", "path": "indexes/bm25_keyword_shards.parquet"}]},
508
+ {"config_name": "vectors", "data_files": [{"split": "train", "path": "data/vectors/*.parquet"}]},
509
+ {"config_name": "vector_meta_index", "data_files": [{"split": "train", "path": "indexes/vector_chunks.parquet"}]},
510
+ {"config_name": "graph_nodes", "data_files": [{"split": "train", "path": "data/graph/nodes/*.parquet"}]},
511
+ {"config_name": "graph_edges", "data_files": [{"split": "train", "path": "data/graph/edges/*.parquet"}]},
512
+ {"config_name": "graph_outgoing_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "out")}]},
513
+ {"config_name": "graph_incoming_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "in")}]},
514
+ ],
515
+ }
516
+ if languages:
517
+ card["language"] = languages
518
+ front = yaml.safe_dump(card, sort_keys=False, allow_unicode=True)
519
  text = f"""---
520
+ {front}---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
 
522
  # {name} legislation IR (CID-keyed sparse GraphRAG)
523
 
 
537
 
538
  | Field | Value |
539
  | --- | --- |
540
+ | Laws (corpus units) | {(counts or {}).get('n_laws', 0)} |
541
+ | Articles (corpus units) | {(counts or {}).get('n_articles', 0)} |
542
+ | Canonical docs | {(counts or {}).get('corpus_rows', 0)} |
543
+ | BM25 terms | {(counts or {}).get('bm25_terms', 0)} |
544
+ | BM25 postings | {(counts or {}).get('bm25_postings', 0)} |
545
+ | Graph nodes | {(counts or {}).get('graph_nodes', 0)} |
546
+ | Graph edges | {(counts or {}).get('graph_edges', 0)} |
547
+ | Vectors | {(counts or {}).get('vector_rows', 0)} × {(vector_stats or {}).get('dimension', 384)}-d `{(vector_stats or {}).get('model_name', 'thenlper/gte-small')}` ({vec_status}) |
548
 
549
  ## Canonical fields
550
 
 
878
  "dataset_revision": source_meta["source_revision"],
879
  "country": country,
880
  "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
881
+ "bm25": {k: (bm25_stats or {}).get(k) for k in (
882
  "k1", "b", "title_weight", "body_weight", "average_document_length",
883
  "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
884
  ) if k in bm25_stats},
 
953
  (out / "manifest.json").write_text(
954
  json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
955
  )
956
+ _write_readme(
957
+ out,
958
+ country,
959
+ source_meta,
960
+ counts,
961
+ bm25_stats,
962
+ gstats,
963
+ vstats,
964
+ hub_id,
965
+ normalization_report=normalization_report,
966
+ )
967
  _write_gitattributes(out)
968
  _write_dataset_configs(out)
969
  checkpoint("package_seq_done")
country_laws_ir/profiles.py CHANGED
@@ -27,13 +27,23 @@ _add("en", "title", "title")
27
  _add("en", "chapter", "chapter")
28
  _add("en", "part", "part")
29
  _add("en", "article", "article")
30
- _add("en", "section", "section", "sec.")
 
 
 
 
 
 
 
 
 
 
31
 
32
  _add("fr", "title", "titre")
33
  _add("fr", "chapter", "chapitre")
34
  _add("fr", "part", "partie")
35
  _add("fr", "article", "article")
36
- _add("fr", "section", "section")
37
 
38
  _add("de", "title", "titel")
39
  _add("de", "chapter", "kapitel")
@@ -52,6 +62,7 @@ _add("es", "chapter", "capítulo", "capitulo")
52
  _add("es", "part", "parte")
53
  _add("es", "article", "artículo", "articulo")
54
  _add("es", "section", "sección", "seccion")
 
55
 
56
  _add("pt", "title", "título", "titulo")
57
  _add("pt", "chapter", "capítulo", "capitulo")
@@ -66,26 +77,222 @@ _add("it", "article", "articolo")
66
  _add("it", "section", "sezione")
67
 
68
  _add("el", "article", "άρθρο", "αρθρο")
69
- _add("hu", "article", "szakasz")
 
70
  _add("cs", "article", "článek")
 
 
71
  _add("sk", "article", "článok")
72
- _add("sl", "article", "član")
73
  _add("nb", "article", "artikkel")
74
- _add("sv", "article", "artikel")
 
 
 
 
 
 
 
75
  _add("pl", "article", "artykuł", "artykul")
76
  _add("ro", "article", "articolul", "articol")
77
- _add("zh", "article", "条")
78
- _add("ar", "article", "مادة", "المادة")
 
 
 
 
 
 
79
  _add("ja", "article", "条")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  # Shared abbreviation; language left unknown.
82
- _add("und", "article", "art.")
83
  _add("und", "section", "§")
84
 
85
  # Scripts we do not Latin-split:
86
- NO_LATIN_SPLIT_LANGS = frozenset({"ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn", "am"})
 
 
 
 
 
87
 
88
- _TOKEN_RE = re.compile(r"[^\W\d_]{2,}|art\.|sec\.|§", re.UNICODE)
89
 
90
 
91
  def classify_heading_token(token: str) -> list[tuple[str, str]]:
 
27
  _add("en", "chapter", "chapter")
28
  _add("en", "part", "part")
29
  _add("en", "article", "article")
30
+ _add("en", "section", "section", "sec.", "rule", "regulation", "schedule", "annex", "appendix")
31
+ _add("fr", "section", "annexe")
32
+ _add("es", "section", "anexo")
33
+ _add("de", "section", "anlage")
34
+ _add("nl", "section", "bijlage")
35
+ _add("it", "section", "allegato")
36
+ _add("pl", "section", "załącznik")
37
+ _add("sv", "section", "bilaga")
38
+ _add("fi", "section", "liite")
39
+ _add("cs", "section", "příloha")
40
+ _add("pt", "section", "anexo")
41
 
42
  _add("fr", "title", "titre")
43
  _add("fr", "chapter", "chapitre")
44
  _add("fr", "part", "partie")
45
  _add("fr", "article", "article")
46
+ _add("fr", "section", "section", "paragraphe")
47
 
48
  _add("de", "title", "titel")
49
  _add("de", "chapter", "kapitel")
 
62
  _add("es", "part", "parte")
63
  _add("es", "article", "artículo", "articulo")
64
  _add("es", "section", "sección", "seccion")
65
+ _add("es", "article", "disposición", "disposicion")
66
 
67
  _add("pt", "title", "título", "titulo")
68
  _add("pt", "chapter", "capítulo", "capitulo")
 
77
  _add("it", "section", "sezione")
78
 
79
  _add("el", "article", "άρθρο", "αρθρο")
80
+ _add("el", "chapter", "κεφάλαιο")
81
+ _add("hu", "article", "szakasz", "cikk")
82
  _add("cs", "article", "článek")
83
+ _add("cs", "chapter", "kapitola")
84
+ _add("cs", "section", "odstavec", "odst.")
85
  _add("sk", "article", "článok")
86
+ _add("sl", "article", "člen")
87
  _add("nb", "article", "artikkel")
88
+ _add("sv", "article", "paragraf")
89
+ _add("fi", "article", "pykälä")
90
+ _add("fi", "chapter", "luku")
91
+ _add("is", "article", "grein")
92
+ _add("lv", "article", "pants")
93
+ _add("lv", "chapter", "nodaļa")
94
+ _add("et", "article", "paragrahv")
95
+ _add("et", "chapter", "peatükk")
96
  _add("pl", "article", "artykuł", "artykul")
97
  _add("ro", "article", "articolul", "articol")
98
+ _add("mt", "article", "artikolu")
99
+ _add("zh", "article", "条", "條")
100
+ _add("ar", "article", "مادة", "المادة", "الماده", "املادة", "املاده")
101
+ _add("ar", "chapter", "الباب")
102
+ _add("ar", "part", "الكتاب")
103
+ _add("ar", "section", "الفصل", "ملحق", "الفرع")
104
+ _add("fa", "article", "ماده")
105
+ _add("fa", "section", "تبصره", "بند")
106
  _add("ja", "article", "条")
107
+ _add("ko", "article", "조")
108
+ _add("he", "article", "סעיף")
109
+ _add("he", "chapter", "פרק")
110
+ _add("he", "part", "חלק")
111
+ _add("he", "section", "סימן", "תוספת", "תקנה")
112
+ _add("th", "article", "มาตรา")
113
+ _add("th", "chapter", "หมวด")
114
+ _add("th", "section", "ข้อ", "วรรค")
115
+ _add("hi", "article", "धारा")
116
+ _add("bn", "article", "ধারা")
117
+ _add("ru", "article", "статья")
118
+ _add("ru", "chapter", "глава")
119
+ _add("ru", "title", "раздел")
120
+ _add("uk", "article", "стаття")
121
+ _add("bg", "article", "член", "чл")
122
+ _add("mk", "article", "член")
123
+ _add("sr", "article", "члан")
124
+ _add("hr", "article", "članak")
125
+ _add("hr", "chapter", "poglavlje")
126
+ _add("bs", "article", "članak")
127
+ _add("sq", "article", "neni")
128
+ _add("tr", "article", "madde")
129
+ _add("az", "article", "maddə")
130
+ _add("uz", "article", "модда")
131
+ _add("mn", "article", "зүйл")
132
+ _add("lo", "article", "ມາດຕາ")
133
+ _add("id", "article", "pasal")
134
+ _add("id", "chapter", "bab")
135
+ _add("ms", "article", "seksyen")
136
+ _add("ms", "part", "bahagian")
137
+ _add("lt", "article", "straipsnis")
138
+ _add("ta", "article", "பிரிவு")
139
+ _add("el", "part", "μέρος")
140
+ _add("el", "section", "παράγραφος")
141
+ _add("uk", "title", "розділ")
142
+ _add("zh", "chapter", "章")
143
+ _add("ja", "chapter", "章")
144
+ _add("ko", "chapter", "장")
145
+ _add("vi", "article", "điều")
146
+ _add("vi", "chapter", "chương")
147
+ _add("ka", "article", "მუხლი")
148
+ _add("hy", "article", "հոդված")
149
+ _add("am", "article", "አንቀጽ")
150
+ _add("km", "article", "មាត្រា")
151
+ _add("my", "article", "ပုဒ်မ")
152
+ _add("ne", "article", "दफा")
153
+ _add("si", "article", "වගන්තිය")
154
+ _add("kk", "article", "бап")
155
+ _add("uz", "article", "modda")
156
+ _add("be", "article", "артыкул")
157
+ _add("ky", "article", "берене")
158
+ _add("ur", "article", "دفعہ")
159
+ _add("so", "article", "qodob", "qodobka")
160
+ _add("ga", "article", "airteagal")
161
+ _add("cy", "article", "erthygl")
162
+ _add("fil", "article", "artikulo")
163
+ _add("fil", "section", "seksyon")
164
+ _add("fil", "chapter", "kabanata")
165
+ _add("id", "part", "bagian")
166
+ _add("vi", "part", "mục")
167
+ _add("sw", "part", "sehemu")
168
+ _add("ht", "article", "atik")
169
+ _add("eu", "article", "artikulua")
170
+ _add("da", "section", "stk")
171
+ _add("nb", "section", "ledd")
172
+ _add("de", "section", "absatz")
173
+ _add("es", "section", "apartado")
174
+ _add("it", "section", "comma")
175
+ _add("tr", "section", "fıkra")
176
+ _add("hr", "section", "stavak")
177
+ _add("bg", "section", "ал")
178
+ _add("te", "article", "ప్రకరణము", "ప్రకరణ")
179
+ _add("kn", "article", "ಪ್ರಕರಣ")
180
+ _add("gu", "article", "કલમ")
181
+ _add("pa", "article", "ਧਾਰਾ")
182
+ _add("ml", "article", "വകുപ്പ്")
183
+ _add("th", "title", "ลักษณะ")
184
+ _add("zh", "part", "编")
185
+ _add("ja", "part", "編")
186
+ _add("ko", "part", "편")
187
+ _add("tg", "article", "модда")
188
+ _add("sw", "article", "kifungu")
189
+ _add("ca", "article", "article")
190
+ _add("ca", "chapter", "capítol", "capitol")
191
+ _add("ca", "title", "títol", "titol")
192
+ _add("ca", "section", "secció", "seccio")
193
+ _add("pl", "chapter", "rozdział")
194
+ _add("pl", "title", "dział")
195
+ _add("ro", "chapter", "capitolul")
196
+ _add("ro", "title", "titlul")
197
+ _add("it", "chapter", "capo")
198
+ _add("cs", "chapter", "hlava")
199
+ _add("sk", "chapter", "hlava")
200
+ _add("es", "part", "libro")
201
+ _add("sv", "chapter", "kap")
202
+ _add("km", "chapter", "ជំពូក")
203
+ _add("lo", "part", "ພາກ")
204
+ _add("my", "chapter", "အခန်း")
205
+ _add("ka", "chapter", "თავი")
206
+ _add("hy", "chapter", "գլուխ")
207
+ _add("am", "chapter", "ምዕራፍ")
208
+ _add("sq", "chapter", "kreu")
209
+ _add("hu", "chapter", "fejezet")
210
+ _add("tr", "chapter", "bölüm")
211
+ _add("az", "chapter", "fəsil")
212
+ _add("lt", "chapter", "skyrius")
213
+ _add("is", "chapter", "kafli")
214
+ _add("ga", "chapter", "caibidil")
215
+ _add("cy", "chapter", "pennod")
216
+ _add("mt", "chapter", "kapitolu")
217
+ _add("ht", "chapter", "chapit")
218
+ _add("sw", "chapter", "sura")
219
+ _add("nb", "chapter", "kapittel")
220
+ _add("ha", "chapter", "sashe")
221
+ _add("mg", "chapter", "andiany")
222
+ _add("mi", "part", "wāhanga", "wahanga")
223
+ _add("sm", "part", "vaega")
224
+ _add("to", "article", "kupu")
225
+ _add("fj", "chapter", "wase")
226
+ _add("tpi", "part", "hap")
227
+ _add("fo", "chapter", "kapittul")
228
+ _add("bi", "article", "atikol")
229
+ _add("rw", "article", "ingingo")
230
+ _add("zu", "chapter", "isigaba")
231
+ _add("xh", "chapter", "icandelo")
232
+ _add("st", "part", "karolo")
233
+ _add("tn", "chapter", "kgaolo")
234
+ _add("sn", "part", "chikamu")
235
+ _add("ny", "article", "ndime")
236
+ _add("ku", "part", "beş")
237
+ _add("ky", "chapter", "бөлүм")
238
+ _add("tg", "chapter", "боби")
239
+ _add("yo", "article", "abala")
240
+ _add("yo", "chapter", "ori")
241
+ _add("ig", "article", "nkeji")
242
+ _add("lg", "part", "ekitundu")
243
+ _add("om", "chapter", "kutaa")
244
+ _add("ln", "part", "eténi", "eteni")
245
+ _add("ti", "article", "ዓንቀጽ")
246
+ _add("bm", "article", "sariya")
247
+ _add("wo", "article", "tere")
248
+ _add("ak", "article", "ahyɛde", "ahyede")
249
+ _add("ee", "part", "akpa")
250
+ _add("ff", "part", "faanda")
251
+ _add("br", "article", "pennad")
252
+ _add("kri", "section", "sekshon")
253
+ _add("bo", "article", "དོན་ཚན")
254
+ _add("ug", "article", "ماددا")
255
+ _add("kw", "article", "erthygel")
256
+ _add("tw", "article", "hyɛdeɛ", "hyedee")
257
+ _add("tet", "article", "artigu")
258
+ _add("haw", "article", "paukū", "pauku")
259
+ _add("ty", "article", "irava")
260
+ _add("ch", "part", "påtte", "patte")
261
+ _add("es", "section", "numeral")
262
+ _add("it", "section", "capoverso")
263
+ _add("de", "section", "nummer")
264
+ _add("so", "part", "qaybta")
265
+ _add("vi", "part", "phần")
266
+ _add("sk", "chapter", "oddiel")
267
+ _add("el", "title", "τίτλος")
268
+ _add("bg", "title", "дял")
269
+ _add("uz", "chapter", "bob")
270
+ _add("kk", "chapter", "тарау")
271
+ _add("hi", "chapter", "अध्याय")
272
+ _add("bn", "chapter", "অধ্যায়")
273
+ _add("ur", "chapter", "باب")
274
+ _add("fa", "chapter", "فصل")
275
+ _add("ne", "chapter", "परिच्छेद")
276
+ _add("zh", "section", "节")
277
+ _add("ja", "section", "節")
278
+ _add("ko", "section", "절")
279
+ _add("th", "section", "ตอน")
280
+ _add("sr", "part", "одељак")
281
+ _add("be", "title", "раздзел")
282
 
283
  # Shared abbreviation; language left unknown.
284
+ _add("und", "article", "art.", "član")
285
  _add("und", "section", "§")
286
 
287
  # Scripts we do not Latin-split:
288
+ NO_LATIN_SPLIT_LANGS = frozenset(
289
+ {
290
+ "ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn",
291
+ "am", "ru", "uk", "be", "ka", "hy", "km", "lo", "my", "si",
292
+ }
293
+ )
294
 
295
+ _TOKEN_RE = re.compile(r"[^\W\d_]+|art\.|sec\.|чл\.|§", re.UNICODE)
296
 
297
 
298
  def classify_heading_token(token: str) -> list[tuple[str, str]]:
country_laws_ir/query.py CHANGED
@@ -158,6 +158,11 @@ class Release:
158
  hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
159
  return hits[:limit]
160
 
 
 
 
 
 
161
 
162
  def _print(rows: list[dict]) -> None:
163
  print(json.dumps(rows, indent=2, ensure_ascii=False))
@@ -189,6 +194,16 @@ def main(argv: list[str] | None = None) -> int:
189
  )
190
  p_n.add_argument("--limit", type=int, default=25)
191
 
 
 
 
 
 
 
 
 
 
 
192
  args = ap.parse_args(argv)
193
  rel = Release(Path(args.local_dir))
194
  if args.cmd == "bm25":
@@ -197,6 +212,8 @@ def main(argv: list[str] | None = None) -> int:
197
  _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
198
  elif args.cmd == "graph" and args.graph_cmd == "neighbors":
199
  _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
 
 
200
  return 0
201
 
202
 
 
158
  hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
159
  return hits[:limit]
160
 
161
+ def cite(self, citation: str, cite_format: str = "any", limit: int = 25) -> list[dict]:
162
+ from .duckdb_store import cite_search
163
+
164
+ return cite_search(self.root, citation, cite_format=cite_format, limit=limit)
165
+
166
 
167
  def _print(rows: list[dict]) -> None:
168
  print(json.dumps(rows, indent=2, ensure_ascii=False))
 
194
  )
195
  p_n.add_argument("--limit", type=int, default=25)
196
 
197
+ p_cite = sub.add_parser("cite")
198
+ p_cite.add_argument("citation")
199
+ p_cite.add_argument(
200
+ "--format",
201
+ dest="cite_format",
202
+ default="any",
203
+ choices=["any", "bluebook", "official"],
204
+ )
205
+ p_cite.add_argument("--limit", type=int, default=25)
206
+
207
  args = ap.parse_args(argv)
208
  rel = Release(Path(args.local_dir))
209
  if args.cmd == "bm25":
 
212
  _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
213
  elif args.cmd == "graph" and args.graph_cmd == "neighbors":
214
  _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
215
+ elif args.cmd == "cite":
216
+ _print(rel.cite(args.citation, cite_format=args.cite_format, limit=args.limit))
217
  return 0
218
 
219
 
country_laws_ir/reconstruct.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reconstruct empty parent law bodies from article children.
2
+
3
+ Never invents legal text. Glue uses the same normalized strings as child
4
+ corpus fields. Eligible empty parents always get a law row (full glue,
5
+ streamed prefix, or title/number stub) — they are not dropped.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ import os
12
+ import re
13
+ import unicodedata
14
+ from typing import Any, Iterable
15
+
16
+ from .structure import normalize_legal_text
17
+
18
+ RECONSTRUCT_MAX_PARENT_CHARS = 2_000_000
19
+ RECONSTRUCT_STUB_MAX_CHARS = 8_192
20
+ RECONSTRUCT_PROCESS_BUDGET_BYTES = 512 * 1024 * 1024
21
+ RSS_ABORT_SKIP_FULL_CONCAT = frozenset({"france", "eu", "denmark"})
22
+ PARENT_TRUNCATED_MAX_CHARS = 40
23
+
24
+ _DIGIT_FOLD = str.maketrans(
25
+ {
26
+ "٠": "0",
27
+ "١": "1",
28
+ "٢": "2",
29
+ "٣": "3",
30
+ "٤": "4",
31
+ "٥": "5",
32
+ "٦": "6",
33
+ "٧": "7",
34
+ "٨": "8",
35
+ "٩": "9",
36
+ "۰": "0",
37
+ "۱": "1",
38
+ "۲": "2",
39
+ "۳": "3",
40
+ "۴": "4",
41
+ "۵": "5",
42
+ "۶": "6",
43
+ "۷": "7",
44
+ "۸": "8",
45
+ "۹": "9",
46
+ "〇": "0",
47
+ "零": "0",
48
+ }
49
+ )
50
+ _NUM_RUN = re.compile(r"\d+|\D+")
51
+
52
+
53
+ def fold_digits(value: str) -> str:
54
+ return unicodedata.normalize("NFKC", value or "").translate(_DIGIT_FOLD)
55
+
56
+
57
+ def article_sort_key(article_number: str, source_id: str) -> tuple:
58
+ folded = fold_digits(article_number or "")
59
+ nums: list[int] = []
60
+ rest: list[str] = []
61
+ for run in _NUM_RUN.findall(folded) if folded else []:
62
+ if run.isdigit():
63
+ nums.append(int(run))
64
+ else:
65
+ rest.append(run)
66
+ if not folded:
67
+ return (0, (), "", source_id or "")
68
+ if nums:
69
+ return (1, tuple(nums), "".join(rest), source_id or "")
70
+ return (2, (), folded, source_id or "")
71
+
72
+
73
+ def glue_piece(title: str, article_number: str, body: str) -> str:
74
+ """One child's contribution to a reconstructed parent (normalized strings)."""
75
+ title = title or ""
76
+ article_number = article_number or ""
77
+ body = body or ""
78
+ chunk = title if title else article_number
79
+ if chunk and not body.lstrip().startswith(chunk):
80
+ return f"{chunk}\n{body}" if body else chunk
81
+ return body
82
+
83
+
84
+ def glue_parent(pieces: Iterable[str]) -> str:
85
+ return "\n\n".join(p for p in pieces if p)
86
+
87
+
88
+ @dataclass
89
+ class ReconstructResult:
90
+ body: str
91
+ reconstructed_from_articles: bool
92
+ reconstruction_truncated: bool
93
+ reconstruction_gap_note: str
94
+ reconstruction_article_count: int
95
+ reconstruction_article_ids: list[str] = field(default_factory=list)
96
+ reconstruction_article_sha256: list[str] = field(default_factory=list)
97
+ extra_bytes: int = 0
98
+ is_stub: bool = False
99
+
100
+ def extra_fields(self) -> dict[str, Any]:
101
+ return {
102
+ "reconstructed_from_articles": self.reconstructed_from_articles,
103
+ "reconstruction_truncated": self.reconstruction_truncated,
104
+ "reconstruction_gap_note": self.reconstruction_gap_note,
105
+ "reconstruction_article_count": self.reconstruction_article_count,
106
+ "reconstruction_article_ids": list(self.reconstruction_article_ids),
107
+ "reconstruction_article_sha256": list(self.reconstruction_article_sha256),
108
+ }
109
+
110
+
111
+ def parent_needs_reconstruct(parent_body: str, n_articles: int) -> bool:
112
+ if n_articles < 1:
113
+ return False
114
+ body = parent_body or ""
115
+ return (not body) or len(body) < PARENT_TRUNCATED_MAX_CHARS
116
+
117
+
118
+ def reconstruct_on() -> bool:
119
+ return os.environ.get("COUNTRY_LAWS_RECONSTRUCT", "1").strip() not in {"0", "false", "off"}
120
+
121
+
122
+ def force_full_concat() -> bool:
123
+ return os.environ.get("COUNTRY_LAWS_RECONSTRUCT_FULL", "").strip() in {"1", "true", "on"}
124
+
125
+
126
+ def process_budget_bytes() -> int:
127
+ raw = os.environ.get("RECONSTRUCT_PROCESS_BUDGET_BYTES")
128
+ if raw and raw.isdigit():
129
+ return int(raw)
130
+ return RECONSTRUCT_PROCESS_BUDGET_BYTES
131
+
132
+
133
+ def reconstruct_parent(
134
+ *,
135
+ slug: str,
136
+ parent_body: str,
137
+ parent_title: str,
138
+ children: list[dict[str, str]],
139
+ running_extra_bytes: int,
140
+ sha256_hex,
141
+ ) -> ReconstructResult:
142
+ """Apply the five-way outcome table. ``children`` already normalized."""
143
+ ordered = sorted(
144
+ children,
145
+ key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""),
146
+ )
147
+ ids = [c.get("id") or "" for c in ordered]
148
+ shas = [sha256_hex((c.get("body") or "").encode("utf-8")) for c in ordered]
149
+ n = len(ordered)
150
+ if n < 1 or not parent_needs_reconstruct(parent_body, n):
151
+ return ReconstructResult(
152
+ body=parent_body,
153
+ reconstructed_from_articles=False,
154
+ reconstruction_truncated=False,
155
+ reconstruction_gap_note="",
156
+ reconstruction_article_count=0,
157
+ )
158
+
159
+ stub_note = ""
160
+ if slug in RSS_ABORT_SKIP_FULL_CONCAT and not force_full_concat():
161
+ stub_note = "rss_abort_slug"
162
+ elif running_extra_bytes >= process_budget_bytes():
163
+ stub_note = "reconstruct_budget"
164
+
165
+ if stub_note:
166
+ parts: list[str] = []
167
+ if parent_title:
168
+ parts.append(parent_title)
169
+ for child in ordered:
170
+ label = child.get("title") or child.get("article_number") or ""
171
+ if label:
172
+ parts.append(label)
173
+ stub = "\n".join(parts)[:RECONSTRUCT_STUB_MAX_CHARS]
174
+ return ReconstructResult(
175
+ body=stub,
176
+ reconstructed_from_articles=True,
177
+ reconstruction_truncated=False,
178
+ reconstruction_gap_note=stub_note,
179
+ reconstruction_article_count=n,
180
+ reconstruction_article_ids=ids,
181
+ reconstruction_article_sha256=shas,
182
+ extra_bytes=0,
183
+ is_stub=True,
184
+ )
185
+
186
+ acc: list[str] = []
187
+ size = 0
188
+ truncated = False
189
+ for child in ordered:
190
+ piece = glue_piece(
191
+ child.get("title") or "",
192
+ child.get("article_number") or "",
193
+ child.get("body") or "",
194
+ )
195
+ if not piece:
196
+ continue
197
+ extra = (2 if acc else 0) + len(piece)
198
+ if size + extra > RECONSTRUCT_MAX_PARENT_CHARS:
199
+ room = RECONSTRUCT_MAX_PARENT_CHARS - size - (2 if acc else 0)
200
+ if room > 0:
201
+ acc.append(piece[:room])
202
+ size = RECONSTRUCT_MAX_PARENT_CHARS
203
+ truncated = True
204
+ break
205
+ acc.append(piece)
206
+ size += extra
207
+ body = glue_parent(acc)
208
+ return ReconstructResult(
209
+ body=body,
210
+ reconstructed_from_articles=True,
211
+ reconstruction_truncated=truncated,
212
+ reconstruction_gap_note="",
213
+ reconstruction_article_count=n,
214
+ reconstruction_article_ids=ids,
215
+ reconstruction_article_sha256=shas,
216
+ extra_bytes=len(body.encode("utf-8")),
217
+ is_stub=False,
218
+ )
219
+
220
+
221
+ def expected_glue_from_children(children: list[dict[str, str]]) -> str:
222
+ ordered = sorted(
223
+ children,
224
+ key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""),
225
+ )
226
+ return glue_parent(
227
+ glue_piece(c.get("title") or "", c.get("article_number") or "", c.get("body") or "")
228
+ for c in ordered
229
+ )
country_laws_ir/sparse.py CHANGED
@@ -31,26 +31,33 @@ def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]:
31
  """
32
  from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text
33
 
34
- _MAX_TITLE = 8_192
35
  _MAX_BODY = 200_000
 
36
  rows: list[dict[str, Any]] = []
37
  for rec in corpus.itertuples(index=False):
38
- title = str(getattr(rec, "title", "") or "").replace("\x00", "").strip()
39
- body = str(getattr(rec, "body", "") or "").replace("\x00", "").strip()
 
 
 
 
40
  if len(title) > _MAX_TITLE:
41
  title = title[:_MAX_TITLE].rstrip()
42
  if len(body) > _MAX_BODY:
43
  body = body[:_MAX_BODY].rstrip()
 
 
44
  if not title and not body:
45
  continue
46
  if not tokenize_bm25_text(title) and not tokenize_bm25_text(body):
47
  continue
48
  rows.append(
49
  {
50
- "entry_cid": str(rec.entry_cid),
51
  "title": title,
52
  "body": body,
53
- "record_type": str(getattr(rec, "record_type", "") or "law"),
54
  "document_index": int(rec.document_index),
55
  }
56
  )
 
31
  """
32
  from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text
33
 
34
+ _MAX_TITLE = 4_096
35
  _MAX_BODY = 200_000
36
+ _CTRL = dict.fromkeys(range(32))
37
  rows: list[dict[str, Any]] = []
38
  for rec in corpus.itertuples(index=False):
39
+ cid = str(getattr(rec, "entry_cid", "") or "")
40
+ record_type = str(getattr(rec, "record_type", "") or "law")
41
+ title = str(getattr(rec, "title", "") or "").replace("\x00", "")
42
+ body = str(getattr(rec, "body", "") or "").replace("\x00", "")
43
+ title = title.translate(_CTRL).strip()
44
+ body = body.strip()
45
  if len(title) > _MAX_TITLE:
46
  title = title[:_MAX_TITLE].rstrip()
47
  if len(body) > _MAX_BODY:
48
  body = body[:_MAX_BODY].rstrip()
49
+ if not title:
50
+ title = f"{record_type} {cid}"[:_MAX_TITLE].strip()
51
  if not title and not body:
52
  continue
53
  if not tokenize_bm25_text(title) and not tokenize_bm25_text(body):
54
  continue
55
  rows.append(
56
  {
57
+ "entry_cid": cid,
58
  "title": title,
59
  "body": body,
60
+ "record_type": record_type,
61
  "document_index": int(rec.document_index),
62
  }
63
  )
country_laws_ir/structure.py CHANGED
@@ -20,6 +20,9 @@ from __future__ import annotations
20
  from dataclasses import dataclass, field
21
  from html.parser import HTMLParser
22
  import html as html_lib
 
 
 
23
  import re
24
  import unicodedata
25
  from typing import Any
@@ -27,24 +30,186 @@ from typing import Any
27
  _WS_RE = re.compile(r"\s+", re.UNICODE)
28
  _HAS_TAG_RE = re.compile(r"</?[a-zA-Z][^>]*>")
29
 
30
- # Line-anchored headings. Numbers may be arabic, roman, or dotted (1.2).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  _HEADING_RE = re.compile(
32
- r"(?im)^[ \t]*(?:"
33
- r"(?P<title>TITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|T[IÍ]TUL)\s+"
34
- r"(?P<title_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)"
35
- r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|CAP\.)\s+"
36
- r"(?P<chapter_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)"
37
- r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL)\s+"
38
- r"(?P<part_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)"
39
- r"|(?P<article>ART(?:ICLE|IKEL|ÍCULO|IGO|ICOLO|IKKEL)?\.?|ART\."
40
- r"|ČLÁNEK|ČLÁNOK|ČLAN|SZAKASZ|ΆΡΘΡΟ|ΑΡΘΡΟ)\s+"
41
- r"(?P<article_n>[0-9IVXLCDMΑ-Ω]+[A-Za-zΑ-Ωa-z0-9.\-]*)"
42
- r"|(?P<section>SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|SEC\.)\s+"
43
- r"(?P<section_n>[0-9A-Za-z.\-]+)"
44
- r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9A-Za-z.\-]+)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  r")"
46
- r"(?P<rest>[^\n]{0,200})?"
 
 
 
 
 
 
 
 
47
  )
 
 
 
48
 
49
  _SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)")
50
 
@@ -60,15 +225,733 @@ _KIND_RANK = {
60
  MIN_SPLIT_HEADINGS = 2
61
  MIN_UNIT_CHARS = 40
62
 
 
63
  _ZH_ART_RE = re.compile(
64
- r"(?:(?<=\n)|^)[  ]*"
65
- r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)"
 
 
 
 
 
 
 
 
 
 
66
  )
67
  _AR_ART_RE = re.compile(
68
- r"(?:(?<=\n)|^)[ \t]*(المادة|مادة)\s*([0-9٠-٩]+)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  )
70
- _JA_ART_RE = re.compile(
71
- r"(?:(?<=\n)|^)[  ]*(第[0-9一二三四五六七八九十百]+条)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  )
73
 
74
 
@@ -121,15 +1004,185 @@ def strip_html(raw: str) -> str:
121
  return text.strip()
122
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  def normalize_legal_text(value: Any) -> str:
125
  """NFKC + HTML strip. Keeps newlines so heading detection still works."""
126
  if value is None:
127
  return ""
128
- text = unicodedata.normalize("NFKC", str(value))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  text = strip_html(text)
 
 
 
 
 
130
  text = text.replace("\xa0", " ")
 
 
 
 
 
131
  text = re.sub(r"[ \t]+", " ", text)
132
  text = re.sub(r"\n[ \t]+", "\n", text)
 
 
133
  text = re.sub(r"\n{3,}", "\n\n", text)
134
  return text.strip()
135
 
@@ -147,6 +1200,8 @@ class StructureUnit:
147
  section_number: str = ""
148
  subsections: tuple[str, ...] = ()
149
  hierarchy_path: str = ""
 
 
150
 
151
  def to_dict(self) -> dict[str, Any]:
152
  return {
@@ -161,6 +1216,8 @@ class StructureUnit:
161
  "section_number": self.section_number,
162
  "subsections": list(self.subsections),
163
  "hierarchy_path": self.hierarchy_path,
 
 
164
  }
165
 
166
 
@@ -190,116 +1247,880 @@ def _subsection_tokens(text: str) -> tuple[str, ...]:
190
  return tuple(seen)
191
 
192
 
193
- def _units_from_regex(
194
- text: str, matches: list[re.Match[str]], *, kind: str, lang: str
195
- ) -> list[StructureUnit]:
196
- if len(matches) < MIN_SPLIT_HEADINGS:
197
- return []
198
- units: list[StructureUnit] = []
199
- for i, match in enumerate(matches):
200
- start = match.start()
201
- end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
202
- chunk = text[start:end].strip()
203
- if len(chunk) < 16:
204
- continue
205
- number = re.sub(r"\s+", "", match.group(0))
206
- heading = re.sub(r"\s+", " ", chunk.split("\n", 1)[0])[:240]
207
- units.append(
208
- StructureUnit(
209
- kind=kind,
210
- number=number,
211
- heading=heading,
212
- body=chunk,
213
- article_number=number,
214
- hierarchy_path=heading,
215
- )
216
- )
217
- return units if len(units) >= MIN_SPLIT_HEADINGS else []
218
 
219
 
220
- def split_script_units(text: str, language: str) -> list[StructureUnit]:
221
- """Article splits for scripts that must not use Latin TITLE/ARTICLE."""
222
  from .profiles import iso_lang
223
 
224
  lang = iso_lang(language)
225
  if lang in {"zh", "zh-cn", "zh-tw"}:
226
- prepared = re.sub(
227
- r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)",
228
- r"\n\1",
229
- text,
230
- )
231
- return _units_from_regex(prepared, list(_ZH_ART_RE.finditer(prepared)), kind="article", lang="zh")
232
- if lang in {"ar", "fa"}:
233
- prepared = re.sub(r"(المادة|مادة)", r"\n\1", text)
234
- return _units_from_regex(prepared, list(_AR_ART_RE.finditer(prepared)), kind="article", lang="ar")
235
  if lang == "ja":
236
- prepared = re.sub(r"(第[0-9一二三四五六七八九十百]+条)", r"\n\1", text)
237
- return _units_from_regex(prepared, list(_JA_ART_RE.finditer(prepared)), kind="article", lang="ja")
238
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
 
241
- def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]:
242
- """Split *text* on legal headings. Empty list means keep the whole instrument.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
 
244
- Latin TITLE/ARTICLE splits are skipped for languages in
245
- ``profiles.NO_LATIN_SPLIT_LANGS`` so Arabic/Chinese bodies are not
246
- carved up on incidental English words.
247
- """
248
- from .profiles import latin_split_allowed
249
 
250
- if not text or len(text) < 16:
251
- return []
252
- if language and not latin_split_allowed(language):
253
- return split_script_units(text, language)
254
- matches = list(_HEADING_RE.finditer(text))
255
- if len(matches) < MIN_SPLIT_HEADINGS:
256
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""}
258
  units: list[StructureUnit] = []
259
- for i, match in enumerate(matches):
260
- start = match.start()
261
- end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
262
- chunk = text[start:end].strip()
263
- kind = ""
264
- number = ""
265
- for name in ("title", "chapter", "part", "article", "section"):
266
- if match.group(name):
267
- kind = name
268
- number = (match.group(f"{name}_n") or "").strip()
269
- break
270
- if match.group("section_sym"):
271
- kind = "section"
272
- number = (match.group("section_sym_n") or "").strip()
273
- if not kind or not number:
274
- continue
275
- cursor[kind] = number
276
  for lower, rank in _KIND_RANK.items():
277
- if rank > _KIND_RANK[kind]:
278
  cursor[lower] = ""
279
- if len(chunk) < MIN_UNIT_CHARS:
280
- continue
281
- rest = (match.group("rest") or "").strip(" .-:")
282
- heading = re.sub(r"\s+", " ", match.group(0)).strip()
283
- if rest and rest not in heading:
284
- heading = f"{heading} {rest}".strip()
285
  units.append(
286
  StructureUnit(
287
- kind=kind,
288
- number=number,
289
- heading=heading[:240],
290
- body=chunk,
291
  title_number=cursor["title"],
292
  chapter_number=cursor["chapter"],
293
  part_number=cursor["part"],
294
  article_number=cursor["article"],
295
  section_number=cursor["section"],
296
- subsections=_subsection_tokens(chunk),
297
  hierarchy_path=_cursor_path(cursor),
 
 
298
  )
299
  )
300
- retrieval = [u for u in units if u.kind in {"article", "section"}]
301
- if len(retrieval) >= MIN_SPLIT_HEADINGS:
302
- return retrieval
303
- if len(units) >= MIN_SPLIT_HEADINGS:
304
- return units
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  return []
 
20
  from dataclasses import dataclass, field
21
  from html.parser import HTMLParser
22
  import html as html_lib
23
+ import json
24
+ import os
25
+ from pathlib import Path
26
  import re
27
  import unicodedata
28
  from typing import Any
 
30
  _WS_RE = re.compile(r"\s+", re.UNICODE)
31
  _HAS_TAG_RE = re.compile(r"</?[a-zA-Z][^>]*>")
32
 
33
+ # 1:1 map so match offsets stay aligned with the stored body. re.I does not
34
+ # treat É as E; gazettes use Décision, Ordonnance, Điều, Člen, etc.
35
+ _LATIN_FOLD = str.maketrans({
36
+ **dict.fromkeys("áàâäãåăąāấầẩẫậắằẳẵặảạ", "a"),
37
+ **dict.fromkeys("ÁÀÂÄÃÅĂĄĀẢẠ", "A"),
38
+ **dict.fromkeys("éèêëěęēếềểễệẻẹə", "e"),
39
+ **dict.fromkeys("ÉÈÊËĚĘĒẺẸƏ", "E"),
40
+ **dict.fromkeys("íìîïĩįīıịỉ", "i"),
41
+ **dict.fromkeys("ÍÌÎÏĨĮĪİỈỊ", "I"),
42
+ **dict.fromkeys("óòôöõőøōốồổỗộớờởỡợỏọ", "o"),
43
+ **dict.fromkeys("ÓÒÔÖÕŐØŌỎỌ", "O"),
44
+ **dict.fromkeys("úùûüűũūůứừửữựủụ", "u"),
45
+ **dict.fromkeys("ÚÙÛÜŰŨŪŮỦỤ", "U"),
46
+ **dict.fromkeys("ýÿỳỹỷỵ", "y"),
47
+ **dict.fromkeys("ÝŸỶỴ", "Y"),
48
+ **dict.fromkeys("çćčĉċ", "c"),
49
+ **dict.fromkeys("ÇĆČĈĊ", "C"),
50
+ **dict.fromkeys("ďđ", "d"),
51
+ **dict.fromkeys("ĎĐ", "D"),
52
+ **dict.fromkeys("ğĝģġ", "g"),
53
+ **dict.fromkeys("ĞĜĢĠ", "G"),
54
+ **dict.fromkeys("ñńņň", "n"),
55
+ **dict.fromkeys("ÑŃŅŇ", "N"),
56
+ **dict.fromkeys("ŕŗř", "r"),
57
+ **dict.fromkeys("ŔŖŘ", "R"),
58
+ **dict.fromkeys("śŝşšș", "s"),
59
+ **dict.fromkeys("ŚŜŞŠȘ", "S"),
60
+ **dict.fromkeys("ţťț", "t"),
61
+ **dict.fromkeys("ŢŤȚ", "T"),
62
+ **dict.fromkeys("źżž", "z"),
63
+ **dict.fromkeys("ŹŻŽ", "Z"),
64
+ **dict.fromkeys("ĺļľł", "l"),
65
+ **dict.fromkeys("ĹĻĽŁ", "L"),
66
+ "æ": "a", "Æ": "A", "œ": "o", "Œ": "O", "ß": "s",
67
+ "ɛ": "e", "Ɛ": "E", "ɔ": "o", "Ɔ": "O", "ŋ": "n", "Ŋ": "N",
68
+ **dict.fromkeys("ơớờởỡợ", "o"),
69
+ **dict.fromkeys("ƠỚỜỞỠỢ", "O"),
70
+ **dict.fromkeys("ưứừửữự", "u"),
71
+ **dict.fromkeys("ƯỨỪỬỮỰ", "U"),
72
+ **dict(zip("άέήίόύώϊϋΐΰ", "αεηιουωιυιυ")),
73
+ **dict(zip("ΆΈΉΊΌΎΏ", "ΑΕΗΙΟΥΩ")),
74
+ "ς": "σ",
75
+ "ё": "е", "Ё": "Е", "ї": "и", "Ї": "И", "є": "е", "Є": "Е", "ґ": "г", "Ґ": "Г",
76
+ })
77
+
78
+
79
+ def _latin_fold(text: str) -> str:
80
+ return text.translate(_LATIN_FOLD)
81
+
82
+ # Headings at line start *or* after . ; : so compacted "Art. 1. … Art. 2." still splits.
83
+ # Separator allows "Art. 1", "Art.1", "Član 12.", "ARTICULO 10.-", "Madde 1 –",
84
+ # "Article (1)", French "Art. L. 111-1", Roman "ARTICLE I".
85
+ _HEADING_NUM = (
86
+ r"(?:[0-9٠-٩۰-۹]+(?:er|ère|bis|ter|quater|o)?"
87
+ r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])"
88
+ r"|premier(?:e)?|première|primero|primeira"
89
+ r"|unique|unico|unica|único|única)"
90
+ )
91
+ _ARTICLE_N = (
92
+ r"(?:"
93
+ r"(?:[LRD]\.?\s*)?"
94
+ r"(?:"
95
+ r"[0-9٠-٩۰-۹]+(?:\.[0-9]+)?"
96
+ r"(?:er|ère|bis|ter|quater|aad|[A-Za-z]|o)?"
97
+ r"(?:/[0-9A-Za-z]+)?"
98
+ r"(?:\s+(?:bis|ter|quater))?"
99
+ r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])"
100
+ r"|[Α-Ω]{1,6}(?![Α-Ωα-ω])"
101
+ r")"
102
+ r"(?:[-–](?:[0-9]+|aad|bis|ter|quater|[A-Za-z](?![A-Za-z])))?"
103
+ r"(?:\([0-9A-Za-z]+\))?"
104
+ r"|premier(?:e)?"
105
+ r"|première"
106
+ r"|unique|unico|unica|único|única"
107
+ r"|primero|primera|primeiro|primeira"
108
+ r"|primo(?![A-Za-z])|secondo(?![A-Za-z])|terzo(?![A-Za-z])|quarto(?![A-Za-z])|quinto(?![A-Za-z])|prima(?![A-Za-z])"
109
+ r"|eerste|första|første"
110
+ r"|annexe"
111
+ r"|primera|segunda|tercera|cuarta|quinta"
112
+ r"|sexta|séptima|octava|novena|décima"
113
+ r")"
114
+ )
115
+ _HEADING_START = r"(?:^|(?<=[.;:])|(?<=\d[ \t]))[ \t\[\(\u00ab\u00bb\"“”‘’«»‹›\u2039\u203a]*"
116
  _HEADING_RE = re.compile(
117
+ _latin_fold(
118
+ r"(?im)" + _HEADING_START + r"(?:"
119
+ r"(?P<title>TITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|TITLUL|T[IÍ]TUL|LUKU|PEAT[UÜ]KK|"
120
+ r"РАЗДЕЛ|РОЗДІЛ|DZIA[ŁL]|ΤΙΤΛΟΣ|ДЯЛ)\s+"
121
+ r"(?P<title_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)"
122
+ r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|"
123
+ r"ROZDZIA[ŁL]|CAPITOLUL|NODA[ĻL]A|GLAVA|ГЛАВА|POGLAVLJE|KAPITOLA|"
124
+ r"ΚΕΦΑΛΑΙ[ΟO]|CH[UƯ][OƠ]NG|BAB|KABANATA|CAPO|HLAVA|KREU|FEJEZET|"
125
+ r"B[ÖO]L[ÜU]M|FESIL|CAIBIDIL|PENNOD|KAPITOLU|CHAPIT|ODDIEL|"
126
+ r"SURA(?:\s+YA)?|KAPITTEL|KAPITTUL|ANDIANY|SASHE(?:\s+NA)?|WASE|"
127
+ r"ISIGABA|ICANDELO|KGAOLO|BOBI|KUTAA|ORI|CAP\.)\s+"
128
+ r"(?P<chapter_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)"
129
+ r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL|LIVRE|BOOK|BUCH|TOMO|KNIHA|"
130
+ r"KODEKS|CODE|ZAKONIK|BAHAGIAN|BAGIAN|SEHEMU|MỤC|MUC|LIBRO|PH[AẦ]N|"
131
+ r"QAYBTA|WAHANGA|VAEGA|HAP|KAROLO|CHIKAMU|BES|EKITUNDU|ETENI|"
132
+ r"AKPA|FAANDA|PATTE|ΜΕΡΟΣ)\s+"
133
+ r"(?P<part_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)"
134
+ r"|(?P<article>(?:l['’])?(?:(?:EK|GEÇICI|GECICI|GEÇİCİ)\s+)?"
135
+ r"(?:ART(?:ICLE|IKEL|ÍCULO|ICULO|IGO|ICOLO|IKKEL|YKU[ŁL]|ICOLUL|ICOL|IKOLU|IKULA)?\.?"
136
+ r"|ART\.|NENI|PASAL|MADDE|MADDƏ|ĐIỀU|ĐIÊU|DIEU|CLANAK|ČLANAK|ČLÁNEK|ČLÁNOK|ČLEN|ČLAN|CLAN"
137
+ r"|ЧЛАНАК|ЧЛАН|ЧЛЕН|ЧЛ\.|СТАТЬЯ|СТАТТЯ|SZAKASZ|CIKK|ΆΡΘΡΟ|ΑΡΘΡΟ"
138
+ r"|PYKÄLÄ|GREIN|PANTS|SEKSYEN|CIKK|KIFUNGU|MODDA|ATIK|KUPU|ATIKOL|"
139
+ r"INGINGO(?:\s+YA)?|NDIME|ABALA|NKEJI|SARIYA|TERE|AHYEDE|PENNAD|ERTHYGEL|HYEDEE|"
140
+ r"ARTIGU|PAUKU|IRAVA"
141
+ r"|მუხლი|ՀՈԴՎԱԾ|Հոդված))(?![A-Za-z])"
142
+ r"(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*"
143
+ r"(?P<article_n>" + _ARTICLE_N + r")\)?"
144
+ r"|(?P<section>SUB(?:-)?SECTION|SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|PARAGRAHV|PARAGRAPHE|PARAGRAAF|PARAGRAPH|"
145
+ r"RECITAL|CONSIDERANDO|"
146
+ r"ALIN[EÉ]A|ALINEATUL|INCISO|P[AÁ]RRAFO|PUNKT(?![A-Za-z])|SATZ(?![A-Za-z])|LID|"
147
+ r"ΠΑΡΑΓΡΑΦΟΣ|ABSATZ|APARTADO|COMMA(?![A-Za-z])|FIKRA|STAVAK|STK\.?|АЛ\.|SEKSHON|"
148
+ r"NUMERAL|CAPOVERSO|NUMMER|"
149
+ r"AYAT|KHOẢN|KHOAN|"
150
+ r"RULE(?![A-Za-z])|REGULATION(?![A-Za-z])|SCHEDULE(?![A-Za-z])|FORM(?![A-Za-z])|"
151
+ r"ORDINANCE|ORDONNANCE|ORDONAN[TŢȚ][AĂÁ]?|ORDIN(?![A-Za-z])|BY-?LAW|DIRECTIVE(?![A-Za-z])|"
152
+ r"D[EÉ]CISION(?![A-Za-z])|DECISION(?![A-Za-z])|DECIZIE|"
153
+ r"BESLUIT(?![A-Za-z])|REGELING(?![A-Za-z])|BESCHIKKING(?![A-Za-z])|"
154
+ r"ODLUKA|PRAVILNIK|HOT[ĂA]R[ÂAÎI]RE|"
155
+ r"RESOLUCI[OÓ]N(?![A-Za-z])|RESOLU[CÇ][AÃ]O(?![A-Za-z])|PORTARIA(?![A-Za-z])|ACUERDO(?![A-Za-z])|"
156
+ r"MEDIDA\s+PROVIS[OÓ]RIA|"
157
+ r"PROCLAMATION(?![A-Za-z])|PROKLAMATION|CIRCULAR(?![A-Za-z])|INSTRUCTION(?![A-Za-z])|"
158
+ r"GUIDELINE(?![A-Za-z])|MEMORANDUM(?![A-Za-z])|"
159
+ r"AVISO(?![A-Za-z])|AVIS(?![A-Za-z])|BEKANNTMACHUNG|MEDDELANDE|"
160
+ r"NORMA(?![A-Za-z])|"
161
+ r"PRESIDENTIAL\s+DECREE|DECRETO-LEI|DECRETO(?![A-Za-z])|DECREE(?![A-Za-z])|"
162
+ r"D[EÉ]CRET-LOI|D[EÉ]CRET(?![A-Za-z])|ARR[EÊ]T[EÉ]|"
163
+ r"DELIBERA[CÇ][AÃ]O|D[EÉ]LIB[EÉ]RATION|COMUNICADO|"
164
+ r"R[EÈ]GLEMENT(?![A-Za-z])|CIRCULAIRE(?![A-Za-z])|VERORDNUNG(?![A-Za-z])|ERLASS(?![A-Za-z])|"
165
+ r"PUNTO(?![A-Za-z])|SUB(?:-)?PARAGRAPH|"
166
+ r"ANNEX(?:E)?(?![A-Za-z])|ANEXO|ANLAGE|BIJLAGE|APPENDIX|ALLEGATO|"
167
+ r"ZA[ŁL][AĄ]CZNIK|BILAGA|LIITE|P[ŘR][IÍ]LOHA|"
168
+ r"UST\.|ODST\.|ODS\.|BEK\.|"
169
+ r"SEC(?:\.|(?=\s+[0-9])))(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?[.\s:]*\(?\s*"
170
+ r"(?P<section_n>(?:[0-9][0-9A-Za-z.\-]*(?:\([0-9A-Za-z]+\))?|"
171
+ r"(?-i:[IVXLCDM]{1,8})(?![A-Za-z])|[A-Za-z](?![A-Za-z])))\)?"
172
+ r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9]+(?:[A-Za-z](?![A-Za-z]))?(?:\s+[A-Za-z](?![A-Za-z]))?(?:\s*\([0-9A-Za-z]+\))?)"
173
+ r"|(?P<section_pre_n>[0-9]+(?:\s*[a-z])?)\s*\.?\s*(?P<section_pre>§)"
174
+ r"|(?P<grein_n>[0-9]+[a-z]?)\s*\.\s*(?P<grein>gr|pants)\.?"
175
+ r"|(?P<straipsnis_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<straipsnis>straipsnis)"
176
+ r"|(?P<artikulua_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<artikulua>artikulua)"
177
+ r"|(?P<ledd_n>[0-9]+)\s*[.]?\s*(?P<ledd>ledd)"
178
+ r"|(?P<kap_n>[0-9]+)\s*(?P<kap>kap)\.?"
179
+ r"|(?P<luku_n>[0-9]+)\s*(?P<luku>luku)"
180
+ r"|(?P<fejezet_n>[IVXLCDM0-9]+)\s*\.\s*(?P<fejezet>fejezet)"
181
+ r"|(?P<peatukk_n>[0-9]+)\s*[.]?\s*(?P<peatukk>peat[uü]kk)"
182
+ r"|(?P<skyrius_n>[IVXLCDM0-9]+)\s*(?P<skyrius>skyrius)"
183
+ r"|(?P<nodala_n>[IVXLCDM0-9]+)\s*(?P<nodala>noda[ļl]a)"
184
+ r"|(?P<kafli_n>[IVXLCDM0-9]+)\s*[.]?\s*(?P<kafli>kafli)"
185
+ r"|(?P<bob_n>[0-9]+)\s*-\s*(?P<bob>bob)"
186
+ r"|(?P<tarau_n>[0-9]+)\s*-\s*(?P<tarau>тарау)"
187
+ r"|(?P<bolum_n>[0-9]+)\s*-\s*(?P<bolum>бөлүм)"
188
+ r"|(?P<modda_n>[0-9]+)\s*-\s*(?P<modda>модда|modda)"
189
+ r"|(?P<mn_n>[0-9]+)\s*(?P<mn>(?:дүгээр|дугаар)\s*зүйл)"
190
+ r"|(?P<kk_n>[0-9]+)\s*-?\s*(?P<kk>бап)"
191
+ r"|(?P<mom_n>[0-9]+)\s*(?P<mom>momentti)"
192
+ r"|(?P<order>(?:EXECUTIVE\s+)?ORDER)\s+(?P<order_n>[0-9]+)"
193
+ r"|(?P<kidogo>KIFUNGU\s+KIDOG[OU])\s*\(?\s*(?P<kidogo_n>[0-9]+)"
194
+ r"|(?P<disp>DISPOSICI[OÓ]N)(?:\s+(?:adicional(?:es)?|transitoria(?:s)?|derogatoria(?:s)?|final(?:es)?))?\s+"
195
+ r"(?P<disp_n>" + _ARTICLE_N + r")"
196
+ r"|(?P<esresol>primero|segundo|tercero|cuarto|quinto|sexto|septimo|octavo|noveno|decimo|"
197
+ r"erstens|zweitens|drittens|viertens|funftens|"
198
+ r"premierement|deuxiemement|troisiemement|quatriemement|cinquiemement)\s*:"
199
  r")"
200
+ )
201
+ )
202
+ # Commonwealth "1. Short title" — used only when keyword headings are scarce.
203
+ _CW_NUM_RE = re.compile(
204
+ r"(?m)^[ \t]*(?P<cw_n>[0-9]+[A-Za-z]?)\.?\s+(?:\([0-9A-Za-z]+\)\s+)?(?=[A-Z][a-z]+)"
205
+ )
206
+ _MONTH_START_RE = re.compile(
207
+ r"(?i)^(january|february|march|april|may|june|july|august|september|october|november|december|"
208
+ r"janvier|f[eé]vrier|marzo|abril|enero|junio|julio)\b"
209
  )
210
+ _CW_NUM_LANGS = frozenset({"", "en", "hi", "bn", "ne", "ur", "ms", "fil", "sw", "si"})
211
+ _LEXICON_HEADING_RE: re.Pattern[str] | None = None
212
+ _LEXICON_KIND: dict[str, str] = {}
213
 
214
  _SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)")
215
 
 
225
  MIN_SPLIT_HEADINGS = 2
226
  MIN_UNIT_CHARS = 40
227
 
228
+ # Markers on the *stored* body (no rewritten newline copy).
229
  _ZH_ART_RE = re.compile(
230
+ r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:之[一二三四五六七八九十百0-9]+)?"
231
+ )
232
+ _AR_ORD = (
233
+ r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*والعشرون|"
234
+ r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*عشرة|"
235
+ r"العشرون|"
236
+ r"الأولى|الأولي|األولى|الاولى|الثانية|الثالثة|الرابعة|الخامسة|"
237
+ r"السادسة|السابعة|الثامنة|التاسعة|العاشرة"
238
+ )
239
+ _AR_ORD_M = (
240
+ r"الأول|الاول|الثاني|الثالث|الرابع|الخامس|"
241
+ r"السادس|السابع|الثامن|التاسع|العاشر"
242
  )
243
  _AR_ART_RE = re.compile(
244
+ r"\(?(?:الماد[ةه]|املاد[ةه]|مادة)\s*[-–]?\s*[()]*\s*(?:[0-9٠-٩۰-۹]+|" + _AR_ORD + r")"
245
+ r"(?:\s*[-–])?(?:\s*[()]*)?(?:\s*مكرر(?:اً|ا)?)?"
246
+ )
247
+ _CITE_TAIL_RE = re.compile(
248
+ _latin_fold(
249
+ r"(?i)\s+(?:"
250
+ r"of\s+(?:this\s+|the\s+)?(?:act|law|agreement|code|constitution|article|section|"
251
+ r"principal\s+act|ordinance|regulation|decree|chapter|part|title|ruling|order)"
252
+ r"|thereof\b"
253
+ r"|hereof\b"
254
+ r"|hereunder\b"
255
+ r"|de\s+la\s+(?:loi|ley|presente|présente)"
256
+ r"|du\s+(?:code|présent|present)"
257
+ r"|des\s+gesetzes"
258
+ r"|van\s+(?:deze\s+)?(?:wet|artikel)"
259
+ r"|i\s+lov\b"
260
+ r"|cua\s+luat(?:\s+nay)?"
261
+ r")\b"
262
+ )
263
+ )
264
+ _NUMERO_FOLD_RE = re.compile(
265
+ r"(?i)(?:№|n\.\s*o\b|n\.?[°º]|nÂ[oº°]|\bno\.?\s+(?=\d))\.?\s*"
266
+ )
267
+ _CJK_RANGE_RE = re.compile(
268
+ r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條]\s*(?:至|到|から)\s*"
269
+ r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:まで)?"
270
+ )
271
+ _FA_ORD = (
272
+ r"یازدهم|دوازدهم|سیزدهم|چهاردهم|پانزدهم|شانزدهم|هفدهم|هجدهم|نوزدهم|بیستم|"
273
+ r"اولی?|نخست|دوم|سوم|چهارم|چارم|جارم|پنجم|ششم|هفتم|هشتم|نهم|دهم"
274
+ )
275
+ _FA_ART_RE = re.compile(r"(?:ماده|مادة)\s*(?:[0-9۰-۹]+|" + _FA_ORD + r")")
276
+ _DA_ART_RE = re.compile(r"(?:Artikel|§)\s*[0-9]+", re.IGNORECASE)
277
+ _CHROME_LINE_RE = re.compile(
278
+ r"(?i)^(?:"
279
+ r"početna stranica\b.*|"
280
+ r"upute za korištenje\b.*|"
281
+ r"elektronička pošta\b.*|"
282
+ r"vsebina uradnega lista\b.*|"
283
+ r"the incident id is\b.*|"
284
+ r"ωράριο λειτουργίας\b.*|"
285
+ r"τηλέφωνο επικοινωνίας\b.*|"
286
+ r"skip to (?:main )?content\b.*|"
287
+ r"javascript is (?:required|disabled)\b.*|"
288
+ r"privacy policy\s*$|"
289
+ r"traduction française pour information\s*$|"
290
+ r"pdf\s*$|"
291
+ r"https?://\S+\s*$|"
292
+ r"légimonaco\b.*|"
293
+ r"statutory instruments\s*$|"
294
+ r"official gazette\s*$|"
295
+ r"government gazette\s*$|"
296
+ r"(?:the )?london gazette\s*$|"
297
+ r"journal officiel(?: de la république(?: [^\n]{0,40})?)?\.?\s*$|"
298
+ r"bulletin officiel\s*$|"
299
+ r"gazette du canada\s*$|"
300
+ r"(?:the )?[\w .'-]{0,50}gazette\s*$|"
301
+ r"الوقائع المصرية\s*$|"
302
+ r"الوقائع العراقية\b.*|"
303
+ r"العدد\s*$|"
304
+ r"العدد\s+\S.{0,80}الوقائع\b.*|"
305
+ r".*شعبة الجريدة الرسمية\s*$|"
306
+ r"(?:the )?(?:republic of sudan gazette|gazette published by authority|official gazette of the republic of sudan)\b.*|"
307
+ r"الصفحة(?:\s*[0-9٠-٩]+)?\s*$|"
308
+ r"(?:الجريدة|اجلريدة|جريدة)(?:\s+الر\s*سمية)?(?:\s+العدد(?:\s*\(\s*\)?\s*[0-9٠-٩]+)?)?\s*$|"
309
+ r"république du s[ée]n[ée]gal\s*$|"
310
+ r"jamhuuriyadda\b.*|"
311
+ r"warta kerajaan\s*$|"
312
+ r"lembaran negara\s*$|"
313
+ r"berita negara\s*$|"
314
+ r"công báo\s*$|"
315
+ r"la gaceta\s*$|"
316
+ r"no\.?\s*\d+\s+government gazette\b.*|"
317
+ r"supplement to (?:the |official ).{0,60}gazette\b.*|"
318
+ r"[a-z0-9 ,.'()-]*supplement to official gazette[a-z0-9 ,.'()-]*$|"
319
+ r"printed by\b.*|"
320
+ r"https?://\S+(?:\s+\d+(?:\.\d+)*)?\s*$|"
321
+ r"©+\s*.*congress\b.*|"
322
+ r"(?:s|sm)\s+congress\b.*|"
323
+ r"palikir,\s*pohnpei\b.*|"
324
+ r"www\.\S+(?:\s+\d+)?\s*$|"
325
+ r"at\s+www\.\S+\s*$|"
326
+ r".*research bulletin.*|"
327
+ r"acts supplement\s*$|"
328
+ r"supplement\s+(?:nr\.\s*|no\.?\s*)\d+(?:\s+\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\.?)?\s*$|"
329
+ r"no\.\s+of\s+\d{4}\.?\s*$|"
330
+ r"act no\.\s+of\s+\d{4}\.?\s*$|"
331
+ r"bill for the\s*$|"
332
+ r"(?:the )?republic of [a-z]+(?:\s+[a-z]+)?\s*$|"
333
+ r"federal republic of [a-z]+(?:\s+[a-z]+)?\s*$|"
334
+ r"democratic people's republic of korea\s*$|"
335
+ r".{0,10}republic of palau\s*$|"
336
+ r"saint vincent and the grenadines\s*$|"
337
+ r"\[?\s*član\s+\.\.\.\s*\]?\s*$|"
338
+ r".*аудиони тинглаш.*|"
339
+ r"reprint\s*$|"
340
+ r"reprint authorised by\b.*|"
341
+ r"parliament building\s*$|"
342
+ r"oau drive, tower hill\s*$|"
343
+ r"office of the clerk of parliament\s*$|"
344
+ r"(?:(?:first|second|third|fourth|fifth)\s+parliament(?:\s+of\s+the\s+(?:first|second|third|fourth|fifth)\s+republic)?\s*){1,2}$|"
345
+ r"(?:(?:first|second|third|fourth|fifth)\s+meeting of parliament\s*){1,2}$|"
346
+ r"تفاصيل\s+(?:النظام|اللائحة)\s*$|"
347
+ r"مجموعة الأنظمة السعودية\s*$|"
348
+ r"المجلد\s+\S+\s*$|"
349
+ r"أنظمة\s+\S.{0,60}$|"
350
+ r"(?:first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth)\s+folder\s*$|"
351
+ r"this law includes:\s*$|"
352
+ r"-\s*اختر\s*-\s*$|"
353
+ r"تاريخ الإصدار\s*$|"
354
+ r"تاريخ النشر\s*$|"
355
+ r"الحالة\s*$|"
356
+ r"ساري\s*$|"
357
+ r"العربية\s*$|"
358
+ r"الإسم\s*$|"
359
+ r"البريد الإلكتروني\s*$|"
360
+ r"رقم الجوال\s*$|"
361
+ r"نوع البلاغ\s*$|"
362
+ r"\d{4}/\d{2}/\d{2}\s+ه\s+الموافق\s*:?\s*\d{2}/\d{2}/\d{4}\s+م\s*$|"
363
+ r"\d{3,4}\s+ه\s*$|"
364
+ r"خطأ لغوي\s*$|"
365
+ r"خطأ في مادة\s*$|"
366
+ r"يتضمن (?:النظام|التنظيم) ما يلي\s*:?\s*$|"
367
+ r"عدد مرات التصفح\s*\d*\s*$|"
368
+ r"نبذة عن النظام\s*$|"
369
+ r"اسم النظام/اللائحة\b.*|"
370
+ r"تاريخ (?:إصدار|نشر) النظام/اللائحة\s*$|"
371
+ r"حالة النظام/اللائحة\b.*|"
372
+ r"أدوات إصدار النظام\s*$|"
373
+ r"نص النظام\s*$|"
374
+ r"مادة معدلة\s*$|"
375
+ r"مادة ملغية\s*$|"
376
+ r"اصل الوثيقة\s*$|"
377
+ r"طباعة\s*$|"
378
+ r"إبلاغ\s*$|"
379
+ r"الإصدارات\s*$|"
380
+ r"اللغات\s*$|"
381
+ r"الإنجليزية\s*\(English\)\s*$|"
382
+ r"(?:\d{4}\s+)?revised edition(?:\s+as at\b.*|\s+page\s+\d+)?\s*$|"
383
+ r"page\s+\d+\s+\d{4}\s+revised edition\s*$|"
384
+ r"\[note: this version\b.*|"
385
+ r"\[this is the version of this document\b.*|"
386
+ r"el peruano\s*$|"
387
+ r"(?:act\s+\d+\s+of\s+\d{4}\s+)?page\s*\d+(?:\s+(?:of\s+\d+|act\s+\d+\s+of\s+\d{4}|[a-z]))?\s*$|"
388
+ r"[a-z]\s+page\s*\d+\s*$|"
389
+ r"(?:section\s+)?pages?\s*$|"
390
+ r"seite\s+\d+(?:\s+(?:von|of|bis)\s+\d+)?\s*$|"
391
+ r"bundesrecht konsolidiert\b.*|"
392
+ r".*ris\.bka\.gv\.at.*$|"
393
+ r"\{\\rtf\d+\b.*|"
394
+ r"p[aá]gina\s+\d+\s*$|"
395
+ r"pagina\s+\d+\s*$|"
396
+ r"strona\s+\d+\s*$|"
397
+ r"p\.\s*\d+(?:\s+(?:of|di|von|sur|de)\s+\d+)?\s*$|"
398
+ r"pag\.\s*\d+(?:\s+(?:di|of|de)\s+\d+)?\s*$|"
399
+ r"blz\.\s*\d+\s*$|"
400
+ r"folio\s+\d+\s*$|"
401
+ r"foglio\s+\d+\s*$|"
402
+ r"лист\s+\d+\s*$|"
403
+ r"стр\.\s*\d+\s*$|"
404
+ r"ص\s*\.?\s*\d+\s*$|"
405
+ r"עמוד\s+\d+\s*$|"
406
+ r"trang\s+\d+\s*$|"
407
+ r"halaman\s+\d+\s*$|"
408
+ r"sayfa\s+\d+\s*$|"
409
+ r"oldal\s+\d+\s*$|"
410
+ r"stran(?:ica)?\s+\d+\s*$|"
411
+ r"www\.\S+\s*$|"
412
+ r"downloaded from\b.*|"
413
+ r"printed on\s+\d.*|"
414
+ r"generated by\b.*|"
415
+ r"e-?mail:\s*\S+@\S+\s*$|"
416
+ r"tel(?:ephone)?:\s*[+\d].*$|"
417
+ r"for more information visit\b.*|"
418
+ r"[-–—]\s*\d{1,4}\s*[-–—]\s*$|"
419
+ r"table of contents\s*$|"
420
+ r"table des mati[eè]res\s*$|"
421
+ r"inhaltsverzeichnis\s*$|"
422
+ r"(?:índice|indice)\s*$|"
423
+ r"sommaire\s*$|"
424
+ r".*\barrangement of (?:sections|provisions|regulations|rules)\.?(?:\s+cap\.\s*[\d.]+.*)?\s*$|"
425
+ r"contents\s*$|"
426
+ r"section\s*$|"
427
+ r"[\s.\-;,*/_×|+~•·{}()\\=»«®∞]+$|"
428
+ r"(?=.*[+|])[+\-|]{3,}\s*$|"
429
+ r"\[original service \d{4}\].*|"
430
+ r"statute law of the [a-z ]+$|"
431
+ r"[A-Z][A-Z .'\-]{0,40}\[ch\.\s*\d+.*|"
432
+ r"التاريخ:\s*$|"
433
+ r"republic of the marshall islands\s*$|"
434
+ r"jepilpilin ke ejukaan\s*$|"
435
+ r"zastupni[cč]ki dom hrvatskoga sabora\s*$|"
436
+ r"dr[zž]avni zavod za normizaciju i mjeriteljstvo\s*$|"
437
+ r"олдинги таҳрирга қаранг\.?\s*$|"
438
+ r"explanatory note\s*$|"
439
+ r"\.\s*\(\s*\d+\s*\)\s*$|"
440
+ r"(?:يناير|فبراير|مارس|أبريل|ابريل|مايو|يونيو|يوليو|أغسطس|اغسطس|سبتمبر|أكتوبر|اكتوبر|نوفمبر|ديسمبر)\s+\d{4}\s*$|"
441
+ r"laws of (?:the )?[a-z]+(?:\s+(?:&|[a-z]+)){0,4}\s*$|"
442
+ r"(?-i:LAWS OF (?:THE )?[A-Z]+(?:\s+[A-Z]+){0,6}\s+s\s*\d+\s*$)|"
443
+ r"(?:í|i)ndice legislativo\s*$|"
444
+ r"قائمة (?:المحتويات|احملتويات)\s*$|"
445
+ r"spis tre[sś]ci\s*$|"
446
+ r"содержание\s*$|"
447
+ r"πίνακας περιεχομένων\s*$|"
448
+ r"목차\s*$|"
449
+ r"目次\s*$|"
450
+ r"สารบัญ\s*$|"
451
+ r"[aα]ριθμός\s+\d+[^\n]{0,24}\s*$|"
452
+ r"[aα]ρ\.\s*\d+(?:/\d+)?[^\n]{0,12}\s*$|"
453
+ r"številka\s+\d+[^\n]{0,24}\s*$|"
454
+ r"(?:nr|no|n[uú]m(?:ero|éro|ber)?|broj|č[ií]slo|szám|sayı|номер)\.?\s*\d{2,}(?:/\d+)?[.\s]*$|"
455
+ r"№\s*\d+\s*$|"
456
+ r"copyright\s*©?\s*\d{4}.*$|"
457
+ r"©\s*\d{4}.*$|"
458
+ r"\d{1,2}[./-]\d{1,2}[./-]\d{2,4}\s*$|"
459
+ r"\d{4}-\d{2}-\d{2}\s*$|"
460
+ r"\d{1,2}\s+(?:january|february|march|april|may|june|july|august|september|october|november|december|"
461
+ r"janvier|f[eé]vrier|mars|avril|mai|juin|juillet|ao[uû]t|septembre|octobre|novembre|d[eé]cembre|"
462
+ r"enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)\s+\d{4}\s*$|"
463
+ r"end of (?:the )?document\s*$|"
464
+ r"fin du document\s*$|"
465
+ r"ende des dokuments?\s*$|"
466
+ r"fin del documento\s*$|"
467
+ r"fim do documento\s*$|"
468
+ r"[-*=._]{3,}\s*$|"
469
+ r"published\s*$|"
470
+ r"publi[eé]\s*$|"
471
+ r"publicado\s*$|"
472
+ r"veröffentlicht\s*$|"
473
+ r"\[?seal\]?\s*$|"
474
+ r"\(seal\)\s*$|"
475
+ r"l\.s\.?\s*$|"
476
+ r"god save the (?:king|queen)\s*$|"
477
+ r"vive la r[eé]publique\s*$|"
478
+ r"by (?:order|command)\s*$|"
479
+ r"signed\s*$|"
480
+ r"diario oficial(?: de la federación)?\s*$|"
481
+ r"gazzetta ufficiale(?: della repubblica(?: italiana)?)?\s*$|"
482
+ r"boletín oficial(?: del estado)?\s*$|"
483
+ r"diário da república\s*$|"
484
+ r"bundesgesetzblatt\s*$|"
485
+ r"moniteur belge\s*$|"
486
+ r"belgisch staatsblad\s*$|"
487
+ r"staatsblad\s*$|"
488
+ r"lovtidende\s*$|"
489
+ r"svensk författningssamling\s*$|"
490
+ r"uradni list\s*$|"
491
+ r"dziennik ustaw\s*$|"
492
+ r"monitorul oficial\s*$|"
493
+ r"εφημερίδα της κυβερνήσεως\s*$|"
494
+ r"resmi gazete\s*$|"
495
+ r"iris oifigiúil\s*$|"
496
+ r"latvijas vēstnesis\s*$|"
497
+ r"valstybės žinios\s*$|"
498
+ r"官報\s*$|"
499
+ r"国务院公报\s*$|"
500
+ r"관보\s*$|"
501
+ r"ราชกิจจานุเบกษา\s*$|"
502
+ r"(?:เล่ม|เลม)\s*[๐-๙0-9].*ราชกิจจานุเบกษา.*|"
503
+ r"اطلاق نسخة جديدة من الميزان\s*$|"
504
+ r"\[\d+/\d{4}(?:\s+wef\s+[\d/]+)?\]\s*$|"
505
+ r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+\s+\d{4}\]\s+.+\s+\d{1,4}\s*$|"
506
+ r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\]\s*$|"
507
+ r"(?:18|19|20)\d{2}\s*$|"
508
+ r"gazette\.?\s*$|"
509
+ r"cap\.\s*\d+(?:\.\d+)*\s*$|"
510
+ r".+\scap\.?\s*[\d.]+\s+section\s+\d+\s*$|"
511
+ r"diario oficial\s*$|"
512
+ r"diário oficial(?: da união)?\s*$|"
513
+ r"gaceta oficial(?: de la república)?\s*$|"
514
+ r"registro oficial\s*$|"
515
+ r"sbírka zákonů\s*$|"
516
+ r"zbierka z[^\n]{0,40}\s*$|"
517
+ r"magyar közlöny\s*$|"
518
+ r"narodne novine\s*$|"
519
+ r"službeni glasnik\s*$|"
520
+ r"службени гласник\s*$|"
521
+ r"държавен вестник\s*$|"
522
+ r"monitorul oficial(?: al româniei)?\s*$|"
523
+ r"norsk lovtidend\s*$|"
524
+ r"suomen säädöskokoelma\s*$|"
525
+ r"finlands författningssamling\s*$|"
526
+ r"riigi teataja\s*$|"
527
+ r"российская газета\s*$|"
528
+ r"(?:the )?kenya gazette\s*$|"
529
+ r"federal negar[ie]t gazett?e\s*$|"
530
+ r"gazette officielle\s*$|"
531
+ r"amtsblatt(?: der europäischen union)?\s*$|"
532
+ r"official journal of the european union\s*$|"
533
+ r"journal officiel de l'union européenne\s*$|"
534
+ r"gazzetta ufficiale dell'unione europea\s*$|"
535
+ r"الجريدة الرسمية\b.*|"
536
+ r"ваш броузер застарів\b.*|"
537
+ r"your browser is (?:out of date|outdated|obsolete)\b.*|"
538
+ r"all rights reserved\b.*|"
539
+ r"subscribe to\s+(?:our\s+)?(?:newsletter|mailing(?:\s+list)?|updates|feed)\b.*|"
540
+ r"(?:we use|this (?:site|website) uses)\s+cookies\b.*|"
541
+ r".{0,80}використовуємо cookies\b.*|"
542
+ r".{0,80}використання cookies\b.*|"
543
+ r"продовжуючи відвідування сайту\b.*|"
544
+ r"al meezan\b.*|"
545
+ r"الميزان\b.*|"
546
+ r".{0,40}وزارة العدل(?: و الشؤون القانونية)?\s*$|"
547
+ r"التشريعات\b.*|"
548
+ r"page not found\b.*|"
549
+ r"(?:error\s+)?404(?:\s+not found)?\b.*|"
550
+ r"access denied\s*$|"
551
+ r"forbidden\s*$|"
552
+ r"public notification\s*$|"
553
+ r"[^\n]{0,40}@mjla\b.*|"
554
+ r".{0,40}gaceta oficial(?: digital)?\b.*|"
555
+ r"paragraph\s*$|"
556
+ r"[^\n]{0,60}slov-lex\s*$|"
557
+ r"(?:crown\s+)?copyright\s*(?:©\s*)?\d{4}\.?\s*$|"
558
+ r"copying\s*/\s*unauthori[sz]ed distribution strictly prohibited\.?\s*$|"
559
+ r"(?:revision|consolidation) date\s*:.*|"
560
+ r"showing the law as at\s+\d.*|"
561
+ r"this is a revised edition of the law\b.*|"
562
+ r"printed under authority by\s*$|"
563
+ r"(?:the )?regional law revision centre\b.*|"
564
+ r"continued on next page\b.*|"
565
+ r"back to (?:page one|the top|top)\s*$|"
566
+ r"page\s*:\s*\d+\s+date\s*:.*|"
567
+ r"bwpageid\s*::.*|"
568
+ r"bwservice\s*::.*|"
569
+ r".*ron_book\b.*|"
570
+ r"\d+\s+service\s+\d+\s*$|"
571
+ r"(?:pdf|word|audio)\s+download\s*$|"
572
+ r"login with (?:facebook|google|apple|twitter|email)\b.*|"
573
+ r"(?:view|print|e-?mail)\s*$|"
574
+ r"last updated(?:\s+on)?\s+\d.*|"
575
+ r"speakers office\s*$|"
576
+ r"fsm congress\s*$|"
577
+ r".*almeezan\b.*|"
578
+ r"add new section\s*$|"
579
+ r"section name\s*$|"
580
+ r".*hijripage\b.*|"
581
+ r"search in articles\s*$|"
582
+ r"privacy statement\s*$|"
583
+ r"terms of use\s*$|"
584
+ r"rate this website\s*$|"
585
+ r"feedback via reach\s*$|"
586
+ r"singapore statutes online\b.*|"
587
+ r".*reprint is authorised by\b.*|"
588
+ r"công báo\s*/\s*số\b.*|"
589
+ r"thời gian ký\s*:.*|"
590
+ r"lex\.?uz\b.*|"
591
+ r"\[?(?:окоз|тсз|спит)\s*:.*|"
592
+ r"\d+(?:\.\d{2}){3,}.*[\u0400-\u04FF].*|"
593
+ r"issue\s*:\s*\d+\s*,\s*amendment\s*:\s*\d+\b.*|"
594
+ r"presidential comm\.?\s*no\b.*|"
595
+ r"(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2},?\s+\d{4}(?:\s+[a-z])?\s*$|"
596
+ r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\.\d+\b(?!.*\b(?!etc\b)[a-z]{3,}\b).*$)|"
597
+ r"(?-i:(?!.*\b(?!etc\b)[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\.\d+(?:\.\d+)*\s+\d{1,4}\s*$)|"
598
+ r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\s+(?!.*\b[a-z]{3,}\b).+$)|"
599
+ r"(?-i:(?!.*\b[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\s+\d{1,4}\s*$)|"
600
+ r"(?-i:\d{1,4}\s+[Cc]hap\.\s*\d+(?::\d+)?\b(?!.*\b[a-z]{3,}\b).*$)|"
601
+ r"(?-i:\d{1,4}\s+(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s*$)|"
602
+ r"(?-i:(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s+\d{1,4}\s*$)|"
603
+ r"constituci[oó]n pol[ií]tica del per[uú]\s+\d+\s*$|"
604
+ r"\d{1,4}\s+edici[oó]n del congreso\b.*|"
605
+ r"nr\.\s*\d+\s*\].*\[.*|"
606
+ r"st\.?\s*christopher and nevis\s*$|"
607
+ r"official gazette\s+nr\.\s*\d[\d\s/.-]*(?:\s+of\s+[\d/.-]+)?\s*$|"
608
+ r"www\.\S+(?:\s+(?!(?:for|under|and|the|is|of)\b)[A-Za-z][\w.-]{1,24}){1,2}\s*$|"
609
+ r".*laws\.africa\b.*|"
610
+ r".*share widely and freely.*|"
611
+ r".*no copyright on the legislative content.*|"
612
+ r"(?-i:^(?:Malawi|Zambia|Kenya|Uganda|Ghana|Namibia|Botswana|Lesotho|Eswatini|Rwanda|Tanzania|Nigeria|Zimbabwe|Mauritius|Seychelles|Liberia|Gambia)\s+.{0,80}\(Chapter\s+\d+\)\s*$)|"
613
+ r"(?-i:^Act\s+\d+\s+(?:[A-Z][a-z]+\s+){1,6}(?:19|20)\d{2}\s*$)|"
614
+ r"issue\s*:?\s*\d+(?:\.\d+)?\s+page\s+\d+\s+of\s+\d+\b.*|"
615
+ r"issue\s*:\s*\d+(?:\.\d+)?\s+\d+\s+\d{1,2}\s+[a-z]+\s+\d{4}\s*$|"
616
+ r".*edition officielle mise [aà] jour.*|"
617
+ r"code general des impots\s+\d{4}\s*$|"
618
+ r"\d{1,2}\.\d{1,2}\.\d{4}\s*-\s*\d{1,2}\.\d{1,2}\.\d{4}\s*$|"
619
+ r"(?!.*δημοσιευ)(?!.*\bστην\b)(?=.*εφημερ.{0,12}κυβερν)(?=.*(?:τευξ|τεύχ|\(\s*τευ)).{0,140}$|"
620
+ r"(?:\d{1,4}\s+)?επ[ιί]σημη\s+εφημερ[ιί]δ[αά]\b.*|"
621
+ r"sistema integrado de gest[aã]o de finan[cç]as p[uú]blicas\s*\(sigfip\)\s*\d+\s*/\s*\d+\s*$|"
622
+ r"editado por\s*:.*\beditado em\s*:.*|"
623
+ r"issue\s+\d{1,4}\s*$|"
624
+ r"\d{1,4}\s*\|\s*page\s*$|"
625
+ r"page\s*\|\s*\d{1,4}\s*$|"
626
+ r"\{\{[^}\n]*\}\}\s*$|"
627
+ r"lap tetej[eé]re\s*$|"
628
+ r"megnyitottak\s*$|"
629
+ r"jogszab[aá]lykeres[oő]\s*$|"
630
+ r".*slu[zž]beni glasnik\b.{0,50}stranica\s+\d+\s*$|"
631
+ r".*\(unknown\)/ron\b.*|"
632
+ r"\[the next page is\s+[\d,]+\s*\]\s*$|"
633
+ r"service\s+\d+\s+[\d,]+\s*$|"
634
+ r"\[act\s+\d+\s+of\s+\d{4}\s+wef\s+[\d/]+\]\s*$|"
635
+ r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})\s+s[eé]rie\s*-\s*n[uú]mero\s+\d+(?:\s+(?:[a-zç]+-feira|s[aá]bado|domingo),?\s*\d{1,2}\s+de\s*[a-zç]+\s+de\s+\d{4})?\s*$|"
636
+ r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})\s*-?\s*s[eé]rie\b.*\d.*|"
637
+ r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})s[eé]rie\b.*\d.*|"
638
+ r"\d+\s+(?:[a-zç]+-feira|s[aá]bado|domingo),?\s+\d{1,2}\s+de\s+[a-zç]+\s+de\s+\d{4}(?:\s+p[aá]gina\s+\d+)?\s*$|"
639
+ r"s[eé]rie\s+[ivx]+\s*,\s*nr\.\s*\d+\b.{0,80}p[aá]gina\s+\d+\s*$|"
640
+ r"(?:[a-zç]+-feira|s[aá]bado|domingo),?\s+\d{1,2}\s+de\s+[a-zç]+\s+de\s+\d{4}\s+s[eé]rie\s+[ivx]+\s*,\s*nr\.\s*\d+\s*$|"
641
+ r"\d+\s*[\(\)]+\s*مذكرة تفسيرية\b.*|"
642
+ r"-\s*\d+\s*-\s*\).*$|"
643
+ r".*constituteproject\.org.*|"
644
+ r"pdf generated\s*:.*|"
645
+ r"[a-z][a-z]+(?:\s+[a-z][a-z]+){0,3}\s+(?:19|20)\d{2}\s+page\s+\d+\s*$|"
646
+ r"الصفحة\s*\.?\s*[0-9٠-٩]+\s*$|"
647
+ r"\[state/territory\]\s*$|"
648
+ r"direction g[eé]n[eé]rale adjointe des imp[oô]ts\s*$|"
649
+ r"et des domaines\s*$|"
650
+ r"rio:\s*\d+\s*$|"
651
+ r"#+\s*journal officiel\b.*|"
652
+ r"journal officiel\s*-\s*banque des?\s*donn[eé]es juridiques\b.*|"
653
+ r"(?!.*\b(?:publie|publi[eé]|shall|entre)\b)journal officiel (?:de la r[eé]publique|du faso)\b.{0,50}$|"
654
+ r"\[(?:\.{3}|…)\]\s*$|"
655
+ r"bsd:\s*\d+\s*$|"
656
+ r"\d{1,2}\.?\s+(?:gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre)\s*$|"
657
+ r"(?-i:(?:[A-Z][A-Za-z]+\s+){1,12}(?:Act|Law|Code),?\s+(?:19|20)\d{2}(?:\s+(?:19|20)\d{2})?\s+nr\.\s*\d+\s+[A-Z]\s+\d+\s*$)|"
658
+ r"(?-i:^[A-Z]\s+\d{1,4}\s+(?:19|20)\d{2}\s+nr\.\s*\d+\s+(?:[A-Z][A-Za-z]+\s+){1,12}(?:Act|Law|Code),?\s+(?:19|20)\d{2}\s*$)|"
659
+ r"printed on the orders? of government\s*\.?\s*$|"
660
+ r".*(?<![A-Za-z])(?:printed|thinted)\b.{0,80}government printing\b.*|"
661
+ r"to be purchased at the govt\.?\s*publications bureau\b.*|"
662
+ r"b\.?\s*l\.?\s*r\.?\s*o\.?\s*\d+\s*/\s*\d{4}\s*$|"
663
+ r"pages authorised\s*$|"
664
+ r"(?:current\s+)?authorised pages\s*$|"
665
+ r"\(inclusive\)\s*by\s+lro\.?\s*$|"
666
+ r"(?-i:(?:[A-Z][a-z]+(?:\s+|$)){1,8}(?:Malawi|Zambia|Kenya|Uganda|Ghana|Namibia|Botswana|Lesotho|Eswatini|Rwanda|Tanzania|Nigeria|Zimbabwe|Mauritius|Seychelles|Liberia|Gambia)\s*$)|"
667
+ r"code\s+\S+(?:\s+\S+){0,6}\s+\d{1,3}/\d{2,3}\s*$|"
668
+ r"index\s*$|"
669
+ r"ministry/program(?:me)?/sub(?:head|program(?:me)?)\s+page\s*$|"
670
+ r"page\s+\d{1,3}\s*/\s*\d{1,3}\s*$|"
671
+ r"\[?\s*printed by authority of the\s*$|"
672
+ r"printed in [a-z][a-z .'-]{0,40}by the government printer\s*$|"
673
+ r"[\w.+-]+@[\w.-]+\.[a-z]{2,}\s+www\.\S+\s*$|"
674
+ r"secr[eé]tariat g[eé]n[eé]ral du gouvernement\s+www\.\S+\s*$|"
675
+ r"site:\s*(?:https?://|www\.)\S+\s*$|"
676
+ r"justice sector support program\s*\(jssp\).*|"
677
+ r"serial number:\s*\d+\b.*|"
678
+ r"copyright government of [a-z]+(?:\s+[a-z]+){0,3}\s*$|"
679
+ r"this page was intentionally left blank\.?\s*$|"
680
+ r"this is page \d+ of \d+\s+pages? of the above table\.?\s*$|"
681
+ r"new provisions(?: in the schedule)? are printed in italics\.?\s*$|"
682
+ r"go to top page(?: next chapter)?\s*$|"
683
+ r"(?:\d{4}\s+)?parliamentary series\s+(?:nr\.|no\.?)\s*\d+\s*$|"
684
+ r"try reloading the page or downloading the pdf\.?\s*$|"
685
+ r"reload page\s*$|"
686
+ r"uploaded by:\s*https?://\S+\s*$|"
687
+ r"t[eé]l[eé]charg[eé] sur www\.\S+\s*$|"
688
+ r"ibirimo/summary/sommaire\b.*|"
689
+ r"website:\s*(?:https?://|www\.)\S+\s*$|"
690
+ r"www\.\S+\s+[\w.+-]+@[\w.-]+\s*$|"
691
+ r"gazette order page\.?\s*$|"
692
+ r"(?:lexis finder|esilec profesional)\s*-\s*www\.\S+\s*$|"
693
+ r"official gazette\s+(?:nr\.|no\.?)\s*(?:special(?:\s+bis)?|\d+\s*bis)\s+of\b.*|"
694
+ r"s[eé]rie\s+[ivxlcdm]+\s*,\s*nr\.\s*\S+(?:\s+[A-Za-z0-9]+)?\s*$|"
695
+ r"unofficial translat(?:ed|ion)\b.*|"
696
+ r"\(?\d[\d\s().-]{6,}\)?\s*\|\s*(?:https?://|www\.)\S+\s*$|"
697
+ r"volume:\s*\d+\s+issue no:\s*\d+\s+government gazette\s*$|"
698
+ r"tonga government gazette supplement\s*$|"
699
+ r"ministry of legal affairs\s+www\.\S+\s*$|"
700
+ r"\d+\s+www\.\S+\s*$|"
701
+ r"www\.\S+\s+\d+\s*/\s*\d+\s*$|"
702
+ r"www\.\S+\s+(?:(?!for\b|is\b|shall\b|the\b)[a-z][a-z .'-]{0,50})$|"
703
+ r".*/type/page>{2,}.*|"
704
+ r"subject\.\s*reference\.\s*page\.?\s*$|"
705
+ r"name reference page no\.?\s*$|"
706
+ r"sl\s*#\s*law\s*#\s*legislation commencement gazette\s*$|"
707
+ r"gn\s*=\s*gazette notice\b.*|"
708
+ r"de blank page\b.*|"
709
+ r"printed and published by the ministry of justice\b.*|"
710
+ r"rarotonga,\s*cook islands:\s*printed under the authority\b.*|"
711
+ r"e-?mail\s*:\s*\S+@\S+.*(?:site web|www\.)\S+.*|"
712
+ r"διεύθυνση στο διαδίκτυο\s*\(url\)\s*:\s*https?://\S+.*|"
713
+ r"spletna stran:\s*www\.\S+\s*$|"
714
+ r"copyright\s*$|"
715
+ r"copyright and designs act\s+\d{4}\s*$|"
716
+ r"copyright act\s+\d{4}\s*$|"
717
+ r"powered by tcpdf\b.*|"
718
+ r"pour l'acquisition de votre abonnement\b.*|"
719
+ r"a\s*bonnement au journal officiel\b.*|"
720
+ r"[eé]dit[eé] par la direction de l'[eé]dition du journal officiel\b.*|"
721
+ r"\[the inclusion of this page is authori[sz]ed by\b.*|"
722
+ r"ins\s*=\s*inserted\b.*|"
723
+ r"[a-z]{2,8}\s*=\s*gazette\b.*|"
724
+ r"site web\s*:\s*www\.\S+\s*$|"
725
+ r"web\s*sites?\s*:?\s*-?\s*www\.\S+\s*$|"
726
+ r".*www\.documents\.gov\.lk\s*$|"
727
+ r"τηλ\.?:?\s*[\d\s,]+φαξ:?\s*[\d\s]+\s*-\s*www\.\S+\s*$|"
728
+ r"das dokument ist einsehbar unter:\s*www\.\S+\s*$|"
729
+ r"sujet articles page\s*$|"
730
+ r"language is printed on uneven numbered pages\.?\s*$|"
731
+ r".*www\.nbs\.sk\.?\s*$|"
732
+ r"\d{2}-\d{4,6}\s+\d{1,3}/\d{1,3}\s*$|"
733
+ r"\d{1,3}/\d{1,3}\s+\d{2}-\d{4,6}\s*$|"
734
+ r"[as]/(?:res|prst)/\d+\s*\(\d{4}\)\s*$|"
735
+ r"ab\s+\d{4},\s*nr\.\s*\d+\s*$|"
736
+ r"grondslag\s*:\s*[.\-–\s]*$|"
737
+ r"رقم الهاتف\s*:.*|"
738
+ r"\+[\u0600-\u06FF]{1,2}\s*$|"
739
+ r"(?-i:(?!.*\b(?:est|sont|doit|shall)\b)(?!.*\b[a-z]{4,}\b).*\bImprimerie\s+[A-Z].*$)|"
740
+ r"(?-i:(?!.*\b(?:shall|is|are|means|under|must)\b).{8,120}\(Chapter\s+\d+(?::\d+)?\)\s+[A-Z][a-z]+\s*$)|"
741
+ r"(?-i:(?!.*\b(?:ACT|LAW|CODE|DECREE|ORDINANCE|CHAPTER|ARTICLE|SECTION|TITLE|PART|SCHEDULE|GENERAL|PROVISIONS|SHORT|INTERPRETATION|PRELIMINARY|AMENDMENT|REPEAL|COMMENCEMENT|DEFINITIONS|REGULATIONS|RULES|ORDER|APPENDIX)\b)(?:[A-ZÁÉÍÓÚÜÑ]{2,}(?:\s+|$)){4,10}\d{1,3}\s*$)|"
742
+ r"(?-i:(?!.*\b(?:ACT|LAW|CODE|DECREE|ORDINANCE|CHAPTER|ARTICLE|SECTION|TITLE|PART|SCHEDULE|GENERAL|PROVISIONS|SHORT|INTERPRETATION|PRELIMINARY|AMENDMENT|REPEAL|COMMENCEMENT|DEFINITIONS|REGULATIONS|RULES|ORDER|APPENDIX)\b)\d{3,4}\s+(?:[A-ZÁÉÍÓÚÜÑ]{3,}(?:\s+|$)){1,3}\s*$)|"
743
+ r"\[\d{1,4}\]?\s*$|"
744
+ r"หน.?า\s+[0-9๐-๙]+\s*$|"
745
+ r"(?:home|blog|contact us|cookie|accueil|startseite|"
746
+ r"página inicial|página principal|επικοινωνία|αρχική)\s*$"
747
+ r")"
748
+ )
749
+ _CHROME_INLINE_RE = re.compile(
750
+ r"(?i)skip to (?:main )?content|all rights reserved|click here|"
751
+ r"légimonaco"
752
+ )
753
+ _JA_ART_RE = re.compile(r"第\s*[0-9一二三四五六七八九十百]+\s*[条條]")
754
+ _CIRCLED_ART_RE = re.compile(r"[①-⑳⑴-⒇❶-❿⓫-⓴]")
755
+ _CJK_ENUM_RE = re.compile(r"(?m)^[ \t]*[一二三四五六七八九十百]+、")
756
+ _CJK_PAREN_RE = re.compile(r"(?m)^[ \t]*[((][一二三四五六七八九十百]+[))]")
757
+ _CJK_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[0-90-9]+、")
758
+ _KO_GA_RE = re.compile(r"(?m)^[ \t]*[가나다라마바사아자차카타파하]\.")
759
+ _JA_KATA_ENUM_RE = re.compile(r"(?m)^[ \t]*[アイウエオカキクケコ]、")
760
+ _HANGUL_GA = "가나다라마바사아자차카타파하"
761
+ _KATA_ENUM = "アイウエオカキクケコ"
762
+ _AR_ABJAD_INDEX = {
763
+ "أ": "1", "ا": "1", "ب": "2", "ج": "3", "د": "4", "ه": "5",
764
+ "و": "6", "ز": "7", "ح": "8", "ط": "9", "ي": "10",
765
+ }
766
+ _HE_ALEF = "אבגדהוזחטי"
767
+ _TH_KO = "กขคงจฉชซฌญ"
768
+ _AR_ABJAD_RE = re.compile(r"(?m)^[ \t]*[(\[]?[أابجدهوزحطي][)\]]?\s*[-.)]")
769
+ _HE_ALEF_RE = re.compile(r"(?m)^[ \t]*[אבגדהוזחטי]\.")
770
+ _HE_PEREK_RE = re.compile(r"(?m)^[ \t]*פרק\s+[א-ת]{1,3}['׳]?")
771
+ _HE_SIMAN_RE = re.compile(r"(?m)^[ \t]*סימן\s+[א-ת]{1,3}['׳]?")
772
+ _HE_HELEK_RE = re.compile(r"(?m)^[ \t]*חלק\s+[א-ת]{1,3}['׳]?")
773
+ _HE_TOS_RE = re.compile(
774
+ r"(?m)^[ \t]*תוספת\s+(?:ראשונה|שנייה|שניה|שלישית|רביעית|חמישית|שישית|[א-ת]['׳]?|[0-9]+)"
775
+ )
776
+ _HE_TAKANA_RE = re.compile(r"(?m)^[ \t]*תקנה\s+[0-9]+")
777
+ _AR_ANNEX_RE = re.compile(r"(?m)^[ \t]*ملحق(?:\s*رقم)?\s*[0-9٠-٩()]+")
778
+ _AR_BAB_RE = re.compile(
779
+ r"(?m)^[ \t]*الباب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
780
+ )
781
+ _AR_FASL_RE = re.compile(
782
+ r"(?m)^[ \t]*الفصل\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
783
+ )
784
+ _AR_KITAB_RE = re.compile(
785
+ r"(?m)^[ \t]*الكتاب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
786
+ )
787
+ _AR_FARA_RE = re.compile(
788
+ r"(?m)^[ \t]*الفرع\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
789
  )
790
+ _FA_BAND_RE = re.compile(r"بند\s*[0-9۰-۹]+")
791
+ _CJK_ZHANG_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*章")
792
+ _KO_JANG_RE = re.compile(r"제\s*[0-9]+\s*장")
793
+ _TA_ART_RE = re.compile(r"பிரிவு\s*[0-9௦-௯]+")
794
+ _TE_ART_RE = re.compile(r"ప్రకరణ(?:ము)?\s*[0-9౦-౯]+")
795
+ _KN_ART_RE = re.compile(r"ಪ್ರಕರಣ\s*[0-9೦-೯]+")
796
+ _GU_ART_RE = re.compile(r"કલમ\s*[0-9૦-૯]+")
797
+ _PA_ART_RE = re.compile(r"ਧਾਰਾ\s*[0-9੦-੯]+")
798
+ _ML_ART_RE = re.compile(r"വകുപ്പ്\s*[0-9൦-൯]+")
799
+ _CJK_BIAN_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[编編]")
800
+ _KO_PYEON_RE = re.compile(r"제\s*[0-9]+\s*편")
801
+ _TH_LAK_RE = re.compile(r"(?m)^[ \t]*ลักษณะ\s*[0-9๐-๙]+")
802
+ _KM_CHAP_RE = re.compile(r"ជំពូក\s*[0-9០-៩]+")
803
+ _LO_PART_RE = re.compile(r"ພາກ\s*[0-9໐-໙]+")
804
+ _MY_CHAP_RE = re.compile(r"အခန်း\s*[0-9၀-၉]+")
805
+ _KA_CHAP_RE = re.compile(r"თავი\s+[IVXLCDM0-9]+")
806
+ _HY_CHAP_RE = re.compile(r"Գլուխ\s+[IVXLCDM0-9]+", re.IGNORECASE)
807
+ _AM_CHAP_RE = re.compile(r"ምዕራፍ\s*[0-9፩-፻]+")
808
+ _HI_CHAP_RE = re.compile(r"अध्याय\s*[0-9०-९]+")
809
+ _BN_CHAP_RE = re.compile(r"অধ্যায়\s*[0-9০-৯]+")
810
+ _UR_CHAP_RE = re.compile(r"باب\s*[0-9۰-۹]+")
811
+ _FA_FASL_RE = re.compile(r"فصل\s*[0-9۰-۹]+")
812
+ _NE_CHAP_RE = re.compile(r"परिच्छेद\s*[0-9०-९]+")
813
+ _CJK_JIE_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[节節]")
814
+ _KO_JEOL_RE = re.compile(r"제\s*[0-9]+\s*절")
815
+ _TH_TON_RE = re.compile(r"(?m)^[ \t]*ตอน\s*[0-9๐-๙]+")
816
+ _SR_PART_RE = re.compile(r"(?:Одељак|ОДЕЉАК)\s+[IVXLCDM0-9]+", re.IGNORECASE)
817
+ _RU_TITLE_RE = re.compile(
818
+ r"(?:Раздел|РАЗДЕЛ|Розділ|РОЗДІЛ|Раздзел|РАЗДЗЕЛ)\s+[IVXLCDM0-9]+",
819
+ re.IGNORECASE,
820
+ )
821
+ _RU_CHAP_RE = re.compile(r"(?:Глава|ГЛАВА)\s+[IVXLCDM0-9]+", re.IGNORECASE)
822
+ _TH_KO_RE = re.compile(r"(?m)^[ \t]*[กขคงจฉชซฌญ]\.")
823
+ _HI_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[०-९]+\s*[.।]")
824
+ _BN_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[০-৯]+\s*[.।]")
825
+ _CYR_AB = "абвгдежзийк"
826
+ _EL_AB = "αβγδεζηθικ"
827
+ _KA_AB = "აბგდევზთიკლ"
828
+ _HY_AB = "աբգդեզէըթժ"
829
+ _CYR_AB_RE = re.compile(r"(?im)^[ \t]*[абвгдежзийк]\s*[).]")
830
+ _EL_AB_RE = re.compile(r"(?im)^[ \t]*[αβγδεζηθικ]\s*[).]")
831
+ _KA_AB_RE = re.compile(r"(?m)^[ \t]*[აბგდევზთიკლ]\s*[).]")
832
+ _HY_AB_RE = re.compile(r"(?m)^[ \t]*[աբգդեզէըթժ]\s*[).]")
833
+ _MARK_AFTER = r"(?:\s+|(?=[^\x00-\x7f]))"
834
+ _LATIN_LETTER_RE = re.compile(
835
+ r"(?m)^[ \t]*(?:\(\s*(?P<paren>[a-z])\s*\)|(?P<bare>[a-z])\)|"
836
+ r"(?P<roman>viii|iii|vii|ii|iv|ix|vi|i|v|x)\.)"
837
+ + _MARK_AFTER
838
+ )
839
+ _BULLET_RE = re.compile(r"(?m)^[ \t]*[•·●‣⁃*#]\s+")
840
+ _DASH_NUM_RE = re.compile(r"(?m)^[ \t]*-\s*(?P<bn>[0-9]{1,3})\s+(?=[^\W\d_])")
841
+ _LATIN_NUM_LIST_RE = re.compile(
842
+ r"(?m)^[ \t]*(?:"
843
+ r"\(\s*(?P<nparen>[0-9]{1,3})\s*\)|"
844
+ r"(?P<nclose>[0-9]{1,3})\)|"
845
+ r"(?P<nord>[0-9]{1,3})[º°o]|"
846
+ r"(?P<ndot>[0-9]{1,3})\.-|"
847
+ r"(?P<ncolon>[0-9]{1,3}):|"
848
+ r"(?P<ndash>[0-9]{1,3})-|"
849
+ r"(?P<dbl>([a-z])\2)\)"
850
+ r")"
851
+ + _MARK_AFTER
852
+ )
853
+ _ROMAN_LOWER = {
854
+ "i": "1", "ii": "2", "iii": "3", "iv": "4", "x": "10",
855
+ "v": "5", "vi": "6", "vii": "7", "viii": "8", "ix": "9",
856
+ }
857
+ _JA_KOU_RE = re.compile(r"第[0-9一二三四五六七八九十百]+項")
858
+ _ZH_KUAN_RE = re.compile(r"第[一二三四五六七八九十百千万零〇两0-9]+款")
859
+ _KO_ART_RE = re.compile(r"제\s*[0-9]+\s*조")
860
+ _KO_HANG_RE = re.compile(r"제\s*[0-9]+\s*항")
861
+ _KO_HO_RE = re.compile(r"제\s*[0-9]+\s*호")
862
+ _TH_PARA_RE = re.compile(r"วรรค\s*[0-9๐-๙]+")
863
+ _TH_KHO_RE = re.compile(r"(?m)^[ \t]*ข้อ\s*[0-9๐-๙]+")
864
+ _TH_HUAT_RE = re.compile(r"(?m)^[ \t]*หมวด\s*[0-9๐-๙]+")
865
+ _FA_TAB_RE = re.compile(r"تبصره\s*[0-9۰-۹]+")
866
+ _HE_PARA_RE = re.compile(r"פסקה\s*[0-9]+")
867
+ _AR_PARA_RE = re.compile(r"الفقرة\s*[0-9٠-٩]+")
868
+ _AR_QARAR_RE = re.compile(r"قرار(?:\s*رقم)?\s*[0-9٠-٩]+")
869
+ _AR_DECREE_RE = re.compile(r"(?:مرسوم|أمر)(?:\s*رقم)?\s*[0-9٠-٩]+")
870
+ _RU_INST_RE = re.compile(r"(?:Указ|Постановление|Приказ)\s+[0-9]+", re.IGNORECASE)
871
+ _KO_RANGE_RE = re.compile(
872
+ r"제\s*[0-9]+\s*조\s*부터\s*제\s*[0-9]+\s*조(?:까지)?"
873
+ )
874
+ _HE_ART_RE = re.compile(
875
+ r"(?:סעיף\s*(?:[0-9]+|(?!קטן)[א-ת]{1,3}['׳]?)|\.\s*[0-9]+(?=[\u0590-\u05FF]))"
876
+ )
877
+ _HE_KATAN_RE = re.compile(r"סעיף\s+קטן\s*\(?\s*[א-ת]'?\)?")
878
+ _TH_ART_RE = re.compile(r"มาตรา\s*[0-9๐-๙]+")
879
+ _HI_ART_RE = re.compile(r"(?:धारा|ধারা)\s*[0-9০-৯]+")
880
+ _RU_ART_RE = re.compile(r"(?:Статья|СТАТЬЯ|Стаття|СТАТТЯ)\s+[0-9]+(?:-[0-9]+)?", re.IGNORECASE)
881
+ _KA_ART_RE = re.compile(r"მუხლი\s*[0-9]+")
882
+ _HY_ART_RE = re.compile(r"Հոդված\s*[0-9]+", re.IGNORECASE)
883
+ _AM_ART_RE = re.compile(r"አንቀጽ\s*[0-9፩-፻]+")
884
+ _BN_ART_RE = re.compile(r"ধারা\s*[0-9০-৯]+")
885
+ _LO_ART_RE = re.compile(r"ມາດຕາ\s*[0-9໐-໙]+")
886
+ _KM_ART_RE = re.compile(r"មាត្រា\s*[0-9០-៩]+")
887
+ _MY_ART_RE = re.compile(r"ပုဒ်မ\s*[0-9၀-၉]+")
888
+ _UZ_ART_RE = re.compile(r"[0-9]+\s*-\s*(?:модда|modda)", re.IGNORECASE)
889
+ _MN_ART_RE = re.compile(r"[0-9]+\s*(?:дүгээр|дугаар)\s*зүйл", re.IGNORECASE)
890
+ _KK_ART_RE = re.compile(r"[0-9]+\s*-?\s*бап", re.IGNORECASE)
891
+ _NE_ART_RE = re.compile(r"दफा\s*[0-9०-९]+")
892
+ _TI_ART_RE = re.compile(r"ዓንቀጽ\s*[0-9፩-፻]+")
893
+ _BO_ART_RE = re.compile(r"དོན་ཚན་\s*[0-9༠-༩]+")
894
+ _UG_ART_RE = re.compile(r"ماددا\s*[0-9۰-۹]+")
895
+ _AR_POINT_RE = re.compile(r"(?m)^[ \t]*(?:أولا|ثانيا|ثالثا|رابعا|خامسا)\s*[:/]")
896
+ _AR_POINT_NUM = (("أولا", "1"), ("ثانيا", "2"), ("ثالثا", "3"), ("رابعا", "4"), ("خامسا", "5"))
897
+ _SI_ART_RE = re.compile(r"වගන්තිය\s*[0-9෦-෯]+")
898
+ _UR_ART_RE = re.compile(r"دفعہ\s*[0-9۰-۹]+")
899
+ _KY_ART_RE = re.compile(r"[0-9]+\s*-?\s*берене", re.IGNORECASE)
900
+ _BE_ART_RE = re.compile(r"Артыкул\s*[0-9]+", re.IGNORECASE)
901
+
902
+ # "A R T Í C U L O 86" / "C A P I T U L O I" → ARTÍCULO 86 / CAPITULO I
903
+ _SPACED_KEYWORD_RE = re.compile(
904
+ r"(?iu)\b((?:[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ]\s+){3,}"
905
+ r"[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ])\b"
906
+ r"(?=\s*[.:\-–—]?\s*[0-9IVXLCDM])"
907
+ )
908
+
909
+
910
+ def _squeeze_spaced_keyword(match: re.Match[str]) -> str:
911
+ return re.sub(r"\s+", "", match.group(1))
912
+
913
+
914
+ _ZW_RE = re.compile(
915
+ r"[\ufeff\u200b\u200c\u200d\u00ad\u2060\u200e\u200f\u202a-\u202e\u2066-\u2069]"
916
+ )
917
+ # Tashkeel, niqqud, Latin combining. Keep Thai/Lao/Khmer/Myanmar/Indic Mn.
918
+ _STRIP_MARKS_RE = re.compile(
919
+ "["
920
+ "\u0300-\u036f"
921
+ "\u0483-\u0489"
922
+ "\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7"
923
+ "\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06ed"
924
+ "\u08d3-\u08e1\u08e3-\u08ff"
925
+ "]"
926
+ )
927
+ _SCRIPT_CITE_TAIL_RE = re.compile(
928
+ r"(?i)^\s*(?:"
929
+ r"من\s*(?:الدستور|القانون|الأمر|المرسوم|القرار)|"
930
+ r"của\s+luật|"
931
+ r"של\s+(?:חוק|פקודה)"
932
+ r")"
933
+ )
934
+
935
+ # UTF-8 read as Latin-1: § (U+00C2 U+00A7) is §, é is é. Âmbito stays.
936
+ _LATIN1_UTF8_RE = re.compile(r"[\u00c2\u00c3][\u0080-\u00bf]")
937
+
938
+
939
+ def _repair_latin1_utf8(text: str) -> str:
940
+ if "\u00c2" not in text and "\u00c3" not in text:
941
+ return text
942
+
943
+ def repl(match: re.Match[str]) -> str:
944
+ try:
945
+ return match.group(0).encode("latin-1").decode("utf-8")
946
+ except UnicodeDecodeError:
947
+ return match.group(0)
948
+
949
+ return _LATIN1_UTF8_RE.sub(repl, text)
950
+
951
+
952
+ # Script-tagged gazettes that still publish English Article/Section translations.
953
+ _LATIN_FALLBACK_LANGS = frozenset(
954
+ {"ka", "km", "hy", "am", "lo", "my", "si", "th", "he", "ne", "fa"}
955
  )
956
 
957
 
 
1004
  return text.strip()
1005
 
1006
 
1007
+ _ROMAN_PAGE_RE = re.compile(
1008
+ r"(?i)(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3}|xiv|xv)$"
1009
+ )
1010
+
1011
+
1012
+ def _is_roman_page_line(line: str, nxt: str) -> bool:
1013
+ """A lone i/ii/iii between blocks is a page stamp, not a list item."""
1014
+ if _ROMAN_PAGE_RE.fullmatch(line.strip()) is None:
1015
+ return False
1016
+ nxt = nxt.strip()
1017
+ if not nxt:
1018
+ return True
1019
+ return not (nxt[:1].islower() or nxt.startswith("("))
1020
+
1021
+
1022
+ def _is_page_num_line(line: str) -> bool:
1023
+ token = line.strip()
1024
+ if 1 <= len(token) <= 4 and all(unicodedata.category(ch) == "Nd" for ch in token):
1025
+ return True
1026
+ # "1/3" between paragraphs is page 1 of 3, not a section.
1027
+ parts = token.split("/")
1028
+ if len(parts) == 2 and all(part.isascii() and part.isdigit() for part in parts):
1029
+ left, right = int(parts[0]), int(parts[1])
1030
+ return 1 <= left <= right <= 30
1031
+ return False
1032
+
1033
+
1034
+ def _is_facing_page_line(line: str) -> bool:
1035
+ """'736 737' between blocks is a two-page spread, not a citation."""
1036
+ parts = line.split()
1037
+ if len(parts) != 2 or not all(part.isascii() and part.isdigit() for part in parts):
1038
+ return False
1039
+ left, right = int(parts[0]), int(parts[1])
1040
+ return 100 <= left and right == left + 1 and right <= 9999
1041
+
1042
+
1043
+ _PAGE_OF_RE = re.compile(r"(?i)(\d{1,2})\s+of\s+(\d{1,2})")
1044
+
1045
+
1046
+ def _is_page_of_line(line: str) -> bool:
1047
+ """'3 of 5' between blocks is a page count, not a citation."""
1048
+ match = _PAGE_OF_RE.fullmatch(line.strip())
1049
+ if match is None:
1050
+ return False
1051
+ left, right = int(match.group(1)), int(match.group(2))
1052
+ return 1 <= left <= right <= 30
1053
+
1054
+
1055
+ def learned_patterns_path() -> Path:
1056
+ override = os.environ.get("COUNTRY_LAWS_LEARNED_PATTERNS")
1057
+ if override:
1058
+ return Path(override)
1059
+ return Path(__file__).resolve().parent / "data" / "learned_line_patterns.json"
1060
+
1061
+
1062
+ _LEARNED: tuple[float, re.Pattern[str] | None] | None = None
1063
+
1064
+
1065
+ def learned_line_pattern() -> re.Pattern[str] | None:
1066
+ """Whole-line rules added by the normalize loop. Compiled once per file change."""
1067
+ global _LEARNED
1068
+ path = learned_patterns_path()
1069
+ if not path.is_file():
1070
+ return None
1071
+ mtime = path.stat().st_mtime
1072
+ if _LEARNED is not None and _LEARNED[0] == mtime:
1073
+ return _LEARNED[1]
1074
+ try:
1075
+ payload = json.loads(path.read_text(encoding="utf-8"))
1076
+ except (OSError, json.JSONDecodeError):
1077
+ _LEARNED = (mtime, None)
1078
+ return None
1079
+ parts: list[str] = []
1080
+ for item in payload.get("patterns") or []:
1081
+ if not isinstance(item, str):
1082
+ continue
1083
+ try:
1084
+ re.compile(item, re.IGNORECASE)
1085
+ except re.error:
1086
+ continue
1087
+ parts.append(item)
1088
+ compiled = re.compile("|".join(f"(?:{part})" for part in parts), re.IGNORECASE) if parts else None
1089
+ _LEARNED = (mtime, compiled)
1090
+ return compiled
1091
+
1092
+
1093
+ def strip_chrome_lines(text: str) -> str:
1094
+ """Drop gazette-site chrome lines. Never invents replacement legal text."""
1095
+ if not text:
1096
+ return ""
1097
+ raw_lines = text.splitlines()
1098
+ multi = sum(1 for ln in raw_lines if ln.strip()) > 1
1099
+ learned = learned_line_pattern()
1100
+ kept = []
1101
+ for idx, ln in enumerate(raw_lines):
1102
+ stripped = ln.strip()
1103
+ if not stripped:
1104
+ continue
1105
+ if _CHROME_LINE_RE.match(stripped) or _CHROME_INLINE_RE.search(ln):
1106
+ continue
1107
+ if learned is not None and learned.match(stripped):
1108
+ continue
1109
+ # A lone "2" or "10" is an article number. The same token inside a
1110
+ # longer page is a page stamp.
1111
+ if multi and (
1112
+ _is_page_num_line(stripped)
1113
+ or _is_facing_page_line(stripped)
1114
+ or _is_page_of_line(stripped)
1115
+ ):
1116
+ continue
1117
+ nxt = ""
1118
+ for later in raw_lines[idx + 1 :]:
1119
+ if later.strip():
1120
+ nxt = later
1121
+ break
1122
+ if multi and _is_roman_page_line(stripped, nxt):
1123
+ continue
1124
+ kept.append(ln)
1125
+ return "\n".join(kept).strip()
1126
+
1127
+
1128
+ _HYPHEN_BREAK_RE = re.compile(r"(?<=[^\W\d_])-[ \t]*\n+[ \t]*([^\W\d_])")
1129
+
1130
+
1131
+ def _join_hyphen_breaks(text: str) -> str:
1132
+ """Join a hyphenated word split across lines. Leave a following capital header."""
1133
+
1134
+ def repl(match: re.Match[str]) -> str:
1135
+ nxt = match.group(1)
1136
+ if nxt.isupper():
1137
+ return match.group(0)
1138
+ return nxt
1139
+
1140
+ return _HYPHEN_BREAK_RE.sub(repl, text)
1141
+
1142
+
1143
  def normalize_legal_text(value: Any) -> str:
1144
  """NFKC + HTML strip. Keeps newlines so heading detection still works."""
1145
  if value is None:
1146
  return ""
1147
+ text = unicodedata.normalize("NFKC", str(value)).replace("\x00", "")
1148
+ if text.startswith("ÿþ") or text.startswith("þÿ"):
1149
+ text = text[2:]
1150
+ text = re.sub(r"[\x00-\x08\x0b\x0e-\x1f\x7f]", " ", text)
1151
+ text = text.replace("\ufffd", " ")
1152
+ text = re.sub(r"[\ue000-\uf8ff]", "", text)
1153
+ text = _repair_latin1_utf8(text)
1154
+ text = re.sub(r"\(cid:\d+\)", " ", text)
1155
+ text = _ZW_RE.sub("", text).replace("ـ", "")
1156
+ text = _STRIP_MARKS_RE.sub("", text)
1157
+ text = re.sub(r"[\u2010-\u2015\u2212\ufe58\ufe63\uff0d]", "-", text)
1158
+ text = re.sub(r"[\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]", " ", text)
1159
+ text = text.replace("\u2028", "\n").replace("\u2029", "\n").replace("\f", "\n")
1160
+ text = _join_hyphen_breaks(text)
1161
+ text = _NUMERO_FOLD_RE.sub("nr. ", text)
1162
+ text = re.sub(r"المادة\s*-\s*اختر\s*-\s*", "", text)
1163
+ text = re.sub(r"(?m)^[ \t]*©+\s*", "", text)
1164
+ text = re.sub(r"\b((?:19|20)\d{2}) \1\b", r"\1", text)
1165
+ text = re.sub(r"(?<=[A-Za-z])!+(?=\d)", " ", text)
1166
+ text = re.sub(r":!+", ":", text)
1167
+ text = re.sub(r"(?m)!+\s*$", "", text)
1168
+ text = _SPACED_KEYWORD_RE.sub(_squeeze_spaced_keyword, text)
1169
+ text = re.sub(r"(?s)<!--.*?-->", " ", text)
1170
  text = strip_html(text)
1171
+ text = html_lib.unescape(text).replace("\xa0", " ")
1172
+ text = re.sub(r"_{3,}", " ", text)
1173
+ text = re.sub(r"\.{4,}", " ", text)
1174
+ text = re.sub(r"(?m)^[ \t]*#{1,6}[ \t]+", "", text)
1175
+ text = strip_chrome_lines(text)
1176
  text = text.replace("\xa0", " ")
1177
+ text = re.sub(r"~\$\S{0,16}", " ", text)
1178
+ text = re.sub(r"\*\*([^*]{1,80})\*\*", r"\1", text)
1179
+ text = re.sub(r"__([^_]{1,80})__", r"\1", text)
1180
+ text = re.sub(r"'{3}([^']{1,80})'{3}", r"\1", text)
1181
+ text = re.sub(r"^={2,6}\s*(.+?)\s*={2,6}\s*$", r"\1", text, flags=re.MULTILINE)
1182
  text = re.sub(r"[ \t]+", " ", text)
1183
  text = re.sub(r"\n[ \t]+", "\n", text)
1184
+ text = re.sub(r"[ \t]+\n", "\n", text)
1185
+ text = _join_hyphen_breaks(text)
1186
  text = re.sub(r"\n{3,}", "\n\n", text)
1187
  return text.strip()
1188
 
 
1200
  section_number: str = ""
1201
  subsections: tuple[str, ...] = ()
1202
  hierarchy_path: str = ""
1203
+ char_start: int = 0
1204
+ char_end: int = 0
1205
 
1206
  def to_dict(self) -> dict[str, Any]:
1207
  return {
 
1216
  "section_number": self.section_number,
1217
  "subsections": list(self.subsections),
1218
  "hierarchy_path": self.hierarchy_path,
1219
+ "char_start": self.char_start,
1220
+ "char_end": self.char_end,
1221
  }
1222
 
1223
 
 
1247
  return tuple(seen)
1248
 
1249
 
1250
+ def check_exclusive_cover(text: str, units: list[StructureUnit]) -> bool:
1251
+ """True iff units are contiguous, non-overlapping, and cover *text* exactly."""
1252
+ if not units:
1253
+ return not text
1254
+ ordered = sorted(units, key=lambda u: u.char_start)
1255
+ if ordered[0].char_start != 0 or ordered[-1].char_end != len(text):
1256
+ return False
1257
+ prev = 0
1258
+ for unit in ordered:
1259
+ if unit.char_start != prev or unit.char_end < unit.char_start:
1260
+ return False
1261
+ if text[unit.char_start : unit.char_end] != unit.body:
1262
+ return False
1263
+ prev = unit.char_end
1264
+ return True
 
 
 
 
 
 
 
 
 
 
1265
 
1266
 
1267
+ def _script_regex(language: str):
 
1268
  from .profiles import iso_lang
1269
 
1270
  lang = iso_lang(language)
1271
  if lang in {"zh", "zh-cn", "zh-tw"}:
1272
+ return _ZH_ART_RE
1273
+ if lang == "ar":
1274
+ return _AR_ART_RE
1275
+ if lang == "fa":
1276
+ return _FA_ART_RE
 
 
 
 
1277
  if lang == "ja":
1278
+ return _JA_ART_RE
1279
+ if lang == "ko":
1280
+ return _KO_ART_RE
1281
+ if lang == "he":
1282
+ return _HE_ART_RE
1283
+ if lang == "th":
1284
+ return _TH_ART_RE
1285
+ if lang == "hi":
1286
+ return _HI_ART_RE
1287
+ if lang == "bn":
1288
+ return _BN_ART_RE
1289
+ if lang in {"ru", "uk", "be"}:
1290
+ return _RU_ART_RE
1291
+ if lang == "ka":
1292
+ return _KA_ART_RE
1293
+ if lang == "hy":
1294
+ return _HY_ART_RE
1295
+ if lang == "am":
1296
+ return _AM_ART_RE
1297
+ if lang == "ti":
1298
+ return _TI_ART_RE
1299
+ if lang == "bo":
1300
+ return _BO_ART_RE
1301
+ if lang == "ug":
1302
+ return _UG_ART_RE
1303
+ if lang == "lo":
1304
+ return _LO_ART_RE
1305
+ if lang == "km":
1306
+ return _KM_ART_RE
1307
+ if lang == "my":
1308
+ return _MY_ART_RE
1309
+ if lang == "uz":
1310
+ return _UZ_ART_RE
1311
+ if lang == "mn":
1312
+ return _MN_ART_RE
1313
+ if lang == "kk":
1314
+ return _KK_ART_RE
1315
+ if lang == "ne":
1316
+ return _NE_ART_RE
1317
+ if lang == "si":
1318
+ return _SI_ART_RE
1319
+ if lang == "ta":
1320
+ return _TA_ART_RE
1321
+ if lang == "te":
1322
+ return _TE_ART_RE
1323
+ if lang == "kn":
1324
+ return _KN_ART_RE
1325
+ if lang == "gu":
1326
+ return _GU_ART_RE
1327
+ if lang == "pa":
1328
+ return _PA_ART_RE
1329
+ if lang == "ml":
1330
+ return _ML_ART_RE
1331
+ if lang == "ur":
1332
+ return _UR_ART_RE
1333
+ if lang == "ky":
1334
+ return _KY_ART_RE
1335
+ if lang == "be":
1336
+ return _BE_ART_RE
1337
+ return None
1338
 
1339
 
1340
+ def _detected_script_regexes(text: str, language: str) -> list:
1341
+ found: list = []
1342
+ primary = _script_regex(language)
1343
+ if primary is not None:
1344
+ found.append(primary)
1345
+ if re.search(r"[①-⑳⑴-⒇❶-❿⓫-⓴]", text):
1346
+ found.append(_CIRCLED_ART_RE)
1347
+ if re.search(r"[\u4e00-\u9fff]", text):
1348
+ found.extend((_ZH_ART_RE, _JA_ART_RE, _ZH_KUAN_RE, _JA_KOU_RE, _CJK_ZHANG_RE, _CJK_BIAN_RE, _CJK_JIE_RE, _CJK_ENUM_RE, _CJK_PAREN_RE, _CJK_DIGIT_ENUM_RE))
1349
+ if re.search(r"[\uac00-\ud7af]", text):
1350
+ found.extend((_KO_ART_RE, _KO_HANG_RE, _KO_HO_RE, _KO_GA_RE, _KO_JANG_RE, _KO_PYEON_RE, _KO_JEOL_RE))
1351
+ if re.search(r"[\u30a0-\u30ff]", text):
1352
+ found.append(_JA_KATA_ENUM_RE)
1353
+ if re.search(r"[\u0600-\u06ff]", text):
1354
+ found.extend((
1355
+ _AR_ART_RE, _FA_ART_RE, _FA_TAB_RE, _FA_BAND_RE, _FA_FASL_RE, _AR_PARA_RE, _AR_QARAR_RE, _AR_DECREE_RE,
1356
+ _AR_ABJAD_RE, _AR_ANNEX_RE, _AR_BAB_RE, _AR_FASL_RE, _AR_KITAB_RE, _AR_FARA_RE, _UR_CHAP_RE, _UG_ART_RE, _AR_POINT_RE,
1357
+ ))
1358
+ if re.search(r"[\u0590-\u05ff]", text):
1359
+ found.extend((
1360
+ _HE_ART_RE, _HE_PARA_RE, _HE_ALEF_RE, _HE_PEREK_RE, _HE_SIMAN_RE,
1361
+ _HE_HELEK_RE, _HE_TOS_RE, _HE_TAKANA_RE, _HE_KATAN_RE,
1362
+ ))
1363
+ if re.search(r"[\u0e00-\u0e7f]", text):
1364
+ found.extend((_TH_ART_RE, _TH_PARA_RE, _TH_KO_RE, _TH_KHO_RE, _TH_HUAT_RE, _TH_LAK_RE, _TH_TON_RE))
1365
+ if re.search(r"[\u0900-\u097f]", text):
1366
+ found.extend((_HI_ART_RE, _HI_DIGIT_ENUM_RE, _HI_CHAP_RE, _NE_CHAP_RE))
1367
+ if re.search(r"[\u0980-\u09ff]", text):
1368
+ found.extend((_BN_ART_RE, _BN_DIGIT_ENUM_RE, _BN_CHAP_RE))
1369
+ if re.search(r"[\u0b80-\u0bff]", text):
1370
+ found.append(_TA_ART_RE)
1371
+ if re.search(r"[\u0c00-\u0c7f]", text):
1372
+ found.append(_TE_ART_RE)
1373
+ if re.search(r"[\u0c80-\u0cff]", text):
1374
+ found.append(_KN_ART_RE)
1375
+ if re.search(r"[\u0a80-\u0aff]", text):
1376
+ found.append(_GU_ART_RE)
1377
+ if re.search(r"[\u0a00-\u0a7f]", text):
1378
+ found.append(_PA_ART_RE)
1379
+ if re.search(r"[\u0d00-\u0d7f]", text):
1380
+ found.append(_ML_ART_RE)
1381
+ if re.search(r"[\u0e80-\u0eff]", text):
1382
+ found.extend((_LO_ART_RE, _LO_PART_RE))
1383
+ if re.search(r"[\u1780-\u17ff]", text):
1384
+ found.extend((_KM_ART_RE, _KM_CHAP_RE))
1385
+ if re.search(r"[\u1000-\u109f]", text):
1386
+ found.extend((_MY_ART_RE, _MY_CHAP_RE))
1387
+ if re.search(r"[\u1200-\u137f]", text):
1388
+ found.extend((_AM_ART_RE, _AM_CHAP_RE, _TI_ART_RE))
1389
+ if re.search(r"[\u0f00-\u0fff]", text):
1390
+ found.append(_BO_ART_RE)
1391
+ if re.search(r"[\u10a0-\u10ff]", text):
1392
+ found.extend((_KA_ART_RE, _KA_AB_RE, _KA_CHAP_RE))
1393
+ if re.search(r"[\u0530-\u058f]", text):
1394
+ found.extend((_HY_ART_RE, _HY_AB_RE, _HY_CHAP_RE))
1395
+ if re.search(r"[\u0400-\u04ff]", text):
1396
+ found.extend((_CYR_AB_RE, _RU_TITLE_RE, _RU_CHAP_RE, _SR_PART_RE))
1397
+ if re.search(r"[\u0370-\u03ff]", text):
1398
+ found.append(_EL_AB_RE)
1399
+ if "модда" in text.casefold() or re.search(r"\bmodda\b", text, re.IGNORECASE):
1400
+ found.append(_UZ_ART_RE)
1401
+ if re.search(r"зүйл", text, re.IGNORECASE):
1402
+ found.append(_MN_ART_RE)
1403
+ if re.search(r"бап", text, re.IGNORECASE):
1404
+ found.append(_KK_ART_RE)
1405
+ if "दफा" in text:
1406
+ found.append(_NE_ART_RE)
1407
+ if "परिच्छेद" in text:
1408
+ found.append(_NE_CHAP_RE)
1409
+ if "වගන්තිය" in text:
1410
+ found.append(_SI_ART_RE)
1411
+ if "دفعہ" in text:
1412
+ found.append(_UR_ART_RE)
1413
+ if re.search(r"берене", text, re.IGNORECASE):
1414
+ found.append(_KY_ART_RE)
1415
+ if re.search(r"артыкул", text, re.IGNORECASE):
1416
+ found.append(_BE_ART_RE)
1417
+ if re.search(r"статья|стаття", text, re.IGNORECASE):
1418
+ found.append(_RU_ART_RE)
1419
+ if re.search(r"указ|постановление|приказ", text, re.IGNORECASE):
1420
+ found.append(_RU_INST_RE)
1421
+ # Preserve order, drop duplicate pattern objects.
1422
+ out: list = []
1423
+ seen: set[int] = set()
1424
+ for regex in found:
1425
+ key = id(regex)
1426
+ if key not in seen:
1427
+ seen.add(key)
1428
+ out.append(regex)
1429
+ return out
1430
 
 
 
 
 
 
1431
 
1432
+ def _lexicon_heading_re() -> re.Pattern[str]:
1433
+ """Heading matcher generated from HEADING_LEXICON so new languages are data."""
1434
+ global _LEXICON_HEADING_RE, _LEXICON_KIND
1435
+ if _LEXICON_HEADING_RE is not None:
1436
+ return _LEXICON_HEADING_RE
1437
+ from .profiles import HEADING_LEXICON
1438
+
1439
+ words: list[str] = []
1440
+ kinds: dict[str, str] = {}
1441
+ for token, hits in HEADING_LEXICON.items():
1442
+ token = (token or "").strip()
1443
+ if len(token) < 2:
1444
+ continue
1445
+ kinds_found = [kind for kind, _lang in hits if kind in {"article", "section", "title", "chapter", "part"}]
1446
+ if not kinds_found:
1447
+ continue
1448
+ folded = _latin_fold(token)
1449
+ words.append(folded)
1450
+ kinds[folded.casefold()] = kinds_found[0]
1451
+ words.sort(key=len, reverse=True)
1452
+ escaped = [re.escape(w) for w in words]
1453
+ _LEXICON_HEADING_RE = re.compile(
1454
+ _latin_fold(
1455
+ r"(?im)" + _HEADING_START + r"(?:l['’])?(?P<lex>"
1456
+ + "|".join(escaped)
1457
+ + r")(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*(?P<lex_n>"
1458
+ + _ARTICLE_N
1459
+ + r")\)?"
1460
+ )
1461
+ )
1462
+ _LEXICON_KIND = kinds
1463
+ return _LEXICON_HEADING_RE
1464
+
1465
+
1466
+ def _plausible_cw_number(raw: str) -> bool:
1467
+ """Drop year-like '1902. Amendment' titles from keyword-less numbering."""
1468
+ digits = re.sub(r"\D", "", raw or "")
1469
+ if not digits:
1470
+ return False
1471
+ value = int(digits)
1472
+ if value <= 0 or value > 2000:
1473
+ return False
1474
+ if 1800 <= value <= 2099:
1475
+ return False
1476
+ return True
1477
+
1478
+
1479
+ def _fold_digits_in_number(raw: str) -> str:
1480
+ """Map Nd digits (١, १, ๑, …) to ASCII so retrieval numbers stay decimal."""
1481
+ if not raw:
1482
+ return raw
1483
+ out: list[str] = []
1484
+ changed = False
1485
+ for ch in raw:
1486
+ if unicodedata.category(ch) == "Nd":
1487
+ digit = unicodedata.digit(ch)
1488
+ if digit is not None:
1489
+ mapped = str(digit)
1490
+ out.append(mapped)
1491
+ if mapped != ch:
1492
+ changed = True
1493
+ continue
1494
+ out.append(ch)
1495
+ return "".join(out) if changed else raw
1496
+
1497
+
1498
+ def _unicode_digit_runs(text: str) -> list[str]:
1499
+ """ASCII-fold Nd runs (Thai ๑, Myanmar ၁, Arabic-Indic, …)."""
1500
+ runs: list[str] = []
1501
+ cur: list[str] = []
1502
+ for char in text:
1503
+ if unicodedata.category(char) == "Nd":
1504
+ cur.append(str(unicodedata.digit(char)))
1505
+ elif cur:
1506
+ runs.append("".join(cur))
1507
+ cur = []
1508
+ if cur:
1509
+ runs.append("".join(cur))
1510
+ return runs
1511
+
1512
+
1513
+ _AR_ORDINAL_NUM = (
1514
+ ("الحادية عشرة", "11"),
1515
+ ("الثانية عشرة", "12"),
1516
+ ("الثالثة عشرة", "13"),
1517
+ ("الرابعة عشرة", "14"),
1518
+ ("الخامسة عشرة", "15"),
1519
+ ("السادسة عشرة", "16"),
1520
+ ("��لسابعة عشرة", "17"),
1521
+ ("الثامنة عشرة", "18"),
1522
+ ("التاسعة عشرة", "19"),
1523
+ ("الحادية والعشرون", "21"),
1524
+ ("الثانية والعشرون", "22"),
1525
+ ("الثالثة والعشرون", "23"),
1526
+ ("الرابعة والعشرون", "24"),
1527
+ ("الخامسة والعشرون", "25"),
1528
+ ("السادسة والعشرون", "26"),
1529
+ ("السابعة والعشرون", "27"),
1530
+ ("الثامنة والعشرون", "28"),
1531
+ ("التاسعة والعشرون", "29"),
1532
+ ("العشرون", "20"),
1533
+ ("الأولى", "1"),
1534
+ ("الأولي", "1"),
1535
+ ("األولى", "1"),
1536
+ ("الاولى", "1"),
1537
+ ("الثانية", "2"),
1538
+ ("الثالثة", "3"),
1539
+ ("الرابعة", "4"),
1540
+ ("الخامسة", "5"),
1541
+ ("السادسة", "6"),
1542
+ ("السابعة", "7"),
1543
+ ("الثامنة", "8"),
1544
+ ("التاسعة", "9"),
1545
+ ("العاشرة", "10"),
1546
+ ("الأول", "1"),
1547
+ ("الاول", "1"),
1548
+ ("الثاني", "2"),
1549
+ ("الثالث", "3"),
1550
+ ("الرابع", "4"),
1551
+ ("الخامس", "5"),
1552
+ ("السادس", "6"),
1553
+ ("السابع", "7"),
1554
+ ("الثامن", "8"),
1555
+ ("التاسع", "9"),
1556
+ ("العاشر", "10"),
1557
+ )
1558
+ _HE_VALUES = {
1559
+ "א": 1, "ב": 2, "ג": 3, "ד": 4, "ה": 5, "ו": 6, "ז": 7, "ח": 8, "ט": 9,
1560
+ "י": 10, "כ": 20, "ך": 20, "ל": 30, "מ": 40, "ם": 40, "נ": 50, "ן": 50,
1561
+ "ס": 60, "ע": 70, "פ": 80, "ף": 80, "צ": 90, "ץ": 90, "ק": 100,
1562
+ "ר": 200, "ש": 300, "ת": 400,
1563
+ }
1564
+ _HE_ORDINAL_NUM = (
1565
+ ("ראשונה", "1"),
1566
+ ("שנייה", "2"),
1567
+ ("שניה", "2"),
1568
+ ("שלישית", "3"),
1569
+ ("רביעית", "4"),
1570
+ ("חמישית", "5"),
1571
+ ("שישית", "6"),
1572
+ )
1573
+ _ETH_VALUES = {
1574
+ "፩": 1, "፪": 2, "፫": 3, "፬": 4, "፭": 5, "፮": 6, "፯": 7, "፰": 8, "፱": 9,
1575
+ "፲": 10, "፳": 20, "፴": 30, "፵": 40, "፶": 50, "፷": 60, "፸": 70, "፹": 80, "፺": 90,
1576
+ "፻": 100, "፼": 10000,
1577
+ }
1578
+ _FA_ORDINAL_NUM = (
1579
+ ("دوازدهم", "12"),
1580
+ ("سیزدهم", "13"),
1581
+ ("چهاردهم", "14"),
1582
+ ("پانزدهم", "15"),
1583
+ ("شانزدهم", "16"),
1584
+ ("هفدهم", "17"),
1585
+ ("هجدهم", "18"),
1586
+ ("نوزدهم", "19"),
1587
+ ("یازدهم", "11"),
1588
+ ("بیستم", "20"),
1589
+ ("چهارم", "4"),
1590
+ ("چارم", "4"),
1591
+ ("جارم", "4"),
1592
+ ("پنجم", "5"),
1593
+ ("ششم", "6"),
1594
+ ("هفتم", "7"),
1595
+ ("هشتم", "8"),
1596
+ ("نهم", "9"),
1597
+ ("دهم", "10"),
1598
+ ("سوم", "3"),
1599
+ ("دوم", "2"),
1600
+ ("اولی", "1"),
1601
+ ("اول", "1"),
1602
+ ("نخست", "1"),
1603
+ )
1604
+ _CJK_DIGIT = {
1605
+ "零": 0, "〇": 0, "一": 1, "二": 2, "三": 3, "四": 4,
1606
+ "五": 5, "六": 6, "七": 7, "八": 8, "九": 9,
1607
+ }
1608
+
1609
+
1610
+ def _cjk_numeral_value(text: str) -> str | None:
1611
+ body = re.sub(r"[第条條項款章编編节節之조항호편절、]", "", text)
1612
+ if not body or not all(ch in _CJK_DIGIT or ch == "十" or ch == "百" for ch in body):
1613
+ return None
1614
+ if body == "十":
1615
+ return "10"
1616
+ if body.startswith("十"):
1617
+ return str(10 + _CJK_DIGIT.get(body[1], 0))
1618
+ if "百" in body:
1619
+ left, right = body.split("百", 1)
1620
+ if not left:
1621
+ hundreds = 100
1622
+ elif left in _CJK_DIGIT:
1623
+ hundreds = _CJK_DIGIT[left] * 100
1624
+ else:
1625
+ return None
1626
+ if not right:
1627
+ return str(hundreds)
1628
+ rest = _cjk_numeral_value(right)
1629
+ if rest is None:
1630
+ return None
1631
+ return str(hundreds + int(rest))
1632
+ if "十" in body:
1633
+ left, right = body.split("十", 1)
1634
+ tens = _CJK_DIGIT.get(left, 0) * 10
1635
+ ones = _CJK_DIGIT.get(right, 0) if right else 0
1636
+ return str(tens + ones)
1637
+ if body in _CJK_DIGIT:
1638
+ return str(_CJK_DIGIT[body])
1639
+ return None
1640
+
1641
+
1642
+ def _circled_to_int(char: str) -> str | None:
1643
+ if not char:
1644
+ return None
1645
+ code = ord(char[0])
1646
+ if 0x2460 <= code <= 0x2473:
1647
+ return str(code - 0x2460 + 1)
1648
+ if 0x2474 <= code <= 0x2487:
1649
+ return str(code - 0x2474 + 1)
1650
+ if 0x2488 <= code <= 0x249B:
1651
+ return str(code - 0x2488 + 1)
1652
+ if 0x2776 <= code <= 0x277F:
1653
+ return str(code - 0x2776 + 1)
1654
+ if 0x24EB <= code <= 0x24F4:
1655
+ return str(code - 0x24EB + 11)
1656
+ return None
1657
+
1658
+
1659
+ def _ethiopic_numeral_value(text: str) -> str | None:
1660
+ chars = [ch for ch in text if ch in _ETH_VALUES]
1661
+ if not chars:
1662
+ return None
1663
+ body = "".join(chars)
1664
+ if "፼" in body:
1665
+ left, right = body.split("፼", 1)
1666
+ mul = _ethiopic_numeral_value(left) if left else "1"
1667
+ rest = _ethiopic_numeral_value(right) if right else "0"
1668
+ if mul is None or rest is None:
1669
+ return None
1670
+ return str(int(mul) * 10000 + int(rest))
1671
+ if "፻" in body:
1672
+ left, right = body.split("፻", 1)
1673
+ mul = sum(_ETH_VALUES[ch] for ch in left) if left else 1
1674
+ rest = sum(_ETH_VALUES[ch] for ch in right)
1675
+ return str(mul * 100 + rest)
1676
+ return str(sum(_ETH_VALUES[ch] for ch in chars))
1677
+
1678
+
1679
+ def _hebrew_letter_num(raw: str) -> str | None:
1680
+ """Map פרק א' / תוספת שניה / סעיף יא to decimal. Long Hebrew words stay unmapped."""
1681
+ cleaned = re.sub(r"['׳״\"`]", "", raw)
1682
+ for word, num in _HE_ORDINAL_NUM:
1683
+ if word in cleaned:
1684
+ return num
1685
+ katan = re.search(r"סעיף\s+קטן\s*\(?\s*([א-ת])", cleaned)
1686
+ if katan:
1687
+ ch = katan.group(1)
1688
+ return str(_HE_VALUES[ch]) if ch in _HE_VALUES else ch
1689
+ match = re.search(r"(?:פרק|סימן|חלק|תוספת|סעיף)\s*(?!קטן)([א-ת]{1,3})", cleaned)
1690
+ if not match:
1691
+ return None
1692
+ total = sum(_HE_VALUES.get(ch, 0) for ch in match.group(1))
1693
+ return str(total) if total else None
1694
+
1695
+
1696
+ def _script_hit_kind(regex: re.Pattern[str]) -> str:
1697
+ if regex is _RU_TITLE_RE or regex is _TH_LAK_RE:
1698
+ return "title"
1699
+ if regex in (
1700
+ _HE_PEREK_RE, _AR_BAB_RE, _TH_HUAT_RE, _CJK_ZHANG_RE, _KO_JANG_RE,
1701
+ _RU_CHAP_RE, _KM_CHAP_RE, _MY_CHAP_RE, _KA_CHAP_RE, _HY_CHAP_RE, _AM_CHAP_RE,
1702
+ _HI_CHAP_RE, _BN_CHAP_RE, _UR_CHAP_RE, _FA_FASL_RE, _NE_CHAP_RE,
1703
+ ):
1704
+ return "chapter"
1705
+ if regex in (_HE_HELEK_RE, _AR_KITAB_RE, _CJK_BIAN_RE, _KO_PYEON_RE, _LO_PART_RE, _SR_PART_RE):
1706
+ return "part"
1707
+ if regex in (
1708
+ _HE_SIMAN_RE,
1709
+ _HE_TOS_RE,
1710
+ _HE_TAKANA_RE,
1711
+ _HE_PARA_RE,
1712
+ _HE_KATAN_RE,
1713
+ _AR_ANNEX_RE,
1714
+ _AR_PARA_RE,
1715
+ _AR_FASL_RE,
1716
+ _AR_FARA_RE,
1717
+ _JA_KOU_RE,
1718
+ _ZH_KUAN_RE,
1719
+ _KO_HANG_RE,
1720
+ _KO_HO_RE,
1721
+ _TH_PARA_RE,
1722
+ _TH_KHO_RE,
1723
+ _TH_TON_RE,
1724
+ _FA_TAB_RE,
1725
+ _FA_BAND_RE,
1726
+ _AR_POINT_RE,
1727
+ _CJK_JIE_RE,
1728
+ _KO_JEOL_RE,
1729
+ ):
1730
+ return "section"
1731
+ return "article"
1732
+
1733
+
1734
+ def _script_article_number(raw: str) -> str:
1735
+ stripped = raw.strip()
1736
+ for word, num in _AR_POINT_NUM:
1737
+ if stripped.startswith(word):
1738
+ return num
1739
+ compact = raw.strip().strip("()[] \t\u3001\uff08\uff09.、-–—")
1740
+ circled = _circled_to_int(compact)
1741
+ if circled:
1742
+ return circled
1743
+ if compact and len(compact) <= 3:
1744
+ first = compact[0]
1745
+ if first in _HANGUL_GA:
1746
+ return str(_HANGUL_GA.index(first) + 1)
1747
+ if first in _KATA_ENUM:
1748
+ return str(_KATA_ENUM.index(first) + 1)
1749
+ if first in _AR_ABJAD_INDEX:
1750
+ return _AR_ABJAD_INDEX[first]
1751
+ if first in _HE_ALEF:
1752
+ return str(_HE_ALEF.index(first) + 1)
1753
+ if first in _TH_KO:
1754
+ return str(_TH_KO.index(first) + 1)
1755
+ low = first.casefold()
1756
+ if low in _CYR_AB:
1757
+ return str(_CYR_AB.index(low) + 1)
1758
+ if low in _EL_AB:
1759
+ return str(_EL_AB.index(low) + 1)
1760
+ if first in _KA_AB:
1761
+ return str(_KA_AB.index(first) + 1)
1762
+ if first in _HY_AB:
1763
+ return str(_HY_AB.index(first) + 1)
1764
+ cjk_early = _cjk_numeral_value(compact)
1765
+ if cjk_early:
1766
+ return cjk_early
1767
+ he = _hebrew_letter_num(raw)
1768
+ if he:
1769
+ return he
1770
+ digits = _unicode_digit_runs(raw)
1771
+ if digits:
1772
+ if len(digits) >= 2 and re.search(r"[0-9٠-٩۰-۹]+-[0-9٠-٩۰-۹]+", raw):
1773
+ return "-".join(digits[:2])
1774
+ return digits[0]
1775
+ eth = _ethiopic_numeral_value(raw)
1776
+ if eth:
1777
+ return eth
1778
+ compact = re.sub(r"[\s\u0640]+", "", raw)
1779
+ for word, num in _AR_ORDINAL_NUM + _FA_ORDINAL_NUM:
1780
+ needle = re.sub(r"[\s\u0640]+", "", word)
1781
+ if needle and needle in compact:
1782
+ return num
1783
+ cjk = _cjk_numeral_value(compact)
1784
+ if cjk:
1785
+ return cjk
1786
+ tail = re.search(r"([0-9٠-٩۰-۹]+|[IVXLCDM]{1,8})$", compact)
1787
+ if tail:
1788
+ return tail.group(1)
1789
+ return compact
1790
+
1791
+
1792
+ def _in_range_boilerplate(text: str, start: int) -> bool:
1793
+ for regex in (_KO_RANGE_RE, _CJK_RANGE_RE):
1794
+ for match in regex.finditer(text):
1795
+ if match.start() <= start < match.end():
1796
+ return True
1797
+ return False
1798
+
1799
+
1800
+ def _kind_number_from_heading_match(match: re.Match) -> tuple[str, str]:
1801
+ for name in ("title", "chapter", "part", "article", "section"):
1802
+ if match.group(name):
1803
+ return name, (match.group(f"{name}_n") or "").strip()
1804
+ if match.group("section_sym"):
1805
+ return "section", (match.group("section_sym_n") or "").strip()
1806
+ if match.group("section_pre"):
1807
+ return "section", (match.group("section_pre_n") or "").strip()
1808
+ if match.group("grein"):
1809
+ return "article", (match.group("grein_n") or "").strip()
1810
+ if match.group("straipsnis"):
1811
+ return "article", (match.group("straipsnis_n") or "").strip()
1812
+ if match.group("artikulua"):
1813
+ return "article", (match.group("artikulua_n") or "").strip()
1814
+ if match.group("ledd"):
1815
+ return "section", (match.group("ledd_n") or "").strip()
1816
+ if match.group("kap"):
1817
+ return "chapter", (match.group("kap_n") or "").strip()
1818
+ if match.group("luku"):
1819
+ return "chapter", (match.group("luku_n") or "").strip()
1820
+ if match.group("fejezet"):
1821
+ return "chapter", (match.group("fejezet_n") or "").strip()
1822
+ if match.group("peatukk"):
1823
+ return "chapter", (match.group("peatukk_n") or "").strip()
1824
+ if match.group("skyrius"):
1825
+ return "chapter", (match.group("skyrius_n") or "").strip()
1826
+ if match.group("nodala"):
1827
+ return "chapter", (match.group("nodala_n") or "").strip()
1828
+ if match.group("kafli"):
1829
+ return "chapter", (match.group("kafli_n") or "").strip()
1830
+ if match.group("bob"):
1831
+ return "chapter", (match.group("bob_n") or "").strip()
1832
+ if match.group("tarau"):
1833
+ return "chapter", (match.group("tarau_n") or "").strip()
1834
+ if match.group("bolum"):
1835
+ return "chapter", (match.group("bolum_n") or "").strip()
1836
+ if match.group("modda"):
1837
+ return "article", (match.group("modda_n") or "").strip()
1838
+ if match.group("mn"):
1839
+ return "article", (match.group("mn_n") or "").strip()
1840
+ if match.group("kk"):
1841
+ return "article", (match.group("kk_n") or "").strip()
1842
+ if match.group("disp"):
1843
+ return "article", (match.group("disp_n") or "").strip()
1844
+ if match.group("mom"):
1845
+ return "section", (match.group("mom_n") or "").strip()
1846
+ if match.group("order"):
1847
+ return "section", (match.group("order_n") or "").strip()
1848
+ if match.group("kidogo"):
1849
+ return "section", (match.group("kidogo_n") or "").strip()
1850
+ if match.group("esresol"):
1851
+ word = _latin_fold(match.group("esresol") or "").casefold()
1852
+ return "section", {
1853
+ "primero": "1", "segundo": "2", "tercero": "3", "cuarto": "4",
1854
+ "quinto": "5", "sexto": "6", "septimo": "7", "octavo": "8",
1855
+ "noveno": "9", "decimo": "10",
1856
+ "erstens": "1", "zweitens": "2", "drittens": "3", "viertens": "4", "funftens": "5",
1857
+ "premierement": "1", "deuxiemement": "2", "troisiemement": "3",
1858
+ "quatriemement": "4", "cinquiemement": "5",
1859
+ }.get(word, word)
1860
+ return "", ""
1861
+
1862
+
1863
+ @dataclass
1864
+ class _Hit:
1865
+ start: int
1866
+ kind: str
1867
+ number: str
1868
+ heading: str
1869
+
1870
+
1871
+ _PAREN_XREF_RE = re.compile(
1872
+ r"(?i)^\s*(?:\([a-z0-9]{1,4}\))?\s+"
1873
+ r"(?:is|are|or|and|of|have|has|was|were|by|to|for|from|in|that|shall)\b"
1874
+ )
1875
+
1876
+
1877
+ def _paren_letter_xref(raw: str, number: str, rest: str) -> bool:
1878
+ """Skip 'paragraph (i) or …' / 'subsection (l)(b) is …' cross-references."""
1879
+ if len(number) != 1 or not number.isalpha() or "(" not in raw:
1880
+ return False
1881
+ return _PAREN_XREF_RE.match(rest) is not None
1882
+
1883
+
1884
+ def _collect_hits(text: str, *, language: str, latin: bool) -> list[_Hit]:
1885
+ hits: list[_Hit] = []
1886
+ folded = _latin_fold(text) if latin else text
1887
+ if latin:
1888
+ for match in _HEADING_RE.finditer(folded):
1889
+ kind, number = _kind_number_from_heading_match(match)
1890
+ if not kind:
1891
+ continue
1892
+ if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]):
1893
+ continue
1894
+ if _paren_letter_xref(match.group(0), number, folded[match.end() : match.end() + 48]):
1895
+ continue
1896
+ for gname in (
1897
+ "title_n", "chapter_n", "part_n", "article_n", "section_n",
1898
+ "section_sym_n", "section_pre_n", "grein_n", "straipsnis_n",
1899
+ "artikulua_n", "ledd_n", "kap_n", "luku_n",
1900
+ "fejezet_n", "peatukk_n", "skyrius_n", "nodala_n",
1901
+ "kafli_n", "bob_n", "tarau_n", "bolum_n",
1902
+ "modda_n", "mn_n", "kk_n", "mom_n", "order_n", "kidogo_n", "disp_n",
1903
+ ):
1904
+ try:
1905
+ start, end = match.span(gname)
1906
+ except IndexError:
1907
+ continue
1908
+ if start >= 0:
1909
+ number = text[start:end]
1910
+ break
1911
+ number = _fold_digits_in_number(number.strip().rstrip(".-:–—"))
1912
+ line_end = text.find("\n", match.start())
1913
+ if line_end < 0:
1914
+ line_end = len(text)
1915
+ heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
1916
+ hits.append(_Hit(match.start(), kind, number, heading))
1917
+ for match in _lexicon_heading_re().finditer(folded):
1918
+ if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]):
1919
+ continue
1920
+ token = (match.group("lex") or "").casefold()
1921
+ kind = _LEXICON_KIND.get(token, "article")
1922
+ start, end = match.span("lex_n")
1923
+ number = _fold_digits_in_number(
1924
+ (text[start:end] if start >= 0 else match.group("lex_n") or "").strip().rstrip(".-:–—")
1925
+ )
1926
+ if not number:
1927
+ continue
1928
+ line_end = text.find("\n", match.start())
1929
+ if line_end < 0:
1930
+ line_end = len(text)
1931
+ heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
1932
+ hits.append(_Hit(match.start(), kind, number, heading))
1933
+ for match in _LATIN_LETTER_RE.finditer(text):
1934
+ letter = match.group("paren") or match.group("bare")
1935
+ if letter:
1936
+ number = str(ord(letter) - 96)
1937
+ else:
1938
+ number = _ROMAN_LOWER.get(match.group("roman") or "", "")
1939
+ if not number:
1940
+ continue
1941
+ line_end = text.find("\n", match.start())
1942
+ if line_end < 0:
1943
+ line_end = len(text)
1944
+ heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
1945
+ hits.append(_Hit(match.start(), "section", number, heading))
1946
+ for match in _LATIN_NUM_LIST_RE.finditer(text):
1947
+ number = (
1948
+ match.group("nparen")
1949
+ or match.group("nclose")
1950
+ or match.group("nord")
1951
+ or match.group("ndot")
1952
+ or match.group("ncolon")
1953
+ or match.group("ndash")
1954
+ or ""
1955
+ )
1956
+ dbl = match.group("dbl")
1957
+ if dbl:
1958
+ number = str(ord(dbl[0]) - 96)
1959
+ if not number:
1960
+ continue
1961
+ line_end = text.find("\n", match.start())
1962
+ if line_end < 0:
1963
+ line_end = len(text)
1964
+ heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
1965
+ hits.append(_Hit(match.start(), "section", number, heading))
1966
+ for i, match in enumerate(_BULLET_RE.finditer(text), start=1):
1967
+ line_end = text.find("\n", match.start())
1968
+ if line_end < 0:
1969
+ line_end = len(text)
1970
+ heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
1971
+ hits.append(_Hit(match.start(), "section", str(i), heading))
1972
+ for match in _DASH_NUM_RE.finditer(text):
1973
+ number = (match.group("bn") or "").strip()
1974
+ if not number:
1975
+ continue
1976
+ line_end = text.find("\n", match.start())
1977
+ if line_end < 0:
1978
+ line_end = len(text)
1979
+ heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
1980
+ hits.append(_Hit(match.start(), "section", number, heading))
1981
+ for regex in _detected_script_regexes(text, language):
1982
+ for match in regex.finditer(text):
1983
+ if _in_range_boilerplate(text, match.start()):
1984
+ continue
1985
+ if _SCRIPT_CITE_TAIL_RE.match(text[match.end() : match.end() + 48]):
1986
+ continue
1987
+ raw = match.group(0)
1988
+ number = _fold_digits_in_number(_script_article_number(raw))
1989
+ heading = re.sub(r"\s+", " ", raw).strip()[:240]
1990
+ hits.append(_Hit(match.start(), _script_hit_kind(regex), number, heading))
1991
+ if latin:
1992
+ from .profiles import iso_lang
1993
+
1994
+ lang = iso_lang(language)
1995
+ keyword_hits = [h for h in hits if h.kind in {"article", "section"}]
1996
+ if len(keyword_hits) < MIN_SPLIT_HEADINGS and lang in _CW_NUM_LANGS:
1997
+ for match in _CW_NUM_RE.finditer(text):
1998
+ number = (match.group("cw_n") or "").strip()
1999
+ if not _plausible_cw_number(number):
2000
+ continue
2001
+ if _MONTH_START_RE.match(text[match.end() : match.end() + 16]):
2002
+ continue
2003
+ hits.append(
2004
+ _Hit(
2005
+ match.start(),
2006
+ "section",
2007
+ number,
2008
+ match.group(0).strip()[:240],
2009
+ )
2010
+ )
2011
+ hits.sort(key=lambda h: (h.start, -len(h.heading)))
2012
+ merged: list[_Hit] = []
2013
+ seen_starts: set[int] = set()
2014
+ for hit in hits:
2015
+ if hit.start in seen_starts:
2016
+ continue
2017
+ seen_starts.add(hit.start)
2018
+ merged.append(hit)
2019
+ return merged
2020
+
2021
+
2022
+ def _units_from_hits(text: str, hits: list[_Hit]) -> list[StructureUnit]:
2023
+ if not hits:
2024
+ return [
2025
+ StructureUnit(kind="preamble", number="", heading="", body=text, char_start=0, char_end=len(text))
2026
+ ]
2027
  cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""}
2028
  units: list[StructureUnit] = []
2029
+ if hits[0].start > 0:
2030
+ units.append(
2031
+ StructureUnit(
2032
+ kind="preamble",
2033
+ number="",
2034
+ heading="",
2035
+ body=text[0 : hits[0].start],
2036
+ char_start=0,
2037
+ char_end=hits[0].start,
2038
+ )
2039
+ )
2040
+ for i, hit in enumerate(hits):
2041
+ start = hit.start
2042
+ end = hits[i + 1].start if i + 1 < len(hits) else len(text)
2043
+ body = text[start:end]
2044
+ cursor[hit.kind] = hit.number
 
2045
  for lower, rank in _KIND_RANK.items():
2046
+ if rank > _KIND_RANK.get(hit.kind, 99):
2047
  cursor[lower] = ""
 
 
 
 
 
 
2048
  units.append(
2049
  StructureUnit(
2050
+ kind=hit.kind,
2051
+ number=hit.number,
2052
+ heading=hit.heading[:240],
2053
+ body=body,
2054
  title_number=cursor["title"],
2055
  chapter_number=cursor["chapter"],
2056
  part_number=cursor["part"],
2057
  article_number=cursor["article"],
2058
  section_number=cursor["section"],
2059
+ subsections=_subsection_tokens(body),
2060
  hierarchy_path=_cursor_path(cursor),
2061
+ char_start=start,
2062
+ char_end=end,
2063
  )
2064
  )
2065
+ return units
2066
+
2067
+
2068
+ def segment_exclusive(text: str, *, language: str = "") -> list[StructureUnit]:
2069
+ """Internal exclusive-span segmentation of *text* (includes preamble)."""
2070
+ from .profiles import iso_lang, latin_split_allowed
2071
+
2072
+ if not text:
2073
+ return []
2074
+ latin = not language or latin_split_allowed(language)
2075
+ hits = _collect_hits(text, language=language, latin=latin)
2076
+ retrieval_like = [h for h in hits if h.kind in {"article", "section"}]
2077
+ if (
2078
+ not latin
2079
+ and len(retrieval_like) < MIN_SPLIT_HEADINGS
2080
+ and iso_lang(language) in _LATIN_FALLBACK_LANGS
2081
+ ):
2082
+ hits = _collect_hits(text, language=language, latin=True)
2083
+ return _units_from_hits(text, hits)
2084
+
2085
+
2086
+ def split_script_units(text: str, language: str) -> list[StructureUnit]:
2087
+ """Retrieval projection of script-specific exclusive spans."""
2088
+ internal = segment_exclusive(text, language=language)
2089
+ retrieval = [u for u in internal if u.kind == "article" and len(u.body.strip()) >= 16]
2090
+ return retrieval if len(retrieval) >= MIN_SPLIT_HEADINGS else []
2091
+
2092
+
2093
+ def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]:
2094
+ """Retrieval units. Empty list means keep the whole instrument.
2095
+
2096
+ Prefers article/section. When those are scarce, numbered chapter then title
2097
+ headings (Cameroon CHAPITRE, Bolivia TÍTULO, Cape Verde CAPÍTULO).
2098
+ """
2099
+ if not text or len(text) < 16:
2100
+ return []
2101
+ from .profiles import latin_split_allowed
2102
+
2103
+ internal = segment_exclusive(text, language=language)
2104
+
2105
+ def _take(kinds: set[str]) -> list[StructureUnit]:
2106
+ out: list[StructureUnit] = []
2107
+ for u in internal:
2108
+ if u.kind not in kinds:
2109
+ continue
2110
+ min_len = 16 if u.number else MIN_UNIT_CHARS
2111
+ if language and not latin_split_allowed(language):
2112
+ min_len = 16
2113
+ if len(u.body.strip()) >= min_len:
2114
+ out.append(u)
2115
+ return out
2116
+
2117
+ for kinds in (
2118
+ {"article", "section"},
2119
+ {"chapter"},
2120
+ {"part"},
2121
+ {"title"},
2122
+ ):
2123
+ retrieval = _take(kinds)
2124
+ if len(retrieval) >= MIN_SPLIT_HEADINGS:
2125
+ return retrieval
2126
  return []
country_laws_ir/upload.py CHANGED
@@ -20,10 +20,82 @@ _OPERATOR_HINT = (
20
  )
21
 
22
 
 
 
 
 
 
 
 
 
 
23
  class UploadError(RuntimeError):
24
  """Raised when a JusticeDAO upload cannot proceed."""
25
 
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def _token_from_env() -> str:
28
  for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
29
  value = (os.environ.get(key) or "").strip()
@@ -92,6 +164,7 @@ def upload_release(
92
  n_files = sum(1 for path in local_dir.rglob("*") if path.is_file())
93
  nbytes = sum(path.stat().st_size for path in local_dir.rglob("*") if path.is_file())
94
  use_large = n_files >= 80 or nbytes >= 80 * 1024 * 1024
 
95
  if use_large and hasattr(api, "upload_large_folder"):
96
  api.upload_large_folder(
97
  folder_path=str(local_dir),
@@ -99,7 +172,19 @@ def upload_release(
99
  repo_type="dataset",
100
  ignore_patterns=ignore,
101
  )
102
- revision = ""
 
 
 
 
 
 
 
 
 
 
 
 
103
  try:
104
  from huggingface_hub import dataset_info as _dataset_info
105
 
@@ -107,26 +192,10 @@ def upload_release(
107
  revision = str(getattr(pinned, "sha", "") or "")
108
  except Exception:
109
  revision = ""
110
- return {
111
- "url": f"https://huggingface.co/datasets/{repo_id}",
112
- "repo_id": repo_id,
113
- "revision": revision,
114
- "local_dir": str(local_dir),
115
- "method": "upload_large_folder",
116
- }
117
- info = api.upload_folder(
118
- folder_path=str(local_dir),
119
- repo_id=repo_id,
120
- repo_type="dataset",
121
- commit_message=commit_message
122
- or f"Incremental country-laws-ir GraphRAG release for {repo_id}",
123
- ignore_patterns=ignore,
124
- )
125
- revision = getattr(info, "oid", None) or getattr(info, "commit_id", None) or ""
126
  return {
127
  "url": f"https://huggingface.co/datasets/{repo_id}",
128
  "repo_id": repo_id,
129
  "revision": revision,
130
  "local_dir": str(local_dir),
131
- "method": "upload_folder",
132
  }
 
20
  )
21
 
22
 
23
+ CARD_FILES = (
24
+ "README.md",
25
+ ".gitattributes",
26
+ "manifest.json",
27
+ "dataset_configs.json",
28
+ "normalization_report.json",
29
+ )
30
+
31
+
32
  class UploadError(RuntimeError):
33
  """Raised when a JusticeDAO upload cannot proceed."""
34
 
35
 
36
+ def ensure_dataset_card(local_dir: Path) -> Path:
37
+ """Write a YAML dataset card if README.md is missing or is a Hub stub."""
38
+ from .package import _write_readme
39
+
40
+ local_dir = Path(local_dir)
41
+ readme = local_dir / "README.md"
42
+ text = readme.read_text(encoding="utf-8") if readme.is_file() else ""
43
+ if text.startswith("---") and "pretty_name:" in text:
44
+ return readme
45
+ manifest_path = local_dir / "manifest.json"
46
+ if not manifest_path.is_file():
47
+ raise UploadError(f"cannot build dataset card; missing {manifest_path}")
48
+ import json
49
+
50
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
51
+ country = manifest.get("country") or {}
52
+ source_meta = manifest.get("source") or {
53
+ "source_dataset": manifest.get("dataset_id") or "",
54
+ "source_revision": manifest.get("dataset_revision") or "",
55
+ }
56
+ hub_id = str(manifest.get("dataset_repo_id") or f"{TARGET_ORG}/ipfs_{country.get('slug', 'unknown')}_laws_ir")
57
+ _write_readme(
58
+ local_dir,
59
+ country,
60
+ source_meta,
61
+ manifest.get("counts") or {},
62
+ manifest.get("bm25") or {},
63
+ manifest.get("graph") or {},
64
+ manifest.get("vector") or {},
65
+ hub_id,
66
+ normalization_report=manifest.get("normalization"),
67
+ )
68
+ return readme
69
+
70
+
71
+ def _commit_dataset_card(api: Any, local_dir: Path, repo_id: str) -> str:
72
+ """Always commit README/metadata after parquet upload.
73
+
74
+ ``upload_large_folder`` often finishes LFS parquet commits while leaving
75
+ a Hub-generated stub README (no YAML card). Regular files are committed
76
+ here in a follow-up so the dataset page always has a parseable card.
77
+ """
78
+ from huggingface_hub import CommitOperationAdd
79
+
80
+ ensure_dataset_card(local_dir)
81
+ operations = []
82
+ for name in CARD_FILES:
83
+ path = local_dir / name
84
+ if path.is_file():
85
+ operations.append(
86
+ CommitOperationAdd(path_in_repo=name, path_or_fileobj=str(path))
87
+ )
88
+ if not operations:
89
+ return ""
90
+ info = api.create_commit(
91
+ repo_id=repo_id,
92
+ repo_type="dataset",
93
+ operations=operations,
94
+ commit_message="Add YAML dataset card and release metadata",
95
+ )
96
+ return str(getattr(info, "oid", None) or getattr(info, "commit_id", None) or "")
97
+
98
+
99
  def _token_from_env() -> str:
100
  for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
101
  value = (os.environ.get(key) or "").strip()
 
164
  n_files = sum(1 for path in local_dir.rglob("*") if path.is_file())
165
  nbytes = sum(path.stat().st_size for path in local_dir.rglob("*") if path.is_file())
166
  use_large = n_files >= 80 or nbytes >= 80 * 1024 * 1024
167
+ method = "upload_folder"
168
  if use_large and hasattr(api, "upload_large_folder"):
169
  api.upload_large_folder(
170
  folder_path=str(local_dir),
 
172
  repo_type="dataset",
173
  ignore_patterns=ignore,
174
  )
175
+ method = "upload_large_folder"
176
+ else:
177
+ api.upload_folder(
178
+ folder_path=str(local_dir),
179
+ repo_id=repo_id,
180
+ repo_type="dataset",
181
+ commit_message=commit_message
182
+ or f"Incremental country-laws-ir GraphRAG release for {repo_id}",
183
+ ignore_patterns=ignore,
184
+ )
185
+ card_sha = _commit_dataset_card(api, local_dir, repo_id)
186
+ revision = card_sha
187
+ if not revision:
188
  try:
189
  from huggingface_hub import dataset_info as _dataset_info
190
 
 
192
  revision = str(getattr(pinned, "sha", "") or "")
193
  except Exception:
194
  revision = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  return {
196
  "url": f"https://huggingface.co/datasets/{repo_id}",
197
  "repo_id": repo_id,
198
  "revision": revision,
199
  "local_dir": str(local_dir),
200
+ "method": method,
201
  }
country_laws_ir/verify.py CHANGED
@@ -189,6 +189,112 @@ def check_heading_language(corpus: pd.DataFrame, report: dict[str, Any]) -> Chec
189
  )
190
 
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
193
  unit = str(report.get("unit") or "")
194
  n = int(len(corpus)) if corpus is not None else 0
@@ -204,7 +310,7 @@ def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
204
  coverage = structured_rows / float(n) if n else 0.0
205
  # Article or structured units are success. Pure law-level is a warning, not a fail:
206
  # many gazettes have no title/section markers.
207
- if unit in {"article", "structured"} or coverage >= 0.5:
208
  return Check(
209
  id="legal_structure",
210
  severity="warn",
@@ -237,6 +343,9 @@ def verify_normalized_corpus(
237
  check_no_invented_text(report),
238
  check_html_residual(corpus),
239
  check_short_bodies(corpus),
 
 
 
240
  check_structure(corpus, report),
241
  check_heading_language(corpus, report),
242
  ]
 
189
  )
190
 
191
 
192
+ def check_reconstruction_grounded(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
193
+ """Parent reconstructed body must equal glue of child title/number/body."""
194
+ from .reconstruct import expected_glue_from_children
195
+
196
+ if corpus is None or corpus.empty:
197
+ return Check(
198
+ id="reconstruction_grounded",
199
+ severity="fail",
200
+ passed=True,
201
+ message="no corpus",
202
+ evidence={},
203
+ )
204
+ if "reconstructed_from_articles" not in corpus.columns:
205
+ return Check(
206
+ id="reconstruction_grounded",
207
+ severity="warn",
208
+ passed=True,
209
+ message="no reconstruction columns",
210
+ evidence={},
211
+ )
212
+ mismatches = 0
213
+ checked = 0
214
+ samples: list[str] = []
215
+ laws = corpus[corpus["record_type"] == "law"] if "record_type" in corpus.columns else corpus
216
+ for rec in laws.itertuples(index=False):
217
+ if not bool(getattr(rec, "reconstructed_from_articles", False)):
218
+ continue
219
+ if str(getattr(rec, "reconstruction_gap_note", "") or "") in {
220
+ "rss_abort_slug",
221
+ "reconstruct_budget",
222
+ }:
223
+ continue
224
+ checked += 1
225
+ iid = str(getattr(rec, "instrument_id", "") or "")
226
+ kids = corpus[
227
+ (corpus["instrument_id"] == iid) & (corpus["record_type"].isin(["article", "section"]))
228
+ ]
229
+ children = [
230
+ {
231
+ "id": str(getattr(k, "source_id", "") or ""),
232
+ "title": str(getattr(k, "article_title", "") or getattr(k, "title", "") or ""),
233
+ "article_number": str(getattr(k, "article_number", "") or ""),
234
+ "body": str(getattr(k, "body", "") or ""),
235
+ }
236
+ for k in kids.itertuples(index=False)
237
+ ]
238
+ expected = expected_glue_from_children(children)
239
+ body = str(getattr(rec, "body", "") or "")
240
+ if bool(getattr(rec, "reconstruction_truncated", False)):
241
+ if not expected.startswith(body) and body != expected[: len(body)]:
242
+ mismatches += 1
243
+ if len(samples) < 5:
244
+ samples.append(iid)
245
+ continue
246
+ if body != expected:
247
+ mismatches += 1
248
+ if len(samples) < 5:
249
+ samples.append(iid)
250
+ ok = mismatches == 0
251
+ return Check(
252
+ id="reconstruction_grounded",
253
+ severity="fail",
254
+ passed=ok,
255
+ message="reconstructed parents match child glue" if ok else f"{mismatches} reconstructed parents fail glue",
256
+ evidence={"checked": checked, "mismatches": mismatches, "samples": samples},
257
+ )
258
+
259
+
260
+ def check_empty_parents_reconstructed(report: dict[str, Any]) -> Check:
261
+ n = int(report.get("n_empty_parents_with_articles_not_reconstructed") or 0)
262
+ return Check(
263
+ id="empty_parents_with_articles",
264
+ severity="fail",
265
+ passed=n == 0,
266
+ message="eligible empty parents all have law rows" if n == 0 else f"{n} empty parents with articles were dropped",
267
+ evidence={"n_empty_parents_with_articles_not_reconstructed": n},
268
+ )
269
+
270
+
271
+ def check_parent_laws(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
272
+ """Fail if source had instruments but GraphRAG corpus has no law rows."""
273
+ n_in = int(report.get("n_laws_in") or 0)
274
+ n_law_rows = 0
275
+ if corpus is not None and not corpus.empty and "record_type" in corpus.columns:
276
+ n_law_rows = int((corpus["record_type"] == "law").sum())
277
+ n_law_rows = int(report.get("n_law_rows") or n_law_rows)
278
+ if n_in > 0 and n_law_rows == 0:
279
+ return Check(
280
+ id="parent_laws",
281
+ severity="fail",
282
+ passed=False,
283
+ message=(
284
+ f"source has {n_in} laws but corpus has 0 law rows "
285
+ "(articles were indexed without parent instruments)"
286
+ ),
287
+ evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows},
288
+ )
289
+ return Check(
290
+ id="parent_laws",
291
+ severity="warn",
292
+ passed=True,
293
+ message=f"parent instruments present ({n_law_rows} law rows from {n_in} source laws)",
294
+ evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows},
295
+ )
296
+
297
+
298
  def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
299
  unit = str(report.get("unit") or "")
300
  n = int(len(corpus)) if corpus is not None else 0
 
310
  coverage = structured_rows / float(n) if n else 0.0
311
  # Article or structured units are success. Pure law-level is a warning, not a fail:
312
  # many gazettes have no title/section markers.
313
+ if unit in {"article", "structured", "law+article", "law+structured"} or coverage >= 0.5:
314
  return Check(
315
  id="legal_structure",
316
  severity="warn",
 
343
  check_no_invented_text(report),
344
  check_html_residual(corpus),
345
  check_short_bodies(corpus),
346
+ check_parent_laws(corpus, report),
347
+ check_reconstruction_grounded(corpus, report),
348
+ check_empty_parents_reconstructed(report),
349
  check_structure(corpus, report),
350
  check_heading_language(corpus, report),
351
  ]
data/bm25/documents/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5474555d602d4a7edcf8bdf1f407a7e1905a3a2b704c44b7b08af1006be365d1
3
- size 78266
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f4a910d1fba32214113195e82134acb6a71f225fa3dd3fcdc71e7dcc0a4cc69
3
+ size 87904
data/bm25/postings/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9410736739d0cd1746c869c64642a5a98cb22ef3962c7e172239b5960161c7ec
3
- size 20303
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ba3a86ca7ba2e1f79f148067d70c9fce30ba5ce2acd443a27748419f6413a16
3
+ size 58922
data/bm25/postings/part-000001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76418f3077ac7bb940604187959f3c2b8f708cb81d7c700b885eac5ac5f732dc
3
+ size 41541
data/bm25/postings/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:426421ee2c2544cce7be53af7905e536003e35e417f5cff313c510c46624fbc8
3
+ size 41173
data/bm25/postings/part-000003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37b28e20a75adbfd97f84c493a7b7d3880acb197353594791291920907fd3050
3
+ size 29520
data/corpus/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e70ac30b4b56d6e25e0973d32a92788e6c4a547f1bc6921b1dc10e03bb110a8e
3
- size 229523
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a92e53e79d3ebdea257eb8a638a1039e3b5984fc79c0bcda3c9ea3e694a45b1
3
+ size 1092458
data/graph/adjacency/in/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ca2e1cbf64c7d4848f1d4fdd2a224d2c51d34b7c51bf8f4b15d35688d481a093
3
- size 211721
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c5d2c781d657e8b6d964e4ca11af9754875c9581a6408d80c59a907634d5c3e
3
+ size 237661
data/graph/adjacency/out/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:67c810d6aba1b5fd44208b87a13b672ba7f055a969443bba0d952f05d19099bd
3
- size 207027
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8c904567de8342b197b0a234fe4eebf786aaa40f3e1b3086d57f5f1ea83cd1a
3
+ size 233161
data/graph/edges/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0f4511a9923aef70c894f68ebaf322afee7fa1f905a5bc40b679ebe37c516e5e
3
- size 183618
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5363848a84b37ebcc35477878b52f45e66474e94e094aa5f5723aea1bf4a82e
3
+ size 189600
data/graph/edges/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1ca5c45475d143dce45c0d3056dfb43c2eba3187a03ff9fbfbbb30ab94b30aa6
3
- size 49259
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee149999a2b980e87ed4aed5e2c690530a344215dd730676c20a115e2d21105e
3
+ size 75033
data/graph/nodes/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a4f48b420b047e94a1699bb085672cd27482c51b0dc09e69f451d3bea13c7b47
3
- size 58340
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c60b4b506b4bfffe5d2fd108aa1dd175db8702ce6b0b16c0029e4f0a250b9293
3
+ size 68213
data/vectors/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ee26f8d7e877052567f07adb65fcf8bd3fd4c0de82946e04dba4cb4ae52ee589
3
- size 1425513
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9918c8841cf13820d4ff95b3fcabaca96194766f4fa96378ae8a70359b78d673
3
+ size 1545290
indexes/bm25_document_chunks.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:8e1679b05c5b5d4270bf0bed0fa2e55b78e5b088ca711887e9294d09dd08527f
3
- size 4578
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:121aa3a0d165362b2c24fe963a3fd84c574f4da5f4cfef04967937f4c85f5dea
3
+ size 4577
indexes/bm25_keyword_shards.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1db292df1497260f33c87750cdb8ebfe16b5c71edc0bb2941b44a2cef03d83ee
3
- size 4821
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8921c612feeaa7fdb9d780325488fa7d34f072c86562cc2b07d379f5fd55c30
3
+ size 5215
indexes/corpus_chunks.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:93e99fba5dc0325bc2c7827ad087fd6c7540ae40649f18e27782072d601f14e8
3
  size 8604
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d20f1d1b8c4907428e637ccf5d3c702e405c52c0ca690d26ff056d8e4a7ee9ea
3
  size 8604
indexes/graph_edge_chunks.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:42ccd9d379a5e4b71cd774eb98f166e3e6fdfca1bba2ee17aa238c91f0373595
3
- size 5008
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74b38c065c8d3fcce1f08cfecf466db16008d8f461b5cb10d9977f7ede38f79a
3
+ size 5001
indexes/graph_in_adjacency.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:698ddf18757c896d7b56de772e7bf5ad3ae6c88139c28cd581b933ba616597f0
3
- size 6348
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48ebb41cc4fdaeb77df91c6235b604bd6dd1c5208eede19076ca7ea088b883aa
3
+ size 6349
indexes/graph_node_chunks.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:88d533b3e29d6374cefb359fe7e397ff839c3e26fdfdc87a90de11b77aa47ab6
3
  size 4768
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f576473dd8fd9213d3fc25f3df3fc585e54d2fee357bf93d5f720b9ff00d814
3
  size 4768
indexes/graph_out_adjacency.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:90f496bdc467c955a052f07b1424d75d1249ae33324dd870da35940bd6fbf313
3
- size 6363
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b44fc38d83678facad00d197ef1bca6a1f6590c889340310809b1ab991a4c752
3
+ size 6364
indexes/vector_chunks.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:06da2c40c46e1ee695908f8e4d21ea1f96d47624cb256749a2503c6ae027e51f
3
- size 18088
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb03df067944ceebdb682c0bca927a9ad12ac15d8967946fbcc027e731bcfc24
3
+ size 18051
manifest.json CHANGED
@@ -19,7 +19,7 @@
19
  "b": 0.75,
20
  "title_weight": 5.0,
21
  "body_weight": 1.0,
22
- "average_document_length": 11.223512336719883,
23
  "tokenizer": "hf-graphrag-bm25-tokens/v1",
24
  "max_query_terms": 64,
25
  "posting_rows_per_record": 4096,
@@ -27,28 +27,28 @@
27
  },
28
  "counts": {
29
  "bm25_document_chunks": 1,
30
- "bm25_documents": 689,
31
- "bm25_keyword_shards": 1,
32
- "bm25_posting_rows": 739,
33
- "bm25_postings": 4645,
34
- "bm25_terms": 739,
35
  "corpus_chunks": 1,
36
- "corpus_rows": 689,
37
  "graph_edge_chunks": 0,
38
- "graph_edges": 4823,
39
  "graph_incoming_adjacency_edges": 0,
40
  "graph_incoming_adjacency_rows": 0,
41
  "graph_incoming_adjacency_shards": 0,
42
  "graph_node_chunks": 0,
43
- "graph_nodes": 822,
44
  "graph_outgoing_adjacency_edges": 0,
45
  "graph_outgoing_adjacency_rows": 0,
46
  "graph_outgoing_adjacency_shards": 0,
47
  "vector_chunks": 1,
48
- "vector_rows": 689,
49
- "n_laws": 0,
50
  "n_articles": 689,
51
- "bm25_token_instances": 7733
52
  },
53
  "parquet": {
54
  "compression": "zstd",
@@ -87,7 +87,7 @@
87
  "default_probe_centroids": 1,
88
  "centroid_count": 1,
89
  "shard_count": 1,
90
- "n_vectors": 689,
91
  "status": "embedded"
92
  },
93
  "canonical_fields": [
@@ -128,7 +128,7 @@
128
  "articles_sha256": "d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
129
  "n_laws_in": 69,
130
  "n_articles_in": 692,
131
- "unit": "article",
132
  "article_law_coverage": 10.028985507246377,
133
  "sparse_article_fallback": false,
134
  "drops": {
@@ -147,7 +147,8 @@
147
  ]
148
  },
149
  "language_breakdown": {
150
- "ar": 689
 
151
  },
152
  "quality_flags": {
153
  "articles_table_empty": false,
@@ -169,29 +170,41 @@
169
  "laws.eli non-null=0/69",
170
  "laws.language values=['ar', 'en']"
171
  ],
172
- "n_out": 689,
173
  "never_invented_legal_text": true,
174
- "n_before_dedupe": 692,
 
 
 
 
 
 
 
175
  "n_dropped_total": 3,
176
  "record_type_breakdown": {
177
- "article": 689
 
178
  },
179
  "jurisdiction_breakdown": {
180
- "LY": 689
181
  },
182
  "snapshot_dates": [
183
- "2026-09-15"
 
184
  ],
185
  "heading_language_counts": {
186
- "ar": 80
 
 
 
187
  },
188
- "heading_language_majority": "ar",
189
  "document_language_majority": "ar",
190
  "verification": {
191
  "schema_version": "country-laws-normalize-verify/v1",
192
  "slug": "",
193
  "admitted": true,
194
- "n_checks": 7,
195
  "n_failed": 0,
196
  "failed_ids": [],
197
  "checks": [
@@ -201,7 +214,7 @@
201
  "passed": true,
202
  "message": "normalized corpus has rows",
203
  "evidence": {
204
- "n_out": 689,
205
  "n_dropped": 3
206
  }
207
  },
@@ -231,10 +244,13 @@
231
  "passed": true,
232
  "message": "HTML tags stripped from legal bodies",
233
  "evidence": {
234
- "n_bodies": 689,
235
- "n_with_tags": 0,
236
- "fraction": 0.0,
237
- "samples": []
 
 
 
238
  }
239
  },
240
  {
@@ -244,31 +260,64 @@
244
  "message": "most legal units have usable body length",
245
  "evidence": {
246
  "n_short": 3,
247
- "n_bodies": 689,
248
- "fraction": 0.0043541364296081275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  }
250
  },
251
  {
252
  "id": "legal_structure",
253
  "severity": "warn",
254
  "passed": true,
255
- "message": "retrieval units are structured (article, coverage=1.00)",
256
  "evidence": {
257
- "unit": "article",
258
  "structured_rows": 689,
259
- "coverage": 1.0
260
  }
261
  },
262
  {
263
  "id": "heading_language",
264
  "severity": "warn",
265
  "passed": true,
266
- "message": "heading lexicon ar vs document language ar",
267
  "evidence": {
268
  "document_language": "ar",
269
- "heading_language": "ar",
270
  "heading_counts": {
271
- "ar": 80
 
 
 
272
  }
273
  }
274
  }
@@ -306,27 +355,27 @@
306
  },
307
  "indexes": {
308
  "bm25_document_chunks": {
309
- "cid": "bafkreieocz43axc3lvbhbpyl5uh2fzk3pds3bcgkoemip2jjjue52ccsp4",
310
- "sha256": "8e1679b05c5b5d4270bf0bed0fa2e55b78e5b088ca711887e9294d09dd08527f",
311
- "size_bytes": 4578,
312
  "relative_path": "indexes/bm25_document_chunks.parquet"
313
  },
314
  "bm25_keyword_shards": {
315
- "cid": "bafkreia5wkjn6fexeyhthsdxkdg3r276c224ohw4bozjig2eulhpapmd5y",
316
- "sha256": "1db292df1497260f33c87750cdb8ebfe16b5c71edc0bb2941b44a2cef03d83ee",
317
- "size_bytes": 4821,
318
  "relative_path": "indexes/bm25_keyword_shards.parquet"
319
  },
320
  "corpus_chunks": {
321
- "cid": "bafkreiet5gp3uxoagjn4fr4cpliip7lmovak4qdet4moe54ca4wwahyu5a",
322
- "sha256": "93e99fba5dc0325bc2c7827ad087fd6c7540ae40649f18e27782072d601f14e8",
323
  "size_bytes": 8604,
324
  "relative_path": "indexes/corpus_chunks.parquet"
325
  },
326
  "graph_edge_chunks": {
327
- "cid": "bafkreiccztm5g6nf4s3rzv3u5ompczxd4367zin3ulxbpkrdrsi7anzvsu",
328
- "sha256": "42ccd9d379a5e4b71cd774eb98f166e3e6fdfca1bba2ee17aa238c91f0373595",
329
- "size_bytes": 5008,
330
  "relative_path": "indexes/graph_edge_chunks.parquet"
331
  },
332
  "graph_incoming_adjacency": {
@@ -334,8 +383,8 @@
334
  "present": false
335
  },
336
  "graph_node_chunks": {
337
- "cid": "bafkreiei2uz3hyu5mn2m56zvt7t6hf77qood4jx57xehveg6cg3xvjd2wy",
338
- "sha256": "88d533b3e29d6374cefb359fe7e397ff839c3e26fdfdc87a90de11b77aa47ab6",
339
  "size_bytes": 4768,
340
  "relative_path": "indexes/graph_node_chunks.parquet"
341
  },
@@ -344,9 +393,9 @@
344
  "present": false
345
  },
346
  "vector_chunks": {
347
- "cid": "bafkreiag3iwebrdod3tjleeprzgsd2q7s3khmjglevtutisqhrvoaj7fd4",
348
- "sha256": "06da2c40c46e1ee695908f8e4d21ea1f96d47624cb256749a2503c6ae027e51f",
349
- "size_bytes": 18088,
350
  "relative_path": "indexes/vector_chunks.parquet"
351
  }
352
  },
@@ -407,14 +456,24 @@
407
  "source_fingerprint": "d46fc6a85eaa4d39efa4aa66c1d6c284a5ab6447|287c69f712386f9e5d5d17e84c0934b40fcfabbef472d6a49b90cae303d44253|d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
408
  "prior_fingerprint": "d46fc6a85eaa4d39efa4aa66c1d6c284a5ab6447|287c69f712386f9e5d5d17e84c0934b40fcfabbef472d6a49b90cae303d44253|d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
409
  "delta": {
410
- "n_added": 689,
411
  "n_removed": 689,
412
  "n_unchanged": 0,
413
  "prior_count": 689,
414
- "current_count": 689,
415
  "changed_ratio": 1.0,
416
  "equivalent_to_full": true,
417
  "added_cids_sample": [
 
 
 
 
 
 
 
 
 
 
418
  "bafkreia2pq4n4el7jdhtl4eemh6hywju4pccmzixncjvue7pymh6ynpdrm",
419
  "bafkreia2r7ff53jw5tyr7u5waob5bj23hegjxotq7wpk53ej7xakddgosm",
420
  "bafkreia2r7ixien6w7wyhvzy6d3kq36bqxyura7tnypa4bhxq3l5x6f7qu",
@@ -423,16 +482,6 @@
423
  "bafkreia4cvhz4ngcaqup7tswr4sawiinymvt73odugpojmhdf522bqkx5e",
424
  "bafkreia4qdfvaotudqjacl3tzyspy2sowxiwjyvoao5jj6ffxwsikvzrzq",
425
  "bafkreia4slsmnhhrq2fx3bj5svedcszqv2lub2w25rpznwziyzrrnr7z5m"
426
- ],
427
- "removed_cids_sample": [
428
- "bafkreia25ulmulpztpvrza4ohaso4lo2jnl6is3x752gva2bpts6n7auzu",
429
- "bafkreia2avmoh5ffxow6ddanvolhupsygttsb62nlqzeev4nohty7dn45a",
430
- "bafkreia2pwr6gfdytfh7lkp7uaag23usk6ii3mk6lkmytjgmcu3t6mgwpi",
431
- "bafkreia2qyj3vmcptekj3dym3nuafjvpza577hmuuqsz2bquejccob3mui",
432
- "bafkreia2xygqodfzxea5issedym7ri2xyfomyeu265wx3chhdw6nhzine4",
433
- "bafkreia2ygsswntklxsskfrhxjit72epnok76unpda5yvglzzdzarqouoq",
434
- "bafkreia36q665ghcpoqlzw6ichuxglkzzqjpmif4yp5ksz3voszyga4j4y",
435
- "bafkreia46r4ne4jywa57czplvprne3uxn4avtg6ze2emxf6tnie3torwt4"
436
  ]
437
  },
438
  "reuse_embeddings": false,
@@ -440,9 +489,9 @@
440
  "equivalent_to_full": true,
441
  "schema_version": "country-laws-ir-graphrag/v1",
442
  "vectors": {
443
- "n_docs": 689,
444
  "n_reused": 0,
445
- "n_encoded": 689,
446
  "n_missing": 0,
447
  "model_name": "thenlper/gte-small",
448
  "model_revision": "17e1f347d17fe144873b1201da91788898c639cd",
@@ -457,7 +506,7 @@
457
  "schema_version": "country-laws-ir-graphrag/v1",
458
  "bm25": {
459
  "bm25": {
460
- "average_document_length": 11.223512336719883,
461
  "b": 0.75,
462
  "body_weight": 1.0,
463
  "k1": 1.2,
@@ -474,34 +523,34 @@
474
  },
475
  "counts": {
476
  "bm25_document_chunks": 1,
477
- "bm25_documents": 689,
478
- "bm25_keyword_shards": 1,
479
- "bm25_posting_rows": 739,
480
- "bm25_postings": 4645,
481
- "bm25_terms": 739,
482
- "bm25_token_instances": 7733
483
  },
484
  "indexes": {
485
  "bm25_document_chunks": {
486
- "cid": "bafkreieocz43axc3lvbhbpyl5uh2fzk3pds3bcgkoemip2jjjue52ccsp4",
487
  "relative_path": "indexes/bm25_document_chunks.parquet",
488
  "row_count": 1,
489
- "sha256": "8e1679b05c5b5d4270bf0bed0fa2e55b78e5b088ca711887e9294d09dd08527f",
490
- "size_bytes": 4578
491
  },
492
  "bm25_keyword_shards": {
493
- "cid": "bafkreia5wkjn6fexeyhthsdxkdg3r276c224ohw4bozjig2eulhpapmd5y",
494
  "relative_path": "indexes/bm25_keyword_shards.parquet",
495
- "row_count": 1,
496
- "sha256": "1db292df1497260f33c87750cdb8ebfe16b5c71edc0bb2941b44a2cef03d83ee",
497
- "size_bytes": 4821
498
  }
499
  },
500
  "schema_version": "hf-graphrag-bm25-layout/v1"
501
  },
502
  "graph": {
503
- "node_count": 822,
504
- "edge_count": 4823,
505
  "adjacency": "data/graph/adjacency/{out,in}/*.parquet"
506
  },
507
  "sqlite": false,
 
19
  "b": 0.75,
20
  "title_weight": 5.0,
21
  "body_weight": 1.0,
22
+ "average_document_length": 386.13324538258576,
23
  "tokenizer": "hf-graphrag-bm25-tokens/v1",
24
  "max_query_terms": 64,
25
  "posting_rows_per_record": 4096,
 
27
  },
28
  "counts": {
29
  "bm25_document_chunks": 1,
30
+ "bm25_documents": 758,
31
+ "bm25_keyword_shards": 4,
32
+ "bm25_posting_rows": 15202,
33
+ "bm25_postings": 33741,
34
+ "bm25_terms": 15202,
35
  "corpus_chunks": 1,
36
+ "corpus_rows": 758,
37
  "graph_edge_chunks": 0,
38
+ "graph_edges": 5306,
39
  "graph_incoming_adjacency_edges": 0,
40
  "graph_incoming_adjacency_rows": 0,
41
  "graph_incoming_adjacency_shards": 0,
42
  "graph_node_chunks": 0,
43
+ "graph_nodes": 975,
44
  "graph_outgoing_adjacency_edges": 0,
45
  "graph_outgoing_adjacency_rows": 0,
46
  "graph_outgoing_adjacency_shards": 0,
47
  "vector_chunks": 1,
48
+ "vector_rows": 758,
49
+ "n_laws": 69,
50
  "n_articles": 689,
51
+ "bm25_token_instances": 292689
52
  },
53
  "parquet": {
54
  "compression": "zstd",
 
87
  "default_probe_centroids": 1,
88
  "centroid_count": 1,
89
  "shard_count": 1,
90
+ "n_vectors": 758,
91
  "status": "embedded"
92
  },
93
  "canonical_fields": [
 
128
  "articles_sha256": "d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
129
  "n_laws_in": 69,
130
  "n_articles_in": 692,
131
+ "unit": "law+article",
132
  "article_law_coverage": 10.028985507246377,
133
  "sparse_article_fallback": false,
134
  "drops": {
 
147
  ]
148
  },
149
  "language_breakdown": {
150
+ "ar": 753,
151
+ "en": 5
152
  },
153
  "quality_flags": {
154
  "articles_table_empty": false,
 
170
  "laws.eli non-null=0/69",
171
  "laws.language values=['ar', 'en']"
172
  ],
173
+ "n_out": 758,
174
  "never_invented_legal_text": true,
175
+ "n_reconstructed_parents": 0,
176
+ "n_reconstructed_truncated": 0,
177
+ "n_reconstructed_stubs": 0,
178
+ "n_empty_parents_with_articles_not_reconstructed": 0,
179
+ "n_before_dedupe": 761,
180
+ "n_law_rows": 69,
181
+ "n_child_rows": 689,
182
+ "n_instruments": 69,
183
  "n_dropped_total": 3,
184
  "record_type_breakdown": {
185
+ "article": 689,
186
+ "law": 69
187
  },
188
  "jurisdiction_breakdown": {
189
+ "LY": 758
190
  },
191
  "snapshot_dates": [
192
+ "2026-09-15",
193
+ "2026-09-18"
194
  ],
195
  "heading_language_counts": {
196
+ "ar": 143,
197
+ "en": 313,
198
+ "fr": 1,
199
+ "yo": 1
200
  },
201
+ "heading_language_majority": "en",
202
  "document_language_majority": "ar",
203
  "verification": {
204
  "schema_version": "country-laws-normalize-verify/v1",
205
  "slug": "",
206
  "admitted": true,
207
+ "n_checks": 10,
208
  "n_failed": 0,
209
  "failed_ids": [],
210
  "checks": [
 
214
  "passed": true,
215
  "message": "normalized corpus has rows",
216
  "evidence": {
217
+ "n_out": 758,
218
  "n_dropped": 3
219
  }
220
  },
 
244
  "passed": true,
245
  "message": "HTML tags stripped from legal bodies",
246
  "evidence": {
247
+ "n_bodies": 758,
248
+ "n_with_tags": 2,
249
+ "fraction": 0.002638522427440633,
250
+ "samples": [
251
+ "BT /F1 14.000 Tf ET\n%PDF-1.4\n%\n0.000 G\n1.000 g\n/GS1 gs\n0.567 w\n0 Tr\n[] 0 d\n3 0 obj\n<>\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<",
252
+ "BT /F1 14.000 Tf ET\n%PDF-1.4\n%\n0.000 G\n1.000 g\n/GS1 gs\n0.567 w\n0 Tr\n[] 0 d\n3 0 obj\n<>\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<"
253
+ ]
254
  }
255
  },
256
  {
 
260
  "message": "most legal units have usable body length",
261
  "evidence": {
262
  "n_short": 3,
263
+ "n_bodies": 758,
264
+ "fraction": 0.00395778364116095
265
+ }
266
+ },
267
+ {
268
+ "id": "parent_laws",
269
+ "severity": "warn",
270
+ "passed": true,
271
+ "message": "parent instruments present (69 law rows from 69 source laws)",
272
+ "evidence": {
273
+ "n_laws_in": 69,
274
+ "n_law_rows": 69
275
+ }
276
+ },
277
+ {
278
+ "id": "reconstruction_grounded",
279
+ "severity": "fail",
280
+ "passed": true,
281
+ "message": "reconstructed parents match child glue",
282
+ "evidence": {
283
+ "checked": 0,
284
+ "mismatches": 0,
285
+ "samples": []
286
+ }
287
+ },
288
+ {
289
+ "id": "empty_parents_with_articles",
290
+ "severity": "fail",
291
+ "passed": true,
292
+ "message": "eligible empty parents all have law rows",
293
+ "evidence": {
294
+ "n_empty_parents_with_articles_not_reconstructed": 0
295
  }
296
  },
297
  {
298
  "id": "legal_structure",
299
  "severity": "warn",
300
  "passed": true,
301
+ "message": "retrieval units are structured (law+article, coverage=0.91)",
302
  "evidence": {
303
+ "unit": "law+article",
304
  "structured_rows": 689,
305
+ "coverage": 0.9089709762532981
306
  }
307
  },
308
  {
309
  "id": "heading_language",
310
  "severity": "warn",
311
  "passed": true,
312
+ "message": "heading lexicon majority is en but documents are ar; review samples before trusting structure",
313
  "evidence": {
314
  "document_language": "ar",
315
+ "heading_language": "en",
316
  "heading_counts": {
317
+ "ar": 143,
318
+ "en": 313,
319
+ "fr": 1,
320
+ "yo": 1
321
  }
322
  }
323
  }
 
355
  },
356
  "indexes": {
357
  "bm25_document_chunks": {
358
+ "cid": "bafkreiasdkr2bulfgyvsyjh6sy5d7wcmk5hu3jpuz7xqjftzg72mqx255i",
359
+ "sha256": "121aa3a0d165362b2c24fe963a3fd84c574f4da5f4cfef04967937f4c85f5dea",
360
+ "size_bytes": 4577,
361
  "relative_path": "indexes/bm25_document_chunks.parquet"
362
  },
363
  "bm25_keyword_shards": {
364
+ "cid": "bafkreihisiogcl7ovj75xhlyamsurd5h2nhqolegkywmfmd5g6pv7vk4ga",
365
+ "sha256": "e8921c612feeaa7fdb9d780325488fa7d34f072c86562cc2b07d379f5fd55c30",
366
+ "size_bytes": 5215,
367
  "relative_path": "indexes/bm25_keyword_shards.parquet"
368
  },
369
  "corpus_chunks": {
370
+ "cid": "bafkreigsb4orxdcja5bi4y34z5oty4boiboffqgknegsn7yfnwheu7xj5i",
371
+ "sha256": "d20f1d1b8c4907428e637ccf5d3c702e405c52c0ca690d26ff056d8e4a7ee9ea",
372
  "size_bytes": 8604,
373
  "relative_path": "indexes/corpus_chunks.parquet"
374
  },
375
  "graph_edge_chunks": {
376
+ "cid": "bafkreiduwogamxenh7god4em73hum3nrmaenr5dbwxfrbwmxp57n4ohxti",
377
+ "sha256": "74b38c065c8d3fcce1f08cfecf466db16008d8f461b5cb10d9977f7ede38f79a",
378
+ "size_bytes": 5001,
379
  "relative_path": "indexes/graph_edge_chunks.parquet"
380
  },
381
  "graph_incoming_adjacency": {
 
383
  "present": false
384
  },
385
  "graph_node_chunks": {
386
+ "cid": "bafkreibpk5shhxmp3eqt2p6cl467h7cylzknf7xdk67zhvpxec476agycq",
387
+ "sha256": "2f576473dd8fd9213d3fc25f3df3fc585e54d2fee357bf93d5f720b9ff00d814",
388
  "size_bytes": 4768,
389
  "relative_path": "indexes/graph_node_chunks.parquet"
390
  },
 
393
  "present": false
394
  },
395
  "vector_chunks": {
396
+ "cid": "bafkreif3appqm6kez3v5w2bmbpfje6u22evmcxmjm6kg7pgae7ttdph4eq",
397
+ "sha256": "bb03df067944ceebdb682c0bca927a9ad12ac15d8967946fbcc027e731bcfc24",
398
+ "size_bytes": 18051,
399
  "relative_path": "indexes/vector_chunks.parquet"
400
  }
401
  },
 
456
  "source_fingerprint": "d46fc6a85eaa4d39efa4aa66c1d6c284a5ab6447|287c69f712386f9e5d5d17e84c0934b40fcfabbef472d6a49b90cae303d44253|d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
457
  "prior_fingerprint": "d46fc6a85eaa4d39efa4aa66c1d6c284a5ab6447|287c69f712386f9e5d5d17e84c0934b40fcfabbef472d6a49b90cae303d44253|d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
458
  "delta": {
459
+ "n_added": 758,
460
  "n_removed": 689,
461
  "n_unchanged": 0,
462
  "prior_count": 689,
463
+ "current_count": 758,
464
  "changed_ratio": 1.0,
465
  "equivalent_to_full": true,
466
  "added_cids_sample": [
467
+ "bafkreia23jn7focwfdfnn6zkoz7w2elyf4lnksigofgqojl2cqmld64kpy",
468
+ "bafkreia2hozpc7hd7zodmunrotupps4yisul5iejytnpmxlsicls2ftsby",
469
+ "bafkreia2s6iozrqctijdtxnuukv3ektqv37kxmh6is3it3tegh7uq25mnq",
470
+ "bafkreia2vf3p72sqrbyv2gmefrpzshy55vnauukhlobzeiqpcyidp7vsba",
471
+ "bafkreia35s5t3hw6v3ihl746epvoogxmmez7bsabkt2cblfnqaty7ggd3i",
472
+ "bafkreia3sulwqm6pzgqdxm25mca4dq4rzzrcjefjwhmca54n47gm5cisli",
473
+ "bafkreia3vyreiyzrkxlahmerfeehfcihuw23oslm4lrmnnowveds32yro4",
474
+ "bafkreia4lljar3iniesc7jtspnlwr2bhvxvunxww2v5dgzabrkzj3evnzq"
475
+ ],
476
+ "removed_cids_sample": [
477
  "bafkreia2pq4n4el7jdhtl4eemh6hywju4pccmzixncjvue7pymh6ynpdrm",
478
  "bafkreia2r7ff53jw5tyr7u5waob5bj23hegjxotq7wpk53ej7xakddgosm",
479
  "bafkreia2r7ixien6w7wyhvzy6d3kq36bqxyura7tnypa4bhxq3l5x6f7qu",
 
482
  "bafkreia4cvhz4ngcaqup7tswr4sawiinymvt73odugpojmhdf522bqkx5e",
483
  "bafkreia4qdfvaotudqjacl3tzyspy2sowxiwjyvoao5jj6ffxwsikvzrzq",
484
  "bafkreia4slsmnhhrq2fx3bj5svedcszqv2lub2w25rpznwziyzrrnr7z5m"
 
 
 
 
 
 
 
 
 
 
485
  ]
486
  },
487
  "reuse_embeddings": false,
 
489
  "equivalent_to_full": true,
490
  "schema_version": "country-laws-ir-graphrag/v1",
491
  "vectors": {
492
+ "n_docs": 758,
493
  "n_reused": 0,
494
+ "n_encoded": 758,
495
  "n_missing": 0,
496
  "model_name": "thenlper/gte-small",
497
  "model_revision": "17e1f347d17fe144873b1201da91788898c639cd",
 
506
  "schema_version": "country-laws-ir-graphrag/v1",
507
  "bm25": {
508
  "bm25": {
509
+ "average_document_length": 386.13324538258576,
510
  "b": 0.75,
511
  "body_weight": 1.0,
512
  "k1": 1.2,
 
523
  },
524
  "counts": {
525
  "bm25_document_chunks": 1,
526
+ "bm25_documents": 758,
527
+ "bm25_keyword_shards": 4,
528
+ "bm25_posting_rows": 15202,
529
+ "bm25_postings": 33741,
530
+ "bm25_terms": 15202,
531
+ "bm25_token_instances": 292689
532
  },
533
  "indexes": {
534
  "bm25_document_chunks": {
535
+ "cid": "bafkreiasdkr2bulfgyvsyjh6sy5d7wcmk5hu3jpuz7xqjftzg72mqx255i",
536
  "relative_path": "indexes/bm25_document_chunks.parquet",
537
  "row_count": 1,
538
+ "sha256": "121aa3a0d165362b2c24fe963a3fd84c574f4da5f4cfef04967937f4c85f5dea",
539
+ "size_bytes": 4577
540
  },
541
  "bm25_keyword_shards": {
542
+ "cid": "bafkreihisiogcl7ovj75xhlyamsurd5h2nhqolegkywmfmd5g6pv7vk4ga",
543
  "relative_path": "indexes/bm25_keyword_shards.parquet",
544
+ "row_count": 4,
545
+ "sha256": "e8921c612feeaa7fdb9d780325488fa7d34f072c86562cc2b07d379f5fd55c30",
546
+ "size_bytes": 5215
547
  }
548
  },
549
  "schema_version": "hf-graphrag-bm25-layout/v1"
550
  },
551
  "graph": {
552
+ "node_count": 975,
553
+ "edge_count": 5306,
554
  "adjacency": "data/graph/adjacency/{out,in}/*.parquet"
555
  },
556
  "sqlite": false,
normalization_report.json CHANGED
@@ -5,7 +5,7 @@
5
  "articles_sha256": "d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
6
  "n_laws_in": 69,
7
  "n_articles_in": 692,
8
- "unit": "article",
9
  "article_law_coverage": 10.028985507246377,
10
  "sparse_article_fallback": false,
11
  "drops": {
@@ -24,7 +24,8 @@
24
  ]
25
  },
26
  "language_breakdown": {
27
- "ar": 689
 
28
  },
29
  "quality_flags": {
30
  "articles_table_empty": false,
@@ -46,29 +47,41 @@
46
  "laws.eli non-null=0/69",
47
  "laws.language values=['ar', 'en']"
48
  ],
49
- "n_out": 689,
50
  "never_invented_legal_text": true,
51
- "n_before_dedupe": 692,
 
 
 
 
 
 
 
52
  "n_dropped_total": 3,
53
  "record_type_breakdown": {
54
- "article": 689
 
55
  },
56
  "jurisdiction_breakdown": {
57
- "LY": 689
58
  },
59
  "snapshot_dates": [
60
- "2026-09-15"
 
61
  ],
62
  "heading_language_counts": {
63
- "ar": 80
 
 
 
64
  },
65
- "heading_language_majority": "ar",
66
  "document_language_majority": "ar",
67
  "verification": {
68
  "schema_version": "country-laws-normalize-verify/v1",
69
  "slug": "",
70
  "admitted": true,
71
- "n_checks": 7,
72
  "n_failed": 0,
73
  "failed_ids": [],
74
  "checks": [
@@ -78,7 +91,7 @@
78
  "passed": true,
79
  "message": "normalized corpus has rows",
80
  "evidence": {
81
- "n_out": 689,
82
  "n_dropped": 3
83
  }
84
  },
@@ -108,10 +121,13 @@
108
  "passed": true,
109
  "message": "HTML tags stripped from legal bodies",
110
  "evidence": {
111
- "n_bodies": 689,
112
- "n_with_tags": 0,
113
- "fraction": 0.0,
114
- "samples": []
 
 
 
115
  }
116
  },
117
  {
@@ -121,31 +137,64 @@
121
  "message": "most legal units have usable body length",
122
  "evidence": {
123
  "n_short": 3,
124
- "n_bodies": 689,
125
- "fraction": 0.0043541364296081275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  }
127
  },
128
  {
129
  "id": "legal_structure",
130
  "severity": "warn",
131
  "passed": true,
132
- "message": "retrieval units are structured (article, coverage=1.00)",
133
  "evidence": {
134
- "unit": "article",
135
  "structured_rows": 689,
136
- "coverage": 1.0
137
  }
138
  },
139
  {
140
  "id": "heading_language",
141
  "severity": "warn",
142
  "passed": true,
143
- "message": "heading lexicon ar vs document language ar",
144
  "evidence": {
145
  "document_language": "ar",
146
- "heading_language": "ar",
147
  "heading_counts": {
148
- "ar": 80
 
 
 
149
  }
150
  }
151
  }
 
5
  "articles_sha256": "d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
6
  "n_laws_in": 69,
7
  "n_articles_in": 692,
8
+ "unit": "law+article",
9
  "article_law_coverage": 10.028985507246377,
10
  "sparse_article_fallback": false,
11
  "drops": {
 
24
  ]
25
  },
26
  "language_breakdown": {
27
+ "ar": 753,
28
+ "en": 5
29
  },
30
  "quality_flags": {
31
  "articles_table_empty": false,
 
47
  "laws.eli non-null=0/69",
48
  "laws.language values=['ar', 'en']"
49
  ],
50
+ "n_out": 758,
51
  "never_invented_legal_text": true,
52
+ "n_reconstructed_parents": 0,
53
+ "n_reconstructed_truncated": 0,
54
+ "n_reconstructed_stubs": 0,
55
+ "n_empty_parents_with_articles_not_reconstructed": 0,
56
+ "n_before_dedupe": 761,
57
+ "n_law_rows": 69,
58
+ "n_child_rows": 689,
59
+ "n_instruments": 69,
60
  "n_dropped_total": 3,
61
  "record_type_breakdown": {
62
+ "article": 689,
63
+ "law": 69
64
  },
65
  "jurisdiction_breakdown": {
66
+ "LY": 758
67
  },
68
  "snapshot_dates": [
69
+ "2026-09-15",
70
+ "2026-09-18"
71
  ],
72
  "heading_language_counts": {
73
+ "ar": 143,
74
+ "en": 313,
75
+ "fr": 1,
76
+ "yo": 1
77
  },
78
+ "heading_language_majority": "en",
79
  "document_language_majority": "ar",
80
  "verification": {
81
  "schema_version": "country-laws-normalize-verify/v1",
82
  "slug": "",
83
  "admitted": true,
84
+ "n_checks": 10,
85
  "n_failed": 0,
86
  "failed_ids": [],
87
  "checks": [
 
91
  "passed": true,
92
  "message": "normalized corpus has rows",
93
  "evidence": {
94
+ "n_out": 758,
95
  "n_dropped": 3
96
  }
97
  },
 
121
  "passed": true,
122
  "message": "HTML tags stripped from legal bodies",
123
  "evidence": {
124
+ "n_bodies": 758,
125
+ "n_with_tags": 2,
126
+ "fraction": 0.002638522427440633,
127
+ "samples": [
128
+ "BT /F1 14.000 Tf ET\n%PDF-1.4\n%\n0.000 G\n1.000 g\n/GS1 gs\n0.567 w\n0 Tr\n[] 0 d\n3 0 obj\n<>\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<",
129
+ "BT /F1 14.000 Tf ET\n%PDF-1.4\n%\n0.000 G\n1.000 g\n/GS1 gs\n0.567 w\n0 Tr\n[] 0 d\n3 0 obj\n<>\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<"
130
+ ]
131
  }
132
  },
133
  {
 
137
  "message": "most legal units have usable body length",
138
  "evidence": {
139
  "n_short": 3,
140
+ "n_bodies": 758,
141
+ "fraction": 0.00395778364116095
142
+ }
143
+ },
144
+ {
145
+ "id": "parent_laws",
146
+ "severity": "warn",
147
+ "passed": true,
148
+ "message": "parent instruments present (69 law rows from 69 source laws)",
149
+ "evidence": {
150
+ "n_laws_in": 69,
151
+ "n_law_rows": 69
152
+ }
153
+ },
154
+ {
155
+ "id": "reconstruction_grounded",
156
+ "severity": "fail",
157
+ "passed": true,
158
+ "message": "reconstructed parents match child glue",
159
+ "evidence": {
160
+ "checked": 0,
161
+ "mismatches": 0,
162
+ "samples": []
163
+ }
164
+ },
165
+ {
166
+ "id": "empty_parents_with_articles",
167
+ "severity": "fail",
168
+ "passed": true,
169
+ "message": "eligible empty parents all have law rows",
170
+ "evidence": {
171
+ "n_empty_parents_with_articles_not_reconstructed": 0
172
  }
173
  },
174
  {
175
  "id": "legal_structure",
176
  "severity": "warn",
177
  "passed": true,
178
+ "message": "retrieval units are structured (law+article, coverage=0.91)",
179
  "evidence": {
180
+ "unit": "law+article",
181
  "structured_rows": 689,
182
+ "coverage": 0.9089709762532981
183
  }
184
  },
185
  {
186
  "id": "heading_language",
187
  "severity": "warn",
188
  "passed": true,
189
+ "message": "heading lexicon majority is en but documents are ar; review samples before trusting structure",
190
  "evidence": {
191
  "document_language": "ar",
192
+ "heading_language": "en",
193
  "heading_counts": {
194
+ "ar": 143,
195
+ "en": 313,
196
+ "fr": 1,
197
+ "yo": 1
198
  }
199
  }
200
  }
normalize.py CHANGED
@@ -24,6 +24,12 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
24
  from .auth import configure_hf, public_token
25
  from .cidutil import cid_of_json, sha256_file, sha256_hex
26
  from .schema import SchemaError, validate_articles, validate_laws
 
 
 
 
 
 
27
  from .structure import normalize_legal_text, split_structured_units
28
 
29
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
@@ -399,6 +405,34 @@ def _base_record(
399
  }
400
  if extra:
401
  rec.update(extra)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  rec["entry_cid"] = _entry_cid(rec)
403
  rec["title_length"] = len(title_for_bm25)
404
  rec["body_length"] = len(body)
@@ -455,16 +489,137 @@ def build_corpus(
455
  "schema_surprises": list(source_meta.get("schema_surprises") or []),
456
  "n_out": 0,
457
  "never_invented_legal_text": True,
 
 
 
 
458
  }
459
 
460
  entries: list[dict[str, Any]] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
 
462
  if sparse_fallback:
463
  report["schema_surprises"].append(
464
  f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
465
  )
466
 
467
- if use_articles:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  for _, row in articles.iterrows():
469
  source_id = _row_get(row, "id")
470
  instrument_id = _row_get(row, "law_id")
@@ -521,13 +676,10 @@ def build_corpus(
521
  },
522
  )
523
  )
524
- else:
525
  for instrument_id, parent in law_map.items():
526
  body = parent["body"]
527
  if not body:
528
- report["drops"]["empty_body"] += 1
529
- if len(report["drop_samples"]["empty_body"]) < 20:
530
- report["drop_samples"]["empty_body"].append(instrument_id)
531
  continue
532
  meta = parent["metadata"]
533
  units = split_structured_units(body, language=parent["language"])
@@ -572,49 +724,11 @@ def build_corpus(
572
  },
573
  )
574
  )
575
- continue
576
- entries.append(
577
- _base_record(
578
- record_type="law",
579
- source_dataset=source_dataset,
580
- source_revision=source_revision,
581
- instrument_id=instrument_id,
582
- instrument_title=parent["instrument_title"],
583
- law_cid=parent["law_cid"],
584
- article_number="",
585
- article_title="",
586
- body=body,
587
- jurisdiction=parent["jurisdiction"],
588
- language=parent["language"],
589
- source_url=parent["source_url"],
590
- snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
591
- coverage=_coverage_from(
592
- parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback
593
- ),
594
- license_expr=parent["license"],
595
- collector=_collector(meta, source_dataset),
596
- source_id=instrument_id,
597
- extra={
598
- "eli": parent["eli"],
599
- "identifier": parent["identifier"],
600
- "official_identifier": parent["official_identifier"],
601
- "source_type": parent["source_type"],
602
- "country": parent["country"],
603
- "law_status": parent["law_status"],
604
- "parent_law_id": "",
605
- "article_id": "",
606
- **_hierarchy_fields(
607
- parent["instrument_title"], body, "", language=parent["language"]
608
- ),
609
- },
610
- )
611
- )
612
 
613
  entries.sort(
614
  key=lambda r: (
615
  r["instrument_id"],
616
- r.get("article_number") or "",
617
- r["source_id"],
618
  )
619
  )
620
  n_before = len(entries)
@@ -639,6 +753,20 @@ def build_corpus(
639
  raise SchemaError("Duplicate entry_cid remained after dedupe")
640
  report["n_before_dedupe"] = n_before
641
  report["n_out"] = int(len(df))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  report["n_dropped_total"] = (
643
  report["drops"]["empty_body"]
644
  + report["drops"]["missing_instrument"]
 
24
  from .auth import configure_hf, public_token
25
  from .cidutil import cid_of_json, sha256_file, sha256_hex
26
  from .schema import SchemaError, validate_articles, validate_laws
27
+ from .reconstruct import (
28
+ article_sort_key,
29
+ parent_needs_reconstruct,
30
+ reconstruct_on,
31
+ reconstruct_parent,
32
+ )
33
  from .structure import normalize_legal_text, split_structured_units
34
 
35
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
 
405
  }
406
  if extra:
407
  rec.update(extra)
408
+ from .citations import assign_citation, citation_fields
409
+
410
+ slug = ""
411
+ if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
412
+ slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
413
+ year = ""
414
+ if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit():
415
+ year = snapshot_date[:4]
416
+ extra = extra or {}
417
+ rec.update(
418
+ citation_fields(
419
+ assign_citation(
420
+ eli=str(rec.get("eli") or extra.get("eli") or ""),
421
+ official_identifier=str(
422
+ rec.get("official_identifier") or extra.get("official_identifier") or ""
423
+ ),
424
+ identifier=str(rec.get("identifier") or extra.get("identifier") or ""),
425
+ instrument_title=instrument_title,
426
+ article_number=article_number,
427
+ section_number=str(extra.get("section_number") or ""),
428
+ record_type=record_type,
429
+ jurisdiction=jurisdiction,
430
+ country=str(extra.get("country") or ""),
431
+ slug=slug,
432
+ year=year,
433
+ )
434
+ )
435
+ )
436
  rec["entry_cid"] = _entry_cid(rec)
437
  rec["title_length"] = len(title_for_bm25)
438
  rec["body_length"] = len(body)
 
489
  "schema_surprises": list(source_meta.get("schema_surprises") or []),
490
  "n_out": 0,
491
  "never_invented_legal_text": True,
492
+ "n_reconstructed_parents": 0,
493
+ "n_reconstructed_truncated": 0,
494
+ "n_reconstructed_stubs": 0,
495
+ "n_empty_parents_with_articles_not_reconstructed": 0,
496
  }
497
 
498
  entries: list[dict[str, Any]] = []
499
+ slug = ""
500
+ if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
501
+ slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
502
+
503
+ children_by_law: dict[str, list[dict[str, Any]]] = {}
504
+ if not articles_empty:
505
+ for _, row in articles.iterrows():
506
+ lid = _row_get(row, "law_id")
507
+ if not lid:
508
+ continue
509
+ children_by_law.setdefault(lid, []).append(
510
+ {
511
+ "id": _row_get(row, "id"),
512
+ "title": _row_get(row, "title"),
513
+ "article_number": _row_get(row, "article_number"),
514
+ "body": _row_get(row, "text"),
515
+ "row": row,
516
+ }
517
+ )
518
+
519
+ reconstructed_ids: set[str] = set()
520
+ running_extra_bytes = 0
521
+
522
+ def _append_law_row(
523
+ instrument_id: str,
524
+ parent: dict[str, Any],
525
+ recon=None,
526
+ ) -> None:
527
+ body = parent["body"]
528
+ recon_extra: dict[str, Any] = {}
529
+ coverage = _coverage_from(
530
+ parent["row"],
531
+ parent["metadata"],
532
+ articles_empty=articles_empty,
533
+ sparse_fallback=sparse_fallback,
534
+ )
535
+ if recon is not None and recon.reconstructed_from_articles:
536
+ body = recon.body
537
+ recon_extra = recon.extra_fields()
538
+ coverage = f"{coverage}; reconstructed_from_articles"
539
+ if not body:
540
+ kids = children_by_law.get(instrument_id) or []
541
+ if kids:
542
+ report["n_empty_parents_with_articles_not_reconstructed"] += 1
543
+ report["drops"]["empty_body"] += 1
544
+ if len(report["drop_samples"]["empty_body"]) < 20:
545
+ report["drop_samples"]["empty_body"].append(instrument_id)
546
+ return
547
+ meta = parent["metadata"]
548
+ entries.append(
549
+ _base_record(
550
+ record_type="law",
551
+ source_dataset=source_dataset,
552
+ source_revision=source_revision,
553
+ instrument_id=instrument_id,
554
+ instrument_title=parent["instrument_title"],
555
+ law_cid=parent["law_cid"],
556
+ article_number="",
557
+ article_title="",
558
+ body=body,
559
+ jurisdiction=parent["jurisdiction"],
560
+ language=parent["language"],
561
+ source_url=parent["source_url"],
562
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
563
+ coverage=coverage,
564
+ license_expr=parent["license"],
565
+ collector=_collector(meta, source_dataset),
566
+ source_id=instrument_id,
567
+ extra={
568
+ "eli": parent["eli"],
569
+ "identifier": parent["identifier"],
570
+ "official_identifier": parent["official_identifier"],
571
+ "source_type": parent["source_type"],
572
+ "country": parent["country"],
573
+ "law_status": parent["law_status"],
574
+ "parent_law_id": "",
575
+ "article_id": "",
576
+ "reconstructed_from_articles": False,
577
+ **_hierarchy_fields(
578
+ parent["instrument_title"], body, "", language=parent["language"]
579
+ ),
580
+ **recon_extra,
581
+ },
582
+ )
583
+ )
584
 
585
  if sparse_fallback:
586
  report["schema_surprises"].append(
587
  f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
588
  )
589
 
590
+ for instrument_id, parent in law_map.items():
591
+ kids = children_by_law.get(instrument_id) or []
592
+ recon = None
593
+ if reconstruct_on() and parent_needs_reconstruct(parent["body"], len(kids)):
594
+ recon = reconstruct_parent(
595
+ slug=slug,
596
+ parent_body=parent["body"],
597
+ parent_title=parent["instrument_title"],
598
+ children=[
599
+ {
600
+ "id": k["id"],
601
+ "title": k["title"],
602
+ "article_number": k["article_number"],
603
+ "body": k["body"],
604
+ }
605
+ for k in kids
606
+ ],
607
+ running_extra_bytes=running_extra_bytes,
608
+ sha256_hex=sha256_hex,
609
+ )
610
+ running_extra_bytes += recon.extra_bytes
611
+ reconstructed_ids.add(instrument_id)
612
+ report["n_reconstructed_parents"] += 1
613
+ if recon.reconstruction_truncated:
614
+ report["n_reconstructed_truncated"] += 1
615
+ if recon.is_stub:
616
+ report["n_reconstructed_stubs"] += 1
617
+ _append_law_row(instrument_id, parent, recon)
618
+
619
+ emit_articles = use_articles or bool(reconstructed_ids)
620
+ skip_body_split = emit_articles
621
+
622
+ if emit_articles:
623
  for _, row in articles.iterrows():
624
  source_id = _row_get(row, "id")
625
  instrument_id = _row_get(row, "law_id")
 
676
  },
677
  )
678
  )
679
+ elif not skip_body_split:
680
  for instrument_id, parent in law_map.items():
681
  body = parent["body"]
682
  if not body:
 
 
 
683
  continue
684
  meta = parent["metadata"]
685
  units = split_structured_units(body, language=parent["language"])
 
724
  },
725
  )
726
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
727
 
728
  entries.sort(
729
  key=lambda r: (
730
  r["instrument_id"],
731
+ article_sort_key(r.get("article_number") or "", r["source_id"]),
 
732
  )
733
  )
734
  n_before = len(entries)
 
753
  raise SchemaError("Duplicate entry_cid remained after dedupe")
754
  report["n_before_dedupe"] = n_before
755
  report["n_out"] = int(len(df))
756
+ if not df.empty and "record_type" in df.columns:
757
+ n_law_rows = int((df["record_type"] == "law").sum())
758
+ n_child_rows = int(df["record_type"].isin(["article", "section"]).sum())
759
+ report["n_law_rows"] = n_law_rows
760
+ report["n_child_rows"] = n_child_rows
761
+ report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows
762
+ if n_law_rows and n_child_rows:
763
+ report["unit"] = (
764
+ "law+structured" if report.get("unit") == "structured" else "law+article"
765
+ )
766
+ elif n_law_rows:
767
+ report["unit"] = "law"
768
+ elif n_child_rows:
769
+ report["unit"] = "article"
770
  report["n_dropped_total"] = (
771
  report["drops"]["empty_body"]
772
  + report["drops"]["missing_instrument"]
query.py CHANGED
@@ -158,6 +158,11 @@ class Release:
158
  hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
159
  return hits[:limit]
160
 
 
 
 
 
 
161
 
162
  def _print(rows: list[dict]) -> None:
163
  print(json.dumps(rows, indent=2, ensure_ascii=False))
@@ -189,6 +194,16 @@ def main(argv: list[str] | None = None) -> int:
189
  )
190
  p_n.add_argument("--limit", type=int, default=25)
191
 
 
 
 
 
 
 
 
 
 
 
192
  args = ap.parse_args(argv)
193
  rel = Release(Path(args.local_dir))
194
  if args.cmd == "bm25":
@@ -197,6 +212,8 @@ def main(argv: list[str] | None = None) -> int:
197
  _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
198
  elif args.cmd == "graph" and args.graph_cmd == "neighbors":
199
  _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
 
 
200
  return 0
201
 
202
 
 
158
  hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
159
  return hits[:limit]
160
 
161
+ def cite(self, citation: str, cite_format: str = "any", limit: int = 25) -> list[dict]:
162
+ from .duckdb_store import cite_search
163
+
164
+ return cite_search(self.root, citation, cite_format=cite_format, limit=limit)
165
+
166
 
167
  def _print(rows: list[dict]) -> None:
168
  print(json.dumps(rows, indent=2, ensure_ascii=False))
 
194
  )
195
  p_n.add_argument("--limit", type=int, default=25)
196
 
197
+ p_cite = sub.add_parser("cite")
198
+ p_cite.add_argument("citation")
199
+ p_cite.add_argument(
200
+ "--format",
201
+ dest="cite_format",
202
+ default="any",
203
+ choices=["any", "bluebook", "official"],
204
+ )
205
+ p_cite.add_argument("--limit", type=int, default=25)
206
+
207
  args = ap.parse_args(argv)
208
  rel = Release(Path(args.local_dir))
209
  if args.cmd == "bm25":
 
212
  _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
213
  elif args.cmd == "graph" and args.graph_cmd == "neighbors":
214
  _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
215
+ elif args.cmd == "cite":
216
+ _print(rel.cite(args.citation, cite_format=args.cite_format, limit=args.limit))
217
  return 0
218
 
219
 
reports/normalization.json CHANGED
@@ -5,7 +5,7 @@
5
  "articles_sha256": "d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
6
  "n_laws_in": 69,
7
  "n_articles_in": 692,
8
- "unit": "article",
9
  "article_law_coverage": 10.028985507246377,
10
  "sparse_article_fallback": false,
11
  "drops": {
@@ -24,7 +24,8 @@
24
  ]
25
  },
26
  "language_breakdown": {
27
- "ar": 689
 
28
  },
29
  "quality_flags": {
30
  "articles_table_empty": false,
@@ -46,29 +47,41 @@
46
  "laws.eli non-null=0/69",
47
  "laws.language values=['ar', 'en']"
48
  ],
49
- "n_out": 689,
50
  "never_invented_legal_text": true,
51
- "n_before_dedupe": 692,
 
 
 
 
 
 
 
52
  "n_dropped_total": 3,
53
  "record_type_breakdown": {
54
- "article": 689
 
55
  },
56
  "jurisdiction_breakdown": {
57
- "LY": 689
58
  },
59
  "snapshot_dates": [
60
- "2026-09-15"
 
61
  ],
62
  "heading_language_counts": {
63
- "ar": 80
 
 
 
64
  },
65
- "heading_language_majority": "ar",
66
  "document_language_majority": "ar",
67
  "verification": {
68
  "schema_version": "country-laws-normalize-verify/v1",
69
  "slug": "",
70
  "admitted": true,
71
- "n_checks": 7,
72
  "n_failed": 0,
73
  "failed_ids": [],
74
  "checks": [
@@ -78,7 +91,7 @@
78
  "passed": true,
79
  "message": "normalized corpus has rows",
80
  "evidence": {
81
- "n_out": 689,
82
  "n_dropped": 3
83
  }
84
  },
@@ -108,10 +121,13 @@
108
  "passed": true,
109
  "message": "HTML tags stripped from legal bodies",
110
  "evidence": {
111
- "n_bodies": 689,
112
- "n_with_tags": 0,
113
- "fraction": 0.0,
114
- "samples": []
 
 
 
115
  }
116
  },
117
  {
@@ -121,31 +137,64 @@
121
  "message": "most legal units have usable body length",
122
  "evidence": {
123
  "n_short": 3,
124
- "n_bodies": 689,
125
- "fraction": 0.0043541364296081275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  }
127
  },
128
  {
129
  "id": "legal_structure",
130
  "severity": "warn",
131
  "passed": true,
132
- "message": "retrieval units are structured (article, coverage=1.00)",
133
  "evidence": {
134
- "unit": "article",
135
  "structured_rows": 689,
136
- "coverage": 1.0
137
  }
138
  },
139
  {
140
  "id": "heading_language",
141
  "severity": "warn",
142
  "passed": true,
143
- "message": "heading lexicon ar vs document language ar",
144
  "evidence": {
145
  "document_language": "ar",
146
- "heading_language": "ar",
147
  "heading_counts": {
148
- "ar": 80
 
 
 
149
  }
150
  }
151
  }
 
5
  "articles_sha256": "d460260fd482656ba74cbf76d56346cec6f4fd86ec0235f5fd495c5fa02e00f1",
6
  "n_laws_in": 69,
7
  "n_articles_in": 692,
8
+ "unit": "law+article",
9
  "article_law_coverage": 10.028985507246377,
10
  "sparse_article_fallback": false,
11
  "drops": {
 
24
  ]
25
  },
26
  "language_breakdown": {
27
+ "ar": 753,
28
+ "en": 5
29
  },
30
  "quality_flags": {
31
  "articles_table_empty": false,
 
47
  "laws.eli non-null=0/69",
48
  "laws.language values=['ar', 'en']"
49
  ],
50
+ "n_out": 758,
51
  "never_invented_legal_text": true,
52
+ "n_reconstructed_parents": 0,
53
+ "n_reconstructed_truncated": 0,
54
+ "n_reconstructed_stubs": 0,
55
+ "n_empty_parents_with_articles_not_reconstructed": 0,
56
+ "n_before_dedupe": 761,
57
+ "n_law_rows": 69,
58
+ "n_child_rows": 689,
59
+ "n_instruments": 69,
60
  "n_dropped_total": 3,
61
  "record_type_breakdown": {
62
+ "article": 689,
63
+ "law": 69
64
  },
65
  "jurisdiction_breakdown": {
66
+ "LY": 758
67
  },
68
  "snapshot_dates": [
69
+ "2026-09-15",
70
+ "2026-09-18"
71
  ],
72
  "heading_language_counts": {
73
+ "ar": 143,
74
+ "en": 313,
75
+ "fr": 1,
76
+ "yo": 1
77
  },
78
+ "heading_language_majority": "en",
79
  "document_language_majority": "ar",
80
  "verification": {
81
  "schema_version": "country-laws-normalize-verify/v1",
82
  "slug": "",
83
  "admitted": true,
84
+ "n_checks": 10,
85
  "n_failed": 0,
86
  "failed_ids": [],
87
  "checks": [
 
91
  "passed": true,
92
  "message": "normalized corpus has rows",
93
  "evidence": {
94
+ "n_out": 758,
95
  "n_dropped": 3
96
  }
97
  },
 
121
  "passed": true,
122
  "message": "HTML tags stripped from legal bodies",
123
  "evidence": {
124
+ "n_bodies": 758,
125
+ "n_with_tags": 2,
126
+ "fraction": 0.002638522427440633,
127
+ "samples": [
128
+ "BT /F1 14.000 Tf ET\n%PDF-1.4\n%\n0.000 G\n1.000 g\n/GS1 gs\n0.567 w\n0 Tr\n[] 0 d\n3 0 obj\n<>\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<",
129
+ "BT /F1 14.000 Tf ET\n%PDF-1.4\n%\n0.000 G\n1.000 g\n/GS1 gs\n0.567 w\n0 Tr\n[] 0 d\n3 0 obj\n<>\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<"
130
+ ]
131
  }
132
  },
133
  {
 
137
  "message": "most legal units have usable body length",
138
  "evidence": {
139
  "n_short": 3,
140
+ "n_bodies": 758,
141
+ "fraction": 0.00395778364116095
142
+ }
143
+ },
144
+ {
145
+ "id": "parent_laws",
146
+ "severity": "warn",
147
+ "passed": true,
148
+ "message": "parent instruments present (69 law rows from 69 source laws)",
149
+ "evidence": {
150
+ "n_laws_in": 69,
151
+ "n_law_rows": 69
152
+ }
153
+ },
154
+ {
155
+ "id": "reconstruction_grounded",
156
+ "severity": "fail",
157
+ "passed": true,
158
+ "message": "reconstructed parents match child glue",
159
+ "evidence": {
160
+ "checked": 0,
161
+ "mismatches": 0,
162
+ "samples": []
163
+ }
164
+ },
165
+ {
166
+ "id": "empty_parents_with_articles",
167
+ "severity": "fail",
168
+ "passed": true,
169
+ "message": "eligible empty parents all have law rows",
170
+ "evidence": {
171
+ "n_empty_parents_with_articles_not_reconstructed": 0
172
  }
173
  },
174
  {
175
  "id": "legal_structure",
176
  "severity": "warn",
177
  "passed": true,
178
+ "message": "retrieval units are structured (law+article, coverage=0.91)",
179
  "evidence": {
180
+ "unit": "law+article",
181
  "structured_rows": 689,
182
+ "coverage": 0.9089709762532981
183
  }
184
  },
185
  {
186
  "id": "heading_language",
187
  "severity": "warn",
188
  "passed": true,
189
+ "message": "heading lexicon majority is en but documents are ar; review samples before trusting structure",
190
  "evidence": {
191
  "document_language": "ar",
192
+ "heading_language": "en",
193
  "heading_counts": {
194
+ "ar": 143,
195
+ "en": 313,
196
+ "fr": 1,
197
+ "yo": 1
198
  }
199
  }
200
  }