endomorphosis commited on
Commit
b8461f1
·
verified ·
1 Parent(s): 3d2ea2d

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. build.py +96 -39
  2. country_laws_ir/__main__.py +83 -3
  3. country_laws_ir/build.py +96 -39
  4. country_laws_ir/coverage.py +4 -1
  5. country_laws_ir/incremental.py +20 -2
  6. country_laws_ir/normalize.py +101 -8
  7. country_laws_ir/profiles.py +124 -0
  8. country_laws_ir/query.py +1 -1
  9. country_laws_ir/sparse.py +10 -2
  10. country_laws_ir/structure.py +305 -0
  11. country_laws_ir/vectors.py +174 -77
  12. country_laws_ir/verify.py +280 -0
  13. data/bm25/documents/part-000000.parquet +2 -2
  14. data/bm25/documents/part-000001.parquet +2 -2
  15. data/corpus/part-000000.parquet +2 -2
  16. data/corpus/part-000001.parquet +2 -2
  17. data/graph/adjacency/in/part-000000.parquet +2 -2
  18. data/graph/adjacency/in/part-000001.parquet +2 -2
  19. data/graph/adjacency/in/part-000002.parquet +2 -2
  20. data/graph/adjacency/in/part-000003.parquet +2 -2
  21. data/graph/adjacency/in/part-000004.parquet +2 -2
  22. data/graph/adjacency/in/part-000005.parquet +2 -2
  23. data/graph/adjacency/in/part-000006.parquet +2 -2
  24. data/graph/adjacency/in/part-000007.parquet +2 -2
  25. data/graph/adjacency/in/part-000008.parquet +2 -2
  26. data/graph/adjacency/out/part-000000.parquet +2 -2
  27. data/graph/adjacency/out/part-000001.parquet +2 -2
  28. data/graph/adjacency/out/part-000002.parquet +2 -2
  29. data/graph/adjacency/out/part-000003.parquet +2 -2
  30. data/graph/adjacency/out/part-000004.parquet +2 -2
  31. data/graph/adjacency/out/part-000005.parquet +2 -2
  32. data/graph/adjacency/out/part-000006.parquet +2 -2
  33. data/graph/edges/part-000000.parquet +2 -2
  34. data/graph/edges/part-000001.parquet +2 -2
  35. data/graph/edges/part-000002.parquet +2 -2
  36. data/graph/edges/part-000003.parquet +2 -2
  37. data/graph/edges/part-000004.parquet +2 -2
  38. data/graph/edges/part-000005.parquet +2 -2
  39. data/graph/edges/part-000006.parquet +2 -2
  40. data/graph/edges/part-000007.parquet +2 -2
  41. data/graph/edges/part-000008.parquet +2 -2
  42. data/graph/edges/part-000009.parquet +2 -2
  43. data/graph/edges/part-000010.parquet +2 -2
  44. data/graph/edges/part-000011.parquet +2 -2
  45. data/graph/edges/part-000012.parquet +2 -2
  46. data/graph/edges/part-000013.parquet +2 -2
  47. data/graph/nodes/part-000000.parquet +2 -2
  48. data/graph/nodes/part-000001.parquet +2 -2
  49. data/graph/nodes/part-000002.parquet +2 -2
  50. data/vectors/part-000000.parquet +2 -2
build.py CHANGED
@@ -39,10 +39,10 @@ from .vectors import (
39
  DIMENSION,
40
  MODEL_NAME,
41
  assemble_embeddings,
42
- embeddings_available,
43
  embeddings_by_cid,
44
  layout_stub_vectors,
45
  layout_vectors,
 
46
  )
47
 
48
  ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
@@ -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(
@@ -113,11 +122,14 @@ def _encode_vectors(
113
  _log(f"embedding cache reused_cids={len(prior_by_cid)}")
114
  try:
115
  positional = CACHE / "embeddings" / f"{country_slug}.npy"
 
 
 
116
  embeddings, vector_report = assemble_embeddings(
117
  corpus,
118
  prior_by_cid,
119
- encode_missing=embeddings_available(),
120
- device=device,
121
  checkpoint_path=str(positional),
122
  )
123
  if (
@@ -157,7 +169,7 @@ def build_country(
157
  source: str,
158
  out: Path | None = None,
159
  upload: bool = False,
160
- device: str = "cpu",
161
  neighbor_k: int = 8,
162
  skip_vectors: bool = False,
163
  mode: str = "auto",
@@ -199,7 +211,11 @@ def build_country(
199
  )
200
  )
201
  plan = plan_rebuild(
202
- mode=mode, source_meta=source_meta, prior=prior, force=force
 
 
 
 
203
  )
204
  if plan.skip_build:
205
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
@@ -231,6 +247,13 @@ def build_country(
231
  )
232
  if corpus.empty:
233
  raise RuntimeError("Normalized corpus is empty; refusing to package")
 
 
 
 
 
 
 
234
 
235
  import gc
236
 
@@ -240,6 +263,7 @@ def build_country(
240
  prior=prior,
241
  current_corpus=corpus,
242
  force=force,
 
243
  )
244
  _log(
245
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
@@ -391,17 +415,29 @@ def reindex_from_gaps(
391
  skip_vectors: bool = False,
392
  workers: int = 4,
393
  mode: str = "auto",
 
 
 
394
  ) -> list[dict[str, Any]]:
395
- """Scan Hub gaps and incrementally rebuild stale/missing country IR.
396
 
397
  Default cap skips huge corpora (Finland, Dominican Republic). Pass
398
  ``max_corpus_rows=None`` to include them.
399
  """
 
400
  from .coverage import gap_report
401
 
402
  if slugs is None:
403
- report = gap_report(workers=workers)
404
- rows = [c for c in report["countries"] if c.get("rebuild")]
 
 
 
 
 
 
 
 
405
  rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
406
  if max_corpus_rows is not None:
407
  rows = [
@@ -412,33 +448,54 @@ def reindex_from_gaps(
412
  if limit is not None:
413
  rows = rows[: int(limit)]
414
  slugs = [str(r["slug"]) for r in rows]
415
- _log(
416
- f"reindex targets n={len(slugs)} "
417
- f"(from scan rebuild={len(report.get('rebuild') or [])})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  )
419
- results: list[dict[str, Any]] = []
420
- for slug in slugs:
421
- _log(f"reindex start {slug}")
422
- try:
423
- results.append(
424
- build_country(
425
- slug,
426
- upload=upload,
427
- mode=mode,
428
- skip_vectors=skip_vectors,
429
- fetch_hub_prior_ir=True,
430
- )
431
- )
432
- except Exception as exc:
433
- _log(f"FAILED {slug}: {exc}")
434
- record_progress(
435
- {
436
- "event": "failed",
437
- "country": slug,
438
- "error": str(exc),
439
- "traceback": traceback.format_exc(),
440
- }
441
- )
442
- results.append({"country": slug, "skipped": False, "error": str(exc)})
443
- continue
444
- return results
 
39
  DIMENSION,
40
  MODEL_NAME,
41
  assemble_embeddings,
 
42
  embeddings_by_cid,
43
  layout_stub_vectors,
44
  layout_vectors,
45
+ select_device,
46
  )
47
 
48
  ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
 
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(
 
122
  _log(f"embedding cache reused_cids={len(prior_by_cid)}")
123
  try:
124
  positional = CACHE / "embeddings" / f"{country_slug}.npy"
125
+ resolved, fallback = select_device(device)
126
+ if fallback:
127
+ _log(f"embedding device fallback requested={device} using={resolved}")
128
  embeddings, vector_report = assemble_embeddings(
129
  corpus,
130
  prior_by_cid,
131
+ encode_missing=True,
132
+ device=resolved,
133
  checkpoint_path=str(positional),
134
  )
135
  if (
 
169
  source: str,
170
  out: Path | None = None,
171
  upload: bool = False,
172
+ device: str = "cuda",
173
  neighbor_k: int = 8,
174
  skip_vectors: bool = False,
175
  mode: str = "auto",
 
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
@@ -16,7 +16,11 @@ def main(argv: list[str] | None = None) -> int:
16
  p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
17
  help="Hub dataset id (endomorphosis/ipfs_<slug>_laws), country slug, or local pack dir")
18
  p_build.add_argument("--out", default=None)
19
- p_build.add_argument("--device", default="cpu")
 
 
 
 
20
  p_build.add_argument("--neighbor-k", type=int, default=8)
21
  p_build.add_argument("--skip-vectors", action="store_true")
22
  p_build.add_argument("--upload", action="store_true",
@@ -62,8 +66,22 @@ def main(argv: list[str] | None = None) -> int:
62
  p_re.add_argument("--max-corpus-rows", type=int, default=20000,
63
  help="Skip IR larger than this many rows (0 = no cap)")
64
  p_re.add_argument("--skip-vectors", action="store_true")
65
- p_re.add_argument("--workers", type=int, default=4)
 
 
66
  p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  p_raw = sub.add_parser("package-raw")
69
  p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
@@ -145,7 +163,7 @@ def main(argv: list[str] | None = None) -> int:
145
  if args.cmd == "reindex":
146
  from .build import reindex_from_gaps
147
 
148
- cap = None if int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
149
  results = reindex_from_gaps(
150
  upload=args.upload,
151
  slugs=args.slugs or None,
@@ -154,6 +172,9 @@ def main(argv: list[str] | None = None) -> int:
154
  skip_vectors=args.skip_vectors,
155
  workers=args.workers,
156
  mode=args.mode,
 
 
 
157
  )
158
  print(json.dumps(
159
  [
@@ -173,6 +194,65 @@ def main(argv: list[str] | None = None) -> int:
173
  default=str,
174
  ))
175
  return 1 if any(r.get("error") for r in results) else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  if args.cmd == "package-raw":
177
  from .build import RELEASES
178
  from .raw_package import default_instruments_dir, package_instruments
 
16
  p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
17
  help="Hub dataset id (endomorphosis/ipfs_<slug>_laws), country slug, or local pack dir")
18
  p_build.add_argument("--out", default=None)
19
+ p_build.add_argument(
20
+ "--device",
21
+ default="cuda",
22
+ help="Embedding device (cuda by default, like US Code / Open US Law; falls back to cpu)",
23
+ )
24
  p_build.add_argument("--neighbor-k", type=int, default=8)
25
  p_build.add_argument("--skip-vectors", action="store_true")
26
  p_build.add_argument("--upload", action="store_true",
 
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
@@ -39,10 +39,10 @@ from .vectors import (
39
  DIMENSION,
40
  MODEL_NAME,
41
  assemble_embeddings,
42
- embeddings_available,
43
  embeddings_by_cid,
44
  layout_stub_vectors,
45
  layout_vectors,
 
46
  )
47
 
48
  ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
@@ -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(
@@ -113,11 +122,14 @@ def _encode_vectors(
113
  _log(f"embedding cache reused_cids={len(prior_by_cid)}")
114
  try:
115
  positional = CACHE / "embeddings" / f"{country_slug}.npy"
 
 
 
116
  embeddings, vector_report = assemble_embeddings(
117
  corpus,
118
  prior_by_cid,
119
- encode_missing=embeddings_available(),
120
- device=device,
121
  checkpoint_path=str(positional),
122
  )
123
  if (
@@ -157,7 +169,7 @@ def build_country(
157
  source: str,
158
  out: Path | None = None,
159
  upload: bool = False,
160
- device: str = "cpu",
161
  neighbor_k: int = 8,
162
  skip_vectors: bool = False,
163
  mode: str = "auto",
@@ -199,7 +211,11 @@ def build_country(
199
  )
200
  )
201
  plan = plan_rebuild(
202
- mode=mode, source_meta=source_meta, prior=prior, force=force
 
 
 
 
203
  )
204
  if plan.skip_build:
205
  _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
@@ -231,6 +247,13 @@ def build_country(
231
  )
232
  if corpus.empty:
233
  raise RuntimeError("Normalized corpus is empty; refusing to package")
 
 
 
 
 
 
 
234
 
235
  import gc
236
 
@@ -240,6 +263,7 @@ def build_country(
240
  prior=prior,
241
  current_corpus=corpus,
242
  force=force,
 
243
  )
244
  _log(
245
  f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
@@ -391,17 +415,29 @@ def reindex_from_gaps(
391
  skip_vectors: bool = False,
392
  workers: int = 4,
393
  mode: str = "auto",
 
 
 
394
  ) -> list[dict[str, Any]]:
395
- """Scan Hub gaps and incrementally rebuild stale/missing country IR.
396
 
397
  Default cap skips huge corpora (Finland, Dominican Republic). Pass
398
  ``max_corpus_rows=None`` to include them.
399
  """
 
400
  from .coverage import gap_report
401
 
402
  if slugs is None:
403
- report = gap_report(workers=workers)
404
- rows = [c for c in report["countries"] if c.get("rebuild")]
 
 
 
 
 
 
 
 
405
  rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
406
  if max_corpus_rows is not None:
407
  rows = [
@@ -412,33 +448,54 @@ def reindex_from_gaps(
412
  if limit is not None:
413
  rows = rows[: int(limit)]
414
  slugs = [str(r["slug"]) for r in rows]
415
- _log(
416
- f"reindex targets n={len(slugs)} "
417
- f"(from scan rebuild={len(report.get('rebuild') or [])})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  )
419
- results: list[dict[str, Any]] = []
420
- for slug in slugs:
421
- _log(f"reindex start {slug}")
422
- try:
423
- results.append(
424
- build_country(
425
- slug,
426
- upload=upload,
427
- mode=mode,
428
- skip_vectors=skip_vectors,
429
- fetch_hub_prior_ir=True,
430
- )
431
- )
432
- except Exception as exc:
433
- _log(f"FAILED {slug}: {exc}")
434
- record_progress(
435
- {
436
- "event": "failed",
437
- "country": slug,
438
- "error": str(exc),
439
- "traceback": traceback.format_exc(),
440
- }
441
- )
442
- results.append({"country": slug, "skipped": False, "error": str(exc)})
443
- continue
444
- return results
 
39
  DIMENSION,
40
  MODEL_NAME,
41
  assemble_embeddings,
 
42
  embeddings_by_cid,
43
  layout_stub_vectors,
44
  layout_vectors,
45
+ select_device,
46
  )
47
 
48
  ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
 
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(
 
122
  _log(f"embedding cache reused_cids={len(prior_by_cid)}")
123
  try:
124
  positional = CACHE / "embeddings" / f"{country_slug}.npy"
125
+ resolved, fallback = select_device(device)
126
+ if fallback:
127
+ _log(f"embedding device fallback requested={device} using={resolved}")
128
  embeddings, vector_report = assemble_embeddings(
129
  corpus,
130
  prior_by_cid,
131
+ encode_missing=True,
132
+ device=resolved,
133
  checkpoint_path=str(positional),
134
  )
135
  if (
 
169
  source: str,
170
  out: Path | None = None,
171
  upload: bool = False,
172
+ device: str = "cuda",
173
  neighbor_k: int = 8,
174
  skip_vectors: bool = False,
175
  mode: str = "auto",
 
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/coverage.py CHANGED
@@ -159,7 +159,10 @@ def classify_gap(
159
  and local_source_revision
160
  and str(source_revision) == str(local_source_revision)
161
  )
162
- rebuild = status in {"missing", "unpublished", "stale", "incomplete"} and not local_current
 
 
 
163
  publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (
164
  "source_missing_laws" not in issues
165
  )
 
159
  and local_source_revision
160
  and str(source_revision) == str(local_source_revision)
161
  )
162
+ rebuild = (
163
+ status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"}
164
+ and (not local_current or status == "stub_vectors")
165
+ )
166
  publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (
167
  "source_missing_laws" not in issues
168
  )
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)
@@ -275,7 +276,19 @@ def plan_rebuild(
275
  equivalent_to_full=True,
276
  )
277
 
278
- if prior_fp == fingerprint and fingerprint.strip("|"):
 
 
 
 
 
 
 
 
 
 
 
 
279
  return RebuildPlan(
280
  kind=RebuildKind.UNCHANGED,
281
  mode=mode,
@@ -314,10 +327,15 @@ def plan_rebuild(
314
  equivalent_to_full=True,
315
  )
316
 
 
 
 
 
 
317
  return RebuildPlan(
318
  kind=RebuildKind.DELTA_REFRESH,
319
  mode=mode,
320
- reason="source changed; reuse embeddings for unchanged entry_cids",
321
  source_revision=revision,
322
  prior_revision=prior_revision,
323
  source_fingerprint=fingerprint,
 
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)
 
276
  equivalent_to_full=True,
277
  )
278
 
279
+ prior_vector_status = str(
280
+ ((prior.manifest.get("vector") or {}) if prior.manifest else {}).get("status")
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",
288
+ "partial",
289
+ }
290
+
291
+ if prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors:
292
  return RebuildPlan(
293
  kind=RebuildKind.UNCHANGED,
294
  mode=mode,
 
327
  equivalent_to_full=True,
328
  )
329
 
330
+ reason = (
331
+ "source fingerprint matches but vectors are stub/incomplete; encode missing CIDs"
332
+ if stub_vectors and prior_fp == fingerprint
333
+ else "source changed; reuse embeddings for unchanged entry_cids"
334
+ )
335
  return RebuildPlan(
336
  kind=RebuildKind.DELTA_REFRESH,
337
  mode=mode,
338
+ reason=reason,
339
  source_revision=revision,
340
  prior_revision=prior_revision,
341
  source_fingerprint=fingerprint,
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):
@@ -489,6 +515,9 @@ def build_corpus(
489
  "law_status": parent["law_status"],
490
  "parent_law_id": instrument_id,
491
  "article_id": source_id,
 
 
 
492
  },
493
  )
494
  )
@@ -501,6 +530,49 @@ def build_corpus(
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",
@@ -531,6 +603,9 @@ def build_corpus(
531
  "law_status": parent["law_status"],
532
  "parent_law_id": "",
533
  "article_id": "",
 
 
 
534
  },
535
  )
536
  )
@@ -607,5 +682,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):
 
515
  "law_status": parent["law_status"],
516
  "parent_law_id": instrument_id,
517
  "article_id": source_id,
518
+ **_hierarchy_fields(
519
+ article_title, body, article_number, language=parent["language"]
520
+ ),
521
  },
522
  )
523
  )
 
530
  report["drop_samples"]["empty_body"].append(instrument_id)
531
  continue
532
  meta = parent["metadata"]
533
+ units = split_structured_units(body, language=parent["language"])
534
+ if units:
535
+ report["unit"] = "structured"
536
+ for unit in units:
537
+ entries.append(
538
+ _base_record(
539
+ record_type=unit.kind if unit.kind in {"article", "section"} else "article",
540
+ source_dataset=source_dataset,
541
+ source_revision=source_revision,
542
+ instrument_id=instrument_id,
543
+ instrument_title=parent["instrument_title"],
544
+ law_cid=parent["law_cid"],
545
+ article_number=unit.article_number or unit.number,
546
+ article_title=unit.heading,
547
+ body=unit.body,
548
+ jurisdiction=parent["jurisdiction"],
549
+ language=parent["language"],
550
+ source_url=parent["source_url"],
551
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
552
+ coverage="structured (headings detected in law body)",
553
+ license_expr=parent["license"],
554
+ collector=_collector(meta, source_dataset),
555
+ source_id=f"{instrument_id}-{unit.kind}-{unit.number}",
556
+ extra={
557
+ "eli": parent["eli"],
558
+ "identifier": parent["identifier"],
559
+ "official_identifier": parent["official_identifier"],
560
+ "source_type": parent["source_type"],
561
+ "country": parent["country"],
562
+ "law_status": parent["law_status"],
563
+ "parent_law_id": instrument_id,
564
+ "article_id": "",
565
+ "hierarchy_kind": unit.kind,
566
+ "hierarchy_path": unit.hierarchy_path,
567
+ "title_number": unit.title_number,
568
+ "chapter_number": unit.chapter_number,
569
+ "part_number": unit.part_number,
570
+ "section_number": unit.section_number,
571
+ "subsections": list(unit.subsections),
572
+ },
573
+ )
574
+ )
575
+ continue
576
  entries.append(
577
  _base_record(
578
  record_type="law",
 
603
  "law_status": parent["law_status"],
604
  "parent_law_id": "",
605
  "article_id": "",
606
+ **_hierarchy_fields(
607
+ parent["instrument_title"], body, "", language=parent["language"]
608
+ ),
609
  },
610
  )
611
  )
 
682
  "empty_bodies_dropped": report["drops"]["empty_body"],
683
  "duplicate_cids_dropped": report["drops"]["duplicate_cid"],
684
  }
685
+ from .profiles import majority_language, score_heading_languages
686
+
687
+ sample_text = ""
688
+ if not df.empty and "body" in df.columns:
689
+ sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist())
690
+ if "title" in df.columns:
691
+ sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text
692
+ heading_langs = score_heading_languages(sample_text)
693
+ report["heading_language_counts"] = dict(heading_langs)
694
+ report["heading_language_majority"] = majority_language(heading_langs)
695
+ report["document_language_majority"] = None
696
+ if report.get("language_breakdown"):
697
+ report["document_language_majority"] = max(
698
+ report["language_breakdown"].items(), key=lambda kv: kv[1]
699
+ )[0]
700
+ from .verify import verify_normalized_corpus
701
+
702
+ report["verification"] = verify_normalized_corpus(df, report)
703
  df.attrs["normalization_report"] = report
704
  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
@@ -176,7 +176,7 @@ def main(argv: list[str] | None = None) -> int:
176
  p_vec.add_argument("query")
177
  p_vec.add_argument("--top-k", type=int, default=10)
178
  p_vec.add_argument("--candidate-centroids", type=int, default=4)
179
- p_vec.add_argument("--device", default="cpu")
180
 
181
  p_g = sub.add_parser("graph")
182
  g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
 
176
  p_vec.add_argument("query")
177
  p_vec.add_argument("--top-k", type=int, default=10)
178
  p_vec.add_argument("--candidate-centroids", type=int, default=4)
179
+ p_vec.add_argument("--device", default="cuda")
180
 
181
  p_g = sub.add_parser("graph")
182
  g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
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
@@ -14,7 +14,11 @@ import pandas as pd
14
  from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
15
 
16
  MODEL_NAME = "thenlper/gte-small"
 
17
  DIMENSION = 384
 
 
 
18
  MAX_ROWS_PER_CENTROID = 8192
19
  MAX_SHARDS_PER_CENTROID = 2
20
 
@@ -24,41 +28,108 @@ def _l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray:
24
  return x / np.maximum(n, eps)
25
 
26
 
27
- def embeddings_available() -> bool:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  try:
29
- import torch # noqa: F401
30
- from sentence_transformers import SentenceTransformer # noqa: F401
31
 
32
  return True
 
 
 
 
 
 
 
 
 
 
33
  except Exception:
34
  return False
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def encode_corpus(
38
  corpus: pd.DataFrame,
39
  batch_size: int = 64,
40
- device: str = "cpu",
41
  checkpoint_path: str | None = None,
42
  chunk_size: int = 4096,
43
  ) -> np.ndarray:
44
- """Encode corpus texts with gte-small in chunks; persist checkpoints when given."""
45
  import json
46
  import os
47
  from datetime import datetime, timezone
48
  from pathlib import Path as _Path
49
 
 
 
 
 
 
50
  from sentence_transformers import SentenceTransformer
51
 
52
  from .auth import configure_hf
53
 
54
  configure_hf()
55
- cache_root = _Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"))) / "cache" / "hf"
56
- os.environ.setdefault("HF_HOME", str(cache_root))
57
- os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
58
- os.environ.setdefault(
59
- "SENTENCE_TRANSFORMERS_HOME",
60
- str(cache_root / "sentence-transformers"),
61
- )
62
  texts = []
63
  for rec in corpus.itertuples(index=False):
64
  title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
@@ -70,12 +141,22 @@ def encode_corpus(
70
  done = 0
71
  ckpt = _Path(checkpoint_path) if checkpoint_path else None
72
  meta_path = ckpt.with_suffix(".json") if ckpt else None
73
- meta_n = None
 
 
 
 
 
 
 
 
74
  if meta_path is not None and meta_path.exists():
75
  try:
76
  meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
77
  except Exception:
78
  meta_n = None
 
 
79
  if ckpt is not None and ckpt.exists():
80
  cached = np.load(ckpt)
81
  same_corpus = meta_n is None or int(meta_n) == n
@@ -87,56 +168,76 @@ def encode_corpus(
87
  ):
88
  done = int(cached.shape[0])
89
  out[:done] = cached.astype(np.float32, copy=False)
90
- print(f"embeddings resume {done}/{n} from {ckpt}", flush=True)
91
- else:
92
- print(
93
- f"embeddings checkpoint shape {getattr(cached, 'shape', None)} "
94
- f"meta_n={meta_n} incompatible with {(n, DIMENSION)}; restarting",
95
- flush=True,
 
 
 
 
 
96
  )
97
- if done >= n:
98
- return out
99
- model = SentenceTransformer(MODEL_NAME, device=device)
100
- while done < n:
101
- j = min(done + int(chunk_size), n)
102
- chunk = model.encode(
103
- texts[done:j],
104
- batch_size=batch_size,
105
- show_progress_bar=True,
106
- convert_to_numpy=True,
107
- normalize_embeddings=True,
108
  )
109
- out[done:j] = np.asarray(chunk, dtype=np.float32)
110
- done = j
111
- print(f"embeddings checkpoint {done}/{n}", flush=True)
112
  try:
113
- from .mem import checkpoint as _mem_checkpoint
114
- _mem_checkpoint(f"embeddings@{done}", row=done, every_n=max(chunk_size, 4096))
115
- except Exception as _mem_exc:
116
- # MemAbort should propagate; other import issues are non-fatal
117
- from .mem import MemAbort
118
- if isinstance(_mem_exc, MemAbort):
119
- raise
120
- if ckpt is not None:
121
- ckpt.parent.mkdir(parents=True, exist_ok=True)
122
- tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
123
- np.save(tmp, out[:done])
124
- tmp.replace(ckpt)
125
- if meta_path is not None:
126
- meta_path.write_text(
127
- json.dumps(
128
- {
129
- "n": n,
130
- "done": done,
131
- "dimension": DIMENSION,
132
- "model_name": MODEL_NAME,
133
- "ts": datetime.now(timezone.utc).isoformat(),
134
- }
 
 
 
 
 
 
 
 
 
 
135
  )
136
- + "\n",
137
- encoding="utf-8",
138
- )
139
- return out
 
 
 
 
 
 
 
 
 
 
140
 
141
 
142
  def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
@@ -345,14 +446,14 @@ def assemble_embeddings(
345
  *,
346
  encode_missing: bool = True,
347
  batch_size: int = 64,
348
- device: str = "cpu",
349
  checkpoint_path: str | None = None,
350
  ) -> tuple[np.ndarray, dict[str, Any]]:
351
- """Align a (n, 384) matrix to *corpus* row order, reusing unchanged CIDs.
352
 
353
- Positional checkpoints are unsafe when scrapes append pages. Identity is
354
- ``entry_cid``. Missing CIDs are encoded only when ``encode_missing`` is true
355
- and sentence-transformers is available.
356
  """
357
  n = int(len(corpus))
358
  out = np.zeros((n, DIMENSION), dtype=np.float32)
@@ -362,18 +463,10 @@ def assemble_embeddings(
362
  cids = corpus["entry_cid"].astype(str).tolist() if n else []
363
  for i, cid in enumerate(cids):
364
  vec = prior.get(cid)
365
- if vec is None:
366
- missing_idx.append(i)
367
- continue
368
- try:
369
- arr = np.asarray(vec, dtype=np.float32).reshape(-1)
370
- except Exception:
371
- missing_idx.append(i)
372
- continue
373
- if arr.shape[0] != DIMENSION:
374
  missing_idx.append(i)
375
  continue
376
- out[i] = arr
377
  reused_idx.append(i)
378
 
379
  report: dict[str, Any] = {
@@ -382,25 +475,29 @@ def assemble_embeddings(
382
  "n_encoded": 0,
383
  "n_missing": len(missing_idx),
384
  "model_name": MODEL_NAME,
 
385
  "dimension": DIMENSION,
386
  "status": "reused" if not missing_idx else "partial",
387
  }
 
 
 
388
  if not missing_idx:
389
  report["status"] = "reused"
390
  return _l2_normalize(out) if n else out, report
391
  if not encode_missing:
392
  report["status"] = "incomplete"
393
  return out, report
394
- if not embeddings_available():
395
  report["status"] = "stub_missing_encoder"
396
- report["reason"] = "sentence-transformers/torch unavailable"
397
  return out, report
398
 
399
  missing = corpus.iloc[missing_idx].reset_index(drop=True)
400
  encoded = encode_corpus(
401
  missing,
402
  batch_size=batch_size,
403
- device=device,
404
  checkpoint_path=checkpoint_path,
405
  )
406
  for local_i, corpus_i in enumerate(missing_idx):
 
14
  from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
15
 
16
  MODEL_NAME = "thenlper/gte-small"
17
+ MODEL_REVISION = "17e1f347d17fe144873b1201da91788898c639cd"
18
  DIMENSION = 384
19
+ MAX_SEQ_LENGTH = 512
20
+ DEFAULT_DEVICE = "cuda"
21
+ SUPPORTED_DEVICES = frozenset({"cpu", "cuda", "cuda:0", "mps", "auto"})
22
  MAX_ROWS_PER_CENTROID = 8192
23
  MAX_SHARDS_PER_CENTROID = 2
24
 
 
28
  return x / np.maximum(n, eps)
29
 
30
 
31
+ def device_is_available(device: str) -> bool:
32
+ """Probe accelerator availability without loading a model."""
33
+ name = str(device or "").strip().lower()
34
+ if not name or name == "cpu":
35
+ return True
36
+ try:
37
+ import torch
38
+ except Exception:
39
+ return False
40
+ if name.startswith("cuda"):
41
+ return bool(
42
+ getattr(torch, "cuda", None)
43
+ and torch.backends.cuda.is_built()
44
+ and torch.cuda.is_available()
45
+ )
46
+ if name == "mps":
47
+ mps = getattr(getattr(torch, "backends", None), "mps", None)
48
+ return bool(mps is not None and mps.is_available())
49
+ return False
50
+
51
+
52
+ def select_device(requested: str = DEFAULT_DEVICE) -> tuple[str, bool]:
53
+ """Prefer CUDA like US Code / Open US Law; fall back to CPU."""
54
+ req = str(requested or DEFAULT_DEVICE).strip().lower() or DEFAULT_DEVICE
55
+ if req == "auto":
56
+ req = "cuda"
57
+ if req not in SUPPORTED_DEVICES and not req.startswith("cuda:"):
58
+ raise ValueError(f"unsupported embedding device: {requested!r}")
59
+ if device_is_available(req):
60
+ return req, False
61
+ return "cpu", True
62
+
63
+
64
+ def ensure_embedding_stack() -> bool:
65
+ """Lazy-import / lazy-install transformers + sentence-transformers.
66
+
67
+ Matches ``ipfs_datasets_py.auto_installer.ensure_module`` used by other
68
+ GraphRAG producers. Importing this module must not pip-install; first
69
+ encode may.
70
+ """
71
+ import os
72
+
73
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
74
  try:
75
+ import sentence_transformers # noqa: F401
76
+ import transformers # noqa: F401
77
 
78
  return True
79
+ except Exception:
80
+ pass
81
+ try:
82
+ from ipfs_datasets_py.auto_installer import ensure_module, install_for_component
83
+
84
+ install_for_component("graphrag")
85
+ ensure_module("torchvision", "torchvision")
86
+ ensure_module("transformers", "transformers")
87
+ module = ensure_module("sentence_transformers", "sentence-transformers")
88
+ return module is not None
89
  except Exception:
90
  return False
91
 
92
 
93
+ def embeddings_available() -> bool:
94
+ return ensure_embedding_stack()
95
+
96
+
97
+ def _is_real_vector(vec: object) -> bool:
98
+ try:
99
+ arr = np.asarray(vec, dtype=np.float32).reshape(-1)
100
+ except Exception:
101
+ return False
102
+ if arr.shape[0] != DIMENSION:
103
+ return False
104
+ if not np.isfinite(arr).all():
105
+ return False
106
+ return float(np.linalg.norm(arr)) > 1e-6
107
+
108
+
109
  def encode_corpus(
110
  corpus: pd.DataFrame,
111
  batch_size: int = 64,
112
+ device: str = DEFAULT_DEVICE,
113
  checkpoint_path: str | None = None,
114
  chunk_size: int = 4096,
115
  ) -> np.ndarray:
116
+ """Encode corpus texts with pinned gte-small on CUDA when available."""
117
  import json
118
  import os
119
  from datetime import datetime, timezone
120
  from pathlib import Path as _Path
121
 
122
+ if not ensure_embedding_stack():
123
+ raise RuntimeError(
124
+ "sentence-transformers is required for production GTE embeddings; "
125
+ "lazy install failed (python -m ipfs_datasets_py.auto_installer)"
126
+ )
127
  from sentence_transformers import SentenceTransformer
128
 
129
  from .auth import configure_hf
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:
 
446
  *,
447
  encode_missing: bool = True,
448
  batch_size: int = 64,
449
+ device: str = DEFAULT_DEVICE,
450
  checkpoint_path: str | None = None,
451
  ) -> tuple[np.ndarray, dict[str, Any]]:
452
+ """Align a (n, 384) matrix to *corpus* row order.
453
 
454
+ Reuse is CID-keyed and only accepts real GTE vectors (finite, 384-d,
455
+ non-zero). Stub/zero priors are treated as missing and re-encoded on
456
+ CUDA when available — the US Code / Open US Law contract.
457
  """
458
  n = int(len(corpus))
459
  out = np.zeros((n, DIMENSION), dtype=np.float32)
 
463
  cids = corpus["entry_cid"].astype(str).tolist() if n else []
464
  for i, cid in enumerate(cids):
465
  vec = prior.get(cid)
466
+ if not _is_real_vector(vec):
 
 
 
 
 
 
 
 
467
  missing_idx.append(i)
468
  continue
469
+ out[i] = np.asarray(vec, dtype=np.float32).reshape(-1)
470
  reused_idx.append(i)
471
 
472
  report: dict[str, Any] = {
 
475
  "n_encoded": 0,
476
  "n_missing": len(missing_idx),
477
  "model_name": MODEL_NAME,
478
+ "model_revision": MODEL_REVISION,
479
  "dimension": DIMENSION,
480
  "status": "reused" if not missing_idx else "partial",
481
  }
482
+ resolved, fallback = select_device(device)
483
+ report["device"] = resolved
484
+ report["device_fallback"] = fallback
485
  if not missing_idx:
486
  report["status"] = "reused"
487
  return _l2_normalize(out) if n else out, report
488
  if not encode_missing:
489
  report["status"] = "incomplete"
490
  return out, report
491
+ if not ensure_embedding_stack():
492
  report["status"] = "stub_missing_encoder"
493
+ report["reason"] = "sentence-transformers/transformers lazy install failed"
494
  return out, report
495
 
496
  missing = corpus.iloc[missing_idx].reset_index(drop=True)
497
  encoded = encode_corpus(
498
  missing,
499
  batch_size=batch_size,
500
+ device=resolved,
501
  checkpoint_path=checkpoint_path,
502
  )
503
  for local_i, corpus_i in enumerate(missing_idx):
country_laws_ir/verify.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
193
+ unit = str(report.get("unit") or "")
194
+ n = int(len(corpus)) if corpus is not None else 0
195
+ structured_rows = 0
196
+ if corpus is not None and not corpus.empty:
197
+ if "hierarchy_path" in corpus.columns:
198
+ structured_rows = int((corpus["hierarchy_path"].fillna("").astype(str).str.len() > 0).sum())
199
+ if "record_type" in corpus.columns:
200
+ structured_rows = max(
201
+ structured_rows,
202
+ int(corpus["record_type"].isin(["article", "section"]).sum()),
203
+ )
204
+ coverage = structured_rows / float(n) if n else 0.0
205
+ # Article or structured units are success. Pure law-level is a warning, not a fail:
206
+ # many gazettes have no title/section markers.
207
+ if unit in {"article", "structured"} or coverage >= 0.5:
208
+ return Check(
209
+ id="legal_structure",
210
+ severity="warn",
211
+ passed=True,
212
+ message=f"retrieval units are structured ({unit}, coverage={coverage:.2f})",
213
+ evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
214
+ )
215
+ return Check(
216
+ id="legal_structure",
217
+ severity="warn",
218
+ passed=True,
219
+ message=(
220
+ "kept whole-instrument units; no title/article/section headings detected "
221
+ "(expected for some gazettes)"
222
+ ),
223
+ evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
224
+ )
225
+
226
+
227
+ def verify_normalized_corpus(
228
+ corpus: pd.DataFrame,
229
+ report: dict[str, Any],
230
+ *,
231
+ slug: str = "",
232
+ ) -> dict[str, Any]:
233
+ """Run all normalization verifiers. Fail-closed on any failed `fail` check."""
234
+ checks = [
235
+ check_nonempty(corpus, report),
236
+ check_entry_cids(corpus, report),
237
+ check_no_invented_text(report),
238
+ check_html_residual(corpus),
239
+ check_short_bodies(corpus),
240
+ check_structure(corpus, report),
241
+ check_heading_language(corpus, report),
242
+ ]
243
+ failed = [c for c in checks if c.severity == "fail" and not c.passed]
244
+ admitted = not failed
245
+ return {
246
+ "schema_version": SCHEMA_VERSION,
247
+ "slug": slug,
248
+ "admitted": admitted,
249
+ "n_checks": len(checks),
250
+ "n_failed": len(failed),
251
+ "failed_ids": [c.id for c in failed],
252
+ "checks": [c.to_dict() for c in checks],
253
+ "blocks_graphrag": not admitted,
254
+ }
255
+
256
+
257
+ class NormalizationAdmissionError(RuntimeError):
258
+ """Raised when verifiers refuse to send a corpus to GraphRAG."""
259
+
260
+
261
+ def verify_source(source: str) -> dict[str, Any]:
262
+ """Load a Hub/local pack, normalize, and run verifiers (no GraphRAG)."""
263
+ from .build import CACHE
264
+ from .catalog import get_country
265
+ from .normalize import build_corpus, load_source
266
+
267
+ country = get_country(source)
268
+ local = country.get("local_source_dir")
269
+ laws, articles, source_meta = load_source(local or country["repo"], CACHE)
270
+ corpus, report = build_corpus(laws, articles, source_meta)
271
+ verdict = verify_normalized_corpus(corpus, report, slug=country["slug"])
272
+ report["verification"] = verdict
273
+ return {
274
+ "slug": country["slug"],
275
+ "source": country["repo"],
276
+ "n_out": report.get("n_out"),
277
+ "unit": report.get("unit"),
278
+ "verification": verdict,
279
+ "drops": report.get("drops"),
280
+ }
data/bm25/documents/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0b662bb923de230d8d1485fc742f51bf85e846eefbfd4cef84a78444838c5aec
3
- size 475351
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:460b93df18faa027d93d98533a93050663a6e7646390941a7a828b8366c8f363
3
+ size 475277
data/bm25/documents/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bf014b7d1643d3d45404e5ac2d14a31d207e967a0effb0e93bdd2532ad6771e3
3
- size 487273
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef04d08740257b450afa4eaae22e4ff400512fe886c5e6da94cb5b3453a3b04b
3
+ size 487237
data/corpus/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:de8188af94587254a44e6fd655aee3b3424aaf57e01a5001ee3f07ce16ff3348
3
- size 2307689
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25e7813b8911d95c122e6fa623b2aa2614d622cec9d9f9838644cd56b1864019
3
+ size 2377416
data/corpus/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7de905c875ec742f78c7efd1976a0f8bf87aef1fac7deb4543c9bc427b4d7524
3
- size 2495771
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e565339afc1d1f2a09bd5287f9b10cc6cc9b2282c0ffea3aac4ac9f5a3c426b8
3
+ size 2572576
data/graph/adjacency/in/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fca17077428de67ef7ac6fb178f8fc4e6c436ac6a2d0bc1d9b996454e03d61af
3
- size 316554
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5ea70c1c8d77e93636c8417decda929c3769b55a727097ce7dfb83f7a501598
3
+ size 316588
data/graph/adjacency/in/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:25d77bf75d244236af46226f0c9a820396b5becc30b2926968cff8721fcc12ab
3
- size 571936
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0247655b967e82ff89cb43de9d8b1ac6740fb197f2b48ad6d16444a88823cf46
3
+ size 572860
data/graph/adjacency/in/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ea84a1a209bb7cea4006cd0bc2bcc0898a11c418291625f00cb6ed9852c66f23
3
- size 407618
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55e6a1ef03beb467d7cd8ba3ddf32a6008a66c9b2788a1a5b45b67c01394f6e6
3
+ size 408484
data/graph/adjacency/in/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:42326f24e20306b969b3a59b2076d5d9ddad16a132261ae59e065e368322eb5d
3
- size 510927
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9779ddccbe028c629045fd5e4b79fd3cf69c8a013d683fab49b2819191b0c1fc
3
+ size 511388
data/graph/adjacency/in/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:cfc08466007f77bf4109c51f1cb1d8daffd3891ff7cc2006cf12c8bd50bfca58
3
- size 373027
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a547efa604a4d94e46e3e3d3b1cec5fb77858ebbeefb5e797ea6414bfcf4a4a
3
+ size 372774
data/graph/adjacency/in/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:32b9aae1a66d9734843277af0cdbddd17c6e7373236168f46222c3518b3460db
3
- size 512847
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8b31c37fa9f390fa4b95c4f20f0aee3b72852a8f375a95d3e6fda9edf21eac4
3
+ size 512632
data/graph/adjacency/in/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bfdef8f5544ca8e59220590e0929682b52fa24690724617c435605d4bd9013f7
3
- size 392399
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac11a83320ad42abbf093ef5fbc69247a5957439153f411cbb884413057fad25
3
+ size 392139
data/graph/adjacency/in/part-000007.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7b6d422f8d17a3e9d6a1bdd1f43ebea0b4ef5ac8fe7401e241eedc5cb8f90990
3
- size 516302
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf71ec170b4b0a544bcd2f29dce7afd30da94d10de17490198a1a918dde32cbc
3
+ size 517362
data/graph/adjacency/in/part-000008.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:de32220d057c192cbdfac912cfbcdc1bbf024d939a7af4e08ff989f709df1bb3
3
- size 82763
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8ab6a3a23ed5ff7ce0d84c81938b3a3b14bd8418293c51a71176b8f58c1c29b
3
+ size 82743
data/graph/adjacency/out/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:027fd8204a5b7d8fcb14462bc29c0905e773832a7d65ac4bf4fca1d2c80326ad
3
- size 382359
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35a676ad8a9926bcc1acf930b8c548a1c6941f995c22f6da165c1f1ebc5b39a7
3
+ size 383181
data/graph/adjacency/out/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9ae272b0d9d60508d6c2be5e2c48f7ae2246e611449f45edac4951d6379e85d8
3
- size 382079
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dbd2f86c77a6093201ad019a1eb26ed9c094cb179f2f9e28447e9b79539cea25
3
+ size 383385
data/graph/adjacency/out/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6e431b536084531787705e2abd060c0d083959657f5b09d136e0115fcbf358f5
3
- size 381672
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edc316004880c2ac916e01b2735b347547731e4b13ad5fb22ec83b9e5cdf51c4
3
+ size 383066
data/graph/adjacency/out/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:33224f09595aa5bbfbcba2bcaf219bb01035f56ed8c4ee38bf691f0a4b87b13b
3
- size 383307
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bafc9d61142c07f30f2588b17f7673a026c42732f15bbdfa08272ff71997c2f7
3
+ size 383363
data/graph/adjacency/out/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:432be4853ae5914c61675e84acd1d630529fd8495d12c53b1b3203956fbf9816
3
- size 383787
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4325529239333361dd44290989e0c96420b34b9233b6e4939462008bacdf92fd
3
+ size 381335
data/graph/adjacency/out/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:261093574601918cbe5a69258a45f9b14e1af12f94fa6d44b10b507cfb7a6b1a
3
- size 383559
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88aad192b7a916b5d6bbc757d423a1207091efa34feec4edc72d21cdf5cb3096
3
+ size 382132
data/graph/adjacency/out/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f0ab3b4697139c261323409300c3b9463e6db050b3a280c0ea451ae95ff7cf5a
3
- size 296760
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe8b34e5690664ed820aca49ed4e6200f8a8890f285576e0172a8af9da7e8331
3
+ size 297299
data/graph/edges/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:21428b00a0321ba37a5bc43288ee34cf94006c4d53747ad91b6fb0c4696b191d
3
- size 294782
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64c8c438f73029872c143ff6696e36dab28a3d2cfbafa1d04ba1370404694f64
3
+ size 292788
data/graph/edges/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1b9cea0516f829a789ef0d71164ea785eb9cd22ddbcf051e4b6a65b6a84e2333
3
- size 294424
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfc633ef9bf6d9b70f494d507f44af118c4f8ae6ac8101f22876f601b19bd74d
3
+ size 295424
data/graph/edges/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2d91070d212e0b9d5cd62cc93c629d5323c6ba40a0ac4ac97216ae680150a078
3
- size 294376
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2f135a25a433e58682afbf174d76d192a9ec4316b0b240af538ec769aabc863
3
+ size 294426
data/graph/edges/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:897916ba941761bce30b42c4d18b814e8a569edffabd53714565e2813ca5a185
3
- size 292957
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3cf6e1bcf5b138b1dbe33a87bc21e15b51c1f9a21e6b9b450f6c89b91fe33bc
3
+ size 294729
data/graph/edges/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d2ccd0b6a2b148135351267ccd0d1be7da6478ddba14490f299be580d0ef631c
3
- size 295027
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e9da5ed631f417ac0d20538a31b9a5a148b7a50b6538c025189babfee7d74ea
3
+ size 295419
data/graph/edges/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:10f105fc2e3c0aa0ed5eb9f5923a2a973536fcc201c61e17aa7a7c1877b63942
3
- size 294298
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3b24f850942ee0a8f5b54aaadfa2c19aa1366dcb693d5ca1d229bb22408467f
3
+ size 294953
data/graph/edges/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ac89aaaf371a16b8d776b0d2b099517fce328e1dd2b812fbf3487cf417743d07
3
- size 292629
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:099ca3b9c9457db48e5a385e1725968f620576b5079332341312be83c0958c57
3
+ size 294836
data/graph/edges/part-000007.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:01951eff89a87f5605b33dca71743388ba6b28a799de36c23b6b4a5c94ffaeaa
3
- size 294475
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90eee28c2fe8d3de995f8aeb065905b0b52702d29cd3398e30ad3a121c113b3b
3
+ size 292884
data/graph/edges/part-000008.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:eb3a8d18ed3e7aa1757ea48e79af1afbed8866a6f488d473636243f081a06505
3
- size 294094
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcf2084a740302b5ea24cc99684da1337f96b820a692d79923d3616663094a84
3
+ size 295885
data/graph/edges/part-000009.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7eb63219c2301f5eba230b7fcaa9330774d4111d2c07947c89f6ded757603b2d
3
- size 294031
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32c82a34b4570eff2d4929c7029a2bfe11b97e28147e1ebc45cebe0f02f19143
3
+ size 294911
data/graph/edges/part-000010.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:832284a909c6399bf61098161c7ea04518ec5c4620b500276f593c54eb950250
3
- size 292979
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e73f9b03c038628fd19155baa2cf79d1200dcaedc1069e0b1f96b87fc46f72f
3
+ size 293854
data/graph/edges/part-000011.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0fa894848b8e32c6a77f178f47f7cdb213fc03995c5757f1bbc549aeb53fa40f
3
- size 295400
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76749c3f60fe6f3c9825a71c35068e356d303b945010aa6e6f93ad331be58f7a
3
+ size 294383
data/graph/edges/part-000012.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3ce3324e52232b46d44496c77e86587f612f52398d3f7d55fa6abc851b1f95ab
3
- size 292949
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9096e81367d7874444a7bed374067cb0beef2267c9eee7454c1fd885fa66ffc5
3
+ size 295537
data/graph/edges/part-000013.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:186a0c1e9121c72a7d58f74c8bacccd8842c821f1a59584f7895cb959c3f31d6
3
- size 168527
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3d2b8b3e409611f9662ac08b092633a1cb11bf4587009a64ea26e401864ac264
3
+ size 167601
data/graph/nodes/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d9501f3fedba78b0ddc2a5a6a647353806f7b6ce161b52d361f8bcb77d3b9d38
3
- size 359564
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c19e2b488467e6e9fcc04b529d36b114d7d2407296867033ca0607df0b26b0c
3
+ size 359603
data/graph/nodes/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d11b2796c86569b0fbae928a7d2121d8f1e3c577a3ba0c6922006b187460dfb2
3
- size 360358
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e9396a6f64a70631ce94adb7728e18caf1c2fda9cffae0c52ffafcaf536913f4
3
+ size 360828
data/graph/nodes/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:dd27b8ce3c419cff070ae196a55e0d7f0db86237e847f9db4897d6d8552e74c0
3
- size 158740
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5861ae106713a4241035013cb13173347c00e32d220da43e7a0f2213d0e35e0e
3
+ size 158860
data/vectors/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:67c7bd47e6a211f28110a853e4403d7a0b80e7c194f4d21bf807af2012687c5f
3
- size 6086870
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c47b38c5ea14b065df28f20242caca067cc548d42c5aa772167d42fac727ea4
3
+ size 6158742