endomorphosis commited on
Commit
b2af978
·
verified ·
1 Parent(s): cfb02ae

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 +131 -2
  2. build.py +381 -51
  3. country_laws_ir/__init__.py +1 -1
  4. country_laws_ir/__main__.py +204 -12
  5. country_laws_ir/auth.py +26 -4
  6. country_laws_ir/build.py +368 -104
  7. country_laws_ir/catalog.py +82 -9
  8. country_laws_ir/cidutil.py +21 -0
  9. country_laws_ir/coverage.py +455 -0
  10. country_laws_ir/duckdb_store.py +408 -0
  11. country_laws_ir/incremental.py +518 -0
  12. country_laws_ir/normalize.py +149 -19
  13. country_laws_ir/package.py +149 -79
  14. country_laws_ir/profiles.py +124 -0
  15. country_laws_ir/query.py +18 -2
  16. country_laws_ir/raw_package.py +324 -0
  17. country_laws_ir/sparse.py +137 -0
  18. country_laws_ir/spill.py +80 -311
  19. country_laws_ir/structure.py +305 -0
  20. country_laws_ir/upload.py +122 -14
  21. country_laws_ir/vectors.py +263 -76
  22. country_laws_ir/verify.py +280 -0
  23. data/bm25/documents/part-000000.parquet +2 -2
  24. data/bm25/documents/part-000001.parquet +2 -2
  25. data/bm25/documents/part-000002.parquet +2 -2
  26. data/bm25/postings/part-000000.parquet +2 -2
  27. data/bm25/postings/part-000001.parquet +2 -2
  28. data/bm25/postings/part-000002.parquet +2 -2
  29. data/bm25/postings/part-000003.parquet +2 -2
  30. data/bm25/postings/part-000004.parquet +2 -2
  31. data/bm25/postings/part-000005.parquet +3 -0
  32. data/corpus/part-000000.parquet +2 -2
  33. data/corpus/part-000001.parquet +2 -2
  34. data/corpus/part-000002.parquet +2 -2
  35. data/graph/adjacency/in/part-000000.parquet +3 -0
  36. data/graph/adjacency/in/part-000001.parquet +3 -0
  37. data/graph/adjacency/in/part-000002.parquet +3 -0
  38. data/graph/adjacency/in/part-000003.parquet +3 -0
  39. data/graph/adjacency/in/part-000004.parquet +3 -0
  40. data/graph/adjacency/in/part-000005.parquet +3 -0
  41. data/graph/adjacency/in/part-000006.parquet +3 -0
  42. data/graph/adjacency/in/part-000007.parquet +3 -0
  43. data/graph/adjacency/in/part-000008.parquet +3 -0
  44. data/graph/adjacency/in/part-000009.parquet +3 -0
  45. data/graph/adjacency/out/part-000000.parquet +3 -0
  46. data/graph/adjacency/out/part-000001.parquet +3 -0
  47. data/graph/adjacency/out/part-000002.parquet +3 -0
  48. data/graph/adjacency/out/part-000003.parquet +3 -0
  49. data/graph/adjacency/out/part-000004.parquet +3 -0
  50. data/graph/adjacency/out/part-000005.parquet +3 -0
README.md CHANGED
@@ -1,3 +1,132 @@
1
- # justicedao/ipfs_kenya_laws_ir
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- Kenya laws IR release.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ task_categories:
4
+ - text-retrieval
5
+ tags:
6
+ - legal
7
+ - law
8
+ - graphrag
9
+ - bm25
10
+ - research
11
+ - not-legal-advice
12
+ - kenya
13
+ pretty_name: Kenya laws IR (CID-keyed GraphRAG)
14
+ configs:
15
+ - config_name: corpus
16
+ data_files:
17
+ - split: train
18
+ path: data/corpus/*.parquet
19
+ - config_name: bm25_documents
20
+ data_files:
21
+ - split: train
22
+ path: data/bm25/documents/*.parquet
23
+ - config_name: bm25_postings
24
+ data_files:
25
+ - split: train
26
+ path: data/bm25/postings/*.parquet
27
+ - config_name: bm25_keyword_index
28
+ data_files:
29
+ - split: train
30
+ path: indexes/bm25_keyword_shards.parquet
31
+ - config_name: vectors
32
+ data_files:
33
+ - split: train
34
+ path: data/vectors/*.parquet
35
+ - config_name: vector_meta_index
36
+ data_files:
37
+ - split: train
38
+ path: indexes/vector_chunks.parquet
39
+ - config_name: graph_nodes
40
+ data_files:
41
+ - split: train
42
+ path: data/graph/nodes/*.parquet
43
+ - config_name: graph_edges
44
+ data_files:
45
+ - split: train
46
+ path: data/graph/edges/*.parquet
47
+ - config_name: graph_outgoing_adjacency
48
+ data_files:
49
+ - split: train
50
+ path: data/graph/adjacency/outgoing/*.parquet
51
+ - config_name: graph_incoming_adjacency
52
+ data_files:
53
+ - split: train
54
+ path: data/graph/adjacency/incoming/*.parquet
55
+ ---
56
 
57
+ # Kenya legislation IR (CID-keyed sparse GraphRAG)
58
+
59
+ Research retrieval release of `endomorphosis/ipfs_kenya_laws` (revision `27b81c642fec385c9123c30b9eb885d093b70f61`) 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 /
63
+ authentic source of Kenya prevails over this corpus. Retrieved documents
64
+ and graph edges are retrieval evidence only. No legal text was invented.
65
+
66
+ Primary key: `entry_cid` (CIDv1 raw sha2-256 of a canonical identity record).
67
+ Integer `document_index` values are compact shard pointers, not identities.
68
+
69
+ Target Hub id (packaging metadata only): `justicedao/ipfs_kenya_laws_ir`.
70
+
71
+ ## Counts
72
+
73
+ | Field | Value |
74
+ | --- | --- |
75
+ | Laws (corpus units) | 0 |
76
+ | Articles (corpus units) | 9802 |
77
+ | Canonical docs | 9802 |
78
+ | BM25 terms | 21080 |
79
+ | BM25 postings | 712415 |
80
+ | Graph nodes | 10223 |
81
+ | Graph edges | 68614 |
82
+ | Vectors | 9802 × 384-d `thenlper/gte-small` (embedded) |
83
+
84
+ ## Canonical fields
85
+
86
+ `entry_cid`, `law_cid`, `record_type`, `jurisdiction`, `language`,
87
+ `instrument_id`, `instrument_title`, `article_number`, `article_title`,
88
+ `title`, `body`, `source_url`, `snapshot_date`, `coverage`, `license`,
89
+ `collector`, `source_dataset`, `source_revision`.
90
+
91
+ Unit policy: prefer article/section rows; fall back to law-level when
92
+ `articles.parquet` is empty.
93
+
94
+ ## Index layout
95
+
96
+ Zstandard parquet shards with at most 4,096 rows.
97
+
98
+ - `indexes/bm25_keyword_shards.parquet` — lexical term ranges → BM25 posting shards
99
+ - `indexes/vector_chunks.parquet` — semantic routing centroids (rows sorted by cosine to shard centroid)
100
+ - `indexes/corpus_chunks.parquet` — document ranges → corpus shards
101
+ - `data/graph/nodes` / `data/graph/edges` — property graph
102
+ - `data/graph/adjacency/{incoming,outgoing}` — score-ordered neighbor pages
103
+
104
+ BM25: Okapi k1=1.2, b=0.75, title_weight=5, body_weight=1 (FTS5 unicode61-style tokenizer).
105
+
106
+ Graph: one node per `entry_cid` plus facet nodes (`_facet_cid(kind, value)` for
107
+ jurisdiction, language, instrument, source, status). Neighbor edges
108
+ `BM25_NEIGHBOR_OF` (k=8) carry score and matched terms. Structural edges:
109
+ `ARTICLE_OF` (article → parent law) when articles exist, plus `IDENTIFIED_BY_ELI`
110
+ / `IDENTIFIED_BY` only when those identifiers are present in the source.
111
+
112
+ ## Query
113
+
114
+ ```
115
+ python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 10
116
+ python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 10
117
+ python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
118
+ ```
119
+
120
+ ## Publish later (operator)
121
+
122
+ ```
123
+ export HF_TOKEN=... # never commit
124
+ hf upload-large-folder justicedao/ipfs_kenya_laws_ir . \
125
+ --repo-type dataset --no-private --num-workers 8 \
126
+ --exclude "**/__pycache__/**" --exclude "**/*.pyc"
127
+ ```
128
+
129
+ ## Provenance
130
+
131
+ Packaged by country-laws-ir. Upstream collector and official license remain those
132
+ of `endomorphosis/ipfs_kenya_laws`. CIDs identify local content; they do not prove public IPFS pinning.
build.py CHANGED
@@ -1,22 +1,51 @@
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"
@@ -31,32 +60,181 @@ def _log(msg: str) -> None:
31
  def record_progress(event: dict[str, Any]) -> None:
32
  event = dict(event)
33
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
34
- with PROGRESS.open("a", encoding="utf-8") as f:
35
- f.write(json.dumps(event, ensure_ascii=False) + "\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
 
38
  def build_country(
39
  source: str,
40
  out: Path | None = None,
41
  upload: bool = False,
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):
48
  raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}")
49
  repo = country["repo"]
50
  out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir"
51
- _log(f"build start {repo} -> {out} (upload={upload})")
 
 
 
 
 
 
 
 
 
 
 
52
  configure_hf()
53
  CACHE.mkdir(parents=True, exist_ok=True)
54
  REPORTS.mkdir(parents=True, exist_ok=True)
55
- laws, articles, source_meta = load_source(repo, CACHE)
56
  _log(
57
  f"source loaded laws={source_meta['n_laws_source']} "
58
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
59
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  corpus, norm_report = build_corpus(laws, articles, source_meta)
61
  report_path = REPORTS / f"{country['slug']}_normalization.json"
62
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
@@ -69,47 +247,94 @@ def build_country(
69
  )
70
  if corpus.empty:
71
  raise RuntimeError("Normalized corpus is empty; refusing to package")
 
 
 
72
 
73
- bm25 = build_index(corpus)
74
- _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
75
- _log(f"bm25 neighbors start n={len(corpus)} k={neighbor_k}")
76
- neighbors = bm25_neighbors(bm25, k=neighbor_k)
77
- _log("bm25 neighbors done")
78
- graph = build_graph(corpus, neighbors)
79
- _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
80
 
81
- vector_blocker = None
82
- if skip_vectors:
83
- vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
84
- vector_blocker = "skip_vectors"
85
- elif embeddings_available():
86
- try:
87
- ckpt = CACHE / "embeddings" / f"{country['slug']}.npy"
88
- _log(f"vectors encode start n={len(corpus)} checkpoint={ckpt}")
89
- embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt))
90
- vectors = layout_vectors(corpus, embeddings)
91
- _log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
92
- except Exception as exc:
93
- vector_blocker = f"embedding_failed: {exc}"
94
- _log(f"vector embedding failed; writing stub ({exc})")
95
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
96
- else:
97
- vector_blocker = "sentence-transformers/torch unavailable"
98
- _log(f"vectors stub: {vector_blocker}")
99
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  code_root = Path(__file__).resolve().parent.parent
102
  manifest = package_release(
103
  out,
104
  corpus,
105
- bm25,
106
- graph,
107
  vectors,
108
  source_meta,
109
  country,
110
  code_root,
111
  normalization_report=norm_report,
 
 
 
112
  )
 
 
113
  _log(f"packaged {out}")
114
  result = {
115
  "country": country["slug"],
@@ -120,7 +345,10 @@ def build_country(
120
  "counts": manifest["counts"],
121
  "normalization": norm_report,
122
  "vector_blocker": vector_blocker,
 
123
  "schema_version": manifest["schema_version"],
 
 
124
  }
125
  if upload:
126
  from .upload import upload_release
@@ -138,25 +366,32 @@ def batch(
138
  slugs: list[str] | None = None,
139
  upload: bool = False,
140
  skip_done: bool = True,
 
 
 
141
  ) -> list[dict[str, Any]]:
142
- done = set()
143
- if skip_done and PROGRESS.exists():
144
- for line in PROGRESS.read_text(encoding="utf-8").splitlines():
145
- if not line.strip():
146
- continue
147
- rec = json.loads(line)
148
- if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
149
- done.add(rec["country"])
150
  targets = slugs or [c["slug"] for c in indexable_countries()]
151
  if "malta" in targets:
152
  targets = ["malta"] + [s for s in targets if s != "malta"]
153
  results = []
 
154
  for slug in targets:
155
- if skip_done and slug in done:
156
- _log(f"skip already done {slug}")
157
- continue
158
  try:
159
- results.append(build_country(slug, upload=upload))
 
 
 
 
 
 
 
 
160
  except Exception as exc:
161
  _log(f"FAILED {slug}: {exc}")
162
  record_progress(
@@ -169,3 +404,98 @@ def batch(
169
  )
170
  continue
171
  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 .sparse import export_sparse_graphrag
22
+ from .mem import MemAbort, checkpoint, log_mem
23
+ from .spill import spill_dir_for, spill_pickle
24
+ from .package import package_from_spill, package_release
25
  from .catalog import get_country, indexable_countries, target_repo
26
+
27
+ from .incremental import (
28
+ fetch_hub_prior,
29
+ load_embedding_cache,
30
+ load_prior_release,
31
+ load_release_vectors_by_cid,
32
+ merge_embedding_maps,
33
+ plan_rebuild,
34
+ save_embedding_cache,
35
+ )
36
  from .normalize import build_corpus, load_source
 
37
  from .auth import configure_hf
38
+ from .vectors import (
39
+ DIMENSION,
40
+ MODEL_NAME,
41
+ assemble_embeddings,
42
+ embeddings_by_cid,
43
+ layout_stub_vectors,
44
+ layout_vectors,
45
+ select_device,
46
+ )
47
 
48
+ ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
49
  CACHE = ROOT / "cache"
50
  RELEASES = ROOT / "releases"
51
  REPORTS = ROOT / "reports"
 
60
  def record_progress(event: dict[str, Any]) -> None:
61
  event = dict(event)
62
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
63
+ PROGRESS.parent.mkdir(parents=True, exist_ok=True)
64
+ lock_path = PROGRESS.with_suffix(".lock")
65
+ with lock_path.open("a", encoding="utf-8") as lock_fh:
66
+ try:
67
+ import fcntl
68
+
69
+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
70
+ except Exception:
71
+ pass
72
+ with PROGRESS.open("a", encoding="utf-8") as f:
73
+ f.write(json.dumps(event, ensure_ascii=False) + "\n")
74
+
75
+
76
+ def _prior_dir_for(
77
+ slug: str,
78
+ out: Path,
79
+ prior_dir: Path | None,
80
+ *,
81
+ fetch_hub: bool = True,
82
+ ) -> Path | None:
83
+ if prior_dir is not None:
84
+ return Path(prior_dir)
85
+ if out.is_dir() and (out / "manifest.json").is_file():
86
+ return out
87
+ default = RELEASES / f"ipfs_{slug}_laws_ir"
88
+ if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve():
89
+ return default
90
+ if not fetch_hub:
91
+ return None
92
+ hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir")
93
+ if hub is not None:
94
+ _log(f"using justicedao prior {hub}")
95
+ return hub
96
+
97
+
98
+ def _encode_vectors(
99
+ *,
100
+ corpus: pd.DataFrame,
101
+ country_slug: str,
102
+ prior,
103
+ plan,
104
+ skip_vectors: bool,
105
+ device: str,
106
+ ) -> tuple[dict[str, Any], str | None, dict[str, Any]]:
107
+ import gc
108
+
109
+ vector_report: dict[str, Any] = {"status": "stub"}
110
+ vector_blocker = None
111
+ if skip_vectors:
112
+ vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
113
+ return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
114
+
115
+ cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet"
116
+ prior_by_cid = {}
117
+ if plan.reuse_embeddings:
118
+ prior_by_cid = merge_embedding_maps(
119
+ load_embedding_cache(cid_cache_path),
120
+ None if prior is None else load_release_vectors_by_cid(prior.directory),
121
+ )
122
+ _log(f"embedding cache reused_cids={len(prior_by_cid)}")
123
+ try:
124
+ positional = CACHE / "embeddings" / f"{country_slug}.npy"
125
+ resolved, fallback = select_device(device)
126
+ if fallback:
127
+ _log(f"embedding device fallback requested={device} using={resolved}")
128
+ embeddings, vector_report = assemble_embeddings(
129
+ corpus,
130
+ prior_by_cid,
131
+ encode_missing=True,
132
+ device=resolved,
133
+ checkpoint_path=str(positional),
134
+ )
135
+ if (
136
+ vector_report.get("status") in {"stub_missing_encoder", "incomplete"}
137
+ and not int(vector_report.get("n_reused") or 0)
138
+ ):
139
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
140
+ vectors = layout_stub_vectors(corpus, reason=str(vector_blocker))
141
+ return vectors, vector_blocker, vector_report
142
+ vectors = layout_vectors(corpus, embeddings)
143
+ if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused":
144
+ vectors["stats"]["status"] = "partial"
145
+ vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0)
146
+ vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0)
147
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
148
+ save_embedding_cache(
149
+ cid_cache_path,
150
+ merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)),
151
+ model_name=MODEL_NAME,
152
+ dimension=DIMENSION,
153
+ )
154
+ del embeddings
155
+ gc.collect()
156
+ _log(
157
+ f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} "
158
+ f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}"
159
+ )
160
+ return vectors, None, vector_report
161
+ except Exception as exc:
162
+ vector_blocker = f"embedding_failed: {exc}"
163
+ _log(f"vector embedding failed; writing stub ({exc})")
164
+ vectors = layout_stub_vectors(corpus, reason=vector_blocker)
165
+ return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
166
 
167
 
168
  def build_country(
169
  source: str,
170
  out: Path | None = None,
171
  upload: bool = False,
172
+ device: str = "cuda",
173
  neighbor_k: int = 8,
174
  skip_vectors: bool = False,
175
+ mode: str = "auto",
176
+ force: bool = False,
177
+ prior_dir: Path | None = None,
178
+ fetch_hub_prior_ir: bool = True,
179
  ) -> dict[str, Any]:
180
  country = get_country(source)
181
  if not country.get("indexable", True):
182
  raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}")
183
  repo = country["repo"]
184
  out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir"
185
+ local_dir = country.get("local_source_dir") or (
186
+ str(Path(source).resolve())
187
+ if Path(source).is_dir()
188
+ and (
189
+ (Path(source) / "data" / "laws.parquet").is_file()
190
+ or (Path(source) / "laws.parquet").is_file()
191
+ )
192
+ else None
193
+ )
194
+ _log(
195
+ f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
196
+ )
197
  configure_hf()
198
  CACHE.mkdir(parents=True, exist_ok=True)
199
  REPORTS.mkdir(parents=True, exist_ok=True)
200
+ laws, articles, source_meta = load_source(local_dir or repo, CACHE)
201
  _log(
202
  f"source loaded laws={source_meta['n_laws_source']} "
203
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
204
  )
205
+ prior = load_prior_release(
206
+ _prior_dir_for(
207
+ country["slug"],
208
+ out,
209
+ prior_dir,
210
+ fetch_hub=fetch_hub_prior_ir,
211
+ )
212
+ )
213
+ plan = plan_rebuild(
214
+ mode=mode,
215
+ source_meta=source_meta,
216
+ prior=prior,
217
+ force=force,
218
+ rebuild_stub_vectors=not skip_vectors,
219
+ )
220
+ if plan.skip_build:
221
+ _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
222
+ result = {
223
+ "country": country["slug"],
224
+ "source": repo,
225
+ "source_revision": source_meta["source_revision"],
226
+ "out": str(out),
227
+ "target_hub_id": target_repo(country["slug"]),
228
+ "skipped": True,
229
+ "incremental": plan.to_dict(),
230
+ "normalization": {"n_out": plan.delta.current_count if plan.delta else 0},
231
+ "vector_blocker": None,
232
+ "neighbor_via": None,
233
+ "schema_version": "country-laws-ir-graphrag/v1",
234
+ }
235
+ record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
236
+ return result
237
+
238
  corpus, norm_report = build_corpus(laws, articles, source_meta)
239
  report_path = REPORTS / f"{country['slug']}_normalization.json"
240
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
 
247
  )
248
  if corpus.empty:
249
  raise RuntimeError("Normalized corpus is empty; refusing to package")
250
+ verdict = (norm_report or {}).get("verification") or {}
251
+ if verdict.get("blocks_graphrag") and not force:
252
+ from .verify import NormalizationAdmissionError
253
 
254
+ raise NormalizationAdmissionError(
255
+ f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}"
256
+ )
 
 
 
 
257
 
258
+ import gc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
 
260
+ plan = plan_rebuild(
261
+ mode=mode,
262
+ source_meta=source_meta,
263
+ prior=prior,
264
+ current_corpus=corpus,
265
+ force=force,
266
+ rebuild_stub_vectors=not skip_vectors,
267
+ )
268
+ _log(
269
+ f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
270
+ f"added={0 if plan.delta is None else plan.delta.n_added} "
271
+ f"removed={0 if plan.delta is None else plan.delta.n_removed}"
272
+ )
273
+
274
+ n_docs = len(corpus)
275
+ spill = spill_dir_for(country["slug"], CACHE)
276
+ spill.mkdir(parents=True, exist_ok=True)
277
+ corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet"
278
+ corpus.to_parquet(corpus_ckpt, index=False)
279
+ checkpoint("after_normalize", log=_log)
280
+
281
+ vectors, vector_blocker, vector_report = _encode_vectors(
282
+ corpus=corpus,
283
+ country_slug=country["slug"],
284
+ prior=prior,
285
+ plan=plan,
286
+ skip_vectors=skip_vectors,
287
+ device=device,
288
+ )
289
+ spill_pickle(spill / "vectors.pkl", vectors)
290
+ del vectors
291
+ gc.collect()
292
+ checkpoint("vectors_spilled", log=_log)
293
+ extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
294
+
295
+ neighbor_via = "hf_graphrag"
296
+ if out.exists():
297
+ import shutil as _shutil
298
+
299
+ _shutil.rmtree(out)
300
+ out.mkdir(parents=True, exist_ok=True)
301
+ _log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}")
302
+ sparse_report = export_sparse_graphrag(corpus, out)
303
+ extra_manifest["sparse"] = sparse_report
304
+ with open(spill / "vectors.pkl", "rb") as _vf:
305
+ import pickle as _pickle
306
+
307
+ vectors = _pickle.load(_vf)
308
+ dummy_bm25 = {
309
+ "documents": pd.DataFrame(),
310
+ "postings": pd.DataFrame(),
311
+ "stats": (sparse_report.get("bm25") or {}).get("bm25")
312
+ or (sparse_report.get("bm25") or {}),
313
+ }
314
+ dummy_graph = {
315
+ "nodes": pd.DataFrame(),
316
+ "edges": pd.DataFrame(),
317
+ "incoming": pd.DataFrame(),
318
+ "outgoing": pd.DataFrame(),
319
+ "stats": sparse_report.get("graph") or {},
320
+ }
321
  code_root = Path(__file__).resolve().parent.parent
322
  manifest = package_release(
323
  out,
324
  corpus,
325
+ dummy_bm25,
326
+ dummy_graph,
327
  vectors,
328
  source_meta,
329
  country,
330
  code_root,
331
  normalization_report=norm_report,
332
+ extra_manifest=extra_manifest,
333
+ wipe=False,
334
+ skip_bm25_graph=True,
335
  )
336
+ del corpus, vectors
337
+ gc.collect()
338
  _log(f"packaged {out}")
339
  result = {
340
  "country": country["slug"],
 
345
  "counts": manifest["counts"],
346
  "normalization": norm_report,
347
  "vector_blocker": vector_blocker,
348
+ "neighbor_via": neighbor_via,
349
  "schema_version": manifest["schema_version"],
350
+ "skipped": False,
351
+ "incremental": extra_manifest["incremental"],
352
  }
353
  if upload:
354
  from .upload import upload_release
 
366
  slugs: list[str] | None = None,
367
  upload: bool = False,
368
  skip_done: bool = True,
369
+ mode: str = "auto",
370
+ force: bool = False,
371
+ skip_vectors: bool = False,
372
  ) -> list[dict[str, Any]]:
373
+ """Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
374
+
375
+ ``skip_done`` is kept for compatibility: it no longer skips a country whose
376
+ source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to
377
+ rebuild regardless of CID overlap.
378
+ """
 
 
379
  targets = slugs or [c["slug"] for c in indexable_countries()]
380
  if "malta" in targets:
381
  targets = ["malta"] + [s for s in targets if s != "malta"]
382
  results = []
383
+ rebuild_force = force or not skip_done
384
  for slug in targets:
 
 
 
385
  try:
386
+ results.append(
387
+ build_country(
388
+ slug,
389
+ upload=upload,
390
+ mode=mode,
391
+ force=rebuild_force,
392
+ skip_vectors=skip_vectors,
393
+ )
394
+ )
395
  except Exception as exc:
396
  _log(f"FAILED {slug}: {exc}")
397
  record_progress(
 
404
  )
405
  continue
406
  return results
407
+
408
+
409
+ def reindex_from_gaps(
410
+ *,
411
+ upload: bool = False,
412
+ slugs: list[str] | None = None,
413
+ limit: int | None = None,
414
+ max_corpus_rows: int | None = 20_000,
415
+ skip_vectors: bool = False,
416
+ workers: int = 4,
417
+ mode: str = "auto",
418
+ force: bool = False,
419
+ all_indexable: bool = False,
420
+ device: str = "cuda",
421
+ ) -> list[dict[str, Any]]:
422
+ """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
423
+
424
+ Default cap skips huge corpora (Finland, Dominican Republic). Pass
425
+ ``max_corpus_rows=None`` to include them.
426
+ """
427
+ from .catalog import indexable_countries
428
+ from .coverage import gap_report
429
+
430
+ if slugs is None:
431
+ if all_indexable:
432
+ rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()]
433
+ _log(f"reindex all indexable n={len(rows)}")
434
+ else:
435
+ report = gap_report(workers=workers)
436
+ rows = [c for c in report["countries"] if c.get("rebuild")]
437
+ _log(
438
+ f"reindex targets n={len(rows)} "
439
+ f"(from scan rebuild={len(report.get('rebuild') or [])})"
440
+ )
441
+ rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
442
+ if max_corpus_rows is not None:
443
+ rows = [
444
+ r
445
+ for r in rows
446
+ if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows)
447
+ ]
448
+ if limit is not None:
449
+ rows = rows[: int(limit)]
450
+ slugs = [str(r["slug"]) for r in rows]
451
+ kwargs = {
452
+ "upload": upload,
453
+ "mode": mode,
454
+ "force": force,
455
+ "skip_vectors": skip_vectors,
456
+ "fetch_hub_prior_ir": True,
457
+ "device": device,
458
+ }
459
+ n_workers = max(1, int(workers or 1))
460
+ _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
461
+ import multiprocessing as mp
462
+ from concurrent.futures import ProcessPoolExecutor, as_completed
463
+
464
+ try:
465
+ mp.set_start_method("spawn", force=False)
466
+ except RuntimeError:
467
+ pass
468
+
469
+ results = [None] * len(slugs)
470
+ with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool:
471
+ futs = {
472
+ pool.submit(_reindex_one_country, (slug, kwargs)): i
473
+ for i, slug in enumerate(slugs)
474
+ }
475
+ for fut in as_completed(futs):
476
+ idx = futs[fut]
477
+ slug = slugs[idx]
478
+ try:
479
+ results[idx] = fut.result()
480
+ except Exception as exc:
481
+ _log(f"FAILED {slug}: {exc}")
482
+ results[idx] = {"country": slug, "skipped": False, "error": str(exc)}
483
+ return [r for r in results if r is not None]
484
+
485
+
486
+ def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]:
487
+ slug, kwargs = item
488
+ _log(f"reindex start {slug}")
489
+ try:
490
+ return build_country(slug, **kwargs)
491
+ except Exception as exc:
492
+ _log(f"FAILED {slug}: {exc}")
493
+ record_progress(
494
+ {
495
+ "event": "failed",
496
+ "country": slug,
497
+ "error": str(exc),
498
+ "traceback": traceback.format_exc(),
499
+ }
500
+ )
501
+ return {"country": slug, "skipped": False, "error": str(exc)}
country_laws_ir/__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,29 @@ 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 +46,52 @@ 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 +104,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 +114,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 +132,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 +146,131 @@ 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(
20
+ "--device",
21
+ default="cuda",
22
+ help="Embedding device (cuda by default, like US Code / Open US Law; falls back to cpu)",
23
+ )
24
  p_build.add_argument("--neighbor-k", type=int, default=8)
25
  p_build.add_argument("--skip-vectors", action="store_true")
26
+ p_build.add_argument("--upload", action="store_true",
27
+ help="Publish the packaged release to justicedao/ipfs_<slug>_laws_ir (requires HF_TOKEN)")
28
+ p_build.add_argument("--mode", default="auto", choices=["auto", "full", "delta"],
29
+ help="auto skips unchanged Hub revisions and reuses embeddings by entry_cid")
30
+ p_build.add_argument("--force", action="store_true", help="Ignore source fingerprint skip and reuse caches")
31
+ p_build.add_argument("--prior-dir", default=None, help="Prior GraphRAG release to delta against")
32
 
33
  p_batch = sub.add_parser("batch")
34
  p_batch.add_argument("--slugs", nargs="*", default=None)
35
  p_batch.add_argument("--upload", action="store_true")
36
+ p_batch.add_argument("--no-skip-done", action="store_true",
37
+ help="Force a full rebuild of every country (ignore unchanged fingerprints)")
38
+ p_batch.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
39
+ p_batch.add_argument("--skip-vectors", action="store_true")
40
 
41
  p_q = sub.add_parser("query")
42
  p_q.add_argument("--local-dir", required=True)
 
46
  p_norm.add_argument("--source-repo", "--source", dest="source", default="malta")
47
  p_norm.add_argument("--out", default=None, help="Optional JSON report path")
48
 
49
+ p_cat = sub.add_parser("catalog")
50
+ p_cat.add_argument("--refresh", action="store_true",
51
+ help="List public endomorphosis/ipfs_*_laws datasets and persist new slugs")
52
+
53
+ p_cov = sub.add_parser("coverage", help="Compare endomorphosis sources vs justicedao GraphRAG releases")
54
+ p_cov.add_argument("--gaps", action="store_true",
55
+ help="Scan Hub for missing, stale, and incomplete IR (downloads manifests)")
56
+ p_cov.add_argument("--workers", type=int, default=8)
57
+
58
+ p_re = sub.add_parser(
59
+ "reindex",
60
+ help="Scan endomorphosis vs justicedao and incrementally rebuild stale/missing IR",
61
+ )
62
+ p_re.add_argument("--upload", action="store_true",
63
+ help="Publish rebuilt packs to justicedao (requires HF_TOKEN)")
64
+ p_re.add_argument("--slugs", nargs="*", default=None)
65
+ p_re.add_argument("--limit", type=int, default=None)
66
+ p_re.add_argument("--max-corpus-rows", type=int, default=20000,
67
+ help="Skip IR larger than this many rows (0 = no cap)")
68
+ p_re.add_argument("--skip-vectors", action="store_true")
69
+ p_re.add_argument("--workers", type=int, default=2,
70
+ help="Parallel country workers (default 2 to stay under MemAbort; CUDA encodes are file-locked)")
71
+ p_re.add_argument("--device", default="cuda")
72
+ p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
73
+ p_re.add_argument("--all", action="store_true",
74
+ help="Process every indexable catalog country (not only Hub gaps)")
75
+ p_re.add_argument("--force", action="store_true",
76
+ help="Rebuild even when the source SHA matches (rerun normalize/verifiers)")
77
+
78
+ p_ver = sub.add_parser(
79
+ "verify",
80
+ help="Normalize a country pack and run admission verifiers (no GraphRAG)",
81
+ )
82
+ p_ver.add_argument("--source-repo", "--source", dest="source", default=None)
83
+ p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country")
84
+ p_ver.add_argument("--limit", type=int, default=None)
85
+
86
+ p_raw = sub.add_parser("package-raw")
87
+ p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
88
+ p_raw.add_argument("--instruments-dir", default=None,
89
+ help="Collector JSON directory (default: $LEGAL_CORPORA_ROOT/<iso-or-slug>/instruments)")
90
+ p_raw.add_argument("--iso", default=None, help="Collector ISO directory name if different from slug")
91
+ p_raw.add_argument("--out", default=None, help="Local pack directory (laws.parquet + pack_meta.json)")
92
+ p_raw.add_argument("--source-dataset", default=None,
93
+ help="Raw Hub id (default endomorphosis/ipfs_<slug>_laws)")
94
+ p_raw.add_argument("--prior-pack", default=None, help="Existing parquet pack to merge into")
95
 
96
  args = ap.parse_args(argv)
97
  if args.cmd == "build":
 
104
  device=args.device,
105
  neighbor_k=args.neighbor_k,
106
  skip_vectors=args.skip_vectors,
107
+ mode=args.mode,
108
+ force=args.force,
109
+ prior_dir=Path(args.prior_dir) if args.prior_dir else None,
110
  )
111
  print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str))
112
  print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str))
 
114
  if args.cmd == "batch":
115
  from .build import batch
116
 
117
+ results = batch(
118
+ slugs=args.slugs,
119
+ upload=args.upload,
120
+ skip_done=not args.no_skip_done,
121
+ mode=args.mode,
122
+ skip_vectors=args.skip_vectors,
123
+ )
124
+ print(json.dumps(
125
+ [{"country": r["country"], "out": r["out"], "skipped": r.get("skipped", False)} for r in results],
126
+ indent=2,
127
+ ))
128
  return 0
129
  if args.cmd == "query":
130
  from .query import main as qmain
 
132
  argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"]
133
  return qmain(argv2)
134
  if args.cmd == "normalize":
135
+ from .build import CACHE, REPORTS
136
  from .catalog import get_country
137
  from .normalize import build_corpus, load_source
138
 
139
  country = get_country(args.source)
140
+ local = country.get("local_source_dir")
141
+ laws, articles, source_meta = load_source(local or country["repo"], CACHE)
142
  corpus, report = build_corpus(laws, articles, source_meta)
143
  out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
144
  out.parent.mkdir(parents=True, exist_ok=True)
 
146
  print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2))
147
  return 0
148
  if args.cmd == "catalog":
149
+ from .catalog import all_countries, refresh_from_hub
150
+
151
+ countries = refresh_from_hub() if args.refresh else all_countries()
152
+ print(json.dumps(
153
+ {"n": len(countries), "indexable": len([c for c in countries if c.get("indexable")]), "countries": countries},
154
+ indent=2,
155
+ ))
156
+ return 0
157
+ if args.cmd == "coverage":
158
+ from .coverage import coverage_report, gap_report
159
+
160
+ report = gap_report(workers=args.workers) if args.gaps else coverage_report()
161
+ print(json.dumps(report, indent=2, default=str))
162
+ return 0
163
+ if args.cmd == "reindex":
164
+ from .build import reindex_from_gaps
165
 
166
+ cap = None if args.all or int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
167
+ results = reindex_from_gaps(
168
+ upload=args.upload,
169
+ slugs=args.slugs or None,
170
+ limit=args.limit,
171
+ max_corpus_rows=cap,
172
+ skip_vectors=args.skip_vectors,
173
+ workers=args.workers,
174
+ mode=args.mode,
175
+ force=args.force,
176
+ all_indexable=args.all,
177
+ device=args.device,
178
+ )
179
+ print(json.dumps(
180
+ [
181
+ {
182
+ "country": r.get("country"),
183
+ "skipped": r.get("skipped", False),
184
+ "out": r.get("out"),
185
+ "hub": (r.get("hub") or {}).get("url") if isinstance(r.get("hub"), dict) else r.get("hub"),
186
+ "error": r.get("error"),
187
+ "kind": (r.get("incremental") or {}).get("kind"),
188
+ "n_added": ((r.get("incremental") or {}).get("delta") or {}).get("n_added"),
189
+ "n_unchanged": ((r.get("incremental") or {}).get("delta") or {}).get("n_unchanged"),
190
+ }
191
+ for r in results
192
+ ],
193
+ indent=2,
194
+ default=str,
195
+ ))
196
+ return 1 if any(r.get("error") for r in results) else 0
197
+ if args.cmd == "verify":
198
+ from .catalog import indexable_countries
199
+ from .verify import verify_source
200
+
201
+ slugs = []
202
+ if args.all:
203
+ slugs = [c["slug"] for c in indexable_countries()]
204
+ if args.limit:
205
+ slugs = slugs[: int(args.limit)]
206
+ elif args.source:
207
+ slugs = [args.source]
208
+ else:
209
+ print(json.dumps({"error": "pass --source or --all"}, indent=2))
210
+ return 2
211
+ rows = []
212
+ failed = 0
213
+ for slug in slugs:
214
+ try:
215
+ row = verify_source(slug)
216
+ except Exception as exc:
217
+ row = {"slug": slug, "error": str(exc), "verification": {"admitted": False}}
218
+ rows.append(row)
219
+ if not (row.get("verification") or {}).get("admitted", False):
220
+ failed += 1
221
+ from collections import Counter
222
+
223
+ units = Counter(str(r.get("unit") or "") for r in rows)
224
+ mismatch = []
225
+ latin_blocked = []
226
+ for r in rows:
227
+ for chk in (r.get("verification") or {}).get("checks") or []:
228
+ if chk.get("id") != "heading_language":
229
+ continue
230
+ ev = chk.get("evidence") or {}
231
+ if chk.get("severity") == "fail" and not chk.get("passed"):
232
+ latin_blocked.append(r.get("slug"))
233
+ if "review samples" in str(chk.get("message") or ""):
234
+ mismatch.append(
235
+ {
236
+ "slug": r.get("slug"),
237
+ "document_language": ev.get("document_language"),
238
+ "heading_language": ev.get("heading_language"),
239
+ }
240
+ )
241
+ print(
242
+ json.dumps(
243
+ {
244
+ "n": len(rows),
245
+ "n_failed": failed,
246
+ "by_unit": dict(units),
247
+ "heading_mismatch": mismatch,
248
+ "latin_split_blocked": latin_blocked,
249
+ "countries": rows,
250
+ },
251
+ indent=2,
252
+ default=str,
253
+ )
254
+ )
255
+ return 1 if failed else 0
256
+ if args.cmd == "package-raw":
257
+ from .build import RELEASES
258
+ from .raw_package import default_instruments_dir, package_instruments
259
+
260
+ instruments = (
261
+ Path(args.instruments_dir)
262
+ if args.instruments_dir
263
+ else default_instruments_dir(args.iso or args.slug)
264
+ )
265
+ out = Path(args.out) if args.out else RELEASES / "raw-packs" / args.slug
266
+ meta = package_instruments(
267
+ instruments_dir=instruments,
268
+ out=out,
269
+ slug=args.slug,
270
+ source_dataset=args.source_dataset,
271
+ prior_pack=Path(args.prior_pack) if args.prior_pack else None,
272
+ )
273
+ print(json.dumps(meta, indent=2, default=str))
274
  return 0
275
  return 1
276
 
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,7 +1,15 @@
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
 
7
  import pandas as pd
@@ -10,25 +18,34 @@ from datetime import datetime, timezone
10
  from pathlib import Path
11
  from typing import Any
12
 
13
- from .bm25 import bm25_neighbors, build_index
14
  from .mem import MemAbort, checkpoint, log_mem
15
- from .spill import (
16
- SQLITE_THRESHOLD,
17
- build_bm25_tf_spill,
18
- build_graph_from_neighbor_shards,
19
- neighbors_via_sqlite,
20
- should_use_sqlite,
21
- spill_dir_for,
22
- spill_pickle,
23
- )
24
  from .package import package_from_spill, package_release
25
  from .catalog import get_country, indexable_countries, target_repo
26
- from .graph import build_graph
 
 
 
 
 
 
 
 
 
27
  from .normalize import build_corpus, load_source
28
  from .auth import configure_hf
29
- from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors
 
 
 
 
 
 
 
 
30
 
31
- ROOT = Path("/workspace/country-laws-ir")
32
  CACHE = ROOT / "cache"
33
  RELEASES = ROOT / "releases"
34
  REPORTS = ROOT / "reports"
@@ -43,17 +60,122 @@ def _log(msg: str) -> None:
43
  def record_progress(event: dict[str, Any]) -> None:
44
  event = dict(event)
45
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
46
- with PROGRESS.open("a", encoding="utf-8") as f:
47
- f.write(json.dumps(event, ensure_ascii=False) + "\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
 
50
  def build_country(
51
  source: str,
52
  out: Path | None = None,
53
  upload: bool = False,
54
- device: str = "cpu",
55
  neighbor_k: int = 8,
56
  skip_vectors: bool = False,
 
 
 
 
57
  ) -> dict[str, Any]:
58
  country = get_country(source)
59
  if not country.get("indexable", True):
@@ -69,7 +191,9 @@ def build_country(
69
  )
70
  else None
71
  )
72
- _log(f"build start {repo} -> {out} (upload={upload}) local={local_dir}")
 
 
73
  configure_hf()
74
  CACHE.mkdir(parents=True, exist_ok=True)
75
  REPORTS.mkdir(parents=True, exist_ok=True)
@@ -78,6 +202,39 @@ def build_country(
78
  f"source loaded laws={source_meta['n_laws_source']} "
79
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
80
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  corpus, norm_report = build_corpus(laws, articles, source_meta)
82
  report_path = REPORTS / f"{country['slug']}_normalization.json"
83
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
@@ -90,9 +247,30 @@ def build_country(
90
  )
91
  if corpus.empty:
92
  raise RuntimeError("Normalized corpus is empty; refusing to package")
 
 
 
 
 
 
 
93
 
94
  import gc
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  n_docs = len(corpus)
97
  spill = spill_dir_for(country["slug"], CACHE)
98
  spill.mkdir(parents=True, exist_ok=True)
@@ -100,81 +278,63 @@ def build_country(
100
  corpus.to_parquet(corpus_ckpt, index=False)
101
  checkpoint("after_normalize", log=_log)
102
 
103
- vector_blocker = None
104
- if skip_vectors:
105
- vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
106
- vector_blocker = "skip_vectors"
107
- spill_pickle(spill / "vectors.pkl", vectors)
108
- del vectors
109
- gc.collect()
110
- elif embeddings_available():
111
- try:
112
- ckpt = CACHE / "embeddings" / f"{country['slug']}.npy"
113
- _log(f"vectors encode start n={n_docs} checkpoint={ckpt}")
114
- embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt))
115
- vectors = layout_vectors(corpus, embeddings)
116
- _log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
117
- spill_pickle(spill / "vectors.pkl", vectors)
118
- del embeddings, vectors
119
- gc.collect()
120
- checkpoint("vectors_spilled", log=_log)
121
- except Exception as exc:
122
- vector_blocker = f"embedding_failed: {exc}"
123
- _log(f"vector embedding failed; writing stub ({exc})")
124
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
125
- spill_pickle(spill / "vectors.pkl", vectors)
126
- del vectors
127
- gc.collect()
128
- else:
129
- vector_blocker = "sentence-transformers/torch unavailable"
130
- _log(f"vectors stub: {vector_blocker}")
131
- vectors = layout_stub_vectors(corpus, reason=vector_blocker)
132
- spill_pickle(spill / "vectors.pkl", vectors)
133
- del vectors
134
- gc.collect()
135
 
136
- use_sqlite = should_use_sqlite(n_docs)
137
- neighbor_via = "stock"
138
- if use_sqlite:
139
- _log(f"sqlite neighbors path n={n_docs} (>= {SQLITE_THRESHOLD}) spill={spill}")
140
- # Free corpus body for neighbor stream — reload later for graph
141
- del corpus
142
- gc.collect()
143
- neighbors_via_sqlite(corpus_ckpt, spill, n_docs, k=neighbor_k, log=_log)
144
- neighbor_via = "sqlite_fts"
145
- bm25_info = build_bm25_tf_spill(corpus_ckpt, spill, n_docs, log=_log)
146
- corpus = pd.read_parquet(corpus_ckpt)
147
- graph = build_graph_from_neighbor_shards(corpus, spill, log=_log)
148
- spill_pickle(spill / "graph.pkl", graph)
149
- del graph, corpus
150
- gc.collect()
151
- checkpoint("graph_spilled", log=_log)
152
- code_root = Path(__file__).resolve().parent.parent
153
- manifest = package_from_spill(
154
- out, spill, corpus_ckpt, source_meta, country, code_root,
155
- normalization_report=norm_report, expected_rows=n_docs,
156
- )
157
- _log(f"packaged sequential via={neighbor_via} {out}")
158
- else:
159
- bm25 = build_index(corpus)
160
- _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
161
- _log(f"bm25 neighbors start n={n_docs} k={neighbor_k}")
162
- neighbors = bm25_neighbors(bm25, k=neighbor_k)
163
- _log("bm25 neighbors done")
164
- graph = build_graph(corpus, neighbors)
165
- del neighbors
166
- gc.collect()
167
- _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
168
- with open(spill / "vectors.pkl", "rb") as _vf:
169
- import pickle as _pickle
170
- vectors = _pickle.load(_vf)
171
- code_root = Path(__file__).resolve().parent.parent
172
- manifest = package_release(
173
- out, corpus, bm25, graph, vectors, source_meta, country, code_root,
174
- normalization_report=norm_report,
175
- )
176
- del corpus, bm25, graph, vectors
177
- gc.collect()
 
178
  _log(f"packaged {out}")
179
  result = {
180
  "country": country["slug"],
@@ -187,6 +347,8 @@ def build_country(
187
  "vector_blocker": vector_blocker,
188
  "neighbor_via": neighbor_via,
189
  "schema_version": manifest["schema_version"],
 
 
190
  }
191
  if upload:
192
  from .upload import upload_release
@@ -204,25 +366,32 @@ def batch(
204
  slugs: list[str] | None = None,
205
  upload: bool = False,
206
  skip_done: bool = True,
 
 
 
207
  ) -> list[dict[str, Any]]:
208
- done = set()
209
- if skip_done and PROGRESS.exists():
210
- for line in PROGRESS.read_text(encoding="utf-8").splitlines():
211
- if not line.strip():
212
- continue
213
- rec = json.loads(line)
214
- if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
215
- done.add(rec["country"])
216
  targets = slugs or [c["slug"] for c in indexable_countries()]
217
  if "malta" in targets:
218
  targets = ["malta"] + [s for s in targets if s != "malta"]
219
  results = []
 
220
  for slug in targets:
221
- if skip_done and slug in done:
222
- _log(f"skip already done {slug}")
223
- continue
224
  try:
225
- results.append(build_country(slug, upload=upload))
 
 
 
 
 
 
 
 
226
  except Exception as exc:
227
  _log(f"FAILED {slug}: {exc}")
228
  record_progress(
@@ -235,3 +404,98 @@ def batch(
235
  )
236
  continue
237
  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
 
18
  from pathlib import Path
19
  from typing import Any
20
 
21
+ from .sparse import export_sparse_graphrag
22
  from .mem import MemAbort, checkpoint, log_mem
23
+ from .spill import spill_dir_for, spill_pickle
 
 
 
 
 
 
 
 
24
  from .package import package_from_spill, package_release
25
  from .catalog import get_country, indexable_countries, target_repo
26
+
27
+ from .incremental import (
28
+ fetch_hub_prior,
29
+ load_embedding_cache,
30
+ load_prior_release,
31
+ load_release_vectors_by_cid,
32
+ merge_embedding_maps,
33
+ plan_rebuild,
34
+ save_embedding_cache,
35
+ )
36
  from .normalize import build_corpus, load_source
37
  from .auth import configure_hf
38
+ from .vectors import (
39
+ DIMENSION,
40
+ MODEL_NAME,
41
+ assemble_embeddings,
42
+ embeddings_by_cid,
43
+ layout_stub_vectors,
44
+ layout_vectors,
45
+ select_device,
46
+ )
47
 
48
+ ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
49
  CACHE = ROOT / "cache"
50
  RELEASES = ROOT / "releases"
51
  REPORTS = ROOT / "reports"
 
60
  def record_progress(event: dict[str, Any]) -> None:
61
  event = dict(event)
62
  event.setdefault("ts", datetime.now(timezone.utc).isoformat())
63
+ PROGRESS.parent.mkdir(parents=True, exist_ok=True)
64
+ lock_path = PROGRESS.with_suffix(".lock")
65
+ with lock_path.open("a", encoding="utf-8") as lock_fh:
66
+ try:
67
+ import fcntl
68
+
69
+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
70
+ except Exception:
71
+ pass
72
+ with PROGRESS.open("a", encoding="utf-8") as f:
73
+ f.write(json.dumps(event, ensure_ascii=False) + "\n")
74
+
75
+
76
+ def _prior_dir_for(
77
+ slug: str,
78
+ out: Path,
79
+ prior_dir: Path | None,
80
+ *,
81
+ fetch_hub: bool = True,
82
+ ) -> Path | None:
83
+ if prior_dir is not None:
84
+ return Path(prior_dir)
85
+ if out.is_dir() and (out / "manifest.json").is_file():
86
+ return out
87
+ default = RELEASES / f"ipfs_{slug}_laws_ir"
88
+ if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve():
89
+ return default
90
+ if not fetch_hub:
91
+ return None
92
+ hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir")
93
+ if hub is not None:
94
+ _log(f"using justicedao prior {hub}")
95
+ return hub
96
+
97
+
98
+ def _encode_vectors(
99
+ *,
100
+ corpus: pd.DataFrame,
101
+ country_slug: str,
102
+ prior,
103
+ plan,
104
+ skip_vectors: bool,
105
+ device: str,
106
+ ) -> tuple[dict[str, Any], str | None, dict[str, Any]]:
107
+ import gc
108
+
109
+ vector_report: dict[str, Any] = {"status": "stub"}
110
+ vector_blocker = None
111
+ if skip_vectors:
112
+ vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
113
+ return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
114
+
115
+ cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet"
116
+ prior_by_cid = {}
117
+ if plan.reuse_embeddings:
118
+ prior_by_cid = merge_embedding_maps(
119
+ load_embedding_cache(cid_cache_path),
120
+ None if prior is None else load_release_vectors_by_cid(prior.directory),
121
+ )
122
+ _log(f"embedding cache reused_cids={len(prior_by_cid)}")
123
+ try:
124
+ positional = CACHE / "embeddings" / f"{country_slug}.npy"
125
+ resolved, fallback = select_device(device)
126
+ if fallback:
127
+ _log(f"embedding device fallback requested={device} using={resolved}")
128
+ embeddings, vector_report = assemble_embeddings(
129
+ corpus,
130
+ prior_by_cid,
131
+ encode_missing=True,
132
+ device=resolved,
133
+ checkpoint_path=str(positional),
134
+ )
135
+ if (
136
+ vector_report.get("status") in {"stub_missing_encoder", "incomplete"}
137
+ and not int(vector_report.get("n_reused") or 0)
138
+ ):
139
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
140
+ vectors = layout_stub_vectors(corpus, reason=str(vector_blocker))
141
+ return vectors, vector_blocker, vector_report
142
+ vectors = layout_vectors(corpus, embeddings)
143
+ if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused":
144
+ vectors["stats"]["status"] = "partial"
145
+ vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0)
146
+ vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0)
147
+ vector_blocker = vector_report.get("reason") or vector_report.get("status")
148
+ save_embedding_cache(
149
+ cid_cache_path,
150
+ merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)),
151
+ model_name=MODEL_NAME,
152
+ dimension=DIMENSION,
153
+ )
154
+ del embeddings
155
+ gc.collect()
156
+ _log(
157
+ f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} "
158
+ f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}"
159
+ )
160
+ return vectors, None, vector_report
161
+ except Exception as exc:
162
+ vector_blocker = f"embedding_failed: {exc}"
163
+ _log(f"vector embedding failed; writing stub ({exc})")
164
+ vectors = layout_stub_vectors(corpus, reason=vector_blocker)
165
+ return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
166
 
167
 
168
  def build_country(
169
  source: str,
170
  out: Path | None = None,
171
  upload: bool = False,
172
+ device: str = "cuda",
173
  neighbor_k: int = 8,
174
  skip_vectors: bool = False,
175
+ mode: str = "auto",
176
+ force: bool = False,
177
+ prior_dir: Path | None = None,
178
+ fetch_hub_prior_ir: bool = True,
179
  ) -> dict[str, Any]:
180
  country = get_country(source)
181
  if not country.get("indexable", True):
 
191
  )
192
  else None
193
  )
194
+ _log(
195
+ f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}"
196
+ )
197
  configure_hf()
198
  CACHE.mkdir(parents=True, exist_ok=True)
199
  REPORTS.mkdir(parents=True, exist_ok=True)
 
202
  f"source loaded laws={source_meta['n_laws_source']} "
203
  f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
204
  )
205
+ prior = load_prior_release(
206
+ _prior_dir_for(
207
+ country["slug"],
208
+ out,
209
+ prior_dir,
210
+ fetch_hub=fetch_hub_prior_ir,
211
+ )
212
+ )
213
+ plan = plan_rebuild(
214
+ mode=mode,
215
+ source_meta=source_meta,
216
+ prior=prior,
217
+ force=force,
218
+ rebuild_stub_vectors=not skip_vectors,
219
+ )
220
+ if plan.skip_build:
221
+ _log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
222
+ result = {
223
+ "country": country["slug"],
224
+ "source": repo,
225
+ "source_revision": source_meta["source_revision"],
226
+ "out": str(out),
227
+ "target_hub_id": target_repo(country["slug"]),
228
+ "skipped": True,
229
+ "incremental": plan.to_dict(),
230
+ "normalization": {"n_out": plan.delta.current_count if plan.delta else 0},
231
+ "vector_blocker": None,
232
+ "neighbor_via": None,
233
+ "schema_version": "country-laws-ir-graphrag/v1",
234
+ }
235
+ record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
236
+ return result
237
+
238
  corpus, norm_report = build_corpus(laws, articles, source_meta)
239
  report_path = REPORTS / f"{country['slug']}_normalization.json"
240
  report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
 
247
  )
248
  if corpus.empty:
249
  raise RuntimeError("Normalized corpus is empty; refusing to package")
250
+ verdict = (norm_report or {}).get("verification") or {}
251
+ if verdict.get("blocks_graphrag") and not force:
252
+ from .verify import NormalizationAdmissionError
253
+
254
+ raise NormalizationAdmissionError(
255
+ f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}"
256
+ )
257
 
258
  import gc
259
 
260
+ plan = plan_rebuild(
261
+ mode=mode,
262
+ source_meta=source_meta,
263
+ prior=prior,
264
+ current_corpus=corpus,
265
+ force=force,
266
+ rebuild_stub_vectors=not skip_vectors,
267
+ )
268
+ _log(
269
+ f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
270
+ f"added={0 if plan.delta is None else plan.delta.n_added} "
271
+ f"removed={0 if plan.delta is None else plan.delta.n_removed}"
272
+ )
273
+
274
  n_docs = len(corpus)
275
  spill = spill_dir_for(country["slug"], CACHE)
276
  spill.mkdir(parents=True, exist_ok=True)
 
278
  corpus.to_parquet(corpus_ckpt, index=False)
279
  checkpoint("after_normalize", log=_log)
280
 
281
+ vectors, vector_blocker, vector_report = _encode_vectors(
282
+ corpus=corpus,
283
+ country_slug=country["slug"],
284
+ prior=prior,
285
+ plan=plan,
286
+ skip_vectors=skip_vectors,
287
+ device=device,
288
+ )
289
+ spill_pickle(spill / "vectors.pkl", vectors)
290
+ del vectors
291
+ gc.collect()
292
+ checkpoint("vectors_spilled", log=_log)
293
+ extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
+ neighbor_via = "hf_graphrag"
296
+ if out.exists():
297
+ import shutil as _shutil
298
+
299
+ _shutil.rmtree(out)
300
+ out.mkdir(parents=True, exist_ok=True)
301
+ _log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}")
302
+ sparse_report = export_sparse_graphrag(corpus, out)
303
+ extra_manifest["sparse"] = sparse_report
304
+ with open(spill / "vectors.pkl", "rb") as _vf:
305
+ import pickle as _pickle
306
+
307
+ vectors = _pickle.load(_vf)
308
+ dummy_bm25 = {
309
+ "documents": pd.DataFrame(),
310
+ "postings": pd.DataFrame(),
311
+ "stats": (sparse_report.get("bm25") or {}).get("bm25")
312
+ or (sparse_report.get("bm25") or {}),
313
+ }
314
+ dummy_graph = {
315
+ "nodes": pd.DataFrame(),
316
+ "edges": pd.DataFrame(),
317
+ "incoming": pd.DataFrame(),
318
+ "outgoing": pd.DataFrame(),
319
+ "stats": sparse_report.get("graph") or {},
320
+ }
321
+ code_root = Path(__file__).resolve().parent.parent
322
+ manifest = package_release(
323
+ out,
324
+ corpus,
325
+ dummy_bm25,
326
+ dummy_graph,
327
+ vectors,
328
+ source_meta,
329
+ country,
330
+ code_root,
331
+ normalization_report=norm_report,
332
+ extra_manifest=extra_manifest,
333
+ wipe=False,
334
+ skip_bm25_graph=True,
335
+ )
336
+ del corpus, vectors
337
+ gc.collect()
338
  _log(f"packaged {out}")
339
  result = {
340
  "country": country["slug"],
 
347
  "vector_blocker": vector_blocker,
348
  "neighbor_via": neighbor_via,
349
  "schema_version": manifest["schema_version"],
350
+ "skipped": False,
351
+ "incremental": extra_manifest["incremental"],
352
  }
353
  if upload:
354
  from .upload import upload_release
 
366
  slugs: list[str] | None = None,
367
  upload: bool = False,
368
  skip_done: bool = True,
369
+ mode: str = "auto",
370
+ force: bool = False,
371
+ skip_vectors: bool = False,
372
  ) -> list[dict[str, Any]]:
373
+ """Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
374
+
375
+ ``skip_done`` is kept for compatibility: it no longer skips a country whose
376
+ source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to
377
+ rebuild regardless of CID overlap.
378
+ """
 
 
379
  targets = slugs or [c["slug"] for c in indexable_countries()]
380
  if "malta" in targets:
381
  targets = ["malta"] + [s for s in targets if s != "malta"]
382
  results = []
383
+ rebuild_force = force or not skip_done
384
  for slug in targets:
 
 
 
385
  try:
386
+ results.append(
387
+ build_country(
388
+ slug,
389
+ upload=upload,
390
+ mode=mode,
391
+ force=rebuild_force,
392
+ skip_vectors=skip_vectors,
393
+ )
394
+ )
395
  except Exception as exc:
396
  _log(f"FAILED {slug}: {exc}")
397
  record_progress(
 
404
  )
405
  continue
406
  return results
407
+
408
+
409
+ def reindex_from_gaps(
410
+ *,
411
+ upload: bool = False,
412
+ slugs: list[str] | None = None,
413
+ limit: int | None = None,
414
+ max_corpus_rows: int | None = 20_000,
415
+ skip_vectors: bool = False,
416
+ workers: int = 4,
417
+ mode: str = "auto",
418
+ force: bool = False,
419
+ all_indexable: bool = False,
420
+ device: str = "cuda",
421
+ ) -> list[dict[str, Any]]:
422
+ """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
423
+
424
+ Default cap skips huge corpora (Finland, Dominican Republic). Pass
425
+ ``max_corpus_rows=None`` to include them.
426
+ """
427
+ from .catalog import indexable_countries
428
+ from .coverage import gap_report
429
+
430
+ if slugs is None:
431
+ if all_indexable:
432
+ rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()]
433
+ _log(f"reindex all indexable n={len(rows)}")
434
+ else:
435
+ report = gap_report(workers=workers)
436
+ rows = [c for c in report["countries"] if c.get("rebuild")]
437
+ _log(
438
+ f"reindex targets n={len(rows)} "
439
+ f"(from scan rebuild={len(report.get('rebuild') or [])})"
440
+ )
441
+ rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
442
+ if max_corpus_rows is not None:
443
+ rows = [
444
+ r
445
+ for r in rows
446
+ if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows)
447
+ ]
448
+ if limit is not None:
449
+ rows = rows[: int(limit)]
450
+ slugs = [str(r["slug"]) for r in rows]
451
+ kwargs = {
452
+ "upload": upload,
453
+ "mode": mode,
454
+ "force": force,
455
+ "skip_vectors": skip_vectors,
456
+ "fetch_hub_prior_ir": True,
457
+ "device": device,
458
+ }
459
+ n_workers = max(1, int(workers or 1))
460
+ _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
461
+ import multiprocessing as mp
462
+ from concurrent.futures import ProcessPoolExecutor, as_completed
463
+
464
+ try:
465
+ mp.set_start_method("spawn", force=False)
466
+ except RuntimeError:
467
+ pass
468
+
469
+ results = [None] * len(slugs)
470
+ with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool:
471
+ futs = {
472
+ pool.submit(_reindex_one_country, (slug, kwargs)): i
473
+ for i, slug in enumerate(slugs)
474
+ }
475
+ for fut in as_completed(futs):
476
+ idx = futs[fut]
477
+ slug = slugs[idx]
478
+ try:
479
+ results[idx] = fut.result()
480
+ except Exception as exc:
481
+ _log(f"FAILED {slug}: {exc}")
482
+ results[idx] = {"country": slug, "skipped": False, "error": str(exc)}
483
+ return [r for r in results if r is not None]
484
+
485
+
486
+ def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]:
487
+ slug, kwargs = item
488
+ _log(f"reindex start {slug}")
489
+ try:
490
+ return build_country(slug, **kwargs)
491
+ except Exception as exc:
492
+ _log(f"FAILED {slug}: {exc}")
493
+ record_progress(
494
+ {
495
+ "event": "failed",
496
+ "country": slug,
497
+ "error": str(exc),
498
+ "traceback": traceback.format_exc(),
499
+ }
500
+ )
501
+ return {"country": slug, "skipped": False, "error": str(exc)}
country_laws_ir/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,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = (
163
+ status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"}
164
+ and (not local_current or status == "stub_vectors")
165
+ )
166
+ publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (
167
+ "source_missing_laws" not in issues
168
+ )
169
+ return {
170
+ "status": status,
171
+ "issues": issues,
172
+ "rebuild": rebuild,
173
+ "publish": publish,
174
+ }
175
+
176
+
177
+ def _ir_source_revision(manifest: Mapping[str, Any] | None) -> str | None:
178
+ if not manifest:
179
+ return None
180
+ pinned = manifest.get("dataset_revision") or (manifest.get("source") or {}).get(
181
+ "source_revision"
182
+ )
183
+ text = str(pinned or "").strip()
184
+ return text or None
185
+
186
+
187
+ def _vector_status(manifest: Mapping[str, Any] | None) -> str | None:
188
+ if not manifest:
189
+ return None
190
+ vector = manifest.get("vector") or {}
191
+ if isinstance(vector, dict) and vector.get("status"):
192
+ return str(vector.get("status"))
193
+ incremental = manifest.get("incremental") or {}
194
+ nested = incremental.get("vectors") if isinstance(incremental, dict) else None
195
+ if isinstance(nested, dict) and nested.get("status"):
196
+ return str(nested.get("status"))
197
+ if isinstance(vector, dict) and vector.get("stub"):
198
+ return "stub"
199
+ return None
200
+
201
+
202
+ def load_local_manifest(release_dir: Path) -> dict[str, Any]:
203
+ path = Path(release_dir) / "manifest.json"
204
+ if not path.is_file():
205
+ return {}
206
+ try:
207
+ data = json.loads(path.read_text(encoding="utf-8"))
208
+ except Exception:
209
+ return {}
210
+ return data if isinstance(data, dict) else {}
211
+
212
+
213
+ def _sibling_map(info: Any) -> dict[str, int | None]:
214
+ out: dict[str, int | None] = {}
215
+ for sib in getattr(info, "siblings", None) or []:
216
+ name = str(getattr(sib, "rfilename", "") or "")
217
+ if not name:
218
+ continue
219
+ size = getattr(sib, "size", None)
220
+ try:
221
+ out[name] = int(size) if size is not None else None # type: ignore[assignment]
222
+ except (TypeError, ValueError):
223
+ out[name] = None # type: ignore[assignment]
224
+ return out
225
+
226
+
227
+ def _inspect_source(slug: str, cache_dir: Path | None = None) -> dict[str, Any]:
228
+ from huggingface_hub import dataset_info
229
+
230
+ from .auth import configure_hf, operator_token, public_token
231
+
232
+ repo = f"endomorphosis/ipfs_{slug}_laws"
233
+ configure_hf()
234
+ info = dataset_info(repo, token=operator_token() or public_token())
235
+ files = _sibling_map(info)
236
+ laws_file = next(
237
+ (name for name in ("data/laws.parquet", "laws.parquet") if name in files),
238
+ None,
239
+ )
240
+ arts_file = next(
241
+ (name for name in ("data/articles.parquet", "articles.parquet") if name in files),
242
+ None,
243
+ )
244
+ return {
245
+ "repo": repo,
246
+ "revision": getattr(info, "sha", None),
247
+ "files": sorted(files),
248
+ "has_laws": laws_file is not None,
249
+ "has_articles": arts_file is not None,
250
+ "laws_bytes": files.get(laws_file) if laws_file else None,
251
+ "articles_bytes": files.get(arts_file) if arts_file else None,
252
+ }
253
+
254
+
255
+ def _inspect_ir(slug: str, cache_dir: Path) -> dict[str, Any] | None:
256
+ from huggingface_hub import HfApi, dataset_info, hf_hub_download
257
+ from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError
258
+
259
+ from .auth import configure_hf, operator_token, public_token
260
+
261
+ repo = target_repo(slug)
262
+ configure_hf()
263
+ token = operator_token() or public_token()
264
+ try:
265
+ info = dataset_info(repo, token=token)
266
+ except RepositoryNotFoundError:
267
+ return None
268
+ files = _sibling_map(info)
269
+ if len(files) < 8:
270
+ try:
271
+ listed = HfApi(token=token).list_repo_files(repo_id=repo, repo_type="dataset")
272
+ for name in listed:
273
+ files.setdefault(str(name), None)
274
+ except Exception:
275
+ pass
276
+ manifest: dict[str, Any] = {}
277
+ if "manifest.json" in files:
278
+ try:
279
+ path = hf_hub_download(
280
+ repo_id=repo,
281
+ filename="manifest.json",
282
+ repo_type="dataset",
283
+ token=token,
284
+ cache_dir=str(cache_dir / "hf"),
285
+ )
286
+ payload = json.loads(Path(path).read_text(encoding="utf-8"))
287
+ if isinstance(payload, dict):
288
+ manifest = payload
289
+ except (EntryNotFoundError, OSError, json.JSONDecodeError):
290
+ manifest = {}
291
+ counts = manifest.get("counts") if isinstance(manifest.get("counts"), dict) else {}
292
+ return {
293
+ "repo": repo,
294
+ "hub_revision": getattr(info, "sha", None),
295
+ "files": sorted(files),
296
+ "manifest": manifest,
297
+ "source_revision": _ir_source_revision(manifest),
298
+ "corpus_rows": counts.get("corpus_rows"),
299
+ "vector_status": _vector_status(manifest),
300
+ }
301
+
302
+
303
+ def gap_report(
304
+ releases_dir: Path | None = None,
305
+ *,
306
+ slugs: list[str] | None = None,
307
+ workers: int = 8,
308
+ ) -> dict[str, Any]:
309
+ """Live Hub scan: missing, stale, incomplete, and unpublished country IR."""
310
+ from .build import CACHE, RELEASES
311
+
312
+ sources = slugs or [
313
+ s
314
+ for s in list_hub_slugs(author="endomorphosis", kind="source")
315
+ if s not in ALIAS_TO_CANONICAL
316
+ ]
317
+ hub_ir = set(list_hub_slugs(author="justicedao", kind="ir"))
318
+ local_dir = Path(releases_dir) if releases_dir else RELEASES
319
+ local_ir = set(local_release_slugs(local_dir))
320
+ cache_dir = CACHE
321
+ cache_dir.mkdir(parents=True, exist_ok=True)
322
+
323
+ rows: list[dict[str, Any]] = []
324
+
325
+ def _one(slug: str) -> dict[str, Any]:
326
+ last_exc: Exception | None = None
327
+ for attempt in range(4):
328
+ try:
329
+ source = _inspect_source(slug)
330
+ ir = _inspect_ir(slug, cache_dir) if slug in hub_ir else None
331
+ break
332
+ except Exception as exc:
333
+ last_exc = exc
334
+ name = type(exc).__name__
335
+ msg = str(exc)
336
+ if "429" in msg or "rate limit" in msg.lower():
337
+ time.sleep(min(45, 3 ** attempt * 2))
338
+ continue
339
+ raise
340
+ else:
341
+ raise last_exc or RuntimeError(f"scan failed for {slug}")
342
+ local_manifest = load_local_manifest(local_dir / f"ipfs_{slug}_laws_ir")
343
+ local_rev = _ir_source_revision(local_manifest) if local_manifest else None
344
+ classified = classify_gap(
345
+ excluded=slug in EXCLUDED_SLUGS,
346
+ alias=False,
347
+ source_has_laws=bool(source.get("has_laws")),
348
+ source_laws_bytes=source.get("laws_bytes"),
349
+ source_revision=source.get("revision"),
350
+ ir_files=None if ir is None else ir.get("files"),
351
+ ir_source_revision=(ir or {}).get("source_revision") or local_rev,
352
+ ir_corpus_rows=(ir or {}).get("corpus_rows")
353
+ if ir is not None
354
+ else (local_manifest.get("counts") or {}).get("corpus_rows")
355
+ if local_manifest
356
+ else None,
357
+ vector_status=(ir or {}).get("vector_status")
358
+ or _vector_status(local_manifest),
359
+ local_only=slug in local_ir and slug not in hub_ir,
360
+ local_source_revision=local_rev,
361
+ )
362
+ return {
363
+ "slug": slug,
364
+ "source": source.get("repo"),
365
+ "target": target_repo(slug),
366
+ "source_revision": source.get("revision"),
367
+ "ir_source_revision": (ir or {}).get("source_revision"),
368
+ "local_source_revision": local_rev,
369
+ "has_hub_ir": ir is not None,
370
+ "has_local_ir": slug in local_ir,
371
+ "source_has_articles": source.get("has_articles"),
372
+ "source_laws_bytes": source.get("laws_bytes"),
373
+ "corpus_rows": (ir or {}).get("corpus_rows")
374
+ if ir is not None
375
+ else (local_manifest.get("counts") or {}).get("corpus_rows")
376
+ if local_manifest
377
+ else None,
378
+ "vector_status": (ir or {}).get("vector_status")
379
+ or _vector_status(local_manifest),
380
+ **classified,
381
+ }
382
+
383
+ workers = max(1, min(int(workers), 16))
384
+ with ThreadPoolExecutor(max_workers=workers) as pool:
385
+ futs = {pool.submit(_one, slug): slug for slug in sources}
386
+ for fut in as_completed(futs):
387
+ slug = futs[fut]
388
+ try:
389
+ rows.append(fut.result())
390
+ except Exception as exc:
391
+ rows.append(
392
+ {
393
+ "slug": slug,
394
+ "source": f"endomorphosis/ipfs_{slug}_laws",
395
+ "target": target_repo(slug),
396
+ "status": "incomplete",
397
+ "issues": [f"scan_error:{type(exc).__name__}"],
398
+ "rebuild": False,
399
+ "publish": False,
400
+ "error": str(exc),
401
+ }
402
+ )
403
+ rows.sort(key=lambda r: str(r.get("slug")))
404
+ by_status: dict[str, list[str]] = {}
405
+ for row in rows:
406
+ by_status.setdefault(str(row.get("status")), []).append(str(row.get("slug")))
407
+ return {
408
+ "n": len(rows),
409
+ "by_status": {k: sorted(v) for k, v in sorted(by_status.items())},
410
+ "counts": {k: len(v) for k, v in sorted(by_status.items())},
411
+ "rebuild": [r["slug"] for r in rows if r.get("rebuild")],
412
+ "publish": [r["slug"] for r in rows if r.get("publish")],
413
+ "countries": rows,
414
+ }
415
+
416
+
417
+ def coverage_report(releases_dir: Path | None = None) -> dict[str, Any]:
418
+ from .build import RELEASES
419
+
420
+ sources = list_hub_slugs(author="endomorphosis", kind="source")
421
+ hub_ir = list_hub_slugs(author="justicedao", kind="ir")
422
+ local_ir = local_release_slugs(Path(releases_dir) if releases_dir else RELEASES)
423
+ hub_ir_canon = {canonical_slug(s) for s in hub_ir}
424
+ local_ir_canon = {canonical_slug(s) for s in local_ir}
425
+ missing_hub: list[dict[str, Any]] = []
426
+ missing_local: list[dict[str, Any]] = []
427
+ excluded: list[str] = []
428
+ aliases: list[str] = []
429
+ for slug in sources:
430
+ if slug in ALIAS_TO_CANONICAL:
431
+ aliases.append(slug)
432
+ continue
433
+ if slug in EXCLUDED_SLUGS:
434
+ excluded.append(slug)
435
+ continue
436
+ row = {
437
+ "slug": slug,
438
+ "source": f"endomorphosis/ipfs_{slug}_laws",
439
+ "target": target_repo(slug),
440
+ }
441
+ if slug not in hub_ir_canon:
442
+ missing_hub.append(row)
443
+ if slug not in local_ir_canon and slug not in hub_ir_canon:
444
+ missing_local.append(row)
445
+ return {
446
+ "n_sources": len(sources),
447
+ "n_hub_ir": len(hub_ir),
448
+ "n_local_ir": len(local_ir),
449
+ "n_catalog": len(all_countries()),
450
+ "excluded": excluded,
451
+ "alias_sources": aliases,
452
+ "missing_justicedao": missing_hub,
453
+ "missing_local_and_hub": missing_local,
454
+ "local_only": sorted(local_ir_canon - hub_ir_canon),
455
+ }
country_laws_ir/duckdb_store.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DuckDB views over country-laws sparse GraphRAG parquet shards.
2
+
3
+ Published artifacts are ZSTD parquet (SkillCenter / publicus-ir family).
4
+ Query and large-corpus neighbor generation read those shards through DuckDB
5
+ instead of loading them into pandas or SQLite.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import pandas as pd
15
+
16
+ K1 = 1.2
17
+ B = 0.75
18
+ TITLE_WEIGHT = 5.0
19
+ BODY_WEIGHT = 1.0
20
+ MAX_QUERY_TERMS = 64
21
+
22
+ VIEWS = (
23
+ ("corpus", "data/corpus/*.parquet"),
24
+ ("bm25_documents", "data/bm25/documents/*.parquet"),
25
+ ("bm25_postings", "data/bm25/postings/*.parquet"),
26
+ ("graph_nodes", "data/graph/nodes/*.parquet"),
27
+ ("graph_edges", "data/graph/edges/*.parquet"),
28
+ # Shared hf_graphrag layout (US Code / state laws / FR).
29
+ ("graph_in", "data/graph/adjacency/in/*.parquet"),
30
+ ("graph_out", "data/graph/adjacency/out/*.parquet"),
31
+ # Legacy country-laws-ir layout still on some Hub packs.
32
+ ("graph_incoming", "data/graph/adjacency/incoming/*.parquet"),
33
+ ("graph_outgoing", "data/graph/adjacency/outgoing/*.parquet"),
34
+ ("vectors", "data/vectors/*.parquet"),
35
+ )
36
+
37
+
38
+ class DuckDBStoreError(RuntimeError):
39
+ """Raised when a parquet/DuckDB sparse index cannot be opened."""
40
+
41
+
42
+ def _require_duckdb():
43
+ try:
44
+ import duckdb # type: ignore
45
+ except ImportError as exc:
46
+ raise DuckDBStoreError("duckdb is required for parquet sparse GraphRAG query") from exc
47
+ return duckdb
48
+
49
+
50
+ def parquet_glob(root: Path, pattern: str) -> str:
51
+ return str(Path(root) / pattern)
52
+
53
+
54
+ def connect_release(root: Path, *, database: str = ":memory:"):
55
+ """Open a DuckDB connection with views over parquet shards."""
56
+ duckdb = _require_duckdb()
57
+ root = Path(root)
58
+ if not (root / "manifest.json").is_file():
59
+ raise DuckDBStoreError(f"release missing manifest.json: {root}")
60
+ con = duckdb.connect(database)
61
+ for name, pattern in VIEWS:
62
+ glob = parquet_glob(root, pattern)
63
+ if list(root.glob(pattern)):
64
+ escaped = glob.replace("'", "''")
65
+ con.execute(
66
+ f"CREATE OR REPLACE VIEW {name} AS SELECT * FROM read_parquet('{escaped}')"
67
+ )
68
+ return con
69
+
70
+
71
+ def load_manifest(root: Path) -> dict[str, Any]:
72
+ return json.loads((Path(root) / "manifest.json").read_text(encoding="utf-8"))
73
+
74
+
75
+ def tokenize(text: str) -> list[str]:
76
+ import re
77
+ import unicodedata
78
+
79
+ if not text:
80
+ return []
81
+ nfkd = unicodedata.normalize("NFKD", text)
82
+ folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
83
+ return re.findall(r"[0-9A-Za-z]+", folded)
84
+
85
+
86
+ def bm25_search(root: Path, query: str, top_k: int = 10) -> list[dict[str, Any]]:
87
+ """Okapi BM25 over parquet posting shards via DuckDB UNNEST."""
88
+ terms = tokenize(query)[:MAX_QUERY_TERMS]
89
+ if not terms:
90
+ return []
91
+ manifest = load_manifest(root)
92
+ avgdl = float((manifest.get("bm25") or {}).get("average_document_length") or 1.0) or 1.0
93
+ con = connect_release(root)
94
+ try:
95
+ tables = {
96
+ r[0]
97
+ for r in con.execute(
98
+ "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
99
+ ).fetchall()
100
+ }
101
+ if "bm25_postings" not in tables or "bm25_documents" not in tables:
102
+ raise DuckDBStoreError("release is missing BM25 parquet shards")
103
+ placeholders = ", ".join(["?"] * len(terms))
104
+ sql = f"""
105
+ WITH exploded AS (
106
+ SELECT
107
+ unnest(document_indices) AS document_index,
108
+ unnest(title_frequencies) AS title_tf,
109
+ unnest(body_frequencies) AS body_tf,
110
+ unnest(document_lengths) AS dl,
111
+ idf
112
+ FROM bm25_postings
113
+ WHERE term IN ({placeholders})
114
+ ),
115
+ scored AS (
116
+ SELECT
117
+ document_index,
118
+ SUM(
119
+ idf * (
120
+ ( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf )
121
+ * ({K1} + 1.0)
122
+ ) / (
123
+ ( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf )
124
+ + {K1} * (1.0 - {B} + {B} * (dl / {avgdl}))
125
+ )
126
+ ) AS score
127
+ FROM exploded
128
+ GROUP BY document_index
129
+ )
130
+ SELECT
131
+ s.document_index,
132
+ s.score,
133
+ d.entry_cid,
134
+ d.title,
135
+ d.record_type
136
+ FROM scored s
137
+ JOIN bm25_documents d USING (document_index)
138
+ ORDER BY s.score DESC, s.document_index
139
+ LIMIT ?
140
+ """
141
+ rows = con.execute(sql, [*terms, int(top_k)]).fetchall()
142
+ cols = [
143
+ "document_index",
144
+ "score",
145
+ "entry_cid",
146
+ "title",
147
+ "record_type",
148
+ ]
149
+ return [dict(zip(cols, row)) for row in rows]
150
+ finally:
151
+ con.close()
152
+
153
+
154
+ def graph_neighbors(
155
+ root: Path,
156
+ node_cid: str,
157
+ *,
158
+ direction: str = "both",
159
+ limit: int = 25,
160
+ ) -> list[dict[str, Any]]:
161
+ """Adjacency lookup over parquet shards via DuckDB."""
162
+ aliases = {
163
+ "both": ("in", "out", "incoming", "outgoing"),
164
+ "in": ("in", "incoming"),
165
+ "out": ("out", "outgoing"),
166
+ "incoming": ("in", "incoming"),
167
+ "outgoing": ("out", "outgoing"),
168
+ }
169
+ dirs = aliases.get(direction, (direction,))
170
+ con = connect_release(root)
171
+ try:
172
+ tables = {
173
+ r[0]
174
+ for r in con.execute(
175
+ "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
176
+ ).fetchall()
177
+ }
178
+ hits: list[dict[str, Any]] = []
179
+ for d in dirs:
180
+ view = {
181
+ "in": "graph_in",
182
+ "out": "graph_out",
183
+ "incoming": "graph_incoming",
184
+ "outgoing": "graph_outgoing",
185
+ }.get(d, d)
186
+ if view not in tables:
187
+ continue
188
+ rows = con.execute(
189
+ f"""
190
+ SELECT node_cid, neighbor_cids, edge_types, scores
191
+ FROM {view}
192
+ WHERE node_cid = ?
193
+ """,
194
+ [node_cid],
195
+ ).fetchall()
196
+ for node, neighs, types, scores in rows:
197
+ neighs = list(neighs or [])
198
+ types = list(types or [])
199
+ scores = list(scores or [])
200
+ for i, neigh in enumerate(neighs):
201
+ hits.append(
202
+ {
203
+ "direction": d,
204
+ "node_cid": node,
205
+ "neighbor_cid": neigh,
206
+ "edge_type": types[i] if i < len(types) else "",
207
+ "score": scores[i] if i < len(scores) else None,
208
+ }
209
+ )
210
+ hits.sort(key=lambda r: (-(r["score"] or 0), str(r["neighbor_cid"])))
211
+ return hits[: int(limit)]
212
+ finally:
213
+ con.close()
214
+
215
+
216
+ def build_fts_index(
217
+ corpus_parquet: Path,
218
+ duckdb_path: Path,
219
+ expected: int,
220
+ *,
221
+ log: Any | None = None,
222
+ ) -> Path:
223
+ """Load corpus parquet into DuckDB and create an FTS index (no SQLite)."""
224
+ duckdb = _require_duckdb()
225
+ duckdb_path = Path(duckdb_path)
226
+ duckdb_path.parent.mkdir(parents=True, exist_ok=True)
227
+ if duckdb_path.exists():
228
+ duckdb_path.unlink()
229
+ escaped = str(Path(corpus_parquet).resolve()).replace("'", "''")
230
+ con = duckdb.connect(str(duckdb_path))
231
+ try:
232
+ con.execute(
233
+ f"""
234
+ CREATE TABLE documents AS
235
+ SELECT
236
+ CAST(document_index AS INTEGER) AS document_index,
237
+ CAST(entry_cid AS VARCHAR) AS entry_cid,
238
+ CAST(COALESCE(title, '') AS VARCHAR) AS title,
239
+ CAST(COALESCE(body, '') AS VARCHAR) AS body
240
+ FROM read_parquet('{escaped}')
241
+ """
242
+ )
243
+ n = int(con.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
244
+ if n != int(expected):
245
+ raise DuckDBStoreError(f"DuckDB corpus rows {n} != expected {expected}")
246
+ con.execute("INSTALL fts")
247
+ con.execute("LOAD fts")
248
+ con.execute(
249
+ "PRAGMA create_fts_index('documents', 'document_index', 'title', 'body', "
250
+ "stemmer='porter', stopwords='english', ignore='(\\.+)', strip_accents=1, lower=1)"
251
+ )
252
+ if log:
253
+ log(f"duckdb fts ready n={n} path={duckdb_path}")
254
+ finally:
255
+ con.close()
256
+ return duckdb_path
257
+
258
+
259
+ def stream_neighbors_to_parquet(
260
+ duckdb_path: Path,
261
+ spill: Path,
262
+ n_docs: int,
263
+ *,
264
+ k: int = 8,
265
+ shard: int = 5000,
266
+ batch: int = 256,
267
+ resume: bool = True,
268
+ log: Any | None = None,
269
+ ) -> list[Path]:
270
+ """Stream DuckDB FTS neighbors into flattened neighbor_*.parquet shards."""
271
+ duckdb = _require_duckdb()
272
+ spill = Path(spill)
273
+ spill.mkdir(parents=True, exist_ok=True)
274
+ existing = sorted(spill.glob("neighbors_*.parquet"))
275
+ buf_start = 0
276
+ shard_paths: list[Path] = []
277
+ if resume and existing:
278
+ covered = 0
279
+ for path in existing:
280
+ parts = path.stem.split("_")
281
+ try:
282
+ start_i, end_i = int(parts[1]), int(parts[2])
283
+ except (IndexError, ValueError):
284
+ continue
285
+ if start_i != covered:
286
+ break
287
+ shard_paths.append(path)
288
+ covered = end_i
289
+ buf_start = covered
290
+ if buf_start >= n_docs:
291
+ if log:
292
+ log(f"neighbors resume complete {buf_start}/{n_docs}")
293
+ return shard_paths
294
+ for path in existing:
295
+ if path not in shard_paths:
296
+ path.unlink(missing_ok=True)
297
+ else:
298
+ for path in existing:
299
+ path.unlink(missing_ok=True)
300
+
301
+ con = duckdb.connect(str(duckdb_path), read_only=True)
302
+ con.execute("LOAD fts")
303
+ rows_buf: list[dict[str, Any]] = []
304
+ shard_start = buf_start
305
+ last_idx = buf_start - 1
306
+ done = buf_start
307
+ try:
308
+ while True:
309
+ batch_rows = con.execute(
310
+ "SELECT document_index, title, body FROM documents "
311
+ "WHERE document_index > ? ORDER BY document_index LIMIT ?",
312
+ [last_idx, batch],
313
+ ).fetchall()
314
+ if not batch_rows:
315
+ break
316
+ for di, title, body in batch_rows:
317
+ di = int(di)
318
+ query = (str(title or "").strip() or str(body or "")[:800]).strip()
319
+ hits: list[tuple[int, float]] = []
320
+ if query:
321
+ hits = con.execute(
322
+ "SELECT document_index, "
323
+ "fts_main_documents.match_bm25(document_index, ?) AS score "
324
+ "FROM documents "
325
+ "WHERE document_index != ? AND score IS NOT NULL "
326
+ "ORDER BY score DESC, document_index "
327
+ "LIMIT ?",
328
+ [query, di, int(k)],
329
+ ).fetchall()
330
+ for neigh_i, score in hits:
331
+ rows_buf.append(
332
+ {
333
+ "source_index": di,
334
+ "neighbor_index": int(neigh_i),
335
+ "score": float(score or 0.0),
336
+ }
337
+ )
338
+ last_idx = di
339
+ done += 1
340
+ if (di + 1 - shard_start) >= shard:
341
+ end = di + 1
342
+ path = spill / f"neighbors_{shard_start:06d}_{end:06d}.parquet"
343
+ pd.DataFrame(rows_buf).to_parquet(path, index=False)
344
+ shard_paths.append(path)
345
+ rows_buf = []
346
+ shard_start = end
347
+ if log:
348
+ log(f"neighbors parquet shard {path.name}")
349
+ if done % 5_000 == 0 and log:
350
+ log(f"duckdb neighbors {done}/{n_docs}")
351
+ if shard_start < n_docs:
352
+ path = spill / f"neighbors_{shard_start:06d}_{n_docs:06d}.parquet"
353
+ pd.DataFrame(rows_buf).to_parquet(path, index=False)
354
+ shard_paths.append(path)
355
+ if log:
356
+ log(f"duckdb neighbors done={done} shards={len(shard_paths)}")
357
+ return shard_paths
358
+ finally:
359
+ con.close()
360
+
361
+
362
+ def iter_neighbor_parquet_shards(spill: Path) -> Any:
363
+ """Yield (start_index, list-of-neighbor-lists) from parquet shards."""
364
+ import pandas as pd
365
+
366
+ paths = sorted(Path(spill).glob("neighbors_*.parquet"))
367
+ for path in paths:
368
+ parts = path.stem.split("_")
369
+ start_i = int(parts[1])
370
+ end_i = int(parts[2])
371
+ frame = pd.read_parquet(path)
372
+ part: list[list] = [[] for _ in range(max(0, end_i - start_i))]
373
+ if not frame.empty:
374
+ for rec in frame.itertuples(index=False):
375
+ src = int(rec.source_index)
376
+ offset = src - start_i
377
+ if 0 <= offset < len(part):
378
+ part[offset].append(
379
+ (int(rec.neighbor_index), float(rec.score), [])
380
+ )
381
+ yield start_i, part
382
+
383
+
384
+ def materialize_corpus_duckdb(corpus_parquet: Path, duckdb_path: Path) -> Path:
385
+ """Load a corpus parquet file into a persistent DuckDB database."""
386
+ duckdb = _require_duckdb()
387
+ duckdb_path = Path(duckdb_path)
388
+ duckdb_path.parent.mkdir(parents=True, exist_ok=True)
389
+ if duckdb_path.exists():
390
+ duckdb_path.unlink()
391
+ con = duckdb.connect(str(duckdb_path))
392
+ try:
393
+ con.execute(
394
+ """
395
+ CREATE TABLE documents AS
396
+ SELECT
397
+ CAST(document_index AS INTEGER) AS document_index,
398
+ CAST(entry_cid AS VARCHAR) AS entry_cid,
399
+ CAST(title AS VARCHAR) AS title,
400
+ CAST(body AS VARCHAR) AS body
401
+ FROM read_parquet(?)
402
+ """,
403
+ [str(corpus_parquet)],
404
+ )
405
+ con.execute("CREATE INDEX documents_idx ON documents(document_index)")
406
+ finally:
407
+ con.close()
408
+ return duckdb_path
country_laws_ir/incremental.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ rebuild_stub_vectors: bool = True,
238
+ ) -> RebuildPlan:
239
+ """Decide skip / delta / full from source fingerprints and CID overlap."""
240
+ mode = BuildMode.coerce(mode)
241
+ revision = str(source_meta.get("source_revision") or "")
242
+ fingerprint = source_fingerprint(source_meta)
243
+ prior_revision = prior.source_revision if prior is not None else None
244
+ prior_fp = prior.fingerprint if prior is not None else None
245
+
246
+ if force or mode is BuildMode.FULL:
247
+ delta = None
248
+ if current_corpus is not None and prior is not None:
249
+ delta = diff_corpus(prior.corpus, current_corpus)
250
+ return RebuildPlan(
251
+ kind=RebuildKind.FULL_REBUILD,
252
+ mode=mode,
253
+ reason="operator forced full rebuild" if force else "build mode is full",
254
+ source_revision=revision,
255
+ prior_revision=prior_revision,
256
+ source_fingerprint=fingerprint,
257
+ prior_fingerprint=prior_fp,
258
+ delta=delta,
259
+ reuse_embeddings=False,
260
+ skip_build=False,
261
+ equivalent_to_full=True,
262
+ )
263
+
264
+ if prior is None:
265
+ return RebuildPlan(
266
+ kind=RebuildKind.FULL_REBUILD,
267
+ mode=mode,
268
+ reason="no prior release",
269
+ source_revision=revision,
270
+ prior_revision=None,
271
+ source_fingerprint=fingerprint,
272
+ prior_fingerprint=None,
273
+ delta=None,
274
+ reuse_embeddings=False,
275
+ skip_build=False,
276
+ equivalent_to_full=True,
277
+ )
278
+
279
+ prior_vector_status = str(
280
+ ((prior.manifest.get("vector") or {}) if prior.manifest else {}).get("status")
281
+ or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status")
282
+ or ""
283
+ ).strip().lower()
284
+ stub_vectors = rebuild_stub_vectors and prior_vector_status in {
285
+ "stub",
286
+ "stub_missing_encoder",
287
+ "incomplete",
288
+ "partial",
289
+ }
290
+
291
+ if prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors:
292
+ return RebuildPlan(
293
+ kind=RebuildKind.UNCHANGED,
294
+ mode=mode,
295
+ reason="source revision and parquet digests match prior release",
296
+ source_revision=revision,
297
+ prior_revision=prior_revision,
298
+ source_fingerprint=fingerprint,
299
+ prior_fingerprint=prior_fp,
300
+ delta=CorpusDelta(
301
+ unchanged_cids=tuple(sorted(_cid_set(prior.corpus))),
302
+ prior_count=int(len(_cid_set(prior.corpus))),
303
+ current_count=int(len(_cid_set(prior.corpus))),
304
+ changed_ratio=0.0,
305
+ equivalent_to_full=False,
306
+ ),
307
+ reuse_embeddings=True,
308
+ skip_build=True,
309
+ equivalent_to_full=False,
310
+ )
311
+
312
+ delta = None
313
+ if current_corpus is not None:
314
+ delta = diff_corpus(prior.corpus, current_corpus)
315
+ if delta.equivalent_to_full:
316
+ return RebuildPlan(
317
+ kind=RebuildKind.FULL_REBUILD,
318
+ mode=mode,
319
+ reason="CID overlap is empty; delta equals a full rebuild",
320
+ source_revision=revision,
321
+ prior_revision=prior_revision,
322
+ source_fingerprint=fingerprint,
323
+ prior_fingerprint=prior_fp,
324
+ delta=delta,
325
+ reuse_embeddings=False,
326
+ skip_build=False,
327
+ equivalent_to_full=True,
328
+ )
329
+
330
+ reason = (
331
+ "source fingerprint matches but vectors are stub/incomplete; encode missing CIDs"
332
+ if stub_vectors and prior_fp == fingerprint
333
+ else "source changed; reuse embeddings for unchanged entry_cids"
334
+ )
335
+ return RebuildPlan(
336
+ kind=RebuildKind.DELTA_REFRESH,
337
+ mode=mode,
338
+ reason=reason,
339
+ source_revision=revision,
340
+ prior_revision=prior_revision,
341
+ source_fingerprint=fingerprint,
342
+ prior_fingerprint=prior_fp,
343
+ delta=delta,
344
+ reuse_embeddings=True,
345
+ skip_build=False,
346
+ equivalent_to_full=False,
347
+ )
348
+
349
+
350
+ def _read_sharded_parquet(directory: Path) -> pd.DataFrame | None:
351
+ if not directory.is_dir():
352
+ return None
353
+ parts = sorted(directory.glob("part-*.parquet"))
354
+ if not parts:
355
+ parts = sorted(p for p in directory.rglob("*.parquet") if p.is_file())
356
+ if not parts:
357
+ return None
358
+ frames = [pd.read_parquet(p) for p in parts]
359
+ return pd.concat(frames, ignore_index=True) if frames else None
360
+
361
+
362
+ def load_release_manifest(release_dir: Path) -> dict[str, Any]:
363
+ path = Path(release_dir) / "manifest.json"
364
+ if not path.is_file():
365
+ return {}
366
+ try:
367
+ data = json.loads(path.read_text(encoding="utf-8"))
368
+ except Exception:
369
+ return {}
370
+ return data if isinstance(data, dict) else {}
371
+
372
+
373
+ def load_release_corpus(release_dir: Path) -> pd.DataFrame | None:
374
+ release_dir = Path(release_dir)
375
+ corpus = _read_sharded_parquet(release_dir / "data" / "corpus")
376
+ if corpus is not None:
377
+ return corpus
378
+ checkpoint = release_dir / "corpus.parquet"
379
+ if checkpoint.is_file():
380
+ return pd.read_parquet(checkpoint)
381
+ return None
382
+
383
+
384
+ def embeddings_from_vector_table(frame: pd.DataFrame) -> dict[str, list[float]]:
385
+ out: dict[str, list[float]] = {}
386
+ if frame is None or frame.empty:
387
+ return out
388
+ if "entry_cid" not in frame.columns or "embedding" not in frame.columns:
389
+ return out
390
+ for rec in frame.itertuples(index=False):
391
+ cid = str(getattr(rec, "entry_cid", "") or "")
392
+ emb = getattr(rec, "embedding", None)
393
+ if not cid or emb is None:
394
+ continue
395
+ if isinstance(emb, float) and pd.isna(emb):
396
+ continue
397
+ try:
398
+ values = [float(x) for x in list(emb)]
399
+ except Exception:
400
+ continue
401
+ if not values:
402
+ continue
403
+ out[cid] = values
404
+ return out
405
+
406
+
407
+ def load_release_vectors_by_cid(release_dir: Path) -> dict[str, list[float]]:
408
+ frame = _read_sharded_parquet(Path(release_dir) / "data" / "vectors")
409
+ if frame is None:
410
+ return {}
411
+ return embeddings_from_vector_table(frame)
412
+
413
+
414
+ def load_prior_release(release_dir: Path | None) -> PriorRelease | None:
415
+ if release_dir is None:
416
+ return None
417
+ directory = Path(release_dir)
418
+ if not directory.is_dir():
419
+ return None
420
+ manifest = load_release_manifest(directory)
421
+ if not manifest and not (directory / "data").is_dir():
422
+ return None
423
+ return PriorRelease(
424
+ directory=directory,
425
+ manifest=manifest,
426
+ corpus=load_release_corpus(directory),
427
+ vectors_by_cid=None,
428
+ )
429
+
430
+
431
+ def load_embedding_cache(path: Path) -> dict[str, list[float]]:
432
+ if not path.is_file():
433
+ return {}
434
+ try:
435
+ frame = pd.read_parquet(path)
436
+ except Exception:
437
+ return {}
438
+ return embeddings_from_vector_table(frame)
439
+
440
+
441
+ def save_embedding_cache(
442
+ path: Path,
443
+ by_cid: Mapping[str, Iterable[float]],
444
+ *,
445
+ model_name: str,
446
+ dimension: int,
447
+ ) -> None:
448
+ path.parent.mkdir(parents=True, exist_ok=True)
449
+ rows = [
450
+ {
451
+ "entry_cid": cid,
452
+ "embedding": list(vec),
453
+ "model_name": model_name,
454
+ "dimension": int(dimension),
455
+ }
456
+ for cid, vec in sorted(by_cid.items())
457
+ ]
458
+ frame = pd.DataFrame(rows)
459
+ tmp = path.with_suffix(path.suffix + ".tmp")
460
+ frame.to_parquet(tmp, index=False)
461
+ tmp.replace(path)
462
+
463
+
464
+ def merge_embedding_maps(
465
+ *maps: Mapping[str, list[float]] | None,
466
+ ) -> dict[str, list[float]]:
467
+ merged: dict[str, list[float]] = {}
468
+ for mapping in maps:
469
+ if not mapping:
470
+ continue
471
+ merged.update(mapping)
472
+ return merged
473
+
474
+
475
+ def fetch_hub_prior(
476
+ slug: str,
477
+ dest: Path | None = None,
478
+ *,
479
+ cache_root: Path | None = None,
480
+ ) -> Path | None:
481
+ """Download JusticeDAO corpus+vector shards to use as an incremental parent.
482
+
483
+ Missing Hub IR is not an error: first-time countries return ``None``.
484
+ """
485
+ from huggingface_hub import snapshot_download
486
+ from huggingface_hub.errors import RepositoryNotFoundError
487
+
488
+ from .auth import operator_token, public_token
489
+ from .catalog import target_repo
490
+
491
+ root = Path(cache_root) if cache_root is not None else (
492
+ Path.home() / ".ipfs_datasets" / "country-laws-ir" / "cache" / "hub-ir"
493
+ )
494
+ dest = Path(dest) if dest is not None else (root / slug)
495
+ dest.mkdir(parents=True, exist_ok=True)
496
+ repo = target_repo(slug)
497
+ try:
498
+ snapshot_download(
499
+ repo_id=repo,
500
+ repo_type="dataset",
501
+ local_dir=str(dest),
502
+ allow_patterns=[
503
+ "manifest.json",
504
+ "data/vectors/**",
505
+ "data/corpus/**",
506
+ "indexes/vector_chunks.parquet",
507
+ ],
508
+ token=operator_token() or public_token(),
509
+ )
510
+ except RepositoryNotFoundError:
511
+ return None
512
+ except Exception:
513
+ if not (dest / "manifest.json").is_file():
514
+ return None
515
+ raise
516
+ if not (dest / "manifest.json").is_file():
517
+ return None
518
+ return dest
country_laws_ir/normalize.py CHANGED
@@ -1,8 +1,9 @@
1
  """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
2
 
3
  Prefer article/section as the retrieval unit; fall back to law-level when
4
- articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE
5
- GraphRAG. Never invent legal text or identifiers.
 
6
 
7
  Public Hub reads only (token=False). No Hugging Face token is read or stored.
8
  """
@@ -11,30 +12,42 @@ from __future__ import annotations
11
 
12
  import json
13
  import os
14
- import re
15
- import unicodedata
16
  from collections import Counter
17
  from pathlib import Path
18
  from typing import Any
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
25
  from .cidutil import cid_of_json, sha256_file, sha256_hex
26
  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:
33
  if value is None or (isinstance(value, float) and pd.isna(value)):
34
  return ""
35
- text = unicodedata.normalize("NFKC", str(value))
36
- text = _WS_RE.sub(" ", text).strip()
37
- return text
38
 
39
 
40
  def _s(value: Any) -> str:
@@ -53,21 +66,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 +117,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 +144,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)),
@@ -248,6 +282,35 @@ def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str,
248
  return ""
249
 
250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  def _collector(meta: dict[str, Any], source_dataset: str) -> str:
252
  nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
253
  for blob in (meta, nested):
@@ -452,6 +515,9 @@ def build_corpus(
452
  "law_status": parent["law_status"],
453
  "parent_law_id": instrument_id,
454
  "article_id": source_id,
 
 
 
455
  },
456
  )
457
  )
@@ -464,6 +530,49 @@ def build_corpus(
464
  report["drop_samples"]["empty_body"].append(instrument_id)
465
  continue
466
  meta = parent["metadata"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  entries.append(
468
  _base_record(
469
  record_type="law",
@@ -494,6 +603,9 @@ def build_corpus(
494
  "law_status": parent["law_status"],
495
  "parent_law_id": "",
496
  "article_id": "",
 
 
 
497
  },
498
  )
499
  )
@@ -570,5 +682,23 @@ def build_corpus(
570
  "empty_bodies_dropped": report["drops"]["empty_body"],
571
  "duplicate_cids_dropped": report["drops"]["duplicate_cid"],
572
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
  df.attrs["normalization_report"] = report
574
  return df, report
 
1
  """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
2
 
3
  Prefer article/section as the retrieval unit; fall back to law-level when
4
+ articles are missing or empty. Strip leftover HTML, then detect multilingual
5
+ title/chapter/article/section headings (Oregon-style) when present. Never
6
+ invent legal text or a hierarchy that is not in the source.
7
 
8
  Public Hub reads only (token=False). No Hugging Face token is read or stored.
9
  """
 
12
 
13
  import json
14
  import os
 
 
15
  from collections import Counter
16
  from pathlib import Path
17
  from typing import Any
18
 
19
  import pandas as pd
20
  from huggingface_hub import dataset_info, hf_hub_download
21
+ from huggingface_hub.errors import EntryNotFoundError
22
 
23
  from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
24
  from .auth import configure_hf, public_token
25
  from .cidutil import cid_of_json, sha256_file, sha256_hex
26
  from .schema import SchemaError, validate_articles, validate_laws
27
+ from .structure import normalize_legal_text, split_structured_units
28
 
 
29
  COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
30
+ EMPTY_ARTICLE_COLUMNS = (
31
+ "law_id",
32
+ "id",
33
+ "title",
34
+ "text",
35
+ "source_url",
36
+ "document_number",
37
+ "article_number",
38
+ "record_type",
39
+ "metadata_json",
40
+ )
41
+
42
+
43
+ def _empty_articles() -> pd.DataFrame:
44
+ return pd.DataFrame(columns=list(EMPTY_ARTICLE_COLUMNS))
45
 
46
 
47
  def normalize_text(value: Any) -> str:
48
  if value is None or (isinstance(value, float) and pd.isna(value)):
49
  return ""
50
+ return normalize_legal_text(value)
 
 
51
 
52
 
53
  def _s(value: Any) -> str:
 
66
  return Path(path)
67
 
68
 
69
+ def _repo_filenames(info: Any) -> set[str]:
70
+ return {str(getattr(s, "rfilename", "") or "") for s in (getattr(info, "siblings", None) or [])}
71
+
72
+
73
+ def _pick_repo_file(filenames: set[str], name: str) -> str | None:
74
+ for cand in (f"data/{name}.parquet", f"{name}.parquet"):
75
+ if cand in filenames:
76
+ return cand
77
+ return None
78
+
79
+
80
+ def _resolve_local_parquet(root: Path, name: str, *, required: bool = True) -> Path | None:
81
  """Accept either <root>/data/<name>.parquet or <root>/<name>.parquet."""
82
  for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"):
83
  if cand.is_file():
84
  return cand
85
+ if required:
86
+ raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)")
87
+ return None
88
 
89
 
90
  def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
91
  """Load a local country-laws pack (filtered preprocess layout)."""
92
  local_dir = Path(local_dir).resolve()
93
  laws_path = _resolve_local_parquet(local_dir, "laws")
94
+ articles_path = _resolve_local_parquet(local_dir, "articles", required=False)
95
  laws = pd.read_parquet(laws_path)
96
+ articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
97
  validate_laws(laws)
98
  validate_articles(articles)
99
  pack_meta: dict[str, Any] = {}
 
117
  "source_dataset": source_dataset,
118
  "source_revision": source_revision,
119
  "laws_path": str(laws_path),
120
+ "articles_path": str(articles_path) if articles_path is not None else None,
121
  "laws_sha256": sha256_file(laws_path),
122
+ "articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
123
  "n_laws_source": int(len(laws)),
124
  "n_articles_source": int(len(articles)),
125
  "laws_columns": list(map(str, laws.columns)),
 
144
  os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
145
  info = dataset_info(repo_id, token=public_token())
146
  revision = info.sha
147
+ filenames = _repo_filenames(info)
148
+ laws_file = _pick_repo_file(filenames, "laws") or "data/laws.parquet"
149
+ articles_file = _pick_repo_file(filenames, "articles")
150
+ laws_path = _download(repo_id, laws_file, cache_dir)
151
+ articles_path: Path | None = None
152
+ if articles_file is not None:
153
+ try:
154
+ articles_path = _download(repo_id, articles_file, cache_dir)
155
+ except EntryNotFoundError:
156
+ articles_path = None
157
  laws = pd.read_parquet(laws_path)
158
+ articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
159
  validate_laws(laws)
160
  validate_articles(articles)
161
  meta = {
162
  "source_dataset": repo_id,
163
  "source_revision": revision,
164
  "laws_path": str(laws_path),
165
+ "articles_path": str(articles_path) if articles_path is not None else None,
166
  "laws_sha256": sha256_file(laws_path),
167
+ "articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
168
  "n_laws_source": int(len(laws)),
169
  "n_articles_source": int(len(articles)),
170
  "laws_columns": list(map(str, laws.columns)),
 
282
  return ""
283
 
284
 
285
+ def _hierarchy_fields(
286
+ title: str, body: str, article_number: str, *, language: str = ""
287
+ ) -> dict[str, Any]:
288
+ """Best-effort hierarchy from a single already-split article/section body."""
289
+ units = split_structured_units(
290
+ f"{title}\n{body}" if title else body, language=language
291
+ )
292
+ if not units:
293
+ return {
294
+ "hierarchy_kind": "article" if article_number else "law",
295
+ "hierarchy_path": "",
296
+ "title_number": "",
297
+ "chapter_number": "",
298
+ "part_number": "",
299
+ "section_number": "",
300
+ "subsections": [],
301
+ }
302
+ unit = units[0]
303
+ return {
304
+ "hierarchy_kind": unit.kind,
305
+ "hierarchy_path": unit.hierarchy_path,
306
+ "title_number": unit.title_number,
307
+ "chapter_number": unit.chapter_number,
308
+ "part_number": unit.part_number,
309
+ "section_number": unit.section_number,
310
+ "subsections": list(unit.subsections),
311
+ }
312
+
313
+
314
  def _collector(meta: dict[str, Any], source_dataset: str) -> str:
315
  nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
316
  for blob in (meta, nested):
 
515
  "law_status": parent["law_status"],
516
  "parent_law_id": instrument_id,
517
  "article_id": source_id,
518
+ **_hierarchy_fields(
519
+ article_title, body, article_number, language=parent["language"]
520
+ ),
521
  },
522
  )
523
  )
 
530
  report["drop_samples"]["empty_body"].append(instrument_id)
531
  continue
532
  meta = parent["metadata"]
533
+ units = split_structured_units(body, language=parent["language"])
534
+ if units:
535
+ report["unit"] = "structured"
536
+ for unit in units:
537
+ entries.append(
538
+ _base_record(
539
+ record_type=unit.kind if unit.kind in {"article", "section"} else "article",
540
+ source_dataset=source_dataset,
541
+ source_revision=source_revision,
542
+ instrument_id=instrument_id,
543
+ instrument_title=parent["instrument_title"],
544
+ law_cid=parent["law_cid"],
545
+ article_number=unit.article_number or unit.number,
546
+ article_title=unit.heading,
547
+ body=unit.body,
548
+ jurisdiction=parent["jurisdiction"],
549
+ language=parent["language"],
550
+ source_url=parent["source_url"],
551
+ snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
552
+ coverage="structured (headings detected in law body)",
553
+ license_expr=parent["license"],
554
+ collector=_collector(meta, source_dataset),
555
+ source_id=f"{instrument_id}-{unit.kind}-{unit.number}",
556
+ extra={
557
+ "eli": parent["eli"],
558
+ "identifier": parent["identifier"],
559
+ "official_identifier": parent["official_identifier"],
560
+ "source_type": parent["source_type"],
561
+ "country": parent["country"],
562
+ "law_status": parent["law_status"],
563
+ "parent_law_id": instrument_id,
564
+ "article_id": "",
565
+ "hierarchy_kind": unit.kind,
566
+ "hierarchy_path": unit.hierarchy_path,
567
+ "title_number": unit.title_number,
568
+ "chapter_number": unit.chapter_number,
569
+ "part_number": unit.part_number,
570
+ "section_number": unit.section_number,
571
+ "subsections": list(unit.subsections),
572
+ },
573
+ )
574
+ )
575
+ continue
576
  entries.append(
577
  _base_record(
578
  record_type="law",
 
603
  "law_status": parent["law_status"],
604
  "parent_law_id": "",
605
  "article_id": "",
606
+ **_hierarchy_fields(
607
+ parent["instrument_title"], body, "", language=parent["language"]
608
+ ),
609
  },
610
  )
611
  )
 
682
  "empty_bodies_dropped": report["drops"]["empty_body"],
683
  "duplicate_cids_dropped": report["drops"]["duplicate_cid"],
684
  }
685
+ from .profiles import majority_language, score_heading_languages
686
+
687
+ sample_text = ""
688
+ if not df.empty and "body" in df.columns:
689
+ sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist())
690
+ if "title" in df.columns:
691
+ sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text
692
+ heading_langs = score_heading_languages(sample_text)
693
+ report["heading_language_counts"] = dict(heading_langs)
694
+ report["heading_language_majority"] = majority_language(heading_langs)
695
+ report["document_language_majority"] = None
696
+ if report.get("language_breakdown"):
697
+ report["document_language_majority"] = max(
698
+ report["language_breakdown"].items(), key=lambda kv: kv[1]
699
+ )[0]
700
+ from .verify import verify_normalized_corpus
701
+
702
+ report["verification"] = verify_normalized_corpus(df, report)
703
  df.attrs["normalization_report"] = report
704
  return df, report
country_laws_ir/package.py CHANGED
@@ -34,8 +34,11 @@ def package_release(
34
  country: dict[str, Any],
35
  code_root: Path,
36
  normalization_report: dict[str, Any] | None = None,
 
 
 
37
  ) -> dict[str, Any]:
38
- if out.exists():
39
  shutil.rmtree(out)
40
  out.mkdir(parents=True, exist_ok=True)
41
  indexes_dir = out / "indexes"
@@ -51,78 +54,95 @@ def package_release(
51
  )
52
  write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
53
 
54
- bm25_doc_idx = write_sharded(
55
- bm25["documents"],
56
- out / "data" / "bm25" / "documents",
57
- "data/bm25/documents",
58
- kind="bm25_documents",
59
- key_col="entry_cid",
60
- index_col="document_index",
61
- )
62
- write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
63
-
64
- postings = bm25["postings"]
65
- posting_idx = write_sharded(
66
- postings,
67
- out / "data" / "bm25" / "postings",
68
- "data/bm25/postings",
69
- kind="bm25_postings",
70
- key_col="term",
71
- )
72
- for row, part_start in zip(posting_idx, range(len(posting_idx))):
73
- shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE]
74
- row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
75
- row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
76
- row["token_instance_count"] = row["posting_count"]
77
- write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
78
-
79
- node_idx = write_sharded(
80
- graph["nodes"],
81
- out / "data" / "graph" / "nodes",
82
- "data/graph/nodes",
83
- kind="graph_nodes",
84
- key_col="node_cid",
85
- )
86
- write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
87
-
88
- edge_idx = write_sharded(
89
- graph["edges"],
90
- out / "data" / "graph" / "edges",
91
- "data/graph/edges",
92
- kind="graph_edges",
93
- key_col="edge_cid",
94
- )
95
- write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
96
-
97
- incoming = graph["incoming"]
98
- outgoing = graph["outgoing"]
99
- in_idx = write_sharded(
100
- incoming if incoming is not None and not incoming.empty else pd.DataFrame(
101
- columns=["node_cid", "page_index", "direction"]
102
- ),
103
- out / "data" / "graph" / "adjacency" / "incoming",
104
- "data/graph/adjacency/incoming",
105
- kind="graph_incoming_adjacency",
106
- key_col="node_cid",
107
- )
108
- out_idx = write_sharded(
109
- outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame(
110
- columns=["node_cid", "page_index", "direction"]
111
- ),
112
- out / "data" / "graph" / "adjacency" / "outgoing",
113
- "data/graph/adjacency/outgoing",
114
- kind="graph_outgoing_adjacency",
115
- key_col="node_cid",
116
- )
117
- for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
118
- for r in rows:
119
- r["direction"] = direction
120
- r["adjacency_count"] = r.get("row_count", 0)
121
- r["node_count"] = r.get("row_count", 0)
122
- r["first_page_index"] = 0
123
- r["last_page_index"] = 0
124
- write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
125
- write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  vectors_df = vectors["vectors"]
128
  # Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
@@ -195,8 +215,8 @@ def package_release(
195
  "bm25_documents": int(len(bm25["documents"])),
196
  "bm25_keyword_shards": len(posting_idx),
197
  "bm25_posting_rows": int(len(postings)),
198
- "bm25_postings": int(bm25["stats"]["n_postings"]),
199
- "bm25_terms": int(bm25["stats"]["n_terms"]),
200
  "corpus_chunks": len(corpus_idx),
201
  "corpus_rows": int(len(corpus)),
202
  "graph_edge_chunks": len(edge_idx),
@@ -214,9 +234,22 @@ def package_release(
214
  "n_laws": n_laws,
215
  "n_articles": n_articles,
216
  }
 
 
 
 
 
 
 
 
 
 
 
217
 
218
  def idx_desc(name: str) -> dict[str, Any]:
219
  path = indexes_dir / name
 
 
220
  return file_descriptor(path, f"indexes/{name}")
221
 
222
  hub_id = target_repo(country["slug"])
@@ -247,6 +280,7 @@ def package_release(
247
  "compression_level": 6,
248
  "max_rows_per_file": MAX_ROWS_PER_FILE,
249
  "row_group_size": MAX_ROWS_PER_FILE,
 
250
  },
251
  "graph": {
252
  "adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
@@ -324,12 +358,35 @@ def package_release(
324
  },
325
  "source": source_meta,
326
  }
 
 
327
  (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
328
  _write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
329
  _write_gitattributes(out)
 
330
  return manifest
331
 
332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  def _write_gitattributes(out: Path) -> None:
334
  (out / ".gitattributes").write_text(
335
  "*.parquet filter=lfs diff=lfs merge=lfs -text\n"
@@ -546,6 +603,7 @@ def package_release_sequential(
546
  code_root: Path,
547
  normalization_report: dict[str, Any] | None = None,
548
  expected_rows: int | None = None,
 
549
  ) -> dict[str, Any]:
550
  """Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
551
 
@@ -753,6 +811,8 @@ def package_release_sequential(
753
 
754
  def idx_desc(name: str) -> dict[str, Any]:
755
  path = indexes_dir / name
 
 
756
  return file_descriptor(path, f"indexes/{name}")
757
 
758
  manifest = {
@@ -835,11 +895,14 @@ def package_release_sequential(
835
  },
836
  "source": source_meta,
837
  }
 
 
838
  (out / "manifest.json").write_text(
839
  json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
840
  )
841
  _write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
842
  _write_gitattributes(out)
 
843
  checkpoint("package_seq_done")
844
  return manifest
845
 
@@ -853,14 +916,20 @@ def package_from_spill(
853
  code_root: Path,
854
  normalization_report: dict[str, Any] | None = None,
855
  expected_rows: int | None = None,
 
856
  ) -> dict[str, Any]:
857
- """Package from spill dir artifacts: bm25_*.parquet, bm25_stats.pkl, graph.pkl, vectors.pkl."""
 
858
  import pickle as _pickle
859
 
860
  spill = Path(spill)
861
- stats_path = spill / "bm25_stats.pkl"
862
- with stats_path.open("rb") as f:
863
- bm25_stats = _pickle.load(f)
 
 
 
 
864
  return package_release_sequential(
865
  out,
866
  corpus_path=Path(corpus_path),
@@ -874,4 +943,5 @@ def package_from_spill(
874
  code_root=Path(code_root),
875
  normalization_report=normalization_report,
876
  expected_rows=expected_rows,
 
877
  )
 
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
+ wipe: bool = True,
39
+ skip_bm25_graph: bool = False,
40
  ) -> dict[str, Any]:
41
+ if wipe and out.exists():
42
  shutil.rmtree(out)
43
  out.mkdir(parents=True, exist_ok=True)
44
  indexes_dir = out / "indexes"
 
54
  )
55
  write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
56
 
57
+ if skip_bm25_graph:
58
+ bm25_doc_idx = []
59
+ posting_idx = []
60
+ postings = pd.DataFrame()
61
+ node_idx = []
62
+ edge_idx = []
63
+ in_idx = []
64
+ out_idx = []
65
+ incoming = pd.DataFrame()
66
+ outgoing = pd.DataFrame()
67
+ bm25 = bm25 or {"documents": pd.DataFrame(), "postings": pd.DataFrame(), "stats": {}}
68
+ graph = graph or {"nodes": pd.DataFrame(), "edges": pd.DataFrame(), "stats": {}}
69
+ else:
70
+ bm25_doc_idx = write_sharded(
71
+ bm25["documents"],
72
+ out / "data" / "bm25" / "documents",
73
+ "data/bm25/documents",
74
+ kind="bm25_documents",
75
+ key_col="entry_cid",
76
+ index_col="document_index",
77
+ )
78
+ write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
79
+
80
+ postings = bm25["postings"]
81
+ posting_idx = write_sharded(
82
+ postings,
83
+ out / "data" / "bm25" / "postings",
84
+ "data/bm25/postings",
85
+ kind="bm25_postings",
86
+ key_col="term",
87
+ )
88
+ for row, part_start in zip(posting_idx, range(len(posting_idx))):
89
+ shard_df = postings.iloc[
90
+ part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE
91
+ ]
92
+ row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
93
+ row["posting_count"] = (
94
+ int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
95
+ )
96
+ row["token_instance_count"] = row["posting_count"]
97
+ write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
98
+
99
+ node_idx = write_sharded(
100
+ graph["nodes"],
101
+ out / "data" / "graph" / "nodes",
102
+ "data/graph/nodes",
103
+ kind="graph_nodes",
104
+ key_col="node_cid",
105
+ )
106
+ write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
107
+
108
+ edge_idx = write_sharded(
109
+ graph["edges"],
110
+ out / "data" / "graph" / "edges",
111
+ "data/graph/edges",
112
+ kind="graph_edges",
113
+ key_col="edge_cid",
114
+ )
115
+ write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
116
+
117
+ incoming = graph["incoming"]
118
+ outgoing = graph["outgoing"]
119
+ in_idx = write_sharded(
120
+ incoming
121
+ if incoming is not None and not incoming.empty
122
+ else pd.DataFrame(columns=["node_cid", "page_index", "direction"]),
123
+ out / "data" / "graph" / "adjacency" / "incoming",
124
+ "data/graph/adjacency/incoming",
125
+ kind="graph_incoming_adjacency",
126
+ key_col="node_cid",
127
+ )
128
+ out_idx = write_sharded(
129
+ outgoing
130
+ if outgoing is not None and not outgoing.empty
131
+ else pd.DataFrame(columns=["node_cid", "page_index", "direction"]),
132
+ out / "data" / "graph" / "adjacency" / "outgoing",
133
+ "data/graph/adjacency/outgoing",
134
+ kind="graph_outgoing_adjacency",
135
+ key_col="node_cid",
136
+ )
137
+ for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
138
+ for r in rows:
139
+ r["direction"] = direction
140
+ r["adjacency_count"] = r.get("row_count", 0)
141
+ r["node_count"] = r.get("row_count", 0)
142
+ r["first_page_index"] = 0
143
+ r["last_page_index"] = 0
144
+ write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
145
+ write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
146
 
147
  vectors_df = vectors["vectors"]
148
  # Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
 
215
  "bm25_documents": int(len(bm25["documents"])),
216
  "bm25_keyword_shards": len(posting_idx),
217
  "bm25_posting_rows": int(len(postings)),
218
+ "bm25_postings": int((bm25.get("stats") or {}).get("n_postings") or 0),
219
+ "bm25_terms": int((bm25.get("stats") or {}).get("n_terms") or 0),
220
  "corpus_chunks": len(corpus_idx),
221
  "corpus_rows": int(len(corpus)),
222
  "graph_edge_chunks": len(edge_idx),
 
234
  "n_laws": n_laws,
235
  "n_articles": n_articles,
236
  }
237
+ if skip_bm25_graph and extra_manifest and extra_manifest.get("sparse"):
238
+ sparse = extra_manifest["sparse"]
239
+ bm25_counts = (sparse.get("bm25") or {}).get("counts") or {}
240
+ graph_counts = sparse.get("graph") or {}
241
+ counts.update(
242
+ {k: int(v) for k, v in bm25_counts.items() if isinstance(v, (int, float))}
243
+ )
244
+ if graph_counts.get("node_count") is not None:
245
+ counts["graph_nodes"] = int(graph_counts["node_count"])
246
+ if graph_counts.get("edge_count") is not None:
247
+ counts["graph_edges"] = int(graph_counts["edge_count"])
248
 
249
  def idx_desc(name: str) -> dict[str, Any]:
250
  path = indexes_dir / name
251
+ if not path.is_file():
252
+ return {"relative_path": f"indexes/{name}", "present": False}
253
  return file_descriptor(path, f"indexes/{name}")
254
 
255
  hub_id = target_repo(country["slug"])
 
280
  "compression_level": 6,
281
  "max_rows_per_file": MAX_ROWS_PER_FILE,
282
  "row_group_size": MAX_ROWS_PER_FILE,
283
+ "query_engine": "duckdb",
284
  },
285
  "graph": {
286
  "adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
 
358
  },
359
  "source": source_meta,
360
  }
361
+ if extra_manifest:
362
+ manifest.update(extra_manifest)
363
  (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
364
  _write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
365
  _write_gitattributes(out)
366
+ _write_dataset_configs(out)
367
  return manifest
368
 
369
 
370
+ def _write_dataset_configs(out: Path) -> None:
371
+ configs = {
372
+ "country-laws-ir-graphrag/v1": {
373
+ "data_files": {
374
+ "corpus": "data/corpus/*.parquet",
375
+ "bm25_documents": "data/bm25/documents/*.parquet",
376
+ "bm25_postings": "data/bm25/postings/*.parquet",
377
+ "graph_nodes": "data/graph/nodes/*.parquet",
378
+ "graph_edges": "data/graph/edges/*.parquet",
379
+ "graph_adjacency_out": "data/graph/adjacency/out/*.parquet",
380
+ "graph_adjacency_in": "data/graph/adjacency/in/*.parquet",
381
+ "vectors": "data/vectors/*.parquet",
382
+ }
383
+ }
384
+ }
385
+ (out / "dataset_configs.json").write_text(
386
+ json.dumps(configs, indent=2) + "\n", encoding="utf-8"
387
+ )
388
+
389
+
390
  def _write_gitattributes(out: Path) -> None:
391
  (out / ".gitattributes").write_text(
392
  "*.parquet filter=lfs diff=lfs merge=lfs -text\n"
 
603
  code_root: Path,
604
  normalization_report: dict[str, Any] | None = None,
605
  expected_rows: int | None = None,
606
+ extra_manifest: dict[str, Any] | None = None,
607
  ) -> dict[str, Any]:
608
  """Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
609
 
 
811
 
812
  def idx_desc(name: str) -> dict[str, Any]:
813
  path = indexes_dir / name
814
+ if not path.is_file():
815
+ return {"relative_path": f"indexes/{name}", "present": False}
816
  return file_descriptor(path, f"indexes/{name}")
817
 
818
  manifest = {
 
895
  },
896
  "source": source_meta,
897
  }
898
+ if extra_manifest:
899
+ manifest.update(extra_manifest)
900
  (out / "manifest.json").write_text(
901
  json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
902
  )
903
  _write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
904
  _write_gitattributes(out)
905
+ _write_dataset_configs(out)
906
  checkpoint("package_seq_done")
907
  return manifest
908
 
 
916
  code_root: Path,
917
  normalization_report: dict[str, Any] | None = None,
918
  expected_rows: int | None = None,
919
+ extra_manifest: dict[str, Any] | None = None,
920
  ) -> dict[str, Any]:
921
+ """Package from spill dir artifacts: bm25_*.parquet, bm25_stats.json, graph.pkl, vectors.pkl."""
922
+ import json as _json
923
  import pickle as _pickle
924
 
925
  spill = Path(spill)
926
+ stats_json = spill / "bm25_stats.json"
927
+ stats_pkl = spill / "bm25_stats.pkl"
928
+ if stats_json.is_file():
929
+ bm25_stats = _json.loads(stats_json.read_text(encoding="utf-8"))
930
+ else:
931
+ with stats_pkl.open("rb") as f:
932
+ bm25_stats = _pickle.load(f)
933
  return package_release_sequential(
934
  out,
935
  corpus_path=Path(corpus_path),
 
943
  code_root=Path(code_root),
944
  normalization_report=normalization_report,
945
  expected_rows=expected_rows,
946
+ extra_manifest=extra_manifest,
947
  )
country_laws_ir/profiles.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-language legal heading lexicons for country-law structure extraction.
2
+
3
+ Oregon (ORS) is English title/chapter/section. Other gazettes use their own
4
+ words (Artikel, Titre, Artículo, 条, مادة). This table is how we *score*
5
+ whether a split used the right language — not a claim that every country
6
+ has a dedicated parser.
7
+
8
+ Languages with no lexicon (ar, zh, ja, ko, …) must not be force-split on
9
+ Latin TITLE/ARTICLE markers; collectors may already have article rows.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections import Counter
15
+ import re
16
+ from typing import Any
17
+
18
+ # keyword -> list of (kind, language); some words are shared (article).
19
+ HEADING_LEXICON: dict[str, list[tuple[str, str]]] = {}
20
+
21
+ def _add(lang: str, kind: str, *words: str) -> None:
22
+ for word in words:
23
+ HEADING_LEXICON.setdefault(word.casefold(), []).append((kind, lang))
24
+
25
+
26
+ _add("en", "title", "title")
27
+ _add("en", "chapter", "chapter")
28
+ _add("en", "part", "part")
29
+ _add("en", "article", "article")
30
+ _add("en", "section", "section", "sec.")
31
+
32
+ _add("fr", "title", "titre")
33
+ _add("fr", "chapter", "chapitre")
34
+ _add("fr", "part", "partie")
35
+ _add("fr", "article", "article")
36
+ _add("fr", "section", "section")
37
+
38
+ _add("de", "title", "titel")
39
+ _add("de", "chapter", "kapitel")
40
+ _add("de", "part", "teil")
41
+ _add("de", "article", "artikel")
42
+ _add("de", "section", "abschnitt", "paragraf")
43
+
44
+ _add("nl", "title", "titel")
45
+ _add("nl", "chapter", "hoofdstuk")
46
+ _add("nl", "part", "deel")
47
+ _add("nl", "article", "artikel")
48
+ _add("nl", "section", "paragraaf", "afdeling")
49
+
50
+ _add("es", "title", "título", "titulo")
51
+ _add("es", "chapter", "capítulo", "capitulo")
52
+ _add("es", "part", "parte")
53
+ _add("es", "article", "artículo", "articulo")
54
+ _add("es", "section", "sección", "seccion")
55
+
56
+ _add("pt", "title", "título", "titulo")
57
+ _add("pt", "chapter", "capítulo", "capitulo")
58
+ _add("pt", "part", "parte")
59
+ _add("pt", "article", "artigo")
60
+ _add("pt", "section", "secção", "secao")
61
+
62
+ _add("it", "title", "titolo")
63
+ _add("it", "chapter", "capitolo")
64
+ _add("it", "part", "parte")
65
+ _add("it", "article", "articolo")
66
+ _add("it", "section", "sezione")
67
+
68
+ _add("el", "article", "άρθρο", "αρθρο")
69
+ _add("hu", "article", "szakasz")
70
+ _add("cs", "article", "článek")
71
+ _add("sk", "article", "článok")
72
+ _add("sl", "article", "član")
73
+ _add("nb", "article", "artikkel")
74
+ _add("sv", "article", "artikel")
75
+ _add("pl", "article", "artykuł", "artykul")
76
+ _add("ro", "article", "articolul", "articol")
77
+ _add("zh", "article", "条")
78
+ _add("ar", "article", "مادة", "المادة")
79
+ _add("ja", "article", "条")
80
+
81
+ # Shared abbreviation; language left unknown.
82
+ _add("und", "article", "art.")
83
+ _add("und", "section", "§")
84
+
85
+ # Scripts we do not Latin-split:
86
+ NO_LATIN_SPLIT_LANGS = frozenset({"ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn", "am"})
87
+
88
+ _TOKEN_RE = re.compile(r"[^\W\d_]{2,}|art\.|sec\.|§", re.UNICODE)
89
+
90
+
91
+ def classify_heading_token(token: str) -> list[tuple[str, str]]:
92
+ return list(HEADING_LEXICON.get(token.casefold()) or ())
93
+
94
+
95
+ def score_heading_languages(text: str) -> Counter[str]:
96
+ """Count distinctive lexicon hits. Shared words like 'article' do not vote."""
97
+ counts: Counter[str] = Counter()
98
+ if not text:
99
+ return counts
100
+ for token in _TOKEN_RE.findall(text):
101
+ hits = classify_heading_token(token)
102
+ langs = {lang for _kind, lang in hits if lang != "und"}
103
+ if len(langs) == 1:
104
+ counts[next(iter(langs))] += 1
105
+ return counts
106
+
107
+
108
+ def majority_language(counts: Counter[str], *, exclude: tuple[str, ...] = ("und",)) -> str | None:
109
+ filtered = Counter({k: v for k, v in counts.items() if k not in exclude})
110
+ if not filtered:
111
+ return None
112
+ lang, _n = filtered.most_common(1)[0]
113
+ return lang
114
+
115
+
116
+ def iso_lang(value: Any) -> str:
117
+ text = str(value or "").strip().lower().replace("_", "-")
118
+ if not text:
119
+ return ""
120
+ return text.split("-")[0]
121
+
122
+
123
+ def latin_split_allowed(language: str) -> bool:
124
+ return iso_lang(language) not in NO_LATIN_SPLIT_LANGS
country_laws_ir/query.py CHANGED
@@ -42,6 +42,12 @@ class Release:
42
  return pd.read_parquet(path)
43
 
44
  def bm25(self, query: str, top_k: int = 10) -> list[dict]:
 
 
 
 
 
 
45
  q_terms = tokenize(query)[:MAX_QUERY_TERMS]
46
  if not q_terms:
47
  return []
@@ -124,6 +130,12 @@ class Release:
124
  return out
125
 
126
  def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]:
 
 
 
 
 
 
127
  dirs = ["incoming", "outgoing"] if direction == "both" else [direction]
128
  hits = []
129
  for d in dirs:
@@ -164,13 +176,17 @@ def main(argv: list[str] | None = None) -> int:
164
  p_vec.add_argument("query")
165
  p_vec.add_argument("--top-k", type=int, default=10)
166
  p_vec.add_argument("--candidate-centroids", type=int, default=4)
167
- p_vec.add_argument("--device", default="cpu")
168
 
169
  p_g = sub.add_parser("graph")
170
  g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
171
  p_n = g_sub.add_parser("neighbors")
172
  p_n.add_argument("node_cid")
173
- p_n.add_argument("--direction", default="both", choices=["both", "incoming", "outgoing"])
 
 
 
 
174
  p_n.add_argument("--limit", type=int, default=25)
175
 
176
  args = ap.parse_args(argv)
 
42
  return pd.read_parquet(path)
43
 
44
  def bm25(self, query: str, top_k: int = 10) -> list[dict]:
45
+ try:
46
+ from .duckdb_store import bm25_search
47
+
48
+ return bm25_search(self.root, query, top_k=top_k)
49
+ except Exception:
50
+ pass
51
  q_terms = tokenize(query)[:MAX_QUERY_TERMS]
52
  if not q_terms:
53
  return []
 
130
  return out
131
 
132
  def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]:
133
+ try:
134
+ from .duckdb_store import graph_neighbors
135
+
136
+ return graph_neighbors(self.root, node_cid, direction=direction, limit=limit)
137
+ except Exception:
138
+ pass
139
  dirs = ["incoming", "outgoing"] if direction == "both" else [direction]
140
  hits = []
141
  for d in dirs:
 
176
  p_vec.add_argument("query")
177
  p_vec.add_argument("--top-k", type=int, default=10)
178
  p_vec.add_argument("--candidate-centroids", type=int, default=4)
179
+ p_vec.add_argument("--device", default="cuda")
180
 
181
  p_g = sub.add_parser("graph")
182
  g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
183
  p_n = g_sub.add_parser("neighbors")
184
  p_n.add_argument("node_cid")
185
+ p_n.add_argument(
186
+ "--direction",
187
+ default="both",
188
+ choices=["both", "in", "out", "incoming", "outgoing"],
189
+ )
190
  p_n.add_argument("--limit", type=int, default=25)
191
 
192
  args = ap.parse_args(argv)
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/sparse.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Country-law sparse GraphRAG export through the shared HF GraphRAG builders.
2
+
3
+ This is the same parquet layout used by US Code, state laws, Federal Register,
4
+ and SkillCenter:
5
+
6
+ * ``ipfs_datasets_py.retrieval.hf_graphrag.bm25.build_bm25_layout``
7
+ * ``ipfs_datasets_py.retrieval.hf_graphrag.graph.write_graph_layout``
8
+
9
+ No SQLite. Indexes are ZSTD parquet shards under ``data/bm25`` and
10
+ ``data/graph``. DuckDB queries those shards at read time.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import pandas as pd
19
+
20
+ from . import EDGE_IDENTITY_SCHEMA, SCHEMA_VERSION
21
+ from .cidutil import cid_of_json
22
+ from .graph import build_graph
23
+
24
+
25
+ def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]:
26
+ """Project a normalized country-law corpus onto the shared BM25 row schema.
27
+
28
+ Rows with no searchable tokens are omitted. The shared
29
+ ``build_bm25_layout`` builder fail-closes on empty documents (same
30
+ admission rule as US Code / Federal Register).
31
+ """
32
+ from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text
33
+
34
+ _MAX_TITLE = 8_192
35
+ _MAX_BODY = 200_000
36
+ rows: list[dict[str, Any]] = []
37
+ for rec in corpus.itertuples(index=False):
38
+ title = str(getattr(rec, "title", "") or "").replace("\x00", "").strip()
39
+ body = str(getattr(rec, "body", "") or "").replace("\x00", "").strip()
40
+ if len(title) > _MAX_TITLE:
41
+ title = title[:_MAX_TITLE].rstrip()
42
+ if len(body) > _MAX_BODY:
43
+ body = body[:_MAX_BODY].rstrip()
44
+ if not title and not body:
45
+ continue
46
+ if not tokenize_bm25_text(title) and not tokenize_bm25_text(body):
47
+ continue
48
+ rows.append(
49
+ {
50
+ "entry_cid": str(rec.entry_cid),
51
+ "title": title,
52
+ "body": body,
53
+ "record_type": str(getattr(rec, "record_type", "") or "law"),
54
+ "document_index": int(rec.document_index),
55
+ }
56
+ )
57
+ if not rows:
58
+ raise RuntimeError("no corpus rows had searchable BM25 tokens")
59
+ for i, row in enumerate(rows):
60
+ row["document_index"] = i
61
+ return rows
62
+
63
+
64
+ def _graph_nodes_and_edges(corpus: pd.DataFrame) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
65
+ """Structural graph only (no precomputed BM25 neighbor matrix)."""
66
+ built = build_graph(corpus, [[] for _ in range(len(corpus))])
67
+ nodes = [
68
+ {
69
+ "node_cid": str(row["node_cid"]),
70
+ "node_type": str(row["node_type"]),
71
+ "label": row.get("label"),
72
+ "entry_cid": row.get("entry_cid") or None,
73
+ }
74
+ for row in built["nodes"].to_dict("records")
75
+ ]
76
+ edges = []
77
+ for row in built["edges"].to_dict("records"):
78
+ source = str(row.get("source_cid") or row.get("source_node_cid") or "")
79
+ target = str(row.get("target_cid") or row.get("target_node_cid") or "")
80
+ edge_type = str(row.get("edge_type") or "")
81
+ if not source or not target or not edge_type:
82
+ continue
83
+ edge_cid = str(row.get("edge_cid") or "") or cid_of_json(
84
+ {
85
+ "edge_type": edge_type,
86
+ "schema": EDGE_IDENTITY_SCHEMA,
87
+ "source": source,
88
+ "target": target,
89
+ }
90
+ )
91
+ edges.append(
92
+ {
93
+ "edge_cid": edge_cid,
94
+ "edge_type": edge_type,
95
+ "source_node_cid": source,
96
+ "target_node_cid": target,
97
+ "retrieval_method": str(row.get("retrieval_method") or "structural"),
98
+ "score": row.get("score"),
99
+ }
100
+ )
101
+ return nodes, edges
102
+
103
+
104
+ def export_sparse_graphrag(
105
+ corpus: pd.DataFrame,
106
+ output_dir: Path,
107
+ ) -> dict[str, Any]:
108
+ """Write BM25 + graph parquet shards using the shared HF GraphRAG builders."""
109
+ from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import (
110
+ BM25LayoutConfig,
111
+ build_bm25_layout,
112
+ )
113
+ from ipfs_datasets_py.retrieval.hf_graphrag.graph import write_graph_layout
114
+
115
+ output_dir = Path(output_dir)
116
+ output_dir.mkdir(parents=True, exist_ok=True)
117
+ rows = corpus_to_bm25_rows(corpus)
118
+ bm25 = build_bm25_layout(
119
+ rows,
120
+ output_dir,
121
+ config=BM25LayoutConfig(max_documents=max(len(rows), 1)),
122
+ )
123
+ nodes, edges = _graph_nodes_and_edges(corpus)
124
+ written = write_graph_layout(nodes, edges, output_dir)
125
+ layout = written.layout
126
+ return {
127
+ "engine": "hf_graphrag",
128
+ "schema_version": SCHEMA_VERSION,
129
+ "bm25": bm25.to_manifest_fragment(),
130
+ "graph": {
131
+ "node_count": int(layout.node_count),
132
+ "edge_count": int(layout.edge_count),
133
+ "adjacency": "data/graph/adjacency/{out,in}/*.parquet",
134
+ },
135
+ "sqlite": False,
136
+ "query_engine": "duckdb",
137
+ }
country_laws_ir/spill.py CHANGED
@@ -1,17 +1,15 @@
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
 
@@ -19,7 +17,6 @@ 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
@@ -41,7 +38,8 @@ 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
@@ -68,19 +66,24 @@ def load_pickle(path: Path) -> Any:
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
@@ -88,265 +91,49 @@ def sqlite_ready(db_path: Path, expected: int) -> bool:
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])
@@ -369,30 +156,9 @@ def assemble_neighbors_streaming(spill: Path, n_docs: int) -> list:
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(
@@ -492,33 +258,35 @@ def build_bm25_tf_spill(
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)
@@ -549,7 +317,6 @@ def build_bm25_tf_spill(
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"])
@@ -593,9 +360,7 @@ def build_bm25_tf_spill(
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:
@@ -612,7 +377,7 @@ def build_bm25_tf_spill(
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)
@@ -623,9 +388,8 @@ def build_bm25_tf_spill(
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
@@ -696,7 +460,7 @@ def build_bm25_tf_spill(
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
@@ -749,9 +513,9 @@ def build_bm25_tf_spill(
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:
@@ -759,5 +523,10 @@ def build_bm25_tf_spill(
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
 
 
 
 
 
 
1
+ """Disk-spill helpers for large country IR builds (DuckDB + parquet).
2
 
3
  Design (CoS / DO OOM lesson):
4
  - Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).
5
+ - Neighbors for n >= DUCKDB_THRESHOLD (40k): DuckDB FTS over corpus parquet,
6
+ streamed into neighbor_*.parquet shards — never hold the full neighbor
7
+ matrix in RAM.
8
+ - BM25 TF: stream tokenize → DuckDB → posting parquet parts.
9
+ - Package: sequential parquet write so corpus, bm25, graph, vectors are never
10
+ all resident together.
11
+
12
+ No SQLite. Intermediate and published artifacts are parquet / DuckDB.
 
 
13
  """
14
  from __future__ import annotations
15
 
 
17
  import json
18
  import math
19
  import pickle
 
20
  from collections import defaultdict
21
  from pathlib import Path
22
  from typing import Any, Callable, Iterable, Iterator
 
38
  from .mem import MemAbort, checkpoint, log_mem
39
  from .tokenize import tokenize
40
 
41
+ DUCKDB_THRESHOLD = 40_000
42
+ SQLITE_THRESHOLD = DUCKDB_THRESHOLD # backward-compatible alias; not SQLite
43
  BATCH = 256
44
  NEIGHBOR_SHARD = 5_000
45
  NEIGHBOR_K = 8
 
66
  return pickle.load(f)
67
 
68
 
 
 
 
 
69
  def _idf(n_docs: int, df: int) -> float:
70
  return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
71
 
72
 
73
+ def _require_duckdb():
74
+ try:
75
+ import duckdb # type: ignore
76
+ except ImportError as exc:
77
+ raise RuntimeError("duckdb is required for sparse GraphRAG spill (no sqlite)") from exc
78
+ return duckdb
79
+
80
+
81
+ def duckdb_ready(db_path: Path, expected: int) -> bool:
82
  if not db_path.is_file():
83
  return False
84
+ duckdb = _require_duckdb()
85
  try:
86
+ conn = duckdb.connect(str(db_path), read_only=True)
87
  n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
88
  conn.close()
89
  return n == expected
 
91
  return False
92
 
93
 
94
+ def build_sqlite_fts(*args, **kwargs): # pragma: no cover - removed
95
+ raise RuntimeError("SQLite FTS is removed; use DuckDB parquet neighbors")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
 
98
+ def neighbors_via_duckdb(
99
+ corpus_path: Path,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  spill: Path,
101
  n_docs: int,
102
  *,
103
  k: int = NEIGHBOR_K,
 
 
 
104
  resume: bool = True,
105
  log: Callable[[str], None] | None = None,
106
  ) -> list[Path]:
107
+ """DuckDB FTS over corpus parquet → neighbor_*.parquet shards. No SQLite."""
108
+ from .duckdb_store import build_fts_index, stream_neighbors_to_parquet
109
 
110
+ spill = Path(spill)
 
 
111
  spill.mkdir(parents=True, exist_ok=True)
112
+ db_path = spill / "neighbors.duckdb"
113
+ if not duckdb_ready(db_path, n_docs):
114
+ if db_path.exists():
115
+ db_path.unlink()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  if log:
117
+ log(f"building duckdb fts n={n_docs} -> {db_path}")
118
+ build_fts_index(corpus_path, db_path, n_docs, log=log)
 
 
 
119
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  if log:
121
+ log(f"reusing duckdb fts n={n_docs} path={db_path}")
122
+ return stream_neighbors_to_parquet(
123
+ db_path, spill, n_docs, k=k, resume=resume, log=log
124
+ )
 
 
125
 
126
 
127
  def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]:
128
+ """Yield (start_index, shard_list) from parquet neighbor shards."""
129
+ from .duckdb_store import iter_neighbor_parquet_shards
130
+
131
+ parquet = list(Path(spill).glob("neighbors_*.parquet"))
132
+ if parquet:
133
+ yield from iter_neighbor_parquet_shards(spill)
134
+ return
135
+ # Legacy pickle shards (pre-DuckDB). Do not create new ones.
136
+ paths = sorted(Path(spill).glob("neighbors_*.pkl"))
137
  for sp in paths:
138
  parts = sp.stem.split("_")
139
  start_i = int(parts[1])
 
156
  return neighbors
157
 
158
 
159
+ def neighbors_via_sqlite(*args, **kwargs):
160
+ """Removed. Sparse GraphRAG neighbors are DuckDB/parquet only."""
161
+ return neighbors_via_duckdb(*args, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
 
164
  def build_graph_from_neighbor_shards(
 
258
  batch: int = 512,
259
  log: Callable[[str], None] | None = None,
260
  ) -> dict[str, Any]:
261
+ """Stream tokenize corpus → DuckDB TF → bm25_documents/postings parquet + stats.
262
 
263
+ Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.json exist
264
  with matching n_docs, reuse.
265
  """
266
  spill.mkdir(parents=True, exist_ok=True)
267
  docs_path = spill / "bm25_documents.parquet"
268
  post_path = spill / "bm25_postings.parquet"
269
+ stats_json = spill / "bm25_stats.json"
270
  stats_path = spill / "bm25_stats.pkl"
271
+ if docs_path.is_file() and post_path.is_file():
272
+ stats = None
273
+ if stats_json.is_file():
274
+ stats = json.loads(stats_json.read_text(encoding="utf-8"))
275
+ elif stats_path.is_file():
276
+ stats = load_pickle(stats_path)
277
+ if stats is not None and int(stats.get("n_docs", -1)) == n_docs:
278
  if log:
279
  log(f"reusing bm25 spill n_docs={n_docs}")
280
  return {"stats": stats, "documents": docs_path, "postings": post_path}
281
 
282
+ duckdb = _require_duckdb()
283
+ bm25_db = spill / "bm25_tf.duckdb"
284
+ if bm25_db.exists():
285
+ bm25_db.unlink()
286
+ conn = duckdb.connect(str(bm25_db))
 
 
 
287
  conn.execute(
288
+ "CREATE TABLE tf (term VARCHAR NOT NULL, doc INTEGER NOT NULL, "
289
+ "ttf INTEGER NOT NULL, btf INTEGER NOT NULL)"
290
  )
291
  title_len = np.zeros(n_docs, dtype=np.int32)
292
  body_len = np.zeros(n_docs, dtype=np.int32)
 
317
  ]
318
  processed = 0
319
  batch_rows: list[tuple] = []
 
320
  for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols):
321
  d = batch_tbl.to_pydict()
322
  m = len(d["document_index"])
 
360
  }
361
  )
362
  if len(batch_rows) >= 20_000:
363
+ conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows)
 
 
364
  batch_rows.clear()
365
  processed += m
366
  if len(meta_buf) >= 20_000:
 
377
  checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log)
378
  gc.collect()
379
  if batch_rows:
380
+ conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows)
381
  batch_rows.clear()
382
  if meta_buf:
383
  dfm = pd.DataFrame(meta_buf)
 
388
  dfm.to_parquet(meta_path, index=False)
389
  del dfm
390
  meta_buf.clear()
 
391
  if log:
392
+ log("bm25 tf spilled to duckdb; writing documents")
393
 
394
  doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
395
  avgdl = float(doc_len.mean()) if n_docs else 0.0
 
460
 
461
  for term, doc, ttf, btf in conn.execute(
462
  "SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc"
463
+ ).fetchall():
464
  term = str(term)
465
  if cur_term is None:
466
  cur_term = term
 
513
  "n_posting_rows": int(out_rows),
514
  "n_postings": int(n_postings),
515
  }
516
+ stats_json.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8")
517
  try:
518
+ bm25_db.unlink()
519
  except Exception:
520
  pass
521
  if log:
 
523
  return {"stats": stats, "documents": docs_path, "postings": post_path}
524
 
525
 
526
+ def should_use_spill(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool:
527
  return n_docs >= threshold
528
+
529
+
530
+ def should_use_sqlite(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool:
531
+ """Alias: large-corpus path is DuckDB/parquet, not SQLite."""
532
+ return should_use_spill(n_docs, threshold)
country_laws_ir/structure.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract legal hierarchy from country-law text (Oregon-style, multilingual).
2
+
3
+ Oregon Revised Statutes are stored as title / chapter / section / subsection
4
+ trees. National gazettes are not that uniform: some use Article/Artikel,
5
+ some §, some only a single instrument body.
6
+
7
+ This module:
8
+
9
+ * strips leftover HTML chrome so GraphRAG sees legal text, not tags;
10
+ * detects multilingual heading markers (title/chapter/part/article/section);
11
+ * splits an instrument into those units when at least two headings exist;
12
+ * otherwise keeps the whole instrument (never invents a hierarchy).
13
+
14
+ Subsection markers such as ``(a)`` / ``(1)`` are recorded on the parent
15
+ unit; they are not forced into their own retrieval rows.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass, field
21
+ from html.parser import HTMLParser
22
+ import html as html_lib
23
+ import re
24
+ import unicodedata
25
+ from typing import Any
26
+
27
+ _WS_RE = re.compile(r"\s+", re.UNICODE)
28
+ _HAS_TAG_RE = re.compile(r"</?[a-zA-Z][^>]*>")
29
+
30
+ # Line-anchored headings. Numbers may be arabic, roman, or dotted (1.2).
31
+ _HEADING_RE = re.compile(
32
+ r"(?im)^[ \t]*(?:"
33
+ r"(?P<title>TITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|T[IÍ]TUL)\s+"
34
+ r"(?P<title_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)"
35
+ r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|CAP\.)\s+"
36
+ r"(?P<chapter_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)"
37
+ r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL)\s+"
38
+ r"(?P<part_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)"
39
+ r"|(?P<article>ART(?:ICLE|IKEL|ÍCULO|IGO|ICOLO|IKKEL)?\.?|ART\."
40
+ r"|ČLÁNEK|ČLÁNOK|ČLAN|SZAKASZ|ΆΡΘΡΟ|ΑΡΘΡΟ)\s+"
41
+ r"(?P<article_n>[0-9IVXLCDMΑ-Ω]+[A-Za-zΑ-Ωa-z0-9.\-]*)"
42
+ r"|(?P<section>SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|SEC\.)\s+"
43
+ r"(?P<section_n>[0-9A-Za-z.\-]+)"
44
+ r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9A-Za-z.\-]+)"
45
+ r")"
46
+ r"(?P<rest>[^\n]{0,200})?"
47
+ )
48
+
49
+ _SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)")
50
+
51
+ _KIND_RANK = {
52
+ "title": 1,
53
+ "chapter": 2,
54
+ "part": 3,
55
+ "article": 4,
56
+ "section": 5,
57
+ "subsection": 6,
58
+ }
59
+
60
+ MIN_SPLIT_HEADINGS = 2
61
+ MIN_UNIT_CHARS = 40
62
+
63
+ _ZH_ART_RE = re.compile(
64
+ r"(?:(?<=\n)|^)[  ]*"
65
+ r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)"
66
+ )
67
+ _AR_ART_RE = re.compile(
68
+ r"(?:(?<=\n)|^)[ \t]*(المادة|مادة)\s*([0-9٠-٩]+)"
69
+ )
70
+ _JA_ART_RE = re.compile(
71
+ r"(?:(?<=\n)|^)[  ]*(第[0-9一二三四五六七八九十百]+条)"
72
+ )
73
+
74
+
75
+ class _HTMLText(HTMLParser):
76
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
77
+
78
+ def __init__(self) -> None:
79
+ super().__init__(convert_charrefs=True)
80
+ self.parts: list[str] = []
81
+ self.skip = 0
82
+
83
+ def handle_starttag(self, tag, attrs):
84
+ if tag in self.SKIP:
85
+ self.skip += 1
86
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
87
+ self.parts.append("\n")
88
+
89
+ def handle_endtag(self, tag):
90
+ if tag in self.SKIP and self.skip:
91
+ self.skip -= 1
92
+ if tag in {"p", "div", "li", "tr"} and self.skip == 0:
93
+ self.parts.append("\n")
94
+
95
+ def handle_data(self, data):
96
+ if self.skip == 0:
97
+ self.parts.append(data)
98
+
99
+
100
+ def has_html_tags(text: str) -> bool:
101
+ return bool(text and _HAS_TAG_RE.search(text))
102
+
103
+
104
+ def strip_html(raw: str) -> str:
105
+ """Turn leftover HTML into visible legal text. No-op if there are no tags."""
106
+ if not raw or not _HAS_TAG_RE.search(raw):
107
+ return raw
108
+ parser = _HTMLText()
109
+ try:
110
+ parser.feed(raw)
111
+ parser.close()
112
+ text = "".join(parser.parts)
113
+ except Exception:
114
+ text = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
115
+ text = re.sub(r"(?is)<style.*?>.*?</style>", " ", text)
116
+ text = re.sub(r"(?is)<[^>]+>", " ", text)
117
+ text = html_lib.unescape(text).replace("\xa0", " ")
118
+ text = re.sub(r"[ \t]+", " ", text)
119
+ text = re.sub(r"\n[ \t]+", "\n", text)
120
+ text = re.sub(r"\n{3,}", "\n\n", text)
121
+ return text.strip()
122
+
123
+
124
+ def normalize_legal_text(value: Any) -> str:
125
+ """NFKC + HTML strip. Keeps newlines so heading detection still works."""
126
+ if value is None:
127
+ return ""
128
+ text = unicodedata.normalize("NFKC", str(value))
129
+ text = strip_html(text)
130
+ text = text.replace("\xa0", " ")
131
+ text = re.sub(r"[ \t]+", " ", text)
132
+ text = re.sub(r"\n[ \t]+", "\n", text)
133
+ text = re.sub(r"\n{3,}", "\n\n", text)
134
+ return text.strip()
135
+
136
+
137
+ @dataclass
138
+ class StructureUnit:
139
+ kind: str
140
+ number: str
141
+ heading: str
142
+ body: str
143
+ title_number: str = ""
144
+ chapter_number: str = ""
145
+ part_number: str = ""
146
+ article_number: str = ""
147
+ section_number: str = ""
148
+ subsections: tuple[str, ...] = ()
149
+ hierarchy_path: str = ""
150
+
151
+ def to_dict(self) -> dict[str, Any]:
152
+ return {
153
+ "kind": self.kind,
154
+ "number": self.number,
155
+ "heading": self.heading,
156
+ "body": self.body,
157
+ "title_number": self.title_number,
158
+ "chapter_number": self.chapter_number,
159
+ "part_number": self.part_number,
160
+ "article_number": self.article_number,
161
+ "section_number": self.section_number,
162
+ "subsections": list(self.subsections),
163
+ "hierarchy_path": self.hierarchy_path,
164
+ }
165
+
166
+
167
+ def _cursor_path(cursor: dict[str, str]) -> str:
168
+ parts = []
169
+ for key, label in (
170
+ ("title", "Title"),
171
+ ("chapter", "Chapter"),
172
+ ("part", "Part"),
173
+ ("article", "Article"),
174
+ ("section", "Section"),
175
+ ):
176
+ value = cursor.get(key) or ""
177
+ if value:
178
+ parts.append(f"{label} {value}")
179
+ return " > ".join(parts)
180
+
181
+
182
+ def _subsection_tokens(text: str) -> tuple[str, ...]:
183
+ seen: list[str] = []
184
+ for match in _SUBSECTION_RE.finditer(text):
185
+ token = match.group(1)
186
+ if token not in seen:
187
+ seen.append(token)
188
+ if len(seen) >= 40:
189
+ break
190
+ return tuple(seen)
191
+
192
+
193
+ def _units_from_regex(
194
+ text: str, matches: list[re.Match[str]], *, kind: str, lang: str
195
+ ) -> list[StructureUnit]:
196
+ if len(matches) < MIN_SPLIT_HEADINGS:
197
+ return []
198
+ units: list[StructureUnit] = []
199
+ for i, match in enumerate(matches):
200
+ start = match.start()
201
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
202
+ chunk = text[start:end].strip()
203
+ if len(chunk) < 16:
204
+ continue
205
+ number = re.sub(r"\s+", "", match.group(0))
206
+ heading = re.sub(r"\s+", " ", chunk.split("\n", 1)[0])[:240]
207
+ units.append(
208
+ StructureUnit(
209
+ kind=kind,
210
+ number=number,
211
+ heading=heading,
212
+ body=chunk,
213
+ article_number=number,
214
+ hierarchy_path=heading,
215
+ )
216
+ )
217
+ return units if len(units) >= MIN_SPLIT_HEADINGS else []
218
+
219
+
220
+ def split_script_units(text: str, language: str) -> list[StructureUnit]:
221
+ """Article splits for scripts that must not use Latin TITLE/ARTICLE."""
222
+ from .profiles import iso_lang
223
+
224
+ lang = iso_lang(language)
225
+ if lang in {"zh", "zh-cn", "zh-tw"}:
226
+ prepared = re.sub(
227
+ r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)",
228
+ r"\n\1",
229
+ text,
230
+ )
231
+ return _units_from_regex(prepared, list(_ZH_ART_RE.finditer(prepared)), kind="article", lang="zh")
232
+ if lang in {"ar", "fa"}:
233
+ prepared = re.sub(r"(المادة|مادة)", r"\n\1", text)
234
+ return _units_from_regex(prepared, list(_AR_ART_RE.finditer(prepared)), kind="article", lang="ar")
235
+ if lang == "ja":
236
+ prepared = re.sub(r"(第[0-9一二三四五六七八九十百]+条)", r"\n\1", text)
237
+ return _units_from_regex(prepared, list(_JA_ART_RE.finditer(prepared)), kind="article", lang="ja")
238
+ return []
239
+
240
+
241
+ def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]:
242
+ """Split *text* on legal headings. Empty list means keep the whole instrument.
243
+
244
+ Latin TITLE/ARTICLE splits are skipped for languages in
245
+ ``profiles.NO_LATIN_SPLIT_LANGS`` so Arabic/Chinese bodies are not
246
+ carved up on incidental English words.
247
+ """
248
+ from .profiles import latin_split_allowed
249
+
250
+ if not text or len(text) < 16:
251
+ return []
252
+ if language and not latin_split_allowed(language):
253
+ return split_script_units(text, language)
254
+ matches = list(_HEADING_RE.finditer(text))
255
+ if len(matches) < MIN_SPLIT_HEADINGS:
256
+ return []
257
+ cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""}
258
+ units: list[StructureUnit] = []
259
+ for i, match in enumerate(matches):
260
+ start = match.start()
261
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
262
+ chunk = text[start:end].strip()
263
+ kind = ""
264
+ number = ""
265
+ for name in ("title", "chapter", "part", "article", "section"):
266
+ if match.group(name):
267
+ kind = name
268
+ number = (match.group(f"{name}_n") or "").strip()
269
+ break
270
+ if match.group("section_sym"):
271
+ kind = "section"
272
+ number = (match.group("section_sym_n") or "").strip()
273
+ if not kind or not number:
274
+ continue
275
+ cursor[kind] = number
276
+ for lower, rank in _KIND_RANK.items():
277
+ if rank > _KIND_RANK[kind]:
278
+ cursor[lower] = ""
279
+ if len(chunk) < MIN_UNIT_CHARS:
280
+ continue
281
+ rest = (match.group("rest") or "").strip(" .-:")
282
+ heading = re.sub(r"\s+", " ", match.group(0)).strip()
283
+ if rest and rest not in heading:
284
+ heading = f"{heading} {rest}".strip()
285
+ units.append(
286
+ StructureUnit(
287
+ kind=kind,
288
+ number=number,
289
+ heading=heading[:240],
290
+ body=chunk,
291
+ title_number=cursor["title"],
292
+ chapter_number=cursor["chapter"],
293
+ part_number=cursor["part"],
294
+ article_number=cursor["article"],
295
+ section_number=cursor["section"],
296
+ subsections=_subsection_tokens(chunk),
297
+ hierarchy_path=_cursor_path(cursor),
298
+ )
299
+ )
300
+ retrieval = [u for u in units if u.kind in {"article", "section"}]
301
+ if len(retrieval) >= MIN_SPLIT_HEADINGS:
302
+ return retrieval
303
+ if len(units) >= MIN_SPLIT_HEADINGS:
304
+ return units
305
+ return []
country_laws_ir/upload.py CHANGED
@@ -1,24 +1,132 @@
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
+ # Fail closed for LCR-protected repos without importing the full package
61
+ # (site-packages ipfs_datasets_py can be stale and break this thin packager).
62
+ _protected = {"justicedao/ipfs_state_laws", "justicedao/ipfs_federal_register"}
63
+ if repo_id in _protected:
64
+ raise UploadError(
65
+ f"{repo_id} is a protected JusticeDAO repository; "
66
+ "mutate it only through legal_corpora_publication_runtime"
67
+ )
68
+ try:
69
+ from ipfs_datasets_py.huggingface.protected_repo_guard import (
70
+ require_unprotected_or_runtime,
71
+ )
72
+
73
+ require_unprotected_or_runtime(repo_id, method="upload_folder")
74
+ except UploadError:
75
+ raise
76
+ except Exception:
77
+ pass
78
+
79
+ resolved = (token or "").strip() or _token_from_env()
80
+ if not resolved:
81
+ raise UploadError(
82
+ "HF_TOKEN is required for --upload. "
83
+ + _OPERATOR_HINT.format(repo=repo_id, local_dir=local_dir)
84
+ )
85
+
86
+ from huggingface_hub import HfApi
87
+
88
+ api = HfApi(token=resolved)
89
+ if create:
90
+ api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True, private=False)
91
+ ignore = ["**/__pycache__/**", "**/*.pyc", "**/*.tmp", "**/*.tmp.npy"]
92
+ n_files = sum(1 for path in local_dir.rglob("*") if path.is_file())
93
+ nbytes = sum(path.stat().st_size for path in local_dir.rglob("*") if path.is_file())
94
+ use_large = n_files >= 80 or nbytes >= 80 * 1024 * 1024
95
+ if use_large and hasattr(api, "upload_large_folder"):
96
+ api.upload_large_folder(
97
+ folder_path=str(local_dir),
98
+ repo_id=repo_id,
99
+ repo_type="dataset",
100
+ ignore_patterns=ignore,
101
+ )
102
+ revision = ""
103
+ try:
104
+ from huggingface_hub import dataset_info as _dataset_info
105
 
106
+ pinned = _dataset_info(repo_id, token=resolved)
107
+ revision = str(getattr(pinned, "sha", "") or "")
108
+ except Exception:
109
+ revision = ""
110
+ return {
111
+ "url": f"https://huggingface.co/datasets/{repo_id}",
112
+ "repo_id": repo_id,
113
+ "revision": revision,
114
+ "local_dir": str(local_dir),
115
+ "method": "upload_large_folder",
116
+ }
117
+ info = api.upload_folder(
118
+ folder_path=str(local_dir),
119
+ repo_id=repo_id,
120
+ repo_type="dataset",
121
+ commit_message=commit_message
122
+ or f"Incremental country-laws-ir GraphRAG release for {repo_id}",
123
+ ignore_patterns=ignore,
124
  )
125
+ revision = getattr(info, "oid", None) or getattr(info, "commit_id", None) or ""
126
+ return {
127
+ "url": f"https://huggingface.co/datasets/{repo_id}",
128
+ "repo_id": repo_id,
129
+ "revision": revision,
130
+ "local_dir": str(local_dir),
131
+ "method": "upload_folder",
132
+ }
country_laws_ir/vectors.py CHANGED
@@ -14,7 +14,11 @@ import pandas as pd
14
  from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
15
 
16
  MODEL_NAME = "thenlper/gte-small"
 
17
  DIMENSION = 384
 
 
 
18
  MAX_ROWS_PER_CENTROID = 8192
19
  MAX_SHARDS_PER_CENTROID = 2
20
 
@@ -24,41 +28,108 @@ def _l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray:
24
  return x / np.maximum(n, eps)
25
 
26
 
27
- def embeddings_available() -> bool:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  try:
29
- import torch # noqa: F401
30
- from sentence_transformers import SentenceTransformer # noqa: F401
31
 
32
  return True
 
 
 
 
 
 
 
 
 
 
33
  except Exception:
34
  return False
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def encode_corpus(
38
  corpus: pd.DataFrame,
39
  batch_size: int = 64,
40
- device: str = "cpu",
41
  checkpoint_path: str | None = None,
42
  chunk_size: int = 4096,
43
  ) -> np.ndarray:
44
- """Encode corpus texts with gte-small in chunks; persist checkpoints when given."""
45
  import json
46
  import os
47
  from datetime import datetime, timezone
48
  from pathlib import Path as _Path
49
 
 
 
 
 
 
50
  from sentence_transformers import SentenceTransformer
51
 
52
  from .auth import configure_hf
53
 
54
  configure_hf()
55
- cache_root = _Path("/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(
59
- "SENTENCE_TRANSFORMERS_HOME",
60
- str(cache_root / "sentence-transformers"),
61
- )
62
  texts = []
63
  for rec in corpus.itertuples(index=False):
64
  title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
@@ -70,12 +141,22 @@ def encode_corpus(
70
  done = 0
71
  ckpt = _Path(checkpoint_path) if checkpoint_path else None
72
  meta_path = ckpt.with_suffix(".json") if ckpt else None
73
- meta_n = None
 
 
 
 
 
 
 
 
74
  if meta_path is not None and meta_path.exists():
75
  try:
76
  meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
77
  except Exception:
78
  meta_n = None
 
 
79
  if ckpt is not None and ckpt.exists():
80
  cached = np.load(ckpt)
81
  same_corpus = meta_n is None or int(meta_n) == n
@@ -87,56 +168,76 @@ def encode_corpus(
87
  ):
88
  done = int(cached.shape[0])
89
  out[:done] = cached.astype(np.float32, copy=False)
90
- print(f"embeddings resume {done}/{n} from {ckpt}", flush=True)
91
- else:
92
- print(
93
- f"embeddings checkpoint shape {getattr(cached, 'shape', None)} "
94
- f"meta_n={meta_n} incompatible with {(n, DIMENSION)}; restarting",
95
- flush=True,
 
 
 
 
 
96
  )
97
- if done >= n:
98
- return out
99
- model = SentenceTransformer(MODEL_NAME, device=device)
100
- while done < n:
101
- j = min(done + int(chunk_size), n)
102
- chunk = model.encode(
103
- texts[done:j],
104
- batch_size=batch_size,
105
- show_progress_bar=True,
106
- convert_to_numpy=True,
107
- normalize_embeddings=True,
108
  )
109
- out[done:j] = np.asarray(chunk, dtype=np.float32)
110
- done = j
111
- print(f"embeddings checkpoint {done}/{n}", flush=True)
112
  try:
113
- from .mem import checkpoint as _mem_checkpoint
114
- _mem_checkpoint(f"embeddings@{done}", row=done, every_n=max(chunk_size, 4096))
115
- except Exception as _mem_exc:
116
- # MemAbort should propagate; other import issues are non-fatal
117
- from .mem import MemAbort
118
- if isinstance(_mem_exc, MemAbort):
119
- raise
120
- if ckpt is not None:
121
- ckpt.parent.mkdir(parents=True, exist_ok=True)
122
- tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
123
- np.save(tmp, out[:done])
124
- tmp.replace(ckpt)
125
- if meta_path is not None:
126
- meta_path.write_text(
127
- json.dumps(
128
- {
129
- "n": n,
130
- "done": done,
131
- "dimension": DIMENSION,
132
- "model_name": MODEL_NAME,
133
- "ts": datetime.now(timezone.utc).isoformat(),
134
- }
 
 
 
 
 
 
 
 
 
 
135
  )
136
- + "\n",
137
- encoding="utf-8",
138
- )
139
- return out
 
 
 
 
 
 
 
 
 
 
140
 
141
 
142
  def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
@@ -160,25 +261,29 @@ def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) ->
160
 
161
 
162
  def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
 
 
 
 
 
163
  n = len(x)
164
- idx = np.arange(n)
165
- if n <= max_size:
166
- return [idx]
167
- labels = _spherical_kmeans(x, k=2)
168
- clusters = []
169
- for lab in (0, 1):
170
- members = idx[labels == lab]
171
- if len(members) == 0:
172
  continue
173
- if len(members) <= max_size:
174
- clusters.append(members)
175
- else:
176
- sub = _recursive_clusters(x[members], max_size=max_size)
177
- clusters.extend([members[s] for s in sub])
178
- if not clusters:
179
- mid = n // 2
180
- return [idx[:mid], idx[mid:]]
181
- return clusters
182
 
183
 
184
  def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
@@ -333,3 +438,85 @@ def layout_stub_vectors(corpus: pd.DataFrame, reason: str) -> dict[str, Any]:
333
  ],
334
  },
335
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
15
 
16
  MODEL_NAME = "thenlper/gte-small"
17
+ MODEL_REVISION = "17e1f347d17fe144873b1201da91788898c639cd"
18
  DIMENSION = 384
19
+ MAX_SEQ_LENGTH = 512
20
+ DEFAULT_DEVICE = "cuda"
21
+ SUPPORTED_DEVICES = frozenset({"cpu", "cuda", "cuda:0", "mps", "auto"})
22
  MAX_ROWS_PER_CENTROID = 8192
23
  MAX_SHARDS_PER_CENTROID = 2
24
 
 
28
  return x / np.maximum(n, eps)
29
 
30
 
31
+ def device_is_available(device: str) -> bool:
32
+ """Probe accelerator availability without loading a model."""
33
+ name = str(device or "").strip().lower()
34
+ if not name or name == "cpu":
35
+ return True
36
+ try:
37
+ import torch
38
+ except Exception:
39
+ return False
40
+ if name.startswith("cuda"):
41
+ return bool(
42
+ getattr(torch, "cuda", None)
43
+ and torch.backends.cuda.is_built()
44
+ and torch.cuda.is_available()
45
+ )
46
+ if name == "mps":
47
+ mps = getattr(getattr(torch, "backends", None), "mps", None)
48
+ return bool(mps is not None and mps.is_available())
49
+ return False
50
+
51
+
52
+ def select_device(requested: str = DEFAULT_DEVICE) -> tuple[str, bool]:
53
+ """Prefer CUDA like US Code / Open US Law; fall back to CPU."""
54
+ req = str(requested or DEFAULT_DEVICE).strip().lower() or DEFAULT_DEVICE
55
+ if req == "auto":
56
+ req = "cuda"
57
+ if req not in SUPPORTED_DEVICES and not req.startswith("cuda:"):
58
+ raise ValueError(f"unsupported embedding device: {requested!r}")
59
+ if device_is_available(req):
60
+ return req, False
61
+ return "cpu", True
62
+
63
+
64
+ def ensure_embedding_stack() -> bool:
65
+ """Lazy-import / lazy-install transformers + sentence-transformers.
66
+
67
+ Matches ``ipfs_datasets_py.auto_installer.ensure_module`` used by other
68
+ GraphRAG producers. Importing this module must not pip-install; first
69
+ encode may.
70
+ """
71
+ import os
72
+
73
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
74
  try:
75
+ import sentence_transformers # noqa: F401
76
+ import transformers # noqa: F401
77
 
78
  return True
79
+ except Exception:
80
+ pass
81
+ try:
82
+ from ipfs_datasets_py.auto_installer import ensure_module, install_for_component
83
+
84
+ install_for_component("graphrag")
85
+ ensure_module("torchvision", "torchvision")
86
+ ensure_module("transformers", "transformers")
87
+ module = ensure_module("sentence_transformers", "sentence-transformers")
88
+ return module is not None
89
  except Exception:
90
  return False
91
 
92
 
93
+ def embeddings_available() -> bool:
94
+ return ensure_embedding_stack()
95
+
96
+
97
+ def _is_real_vector(vec: object) -> bool:
98
+ try:
99
+ arr = np.asarray(vec, dtype=np.float32).reshape(-1)
100
+ except Exception:
101
+ return False
102
+ if arr.shape[0] != DIMENSION:
103
+ return False
104
+ if not np.isfinite(arr).all():
105
+ return False
106
+ return float(np.linalg.norm(arr)) > 1e-6
107
+
108
+
109
  def encode_corpus(
110
  corpus: pd.DataFrame,
111
  batch_size: int = 64,
112
+ device: str = DEFAULT_DEVICE,
113
  checkpoint_path: str | None = None,
114
  chunk_size: int = 4096,
115
  ) -> np.ndarray:
116
+ """Encode corpus texts with pinned gte-small on CUDA when available."""
117
  import json
118
  import os
119
  from datetime import datetime, timezone
120
  from pathlib import Path as _Path
121
 
122
+ if not ensure_embedding_stack():
123
+ raise RuntimeError(
124
+ "sentence-transformers is required for production GTE embeddings; "
125
+ "lazy install failed (python -m ipfs_datasets_py.auto_installer)"
126
+ )
127
  from sentence_transformers import SentenceTransformer
128
 
129
  from .auth import configure_hf
130
 
131
  configure_hf()
132
+ device, _fallback = select_device(device)
 
 
 
 
 
 
133
  texts = []
134
  for rec in corpus.itertuples(index=False):
135
  title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
 
141
  done = 0
142
  ckpt = _Path(checkpoint_path) if checkpoint_path else None
143
  meta_path = ckpt.with_suffix(".json") if ckpt else None
144
+ cache_root = _Path(
145
+ os.environ.get(
146
+ "COUNTRY_LAWS_IR_ROOT",
147
+ str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"),
148
+ )
149
+ ) / "cache" / "hf"
150
+ os.environ.setdefault("HF_HOME", str(cache_root))
151
+ os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
152
+ os.environ.setdefault("SENTENCE_TRANSFORMERS_HOME", str(cache_root / "sentence-transformers"))
153
  if meta_path is not None and meta_path.exists():
154
  try:
155
  meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
156
  except Exception:
157
  meta_n = None
158
+ else:
159
+ meta_n = None
160
  if ckpt is not None and ckpt.exists():
161
  cached = np.load(ckpt)
162
  same_corpus = meta_n is None or int(meta_n) == n
 
168
  ):
169
  done = int(cached.shape[0])
170
  out[:done] = cached.astype(np.float32, copy=False)
171
+ if done >= n:
172
+ return out
173
+
174
+ lock_fh = None
175
+ if device.startswith("cuda"):
176
+ import fcntl
177
+
178
+ lock_path = _Path(
179
+ os.environ.get(
180
+ "COUNTRY_LAWS_IR_ROOT",
181
+ str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"),
182
  )
183
+ ) / "cuda.encode.lock"
184
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
185
+ lock_fh = open(lock_path, "a", encoding="utf-8")
186
+ fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
187
+ try:
188
+ model = SentenceTransformer(
189
+ MODEL_NAME,
190
+ revision=MODEL_REVISION,
191
+ device=device,
 
 
192
  )
 
 
 
193
  try:
194
+ model.max_seq_length = MAX_SEQ_LENGTH
195
+ except Exception:
196
+ pass
197
+ while done < n:
198
+ j = min(done + int(chunk_size), n)
199
+ chunk = model.encode(
200
+ texts[done:j],
201
+ batch_size=batch_size,
202
+ show_progress_bar=True,
203
+ convert_to_numpy=True,
204
+ normalize_embeddings=True,
205
+ )
206
+ out[done:j] = np.asarray(chunk, dtype=np.float32)
207
+ done = j
208
+ if ckpt is not None:
209
+ ckpt.parent.mkdir(parents=True, exist_ok=True)
210
+ tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
211
+ np.save(tmp, out[:done])
212
+ tmp.replace(ckpt)
213
+ if meta_path is not None:
214
+ meta_path.write_text(
215
+ json.dumps(
216
+ {
217
+ "n": n,
218
+ "done": done,
219
+ "dimension": DIMENSION,
220
+ "model_name": MODEL_NAME,
221
+ "ts": datetime.now(timezone.utc).isoformat(),
222
+ }
223
+ )
224
+ + "\n",
225
+ encoding="utf-8",
226
  )
227
+ return out
228
+ finally:
229
+ if lock_fh is not None:
230
+ import fcntl as _fcntl
231
+
232
+ _fcntl.flock(lock_fh.fileno(), _fcntl.LOCK_UN)
233
+ lock_fh.close()
234
+ try:
235
+ import torch as _torch
236
+
237
+ if _torch.cuda.is_available():
238
+ _torch.cuda.empty_cache()
239
+ except Exception:
240
+ pass
241
 
242
 
243
  def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
 
261
 
262
 
263
  def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
264
+ """Split vectors into shards of at most *max_size* without unbounded recursion.
265
+
266
+ Spherical k-means can fail to split (all points one label). In that case
267
+ fall back to an even index split so layout cannot recurse forever.
268
+ """
269
  n = len(x)
270
+ if n == 0:
271
+ return []
272
+ pending: list[np.ndarray] = [np.arange(n)]
273
+ clusters: list[np.ndarray] = []
274
+ while pending:
275
+ idx = pending.pop()
276
+ if len(idx) <= max_size:
277
+ clusters.append(idx)
278
  continue
279
+ labels = _spherical_kmeans(x[idx], k=2)
280
+ parts = [idx[labels == lab] for lab in (0, 1)]
281
+ parts = [p for p in parts if len(p)]
282
+ if len(parts) < 2 or max(len(p) for p in parts) == len(idx):
283
+ mid = len(idx) // 2
284
+ parts = [idx[:mid], idx[mid:]]
285
+ pending.extend(parts)
286
+ return clusters or [np.arange(n)]
 
287
 
288
 
289
  def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
 
438
  ],
439
  },
440
  }
441
+
442
+
443
+ def assemble_embeddings(
444
+ corpus: pd.DataFrame,
445
+ prior_by_cid: dict[str, list[float]] | None = None,
446
+ *,
447
+ encode_missing: bool = True,
448
+ batch_size: int = 64,
449
+ device: str = DEFAULT_DEVICE,
450
+ checkpoint_path: str | None = None,
451
+ ) -> tuple[np.ndarray, dict[str, Any]]:
452
+ """Align a (n, 384) matrix to *corpus* row order.
453
+
454
+ Reuse is CID-keyed and only accepts real GTE vectors (finite, 384-d,
455
+ non-zero). Stub/zero priors are treated as missing and re-encoded on
456
+ CUDA when available — the US Code / Open US Law contract.
457
+ """
458
+ n = int(len(corpus))
459
+ out = np.zeros((n, DIMENSION), dtype=np.float32)
460
+ prior = prior_by_cid or {}
461
+ reused_idx: list[int] = []
462
+ missing_idx: list[int] = []
463
+ cids = corpus["entry_cid"].astype(str).tolist() if n else []
464
+ for i, cid in enumerate(cids):
465
+ vec = prior.get(cid)
466
+ if not _is_real_vector(vec):
467
+ missing_idx.append(i)
468
+ continue
469
+ out[i] = np.asarray(vec, dtype=np.float32).reshape(-1)
470
+ reused_idx.append(i)
471
+
472
+ report: dict[str, Any] = {
473
+ "n_docs": n,
474
+ "n_reused": len(reused_idx),
475
+ "n_encoded": 0,
476
+ "n_missing": len(missing_idx),
477
+ "model_name": MODEL_NAME,
478
+ "model_revision": MODEL_REVISION,
479
+ "dimension": DIMENSION,
480
+ "status": "reused" if not missing_idx else "partial",
481
+ }
482
+ resolved, fallback = select_device(device)
483
+ report["device"] = resolved
484
+ report["device_fallback"] = fallback
485
+ if not missing_idx:
486
+ report["status"] = "reused"
487
+ return _l2_normalize(out) if n else out, report
488
+ if not encode_missing:
489
+ report["status"] = "incomplete"
490
+ return out, report
491
+ if not ensure_embedding_stack():
492
+ report["status"] = "stub_missing_encoder"
493
+ report["reason"] = "sentence-transformers/transformers lazy install failed"
494
+ return out, report
495
+
496
+ missing = corpus.iloc[missing_idx].reset_index(drop=True)
497
+ encoded = encode_corpus(
498
+ missing,
499
+ batch_size=batch_size,
500
+ device=resolved,
501
+ checkpoint_path=checkpoint_path,
502
+ )
503
+ for local_i, corpus_i in enumerate(missing_idx):
504
+ out[corpus_i] = encoded[local_i]
505
+ report["n_encoded"] = int(len(missing_idx))
506
+ report["n_missing"] = 0
507
+ report["status"] = "merged"
508
+ return _l2_normalize(out), report
509
+
510
+
511
+ def embeddings_by_cid(corpus: pd.DataFrame, matrix: np.ndarray) -> dict[str, list[float]]:
512
+ """Project a row-aligned embedding matrix back to a CID map."""
513
+ out: dict[str, list[float]] = {}
514
+ if corpus is None or corpus.empty:
515
+ return out
516
+ x = np.asarray(matrix, dtype=np.float32)
517
+ cids = corpus["entry_cid"].astype(str).tolist()
518
+ for i, cid in enumerate(cids):
519
+ if i >= len(x):
520
+ break
521
+ out[cid] = x[i].astype(np.float32).tolist()
522
+ return out
country_laws_ir/verify.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Admission verifiers for country-law normalization, before GraphRAG.
2
+
3
+ Oregon-style structure is preferred but not required for every gazette.
4
+ Verifiers fail closed on invented text, residual HTML, empty corpora, and
5
+ duplicate CIDs. Missing title/section hierarchy is a warning unless the
6
+ corpus already split into articles.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import asdict, dataclass
12
+ import re
13
+ from typing import Any
14
+
15
+ import pandas as pd
16
+
17
+ from .structure import has_html_tags
18
+
19
+ SCHEMA_VERSION = "country-laws-normalize-verify/v1"
20
+
21
+ _HTML_FAIL_FRACTION = 0.02
22
+ _SHORT_BODY_FAIL_FRACTION = 0.50
23
+ _MIN_BODY_CHARS = 40
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Check:
28
+ id: str
29
+ severity: str # fail | warn
30
+ passed: bool
31
+ message: str
32
+ evidence: dict[str, Any]
33
+
34
+ def to_dict(self) -> dict[str, Any]:
35
+ return asdict(self)
36
+
37
+
38
+ def _bodies(corpus: pd.DataFrame) -> list[str]:
39
+ if corpus is None or corpus.empty or "body" not in corpus.columns:
40
+ return []
41
+ return [str(x or "") for x in corpus["body"].tolist()]
42
+
43
+
44
+ def check_nonempty(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
45
+ n = int(len(corpus)) if corpus is not None else 0
46
+ return Check(
47
+ id="nonempty_corpus",
48
+ severity="fail",
49
+ passed=n > 0,
50
+ message="normalized corpus has rows" if n else "normalized corpus is empty",
51
+ evidence={"n_out": n, "n_dropped": report.get("n_dropped_total")},
52
+ )
53
+
54
+
55
+ def check_entry_cids(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
56
+ if corpus is None or corpus.empty:
57
+ return Check(
58
+ id="entry_cid_unique",
59
+ severity="fail",
60
+ passed=False,
61
+ message="no entry_cid values to verify",
62
+ evidence={},
63
+ )
64
+ missing = int(corpus["entry_cid"].isna().sum()) if "entry_cid" in corpus.columns else int(len(corpus))
65
+ dupes = int(corpus["entry_cid"].duplicated().sum()) if "entry_cid" in corpus.columns else 0
66
+ empty = int((corpus["entry_cid"].astype(str).str.strip() == "").sum()) if "entry_cid" in corpus.columns else 0
67
+ ok = missing == 0 and dupes == 0 and empty == 0
68
+ return Check(
69
+ id="entry_cid_unique",
70
+ severity="fail",
71
+ passed=ok,
72
+ message="every row has a unique entry_cid" if ok else "missing or duplicate entry_cid",
73
+ evidence={"missing": missing, "empty": empty, "duplicate": dupes},
74
+ )
75
+
76
+
77
+ def check_no_invented_text(report: dict[str, Any]) -> Check:
78
+ flag = bool(report.get("never_invented_legal_text", False))
79
+ return Check(
80
+ id="never_invented_legal_text",
81
+ severity="fail",
82
+ passed=flag,
83
+ message="normalizer did not invent legal text" if flag else "invented-text flag is false",
84
+ evidence={"never_invented_legal_text": flag},
85
+ )
86
+
87
+
88
+ def check_html_residual(corpus: pd.DataFrame) -> Check:
89
+ bodies = _bodies(corpus)
90
+ tagged = [b for b in bodies if has_html_tags(b)]
91
+ n = len(bodies) or 1
92
+ fraction = len(tagged) / float(n)
93
+ passed = fraction <= _HTML_FAIL_FRACTION
94
+ return Check(
95
+ id="html_residual",
96
+ severity="fail",
97
+ passed=passed,
98
+ message=(
99
+ "HTML tags stripped from legal bodies"
100
+ if passed
101
+ else f"{len(tagged)}/{len(bodies)} bodies still contain HTML tags"
102
+ ),
103
+ evidence={
104
+ "n_bodies": len(bodies),
105
+ "n_with_tags": len(tagged),
106
+ "fraction": fraction,
107
+ "samples": [b[:120] for b in tagged[:5]],
108
+ },
109
+ )
110
+
111
+
112
+ def check_short_bodies(corpus: pd.DataFrame) -> Check:
113
+ bodies = _bodies(corpus)
114
+ if not bodies:
115
+ return Check(
116
+ id="short_bodies",
117
+ severity="fail",
118
+ passed=False,
119
+ message="no bodies to measure",
120
+ evidence={},
121
+ )
122
+ short = sum(1 for b in bodies if len(b) < _MIN_BODY_CHARS)
123
+ fraction = short / float(len(bodies))
124
+ passed = fraction <= _SHORT_BODY_FAIL_FRACTION
125
+ return Check(
126
+ id="short_bodies",
127
+ severity="fail" if not passed else "warn",
128
+ passed=passed,
129
+ message=(
130
+ "most legal units have usable body length"
131
+ if passed
132
+ else f"{short}/{len(bodies)} bodies shorter than {_MIN_BODY_CHARS} characters"
133
+ ),
134
+ evidence={"n_short": short, "n_bodies": len(bodies), "fraction": fraction},
135
+ )
136
+
137
+
138
+ def check_heading_language(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
139
+ """Warn when Latin heading dialect disagrees with the document language."""
140
+ from .profiles import NO_LATIN_SPLIT_LANGS, iso_lang
141
+
142
+ doc_lang = iso_lang(report.get("document_language_majority") or "")
143
+ head_lang = iso_lang(report.get("heading_language_majority") or "")
144
+ counts = report.get("heading_language_counts") or {}
145
+ if (
146
+ doc_lang in NO_LATIN_SPLIT_LANGS
147
+ and report.get("unit") == "structured"
148
+ and head_lang
149
+ and head_lang not in NO_LATIN_SPLIT_LANGS
150
+ and head_lang != doc_lang
151
+ ):
152
+ return Check(
153
+ id="heading_language",
154
+ severity="fail",
155
+ passed=False,
156
+ message=(
157
+ f"document language {doc_lang} was split with Latin headings ({head_lang}); "
158
+ "use script-specific article markers or collector article rows"
159
+ ),
160
+ evidence={"document_language": doc_lang, "heading_counts": counts, "unit": report.get("unit")},
161
+ )
162
+ if doc_lang and head_lang and doc_lang != head_lang and sum(counts.values()) >= 8:
163
+ return Check(
164
+ id="heading_language",
165
+ severity="warn",
166
+ passed=True,
167
+ message=(
168
+ f"heading lexicon majority is {head_lang} but documents are {doc_lang}; "
169
+ "review samples before trusting structure"
170
+ ),
171
+ evidence={
172
+ "document_language": doc_lang,
173
+ "heading_language": head_lang,
174
+ "heading_counts": counts,
175
+ },
176
+ )
177
+ return Check(
178
+ id="heading_language",
179
+ severity="warn",
180
+ passed=True,
181
+ message=(
182
+ f"heading lexicon {head_lang or 'none'} vs document language {doc_lang or 'unknown'}"
183
+ ),
184
+ evidence={
185
+ "document_language": doc_lang,
186
+ "heading_language": head_lang,
187
+ "heading_counts": counts,
188
+ },
189
+ )
190
+
191
+
192
+ def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
193
+ unit = str(report.get("unit") or "")
194
+ n = int(len(corpus)) if corpus is not None else 0
195
+ structured_rows = 0
196
+ if corpus is not None and not corpus.empty:
197
+ if "hierarchy_path" in corpus.columns:
198
+ structured_rows = int((corpus["hierarchy_path"].fillna("").astype(str).str.len() > 0).sum())
199
+ if "record_type" in corpus.columns:
200
+ structured_rows = max(
201
+ structured_rows,
202
+ int(corpus["record_type"].isin(["article", "section"]).sum()),
203
+ )
204
+ coverage = structured_rows / float(n) if n else 0.0
205
+ # Article or structured units are success. Pure law-level is a warning, not a fail:
206
+ # many gazettes have no title/section markers.
207
+ if unit in {"article", "structured"} or coverage >= 0.5:
208
+ return Check(
209
+ id="legal_structure",
210
+ severity="warn",
211
+ passed=True,
212
+ message=f"retrieval units are structured ({unit}, coverage={coverage:.2f})",
213
+ evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
214
+ )
215
+ return Check(
216
+ id="legal_structure",
217
+ severity="warn",
218
+ passed=True,
219
+ message=(
220
+ "kept whole-instrument units; no title/article/section headings detected "
221
+ "(expected for some gazettes)"
222
+ ),
223
+ evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
224
+ )
225
+
226
+
227
+ def verify_normalized_corpus(
228
+ corpus: pd.DataFrame,
229
+ report: dict[str, Any],
230
+ *,
231
+ slug: str = "",
232
+ ) -> dict[str, Any]:
233
+ """Run all normalization verifiers. Fail-closed on any failed `fail` check."""
234
+ checks = [
235
+ check_nonempty(corpus, report),
236
+ check_entry_cids(corpus, report),
237
+ check_no_invented_text(report),
238
+ check_html_residual(corpus),
239
+ check_short_bodies(corpus),
240
+ check_structure(corpus, report),
241
+ check_heading_language(corpus, report),
242
+ ]
243
+ failed = [c for c in checks if c.severity == "fail" and not c.passed]
244
+ admitted = not failed
245
+ return {
246
+ "schema_version": SCHEMA_VERSION,
247
+ "slug": slug,
248
+ "admitted": admitted,
249
+ "n_checks": len(checks),
250
+ "n_failed": len(failed),
251
+ "failed_ids": [c.id for c in failed],
252
+ "checks": [c.to_dict() for c in checks],
253
+ "blocks_graphrag": not admitted,
254
+ }
255
+
256
+
257
+ class NormalizationAdmissionError(RuntimeError):
258
+ """Raised when verifiers refuse to send a corpus to GraphRAG."""
259
+
260
+
261
+ def verify_source(source: str) -> dict[str, Any]:
262
+ """Load a Hub/local pack, normalize, and run verifiers (no GraphRAG)."""
263
+ from .build import CACHE
264
+ from .catalog import get_country
265
+ from .normalize import build_corpus, load_source
266
+
267
+ country = get_country(source)
268
+ local = country.get("local_source_dir")
269
+ laws, articles, source_meta = load_source(local or country["repo"], CACHE)
270
+ corpus, report = build_corpus(laws, articles, source_meta)
271
+ verdict = verify_normalized_corpus(corpus, report, slug=country["slug"])
272
+ report["verification"] = verdict
273
+ return {
274
+ "slug": country["slug"],
275
+ "source": country["repo"],
276
+ "n_out": report.get("n_out"),
277
+ "unit": report.get("unit"),
278
+ "verification": verdict,
279
+ "drops": report.get("drops"),
280
+ }
data/bm25/documents/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:860a20675797c95295d0858ae80606b1c41f8085b5518b375e9abe0cc3c71dc1
3
- size 368561
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5fd4064d3307d65014eda40a56474c085ee0eac48f6882aafd2eeb9596fe5df
3
+ size 505685
data/bm25/documents/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9aed57473c8c6a419d70f7a88e2f812d42d903624437d261637119ced083bf3c
3
- size 368413
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74795c6ccfa80c09b8bd6bc315c86eb173ec038addbaf3a286731a9836908b2d
3
+ size 505256
data/bm25/documents/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2865aebd34ab1550cb1bde375e4b8746f414cdb97092ff30cf33af92dfb8ef99
3
- size 165483
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8fcb8e856d47144a383b748ad2c1e75f27399b68f0bfbf61f2f7a82ca5236d0
3
+ size 207945
data/bm25/postings/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:449352808135f06bfca2bf528de4e6f8b0d6cd3a3f34984c87edfd2570c745f1
3
- size 793240
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74899c071ecc3ab75bd7fcac7ad5a6fa4f38f0b7fffbe8fd973f58f718873c22
3
+ size 209619
data/bm25/postings/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:033470212ddcd40e12979c4ddd2443fcf4a03786ede837ce4024837ffec7ab04
3
- size 783392
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8be646723478d95c9e03a8a4e5b12ccd93c6bd6ab645e468bb05e6515fc0c493
3
+ size 594030
data/bm25/postings/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0c17ca6cb1c03079c20f9c96336842b1412e554bd555d4c5024085b863697754
3
- size 948081
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8497d4b6354f5c3b31181f041bb4e055c2e1d49fb8114803af454071d56415e3
3
+ size 514556
data/bm25/postings/part-000003.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:61e65f19169774f27e5cd71a3e00db3dee7aa3d13c36b87042d838cd71d996ac
3
- size 990527
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35b3910b79ba80d5e12f86b657485f40c98ea7a7a26ff5814d17e6eb63595c20
3
+ size 500924
data/bm25/postings/part-000004.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:22b90eb7821fa024d2fe0fcb23a9828b010058381b364b1eeafac5d9bbe98cd7
3
- size 272391
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1e4707df479e2f0087ce851102cb5e8bbc4a2572cc1aa72c34dc795ca2e58c6
3
+ size 566517
data/bm25/postings/part-000005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e741b34a0f0c0c5be57b1e4eaed76a1665a5bdf98fda0893a5570458de05906
3
+ size 121832
data/corpus/part-000000.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bd47600c807926c73563bf5c40579653a2b8e937ab6e5a1634605b541ca46c9d
3
- size 1561917
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f19ce33a158a468119e6fc7f7de456d5482dbd1c0a7e20d2ecc47a72fed4d74c
3
+ size 1570303
data/corpus/part-000001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:db51d39448f4f36bdd0e70cb7a3413acb3e0bbd72df05f86604365d5625e5cba
3
- size 1453906
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edd08e86c071d1146b68a4662720faedeb109b3b4cd008ae44fab6594a5cfb8d
3
+ size 1460927
data/corpus/part-000002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:93f54c3b249d84fcc259f5022b23e99101d1ae515143995e4605414b0f8baa55
3
- size 596594
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f48adf69ee081949795f9aa1a9de3b6ee497ce8b9035fbc5f7c816e019ce256
3
+ size 601572
data/graph/adjacency/in/part-000000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab76e07550cf005e6a861d466ce304763a2e05b3f5ef47fb13aa2307d82d4cc1
3
+ size 511238
data/graph/adjacency/in/part-000001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec8d8e0c2f49c1bb6b378df401494a06fa0bb7e0c9d7f29f571fe452c6a692c8
3
+ size 519126
data/graph/adjacency/in/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9eefba389959082004b444c065b7daa4e17df0f6223e76e28a0c22fe5fba0fe1
3
+ size 467734
data/graph/adjacency/in/part-000003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99060370a128f8418041a0caef44cfb002b5927b0b0101728256125f0d06f02d
3
+ size 402067
data/graph/adjacency/in/part-000004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:167b7bb1a404185c28acd8e153453d146a829cca3ecd1a765303b4b6d489b5fa
3
+ size 480282
data/graph/adjacency/in/part-000005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d489f01fd72dcf69f9e287a017c2a4dd58dc965fa16c1e8fde451386ca9b2c35
3
+ size 583488
data/graph/adjacency/in/part-000006.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33edd225916b56b0761c442933000867564a048fd57fd551bc69e1505c08a7d6
3
+ size 295841
data/graph/adjacency/in/part-000007.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:731801565bbeabc1ead1d9e6b86444cf4bb3477911448f7cef263c7eaae25071
3
+ size 583935
data/graph/adjacency/in/part-000008.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d6aa3b3c55765a7467540992ee45c4320828e2ae508ed0137dfa373f75543a1
3
+ size 529049
data/graph/adjacency/in/part-000009.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c666a42bc11f134c20f06b476ef7ed43328476d149771c86685025d695f74f1d
3
+ size 246648
data/graph/adjacency/out/part-000000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aaf58471bdab7ec191adbce1d5b1e20ae901f9307b31295e9bbdfd2667e694dc
3
+ size 356063
data/graph/adjacency/out/part-000001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd53cd85a58f9e9004d7b3ae69fcbc1f3f818558c5908ec0a5bfe95d4d1fdd9a
3
+ size 356439
data/graph/adjacency/out/part-000002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76c8ea87ff438794fe03ca9ebb34bc542012beb6a86446daa0e9bd55a1ee86e1
3
+ size 356217
data/graph/adjacency/out/part-000003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26e3c07920dabebbec3a9cad5c192f609c9ad2c0847ad863ab9443e33e7c97ed
3
+ size 356067
data/graph/adjacency/out/part-000004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f327391a50760b4dbd84e5effa8b70b50d9f716632800604aef49450d421ae63
3
+ size 356743
data/graph/adjacency/out/part-000005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e542407c88fbe94be6d29bb169a775a5e8a4d975c1ed11e96e31380de654ea6f
3
+ size 356541