endomorphosis commited on
Commit
0d14e33
·
verified ·
1 Parent(s): b8461f1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +14 -10
  2. build.py +29 -2
  3. country_laws_ir/__main__.py +138 -1
  4. country_laws_ir/build.py +29 -2
  5. country_laws_ir/citations.py +139 -0
  6. country_laws_ir/data/bluebook_t2.json +27 -0
  7. country_laws_ir/data/learned_line_patterns.json +3 -0
  8. country_laws_ir/duckdb_store.py +67 -0
  9. country_laws_ir/graph.py +21 -7
  10. country_laws_ir/incremental.py +17 -1
  11. country_laws_ir/normalize.py +372 -45
  12. country_laws_ir/normalize_loop.py +621 -0
  13. country_laws_ir/package.py +137 -74
  14. country_laws_ir/profiles.py +217 -10
  15. country_laws_ir/query.py +17 -0
  16. country_laws_ir/reconstruct.py +229 -0
  17. country_laws_ir/sparse.py +12 -5
  18. country_laws_ir/structure.py +1929 -108
  19. country_laws_ir/upload.py +87 -18
  20. country_laws_ir/verify.py +110 -1
  21. data/bm25/documents/part-000000.parquet +2 -2
  22. data/bm25/documents/part-000001.parquet +2 -2
  23. data/bm25/documents/part-000002.parquet +3 -0
  24. data/bm25/postings/part-000000.parquet +2 -2
  25. data/bm25/postings/part-000001.parquet +3 -0
  26. data/corpus/part-000000.parquet +2 -2
  27. data/corpus/part-000001.parquet +2 -2
  28. data/corpus/part-000002.parquet +3 -0
  29. data/graph/adjacency/in/part-000000.parquet +2 -2
  30. data/graph/adjacency/in/part-000001.parquet +2 -2
  31. data/graph/adjacency/in/part-000002.parquet +2 -2
  32. data/graph/adjacency/in/part-000003.parquet +2 -2
  33. data/graph/adjacency/in/part-000004.parquet +2 -2
  34. data/graph/adjacency/in/part-000005.parquet +2 -2
  35. data/graph/adjacency/in/part-000006.parquet +2 -2
  36. data/graph/adjacency/in/part-000007.parquet +2 -2
  37. data/graph/adjacency/in/part-000008.parquet +2 -2
  38. data/graph/adjacency/in/part-000009.parquet +3 -0
  39. data/graph/adjacency/in/part-000010.parquet +3 -0
  40. data/graph/adjacency/out/part-000000.parquet +2 -2
  41. data/graph/adjacency/out/part-000001.parquet +2 -2
  42. data/graph/adjacency/out/part-000002.parquet +2 -2
  43. data/graph/adjacency/out/part-000003.parquet +2 -2
  44. data/graph/adjacency/out/part-000004.parquet +2 -2
  45. data/graph/adjacency/out/part-000005.parquet +2 -2
  46. data/graph/adjacency/out/part-000006.parquet +2 -2
  47. data/graph/adjacency/out/part-000007.parquet +3 -0
  48. data/graph/adjacency/out/part-000008.parquet +3 -0
  49. data/graph/adjacency/out/part-000009.parquet +3 -0
  50. data/graph/edges/part-000000.parquet +2 -2
README.md CHANGED
@@ -11,6 +11,8 @@ tags:
11
  - not-legal-advice
12
  - israel
13
  pretty_name: Israel laws IR (CID-keyed GraphRAG)
 
 
14
  configs:
15
  - config_name: corpus
16
  data_files:
@@ -47,11 +49,13 @@ 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
  # Israel legislation IR (CID-keyed sparse GraphRAG)
@@ -72,14 +76,14 @@ Target Hub id (packaging metadata only): `justicedao/ipfs_israel_laws_ir`.
72
 
73
  | Field | Value |
74
  | --- | --- |
75
- | Laws (corpus units) | 0 |
76
- | Articles (corpus units) | 7915 |
77
- | Canonical docs | 7915 |
78
- | BM25 terms | 3974 |
79
- | BM25 postings | 67751 |
80
- | Graph nodes | 9904 |
81
- | Graph edges | 55405 |
82
- | Vectors | 7915 × 384-d `thenlper/gte-small` (embedded) |
83
 
84
  ## Canonical fields
85
 
 
11
  - not-legal-advice
12
  - israel
13
  pretty_name: Israel laws IR (CID-keyed GraphRAG)
14
+ size_categories:
15
+ - 10K<n<100K
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
+ - he
59
  ---
60
 
61
  # Israel legislation IR (CID-keyed sparse GraphRAG)
 
76
 
77
  | Field | Value |
78
  | --- | --- |
79
+ | Laws (corpus units) | 995 |
80
+ | Articles (corpus units) | 9624 |
81
+ | Canonical docs | 10785 |
82
+ | BM25 terms | 5169 |
83
+ | BM25 postings | 121122 |
84
+ | Graph nodes | 13776 |
85
+ | Graph edges | 75495 |
86
+ | Vectors | 10785 × 384-d `thenlper/gte-small` (embedded) |
87
 
88
  ## Canonical fields
89
 
build.py CHANGED
@@ -176,6 +176,7 @@ def build_country(
176
  force: bool = False,
177
  prior_dir: Path | None = None,
178
  fetch_hub_prior_ir: bool = True,
 
179
  ) -> dict[str, Any]:
180
  country = get_country(source)
181
  if not country.get("indexable", True):
@@ -192,7 +193,8 @@ def build_country(
192
  else None
193
  )
194
  _log(
195
- f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
 
196
  )
197
  configure_hf()
198
  CACHE.mkdir(parents=True, exist_ok=True)
@@ -217,7 +219,7 @@ def build_country(
217
  force=force,
218
  rebuild_stub_vectors=not skip_vectors,
219
  )
220
- if plan.skip_build:
221
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
222
  result = {
223
  "country": country["slug"],
@@ -264,12 +266,35 @@ def build_country(
264
  current_corpus=corpus,
265
  force=force,
266
  rebuild_stub_vectors=not skip_vectors,
 
267
  )
268
  _log(
269
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
270
  f"added={0 if plan.delta is None else plan.delta.n_added} "
271
  f"removed={0 if plan.delta is None else plan.delta.n_removed}"
272
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
  n_docs = len(corpus)
275
  spill = spill_dir_for(country["slug"], CACHE)
@@ -418,6 +443,7 @@ def reindex_from_gaps(
418
  force: bool = False,
419
  all_indexable: bool = False,
420
  device: str = "cuda",
 
421
  ) -> list[dict[str, Any]]:
422
  """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
423
 
@@ -455,6 +481,7 @@ def reindex_from_gaps(
455
  "skip_vectors": skip_vectors,
456
  "fetch_hub_prior_ir": True,
457
  "device": device,
 
458
  }
459
  n_workers = max(1, int(workers or 1))
460
  _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
 
176
  force: bool = False,
177
  prior_dir: Path | None = None,
178
  fetch_hub_prior_ir: bool = True,
179
+ renormalize: bool = False,
180
  ) -> dict[str, Any]:
181
  country = get_country(source)
182
  if not country.get("indexable", True):
 
193
  else None
194
  )
195
  _log(
196
+ f"build start {repo} -> {out} "
197
+ f"(upload={upload} mode={mode} force={force} renormalize={renormalize}) local={local_dir}"
198
  )
199
  configure_hf()
200
  CACHE.mkdir(parents=True, exist_ok=True)
 
219
  force=force,
220
  rebuild_stub_vectors=not skip_vectors,
221
  )
222
+ if plan.skip_build and not renormalize:
223
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
224
  result = {
225
  "country": country["slug"],
 
266
  current_corpus=corpus,
267
  force=force,
268
  rebuild_stub_vectors=not skip_vectors,
269
+ compare_normalized=renormalize and not force,
270
  )
271
  _log(
272
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
273
  f"added={0 if plan.delta is None else plan.delta.n_added} "
274
  f"removed={0 if plan.delta is None else plan.delta.n_removed}"
275
  )
276
+ if plan.skip_build:
277
+ _log(f"skip unchanged after normalize {country['slug']}")
278
+ result = {
279
+ "country": country["slug"],
280
+ "source": repo,
281
+ "source_revision": source_meta["source_revision"],
282
+ "out": str(out),
283
+ "target_hub_id": target_repo(country["slug"]),
284
+ "skipped": True,
285
+ "incremental": plan.to_dict(),
286
+ "normalization": {
287
+ "n_out": norm_report.get("n_out"),
288
+ "unit": norm_report.get("unit"),
289
+ "n_law_rows": norm_report.get("n_law_rows"),
290
+ "n_child_rows": norm_report.get("n_child_rows"),
291
+ },
292
+ "vector_blocker": None,
293
+ "neighbor_via": None,
294
+ "schema_version": "country-laws-ir-graphrag/v1",
295
+ }
296
+ record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
297
+ return result
298
 
299
  n_docs = len(corpus)
300
  spill = spill_dir_for(country["slug"], CACHE)
 
443
  force: bool = False,
444
  all_indexable: bool = False,
445
  device: str = "cuda",
446
+ renormalize: bool = False,
447
  ) -> list[dict[str, Any]]:
448
  """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
449
 
 
481
  "skip_vectors": skip_vectors,
482
  "fetch_hub_prior_ir": True,
483
  "device": device,
484
+ "renormalize": renormalize,
485
  }
486
  n_workers = max(1, int(workers or 1))
487
  _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
country_laws_ir/__main__.py CHANGED
@@ -73,7 +73,9 @@ def main(argv: list[str] | None = None) -> int:
73
  p_re.add_argument("--all", action="store_true",
74
  help="Process every indexable catalog country (not only Hub gaps)")
75
  p_re.add_argument("--force", action="store_true",
76
- help="Rebuild even when the source SHA matches (rerun normalize/verifiers)")
 
 
77
 
78
  p_ver = sub.add_parser(
79
  "verify",
@@ -83,6 +85,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,
@@ -175,6 +192,7 @@ def main(argv: list[str] | None = None) -> int:
175
  force=args.force,
176
  all_indexable=args.all,
177
  device=args.device,
 
178
  )
179
  print(json.dumps(
180
  [
@@ -253,6 +271,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
 
73
  p_re.add_argument("--all", action="store_true",
74
  help="Process every indexable catalog country (not only Hub gaps)")
75
  p_re.add_argument("--force", action="store_true",
76
+ help="Rebuild even when the source SHA matches, and re-encode every row")
77
+ p_re.add_argument("--renormalize", action="store_true",
78
+ help="Rerun normalization, then reindex only packs whose entry rows changed")
79
 
80
  p_ver = sub.add_parser(
81
  "verify",
 
85
  p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country")
86
  p_ver.add_argument("--limit", type=int, default=None)
87
 
88
+ p_loop = sub.add_parser(
89
+ "normalize-loop",
90
+ help="scan residuals, improve the normalizer script with llm_router, or apply that script",
91
+ )
92
+ p_loop.add_argument("stage", choices=["scan", "improve", "apply", "run"])
93
+ p_loop.add_argument("--cache", default=None)
94
+ p_loop.add_argument("--out", default=None)
95
+ p_loop.add_argument("--reports", default=None, help="Per-country residual JSON directory")
96
+ p_loop.add_argument("--slug", default=None, help="One country, for a subprocess")
97
+ p_loop.add_argument("--workers", type=int, default=None, help="Country processes (default: one per CPU)")
98
+ p_loop.add_argument("--limit", type=int, default=None)
99
+ p_loop.add_argument("--passes", type=int, default=40, help="Improve batches sent to llm_router")
100
+ p_loop.add_argument("--force", action="store_true", help="Redo finished countries and retry unresolved lines")
101
+ p_loop.add_argument("--progress", default=None, help="JSONL file appended as each country or improve pass finishes")
102
+
103
  p_raw = sub.add_parser("package-raw")
104
  p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
105
  p_raw.add_argument("--instruments-dir", default=None,
 
192
  force=args.force,
193
  all_indexable=args.all,
194
  device=args.device,
195
+ renormalize=args.renormalize,
196
  )
197
  print(json.dumps(
198
  [
 
271
  )
272
  )
273
  return 1 if failed else 0
274
+ if args.cmd == "normalize-loop":
275
+ from .build import CACHE, ROOT
276
+ from .normalize_loop import (
277
+ _apply_job,
278
+ _scan_job,
279
+ append_progress,
280
+ apply_done,
281
+ cache_packs,
282
+ improve_from_reports,
283
+ load_generate_text,
284
+ run_parallel,
285
+ scan_done,
286
+ worker_count,
287
+ )
288
+
289
+ cache = Path(args.cache) if args.cache else CACHE
290
+ reports = Path(args.reports) if args.reports else ROOT / "reports" / "residuals"
291
+ out = Path(args.out) if args.out else ROOT / "llm-normalized"
292
+ packs = cache_packs(cache, slug=args.slug)
293
+ if args.limit:
294
+ packs = packs[: int(args.limit)]
295
+ workers = worker_count(args.workers)
296
+ progress = Path(args.progress) if args.progress else ROOT / "reports" / f"normalize_{args.stage}.jsonl"
297
+
298
+ def _pending(stage: str) -> tuple[list[tuple[str, str, str]], list[str]]:
299
+ jobs: list[tuple[str, str, str]] = []
300
+ skipped: list[str] = []
301
+ for slug, path in packs:
302
+ done = scan_done(reports, slug) if stage == "scan" else apply_done(out, slug)
303
+ if done and not args.force:
304
+ skipped.append(slug)
305
+ continue
306
+ dest = reports if stage == "scan" else out
307
+ jobs.append((slug, str(path), str(dest)))
308
+ return jobs, skipped
309
+
310
+ def _run(stage: str, worker) -> list[dict]:
311
+ jobs, skipped = _pending(stage)
312
+ total = len(jobs) + len(skipped)
313
+ done = len(skipped)
314
+ print(json.dumps({
315
+ "event": "start",
316
+ "stage": stage,
317
+ "workers": workers,
318
+ "done": done,
319
+ "pending": len(jobs),
320
+ "total": total,
321
+ "progress": str(progress),
322
+ }), flush=True)
323
+ state = {"done": done}
324
+
325
+ def _on_done(row: dict) -> None:
326
+ state["done"] += 1
327
+ print(json.dumps({
328
+ "event": stage,
329
+ "done": state["done"],
330
+ "total": total,
331
+ **row,
332
+ }), flush=True)
333
+
334
+ return run_parallel(jobs, worker, workers, progress_path=progress, on_done=_on_done)
335
+
336
+ if args.stage == "scan":
337
+ rows = _run("scan", _scan_job)
338
+ failed = [row for row in rows if row.get("error")]
339
+ print(json.dumps({"stage": "scan", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2))
340
+ return 1 if failed else 0
341
+ if args.stage == "apply":
342
+ rows = _run("apply", _apply_job)
343
+ failed = [row for row in rows if row.get("error")]
344
+ print(json.dumps({"stage": "apply", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2))
345
+ return 1 if failed else 0
346
+ def _on_pass(row: dict) -> None:
347
+ print(json.dumps({"event": "improve", **row}, ensure_ascii=False), flush=True)
348
+ append_progress(progress, {"event": "improve", **row})
349
+
350
+ def _improve():
351
+ print(json.dumps({
352
+ "event": "start",
353
+ "stage": "improve",
354
+ "passes": args.passes,
355
+ "reports": str(reports),
356
+ }), flush=True)
357
+ try:
358
+ generate = load_generate_text()
359
+ except Exception as exc:
360
+ print(json.dumps({"error": f"llm_router unavailable: {exc}"}), flush=True)
361
+ return None
362
+ return improve_from_reports(
363
+ reports,
364
+ generate,
365
+ max_passes=args.passes,
366
+ on_pass=_on_pass,
367
+ reset_unresolved=bool(args.force),
368
+ )
369
+
370
+ if args.stage == "improve":
371
+ result = _improve()
372
+ if result is None:
373
+ return 1
374
+ print(json.dumps({"stage": "improve", **result}, indent=2, ensure_ascii=False))
375
+ return 0
376
+ # run scans, then improves the script. Applying the script to every
377
+ # pack is the separate ``apply`` stage.
378
+ scan_rows = _run("scan", _scan_job)
379
+ failed = [row for row in scan_rows if row.get("error")]
380
+ if failed:
381
+ print(json.dumps({"stage": "run", "n_scanned": len(scan_rows), "n_failed": len(failed)}, indent=2))
382
+ return 1
383
+ improved = _improve()
384
+ if improved is None:
385
+ return 1
386
+ print(json.dumps(
387
+ {"stage": "run", "workers": workers, "improve": improved, "n_scanned": len(scan_rows)},
388
+ indent=2,
389
+ ensure_ascii=False,
390
+ default=str,
391
+ ))
392
+ return 0
393
  if args.cmd == "package-raw":
394
  from .build import RELEASES
395
  from .raw_package import default_instruments_dir, package_instruments
country_laws_ir/build.py CHANGED
@@ -176,6 +176,7 @@ def build_country(
176
  force: bool = False,
177
  prior_dir: Path | None = None,
178
  fetch_hub_prior_ir: bool = True,
 
179
  ) -> dict[str, Any]:
180
  country = get_country(source)
181
  if not country.get("indexable", True):
@@ -192,7 +193,8 @@ def build_country(
192
  else None
193
  )
194
  _log(
195
- f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
 
196
  )
197
  configure_hf()
198
  CACHE.mkdir(parents=True, exist_ok=True)
@@ -217,7 +219,7 @@ def build_country(
217
  force=force,
218
  rebuild_stub_vectors=not skip_vectors,
219
  )
220
- if plan.skip_build:
221
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
222
  result = {
223
  "country": country["slug"],
@@ -264,12 +266,35 @@ def build_country(
264
  current_corpus=corpus,
265
  force=force,
266
  rebuild_stub_vectors=not skip_vectors,
 
267
  )
268
  _log(
269
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
270
  f"added={0 if plan.delta is None else plan.delta.n_added} "
271
  f"removed={0 if plan.delta is None else plan.delta.n_removed}"
272
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
  n_docs = len(corpus)
275
  spill = spill_dir_for(country["slug"], CACHE)
@@ -418,6 +443,7 @@ def reindex_from_gaps(
418
  force: bool = False,
419
  all_indexable: bool = False,
420
  device: str = "cuda",
 
421
  ) -> list[dict[str, Any]]:
422
  """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
423
 
@@ -455,6 +481,7 @@ def reindex_from_gaps(
455
  "skip_vectors": skip_vectors,
456
  "fetch_hub_prior_ir": True,
457
  "device": device,
 
458
  }
459
  n_workers = max(1, int(workers or 1))
460
  _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
 
176
  force: bool = False,
177
  prior_dir: Path | None = None,
178
  fetch_hub_prior_ir: bool = True,
179
+ renormalize: bool = False,
180
  ) -> dict[str, Any]:
181
  country = get_country(source)
182
  if not country.get("indexable", True):
 
193
  else None
194
  )
195
  _log(
196
+ f"build start {repo} -> {out} "
197
+ f"(upload={upload} mode={mode} force={force} renormalize={renormalize}) local={local_dir}"
198
  )
199
  configure_hf()
200
  CACHE.mkdir(parents=True, exist_ok=True)
 
219
  force=force,
220
  rebuild_stub_vectors=not skip_vectors,
221
  )
222
+ if plan.skip_build and not renormalize:
223
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
224
  result = {
225
  "country": country["slug"],
 
266
  current_corpus=corpus,
267
  force=force,
268
  rebuild_stub_vectors=not skip_vectors,
269
+ compare_normalized=renormalize and not force,
270
  )
271
  _log(
272
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
273
  f"added={0 if plan.delta is None else plan.delta.n_added} "
274
  f"removed={0 if plan.delta is None else plan.delta.n_removed}"
275
  )
276
+ if plan.skip_build:
277
+ _log(f"skip unchanged after normalize {country['slug']}")
278
+ result = {
279
+ "country": country["slug"],
280
+ "source": repo,
281
+ "source_revision": source_meta["source_revision"],
282
+ "out": str(out),
283
+ "target_hub_id": target_repo(country["slug"]),
284
+ "skipped": True,
285
+ "incremental": plan.to_dict(),
286
+ "normalization": {
287
+ "n_out": norm_report.get("n_out"),
288
+ "unit": norm_report.get("unit"),
289
+ "n_law_rows": norm_report.get("n_law_rows"),
290
+ "n_child_rows": norm_report.get("n_child_rows"),
291
+ },
292
+ "vector_blocker": None,
293
+ "neighbor_via": None,
294
+ "schema_version": "country-laws-ir-graphrag/v1",
295
+ }
296
+ record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
297
+ return result
298
 
299
  n_docs = len(corpus)
300
  spill = spill_dir_for(country["slug"], CACHE)
 
443
  force: bool = False,
444
  all_indexable: bool = False,
445
  device: str = "cuda",
446
+ renormalize: bool = False,
447
  ) -> list[dict[str, Any]]:
448
  """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
449
 
 
481
  "skip_vectors": skip_vectors,
482
  "fetch_hub_prior_ir": True,
483
  "device": device,
484
+ "renormalize": renormalize,
485
  }
486
  n_workers = max(1, int(workers or 1))
487
  _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
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
@@ -21,6 +21,15 @@ FACET_FIELDS = (
21
  )
22
  ADJ_POINTERS_PER_ROW = 4096
23
  ADJ_POINTERS_PER_SHARD = 8192
 
 
 
 
 
 
 
 
 
24
 
25
 
26
  def _facet_cid(kind: str, value: str) -> str:
@@ -68,7 +77,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,
@@ -85,14 +94,19 @@ def build_graph(
85
  nodes.append(law_node)
86
 
87
  for rec in corpus.itertuples(index=False):
88
- node_type = "law_entry" if rec.record_type == "law" else "article"
 
 
 
 
 
89
  title = getattr(rec, "title", None) or getattr(rec, "instrument_title", None) or rec.source_id
90
  nodes.append(
91
  {
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 +126,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
  }
@@ -130,7 +144,7 @@ def build_graph(
130
  "node_cid": fc,
131
  "node_type": "facet_eli",
132
  "entry_cid": "",
133
- "label": f"eli:{eli}",
134
  "properties_json": _json({"kind": "eli", "value": eli}),
135
  "schema_version": SCHEMA_VERSION,
136
  }
@@ -146,7 +160,7 @@ def build_graph(
146
  "node_cid": fc,
147
  "node_type": "facet_identifier",
148
  "entry_cid": "",
149
- "label": f"identifier:{ident}",
150
  "properties_json": _json({"kind": "identifier", "value": ident}),
151
  "schema_version": SCHEMA_VERSION,
152
  }
@@ -157,7 +171,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(
 
21
  )
22
  ADJ_POINTERS_PER_ROW = 4096
23
  ADJ_POINTERS_PER_SHARD = 8192
24
+ _LABEL_MAX = 4096
25
+
26
+
27
+ def _graph_label(text: str, fallback: str) -> str:
28
+ """Node labels are capped at 4096 characters. The full value stays in properties."""
29
+ cleaned = str(text or "").replace("\x00", "").strip() or fallback
30
+ if len(cleaned) > _LABEL_MAX:
31
+ return cleaned[: _LABEL_MAX - 3] + "..."
32
+ return cleaned
33
 
34
 
35
  def _facet_cid(kind: str, value: str) -> str:
 
77
  "node_cid": law_cid,
78
  "node_type": "law",
79
  "entry_cid": "",
80
+ "label": _graph_label(getattr(rec, "instrument_title", None) or instrument_id, instrument_id),
81
  "properties_json": _json(
82
  {
83
  "instrument_id": instrument_id,
 
94
  nodes.append(law_node)
95
 
96
  for rec in corpus.itertuples(index=False):
97
+ if rec.record_type == "law":
98
+ node_type = "law_entry"
99
+ elif rec.record_type == "notice":
100
+ node_type = "notice"
101
+ else:
102
+ node_type = "article"
103
  title = getattr(rec, "title", None) or getattr(rec, "instrument_title", None) or rec.source_id
104
  nodes.append(
105
  {
106
  "node_cid": rec.entry_cid,
107
  "node_type": node_type,
108
  "entry_cid": rec.entry_cid,
109
+ "label": _graph_label(title or rec.source_id, str(rec.source_id)),
110
  "properties_json": _props_tuple(rec),
111
  "schema_version": SCHEMA_VERSION,
112
  }
 
126
  "node_cid": fc,
127
  "node_type": f"facet_{kind}",
128
  "entry_cid": "",
129
+ "label": _graph_label(f"{kind}:{value}", kind),
130
  "properties_json": _json({"kind": kind, "value": value}),
131
  "schema_version": SCHEMA_VERSION,
132
  }
 
144
  "node_cid": fc,
145
  "node_type": "facet_eli",
146
  "entry_cid": "",
147
+ "label": _graph_label(f"eli:{eli}", "eli"),
148
  "properties_json": _json({"kind": "eli", "value": eli}),
149
  "schema_version": SCHEMA_VERSION,
150
  }
 
160
  "node_cid": fc,
161
  "node_type": "facet_identifier",
162
  "entry_cid": "",
163
+ "label": _graph_label(f"identifier:{ident}", "identifier"),
164
  "properties_json": _json({"kind": "identifier", "value": ident}),
165
  "schema_version": SCHEMA_VERSION,
166
  }
 
171
 
172
  law_cid = str(row_map.get("law_cid") or "")
173
  instrument_id = str(row_map.get("instrument_id") or "")
174
+ if rec.record_type in {"article", "section"}:
175
  parent = entry_by_instrument.get(instrument_id) or law_cid
176
  if parent and parent != rec.entry_cid:
177
  edges.append(
country_laws_ir/incremental.py CHANGED
@@ -235,6 +235,7 @@ def plan_rebuild(
235
  current_corpus: pd.DataFrame | None = None,
236
  force: bool = False,
237
  rebuild_stub_vectors: bool = True,
 
238
  ) -> RebuildPlan:
239
  """Decide skip / delta / full from source fingerprints and CID overlap."""
240
  mode = BuildMode.coerce(mode)
@@ -288,7 +289,8 @@ def plan_rebuild(
288
  "partial",
289
  }
290
 
291
- if prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors:
 
292
  return RebuildPlan(
293
  kind=RebuildKind.UNCHANGED,
294
  mode=mode,
@@ -312,6 +314,20 @@ def plan_rebuild(
312
  delta = None
313
  if current_corpus is not None:
314
  delta = diff_corpus(prior.corpus, current_corpus)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  if delta.equivalent_to_full:
316
  return RebuildPlan(
317
  kind=RebuildKind.FULL_REBUILD,
 
235
  current_corpus: pd.DataFrame | None = None,
236
  force: bool = False,
237
  rebuild_stub_vectors: bool = True,
238
+ compare_normalized: bool = False,
239
  ) -> RebuildPlan:
240
  """Decide skip / delta / full from source fingerprints and CID overlap."""
241
  mode = BuildMode.coerce(mode)
 
289
  "partial",
290
  }
291
 
292
+ fingerprint_match = bool(prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors)
293
+ if fingerprint_match and not (compare_normalized and current_corpus is not None):
294
  return RebuildPlan(
295
  kind=RebuildKind.UNCHANGED,
296
  mode=mode,
 
314
  delta = None
315
  if current_corpus is not None:
316
  delta = diff_corpus(prior.corpus, current_corpus)
317
+ if delta.n_added == 0 and delta.n_removed == 0 and not stub_vectors:
318
+ return RebuildPlan(
319
+ kind=RebuildKind.UNCHANGED,
320
+ mode=mode,
321
+ reason="normalized entry_cids match the prior release",
322
+ source_revision=revision,
323
+ prior_revision=prior_revision,
324
+ source_fingerprint=fingerprint,
325
+ prior_fingerprint=prior_fp,
326
+ delta=delta,
327
+ reuse_embeddings=True,
328
+ skip_build=True,
329
+ equivalent_to_full=False,
330
+ )
331
  if delta.equivalent_to_full:
332
  return RebuildPlan(
333
  kind=RebuildKind.FULL_REBUILD,
country_laws_ir/normalize.py CHANGED
@@ -12,6 +12,7 @@ from __future__ import annotations
12
 
13
  import json
14
  import os
 
15
  from collections import Counter
16
  from pathlib import Path
17
  from typing import Any
@@ -24,6 +25,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"
@@ -311,6 +318,118 @@ def _hierarchy_fields(
311
  }
312
 
313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  def _collector(meta: dict[str, Any], source_dataset: str) -> str:
315
  nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
316
  for blob in (meta, nested):
@@ -399,6 +518,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 +602,158 @@ 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")
@@ -477,6 +766,16 @@ def build_corpus(
477
  report["drop_samples"]["empty_body"].append(source_id)
478
  continue
479
  parent = law_map.get(instrument_id)
 
 
 
 
 
 
 
 
 
 
480
  if not parent:
481
  report["drops"]["missing_instrument"] += 1
482
  if len(report["drop_samples"]["missing_instrument"]) < 20:
@@ -521,22 +820,74 @@ 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"])
534
  if units:
535
  report["unit"] = "structured"
 
536
  for unit in units:
537
  entries.append(
538
  _base_record(
539
- record_type=unit.kind if unit.kind in {"article", "section"} else "article",
 
 
 
 
 
540
  source_dataset=source_dataset,
541
  source_revision=source_revision,
542
  instrument_id=instrument_id,
@@ -572,49 +923,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 +952,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"]
 
12
 
13
  import json
14
  import os
15
+ import re
16
  from collections import Counter
17
  from pathlib import Path
18
  from typing import Any
 
25
  from .auth import configure_hf, public_token
26
  from .cidutil import cid_of_json, sha256_file, sha256_hex
27
  from .schema import SchemaError, validate_articles, validate_laws
28
+ from .reconstruct import (
29
+ article_sort_key,
30
+ parent_needs_reconstruct,
31
+ reconstruct_on,
32
+ reconstruct_parent,
33
+ )
34
  from .structure import normalize_legal_text, split_structured_units
35
 
36
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
 
318
  }
319
 
320
 
321
+ def _compact_line(text: str) -> str:
322
+ return re.sub(r"\s+", " ", text or "").strip().casefold()
323
+
324
+
325
+ def _is_title_shell(body: str, title: str) -> bool:
326
+ """True when the article row is only its heading, repeated once."""
327
+ folded_body = _compact_line(body)
328
+ folded_title = _compact_line(title)
329
+ if len(folded_title) < 24 or not folded_body:
330
+ return False
331
+ return folded_body == folded_title or folded_body == f"{folded_title} {folded_title}"
332
+
333
+
334
+ _NOTICE_RE = re.compile(
335
+ r"(?i)(\bnewsletter\b|\bblog\b|press release|communiqu[eé]|"
336
+ r"\bnews item\b|\bnotice board\b)"
337
+ )
338
+
339
+
340
+ def _instrument_record_type(metadata: dict[str, Any], title: str) -> str:
341
+ """A normative instrument is a law, even when its title says Article.
342
+
343
+ Newsletters, blogs, and press notices are not laws. A provision inside a
344
+ law stays an article; this label is only for the instrument itself.
345
+ """
346
+ meta = metadata or {}
347
+ document_type = str(meta.get("document_type") or "").strip().casefold()
348
+ meta_type = str(meta.get("record_type") or "").strip().casefold()
349
+ if _NOTICE_RE.search(title or "") or document_type in {
350
+ "newsletter",
351
+ "blog",
352
+ "press",
353
+ "press_release",
354
+ "notice",
355
+ }:
356
+ return "notice"
357
+ if document_type in {"gazette", "gazette_pdf"} and meta_type not in {
358
+ "law",
359
+ "statute",
360
+ "constitution",
361
+ }:
362
+ return "notice"
363
+ return "law"
364
+
365
+
366
+ def _unit_record_type(unit: Any, instrument_type: str, *, n_units: int, parent_body: str) -> str:
367
+ """One unit that is the whole instrument keeps the instrument label."""
368
+ if instrument_type == "notice":
369
+ return "notice"
370
+ if (
371
+ n_units == 1
372
+ and parent_body
373
+ and len(getattr(unit, "body", "") or "") >= int(0.8 * len(parent_body))
374
+ ):
375
+ return "law"
376
+ kind = getattr(unit, "kind", "") or ""
377
+ if kind in {"article", "section"}:
378
+ return kind
379
+ return "article"
380
+
381
+
382
+ def _children_are_rich(kids: list[dict[str, Any]], parent_body: str) -> bool:
383
+ """True when the article rows already carry the statute, not just headings."""
384
+ if not kids:
385
+ return False
386
+ total = sum(len((kid.get("body") or "").strip()) for kid in kids)
387
+ if total >= max(int(len(parent_body) * 0.5), 200):
388
+ return True
389
+ return any(
390
+ len((kid.get("body") or "").strip()) >= 80
391
+ and not _is_title_shell(kid.get("body") or "", kid.get("title") or "")
392
+ for kid in kids
393
+ )
394
+
395
+
396
+ def _needs_parent_split(kids: list[dict[str, Any]], parent_body: str) -> bool:
397
+ """Split the parent when it holds the text and the article rows do not."""
398
+ if len(parent_body) < 250 or len(parent_body) > 1_200_000:
399
+ return False
400
+ return not _children_are_rich(kids, parent_body)
401
+
402
+
403
+ def _expand_title_shell(parent: str, title: str, sibling_titles: set[str]) -> str | None:
404
+ """Copy the parent span from this heading to the next sibling heading.
405
+
406
+ The span is taken only from lines already in the parent. A short heading
407
+ such as "Article 1" is left alone, because it matches too many lines.
408
+ """
409
+ key = _compact_line(title)
410
+ peers = {item for item in sibling_titles if item and item != key and len(item) >= 24}
411
+ if len(key) < 24 or not peers or not parent:
412
+ return None
413
+ lines = [ln.strip() for ln in parent.splitlines() if ln.strip()]
414
+ compact = [_compact_line(ln) for ln in lines]
415
+ best = ""
416
+ for index, folded in enumerate(compact):
417
+ if folded != key:
418
+ continue
419
+ chunk = [lines[index]]
420
+ for later, later_folded in zip(lines[index + 1 :], compact[index + 1 :]):
421
+ if later_folded in peers:
422
+ break
423
+ chunk.append(later)
424
+ text = "\n".join(chunk).strip()
425
+ if len(text) > len(best):
426
+ best = text
427
+ # The heading alone is not enough. Require a following sentence from the parent.
428
+ if len(best) < len(key) + 40:
429
+ return None
430
+ return best
431
+
432
+
433
  def _collector(meta: dict[str, Any], source_dataset: str) -> str:
434
  nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
435
  for blob in (meta, nested):
 
518
  }
519
  if extra:
520
  rec.update(extra)
521
+ from .citations import assign_citation, citation_fields
522
+
523
+ slug = ""
524
+ if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
525
+ slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
526
+ year = ""
527
+ if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit():
528
+ year = snapshot_date[:4]
529
+ extra = extra or {}
530
+ rec.update(
531
+ citation_fields(
532
+ assign_citation(
533
+ eli=str(rec.get("eli") or extra.get("eli") or ""),
534
+ official_identifier=str(
535
+ rec.get("official_identifier") or extra.get("official_identifier") or ""
536
+ ),
537
+ identifier=str(rec.get("identifier") or extra.get("identifier") or ""),
538
+ instrument_title=instrument_title,
539
+ article_number=article_number,
540
+ section_number=str(extra.get("section_number") or ""),
541
+ record_type=record_type,
542
+ jurisdiction=jurisdiction,
543
+ country=str(extra.get("country") or ""),
544
+ slug=slug,
545
+ year=year,
546
+ )
547
+ )
548
+ )
549
  rec["entry_cid"] = _entry_cid(rec)
550
  rec["title_length"] = len(title_for_bm25)
551
  rec["body_length"] = len(body)
 
602
  "schema_surprises": list(source_meta.get("schema_surprises") or []),
603
  "n_out": 0,
604
  "never_invented_legal_text": True,
605
+ "n_reconstructed_parents": 0,
606
+ "n_reconstructed_truncated": 0,
607
+ "n_reconstructed_stubs": 0,
608
+ "n_empty_parents_with_articles_not_reconstructed": 0,
609
+ "n_thin_instruments_replaced": 0,
610
  }
611
 
612
  entries: list[dict[str, Any]] = []
613
+ slug = ""
614
+ if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
615
+ slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
616
+
617
+ children_by_law: dict[str, list[dict[str, Any]]] = {}
618
+ if not articles_empty:
619
+ for _, row in articles.iterrows():
620
+ lid = _row_get(row, "law_id")
621
+ if not lid:
622
+ continue
623
+ children_by_law.setdefault(lid, []).append(
624
+ {
625
+ "id": _row_get(row, "id"),
626
+ "title": _row_get(row, "title"),
627
+ "article_number": _row_get(row, "article_number"),
628
+ "body": _row_get(row, "text"),
629
+ "row": row,
630
+ }
631
+ )
632
+
633
+ reconstructed_ids: set[str] = set()
634
+ running_extra_bytes = 0
635
+
636
+ def _append_law_row(
637
+ instrument_id: str,
638
+ parent: dict[str, Any],
639
+ recon=None,
640
+ ) -> None:
641
+ body = parent["body"]
642
+ recon_extra: dict[str, Any] = {}
643
+ coverage = _coverage_from(
644
+ parent["row"],
645
+ parent["metadata"],
646
+ articles_empty=articles_empty,
647
+ sparse_fallback=sparse_fallback,
648
+ )
649
+ if recon is not None and recon.reconstructed_from_articles:
650
+ body = recon.body
651
+ recon_extra = recon.extra_fields()
652
+ coverage = f"{coverage}; reconstructed_from_articles"
653
+ if not body:
654
+ kids = children_by_law.get(instrument_id) or []
655
+ if kids:
656
+ report["n_empty_parents_with_articles_not_reconstructed"] += 1
657
+ report["drops"]["empty_body"] += 1
658
+ if len(report["drop_samples"]["empty_body"]) < 20:
659
+ report["drop_samples"]["empty_body"].append(instrument_id)
660
+ return
661
+ meta = parent["metadata"]
662
+ entries.append(
663
+ _base_record(
664
+ record_type=_instrument_record_type(meta, parent["instrument_title"]),
665
+ source_dataset=source_dataset,
666
+ source_revision=source_revision,
667
+ instrument_id=instrument_id,
668
+ instrument_title=parent["instrument_title"],
669
+ law_cid=parent["law_cid"],
670
+ article_number="",
671
+ article_title="",
672
+ body=body,
673
+ jurisdiction=parent["jurisdiction"],
674
+ language=parent["language"],
675
+ source_url=parent["source_url"],
676
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
677
+ coverage=coverage,
678
+ license_expr=parent["license"],
679
+ collector=_collector(meta, source_dataset),
680
+ source_id=instrument_id,
681
+ extra={
682
+ "eli": parent["eli"],
683
+ "identifier": parent["identifier"],
684
+ "official_identifier": parent["official_identifier"],
685
+ "source_type": parent["source_type"],
686
+ "country": parent["country"],
687
+ "law_status": parent["law_status"],
688
+ "parent_law_id": "",
689
+ "article_id": "",
690
+ "reconstructed_from_articles": False,
691
+ **_hierarchy_fields(
692
+ parent["instrument_title"], body, "", language=parent["language"]
693
+ ),
694
+ **recon_extra,
695
+ },
696
+ )
697
+ )
698
 
699
  if sparse_fallback:
700
  report["schema_surprises"].append(
701
  f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
702
  )
703
 
704
+ for instrument_id, parent in law_map.items():
705
+ kids = children_by_law.get(instrument_id) or []
706
+ recon = None
707
+ if reconstruct_on() and parent_needs_reconstruct(parent["body"], len(kids)):
708
+ recon = reconstruct_parent(
709
+ slug=slug,
710
+ parent_body=parent["body"],
711
+ parent_title=parent["instrument_title"],
712
+ children=[
713
+ {
714
+ "id": k["id"],
715
+ "title": k["title"],
716
+ "article_number": k["article_number"],
717
+ "body": k["body"],
718
+ }
719
+ for k in kids
720
+ ],
721
+ running_extra_bytes=running_extra_bytes,
722
+ sha256_hex=sha256_hex,
723
+ )
724
+ running_extra_bytes += recon.extra_bytes
725
+ reconstructed_ids.add(instrument_id)
726
+ report["n_reconstructed_parents"] += 1
727
+ if recon.reconstruction_truncated:
728
+ report["n_reconstructed_truncated"] += 1
729
+ if recon.is_stub:
730
+ report["n_reconstructed_stubs"] += 1
731
+ _append_law_row(instrument_id, parent, recon)
732
+
733
+ emit_articles = use_articles or bool(reconstructed_ids)
734
+ skip_body_split = emit_articles
735
+ sibling_titles = {
736
+ instrument_id: {_compact_line(kid["title"]) for kid in kids}
737
+ for instrument_id, kids in children_by_law.items()
738
+ }
739
+ promoted: dict[str, list[Any]] = {}
740
+ if emit_articles:
741
+ for instrument_id, parent in law_map.items():
742
+ kids = children_by_law.get(instrument_id) or []
743
+ if not _needs_parent_split(kids, parent["body"]):
744
+ continue
745
+ units = split_structured_units(parent["body"], language=parent["language"])
746
+ covered = sum(len(unit.body) for unit in units)
747
+ if len(units) >= 2 and covered >= int(0.35 * len(parent["body"])):
748
+ promoted[instrument_id] = units
749
+ if promoted:
750
+ report["n_thin_instruments_replaced"] = len(promoted)
751
+ report["schema_surprises"].append(
752
+ "parent headings used for "
753
+ f"{len(promoted)} instruments whose article rows were missing or thin"
754
+ )
755
+
756
+ if emit_articles:
757
  for _, row in articles.iterrows():
758
  source_id = _row_get(row, "id")
759
  instrument_id = _row_get(row, "law_id")
 
766
  report["drop_samples"]["empty_body"].append(source_id)
767
  continue
768
  parent = law_map.get(instrument_id)
769
+ if instrument_id in promoted:
770
+ continue
771
+ if parent and _is_title_shell(body, article_title):
772
+ expanded = _expand_title_shell(
773
+ parent["body"],
774
+ article_title,
775
+ sibling_titles.get(instrument_id) or set(),
776
+ )
777
+ if expanded:
778
+ body = expanded
779
  if not parent:
780
  report["drops"]["missing_instrument"] += 1
781
  if len(report["drop_samples"]["missing_instrument"]) < 20:
 
820
  },
821
  )
822
  )
823
+ for instrument_id, units in promoted.items():
824
+ parent = law_map[instrument_id]
825
+ meta = parent["metadata"]
826
+ report["unit"] = "structured"
827
+ instrument_type = _instrument_record_type(meta, parent["instrument_title"])
828
+ for unit in units:
829
+ entries.append(
830
+ _base_record(
831
+ record_type=_unit_record_type(
832
+ unit,
833
+ instrument_type,
834
+ n_units=len(units),
835
+ parent_body=parent["body"],
836
+ ),
837
+ source_dataset=source_dataset,
838
+ source_revision=source_revision,
839
+ instrument_id=instrument_id,
840
+ instrument_title=parent["instrument_title"],
841
+ law_cid=parent["law_cid"],
842
+ article_number=unit.article_number or unit.number,
843
+ article_title=unit.heading,
844
+ body=unit.body,
845
+ jurisdiction=parent["jurisdiction"],
846
+ language=parent["language"],
847
+ source_url=parent["source_url"],
848
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
849
+ coverage="structured (thin article rows replaced from the parent law)",
850
+ license_expr=parent["license"],
851
+ collector=_collector(meta, source_dataset),
852
+ source_id=f"{instrument_id}-{unit.kind}-{unit.number}",
853
+ extra={
854
+ "eli": parent["eli"],
855
+ "identifier": parent["identifier"],
856
+ "official_identifier": parent["official_identifier"],
857
+ "source_type": parent["source_type"],
858
+ "country": parent["country"],
859
+ "law_status": parent["law_status"],
860
+ "parent_law_id": instrument_id,
861
+ "article_id": "",
862
+ "hierarchy_kind": unit.kind,
863
+ "hierarchy_path": unit.hierarchy_path,
864
+ "title_number": unit.title_number,
865
+ "chapter_number": unit.chapter_number,
866
+ "part_number": unit.part_number,
867
+ "section_number": unit.section_number,
868
+ "subsections": list(unit.subsections),
869
+ },
870
+ )
871
+ )
872
+ elif not skip_body_split:
873
  for instrument_id, parent in law_map.items():
874
  body = parent["body"]
875
  if not body:
 
 
 
876
  continue
877
  meta = parent["metadata"]
878
  units = split_structured_units(body, language=parent["language"])
879
  if units:
880
  report["unit"] = "structured"
881
+ instrument_type = _instrument_record_type(meta, parent["instrument_title"])
882
  for unit in units:
883
  entries.append(
884
  _base_record(
885
+ record_type=_unit_record_type(
886
+ unit,
887
+ instrument_type,
888
+ n_units=len(units),
889
+ parent_body=body,
890
+ ),
891
  source_dataset=source_dataset,
892
  source_revision=source_revision,
893
  instrument_id=instrument_id,
 
923
  },
924
  )
925
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
926
 
927
  entries.sort(
928
  key=lambda r: (
929
  r["instrument_id"],
930
+ article_sort_key(r.get("article_number") or "", r["source_id"]),
 
931
  )
932
  )
933
  n_before = len(entries)
 
952
  raise SchemaError("Duplicate entry_cid remained after dedupe")
953
  report["n_before_dedupe"] = n_before
954
  report["n_out"] = int(len(df))
955
+ if not df.empty and "record_type" in df.columns:
956
+ n_law_rows = int((df["record_type"] == "law").sum())
957
+ n_child_rows = int(df["record_type"].isin(["article", "section"]).sum())
958
+ report["n_law_rows"] = n_law_rows
959
+ report["n_child_rows"] = n_child_rows
960
+ report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows
961
+ if n_law_rows and n_child_rows:
962
+ report["unit"] = (
963
+ "law+structured" if report.get("unit") == "structured" else "law+article"
964
+ )
965
+ elif n_law_rows:
966
+ report["unit"] = "law"
967
+ elif n_child_rows:
968
+ report["unit"] = "article"
969
  report["n_dropped_total"] = (
970
  report["drops"]["empty_body"]
971
  + report["drops"]["missing_instrument"]
country_laws_ir/normalize_loop.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ _BARE_PATTERN = re.compile(r"\^[^\n]{1,180}\$")
292
+
293
+
294
+ def _patterns_from_model_text(raw: str) -> list[str]:
295
+ """Read whole-line patterns from JSON, or from a model that skipped the JSON."""
296
+ start, end = raw.find("{"), raw.rfind("}")
297
+ if start >= 0 and end > start:
298
+ try:
299
+ payload = json.loads(raw[start : end + 1])
300
+ except json.JSONDecodeError:
301
+ payload = None
302
+ found = payload.get("line_patterns") if isinstance(payload, dict) else None
303
+ if isinstance(found, list):
304
+ return [item for item in found if isinstance(item, str)]
305
+ seen: set[str] = set()
306
+ bare: list[str] = []
307
+ for item in _BARE_PATTERN.findall(raw):
308
+ if item not in seen and item != "^...$":
309
+ seen.add(item)
310
+ bare.append(item)
311
+ return bare
312
+
313
+
314
+ def propose_line_patterns(
315
+ leftovers: Sequence[dict[str, Any]],
316
+ generate_text: GenerateText,
317
+ *,
318
+ char_budget: int = PROMPT_CHAR_BUDGET,
319
+ ) -> list[str]:
320
+ """One router call. The model proposes whole-line patterns, not statute text."""
321
+ if not leftovers:
322
+ return []
323
+ body: list[str] = []
324
+ used = len(_PROMPT_PREFIX)
325
+ for item in leftovers:
326
+ row = f"- {item['count']}× {item['line']}\n"
327
+ if used + len(row) > char_budget:
328
+ break
329
+ body.append(row)
330
+ used += len(row)
331
+ if not body:
332
+ room = max(0, char_budget - len(_PROMPT_PREFIX) - 16)
333
+ snippet = str(leftovers[0]["line"])[:room]
334
+ body.append(f"- {leftovers[0]['count']}× {snippet}\n")
335
+ raw = str(generate_text(_PROMPT_PREFIX + "".join(body)))
336
+ return _patterns_from_model_text(raw)
337
+
338
+
339
+ def load_learned_patterns() -> list[str]:
340
+ path = learned_patterns_path()
341
+ if not path.is_file():
342
+ return []
343
+ try:
344
+ payload = json.loads(path.read_text(encoding="utf-8"))
345
+ except (OSError, json.JSONDecodeError):
346
+ return []
347
+ return [item for item in payload.get("patterns") or [] if isinstance(item, str)]
348
+
349
+
350
+ def save_learned_patterns(patterns: Sequence[str]) -> None:
351
+ path = learned_patterns_path()
352
+ path.parent.mkdir(parents=True, exist_ok=True)
353
+ path.write_text(
354
+ json.dumps({"patterns": list(patterns)}, ensure_ascii=False, indent=2) + "\n",
355
+ encoding="utf-8",
356
+ )
357
+ # The structure cache keys on mtime; the write updates it.
358
+
359
+
360
+ def unresolved_path(report_dir: Path) -> Path:
361
+ return report_dir / "_unresolved.json"
362
+
363
+
364
+ def load_unresolved(report_dir: Path) -> set[str]:
365
+ path = unresolved_path(report_dir)
366
+ if not path.is_file():
367
+ return set()
368
+ try:
369
+ payload = json.loads(path.read_text(encoding="utf-8"))
370
+ except (OSError, json.JSONDecodeError):
371
+ return set()
372
+ return {item.strip() for item in payload.get("lines") or [] if isinstance(item, str) and item.strip()}
373
+
374
+
375
+ def save_unresolved(report_dir: Path, lines: set[str]) -> None:
376
+ path = unresolved_path(report_dir)
377
+ path.parent.mkdir(parents=True, exist_ok=True)
378
+ path.write_text(
379
+ json.dumps({"lines": sorted(lines)}, ensure_ascii=False, indent=2) + "\n",
380
+ encoding="utf-8",
381
+ )
382
+
383
+
384
+ def collect_leftovers(report_dir: Path) -> list[dict[str, Any]]:
385
+ """Merge per-country residual lines. Counts for the same line are summed."""
386
+ counts: Counter[str] = Counter()
387
+ if not report_dir.is_dir():
388
+ return []
389
+ for path in sorted(report_dir.glob("*.json")):
390
+ if path.name.startswith("_"):
391
+ continue
392
+ try:
393
+ payload = json.loads(path.read_text(encoding="utf-8"))
394
+ except (OSError, json.JSONDecodeError):
395
+ continue
396
+ for item in payload.get("leftovers") or []:
397
+ if isinstance(item, dict) and isinstance(item.get("line"), str):
398
+ line = item["line"].strip()
399
+ if line:
400
+ counts[line] += int(item.get("count") or 0)
401
+ return [{"line": line, "count": count} for line, count in counts.most_common()]
402
+
403
+
404
+ def improve_from_reports(
405
+ report_dir: Path,
406
+ generate_text: GenerateText,
407
+ *,
408
+ max_passes: int = 40,
409
+ batch_size: int = 12,
410
+ char_budget: int = PROMPT_CHAR_BUDGET,
411
+ on_pass: Callable[[dict[str, Any]], None] | None = None,
412
+ reset_unresolved: bool = False,
413
+ ) -> dict[str, Any]:
414
+ """Ask the router, one short batch at a time, for rules the script can apply.
415
+
416
+ A batch is one repeated family. Patterns that do not remove a line, or that
417
+ also match a publication sentence, are not stored. Families the model cannot
418
+ safely pattern are remembered so the next batch is a different family.
419
+ """
420
+ merged = collect_leftovers(report_dir)
421
+ pool_lines = [str(item["line"]) for item in merged]
422
+ presence: dict[str, bool] = {}
423
+ skip = set() if reset_unresolved else load_unresolved(report_dir)
424
+ existing = load_learned_patterns()
425
+ accepted_all: list[str] = []
426
+ removed_lines: list[str] = []
427
+ proposed = 0
428
+ passes = 0
429
+
430
+ def _emit(row: dict[str, Any]) -> None:
431
+ if on_pass is not None:
432
+ on_pass(row)
433
+
434
+ for pass_no in range(1, max(1, max_passes) + 1):
435
+ pending = router_candidates(merged, limit=100_000, skip=skip, presence=presence)
436
+ if not pending:
437
+ break
438
+ batch = largest_cluster(pending, batch_size)
439
+ cluster = _cluster_key(str(batch[0]["line"]))
440
+ _emit({
441
+ "event": "prompt",
442
+ "pass": pass_no,
443
+ "cluster": cluster,
444
+ "batch_id": hashlib.sha256(cluster.encode("utf-8")).hexdigest()[:8],
445
+ "candidates": len(batch),
446
+ "lines": [str(item["line"]) for item in batch],
447
+ })
448
+ try:
449
+ proposals = propose_line_patterns(batch, generate_text, char_budget=char_budget)
450
+ except Exception as exc:
451
+ passes += 1
452
+ _emit({"event": "pass", "pass": pass_no, "cluster": cluster, "error": str(exc)})
453
+ break
454
+ proposed += len(proposals)
455
+ accepted = accept_line_patterns(proposals, pool_lines, existing, must_hit=[str(item["line"]) for item in batch])
456
+ before = list(existing)
457
+ kept: list[str] = []
458
+ removed_now: list[str] = []
459
+ if accepted:
460
+ save_learned_patterns([*before, *accepted])
461
+ for pattern in accepted:
462
+ compiled = re.compile(pattern, re.IGNORECASE)
463
+ hits = [line for line in pool_lines if compiled.fullmatch(line)]
464
+ dropped = [line for line in hits if not line_still_present(line)]
465
+ if not dropped:
466
+ continue
467
+ kept.append(pattern)
468
+ removed_now.extend(dropped)
469
+ if kept != accepted:
470
+ save_learned_patterns([*before, *kept])
471
+ if not kept:
472
+ skip.update(str(item["line"]) for item in batch)
473
+ else:
474
+ for line in removed_now:
475
+ presence[line] = False
476
+ skip.discard(line)
477
+ if line not in removed_lines:
478
+ removed_lines.append(line)
479
+ existing = [*before, *kept]
480
+ accepted_all.extend(kept)
481
+ passes += 1
482
+ _emit({
483
+ "event": "pass",
484
+ "pass": pass_no,
485
+ "cluster": cluster,
486
+ "proposed": len(proposals),
487
+ "accepted": kept,
488
+ "removed": len(removed_now),
489
+ })
490
+
491
+ save_unresolved(report_dir, skip)
492
+ withheld = 0
493
+ for item in merged:
494
+ line = str(item["line"])
495
+ if line not in presence:
496
+ presence[line] = line_still_present(line)
497
+ if presence[line] and _blocked_candidate(line):
498
+ withheld += 1
499
+ remaining = router_candidates(merged, limit=100_000, skip=skip, presence=presence)
500
+ return {
501
+ "proposed": proposed,
502
+ "accepted": accepted_all,
503
+ "leftover_lines": len(merged),
504
+ "removed": len(removed_lines),
505
+ "removed_lines": removed_lines[:40],
506
+ "unresolved": len(skip),
507
+ "withheld": withheld,
508
+ "remaining": len(remaining),
509
+ "passes": passes,
510
+ }
511
+
512
+
513
+ def worker_count(requested: int | None) -> int:
514
+ if requested is not None:
515
+ return max(1, int(requested))
516
+ return max(1, os.cpu_count() or 1)
517
+
518
+
519
+ def _scan_job(job: tuple[str, str, str]) -> dict[str, Any]:
520
+ slug, path, report_dir = job
521
+ stats = scan_pack(Path(path))
522
+ write_scan(Path(report_dir), slug, stats)
523
+ return {"slug": slug, "n": stats["n"], "n_changed": stats["n_changed"], "n_unstable": stats["n_unstable"], "leftovers": len(stats["leftovers"])}
524
+
525
+
526
+ def _apply_job(job: tuple[str, str, str]) -> dict[str, Any]:
527
+ slug, path, out_dir = job
528
+ out_path = Path(out_dir) / Path(path).name
529
+ stats = apply_pack(Path(path), out_path)
530
+ return {"slug": slug, "out": str(out_path), **stats}
531
+
532
+
533
+ def run_parallel(
534
+ jobs: Sequence[tuple[str, str, str]],
535
+ worker,
536
+ workers: int | None,
537
+ *,
538
+ progress_path: Path | None = None,
539
+ on_done: Callable[[dict[str, Any]], None] | None = None,
540
+ ) -> list[dict[str, Any]]:
541
+ """One process per batch of countries. Each country writes its own file.
542
+
543
+ Progress is recorded in the parent as each country finishes, so a later
544
+ run can skip those slugs.
545
+ """
546
+ count = worker_count(workers)
547
+
548
+ def _finish(row: dict[str, Any]) -> dict[str, Any]:
549
+ if progress_path is not None:
550
+ append_progress(progress_path, row)
551
+ if on_done is not None:
552
+ on_done(row)
553
+ return row
554
+
555
+ if count == 1 or len(jobs) <= 1:
556
+ return [_finish(worker(job)) for job in jobs]
557
+ rows: list[dict[str, Any]] = []
558
+ with ProcessPoolExecutor(max_workers=min(count, len(jobs))) as pool:
559
+ futures = {pool.submit(worker, job): job[0] for job in jobs}
560
+ for future in as_completed(futures):
561
+ slug = futures[future]
562
+ try:
563
+ row = future.result()
564
+ except Exception as exc:
565
+ row = {"slug": slug, "error": str(exc)}
566
+ rows.append(_finish(row))
567
+ rows.sort(key=lambda row: str(row.get("slug") or ""))
568
+ return rows
569
+
570
+
571
+ def write_scan(report_dir: Path, slug: str, stats: dict[str, Any]) -> Path:
572
+ report_dir.mkdir(parents=True, exist_ok=True)
573
+ path = report_dir / f"{slug}.json"
574
+ tmp = path.with_suffix(".json.tmp")
575
+ tmp.write_text(json.dumps({"slug": slug, **stats}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
576
+ tmp.replace(path)
577
+ return path
578
+
579
+
580
+ def scan_done(report_dir: Path, slug: str) -> bool:
581
+ path = report_dir / f"{slug}.json"
582
+ if not path.is_file():
583
+ return False
584
+ try:
585
+ payload = json.loads(path.read_text(encoding="utf-8"))
586
+ except (OSError, json.JSONDecodeError):
587
+ return False
588
+ return isinstance(payload.get("n"), int)
589
+
590
+
591
+ def apply_done(out_dir: Path, slug: str) -> bool:
592
+ path = out_dir / f"{slug}_corpus.parquet"
593
+ if not path.is_file() or path.stat().st_size < 12:
594
+ return False
595
+ with path.open("rb") as handle:
596
+ if handle.read(4) != b"PAR1":
597
+ return False
598
+ handle.seek(-4, 2)
599
+ return handle.read(4) == b"PAR1"
600
+
601
+
602
+ def append_progress(path: Path, row: dict[str, Any]) -> None:
603
+ path.parent.mkdir(parents=True, exist_ok=True)
604
+ with path.open("a", encoding="utf-8") as handle:
605
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
606
+ handle.flush()
607
+
608
+
609
+ def load_generate_text() -> GenerateText:
610
+ """Import the router once per process. Scan and apply never call this."""
611
+ from ipfs_datasets_py.llm_router import generate_text
612
+
613
+ return generate_text
614
+
615
+
616
+ def default_paths(root: Path) -> dict[str, Path]:
617
+ return {
618
+ "cache": root / "cache",
619
+ "reports": root / "reports" / "residuals",
620
+ "out": root / "llm-normalized",
621
+ }
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:460b93df18faa027d93d98533a93050663a6e7646390941a7a828b8366c8f363
3
- size 475277
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c3f9b7e1ce20753f1e5337bdd5505c1a531a207a0317c25f9c274b74e283ee1
3
+ size 472328
data/bm25/documents/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ef04d08740257b450afa4eaae22e4ff400512fe886c5e6da94cb5b3453a3b04b
3
- size 487237
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68926c1233d92cf7d92d05c2af0d6f7136360dce97e04bfdbb763814193b02af
3
+ size 537036
data/bm25/documents/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec81b4043426c5f88156c7d86605250494e898799c8e334b6b88d150b2e3705a
3
+ size 266215
data/bm25/postings/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:544a15038907b216c2b9d85cdc0794390716af3e7fd9b435d8c0c8bfbcc12fa7
3
- size 217533
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40f0d18d19e7261b8055ec8d9bb383d54ef2d06b5db65d60cffda1ac471772f4
3
+ size 327960
data/bm25/postings/part-000001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58f21178f4f6c47dc5e5e47a0bb03b238798ad45f5533550dd73526873735d1c
3
+ size 21870
data/corpus/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:25e7813b8911d95c122e6fa623b2aa2614d622cec9d9f9838644cd56b1864019
3
- size 2377416
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4afdcd0bd81cfeb4f9477ec39720bd8911228754ff9ce32f76479280c85e75ee
3
+ size 2900437
data/corpus/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e565339afc1d1f2a09bd5287f9b10cc6cc9b2282c0ffea3aac4ac9f5a3c426b8
3
- size 2572576
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edca9bd7578a90c386aec0f45a33592e5723634111c61ed3eaae1ebcc086df97
3
+ size 2685082
data/corpus/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:178554367b46f64b5ce3d6edd4c0fb1360369c613ca9b29fdeb23cbdeede29bb
3
+ size 1148760
data/graph/adjacency/in/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e5ea70c1c8d77e93636c8417decda929c3769b55a727097ce7dfb83f7a501598
3
- size 316588
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05a1072d508a8b97cc5f1553ea34d6774de039c180b9e2ca787249744efe338a
3
+ size 327804
data/graph/adjacency/in/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0247655b967e82ff89cb43de9d8b1ac6740fb197f2b48ad6d16444a88823cf46
3
- size 572860
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c2146b9710cc187134af8251560063ab64befdf610e0c97461342b2a0505d02
3
+ size 482453
data/graph/adjacency/in/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:55e6a1ef03beb467d7cd8ba3ddf32a6008a66c9b2788a1a5b45b67c01394f6e6
3
- size 408484
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e42b0e8743795080b4cb9711f0468e3fdd396af5c4e201bb5a73c6d9b9f06ae
3
+ size 584666
data/graph/adjacency/in/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9779ddccbe028c629045fd5e4b79fd3cf69c8a013d683fab49b2819191b0c1fc
3
- size 511388
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7b74f62a4fe9989f5b9d5f15e4d3b06f778dccf4d767f74410e174ce19ca390
3
+ size 398868
data/graph/adjacency/in/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5a547efa604a4d94e46e3e3d3b1cec5fb77858ebbeefb5e797ea6414bfcf4a4a
3
- size 372774
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92a25d2bb05a099ceca74d06cd6250f5ba2966a8c983b7225cec6bb91cfdb8a5
3
+ size 536039
data/graph/adjacency/in/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c8b31c37fa9f390fa4b95c4f20f0aee3b72852a8f375a95d3e6fda9edf21eac4
3
- size 512632
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d839343221d5f3c6d347bf258124433c23390a23a2d63f60d11f2a820f22a344
3
+ size 559348
data/graph/adjacency/in/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ac11a83320ad42abbf093ef5fbc69247a5957439153f411cbb884413057fad25
3
- size 392139
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f9b0bcce59663714fbed8cde41f060562d7e3e7c6c535d49e7e2ff234830c08e
3
+ size 554553
data/graph/adjacency/in/part-000007.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:cf71ec170b4b0a544bcd2f29dce7afd30da94d10de17490198a1a918dde32cbc
3
- size 517362
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc5b039a388d9a72297e28ed51ae8d13d1d243b41ffd82fd4962f3c7e710c4a0
3
+ size 512531
data/graph/adjacency/in/part-000008.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e8ab6a3a23ed5ff7ce0d84c81938b3a3b14bd8418293c51a71176b8f58c1c29b
3
- size 82743
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:980ea6da315cc2a0f266738e7816d33b733f2bbffa3f6b916466dfe0ea0b69ac
3
+ size 585135
data/graph/adjacency/in/part-000009.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a5257f809e7bf03f3aa2299149f777956afb013182ee0479b1de4a9f28b88b2
3
+ size 549224
data/graph/adjacency/in/part-000010.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06cc61c32f8d5dbeabba0b92ebebf48ba91de1cd3a3ccf34b8354dd27c085e4f
3
+ size 163811
data/graph/adjacency/out/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:35a676ad8a9926bcc1acf930b8c548a1c6941f995c22f6da165c1f1ebc5b39a7
3
- size 383181
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:593e26ea725d3b9690e7c9a2a3fb6f321301665f479f03bcb77c8ad754864836
3
+ size 398747
data/graph/adjacency/out/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:dbd2f86c77a6093201ad019a1eb26ed9c094cb179f2f9e28447e9b79539cea25
3
- size 383385
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37471ef3d33b2312234cfd3d78617b8da3f477d6c9e0f95ed6b147d438b74fe7
3
+ size 398315
data/graph/adjacency/out/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:edc316004880c2ac916e01b2735b347547731e4b13ad5fb22ec83b9e5cdf51c4
3
- size 383066
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a33f641f346a218ea9c3eae4a6bdf0c61e708ad5e0999e1e2e0b93421385672
3
+ size 399603
data/graph/adjacency/out/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bafc9d61142c07f30f2588b17f7673a026c42732f15bbdfa08272ff71997c2f7
3
- size 383363
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2626233a5b070927ce5f9690b8641c0edf55608fbdade8140b3b372ec3280066
3
+ size 399159
data/graph/adjacency/out/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:4325529239333361dd44290989e0c96420b34b9233b6e4939462008bacdf92fd
3
- size 381335
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dc80e9b2c38dd8503cd89430be90673230e3ff463257eae78ddcaad3bd6511a
3
+ size 397678
data/graph/adjacency/out/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:88aad192b7a916b5d6bbc757d423a1207091efa34feec4edc72d21cdf5cb3096
3
- size 382132
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:338236adbe80e2e7d5296ec200c960c062e82dac49bf2c615489d6e6030260f6
3
+ size 399071
data/graph/adjacency/out/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fe8b34e5690664ed820aca49ed4e6200f8a8890f285576e0172a8af9da7e8331
3
- size 297299
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65b4cc5c9e015d9effeb0ba26e638f48e85c00a6aca8d5b102791973ceb8c708
3
+ size 401006
data/graph/adjacency/out/part-000007.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd880dc8dcebd070062d3dcd2059380e6fab72d868efa198e6dbdd249dca5b23
3
+ size 398325
data/graph/adjacency/out/part-000008.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da489fa0c3f4288cbdbcb009488a3553ba86bf8c239077dbb46c9aa900ff68e2
3
+ size 398778
data/graph/adjacency/out/part-000009.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0475314de7ccb223241bfdbfb7e78246eb55f5acdc081479f89202730b600273
3
+ size 99295
data/graph/edges/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:64c8c438f73029872c143ff6696e36dab28a3d2cfbafa1d04ba1370404694f64
3
- size 292788
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8cf9baee63ba63edfca15e213bc54a23c63adad8ba45e4736b71a73f25c50ba
3
+ size 309192