Datasets:
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +8 -8
- build.py +142 -94
- country_laws_ir/__main__.py +83 -3
- country_laws_ir/build.py +142 -94
- country_laws_ir/citations.py +147 -0
- country_laws_ir/coverage.py +4 -1
- country_laws_ir/duckdb_store.py +475 -0
- country_laws_ir/incremental.py +20 -2
- country_laws_ir/normalize.py +190 -44
- country_laws_ir/package.py +141 -79
- country_laws_ir/profiles.py +124 -0
- country_laws_ir/query.py +35 -2
- country_laws_ir/sparse.py +137 -0
- country_laws_ir/spill.py +80 -311
- country_laws_ir/structure.py +305 -0
- country_laws_ir/upload.py +17 -4
- country_laws_ir/vectors.py +174 -77
- country_laws_ir/verify.py +308 -0
- data/bm25/documents/part-000000.parquet +2 -2
- data/bm25/documents/part-000001.parquet +2 -2
- data/bm25/documents/part-000002.parquet +2 -2
- data/bm25/documents/part-000003.parquet +2 -2
- data/bm25/documents/part-000004.parquet +2 -2
- data/bm25/documents/part-000005.parquet +2 -2
- data/bm25/documents/part-000006.parquet +2 -2
- data/bm25/documents/part-000007.parquet +2 -2
- data/bm25/documents/part-000008.parquet +2 -2
- data/bm25/documents/part-000009.parquet +2 -2
- data/bm25/documents/part-000010.parquet +2 -2
- data/bm25/postings/part-000000.parquet +2 -2
- data/bm25/postings/part-000001.parquet +2 -2
- data/bm25/postings/part-000002.parquet +2 -2
- data/bm25/postings/part-000003.parquet +2 -2
- data/bm25/postings/part-000004.parquet +2 -2
- data/bm25/postings/part-000005.parquet +2 -2
- data/bm25/postings/part-000006.parquet +2 -2
- data/bm25/postings/part-000007.parquet +2 -2
- data/bm25/postings/part-000008.parquet +2 -2
- data/bm25/postings/part-000009.parquet +3 -0
- data/bm25/postings/part-000010.parquet +3 -0
- data/bm25/postings/part-000011.parquet +3 -0
- data/corpus/part-000000.parquet +2 -2
- data/corpus/part-000001.parquet +2 -2
- data/corpus/part-000002.parquet +2 -2
- data/corpus/part-000003.parquet +2 -2
- data/corpus/part-000004.parquet +2 -2
- data/corpus/part-000005.parquet +2 -2
- data/corpus/part-000006.parquet +2 -2
- data/corpus/part-000007.parquet +2 -2
- data/corpus/part-000008.parquet +2 -2
README.md
CHANGED
|
@@ -72,14 +72,14 @@ Target Hub id (packaging metadata only): `justicedao/ipfs_pakistan_laws_ir`.
|
|
| 72 |
|
| 73 |
| Field | Value |
|
| 74 |
| --- | --- |
|
| 75 |
-
| Laws (corpus units) |
|
| 76 |
-
| Articles (corpus units) |
|
| 77 |
-
| Canonical docs |
|
| 78 |
-
| BM25 terms |
|
| 79 |
-
| BM25 postings |
|
| 80 |
-
| Graph nodes |
|
| 81 |
-
| Graph edges |
|
| 82 |
-
| Vectors |
|
| 83 |
|
| 84 |
## Canonical fields
|
| 85 |
|
|
|
|
| 72 |
|
| 73 |
| Field | Value |
|
| 74 |
| --- | --- |
|
| 75 |
+
| Laws (corpus units) | 958 |
|
| 76 |
+
| Articles (corpus units) | 41754 |
|
| 77 |
+
| Canonical docs | 42712 |
|
| 78 |
+
| BM25 terms | 47090 |
|
| 79 |
+
| BM25 postings | 3493690 |
|
| 80 |
+
| Graph nodes | 45587 |
|
| 81 |
+
| Graph edges | 298984 |
|
| 82 |
+
| Vectors | 42712 × 384-d `thenlper/gte-small` (embedded) |
|
| 83 |
|
| 84 |
## Canonical fields
|
| 85 |
|
build.py
CHANGED
|
@@ -18,20 +18,12 @@ from datetime import datetime, timezone
|
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import Any
|
| 20 |
|
| 21 |
-
from .
|
| 22 |
from .mem import MemAbort, checkpoint, log_mem
|
| 23 |
-
from .spill import
|
| 24 |
-
SQLITE_THRESHOLD,
|
| 25 |
-
build_bm25_tf_spill,
|
| 26 |
-
build_graph_from_neighbor_shards,
|
| 27 |
-
neighbors_via_sqlite,
|
| 28 |
-
should_use_sqlite,
|
| 29 |
-
spill_dir_for,
|
| 30 |
-
spill_pickle,
|
| 31 |
-
)
|
| 32 |
from .package import package_from_spill, package_release
|
| 33 |
from .catalog import get_country, indexable_countries, target_repo
|
| 34 |
-
|
| 35 |
from .incremental import (
|
| 36 |
fetch_hub_prior,
|
| 37 |
load_embedding_cache,
|
|
@@ -47,10 +39,10 @@ from .vectors import (
|
|
| 47 |
DIMENSION,
|
| 48 |
MODEL_NAME,
|
| 49 |
assemble_embeddings,
|
| 50 |
-
embeddings_available,
|
| 51 |
embeddings_by_cid,
|
| 52 |
layout_stub_vectors,
|
| 53 |
layout_vectors,
|
|
|
|
| 54 |
)
|
| 55 |
|
| 56 |
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
|
|
@@ -68,8 +60,17 @@ def _log(msg: str) -> None:
|
|
| 68 |
def record_progress(event: dict[str, Any]) -> None:
|
| 69 |
event = dict(event)
|
| 70 |
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
def _prior_dir_for(
|
|
@@ -121,11 +122,14 @@ def _encode_vectors(
|
|
| 121 |
_log(f"embedding cache reused_cids={len(prior_by_cid)}")
|
| 122 |
try:
|
| 123 |
positional = CACHE / "embeddings" / f"{country_slug}.npy"
|
|
|
|
|
|
|
|
|
|
| 124 |
embeddings, vector_report = assemble_embeddings(
|
| 125 |
corpus,
|
| 126 |
prior_by_cid,
|
| 127 |
-
encode_missing=
|
| 128 |
-
device=
|
| 129 |
checkpoint_path=str(positional),
|
| 130 |
)
|
| 131 |
if (
|
|
@@ -165,7 +169,7 @@ def build_country(
|
|
| 165 |
source: str,
|
| 166 |
out: Path | None = None,
|
| 167 |
upload: bool = False,
|
| 168 |
-
device: str = "
|
| 169 |
neighbor_k: int = 8,
|
| 170 |
skip_vectors: bool = False,
|
| 171 |
mode: str = "auto",
|
|
@@ -207,7 +211,11 @@ def build_country(
|
|
| 207 |
)
|
| 208 |
)
|
| 209 |
plan = plan_rebuild(
|
| 210 |
-
mode=mode,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
)
|
| 212 |
if plan.skip_build:
|
| 213 |
_log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
|
|
@@ -239,6 +247,13 @@ def build_country(
|
|
| 239 |
)
|
| 240 |
if corpus.empty:
|
| 241 |
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
import gc
|
| 244 |
|
|
@@ -248,6 +263,7 @@ def build_country(
|
|
| 248 |
prior=prior,
|
| 249 |
current_corpus=corpus,
|
| 250 |
force=force,
|
|
|
|
| 251 |
)
|
| 252 |
_log(
|
| 253 |
f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
|
|
@@ -276,50 +292,49 @@ def build_country(
|
|
| 276 |
checkpoint("vectors_spilled", log=_log)
|
| 277 |
extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
|
| 278 |
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
gc.collect()
|
| 323 |
_log(f"packaged {out}")
|
| 324 |
result = {
|
| 325 |
"country": country["slug"],
|
|
@@ -400,17 +415,29 @@ def reindex_from_gaps(
|
|
| 400 |
skip_vectors: bool = False,
|
| 401 |
workers: int = 4,
|
| 402 |
mode: str = "auto",
|
|
|
|
|
|
|
|
|
|
| 403 |
) -> list[dict[str, Any]]:
|
| 404 |
-
"""
|
| 405 |
|
| 406 |
Default cap skips huge corpora (Finland, Dominican Republic). Pass
|
| 407 |
``max_corpus_rows=None`` to include them.
|
| 408 |
"""
|
|
|
|
| 409 |
from .coverage import gap_report
|
| 410 |
|
| 411 |
if slugs is None:
|
| 412 |
-
|
| 413 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
|
| 415 |
if max_corpus_rows is not None:
|
| 416 |
rows = [
|
|
@@ -421,33 +448,54 @@ def reindex_from_gaps(
|
|
| 421 |
if limit is not None:
|
| 422 |
rows = rows[: int(limit)]
|
| 423 |
slugs = [str(r["slug"]) for r in rows]
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
)
|
| 428 |
-
|
| 429 |
-
for slug in slugs:
|
| 430 |
-
_log(f"reindex start {slug}")
|
| 431 |
-
try:
|
| 432 |
-
results.append(
|
| 433 |
-
build_country(
|
| 434 |
-
slug,
|
| 435 |
-
upload=upload,
|
| 436 |
-
mode=mode,
|
| 437 |
-
skip_vectors=skip_vectors,
|
| 438 |
-
fetch_hub_prior_ir=True,
|
| 439 |
-
)
|
| 440 |
-
)
|
| 441 |
-
except Exception as exc:
|
| 442 |
-
_log(f"FAILED {slug}: {exc}")
|
| 443 |
-
record_progress(
|
| 444 |
-
{
|
| 445 |
-
"event": "failed",
|
| 446 |
-
"country": slug,
|
| 447 |
-
"error": str(exc),
|
| 448 |
-
"traceback": traceback.format_exc(),
|
| 449 |
-
}
|
| 450 |
-
)
|
| 451 |
-
results.append({"country": slug, "skipped": False, "error": str(exc)})
|
| 452 |
-
continue
|
| 453 |
-
return results
|
|
|
|
| 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,
|
|
|
|
| 39 |
DIMENSION,
|
| 40 |
MODEL_NAME,
|
| 41 |
assemble_embeddings,
|
|
|
|
| 42 |
embeddings_by_cid,
|
| 43 |
layout_stub_vectors,
|
| 44 |
layout_vectors,
|
| 45 |
+
select_device,
|
| 46 |
)
|
| 47 |
|
| 48 |
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
|
|
|
|
| 60 |
def record_progress(event: dict[str, Any]) -> None:
|
| 61 |
event = dict(event)
|
| 62 |
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 63 |
+
PROGRESS.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
lock_path = PROGRESS.with_suffix(".lock")
|
| 65 |
+
with lock_path.open("a", encoding="utf-8") as lock_fh:
|
| 66 |
+
try:
|
| 67 |
+
import fcntl
|
| 68 |
+
|
| 69 |
+
fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
|
| 70 |
+
except Exception:
|
| 71 |
+
pass
|
| 72 |
+
with PROGRESS.open("a", encoding="utf-8") as f:
|
| 73 |
+
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 74 |
|
| 75 |
|
| 76 |
def _prior_dir_for(
|
|
|
|
| 122 |
_log(f"embedding cache reused_cids={len(prior_by_cid)}")
|
| 123 |
try:
|
| 124 |
positional = CACHE / "embeddings" / f"{country_slug}.npy"
|
| 125 |
+
resolved, fallback = select_device(device)
|
| 126 |
+
if fallback:
|
| 127 |
+
_log(f"embedding device fallback requested={device} using={resolved}")
|
| 128 |
embeddings, vector_report = assemble_embeddings(
|
| 129 |
corpus,
|
| 130 |
prior_by_cid,
|
| 131 |
+
encode_missing=True,
|
| 132 |
+
device=resolved,
|
| 133 |
checkpoint_path=str(positional),
|
| 134 |
)
|
| 135 |
if (
|
|
|
|
| 169 |
source: str,
|
| 170 |
out: Path | None = None,
|
| 171 |
upload: bool = False,
|
| 172 |
+
device: str = "cuda",
|
| 173 |
neighbor_k: int = 8,
|
| 174 |
skip_vectors: bool = False,
|
| 175 |
mode: str = "auto",
|
|
|
|
| 211 |
)
|
| 212 |
)
|
| 213 |
plan = plan_rebuild(
|
| 214 |
+
mode=mode,
|
| 215 |
+
source_meta=source_meta,
|
| 216 |
+
prior=prior,
|
| 217 |
+
force=force,
|
| 218 |
+
rebuild_stub_vectors=not skip_vectors,
|
| 219 |
)
|
| 220 |
if plan.skip_build:
|
| 221 |
_log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
|
|
|
|
| 247 |
)
|
| 248 |
if corpus.empty:
|
| 249 |
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
| 250 |
+
verdict = (norm_report or {}).get("verification") or {}
|
| 251 |
+
if verdict.get("blocks_graphrag") and not force:
|
| 252 |
+
from .verify import NormalizationAdmissionError
|
| 253 |
+
|
| 254 |
+
raise NormalizationAdmissionError(
|
| 255 |
+
f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}"
|
| 256 |
+
)
|
| 257 |
|
| 258 |
import gc
|
| 259 |
|
|
|
|
| 263 |
prior=prior,
|
| 264 |
current_corpus=corpus,
|
| 265 |
force=force,
|
| 266 |
+
rebuild_stub_vectors=not skip_vectors,
|
| 267 |
)
|
| 268 |
_log(
|
| 269 |
f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
|
|
|
|
| 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"],
|
|
|
|
| 415 |
skip_vectors: bool = False,
|
| 416 |
workers: int = 4,
|
| 417 |
mode: str = "auto",
|
| 418 |
+
force: bool = False,
|
| 419 |
+
all_indexable: bool = False,
|
| 420 |
+
device: str = "cuda",
|
| 421 |
) -> list[dict[str, Any]]:
|
| 422 |
+
"""Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
|
| 423 |
|
| 424 |
Default cap skips huge corpora (Finland, Dominican Republic). Pass
|
| 425 |
``max_corpus_rows=None`` to include them.
|
| 426 |
"""
|
| 427 |
+
from .catalog import indexable_countries
|
| 428 |
from .coverage import gap_report
|
| 429 |
|
| 430 |
if slugs is None:
|
| 431 |
+
if all_indexable:
|
| 432 |
+
rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()]
|
| 433 |
+
_log(f"reindex all indexable n={len(rows)}")
|
| 434 |
+
else:
|
| 435 |
+
report = gap_report(workers=workers)
|
| 436 |
+
rows = [c for c in report["countries"] if c.get("rebuild")]
|
| 437 |
+
_log(
|
| 438 |
+
f"reindex targets n={len(rows)} "
|
| 439 |
+
f"(from scan rebuild={len(report.get('rebuild') or [])})"
|
| 440 |
+
)
|
| 441 |
rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
|
| 442 |
if max_corpus_rows is not None:
|
| 443 |
rows = [
|
|
|
|
| 448 |
if limit is not None:
|
| 449 |
rows = rows[: int(limit)]
|
| 450 |
slugs = [str(r["slug"]) for r in rows]
|
| 451 |
+
kwargs = {
|
| 452 |
+
"upload": upload,
|
| 453 |
+
"mode": mode,
|
| 454 |
+
"force": force,
|
| 455 |
+
"skip_vectors": skip_vectors,
|
| 456 |
+
"fetch_hub_prior_ir": True,
|
| 457 |
+
"device": device,
|
| 458 |
+
}
|
| 459 |
+
n_workers = max(1, int(workers or 1))
|
| 460 |
+
_log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
|
| 461 |
+
import multiprocessing as mp
|
| 462 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 463 |
+
|
| 464 |
+
try:
|
| 465 |
+
mp.set_start_method("spawn", force=False)
|
| 466 |
+
except RuntimeError:
|
| 467 |
+
pass
|
| 468 |
+
|
| 469 |
+
results = [None] * len(slugs)
|
| 470 |
+
with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool:
|
| 471 |
+
futs = {
|
| 472 |
+
pool.submit(_reindex_one_country, (slug, kwargs)): i
|
| 473 |
+
for i, slug in enumerate(slugs)
|
| 474 |
+
}
|
| 475 |
+
for fut in as_completed(futs):
|
| 476 |
+
idx = futs[fut]
|
| 477 |
+
slug = slugs[idx]
|
| 478 |
+
try:
|
| 479 |
+
results[idx] = fut.result()
|
| 480 |
+
except Exception as exc:
|
| 481 |
+
_log(f"FAILED {slug}: {exc}")
|
| 482 |
+
results[idx] = {"country": slug, "skipped": False, "error": str(exc)}
|
| 483 |
+
return [r for r in results if r is not None]
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]:
|
| 487 |
+
slug, kwargs = item
|
| 488 |
+
_log(f"reindex start {slug}")
|
| 489 |
+
try:
|
| 490 |
+
return build_country(slug, **kwargs)
|
| 491 |
+
except Exception as exc:
|
| 492 |
+
_log(f"FAILED {slug}: {exc}")
|
| 493 |
+
record_progress(
|
| 494 |
+
{
|
| 495 |
+
"event": "failed",
|
| 496 |
+
"country": slug,
|
| 497 |
+
"error": str(exc),
|
| 498 |
+
"traceback": traceback.format_exc(),
|
| 499 |
+
}
|
| 500 |
)
|
| 501 |
+
return {"country": slug, "skipped": False, "error": str(exc)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
country_laws_ir/__main__.py
CHANGED
|
@@ -16,7 +16,11 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 16 |
p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
|
| 17 |
help="Hub dataset id (endomorphosis/ipfs_<slug>_laws), country slug, or local pack dir")
|
| 18 |
p_build.add_argument("--out", default=None)
|
| 19 |
-
p_build.add_argument(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
p_build.add_argument("--neighbor-k", type=int, default=8)
|
| 21 |
p_build.add_argument("--skip-vectors", action="store_true")
|
| 22 |
p_build.add_argument("--upload", action="store_true",
|
|
@@ -62,8 +66,22 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 62 |
p_re.add_argument("--max-corpus-rows", type=int, default=20000,
|
| 63 |
help="Skip IR larger than this many rows (0 = no cap)")
|
| 64 |
p_re.add_argument("--skip-vectors", action="store_true")
|
| 65 |
-
p_re.add_argument("--workers", type=int, default=
|
|
|
|
|
|
|
| 66 |
p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
p_raw = sub.add_parser("package-raw")
|
| 69 |
p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
|
|
@@ -145,7 +163,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 145 |
if args.cmd == "reindex":
|
| 146 |
from .build import reindex_from_gaps
|
| 147 |
|
| 148 |
-
cap = None if int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
|
| 149 |
results = reindex_from_gaps(
|
| 150 |
upload=args.upload,
|
| 151 |
slugs=args.slugs or None,
|
|
@@ -154,6 +172,9 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 154 |
skip_vectors=args.skip_vectors,
|
| 155 |
workers=args.workers,
|
| 156 |
mode=args.mode,
|
|
|
|
|
|
|
|
|
|
| 157 |
)
|
| 158 |
print(json.dumps(
|
| 159 |
[
|
|
@@ -173,6 +194,65 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 173 |
default=str,
|
| 174 |
))
|
| 175 |
return 1 if any(r.get("error") for r in results) else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
if args.cmd == "package-raw":
|
| 177 |
from .build import RELEASES
|
| 178 |
from .raw_package import default_instruments_dir, package_instruments
|
|
|
|
| 16 |
p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
|
| 17 |
help="Hub dataset id (endomorphosis/ipfs_<slug>_laws), country slug, or local pack dir")
|
| 18 |
p_build.add_argument("--out", default=None)
|
| 19 |
+
p_build.add_argument(
|
| 20 |
+
"--device",
|
| 21 |
+
default="cuda",
|
| 22 |
+
help="Embedding device (cuda by default, like US Code / Open US Law; falls back to cpu)",
|
| 23 |
+
)
|
| 24 |
p_build.add_argument("--neighbor-k", type=int, default=8)
|
| 25 |
p_build.add_argument("--skip-vectors", action="store_true")
|
| 26 |
p_build.add_argument("--upload", action="store_true",
|
|
|
|
| 66 |
p_re.add_argument("--max-corpus-rows", type=int, default=20000,
|
| 67 |
help="Skip IR larger than this many rows (0 = no cap)")
|
| 68 |
p_re.add_argument("--skip-vectors", action="store_true")
|
| 69 |
+
p_re.add_argument("--workers", type=int, default=2,
|
| 70 |
+
help="Parallel country workers (default 2 to stay under MemAbort; CUDA encodes are file-locked)")
|
| 71 |
+
p_re.add_argument("--device", default="cuda")
|
| 72 |
p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
|
| 73 |
+
p_re.add_argument("--all", action="store_true",
|
| 74 |
+
help="Process every indexable catalog country (not only Hub gaps)")
|
| 75 |
+
p_re.add_argument("--force", action="store_true",
|
| 76 |
+
help="Rebuild even when the source SHA matches (rerun normalize/verifiers)")
|
| 77 |
+
|
| 78 |
+
p_ver = sub.add_parser(
|
| 79 |
+
"verify",
|
| 80 |
+
help="Normalize a country pack and run admission verifiers (no GraphRAG)",
|
| 81 |
+
)
|
| 82 |
+
p_ver.add_argument("--source-repo", "--source", dest="source", default=None)
|
| 83 |
+
p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country")
|
| 84 |
+
p_ver.add_argument("--limit", type=int, default=None)
|
| 85 |
|
| 86 |
p_raw = sub.add_parser("package-raw")
|
| 87 |
p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
|
|
|
|
| 163 |
if args.cmd == "reindex":
|
| 164 |
from .build import reindex_from_gaps
|
| 165 |
|
| 166 |
+
cap = None if args.all or int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
|
| 167 |
results = reindex_from_gaps(
|
| 168 |
upload=args.upload,
|
| 169 |
slugs=args.slugs or None,
|
|
|
|
| 172 |
skip_vectors=args.skip_vectors,
|
| 173 |
workers=args.workers,
|
| 174 |
mode=args.mode,
|
| 175 |
+
force=args.force,
|
| 176 |
+
all_indexable=args.all,
|
| 177 |
+
device=args.device,
|
| 178 |
)
|
| 179 |
print(json.dumps(
|
| 180 |
[
|
|
|
|
| 194 |
default=str,
|
| 195 |
))
|
| 196 |
return 1 if any(r.get("error") for r in results) else 0
|
| 197 |
+
if args.cmd == "verify":
|
| 198 |
+
from .catalog import indexable_countries
|
| 199 |
+
from .verify import verify_source
|
| 200 |
+
|
| 201 |
+
slugs = []
|
| 202 |
+
if args.all:
|
| 203 |
+
slugs = [c["slug"] for c in indexable_countries()]
|
| 204 |
+
if args.limit:
|
| 205 |
+
slugs = slugs[: int(args.limit)]
|
| 206 |
+
elif args.source:
|
| 207 |
+
slugs = [args.source]
|
| 208 |
+
else:
|
| 209 |
+
print(json.dumps({"error": "pass --source or --all"}, indent=2))
|
| 210 |
+
return 2
|
| 211 |
+
rows = []
|
| 212 |
+
failed = 0
|
| 213 |
+
for slug in slugs:
|
| 214 |
+
try:
|
| 215 |
+
row = verify_source(slug)
|
| 216 |
+
except Exception as exc:
|
| 217 |
+
row = {"slug": slug, "error": str(exc), "verification": {"admitted": False}}
|
| 218 |
+
rows.append(row)
|
| 219 |
+
if not (row.get("verification") or {}).get("admitted", False):
|
| 220 |
+
failed += 1
|
| 221 |
+
from collections import Counter
|
| 222 |
+
|
| 223 |
+
units = Counter(str(r.get("unit") or "") for r in rows)
|
| 224 |
+
mismatch = []
|
| 225 |
+
latin_blocked = []
|
| 226 |
+
for r in rows:
|
| 227 |
+
for chk in (r.get("verification") or {}).get("checks") or []:
|
| 228 |
+
if chk.get("id") != "heading_language":
|
| 229 |
+
continue
|
| 230 |
+
ev = chk.get("evidence") or {}
|
| 231 |
+
if chk.get("severity") == "fail" and not chk.get("passed"):
|
| 232 |
+
latin_blocked.append(r.get("slug"))
|
| 233 |
+
if "review samples" in str(chk.get("message") or ""):
|
| 234 |
+
mismatch.append(
|
| 235 |
+
{
|
| 236 |
+
"slug": r.get("slug"),
|
| 237 |
+
"document_language": ev.get("document_language"),
|
| 238 |
+
"heading_language": ev.get("heading_language"),
|
| 239 |
+
}
|
| 240 |
+
)
|
| 241 |
+
print(
|
| 242 |
+
json.dumps(
|
| 243 |
+
{
|
| 244 |
+
"n": len(rows),
|
| 245 |
+
"n_failed": failed,
|
| 246 |
+
"by_unit": dict(units),
|
| 247 |
+
"heading_mismatch": mismatch,
|
| 248 |
+
"latin_split_blocked": latin_blocked,
|
| 249 |
+
"countries": rows,
|
| 250 |
+
},
|
| 251 |
+
indent=2,
|
| 252 |
+
default=str,
|
| 253 |
+
)
|
| 254 |
+
)
|
| 255 |
+
return 1 if failed else 0
|
| 256 |
if args.cmd == "package-raw":
|
| 257 |
from .build import RELEASES
|
| 258 |
from .raw_package import default_instruments_dir, package_instruments
|
country_laws_ir/build.py
CHANGED
|
@@ -18,20 +18,12 @@ from datetime import datetime, timezone
|
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import Any
|
| 20 |
|
| 21 |
-
from .
|
| 22 |
from .mem import MemAbort, checkpoint, log_mem
|
| 23 |
-
from .spill import
|
| 24 |
-
SQLITE_THRESHOLD,
|
| 25 |
-
build_bm25_tf_spill,
|
| 26 |
-
build_graph_from_neighbor_shards,
|
| 27 |
-
neighbors_via_sqlite,
|
| 28 |
-
should_use_sqlite,
|
| 29 |
-
spill_dir_for,
|
| 30 |
-
spill_pickle,
|
| 31 |
-
)
|
| 32 |
from .package import package_from_spill, package_release
|
| 33 |
from .catalog import get_country, indexable_countries, target_repo
|
| 34 |
-
|
| 35 |
from .incremental import (
|
| 36 |
fetch_hub_prior,
|
| 37 |
load_embedding_cache,
|
|
@@ -47,10 +39,10 @@ from .vectors import (
|
|
| 47 |
DIMENSION,
|
| 48 |
MODEL_NAME,
|
| 49 |
assemble_embeddings,
|
| 50 |
-
embeddings_available,
|
| 51 |
embeddings_by_cid,
|
| 52 |
layout_stub_vectors,
|
| 53 |
layout_vectors,
|
|
|
|
| 54 |
)
|
| 55 |
|
| 56 |
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
|
|
@@ -68,8 +60,17 @@ def _log(msg: str) -> None:
|
|
| 68 |
def record_progress(event: dict[str, Any]) -> None:
|
| 69 |
event = dict(event)
|
| 70 |
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
def _prior_dir_for(
|
|
@@ -121,11 +122,14 @@ def _encode_vectors(
|
|
| 121 |
_log(f"embedding cache reused_cids={len(prior_by_cid)}")
|
| 122 |
try:
|
| 123 |
positional = CACHE / "embeddings" / f"{country_slug}.npy"
|
|
|
|
|
|
|
|
|
|
| 124 |
embeddings, vector_report = assemble_embeddings(
|
| 125 |
corpus,
|
| 126 |
prior_by_cid,
|
| 127 |
-
encode_missing=
|
| 128 |
-
device=
|
| 129 |
checkpoint_path=str(positional),
|
| 130 |
)
|
| 131 |
if (
|
|
@@ -165,7 +169,7 @@ def build_country(
|
|
| 165 |
source: str,
|
| 166 |
out: Path | None = None,
|
| 167 |
upload: bool = False,
|
| 168 |
-
device: str = "
|
| 169 |
neighbor_k: int = 8,
|
| 170 |
skip_vectors: bool = False,
|
| 171 |
mode: str = "auto",
|
|
@@ -207,7 +211,11 @@ def build_country(
|
|
| 207 |
)
|
| 208 |
)
|
| 209 |
plan = plan_rebuild(
|
| 210 |
-
mode=mode,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
)
|
| 212 |
if plan.skip_build:
|
| 213 |
_log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
|
|
@@ -239,6 +247,13 @@ def build_country(
|
|
| 239 |
)
|
| 240 |
if corpus.empty:
|
| 241 |
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
import gc
|
| 244 |
|
|
@@ -248,6 +263,7 @@ def build_country(
|
|
| 248 |
prior=prior,
|
| 249 |
current_corpus=corpus,
|
| 250 |
force=force,
|
|
|
|
| 251 |
)
|
| 252 |
_log(
|
| 253 |
f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
|
|
@@ -276,50 +292,49 @@ def build_country(
|
|
| 276 |
checkpoint("vectors_spilled", log=_log)
|
| 277 |
extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
|
| 278 |
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
gc.collect()
|
| 323 |
_log(f"packaged {out}")
|
| 324 |
result = {
|
| 325 |
"country": country["slug"],
|
|
@@ -400,17 +415,29 @@ def reindex_from_gaps(
|
|
| 400 |
skip_vectors: bool = False,
|
| 401 |
workers: int = 4,
|
| 402 |
mode: str = "auto",
|
|
|
|
|
|
|
|
|
|
| 403 |
) -> list[dict[str, Any]]:
|
| 404 |
-
"""
|
| 405 |
|
| 406 |
Default cap skips huge corpora (Finland, Dominican Republic). Pass
|
| 407 |
``max_corpus_rows=None`` to include them.
|
| 408 |
"""
|
|
|
|
| 409 |
from .coverage import gap_report
|
| 410 |
|
| 411 |
if slugs is None:
|
| 412 |
-
|
| 413 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
|
| 415 |
if max_corpus_rows is not None:
|
| 416 |
rows = [
|
|
@@ -421,33 +448,54 @@ def reindex_from_gaps(
|
|
| 421 |
if limit is not None:
|
| 422 |
rows = rows[: int(limit)]
|
| 423 |
slugs = [str(r["slug"]) for r in rows]
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
)
|
| 428 |
-
|
| 429 |
-
for slug in slugs:
|
| 430 |
-
_log(f"reindex start {slug}")
|
| 431 |
-
try:
|
| 432 |
-
results.append(
|
| 433 |
-
build_country(
|
| 434 |
-
slug,
|
| 435 |
-
upload=upload,
|
| 436 |
-
mode=mode,
|
| 437 |
-
skip_vectors=skip_vectors,
|
| 438 |
-
fetch_hub_prior_ir=True,
|
| 439 |
-
)
|
| 440 |
-
)
|
| 441 |
-
except Exception as exc:
|
| 442 |
-
_log(f"FAILED {slug}: {exc}")
|
| 443 |
-
record_progress(
|
| 444 |
-
{
|
| 445 |
-
"event": "failed",
|
| 446 |
-
"country": slug,
|
| 447 |
-
"error": str(exc),
|
| 448 |
-
"traceback": traceback.format_exc(),
|
| 449 |
-
}
|
| 450 |
-
)
|
| 451 |
-
results.append({"country": slug, "skipped": False, "error": str(exc)})
|
| 452 |
-
continue
|
| 453 |
-
return results
|
|
|
|
| 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,
|
|
|
|
| 39 |
DIMENSION,
|
| 40 |
MODEL_NAME,
|
| 41 |
assemble_embeddings,
|
|
|
|
| 42 |
embeddings_by_cid,
|
| 43 |
layout_stub_vectors,
|
| 44 |
layout_vectors,
|
| 45 |
+
select_device,
|
| 46 |
)
|
| 47 |
|
| 48 |
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
|
|
|
|
| 60 |
def record_progress(event: dict[str, Any]) -> None:
|
| 61 |
event = dict(event)
|
| 62 |
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 63 |
+
PROGRESS.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
lock_path = PROGRESS.with_suffix(".lock")
|
| 65 |
+
with lock_path.open("a", encoding="utf-8") as lock_fh:
|
| 66 |
+
try:
|
| 67 |
+
import fcntl
|
| 68 |
+
|
| 69 |
+
fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
|
| 70 |
+
except Exception:
|
| 71 |
+
pass
|
| 72 |
+
with PROGRESS.open("a", encoding="utf-8") as f:
|
| 73 |
+
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 74 |
|
| 75 |
|
| 76 |
def _prior_dir_for(
|
|
|
|
| 122 |
_log(f"embedding cache reused_cids={len(prior_by_cid)}")
|
| 123 |
try:
|
| 124 |
positional = CACHE / "embeddings" / f"{country_slug}.npy"
|
| 125 |
+
resolved, fallback = select_device(device)
|
| 126 |
+
if fallback:
|
| 127 |
+
_log(f"embedding device fallback requested={device} using={resolved}")
|
| 128 |
embeddings, vector_report = assemble_embeddings(
|
| 129 |
corpus,
|
| 130 |
prior_by_cid,
|
| 131 |
+
encode_missing=True,
|
| 132 |
+
device=resolved,
|
| 133 |
checkpoint_path=str(positional),
|
| 134 |
)
|
| 135 |
if (
|
|
|
|
| 169 |
source: str,
|
| 170 |
out: Path | None = None,
|
| 171 |
upload: bool = False,
|
| 172 |
+
device: str = "cuda",
|
| 173 |
neighbor_k: int = 8,
|
| 174 |
skip_vectors: bool = False,
|
| 175 |
mode: str = "auto",
|
|
|
|
| 211 |
)
|
| 212 |
)
|
| 213 |
plan = plan_rebuild(
|
| 214 |
+
mode=mode,
|
| 215 |
+
source_meta=source_meta,
|
| 216 |
+
prior=prior,
|
| 217 |
+
force=force,
|
| 218 |
+
rebuild_stub_vectors=not skip_vectors,
|
| 219 |
)
|
| 220 |
if plan.skip_build:
|
| 221 |
_log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
|
|
|
|
| 247 |
)
|
| 248 |
if corpus.empty:
|
| 249 |
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
| 250 |
+
verdict = (norm_report or {}).get("verification") or {}
|
| 251 |
+
if verdict.get("blocks_graphrag") and not force:
|
| 252 |
+
from .verify import NormalizationAdmissionError
|
| 253 |
+
|
| 254 |
+
raise NormalizationAdmissionError(
|
| 255 |
+
f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}"
|
| 256 |
+
)
|
| 257 |
|
| 258 |
import gc
|
| 259 |
|
|
|
|
| 263 |
prior=prior,
|
| 264 |
current_corpus=corpus,
|
| 265 |
force=force,
|
| 266 |
+
rebuild_stub_vectors=not skip_vectors,
|
| 267 |
)
|
| 268 |
_log(
|
| 269 |
f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
|
|
|
|
| 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"],
|
|
|
|
| 415 |
skip_vectors: bool = False,
|
| 416 |
workers: int = 4,
|
| 417 |
mode: str = "auto",
|
| 418 |
+
force: bool = False,
|
| 419 |
+
all_indexable: bool = False,
|
| 420 |
+
device: str = "cuda",
|
| 421 |
) -> list[dict[str, Any]]:
|
| 422 |
+
"""Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
|
| 423 |
|
| 424 |
Default cap skips huge corpora (Finland, Dominican Republic). Pass
|
| 425 |
``max_corpus_rows=None`` to include them.
|
| 426 |
"""
|
| 427 |
+
from .catalog import indexable_countries
|
| 428 |
from .coverage import gap_report
|
| 429 |
|
| 430 |
if slugs is None:
|
| 431 |
+
if all_indexable:
|
| 432 |
+
rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()]
|
| 433 |
+
_log(f"reindex all indexable n={len(rows)}")
|
| 434 |
+
else:
|
| 435 |
+
report = gap_report(workers=workers)
|
| 436 |
+
rows = [c for c in report["countries"] if c.get("rebuild")]
|
| 437 |
+
_log(
|
| 438 |
+
f"reindex targets n={len(rows)} "
|
| 439 |
+
f"(from scan rebuild={len(report.get('rebuild') or [])})"
|
| 440 |
+
)
|
| 441 |
rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
|
| 442 |
if max_corpus_rows is not None:
|
| 443 |
rows = [
|
|
|
|
| 448 |
if limit is not None:
|
| 449 |
rows = rows[: int(limit)]
|
| 450 |
slugs = [str(r["slug"]) for r in rows]
|
| 451 |
+
kwargs = {
|
| 452 |
+
"upload": upload,
|
| 453 |
+
"mode": mode,
|
| 454 |
+
"force": force,
|
| 455 |
+
"skip_vectors": skip_vectors,
|
| 456 |
+
"fetch_hub_prior_ir": True,
|
| 457 |
+
"device": device,
|
| 458 |
+
}
|
| 459 |
+
n_workers = max(1, int(workers or 1))
|
| 460 |
+
_log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda")
|
| 461 |
+
import multiprocessing as mp
|
| 462 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 463 |
+
|
| 464 |
+
try:
|
| 465 |
+
mp.set_start_method("spawn", force=False)
|
| 466 |
+
except RuntimeError:
|
| 467 |
+
pass
|
| 468 |
+
|
| 469 |
+
results = [None] * len(slugs)
|
| 470 |
+
with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool:
|
| 471 |
+
futs = {
|
| 472 |
+
pool.submit(_reindex_one_country, (slug, kwargs)): i
|
| 473 |
+
for i, slug in enumerate(slugs)
|
| 474 |
+
}
|
| 475 |
+
for fut in as_completed(futs):
|
| 476 |
+
idx = futs[fut]
|
| 477 |
+
slug = slugs[idx]
|
| 478 |
+
try:
|
| 479 |
+
results[idx] = fut.result()
|
| 480 |
+
except Exception as exc:
|
| 481 |
+
_log(f"FAILED {slug}: {exc}")
|
| 482 |
+
results[idx] = {"country": slug, "skipped": False, "error": str(exc)}
|
| 483 |
+
return [r for r in results if r is not None]
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]:
|
| 487 |
+
slug, kwargs = item
|
| 488 |
+
_log(f"reindex start {slug}")
|
| 489 |
+
try:
|
| 490 |
+
return build_country(slug, **kwargs)
|
| 491 |
+
except Exception as exc:
|
| 492 |
+
_log(f"FAILED {slug}: {exc}")
|
| 493 |
+
record_progress(
|
| 494 |
+
{
|
| 495 |
+
"event": "failed",
|
| 496 |
+
"country": slug,
|
| 497 |
+
"error": str(exc),
|
| 498 |
+
"traceback": traceback.format_exc(),
|
| 499 |
+
}
|
| 500 |
)
|
| 501 |
+
return {"country": slug, "skipped": False, "error": str(exc)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
country_laws_ir/citations.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official and Bluebook citations for country-law corpus rows.
|
| 2 |
+
|
| 3 |
+
Bluebook T2/T10 abbreviations are used only when this table has a row.
|
| 4 |
+
Unknown jurisdictions get ``official_citation`` only — never a invented
|
| 5 |
+
Bluebook form. Query keys are normalized so ``ORS 1.010`` and
|
| 6 |
+
``Or. Rev. Stat. § 1.010`` can hit the same row later.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
import re
|
| 13 |
+
import unicodedata
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
# slug or country name (lower) -> Bluebook T2/T10 statute abbreviation.
|
| 17 |
+
# Empty pinpoint templates are filled with article/section when present.
|
| 18 |
+
_BLUEBOOK_STATUTE: dict[str, str] = {
|
| 19 |
+
"australia": "Cth",
|
| 20 |
+
"canada": "S.C.",
|
| 21 |
+
"united kingdom": "U.K.",
|
| 22 |
+
"uk": "U.K.",
|
| 23 |
+
"united states": "U.S.C.",
|
| 24 |
+
"usa": "U.S.C.",
|
| 25 |
+
"germany": "BGBl.",
|
| 26 |
+
"france": "J.O.",
|
| 27 |
+
"malta": "Laws of Malta",
|
| 28 |
+
"ireland": "Ir.",
|
| 29 |
+
"newzealand": "N.Z.",
|
| 30 |
+
"new zealand": "N.Z.",
|
| 31 |
+
"southafrica": "S. Afr.",
|
| 32 |
+
"south africa": "S. Afr.",
|
| 33 |
+
"india": "India",
|
| 34 |
+
"japan": "Japan",
|
| 35 |
+
"china": "P.R.C.",
|
| 36 |
+
"netherlands": "Stb.",
|
| 37 |
+
"austria": "BGBl.",
|
| 38 |
+
"switzerland": "AS",
|
| 39 |
+
"sweden": "SFS",
|
| 40 |
+
"norway": "Norsk Lovtidend",
|
| 41 |
+
"denmark": "Lovtidende",
|
| 42 |
+
"finland": "Finlex",
|
| 43 |
+
"eu": "O.J.",
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass(frozen=True)
|
| 48 |
+
class Citation:
|
| 49 |
+
official_citation: str
|
| 50 |
+
bluebook_citation: str
|
| 51 |
+
cite_key: str
|
| 52 |
+
citation_status: str # bluebook | official_only | unknown
|
| 53 |
+
pinpoint: str
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def normalize_cite_key(value: str) -> str:
|
| 57 |
+
if not value:
|
| 58 |
+
return ""
|
| 59 |
+
text = unicodedata.normalize("NFKC", value).lower()
|
| 60 |
+
text = text.replace("§", " s ")
|
| 61 |
+
text = text.replace("¶", " ")
|
| 62 |
+
text = re.sub(r"\bart(?:icle|\.)?\b", "art", text)
|
| 63 |
+
text = re.sub(r"\bsec(?:tion|\.)?\b", "s", text)
|
| 64 |
+
text = re.sub(r"[^a-z0-9]+", " ", text)
|
| 65 |
+
return re.sub(r"\s+", " ", text).strip()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _pinpoint(article_number: str, section_number: str, record_type: str) -> str:
|
| 69 |
+
if record_type == "section" and section_number:
|
| 70 |
+
return f"§ {section_number}"
|
| 71 |
+
if article_number:
|
| 72 |
+
return f"art. {article_number}"
|
| 73 |
+
if section_number:
|
| 74 |
+
return f"§ {section_number}"
|
| 75 |
+
return ""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _bluebook_abbrev(jurisdiction: str, country: str, slug: str = "") -> str:
|
| 79 |
+
for key in (slug, country, jurisdiction):
|
| 80 |
+
hit = _BLUEBOOK_STATUTE.get(str(key or "").strip().lower().replace("_", " "))
|
| 81 |
+
if hit:
|
| 82 |
+
return hit
|
| 83 |
+
return ""
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def assign_citation(
|
| 87 |
+
*,
|
| 88 |
+
eli: str = "",
|
| 89 |
+
official_identifier: str = "",
|
| 90 |
+
identifier: str = "",
|
| 91 |
+
instrument_title: str = "",
|
| 92 |
+
article_number: str = "",
|
| 93 |
+
section_number: str = "",
|
| 94 |
+
record_type: str = "law",
|
| 95 |
+
jurisdiction: str = "",
|
| 96 |
+
country: str = "",
|
| 97 |
+
slug: str = "",
|
| 98 |
+
year: str = "",
|
| 99 |
+
) -> Citation:
|
| 100 |
+
pinpoint = _pinpoint(article_number, section_number, record_type)
|
| 101 |
+
official = (
|
| 102 |
+
(eli or "").strip()
|
| 103 |
+
or (official_identifier or "").strip()
|
| 104 |
+
or (identifier or "").strip()
|
| 105 |
+
or (instrument_title or "").strip()
|
| 106 |
+
)
|
| 107 |
+
if official and pinpoint and pinpoint.lower() not in official.lower():
|
| 108 |
+
official_cite = f"{official}, {pinpoint}"
|
| 109 |
+
else:
|
| 110 |
+
official_cite = official
|
| 111 |
+
|
| 112 |
+
abbrev = _bluebook_abbrev(jurisdiction, country, slug)
|
| 113 |
+
bluebook = ""
|
| 114 |
+
if abbrev and official:
|
| 115 |
+
if pinpoint:
|
| 116 |
+
if year:
|
| 117 |
+
bluebook = f"{abbrev} {pinpoint} ({year})"
|
| 118 |
+
else:
|
| 119 |
+
bluebook = f"{abbrev} {pinpoint}"
|
| 120 |
+
else:
|
| 121 |
+
bluebook = f"{abbrev} {official}" if official != abbrev else abbrev
|
| 122 |
+
|
| 123 |
+
if bluebook:
|
| 124 |
+
status = "bluebook"
|
| 125 |
+
elif official_cite:
|
| 126 |
+
status = "official_only"
|
| 127 |
+
else:
|
| 128 |
+
status = "unknown"
|
| 129 |
+
|
| 130 |
+
key_src = bluebook or official_cite
|
| 131 |
+
return Citation(
|
| 132 |
+
official_citation=official_cite,
|
| 133 |
+
bluebook_citation=bluebook,
|
| 134 |
+
cite_key=normalize_cite_key(key_src),
|
| 135 |
+
citation_status=status,
|
| 136 |
+
pinpoint=pinpoint,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def citation_fields(cite: Citation) -> dict[str, Any]:
|
| 141 |
+
return {
|
| 142 |
+
"official_citation": cite.official_citation,
|
| 143 |
+
"bluebook_citation": cite.bluebook_citation,
|
| 144 |
+
"cite_key": cite.cite_key,
|
| 145 |
+
"citation_status": cite.citation_status,
|
| 146 |
+
"pinpoint": cite.pinpoint,
|
| 147 |
+
}
|
country_laws_ir/coverage.py
CHANGED
|
@@ -159,7 +159,10 @@ def classify_gap(
|
|
| 159 |
and local_source_revision
|
| 160 |
and str(source_revision) == str(local_source_revision)
|
| 161 |
)
|
| 162 |
-
rebuild =
|
|
|
|
|
|
|
|
|
|
| 163 |
publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (
|
| 164 |
"source_missing_laws" not in issues
|
| 165 |
)
|
|
|
|
| 159 |
and local_source_revision
|
| 160 |
and str(source_revision) == str(local_source_revision)
|
| 161 |
)
|
| 162 |
+
rebuild = (
|
| 163 |
+
status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"}
|
| 164 |
+
and (not local_current or status == "stub_vectors")
|
| 165 |
+
)
|
| 166 |
publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (
|
| 167 |
"source_missing_laws" not in issues
|
| 168 |
)
|
country_laws_ir/duckdb_store.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 cite_search(
|
| 155 |
+
root: Path,
|
| 156 |
+
citation: str,
|
| 157 |
+
*,
|
| 158 |
+
cite_format: str = "any",
|
| 159 |
+
limit: int = 25,
|
| 160 |
+
) -> list[dict[str, Any]]:
|
| 161 |
+
"""Look up corpus rows by Bluebook, official cite, or normalized cite_key."""
|
| 162 |
+
from .citations import normalize_cite_key
|
| 163 |
+
|
| 164 |
+
needle = (citation or "").strip()
|
| 165 |
+
if not needle:
|
| 166 |
+
return []
|
| 167 |
+
key = normalize_cite_key(needle)
|
| 168 |
+
con = connect_release(root)
|
| 169 |
+
try:
|
| 170 |
+
tables = {
|
| 171 |
+
r[0]
|
| 172 |
+
for r in con.execute(
|
| 173 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
|
| 174 |
+
).fetchall()
|
| 175 |
+
}
|
| 176 |
+
if "corpus" not in tables:
|
| 177 |
+
raise DuckDBStoreError("release is missing corpus parquet shards")
|
| 178 |
+
cols = [
|
| 179 |
+
r[1]
|
| 180 |
+
for r in con.execute(
|
| 181 |
+
"SELECT table_schema, column_name FROM information_schema.columns "
|
| 182 |
+
"WHERE table_schema = 'main' AND table_name = 'corpus'"
|
| 183 |
+
).fetchall()
|
| 184 |
+
]
|
| 185 |
+
wanted = [
|
| 186 |
+
"entry_cid",
|
| 187 |
+
"record_type",
|
| 188 |
+
"title",
|
| 189 |
+
"instrument_title",
|
| 190 |
+
"article_number",
|
| 191 |
+
"official_citation",
|
| 192 |
+
"bluebook_citation",
|
| 193 |
+
"cite_key",
|
| 194 |
+
"citation_status",
|
| 195 |
+
"source_url",
|
| 196 |
+
]
|
| 197 |
+
select = ", ".join(c for c in wanted if c in cols) or "*"
|
| 198 |
+
clauses = []
|
| 199 |
+
params: list[Any] = []
|
| 200 |
+
fmt = (cite_format or "any").strip().lower()
|
| 201 |
+
if fmt in {"any", "bluebook"} and "bluebook_citation" in cols:
|
| 202 |
+
clauses.append("lower(coalesce(bluebook_citation, '')) = lower(?)")
|
| 203 |
+
params.append(needle)
|
| 204 |
+
if fmt in {"any", "official"} and "official_citation" in cols:
|
| 205 |
+
clauses.append("lower(coalesce(official_citation, '')) = lower(?)")
|
| 206 |
+
params.append(needle)
|
| 207 |
+
if "cite_key" in cols and key:
|
| 208 |
+
clauses.append("cite_key = ?")
|
| 209 |
+
params.append(key)
|
| 210 |
+
if not clauses:
|
| 211 |
+
return []
|
| 212 |
+
sql = f"SELECT {select} FROM corpus WHERE {' OR '.join(clauses)} LIMIT ?"
|
| 213 |
+
params.append(int(limit))
|
| 214 |
+
rows = con.execute(sql, params).fetchall()
|
| 215 |
+
names = [c for c in wanted if c in cols] if select != "*" else list(cols)
|
| 216 |
+
return [dict(zip(names, row)) for row in rows]
|
| 217 |
+
finally:
|
| 218 |
+
con.close()
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def graph_neighbors(
|
| 222 |
+
root: Path,
|
| 223 |
+
node_cid: str,
|
| 224 |
+
*,
|
| 225 |
+
direction: str = "both",
|
| 226 |
+
limit: int = 25,
|
| 227 |
+
) -> list[dict[str, Any]]:
|
| 228 |
+
"""Adjacency lookup over parquet shards via DuckDB."""
|
| 229 |
+
aliases = {
|
| 230 |
+
"both": ("in", "out", "incoming", "outgoing"),
|
| 231 |
+
"in": ("in", "incoming"),
|
| 232 |
+
"out": ("out", "outgoing"),
|
| 233 |
+
"incoming": ("in", "incoming"),
|
| 234 |
+
"outgoing": ("out", "outgoing"),
|
| 235 |
+
}
|
| 236 |
+
dirs = aliases.get(direction, (direction,))
|
| 237 |
+
con = connect_release(root)
|
| 238 |
+
try:
|
| 239 |
+
tables = {
|
| 240 |
+
r[0]
|
| 241 |
+
for r in con.execute(
|
| 242 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
|
| 243 |
+
).fetchall()
|
| 244 |
+
}
|
| 245 |
+
hits: list[dict[str, Any]] = []
|
| 246 |
+
for d in dirs:
|
| 247 |
+
view = {
|
| 248 |
+
"in": "graph_in",
|
| 249 |
+
"out": "graph_out",
|
| 250 |
+
"incoming": "graph_incoming",
|
| 251 |
+
"outgoing": "graph_outgoing",
|
| 252 |
+
}.get(d, d)
|
| 253 |
+
if view not in tables:
|
| 254 |
+
continue
|
| 255 |
+
rows = con.execute(
|
| 256 |
+
f"""
|
| 257 |
+
SELECT node_cid, neighbor_cids, edge_types, scores
|
| 258 |
+
FROM {view}
|
| 259 |
+
WHERE node_cid = ?
|
| 260 |
+
""",
|
| 261 |
+
[node_cid],
|
| 262 |
+
).fetchall()
|
| 263 |
+
for node, neighs, types, scores in rows:
|
| 264 |
+
neighs = list(neighs or [])
|
| 265 |
+
types = list(types or [])
|
| 266 |
+
scores = list(scores or [])
|
| 267 |
+
for i, neigh in enumerate(neighs):
|
| 268 |
+
hits.append(
|
| 269 |
+
{
|
| 270 |
+
"direction": d,
|
| 271 |
+
"node_cid": node,
|
| 272 |
+
"neighbor_cid": neigh,
|
| 273 |
+
"edge_type": types[i] if i < len(types) else "",
|
| 274 |
+
"score": scores[i] if i < len(scores) else None,
|
| 275 |
+
}
|
| 276 |
+
)
|
| 277 |
+
hits.sort(key=lambda r: (-(r["score"] or 0), str(r["neighbor_cid"])))
|
| 278 |
+
return hits[: int(limit)]
|
| 279 |
+
finally:
|
| 280 |
+
con.close()
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def build_fts_index(
|
| 284 |
+
corpus_parquet: Path,
|
| 285 |
+
duckdb_path: Path,
|
| 286 |
+
expected: int,
|
| 287 |
+
*,
|
| 288 |
+
log: Any | None = None,
|
| 289 |
+
) -> Path:
|
| 290 |
+
"""Load corpus parquet into DuckDB and create an FTS index (no SQLite)."""
|
| 291 |
+
duckdb = _require_duckdb()
|
| 292 |
+
duckdb_path = Path(duckdb_path)
|
| 293 |
+
duckdb_path.parent.mkdir(parents=True, exist_ok=True)
|
| 294 |
+
if duckdb_path.exists():
|
| 295 |
+
duckdb_path.unlink()
|
| 296 |
+
escaped = str(Path(corpus_parquet).resolve()).replace("'", "''")
|
| 297 |
+
con = duckdb.connect(str(duckdb_path))
|
| 298 |
+
try:
|
| 299 |
+
con.execute(
|
| 300 |
+
f"""
|
| 301 |
+
CREATE TABLE documents AS
|
| 302 |
+
SELECT
|
| 303 |
+
CAST(document_index AS INTEGER) AS document_index,
|
| 304 |
+
CAST(entry_cid AS VARCHAR) AS entry_cid,
|
| 305 |
+
CAST(COALESCE(title, '') AS VARCHAR) AS title,
|
| 306 |
+
CAST(COALESCE(body, '') AS VARCHAR) AS body
|
| 307 |
+
FROM read_parquet('{escaped}')
|
| 308 |
+
"""
|
| 309 |
+
)
|
| 310 |
+
n = int(con.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 311 |
+
if n != int(expected):
|
| 312 |
+
raise DuckDBStoreError(f"DuckDB corpus rows {n} != expected {expected}")
|
| 313 |
+
con.execute("INSTALL fts")
|
| 314 |
+
con.execute("LOAD fts")
|
| 315 |
+
con.execute(
|
| 316 |
+
"PRAGMA create_fts_index('documents', 'document_index', 'title', 'body', "
|
| 317 |
+
"stemmer='porter', stopwords='english', ignore='(\\.+)', strip_accents=1, lower=1)"
|
| 318 |
+
)
|
| 319 |
+
if log:
|
| 320 |
+
log(f"duckdb fts ready n={n} path={duckdb_path}")
|
| 321 |
+
finally:
|
| 322 |
+
con.close()
|
| 323 |
+
return duckdb_path
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def stream_neighbors_to_parquet(
|
| 327 |
+
duckdb_path: Path,
|
| 328 |
+
spill: Path,
|
| 329 |
+
n_docs: int,
|
| 330 |
+
*,
|
| 331 |
+
k: int = 8,
|
| 332 |
+
shard: int = 5000,
|
| 333 |
+
batch: int = 256,
|
| 334 |
+
resume: bool = True,
|
| 335 |
+
log: Any | None = None,
|
| 336 |
+
) -> list[Path]:
|
| 337 |
+
"""Stream DuckDB FTS neighbors into flattened neighbor_*.parquet shards."""
|
| 338 |
+
duckdb = _require_duckdb()
|
| 339 |
+
spill = Path(spill)
|
| 340 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 341 |
+
existing = sorted(spill.glob("neighbors_*.parquet"))
|
| 342 |
+
buf_start = 0
|
| 343 |
+
shard_paths: list[Path] = []
|
| 344 |
+
if resume and existing:
|
| 345 |
+
covered = 0
|
| 346 |
+
for path in existing:
|
| 347 |
+
parts = path.stem.split("_")
|
| 348 |
+
try:
|
| 349 |
+
start_i, end_i = int(parts[1]), int(parts[2])
|
| 350 |
+
except (IndexError, ValueError):
|
| 351 |
+
continue
|
| 352 |
+
if start_i != covered:
|
| 353 |
+
break
|
| 354 |
+
shard_paths.append(path)
|
| 355 |
+
covered = end_i
|
| 356 |
+
buf_start = covered
|
| 357 |
+
if buf_start >= n_docs:
|
| 358 |
+
if log:
|
| 359 |
+
log(f"neighbors resume complete {buf_start}/{n_docs}")
|
| 360 |
+
return shard_paths
|
| 361 |
+
for path in existing:
|
| 362 |
+
if path not in shard_paths:
|
| 363 |
+
path.unlink(missing_ok=True)
|
| 364 |
+
else:
|
| 365 |
+
for path in existing:
|
| 366 |
+
path.unlink(missing_ok=True)
|
| 367 |
+
|
| 368 |
+
con = duckdb.connect(str(duckdb_path), read_only=True)
|
| 369 |
+
con.execute("LOAD fts")
|
| 370 |
+
rows_buf: list[dict[str, Any]] = []
|
| 371 |
+
shard_start = buf_start
|
| 372 |
+
last_idx = buf_start - 1
|
| 373 |
+
done = buf_start
|
| 374 |
+
try:
|
| 375 |
+
while True:
|
| 376 |
+
batch_rows = con.execute(
|
| 377 |
+
"SELECT document_index, title, body FROM documents "
|
| 378 |
+
"WHERE document_index > ? ORDER BY document_index LIMIT ?",
|
| 379 |
+
[last_idx, batch],
|
| 380 |
+
).fetchall()
|
| 381 |
+
if not batch_rows:
|
| 382 |
+
break
|
| 383 |
+
for di, title, body in batch_rows:
|
| 384 |
+
di = int(di)
|
| 385 |
+
query = (str(title or "").strip() or str(body or "")[:800]).strip()
|
| 386 |
+
hits: list[tuple[int, float]] = []
|
| 387 |
+
if query:
|
| 388 |
+
hits = con.execute(
|
| 389 |
+
"SELECT document_index, "
|
| 390 |
+
"fts_main_documents.match_bm25(document_index, ?) AS score "
|
| 391 |
+
"FROM documents "
|
| 392 |
+
"WHERE document_index != ? AND score IS NOT NULL "
|
| 393 |
+
"ORDER BY score DESC, document_index "
|
| 394 |
+
"LIMIT ?",
|
| 395 |
+
[query, di, int(k)],
|
| 396 |
+
).fetchall()
|
| 397 |
+
for neigh_i, score in hits:
|
| 398 |
+
rows_buf.append(
|
| 399 |
+
{
|
| 400 |
+
"source_index": di,
|
| 401 |
+
"neighbor_index": int(neigh_i),
|
| 402 |
+
"score": float(score or 0.0),
|
| 403 |
+
}
|
| 404 |
+
)
|
| 405 |
+
last_idx = di
|
| 406 |
+
done += 1
|
| 407 |
+
if (di + 1 - shard_start) >= shard:
|
| 408 |
+
end = di + 1
|
| 409 |
+
path = spill / f"neighbors_{shard_start:06d}_{end:06d}.parquet"
|
| 410 |
+
pd.DataFrame(rows_buf).to_parquet(path, index=False)
|
| 411 |
+
shard_paths.append(path)
|
| 412 |
+
rows_buf = []
|
| 413 |
+
shard_start = end
|
| 414 |
+
if log:
|
| 415 |
+
log(f"neighbors parquet shard {path.name}")
|
| 416 |
+
if done % 5_000 == 0 and log:
|
| 417 |
+
log(f"duckdb neighbors {done}/{n_docs}")
|
| 418 |
+
if shard_start < n_docs:
|
| 419 |
+
path = spill / f"neighbors_{shard_start:06d}_{n_docs:06d}.parquet"
|
| 420 |
+
pd.DataFrame(rows_buf).to_parquet(path, index=False)
|
| 421 |
+
shard_paths.append(path)
|
| 422 |
+
if log:
|
| 423 |
+
log(f"duckdb neighbors done={done} shards={len(shard_paths)}")
|
| 424 |
+
return shard_paths
|
| 425 |
+
finally:
|
| 426 |
+
con.close()
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def iter_neighbor_parquet_shards(spill: Path) -> Any:
|
| 430 |
+
"""Yield (start_index, list-of-neighbor-lists) from parquet shards."""
|
| 431 |
+
import pandas as pd
|
| 432 |
+
|
| 433 |
+
paths = sorted(Path(spill).glob("neighbors_*.parquet"))
|
| 434 |
+
for path in paths:
|
| 435 |
+
parts = path.stem.split("_")
|
| 436 |
+
start_i = int(parts[1])
|
| 437 |
+
end_i = int(parts[2])
|
| 438 |
+
frame = pd.read_parquet(path)
|
| 439 |
+
part: list[list] = [[] for _ in range(max(0, end_i - start_i))]
|
| 440 |
+
if not frame.empty:
|
| 441 |
+
for rec in frame.itertuples(index=False):
|
| 442 |
+
src = int(rec.source_index)
|
| 443 |
+
offset = src - start_i
|
| 444 |
+
if 0 <= offset < len(part):
|
| 445 |
+
part[offset].append(
|
| 446 |
+
(int(rec.neighbor_index), float(rec.score), [])
|
| 447 |
+
)
|
| 448 |
+
yield start_i, part
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def materialize_corpus_duckdb(corpus_parquet: Path, duckdb_path: Path) -> Path:
|
| 452 |
+
"""Load a corpus parquet file into a persistent DuckDB database."""
|
| 453 |
+
duckdb = _require_duckdb()
|
| 454 |
+
duckdb_path = Path(duckdb_path)
|
| 455 |
+
duckdb_path.parent.mkdir(parents=True, exist_ok=True)
|
| 456 |
+
if duckdb_path.exists():
|
| 457 |
+
duckdb_path.unlink()
|
| 458 |
+
con = duckdb.connect(str(duckdb_path))
|
| 459 |
+
try:
|
| 460 |
+
con.execute(
|
| 461 |
+
"""
|
| 462 |
+
CREATE TABLE documents AS
|
| 463 |
+
SELECT
|
| 464 |
+
CAST(document_index AS INTEGER) AS document_index,
|
| 465 |
+
CAST(entry_cid AS VARCHAR) AS entry_cid,
|
| 466 |
+
CAST(title AS VARCHAR) AS title,
|
| 467 |
+
CAST(body AS VARCHAR) AS body
|
| 468 |
+
FROM read_parquet(?)
|
| 469 |
+
""",
|
| 470 |
+
[str(corpus_parquet)],
|
| 471 |
+
)
|
| 472 |
+
con.execute("CREATE INDEX documents_idx ON documents(document_index)")
|
| 473 |
+
finally:
|
| 474 |
+
con.close()
|
| 475 |
+
return duckdb_path
|
country_laws_ir/incremental.py
CHANGED
|
@@ -234,6 +234,7 @@ def plan_rebuild(
|
|
| 234 |
prior: PriorRelease | None,
|
| 235 |
current_corpus: pd.DataFrame | None = None,
|
| 236 |
force: bool = False,
|
|
|
|
| 237 |
) -> RebuildPlan:
|
| 238 |
"""Decide skip / delta / full from source fingerprints and CID overlap."""
|
| 239 |
mode = BuildMode.coerce(mode)
|
|
@@ -275,7 +276,19 @@ def plan_rebuild(
|
|
| 275 |
equivalent_to_full=True,
|
| 276 |
)
|
| 277 |
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
return RebuildPlan(
|
| 280 |
kind=RebuildKind.UNCHANGED,
|
| 281 |
mode=mode,
|
|
@@ -314,10 +327,15 @@ def plan_rebuild(
|
|
| 314 |
equivalent_to_full=True,
|
| 315 |
)
|
| 316 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
return RebuildPlan(
|
| 318 |
kind=RebuildKind.DELTA_REFRESH,
|
| 319 |
mode=mode,
|
| 320 |
-
reason=
|
| 321 |
source_revision=revision,
|
| 322 |
prior_revision=prior_revision,
|
| 323 |
source_fingerprint=fingerprint,
|
|
|
|
| 234 |
prior: PriorRelease | None,
|
| 235 |
current_corpus: pd.DataFrame | None = None,
|
| 236 |
force: bool = False,
|
| 237 |
+
rebuild_stub_vectors: bool = True,
|
| 238 |
) -> RebuildPlan:
|
| 239 |
"""Decide skip / delta / full from source fingerprints and CID overlap."""
|
| 240 |
mode = BuildMode.coerce(mode)
|
|
|
|
| 276 |
equivalent_to_full=True,
|
| 277 |
)
|
| 278 |
|
| 279 |
+
prior_vector_status = str(
|
| 280 |
+
((prior.manifest.get("vector") or {}) if prior.manifest else {}).get("status")
|
| 281 |
+
or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status")
|
| 282 |
+
or ""
|
| 283 |
+
).strip().lower()
|
| 284 |
+
stub_vectors = rebuild_stub_vectors and prior_vector_status in {
|
| 285 |
+
"stub",
|
| 286 |
+
"stub_missing_encoder",
|
| 287 |
+
"incomplete",
|
| 288 |
+
"partial",
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
if prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors:
|
| 292 |
return RebuildPlan(
|
| 293 |
kind=RebuildKind.UNCHANGED,
|
| 294 |
mode=mode,
|
|
|
|
| 327 |
equivalent_to_full=True,
|
| 328 |
)
|
| 329 |
|
| 330 |
+
reason = (
|
| 331 |
+
"source fingerprint matches but vectors are stub/incomplete; encode missing CIDs"
|
| 332 |
+
if stub_vectors and prior_fp == fingerprint
|
| 333 |
+
else "source changed; reuse embeddings for unchanged entry_cids"
|
| 334 |
+
)
|
| 335 |
return RebuildPlan(
|
| 336 |
kind=RebuildKind.DELTA_REFRESH,
|
| 337 |
mode=mode,
|
| 338 |
+
reason=reason,
|
| 339 |
source_revision=revision,
|
| 340 |
prior_revision=prior_revision,
|
| 341 |
source_fingerprint=fingerprint,
|
country_laws_ir/normalize.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
"""Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
|
| 2 |
|
| 3 |
Prefer article/section as the retrieval unit; fall back to law-level when
|
| 4 |
-
articles are missing or empty.
|
| 5 |
-
|
|
|
|
| 6 |
|
| 7 |
Public Hub reads only (token=False). No Hugging Face token is read or stored.
|
| 8 |
"""
|
|
@@ -11,8 +12,6 @@ from __future__ import annotations
|
|
| 11 |
|
| 12 |
import json
|
| 13 |
import os
|
| 14 |
-
import re
|
| 15 |
-
import unicodedata
|
| 16 |
from collections import Counter
|
| 17 |
from pathlib import Path
|
| 18 |
from typing import Any
|
|
@@ -25,8 +24,8 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
|
|
| 25 |
from .auth import configure_hf, public_token
|
| 26 |
from .cidutil import cid_of_json, sha256_file, sha256_hex
|
| 27 |
from .schema import SchemaError, validate_articles, validate_laws
|
|
|
|
| 28 |
|
| 29 |
-
_WS_RE = re.compile(r"\s+", re.UNICODE)
|
| 30 |
COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
|
| 31 |
EMPTY_ARTICLE_COLUMNS = (
|
| 32 |
"law_id",
|
|
@@ -48,9 +47,7 @@ def _empty_articles() -> pd.DataFrame:
|
|
| 48 |
def normalize_text(value: Any) -> str:
|
| 49 |
if value is None or (isinstance(value, float) and pd.isna(value)):
|
| 50 |
return ""
|
| 51 |
-
|
| 52 |
-
text = _WS_RE.sub(" ", text).strip()
|
| 53 |
-
return text
|
| 54 |
|
| 55 |
|
| 56 |
def _s(value: Any) -> str:
|
|
@@ -285,6 +282,35 @@ def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str,
|
|
| 285 |
return ""
|
| 286 |
|
| 287 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
def _collector(meta: dict[str, Any], source_dataset: str) -> str:
|
| 289 |
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 290 |
for blob in (meta, nested):
|
|
@@ -373,6 +399,34 @@ def _base_record(
|
|
| 373 |
}
|
| 374 |
if extra:
|
| 375 |
rec.update(extra)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
rec["entry_cid"] = _entry_cid(rec)
|
| 377 |
rec["title_length"] = len(title_for_bm25)
|
| 378 |
rec["body_length"] = len(body)
|
|
@@ -433,11 +487,62 @@ def build_corpus(
|
|
| 433 |
|
| 434 |
entries: list[dict[str, Any]] = []
|
| 435 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
if sparse_fallback:
|
| 437 |
report["schema_surprises"].append(
|
| 438 |
f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
|
| 439 |
)
|
| 440 |
|
|
|
|
|
|
|
|
|
|
| 441 |
if use_articles:
|
| 442 |
for _, row in articles.iterrows():
|
| 443 |
source_id = _row_get(row, "id")
|
|
@@ -489,6 +594,9 @@ def build_corpus(
|
|
| 489 |
"law_status": parent["law_status"],
|
| 490 |
"parent_law_id": instrument_id,
|
| 491 |
"article_id": source_id,
|
|
|
|
|
|
|
|
|
|
| 492 |
},
|
| 493 |
)
|
| 494 |
)
|
|
@@ -496,44 +604,50 @@ def build_corpus(
|
|
| 496 |
for instrument_id, parent in law_map.items():
|
| 497 |
body = parent["body"]
|
| 498 |
if not body:
|
| 499 |
-
report["drops"]["empty_body"] += 1
|
| 500 |
-
if len(report["drop_samples"]["empty_body"]) < 20:
|
| 501 |
-
report["drop_samples"]["empty_body"].append(instrument_id)
|
| 502 |
continue
|
| 503 |
meta = parent["metadata"]
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
|
| 538 |
entries.sort(
|
| 539 |
key=lambda r: (
|
|
@@ -564,6 +678,20 @@ def build_corpus(
|
|
| 564 |
raise SchemaError("Duplicate entry_cid remained after dedupe")
|
| 565 |
report["n_before_dedupe"] = n_before
|
| 566 |
report["n_out"] = int(len(df))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
report["n_dropped_total"] = (
|
| 568 |
report["drops"]["empty_body"]
|
| 569 |
+ report["drops"]["missing_instrument"]
|
|
@@ -607,5 +735,23 @@ def build_corpus(
|
|
| 607 |
"empty_bodies_dropped": report["drops"]["empty_body"],
|
| 608 |
"duplicate_cids_dropped": report["drops"]["duplicate_cid"],
|
| 609 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
df.attrs["normalization_report"] = report
|
| 611 |
return df, report
|
|
|
|
| 1 |
"""Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
|
| 2 |
|
| 3 |
Prefer article/section as the retrieval unit; fall back to law-level when
|
| 4 |
+
articles are missing or empty. Strip leftover HTML, then detect multilingual
|
| 5 |
+
title/chapter/article/section headings (Oregon-style) when present. Never
|
| 6 |
+
invent legal text or a hierarchy that is not in the source.
|
| 7 |
|
| 8 |
Public Hub reads only (token=False). No Hugging Face token is read or stored.
|
| 9 |
"""
|
|
|
|
| 12 |
|
| 13 |
import json
|
| 14 |
import os
|
|
|
|
|
|
|
| 15 |
from collections import Counter
|
| 16 |
from pathlib import Path
|
| 17 |
from typing import Any
|
|
|
|
| 24 |
from .auth import configure_hf, public_token
|
| 25 |
from .cidutil import cid_of_json, sha256_file, sha256_hex
|
| 26 |
from .schema import SchemaError, validate_articles, validate_laws
|
| 27 |
+
from .structure import normalize_legal_text, split_structured_units
|
| 28 |
|
|
|
|
| 29 |
COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
|
| 30 |
EMPTY_ARTICLE_COLUMNS = (
|
| 31 |
"law_id",
|
|
|
|
| 47 |
def normalize_text(value: Any) -> str:
|
| 48 |
if value is None or (isinstance(value, float) and pd.isna(value)):
|
| 49 |
return ""
|
| 50 |
+
return normalize_legal_text(value)
|
|
|
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
def _s(value: Any) -> str:
|
|
|
|
| 282 |
return ""
|
| 283 |
|
| 284 |
|
| 285 |
+
def _hierarchy_fields(
|
| 286 |
+
title: str, body: str, article_number: str, *, language: str = ""
|
| 287 |
+
) -> dict[str, Any]:
|
| 288 |
+
"""Best-effort hierarchy from a single already-split article/section body."""
|
| 289 |
+
units = split_structured_units(
|
| 290 |
+
f"{title}\n{body}" if title else body, language=language
|
| 291 |
+
)
|
| 292 |
+
if not units:
|
| 293 |
+
return {
|
| 294 |
+
"hierarchy_kind": "article" if article_number else "law",
|
| 295 |
+
"hierarchy_path": "",
|
| 296 |
+
"title_number": "",
|
| 297 |
+
"chapter_number": "",
|
| 298 |
+
"part_number": "",
|
| 299 |
+
"section_number": "",
|
| 300 |
+
"subsections": [],
|
| 301 |
+
}
|
| 302 |
+
unit = units[0]
|
| 303 |
+
return {
|
| 304 |
+
"hierarchy_kind": unit.kind,
|
| 305 |
+
"hierarchy_path": unit.hierarchy_path,
|
| 306 |
+
"title_number": unit.title_number,
|
| 307 |
+
"chapter_number": unit.chapter_number,
|
| 308 |
+
"part_number": unit.part_number,
|
| 309 |
+
"section_number": unit.section_number,
|
| 310 |
+
"subsections": list(unit.subsections),
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
|
| 314 |
def _collector(meta: dict[str, Any], source_dataset: str) -> str:
|
| 315 |
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 316 |
for blob in (meta, nested):
|
|
|
|
| 399 |
}
|
| 400 |
if extra:
|
| 401 |
rec.update(extra)
|
| 402 |
+
from .citations import assign_citation, citation_fields
|
| 403 |
+
|
| 404 |
+
slug = ""
|
| 405 |
+
if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
|
| 406 |
+
slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 407 |
+
year = ""
|
| 408 |
+
if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit():
|
| 409 |
+
year = snapshot_date[:4]
|
| 410 |
+
extra = extra or {}
|
| 411 |
+
rec.update(
|
| 412 |
+
citation_fields(
|
| 413 |
+
assign_citation(
|
| 414 |
+
eli=str(rec.get("eli") or extra.get("eli") or ""),
|
| 415 |
+
official_identifier=str(
|
| 416 |
+
rec.get("official_identifier") or extra.get("official_identifier") or ""
|
| 417 |
+
),
|
| 418 |
+
identifier=str(rec.get("identifier") or extra.get("identifier") or ""),
|
| 419 |
+
instrument_title=instrument_title,
|
| 420 |
+
article_number=article_number,
|
| 421 |
+
section_number=str(extra.get("section_number") or ""),
|
| 422 |
+
record_type=record_type,
|
| 423 |
+
jurisdiction=jurisdiction,
|
| 424 |
+
country=str(extra.get("country") or ""),
|
| 425 |
+
slug=slug,
|
| 426 |
+
year=year,
|
| 427 |
+
)
|
| 428 |
+
)
|
| 429 |
+
)
|
| 430 |
rec["entry_cid"] = _entry_cid(rec)
|
| 431 |
rec["title_length"] = len(title_for_bm25)
|
| 432 |
rec["body_length"] = len(body)
|
|
|
|
| 487 |
|
| 488 |
entries: list[dict[str, Any]] = []
|
| 489 |
|
| 490 |
+
def _append_law_row(instrument_id: str, parent: dict[str, Any]) -> None:
|
| 491 |
+
body = parent["body"]
|
| 492 |
+
if not body:
|
| 493 |
+
report["drops"]["empty_body"] += 1
|
| 494 |
+
if len(report["drop_samples"]["empty_body"]) < 20:
|
| 495 |
+
report["drop_samples"]["empty_body"].append(instrument_id)
|
| 496 |
+
return
|
| 497 |
+
meta = parent["metadata"]
|
| 498 |
+
entries.append(
|
| 499 |
+
_base_record(
|
| 500 |
+
record_type="law",
|
| 501 |
+
source_dataset=source_dataset,
|
| 502 |
+
source_revision=source_revision,
|
| 503 |
+
instrument_id=instrument_id,
|
| 504 |
+
instrument_title=parent["instrument_title"],
|
| 505 |
+
law_cid=parent["law_cid"],
|
| 506 |
+
article_number="",
|
| 507 |
+
article_title="",
|
| 508 |
+
body=body,
|
| 509 |
+
jurisdiction=parent["jurisdiction"],
|
| 510 |
+
language=parent["language"],
|
| 511 |
+
source_url=parent["source_url"],
|
| 512 |
+
snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
|
| 513 |
+
coverage=_coverage_from(
|
| 514 |
+
parent["row"],
|
| 515 |
+
meta,
|
| 516 |
+
articles_empty=articles_empty,
|
| 517 |
+
sparse_fallback=sparse_fallback,
|
| 518 |
+
),
|
| 519 |
+
license_expr=parent["license"],
|
| 520 |
+
collector=_collector(meta, source_dataset),
|
| 521 |
+
source_id=instrument_id,
|
| 522 |
+
extra={
|
| 523 |
+
"eli": parent["eli"],
|
| 524 |
+
"identifier": parent["identifier"],
|
| 525 |
+
"official_identifier": parent["official_identifier"],
|
| 526 |
+
"source_type": parent["source_type"],
|
| 527 |
+
"country": parent["country"],
|
| 528 |
+
"law_status": parent["law_status"],
|
| 529 |
+
"parent_law_id": "",
|
| 530 |
+
"article_id": "",
|
| 531 |
+
**_hierarchy_fields(
|
| 532 |
+
parent["instrument_title"], body, "", language=parent["language"]
|
| 533 |
+
),
|
| 534 |
+
},
|
| 535 |
+
)
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
if sparse_fallback:
|
| 539 |
report["schema_surprises"].append(
|
| 540 |
f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
|
| 541 |
)
|
| 542 |
|
| 543 |
+
for instrument_id, parent in law_map.items():
|
| 544 |
+
_append_law_row(instrument_id, parent)
|
| 545 |
+
|
| 546 |
if use_articles:
|
| 547 |
for _, row in articles.iterrows():
|
| 548 |
source_id = _row_get(row, "id")
|
|
|
|
| 594 |
"law_status": parent["law_status"],
|
| 595 |
"parent_law_id": instrument_id,
|
| 596 |
"article_id": source_id,
|
| 597 |
+
**_hierarchy_fields(
|
| 598 |
+
article_title, body, article_number, language=parent["language"]
|
| 599 |
+
),
|
| 600 |
},
|
| 601 |
)
|
| 602 |
)
|
|
|
|
| 604 |
for instrument_id, parent in law_map.items():
|
| 605 |
body = parent["body"]
|
| 606 |
if not body:
|
|
|
|
|
|
|
|
|
|
| 607 |
continue
|
| 608 |
meta = parent["metadata"]
|
| 609 |
+
units = split_structured_units(body, language=parent["language"])
|
| 610 |
+
if units:
|
| 611 |
+
report["unit"] = "structured"
|
| 612 |
+
for unit in units:
|
| 613 |
+
entries.append(
|
| 614 |
+
_base_record(
|
| 615 |
+
record_type=unit.kind if unit.kind in {"article", "section"} else "article",
|
| 616 |
+
source_dataset=source_dataset,
|
| 617 |
+
source_revision=source_revision,
|
| 618 |
+
instrument_id=instrument_id,
|
| 619 |
+
instrument_title=parent["instrument_title"],
|
| 620 |
+
law_cid=parent["law_cid"],
|
| 621 |
+
article_number=unit.article_number or unit.number,
|
| 622 |
+
article_title=unit.heading,
|
| 623 |
+
body=unit.body,
|
| 624 |
+
jurisdiction=parent["jurisdiction"],
|
| 625 |
+
language=parent["language"],
|
| 626 |
+
source_url=parent["source_url"],
|
| 627 |
+
snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
|
| 628 |
+
coverage="structured (headings detected in law body)",
|
| 629 |
+
license_expr=parent["license"],
|
| 630 |
+
collector=_collector(meta, source_dataset),
|
| 631 |
+
source_id=f"{instrument_id}-{unit.kind}-{unit.number}",
|
| 632 |
+
extra={
|
| 633 |
+
"eli": parent["eli"],
|
| 634 |
+
"identifier": parent["identifier"],
|
| 635 |
+
"official_identifier": parent["official_identifier"],
|
| 636 |
+
"source_type": parent["source_type"],
|
| 637 |
+
"country": parent["country"],
|
| 638 |
+
"law_status": parent["law_status"],
|
| 639 |
+
"parent_law_id": instrument_id,
|
| 640 |
+
"article_id": "",
|
| 641 |
+
"hierarchy_kind": unit.kind,
|
| 642 |
+
"hierarchy_path": unit.hierarchy_path,
|
| 643 |
+
"title_number": unit.title_number,
|
| 644 |
+
"chapter_number": unit.chapter_number,
|
| 645 |
+
"part_number": unit.part_number,
|
| 646 |
+
"section_number": unit.section_number,
|
| 647 |
+
"subsections": list(unit.subsections),
|
| 648 |
+
},
|
| 649 |
+
)
|
| 650 |
+
)
|
| 651 |
|
| 652 |
entries.sort(
|
| 653 |
key=lambda r: (
|
|
|
|
| 678 |
raise SchemaError("Duplicate entry_cid remained after dedupe")
|
| 679 |
report["n_before_dedupe"] = n_before
|
| 680 |
report["n_out"] = int(len(df))
|
| 681 |
+
if not df.empty and "record_type" in df.columns:
|
| 682 |
+
n_law_rows = int((df["record_type"] == "law").sum())
|
| 683 |
+
n_child_rows = int(df["record_type"].isin(["article", "section"]).sum())
|
| 684 |
+
report["n_law_rows"] = n_law_rows
|
| 685 |
+
report["n_child_rows"] = n_child_rows
|
| 686 |
+
report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows
|
| 687 |
+
if n_law_rows and n_child_rows:
|
| 688 |
+
report["unit"] = (
|
| 689 |
+
"law+structured" if report.get("unit") == "structured" else "law+article"
|
| 690 |
+
)
|
| 691 |
+
elif n_law_rows:
|
| 692 |
+
report["unit"] = "law"
|
| 693 |
+
elif n_child_rows:
|
| 694 |
+
report["unit"] = "article"
|
| 695 |
report["n_dropped_total"] = (
|
| 696 |
report["drops"]["empty_body"]
|
| 697 |
+ report["drops"]["missing_instrument"]
|
|
|
|
| 735 |
"empty_bodies_dropped": report["drops"]["empty_body"],
|
| 736 |
"duplicate_cids_dropped": report["drops"]["duplicate_cid"],
|
| 737 |
}
|
| 738 |
+
from .profiles import majority_language, score_heading_languages
|
| 739 |
+
|
| 740 |
+
sample_text = ""
|
| 741 |
+
if not df.empty and "body" in df.columns:
|
| 742 |
+
sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist())
|
| 743 |
+
if "title" in df.columns:
|
| 744 |
+
sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text
|
| 745 |
+
heading_langs = score_heading_languages(sample_text)
|
| 746 |
+
report["heading_language_counts"] = dict(heading_langs)
|
| 747 |
+
report["heading_language_majority"] = majority_language(heading_langs)
|
| 748 |
+
report["document_language_majority"] = None
|
| 749 |
+
if report.get("language_breakdown"):
|
| 750 |
+
report["document_language_majority"] = max(
|
| 751 |
+
report["language_breakdown"].items(), key=lambda kv: kv[1]
|
| 752 |
+
)[0]
|
| 753 |
+
from .verify import verify_normalized_corpus
|
| 754 |
+
|
| 755 |
+
report["verification"] = verify_normalized_corpus(df, report)
|
| 756 |
df.attrs["normalization_report"] = report
|
| 757 |
return df, report
|
country_laws_ir/package.py
CHANGED
|
@@ -35,8 +35,10 @@ def package_release(
|
|
| 35 |
code_root: Path,
|
| 36 |
normalization_report: dict[str, Any] | None = None,
|
| 37 |
extra_manifest: dict[str, Any] | None = None,
|
|
|
|
|
|
|
| 38 |
) -> dict[str, Any]:
|
| 39 |
-
if out.exists():
|
| 40 |
shutil.rmtree(out)
|
| 41 |
out.mkdir(parents=True, exist_ok=True)
|
| 42 |
indexes_dir = out / "indexes"
|
|
@@ -52,78 +54,95 @@ def package_release(
|
|
| 52 |
)
|
| 53 |
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
vectors_df = vectors["vectors"]
|
| 129 |
# Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
|
|
@@ -196,8 +215,8 @@ def package_release(
|
|
| 196 |
"bm25_documents": int(len(bm25["documents"])),
|
| 197 |
"bm25_keyword_shards": len(posting_idx),
|
| 198 |
"bm25_posting_rows": int(len(postings)),
|
| 199 |
-
"bm25_postings": int(bm25
|
| 200 |
-
"bm25_terms": int(bm25
|
| 201 |
"corpus_chunks": len(corpus_idx),
|
| 202 |
"corpus_rows": int(len(corpus)),
|
| 203 |
"graph_edge_chunks": len(edge_idx),
|
|
@@ -215,9 +234,22 @@ def package_release(
|
|
| 215 |
"n_laws": n_laws,
|
| 216 |
"n_articles": n_articles,
|
| 217 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
def idx_desc(name: str) -> dict[str, Any]:
|
| 220 |
path = indexes_dir / name
|
|
|
|
|
|
|
| 221 |
return file_descriptor(path, f"indexes/{name}")
|
| 222 |
|
| 223 |
hub_id = target_repo(country["slug"])
|
|
@@ -248,6 +280,7 @@ def package_release(
|
|
| 248 |
"compression_level": 6,
|
| 249 |
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 250 |
"row_group_size": MAX_ROWS_PER_FILE,
|
|
|
|
| 251 |
},
|
| 252 |
"graph": {
|
| 253 |
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
|
@@ -330,9 +363,30 @@ def package_release(
|
|
| 330 |
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 331 |
_write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
|
| 332 |
_write_gitattributes(out)
|
|
|
|
| 333 |
return manifest
|
| 334 |
|
| 335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
def _write_gitattributes(out: Path) -> None:
|
| 337 |
(out / ".gitattributes").write_text(
|
| 338 |
"*.parquet filter=lfs diff=lfs merge=lfs -text\n"
|
|
@@ -757,6 +811,8 @@ def package_release_sequential(
|
|
| 757 |
|
| 758 |
def idx_desc(name: str) -> dict[str, Any]:
|
| 759 |
path = indexes_dir / name
|
|
|
|
|
|
|
| 760 |
return file_descriptor(path, f"indexes/{name}")
|
| 761 |
|
| 762 |
manifest = {
|
|
@@ -846,6 +902,7 @@ def package_release_sequential(
|
|
| 846 |
)
|
| 847 |
_write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
|
| 848 |
_write_gitattributes(out)
|
|
|
|
| 849 |
checkpoint("package_seq_done")
|
| 850 |
return manifest
|
| 851 |
|
|
@@ -861,13 +918,18 @@ def package_from_spill(
|
|
| 861 |
expected_rows: int | None = None,
|
| 862 |
extra_manifest: dict[str, Any] | None = None,
|
| 863 |
) -> dict[str, Any]:
|
| 864 |
-
"""Package from spill dir artifacts: bm25_*.parquet, bm25_stats.
|
|
|
|
| 865 |
import pickle as _pickle
|
| 866 |
|
| 867 |
spill = Path(spill)
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 871 |
return package_release_sequential(
|
| 872 |
out,
|
| 873 |
corpus_path=Path(corpus_path),
|
|
|
|
| 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,
|
|
|
|
| 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"
|
|
|
|
| 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 = {
|
|
|
|
| 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 |
|
|
|
|
| 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),
|
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:
|
|
@@ -146,6 +158,11 @@ class Release:
|
|
| 146 |
hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
|
| 147 |
return hits[:limit]
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
def _print(rows: list[dict]) -> None:
|
| 151 |
print(json.dumps(rows, indent=2, ensure_ascii=False))
|
|
@@ -164,15 +181,29 @@ 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="
|
| 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
p_n.add_argument("--limit", type=int, default=25)
|
| 175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
args = ap.parse_args(argv)
|
| 177 |
rel = Release(Path(args.local_dir))
|
| 178 |
if args.cmd == "bm25":
|
|
@@ -181,6 +212,8 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 181 |
_print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
|
| 182 |
elif args.cmd == "graph" and args.graph_cmd == "neighbors":
|
| 183 |
_print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
|
|
|
|
|
|
|
| 184 |
return 0
|
| 185 |
|
| 186 |
|
|
|
|
| 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:
|
|
|
|
| 158 |
hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
|
| 159 |
return hits[:limit]
|
| 160 |
|
| 161 |
+
def cite(self, citation: str, cite_format: str = "any", limit: int = 25) -> list[dict]:
|
| 162 |
+
from .duckdb_store import cite_search
|
| 163 |
+
|
| 164 |
+
return cite_search(self.root, citation, cite_format=cite_format, limit=limit)
|
| 165 |
+
|
| 166 |
|
| 167 |
def _print(rows: list[dict]) -> None:
|
| 168 |
print(json.dumps(rows, indent=2, ensure_ascii=False))
|
|
|
|
| 181 |
p_vec.add_argument("query")
|
| 182 |
p_vec.add_argument("--top-k", type=int, default=10)
|
| 183 |
p_vec.add_argument("--candidate-centroids", type=int, default=4)
|
| 184 |
+
p_vec.add_argument("--device", default="cuda")
|
| 185 |
|
| 186 |
p_g = sub.add_parser("graph")
|
| 187 |
g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
|
| 188 |
p_n = g_sub.add_parser("neighbors")
|
| 189 |
p_n.add_argument("node_cid")
|
| 190 |
+
p_n.add_argument(
|
| 191 |
+
"--direction",
|
| 192 |
+
default="both",
|
| 193 |
+
choices=["both", "in", "out", "incoming", "outgoing"],
|
| 194 |
+
)
|
| 195 |
p_n.add_argument("--limit", type=int, default=25)
|
| 196 |
|
| 197 |
+
p_cite = sub.add_parser("cite")
|
| 198 |
+
p_cite.add_argument("citation")
|
| 199 |
+
p_cite.add_argument(
|
| 200 |
+
"--format",
|
| 201 |
+
dest="cite_format",
|
| 202 |
+
default="any",
|
| 203 |
+
choices=["any", "bluebook", "official"],
|
| 204 |
+
)
|
| 205 |
+
p_cite.add_argument("--limit", type=int, default=25)
|
| 206 |
+
|
| 207 |
args = ap.parse_args(argv)
|
| 208 |
rel = Release(Path(args.local_dir))
|
| 209 |
if args.cmd == "bm25":
|
|
|
|
| 212 |
_print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
|
| 213 |
elif args.cmd == "graph" and args.graph_cmd == "neighbors":
|
| 214 |
_print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
|
| 215 |
+
elif args.cmd == "cite":
|
| 216 |
+
_print(rel.cite(args.citation, cite_format=args.cite_format, limit=args.limit))
|
| 217 |
return 0
|
| 218 |
|
| 219 |
|
country_laws_ir/sparse.py
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 (
|
| 2 |
|
| 3 |
Design (CoS / DO OOM lesson):
|
| 4 |
- Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).
|
| 5 |
-
- Neighbors for n >=
|
| 6 |
-
into neighbor_*.
|
| 7 |
-
|
| 8 |
-
- BM25 TF: stream tokenize →
|
| 9 |
-
- Package:
|
| 10 |
-
|
| 11 |
-
|
| 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 |
-
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
if not db_path.is_file():
|
| 81 |
return False
|
|
|
|
| 82 |
try:
|
| 83 |
-
conn =
|
| 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 |
-
|
| 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
|
| 190 |
-
|
| 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 |
-
"""
|
|
|
|
| 226 |
|
| 227 |
-
|
| 228 |
-
whose end index is covered (contiguous from 0).
|
| 229 |
-
"""
|
| 230 |
spill.mkdir(parents=True, exist_ok=True)
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 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"
|
| 255 |
-
|
| 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"
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 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)
|
| 349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 374 |
-
|
| 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 →
|
| 496 |
|
| 497 |
-
Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.
|
| 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()
|
| 505 |
-
stats =
|
| 506 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
conn
|
| 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
|
| 521 |
-
"ttf INTEGER NOT NULL, btf INTEGER NOT NULL
|
| 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
|
| 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 |
-
|
| 753 |
try:
|
| 754 |
-
|
| 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
|
| 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
|
@@ -57,11 +57,24 @@ def upload_release(
|
|
| 57 |
if not (local_dir / "manifest.json").is_file():
|
| 58 |
raise UploadError(f"release is missing manifest.json: {local_dir}")
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
resolved = (token or "").strip() or _token_from_env()
|
| 67 |
if not resolved:
|
|
|
|
| 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:
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
-
import
|
| 30 |
-
|
| 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 =
|
| 41 |
checkpoint_path: str | None = None,
|
| 42 |
chunk_size: int = 4096,
|
| 43 |
) -> np.ndarray:
|
| 44 |
-
"""Encode corpus texts with gte-small
|
| 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 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 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 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
)
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
|
| 142 |
def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
|
|
@@ -345,14 +446,14 @@ def assemble_embeddings(
|
|
| 345 |
*,
|
| 346 |
encode_missing: bool = True,
|
| 347 |
batch_size: int = 64,
|
| 348 |
-
device: str =
|
| 349 |
checkpoint_path: str | None = None,
|
| 350 |
) -> tuple[np.ndarray, dict[str, Any]]:
|
| 351 |
-
"""Align a (n, 384) matrix to *corpus* row order
|
| 352 |
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
"""
|
| 357 |
n = int(len(corpus))
|
| 358 |
out = np.zeros((n, DIMENSION), dtype=np.float32)
|
|
@@ -362,18 +463,10 @@ def assemble_embeddings(
|
|
| 362 |
cids = corpus["entry_cid"].astype(str).tolist() if n else []
|
| 363 |
for i, cid in enumerate(cids):
|
| 364 |
vec = prior.get(cid)
|
| 365 |
-
if
|
| 366 |
-
missing_idx.append(i)
|
| 367 |
-
continue
|
| 368 |
-
try:
|
| 369 |
-
arr = np.asarray(vec, dtype=np.float32).reshape(-1)
|
| 370 |
-
except Exception:
|
| 371 |
-
missing_idx.append(i)
|
| 372 |
-
continue
|
| 373 |
-
if arr.shape[0] != DIMENSION:
|
| 374 |
missing_idx.append(i)
|
| 375 |
continue
|
| 376 |
-
out[i] =
|
| 377 |
reused_idx.append(i)
|
| 378 |
|
| 379 |
report: dict[str, Any] = {
|
|
@@ -382,25 +475,29 @@ def assemble_embeddings(
|
|
| 382 |
"n_encoded": 0,
|
| 383 |
"n_missing": len(missing_idx),
|
| 384 |
"model_name": MODEL_NAME,
|
|
|
|
| 385 |
"dimension": DIMENSION,
|
| 386 |
"status": "reused" if not missing_idx else "partial",
|
| 387 |
}
|
|
|
|
|
|
|
|
|
|
| 388 |
if not missing_idx:
|
| 389 |
report["status"] = "reused"
|
| 390 |
return _l2_normalize(out) if n else out, report
|
| 391 |
if not encode_missing:
|
| 392 |
report["status"] = "incomplete"
|
| 393 |
return out, report
|
| 394 |
-
if not
|
| 395 |
report["status"] = "stub_missing_encoder"
|
| 396 |
-
report["reason"] = "sentence-transformers/
|
| 397 |
return out, report
|
| 398 |
|
| 399 |
missing = corpus.iloc[missing_idx].reset_index(drop=True)
|
| 400 |
encoded = encode_corpus(
|
| 401 |
missing,
|
| 402 |
batch_size=batch_size,
|
| 403 |
-
device=
|
| 404 |
checkpoint_path=checkpoint_path,
|
| 405 |
)
|
| 406 |
for local_i, corpus_i in enumerate(missing_idx):
|
|
|
|
| 14 |
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 15 |
|
| 16 |
MODEL_NAME = "thenlper/gte-small"
|
| 17 |
+
MODEL_REVISION = "17e1f347d17fe144873b1201da91788898c639cd"
|
| 18 |
DIMENSION = 384
|
| 19 |
+
MAX_SEQ_LENGTH = 512
|
| 20 |
+
DEFAULT_DEVICE = "cuda"
|
| 21 |
+
SUPPORTED_DEVICES = frozenset({"cpu", "cuda", "cuda:0", "mps", "auto"})
|
| 22 |
MAX_ROWS_PER_CENTROID = 8192
|
| 23 |
MAX_SHARDS_PER_CENTROID = 2
|
| 24 |
|
|
|
|
| 28 |
return x / np.maximum(n, eps)
|
| 29 |
|
| 30 |
|
| 31 |
+
def device_is_available(device: str) -> bool:
|
| 32 |
+
"""Probe accelerator availability without loading a model."""
|
| 33 |
+
name = str(device or "").strip().lower()
|
| 34 |
+
if not name or name == "cpu":
|
| 35 |
+
return True
|
| 36 |
+
try:
|
| 37 |
+
import torch
|
| 38 |
+
except Exception:
|
| 39 |
+
return False
|
| 40 |
+
if name.startswith("cuda"):
|
| 41 |
+
return bool(
|
| 42 |
+
getattr(torch, "cuda", None)
|
| 43 |
+
and torch.backends.cuda.is_built()
|
| 44 |
+
and torch.cuda.is_available()
|
| 45 |
+
)
|
| 46 |
+
if name == "mps":
|
| 47 |
+
mps = getattr(getattr(torch, "backends", None), "mps", None)
|
| 48 |
+
return bool(mps is not None and mps.is_available())
|
| 49 |
+
return False
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def select_device(requested: str = DEFAULT_DEVICE) -> tuple[str, bool]:
|
| 53 |
+
"""Prefer CUDA like US Code / Open US Law; fall back to CPU."""
|
| 54 |
+
req = str(requested or DEFAULT_DEVICE).strip().lower() or DEFAULT_DEVICE
|
| 55 |
+
if req == "auto":
|
| 56 |
+
req = "cuda"
|
| 57 |
+
if req not in SUPPORTED_DEVICES and not req.startswith("cuda:"):
|
| 58 |
+
raise ValueError(f"unsupported embedding device: {requested!r}")
|
| 59 |
+
if device_is_available(req):
|
| 60 |
+
return req, False
|
| 61 |
+
return "cpu", True
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def ensure_embedding_stack() -> bool:
|
| 65 |
+
"""Lazy-import / lazy-install transformers + sentence-transformers.
|
| 66 |
+
|
| 67 |
+
Matches ``ipfs_datasets_py.auto_installer.ensure_module`` used by other
|
| 68 |
+
GraphRAG producers. Importing this module must not pip-install; first
|
| 69 |
+
encode may.
|
| 70 |
+
"""
|
| 71 |
+
import os
|
| 72 |
+
|
| 73 |
+
os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
|
| 74 |
try:
|
| 75 |
+
import sentence_transformers # noqa: F401
|
| 76 |
+
import transformers # noqa: F401
|
| 77 |
|
| 78 |
return True
|
| 79 |
+
except Exception:
|
| 80 |
+
pass
|
| 81 |
+
try:
|
| 82 |
+
from ipfs_datasets_py.auto_installer import ensure_module, install_for_component
|
| 83 |
+
|
| 84 |
+
install_for_component("graphrag")
|
| 85 |
+
ensure_module("torchvision", "torchvision")
|
| 86 |
+
ensure_module("transformers", "transformers")
|
| 87 |
+
module = ensure_module("sentence_transformers", "sentence-transformers")
|
| 88 |
+
return module is not None
|
| 89 |
except Exception:
|
| 90 |
return False
|
| 91 |
|
| 92 |
|
| 93 |
+
def embeddings_available() -> bool:
|
| 94 |
+
return ensure_embedding_stack()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _is_real_vector(vec: object) -> bool:
|
| 98 |
+
try:
|
| 99 |
+
arr = np.asarray(vec, dtype=np.float32).reshape(-1)
|
| 100 |
+
except Exception:
|
| 101 |
+
return False
|
| 102 |
+
if arr.shape[0] != DIMENSION:
|
| 103 |
+
return False
|
| 104 |
+
if not np.isfinite(arr).all():
|
| 105 |
+
return False
|
| 106 |
+
return float(np.linalg.norm(arr)) > 1e-6
|
| 107 |
+
|
| 108 |
+
|
| 109 |
def encode_corpus(
|
| 110 |
corpus: pd.DataFrame,
|
| 111 |
batch_size: int = 64,
|
| 112 |
+
device: str = DEFAULT_DEVICE,
|
| 113 |
checkpoint_path: str | None = None,
|
| 114 |
chunk_size: int = 4096,
|
| 115 |
) -> np.ndarray:
|
| 116 |
+
"""Encode corpus texts with pinned gte-small on CUDA when available."""
|
| 117 |
import json
|
| 118 |
import os
|
| 119 |
from datetime import datetime, timezone
|
| 120 |
from pathlib import Path as _Path
|
| 121 |
|
| 122 |
+
if not ensure_embedding_stack():
|
| 123 |
+
raise RuntimeError(
|
| 124 |
+
"sentence-transformers is required for production GTE embeddings; "
|
| 125 |
+
"lazy install failed (python -m ipfs_datasets_py.auto_installer)"
|
| 126 |
+
)
|
| 127 |
from sentence_transformers import SentenceTransformer
|
| 128 |
|
| 129 |
from .auth import configure_hf
|
| 130 |
|
| 131 |
configure_hf()
|
| 132 |
+
device, _fallback = select_device(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
texts = []
|
| 134 |
for rec in corpus.itertuples(index=False):
|
| 135 |
title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
|
|
|
|
| 141 |
done = 0
|
| 142 |
ckpt = _Path(checkpoint_path) if checkpoint_path else None
|
| 143 |
meta_path = ckpt.with_suffix(".json") if ckpt else None
|
| 144 |
+
cache_root = _Path(
|
| 145 |
+
os.environ.get(
|
| 146 |
+
"COUNTRY_LAWS_IR_ROOT",
|
| 147 |
+
str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"),
|
| 148 |
+
)
|
| 149 |
+
) / "cache" / "hf"
|
| 150 |
+
os.environ.setdefault("HF_HOME", str(cache_root))
|
| 151 |
+
os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
|
| 152 |
+
os.environ.setdefault("SENTENCE_TRANSFORMERS_HOME", str(cache_root / "sentence-transformers"))
|
| 153 |
if meta_path is not None and meta_path.exists():
|
| 154 |
try:
|
| 155 |
meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
|
| 156 |
except Exception:
|
| 157 |
meta_n = None
|
| 158 |
+
else:
|
| 159 |
+
meta_n = None
|
| 160 |
if ckpt is not None and ckpt.exists():
|
| 161 |
cached = np.load(ckpt)
|
| 162 |
same_corpus = meta_n is None or int(meta_n) == n
|
|
|
|
| 168 |
):
|
| 169 |
done = int(cached.shape[0])
|
| 170 |
out[:done] = cached.astype(np.float32, copy=False)
|
| 171 |
+
if done >= n:
|
| 172 |
+
return out
|
| 173 |
+
|
| 174 |
+
lock_fh = None
|
| 175 |
+
if device.startswith("cuda"):
|
| 176 |
+
import fcntl
|
| 177 |
+
|
| 178 |
+
lock_path = _Path(
|
| 179 |
+
os.environ.get(
|
| 180 |
+
"COUNTRY_LAWS_IR_ROOT",
|
| 181 |
+
str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"),
|
| 182 |
)
|
| 183 |
+
) / "cuda.encode.lock"
|
| 184 |
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
| 185 |
+
lock_fh = open(lock_path, "a", encoding="utf-8")
|
| 186 |
+
fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
|
| 187 |
+
try:
|
| 188 |
+
model = SentenceTransformer(
|
| 189 |
+
MODEL_NAME,
|
| 190 |
+
revision=MODEL_REVISION,
|
| 191 |
+
device=device,
|
|
|
|
|
|
|
| 192 |
)
|
|
|
|
|
|
|
|
|
|
| 193 |
try:
|
| 194 |
+
model.max_seq_length = MAX_SEQ_LENGTH
|
| 195 |
+
except Exception:
|
| 196 |
+
pass
|
| 197 |
+
while done < n:
|
| 198 |
+
j = min(done + int(chunk_size), n)
|
| 199 |
+
chunk = model.encode(
|
| 200 |
+
texts[done:j],
|
| 201 |
+
batch_size=batch_size,
|
| 202 |
+
show_progress_bar=True,
|
| 203 |
+
convert_to_numpy=True,
|
| 204 |
+
normalize_embeddings=True,
|
| 205 |
+
)
|
| 206 |
+
out[done:j] = np.asarray(chunk, dtype=np.float32)
|
| 207 |
+
done = j
|
| 208 |
+
if ckpt is not None:
|
| 209 |
+
ckpt.parent.mkdir(parents=True, exist_ok=True)
|
| 210 |
+
tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
|
| 211 |
+
np.save(tmp, out[:done])
|
| 212 |
+
tmp.replace(ckpt)
|
| 213 |
+
if meta_path is not None:
|
| 214 |
+
meta_path.write_text(
|
| 215 |
+
json.dumps(
|
| 216 |
+
{
|
| 217 |
+
"n": n,
|
| 218 |
+
"done": done,
|
| 219 |
+
"dimension": DIMENSION,
|
| 220 |
+
"model_name": MODEL_NAME,
|
| 221 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 222 |
+
}
|
| 223 |
+
)
|
| 224 |
+
+ "\n",
|
| 225 |
+
encoding="utf-8",
|
| 226 |
)
|
| 227 |
+
return out
|
| 228 |
+
finally:
|
| 229 |
+
if lock_fh is not None:
|
| 230 |
+
import fcntl as _fcntl
|
| 231 |
+
|
| 232 |
+
_fcntl.flock(lock_fh.fileno(), _fcntl.LOCK_UN)
|
| 233 |
+
lock_fh.close()
|
| 234 |
+
try:
|
| 235 |
+
import torch as _torch
|
| 236 |
+
|
| 237 |
+
if _torch.cuda.is_available():
|
| 238 |
+
_torch.cuda.empty_cache()
|
| 239 |
+
except Exception:
|
| 240 |
+
pass
|
| 241 |
|
| 242 |
|
| 243 |
def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
|
|
|
|
| 446 |
*,
|
| 447 |
encode_missing: bool = True,
|
| 448 |
batch_size: int = 64,
|
| 449 |
+
device: str = DEFAULT_DEVICE,
|
| 450 |
checkpoint_path: str | None = None,
|
| 451 |
) -> tuple[np.ndarray, dict[str, Any]]:
|
| 452 |
+
"""Align a (n, 384) matrix to *corpus* row order.
|
| 453 |
|
| 454 |
+
Reuse is CID-keyed and only accepts real GTE vectors (finite, 384-d,
|
| 455 |
+
non-zero). Stub/zero priors are treated as missing and re-encoded on
|
| 456 |
+
CUDA when available — the US Code / Open US Law contract.
|
| 457 |
"""
|
| 458 |
n = int(len(corpus))
|
| 459 |
out = np.zeros((n, DIMENSION), dtype=np.float32)
|
|
|
|
| 463 |
cids = corpus["entry_cid"].astype(str).tolist() if n else []
|
| 464 |
for i, cid in enumerate(cids):
|
| 465 |
vec = prior.get(cid)
|
| 466 |
+
if not _is_real_vector(vec):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 467 |
missing_idx.append(i)
|
| 468 |
continue
|
| 469 |
+
out[i] = np.asarray(vec, dtype=np.float32).reshape(-1)
|
| 470 |
reused_idx.append(i)
|
| 471 |
|
| 472 |
report: dict[str, Any] = {
|
|
|
|
| 475 |
"n_encoded": 0,
|
| 476 |
"n_missing": len(missing_idx),
|
| 477 |
"model_name": MODEL_NAME,
|
| 478 |
+
"model_revision": MODEL_REVISION,
|
| 479 |
"dimension": DIMENSION,
|
| 480 |
"status": "reused" if not missing_idx else "partial",
|
| 481 |
}
|
| 482 |
+
resolved, fallback = select_device(device)
|
| 483 |
+
report["device"] = resolved
|
| 484 |
+
report["device_fallback"] = fallback
|
| 485 |
if not missing_idx:
|
| 486 |
report["status"] = "reused"
|
| 487 |
return _l2_normalize(out) if n else out, report
|
| 488 |
if not encode_missing:
|
| 489 |
report["status"] = "incomplete"
|
| 490 |
return out, report
|
| 491 |
+
if not ensure_embedding_stack():
|
| 492 |
report["status"] = "stub_missing_encoder"
|
| 493 |
+
report["reason"] = "sentence-transformers/transformers lazy install failed"
|
| 494 |
return out, report
|
| 495 |
|
| 496 |
missing = corpus.iloc[missing_idx].reset_index(drop=True)
|
| 497 |
encoded = encode_corpus(
|
| 498 |
missing,
|
| 499 |
batch_size=batch_size,
|
| 500 |
+
device=resolved,
|
| 501 |
checkpoint_path=checkpoint_path,
|
| 502 |
)
|
| 503 |
for local_i, corpus_i in enumerate(missing_idx):
|
country_laws_ir/verify.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Admission verifiers for country-law normalization, before GraphRAG.
|
| 2 |
+
|
| 3 |
+
Oregon-style structure is preferred but not required for every gazette.
|
| 4 |
+
Verifiers fail closed on invented text, residual HTML, empty corpora, and
|
| 5 |
+
duplicate CIDs. Missing title/section hierarchy is a warning unless the
|
| 6 |
+
corpus already split into articles.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from dataclasses import asdict, dataclass
|
| 12 |
+
import re
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
from .structure import has_html_tags
|
| 18 |
+
|
| 19 |
+
SCHEMA_VERSION = "country-laws-normalize-verify/v1"
|
| 20 |
+
|
| 21 |
+
_HTML_FAIL_FRACTION = 0.02
|
| 22 |
+
_SHORT_BODY_FAIL_FRACTION = 0.50
|
| 23 |
+
_MIN_BODY_CHARS = 40
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class Check:
|
| 28 |
+
id: str
|
| 29 |
+
severity: str # fail | warn
|
| 30 |
+
passed: bool
|
| 31 |
+
message: str
|
| 32 |
+
evidence: dict[str, Any]
|
| 33 |
+
|
| 34 |
+
def to_dict(self) -> dict[str, Any]:
|
| 35 |
+
return asdict(self)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _bodies(corpus: pd.DataFrame) -> list[str]:
|
| 39 |
+
if corpus is None or corpus.empty or "body" not in corpus.columns:
|
| 40 |
+
return []
|
| 41 |
+
return [str(x or "") for x in corpus["body"].tolist()]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def check_nonempty(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
|
| 45 |
+
n = int(len(corpus)) if corpus is not None else 0
|
| 46 |
+
return Check(
|
| 47 |
+
id="nonempty_corpus",
|
| 48 |
+
severity="fail",
|
| 49 |
+
passed=n > 0,
|
| 50 |
+
message="normalized corpus has rows" if n else "normalized corpus is empty",
|
| 51 |
+
evidence={"n_out": n, "n_dropped": report.get("n_dropped_total")},
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def check_entry_cids(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
|
| 56 |
+
if corpus is None or corpus.empty:
|
| 57 |
+
return Check(
|
| 58 |
+
id="entry_cid_unique",
|
| 59 |
+
severity="fail",
|
| 60 |
+
passed=False,
|
| 61 |
+
message="no entry_cid values to verify",
|
| 62 |
+
evidence={},
|
| 63 |
+
)
|
| 64 |
+
missing = int(corpus["entry_cid"].isna().sum()) if "entry_cid" in corpus.columns else int(len(corpus))
|
| 65 |
+
dupes = int(corpus["entry_cid"].duplicated().sum()) if "entry_cid" in corpus.columns else 0
|
| 66 |
+
empty = int((corpus["entry_cid"].astype(str).str.strip() == "").sum()) if "entry_cid" in corpus.columns else 0
|
| 67 |
+
ok = missing == 0 and dupes == 0 and empty == 0
|
| 68 |
+
return Check(
|
| 69 |
+
id="entry_cid_unique",
|
| 70 |
+
severity="fail",
|
| 71 |
+
passed=ok,
|
| 72 |
+
message="every row has a unique entry_cid" if ok else "missing or duplicate entry_cid",
|
| 73 |
+
evidence={"missing": missing, "empty": empty, "duplicate": dupes},
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_no_invented_text(report: dict[str, Any]) -> Check:
|
| 78 |
+
flag = bool(report.get("never_invented_legal_text", False))
|
| 79 |
+
return Check(
|
| 80 |
+
id="never_invented_legal_text",
|
| 81 |
+
severity="fail",
|
| 82 |
+
passed=flag,
|
| 83 |
+
message="normalizer did not invent legal text" if flag else "invented-text flag is false",
|
| 84 |
+
evidence={"never_invented_legal_text": flag},
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def check_html_residual(corpus: pd.DataFrame) -> Check:
|
| 89 |
+
bodies = _bodies(corpus)
|
| 90 |
+
tagged = [b for b in bodies if has_html_tags(b)]
|
| 91 |
+
n = len(bodies) or 1
|
| 92 |
+
fraction = len(tagged) / float(n)
|
| 93 |
+
passed = fraction <= _HTML_FAIL_FRACTION
|
| 94 |
+
return Check(
|
| 95 |
+
id="html_residual",
|
| 96 |
+
severity="fail",
|
| 97 |
+
passed=passed,
|
| 98 |
+
message=(
|
| 99 |
+
"HTML tags stripped from legal bodies"
|
| 100 |
+
if passed
|
| 101 |
+
else f"{len(tagged)}/{len(bodies)} bodies still contain HTML tags"
|
| 102 |
+
),
|
| 103 |
+
evidence={
|
| 104 |
+
"n_bodies": len(bodies),
|
| 105 |
+
"n_with_tags": len(tagged),
|
| 106 |
+
"fraction": fraction,
|
| 107 |
+
"samples": [b[:120] for b in tagged[:5]],
|
| 108 |
+
},
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def check_short_bodies(corpus: pd.DataFrame) -> Check:
|
| 113 |
+
bodies = _bodies(corpus)
|
| 114 |
+
if not bodies:
|
| 115 |
+
return Check(
|
| 116 |
+
id="short_bodies",
|
| 117 |
+
severity="fail",
|
| 118 |
+
passed=False,
|
| 119 |
+
message="no bodies to measure",
|
| 120 |
+
evidence={},
|
| 121 |
+
)
|
| 122 |
+
short = sum(1 for b in bodies if len(b) < _MIN_BODY_CHARS)
|
| 123 |
+
fraction = short / float(len(bodies))
|
| 124 |
+
passed = fraction <= _SHORT_BODY_FAIL_FRACTION
|
| 125 |
+
return Check(
|
| 126 |
+
id="short_bodies",
|
| 127 |
+
severity="fail" if not passed else "warn",
|
| 128 |
+
passed=passed,
|
| 129 |
+
message=(
|
| 130 |
+
"most legal units have usable body length"
|
| 131 |
+
if passed
|
| 132 |
+
else f"{short}/{len(bodies)} bodies shorter than {_MIN_BODY_CHARS} characters"
|
| 133 |
+
),
|
| 134 |
+
evidence={"n_short": short, "n_bodies": len(bodies), "fraction": fraction},
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def check_heading_language(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
|
| 139 |
+
"""Warn when Latin heading dialect disagrees with the document language."""
|
| 140 |
+
from .profiles import NO_LATIN_SPLIT_LANGS, iso_lang
|
| 141 |
+
|
| 142 |
+
doc_lang = iso_lang(report.get("document_language_majority") or "")
|
| 143 |
+
head_lang = iso_lang(report.get("heading_language_majority") or "")
|
| 144 |
+
counts = report.get("heading_language_counts") or {}
|
| 145 |
+
if (
|
| 146 |
+
doc_lang in NO_LATIN_SPLIT_LANGS
|
| 147 |
+
and report.get("unit") == "structured"
|
| 148 |
+
and head_lang
|
| 149 |
+
and head_lang not in NO_LATIN_SPLIT_LANGS
|
| 150 |
+
and head_lang != doc_lang
|
| 151 |
+
):
|
| 152 |
+
return Check(
|
| 153 |
+
id="heading_language",
|
| 154 |
+
severity="fail",
|
| 155 |
+
passed=False,
|
| 156 |
+
message=(
|
| 157 |
+
f"document language {doc_lang} was split with Latin headings ({head_lang}); "
|
| 158 |
+
"use script-specific article markers or collector article rows"
|
| 159 |
+
),
|
| 160 |
+
evidence={"document_language": doc_lang, "heading_counts": counts, "unit": report.get("unit")},
|
| 161 |
+
)
|
| 162 |
+
if doc_lang and head_lang and doc_lang != head_lang and sum(counts.values()) >= 8:
|
| 163 |
+
return Check(
|
| 164 |
+
id="heading_language",
|
| 165 |
+
severity="warn",
|
| 166 |
+
passed=True,
|
| 167 |
+
message=(
|
| 168 |
+
f"heading lexicon majority is {head_lang} but documents are {doc_lang}; "
|
| 169 |
+
"review samples before trusting structure"
|
| 170 |
+
),
|
| 171 |
+
evidence={
|
| 172 |
+
"document_language": doc_lang,
|
| 173 |
+
"heading_language": head_lang,
|
| 174 |
+
"heading_counts": counts,
|
| 175 |
+
},
|
| 176 |
+
)
|
| 177 |
+
return Check(
|
| 178 |
+
id="heading_language",
|
| 179 |
+
severity="warn",
|
| 180 |
+
passed=True,
|
| 181 |
+
message=(
|
| 182 |
+
f"heading lexicon {head_lang or 'none'} vs document language {doc_lang or 'unknown'}"
|
| 183 |
+
),
|
| 184 |
+
evidence={
|
| 185 |
+
"document_language": doc_lang,
|
| 186 |
+
"heading_language": head_lang,
|
| 187 |
+
"heading_counts": counts,
|
| 188 |
+
},
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def check_parent_laws(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
|
| 193 |
+
"""Fail if source had instruments but GraphRAG corpus has no law rows."""
|
| 194 |
+
n_in = int(report.get("n_laws_in") or 0)
|
| 195 |
+
n_law_rows = 0
|
| 196 |
+
if corpus is not None and not corpus.empty and "record_type" in corpus.columns:
|
| 197 |
+
n_law_rows = int((corpus["record_type"] == "law").sum())
|
| 198 |
+
n_law_rows = int(report.get("n_law_rows") or n_law_rows)
|
| 199 |
+
if n_in > 0 and n_law_rows == 0:
|
| 200 |
+
return Check(
|
| 201 |
+
id="parent_laws",
|
| 202 |
+
severity="fail",
|
| 203 |
+
passed=False,
|
| 204 |
+
message=(
|
| 205 |
+
f"source has {n_in} laws but corpus has 0 law rows "
|
| 206 |
+
"(articles were indexed without parent instruments)"
|
| 207 |
+
),
|
| 208 |
+
evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows},
|
| 209 |
+
)
|
| 210 |
+
return Check(
|
| 211 |
+
id="parent_laws",
|
| 212 |
+
severity="warn",
|
| 213 |
+
passed=True,
|
| 214 |
+
message=f"parent instruments present ({n_law_rows} law rows from {n_in} source laws)",
|
| 215 |
+
evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows},
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check:
|
| 220 |
+
unit = str(report.get("unit") or "")
|
| 221 |
+
n = int(len(corpus)) if corpus is not None else 0
|
| 222 |
+
structured_rows = 0
|
| 223 |
+
if corpus is not None and not corpus.empty:
|
| 224 |
+
if "hierarchy_path" in corpus.columns:
|
| 225 |
+
structured_rows = int((corpus["hierarchy_path"].fillna("").astype(str).str.len() > 0).sum())
|
| 226 |
+
if "record_type" in corpus.columns:
|
| 227 |
+
structured_rows = max(
|
| 228 |
+
structured_rows,
|
| 229 |
+
int(corpus["record_type"].isin(["article", "section"]).sum()),
|
| 230 |
+
)
|
| 231 |
+
coverage = structured_rows / float(n) if n else 0.0
|
| 232 |
+
# Article or structured units are success. Pure law-level is a warning, not a fail:
|
| 233 |
+
# many gazettes have no title/section markers.
|
| 234 |
+
if unit in {"article", "structured", "law+article", "law+structured"} or coverage >= 0.5:
|
| 235 |
+
return Check(
|
| 236 |
+
id="legal_structure",
|
| 237 |
+
severity="warn",
|
| 238 |
+
passed=True,
|
| 239 |
+
message=f"retrieval units are structured ({unit}, coverage={coverage:.2f})",
|
| 240 |
+
evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
|
| 241 |
+
)
|
| 242 |
+
return Check(
|
| 243 |
+
id="legal_structure",
|
| 244 |
+
severity="warn",
|
| 245 |
+
passed=True,
|
| 246 |
+
message=(
|
| 247 |
+
"kept whole-instrument units; no title/article/section headings detected "
|
| 248 |
+
"(expected for some gazettes)"
|
| 249 |
+
),
|
| 250 |
+
evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage},
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def verify_normalized_corpus(
|
| 255 |
+
corpus: pd.DataFrame,
|
| 256 |
+
report: dict[str, Any],
|
| 257 |
+
*,
|
| 258 |
+
slug: str = "",
|
| 259 |
+
) -> dict[str, Any]:
|
| 260 |
+
"""Run all normalization verifiers. Fail-closed on any failed `fail` check."""
|
| 261 |
+
checks = [
|
| 262 |
+
check_nonempty(corpus, report),
|
| 263 |
+
check_entry_cids(corpus, report),
|
| 264 |
+
check_no_invented_text(report),
|
| 265 |
+
check_html_residual(corpus),
|
| 266 |
+
check_short_bodies(corpus),
|
| 267 |
+
check_parent_laws(corpus, report),
|
| 268 |
+
check_structure(corpus, report),
|
| 269 |
+
check_heading_language(corpus, report),
|
| 270 |
+
]
|
| 271 |
+
failed = [c for c in checks if c.severity == "fail" and not c.passed]
|
| 272 |
+
admitted = not failed
|
| 273 |
+
return {
|
| 274 |
+
"schema_version": SCHEMA_VERSION,
|
| 275 |
+
"slug": slug,
|
| 276 |
+
"admitted": admitted,
|
| 277 |
+
"n_checks": len(checks),
|
| 278 |
+
"n_failed": len(failed),
|
| 279 |
+
"failed_ids": [c.id for c in failed],
|
| 280 |
+
"checks": [c.to_dict() for c in checks],
|
| 281 |
+
"blocks_graphrag": not admitted,
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class NormalizationAdmissionError(RuntimeError):
|
| 286 |
+
"""Raised when verifiers refuse to send a corpus to GraphRAG."""
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def verify_source(source: str) -> dict[str, Any]:
|
| 290 |
+
"""Load a Hub/local pack, normalize, and run verifiers (no GraphRAG)."""
|
| 291 |
+
from .build import CACHE
|
| 292 |
+
from .catalog import get_country
|
| 293 |
+
from .normalize import build_corpus, load_source
|
| 294 |
+
|
| 295 |
+
country = get_country(source)
|
| 296 |
+
local = country.get("local_source_dir")
|
| 297 |
+
laws, articles, source_meta = load_source(local or country["repo"], CACHE)
|
| 298 |
+
corpus, report = build_corpus(laws, articles, source_meta)
|
| 299 |
+
verdict = verify_normalized_corpus(corpus, report, slug=country["slug"])
|
| 300 |
+
report["verification"] = verdict
|
| 301 |
+
return {
|
| 302 |
+
"slug": country["slug"],
|
| 303 |
+
"source": country["repo"],
|
| 304 |
+
"n_out": report.get("n_out"),
|
| 305 |
+
"unit": report.get("unit"),
|
| 306 |
+
"verification": verdict,
|
| 307 |
+
"drops": report.get("drops"),
|
| 308 |
+
}
|
data/bm25/documents/part-000000.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0dc41163937cde4a93321e0e5df77756142777482a0f709dc3eaf9bc0e6ec6e9
|
| 3 |
+
size 532963
|
data/bm25/documents/part-000001.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e84061eda1f5fa8e83132e3f82377f606dfe5f482b4ec304d7fc9efcdba39399
|
| 3 |
+
size 537560
|
data/bm25/documents/part-000002.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5601dc98b5138f3ca6931e03aa7edbbbe374b2518a0b4fbbba1720acd48b3afc
|
| 3 |
+
size 536067
|
data/bm25/documents/part-000003.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1562a0fdeeb8e976ab8bb02c8bb4289b053cc781ae01466df003a3ab2f4e94e5
|
| 3 |
+
size 541085
|
data/bm25/documents/part-000004.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e5c7a4ca4eafd900757d5183243d8224fceeeabc3966187c25e5678c36ad1cb3
|
| 3 |
+
size 542027
|
data/bm25/documents/part-000005.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6ab066f3ede378909422d24b4ceb3816cba05621601ec6914e40a6681dbd487
|
| 3 |
+
size 537490
|
data/bm25/documents/part-000006.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f61d33bd30fa8d1b254806b1f57a06c5c78a4e25ea322ff14dd7a69c2b368dc0
|
| 3 |
+
size 536486
|
data/bm25/documents/part-000007.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e68f87922afea7d07c20737fbc5fc496382cfef07c31d069e0b720fd35710148
|
| 3 |
+
size 547801
|
data/bm25/documents/part-000008.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a2b1a8bf822d87a0c8aa1c1f80112b690bad9f16a18c0ea371edc98fb14e6615
|
| 3 |
+
size 540182
|
data/bm25/documents/part-000009.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e308cecbcef83df0f0e05391d9ebe02fb7d7643c118610fcb5f33f8562efae74
|
| 3 |
+
size 542535
|
data/bm25/documents/part-000010.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:913cff9304da74abcf1ccf8852064a3c39a9d7c7786ebed9f9bb96de6a7601a9
|
| 3 |
+
size 246128
|
data/bm25/postings/part-000000.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9865fc7c12c577bd22b2c2f349e5425f0c716926327914cb3e2de32de30e98fa
|
| 3 |
+
size 557563
|
data/bm25/postings/part-000001.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b51bfca4594df61a9801d108a861da331d4611447e4a45ecf2687b19d651cda4
|
| 3 |
+
size 422841
|
data/bm25/postings/part-000002.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1fd223410a4368b6685eea55dae43b0f488741052d69d063c35ac79308b6aed4
|
| 3 |
+
size 1190336
|
data/bm25/postings/part-000003.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:51ed00a483e5dcab39ece240d3eb0f0c3ab42a62b6feb10a8ce755fd8db089eb
|
| 3 |
+
size 1424844
|
data/bm25/postings/part-000004.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:67d10b0460ef24764539eee3dc6c66712237669218bf8b97d1e4f18df5fd21e3
|
| 3 |
+
size 1121795
|
data/bm25/postings/part-000005.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3881ac6afc655231fc7b9b9e1fbc9bdcc01134f6a0f3abe45abc6153635a6764
|
| 3 |
+
size 1439664
|
data/bm25/postings/part-000006.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d541ed9097bf6cc07151f02a2b212cbd1dbe030831705bcf39c5280a5d9ed36f
|
| 3 |
+
size 1145449
|
data/bm25/postings/part-000007.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f4d78dcaf638e8b6dd551cbad6dc76f7864b43ff584eb6a6a77258f7cbc1abec
|
| 3 |
+
size 1246221
|
data/bm25/postings/part-000008.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d0eabcf01ca7989d7e1bbe9ad7a7b11bf5bf3feedbe660bdec01903287eddb56
|
| 3 |
+
size 1438385
|
data/bm25/postings/part-000009.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d34b6025f2c8027a126c145fbb822d55678a98ce530502791104b6de714d4b87
|
| 3 |
+
size 1198068
|
data/bm25/postings/part-000010.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:11769fb214752511de7af16dc394c89ff04d8f219b481d9663a25b280d9029e8
|
| 3 |
+
size 1432381
|
data/bm25/postings/part-000011.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:814f101d7ad8bbc5b1e65b06cad5ef4242154d8d2c195e7f481682a03a6544d9
|
| 3 |
+
size 816305
|
data/corpus/part-000000.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:28a5c4233e55e00a8525d5a8851d4bc32c7028a13d7d3da2a5bb713f551ccb12
|
| 3 |
+
size 2191725
|
data/corpus/part-000001.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4dd46ced87eef5566a73ef985fc5447dd7c23430fd7e7f35c8ea8c9b1a88b776
|
| 3 |
+
size 1785264
|
data/corpus/part-000002.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ac696fdf8a2591d5b180faad496f4ead4817e21f09be6dbb5e7c0258a83c1efa
|
| 3 |
+
size 1839553
|
data/corpus/part-000003.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e863c055474c5a6a9125d11756269d03d6358f645a55a70ef57114c6e8f5c4c6
|
| 3 |
+
size 2161756
|
data/corpus/part-000004.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:528577a2cfb11d4cd18f1cdfc5b00bfd50ba66e7429174a03dc1296c026a9c75
|
| 3 |
+
size 1827819
|
data/corpus/part-000005.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d3e23b5080a9eaee0b40e2eb7ce91c5e3c4b6c52e1851f63a5d03d0e180bc3e
|
| 3 |
+
size 2194002
|
data/corpus/part-000006.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9e8ebb7a064dfc9faaf10c5c1124c25b8e2a45b1bb44f49490058bee50599e9b
|
| 3 |
+
size 1787207
|
data/corpus/part-000007.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2ead41e938ac9d612d39d31857b6b871c7bfc1d29dfbb6c19159f42741db0623
|
| 3 |
+
size 1847623
|
data/corpus/part-000008.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6eff3a7c223ab77726b62d9ae1c31f1613b1bd705fd77e05ca633bb3718888fe
|
| 3 |
+
size 1785444
|