endomorphosis commited on
Commit
69f5a55
·
verified ·
1 Parent(s): dded496

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +8 -8
  2. build.py +326 -53
  3. country_laws_ir/__init__.py +1 -1
  4. country_laws_ir/__main__.py +123 -11
  5. country_laws_ir/auth.py +26 -4
  6. country_laws_ir/build.py +326 -53
  7. country_laws_ir/catalog.py +82 -9
  8. country_laws_ir/cidutil.py +21 -0
  9. country_laws_ir/coverage.py +452 -0
  10. country_laws_ir/incremental.py +500 -0
  11. country_laws_ir/mem.py +236 -0
  12. country_laws_ir/normalize.py +48 -11
  13. country_laws_ir/package.py +355 -0
  14. country_laws_ir/raw_package.py +324 -0
  15. country_laws_ir/spill.py +763 -0
  16. country_laws_ir/upload.py +109 -14
  17. country_laws_ir/vectors.py +116 -18
  18. data/bm25/documents/part-000000.parquet +2 -2
  19. data/bm25/documents/part-000001.parquet +2 -2
  20. data/bm25/documents/part-000002.parquet +3 -0
  21. data/bm25/postings/part-000000.parquet +2 -2
  22. data/corpus/part-000000.parquet +2 -2
  23. data/corpus/part-000001.parquet +2 -2
  24. data/corpus/part-000002.parquet +3 -0
  25. data/graph/adjacency/incoming/part-000000.parquet +2 -2
  26. data/graph/adjacency/incoming/part-000001.parquet +3 -0
  27. data/graph/adjacency/outgoing/part-000000.parquet +2 -2
  28. data/graph/adjacency/outgoing/part-000001.parquet +2 -2
  29. data/graph/adjacency/outgoing/part-000002.parquet +3 -0
  30. data/graph/edges/part-000000.parquet +2 -2
  31. data/graph/edges/part-000001.parquet +2 -2
  32. data/graph/edges/part-000002.parquet +2 -2
  33. data/graph/edges/part-000003.parquet +2 -2
  34. data/graph/edges/part-000004.parquet +2 -2
  35. data/graph/edges/part-000005.parquet +2 -2
  36. data/graph/edges/part-000006.parquet +2 -2
  37. data/graph/edges/part-000007.parquet +2 -2
  38. data/graph/edges/part-000008.parquet +2 -2
  39. data/graph/edges/part-000009.parquet +2 -2
  40. data/graph/edges/part-000010.parquet +2 -2
  41. data/graph/edges/part-000011.parquet +2 -2
  42. data/graph/edges/part-000012.parquet +3 -0
  43. data/graph/edges/part-000013.parquet +3 -0
  44. data/graph/edges/part-000014.parquet +3 -0
  45. data/graph/edges/part-000015.parquet +3 -0
  46. data/graph/edges/part-000016.parquet +3 -0
  47. data/graph/edges/part-000017.parquet +3 -0
  48. data/graph/edges/part-000018.parquet +3 -0
  49. data/graph/edges/part-000019.parquet +3 -0
  50. data/graph/edges/part-000020.parquet +3 -0
README.md CHANGED
@@ -56,7 +56,7 @@ configs:
56
 
57
  # Saudi Arabia legislation IR (CID-keyed sparse GraphRAG)
58
 
59
- Research retrieval release of `endomorphosis/ipfs_saudiarabia_laws` (revision `47bbf142ade8`) packaged as
60
  `country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3` / publicus-ir).
61
 
62
  **Not legal advice.** This is a research snapshot. The official gazette /
@@ -73,13 +73,13 @@ Target Hub id (packaging metadata only): `justicedao/ipfs_saudiarabia_laws_ir`.
73
  | Field | Value |
74
  | --- | --- |
75
  | Laws (corpus units) | 0 |
76
- | Articles (corpus units) | 4664 |
77
- | Canonical docs | 4664 |
78
- | BM25 terms | 1498 |
79
- | BM25 postings | 10560 |
80
- | Graph nodes | 5353 |
81
- | Graph edges | 45185 |
82
- | Vectors | 4664 × 384-d `thenlper/gte-small` (embedded) |
83
 
84
  ## Canonical fields
85
 
 
56
 
57
  # Saudi Arabia legislation IR (CID-keyed sparse GraphRAG)
58
 
59
+ Research retrieval release of `endomorphosis/ipfs_saudiarabia_laws` (revision `94bd316e19d5d391c4b9e202d199d5debf8965c3`) packaged as
60
  `country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3` / publicus-ir).
61
 
62
  **Not legal advice.** This is a research snapshot. The official gazette /
 
73
  | Field | Value |
74
  | --- | --- |
75
  | Laws (corpus units) | 0 |
76
+ | Articles (corpus units) | 10466 |
77
+ | Canonical docs | 10466 |
78
+ | BM25 terms | 1628 |
79
+ | BM25 postings | 16654 |
80
+ | Graph nodes | 11743 |
81
+ | Graph edges | 99133 |
82
+ | Vectors | 10466 × 384-d `thenlper/gte-small` (partial) |
83
 
84
  ## Canonical fields
85
 
build.py CHANGED
@@ -1,22 +1,59 @@
1
- """End-to-end build: normalize → BM25 → graph → vectors → package (no upload by default)."""
 
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
 
 
5
  import json
 
 
6
  import traceback
7
  from datetime import datetime, timezone
8
  from pathlib import Path
9
  from typing import Any
10
 
11
  from .bm25 import bm25_neighbors, build_index
 
 
 
 
 
 
 
 
 
 
 
12
  from .catalog import get_country, indexable_countries, target_repo
13
  from .graph import build_graph
 
 
 
 
 
 
 
 
 
14
  from .normalize import build_corpus, load_source
15
- from .package import package_release
16
  from .auth import configure_hf
17
- from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors
 
 
 
 
 
 
 
 
18
 
19
- ROOT = Path("/workspace/country-laws-ir")
20
  CACHE = ROOT / "cache"
21
  RELEASES = ROOT / "releases"
22
  REPORTS = ROOT / "reports"
@@ -35,6 +72,95 @@ def record_progress(event: dict[str, Any]) -> None:
35
  f.write(json.dumps(event, ensure_ascii=False) + "\n")
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def build_country(
39
  source: str,
40
  out: Path | None = None,
@@ -42,6 +168,10 @@ def build_country(
42
  device: str = "cpu",
43
  neighbor_k: int = 8,
44
  skip_vectors: bool = False,
 
 
 
 
45
  ) -> dict[str, Any]:
46
  country = get_country(source)
47
  if not country.get("indexable", True):
@@ -57,7 +187,9 @@ def build_country(
57
  )
58
  else None
59
  )
60
- _log(f"build start {repo} -> {out} (upload={upload}) local={local_dir}")
 
 
61
  configure_hf()
62
  CACHE.mkdir(parents=True, exist_ok=True)
63
  REPORTS.mkdir(parents=True, exist_ok=True)
@@ -66,6 +198,35 @@ def build_country(
66
  f"source loaded laws={source_meta['n_laws_source']} "
67
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
68
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  corpus, norm_report = build_corpus(laws, articles, source_meta)
70
  report_path = REPORTS / f"{country['slug']}_normalization.json"
71
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
@@ -79,46 +240,86 @@ def build_country(
79
  if corpus.empty:
80
  raise RuntimeError("Normalized corpus is empty; refusing to package")
81
 
82
- bm25 = build_index(corpus)
83
- _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
84
- _log(f"bm25 neighbors start n={len(corpus)} k={neighbor_k}")
85
- neighbors = bm25_neighbors(bm25, k=neighbor_k)
86
- _log("bm25 neighbors done")
87
- graph = build_graph(corpus, neighbors)
88
- _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
89
 
90
- vector_blocker = None
91
- if skip_vectors:
92
- vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
93
- vector_blocker = "skip_vectors"
94
- elif embeddings_available():
95
- try:
96
- ckpt = CACHE / "embeddings" / f"{country['slug']}.npy"
97
- _log(f"vectors encode start n={len(corpus)} checkpoint={ckpt}")
98
- embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt))
99
- vectors = layout_vectors(corpus, embeddings)
100
- _log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
101
- except Exception as exc:
102
- vector_blocker = f"embedding_failed: {exc}"
103
- _log(f"vector embedding failed; writing stub ({exc})")
104
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
105
- else:
106
- vector_blocker = "sentence-transformers/torch unavailable"
107
- _log(f"vectors stub: {vector_blocker}")
108
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
109
 
110
- code_root = Path(__file__).resolve().parent.parent
111
- manifest = package_release(
112
- out,
113
- corpus,
114
- bm25,
115
- graph,
116
- vectors,
117
- source_meta,
118
- country,
119
- code_root,
120
- normalization_report=norm_report,
121
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  _log(f"packaged {out}")
123
  result = {
124
  "country": country["slug"],
@@ -129,7 +330,10 @@ def build_country(
129
  "counts": manifest["counts"],
130
  "normalization": norm_report,
131
  "vector_blocker": vector_blocker,
 
132
  "schema_version": manifest["schema_version"],
 
 
133
  }
134
  if upload:
135
  from .upload import upload_release
@@ -147,25 +351,93 @@ def batch(
147
  slugs: list[str] | None = None,
148
  upload: bool = False,
149
  skip_done: bool = True,
 
 
 
150
  ) -> list[dict[str, Any]]:
151
- done = set()
152
- if skip_done and PROGRESS.exists():
153
- for line in PROGRESS.read_text(encoding="utf-8").splitlines():
154
- if not line.strip():
155
- continue
156
- rec = json.loads(line)
157
- if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
158
- done.add(rec["country"])
159
  targets = slugs or [c["slug"] for c in indexable_countries()]
160
  if "malta" in targets:
161
  targets = ["malta"] + [s for s in targets if s != "malta"]
162
  results = []
 
163
  for slug in targets:
164
- if skip_done and slug in done:
165
- _log(f"skip already done {slug}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  try:
168
- results.append(build_country(slug, upload=upload))
 
 
 
 
 
 
 
 
169
  except Exception as exc:
170
  _log(f"FAILED {slug}: {exc}")
171
  record_progress(
@@ -176,5 +448,6 @@ def batch(
176
  "traceback": traceback.format_exc(),
177
  }
178
  )
 
179
  continue
180
  return results
 
1
+ """End-to-end build: normalize → incremental vectors → BM25 → graph → package.
2
+
3
+ Default mode is ``auto``: skip when the endomorphosis source revision is
4
+ unchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuild
5
+ BM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-in
6
+ via ``upload=True``.
7
+ """
8
 
9
  from __future__ import annotations
10
 
11
+ import os
12
+
13
  import json
14
+
15
+ import pandas as pd
16
  import traceback
17
  from datetime import datetime, timezone
18
  from pathlib import Path
19
  from typing import Any
20
 
21
  from .bm25 import bm25_neighbors, build_index
22
+ from .mem import MemAbort, checkpoint, log_mem
23
+ from .spill import (
24
+ SQLITE_THRESHOLD,
25
+ build_bm25_tf_spill,
26
+ build_graph_from_neighbor_shards,
27
+ neighbors_via_sqlite,
28
+ should_use_sqlite,
29
+ spill_dir_for,
30
+ spill_pickle,
31
+ )
32
+ from .package import package_from_spill, package_release
33
  from .catalog import get_country, indexable_countries, target_repo
34
  from .graph import build_graph
35
+ from .incremental import (
36
+ fetch_hub_prior,
37
+ load_embedding_cache,
38
+ load_prior_release,
39
+ load_release_vectors_by_cid,
40
+ merge_embedding_maps,
41
+ plan_rebuild,
42
+ save_embedding_cache,
43
+ )
44
  from .normalize import build_corpus, load_source
 
45
  from .auth import configure_hf
46
+ from .vectors import (
47
+ DIMENSION,
48
+ MODEL_NAME,
49
+ assemble_embeddings,
50
+ embeddings_available,
51
+ embeddings_by_cid,
52
+ layout_stub_vectors,
53
+ layout_vectors,
54
+ )
55
 
56
+ ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
57
  CACHE = ROOT / "cache"
58
  RELEASES = ROOT / "releases"
59
  REPORTS = ROOT / "reports"
 
72
  f.write(json.dumps(event, ensure_ascii=False) + "\n")
73
 
74
 
75
+ def _prior_dir_for(
76
+ slug: str,
77
+ out: Path,
78
+ prior_dir: Path | None,
79
+ *,
80
+ fetch_hub: bool = True,
81
+ ) -> Path | None:
82
+ if prior_dir is not None:
83
+ return Path(prior_dir)
84
+ if out.is_dir() and (out / "manifest.json").is_file():
85
+ return out
86
+ default = RELEASES / f"ipfs_{slug}_laws_ir"
87
+ if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve():
88
+ return default
89
+ if not fetch_hub:
90
+ return None
91
+ hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir")
92
+ if hub is not None:
93
+ _log(f"using justicedao prior {hub}")
94
+ return hub
95
+
96
+
97
+ def _encode_vectors(
98
+ *,
99
+ corpus: pd.DataFrame,
100
+ country_slug: str,
101
+ prior,
102
+ plan,
103
+ skip_vectors: bool,
104
+ device: str,
105
+ ) -> tuple[dict[str, Any], str | None, dict[str, Any]]:
106
+ import gc
107
+
108
+ vector_report: dict[str, Any] = {"status": "stub"}
109
+ vector_blocker = None
110
+ if skip_vectors:
111
+ vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
112
+ return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
113
+
114
+ cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet"
115
+ prior_by_cid = {}
116
+ if plan.reuse_embeddings:
117
+ prior_by_cid = merge_embedding_maps(
118
+ load_embedding_cache(cid_cache_path),
119
+ None if prior is None else load_release_vectors_by_cid(prior.directory),
120
+ )
121
+ _log(f"embedding cache reused_cids={len(prior_by_cid)}")
122
+ try:
123
+ positional = CACHE / "embeddings" / f"{country_slug}.npy"
124
+ embeddings, vector_report = assemble_embeddings(
125
+ corpus,
126
+ prior_by_cid,
127
+ encode_missing=embeddings_available(),
128
+ device=device,
129
+ checkpoint_path=str(positional),
130
+ )
131
+ if (
132
+ vector_report.get("status") in {"stub_missing_encoder", "incomplete"}
133
+ and not int(vector_report.get("n_reused") or 0)
134
+ ):
135
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
136
+ vectors = layout_stub_vectors(corpus, reason=str(vector_blocker))
137
+ return vectors, vector_blocker, vector_report
138
+ vectors = layout_vectors(corpus, embeddings)
139
+ if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused":
140
+ vectors["stats"]["status"] = "partial"
141
+ vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0)
142
+ vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0)
143
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
144
+ save_embedding_cache(
145
+ cid_cache_path,
146
+ merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)),
147
+ model_name=MODEL_NAME,
148
+ dimension=DIMENSION,
149
+ )
150
+ del embeddings
151
+ gc.collect()
152
+ _log(
153
+ f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} "
154
+ f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}"
155
+ )
156
+ return vectors, None, vector_report
157
+ except Exception as exc:
158
+ vector_blocker = f"embedding_failed: {exc}"
159
+ _log(f"vector embedding failed; writing stub ({exc})")
160
+ vectors = layout_stub_vectors(corpus, reason=vector_blocker)
161
+ return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
162
+
163
+
164
  def build_country(
165
  source: str,
166
  out: Path | None = None,
 
168
  device: str = "cpu",
169
  neighbor_k: int = 8,
170
  skip_vectors: bool = False,
171
+ mode: str = "auto",
172
+ force: bool = False,
173
+ prior_dir: Path | None = None,
174
+ fetch_hub_prior_ir: bool = True,
175
  ) -> dict[str, Any]:
176
  country = get_country(source)
177
  if not country.get("indexable", True):
 
187
  )
188
  else None
189
  )
190
+ _log(
191
+ f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
192
+ )
193
  configure_hf()
194
  CACHE.mkdir(parents=True, exist_ok=True)
195
  REPORTS.mkdir(parents=True, exist_ok=True)
 
198
  f"source loaded laws={source_meta['n_laws_source']} "
199
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
200
  )
201
+ prior = load_prior_release(
202
+ _prior_dir_for(
203
+ country["slug"],
204
+ out,
205
+ prior_dir,
206
+ fetch_hub=fetch_hub_prior_ir,
207
+ )
208
+ )
209
+ plan = plan_rebuild(
210
+ mode=mode, source_meta=source_meta, prior=prior, force=force
211
+ )
212
+ if plan.skip_build:
213
+ _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
214
+ result = {
215
+ "country": country["slug"],
216
+ "source": repo,
217
+ "source_revision": source_meta["source_revision"],
218
+ "out": str(out),
219
+ "target_hub_id": target_repo(country["slug"]),
220
+ "skipped": True,
221
+ "incremental": plan.to_dict(),
222
+ "normalization": {"n_out": plan.delta.current_count if plan.delta else 0},
223
+ "vector_blocker": None,
224
+ "neighbor_via": None,
225
+ "schema_version": "country-laws-ir-graphrag/v1",
226
+ }
227
+ record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
228
+ return result
229
+
230
  corpus, norm_report = build_corpus(laws, articles, source_meta)
231
  report_path = REPORTS / f"{country['slug']}_normalization.json"
232
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
 
240
  if corpus.empty:
241
  raise RuntimeError("Normalized corpus is empty; refusing to package")
242
 
243
+ import gc
 
 
 
 
 
 
244
 
245
+ plan = plan_rebuild(
246
+ mode=mode,
247
+ source_meta=source_meta,
248
+ prior=prior,
249
+ current_corpus=corpus,
250
+ force=force,
251
+ )
252
+ _log(
253
+ f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
254
+ f"added={0 if plan.delta is None else plan.delta.n_added} "
255
+ f"removed={0 if plan.delta is None else plan.delta.n_removed}"
256
+ )
257
+
258
+ n_docs = len(corpus)
259
+ spill = spill_dir_for(country["slug"], CACHE)
260
+ spill.mkdir(parents=True, exist_ok=True)
261
+ corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet"
262
+ corpus.to_parquet(corpus_ckpt, index=False)
263
+ checkpoint("after_normalize", log=_log)
264
 
265
+ vectors, vector_blocker, vector_report = _encode_vectors(
266
+ corpus=corpus,
267
+ country_slug=country["slug"],
268
+ prior=prior,
269
+ plan=plan,
270
+ skip_vectors=skip_vectors,
271
+ device=device,
 
 
 
 
272
  )
273
+ spill_pickle(spill / "vectors.pkl", vectors)
274
+ del vectors
275
+ gc.collect()
276
+ checkpoint("vectors_spilled", log=_log)
277
+ extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
278
+
279
+ use_sqlite = should_use_sqlite(n_docs)
280
+ neighbor_via = "stock"
281
+ if use_sqlite:
282
+ _log(f"sqlite neighbors path n={n_docs} (>= {SQLITE_THRESHOLD}) spill={spill}")
283
+ # Free corpus body for neighbor stream — reload later for graph
284
+ del corpus
285
+ gc.collect()
286
+ neighbors_via_sqlite(corpus_ckpt, spill, n_docs, k=neighbor_k, log=_log)
287
+ neighbor_via = "sqlite_fts"
288
+ bm25_info = build_bm25_tf_spill(corpus_ckpt, spill, n_docs, log=_log)
289
+ corpus = pd.read_parquet(corpus_ckpt)
290
+ graph = build_graph_from_neighbor_shards(corpus, spill, log=_log)
291
+ spill_pickle(spill / "graph.pkl", graph)
292
+ del graph, corpus
293
+ gc.collect()
294
+ checkpoint("graph_spilled", log=_log)
295
+ code_root = Path(__file__).resolve().parent.parent
296
+ manifest = package_from_spill(
297
+ out, spill, corpus_ckpt, source_meta, country, code_root,
298
+ normalization_report=norm_report, expected_rows=n_docs,
299
+ extra_manifest=extra_manifest,
300
+ )
301
+ _log(f"packaged sequential via={neighbor_via} {out}")
302
+ else:
303
+ bm25 = build_index(corpus)
304
+ _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
305
+ _log(f"bm25 neighbors start n={n_docs} k={neighbor_k}")
306
+ neighbors = bm25_neighbors(bm25, k=neighbor_k)
307
+ _log("bm25 neighbors done")
308
+ graph = build_graph(corpus, neighbors)
309
+ del neighbors
310
+ gc.collect()
311
+ _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
312
+ with open(spill / "vectors.pkl", "rb") as _vf:
313
+ import pickle as _pickle
314
+ vectors = _pickle.load(_vf)
315
+ code_root = Path(__file__).resolve().parent.parent
316
+ manifest = package_release(
317
+ out, corpus, bm25, graph, vectors, source_meta, country, code_root,
318
+ normalization_report=norm_report,
319
+ extra_manifest=extra_manifest,
320
+ )
321
+ del corpus, bm25, graph, vectors
322
+ gc.collect()
323
  _log(f"packaged {out}")
324
  result = {
325
  "country": country["slug"],
 
330
  "counts": manifest["counts"],
331
  "normalization": norm_report,
332
  "vector_blocker": vector_blocker,
333
+ "neighbor_via": neighbor_via,
334
  "schema_version": manifest["schema_version"],
335
+ "skipped": False,
336
+ "incremental": extra_manifest["incremental"],
337
  }
338
  if upload:
339
  from .upload import upload_release
 
351
  slugs: list[str] | None = None,
352
  upload: bool = False,
353
  skip_done: bool = True,
354
+ mode: str = "auto",
355
+ force: bool = False,
356
+ skip_vectors: bool = False,
357
  ) -> list[dict[str, Any]]:
358
+ """Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
359
+
360
+ ``skip_done`` is kept for compatibility: it no longer skips a country whose
361
+ source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to
362
+ rebuild regardless of CID overlap.
363
+ """
 
 
364
  targets = slugs or [c["slug"] for c in indexable_countries()]
365
  if "malta" in targets:
366
  targets = ["malta"] + [s for s in targets if s != "malta"]
367
  results = []
368
+ rebuild_force = force or not skip_done
369
  for slug in targets:
370
+ try:
371
+ results.append(
372
+ build_country(
373
+ slug,
374
+ upload=upload,
375
+ mode=mode,
376
+ force=rebuild_force,
377
+ skip_vectors=skip_vectors,
378
+ )
379
+ )
380
+ except Exception as exc:
381
+ _log(f"FAILED {slug}: {exc}")
382
+ record_progress(
383
+ {
384
+ "event": "failed",
385
+ "country": slug,
386
+ "error": str(exc),
387
+ "traceback": traceback.format_exc(),
388
+ }
389
+ )
390
  continue
391
+ return results
392
+
393
+
394
+ def reindex_from_gaps(
395
+ *,
396
+ upload: bool = False,
397
+ slugs: list[str] | None = None,
398
+ limit: int | None = None,
399
+ max_corpus_rows: int | None = 20_000,
400
+ skip_vectors: bool = False,
401
+ workers: int = 4,
402
+ mode: str = "auto",
403
+ ) -> list[dict[str, Any]]:
404
+ """Scan Hub gaps and incrementally rebuild stale/missing country IR.
405
+
406
+ Default cap skips huge corpora (Finland, Dominican Republic). Pass
407
+ ``max_corpus_rows=None`` to include them.
408
+ """
409
+ from .coverage import gap_report
410
+
411
+ if slugs is None:
412
+ report = gap_report(workers=workers)
413
+ rows = [c for c in report["countries"] if c.get("rebuild")]
414
+ rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
415
+ if max_corpus_rows is not None:
416
+ rows = [
417
+ r
418
+ for r in rows
419
+ if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows)
420
+ ]
421
+ if limit is not None:
422
+ rows = rows[: int(limit)]
423
+ slugs = [str(r["slug"]) for r in rows]
424
+ _log(
425
+ f"reindex targets n={len(slugs)} "
426
+ f"(from scan rebuild={len(report.get('rebuild') or [])})"
427
+ )
428
+ results: list[dict[str, Any]] = []
429
+ for slug in slugs:
430
+ _log(f"reindex start {slug}")
431
  try:
432
+ results.append(
433
+ build_country(
434
+ slug,
435
+ upload=upload,
436
+ mode=mode,
437
+ skip_vectors=skip_vectors,
438
+ fetch_hub_prior_ir=True,
439
+ )
440
+ )
441
  except Exception as exc:
442
  _log(f"FAILED {slug}: {exc}")
443
  record_progress(
 
448
  "traceback": traceback.format_exc(),
449
  }
450
  )
451
+ results.append({"country": slug, "skipped": False, "error": str(exc)})
452
  continue
453
  return results
country_laws_ir/__init__.py CHANGED
@@ -1,6 +1,6 @@
1
  """Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
2
 
3
- __version__ = "0.3.0"
4
  # Layout matches SkillCenter HF release / publicus-ir family; schema string is domain-specific.
5
  SCHEMA_VERSION = "country-laws-ir-graphrag/v1"
6
  LAYOUT_FAMILY = "skillcenter-huggingface-release/v3"
 
1
  """Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
2
 
3
+ __version__ = "0.5.0"
4
  # Layout matches SkillCenter HF release / publicus-ir family; schema string is domain-specific.
5
  SCHEMA_VERSION = "country-laws-ir-graphrag/v1"
6
  LAYOUT_FAMILY = "skillcenter-huggingface-release/v3"
country_laws_ir/__main__.py CHANGED
@@ -1,4 +1,4 @@
1
- """python -m country_laws_ir {build,query,batch,catalog}"""
2
 
3
  from __future__ import annotations
4
 
@@ -14,17 +14,25 @@ def main(argv: list[str] | None = None) -> int:
14
 
15
  p_build = sub.add_parser("build")
16
  p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
17
- help="Hub dataset id (endomorphosis/ipfs_<slug>_laws) or country slug")
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")
 
 
 
 
 
23
 
24
  p_batch = sub.add_parser("batch")
25
  p_batch.add_argument("--slugs", nargs="*", default=None)
26
  p_batch.add_argument("--upload", action="store_true")
27
- p_batch.add_argument("--no-skip-done", action="store_true")
 
 
 
28
 
29
  p_q = sub.add_parser("query")
30
  p_q.add_argument("--local-dir", required=True)
@@ -34,7 +42,38 @@ def main(argv: list[str] | None = None) -> int:
34
  p_norm.add_argument("--source-repo", "--source", dest="source", default="malta")
35
  p_norm.add_argument("--out", default=None, help="Optional JSON report path")
36
 
37
- sub.add_parser("catalog")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  args = ap.parse_args(argv)
40
  if args.cmd == "build":
@@ -47,6 +86,9 @@ def main(argv: list[str] | None = None) -> int:
47
  device=args.device,
48
  neighbor_k=args.neighbor_k,
49
  skip_vectors=args.skip_vectors,
 
 
 
50
  )
51
  print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str))
52
  print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str))
@@ -54,8 +96,17 @@ def main(argv: list[str] | None = None) -> int:
54
  if args.cmd == "batch":
55
  from .build import batch
56
 
57
- results = batch(slugs=args.slugs, upload=args.upload, skip_done=not args.no_skip_done)
58
- print(json.dumps([{"country": r["country"], "out": r["out"]} for r in results], indent=2))
 
 
 
 
 
 
 
 
 
59
  return 0
60
  if args.cmd == "query":
61
  from .query import main as qmain
@@ -63,12 +114,13 @@ def main(argv: list[str] | None = None) -> int:
63
  argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"]
64
  return qmain(argv2)
65
  if args.cmd == "normalize":
66
- from .build import CACHE, REPORTS, ROOT
67
  from .catalog import get_country
68
  from .normalize import build_corpus, load_source
69
 
70
  country = get_country(args.source)
71
- laws, articles, source_meta = load_source(country["repo"], CACHE)
 
72
  corpus, report = build_corpus(laws, articles, source_meta)
73
  out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
74
  out.parent.mkdir(parents=True, exist_ok=True)
@@ -76,9 +128,69 @@ def main(argv: list[str] | None = None) -> int:
76
  print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2))
77
  return 0
78
  if args.cmd == "catalog":
79
- from .catalog import COUNTRIES, indexable_countries
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- print(json.dumps({"n": len(COUNTRIES), "indexable": len(indexable_countries()), "countries": COUNTRIES}, indent=2))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  return 0
83
  return 1
84
 
 
1
+ """python -m country_laws_ir {build,query,batch,catalog,normalize,package-raw}"""
2
 
3
  from __future__ import annotations
4
 
 
14
 
15
  p_build = sub.add_parser("build")
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",
23
+ help="Publish the packaged release to justicedao/ipfs_<slug>_laws_ir (requires HF_TOKEN)")
24
+ p_build.add_argument("--mode", default="auto", choices=["auto", "full", "delta"],
25
+ help="auto skips unchanged Hub revisions and reuses embeddings by entry_cid")
26
+ p_build.add_argument("--force", action="store_true", help="Ignore source fingerprint skip and reuse caches")
27
+ p_build.add_argument("--prior-dir", default=None, help="Prior GraphRAG release to delta against")
28
 
29
  p_batch = sub.add_parser("batch")
30
  p_batch.add_argument("--slugs", nargs="*", default=None)
31
  p_batch.add_argument("--upload", action="store_true")
32
+ p_batch.add_argument("--no-skip-done", action="store_true",
33
+ help="Force a full rebuild of every country (ignore unchanged fingerprints)")
34
+ p_batch.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
35
+ p_batch.add_argument("--skip-vectors", action="store_true")
36
 
37
  p_q = sub.add_parser("query")
38
  p_q.add_argument("--local-dir", required=True)
 
42
  p_norm.add_argument("--source-repo", "--source", dest="source", default="malta")
43
  p_norm.add_argument("--out", default=None, help="Optional JSON report path")
44
 
45
+ p_cat = sub.add_parser("catalog")
46
+ p_cat.add_argument("--refresh", action="store_true",
47
+ help="List public endomorphosis/ipfs_*_laws datasets and persist new slugs")
48
+
49
+ p_cov = sub.add_parser("coverage", help="Compare endomorphosis sources vs justicedao GraphRAG releases")
50
+ p_cov.add_argument("--gaps", action="store_true",
51
+ help="Scan Hub for missing, stale, and incomplete IR (downloads manifests)")
52
+ p_cov.add_argument("--workers", type=int, default=8)
53
+
54
+ p_re = sub.add_parser(
55
+ "reindex",
56
+ help="Scan endomorphosis vs justicedao and incrementally rebuild stale/missing IR",
57
+ )
58
+ p_re.add_argument("--upload", action="store_true",
59
+ help="Publish rebuilt packs to justicedao (requires HF_TOKEN)")
60
+ p_re.add_argument("--slugs", nargs="*", default=None)
61
+ p_re.add_argument("--limit", type=int, default=None)
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")
70
+ p_raw.add_argument("--instruments-dir", default=None,
71
+ help="Collector JSON directory (default: $LEGAL_CORPORA_ROOT/<iso-or-slug>/instruments)")
72
+ p_raw.add_argument("--iso", default=None, help="Collector ISO directory name if different from slug")
73
+ p_raw.add_argument("--out", default=None, help="Local pack directory (laws.parquet + pack_meta.json)")
74
+ p_raw.add_argument("--source-dataset", default=None,
75
+ help="Raw Hub id (default endomorphosis/ipfs_<slug>_laws)")
76
+ p_raw.add_argument("--prior-pack", default=None, help="Existing parquet pack to merge into")
77
 
78
  args = ap.parse_args(argv)
79
  if args.cmd == "build":
 
86
  device=args.device,
87
  neighbor_k=args.neighbor_k,
88
  skip_vectors=args.skip_vectors,
89
+ mode=args.mode,
90
+ force=args.force,
91
+ prior_dir=Path(args.prior_dir) if args.prior_dir else None,
92
  )
93
  print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str))
94
  print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str))
 
96
  if args.cmd == "batch":
97
  from .build import batch
98
 
99
+ results = batch(
100
+ slugs=args.slugs,
101
+ upload=args.upload,
102
+ skip_done=not args.no_skip_done,
103
+ mode=args.mode,
104
+ skip_vectors=args.skip_vectors,
105
+ )
106
+ print(json.dumps(
107
+ [{"country": r["country"], "out": r["out"], "skipped": r.get("skipped", False)} for r in results],
108
+ indent=2,
109
+ ))
110
  return 0
111
  if args.cmd == "query":
112
  from .query import main as qmain
 
114
  argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"]
115
  return qmain(argv2)
116
  if args.cmd == "normalize":
117
+ from .build import CACHE, REPORTS
118
  from .catalog import get_country
119
  from .normalize import build_corpus, load_source
120
 
121
  country = get_country(args.source)
122
+ local = country.get("local_source_dir")
123
+ laws, articles, source_meta = load_source(local or country["repo"], CACHE)
124
  corpus, report = build_corpus(laws, articles, source_meta)
125
  out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
126
  out.parent.mkdir(parents=True, exist_ok=True)
 
128
  print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2))
129
  return 0
130
  if args.cmd == "catalog":
131
+ from .catalog import all_countries, refresh_from_hub
132
+
133
+ countries = refresh_from_hub() if args.refresh else all_countries()
134
+ print(json.dumps(
135
+ {"n": len(countries), "indexable": len([c for c in countries if c.get("indexable")]), "countries": countries},
136
+ indent=2,
137
+ ))
138
+ return 0
139
+ if args.cmd == "coverage":
140
+ from .coverage import coverage_report, gap_report
141
+
142
+ report = gap_report(workers=args.workers) if args.gaps else coverage_report()
143
+ print(json.dumps(report, indent=2, default=str))
144
+ return 0
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,
152
+ limit=args.limit,
153
+ max_corpus_rows=cap,
154
+ skip_vectors=args.skip_vectors,
155
+ workers=args.workers,
156
+ mode=args.mode,
157
+ )
158
+ print(json.dumps(
159
+ [
160
+ {
161
+ "country": r.get("country"),
162
+ "skipped": r.get("skipped", False),
163
+ "out": r.get("out"),
164
+ "hub": (r.get("hub") or {}).get("url") if isinstance(r.get("hub"), dict) else r.get("hub"),
165
+ "error": r.get("error"),
166
+ "kind": (r.get("incremental") or {}).get("kind"),
167
+ "n_added": ((r.get("incremental") or {}).get("delta") or {}).get("n_added"),
168
+ "n_unchanged": ((r.get("incremental") or {}).get("delta") or {}).get("n_unchanged"),
169
+ }
170
+ for r in results
171
+ ],
172
+ indent=2,
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
179
+
180
+ instruments = (
181
+ Path(args.instruments_dir)
182
+ if args.instruments_dir
183
+ else default_instruments_dir(args.iso or args.slug)
184
+ )
185
+ out = Path(args.out) if args.out else RELEASES / "raw-packs" / args.slug
186
+ meta = package_instruments(
187
+ instruments_dir=instruments,
188
+ out=out,
189
+ slug=args.slug,
190
+ source_dataset=args.source_dataset,
191
+ prior_pack=Path(args.prior_pack) if args.prior_pack else None,
192
+ )
193
+ print(json.dumps(meta, indent=2, default=str))
194
  return 0
195
  return 1
196
 
country_laws_ir/auth.py CHANGED
@@ -1,16 +1,38 @@
1
- """Public Hugging Face reads only. This pipeline never loads, stores, or uses a token."""
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
5
  import os
 
6
 
7
 
8
  def configure_hf() -> None:
9
- """Force anonymous public Hub access. Tokens are ignored, never printed, never stored."""
10
- os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
11
- # Do not read HF_TOKEN / HUGGING_FACE_HUB_TOKEN. Public datasets need no auth.
12
 
13
 
14
  def public_token() -> bool:
15
  """huggingface_hub `token=False` means anonymous (do not pick up env tokens)."""
16
  return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face auth helpers.
2
+
3
+ Default reads stay anonymous. Gap scans and JusticeDAO uploads may use the
4
+ operator token from the Hugging Face cache file or the environment. The token
5
+ is never logged.
6
+ """
7
 
8
  from __future__ import annotations
9
 
10
  import os
11
+ from pathlib import Path
12
 
13
 
14
  def configure_hf() -> None:
15
+ """Do not implicitly pick up ambient tokens for anonymous public reads."""
16
+ os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
 
17
 
18
 
19
  def public_token() -> bool:
20
  """huggingface_hub `token=False` means anonymous (do not pick up env tokens)."""
21
  return False
22
+
23
+
24
+ def operator_token() -> str | bool:
25
+ """Return a token for authenticated Hub reads/writes, or False if none."""
26
+ for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
27
+ value = (os.environ.get(key) or "").strip()
28
+ if value:
29
+ return value
30
+ path = Path.home() / ".cache" / "huggingface" / "token"
31
+ if path.is_file():
32
+ try:
33
+ value = path.read_text(encoding="utf-8").strip()
34
+ except OSError:
35
+ return False
36
+ if value:
37
+ return value
38
+ return False
country_laws_ir/build.py CHANGED
@@ -1,22 +1,59 @@
1
- """End-to-end build: normalize → BM25 → graph → vectors → package (no upload by default)."""
 
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
 
 
5
  import json
 
 
6
  import traceback
7
  from datetime import datetime, timezone
8
  from pathlib import Path
9
  from typing import Any
10
 
11
  from .bm25 import bm25_neighbors, build_index
 
 
 
 
 
 
 
 
 
 
 
12
  from .catalog import get_country, indexable_countries, target_repo
13
  from .graph import build_graph
 
 
 
 
 
 
 
 
 
14
  from .normalize import build_corpus, load_source
15
- from .package import package_release
16
  from .auth import configure_hf
17
- from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors
 
 
 
 
 
 
 
 
18
 
19
- ROOT = Path("/workspace/country-laws-ir")
20
  CACHE = ROOT / "cache"
21
  RELEASES = ROOT / "releases"
22
  REPORTS = ROOT / "reports"
@@ -35,6 +72,95 @@ def record_progress(event: dict[str, Any]) -> None:
35
  f.write(json.dumps(event, ensure_ascii=False) + "\n")
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def build_country(
39
  source: str,
40
  out: Path | None = None,
@@ -42,6 +168,10 @@ def build_country(
42
  device: str = "cpu",
43
  neighbor_k: int = 8,
44
  skip_vectors: bool = False,
 
 
 
 
45
  ) -> dict[str, Any]:
46
  country = get_country(source)
47
  if not country.get("indexable", True):
@@ -57,7 +187,9 @@ def build_country(
57
  )
58
  else None
59
  )
60
- _log(f"build start {repo} -> {out} (upload={upload}) local={local_dir}")
 
 
61
  configure_hf()
62
  CACHE.mkdir(parents=True, exist_ok=True)
63
  REPORTS.mkdir(parents=True, exist_ok=True)
@@ -66,6 +198,35 @@ def build_country(
66
  f"source loaded laws={source_meta['n_laws_source']} "
67
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
68
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  corpus, norm_report = build_corpus(laws, articles, source_meta)
70
  report_path = REPORTS / f"{country['slug']}_normalization.json"
71
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
@@ -79,46 +240,86 @@ def build_country(
79
  if corpus.empty:
80
  raise RuntimeError("Normalized corpus is empty; refusing to package")
81
 
82
- bm25 = build_index(corpus)
83
- _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
84
- _log(f"bm25 neighbors start n={len(corpus)} k={neighbor_k}")
85
- neighbors = bm25_neighbors(bm25, k=neighbor_k)
86
- _log("bm25 neighbors done")
87
- graph = build_graph(corpus, neighbors)
88
- _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
89
 
90
- vector_blocker = None
91
- if skip_vectors:
92
- vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
93
- vector_blocker = "skip_vectors"
94
- elif embeddings_available():
95
- try:
96
- ckpt = CACHE / "embeddings" / f"{country['slug']}.npy"
97
- _log(f"vectors encode start n={len(corpus)} checkpoint={ckpt}")
98
- embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt))
99
- vectors = layout_vectors(corpus, embeddings)
100
- _log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
101
- except Exception as exc:
102
- vector_blocker = f"embedding_failed: {exc}"
103
- _log(f"vector embedding failed; writing stub ({exc})")
104
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
105
- else:
106
- vector_blocker = "sentence-transformers/torch unavailable"
107
- _log(f"vectors stub: {vector_blocker}")
108
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
109
 
110
- code_root = Path(__file__).resolve().parent.parent
111
- manifest = package_release(
112
- out,
113
- corpus,
114
- bm25,
115
- graph,
116
- vectors,
117
- source_meta,
118
- country,
119
- code_root,
120
- normalization_report=norm_report,
121
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  _log(f"packaged {out}")
123
  result = {
124
  "country": country["slug"],
@@ -129,7 +330,10 @@ def build_country(
129
  "counts": manifest["counts"],
130
  "normalization": norm_report,
131
  "vector_blocker": vector_blocker,
 
132
  "schema_version": manifest["schema_version"],
 
 
133
  }
134
  if upload:
135
  from .upload import upload_release
@@ -147,25 +351,93 @@ def batch(
147
  slugs: list[str] | None = None,
148
  upload: bool = False,
149
  skip_done: bool = True,
 
 
 
150
  ) -> list[dict[str, Any]]:
151
- done = set()
152
- if skip_done and PROGRESS.exists():
153
- for line in PROGRESS.read_text(encoding="utf-8").splitlines():
154
- if not line.strip():
155
- continue
156
- rec = json.loads(line)
157
- if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
158
- done.add(rec["country"])
159
  targets = slugs or [c["slug"] for c in indexable_countries()]
160
  if "malta" in targets:
161
  targets = ["malta"] + [s for s in targets if s != "malta"]
162
  results = []
 
163
  for slug in targets:
164
- if skip_done and slug in done:
165
- _log(f"skip already done {slug}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  try:
168
- results.append(build_country(slug, upload=upload))
 
 
 
 
 
 
 
 
169
  except Exception as exc:
170
  _log(f"FAILED {slug}: {exc}")
171
  record_progress(
@@ -176,5 +448,6 @@ def batch(
176
  "traceback": traceback.format_exc(),
177
  }
178
  )
 
179
  continue
180
  return results
 
1
+ """End-to-end build: normalize → incremental vectors → BM25 → graph → package.
2
+
3
+ Default mode is ``auto``: skip when the endomorphosis source revision is
4
+ unchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuild
5
+ BM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-in
6
+ via ``upload=True``.
7
+ """
8
 
9
  from __future__ import annotations
10
 
11
+ import os
12
+
13
  import json
14
+
15
+ import pandas as pd
16
  import traceback
17
  from datetime import datetime, timezone
18
  from pathlib import Path
19
  from typing import Any
20
 
21
  from .bm25 import bm25_neighbors, build_index
22
+ from .mem import MemAbort, checkpoint, log_mem
23
+ from .spill import (
24
+ SQLITE_THRESHOLD,
25
+ build_bm25_tf_spill,
26
+ build_graph_from_neighbor_shards,
27
+ neighbors_via_sqlite,
28
+ should_use_sqlite,
29
+ spill_dir_for,
30
+ spill_pickle,
31
+ )
32
+ from .package import package_from_spill, package_release
33
  from .catalog import get_country, indexable_countries, target_repo
34
  from .graph import build_graph
35
+ from .incremental import (
36
+ fetch_hub_prior,
37
+ load_embedding_cache,
38
+ load_prior_release,
39
+ load_release_vectors_by_cid,
40
+ merge_embedding_maps,
41
+ plan_rebuild,
42
+ save_embedding_cache,
43
+ )
44
  from .normalize import build_corpus, load_source
 
45
  from .auth import configure_hf
46
+ from .vectors import (
47
+ DIMENSION,
48
+ MODEL_NAME,
49
+ assemble_embeddings,
50
+ embeddings_available,
51
+ embeddings_by_cid,
52
+ layout_stub_vectors,
53
+ layout_vectors,
54
+ )
55
 
56
+ ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
57
  CACHE = ROOT / "cache"
58
  RELEASES = ROOT / "releases"
59
  REPORTS = ROOT / "reports"
 
72
  f.write(json.dumps(event, ensure_ascii=False) + "\n")
73
 
74
 
75
+ def _prior_dir_for(
76
+ slug: str,
77
+ out: Path,
78
+ prior_dir: Path | None,
79
+ *,
80
+ fetch_hub: bool = True,
81
+ ) -> Path | None:
82
+ if prior_dir is not None:
83
+ return Path(prior_dir)
84
+ if out.is_dir() and (out / "manifest.json").is_file():
85
+ return out
86
+ default = RELEASES / f"ipfs_{slug}_laws_ir"
87
+ if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve():
88
+ return default
89
+ if not fetch_hub:
90
+ return None
91
+ hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir")
92
+ if hub is not None:
93
+ _log(f"using justicedao prior {hub}")
94
+ return hub
95
+
96
+
97
+ def _encode_vectors(
98
+ *,
99
+ corpus: pd.DataFrame,
100
+ country_slug: str,
101
+ prior,
102
+ plan,
103
+ skip_vectors: bool,
104
+ device: str,
105
+ ) -> tuple[dict[str, Any], str | None, dict[str, Any]]:
106
+ import gc
107
+
108
+ vector_report: dict[str, Any] = {"status": "stub"}
109
+ vector_blocker = None
110
+ if skip_vectors:
111
+ vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
112
+ return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
113
+
114
+ cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet"
115
+ prior_by_cid = {}
116
+ if plan.reuse_embeddings:
117
+ prior_by_cid = merge_embedding_maps(
118
+ load_embedding_cache(cid_cache_path),
119
+ None if prior is None else load_release_vectors_by_cid(prior.directory),
120
+ )
121
+ _log(f"embedding cache reused_cids={len(prior_by_cid)}")
122
+ try:
123
+ positional = CACHE / "embeddings" / f"{country_slug}.npy"
124
+ embeddings, vector_report = assemble_embeddings(
125
+ corpus,
126
+ prior_by_cid,
127
+ encode_missing=embeddings_available(),
128
+ device=device,
129
+ checkpoint_path=str(positional),
130
+ )
131
+ if (
132
+ vector_report.get("status") in {"stub_missing_encoder", "incomplete"}
133
+ and not int(vector_report.get("n_reused") or 0)
134
+ ):
135
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
136
+ vectors = layout_stub_vectors(corpus, reason=str(vector_blocker))
137
+ return vectors, vector_blocker, vector_report
138
+ vectors = layout_vectors(corpus, embeddings)
139
+ if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused":
140
+ vectors["stats"]["status"] = "partial"
141
+ vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0)
142
+ vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0)
143
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
144
+ save_embedding_cache(
145
+ cid_cache_path,
146
+ merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)),
147
+ model_name=MODEL_NAME,
148
+ dimension=DIMENSION,
149
+ )
150
+ del embeddings
151
+ gc.collect()
152
+ _log(
153
+ f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} "
154
+ f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}"
155
+ )
156
+ return vectors, None, vector_report
157
+ except Exception as exc:
158
+ vector_blocker = f"embedding_failed: {exc}"
159
+ _log(f"vector embedding failed; writing stub ({exc})")
160
+ vectors = layout_stub_vectors(corpus, reason=vector_blocker)
161
+ return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
162
+
163
+
164
  def build_country(
165
  source: str,
166
  out: Path | None = None,
 
168
  device: str = "cpu",
169
  neighbor_k: int = 8,
170
  skip_vectors: bool = False,
171
+ mode: str = "auto",
172
+ force: bool = False,
173
+ prior_dir: Path | None = None,
174
+ fetch_hub_prior_ir: bool = True,
175
  ) -> dict[str, Any]:
176
  country = get_country(source)
177
  if not country.get("indexable", True):
 
187
  )
188
  else None
189
  )
190
+ _log(
191
+ f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
192
+ )
193
  configure_hf()
194
  CACHE.mkdir(parents=True, exist_ok=True)
195
  REPORTS.mkdir(parents=True, exist_ok=True)
 
198
  f"source loaded laws={source_meta['n_laws_source']} "
199
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
200
  )
201
+ prior = load_prior_release(
202
+ _prior_dir_for(
203
+ country["slug"],
204
+ out,
205
+ prior_dir,
206
+ fetch_hub=fetch_hub_prior_ir,
207
+ )
208
+ )
209
+ plan = plan_rebuild(
210
+ mode=mode, source_meta=source_meta, prior=prior, force=force
211
+ )
212
+ if plan.skip_build:
213
+ _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
214
+ result = {
215
+ "country": country["slug"],
216
+ "source": repo,
217
+ "source_revision": source_meta["source_revision"],
218
+ "out": str(out),
219
+ "target_hub_id": target_repo(country["slug"]),
220
+ "skipped": True,
221
+ "incremental": plan.to_dict(),
222
+ "normalization": {"n_out": plan.delta.current_count if plan.delta else 0},
223
+ "vector_blocker": None,
224
+ "neighbor_via": None,
225
+ "schema_version": "country-laws-ir-graphrag/v1",
226
+ }
227
+ record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
228
+ return result
229
+
230
  corpus, norm_report = build_corpus(laws, articles, source_meta)
231
  report_path = REPORTS / f"{country['slug']}_normalization.json"
232
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
 
240
  if corpus.empty:
241
  raise RuntimeError("Normalized corpus is empty; refusing to package")
242
 
243
+ import gc
 
 
 
 
 
 
244
 
245
+ plan = plan_rebuild(
246
+ mode=mode,
247
+ source_meta=source_meta,
248
+ prior=prior,
249
+ current_corpus=corpus,
250
+ force=force,
251
+ )
252
+ _log(
253
+ f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
254
+ f"added={0 if plan.delta is None else plan.delta.n_added} "
255
+ f"removed={0 if plan.delta is None else plan.delta.n_removed}"
256
+ )
257
+
258
+ n_docs = len(corpus)
259
+ spill = spill_dir_for(country["slug"], CACHE)
260
+ spill.mkdir(parents=True, exist_ok=True)
261
+ corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet"
262
+ corpus.to_parquet(corpus_ckpt, index=False)
263
+ checkpoint("after_normalize", log=_log)
264
 
265
+ vectors, vector_blocker, vector_report = _encode_vectors(
266
+ corpus=corpus,
267
+ country_slug=country["slug"],
268
+ prior=prior,
269
+ plan=plan,
270
+ skip_vectors=skip_vectors,
271
+ device=device,
 
 
 
 
272
  )
273
+ spill_pickle(spill / "vectors.pkl", vectors)
274
+ del vectors
275
+ gc.collect()
276
+ checkpoint("vectors_spilled", log=_log)
277
+ extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
278
+
279
+ use_sqlite = should_use_sqlite(n_docs)
280
+ neighbor_via = "stock"
281
+ if use_sqlite:
282
+ _log(f"sqlite neighbors path n={n_docs} (>= {SQLITE_THRESHOLD}) spill={spill}")
283
+ # Free corpus body for neighbor stream — reload later for graph
284
+ del corpus
285
+ gc.collect()
286
+ neighbors_via_sqlite(corpus_ckpt, spill, n_docs, k=neighbor_k, log=_log)
287
+ neighbor_via = "sqlite_fts"
288
+ bm25_info = build_bm25_tf_spill(corpus_ckpt, spill, n_docs, log=_log)
289
+ corpus = pd.read_parquet(corpus_ckpt)
290
+ graph = build_graph_from_neighbor_shards(corpus, spill, log=_log)
291
+ spill_pickle(spill / "graph.pkl", graph)
292
+ del graph, corpus
293
+ gc.collect()
294
+ checkpoint("graph_spilled", log=_log)
295
+ code_root = Path(__file__).resolve().parent.parent
296
+ manifest = package_from_spill(
297
+ out, spill, corpus_ckpt, source_meta, country, code_root,
298
+ normalization_report=norm_report, expected_rows=n_docs,
299
+ extra_manifest=extra_manifest,
300
+ )
301
+ _log(f"packaged sequential via={neighbor_via} {out}")
302
+ else:
303
+ bm25 = build_index(corpus)
304
+ _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
305
+ _log(f"bm25 neighbors start n={n_docs} k={neighbor_k}")
306
+ neighbors = bm25_neighbors(bm25, k=neighbor_k)
307
+ _log("bm25 neighbors done")
308
+ graph = build_graph(corpus, neighbors)
309
+ del neighbors
310
+ gc.collect()
311
+ _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
312
+ with open(spill / "vectors.pkl", "rb") as _vf:
313
+ import pickle as _pickle
314
+ vectors = _pickle.load(_vf)
315
+ code_root = Path(__file__).resolve().parent.parent
316
+ manifest = package_release(
317
+ out, corpus, bm25, graph, vectors, source_meta, country, code_root,
318
+ normalization_report=norm_report,
319
+ extra_manifest=extra_manifest,
320
+ )
321
+ del corpus, bm25, graph, vectors
322
+ gc.collect()
323
  _log(f"packaged {out}")
324
  result = {
325
  "country": country["slug"],
 
330
  "counts": manifest["counts"],
331
  "normalization": norm_report,
332
  "vector_blocker": vector_blocker,
333
+ "neighbor_via": neighbor_via,
334
  "schema_version": manifest["schema_version"],
335
+ "skipped": False,
336
+ "incremental": extra_manifest["incremental"],
337
  }
338
  if upload:
339
  from .upload import upload_release
 
351
  slugs: list[str] | None = None,
352
  upload: bool = False,
353
  skip_done: bool = True,
354
+ mode: str = "auto",
355
+ force: bool = False,
356
+ skip_vectors: bool = False,
357
  ) -> list[dict[str, Any]]:
358
+ """Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
359
+
360
+ ``skip_done`` is kept for compatibility: it no longer skips a country whose
361
+ source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to
362
+ rebuild regardless of CID overlap.
363
+ """
 
 
364
  targets = slugs or [c["slug"] for c in indexable_countries()]
365
  if "malta" in targets:
366
  targets = ["malta"] + [s for s in targets if s != "malta"]
367
  results = []
368
+ rebuild_force = force or not skip_done
369
  for slug in targets:
370
+ try:
371
+ results.append(
372
+ build_country(
373
+ slug,
374
+ upload=upload,
375
+ mode=mode,
376
+ force=rebuild_force,
377
+ skip_vectors=skip_vectors,
378
+ )
379
+ )
380
+ except Exception as exc:
381
+ _log(f"FAILED {slug}: {exc}")
382
+ record_progress(
383
+ {
384
+ "event": "failed",
385
+ "country": slug,
386
+ "error": str(exc),
387
+ "traceback": traceback.format_exc(),
388
+ }
389
+ )
390
  continue
391
+ return results
392
+
393
+
394
+ def reindex_from_gaps(
395
+ *,
396
+ upload: bool = False,
397
+ slugs: list[str] | None = None,
398
+ limit: int | None = None,
399
+ max_corpus_rows: int | None = 20_000,
400
+ skip_vectors: bool = False,
401
+ workers: int = 4,
402
+ mode: str = "auto",
403
+ ) -> list[dict[str, Any]]:
404
+ """Scan Hub gaps and incrementally rebuild stale/missing country IR.
405
+
406
+ Default cap skips huge corpora (Finland, Dominican Republic). Pass
407
+ ``max_corpus_rows=None`` to include them.
408
+ """
409
+ from .coverage import gap_report
410
+
411
+ if slugs is None:
412
+ report = gap_report(workers=workers)
413
+ rows = [c for c in report["countries"] if c.get("rebuild")]
414
+ rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
415
+ if max_corpus_rows is not None:
416
+ rows = [
417
+ r
418
+ for r in rows
419
+ if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows)
420
+ ]
421
+ if limit is not None:
422
+ rows = rows[: int(limit)]
423
+ slugs = [str(r["slug"]) for r in rows]
424
+ _log(
425
+ f"reindex targets n={len(slugs)} "
426
+ f"(from scan rebuild={len(report.get('rebuild') or [])})"
427
+ )
428
+ results: list[dict[str, Any]] = []
429
+ for slug in slugs:
430
+ _log(f"reindex start {slug}")
431
  try:
432
+ results.append(
433
+ build_country(
434
+ slug,
435
+ upload=upload,
436
+ mode=mode,
437
+ skip_vectors=skip_vectors,
438
+ fetch_hub_prior_ir=True,
439
+ )
440
+ )
441
  except Exception as exc:
442
  _log(f"FAILED {slug}: {exc}")
443
  record_progress(
 
448
  "traceback": traceback.format_exc(),
449
  }
450
  )
451
+ results.append({"country": slug, "skipped": False, "error": str(exc)})
452
  continue
453
  return results
country_laws_ir/catalog.py CHANGED
@@ -2,15 +2,39 @@
2
 
3
  Belgium, Portugal, and Lithuania are incomplete Wayback harvests and are
4
  excluded from indexing. american_municipal_law is out of scope.
 
 
 
 
5
  """
6
 
7
  from __future__ import annotations
8
 
 
 
 
9
  from typing import Any
10
 
11
- EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania"}
12
  EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS}
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`.
15
  COUNTRIES: list[dict[str, Any]] = [
16
  {"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True},
@@ -88,6 +112,54 @@ COUNTRIES: list[dict[str, Any]] = [
88
  ]
89
 
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  def get_country(source: str) -> dict[str, Any]:
92
  source = source.strip()
93
  # Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json)
@@ -133,7 +205,7 @@ def get_country(source: str) -> dict[str, Any]:
133
  if "/" in source:
134
  slug = source.rsplit("/", 1)[-1]
135
  slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir")
136
- for row in COUNTRIES:
137
  if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source):
138
  return dict(row)
139
  if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"):
@@ -143,20 +215,20 @@ def get_country(source: str) -> dict[str, Any]:
143
  "repo": source,
144
  "name": inferred.replace("_", " ").title(),
145
  "indexable": inferred not in EXCLUDED_SLUGS,
146
- "skip_reason": "incomplete Wayback harvest" if inferred in EXCLUDED_SLUGS else None,
147
  }
148
  raise KeyError(f"Unknown country-law source: {source}")
149
 
150
 
151
  def indexable_countries() -> list[dict[str, Any]]:
152
- return [c for c in COUNTRIES if c.get("indexable")]
153
 
154
 
155
  def target_repo(slug: str) -> str:
156
  return f"justicedao/ipfs_{slug}_laws_ir"
157
 
158
 
159
- def refresh_from_hub() -> list[dict[str, Any]]:
160
  """Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets."""
161
  from huggingface_hub import HfApi
162
 
@@ -175,9 +247,10 @@ def refresh_from_hub() -> list[dict[str, Any]]:
175
  "repo": ds_id,
176
  "name": slug.replace("_", " ").title(),
177
  "indexable": slug not in EXCLUDED_SLUGS,
178
- "skip_reason": (
179
- "incomplete Wayback harvest" if slug in EXCLUDED_SLUGS else None
180
- ),
181
  })
182
  found.sort(key=lambda r: r["slug"])
183
- return found
 
 
 
 
2
 
3
  Belgium, Portugal, and Lithuania are incomplete Wayback harvests and are
4
  excluded from indexing. american_municipal_law is out of scope.
5
+
6
+ The static ``COUNTRIES`` list is the fail-closed baseline. ``refresh_from_hub``
7
+ persists a sidecar cache of newly listed Hub datasets so incremental scrapes
8
+ of additional jurisdictions are indexable without a code change.
9
  """
10
 
11
  from __future__ import annotations
12
 
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
  from typing import Any
17
 
18
+ EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania", "ghana"}
19
  EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS}
20
 
21
+ _SKIP_REASONS = {
22
+ "belgium": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)",
23
+ "portugal": "incomplete Wayback harvest (Diário da República archive shard)",
24
+ "lithuania": "incomplete Wayback harvest (e-TAR archive shard)",
25
+ "ghana": "thin scrape; Act PDF path blocked by robots",
26
+ }
27
+
28
+
29
+ def catalog_cache_path() -> Path:
30
+ root = Path(
31
+ os.environ.get(
32
+ "COUNTRY_LAWS_IR_ROOT",
33
+ str(Path.home() / ".ipfs_datasets" / "country-laws-ir"),
34
+ )
35
+ )
36
+ return root / "catalog_cache.json"
37
+
38
  # Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`.
39
  COUNTRIES: list[dict[str, Any]] = [
40
  {"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True},
 
112
  ]
113
 
114
 
115
+ def load_cached_countries() -> list[dict[str, Any]]:
116
+ path = catalog_cache_path()
117
+ if not path.is_file():
118
+ return []
119
+ try:
120
+ payload = json.loads(path.read_text(encoding="utf-8"))
121
+ except Exception:
122
+ return []
123
+ rows = payload.get("countries") if isinstance(payload, dict) else payload
124
+ if not isinstance(rows, list):
125
+ return []
126
+ out: list[dict[str, Any]] = []
127
+ for row in rows:
128
+ if isinstance(row, dict) and row.get("slug") and row.get("repo"):
129
+ out.append(dict(row))
130
+ return out
131
+
132
+
133
+ def persist_catalog(countries: list[dict[str, Any]], path: Path | None = None) -> Path:
134
+ dest = path or catalog_cache_path()
135
+ dest.parent.mkdir(parents=True, exist_ok=True)
136
+ payload = {
137
+ "n": len(countries),
138
+ "indexable": sum(1 for c in countries if c.get("indexable")),
139
+ "countries": countries,
140
+ }
141
+ dest.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
142
+ return dest
143
+
144
+
145
+ def merge_country_rows(
146
+ baseline: list[dict[str, Any]],
147
+ extra: list[dict[str, Any]],
148
+ ) -> list[dict[str, Any]]:
149
+ """Static catalog wins on slug; Hub extras fill gaps."""
150
+ by_slug = {str(row["slug"]): dict(row) for row in baseline if row.get("slug")}
151
+ for row in extra:
152
+ slug = str(row.get("slug") or "")
153
+ if not slug or slug in by_slug:
154
+ continue
155
+ by_slug[slug] = dict(row)
156
+ return [by_slug[k] for k in sorted(by_slug)]
157
+
158
+
159
+ def all_countries() -> list[dict[str, Any]]:
160
+ return merge_country_rows(COUNTRIES, load_cached_countries())
161
+
162
+
163
  def get_country(source: str) -> dict[str, Any]:
164
  source = source.strip()
165
  # Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json)
 
205
  if "/" in source:
206
  slug = source.rsplit("/", 1)[-1]
207
  slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir")
208
+ for row in all_countries():
209
  if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source):
210
  return dict(row)
211
  if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"):
 
215
  "repo": source,
216
  "name": inferred.replace("_", " ").title(),
217
  "indexable": inferred not in EXCLUDED_SLUGS,
218
+ "skip_reason": _SKIP_REASONS.get(inferred),
219
  }
220
  raise KeyError(f"Unknown country-law source: {source}")
221
 
222
 
223
  def indexable_countries() -> list[dict[str, Any]]:
224
+ return [c for c in all_countries() if c.get("indexable")]
225
 
226
 
227
  def target_repo(slug: str) -> str:
228
  return f"justicedao/ipfs_{slug}_laws_ir"
229
 
230
 
231
+ def refresh_from_hub(*, persist: bool = True) -> list[dict[str, Any]]:
232
  """Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets."""
233
  from huggingface_hub import HfApi
234
 
 
247
  "repo": ds_id,
248
  "name": slug.replace("_", " ").title(),
249
  "indexable": slug not in EXCLUDED_SLUGS,
250
+ "skip_reason": _SKIP_REASONS.get(slug),
 
 
251
  })
252
  found.sort(key=lambda r: r["slug"])
253
+ merged = merge_country_rows(COUNTRIES, found)
254
+ if persist:
255
+ persist_catalog(merged)
256
+ return merged
country_laws_ir/cidutil.py CHANGED
@@ -59,6 +59,27 @@ def cid_v1_raw_sha256(data: bytes) -> str:
59
  return "b" + _b32encode(cid_bytes)
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def cid_of_json(obj: Any) -> str:
63
  return cid_v1_raw_sha256(canonical_json_bytes(obj))
64
 
 
59
  return "b" + _b32encode(cid_bytes)
60
 
61
 
62
+ def sha256_key_to_cidv1(value: str) -> str:
63
+ """Turn a bare/prefixed SHA-256 routing key into ``bafkrei…`` CIDv1.
64
+
65
+ GraphRAG locators must not use hex digests as ``entry_cid`` / ``node_cid``.
66
+ """
67
+
68
+ text = str(value or "").strip()
69
+ if text.startswith("bafkrei"):
70
+ return text
71
+ hex_part = text[7:71] if text.lower().startswith("sha256:") else text[:64]
72
+ rest = text[71:] if text.lower().startswith("sha256:") else text[64:]
73
+ if len(hex_part) != 64:
74
+ return text
75
+ try:
76
+ digest = bytes.fromhex(hex_part)
77
+ except ValueError:
78
+ return text
79
+ cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest
80
+ return "b" + _b32encode(cid_bytes) + rest
81
+
82
+
83
  def cid_of_json(obj: Any) -> str:
84
  return cid_v1_raw_sha256(canonical_json_bytes(obj))
85
 
country_laws_ir/coverage.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare endomorphosis raw sources against justicedao GraphRAG releases.
2
+
3
+ Gap kinds
4
+ ---------
5
+ * missing — no JusticeDAO IR (and no local pack)
6
+ * unpublished — local IR exists, Hub IR does not
7
+ * stale — Hub/local IR source revision does not match current endomorphosis SHA
8
+ * incomplete — missing corpus/BM25/graph, empty corpus, or source has no laws
9
+ * stub_vectors — IR is otherwise current but embeddings were stubbed
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import time
16
+ from concurrent.futures import ThreadPoolExecutor, as_completed
17
+ from pathlib import Path
18
+ from typing import Any, Mapping
19
+
20
+ from .catalog import EXCLUDED_SLUGS, all_countries, target_repo
21
+
22
+ ALIAS_TO_CANONICAL = {
23
+ "dominican_republic": "dominicanrepublic",
24
+ "el_salvador": "elsalvador",
25
+ "north_korea": "northkorea",
26
+ "papua_new_guinea": "papuanewguinea",
27
+ "san_marino": "sanmarino",
28
+ "trinidad_and_tobago": "trinidad",
29
+ }
30
+
31
+
32
+ def _slug_from_source(dataset_id: str) -> str | None:
33
+ if not dataset_id.startswith("endomorphosis/ipfs_") or not dataset_id.endswith("_laws"):
34
+ return None
35
+ return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws")
36
+
37
+
38
+ def _slug_from_ir(dataset_id: str) -> str | None:
39
+ if not dataset_id.startswith("justicedao/ipfs_") or not dataset_id.endswith("_laws_ir"):
40
+ return None
41
+ return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws_ir")
42
+
43
+
44
+ def canonical_slug(slug: str) -> str:
45
+ return ALIAS_TO_CANONICAL.get(slug, slug)
46
+
47
+
48
+ def list_hub_slugs(*, author: str, kind: str) -> list[str]:
49
+ from huggingface_hub import HfApi
50
+
51
+ from .auth import configure_hf, operator_token, public_token
52
+
53
+ configure_hf()
54
+ token = operator_token() or public_token()
55
+ api = HfApi(token=token)
56
+ out: list[str] = []
57
+ for ds in api.list_datasets(author=author):
58
+ slug = _slug_from_source(ds.id) if kind == "source" else _slug_from_ir(ds.id)
59
+ if slug:
60
+ out.append(slug)
61
+ return sorted(set(out))
62
+
63
+
64
+ def local_release_slugs(releases_dir: Path) -> list[str]:
65
+ if not releases_dir.is_dir():
66
+ return []
67
+ found: list[str] = []
68
+ for path in sorted(releases_dir.glob("ipfs_*_laws_ir")):
69
+ if (path / "manifest.json").is_file():
70
+ slug = path.name.removeprefix("ipfs_").removesuffix("_laws_ir")
71
+ found.append(slug)
72
+ return found
73
+
74
+
75
+ IR_FAMILY_PREFIXES = (
76
+ ("data/corpus/", "ir_missing_corpus"),
77
+ ("data/bm25/", "ir_missing_bm25"),
78
+ ("data/graph/", "ir_missing_graph"),
79
+ )
80
+ STUB_VECTOR_STATUSES = {"stub", "stub_missing_encoder", "incomplete"}
81
+ TINY_LAWS_BYTES = 1024
82
+
83
+
84
+ def classify_gap(
85
+ *,
86
+ excluded: bool = False,
87
+ alias: bool = False,
88
+ source_has_laws: bool = True,
89
+ source_laws_bytes: int | None = None,
90
+ source_revision: str | None = None,
91
+ ir_files: list[str] | None = None,
92
+ ir_source_revision: str | None = None,
93
+ ir_corpus_rows: int | None = None,
94
+ vector_status: str | None = None,
95
+ local_only: bool = False,
96
+ local_source_revision: str | None = None,
97
+ ) -> dict[str, Any]:
98
+ """Pure classifier for missing / stale / incomplete country IR."""
99
+ issues: list[str] = []
100
+ if alias:
101
+ return {"status": "alias", "issues": issues, "rebuild": False, "publish": False}
102
+ if excluded:
103
+ return {"status": "excluded", "issues": issues, "rebuild": False, "publish": False}
104
+
105
+ if not source_has_laws:
106
+ issues.append("source_missing_laws")
107
+ if (
108
+ source_laws_bytes is not None
109
+ and source_laws_bytes >= 0
110
+ and source_laws_bytes < TINY_LAWS_BYTES
111
+ ):
112
+ issues.append("source_laws_tiny")
113
+
114
+ if ir_files is None:
115
+ issues.append("missing_ir")
116
+ else:
117
+ names = set(ir_files)
118
+ if "manifest.json" not in names:
119
+ issues.append("ir_missing_manifest")
120
+ for prefix, issue in IR_FAMILY_PREFIXES:
121
+ if not any(name.startswith(prefix) for name in names):
122
+ issues.append(issue)
123
+ if ir_corpus_rows is not None and int(ir_corpus_rows) <= 0:
124
+ issues.append("ir_empty_corpus")
125
+ if (
126
+ source_revision
127
+ and ir_source_revision
128
+ and str(source_revision) != str(ir_source_revision)
129
+ ):
130
+ issues.append("stale_source_revision")
131
+ if vector_status in STUB_VECTOR_STATUSES:
132
+ issues.append("ir_stub_vectors")
133
+
134
+ structural = {
135
+ "source_missing_laws",
136
+ "source_laws_tiny",
137
+ "ir_missing_manifest",
138
+ "ir_missing_corpus",
139
+ "ir_missing_bm25",
140
+ "ir_missing_graph",
141
+ "ir_empty_corpus",
142
+ }
143
+ issue_set = set(issues)
144
+ if "missing_ir" in issue_set:
145
+ status = "unpublished" if local_only else "missing"
146
+ elif "stale_source_revision" in issue_set:
147
+ status = "stale"
148
+ elif issue_set & structural:
149
+ status = "incomplete"
150
+ elif issue_set == {"ir_stub_vectors"}:
151
+ status = "stub_vectors"
152
+ elif not issues:
153
+ status = "current"
154
+ else:
155
+ status = "incomplete"
156
+
157
+ local_current = bool(
158
+ source_revision
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
+ )
166
+ return {
167
+ "status": status,
168
+ "issues": issues,
169
+ "rebuild": rebuild,
170
+ "publish": publish,
171
+ }
172
+
173
+
174
+ def _ir_source_revision(manifest: Mapping[str, Any] | None) -> str | None:
175
+ if not manifest:
176
+ return None
177
+ pinned = manifest.get("dataset_revision") or (manifest.get("source") or {}).get(
178
+ "source_revision"
179
+ )
180
+ text = str(pinned or "").strip()
181
+ return text or None
182
+
183
+
184
+ def _vector_status(manifest: Mapping[str, Any] | None) -> str | None:
185
+ if not manifest:
186
+ return None
187
+ vector = manifest.get("vector") or {}
188
+ if isinstance(vector, dict) and vector.get("status"):
189
+ return str(vector.get("status"))
190
+ incremental = manifest.get("incremental") or {}
191
+ nested = incremental.get("vectors") if isinstance(incremental, dict) else None
192
+ if isinstance(nested, dict) and nested.get("status"):
193
+ return str(nested.get("status"))
194
+ if isinstance(vector, dict) and vector.get("stub"):
195
+ return "stub"
196
+ return None
197
+
198
+
199
+ def load_local_manifest(release_dir: Path) -> dict[str, Any]:
200
+ path = Path(release_dir) / "manifest.json"
201
+ if not path.is_file():
202
+ return {}
203
+ try:
204
+ data = json.loads(path.read_text(encoding="utf-8"))
205
+ except Exception:
206
+ return {}
207
+ return data if isinstance(data, dict) else {}
208
+
209
+
210
+ def _sibling_map(info: Any) -> dict[str, int | None]:
211
+ out: dict[str, int | None] = {}
212
+ for sib in getattr(info, "siblings", None) or []:
213
+ name = str(getattr(sib, "rfilename", "") or "")
214
+ if not name:
215
+ continue
216
+ size = getattr(sib, "size", None)
217
+ try:
218
+ out[name] = int(size) if size is not None else None # type: ignore[assignment]
219
+ except (TypeError, ValueError):
220
+ out[name] = None # type: ignore[assignment]
221
+ return out
222
+
223
+
224
+ def _inspect_source(slug: str, cache_dir: Path | None = None) -> dict[str, Any]:
225
+ from huggingface_hub import dataset_info
226
+
227
+ from .auth import configure_hf, operator_token, public_token
228
+
229
+ repo = f"endomorphosis/ipfs_{slug}_laws"
230
+ configure_hf()
231
+ info = dataset_info(repo, token=operator_token() or public_token())
232
+ files = _sibling_map(info)
233
+ laws_file = next(
234
+ (name for name in ("data/laws.parquet", "laws.parquet") if name in files),
235
+ None,
236
+ )
237
+ arts_file = next(
238
+ (name for name in ("data/articles.parquet", "articles.parquet") if name in files),
239
+ None,
240
+ )
241
+ return {
242
+ "repo": repo,
243
+ "revision": getattr(info, "sha", None),
244
+ "files": sorted(files),
245
+ "has_laws": laws_file is not None,
246
+ "has_articles": arts_file is not None,
247
+ "laws_bytes": files.get(laws_file) if laws_file else None,
248
+ "articles_bytes": files.get(arts_file) if arts_file else None,
249
+ }
250
+
251
+
252
+ def _inspect_ir(slug: str, cache_dir: Path) -> dict[str, Any] | None:
253
+ from huggingface_hub import HfApi, dataset_info, hf_hub_download
254
+ from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError
255
+
256
+ from .auth import configure_hf, operator_token, public_token
257
+
258
+ repo = target_repo(slug)
259
+ configure_hf()
260
+ token = operator_token() or public_token()
261
+ try:
262
+ info = dataset_info(repo, token=token)
263
+ except RepositoryNotFoundError:
264
+ return None
265
+ files = _sibling_map(info)
266
+ if len(files) < 8:
267
+ try:
268
+ listed = HfApi(token=token).list_repo_files(repo_id=repo, repo_type="dataset")
269
+ for name in listed:
270
+ files.setdefault(str(name), None)
271
+ except Exception:
272
+ pass
273
+ manifest: dict[str, Any] = {}
274
+ if "manifest.json" in files:
275
+ try:
276
+ path = hf_hub_download(
277
+ repo_id=repo,
278
+ filename="manifest.json",
279
+ repo_type="dataset",
280
+ token=token,
281
+ cache_dir=str(cache_dir / "hf"),
282
+ )
283
+ payload = json.loads(Path(path).read_text(encoding="utf-8"))
284
+ if isinstance(payload, dict):
285
+ manifest = payload
286
+ except (EntryNotFoundError, OSError, json.JSONDecodeError):
287
+ manifest = {}
288
+ counts = manifest.get("counts") if isinstance(manifest.get("counts"), dict) else {}
289
+ return {
290
+ "repo": repo,
291
+ "hub_revision": getattr(info, "sha", None),
292
+ "files": sorted(files),
293
+ "manifest": manifest,
294
+ "source_revision": _ir_source_revision(manifest),
295
+ "corpus_rows": counts.get("corpus_rows"),
296
+ "vector_status": _vector_status(manifest),
297
+ }
298
+
299
+
300
+ def gap_report(
301
+ releases_dir: Path | None = None,
302
+ *,
303
+ slugs: list[str] | None = None,
304
+ workers: int = 8,
305
+ ) -> dict[str, Any]:
306
+ """Live Hub scan: missing, stale, incomplete, and unpublished country IR."""
307
+ from .build import CACHE, RELEASES
308
+
309
+ sources = slugs or [
310
+ s
311
+ for s in list_hub_slugs(author="endomorphosis", kind="source")
312
+ if s not in ALIAS_TO_CANONICAL
313
+ ]
314
+ hub_ir = set(list_hub_slugs(author="justicedao", kind="ir"))
315
+ local_dir = Path(releases_dir) if releases_dir else RELEASES
316
+ local_ir = set(local_release_slugs(local_dir))
317
+ cache_dir = CACHE
318
+ cache_dir.mkdir(parents=True, exist_ok=True)
319
+
320
+ rows: list[dict[str, Any]] = []
321
+
322
+ def _one(slug: str) -> dict[str, Any]:
323
+ last_exc: Exception | None = None
324
+ for attempt in range(4):
325
+ try:
326
+ source = _inspect_source(slug)
327
+ ir = _inspect_ir(slug, cache_dir) if slug in hub_ir else None
328
+ break
329
+ except Exception as exc:
330
+ last_exc = exc
331
+ name = type(exc).__name__
332
+ msg = str(exc)
333
+ if "429" in msg or "rate limit" in msg.lower():
334
+ time.sleep(min(45, 3 ** attempt * 2))
335
+ continue
336
+ raise
337
+ else:
338
+ raise last_exc or RuntimeError(f"scan failed for {slug}")
339
+ local_manifest = load_local_manifest(local_dir / f"ipfs_{slug}_laws_ir")
340
+ local_rev = _ir_source_revision(local_manifest) if local_manifest else None
341
+ classified = classify_gap(
342
+ excluded=slug in EXCLUDED_SLUGS,
343
+ alias=False,
344
+ source_has_laws=bool(source.get("has_laws")),
345
+ source_laws_bytes=source.get("laws_bytes"),
346
+ source_revision=source.get("revision"),
347
+ ir_files=None if ir is None else ir.get("files"),
348
+ ir_source_revision=(ir or {}).get("source_revision") or local_rev,
349
+ ir_corpus_rows=(ir or {}).get("corpus_rows")
350
+ if ir is not None
351
+ else (local_manifest.get("counts") or {}).get("corpus_rows")
352
+ if local_manifest
353
+ else None,
354
+ vector_status=(ir or {}).get("vector_status")
355
+ or _vector_status(local_manifest),
356
+ local_only=slug in local_ir and slug not in hub_ir,
357
+ local_source_revision=local_rev,
358
+ )
359
+ return {
360
+ "slug": slug,
361
+ "source": source.get("repo"),
362
+ "target": target_repo(slug),
363
+ "source_revision": source.get("revision"),
364
+ "ir_source_revision": (ir or {}).get("source_revision"),
365
+ "local_source_revision": local_rev,
366
+ "has_hub_ir": ir is not None,
367
+ "has_local_ir": slug in local_ir,
368
+ "source_has_articles": source.get("has_articles"),
369
+ "source_laws_bytes": source.get("laws_bytes"),
370
+ "corpus_rows": (ir or {}).get("corpus_rows")
371
+ if ir is not None
372
+ else (local_manifest.get("counts") or {}).get("corpus_rows")
373
+ if local_manifest
374
+ else None,
375
+ "vector_status": (ir or {}).get("vector_status")
376
+ or _vector_status(local_manifest),
377
+ **classified,
378
+ }
379
+
380
+ workers = max(1, min(int(workers), 16))
381
+ with ThreadPoolExecutor(max_workers=workers) as pool:
382
+ futs = {pool.submit(_one, slug): slug for slug in sources}
383
+ for fut in as_completed(futs):
384
+ slug = futs[fut]
385
+ try:
386
+ rows.append(fut.result())
387
+ except Exception as exc:
388
+ rows.append(
389
+ {
390
+ "slug": slug,
391
+ "source": f"endomorphosis/ipfs_{slug}_laws",
392
+ "target": target_repo(slug),
393
+ "status": "incomplete",
394
+ "issues": [f"scan_error:{type(exc).__name__}"],
395
+ "rebuild": False,
396
+ "publish": False,
397
+ "error": str(exc),
398
+ }
399
+ )
400
+ rows.sort(key=lambda r: str(r.get("slug")))
401
+ by_status: dict[str, list[str]] = {}
402
+ for row in rows:
403
+ by_status.setdefault(str(row.get("status")), []).append(str(row.get("slug")))
404
+ return {
405
+ "n": len(rows),
406
+ "by_status": {k: sorted(v) for k, v in sorted(by_status.items())},
407
+ "counts": {k: len(v) for k, v in sorted(by_status.items())},
408
+ "rebuild": [r["slug"] for r in rows if r.get("rebuild")],
409
+ "publish": [r["slug"] for r in rows if r.get("publish")],
410
+ "countries": rows,
411
+ }
412
+
413
+
414
+ def coverage_report(releases_dir: Path | None = None) -> dict[str, Any]:
415
+ from .build import RELEASES
416
+
417
+ sources = list_hub_slugs(author="endomorphosis", kind="source")
418
+ hub_ir = list_hub_slugs(author="justicedao", kind="ir")
419
+ local_ir = local_release_slugs(Path(releases_dir) if releases_dir else RELEASES)
420
+ hub_ir_canon = {canonical_slug(s) for s in hub_ir}
421
+ local_ir_canon = {canonical_slug(s) for s in local_ir}
422
+ missing_hub: list[dict[str, Any]] = []
423
+ missing_local: list[dict[str, Any]] = []
424
+ excluded: list[str] = []
425
+ aliases: list[str] = []
426
+ for slug in sources:
427
+ if slug in ALIAS_TO_CANONICAL:
428
+ aliases.append(slug)
429
+ continue
430
+ if slug in EXCLUDED_SLUGS:
431
+ excluded.append(slug)
432
+ continue
433
+ row = {
434
+ "slug": slug,
435
+ "source": f"endomorphosis/ipfs_{slug}_laws",
436
+ "target": target_repo(slug),
437
+ }
438
+ if slug not in hub_ir_canon:
439
+ missing_hub.append(row)
440
+ if slug not in local_ir_canon and slug not in hub_ir_canon:
441
+ missing_local.append(row)
442
+ return {
443
+ "n_sources": len(sources),
444
+ "n_hub_ir": len(hub_ir),
445
+ "n_local_ir": len(local_ir),
446
+ "n_catalog": len(all_countries()),
447
+ "excluded": excluded,
448
+ "alias_sources": aliases,
449
+ "missing_justicedao": missing_hub,
450
+ "missing_local_and_hub": missing_local,
451
+ "local_only": sorted(local_ir_canon - hub_ir_canon),
452
+ }
country_laws_ir/incremental.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CID-keyed incremental GraphRAG rebuild for country-laws IR.
2
+
3
+ Follows the US Code / patent persistent-index pattern:
4
+
5
+ * ``entry_cid`` is the durable identity (not positional ``document_index``).
6
+ * A matching source revision + parquet digest is a no-op.
7
+ * Unchanged CIDs reuse embeddings; BM25/graph are rebuilt from the current
8
+ corpus because ``document_index`` is a shard pointer, not an identity.
9
+ * Delta refresh is never labeled equivalent to a full rebuild.
10
+
11
+ Public Hub reads stay anonymous. Publication to ``justicedao/*`` is a separate
12
+ gated upload step.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from enum import Enum
19
+ import json
20
+ from pathlib import Path
21
+ from typing import Any, Iterable, Mapping
22
+
23
+ import pandas as pd
24
+
25
+ from . import SCHEMA_VERSION
26
+
27
+ class RebuildKind(str, Enum):
28
+ UNCHANGED = "unchanged"
29
+ DELTA_REFRESH = "delta_refresh"
30
+ FULL_REBUILD = "full_rebuild"
31
+
32
+ @classmethod
33
+ def coerce(cls, value: Any) -> "RebuildKind":
34
+ if isinstance(value, RebuildKind):
35
+ return value
36
+ text = str(value or "").strip().lower().replace("-", "_")
37
+ aliases = {
38
+ "skip": cls.UNCHANGED,
39
+ "noop": cls.UNCHANGED,
40
+ "none": cls.UNCHANGED,
41
+ "delta": cls.DELTA_REFRESH,
42
+ "incremental": cls.DELTA_REFRESH,
43
+ "partial": cls.DELTA_REFRESH,
44
+ "full": cls.FULL_REBUILD,
45
+ "rebuild": cls.FULL_REBUILD,
46
+ "force": cls.FULL_REBUILD,
47
+ }
48
+ if text in aliases:
49
+ return aliases[text]
50
+ for kind in cls:
51
+ if kind.value == text or kind.name.lower() == text:
52
+ return kind
53
+ raise ValueError(f"unknown rebuild kind: {value!r}")
54
+
55
+
56
+ class BuildMode(str, Enum):
57
+ AUTO = "auto"
58
+ FULL = "full"
59
+ DELTA = "delta"
60
+
61
+ @classmethod
62
+ def coerce(cls, value: Any) -> "BuildMode":
63
+ if isinstance(value, BuildMode):
64
+ return value
65
+ text = str(value or "").strip().lower().replace("-", "_")
66
+ aliases = {
67
+ "incremental": cls.DELTA,
68
+ "diff": cls.DELTA,
69
+ "rebuild": cls.FULL,
70
+ "complete": cls.FULL,
71
+ }
72
+ if text in aliases:
73
+ return aliases[text]
74
+ for mode in cls:
75
+ if mode.value == text or mode.name.lower() == text:
76
+ return mode
77
+ raise ValueError(f"unknown build mode: {value!r}")
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class CorpusDelta:
82
+ added_cids: tuple[str, ...] = ()
83
+ removed_cids: tuple[str, ...] = ()
84
+ unchanged_cids: tuple[str, ...] = ()
85
+ prior_count: int = 0
86
+ current_count: int = 0
87
+ changed_ratio: float = 1.0
88
+ equivalent_to_full: bool = False
89
+
90
+ @property
91
+ def n_added(self) -> int:
92
+ return len(self.added_cids)
93
+
94
+ @property
95
+ def n_removed(self) -> int:
96
+ return len(self.removed_cids)
97
+
98
+ @property
99
+ def n_unchanged(self) -> int:
100
+ return len(self.unchanged_cids)
101
+
102
+ def to_dict(self, *, include_cids: bool = False, cid_sample: int = 8) -> dict[str, Any]:
103
+ payload = {
104
+ "n_added": self.n_added,
105
+ "n_removed": self.n_removed,
106
+ "n_unchanged": self.n_unchanged,
107
+ "prior_count": self.prior_count,
108
+ "current_count": self.current_count,
109
+ "changed_ratio": self.changed_ratio,
110
+ "equivalent_to_full": self.equivalent_to_full,
111
+ }
112
+ if include_cids:
113
+ payload["added_cids"] = list(self.added_cids)
114
+ payload["removed_cids"] = list(self.removed_cids)
115
+ payload["unchanged_cids"] = list(self.unchanged_cids)
116
+ else:
117
+ payload["added_cids_sample"] = list(self.added_cids[:cid_sample])
118
+ payload["removed_cids_sample"] = list(self.removed_cids[:cid_sample])
119
+ return payload
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class RebuildPlan:
124
+ kind: RebuildKind
125
+ mode: BuildMode
126
+ reason: str
127
+ source_revision: str
128
+ prior_revision: str | None = None
129
+ source_fingerprint: str = ""
130
+ prior_fingerprint: str | None = None
131
+ delta: CorpusDelta | None = None
132
+ reuse_embeddings: bool = False
133
+ skip_build: bool = False
134
+ equivalent_to_full: bool = False
135
+
136
+ def to_dict(self) -> dict[str, Any]:
137
+ return {
138
+ "kind": self.kind.value,
139
+ "mode": self.mode.value,
140
+ "reason": self.reason,
141
+ "source_revision": self.source_revision,
142
+ "prior_revision": self.prior_revision,
143
+ "source_fingerprint": self.source_fingerprint,
144
+ "prior_fingerprint": self.prior_fingerprint,
145
+ "delta": None if self.delta is None else self.delta.to_dict(include_cids=False),
146
+ "reuse_embeddings": self.reuse_embeddings,
147
+ "skip_build": self.skip_build,
148
+ "equivalent_to_full": self.equivalent_to_full,
149
+ "schema_version": SCHEMA_VERSION,
150
+ }
151
+
152
+
153
+ @dataclass
154
+ class PriorRelease:
155
+ directory: Path
156
+ manifest: dict[str, Any] = field(default_factory=dict)
157
+ corpus: pd.DataFrame | None = None
158
+ vectors_by_cid: dict[str, list[float]] | None = None
159
+
160
+ @property
161
+ def source_revision(self) -> str | None:
162
+ return (
163
+ self.manifest.get("dataset_revision")
164
+ or (self.manifest.get("source") or {}).get("source_revision")
165
+ )
166
+
167
+ @property
168
+ def fingerprint(self) -> str:
169
+ return source_fingerprint_from_manifest(self.manifest)
170
+
171
+
172
+ def source_fingerprint(source_meta: Mapping[str, Any]) -> str:
173
+ """Stable skip key: Hub SHA plus parquet digests when present."""
174
+ revision = str(source_meta.get("source_revision") or "")
175
+ laws = str(source_meta.get("laws_sha256") or "")
176
+ articles = str(source_meta.get("articles_sha256") or "")
177
+ return f"{revision}|{laws}|{articles}"
178
+
179
+
180
+ def source_fingerprint_from_manifest(manifest: Mapping[str, Any]) -> str:
181
+ revision = str(
182
+ manifest.get("dataset_revision")
183
+ or (manifest.get("source") or {}).get("source_revision")
184
+ or ""
185
+ )
186
+ sha = manifest.get("input_sha256") or {}
187
+ laws = str(sha.get("laws.parquet") or "")
188
+ articles = str(sha.get("articles.parquet") or "")
189
+ if not laws and not articles:
190
+ src = manifest.get("source") or {}
191
+ laws = str(src.get("laws_sha256") or "")
192
+ articles = str(src.get("articles_sha256") or "")
193
+ return f"{revision}|{laws}|{articles}"
194
+
195
+
196
+ def _cid_set(frame: pd.DataFrame | None) -> set[str]:
197
+ if frame is None or frame.empty or "entry_cid" not in frame.columns:
198
+ return set()
199
+ return {str(x) for x in frame["entry_cid"].dropna().astype(str) if str(x).strip()}
200
+
201
+
202
+ def diff_corpus(
203
+ prior: pd.DataFrame | None,
204
+ current: pd.DataFrame,
205
+ ) -> CorpusDelta:
206
+ """Diff two CID-keyed corpora. Same ``entry_cid`` implies same body."""
207
+ current_cids = _cid_set(current)
208
+ prior_cids = _cid_set(prior)
209
+ added = tuple(sorted(current_cids - prior_cids))
210
+ removed = tuple(sorted(prior_cids - current_cids))
211
+ unchanged = tuple(sorted(current_cids & prior_cids))
212
+ current_count = int(len(current_cids))
213
+ prior_count = int(len(prior_cids))
214
+ if current_count == 0:
215
+ ratio = 1.0 if prior_count else 0.0
216
+ else:
217
+ ratio = 1.0 - (len(unchanged) / float(current_count))
218
+ equivalent = prior_count == 0 or (not unchanged and current_count > 0)
219
+ return CorpusDelta(
220
+ added_cids=added,
221
+ removed_cids=removed,
222
+ unchanged_cids=unchanged,
223
+ prior_count=prior_count,
224
+ current_count=current_count,
225
+ changed_ratio=float(ratio),
226
+ equivalent_to_full=equivalent,
227
+ )
228
+
229
+
230
+ def plan_rebuild(
231
+ *,
232
+ mode: BuildMode | str,
233
+ source_meta: Mapping[str, Any],
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)
240
+ revision = str(source_meta.get("source_revision") or "")
241
+ fingerprint = source_fingerprint(source_meta)
242
+ prior_revision = prior.source_revision if prior is not None else None
243
+ prior_fp = prior.fingerprint if prior is not None else None
244
+
245
+ if force or mode is BuildMode.FULL:
246
+ delta = None
247
+ if current_corpus is not None and prior is not None:
248
+ delta = diff_corpus(prior.corpus, current_corpus)
249
+ return RebuildPlan(
250
+ kind=RebuildKind.FULL_REBUILD,
251
+ mode=mode,
252
+ reason="operator forced full rebuild" if force else "build mode is full",
253
+ source_revision=revision,
254
+ prior_revision=prior_revision,
255
+ source_fingerprint=fingerprint,
256
+ prior_fingerprint=prior_fp,
257
+ delta=delta,
258
+ reuse_embeddings=False,
259
+ skip_build=False,
260
+ equivalent_to_full=True,
261
+ )
262
+
263
+ if prior is None:
264
+ return RebuildPlan(
265
+ kind=RebuildKind.FULL_REBUILD,
266
+ mode=mode,
267
+ reason="no prior release",
268
+ source_revision=revision,
269
+ prior_revision=None,
270
+ source_fingerprint=fingerprint,
271
+ prior_fingerprint=None,
272
+ delta=None,
273
+ reuse_embeddings=False,
274
+ skip_build=False,
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,
282
+ reason="source revision and parquet digests match prior release",
283
+ source_revision=revision,
284
+ prior_revision=prior_revision,
285
+ source_fingerprint=fingerprint,
286
+ prior_fingerprint=prior_fp,
287
+ delta=CorpusDelta(
288
+ unchanged_cids=tuple(sorted(_cid_set(prior.corpus))),
289
+ prior_count=int(len(_cid_set(prior.corpus))),
290
+ current_count=int(len(_cid_set(prior.corpus))),
291
+ changed_ratio=0.0,
292
+ equivalent_to_full=False,
293
+ ),
294
+ reuse_embeddings=True,
295
+ skip_build=True,
296
+ equivalent_to_full=False,
297
+ )
298
+
299
+ delta = None
300
+ if current_corpus is not None:
301
+ delta = diff_corpus(prior.corpus, current_corpus)
302
+ if delta.equivalent_to_full:
303
+ return RebuildPlan(
304
+ kind=RebuildKind.FULL_REBUILD,
305
+ mode=mode,
306
+ reason="CID overlap is empty; delta equals a full rebuild",
307
+ source_revision=revision,
308
+ prior_revision=prior_revision,
309
+ source_fingerprint=fingerprint,
310
+ prior_fingerprint=prior_fp,
311
+ delta=delta,
312
+ reuse_embeddings=False,
313
+ skip_build=False,
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,
324
+ prior_fingerprint=prior_fp,
325
+ delta=delta,
326
+ reuse_embeddings=True,
327
+ skip_build=False,
328
+ equivalent_to_full=False,
329
+ )
330
+
331
+
332
+ def _read_sharded_parquet(directory: Path) -> pd.DataFrame | None:
333
+ if not directory.is_dir():
334
+ return None
335
+ parts = sorted(directory.glob("part-*.parquet"))
336
+ if not parts:
337
+ parts = sorted(p for p in directory.rglob("*.parquet") if p.is_file())
338
+ if not parts:
339
+ return None
340
+ frames = [pd.read_parquet(p) for p in parts]
341
+ return pd.concat(frames, ignore_index=True) if frames else None
342
+
343
+
344
+ def load_release_manifest(release_dir: Path) -> dict[str, Any]:
345
+ path = Path(release_dir) / "manifest.json"
346
+ if not path.is_file():
347
+ return {}
348
+ try:
349
+ data = json.loads(path.read_text(encoding="utf-8"))
350
+ except Exception:
351
+ return {}
352
+ return data if isinstance(data, dict) else {}
353
+
354
+
355
+ def load_release_corpus(release_dir: Path) -> pd.DataFrame | None:
356
+ release_dir = Path(release_dir)
357
+ corpus = _read_sharded_parquet(release_dir / "data" / "corpus")
358
+ if corpus is not None:
359
+ return corpus
360
+ checkpoint = release_dir / "corpus.parquet"
361
+ if checkpoint.is_file():
362
+ return pd.read_parquet(checkpoint)
363
+ return None
364
+
365
+
366
+ def embeddings_from_vector_table(frame: pd.DataFrame) -> dict[str, list[float]]:
367
+ out: dict[str, list[float]] = {}
368
+ if frame is None or frame.empty:
369
+ return out
370
+ if "entry_cid" not in frame.columns or "embedding" not in frame.columns:
371
+ return out
372
+ for rec in frame.itertuples(index=False):
373
+ cid = str(getattr(rec, "entry_cid", "") or "")
374
+ emb = getattr(rec, "embedding", None)
375
+ if not cid or emb is None:
376
+ continue
377
+ if isinstance(emb, float) and pd.isna(emb):
378
+ continue
379
+ try:
380
+ values = [float(x) for x in list(emb)]
381
+ except Exception:
382
+ continue
383
+ if not values:
384
+ continue
385
+ out[cid] = values
386
+ return out
387
+
388
+
389
+ def load_release_vectors_by_cid(release_dir: Path) -> dict[str, list[float]]:
390
+ frame = _read_sharded_parquet(Path(release_dir) / "data" / "vectors")
391
+ if frame is None:
392
+ return {}
393
+ return embeddings_from_vector_table(frame)
394
+
395
+
396
+ def load_prior_release(release_dir: Path | None) -> PriorRelease | None:
397
+ if release_dir is None:
398
+ return None
399
+ directory = Path(release_dir)
400
+ if not directory.is_dir():
401
+ return None
402
+ manifest = load_release_manifest(directory)
403
+ if not manifest and not (directory / "data").is_dir():
404
+ return None
405
+ return PriorRelease(
406
+ directory=directory,
407
+ manifest=manifest,
408
+ corpus=load_release_corpus(directory),
409
+ vectors_by_cid=None,
410
+ )
411
+
412
+
413
+ def load_embedding_cache(path: Path) -> dict[str, list[float]]:
414
+ if not path.is_file():
415
+ return {}
416
+ try:
417
+ frame = pd.read_parquet(path)
418
+ except Exception:
419
+ return {}
420
+ return embeddings_from_vector_table(frame)
421
+
422
+
423
+ def save_embedding_cache(
424
+ path: Path,
425
+ by_cid: Mapping[str, Iterable[float]],
426
+ *,
427
+ model_name: str,
428
+ dimension: int,
429
+ ) -> None:
430
+ path.parent.mkdir(parents=True, exist_ok=True)
431
+ rows = [
432
+ {
433
+ "entry_cid": cid,
434
+ "embedding": list(vec),
435
+ "model_name": model_name,
436
+ "dimension": int(dimension),
437
+ }
438
+ for cid, vec in sorted(by_cid.items())
439
+ ]
440
+ frame = pd.DataFrame(rows)
441
+ tmp = path.with_suffix(path.suffix + ".tmp")
442
+ frame.to_parquet(tmp, index=False)
443
+ tmp.replace(path)
444
+
445
+
446
+ def merge_embedding_maps(
447
+ *maps: Mapping[str, list[float]] | None,
448
+ ) -> dict[str, list[float]]:
449
+ merged: dict[str, list[float]] = {}
450
+ for mapping in maps:
451
+ if not mapping:
452
+ continue
453
+ merged.update(mapping)
454
+ return merged
455
+
456
+
457
+ def fetch_hub_prior(
458
+ slug: str,
459
+ dest: Path | None = None,
460
+ *,
461
+ cache_root: Path | None = None,
462
+ ) -> Path | None:
463
+ """Download JusticeDAO corpus+vector shards to use as an incremental parent.
464
+
465
+ Missing Hub IR is not an error: first-time countries return ``None``.
466
+ """
467
+ from huggingface_hub import snapshot_download
468
+ from huggingface_hub.errors import RepositoryNotFoundError
469
+
470
+ from .auth import operator_token, public_token
471
+ from .catalog import target_repo
472
+
473
+ root = Path(cache_root) if cache_root is not None else (
474
+ Path.home() / ".ipfs_datasets" / "country-laws-ir" / "cache" / "hub-ir"
475
+ )
476
+ dest = Path(dest) if dest is not None else (root / slug)
477
+ dest.mkdir(parents=True, exist_ok=True)
478
+ repo = target_repo(slug)
479
+ try:
480
+ snapshot_download(
481
+ repo_id=repo,
482
+ repo_type="dataset",
483
+ local_dir=str(dest),
484
+ allow_patterns=[
485
+ "manifest.json",
486
+ "data/vectors/**",
487
+ "data/corpus/**",
488
+ "indexes/vector_chunks.parquet",
489
+ ],
490
+ token=operator_token() or public_token(),
491
+ )
492
+ except RepositoryNotFoundError:
493
+ return None
494
+ except Exception:
495
+ if not (dest / "manifest.json").is_file():
496
+ return None
497
+ raise
498
+ if not (dest / "manifest.json").is_file():
499
+ return None
500
+ return dest
country_laws_ir/mem.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Process / host memory watchdog for large IR builds (DO OOM lesson).
2
+
3
+ Env overrides:
4
+ IR_MEM_WARN_GIB MemAvailable threshold to shed collectors (default 3.5)
5
+ IR_MEM_ABORT_GIB MemAvailable abort floor (default 2.5)
6
+ IR_RSS_ABORT_GIB process RSS hard abort (default 12.0)
7
+ IR_MEM_LOG_EVERY rows between mem logs when callers pass every_n (default 5000)
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import gc
12
+ import os
13
+ import signal
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Any, Callable
17
+
18
+ DEFAULT_WARN_GIB = 3.5
19
+ DEFAULT_ABORT_AVAIL_GIB = 2.5
20
+ DEFAULT_ABORT_RSS_GIB = 12.0
21
+ DEFAULT_LOG_EVERY = 5000
22
+
23
+ # Prefer shedding zero-article / lean collectors first; protect AT+DK until last.
24
+ DEFAULT_SHED_ORDER: list[tuple[str, tuple[str, ...]]] = [
25
+ ("mm", ("collect_mm", "run_collector_cc.sh collect_mm")),
26
+ ("th", ("collect_th", "run_collector_cc.sh collect_th")),
27
+ ("is-reg", ("collect_is", "is-reg", "run_collector_cc.sh collect_is")),
28
+ ("lt", ("collect_lt", "run_collector_cc.sh collect_lt")),
29
+ ("kw", ("collect_kw", "run_collector_cc.sh collect_kw")),
30
+ ("mt", ("collect_mt", "run_collector_cc.sh collect_mt")),
31
+ ("dk", ("collect_dk", "run_collector_cc.sh collect_dk")),
32
+ ("at", ("collect_at", "run_collector_cc.sh collect_at", "at_deepen")),
33
+ ]
34
+
35
+
36
+ class MemAbort(RuntimeError):
37
+ """Raised when MemAvailable or RSS crosses hard abort thresholds."""
38
+
39
+
40
+ def _env_float(name: str, default: float) -> float:
41
+ raw = os.environ.get(name)
42
+ if raw is None or raw == "":
43
+ return default
44
+ try:
45
+ return float(raw)
46
+ except ValueError:
47
+ return default
48
+
49
+
50
+ def warn_gib() -> float:
51
+ return _env_float("IR_MEM_WARN_GIB", DEFAULT_WARN_GIB)
52
+
53
+
54
+ def abort_avail_gib() -> float:
55
+ return _env_float("IR_MEM_ABORT_GIB", DEFAULT_ABORT_AVAIL_GIB)
56
+
57
+
58
+ def abort_rss_gib() -> float:
59
+ return _env_float("IR_RSS_ABORT_GIB", DEFAULT_ABORT_RSS_GIB)
60
+
61
+
62
+ def log_every() -> int:
63
+ try:
64
+ return max(1, int(os.environ.get("IR_MEM_LOG_EVERY", DEFAULT_LOG_EVERY)))
65
+ except ValueError:
66
+ return DEFAULT_LOG_EVERY
67
+
68
+
69
+ def mem_available_gib() -> float:
70
+ try:
71
+ for line in Path("/proc/meminfo").read_text().splitlines():
72
+ if line.startswith("MemAvailable:"):
73
+ return int(line.split()[1]) / 1024 / 1024
74
+ except Exception:
75
+ pass
76
+ return -1.0
77
+
78
+
79
+ def rss_gib(pid: int | None = None) -> float:
80
+ path = Path(f"/proc/{pid or 'self'}/status")
81
+ try:
82
+ for line in path.read_text().splitlines():
83
+ if line.startswith("VmRSS:"):
84
+ return int(line.split()[1]) / 1024 / 1024
85
+ except Exception:
86
+ pass
87
+ return -1.0
88
+
89
+
90
+ def snapshot(stage: str = "") -> dict[str, Any]:
91
+ return {
92
+ "stage": stage,
93
+ "mem_avail_gib": round(mem_available_gib(), 3),
94
+ "rss_gib": round(rss_gib(), 3),
95
+ "ts": datetime.now(timezone.utc).isoformat(),
96
+ }
97
+
98
+
99
+ def log_mem(stage: str, log: Callable[[str], None] | None = None) -> dict[str, Any]:
100
+ snap = snapshot(stage)
101
+ msg = (
102
+ f"mem stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G "
103
+ f"RSS={snap['rss_gib']:.2f}G"
104
+ )
105
+ if log is not None:
106
+ log(msg)
107
+ else:
108
+ print(f"[{snap['ts']}] {msg}", flush=True)
109
+ return snap
110
+
111
+
112
+ def discover_pids(*patterns: str) -> list[int]:
113
+ found: list[int] = []
114
+ try:
115
+ for proc in Path("/proc").iterdir():
116
+ if not proc.name.isdigit():
117
+ continue
118
+ try:
119
+ cmd = (proc / "cmdline").read_bytes().replace(b"\x00", b" ").decode(
120
+ "utf-8", "ignore"
121
+ )
122
+ except Exception:
123
+ continue
124
+ if any(p in cmd for p in patterns):
125
+ found.append(int(proc.name))
126
+ except Exception:
127
+ pass
128
+ return found
129
+
130
+
131
+ def shed_collectors(
132
+ stage: str,
133
+ *,
134
+ warn: float | None = None,
135
+ protect: frozenset[str] | None = None,
136
+ log: Callable[[str], None] | None = None,
137
+ notes: list[dict[str, Any]] | None = None,
138
+ ) -> list[dict[str, Any]]:
139
+ """SIGTERM lean collectors when MemAvailable < warn. Protect AT/DK by default until last."""
140
+ warn = warn_gib() if warn is None else warn
141
+ protect = protect if protect is not None else frozenset({"at", "dk"})
142
+ g = mem_available_gib()
143
+ out: list[dict[str, Any]] = []
144
+ if g < 0 or g >= warn:
145
+ return out
146
+ # First pass: non-protected; second pass: protected if still under warn.
147
+ for pass_protected in (False, True):
148
+ for name, pats in DEFAULT_SHED_ORDER:
149
+ if (name in protect) != pass_protected:
150
+ continue
151
+ pids = discover_pids(*pats)
152
+ for pid in pids:
153
+ try:
154
+ os.kill(pid, 0)
155
+ except ProcessLookupError:
156
+ continue
157
+ except PermissionError:
158
+ continue
159
+ try:
160
+ os.kill(pid, signal.SIGTERM)
161
+ note = {
162
+ "stage": stage,
163
+ "name": name,
164
+ "pid": pid,
165
+ "mem_before": round(g, 2),
166
+ "protected_pass": pass_protected,
167
+ }
168
+ out.append(note)
169
+ if notes is not None:
170
+ notes.append(note)
171
+ msg = f"SIGTERM collector {name} pid={pid} mem={g:.2f}G stage={stage}"
172
+ if log:
173
+ log(msg)
174
+ else:
175
+ print(msg, flush=True)
176
+ except ProcessLookupError:
177
+ pass
178
+ except Exception as exc:
179
+ msg = f"SIGTERM failed {name} pid={pid}: {exc}"
180
+ if log:
181
+ log(msg)
182
+ else:
183
+ print(msg, flush=True)
184
+ g = mem_available_gib()
185
+ if g >= warn:
186
+ return out
187
+ return out
188
+
189
+
190
+ def checkpoint(
191
+ stage: str,
192
+ *,
193
+ row: int | None = None,
194
+ every_n: int | None = None,
195
+ shed: bool = True,
196
+ abort: bool = True,
197
+ log: Callable[[str], None] | None = None,
198
+ notes: list[dict[str, Any]] | None = None,
199
+ ) -> dict[str, Any]:
200
+ """Periodic mem log + optional shed + hard abort.
201
+
202
+ Call every N rows with ``row`` set; always logs when row is None.
203
+ """
204
+ every = every_n if every_n is not None else log_every()
205
+ if row is not None and row != 0 and row % every != 0:
206
+ # Still enforce hard abort cheaply on every call.
207
+ rss = rss_gib()
208
+ avail = mem_available_gib()
209
+ if abort and rss >= abort_rss_gib():
210
+ raise MemAbort(f"RSS_ABORT stage={stage} rss={rss:.2f}G > {abort_rss_gib()}G")
211
+ if abort and 0 <= avail < abort_avail_gib():
212
+ if shed:
213
+ shed_collectors(stage, log=log, notes=notes)
214
+ avail = mem_available_gib()
215
+ if 0 <= avail < abort_avail_gib():
216
+ raise MemAbort(
217
+ f"MEM_ABORT stage={stage} MemAvailable={avail:.2f}G < {abort_avail_gib()}G"
218
+ )
219
+ return snapshot(stage)
220
+
221
+ snap = log_mem(stage if row is None else f"{stage}@{row}", log=log)
222
+ if shed and 0 <= snap["mem_avail_gib"] < warn_gib():
223
+ shed_collectors(stage, log=log, notes=notes)
224
+ snap = log_mem(f"{stage}_after_shed", log=log)
225
+ gc.collect()
226
+ if abort:
227
+ if snap["rss_gib"] >= abort_rss_gib():
228
+ raise MemAbort(
229
+ f"RSS_ABORT stage={stage} rss={snap['rss_gib']:.2f}G > {abort_rss_gib()}G"
230
+ )
231
+ if 0 <= snap["mem_avail_gib"] < abort_avail_gib():
232
+ raise MemAbort(
233
+ f"MEM_ABORT stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G "
234
+ f"< {abort_avail_gib()}G"
235
+ )
236
+ return snap
country_laws_ir/normalize.py CHANGED
@@ -19,6 +19,7 @@ from typing import Any
19
 
20
  import pandas as pd
21
  from huggingface_hub import dataset_info, hf_hub_download
 
22
 
23
  from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
24
  from .auth import configure_hf, public_token
@@ -27,6 +28,21 @@ from .schema import SchemaError, validate_articles, validate_laws
27
 
28
  _WS_RE = re.compile(r"\s+", re.UNICODE)
29
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def normalize_text(value: Any) -> str:
@@ -53,21 +69,34 @@ def _download(repo_id: str, filename: str, cache_dir: Path) -> Path:
53
  return Path(path)
54
 
55
 
56
- def _resolve_local_parquet(root: Path, name: str) -> Path:
 
 
 
 
 
 
 
 
 
 
 
57
  """Accept either <root>/data/<name>.parquet or <root>/<name>.parquet."""
58
  for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"):
59
  if cand.is_file():
60
  return cand
61
- raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)")
 
 
62
 
63
 
64
  def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
65
  """Load a local country-laws pack (filtered preprocess layout)."""
66
  local_dir = Path(local_dir).resolve()
67
  laws_path = _resolve_local_parquet(local_dir, "laws")
68
- articles_path = _resolve_local_parquet(local_dir, "articles")
69
  laws = pd.read_parquet(laws_path)
70
- articles = pd.read_parquet(articles_path)
71
  validate_laws(laws)
72
  validate_articles(articles)
73
  pack_meta: dict[str, Any] = {}
@@ -91,9 +120,9 @@ def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict
91
  "source_dataset": source_dataset,
92
  "source_revision": source_revision,
93
  "laws_path": str(laws_path),
94
- "articles_path": str(articles_path),
95
  "laws_sha256": sha256_file(laws_path),
96
- "articles_sha256": sha256_file(articles_path),
97
  "n_laws_source": int(len(laws)),
98
  "n_articles_source": int(len(articles)),
99
  "laws_columns": list(map(str, laws.columns)),
@@ -118,19 +147,27 @@ def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFra
118
  os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
119
  info = dataset_info(repo_id, token=public_token())
120
  revision = info.sha
121
- laws_path = _download(repo_id, "data/laws.parquet", cache_dir)
122
- articles_path = _download(repo_id, "data/articles.parquet", cache_dir)
 
 
 
 
 
 
 
 
123
  laws = pd.read_parquet(laws_path)
124
- articles = pd.read_parquet(articles_path)
125
  validate_laws(laws)
126
  validate_articles(articles)
127
  meta = {
128
  "source_dataset": repo_id,
129
  "source_revision": revision,
130
  "laws_path": str(laws_path),
131
- "articles_path": str(articles_path),
132
  "laws_sha256": sha256_file(laws_path),
133
- "articles_sha256": sha256_file(articles_path),
134
  "n_laws_source": int(len(laws)),
135
  "n_articles_source": int(len(articles)),
136
  "laws_columns": list(map(str, laws.columns)),
 
19
 
20
  import pandas as pd
21
  from huggingface_hub import dataset_info, hf_hub_download
22
+ from huggingface_hub.errors import EntryNotFoundError
23
 
24
  from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
25
  from .auth import configure_hf, public_token
 
28
 
29
  _WS_RE = re.compile(r"\s+", re.UNICODE)
30
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
31
+ EMPTY_ARTICLE_COLUMNS = (
32
+ "law_id",
33
+ "id",
34
+ "title",
35
+ "text",
36
+ "source_url",
37
+ "document_number",
38
+ "article_number",
39
+ "record_type",
40
+ "metadata_json",
41
+ )
42
+
43
+
44
+ def _empty_articles() -> pd.DataFrame:
45
+ return pd.DataFrame(columns=list(EMPTY_ARTICLE_COLUMNS))
46
 
47
 
48
  def normalize_text(value: Any) -> str:
 
69
  return Path(path)
70
 
71
 
72
+ def _repo_filenames(info: Any) -> set[str]:
73
+ return {str(getattr(s, "rfilename", "") or "") for s in (getattr(info, "siblings", None) or [])}
74
+
75
+
76
+ def _pick_repo_file(filenames: set[str], name: str) -> str | None:
77
+ for cand in (f"data/{name}.parquet", f"{name}.parquet"):
78
+ if cand in filenames:
79
+ return cand
80
+ return None
81
+
82
+
83
+ def _resolve_local_parquet(root: Path, name: str, *, required: bool = True) -> Path | None:
84
  """Accept either <root>/data/<name>.parquet or <root>/<name>.parquet."""
85
  for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"):
86
  if cand.is_file():
87
  return cand
88
+ if required:
89
+ raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)")
90
+ return None
91
 
92
 
93
  def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
94
  """Load a local country-laws pack (filtered preprocess layout)."""
95
  local_dir = Path(local_dir).resolve()
96
  laws_path = _resolve_local_parquet(local_dir, "laws")
97
+ articles_path = _resolve_local_parquet(local_dir, "articles", required=False)
98
  laws = pd.read_parquet(laws_path)
99
+ articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
100
  validate_laws(laws)
101
  validate_articles(articles)
102
  pack_meta: dict[str, Any] = {}
 
120
  "source_dataset": source_dataset,
121
  "source_revision": source_revision,
122
  "laws_path": str(laws_path),
123
+ "articles_path": str(articles_path) if articles_path is not None else None,
124
  "laws_sha256": sha256_file(laws_path),
125
+ "articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
126
  "n_laws_source": int(len(laws)),
127
  "n_articles_source": int(len(articles)),
128
  "laws_columns": list(map(str, laws.columns)),
 
147
  os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
148
  info = dataset_info(repo_id, token=public_token())
149
  revision = info.sha
150
+ filenames = _repo_filenames(info)
151
+ laws_file = _pick_repo_file(filenames, "laws") or "data/laws.parquet"
152
+ articles_file = _pick_repo_file(filenames, "articles")
153
+ laws_path = _download(repo_id, laws_file, cache_dir)
154
+ articles_path: Path | None = None
155
+ if articles_file is not None:
156
+ try:
157
+ articles_path = _download(repo_id, articles_file, cache_dir)
158
+ except EntryNotFoundError:
159
+ articles_path = None
160
  laws = pd.read_parquet(laws_path)
161
+ articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
162
  validate_laws(laws)
163
  validate_articles(articles)
164
  meta = {
165
  "source_dataset": repo_id,
166
  "source_revision": revision,
167
  "laws_path": str(laws_path),
168
+ "articles_path": str(articles_path) if articles_path is not None else None,
169
  "laws_sha256": sha256_file(laws_path),
170
+ "articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
171
  "n_laws_source": int(len(laws)),
172
  "n_articles_source": int(len(articles)),
173
  "laws_columns": list(map(str, laws.columns)),
country_laws_ir/package.py CHANGED
@@ -2,7 +2,9 @@
2
 
3
  from __future__ import annotations
4
 
 
5
  import json
 
6
  import shutil
7
  from pathlib import Path
8
  from typing import Any
@@ -32,6 +34,7 @@ def package_release(
32
  country: dict[str, Any],
33
  code_root: Path,
34
  normalization_report: dict[str, Any] | None = None,
 
35
  ) -> dict[str, Any]:
36
  if out.exists():
37
  shutil.rmtree(out)
@@ -322,6 +325,8 @@ def package_release(
322
  },
323
  "source": source_meta,
324
  }
 
 
325
  (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
326
  _write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
327
  _write_gitattributes(out)
@@ -528,3 +533,353 @@ python -m country_laws_ir query --local-dir /workspace/country-laws-ir/releases/
528
  Do not treat retrieval as proof. Do not invent citations.
529
  """
530
  (skill_dir / "SKILL.md").write_text(text, encoding="utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
5
+ import gc
6
  import json
7
+ import pickle
8
  import shutil
9
  from pathlib import Path
10
  from typing import Any
 
34
  country: dict[str, Any],
35
  code_root: Path,
36
  normalization_report: dict[str, Any] | None = None,
37
+ extra_manifest: dict[str, Any] | None = None,
38
  ) -> dict[str, Any]:
39
  if out.exists():
40
  shutil.rmtree(out)
 
325
  },
326
  "source": source_meta,
327
  }
328
+ if extra_manifest:
329
+ manifest.update(extra_manifest)
330
  (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
331
  _write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
332
  _write_gitattributes(out)
 
533
  Do not treat retrieval as proof. Do not invent citations.
534
  """
535
  (skill_dir / "SKILL.md").write_text(text, encoding="utf-8")
536
+
537
+
538
+ def package_release_sequential(
539
+ out: Path,
540
+ *,
541
+ corpus_path: Path,
542
+ bm25_documents_path: Path,
543
+ bm25_postings_path: Path,
544
+ bm25_stats: dict[str, Any],
545
+ graph: dict[str, Any] | Path,
546
+ vectors: dict[str, Any] | Path,
547
+ source_meta: dict[str, Any],
548
+ country: dict[str, Any],
549
+ code_root: Path,
550
+ normalization_report: dict[str, Any] | None = None,
551
+ expected_rows: int | None = None,
552
+ extra_manifest: dict[str, Any] | None = None,
553
+ ) -> dict[str, Any]:
554
+ """Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
555
+
556
+ ``graph`` / ``vectors`` may be in-memory dicts or pickle Paths.
557
+ Loads and frees each artifact before the next. Prefer this for n>=40k.
558
+ """
559
+ from .mem import checkpoint, log_mem
560
+
561
+ def _load_obj(obj_or_path):
562
+ if isinstance(obj_or_path, (str, Path)):
563
+ p = Path(obj_or_path)
564
+ with p.open("rb") as f:
565
+ return pickle.load(f)
566
+ return obj_or_path
567
+
568
+ if out.exists():
569
+ shutil.rmtree(out)
570
+ out.mkdir(parents=True, exist_ok=True)
571
+ indexes_dir = out / "indexes"
572
+ indexes_dir.mkdir(parents=True, exist_ok=True)
573
+ log_mem("package_seq_start")
574
+
575
+ # --- corpus ---
576
+ corpus = pd.read_parquet(corpus_path)
577
+ if expected_rows is not None and len(corpus) != expected_rows:
578
+ raise ValueError(f"corpus rows {len(corpus)} != expected {expected_rows}")
579
+ n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0
580
+ n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0
581
+ corpus_rows = int(len(corpus))
582
+ corpus_idx = write_sharded(
583
+ corpus, out / "data" / "corpus", "data/corpus",
584
+ kind="corpus", key_col="entry_cid", index_col="document_index",
585
+ )
586
+ write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
587
+ del corpus
588
+ gc.collect()
589
+ checkpoint("package_corpus_done")
590
+
591
+ # --- bm25 documents ---
592
+ documents = pd.read_parquet(bm25_documents_path)
593
+ bm25_doc_idx = write_sharded(
594
+ documents, out / "data" / "bm25" / "documents", "data/bm25/documents",
595
+ kind="bm25_documents", key_col="entry_cid", index_col="document_index",
596
+ )
597
+ write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
598
+ n_bm25_docs = int(len(documents))
599
+ del documents
600
+ gc.collect()
601
+
602
+ postings = pd.read_parquet(bm25_postings_path)
603
+ posting_idx = write_sharded(
604
+ postings, out / "data" / "bm25" / "postings", "data/bm25/postings",
605
+ kind="bm25_postings", key_col="term",
606
+ )
607
+ for row, part_start in zip(posting_idx, range(len(posting_idx))):
608
+ shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE]
609
+ row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
610
+ row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
611
+ row["token_instance_count"] = row["posting_count"]
612
+ write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
613
+ n_posting_rows = int(len(postings))
614
+ del postings
615
+ gc.collect()
616
+ checkpoint("package_bm25_done")
617
+
618
+ # --- graph ---
619
+ graph = _load_obj(graph)
620
+ node_idx = write_sharded(
621
+ graph["nodes"], out / "data" / "graph" / "nodes", "data/graph/nodes",
622
+ kind="graph_nodes", key_col="node_cid",
623
+ )
624
+ write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
625
+ edge_idx = write_sharded(
626
+ graph["edges"], out / "data" / "graph" / "edges", "data/graph/edges",
627
+ kind="graph_edges", key_col="edge_cid",
628
+ )
629
+ write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
630
+ incoming = graph["incoming"]
631
+ outgoing = graph["outgoing"]
632
+ in_idx = write_sharded(
633
+ incoming if incoming is not None and not incoming.empty else pd.DataFrame(
634
+ columns=["node_cid", "page_index", "direction"]
635
+ ),
636
+ out / "data" / "graph" / "adjacency" / "incoming",
637
+ "data/graph/adjacency/incoming",
638
+ kind="graph_incoming_adjacency",
639
+ key_col="node_cid",
640
+ )
641
+ out_idx = write_sharded(
642
+ outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame(
643
+ columns=["node_cid", "page_index", "direction"]
644
+ ),
645
+ out / "data" / "graph" / "adjacency" / "outgoing",
646
+ "data/graph/adjacency/outgoing",
647
+ kind="graph_outgoing_adjacency",
648
+ key_col="node_cid",
649
+ )
650
+ for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
651
+ for r in rows:
652
+ r["direction"] = direction
653
+ r["adjacency_count"] = r.get("row_count", 0)
654
+ r["node_count"] = r.get("row_count", 0)
655
+ r["first_page_index"] = 0
656
+ r["last_page_index"] = 0
657
+ write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
658
+ write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
659
+ gstats = graph["stats"]
660
+ n_graph_nodes = int(len(graph["nodes"]))
661
+ n_graph_edges = int(len(graph["edges"]))
662
+ n_in = int(len(incoming)) if incoming is not None else 0
663
+ n_out = int(len(outgoing)) if outgoing is not None else 0
664
+ edge_types = gstats.get("edge_types") or [
665
+ "HAS_JURISDICTION", "HAS_LANGUAGE", "BELONGS_TO_LAW", "HAS_ARTICLE", "BM25_NEIGHBOR_OF",
666
+ ]
667
+ del graph, incoming, outgoing
668
+ gc.collect()
669
+ checkpoint("package_graph_done")
670
+
671
+ # --- vectors ---
672
+ vectors = _load_obj(vectors)
673
+ vectors_df = vectors["vectors"]
674
+ if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all():
675
+ vectors_write = vectors_df.drop(columns=["embedding"])
676
+ vectors_write["embedding_status"] = "stub_missing"
677
+ else:
678
+ vectors_write = vectors_df
679
+ vec_idx = write_sharded(
680
+ vectors_write, out / "data" / "vectors", "data/vectors",
681
+ kind="vectors", key_col="entry_cid", index_col="document_index",
682
+ )
683
+ meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]}
684
+ for r in vec_idx:
685
+ m = meta_by_cluster.get(r["shard_id"], {})
686
+ r["centroid"] = m.get("centroid", [])
687
+ r["shard_centroid"] = m.get("shard_centroid", [])
688
+ r["centroid_min_score"] = m.get("centroid_min_score", 0.0)
689
+ r["centroid_shard_count"] = m.get("centroid_shard_count", 1)
690
+ r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0)
691
+ r["cluster_id"] = m.get("cluster_id", r["shard_id"])
692
+ r["dimension"] = 384
693
+ r["model_name"] = "thenlper/gte-small"
694
+ if m.get("stub"):
695
+ r["stub"] = True
696
+ r["stub_reason"] = m.get("stub_reason", "")
697
+ write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx))
698
+ vstats = vectors["stats"]
699
+ n_vectors = int(len(vectors_df))
700
+ del vectors, vectors_df, vectors_write
701
+ gc.collect()
702
+ checkpoint("package_vectors_done")
703
+
704
+ # --- bundle code ---
705
+ pkg_src = Path(__file__).resolve().parent
706
+ dest_pkg = out / "country_laws_ir"
707
+ shutil.copytree(
708
+ pkg_src, dest_pkg, dirs_exist_ok=True,
709
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"),
710
+ )
711
+ scripts_dir = out / "scripts"
712
+ scripts_dir.mkdir(exist_ok=True)
713
+ for name in (
714
+ "build_country_laws_ir.py", "normalize_country_laws.py",
715
+ "query_country_laws_hf.py", "query_country_laws_ir.py", "generate_country_laws_ir.py",
716
+ ):
717
+ src = code_root / "scripts" / name
718
+ if src.exists():
719
+ shutil.copy2(src, scripts_dir / name)
720
+ shutil.copy2(pkg_src / "normalize.py", out / "normalize.py")
721
+ shutil.copy2(pkg_src / "query.py", out / "query.py")
722
+ shutil.copy2(pkg_src / "build.py", out / "build.py")
723
+ hub_id = target_repo(country["slug"])
724
+ _write_skill(out, country, hub_id=hub_id)
725
+
726
+ reports_dir = out / "reports"
727
+ reports_dir.mkdir(exist_ok=True)
728
+ if normalization_report is not None:
729
+ payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n"
730
+ (out / "normalization_report.json").write_text(payload, encoding="utf-8")
731
+ (reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
732
+
733
+ counts = {
734
+ "bm25_document_chunks": len(bm25_doc_idx),
735
+ "bm25_documents": n_bm25_docs,
736
+ "bm25_keyword_shards": len(posting_idx),
737
+ "bm25_posting_rows": n_posting_rows,
738
+ "bm25_postings": int(bm25_stats["n_postings"]),
739
+ "bm25_terms": int(bm25_stats["n_terms"]),
740
+ "corpus_chunks": len(corpus_idx),
741
+ "corpus_rows": corpus_rows,
742
+ "graph_edge_chunks": len(edge_idx),
743
+ "graph_edges": n_graph_edges,
744
+ "graph_incoming_adjacency_edges": n_graph_edges,
745
+ "graph_incoming_adjacency_rows": n_in,
746
+ "graph_incoming_adjacency_shards": len(in_idx),
747
+ "graph_node_chunks": len(node_idx),
748
+ "graph_nodes": n_graph_nodes,
749
+ "graph_outgoing_adjacency_edges": n_graph_edges,
750
+ "graph_outgoing_adjacency_rows": n_out,
751
+ "graph_outgoing_adjacency_shards": len(out_idx),
752
+ "vector_chunks": len(vec_idx),
753
+ "vector_rows": n_vectors,
754
+ "n_laws": n_laws,
755
+ "n_articles": n_articles,
756
+ }
757
+
758
+ def idx_desc(name: str) -> dict[str, Any]:
759
+ path = indexes_dir / name
760
+ return file_descriptor(path, f"indexes/{name}")
761
+
762
+ manifest = {
763
+ "schema_version": SCHEMA_VERSION,
764
+ "layout_family": LAYOUT_FAMILY,
765
+ "packager_version": __version__,
766
+ "primary_key": "entry_cid",
767
+ "dataset_id": source_meta["source_dataset"],
768
+ "dataset_repo_id": hub_id,
769
+ "dataset_revision": source_meta["source_revision"],
770
+ "country": country,
771
+ "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
772
+ "bm25": {k: bm25_stats[k] for k in (
773
+ "k1", "b", "title_weight", "body_weight", "average_document_length",
774
+ "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
775
+ ) if k in bm25_stats},
776
+ "counts": counts,
777
+ "parquet": {
778
+ "compression": "zstd",
779
+ "compression_level": 6,
780
+ "max_rows_per_file": MAX_ROWS_PER_FILE,
781
+ "row_group_size": MAX_ROWS_PER_FILE,
782
+ },
783
+ "graph": {
784
+ "adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
785
+ "adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD,
786
+ "directions": ["incoming", "outgoing"],
787
+ "max_remote_walk_depth": 8,
788
+ "ordering": "score_desc_nulls_last",
789
+ "edge_types": edge_types,
790
+ },
791
+ "vector": vstats,
792
+ "canonical_fields": [
793
+ "entry_cid", "law_cid", "record_type", "jurisdiction", "language",
794
+ "instrument_id", "instrument_title", "article_number", "article_title",
795
+ "title", "body", "source_url", "snapshot_date", "coverage", "license",
796
+ "collector", "source_dataset", "source_revision",
797
+ ],
798
+ "input_sha256": {
799
+ "laws.parquet": source_meta.get("laws_sha256"),
800
+ "articles.parquet": source_meta.get("articles_sha256"),
801
+ },
802
+ "model_id": (vstats or {}).get("model_name", "thenlper/gte-small"),
803
+ "cid": {
804
+ "codec": "raw",
805
+ "hash": "sha2-256",
806
+ "multibase": "base32",
807
+ "payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')",
808
+ },
809
+ "normalization": normalization_report or {},
810
+ "packaging_mode": "sequential_spill",
811
+ "schema_mapping": {
812
+ "laws": {
813
+ "id": "instrument_id", "title": "instrument_title", "text": "body",
814
+ "article_count_dtype_source": source_meta.get("article_count_dtype"),
815
+ },
816
+ "articles": {
817
+ "id": "source_id / article identity", "law_id": "instrument_id",
818
+ "title": "article_title", "text": "body",
819
+ },
820
+ "unit_policy": "prefer articles; fall back to law-level when articles empty",
821
+ "required_law_columns": ["id", "title", "text"],
822
+ "required_article_columns": ["id", "law_id", "title", "text"],
823
+ "fail_closed": True,
824
+ "notes": (
825
+ "Malta and Germany share the same column names. Drift: Malta article_count "
826
+ "is int64, Germany article_count is int32; Germany eli is often null. "
827
+ "Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family."
828
+ ),
829
+ },
830
+ "indexes": {
831
+ "bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"),
832
+ "bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"),
833
+ "corpus_chunks": idx_desc("corpus_chunks.parquet"),
834
+ "graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"),
835
+ "graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"),
836
+ "graph_node_chunks": idx_desc("graph_node_chunks.parquet"),
837
+ "graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"),
838
+ "vector_chunks": idx_desc("vector_chunks.parquet"),
839
+ },
840
+ "source": source_meta,
841
+ }
842
+ if extra_manifest:
843
+ manifest.update(extra_manifest)
844
+ (out / "manifest.json").write_text(
845
+ json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
846
+ )
847
+ _write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
848
+ _write_gitattributes(out)
849
+ checkpoint("package_seq_done")
850
+ return manifest
851
+
852
+
853
+ def package_from_spill(
854
+ out: Path,
855
+ spill: Path,
856
+ corpus_path: Path,
857
+ source_meta: dict[str, Any],
858
+ country: dict[str, Any],
859
+ code_root: Path,
860
+ normalization_report: dict[str, Any] | None = None,
861
+ expected_rows: int | None = None,
862
+ extra_manifest: dict[str, Any] | None = None,
863
+ ) -> dict[str, Any]:
864
+ """Package from spill dir artifacts: bm25_*.parquet, bm25_stats.pkl, graph.pkl, vectors.pkl."""
865
+ import pickle as _pickle
866
+
867
+ spill = Path(spill)
868
+ stats_path = spill / "bm25_stats.pkl"
869
+ with stats_path.open("rb") as f:
870
+ bm25_stats = _pickle.load(f)
871
+ return package_release_sequential(
872
+ out,
873
+ corpus_path=Path(corpus_path),
874
+ bm25_documents_path=spill / "bm25_documents.parquet",
875
+ bm25_postings_path=spill / "bm25_postings.parquet",
876
+ bm25_stats=bm25_stats,
877
+ graph=spill / "graph.pkl",
878
+ vectors=spill / "vectors.pkl",
879
+ source_meta=source_meta,
880
+ country=country,
881
+ code_root=Path(code_root),
882
+ normalization_report=normalization_report,
883
+ expected_rows=expected_rows,
884
+ extra_manifest=extra_manifest,
885
+ )
country_laws_ir/raw_package.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incrementally package raw collector instruments into laws/articles parquet.
2
+
3
+ Collectors write one JSON instrument per official page under
4
+ ``$LEGAL_CORPORA_ROOT/<iso>/instruments/*.json``. Those files grow as new
5
+ pages are scraped. This module merges them into the ``endomorphosis/ipfs_*_laws``
6
+ parquet schema without rewriting unchanged rows, so the GraphRAG builder can
7
+ delta-rebuild from the resulting pack.
8
+
9
+ Never invents legal text or identifiers. Empty/short bodies are dropped, not
10
+ filled.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import pandas as pd
22
+
23
+ from .cidutil import sha256_file
24
+ from .schema import LAW_FIELD_MAP, REQUIRED_ARTICLE_COLUMNS, REQUIRED_LAW_COLUMNS
25
+
26
+ LAW_COLS = [
27
+ "id",
28
+ "title",
29
+ "text",
30
+ "source_url",
31
+ "source_type",
32
+ "jurisdiction",
33
+ "country",
34
+ "language",
35
+ "eli",
36
+ "date",
37
+ "date_issued",
38
+ "retrieved_at",
39
+ "license",
40
+ "law_status",
41
+ "identifier",
42
+ "official_identifier",
43
+ "article_count",
44
+ "json_path",
45
+ "metadata_json",
46
+ ]
47
+ ART_COLS = [
48
+ "law_id",
49
+ "id",
50
+ "title",
51
+ "text",
52
+ "source_url",
53
+ "document_number",
54
+ "article_number",
55
+ "record_type",
56
+ "metadata_json",
57
+ ]
58
+
59
+ MIN_BODY_CHARS = 80
60
+ DEFAULT_CORPORA_ROOT = Path(
61
+ os.environ.get(
62
+ "LEGAL_CORPORA_ROOT",
63
+ str(Path.home() / ".ipfs_datasets" / "legal-corpora"),
64
+ )
65
+ )
66
+
67
+
68
+ def _s(value: Any) -> str:
69
+ if value is None:
70
+ return ""
71
+ return str(value).strip()
72
+
73
+
74
+ def _meta_json(value: Any) -> str:
75
+ if isinstance(value, str):
76
+ return value
77
+ try:
78
+ return json.dumps(value or {}, ensure_ascii=False)
79
+ except Exception:
80
+ return "{}"
81
+
82
+
83
+ def instruments_to_frames(
84
+ instruments_dir: Path,
85
+ *,
86
+ min_body_chars: int = MIN_BODY_CHARS,
87
+ ) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
88
+ """Read collector JSON instruments into laws/articles dataframes."""
89
+ laws: list[dict[str, Any]] = []
90
+ arts: list[dict[str, Any]] = []
91
+ skipped_short = 0
92
+ skipped_bad = 0
93
+ root = Path(instruments_dir)
94
+ files = sorted(root.glob("*.json")) if root.is_dir() else []
95
+ for path in files:
96
+ try:
97
+ rec = json.loads(path.read_text(encoding="utf-8"))
98
+ except Exception:
99
+ skipped_bad += 1
100
+ continue
101
+ if not isinstance(rec, dict):
102
+ skipped_bad += 1
103
+ continue
104
+ text = _s(rec.get("text"))
105
+ ident = _s(rec.get("id"))
106
+ title = _s(rec.get("title"))
107
+ if not ident or not title or len(text) < min_body_chars:
108
+ skipped_short += 1
109
+ continue
110
+ meta = rec.get("metadata") or {}
111
+ laws.append(
112
+ {
113
+ "id": ident,
114
+ "title": title,
115
+ "text": text,
116
+ "source_url": _s(rec.get("source_url")),
117
+ "source_type": _s(rec.get("source_type")),
118
+ "jurisdiction": _s(rec.get("jurisdiction")),
119
+ "country": _s(rec.get("country")),
120
+ "language": _s(rec.get("language")),
121
+ "eli": _s(rec.get("eli")) or None,
122
+ "date": _s(rec.get("date")) or None,
123
+ "date_issued": _s(rec.get("date_issued") or rec.get("date")) or None,
124
+ "retrieved_at": _s(rec.get("retrieved_at")) or None,
125
+ "license": _s(rec.get("license")),
126
+ "law_status": _s(rec.get("law_status")),
127
+ "identifier": _s(rec.get("identifier")) or ident,
128
+ "official_identifier": _s(rec.get("official_identifier")),
129
+ "article_count": rec.get("article_count") or len(rec.get("documents") or []),
130
+ "json_path": f"instruments/{path.name}",
131
+ "metadata_json": _meta_json(meta),
132
+ }
133
+ )
134
+ for doc in rec.get("documents") or []:
135
+ if not isinstance(doc, dict):
136
+ continue
137
+ art_id = _s(doc.get("id"))
138
+ art_title = _s(doc.get("title"))
139
+ art_text = _s(doc.get("text"))
140
+ if not art_id or not art_title or not art_text:
141
+ continue
142
+ arts.append(
143
+ {
144
+ "law_id": ident,
145
+ "id": art_id,
146
+ "title": art_title,
147
+ "text": art_text,
148
+ "source_url": _s(doc.get("source_url")) or _s(rec.get("source_url")),
149
+ "document_number": _s(doc.get("document_number")),
150
+ "article_number": _s(doc.get("article_number")),
151
+ "record_type": _s(doc.get("record_type")) or "article",
152
+ "metadata_json": _meta_json(doc.get("metadata") or {}),
153
+ }
154
+ )
155
+ report = {
156
+ "n_instrument_files": len(files),
157
+ "n_laws": len(laws),
158
+ "n_articles": len(arts),
159
+ "skipped_short_or_empty": skipped_short,
160
+ "skipped_unreadable": skipped_bad,
161
+ "min_body_chars": min_body_chars,
162
+ "never_invented_legal_text": True,
163
+ "required_law_columns": list(REQUIRED_LAW_COLUMNS),
164
+ "required_article_columns": list(REQUIRED_ARTICLE_COLUMNS),
165
+ "law_field_map": dict(LAW_FIELD_MAP),
166
+ }
167
+ return (
168
+ pd.DataFrame(laws, columns=LAW_COLS),
169
+ pd.DataFrame(arts, columns=ART_COLS),
170
+ report,
171
+ )
172
+
173
+
174
+ def _retrieved_key(value: Any) -> str:
175
+ return _s(value)
176
+
177
+
178
+ def merge_laws(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame:
179
+ """Upsert laws by ``id``. Newer ``retrieved_at`` wins; otherwise incoming wins."""
180
+ if prior is None or prior.empty:
181
+ return incoming.copy() if incoming is not None else pd.DataFrame(columns=LAW_COLS)
182
+ if incoming is None or incoming.empty:
183
+ return prior.copy()
184
+ by_id: dict[str, dict[str, Any]] = {}
185
+ for frame, incoming_flag in ((prior, False), (incoming, True)):
186
+ for rec in frame.to_dict(orient="records"):
187
+ ident = _s(rec.get("id"))
188
+ if not ident:
189
+ continue
190
+ existing = by_id.get(ident)
191
+ if existing is None:
192
+ by_id[ident] = rec
193
+ continue
194
+ if incoming_flag:
195
+ new_ts = _retrieved_key(rec.get("retrieved_at"))
196
+ old_ts = _retrieved_key(existing.get("retrieved_at"))
197
+ if not old_ts or new_ts >= old_ts:
198
+ by_id[ident] = rec
199
+ rows = [by_id[k] for k in sorted(by_id)]
200
+ return pd.DataFrame(rows, columns=LAW_COLS)
201
+
202
+
203
+ def merge_articles(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame:
204
+ """Upsert articles by ``id``. Incoming replaces the same article id."""
205
+ if prior is None or prior.empty:
206
+ return incoming.copy() if incoming is not None else pd.DataFrame(columns=ART_COLS)
207
+ if incoming is None or incoming.empty:
208
+ return prior.copy()
209
+ by_id: dict[str, dict[str, Any]] = {}
210
+ for frame in (prior, incoming):
211
+ for rec in frame.to_dict(orient="records"):
212
+ ident = _s(rec.get("id"))
213
+ if not ident:
214
+ continue
215
+ by_id[ident] = rec
216
+ rows = [by_id[k] for k in sorted(by_id)]
217
+ return pd.DataFrame(rows, columns=ART_COLS)
218
+
219
+
220
+ def load_existing_parquet(pack_dir: Path) -> tuple[pd.DataFrame | None, pd.DataFrame | None]:
221
+ pack_dir = Path(pack_dir)
222
+ laws_path = None
223
+ arts_path = None
224
+ for cand in (pack_dir / "data" / "laws.parquet", pack_dir / "laws.parquet"):
225
+ if cand.is_file():
226
+ laws_path = cand
227
+ break
228
+ for cand in (pack_dir / "data" / "articles.parquet", pack_dir / "articles.parquet"):
229
+ if cand.is_file():
230
+ arts_path = cand
231
+ break
232
+ laws = pd.read_parquet(laws_path) if laws_path else None
233
+ arts = pd.read_parquet(arts_path) if arts_path else None
234
+ return laws, arts
235
+
236
+
237
+ def write_pack(
238
+ out: Path,
239
+ laws: pd.DataFrame,
240
+ articles: pd.DataFrame,
241
+ *,
242
+ slug: str,
243
+ source_dataset: str,
244
+ name: str | None = None,
245
+ extra_meta: dict[str, Any] | None = None,
246
+ ) -> dict[str, Any]:
247
+ """Write a local pack that ``load_source`` / ``get_country`` can consume."""
248
+ out = Path(out)
249
+ data_dir = out / "data"
250
+ data_dir.mkdir(parents=True, exist_ok=True)
251
+ laws_path = data_dir / "laws.parquet"
252
+ arts_path = data_dir / "articles.parquet"
253
+ laws.to_parquet(laws_path, index=False)
254
+ articles.to_parquet(arts_path, index=False)
255
+ now = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
256
+ meta = {
257
+ "slug": slug,
258
+ "repo": source_dataset,
259
+ "source_dataset": source_dataset,
260
+ "name": name or slug.replace("_", " ").title(),
261
+ "indexable": True,
262
+ "source_revision": f"local:{now}",
263
+ "n_laws": int(len(laws)),
264
+ "n_articles": int(len(articles)),
265
+ "laws_sha256": sha256_file(laws_path),
266
+ "articles_sha256": sha256_file(arts_path),
267
+ "generated_at": now,
268
+ "incremental": True,
269
+ }
270
+ if extra_meta:
271
+ meta.update(extra_meta)
272
+ (out / "pack_meta.json").write_text(
273
+ json.dumps(meta, indent=2, ensure_ascii=False) + "\n",
274
+ encoding="utf-8",
275
+ )
276
+ return meta
277
+
278
+
279
+ def package_instruments(
280
+ *,
281
+ instruments_dir: Path,
282
+ out: Path,
283
+ slug: str,
284
+ source_dataset: str | None = None,
285
+ prior_pack: Path | None = None,
286
+ name: str | None = None,
287
+ min_body_chars: int = MIN_BODY_CHARS,
288
+ ) -> dict[str, Any]:
289
+ """Merge collector JSON (+ optional prior parquet) into a local IR source pack."""
290
+ incoming_laws, incoming_arts, extract_report = instruments_to_frames(
291
+ instruments_dir, min_body_chars=min_body_chars
292
+ )
293
+ prior_laws = prior_arts = None
294
+ prior_dir = Path(prior_pack) if prior_pack else (out if out.exists() else None)
295
+ if prior_dir is not None:
296
+ prior_laws, prior_arts = load_existing_parquet(prior_dir)
297
+ laws = merge_laws(prior_laws, incoming_laws)
298
+ articles = merge_articles(prior_arts, incoming_arts)
299
+ if laws.empty:
300
+ raise RuntimeError(
301
+ f"no laws with text>={min_body_chars} under {instruments_dir}"
302
+ )
303
+ repo = source_dataset or f"endomorphosis/ipfs_{slug}_laws"
304
+ meta = write_pack(
305
+ out,
306
+ laws,
307
+ articles,
308
+ slug=slug,
309
+ source_dataset=repo,
310
+ name=name,
311
+ extra_meta={"extract": extract_report},
312
+ )
313
+ meta["extract"] = extract_report
314
+ meta["n_laws_prior"] = int(len(prior_laws)) if prior_laws is not None else 0
315
+ meta["n_articles_prior"] = int(len(prior_arts)) if prior_arts is not None else 0
316
+ meta["n_laws_incoming"] = int(len(incoming_laws))
317
+ meta["n_articles_incoming"] = int(len(incoming_arts))
318
+ meta["out"] = str(out)
319
+ return meta
320
+
321
+
322
+ def default_instruments_dir(iso_or_slug: str, root: Path | None = None) -> Path:
323
+ base = Path(root) if root is not None else DEFAULT_CORPORA_ROOT
324
+ return base / iso_or_slug / "instruments"
country_laws_ir/spill.py ADDED
@@ -0,0 +1,763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Disk-spill helpers for large country IR builds (SQLite FTS neighbors + BM25 TF).
2
+
3
+ Design (CoS / DO OOM lesson):
4
+ - Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).
5
+ - Neighbors for n >= SQLITE_THRESHOLD (40k): SQLite FTS5 title-only MATCH streaming
6
+ into neighbor_*.pkl shards under cache/<slug>_bm25_spill/ — never hold full
7
+ neighbor matrix in RAM during streaming.
8
+ - BM25 TF: stream tokenize → SQLite WITHOUT ROWID → posting parquet parts.
9
+ - Package: use package.package_release_sequential / package_from_spill so corpus,
10
+ bm25, graph, vectors are never all resident together; neighbor edges can be
11
+ streamed from shards into graph then spilled as graph.pkl.
12
+
13
+ Resume-safe: existing FTS DB / neighbor shards / bm25_*.parquet are reused when
14
+ row counts match.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import gc
19
+ import json
20
+ import math
21
+ import pickle
22
+ import sqlite3
23
+ from collections import defaultdict
24
+ from pathlib import Path
25
+ from typing import Any, Callable, Iterable, Iterator
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ import pyarrow.parquet as pq
30
+
31
+ from . import SCHEMA_VERSION
32
+ from .bm25 import (
33
+ B,
34
+ BODY_WEIGHT,
35
+ K1,
36
+ POSTING_ROWS_PER_RECORD,
37
+ TERMS_PER_SHARD,
38
+ TITLE_WEIGHT,
39
+ )
40
+ from .graph import _adjacency, _edge, build_graph
41
+ from .mem import MemAbort, checkpoint, log_mem
42
+ from .tokenize import tokenize
43
+
44
+ SQLITE_THRESHOLD = 40_000
45
+ BATCH = 256
46
+ NEIGHBOR_SHARD = 5_000
47
+ NEIGHBOR_K = 8
48
+ DF_CAP = 1500
49
+ MAX_QTERMS = 8
50
+ TITLE_W = TITLE_WEIGHT
51
+ BODY_W = BODY_WEIGHT
52
+
53
+
54
+ def spill_dir_for(slug: str, cache: Path) -> Path:
55
+ return Path(cache) / f"{slug}_bm25_spill"
56
+
57
+
58
+ def spill_pickle(path: Path, obj: Any) -> None:
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ tmp = path.with_suffix(path.suffix + ".tmp")
61
+ with tmp.open("wb") as f:
62
+ pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
63
+ tmp.replace(path)
64
+
65
+
66
+ def load_pickle(path: Path) -> Any:
67
+ with path.open("rb") as f:
68
+ return pickle.load(f)
69
+
70
+
71
+ def quote_fts_term(term: str) -> str:
72
+ return '"' + term.replace('"', '""') + '"'
73
+
74
+
75
+ def _idf(n_docs: int, df: int) -> float:
76
+ return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
77
+
78
+
79
+ def sqlite_ready(db_path: Path, expected: int) -> bool:
80
+ if not db_path.is_file():
81
+ return False
82
+ try:
83
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
84
+ n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
85
+ conn.close()
86
+ return n == expected
87
+ except Exception:
88
+ return False
89
+
90
+
91
+ def build_sqlite_fts(
92
+ corpus_path: Path,
93
+ db_path: Path,
94
+ expected: int,
95
+ *,
96
+ batch: int = BATCH,
97
+ log: Callable[[str], None] | None = None,
98
+ ) -> int:
99
+ """Contentless FTS5 over title+body; documents table holds query_text."""
100
+ if db_path.exists():
101
+ db_path.unlink()
102
+ db_path.parent.mkdir(parents=True, exist_ok=True)
103
+ conn = sqlite3.connect(str(db_path))
104
+ try:
105
+ conn.executescript(
106
+ """
107
+ PRAGMA journal_mode = OFF;
108
+ PRAGMA synchronous = OFF;
109
+ PRAGMA temp_store = MEMORY;
110
+ PRAGMA locking_mode = EXCLUSIVE;
111
+ PRAGMA page_size = 32768;
112
+ CREATE TABLE documents (
113
+ document_index INTEGER PRIMARY KEY,
114
+ entry_cid TEXT NOT NULL UNIQUE,
115
+ title TEXT NOT NULL,
116
+ query_text TEXT NOT NULL
117
+ );
118
+ CREATE VIRTUAL TABLE documents_fts USING fts5(
119
+ title,
120
+ body,
121
+ content='',
122
+ columnsize=1,
123
+ tokenize='unicode61 remove_diacritics 2'
124
+ );
125
+ """
126
+ )
127
+ pf = pq.ParquetFile(corpus_path)
128
+ n = 0
129
+ meta_batch: list[tuple] = []
130
+ fts_batch: list[tuple] = []
131
+ conn.execute("BEGIN")
132
+ for batch_tbl in pf.iter_batches(
133
+ batch_size=batch, columns=["document_index", "entry_cid", "title", "body"]
134
+ ):
135
+ cols = batch_tbl.to_pydict()
136
+ for i in range(len(cols["document_index"])):
137
+ di = int(cols["document_index"][i])
138
+ title = str(cols["title"][i] or "")
139
+ body = str(cols["body"][i] or "")
140
+ cid = str(cols["entry_cid"][i])
141
+ qtext = title.strip() if title.strip() else body[:800]
142
+ meta_batch.append((di, cid, title, qtext))
143
+ fts_batch.append((di + 1, title, body))
144
+ if len(meta_batch) >= batch:
145
+ conn.executemany(
146
+ "INSERT INTO documents(document_index, entry_cid, title, query_text) "
147
+ "VALUES (?,?,?,?)",
148
+ meta_batch,
149
+ )
150
+ conn.executemany(
151
+ "INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)",
152
+ fts_batch,
153
+ )
154
+ n += len(meta_batch)
155
+ meta_batch.clear()
156
+ fts_batch.clear()
157
+ if n % 20_000 == 0:
158
+ checkpoint(f"fts_insert@{n}", row=n, every_n=20_000, log=log)
159
+ gc.collect()
160
+ if meta_batch:
161
+ conn.executemany(
162
+ "INSERT INTO documents(document_index, entry_cid, title, query_text) "
163
+ "VALUES (?,?,?,?)",
164
+ meta_batch,
165
+ )
166
+ conn.executemany(
167
+ "INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)",
168
+ fts_batch,
169
+ )
170
+ n += len(meta_batch)
171
+ conn.commit()
172
+ conn.execute("INSERT INTO documents_fts(documents_fts) VALUES('optimize')")
173
+ conn.commit()
174
+ conn.execute(
175
+ "CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')"
176
+ )
177
+ conn.commit()
178
+ got = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
179
+ assert got == n == expected, (got, n, expected)
180
+ return n
181
+ except Exception:
182
+ conn.rollback()
183
+ raise
184
+ finally:
185
+ conn.close()
186
+ gc.collect()
187
+
188
+
189
+ def load_df_map(conn: sqlite3.Connection, df_cap: int = DF_CAP) -> dict[str, int]:
190
+ df_map: dict[str, int] = {}
191
+ for term, doc in conn.execute(
192
+ "SELECT term, doc FROM documents_vocab WHERE doc <= ?", (df_cap,)
193
+ ):
194
+ df_map[str(term)] = int(doc)
195
+ return df_map
196
+
197
+
198
+ def select_query_terms(query_text: str, df_map: dict[str, int]) -> list[str]:
199
+ toks = tokenize(query_text)[:24]
200
+ seen: set[str] = set()
201
+ cands: list[tuple[int, str]] = []
202
+ for t in toks:
203
+ if t in seen or len(t) < 2:
204
+ continue
205
+ seen.add(t)
206
+ if t not in df_map:
207
+ continue
208
+ cands.append((df_map[t], t))
209
+ cands.sort()
210
+ return [t for _, t in cands[:MAX_QTERMS]]
211
+
212
+
213
+ def stream_neighbors_to_shards(
214
+ db_path: Path,
215
+ spill: Path,
216
+ n_docs: int,
217
+ *,
218
+ k: int = NEIGHBOR_K,
219
+ shard: int = NEIGHBOR_SHARD,
220
+ batch: int = BATCH,
221
+ df_cap: int = DF_CAP,
222
+ resume: bool = True,
223
+ log: Callable[[str], None] | None = None,
224
+ ) -> list[Path]:
225
+ """Stream FTS5 title-only neighbors into neighbor_START_END.pkl shards.
226
+
227
+ Does not assemble the full neighbor list. Resume skips shards already on disk
228
+ whose end index is covered (contiguous from 0).
229
+ """
230
+ spill.mkdir(parents=True, exist_ok=True)
231
+ existing = sorted(spill.glob("neighbors_*.pkl"))
232
+ buf_start = 0
233
+ shard_paths: list[Path] = []
234
+ if resume and existing:
235
+ # Contiguous cover from 0
236
+ covered = 0
237
+ for sp in existing:
238
+ parts = sp.stem.split("_")
239
+ # neighbors_000000_005000
240
+ try:
241
+ start_i, end_i = int(parts[1]), int(parts[2])
242
+ except (IndexError, ValueError):
243
+ continue
244
+ if start_i != covered:
245
+ break
246
+ shard_paths.append(sp)
247
+ covered = end_i
248
+ buf_start = covered
249
+ if buf_start >= n_docs:
250
+ if log:
251
+ log(f"neighbors resume complete {buf_start}/{n_docs}")
252
+ return shard_paths
253
+ if log:
254
+ log(f"neighbors resume from {buf_start}/{n_docs} shards={len(shard_paths)}")
255
+ # Drop non-contiguous leftover shards beyond covered
256
+ for sp in existing:
257
+ if sp not in shard_paths:
258
+ sp.unlink(missing_ok=True)
259
+ else:
260
+ for sp in existing:
261
+ sp.unlink(missing_ok=True)
262
+
263
+ conn_rw = sqlite3.connect(str(db_path))
264
+ row = conn_rw.execute(
265
+ "SELECT name FROM sqlite_master WHERE name='documents_vocab'"
266
+ ).fetchone()
267
+ if row is None:
268
+ conn_rw.execute(
269
+ "CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')"
270
+ )
271
+ conn_rw.commit()
272
+ df_map = load_df_map(conn_rw, df_cap)
273
+ conn_rw.close()
274
+ spill_pickle(spill / "df_map_meta.pkl", {"n_rare": len(df_map), "df_cap": df_cap})
275
+ if log:
276
+ log(f"vocab rare_terms={len(df_map)} df_cap={df_cap}")
277
+
278
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
279
+ conn.row_factory = sqlite3.Row
280
+ buf: list = []
281
+ done = buf_start
282
+ score_sql = f"-bm25(documents_fts, {TITLE_W}, {BODY_W})"
283
+ last_idx = buf_start - 1
284
+ try:
285
+ while True:
286
+ rows = conn.execute(
287
+ "SELECT document_index, entry_cid, query_text FROM documents "
288
+ "WHERE document_index > ? ORDER BY document_index LIMIT ?",
289
+ (last_idx, batch),
290
+ ).fetchall()
291
+ if not rows:
292
+ break
293
+ for row in rows:
294
+ di = int(row["document_index"])
295
+ terms = select_query_terms(str(row["query_text"]), df_map)
296
+ if not terms:
297
+ neigh: list = []
298
+ else:
299
+ expr = " OR ".join("title : " + quote_fts_term(t) for t in terms)
300
+ sql = (
301
+ "SELECT d.document_index, " + score_sql + " AS score "
302
+ "FROM documents_fts "
303
+ "JOIN documents AS d ON d.document_index = documents_fts.rowid - 1 "
304
+ "WHERE documents_fts MATCH ? AND d.document_index != ? "
305
+ "ORDER BY score DESC, d.document_index LIMIT ?"
306
+ )
307
+ hits = conn.execute(sql, (expr, di, k)).fetchall()
308
+ neigh = [
309
+ (int(h["document_index"]), max(0.0, float(h["score"])), list(terms)[:4])
310
+ for h in hits
311
+ ]
312
+ while buf_start + len(buf) < di:
313
+ buf.append([])
314
+ buf.append(neigh)
315
+ last_idx = di
316
+ done += 1
317
+ if len(buf) >= shard:
318
+ end = buf_start + len(buf)
319
+ sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl"
320
+ spill_pickle(sp, buf)
321
+ shard_paths.append(sp)
322
+ checkpoint(
323
+ f"neighbors_shard_{buf_start}_{end}",
324
+ log=log,
325
+ )
326
+ buf_start = end
327
+ buf = []
328
+ gc.collect()
329
+ if done % 5_000 == 0:
330
+ checkpoint(f"neighbors_stream", row=done, every_n=5_000, log=log)
331
+ if buf:
332
+ end = buf_start + len(buf)
333
+ sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl"
334
+ spill_pickle(sp, buf)
335
+ shard_paths.append(sp)
336
+ if log:
337
+ log(f"neighbors shard final {buf_start}:{end}/{n_docs}")
338
+ if log:
339
+ log(f"bm25 neighbors streamed done={done} n_docs={n_docs} shards={len(shard_paths)}")
340
+ return shard_paths
341
+ finally:
342
+ conn.close()
343
+ del df_map
344
+ gc.collect()
345
+
346
+
347
+ def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]:
348
+ """Yield (start_index, shard_list) without loading all shards."""
349
+ paths = sorted(spill.glob("neighbors_*.pkl"))
350
+ for sp in paths:
351
+ parts = sp.stem.split("_")
352
+ start_i = int(parts[1])
353
+ yield start_i, load_pickle(sp)
354
+
355
+
356
+ def assemble_neighbors_streaming(spill: Path, n_docs: int) -> list:
357
+ """Assemble only when unavoidable; prefer build_graph_from_neighbor_shards."""
358
+ neighbors: list = []
359
+ for start_i, part in iter_neighbor_shards(spill):
360
+ while len(neighbors) < start_i:
361
+ neighbors.append([])
362
+ neighbors.extend(part)
363
+ del part
364
+ gc.collect()
365
+ while len(neighbors) < n_docs:
366
+ neighbors.append([])
367
+ if len(neighbors) > n_docs:
368
+ neighbors = neighbors[:n_docs]
369
+ return neighbors
370
+
371
+
372
+ def neighbors_via_sqlite(
373
+ corpus_path: Path,
374
+ spill: Path,
375
+ n_docs: int,
376
+ *,
377
+ k: int = NEIGHBOR_K,
378
+ resume: bool = True,
379
+ log: Callable[[str], None] | None = None,
380
+ ) -> list[Path]:
381
+ """Ensure FTS DB + neighbor shards; return shard paths (not full list)."""
382
+ spill.mkdir(parents=True, exist_ok=True)
383
+ db_path = spill / "fts.sqlite"
384
+ if not sqlite_ready(db_path, n_docs):
385
+ if db_path.exists():
386
+ db_path.unlink()
387
+ if log:
388
+ log(f"building sqlite fts n={n_docs} -> {db_path}")
389
+ build_sqlite_fts(corpus_path, db_path, n_docs, log=log)
390
+ else:
391
+ if log:
392
+ log(f"reusing sqlite fts n={n_docs} path={db_path}")
393
+ return stream_neighbors_to_shards(
394
+ db_path, spill, n_docs, k=k, resume=resume, log=log
395
+ )
396
+
397
+
398
+ def build_graph_from_neighbor_shards(
399
+ corpus: pd.DataFrame,
400
+ spill: Path,
401
+ *,
402
+ log: Callable[[str], None] | None = None,
403
+ ) -> dict[str, Any]:
404
+ """Build graph without holding the full neighbor list.
405
+
406
+ Structural edges first (neighbors=[]), then stream BM25_NEIGHBOR_OF from shards
407
+ and recompute adjacency once.
408
+ """
409
+ n = len(corpus)
410
+ # Structural + facets only
411
+ graph = build_graph(corpus, [[] for _ in range(n)])
412
+ cid_by_idx = corpus["entry_cid"].tolist()
413
+ extra_edges: list[dict[str, Any]] = []
414
+ seen = 0
415
+ for start_i, part in iter_neighbor_shards(spill):
416
+ for offset, neigh in enumerate(part):
417
+ i = start_i + offset
418
+ if i >= n:
419
+ break
420
+ src = cid_by_idx[i]
421
+ for item in neigh:
422
+ if len(item) == 3:
423
+ j, score, terms = item
424
+ else:
425
+ j, score = item[0], item[1]
426
+ terms = []
427
+ tgt = cid_by_idx[int(j)]
428
+ extra_edges.append(
429
+ _edge(
430
+ src,
431
+ "BM25_NEIGHBOR_OF",
432
+ tgt,
433
+ "bm25-okapi",
434
+ float(score),
435
+ {"k": 8, "neighbor_index": int(j)},
436
+ matched_terms=list(terms),
437
+ )
438
+ )
439
+ seen += len(part)
440
+ del part
441
+ if len(extra_edges) >= 50_000:
442
+ # Flush into edges df incrementally
443
+ add = pd.DataFrame(extra_edges)
444
+ graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True)
445
+ extra_edges.clear()
446
+ del add
447
+ gc.collect()
448
+ checkpoint(f"graph_neighbor_edges@{seen}", row=seen, every_n=50_000, log=log)
449
+ if extra_edges:
450
+ add = pd.DataFrame(extra_edges)
451
+ graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True)
452
+ del add, extra_edges
453
+ gc.collect()
454
+
455
+ edges_df = graph["edges"]
456
+ if not edges_df.empty:
457
+ edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True)
458
+ edges_df = edges_df.sort_values(
459
+ ["edge_type", "source_cid", "target_cid"]
460
+ ).reset_index(drop=True)
461
+ graph["edges"] = edges_df
462
+ node_type = {r["node_cid"]: r["node_type"] for r in graph["nodes"].to_dict("records")}
463
+ incoming, outgoing = _adjacency(edges_df, node_type)
464
+ graph["incoming"] = incoming
465
+ graph["outgoing"] = outgoing
466
+ graph["stats"] = {
467
+ "n_nodes": int(len(graph["nodes"])),
468
+ "n_edges": int(len(edges_df)),
469
+ "n_doc_nodes": int(
470
+ graph["nodes"]["node_type"].isin(["law_entry", "article", "law"]).sum()
471
+ ),
472
+ "n_facet_nodes": int(
473
+ graph["nodes"]["node_type"].astype(str).str.startswith("facet_").sum()
474
+ ),
475
+ "edge_types": sorted(edges_df["edge_type"].unique().tolist())
476
+ if not edges_df.empty
477
+ else [],
478
+ }
479
+ if log:
480
+ log(
481
+ f"graph from shards nodes={graph['stats']['n_nodes']} "
482
+ f"edges={graph['stats']['n_edges']}"
483
+ )
484
+ return graph
485
+
486
+
487
+ def build_bm25_tf_spill(
488
+ corpus_path: Path,
489
+ spill: Path,
490
+ n_docs: int,
491
+ *,
492
+ batch: int = 512,
493
+ log: Callable[[str], None] | None = None,
494
+ ) -> dict[str, Any]:
495
+ """Stream tokenize corpus → SQLite TF → bm25_documents/postings parquet + stats.
496
+
497
+ Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.pkl exist
498
+ with matching n_docs, reuse.
499
+ """
500
+ spill.mkdir(parents=True, exist_ok=True)
501
+ docs_path = spill / "bm25_documents.parquet"
502
+ post_path = spill / "bm25_postings.parquet"
503
+ stats_path = spill / "bm25_stats.pkl"
504
+ if docs_path.is_file() and post_path.is_file() and stats_path.is_file():
505
+ stats = load_pickle(stats_path)
506
+ if int(stats.get("n_docs", -1)) == n_docs:
507
+ if log:
508
+ log(f"reusing bm25 spill n_docs={n_docs}")
509
+ return {"stats": stats, "documents": docs_path, "postings": post_path}
510
+
511
+ bm25_sql = spill / "bm25_tf.sqlite"
512
+ if bm25_sql.exists():
513
+ bm25_sql.unlink()
514
+ conn = sqlite3.connect(str(bm25_sql))
515
+ conn.execute("PRAGMA journal_mode=OFF")
516
+ conn.execute("PRAGMA synchronous=OFF")
517
+ conn.execute("PRAGMA temp_store=MEMORY")
518
+ conn.execute("PRAGMA locking_mode=EXCLUSIVE")
519
+ conn.execute(
520
+ "CREATE TABLE tf (term TEXT NOT NULL, doc INTEGER NOT NULL, "
521
+ "ttf INTEGER NOT NULL, btf INTEGER NOT NULL, PRIMARY KEY(term, doc)) WITHOUT ROWID"
522
+ )
523
+ title_len = np.zeros(n_docs, dtype=np.int32)
524
+ body_len = np.zeros(n_docs, dtype=np.int32)
525
+ meta_path = spill / "doc_meta_rows.parquet"
526
+ meta_path.unlink(missing_ok=True)
527
+ meta_buf: list[dict] = []
528
+ pf = pq.ParquetFile(corpus_path)
529
+ schema_names = set(pf.schema_arrow.names)
530
+ cols = [
531
+ c
532
+ for c in [
533
+ "document_index",
534
+ "entry_cid",
535
+ "law_cid",
536
+ "instrument_id",
537
+ "law_id",
538
+ "source_id",
539
+ "title",
540
+ "instrument_title",
541
+ "article_number",
542
+ "article_title",
543
+ "record_type",
544
+ "language",
545
+ "jurisdiction",
546
+ "body",
547
+ ]
548
+ if c in schema_names
549
+ ]
550
+ processed = 0
551
+ batch_rows: list[tuple] = []
552
+ conn.execute("BEGIN")
553
+ for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols):
554
+ d = batch_tbl.to_pydict()
555
+ m = len(d["document_index"])
556
+ for i in range(m):
557
+ di = int(d["document_index"][i])
558
+ title = str((d.get("title") or [""])[i] or "")
559
+ body = str((d.get("body") or [""])[i] or "")
560
+ tt = tokenize(title)
561
+ bt = tokenize(body)
562
+ title_len[di] = len(tt)
563
+ body_len[di] = len(bt)
564
+ tf_t: dict[str, int] = defaultdict(int)
565
+ tf_b: dict[str, int] = defaultdict(int)
566
+ for tok in tt:
567
+ tf_t[tok] += 1
568
+ for tok in bt:
569
+ tf_b[tok] += 1
570
+ for tok in set(tf_t) | set(tf_b):
571
+ batch_rows.append((tok, di, int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0))))
572
+ law_id = str((d.get("law_id") or d.get("instrument_id") or [""])[i] or "")
573
+ instrument_id = str(
574
+ (d.get("instrument_id") or d.get("law_id") or [""])[i] or ""
575
+ )
576
+ meta_buf.append(
577
+ {
578
+ "entry_cid": str(d["entry_cid"][i]),
579
+ "document_index": di,
580
+ "law_cid": str((d.get("law_cid") or [""])[i] or ""),
581
+ "instrument_id": instrument_id,
582
+ "law_id": law_id,
583
+ "source_id": str(d["source_id"][i]),
584
+ "title": title,
585
+ "instrument_title": str(
586
+ (d.get("instrument_title") or [""])[i] or ""
587
+ ),
588
+ "article_number": str((d.get("article_number") or [""])[i] or ""),
589
+ "article_title": str((d.get("article_title") or [""])[i] or ""),
590
+ "record_type": str(d["record_type"][i]),
591
+ "language": str((d.get("language") or [""])[i] or ""),
592
+ "jurisdiction": str((d.get("jurisdiction") or [""])[i] or ""),
593
+ }
594
+ )
595
+ if len(batch_rows) >= 20_000:
596
+ conn.executemany(
597
+ "INSERT OR REPLACE INTO tf VALUES (?,?,?,?)", batch_rows
598
+ )
599
+ batch_rows.clear()
600
+ processed += m
601
+ if len(meta_buf) >= 20_000:
602
+ dfm = pd.DataFrame(meta_buf)
603
+ if meta_path.exists():
604
+ old = pd.read_parquet(meta_path)
605
+ dfm = pd.concat([old, dfm], ignore_index=True)
606
+ del old
607
+ dfm.to_parquet(meta_path, index=False)
608
+ del dfm
609
+ meta_buf.clear()
610
+ gc.collect()
611
+ if processed % 20_000 == 0:
612
+ checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log)
613
+ gc.collect()
614
+ if batch_rows:
615
+ conn.executemany("INSERT OR REPLACE INTO tf VALUES (?,?,?,?)", batch_rows)
616
+ batch_rows.clear()
617
+ if meta_buf:
618
+ dfm = pd.DataFrame(meta_buf)
619
+ if meta_path.exists():
620
+ old = pd.read_parquet(meta_path)
621
+ dfm = pd.concat([old, dfm], ignore_index=True)
622
+ del old
623
+ dfm.to_parquet(meta_path, index=False)
624
+ del dfm
625
+ meta_buf.clear()
626
+ conn.commit()
627
+ if log:
628
+ log("bm25 tf spilled; writing documents")
629
+
630
+ doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
631
+ avgdl = float(doc_len.mean()) if n_docs else 0.0
632
+ meta_df = pd.read_parquet(meta_path).sort_values("document_index").reset_index(drop=True)
633
+ assert len(meta_df) == n_docs
634
+ meta_df["title_length"] = title_len[meta_df["document_index"].to_numpy()]
635
+ meta_df["body_length"] = body_len[meta_df["document_index"].to_numpy()]
636
+ meta_df["document_length"] = np.round(
637
+ doc_len[meta_df["document_index"].to_numpy()]
638
+ ).astype(int)
639
+ meta_df["schema_version"] = SCHEMA_VERSION
640
+ meta_df.to_parquet(docs_path, index=False)
641
+ del meta_df
642
+ gc.collect()
643
+ meta_path.unlink(missing_ok=True)
644
+
645
+ posting_rows: list[dict] = []
646
+ n_postings = 0
647
+ n_terms = 0
648
+ part_i = 0
649
+ cur_term = None
650
+ cur_items: list = []
651
+
652
+ def flush_term(term: str, items: list) -> None:
653
+ nonlocal n_postings, n_terms, part_i, posting_rows
654
+ if not items:
655
+ return
656
+ n_terms += 1
657
+ dfreq = len(items)
658
+ cfreq = sum(int(ttf) + int(btf) for _, ttf, btf in items)
659
+ idf = _idf(n_docs, dfreq)
660
+ chunks = [
661
+ items[i : i + POSTING_ROWS_PER_RECORD]
662
+ for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD)
663
+ ]
664
+ n_chunks = len(chunks)
665
+ for cidx, chunk in enumerate(chunks):
666
+ posting_rows.append(
667
+ {
668
+ "term": term,
669
+ "document_indices": [int(d) for d, _, _ in chunk],
670
+ "title_frequencies": [int(ttf) for _, ttf, _ in chunk],
671
+ "body_frequencies": [int(btf) for _, _, btf in chunk],
672
+ "tfs": [
673
+ TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf)
674
+ for _, ttf, btf in chunk
675
+ ],
676
+ "lengths": [int(round(doc_len[int(d)])) for d, _, _ in chunk],
677
+ "document_lengths": [
678
+ int(round(doc_len[int(d)])) for d, _, _ in chunk
679
+ ],
680
+ "document_frequency": int(dfreq),
681
+ "corpus_frequency": int(cfreq),
682
+ "idf": float(idf),
683
+ "posting_chunk_index": int(cidx),
684
+ "posting_chunk_count": int(n_chunks),
685
+ "schema_version": SCHEMA_VERSION,
686
+ }
687
+ )
688
+ n_postings += dfreq
689
+ if len(posting_rows) >= 8_000:
690
+ pd.DataFrame(posting_rows).to_parquet(
691
+ spill / f"postings_part_{part_i:08d}.parquet", index=False
692
+ )
693
+ posting_rows.clear()
694
+ part_i += 1
695
+ gc.collect()
696
+
697
+ for term, doc, ttf, btf in conn.execute(
698
+ "SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc"
699
+ ):
700
+ term = str(term)
701
+ if cur_term is None:
702
+ cur_term = term
703
+ if term != cur_term:
704
+ flush_term(cur_term, cur_items)
705
+ cur_items = []
706
+ cur_term = term
707
+ if n_terms and n_terms % 50_000 == 0:
708
+ checkpoint(f"bm25_postings_terms", row=n_terms, every_n=50_000, log=log)
709
+ cur_items.append((int(doc), int(ttf), int(btf)))
710
+ if cur_term is not None:
711
+ flush_term(cur_term, cur_items)
712
+ if posting_rows:
713
+ pd.DataFrame(posting_rows).to_parquet(
714
+ spill / f"postings_part_{part_i:08d}.parquet", index=False
715
+ )
716
+ posting_rows.clear()
717
+ conn.close()
718
+ gc.collect()
719
+
720
+ parts = sorted(spill.glob("postings_part_*.parquet"))
721
+ frames: list[pd.DataFrame] = []
722
+ for i, part in enumerate(parts):
723
+ frames.append(pd.read_parquet(part))
724
+ if len(frames) >= 8:
725
+ frames = [pd.concat(frames, ignore_index=True)]
726
+ gc.collect()
727
+ if i and i % 20 == 0:
728
+ checkpoint(f"concat_postings", row=i, every_n=20, log=log)
729
+ postings = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
730
+ del frames
731
+ for part in parts:
732
+ part.unlink()
733
+ postings.to_parquet(post_path, index=False)
734
+ out_rows = len(postings)
735
+ del postings
736
+ gc.collect()
737
+ stats = {
738
+ "k1": K1,
739
+ "b": B,
740
+ "title_weight": TITLE_WEIGHT,
741
+ "body_weight": BODY_WEIGHT,
742
+ "average_document_length": avgdl,
743
+ "tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1",
744
+ "max_query_terms": 64,
745
+ "posting_rows_per_record": POSTING_ROWS_PER_RECORD,
746
+ "terms_per_shard": TERMS_PER_SHARD,
747
+ "n_docs": n_docs,
748
+ "n_terms": int(n_terms),
749
+ "n_posting_rows": int(out_rows),
750
+ "n_postings": int(n_postings),
751
+ }
752
+ spill_pickle(stats_path, stats)
753
+ try:
754
+ bm25_sql.unlink()
755
+ except Exception:
756
+ pass
757
+ if log:
758
+ log(f"bm25 spill done terms={n_terms} posting_rows={out_rows}")
759
+ return {"stats": stats, "documents": docs_path, "postings": post_path}
760
+
761
+
762
+ def should_use_sqlite(n_docs: int, threshold: int = SQLITE_THRESHOLD) -> bool:
763
+ return n_docs >= threshold
country_laws_ir/upload.py CHANGED
@@ -1,24 +1,119 @@
1
- """Hub upload is intentionally not implemented in this local pipeline.
2
 
3
- Later publish (operator machine, never from this run):
4
-
5
- export HF_TOKEN=... # never commit / never echo
6
- hf upload-large-folder justicedao/ipfs_malta_laws_ir \\
7
- /workspace/country-laws-ir/releases/ipfs_malta_laws_ir \\
8
- --repo-type dataset --no-private --num-workers 8 \\
9
- --exclude "**/__pycache__/**" --exclude "**/*.pyc"
10
  """
11
 
12
  from __future__ import annotations
13
 
 
14
  from pathlib import Path
15
  from typing import Any
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def upload_release(local_dir: Path, repo_id: str) -> dict[str, Any]:
19
- raise RuntimeError(
20
- "Hub upload is disabled in the local country-laws-ir pipeline. "
21
- "Publish later with: hf upload-large-folder "
22
- f"{repo_id} {local_dir} --repo-type dataset --no-private --num-workers 8 "
23
- '--exclude "**/__pycache__/**" --exclude "**/*.pyc"'
 
 
 
 
 
 
 
 
 
 
 
 
24
  )
 
 
 
 
 
 
 
 
 
1
+ """Publish a local country-laws-ir release to the JusticeDAO Hugging Face org.
2
 
3
+ Reads stay anonymous (see ``auth.py``). Writes require an explicit ``--upload``
4
+ path, a ``justicedao/`` repo id, and ``HF_TOKEN``. Protected LCR repositories
5
+ are fail-closed via ``require_unprotected_or_runtime``.
 
 
 
 
6
  """
7
 
8
  from __future__ import annotations
9
 
10
+ import os
11
  from pathlib import Path
12
  from typing import Any
13
 
14
+ from . import TARGET_ORG
15
+
16
+ _OPERATOR_HINT = (
17
+ "Publish later with: hf upload-large-folder "
18
+ "{repo} {local_dir} --repo-type dataset --no-private --num-workers 8 "
19
+ '--exclude "**/__pycache__/**" --exclude "**/*.pyc"'
20
+ )
21
+
22
+
23
+ class UploadError(RuntimeError):
24
+ """Raised when a JusticeDAO upload cannot proceed."""
25
+
26
+
27
+ def _token_from_env() -> str:
28
+ for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
29
+ value = (os.environ.get(key) or "").strip()
30
+ if value:
31
+ return value
32
+ token_path = Path.home() / ".cache" / "huggingface" / "token"
33
+ if token_path.is_file():
34
+ try:
35
+ return token_path.read_text(encoding="utf-8").strip()
36
+ except OSError:
37
+ return ""
38
+ return ""
39
+
40
+
41
+ def upload_release(
42
+ local_dir: Path,
43
+ repo_id: str,
44
+ *,
45
+ token: str | None = None,
46
+ commit_message: str | None = None,
47
+ create: bool = True,
48
+ ) -> dict[str, Any]:
49
+ local_dir = Path(local_dir)
50
+ repo_id = str(repo_id or "").strip()
51
+ if not local_dir.is_dir():
52
+ raise UploadError(f"release directory does not exist: {local_dir}")
53
+ if not repo_id.startswith(f"{TARGET_ORG}/"):
54
+ raise UploadError(
55
+ f"country-laws-ir publishes only to {TARGET_ORG}/*; got {repo_id!r}"
56
+ )
57
+ if not (local_dir / "manifest.json").is_file():
58
+ raise UploadError(f"release is missing manifest.json: {local_dir}")
59
+
60
+ from ipfs_datasets_py.huggingface.protected_repo_guard import (
61
+ require_unprotected_or_runtime,
62
+ )
63
+
64
+ require_unprotected_or_runtime(repo_id, method="upload_folder")
65
+
66
+ resolved = (token or "").strip() or _token_from_env()
67
+ if not resolved:
68
+ raise UploadError(
69
+ "HF_TOKEN is required for --upload. "
70
+ + _OPERATOR_HINT.format(repo=repo_id, local_dir=local_dir)
71
+ )
72
+
73
+ from huggingface_hub import HfApi
74
+
75
+ api = HfApi(token=resolved)
76
+ if create:
77
+ api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True, private=False)
78
+ ignore = ["**/__pycache__/**", "**/*.pyc", "**/*.tmp", "**/*.tmp.npy"]
79
+ n_files = sum(1 for path in local_dir.rglob("*") if path.is_file())
80
+ nbytes = sum(path.stat().st_size for path in local_dir.rglob("*") if path.is_file())
81
+ use_large = n_files >= 80 or nbytes >= 80 * 1024 * 1024
82
+ if use_large and hasattr(api, "upload_large_folder"):
83
+ api.upload_large_folder(
84
+ folder_path=str(local_dir),
85
+ repo_id=repo_id,
86
+ repo_type="dataset",
87
+ ignore_patterns=ignore,
88
+ )
89
+ revision = ""
90
+ try:
91
+ from huggingface_hub import dataset_info as _dataset_info
92
 
93
+ pinned = _dataset_info(repo_id, token=resolved)
94
+ revision = str(getattr(pinned, "sha", "") or "")
95
+ except Exception:
96
+ revision = ""
97
+ return {
98
+ "url": f"https://huggingface.co/datasets/{repo_id}",
99
+ "repo_id": repo_id,
100
+ "revision": revision,
101
+ "local_dir": str(local_dir),
102
+ "method": "upload_large_folder",
103
+ }
104
+ info = api.upload_folder(
105
+ folder_path=str(local_dir),
106
+ repo_id=repo_id,
107
+ repo_type="dataset",
108
+ commit_message=commit_message
109
+ or f"Incremental country-laws-ir GraphRAG release for {repo_id}",
110
+ ignore_patterns=ignore,
111
  )
112
+ revision = getattr(info, "oid", None) or getattr(info, "commit_id", None) or ""
113
+ return {
114
+ "url": f"https://huggingface.co/datasets/{repo_id}",
115
+ "repo_id": repo_id,
116
+ "revision": revision,
117
+ "local_dir": str(local_dir),
118
+ "method": "upload_folder",
119
+ }
country_laws_ir/vectors.py CHANGED
@@ -52,7 +52,7 @@ def encode_corpus(
52
  from .auth import configure_hf
53
 
54
  configure_hf()
55
- cache_root = _Path("/workspace/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(
@@ -109,6 +109,14 @@ def encode_corpus(
109
  out[done:j] = np.asarray(chunk, dtype=np.float32)
110
  done = j
111
  print(f"embeddings checkpoint {done}/{n}", flush=True)
 
 
 
 
 
 
 
 
112
  if ckpt is not None:
113
  ckpt.parent.mkdir(parents=True, exist_ok=True)
114
  tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
@@ -152,25 +160,29 @@ def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) ->
152
 
153
 
154
  def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
 
 
 
 
 
155
  n = len(x)
156
- idx = np.arange(n)
157
- if n <= max_size:
158
- return [idx]
159
- labels = _spherical_kmeans(x, k=2)
160
- clusters = []
161
- for lab in (0, 1):
162
- members = idx[labels == lab]
163
- if len(members) == 0:
164
  continue
165
- if len(members) <= max_size:
166
- clusters.append(members)
167
- else:
168
- sub = _recursive_clusters(x[members], max_size=max_size)
169
- clusters.extend([members[s] for s in sub])
170
- if not clusters:
171
- mid = n // 2
172
- return [idx[:mid], idx[mid:]]
173
- return clusters
174
 
175
 
176
  def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
@@ -325,3 +337,89 @@ def layout_stub_vectors(corpus: pd.DataFrame, reason: str) -> dict[str, Any]:
325
  ],
326
  },
327
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
 
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")
 
160
 
161
 
162
  def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
163
+ """Split vectors into shards of at most *max_size* without unbounded recursion.
164
+
165
+ Spherical k-means can fail to split (all points one label). In that case
166
+ fall back to an even index split so layout cannot recurse forever.
167
+ """
168
  n = len(x)
169
+ if n == 0:
170
+ return []
171
+ pending: list[np.ndarray] = [np.arange(n)]
172
+ clusters: list[np.ndarray] = []
173
+ while pending:
174
+ idx = pending.pop()
175
+ if len(idx) <= max_size:
176
+ clusters.append(idx)
177
  continue
178
+ labels = _spherical_kmeans(x[idx], k=2)
179
+ parts = [idx[labels == lab] for lab in (0, 1)]
180
+ parts = [p for p in parts if len(p)]
181
+ if len(parts) < 2 or max(len(p) for p in parts) == len(idx):
182
+ mid = len(idx) // 2
183
+ parts = [idx[:mid], idx[mid:]]
184
+ pending.extend(parts)
185
+ return clusters or [np.arange(n)]
 
186
 
187
 
188
  def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
 
337
  ],
338
  },
339
  }
340
+
341
+
342
+ def assemble_embeddings(
343
+ corpus: pd.DataFrame,
344
+ prior_by_cid: dict[str, list[float]] | None = None,
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)
359
+ prior = prior_by_cid or {}
360
+ reused_idx: list[int] = []
361
+ missing_idx: list[int] = []
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] = {
380
+ "n_docs": n,
381
+ "n_reused": len(reused_idx),
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):
407
+ out[corpus_i] = encoded[local_i]
408
+ report["n_encoded"] = int(len(missing_idx))
409
+ report["n_missing"] = 0
410
+ report["status"] = "merged"
411
+ return _l2_normalize(out), report
412
+
413
+
414
+ def embeddings_by_cid(corpus: pd.DataFrame, matrix: np.ndarray) -> dict[str, list[float]]:
415
+ """Project a row-aligned embedding matrix back to a CID map."""
416
+ out: dict[str, list[float]] = {}
417
+ if corpus is None or corpus.empty:
418
+ return out
419
+ x = np.asarray(matrix, dtype=np.float32)
420
+ cids = corpus["entry_cid"].astype(str).tolist()
421
+ for i, cid in enumerate(cids):
422
+ if i >= len(x):
423
+ break
424
+ out[cid] = x[i].astype(np.float32).tolist()
425
+ return out
data/bm25/documents/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d345ec5581397c74a89b1ed1048f474287f1b5129367c9b638003a9c3484d603
3
- size 264694
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9715076442ca16843e1d3b668c2dd4f72da6fe73ca866a619410f0e7e05bef22
3
+ size 225443
data/bm25/documents/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1c34ab9ba4967e07d922a3e1dc40d2ea8ccbc6c63f0ca933ed6c55ad823f40fe
3
- size 60550
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d79f787718607e3065b05ac9158ba4cf04849eb19487abc3dd0a9cac1d84d336
3
+ size 228691
data/bm25/documents/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00973aba5a8172eb46678a85a7e4b66b89ebac750bdf06c76ebf8ac3033b351b
3
+ size 128350
data/bm25/postings/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9e4eee65e33f3248b0a26291e28eedb3aaf5ed23aa5c9598ec9d0578f3576b5b
3
- size 61192
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:266797c124919a5850f86412ec1d6048e89eafd7256167b93aab43adbfcdf8af
3
+ size 91212
data/corpus/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:de235829a76e4a7cce70a64b8012a2429df5dd491900693d1539f330d5b3011a
3
- size 1169368
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46102abb0a7568dbe47d0a5499394ed6cbc49e2bf3d4299f52240d0ea8b1b182
3
+ size 825350
data/corpus/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:71264c61710b4ba78aa5d43d811413fced90735af5d5ea2adea21c8370067706
3
- size 217659
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3dcf57cf368128c832290a45e1a8b3b2bb955dcea47e4b7d1ba7ee7cefd8141
3
+ size 889092
data/corpus/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac6933e1c76557ad762619290bd97a9699b1af52b1da24fd3b378bdcb9dfcbb7
3
+ size 434058
data/graph/adjacency/incoming/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1470056f8510670ca0d7415acd2036f06b4822198bfb595226fda3899aa07028
3
- size 1919573
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5ae8159e9610e8273b6f0ae6808135665013f4e2a2328dc58b807e553d60c39
3
+ size 4043739
data/graph/adjacency/incoming/part-000001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0958d9c785bd9a2a7038ec8e67dc3ff441663fc4081cee4a5e1ddd9fba032818
3
+ size 129543
data/graph/adjacency/outgoing/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:170fd7e68c564206b2787385b5f04e19a0196b7095a5a675c748b7739513a346
3
- size 1690859
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a25617b35049c699a029cbe0bd2f8c66bdabca99de45f26cde1a7c067552400c
3
+ size 1697225
data/graph/adjacency/outgoing/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:318f674adc836c6f059986fd1c606a3c14789508f5d0b0d3a5faa7262088fb55
3
- size 284009
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:307f38ab0a43180a9633bc71c28f7e9f6ba8a394f30419917db2d9dc51f97ae8
3
+ size 1706486
data/graph/adjacency/outgoing/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:951bd81ccee5c107caa6c4f2affc12b7da35e8944ad697426421a71658eb08a8
3
+ size 1000954
data/graph/edges/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:4e1e7ae18f7f655a1284c8a08971b3821975e34dfd5f3f73a5e8334c04a7a3a3
3
- size 336796
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e51821bcf8f013af89fc53a9924d5b2b6deb04470e10618e6654de10981f3e5
3
+ size 348216
data/graph/edges/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:4cd2b8af88680ad1a586445e7b2885a28c8be29dfec2c0ec0ff329b6b8f41744
3
- size 271946
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a541f531b76a820aa78026ce21f31a22777dd3438375550930f8ee39bcd4185
3
+ size 348363
data/graph/edges/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:669a1f7747159d8049ec6f0621767868e622cbcd11c88abbc5e259c62819c6ca
3
- size 244967
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbbd636f8d7b99cb7003542cf13d8f278c98c0fedff4004be73374a6147ac5c6
3
+ size 330693
data/graph/edges/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6c420523f984d8681a7f9076bfeb4f964dee054d2612f5192592f37fbbee08bc
3
- size 250330
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d53666031670a391288610840421c434fd843c70aae3aaf35fc6f487c4f63fe
3
+ size 260252
data/graph/edges/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:698cae834637ba330cac9f38b2592eae9c46220b1bc734bce877a8f62188d4f6
3
- size 318588
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:feb8c16c3cdedc1c18f494a1dc278c150f621bd0a95644edce79624287cdbfc9
3
+ size 262502
data/graph/edges/part-000005.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d034aefbb5e1133fed88c915b0c60644bfd9e6be1628058fec015caefe02822e
3
- size 309322
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22c81d796baa1c7e1ae327932db90377301f6962c002388f0c8238b792c087be
3
+ size 255648
data/graph/edges/part-000006.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2df223ad01074d03c32638631a1f27c9f8818d6d665272fb815b5dc1cf61c47f
3
- size 295287
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08de6ce68626afd1133d61fbac3e80d5352eabd5490a33c6a54c97fe4e814e3f
3
+ size 259115
data/graph/edges/part-000007.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f042a4f3ed3a1899c392363f6aac204a514da5fb614fbe75b3a08da69ecbd168
3
- size 295317
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32f91d29ec12a64f68c17039f75714915f3edd93bba0deba18c92bfd7a02b98e
3
+ size 261895
data/graph/edges/part-000008.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:01046772948634bcec10e065befdeedf19720bd9d3bdbdef79a6b8b5a0d98ccf
3
- size 295177
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fee4ab4126d602f365eb58ac6ba71fed18669174ee1f25d00aea324be297d88
3
+ size 287748
data/graph/edges/part-000009.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f71d7008f704d2ac3940cb652e9f9095a524a20c1103702b337934feae5fe5a9
3
- size 304736
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:667069c928f98dba9d646e16edd75d353023c4f1215f3b366f5b519513117d72
3
+ size 325546
data/graph/edges/part-000010.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3b2b1616145a5a52e8d7831dfb7d46d71a6ec295eac1c09698c610e8b2323964
3
- size 313212
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5095fe5abfa27d30d8b59957761caecbb1bae240b4f0eb7746dc5926ab72776
3
+ size 325416
data/graph/edges/part-000011.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3a6eeabea29335583af5848c6d69769c91881da832c1fc131b83f92b84e3ac64
3
- size 20795
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b782af9977168879129a14bfe0965fba9da3b0bd2d69cc3b284224048b5eddc
3
+ size 318293
data/graph/edges/part-000012.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2e3d050df4effc9ed2299de2a298b7ca8dd377d279364a1633215e146fdfdb8
3
+ size 294169
data/graph/edges/part-000013.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc85d357afe6b44ef2ffde8bf89c4803cc2b8ac3654a0f65954f04b1e2d4aaa5
3
+ size 294115
data/graph/edges/part-000014.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24887219d8c24dba936fd02cc7c8a09d5a78173329ea6eb48fb721fceadb3986
3
+ size 294524
data/graph/edges/part-000015.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85e67c754d2358d4930abe7210a6d5c7d583a8f83888458083ebf4c4b950a02e
3
+ size 294678
data/graph/edges/part-000016.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2561afdb5b7e0fa05aeafd3fa4cfa422774f0bf9b4b29903c9a5df62641d3e8a
3
+ size 294442
data/graph/edges/part-000017.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:462eb32189341a56a98d4e6cd168e644786045d7fdd2b5493645f0cdd5506356
3
+ size 294119
data/graph/edges/part-000018.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd651b58fc023d8827b080543927fdabf481cbc2584d93be671ff65dfea6a1ea
3
+ size 293980
data/graph/edges/part-000019.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c79599baaffca466feab821660e603beeb68bdba957ee48b384eb2ee222a5747
3
+ size 295221
data/graph/edges/part-000020.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6593287bcf0b35b4f324bad8964770ef278da3102626856ba12b24dc71268bea
3
+ size 295194