endomorphosis commited on
Commit
4d69477
·
verified ·
1 Parent(s): 5fe6cbe

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 +7 -7
  2. build.py +89 -35
  3. country_laws_ir/__main__.py +78 -2
  4. country_laws_ir/build.py +89 -35
  5. country_laws_ir/citations.py +147 -0
  6. country_laws_ir/duckdb_store.py +67 -0
  7. country_laws_ir/incremental.py +2 -1
  8. country_laws_ir/normalize.py +190 -44
  9. country_laws_ir/profiles.py +124 -0
  10. country_laws_ir/query.py +17 -0
  11. country_laws_ir/sparse.py +10 -2
  12. country_laws_ir/structure.py +305 -0
  13. country_laws_ir/vectors.py +76 -61
  14. country_laws_ir/verify.py +308 -0
  15. data/bm25/documents/part-000000.parquet +2 -2
  16. data/bm25/documents/part-000001.parquet +2 -2
  17. data/bm25/documents/part-000002.parquet +2 -2
  18. data/bm25/documents/part-000003.parquet +2 -2
  19. data/bm25/postings/part-000000.parquet +2 -2
  20. data/bm25/postings/part-000001.parquet +2 -2
  21. data/bm25/postings/part-000002.parquet +2 -2
  22. data/bm25/postings/part-000003.parquet +2 -2
  23. data/bm25/postings/part-000004.parquet +2 -2
  24. data/bm25/postings/part-000005.parquet +2 -2
  25. data/bm25/postings/part-000006.parquet +2 -2
  26. data/bm25/postings/part-000007.parquet +2 -2
  27. data/bm25/postings/part-000008.parquet +2 -2
  28. data/bm25/postings/part-000009.parquet +2 -2
  29. data/bm25/postings/part-000010.parquet +2 -2
  30. data/bm25/postings/part-000011.parquet +2 -2
  31. data/bm25/postings/part-000012.parquet +2 -2
  32. data/bm25/postings/part-000013.parquet +2 -2
  33. data/bm25/postings/part-000014.parquet +2 -2
  34. data/bm25/postings/part-000015.parquet +2 -2
  35. data/bm25/postings/part-000016.parquet +3 -0
  36. data/corpus/part-000000.parquet +2 -2
  37. data/corpus/part-000001.parquet +2 -2
  38. data/corpus/part-000002.parquet +2 -2
  39. data/corpus/part-000003.parquet +2 -2
  40. data/graph/adjacency/in/part-000000.parquet +2 -2
  41. data/graph/adjacency/in/part-000001.parquet +2 -2
  42. data/graph/adjacency/in/part-000002.parquet +2 -2
  43. data/graph/adjacency/in/part-000003.parquet +2 -2
  44. data/graph/adjacency/in/part-000004.parquet +2 -2
  45. data/graph/adjacency/in/part-000005.parquet +2 -2
  46. data/graph/adjacency/in/part-000006.parquet +2 -2
  47. data/graph/adjacency/in/part-000007.parquet +2 -2
  48. data/graph/adjacency/in/part-000008.parquet +2 -2
  49. data/graph/adjacency/in/part-000009.parquet +2 -2
  50. data/graph/adjacency/in/part-000010.parquet +2 -2
README.md CHANGED
@@ -72,14 +72,14 @@ Target Hub id (packaging metadata only): `justicedao/ipfs_peru_laws_ir`.
72
 
73
  | Field | Value |
74
  | --- | --- |
75
- | Laws (corpus units) | 0 |
76
  | Articles (corpus units) | 14345 |
77
- | Canonical docs | 14345 |
78
- | BM25 terms | 63616 |
79
- | BM25 postings | 1546715 |
80
- | Graph nodes | 20617 |
81
- | Graph edges | 114760 |
82
- | Vectors | 14345 × 384-d `thenlper/gte-small` (partial) |
83
 
84
  ## Canonical fields
85
 
 
72
 
73
  | Field | Value |
74
  | --- | --- |
75
+ | Laws (corpus units) | 1735 |
76
  | Articles (corpus units) | 14345 |
77
+ | Canonical docs | 16080 |
78
+ | BM25 terms | 67529 |
79
+ | BM25 postings | 2428340 |
80
+ | Graph nodes | 23024 |
81
+ | Graph edges | 128640 |
82
+ | Vectors | 16080 × 384-d `thenlper/gte-small` (embedded) |
83
 
84
  ## Canonical fields
85
 
build.py CHANGED
@@ -60,8 +60,17 @@ def _log(msg: str) -> None:
60
  def record_progress(event: dict[str, Any]) -> None:
61
  event = dict(event)
62
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
63
- with PROGRESS.open("a", encoding="utf-8") as f:
64
- f.write(json.dumps(event, ensure_ascii=False) + "\n")
 
 
 
 
 
 
 
 
 
65
 
66
 
67
  def _prior_dir_for(
@@ -202,7 +211,11 @@ def build_country(
202
  )
203
  )
204
  plan = plan_rebuild(
205
- mode=mode, source_meta=source_meta, prior=prior, force=force
 
 
 
 
206
  )
207
  if plan.skip_build:
208
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
@@ -234,6 +247,13 @@ def build_country(
234
  )
235
  if corpus.empty:
236
  raise RuntimeError("Normalized corpus is empty; refusing to package")
 
 
 
 
 
 
 
237
 
238
  import gc
239
 
@@ -243,6 +263,7 @@ def build_country(
243
  prior=prior,
244
  current_corpus=corpus,
245
  force=force,
 
246
  )
247
  _log(
248
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
@@ -394,17 +415,29 @@ def reindex_from_gaps(
394
  skip_vectors: bool = False,
395
  workers: int = 4,
396
  mode: str = "auto",
 
 
 
397
  ) -> list[dict[str, Any]]:
398
- """Scan Hub gaps and incrementally rebuild stale/missing country IR.
399
 
400
  Default cap skips huge corpora (Finland, Dominican Republic). Pass
401
  ``max_corpus_rows=None`` to include them.
402
  """
 
403
  from .coverage import gap_report
404
 
405
  if slugs is None:
406
- report = gap_report(workers=workers)
407
- rows = [c for c in report["countries"] if c.get("rebuild")]
 
 
 
 
 
 
 
 
408
  rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
409
  if max_corpus_rows is not None:
410
  rows = [
@@ -415,33 +448,54 @@ def reindex_from_gaps(
415
  if limit is not None:
416
  rows = rows[: int(limit)]
417
  slugs = [str(r["slug"]) for r in rows]
418
- _log(
419
- f"reindex targets n={len(slugs)} "
420
- f"(from scan rebuild={len(report.get('rebuild') or [])})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  )
422
- results: list[dict[str, Any]] = []
423
- for slug in slugs:
424
- _log(f"reindex start {slug}")
425
- try:
426
- results.append(
427
- build_country(
428
- slug,
429
- upload=upload,
430
- mode=mode,
431
- skip_vectors=skip_vectors,
432
- fetch_hub_prior_ir=True,
433
- )
434
- )
435
- except Exception as exc:
436
- _log(f"FAILED {slug}: {exc}")
437
- record_progress(
438
- {
439
- "event": "failed",
440
- "country": slug,
441
- "error": str(exc),
442
- "traceback": traceback.format_exc(),
443
- }
444
- )
445
- results.append({"country": slug, "skipped": False, "error": str(exc)})
446
- continue
447
- return results
 
60
  def record_progress(event: dict[str, Any]) -> None:
61
  event = dict(event)
62
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
63
+ PROGRESS.parent.mkdir(parents=True, exist_ok=True)
64
+ lock_path = PROGRESS.with_suffix(".lock")
65
+ with lock_path.open("a", encoding="utf-8") as lock_fh:
66
+ try:
67
+ import fcntl
68
+
69
+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
70
+ except Exception:
71
+ pass
72
+ with PROGRESS.open("a", encoding="utf-8") as f:
73
+ f.write(json.dumps(event, ensure_ascii=False) + "\n")
74
 
75
 
76
  def _prior_dir_for(
 
211
  )
212
  )
213
  plan = plan_rebuild(
214
+ mode=mode,
215
+ source_meta=source_meta,
216
+ prior=prior,
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}")
 
247
  )
248
  if corpus.empty:
249
  raise RuntimeError("Normalized corpus is empty; refusing to package")
250
+ verdict = (norm_report or {}).get("verification") or {}
251
+ if verdict.get("blocks_graphrag") and not force:
252
+ from .verify import NormalizationAdmissionError
253
+
254
+ raise NormalizationAdmissionError(
255
+ f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}"
256
+ )
257
 
258
  import gc
259
 
 
263
  prior=prior,
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} "
 
415
  skip_vectors: bool = False,
416
  workers: int = 4,
417
  mode: str = "auto",
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
 
424
  Default cap skips huge corpora (Finland, Dominican Republic). Pass
425
  ``max_corpus_rows=None`` to include them.
426
  """
427
+ from .catalog import indexable_countries
428
  from .coverage import gap_report
429
 
430
  if slugs is None:
431
+ if all_indexable:
432
+ rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()]
433
+ _log(f"reindex all indexable n={len(rows)}")
434
+ else:
435
+ report = gap_report(workers=workers)
436
+ rows = [c for c in report["countries"] if c.get("rebuild")]
437
+ _log(
438
+ f"reindex targets n={len(rows)} "
439
+ f"(from scan rebuild={len(report.get('rebuild') or [])})"
440
+ )
441
  rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
442
  if max_corpus_rows is not None:
443
  rows = [
 
448
  if limit is not None:
449
  rows = rows[: int(limit)]
450
  slugs = [str(r["slug"]) for r in rows]
451
+ kwargs = {
452
+ "upload": upload,
453
+ "mode": mode,
454
+ "force": force,
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")
461
+ import multiprocessing as mp
462
+ from concurrent.futures import ProcessPoolExecutor, as_completed
463
+
464
+ try:
465
+ mp.set_start_method("spawn", force=False)
466
+ except RuntimeError:
467
+ pass
468
+
469
+ results = [None] * len(slugs)
470
+ with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool:
471
+ futs = {
472
+ pool.submit(_reindex_one_country, (slug, kwargs)): i
473
+ for i, slug in enumerate(slugs)
474
+ }
475
+ for fut in as_completed(futs):
476
+ idx = futs[fut]
477
+ slug = slugs[idx]
478
+ try:
479
+ results[idx] = fut.result()
480
+ except Exception as exc:
481
+ _log(f"FAILED {slug}: {exc}")
482
+ results[idx] = {"country": slug, "skipped": False, "error": str(exc)}
483
+ return [r for r in results if r is not None]
484
+
485
+
486
+ def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]:
487
+ slug, kwargs = item
488
+ _log(f"reindex start {slug}")
489
+ try:
490
+ return build_country(slug, **kwargs)
491
+ except Exception as exc:
492
+ _log(f"FAILED {slug}: {exc}")
493
+ record_progress(
494
+ {
495
+ "event": "failed",
496
+ "country": slug,
497
+ "error": str(exc),
498
+ "traceback": traceback.format_exc(),
499
+ }
500
  )
501
+ return {"country": slug, "skipped": False, "error": str(exc)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
country_laws_ir/__main__.py CHANGED
@@ -66,8 +66,22 @@ def main(argv: list[str] | None = None) -> int:
66
  p_re.add_argument("--max-corpus-rows", type=int, default=20000,
67
  help="Skip IR larger than this many rows (0 = no cap)")
68
  p_re.add_argument("--skip-vectors", action="store_true")
69
- p_re.add_argument("--workers", type=int, default=4)
 
 
70
  p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  p_raw = sub.add_parser("package-raw")
73
  p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
@@ -149,7 +163,7 @@ def main(argv: list[str] | None = None) -> int:
149
  if args.cmd == "reindex":
150
  from .build import reindex_from_gaps
151
 
152
- cap = None if int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
153
  results = reindex_from_gaps(
154
  upload=args.upload,
155
  slugs=args.slugs or None,
@@ -158,6 +172,9 @@ def main(argv: list[str] | None = None) -> int:
158
  skip_vectors=args.skip_vectors,
159
  workers=args.workers,
160
  mode=args.mode,
 
 
 
161
  )
162
  print(json.dumps(
163
  [
@@ -177,6 +194,65 @@ def main(argv: list[str] | None = None) -> int:
177
  default=str,
178
  ))
179
  return 1 if any(r.get("error") for r in results) else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  if args.cmd == "package-raw":
181
  from .build import RELEASES
182
  from .raw_package import default_instruments_dir, package_instruments
 
66
  p_re.add_argument("--max-corpus-rows", type=int, default=20000,
67
  help="Skip IR larger than this many rows (0 = no cap)")
68
  p_re.add_argument("--skip-vectors", action="store_true")
69
+ p_re.add_argument("--workers", type=int, default=2,
70
+ help="Parallel country workers (default 2 to stay under MemAbort; CUDA encodes are file-locked)")
71
+ p_re.add_argument("--device", default="cuda")
72
  p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
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",
80
+ help="Normalize a country pack and run admission verifiers (no GraphRAG)",
81
+ )
82
+ p_ver.add_argument("--source-repo", "--source", dest="source", default=None)
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")
 
163
  if args.cmd == "reindex":
164
  from .build import reindex_from_gaps
165
 
166
+ cap = None if args.all or int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
167
  results = reindex_from_gaps(
168
  upload=args.upload,
169
  slugs=args.slugs or None,
 
172
  skip_vectors=args.skip_vectors,
173
  workers=args.workers,
174
  mode=args.mode,
175
+ force=args.force,
176
+ all_indexable=args.all,
177
+ device=args.device,
178
  )
179
  print(json.dumps(
180
  [
 
194
  default=str,
195
  ))
196
  return 1 if any(r.get("error") for r in results) else 0
197
+ if args.cmd == "verify":
198
+ from .catalog import indexable_countries
199
+ from .verify import verify_source
200
+
201
+ slugs = []
202
+ if args.all:
203
+ slugs = [c["slug"] for c in indexable_countries()]
204
+ if args.limit:
205
+ slugs = slugs[: int(args.limit)]
206
+ elif args.source:
207
+ slugs = [args.source]
208
+ else:
209
+ print(json.dumps({"error": "pass --source or --all"}, indent=2))
210
+ return 2
211
+ rows = []
212
+ failed = 0
213
+ for slug in slugs:
214
+ try:
215
+ row = verify_source(slug)
216
+ except Exception as exc:
217
+ row = {"slug": slug, "error": str(exc), "verification": {"admitted": False}}
218
+ rows.append(row)
219
+ if not (row.get("verification") or {}).get("admitted", False):
220
+ failed += 1
221
+ from collections import Counter
222
+
223
+ units = Counter(str(r.get("unit") or "") for r in rows)
224
+ mismatch = []
225
+ latin_blocked = []
226
+ for r in rows:
227
+ for chk in (r.get("verification") or {}).get("checks") or []:
228
+ if chk.get("id") != "heading_language":
229
+ continue
230
+ ev = chk.get("evidence") or {}
231
+ if chk.get("severity") == "fail" and not chk.get("passed"):
232
+ latin_blocked.append(r.get("slug"))
233
+ if "review samples" in str(chk.get("message") or ""):
234
+ mismatch.append(
235
+ {
236
+ "slug": r.get("slug"),
237
+ "document_language": ev.get("document_language"),
238
+ "heading_language": ev.get("heading_language"),
239
+ }
240
+ )
241
+ print(
242
+ json.dumps(
243
+ {
244
+ "n": len(rows),
245
+ "n_failed": failed,
246
+ "by_unit": dict(units),
247
+ "heading_mismatch": mismatch,
248
+ "latin_split_blocked": latin_blocked,
249
+ "countries": rows,
250
+ },
251
+ indent=2,
252
+ default=str,
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
country_laws_ir/build.py CHANGED
@@ -60,8 +60,17 @@ def _log(msg: str) -> None:
60
  def record_progress(event: dict[str, Any]) -> None:
61
  event = dict(event)
62
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
63
- with PROGRESS.open("a", encoding="utf-8") as f:
64
- f.write(json.dumps(event, ensure_ascii=False) + "\n")
 
 
 
 
 
 
 
 
 
65
 
66
 
67
  def _prior_dir_for(
@@ -202,7 +211,11 @@ def build_country(
202
  )
203
  )
204
  plan = plan_rebuild(
205
- mode=mode, source_meta=source_meta, prior=prior, force=force
 
 
 
 
206
  )
207
  if plan.skip_build:
208
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
@@ -234,6 +247,13 @@ def build_country(
234
  )
235
  if corpus.empty:
236
  raise RuntimeError("Normalized corpus is empty; refusing to package")
 
 
 
 
 
 
 
237
 
238
  import gc
239
 
@@ -243,6 +263,7 @@ def build_country(
243
  prior=prior,
244
  current_corpus=corpus,
245
  force=force,
 
246
  )
247
  _log(
248
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
@@ -394,17 +415,29 @@ def reindex_from_gaps(
394
  skip_vectors: bool = False,
395
  workers: int = 4,
396
  mode: str = "auto",
 
 
 
397
  ) -> list[dict[str, Any]]:
398
- """Scan Hub gaps and incrementally rebuild stale/missing country IR.
399
 
400
  Default cap skips huge corpora (Finland, Dominican Republic). Pass
401
  ``max_corpus_rows=None`` to include them.
402
  """
 
403
  from .coverage import gap_report
404
 
405
  if slugs is None:
406
- report = gap_report(workers=workers)
407
- rows = [c for c in report["countries"] if c.get("rebuild")]
 
 
 
 
 
 
 
 
408
  rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
409
  if max_corpus_rows is not None:
410
  rows = [
@@ -415,33 +448,54 @@ def reindex_from_gaps(
415
  if limit is not None:
416
  rows = rows[: int(limit)]
417
  slugs = [str(r["slug"]) for r in rows]
418
- _log(
419
- f"reindex targets n={len(slugs)} "
420
- f"(from scan rebuild={len(report.get('rebuild') or [])})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  )
422
- results: list[dict[str, Any]] = []
423
- for slug in slugs:
424
- _log(f"reindex start {slug}")
425
- try:
426
- results.append(
427
- build_country(
428
- slug,
429
- upload=upload,
430
- mode=mode,
431
- skip_vectors=skip_vectors,
432
- fetch_hub_prior_ir=True,
433
- )
434
- )
435
- except Exception as exc:
436
- _log(f"FAILED {slug}: {exc}")
437
- record_progress(
438
- {
439
- "event": "failed",
440
- "country": slug,
441
- "error": str(exc),
442
- "traceback": traceback.format_exc(),
443
- }
444
- )
445
- results.append({"country": slug, "skipped": False, "error": str(exc)})
446
- continue
447
- return results
 
60
  def record_progress(event: dict[str, Any]) -> None:
61
  event = dict(event)
62
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
63
+ PROGRESS.parent.mkdir(parents=True, exist_ok=True)
64
+ lock_path = PROGRESS.with_suffix(".lock")
65
+ with lock_path.open("a", encoding="utf-8") as lock_fh:
66
+ try:
67
+ import fcntl
68
+
69
+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
70
+ except Exception:
71
+ pass
72
+ with PROGRESS.open("a", encoding="utf-8") as f:
73
+ f.write(json.dumps(event, ensure_ascii=False) + "\n")
74
 
75
 
76
  def _prior_dir_for(
 
211
  )
212
  )
213
  plan = plan_rebuild(
214
+ mode=mode,
215
+ source_meta=source_meta,
216
+ prior=prior,
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}")
 
247
  )
248
  if corpus.empty:
249
  raise RuntimeError("Normalized corpus is empty; refusing to package")
250
+ verdict = (norm_report or {}).get("verification") or {}
251
+ if verdict.get("blocks_graphrag") and not force:
252
+ from .verify import NormalizationAdmissionError
253
+
254
+ raise NormalizationAdmissionError(
255
+ f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}"
256
+ )
257
 
258
  import gc
259
 
 
263
  prior=prior,
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} "
 
415
  skip_vectors: bool = False,
416
  workers: int = 4,
417
  mode: str = "auto",
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
 
424
  Default cap skips huge corpora (Finland, Dominican Republic). Pass
425
  ``max_corpus_rows=None`` to include them.
426
  """
427
+ from .catalog import indexable_countries
428
  from .coverage import gap_report
429
 
430
  if slugs is None:
431
+ if all_indexable:
432
+ rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()]
433
+ _log(f"reindex all indexable n={len(rows)}")
434
+ else:
435
+ report = gap_report(workers=workers)
436
+ rows = [c for c in report["countries"] if c.get("rebuild")]
437
+ _log(
438
+ f"reindex targets n={len(rows)} "
439
+ f"(from scan rebuild={len(report.get('rebuild') or [])})"
440
+ )
441
  rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
442
  if max_corpus_rows is not None:
443
  rows = [
 
448
  if limit is not None:
449
  rows = rows[: int(limit)]
450
  slugs = [str(r["slug"]) for r in rows]
451
+ kwargs = {
452
+ "upload": upload,
453
+ "mode": mode,
454
+ "force": force,
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")
461
+ import multiprocessing as mp
462
+ from concurrent.futures import ProcessPoolExecutor, as_completed
463
+
464
+ try:
465
+ mp.set_start_method("spawn", force=False)
466
+ except RuntimeError:
467
+ pass
468
+
469
+ results = [None] * len(slugs)
470
+ with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool:
471
+ futs = {
472
+ pool.submit(_reindex_one_country, (slug, kwargs)): i
473
+ for i, slug in enumerate(slugs)
474
+ }
475
+ for fut in as_completed(futs):
476
+ idx = futs[fut]
477
+ slug = slugs[idx]
478
+ try:
479
+ results[idx] = fut.result()
480
+ except Exception as exc:
481
+ _log(f"FAILED {slug}: {exc}")
482
+ results[idx] = {"country": slug, "skipped": False, "error": str(exc)}
483
+ return [r for r in results if r is not None]
484
+
485
+
486
+ def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]:
487
+ slug, kwargs = item
488
+ _log(f"reindex start {slug}")
489
+ try:
490
+ return build_country(slug, **kwargs)
491
+ except Exception as exc:
492
+ _log(f"FAILED {slug}: {exc}")
493
+ record_progress(
494
+ {
495
+ "event": "failed",
496
+ "country": slug,
497
+ "error": str(exc),
498
+ "traceback": traceback.format_exc(),
499
+ }
500
  )
501
+ return {"country": slug, "skipped": False, "error": str(exc)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
country_laws_ir/citations.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # slug or country name (lower) -> Bluebook T2/T10 statute abbreviation.
17
+ # Empty pinpoint templates are filled with article/section when present.
18
+ _BLUEBOOK_STATUTE: dict[str, str] = {
19
+ "australia": "Cth",
20
+ "canada": "S.C.",
21
+ "united kingdom": "U.K.",
22
+ "uk": "U.K.",
23
+ "united states": "U.S.C.",
24
+ "usa": "U.S.C.",
25
+ "germany": "BGBl.",
26
+ "france": "J.O.",
27
+ "malta": "Laws of Malta",
28
+ "ireland": "Ir.",
29
+ "newzealand": "N.Z.",
30
+ "new zealand": "N.Z.",
31
+ "southafrica": "S. Afr.",
32
+ "south africa": "S. Afr.",
33
+ "india": "India",
34
+ "japan": "Japan",
35
+ "china": "P.R.C.",
36
+ "netherlands": "Stb.",
37
+ "austria": "BGBl.",
38
+ "switzerland": "AS",
39
+ "sweden": "SFS",
40
+ "norway": "Norsk Lovtidend",
41
+ "denmark": "Lovtidende",
42
+ "finland": "Finlex",
43
+ "eu": "O.J.",
44
+ }
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Citation:
49
+ official_citation: str
50
+ bluebook_citation: str
51
+ cite_key: str
52
+ citation_status: str # bluebook | official_only | unknown
53
+ pinpoint: str
54
+
55
+
56
+ def normalize_cite_key(value: str) -> str:
57
+ if not value:
58
+ return ""
59
+ text = unicodedata.normalize("NFKC", value).lower()
60
+ text = text.replace("§", " s ")
61
+ text = text.replace("¶", " ")
62
+ text = re.sub(r"\bart(?:icle|\.)?\b", "art", text)
63
+ text = re.sub(r"\bsec(?:tion|\.)?\b", "s", text)
64
+ text = re.sub(r"[^a-z0-9]+", " ", text)
65
+ return re.sub(r"\s+", " ", text).strip()
66
+
67
+
68
+ def _pinpoint(article_number: str, section_number: str, record_type: str) -> str:
69
+ if record_type == "section" and section_number:
70
+ return f"§ {section_number}"
71
+ if article_number:
72
+ return f"art. {article_number}"
73
+ if section_number:
74
+ return f"§ {section_number}"
75
+ return ""
76
+
77
+
78
+ def _bluebook_abbrev(jurisdiction: str, country: str, slug: str = "") -> str:
79
+ for key in (slug, country, jurisdiction):
80
+ hit = _BLUEBOOK_STATUTE.get(str(key or "").strip().lower().replace("_", " "))
81
+ if hit:
82
+ return hit
83
+ return ""
84
+
85
+
86
+ def assign_citation(
87
+ *,
88
+ eli: str = "",
89
+ official_identifier: str = "",
90
+ identifier: str = "",
91
+ instrument_title: str = "",
92
+ article_number: str = "",
93
+ section_number: str = "",
94
+ record_type: str = "law",
95
+ jurisdiction: str = "",
96
+ country: str = "",
97
+ slug: str = "",
98
+ year: str = "",
99
+ ) -> Citation:
100
+ pinpoint = _pinpoint(article_number, section_number, record_type)
101
+ official = (
102
+ (eli or "").strip()
103
+ or (official_identifier or "").strip()
104
+ or (identifier or "").strip()
105
+ or (instrument_title or "").strip()
106
+ )
107
+ if official and pinpoint and pinpoint.lower() not in official.lower():
108
+ official_cite = f"{official}, {pinpoint}"
109
+ else:
110
+ official_cite = official
111
+
112
+ abbrev = _bluebook_abbrev(jurisdiction, country, slug)
113
+ bluebook = ""
114
+ if abbrev and official:
115
+ if pinpoint:
116
+ if year:
117
+ bluebook = f"{abbrev} {pinpoint} ({year})"
118
+ else:
119
+ bluebook = f"{abbrev} {pinpoint}"
120
+ else:
121
+ bluebook = f"{abbrev} {official}" if official != abbrev else abbrev
122
+
123
+ if bluebook:
124
+ status = "bluebook"
125
+ elif official_cite:
126
+ status = "official_only"
127
+ else:
128
+ status = "unknown"
129
+
130
+ key_src = bluebook or official_cite
131
+ return Citation(
132
+ official_citation=official_cite,
133
+ bluebook_citation=bluebook,
134
+ cite_key=normalize_cite_key(key_src),
135
+ citation_status=status,
136
+ pinpoint=pinpoint,
137
+ )
138
+
139
+
140
+ def citation_fields(cite: Citation) -> dict[str, Any]:
141
+ return {
142
+ "official_citation": cite.official_citation,
143
+ "bluebook_citation": cite.bluebook_citation,
144
+ "cite_key": cite.cite_key,
145
+ "citation_status": cite.citation_status,
146
+ "pinpoint": cite.pinpoint,
147
+ }
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/incremental.py CHANGED
@@ -234,6 +234,7 @@ def plan_rebuild(
234
  prior: PriorRelease | None,
235
  current_corpus: pd.DataFrame | None = None,
236
  force: bool = False,
 
237
  ) -> RebuildPlan:
238
  """Decide skip / delta / full from source fingerprints and CID overlap."""
239
  mode = BuildMode.coerce(mode)
@@ -280,7 +281,7 @@ def plan_rebuild(
280
  or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status")
281
  or ""
282
  ).strip().lower()
283
- stub_vectors = prior_vector_status in {
284
  "stub",
285
  "stub_missing_encoder",
286
  "incomplete",
 
234
  prior: PriorRelease | None,
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)
 
281
  or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status")
282
  or ""
283
  ).strip().lower()
284
+ stub_vectors = rebuild_stub_vectors and prior_vector_status in {
285
  "stub",
286
  "stub_missing_encoder",
287
  "incomplete",
country_laws_ir/normalize.py CHANGED
@@ -1,8 +1,9 @@
1
  """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
2
 
3
  Prefer article/section as the retrieval unit; fall back to law-level when
4
- articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE
5
- GraphRAG. Never invent legal text or identifiers.
 
6
 
7
  Public Hub reads only (token=False). No Hugging Face token is read or stored.
8
  """
@@ -11,8 +12,6 @@ from __future__ import annotations
11
 
12
  import json
13
  import os
14
- import re
15
- import unicodedata
16
  from collections import Counter
17
  from pathlib import Path
18
  from typing import Any
@@ -25,8 +24,8 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
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
 
29
- _WS_RE = re.compile(r"\s+", re.UNICODE)
30
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
31
  EMPTY_ARTICLE_COLUMNS = (
32
  "law_id",
@@ -48,9 +47,7 @@ def _empty_articles() -> pd.DataFrame:
48
  def normalize_text(value: Any) -> str:
49
  if value is None or (isinstance(value, float) and pd.isna(value)):
50
  return ""
51
- text = unicodedata.normalize("NFKC", str(value))
52
- text = _WS_RE.sub(" ", text).strip()
53
- return text
54
 
55
 
56
  def _s(value: Any) -> str:
@@ -285,6 +282,35 @@ def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str,
285
  return ""
286
 
287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  def _collector(meta: dict[str, Any], source_dataset: str) -> str:
289
  nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
290
  for blob in (meta, nested):
@@ -373,6 +399,34 @@ def _base_record(
373
  }
374
  if extra:
375
  rec.update(extra)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  rec["entry_cid"] = _entry_cid(rec)
377
  rec["title_length"] = len(title_for_bm25)
378
  rec["body_length"] = len(body)
@@ -433,11 +487,62 @@ def build_corpus(
433
 
434
  entries: list[dict[str, Any]] = []
435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
  if sparse_fallback:
437
  report["schema_surprises"].append(
438
  f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
439
  )
440
 
 
 
 
441
  if use_articles:
442
  for _, row in articles.iterrows():
443
  source_id = _row_get(row, "id")
@@ -489,6 +594,9 @@ def build_corpus(
489
  "law_status": parent["law_status"],
490
  "parent_law_id": instrument_id,
491
  "article_id": source_id,
 
 
 
492
  },
493
  )
494
  )
@@ -496,44 +604,50 @@ def build_corpus(
496
  for instrument_id, parent in law_map.items():
497
  body = parent["body"]
498
  if not body:
499
- report["drops"]["empty_body"] += 1
500
- if len(report["drop_samples"]["empty_body"]) < 20:
501
- report["drop_samples"]["empty_body"].append(instrument_id)
502
  continue
503
  meta = parent["metadata"]
504
- entries.append(
505
- _base_record(
506
- record_type="law",
507
- source_dataset=source_dataset,
508
- source_revision=source_revision,
509
- instrument_id=instrument_id,
510
- instrument_title=parent["instrument_title"],
511
- law_cid=parent["law_cid"],
512
- article_number="",
513
- article_title="",
514
- body=body,
515
- jurisdiction=parent["jurisdiction"],
516
- language=parent["language"],
517
- source_url=parent["source_url"],
518
- snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
519
- coverage=_coverage_from(
520
- parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback
521
- ),
522
- license_expr=parent["license"],
523
- collector=_collector(meta, source_dataset),
524
- source_id=instrument_id,
525
- extra={
526
- "eli": parent["eli"],
527
- "identifier": parent["identifier"],
528
- "official_identifier": parent["official_identifier"],
529
- "source_type": parent["source_type"],
530
- "country": parent["country"],
531
- "law_status": parent["law_status"],
532
- "parent_law_id": "",
533
- "article_id": "",
534
- },
535
- )
536
- )
 
 
 
 
 
 
 
 
 
537
 
538
  entries.sort(
539
  key=lambda r: (
@@ -564,6 +678,20 @@ def build_corpus(
564
  raise SchemaError("Duplicate entry_cid remained after dedupe")
565
  report["n_before_dedupe"] = n_before
566
  report["n_out"] = int(len(df))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567
  report["n_dropped_total"] = (
568
  report["drops"]["empty_body"]
569
  + report["drops"]["missing_instrument"]
@@ -607,5 +735,23 @@ def build_corpus(
607
  "empty_bodies_dropped": report["drops"]["empty_body"],
608
  "duplicate_cids_dropped": report["drops"]["duplicate_cid"],
609
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610
  df.attrs["normalization_report"] = report
611
  return df, report
 
1
  """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
2
 
3
  Prefer article/section as the retrieval unit; fall back to law-level when
4
+ articles are missing or empty. Strip leftover HTML, then detect multilingual
5
+ title/chapter/article/section headings (Oregon-style) when present. Never
6
+ invent legal text or a hierarchy that is not in the source.
7
 
8
  Public Hub reads only (token=False). No Hugging Face token is read or stored.
9
  """
 
12
 
13
  import json
14
  import os
 
 
15
  from collections import Counter
16
  from pathlib import Path
17
  from typing import Any
 
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"
30
  EMPTY_ARTICLE_COLUMNS = (
31
  "law_id",
 
47
  def normalize_text(value: Any) -> str:
48
  if value is None or (isinstance(value, float) and pd.isna(value)):
49
  return ""
50
+ return normalize_legal_text(value)
 
 
51
 
52
 
53
  def _s(value: Any) -> str:
 
282
  return ""
283
 
284
 
285
+ def _hierarchy_fields(
286
+ title: str, body: str, article_number: str, *, language: str = ""
287
+ ) -> dict[str, Any]:
288
+ """Best-effort hierarchy from a single already-split article/section body."""
289
+ units = split_structured_units(
290
+ f"{title}\n{body}" if title else body, language=language
291
+ )
292
+ if not units:
293
+ return {
294
+ "hierarchy_kind": "article" if article_number else "law",
295
+ "hierarchy_path": "",
296
+ "title_number": "",
297
+ "chapter_number": "",
298
+ "part_number": "",
299
+ "section_number": "",
300
+ "subsections": [],
301
+ }
302
+ unit = units[0]
303
+ return {
304
+ "hierarchy_kind": unit.kind,
305
+ "hierarchy_path": unit.hierarchy_path,
306
+ "title_number": unit.title_number,
307
+ "chapter_number": unit.chapter_number,
308
+ "part_number": unit.part_number,
309
+ "section_number": unit.section_number,
310
+ "subsections": list(unit.subsections),
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
  }
400
  if extra:
401
  rec.update(extra)
402
+ from .citations import assign_citation, citation_fields
403
+
404
+ slug = ""
405
+ if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
406
+ slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
407
+ year = ""
408
+ if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit():
409
+ year = snapshot_date[:4]
410
+ extra = extra or {}
411
+ rec.update(
412
+ citation_fields(
413
+ assign_citation(
414
+ eli=str(rec.get("eli") or extra.get("eli") or ""),
415
+ official_identifier=str(
416
+ rec.get("official_identifier") or extra.get("official_identifier") or ""
417
+ ),
418
+ identifier=str(rec.get("identifier") or extra.get("identifier") or ""),
419
+ instrument_title=instrument_title,
420
+ article_number=article_number,
421
+ section_number=str(extra.get("section_number") or ""),
422
+ record_type=record_type,
423
+ jurisdiction=jurisdiction,
424
+ country=str(extra.get("country") or ""),
425
+ slug=slug,
426
+ year=year,
427
+ )
428
+ )
429
+ )
430
  rec["entry_cid"] = _entry_cid(rec)
431
  rec["title_length"] = len(title_for_bm25)
432
  rec["body_length"] = len(body)
 
487
 
488
  entries: list[dict[str, Any]] = []
489
 
490
+ def _append_law_row(instrument_id: str, parent: dict[str, Any]) -> None:
491
+ body = parent["body"]
492
+ if not body:
493
+ report["drops"]["empty_body"] += 1
494
+ if len(report["drop_samples"]["empty_body"]) < 20:
495
+ report["drop_samples"]["empty_body"].append(instrument_id)
496
+ return
497
+ meta = parent["metadata"]
498
+ entries.append(
499
+ _base_record(
500
+ record_type="law",
501
+ source_dataset=source_dataset,
502
+ source_revision=source_revision,
503
+ instrument_id=instrument_id,
504
+ instrument_title=parent["instrument_title"],
505
+ law_cid=parent["law_cid"],
506
+ article_number="",
507
+ article_title="",
508
+ body=body,
509
+ jurisdiction=parent["jurisdiction"],
510
+ language=parent["language"],
511
+ source_url=parent["source_url"],
512
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
513
+ coverage=_coverage_from(
514
+ parent["row"],
515
+ meta,
516
+ articles_empty=articles_empty,
517
+ sparse_fallback=sparse_fallback,
518
+ ),
519
+ license_expr=parent["license"],
520
+ collector=_collector(meta, source_dataset),
521
+ source_id=instrument_id,
522
+ extra={
523
+ "eli": parent["eli"],
524
+ "identifier": parent["identifier"],
525
+ "official_identifier": parent["official_identifier"],
526
+ "source_type": parent["source_type"],
527
+ "country": parent["country"],
528
+ "law_status": parent["law_status"],
529
+ "parent_law_id": "",
530
+ "article_id": "",
531
+ **_hierarchy_fields(
532
+ parent["instrument_title"], body, "", language=parent["language"]
533
+ ),
534
+ },
535
+ )
536
+ )
537
+
538
  if sparse_fallback:
539
  report["schema_surprises"].append(
540
  f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
541
  )
542
 
543
+ for instrument_id, parent in law_map.items():
544
+ _append_law_row(instrument_id, parent)
545
+
546
  if use_articles:
547
  for _, row in articles.iterrows():
548
  source_id = _row_get(row, "id")
 
594
  "law_status": parent["law_status"],
595
  "parent_law_id": instrument_id,
596
  "article_id": source_id,
597
+ **_hierarchy_fields(
598
+ article_title, body, article_number, language=parent["language"]
599
+ ),
600
  },
601
  )
602
  )
 
604
  for instrument_id, parent in law_map.items():
605
  body = parent["body"]
606
  if not body:
 
 
 
607
  continue
608
  meta = parent["metadata"]
609
+ units = split_structured_units(body, language=parent["language"])
610
+ if units:
611
+ report["unit"] = "structured"
612
+ for unit in units:
613
+ entries.append(
614
+ _base_record(
615
+ record_type=unit.kind if unit.kind in {"article", "section"} else "article",
616
+ source_dataset=source_dataset,
617
+ source_revision=source_revision,
618
+ instrument_id=instrument_id,
619
+ instrument_title=parent["instrument_title"],
620
+ law_cid=parent["law_cid"],
621
+ article_number=unit.article_number or unit.number,
622
+ article_title=unit.heading,
623
+ body=unit.body,
624
+ jurisdiction=parent["jurisdiction"],
625
+ language=parent["language"],
626
+ source_url=parent["source_url"],
627
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
628
+ coverage="structured (headings detected in law body)",
629
+ license_expr=parent["license"],
630
+ collector=_collector(meta, source_dataset),
631
+ source_id=f"{instrument_id}-{unit.kind}-{unit.number}",
632
+ extra={
633
+ "eli": parent["eli"],
634
+ "identifier": parent["identifier"],
635
+ "official_identifier": parent["official_identifier"],
636
+ "source_type": parent["source_type"],
637
+ "country": parent["country"],
638
+ "law_status": parent["law_status"],
639
+ "parent_law_id": instrument_id,
640
+ "article_id": "",
641
+ "hierarchy_kind": unit.kind,
642
+ "hierarchy_path": unit.hierarchy_path,
643
+ "title_number": unit.title_number,
644
+ "chapter_number": unit.chapter_number,
645
+ "part_number": unit.part_number,
646
+ "section_number": unit.section_number,
647
+ "subsections": list(unit.subsections),
648
+ },
649
+ )
650
+ )
651
 
652
  entries.sort(
653
  key=lambda r: (
 
678
  raise SchemaError("Duplicate entry_cid remained after dedupe")
679
  report["n_before_dedupe"] = n_before
680
  report["n_out"] = int(len(df))
681
+ if not df.empty and "record_type" in df.columns:
682
+ n_law_rows = int((df["record_type"] == "law").sum())
683
+ n_child_rows = int(df["record_type"].isin(["article", "section"]).sum())
684
+ report["n_law_rows"] = n_law_rows
685
+ report["n_child_rows"] = n_child_rows
686
+ report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows
687
+ if n_law_rows and n_child_rows:
688
+ report["unit"] = (
689
+ "law+structured" if report.get("unit") == "structured" else "law+article"
690
+ )
691
+ elif n_law_rows:
692
+ report["unit"] = "law"
693
+ elif n_child_rows:
694
+ report["unit"] = "article"
695
  report["n_dropped_total"] = (
696
  report["drops"]["empty_body"]
697
  + report["drops"]["missing_instrument"]
 
735
  "empty_bodies_dropped": report["drops"]["empty_body"],
736
  "duplicate_cids_dropped": report["drops"]["duplicate_cid"],
737
  }
738
+ from .profiles import majority_language, score_heading_languages
739
+
740
+ sample_text = ""
741
+ if not df.empty and "body" in df.columns:
742
+ sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist())
743
+ if "title" in df.columns:
744
+ sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text
745
+ heading_langs = score_heading_languages(sample_text)
746
+ report["heading_language_counts"] = dict(heading_langs)
747
+ report["heading_language_majority"] = majority_language(heading_langs)
748
+ report["document_language_majority"] = None
749
+ if report.get("language_breakdown"):
750
+ report["document_language_majority"] = max(
751
+ report["language_breakdown"].items(), key=lambda kv: kv[1]
752
+ )[0]
753
+ from .verify import verify_normalized_corpus
754
+
755
+ report["verification"] = verify_normalized_corpus(df, report)
756
  df.attrs["normalization_report"] = report
757
  return df, report
country_laws_ir/profiles.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-language legal heading lexicons for country-law structure extraction.
2
+
3
+ Oregon (ORS) is English title/chapter/section. Other gazettes use their own
4
+ words (Artikel, Titre, Artículo, 条, مادة). This table is how we *score*
5
+ whether a split used the right language — not a claim that every country
6
+ has a dedicated parser.
7
+
8
+ Languages with no lexicon (ar, zh, ja, ko, …) must not be force-split on
9
+ Latin TITLE/ARTICLE markers; collectors may already have article rows.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections import Counter
15
+ import re
16
+ from typing import Any
17
+
18
+ # keyword -> list of (kind, language); some words are shared (article).
19
+ HEADING_LEXICON: dict[str, list[tuple[str, str]]] = {}
20
+
21
+ def _add(lang: str, kind: str, *words: str) -> None:
22
+ for word in words:
23
+ HEADING_LEXICON.setdefault(word.casefold(), []).append((kind, lang))
24
+
25
+
26
+ _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")
40
+ _add("de", "part", "teil")
41
+ _add("de", "article", "artikel")
42
+ _add("de", "section", "abschnitt", "paragraf")
43
+
44
+ _add("nl", "title", "titel")
45
+ _add("nl", "chapter", "hoofdstuk")
46
+ _add("nl", "part", "deel")
47
+ _add("nl", "article", "artikel")
48
+ _add("nl", "section", "paragraaf", "afdeling")
49
+
50
+ _add("es", "title", "título", "titulo")
51
+ _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")
58
+ _add("pt", "part", "parte")
59
+ _add("pt", "article", "artigo")
60
+ _add("pt", "section", "secção", "secao")
61
+
62
+ _add("it", "title", "titolo")
63
+ _add("it", "chapter", "capitolo")
64
+ _add("it", "part", "parte")
65
+ _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]]:
92
+ return list(HEADING_LEXICON.get(token.casefold()) or ())
93
+
94
+
95
+ def score_heading_languages(text: str) -> Counter[str]:
96
+ """Count distinctive lexicon hits. Shared words like 'article' do not vote."""
97
+ counts: Counter[str] = Counter()
98
+ if not text:
99
+ return counts
100
+ for token in _TOKEN_RE.findall(text):
101
+ hits = classify_heading_token(token)
102
+ langs = {lang for _kind, lang in hits if lang != "und"}
103
+ if len(langs) == 1:
104
+ counts[next(iter(langs))] += 1
105
+ return counts
106
+
107
+
108
+ def majority_language(counts: Counter[str], *, exclude: tuple[str, ...] = ("und",)) -> str | None:
109
+ filtered = Counter({k: v for k, v in counts.items() if k not in exclude})
110
+ if not filtered:
111
+ return None
112
+ lang, _n = filtered.most_common(1)[0]
113
+ return lang
114
+
115
+
116
+ def iso_lang(value: Any) -> str:
117
+ text = str(value or "").strip().lower().replace("_", "-")
118
+ if not text:
119
+ return ""
120
+ return text.split("-")[0]
121
+
122
+
123
+ def latin_split_allowed(language: str) -> bool:
124
+ return iso_lang(language) not in NO_LATIN_SPLIT_LANGS
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/sparse.py CHANGED
@@ -31,10 +31,18 @@ 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
  rows: list[dict[str, Any]] = []
35
  for rec in corpus.itertuples(index=False):
36
- title = str(getattr(rec, "title", "") or "")
37
- body = str(getattr(rec, "body", "") or "")
 
 
 
 
 
 
38
  if not tokenize_bm25_text(title) and not tokenize_bm25_text(body):
39
  continue
40
  rows.append(
 
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(
country_laws_ir/structure.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract legal hierarchy from country-law text (Oregon-style, multilingual).
2
+
3
+ Oregon Revised Statutes are stored as title / chapter / section / subsection
4
+ trees. National gazettes are not that uniform: some use Article/Artikel,
5
+ some §, some only a single instrument body.
6
+
7
+ This module:
8
+
9
+ * strips leftover HTML chrome so GraphRAG sees legal text, not tags;
10
+ * detects multilingual heading markers (title/chapter/part/article/section);
11
+ * splits an instrument into those units when at least two headings exist;
12
+ * otherwise keeps the whole instrument (never invents a hierarchy).
13
+
14
+ Subsection markers such as ``(a)`` / ``(1)`` are recorded on the parent
15
+ unit; they are not forced into their own retrieval rows.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
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
26
+
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
+
51
+ _KIND_RANK = {
52
+ "title": 1,
53
+ "chapter": 2,
54
+ "part": 3,
55
+ "article": 4,
56
+ "section": 5,
57
+ "subsection": 6,
58
+ }
59
+
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
+
75
+ class _HTMLText(HTMLParser):
76
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
77
+
78
+ def __init__(self) -> None:
79
+ super().__init__(convert_charrefs=True)
80
+ self.parts: list[str] = []
81
+ self.skip = 0
82
+
83
+ def handle_starttag(self, tag, attrs):
84
+ if tag in self.SKIP:
85
+ self.skip += 1
86
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
87
+ self.parts.append("\n")
88
+
89
+ def handle_endtag(self, tag):
90
+ if tag in self.SKIP and self.skip:
91
+ self.skip -= 1
92
+ if tag in {"p", "div", "li", "tr"} and self.skip == 0:
93
+ self.parts.append("\n")
94
+
95
+ def handle_data(self, data):
96
+ if self.skip == 0:
97
+ self.parts.append(data)
98
+
99
+
100
+ def has_html_tags(text: str) -> bool:
101
+ return bool(text and _HAS_TAG_RE.search(text))
102
+
103
+
104
+ def strip_html(raw: str) -> str:
105
+ """Turn leftover HTML into visible legal text. No-op if there are no tags."""
106
+ if not raw or not _HAS_TAG_RE.search(raw):
107
+ return raw
108
+ parser = _HTMLText()
109
+ try:
110
+ parser.feed(raw)
111
+ parser.close()
112
+ text = "".join(parser.parts)
113
+ except Exception:
114
+ text = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
115
+ text = re.sub(r"(?is)<style.*?>.*?</style>", " ", text)
116
+ text = re.sub(r"(?is)<[^>]+>", " ", text)
117
+ text = html_lib.unescape(text).replace("\xa0", " ")
118
+ text = re.sub(r"[ \t]+", " ", text)
119
+ text = re.sub(r"\n[ \t]+", "\n", text)
120
+ text = re.sub(r"\n{3,}", "\n\n", text)
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
+
136
+
137
+ @dataclass
138
+ class StructureUnit:
139
+ kind: str
140
+ number: str
141
+ heading: str
142
+ body: str
143
+ title_number: str = ""
144
+ chapter_number: str = ""
145
+ part_number: str = ""
146
+ article_number: str = ""
147
+ section_number: str = ""
148
+ subsections: tuple[str, ...] = ()
149
+ hierarchy_path: str = ""
150
+
151
+ def to_dict(self) -> dict[str, Any]:
152
+ return {
153
+ "kind": self.kind,
154
+ "number": self.number,
155
+ "heading": self.heading,
156
+ "body": self.body,
157
+ "title_number": self.title_number,
158
+ "chapter_number": self.chapter_number,
159
+ "part_number": self.part_number,
160
+ "article_number": self.article_number,
161
+ "section_number": self.section_number,
162
+ "subsections": list(self.subsections),
163
+ "hierarchy_path": self.hierarchy_path,
164
+ }
165
+
166
+
167
+ def _cursor_path(cursor: dict[str, str]) -> str:
168
+ parts = []
169
+ for key, label in (
170
+ ("title", "Title"),
171
+ ("chapter", "Chapter"),
172
+ ("part", "Part"),
173
+ ("article", "Article"),
174
+ ("section", "Section"),
175
+ ):
176
+ value = cursor.get(key) or ""
177
+ if value:
178
+ parts.append(f"{label} {value}")
179
+ return " > ".join(parts)
180
+
181
+
182
+ def _subsection_tokens(text: str) -> tuple[str, ...]:
183
+ seen: list[str] = []
184
+ for match in _SUBSECTION_RE.finditer(text):
185
+ token = match.group(1)
186
+ if token not in seen:
187
+ seen.append(token)
188
+ if len(seen) >= 40:
189
+ break
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 []
country_laws_ir/vectors.py CHANGED
@@ -130,13 +130,6 @@ def encode_corpus(
130
 
131
  configure_hf()
132
  device, _fallback = select_device(device)
133
- cache_root = _Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"))) / "cache" / "hf"
134
- os.environ.setdefault("HF_HOME", str(cache_root))
135
- os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
136
- os.environ.setdefault(
137
- "SENTENCE_TRANSFORMERS_HOME",
138
- str(cache_root / "sentence-transformers"),
139
- )
140
  texts = []
141
  for rec in corpus.itertuples(index=False):
142
  title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
@@ -148,12 +141,22 @@ def encode_corpus(
148
  done = 0
149
  ckpt = _Path(checkpoint_path) if checkpoint_path else None
150
  meta_path = ckpt.with_suffix(".json") if ckpt else None
151
- meta_n = None
 
 
 
 
 
 
 
 
152
  if meta_path is not None and meta_path.exists():
153
  try:
154
  meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
155
  except Exception:
156
  meta_n = None
 
 
157
  if ckpt is not None and ckpt.exists():
158
  cached = np.load(ckpt)
159
  same_corpus = meta_n is None or int(meta_n) == n
@@ -165,64 +168,76 @@ def encode_corpus(
165
  ):
166
  done = int(cached.shape[0])
167
  out[:done] = cached.astype(np.float32, copy=False)
168
- print(f"embeddings resume {done}/{n} from {ckpt}", flush=True)
169
- else:
170
- print(
171
- f"embeddings checkpoint shape {getattr(cached, 'shape', None)} "
172
- f"meta_n={meta_n} incompatible with {(n, DIMENSION)}; restarting",
173
- flush=True,
 
 
 
 
 
174
  )
175
- if done >= n:
176
- return out
177
- model = SentenceTransformer(
178
- MODEL_NAME,
179
- revision=MODEL_REVISION,
180
- device=device,
181
- )
182
  try:
183
- model.max_seq_length = MAX_SEQ_LENGTH
184
- except Exception:
185
- pass
186
- while done < n:
187
- j = min(done + int(chunk_size), n)
188
- chunk = model.encode(
189
- texts[done:j],
190
- batch_size=batch_size,
191
- show_progress_bar=True,
192
- convert_to_numpy=True,
193
- normalize_embeddings=True,
194
  )
195
- out[done:j] = np.asarray(chunk, dtype=np.float32)
196
- done = j
197
- print(f"embeddings checkpoint {done}/{n}", flush=True)
198
  try:
199
- from .mem import checkpoint as _mem_checkpoint
200
- _mem_checkpoint(f"embeddings@{done}", row=done, every_n=max(chunk_size, 4096))
201
- except Exception as _mem_exc:
202
- # MemAbort should propagate; other import issues are non-fatal
203
- from .mem import MemAbort
204
- if isinstance(_mem_exc, MemAbort):
205
- raise
206
- if ckpt is not None:
207
- ckpt.parent.mkdir(parents=True, exist_ok=True)
208
- tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
209
- np.save(tmp, out[:done])
210
- tmp.replace(ckpt)
211
- if meta_path is not None:
212
- meta_path.write_text(
213
- json.dumps(
214
- {
215
- "n": n,
216
- "done": done,
217
- "dimension": DIMENSION,
218
- "model_name": MODEL_NAME,
219
- "ts": datetime.now(timezone.utc).isoformat(),
220
- }
 
 
 
 
 
 
 
 
 
 
221
  )
222
- + "\n",
223
- encoding="utf-8",
224
- )
225
- return out
 
 
 
 
 
 
 
 
 
 
226
 
227
 
228
  def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
 
130
 
131
  configure_hf()
132
  device, _fallback = select_device(device)
 
 
 
 
 
 
 
133
  texts = []
134
  for rec in corpus.itertuples(index=False):
135
  title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
 
141
  done = 0
142
  ckpt = _Path(checkpoint_path) if checkpoint_path else None
143
  meta_path = ckpt.with_suffix(".json") if ckpt else None
144
+ cache_root = _Path(
145
+ os.environ.get(
146
+ "COUNTRY_LAWS_IR_ROOT",
147
+ str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"),
148
+ )
149
+ ) / "cache" / "hf"
150
+ os.environ.setdefault("HF_HOME", str(cache_root))
151
+ os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
152
+ os.environ.setdefault("SENTENCE_TRANSFORMERS_HOME", str(cache_root / "sentence-transformers"))
153
  if meta_path is not None and meta_path.exists():
154
  try:
155
  meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
156
  except Exception:
157
  meta_n = None
158
+ else:
159
+ meta_n = None
160
  if ckpt is not None and ckpt.exists():
161
  cached = np.load(ckpt)
162
  same_corpus = meta_n is None or int(meta_n) == n
 
168
  ):
169
  done = int(cached.shape[0])
170
  out[:done] = cached.astype(np.float32, copy=False)
171
+ if done >= n:
172
+ return out
173
+
174
+ lock_fh = None
175
+ if device.startswith("cuda"):
176
+ import fcntl
177
+
178
+ lock_path = _Path(
179
+ os.environ.get(
180
+ "COUNTRY_LAWS_IR_ROOT",
181
+ str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"),
182
  )
183
+ ) / "cuda.encode.lock"
184
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
185
+ lock_fh = open(lock_path, "a", encoding="utf-8")
186
+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
 
 
 
187
  try:
188
+ model = SentenceTransformer(
189
+ MODEL_NAME,
190
+ revision=MODEL_REVISION,
191
+ device=device,
 
 
 
 
 
 
 
192
  )
 
 
 
193
  try:
194
+ model.max_seq_length = MAX_SEQ_LENGTH
195
+ except Exception:
196
+ pass
197
+ while done < n:
198
+ j = min(done + int(chunk_size), n)
199
+ chunk = model.encode(
200
+ texts[done:j],
201
+ batch_size=batch_size,
202
+ show_progress_bar=True,
203
+ convert_to_numpy=True,
204
+ normalize_embeddings=True,
205
+ )
206
+ out[done:j] = np.asarray(chunk, dtype=np.float32)
207
+ done = j
208
+ if ckpt is not None:
209
+ ckpt.parent.mkdir(parents=True, exist_ok=True)
210
+ tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
211
+ np.save(tmp, out[:done])
212
+ tmp.replace(ckpt)
213
+ if meta_path is not None:
214
+ meta_path.write_text(
215
+ json.dumps(
216
+ {
217
+ "n": n,
218
+ "done": done,
219
+ "dimension": DIMENSION,
220
+ "model_name": MODEL_NAME,
221
+ "ts": datetime.now(timezone.utc).isoformat(),
222
+ }
223
+ )
224
+ + "\n",
225
+ encoding="utf-8",
226
  )
227
+ return out
228
+ finally:
229
+ if lock_fh is not None:
230
+ import fcntl as _fcntl
231
+
232
+ _fcntl.flock(lock_fh.fileno(), _fcntl.LOCK_UN)
233
+ lock_fh.close()
234
+ try:
235
+ import torch as _torch
236
+
237
+ if _torch.cuda.is_available():
238
+ _torch.cuda.empty_cache()
239
+ except Exception:
240
+ pass
241
 
242
 
243
  def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
country_laws_ir/verify.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Admission verifiers for country-law normalization, before GraphRAG.
2
+
3
+ Oregon-style structure is preferred but not required for every gazette.
4
+ Verifiers fail closed on invented text, residual HTML, empty corpora, and
5
+ duplicate CIDs. Missing title/section hierarchy is a warning unless the
6
+ corpus already split into articles.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import asdict, dataclass
12
+ import re
13
+ from typing import Any
14
+
15
+ import pandas as pd
16
+
17
+ from .structure import has_html_tags
18
+
19
+ SCHEMA_VERSION = "country-laws-normalize-verify/v1"
20
+
21
+ _HTML_FAIL_FRACTION = 0.02
22
+ _SHORT_BODY_FAIL_FRACTION = 0.50
23
+ _MIN_BODY_CHARS = 40
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Check:
28
+ id: str
29
+ severity: str # fail | warn
30
+ passed: bool
31
+ message: str
32
+ evidence: dict[str, Any]
33
+
34
+ def to_dict(self) -> dict[str, Any]:
35
+ return asdict(self)
36
+
37
+
38
+ def _bodies(corpus: pd.DataFrame) -> list[str]:
39
+ if corpus is None or corpus.empty or "body" not in corpus.columns:
40
+ return []
41
+ return [str(x or "") for x in corpus["body"].tolist()]
42
+
43
+
44
+ def check_nonempty(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
45
+ n = int(len(corpus)) if corpus is not None else 0
46
+ return Check(
47
+ id="nonempty_corpus",
48
+ severity="fail",
49
+ passed=n > 0,
50
+ message="normalized corpus has rows" if n else "normalized corpus is empty",
51
+ evidence={"n_out": n, "n_dropped": report.get("n_dropped_total")},
52
+ )
53
+
54
+
55
+ def check_entry_cids(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
56
+ if corpus is None or corpus.empty:
57
+ return Check(
58
+ id="entry_cid_unique",
59
+ severity="fail",
60
+ passed=False,
61
+ message="no entry_cid values to verify",
62
+ evidence={},
63
+ )
64
+ missing = int(corpus["entry_cid"].isna().sum()) if "entry_cid" in corpus.columns else int(len(corpus))
65
+ dupes = int(corpus["entry_cid"].duplicated().sum()) if "entry_cid" in corpus.columns else 0
66
+ empty = int((corpus["entry_cid"].astype(str).str.strip() == "").sum()) if "entry_cid" in corpus.columns else 0
67
+ ok = missing == 0 and dupes == 0 and empty == 0
68
+ return Check(
69
+ id="entry_cid_unique",
70
+ severity="fail",
71
+ passed=ok,
72
+ message="every row has a unique entry_cid" if ok else "missing or duplicate entry_cid",
73
+ evidence={"missing": missing, "empty": empty, "duplicate": dupes},
74
+ )
75
+
76
+
77
+ def check_no_invented_text(report: dict[str, Any]) -> Check:
78
+ flag = bool(report.get("never_invented_legal_text", False))
79
+ return Check(
80
+ id="never_invented_legal_text",
81
+ severity="fail",
82
+ passed=flag,
83
+ message="normalizer did not invent legal text" if flag else "invented-text flag is false",
84
+ evidence={"never_invented_legal_text": flag},
85
+ )
86
+
87
+
88
+ def check_html_residual(corpus: pd.DataFrame) -> Check:
89
+ bodies = _bodies(corpus)
90
+ tagged = [b for b in bodies if has_html_tags(b)]
91
+ n = len(bodies) or 1
92
+ fraction = len(tagged) / float(n)
93
+ passed = fraction <= _HTML_FAIL_FRACTION
94
+ return Check(
95
+ id="html_residual",
96
+ severity="fail",
97
+ passed=passed,
98
+ message=(
99
+ "HTML tags stripped from legal bodies"
100
+ if passed
101
+ else f"{len(tagged)}/{len(bodies)} bodies still contain HTML tags"
102
+ ),
103
+ evidence={
104
+ "n_bodies": len(bodies),
105
+ "n_with_tags": len(tagged),
106
+ "fraction": fraction,
107
+ "samples": [b[:120] for b in tagged[:5]],
108
+ },
109
+ )
110
+
111
+
112
+ def check_short_bodies(corpus: pd.DataFrame) -> Check:
113
+ bodies = _bodies(corpus)
114
+ if not bodies:
115
+ return Check(
116
+ id="short_bodies",
117
+ severity="fail",
118
+ passed=False,
119
+ message="no bodies to measure",
120
+ evidence={},
121
+ )
122
+ short = sum(1 for b in bodies if len(b) < _MIN_BODY_CHARS)
123
+ fraction = short / float(len(bodies))
124
+ passed = fraction <= _SHORT_BODY_FAIL_FRACTION
125
+ return Check(
126
+ id="short_bodies",
127
+ severity="fail" if not passed else "warn",
128
+ passed=passed,
129
+ message=(
130
+ "most legal units have usable body length"
131
+ if passed
132
+ else f"{short}/{len(bodies)} bodies shorter than {_MIN_BODY_CHARS} characters"
133
+ ),
134
+ evidence={"n_short": short, "n_bodies": len(bodies), "fraction": fraction},
135
+ )
136
+
137
+
138
+ def check_heading_language(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
139
+ """Warn when Latin heading dialect disagrees with the document language."""
140
+ from .profiles import NO_LATIN_SPLIT_LANGS, iso_lang
141
+
142
+ doc_lang = iso_lang(report.get("document_language_majority") or "")
143
+ head_lang = iso_lang(report.get("heading_language_majority") or "")
144
+ counts = report.get("heading_language_counts") or {}
145
+ if (
146
+ doc_lang in NO_LATIN_SPLIT_LANGS
147
+ and report.get("unit") == "structured"
148
+ and head_lang
149
+ and head_lang not in NO_LATIN_SPLIT_LANGS
150
+ and head_lang != doc_lang
151
+ ):
152
+ return Check(
153
+ id="heading_language",
154
+ severity="fail",
155
+ passed=False,
156
+ message=(
157
+ f"document language {doc_lang} was split with Latin headings ({head_lang}); "
158
+ "use script-specific article markers or collector article rows"
159
+ ),
160
+ evidence={"document_language": doc_lang, "heading_counts": counts, "unit": report.get("unit")},
161
+ )
162
+ if doc_lang and head_lang and doc_lang != head_lang and sum(counts.values()) >= 8:
163
+ return Check(
164
+ id="heading_language",
165
+ severity="warn",
166
+ passed=True,
167
+ message=(
168
+ f"heading lexicon majority is {head_lang} but documents are {doc_lang}; "
169
+ "review samples before trusting structure"
170
+ ),
171
+ evidence={
172
+ "document_language": doc_lang,
173
+ "heading_language": head_lang,
174
+ "heading_counts": counts,
175
+ },
176
+ )
177
+ return Check(
178
+ id="heading_language",
179
+ severity="warn",
180
+ passed=True,
181
+ message=(
182
+ f"heading lexicon {head_lang or 'none'} vs document language {doc_lang or 'unknown'}"
183
+ ),
184
+ evidence={
185
+ "document_language": doc_lang,
186
+ "heading_language": head_lang,
187
+ "heading_counts": counts,
188
+ },
189
+ )
190
+
191
+
192
+ def check_parent_laws(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
193
+ """Fail if source had instruments but GraphRAG corpus has no law rows."""
194
+ n_in = int(report.get("n_laws_in") or 0)
195
+ n_law_rows = 0
196
+ if corpus is not None and not corpus.empty and "record_type" in corpus.columns:
197
+ n_law_rows = int((corpus["record_type"] == "law").sum())
198
+ n_law_rows = int(report.get("n_law_rows") or n_law_rows)
199
+ if n_in > 0 and n_law_rows == 0:
200
+ return Check(
201
+ id="parent_laws",
202
+ severity="fail",
203
+ passed=False,
204
+ message=(
205
+ f"source has {n_in} laws but corpus has 0 law rows "
206
+ "(articles were indexed without parent instruments)"
207
+ ),
208
+ evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows},
209
+ )
210
+ return Check(
211
+ id="parent_laws",
212
+ severity="warn",
213
+ passed=True,
214
+ message=f"parent instruments present ({n_law_rows} law rows from {n_in} source laws)",
215
+ evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows},
216
+ )
217
+
218
+
219
+ def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
220
+ unit = str(report.get("unit") or "")
221
+ n = int(len(corpus)) if corpus is not None else 0
222
+ structured_rows = 0
223
+ if corpus is not None and not corpus.empty:
224
+ if "hierarchy_path" in corpus.columns:
225
+ structured_rows = int((corpus["hierarchy_path"].fillna("").astype(str).str.len() > 0).sum())
226
+ if "record_type" in corpus.columns:
227
+ structured_rows = max(
228
+ structured_rows,
229
+ int(corpus["record_type"].isin(["article", "section"]).sum()),
230
+ )
231
+ coverage = structured_rows / float(n) if n else 0.0
232
+ # Article or structured units are success. Pure law-level is a warning, not a fail:
233
+ # many gazettes have no title/section markers.
234
+ if unit in {"article", "structured", "law+article", "law+structured"} or coverage >= 0.5:
235
+ return Check(
236
+ id="legal_structure",
237
+ severity="warn",
238
+ passed=True,
239
+ message=f"retrieval units are structured ({unit}, coverage={coverage:.2f})",
240
+ evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
241
+ )
242
+ return Check(
243
+ id="legal_structure",
244
+ severity="warn",
245
+ passed=True,
246
+ message=(
247
+ "kept whole-instrument units; no title/article/section headings detected "
248
+ "(expected for some gazettes)"
249
+ ),
250
+ evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
251
+ )
252
+
253
+
254
+ def verify_normalized_corpus(
255
+ corpus: pd.DataFrame,
256
+ report: dict[str, Any],
257
+ *,
258
+ slug: str = "",
259
+ ) -> dict[str, Any]:
260
+ """Run all normalization verifiers. Fail-closed on any failed `fail` check."""
261
+ checks = [
262
+ check_nonempty(corpus, report),
263
+ check_entry_cids(corpus, report),
264
+ check_no_invented_text(report),
265
+ check_html_residual(corpus),
266
+ check_short_bodies(corpus),
267
+ check_parent_laws(corpus, report),
268
+ check_structure(corpus, report),
269
+ check_heading_language(corpus, report),
270
+ ]
271
+ failed = [c for c in checks if c.severity == "fail" and not c.passed]
272
+ admitted = not failed
273
+ return {
274
+ "schema_version": SCHEMA_VERSION,
275
+ "slug": slug,
276
+ "admitted": admitted,
277
+ "n_checks": len(checks),
278
+ "n_failed": len(failed),
279
+ "failed_ids": [c.id for c in failed],
280
+ "checks": [c.to_dict() for c in checks],
281
+ "blocks_graphrag": not admitted,
282
+ }
283
+
284
+
285
+ class NormalizationAdmissionError(RuntimeError):
286
+ """Raised when verifiers refuse to send a corpus to GraphRAG."""
287
+
288
+
289
+ def verify_source(source: str) -> dict[str, Any]:
290
+ """Load a Hub/local pack, normalize, and run verifiers (no GraphRAG)."""
291
+ from .build import CACHE
292
+ from .catalog import get_country
293
+ from .normalize import build_corpus, load_source
294
+
295
+ country = get_country(source)
296
+ local = country.get("local_source_dir")
297
+ laws, articles, source_meta = load_source(local or country["repo"], CACHE)
298
+ corpus, report = build_corpus(laws, articles, source_meta)
299
+ verdict = verify_normalized_corpus(corpus, report, slug=country["slug"])
300
+ report["verification"] = verdict
301
+ return {
302
+ "slug": country["slug"],
303
+ "source": country["repo"],
304
+ "n_out": report.get("n_out"),
305
+ "unit": report.get("unit"),
306
+ "verification": verdict,
307
+ "drops": report.get("drops"),
308
+ }
data/bm25/documents/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d5b1b2c049eee968b5e6f9d8f6ad9e08ff5486d95979d38bbc85cfd4c3d8415a
3
- size 501263
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ffebeddf05da3e782aad210b042a5b1dec6092afb33fa7fdb5bfd957f1c52996
3
+ size 513358
data/bm25/documents/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a3b9f3b04c80ca3c6b50747cc9c8a48237373e1a48b3467d8f4be2c07d9d5835
3
- size 484287
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c0c76d50334c876b59d3e635a706e3bffb61dca83d633bd308527c44924980c
3
+ size 504395
data/bm25/documents/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:29208abd1e55fa3d9128634f5b3abdb76eab6e04622d7f22d49a1161ec14388e
3
- size 463293
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab034f772d3f23427c662b9463a226d54173fb83386740842c35a9f838a4927c
3
+ size 489782
data/bm25/documents/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b62303b83f19ddc1d55f321ce42f09caa27539cb7d4724cb245d89231e21e2be
3
- size 246417
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6911cd2bb6f7c2f3f7d35cb94cca63e5e68b4c88c3816b7c3873ebac459705a6
3
+ size 457724
data/bm25/postings/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:494600cc82f1b3d6dbfaa05b1f7f867a90005f2b6b958ca00b767e3c62f1585d
3
- size 106349
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4270c6d7617221b9dd6a401f1733fa801092f282948ae04dcd513f256569e21d
3
+ size 92819
data/bm25/postings/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:93628889d2fb65f24a9c48e47d622a498c8d145667187fbe75391c3266ec4fef
3
- size 105720
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70812cbac3868dd34ffc0dd255d2a7170933b41c6f734641448598c80b3be4f2
3
+ size 162511
data/bm25/postings/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:686a1705a215dfdaedc9ea304ba69c436db3160bd65ef735a78a7558ef87a4e3
3
- size 121059
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8624d2f9b9abb3fbf22a9eb4115af00e30c8249c9f54c068742ba724d1ec14bc
3
+ size 120821
data/bm25/postings/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a932b74a5b07f429ed5aa4915ae27c56a0946c2e4e100427a23b02e4168894d9
3
- size 45415
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6f922c703ba2deb068ea24bc7252421c2e0b436e2471efe6cd7dc41567363eb
3
+ size 153968
data/bm25/postings/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c58bcd1632128ea4cf483b95aa9be88bb1327550ffe4be405c76362779bf38a8
3
- size 112621
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e022b6209ffc4f514a85aa247e9d7e3dd7cfbdb4344b70b9b98475be3e1b1e34
3
+ size 141594
data/bm25/postings/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e006962a8e9fbeb3f518aba118ea33eb27a099ac8c6e9cbd249a6da2bdd58ce7
3
- size 133183
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ceec0cd4542b8984385ec5e5fbc7154c18eaee344815afb11c78fa243aa8ee6
3
+ size 142728
data/bm25/postings/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b61c6477341715bbad747a60c872b3e2c32c7aa9a54fa800a9b8cdf0f280f2ab
3
- size 320649
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d76a151c18c7a2de870f9e893395dc44db631aa95571a8c499eadda5f9fd3ce4
3
+ size 128555
data/bm25/postings/part-000007.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:381f3b2648d8e4f34d7b1b62e6517c1cc30cb283e1b48a4a01667287c442d779
3
- size 455025
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd4c22df4f2312c06a32259da6a0c217d2604104b3045c42411fcaaa4800bdc3
3
+ size 432728
data/bm25/postings/part-000008.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:95bbfdcb66521a0da27a8ec6869b3d9ac6e42d529ede55bde3fb17cd8173fb48
3
- size 597690
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d326b0a70c252ac257a5a426ecf9125305c5b28ba17527ffb919dd5999e7185e
3
+ size 617863
data/bm25/postings/part-000009.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5c7106a0661c1253fd550634e28a7515220e42520b7ce4c1b9513ae3bdd993dc
3
- size 693372
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc3b66602773add98b70ee3fe8e09e482bc8a4d1a9a0355b18d52f9a9212b20d
3
+ size 834589
data/bm25/postings/part-000010.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:389e704a2013ce9bbc7ca2c846a5c934cc362edb90e97b16063583e5a3989da8
3
- size 408149
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7743a2dbaa0893c7d311482d87e42e5f64c98a9bf987b9e5450600a08dfc6121
3
+ size 956886
data/bm25/postings/part-000011.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ab86bc6ddf48c8072a3cec33b6a3a2254c4c5bf79f20eae54134a97685ec38d2
3
- size 565290
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e47751997de26359e940299858ad19dbb7b0bb3e600f9795fff2291f61d52419
3
+ size 561025
data/bm25/postings/part-000012.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1fb37a311decd8c61641b5fe6d5869705242dc206ac3505762f82ebb3e899db1
3
- size 622313
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4efe955030668fee1ed26db1545ee1c1de919a61c8e1e72fe86620233d87610
3
+ size 776840
data/bm25/postings/part-000013.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:cdc9ceb0dab793d1776d907e2c6cfd07c3d4ad5834b11ad9ff5fc7f5f8d144f0
3
- size 590569
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5937727b617f773f4ca837c96a3c2a061085f4e58d3455505b1d7a8a84f18fb
3
+ size 851922
data/bm25/postings/part-000014.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3c311aefa3fc49b8c0e3b99e0ff38494f498b83d19e2c652492400083592bf11
3
- size 571075
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d43a859923da0c18f1b356a7014ce3391817264c453212c8285c14226e5d07e
3
+ size 888867
data/bm25/postings/part-000015.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a1f18da19ec633e11d78032996bbe2439e83ce1639b3c117af72d51473e44dca
3
- size 261877
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7cb739836d62a19eb3326125e4d6695048fbb6c31e153851f506ae2787610d0
3
+ size 763588
data/bm25/postings/part-000016.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cbe4eaad81a2ea360170596bca7a5cc793512f4c68fdf9fc21209c8e455b535
3
+ size 334563
data/corpus/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:eb7d8c554113cbc0560f9e2d98d670c1d440b5553b6a0937df8f9c44888b39a4
3
- size 1951466
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab974a2845f50a753e8cf522d670bc8fc350882a594e439a51fee1a882760c61
3
+ size 2114859
data/corpus/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c5fa74a0b0f879dfda67f783f63817a96be691be3e68640d68b56af4ebc812dd
3
- size 1727243
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43beb750de02d16013a5063764a8b26a302cefa281a9c372e8144bcaa4cf9169
3
+ size 2017293
data/corpus/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f6ecd95e6b87d219f99332a05226893f6dd2dca41f01e99f5bfbde2ef01acb54
3
- size 1751152
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a44db5e43e50f93b863bb836f868802d572a0da122027732a908a70d00c8bc2d
3
+ size 1898388
data/corpus/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f62cf8c89fef6c76f749a8d29f61f01f66527f3db5a82743bb61fdc601fd1fcf
3
- size 1079395
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79222f0246b060b5ed007d94e722636bf2460cec405b29854e9b24a4b5995ab4
3
+ size 1966041
data/graph/adjacency/in/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:8a86cbe58fa2eb58cd345c7ca8eaf6e219fbea34b61c1a378e76b4c49dde8a6c
3
- size 563014
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0f4028fc01a25a8e6fe9d5431b56a298575f78127d7ac0536188025a987b687
3
+ size 577124
data/graph/adjacency/in/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:554b9387ed59a575011de1b9eb3e35a15390f5708afd244897a50b9499ea1c10
3
- size 583151
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b0f43d85d9fbb4708737589f4d3461843be50751a5a4a4e48f19292a5805636
3
+ size 584309
data/graph/adjacency/in/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6b60688fe5a41b61b0fdcd8c63ee1ac614375a39bbb5e3bfa71a26b6388990fa
3
- size 563252
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0799da0d7b773772d5f88a5385ff8f0c586dc8541100d974ed14bf474e47c00c
3
+ size 579557
data/graph/adjacency/in/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:62c7728bd631ca8037b287795b17fe98bd059750a4bc993f959e90c93c1f8e35
3
- size 410002
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40f0a161ef976d21ec007a2a56232a9f66e1def32c2df0d736dfa9f4abad75c0
3
+ size 322534
data/graph/adjacency/in/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e9877fb824e3748cb95ea6bea417900335b6377f786d0f93134dd6a09062c30b
3
- size 583330
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1551f01d7574dd442effe3e1f1df8d71a6863f4410dee17faa934f78e1281d8
3
+ size 584279
data/graph/adjacency/in/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:85539b8d818514092fa67839ad8e6275589b888698a5fcf2360a68bf6c19857c
3
- size 563382
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09e76002403a7963fcb9c2fc034878b13e4393505f14ce99017842bafa4909e9
3
+ size 580199
data/graph/adjacency/in/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3cf4c06829f023498f3ab3a3b1a6dcb06974b03c1e1d545ea980fe8169e02dca
3
- size 574601
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e2daf8b3a33664c27899421285a78f0c7972ab4247c067f04836aee8af6df99
3
+ size 593352
data/graph/adjacency/in/part-000007.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5a78e4bef1132fe838f24db475fbb7f9cad2564bdf3cd3fafd4bda854bbe1b05
3
- size 570762
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b923a47549c142b50351b41e291cef2343128a7063ab840c6cf3e60b751a792
3
+ size 595719
data/graph/adjacency/in/part-000008.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ace8971285550b720254363b05249b673675c9f897d6d5e7a497f30eace4792a
3
- size 398881
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7587ee1b1ca7e1a3baad04f8e5a8b5e3e2046deb5a79b30efe3f2e53b98190b
3
+ size 589095
data/graph/adjacency/in/part-000009.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:550483bb874d9b1b4a1a0dfef2279c2d46bb1e70d8ff73f545c47eb9fac890b3
3
- size 583119
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f679a37b5dcab4ac024c75a1d531fa344b9c3c62c74b8c1f6d07ab0189c2a3d
3
+ size 520675
data/graph/adjacency/in/part-000010.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d945f64abd04cd60a2ee1586ae33e25c42dc733b9c617e4b26ba03e6775dbb2d
3
- size 561848
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:367dec54f2150f951b839181c7e6a6ca4687c98dc3577880bf0f4a2dba161fbe
3
+ size 583911