diff --git a/README.md b/README.md index a61db5e6b9717f678c8c423a4ea8d6b439b035bd..309fb6f04df769e1b455068a197faf281197401c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,132 @@ -# justicedao/ipfs_kenya_laws_ir +--- +license: other +task_categories: +- text-retrieval +tags: +- legal +- law +- graphrag +- bm25 +- research +- not-legal-advice +- kenya +pretty_name: Kenya laws IR (CID-keyed GraphRAG) +configs: +- config_name: corpus + data_files: + - split: train + path: data/corpus/*.parquet +- config_name: bm25_documents + data_files: + - split: train + path: data/bm25/documents/*.parquet +- config_name: bm25_postings + data_files: + - split: train + path: data/bm25/postings/*.parquet +- config_name: bm25_keyword_index + data_files: + - split: train + path: indexes/bm25_keyword_shards.parquet +- config_name: vectors + data_files: + - split: train + path: data/vectors/*.parquet +- config_name: vector_meta_index + data_files: + - split: train + path: indexes/vector_chunks.parquet +- config_name: graph_nodes + data_files: + - split: train + path: data/graph/nodes/*.parquet +- config_name: graph_edges + data_files: + - split: train + path: data/graph/edges/*.parquet +- config_name: graph_outgoing_adjacency + data_files: + - split: train + path: data/graph/adjacency/outgoing/*.parquet +- config_name: graph_incoming_adjacency + data_files: + - split: train + path: data/graph/adjacency/incoming/*.parquet +--- -Kenya laws IR release. +# Kenya legislation IR (CID-keyed sparse GraphRAG) + +Research retrieval release of `endomorphosis/ipfs_kenya_laws` (revision `27b81c642fec385c9123c30b9eb885d093b70f61`) packaged as +`country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3` / publicus-ir). + +**Not legal advice.** This is a research snapshot. The official gazette / +authentic source of Kenya prevails over this corpus. Retrieved documents +and graph edges are retrieval evidence only. No legal text was invented. + +Primary key: `entry_cid` (CIDv1 raw sha2-256 of a canonical identity record). +Integer `document_index` values are compact shard pointers, not identities. + +Target Hub id (packaging metadata only): `justicedao/ipfs_kenya_laws_ir`. + +## Counts + +| Field | Value | +| --- | --- | +| Laws (corpus units) | 0 | +| Articles (corpus units) | 9802 | +| Canonical docs | 9802 | +| BM25 terms | 21080 | +| BM25 postings | 712415 | +| Graph nodes | 10223 | +| Graph edges | 68614 | +| Vectors | 9802 × 384-d `thenlper/gte-small` (embedded) | + +## Canonical fields + +`entry_cid`, `law_cid`, `record_type`, `jurisdiction`, `language`, +`instrument_id`, `instrument_title`, `article_number`, `article_title`, +`title`, `body`, `source_url`, `snapshot_date`, `coverage`, `license`, +`collector`, `source_dataset`, `source_revision`. + +Unit policy: prefer article/section rows; fall back to law-level when +`articles.parquet` is empty. + +## Index layout + +Zstandard parquet shards with at most 4,096 rows. + +- `indexes/bm25_keyword_shards.parquet` — lexical term ranges → BM25 posting shards +- `indexes/vector_chunks.parquet` — semantic routing centroids (rows sorted by cosine to shard centroid) +- `indexes/corpus_chunks.parquet` — document ranges → corpus shards +- `data/graph/nodes` / `data/graph/edges` — property graph +- `data/graph/adjacency/{incoming,outgoing}` — score-ordered neighbor pages + +BM25: Okapi k1=1.2, b=0.75, title_weight=5, body_weight=1 (FTS5 unicode61-style tokenizer). + +Graph: one node per `entry_cid` plus facet nodes (`_facet_cid(kind, value)` for +jurisdiction, language, instrument, source, status). Neighbor edges +`BM25_NEIGHBOR_OF` (k=8) carry score and matched terms. Structural edges: +`ARTICLE_OF` (article → parent law) when articles exist, plus `IDENTIFIED_BY_ELI` +/ `IDENTIFIED_BY` only when those identifiers are present in the source. + +## Query + +``` +python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 10 +python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 10 +python scripts/query_country_laws_hf.py --local-dir . graph neighbors +``` + +## Publish later (operator) + +``` +export HF_TOKEN=... # never commit +hf upload-large-folder justicedao/ipfs_kenya_laws_ir . \ + --repo-type dataset --no-private --num-workers 8 \ + --exclude "**/__pycache__/**" --exclude "**/*.pyc" +``` + +## Provenance + +Packaged by country-laws-ir. Upstream collector and official license remain those +of `endomorphosis/ipfs_kenya_laws`. CIDs identify local content; they do not prove public IPFS pinning. diff --git a/build.py b/build.py index 26c3b33fc4736b84ad0436ae30bebbebfc0e2b59..768973af97da5ea96deef2b5b7bbbc06909d9ebe 100644 --- a/build.py +++ b/build.py @@ -1,22 +1,51 @@ -"""End-to-end build: normalize → BM25 → graph → vectors → package (no upload by default).""" +"""End-to-end build: normalize → incremental vectors → BM25 → graph → package. + +Default mode is ``auto``: skip when the endomorphosis source revision is +unchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuild +BM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-in +via ``upload=True``. +""" from __future__ import annotations +import os + import json + +import pandas as pd import traceback from datetime import datetime, timezone from pathlib import Path from typing import Any -from .bm25 import bm25_neighbors, build_index +from .sparse import export_sparse_graphrag +from .mem import MemAbort, checkpoint, log_mem +from .spill import spill_dir_for, spill_pickle +from .package import package_from_spill, package_release from .catalog import get_country, indexable_countries, target_repo -from .graph import build_graph + +from .incremental import ( + fetch_hub_prior, + load_embedding_cache, + load_prior_release, + load_release_vectors_by_cid, + merge_embedding_maps, + plan_rebuild, + save_embedding_cache, +) from .normalize import build_corpus, load_source -from .package import package_release from .auth import configure_hf -from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors +from .vectors import ( + DIMENSION, + MODEL_NAME, + assemble_embeddings, + embeddings_by_cid, + layout_stub_vectors, + layout_vectors, + select_device, +) -ROOT = Path("/workspace/country-laws-ir") +ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir"))) CACHE = ROOT / "cache" RELEASES = ROOT / "releases" REPORTS = ROOT / "reports" @@ -31,32 +60,181 @@ def _log(msg: str) -> None: def record_progress(event: dict[str, Any]) -> None: event = dict(event) event.setdefault("ts", datetime.now(timezone.utc).isoformat()) - with PROGRESS.open("a", encoding="utf-8") as f: - f.write(json.dumps(event, ensure_ascii=False) + "\n") + PROGRESS.parent.mkdir(parents=True, exist_ok=True) + lock_path = PROGRESS.with_suffix(".lock") + with lock_path.open("a", encoding="utf-8") as lock_fh: + try: + import fcntl + + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) + except Exception: + pass + with PROGRESS.open("a", encoding="utf-8") as f: + f.write(json.dumps(event, ensure_ascii=False) + "\n") + + +def _prior_dir_for( + slug: str, + out: Path, + prior_dir: Path | None, + *, + fetch_hub: bool = True, +) -> Path | None: + if prior_dir is not None: + return Path(prior_dir) + if out.is_dir() and (out / "manifest.json").is_file(): + return out + default = RELEASES / f"ipfs_{slug}_laws_ir" + if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve(): + return default + if not fetch_hub: + return None + hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir") + if hub is not None: + _log(f"using justicedao prior {hub}") + return hub + + +def _encode_vectors( + *, + corpus: pd.DataFrame, + country_slug: str, + prior, + plan, + skip_vectors: bool, + device: str, +) -> tuple[dict[str, Any], str | None, dict[str, Any]]: + import gc + + vector_report: dict[str, Any] = {"status": "stub"} + vector_blocker = None + if skip_vectors: + vectors = layout_stub_vectors(corpus, reason="skip_vectors flag") + return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"} + + cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet" + prior_by_cid = {} + if plan.reuse_embeddings: + prior_by_cid = merge_embedding_maps( + load_embedding_cache(cid_cache_path), + None if prior is None else load_release_vectors_by_cid(prior.directory), + ) + _log(f"embedding cache reused_cids={len(prior_by_cid)}") + try: + positional = CACHE / "embeddings" / f"{country_slug}.npy" + resolved, fallback = select_device(device) + if fallback: + _log(f"embedding device fallback requested={device} using={resolved}") + embeddings, vector_report = assemble_embeddings( + corpus, + prior_by_cid, + encode_missing=True, + device=resolved, + checkpoint_path=str(positional), + ) + if ( + vector_report.get("status") in {"stub_missing_encoder", "incomplete"} + and not int(vector_report.get("n_reused") or 0) + ): + vector_blocker = vector_report.get("reason") or vector_report.get("status") + vectors = layout_stub_vectors(corpus, reason=str(vector_blocker)) + return vectors, vector_blocker, vector_report + vectors = layout_vectors(corpus, embeddings) + if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused": + vectors["stats"]["status"] = "partial" + vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0) + vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0) + vector_blocker = vector_report.get("reason") or vector_report.get("status") + save_embedding_cache( + cid_cache_path, + merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)), + model_name=MODEL_NAME, + dimension=DIMENSION, + ) + del embeddings + gc.collect() + _log( + f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} " + f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}" + ) + return vectors, None, vector_report + except Exception as exc: + vector_blocker = f"embedding_failed: {exc}" + _log(f"vector embedding failed; writing stub ({exc})") + vectors = layout_stub_vectors(corpus, reason=vector_blocker) + return vectors, vector_blocker, {"status": "failed", "reason": str(exc)} def build_country( source: str, out: Path | None = None, upload: bool = False, - device: str = "cpu", + device: str = "cuda", neighbor_k: int = 8, skip_vectors: bool = False, + mode: str = "auto", + force: bool = False, + prior_dir: Path | None = None, + fetch_hub_prior_ir: bool = True, ) -> dict[str, Any]: country = get_country(source) if not country.get("indexable", True): raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}") repo = country["repo"] out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir" - _log(f"build start {repo} -> {out} (upload={upload})") + local_dir = country.get("local_source_dir") or ( + str(Path(source).resolve()) + if Path(source).is_dir() + and ( + (Path(source) / "data" / "laws.parquet").is_file() + or (Path(source) / "laws.parquet").is_file() + ) + else None + ) + _log( + f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}" + ) configure_hf() CACHE.mkdir(parents=True, exist_ok=True) REPORTS.mkdir(parents=True, exist_ok=True) - laws, articles, source_meta = load_source(repo, CACHE) + laws, articles, source_meta = load_source(local_dir or repo, CACHE) _log( f"source loaded laws={source_meta['n_laws_source']} " f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}" ) + prior = load_prior_release( + _prior_dir_for( + country["slug"], + out, + prior_dir, + fetch_hub=fetch_hub_prior_ir, + ) + ) + plan = plan_rebuild( + mode=mode, + source_meta=source_meta, + prior=prior, + force=force, + rebuild_stub_vectors=not skip_vectors, + ) + if plan.skip_build: + _log(f"skip unchanged {country['slug']} rev={plan.source_revision}") + result = { + "country": country["slug"], + "source": repo, + "source_revision": source_meta["source_revision"], + "out": str(out), + "target_hub_id": target_repo(country["slug"]), + "skipped": True, + "incremental": plan.to_dict(), + "normalization": {"n_out": plan.delta.current_count if plan.delta else 0}, + "vector_blocker": None, + "neighbor_via": None, + "schema_version": "country-laws-ir-graphrag/v1", + } + record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}}) + return result + corpus, norm_report = build_corpus(laws, articles, source_meta) report_path = REPORTS / f"{country['slug']}_normalization.json" report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") @@ -69,47 +247,94 @@ def build_country( ) if corpus.empty: raise RuntimeError("Normalized corpus is empty; refusing to package") + verdict = (norm_report or {}).get("verification") or {} + if verdict.get("blocks_graphrag") and not force: + from .verify import NormalizationAdmissionError - bm25 = build_index(corpus) - _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}") - _log(f"bm25 neighbors start n={len(corpus)} k={neighbor_k}") - neighbors = bm25_neighbors(bm25, k=neighbor_k) - _log("bm25 neighbors done") - graph = build_graph(corpus, neighbors) - _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}") + raise NormalizationAdmissionError( + f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}" + ) - vector_blocker = None - if skip_vectors: - vectors = layout_stub_vectors(corpus, reason="skip_vectors flag") - vector_blocker = "skip_vectors" - elif embeddings_available(): - try: - ckpt = CACHE / "embeddings" / f"{country['slug']}.npy" - _log(f"vectors encode start n={len(corpus)} checkpoint={ckpt}") - embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt)) - vectors = layout_vectors(corpus, embeddings) - _log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}") - except Exception as exc: - vector_blocker = f"embedding_failed: {exc}" - _log(f"vector embedding failed; writing stub ({exc})") - vectors = layout_stub_vectors(corpus, reason=vector_blocker) - else: - vector_blocker = "sentence-transformers/torch unavailable" - _log(f"vectors stub: {vector_blocker}") - vectors = layout_stub_vectors(corpus, reason=vector_blocker) + import gc + plan = plan_rebuild( + mode=mode, + source_meta=source_meta, + prior=prior, + current_corpus=corpus, + force=force, + rebuild_stub_vectors=not skip_vectors, + ) + _log( + f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} " + f"added={0 if plan.delta is None else plan.delta.n_added} " + f"removed={0 if plan.delta is None else plan.delta.n_removed}" + ) + + n_docs = len(corpus) + spill = spill_dir_for(country["slug"], CACHE) + spill.mkdir(parents=True, exist_ok=True) + corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet" + corpus.to_parquet(corpus_ckpt, index=False) + checkpoint("after_normalize", log=_log) + + vectors, vector_blocker, vector_report = _encode_vectors( + corpus=corpus, + country_slug=country["slug"], + prior=prior, + plan=plan, + skip_vectors=skip_vectors, + device=device, + ) + spill_pickle(spill / "vectors.pkl", vectors) + del vectors + gc.collect() + checkpoint("vectors_spilled", log=_log) + extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}} + + neighbor_via = "hf_graphrag" + if out.exists(): + import shutil as _shutil + + _shutil.rmtree(out) + out.mkdir(parents=True, exist_ok=True) + _log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}") + sparse_report = export_sparse_graphrag(corpus, out) + extra_manifest["sparse"] = sparse_report + with open(spill / "vectors.pkl", "rb") as _vf: + import pickle as _pickle + + vectors = _pickle.load(_vf) + dummy_bm25 = { + "documents": pd.DataFrame(), + "postings": pd.DataFrame(), + "stats": (sparse_report.get("bm25") or {}).get("bm25") + or (sparse_report.get("bm25") or {}), + } + dummy_graph = { + "nodes": pd.DataFrame(), + "edges": pd.DataFrame(), + "incoming": pd.DataFrame(), + "outgoing": pd.DataFrame(), + "stats": sparse_report.get("graph") or {}, + } code_root = Path(__file__).resolve().parent.parent manifest = package_release( out, corpus, - bm25, - graph, + dummy_bm25, + dummy_graph, vectors, source_meta, country, code_root, normalization_report=norm_report, + extra_manifest=extra_manifest, + wipe=False, + skip_bm25_graph=True, ) + del corpus, vectors + gc.collect() _log(f"packaged {out}") result = { "country": country["slug"], @@ -120,7 +345,10 @@ def build_country( "counts": manifest["counts"], "normalization": norm_report, "vector_blocker": vector_blocker, + "neighbor_via": neighbor_via, "schema_version": manifest["schema_version"], + "skipped": False, + "incremental": extra_manifest["incremental"], } if upload: from .upload import upload_release @@ -138,25 +366,32 @@ def batch( slugs: list[str] | None = None, upload: bool = False, skip_done: bool = True, + mode: str = "auto", + force: bool = False, + skip_vectors: bool = False, ) -> list[dict[str, Any]]: - done = set() - if skip_done and PROGRESS.exists(): - for line in PROGRESS.read_text(encoding="utf-8").splitlines(): - if not line.strip(): - continue - rec = json.loads(line) - if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"): - done.add(rec["country"]) + """Build every indexable country. Unchanged Hub revisions are skipped in auto mode. + + ``skip_done`` is kept for compatibility: it no longer skips a country whose + source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to + rebuild regardless of CID overlap. + """ targets = slugs or [c["slug"] for c in indexable_countries()] if "malta" in targets: targets = ["malta"] + [s for s in targets if s != "malta"] results = [] + rebuild_force = force or not skip_done for slug in targets: - if skip_done and slug in done: - _log(f"skip already done {slug}") - continue try: - results.append(build_country(slug, upload=upload)) + results.append( + build_country( + slug, + upload=upload, + mode=mode, + force=rebuild_force, + skip_vectors=skip_vectors, + ) + ) except Exception as exc: _log(f"FAILED {slug}: {exc}") record_progress( @@ -169,3 +404,98 @@ def batch( ) continue return results + + +def reindex_from_gaps( + *, + upload: bool = False, + slugs: list[str] | None = None, + limit: int | None = None, + max_corpus_rows: int | None = 20_000, + skip_vectors: bool = False, + workers: int = 4, + mode: str = "auto", + force: bool = False, + all_indexable: bool = False, + device: str = "cuda", +) -> list[dict[str, Any]]: + """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country. + + Default cap skips huge corpora (Finland, Dominican Republic). Pass + ``max_corpus_rows=None`` to include them. + """ + from .catalog import indexable_countries + from .coverage import gap_report + + if slugs is None: + if all_indexable: + rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()] + _log(f"reindex all indexable n={len(rows)}") + else: + report = gap_report(workers=workers) + rows = [c for c in report["countries"] if c.get("rebuild")] + _log( + f"reindex targets n={len(rows)} " + f"(from scan rebuild={len(report.get('rebuild') or [])})" + ) + rows.sort(key=lambda r: int(r.get("corpus_rows") or 0)) + if max_corpus_rows is not None: + rows = [ + r + for r in rows + if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows) + ] + if limit is not None: + rows = rows[: int(limit)] + slugs = [str(r["slug"]) for r in rows] + kwargs = { + "upload": upload, + "mode": mode, + "force": force, + "skip_vectors": skip_vectors, + "fetch_hub_prior_ir": True, + "device": device, + } + n_workers = max(1, int(workers or 1)) + _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda") + import multiprocessing as mp + from concurrent.futures import ProcessPoolExecutor, as_completed + + try: + mp.set_start_method("spawn", force=False) + except RuntimeError: + pass + + results = [None] * len(slugs) + with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool: + futs = { + pool.submit(_reindex_one_country, (slug, kwargs)): i + for i, slug in enumerate(slugs) + } + for fut in as_completed(futs): + idx = futs[fut] + slug = slugs[idx] + try: + results[idx] = fut.result() + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + results[idx] = {"country": slug, "skipped": False, "error": str(exc)} + return [r for r in results if r is not None] + + +def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]: + slug, kwargs = item + _log(f"reindex start {slug}") + try: + return build_country(slug, **kwargs) + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + record_progress( + { + "event": "failed", + "country": slug, + "error": str(exc), + "traceback": traceback.format_exc(), + } + ) + return {"country": slug, "skipped": False, "error": str(exc)} diff --git a/country_laws_ir/__init__.py b/country_laws_ir/__init__.py index cb97e439ac1cd1646bbaa3943b7b61b3fa3b124f..35db2f270ce51a1cb5b90306650e116f8f4aa343 100644 --- a/country_laws_ir/__init__.py +++ b/country_laws_ir/__init__.py @@ -1,6 +1,6 @@ """Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family).""" -__version__ = "0.3.0" +__version__ = "0.5.0" # Layout matches SkillCenter HF release / publicus-ir family; schema string is domain-specific. SCHEMA_VERSION = "country-laws-ir-graphrag/v1" LAYOUT_FAMILY = "skillcenter-huggingface-release/v3" diff --git a/country_laws_ir/__main__.py b/country_laws_ir/__main__.py index 419fbb5dde4d0636b7e6c2458ca7df517b72b18c..438bb8d0cca0f061a42ee449d414a2ff2c0383cf 100644 --- a/country_laws_ir/__main__.py +++ b/country_laws_ir/__main__.py @@ -1,4 +1,4 @@ -"""python -m country_laws_ir {build,query,batch,catalog}""" +"""python -m country_laws_ir {build,query,batch,catalog,normalize,package-raw}""" from __future__ import annotations @@ -14,17 +14,29 @@ def main(argv: list[str] | None = None) -> int: p_build = sub.add_parser("build") p_build.add_argument("--source-repo", "--source", dest="source", default="malta", - help="Hub dataset id (endomorphosis/ipfs__laws) or country slug") + help="Hub dataset id (endomorphosis/ipfs__laws), country slug, or local pack dir") p_build.add_argument("--out", default=None) - p_build.add_argument("--device", default="cpu") + p_build.add_argument( + "--device", + default="cuda", + help="Embedding device (cuda by default, like US Code / Open US Law; falls back to cpu)", + ) p_build.add_argument("--neighbor-k", type=int, default=8) p_build.add_argument("--skip-vectors", action="store_true") - p_build.add_argument("--upload", action="store_true") + p_build.add_argument("--upload", action="store_true", + help="Publish the packaged release to justicedao/ipfs__laws_ir (requires HF_TOKEN)") + p_build.add_argument("--mode", default="auto", choices=["auto", "full", "delta"], + help="auto skips unchanged Hub revisions and reuses embeddings by entry_cid") + p_build.add_argument("--force", action="store_true", help="Ignore source fingerprint skip and reuse caches") + p_build.add_argument("--prior-dir", default=None, help="Prior GraphRAG release to delta against") p_batch = sub.add_parser("batch") p_batch.add_argument("--slugs", nargs="*", default=None) p_batch.add_argument("--upload", action="store_true") - p_batch.add_argument("--no-skip-done", action="store_true") + p_batch.add_argument("--no-skip-done", action="store_true", + help="Force a full rebuild of every country (ignore unchanged fingerprints)") + p_batch.add_argument("--mode", default="auto", choices=["auto", "full", "delta"]) + p_batch.add_argument("--skip-vectors", action="store_true") p_q = sub.add_parser("query") p_q.add_argument("--local-dir", required=True) @@ -34,7 +46,52 @@ def main(argv: list[str] | None = None) -> int: p_norm.add_argument("--source-repo", "--source", dest="source", default="malta") p_norm.add_argument("--out", default=None, help="Optional JSON report path") - sub.add_parser("catalog") + p_cat = sub.add_parser("catalog") + p_cat.add_argument("--refresh", action="store_true", + help="List public endomorphosis/ipfs_*_laws datasets and persist new slugs") + + p_cov = sub.add_parser("coverage", help="Compare endomorphosis sources vs justicedao GraphRAG releases") + p_cov.add_argument("--gaps", action="store_true", + help="Scan Hub for missing, stale, and incomplete IR (downloads manifests)") + p_cov.add_argument("--workers", type=int, default=8) + + p_re = sub.add_parser( + "reindex", + help="Scan endomorphosis vs justicedao and incrementally rebuild stale/missing IR", + ) + p_re.add_argument("--upload", action="store_true", + help="Publish rebuilt packs to justicedao (requires HF_TOKEN)") + p_re.add_argument("--slugs", nargs="*", default=None) + p_re.add_argument("--limit", type=int, default=None) + p_re.add_argument("--max-corpus-rows", type=int, default=20000, + help="Skip IR larger than this many rows (0 = no cap)") + p_re.add_argument("--skip-vectors", action="store_true") + p_re.add_argument("--workers", type=int, default=2, + help="Parallel country workers (default 2 to stay under MemAbort; CUDA encodes are file-locked)") + p_re.add_argument("--device", default="cuda") + p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"]) + p_re.add_argument("--all", action="store_true", + help="Process every indexable catalog country (not only Hub gaps)") + p_re.add_argument("--force", action="store_true", + help="Rebuild even when the source SHA matches (rerun normalize/verifiers)") + + p_ver = sub.add_parser( + "verify", + help="Normalize a country pack and run admission verifiers (no GraphRAG)", + ) + p_ver.add_argument("--source-repo", "--source", dest="source", default=None) + p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country") + p_ver.add_argument("--limit", type=int, default=None) + + p_raw = sub.add_parser("package-raw") + p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs__laws_ir") + p_raw.add_argument("--instruments-dir", default=None, + help="Collector JSON directory (default: $LEGAL_CORPORA_ROOT//instruments)") + p_raw.add_argument("--iso", default=None, help="Collector ISO directory name if different from slug") + p_raw.add_argument("--out", default=None, help="Local pack directory (laws.parquet + pack_meta.json)") + p_raw.add_argument("--source-dataset", default=None, + help="Raw Hub id (default endomorphosis/ipfs__laws)") + p_raw.add_argument("--prior-pack", default=None, help="Existing parquet pack to merge into") args = ap.parse_args(argv) if args.cmd == "build": @@ -47,6 +104,9 @@ def main(argv: list[str] | None = None) -> int: device=args.device, neighbor_k=args.neighbor_k, skip_vectors=args.skip_vectors, + mode=args.mode, + force=args.force, + prior_dir=Path(args.prior_dir) if args.prior_dir else None, ) print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str)) print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str)) @@ -54,8 +114,17 @@ def main(argv: list[str] | None = None) -> int: if args.cmd == "batch": from .build import batch - results = batch(slugs=args.slugs, upload=args.upload, skip_done=not args.no_skip_done) - print(json.dumps([{"country": r["country"], "out": r["out"]} for r in results], indent=2)) + results = batch( + slugs=args.slugs, + upload=args.upload, + skip_done=not args.no_skip_done, + mode=args.mode, + skip_vectors=args.skip_vectors, + ) + print(json.dumps( + [{"country": r["country"], "out": r["out"], "skipped": r.get("skipped", False)} for r in results], + indent=2, + )) return 0 if args.cmd == "query": from .query import main as qmain @@ -63,12 +132,13 @@ def main(argv: list[str] | None = None) -> int: argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"] return qmain(argv2) if args.cmd == "normalize": - from .build import CACHE, REPORTS, ROOT + from .build import CACHE, REPORTS from .catalog import get_country from .normalize import build_corpus, load_source country = get_country(args.source) - laws, articles, source_meta = load_source(country["repo"], CACHE) + local = country.get("local_source_dir") + laws, articles, source_meta = load_source(local or country["repo"], CACHE) corpus, report = build_corpus(laws, articles, source_meta) out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json" out.parent.mkdir(parents=True, exist_ok=True) @@ -76,9 +146,131 @@ def main(argv: list[str] | None = None) -> int: print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2)) return 0 if args.cmd == "catalog": - from .catalog import COUNTRIES, indexable_countries + from .catalog import all_countries, refresh_from_hub + + countries = refresh_from_hub() if args.refresh else all_countries() + print(json.dumps( + {"n": len(countries), "indexable": len([c for c in countries if c.get("indexable")]), "countries": countries}, + indent=2, + )) + return 0 + if args.cmd == "coverage": + from .coverage import coverage_report, gap_report + + report = gap_report(workers=args.workers) if args.gaps else coverage_report() + print(json.dumps(report, indent=2, default=str)) + return 0 + if args.cmd == "reindex": + from .build import reindex_from_gaps - print(json.dumps({"n": len(COUNTRIES), "indexable": len(indexable_countries()), "countries": COUNTRIES}, indent=2)) + cap = None if args.all or int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows) + results = reindex_from_gaps( + upload=args.upload, + slugs=args.slugs or None, + limit=args.limit, + max_corpus_rows=cap, + skip_vectors=args.skip_vectors, + workers=args.workers, + mode=args.mode, + force=args.force, + all_indexable=args.all, + device=args.device, + ) + print(json.dumps( + [ + { + "country": r.get("country"), + "skipped": r.get("skipped", False), + "out": r.get("out"), + "hub": (r.get("hub") or {}).get("url") if isinstance(r.get("hub"), dict) else r.get("hub"), + "error": r.get("error"), + "kind": (r.get("incremental") or {}).get("kind"), + "n_added": ((r.get("incremental") or {}).get("delta") or {}).get("n_added"), + "n_unchanged": ((r.get("incremental") or {}).get("delta") or {}).get("n_unchanged"), + } + for r in results + ], + indent=2, + default=str, + )) + return 1 if any(r.get("error") for r in results) else 0 + if args.cmd == "verify": + from .catalog import indexable_countries + from .verify import verify_source + + slugs = [] + if args.all: + slugs = [c["slug"] for c in indexable_countries()] + if args.limit: + slugs = slugs[: int(args.limit)] + elif args.source: + slugs = [args.source] + else: + print(json.dumps({"error": "pass --source or --all"}, indent=2)) + return 2 + rows = [] + failed = 0 + for slug in slugs: + try: + row = verify_source(slug) + except Exception as exc: + row = {"slug": slug, "error": str(exc), "verification": {"admitted": False}} + rows.append(row) + if not (row.get("verification") or {}).get("admitted", False): + failed += 1 + from collections import Counter + + units = Counter(str(r.get("unit") or "") for r in rows) + mismatch = [] + latin_blocked = [] + for r in rows: + for chk in (r.get("verification") or {}).get("checks") or []: + if chk.get("id") != "heading_language": + continue + ev = chk.get("evidence") or {} + if chk.get("severity") == "fail" and not chk.get("passed"): + latin_blocked.append(r.get("slug")) + if "review samples" in str(chk.get("message") or ""): + mismatch.append( + { + "slug": r.get("slug"), + "document_language": ev.get("document_language"), + "heading_language": ev.get("heading_language"), + } + ) + print( + json.dumps( + { + "n": len(rows), + "n_failed": failed, + "by_unit": dict(units), + "heading_mismatch": mismatch, + "latin_split_blocked": latin_blocked, + "countries": rows, + }, + indent=2, + default=str, + ) + ) + return 1 if failed else 0 + if args.cmd == "package-raw": + from .build import RELEASES + from .raw_package import default_instruments_dir, package_instruments + + instruments = ( + Path(args.instruments_dir) + if args.instruments_dir + else default_instruments_dir(args.iso or args.slug) + ) + out = Path(args.out) if args.out else RELEASES / "raw-packs" / args.slug + meta = package_instruments( + instruments_dir=instruments, + out=out, + slug=args.slug, + source_dataset=args.source_dataset, + prior_pack=Path(args.prior_pack) if args.prior_pack else None, + ) + print(json.dumps(meta, indent=2, default=str)) return 0 return 1 diff --git a/country_laws_ir/auth.py b/country_laws_ir/auth.py index 36e9336012789878e1428b4c22e1af86092403ae..9b29b3788cf870a87958a35a592bd229f5970195 100644 --- a/country_laws_ir/auth.py +++ b/country_laws_ir/auth.py @@ -1,16 +1,38 @@ -"""Public Hugging Face reads only. This pipeline never loads, stores, or uses a token.""" +"""Hugging Face auth helpers. + +Default reads stay anonymous. Gap scans and JusticeDAO uploads may use the +operator token from the Hugging Face cache file or the environment. The token +is never logged. +""" from __future__ import annotations import os +from pathlib import Path def configure_hf() -> None: - """Force anonymous public Hub access. Tokens are ignored, never printed, never stored.""" - os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1" - # Do not read HF_TOKEN / HUGGING_FACE_HUB_TOKEN. Public datasets need no auth. + """Do not implicitly pick up ambient tokens for anonymous public reads.""" + os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1") def public_token() -> bool: """huggingface_hub `token=False` means anonymous (do not pick up env tokens).""" return False + + +def operator_token() -> str | bool: + """Return a token for authenticated Hub reads/writes, or False if none.""" + for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): + value = (os.environ.get(key) or "").strip() + if value: + return value + path = Path.home() / ".cache" / "huggingface" / "token" + if path.is_file(): + try: + value = path.read_text(encoding="utf-8").strip() + except OSError: + return False + if value: + return value + return False diff --git a/country_laws_ir/build.py b/country_laws_ir/build.py index 2bfbf08482b470e7187cc6584d5bb448b235d5df..768973af97da5ea96deef2b5b7bbbc06909d9ebe 100644 --- a/country_laws_ir/build.py +++ b/country_laws_ir/build.py @@ -1,7 +1,15 @@ -"""End-to-end build: normalize → BM25 → graph → vectors → package (no upload by default).""" +"""End-to-end build: normalize → incremental vectors → BM25 → graph → package. + +Default mode is ``auto``: skip when the endomorphosis source revision is +unchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuild +BM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-in +via ``upload=True``. +""" from __future__ import annotations +import os + import json import pandas as pd @@ -10,25 +18,34 @@ from datetime import datetime, timezone from pathlib import Path from typing import Any -from .bm25 import bm25_neighbors, build_index +from .sparse import export_sparse_graphrag from .mem import MemAbort, checkpoint, log_mem -from .spill import ( - SQLITE_THRESHOLD, - build_bm25_tf_spill, - build_graph_from_neighbor_shards, - neighbors_via_sqlite, - should_use_sqlite, - spill_dir_for, - spill_pickle, -) +from .spill import spill_dir_for, spill_pickle from .package import package_from_spill, package_release from .catalog import get_country, indexable_countries, target_repo -from .graph import build_graph + +from .incremental import ( + fetch_hub_prior, + load_embedding_cache, + load_prior_release, + load_release_vectors_by_cid, + merge_embedding_maps, + plan_rebuild, + save_embedding_cache, +) from .normalize import build_corpus, load_source from .auth import configure_hf -from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors +from .vectors import ( + DIMENSION, + MODEL_NAME, + assemble_embeddings, + embeddings_by_cid, + layout_stub_vectors, + layout_vectors, + select_device, +) -ROOT = Path("/workspace/country-laws-ir") +ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir"))) CACHE = ROOT / "cache" RELEASES = ROOT / "releases" REPORTS = ROOT / "reports" @@ -43,17 +60,122 @@ def _log(msg: str) -> None: def record_progress(event: dict[str, Any]) -> None: event = dict(event) event.setdefault("ts", datetime.now(timezone.utc).isoformat()) - with PROGRESS.open("a", encoding="utf-8") as f: - f.write(json.dumps(event, ensure_ascii=False) + "\n") + PROGRESS.parent.mkdir(parents=True, exist_ok=True) + lock_path = PROGRESS.with_suffix(".lock") + with lock_path.open("a", encoding="utf-8") as lock_fh: + try: + import fcntl + + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) + except Exception: + pass + with PROGRESS.open("a", encoding="utf-8") as f: + f.write(json.dumps(event, ensure_ascii=False) + "\n") + + +def _prior_dir_for( + slug: str, + out: Path, + prior_dir: Path | None, + *, + fetch_hub: bool = True, +) -> Path | None: + if prior_dir is not None: + return Path(prior_dir) + if out.is_dir() and (out / "manifest.json").is_file(): + return out + default = RELEASES / f"ipfs_{slug}_laws_ir" + if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve(): + return default + if not fetch_hub: + return None + hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir") + if hub is not None: + _log(f"using justicedao prior {hub}") + return hub + + +def _encode_vectors( + *, + corpus: pd.DataFrame, + country_slug: str, + prior, + plan, + skip_vectors: bool, + device: str, +) -> tuple[dict[str, Any], str | None, dict[str, Any]]: + import gc + + vector_report: dict[str, Any] = {"status": "stub"} + vector_blocker = None + if skip_vectors: + vectors = layout_stub_vectors(corpus, reason="skip_vectors flag") + return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"} + + cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet" + prior_by_cid = {} + if plan.reuse_embeddings: + prior_by_cid = merge_embedding_maps( + load_embedding_cache(cid_cache_path), + None if prior is None else load_release_vectors_by_cid(prior.directory), + ) + _log(f"embedding cache reused_cids={len(prior_by_cid)}") + try: + positional = CACHE / "embeddings" / f"{country_slug}.npy" + resolved, fallback = select_device(device) + if fallback: + _log(f"embedding device fallback requested={device} using={resolved}") + embeddings, vector_report = assemble_embeddings( + corpus, + prior_by_cid, + encode_missing=True, + device=resolved, + checkpoint_path=str(positional), + ) + if ( + vector_report.get("status") in {"stub_missing_encoder", "incomplete"} + and not int(vector_report.get("n_reused") or 0) + ): + vector_blocker = vector_report.get("reason") or vector_report.get("status") + vectors = layout_stub_vectors(corpus, reason=str(vector_blocker)) + return vectors, vector_blocker, vector_report + vectors = layout_vectors(corpus, embeddings) + if int(vector_report.get("n_reused") or 0) and vector_report.get("status") != "reused": + vectors["stats"]["status"] = "partial" + vectors["stats"]["n_reused"] = int(vector_report.get("n_reused") or 0) + vectors["stats"]["n_missing"] = int(vector_report.get("n_missing") or 0) + vector_blocker = vector_report.get("reason") or vector_report.get("status") + save_embedding_cache( + cid_cache_path, + merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)), + model_name=MODEL_NAME, + dimension=DIMENSION, + ) + del embeddings + gc.collect() + _log( + f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} " + f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}" + ) + return vectors, None, vector_report + except Exception as exc: + vector_blocker = f"embedding_failed: {exc}" + _log(f"vector embedding failed; writing stub ({exc})") + vectors = layout_stub_vectors(corpus, reason=vector_blocker) + return vectors, vector_blocker, {"status": "failed", "reason": str(exc)} def build_country( source: str, out: Path | None = None, upload: bool = False, - device: str = "cpu", + device: str = "cuda", neighbor_k: int = 8, skip_vectors: bool = False, + mode: str = "auto", + force: bool = False, + prior_dir: Path | None = None, + fetch_hub_prior_ir: bool = True, ) -> dict[str, Any]: country = get_country(source) if not country.get("indexable", True): @@ -69,7 +191,9 @@ def build_country( ) else None ) - _log(f"build start {repo} -> {out} (upload={upload}) local={local_dir}") + _log( + f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}" + ) configure_hf() CACHE.mkdir(parents=True, exist_ok=True) REPORTS.mkdir(parents=True, exist_ok=True) @@ -78,6 +202,39 @@ def build_country( f"source loaded laws={source_meta['n_laws_source']} " f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}" ) + prior = load_prior_release( + _prior_dir_for( + country["slug"], + out, + prior_dir, + fetch_hub=fetch_hub_prior_ir, + ) + ) + plan = plan_rebuild( + mode=mode, + source_meta=source_meta, + prior=prior, + force=force, + rebuild_stub_vectors=not skip_vectors, + ) + if plan.skip_build: + _log(f"skip unchanged {country['slug']} rev={plan.source_revision}") + result = { + "country": country["slug"], + "source": repo, + "source_revision": source_meta["source_revision"], + "out": str(out), + "target_hub_id": target_repo(country["slug"]), + "skipped": True, + "incremental": plan.to_dict(), + "normalization": {"n_out": plan.delta.current_count if plan.delta else 0}, + "vector_blocker": None, + "neighbor_via": None, + "schema_version": "country-laws-ir-graphrag/v1", + } + record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}}) + return result + corpus, norm_report = build_corpus(laws, articles, source_meta) report_path = REPORTS / f"{country['slug']}_normalization.json" report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") @@ -90,9 +247,30 @@ def build_country( ) if corpus.empty: raise RuntimeError("Normalized corpus is empty; refusing to package") + verdict = (norm_report or {}).get("verification") or {} + if verdict.get("blocks_graphrag") and not force: + from .verify import NormalizationAdmissionError + + raise NormalizationAdmissionError( + f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}" + ) import gc + plan = plan_rebuild( + mode=mode, + source_meta=source_meta, + prior=prior, + current_corpus=corpus, + force=force, + rebuild_stub_vectors=not skip_vectors, + ) + _log( + f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} " + f"added={0 if plan.delta is None else plan.delta.n_added} " + f"removed={0 if plan.delta is None else plan.delta.n_removed}" + ) + n_docs = len(corpus) spill = spill_dir_for(country["slug"], CACHE) spill.mkdir(parents=True, exist_ok=True) @@ -100,81 +278,63 @@ def build_country( corpus.to_parquet(corpus_ckpt, index=False) checkpoint("after_normalize", log=_log) - vector_blocker = None - if skip_vectors: - vectors = layout_stub_vectors(corpus, reason="skip_vectors flag") - vector_blocker = "skip_vectors" - spill_pickle(spill / "vectors.pkl", vectors) - del vectors - gc.collect() - elif embeddings_available(): - try: - ckpt = CACHE / "embeddings" / f"{country['slug']}.npy" - _log(f"vectors encode start n={n_docs} checkpoint={ckpt}") - embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt)) - vectors = layout_vectors(corpus, embeddings) - _log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}") - spill_pickle(spill / "vectors.pkl", vectors) - del embeddings, vectors - gc.collect() - checkpoint("vectors_spilled", log=_log) - except Exception as exc: - vector_blocker = f"embedding_failed: {exc}" - _log(f"vector embedding failed; writing stub ({exc})") - vectors = layout_stub_vectors(corpus, reason=vector_blocker) - spill_pickle(spill / "vectors.pkl", vectors) - del vectors - gc.collect() - else: - vector_blocker = "sentence-transformers/torch unavailable" - _log(f"vectors stub: {vector_blocker}") - vectors = layout_stub_vectors(corpus, reason=vector_blocker) - spill_pickle(spill / "vectors.pkl", vectors) - del vectors - gc.collect() + vectors, vector_blocker, vector_report = _encode_vectors( + corpus=corpus, + country_slug=country["slug"], + prior=prior, + plan=plan, + skip_vectors=skip_vectors, + device=device, + ) + spill_pickle(spill / "vectors.pkl", vectors) + del vectors + gc.collect() + checkpoint("vectors_spilled", log=_log) + extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}} - use_sqlite = should_use_sqlite(n_docs) - neighbor_via = "stock" - if use_sqlite: - _log(f"sqlite neighbors path n={n_docs} (>= {SQLITE_THRESHOLD}) spill={spill}") - # Free corpus body for neighbor stream — reload later for graph - del corpus - gc.collect() - neighbors_via_sqlite(corpus_ckpt, spill, n_docs, k=neighbor_k, log=_log) - neighbor_via = "sqlite_fts" - bm25_info = build_bm25_tf_spill(corpus_ckpt, spill, n_docs, log=_log) - corpus = pd.read_parquet(corpus_ckpt) - graph = build_graph_from_neighbor_shards(corpus, spill, log=_log) - spill_pickle(spill / "graph.pkl", graph) - del graph, corpus - gc.collect() - checkpoint("graph_spilled", log=_log) - code_root = Path(__file__).resolve().parent.parent - manifest = package_from_spill( - out, spill, corpus_ckpt, source_meta, country, code_root, - normalization_report=norm_report, expected_rows=n_docs, - ) - _log(f"packaged sequential via={neighbor_via} {out}") - else: - bm25 = build_index(corpus) - _log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}") - _log(f"bm25 neighbors start n={n_docs} k={neighbor_k}") - neighbors = bm25_neighbors(bm25, k=neighbor_k) - _log("bm25 neighbors done") - graph = build_graph(corpus, neighbors) - del neighbors - gc.collect() - _log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}") - with open(spill / "vectors.pkl", "rb") as _vf: - import pickle as _pickle - vectors = _pickle.load(_vf) - code_root = Path(__file__).resolve().parent.parent - manifest = package_release( - out, corpus, bm25, graph, vectors, source_meta, country, code_root, - normalization_report=norm_report, - ) - del corpus, bm25, graph, vectors - gc.collect() + neighbor_via = "hf_graphrag" + if out.exists(): + import shutil as _shutil + + _shutil.rmtree(out) + out.mkdir(parents=True, exist_ok=True) + _log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}") + sparse_report = export_sparse_graphrag(corpus, out) + extra_manifest["sparse"] = sparse_report + with open(spill / "vectors.pkl", "rb") as _vf: + import pickle as _pickle + + vectors = _pickle.load(_vf) + dummy_bm25 = { + "documents": pd.DataFrame(), + "postings": pd.DataFrame(), + "stats": (sparse_report.get("bm25") or {}).get("bm25") + or (sparse_report.get("bm25") or {}), + } + dummy_graph = { + "nodes": pd.DataFrame(), + "edges": pd.DataFrame(), + "incoming": pd.DataFrame(), + "outgoing": pd.DataFrame(), + "stats": sparse_report.get("graph") or {}, + } + code_root = Path(__file__).resolve().parent.parent + manifest = package_release( + out, + corpus, + dummy_bm25, + dummy_graph, + vectors, + source_meta, + country, + code_root, + normalization_report=norm_report, + extra_manifest=extra_manifest, + wipe=False, + skip_bm25_graph=True, + ) + del corpus, vectors + gc.collect() _log(f"packaged {out}") result = { "country": country["slug"], @@ -187,6 +347,8 @@ def build_country( "vector_blocker": vector_blocker, "neighbor_via": neighbor_via, "schema_version": manifest["schema_version"], + "skipped": False, + "incremental": extra_manifest["incremental"], } if upload: from .upload import upload_release @@ -204,25 +366,32 @@ def batch( slugs: list[str] | None = None, upload: bool = False, skip_done: bool = True, + mode: str = "auto", + force: bool = False, + skip_vectors: bool = False, ) -> list[dict[str, Any]]: - done = set() - if skip_done and PROGRESS.exists(): - for line in PROGRESS.read_text(encoding="utf-8").splitlines(): - if not line.strip(): - continue - rec = json.loads(line) - if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"): - done.add(rec["country"]) + """Build every indexable country. Unchanged Hub revisions are skipped in auto mode. + + ``skip_done`` is kept for compatibility: it no longer skips a country whose + source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to + rebuild regardless of CID overlap. + """ targets = slugs or [c["slug"] for c in indexable_countries()] if "malta" in targets: targets = ["malta"] + [s for s in targets if s != "malta"] results = [] + rebuild_force = force or not skip_done for slug in targets: - if skip_done and slug in done: - _log(f"skip already done {slug}") - continue try: - results.append(build_country(slug, upload=upload)) + results.append( + build_country( + slug, + upload=upload, + mode=mode, + force=rebuild_force, + skip_vectors=skip_vectors, + ) + ) except Exception as exc: _log(f"FAILED {slug}: {exc}") record_progress( @@ -235,3 +404,98 @@ def batch( ) continue return results + + +def reindex_from_gaps( + *, + upload: bool = False, + slugs: list[str] | None = None, + limit: int | None = None, + max_corpus_rows: int | None = 20_000, + skip_vectors: bool = False, + workers: int = 4, + mode: str = "auto", + force: bool = False, + all_indexable: bool = False, + device: str = "cuda", +) -> list[dict[str, Any]]: + """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country. + + Default cap skips huge corpora (Finland, Dominican Republic). Pass + ``max_corpus_rows=None`` to include them. + """ + from .catalog import indexable_countries + from .coverage import gap_report + + if slugs is None: + if all_indexable: + rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()] + _log(f"reindex all indexable n={len(rows)}") + else: + report = gap_report(workers=workers) + rows = [c for c in report["countries"] if c.get("rebuild")] + _log( + f"reindex targets n={len(rows)} " + f"(from scan rebuild={len(report.get('rebuild') or [])})" + ) + rows.sort(key=lambda r: int(r.get("corpus_rows") or 0)) + if max_corpus_rows is not None: + rows = [ + r + for r in rows + if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows) + ] + if limit is not None: + rows = rows[: int(limit)] + slugs = [str(r["slug"]) for r in rows] + kwargs = { + "upload": upload, + "mode": mode, + "force": force, + "skip_vectors": skip_vectors, + "fetch_hub_prior_ir": True, + "device": device, + } + n_workers = max(1, int(workers or 1)) + _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda") + import multiprocessing as mp + from concurrent.futures import ProcessPoolExecutor, as_completed + + try: + mp.set_start_method("spawn", force=False) + except RuntimeError: + pass + + results = [None] * len(slugs) + with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool: + futs = { + pool.submit(_reindex_one_country, (slug, kwargs)): i + for i, slug in enumerate(slugs) + } + for fut in as_completed(futs): + idx = futs[fut] + slug = slugs[idx] + try: + results[idx] = fut.result() + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + results[idx] = {"country": slug, "skipped": False, "error": str(exc)} + return [r for r in results if r is not None] + + +def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]: + slug, kwargs = item + _log(f"reindex start {slug}") + try: + return build_country(slug, **kwargs) + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + record_progress( + { + "event": "failed", + "country": slug, + "error": str(exc), + "traceback": traceback.format_exc(), + } + ) + return {"country": slug, "skipped": False, "error": str(exc)} diff --git a/country_laws_ir/catalog.py b/country_laws_ir/catalog.py index d4352954caaa28b441485d76ce2b8a8f5ae92ec8..848143231166ea442bbc43d0c3d6bb11b4603f15 100644 --- a/country_laws_ir/catalog.py +++ b/country_laws_ir/catalog.py @@ -2,15 +2,39 @@ Belgium, Portugal, and Lithuania are incomplete Wayback harvests and are excluded from indexing. american_municipal_law is out of scope. + +The static ``COUNTRIES`` list is the fail-closed baseline. ``refresh_from_hub`` +persists a sidecar cache of newly listed Hub datasets so incremental scrapes +of additional jurisdictions are indexable without a code change. """ from __future__ import annotations +import json +import os +from pathlib import Path from typing import Any -EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania"} +EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania", "ghana"} EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS} +_SKIP_REASONS = { + "belgium": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)", + "portugal": "incomplete Wayback harvest (Diário da República archive shard)", + "lithuania": "incomplete Wayback harvest (e-TAR archive shard)", + "ghana": "thin scrape; Act PDF path blocked by robots", +} + + +def catalog_cache_path() -> Path: + root = Path( + os.environ.get( + "COUNTRY_LAWS_IR_ROOT", + str(Path.home() / ".ipfs_datasets" / "country-laws-ir"), + ) + ) + return root / "catalog_cache.json" + # Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`. COUNTRIES: list[dict[str, Any]] = [ {"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True}, @@ -88,6 +112,54 @@ COUNTRIES: list[dict[str, Any]] = [ ] +def load_cached_countries() -> list[dict[str, Any]]: + path = catalog_cache_path() + if not path.is_file(): + return [] + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return [] + rows = payload.get("countries") if isinstance(payload, dict) else payload + if not isinstance(rows, list): + return [] + out: list[dict[str, Any]] = [] + for row in rows: + if isinstance(row, dict) and row.get("slug") and row.get("repo"): + out.append(dict(row)) + return out + + +def persist_catalog(countries: list[dict[str, Any]], path: Path | None = None) -> Path: + dest = path or catalog_cache_path() + dest.parent.mkdir(parents=True, exist_ok=True) + payload = { + "n": len(countries), + "indexable": sum(1 for c in countries if c.get("indexable")), + "countries": countries, + } + dest.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + return dest + + +def merge_country_rows( + baseline: list[dict[str, Any]], + extra: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """Static catalog wins on slug; Hub extras fill gaps.""" + by_slug = {str(row["slug"]): dict(row) for row in baseline if row.get("slug")} + for row in extra: + slug = str(row.get("slug") or "") + if not slug or slug in by_slug: + continue + by_slug[slug] = dict(row) + return [by_slug[k] for k in sorted(by_slug)] + + +def all_countries() -> list[dict[str, Any]]: + return merge_country_rows(COUNTRIES, load_cached_countries()) + + def get_country(source: str) -> dict[str, Any]: source = source.strip() # Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json) @@ -133,7 +205,7 @@ def get_country(source: str) -> dict[str, Any]: if "/" in source: slug = source.rsplit("/", 1)[-1] slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir") - for row in COUNTRIES: + for row in all_countries(): if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source): return dict(row) if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"): @@ -143,20 +215,20 @@ def get_country(source: str) -> dict[str, Any]: "repo": source, "name": inferred.replace("_", " ").title(), "indexable": inferred not in EXCLUDED_SLUGS, - "skip_reason": "incomplete Wayback harvest" if inferred in EXCLUDED_SLUGS else None, + "skip_reason": _SKIP_REASONS.get(inferred), } raise KeyError(f"Unknown country-law source: {source}") def indexable_countries() -> list[dict[str, Any]]: - return [c for c in COUNTRIES if c.get("indexable")] + return [c for c in all_countries() if c.get("indexable")] def target_repo(slug: str) -> str: return f"justicedao/ipfs_{slug}_laws_ir" -def refresh_from_hub() -> list[dict[str, Any]]: +def refresh_from_hub(*, persist: bool = True) -> list[dict[str, Any]]: """Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets.""" from huggingface_hub import HfApi @@ -175,9 +247,10 @@ def refresh_from_hub() -> list[dict[str, Any]]: "repo": ds_id, "name": slug.replace("_", " ").title(), "indexable": slug not in EXCLUDED_SLUGS, - "skip_reason": ( - "incomplete Wayback harvest" if slug in EXCLUDED_SLUGS else None - ), + "skip_reason": _SKIP_REASONS.get(slug), }) found.sort(key=lambda r: r["slug"]) - return found + merged = merge_country_rows(COUNTRIES, found) + if persist: + persist_catalog(merged) + return merged diff --git a/country_laws_ir/cidutil.py b/country_laws_ir/cidutil.py index e9ace7c381c76685dbdb4bab8a75791711e8e27e..f6e13daa170a5b874d50d4539ad1817565fdd0e9 100644 --- a/country_laws_ir/cidutil.py +++ b/country_laws_ir/cidutil.py @@ -59,6 +59,27 @@ def cid_v1_raw_sha256(data: bytes) -> str: return "b" + _b32encode(cid_bytes) +def sha256_key_to_cidv1(value: str) -> str: + """Turn a bare/prefixed SHA-256 routing key into ``bafkrei…`` CIDv1. + + GraphRAG locators must not use hex digests as ``entry_cid`` / ``node_cid``. + """ + + text = str(value or "").strip() + if text.startswith("bafkrei"): + return text + hex_part = text[7:71] if text.lower().startswith("sha256:") else text[:64] + rest = text[71:] if text.lower().startswith("sha256:") else text[64:] + if len(hex_part) != 64: + return text + try: + digest = bytes.fromhex(hex_part) + except ValueError: + return text + cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest + return "b" + _b32encode(cid_bytes) + rest + + def cid_of_json(obj: Any) -> str: return cid_v1_raw_sha256(canonical_json_bytes(obj)) diff --git a/country_laws_ir/coverage.py b/country_laws_ir/coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..380d7fda93c8d35799efb1997f13847eec6ea3aa --- /dev/null +++ b/country_laws_ir/coverage.py @@ -0,0 +1,455 @@ +"""Compare endomorphosis raw sources against justicedao GraphRAG releases. + +Gap kinds +--------- +* missing — no JusticeDAO IR (and no local pack) +* unpublished — local IR exists, Hub IR does not +* stale — Hub/local IR source revision does not match current endomorphosis SHA +* incomplete — missing corpus/BM25/graph, empty corpus, or source has no laws +* stub_vectors — IR is otherwise current but embeddings were stubbed +""" + +from __future__ import annotations + +import json +import time +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path +from typing import Any, Mapping + +from .catalog import EXCLUDED_SLUGS, all_countries, target_repo + +ALIAS_TO_CANONICAL = { + "dominican_republic": "dominicanrepublic", + "el_salvador": "elsalvador", + "north_korea": "northkorea", + "papua_new_guinea": "papuanewguinea", + "san_marino": "sanmarino", + "trinidad_and_tobago": "trinidad", +} + + +def _slug_from_source(dataset_id: str) -> str | None: + if not dataset_id.startswith("endomorphosis/ipfs_") or not dataset_id.endswith("_laws"): + return None + return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws") + + +def _slug_from_ir(dataset_id: str) -> str | None: + if not dataset_id.startswith("justicedao/ipfs_") or not dataset_id.endswith("_laws_ir"): + return None + return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws_ir") + + +def canonical_slug(slug: str) -> str: + return ALIAS_TO_CANONICAL.get(slug, slug) + + +def list_hub_slugs(*, author: str, kind: str) -> list[str]: + from huggingface_hub import HfApi + + from .auth import configure_hf, operator_token, public_token + + configure_hf() + token = operator_token() or public_token() + api = HfApi(token=token) + out: list[str] = [] + for ds in api.list_datasets(author=author): + slug = _slug_from_source(ds.id) if kind == "source" else _slug_from_ir(ds.id) + if slug: + out.append(slug) + return sorted(set(out)) + + +def local_release_slugs(releases_dir: Path) -> list[str]: + if not releases_dir.is_dir(): + return [] + found: list[str] = [] + for path in sorted(releases_dir.glob("ipfs_*_laws_ir")): + if (path / "manifest.json").is_file(): + slug = path.name.removeprefix("ipfs_").removesuffix("_laws_ir") + found.append(slug) + return found + + +IR_FAMILY_PREFIXES = ( + ("data/corpus/", "ir_missing_corpus"), + ("data/bm25/", "ir_missing_bm25"), + ("data/graph/", "ir_missing_graph"), +) +STUB_VECTOR_STATUSES = {"stub", "stub_missing_encoder", "incomplete"} +TINY_LAWS_BYTES = 1024 + + +def classify_gap( + *, + excluded: bool = False, + alias: bool = False, + source_has_laws: bool = True, + source_laws_bytes: int | None = None, + source_revision: str | None = None, + ir_files: list[str] | None = None, + ir_source_revision: str | None = None, + ir_corpus_rows: int | None = None, + vector_status: str | None = None, + local_only: bool = False, + local_source_revision: str | None = None, +) -> dict[str, Any]: + """Pure classifier for missing / stale / incomplete country IR.""" + issues: list[str] = [] + if alias: + return {"status": "alias", "issues": issues, "rebuild": False, "publish": False} + if excluded: + return {"status": "excluded", "issues": issues, "rebuild": False, "publish": False} + + if not source_has_laws: + issues.append("source_missing_laws") + if ( + source_laws_bytes is not None + and source_laws_bytes >= 0 + and source_laws_bytes < TINY_LAWS_BYTES + ): + issues.append("source_laws_tiny") + + if ir_files is None: + issues.append("missing_ir") + else: + names = set(ir_files) + if "manifest.json" not in names: + issues.append("ir_missing_manifest") + for prefix, issue in IR_FAMILY_PREFIXES: + if not any(name.startswith(prefix) for name in names): + issues.append(issue) + if ir_corpus_rows is not None and int(ir_corpus_rows) <= 0: + issues.append("ir_empty_corpus") + if ( + source_revision + and ir_source_revision + and str(source_revision) != str(ir_source_revision) + ): + issues.append("stale_source_revision") + if vector_status in STUB_VECTOR_STATUSES: + issues.append("ir_stub_vectors") + + structural = { + "source_missing_laws", + "source_laws_tiny", + "ir_missing_manifest", + "ir_missing_corpus", + "ir_missing_bm25", + "ir_missing_graph", + "ir_empty_corpus", + } + issue_set = set(issues) + if "missing_ir" in issue_set: + status = "unpublished" if local_only else "missing" + elif "stale_source_revision" in issue_set: + status = "stale" + elif issue_set & structural: + status = "incomplete" + elif issue_set == {"ir_stub_vectors"}: + status = "stub_vectors" + elif not issues: + status = "current" + else: + status = "incomplete" + + local_current = bool( + source_revision + and local_source_revision + and str(source_revision) == str(local_source_revision) + ) + rebuild = ( + status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} + and (not local_current or status == "stub_vectors") + ) + publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and ( + "source_missing_laws" not in issues + ) + return { + "status": status, + "issues": issues, + "rebuild": rebuild, + "publish": publish, + } + + +def _ir_source_revision(manifest: Mapping[str, Any] | None) -> str | None: + if not manifest: + return None + pinned = manifest.get("dataset_revision") or (manifest.get("source") or {}).get( + "source_revision" + ) + text = str(pinned or "").strip() + return text or None + + +def _vector_status(manifest: Mapping[str, Any] | None) -> str | None: + if not manifest: + return None + vector = manifest.get("vector") or {} + if isinstance(vector, dict) and vector.get("status"): + return str(vector.get("status")) + incremental = manifest.get("incremental") or {} + nested = incremental.get("vectors") if isinstance(incremental, dict) else None + if isinstance(nested, dict) and nested.get("status"): + return str(nested.get("status")) + if isinstance(vector, dict) and vector.get("stub"): + return "stub" + return None + + +def load_local_manifest(release_dir: Path) -> dict[str, Any]: + path = Path(release_dir) / "manifest.json" + if not path.is_file(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return {} + return data if isinstance(data, dict) else {} + + +def _sibling_map(info: Any) -> dict[str, int | None]: + out: dict[str, int | None] = {} + for sib in getattr(info, "siblings", None) or []: + name = str(getattr(sib, "rfilename", "") or "") + if not name: + continue + size = getattr(sib, "size", None) + try: + out[name] = int(size) if size is not None else None # type: ignore[assignment] + except (TypeError, ValueError): + out[name] = None # type: ignore[assignment] + return out + + +def _inspect_source(slug: str, cache_dir: Path | None = None) -> dict[str, Any]: + from huggingface_hub import dataset_info + + from .auth import configure_hf, operator_token, public_token + + repo = f"endomorphosis/ipfs_{slug}_laws" + configure_hf() + info = dataset_info(repo, token=operator_token() or public_token()) + files = _sibling_map(info) + laws_file = next( + (name for name in ("data/laws.parquet", "laws.parquet") if name in files), + None, + ) + arts_file = next( + (name for name in ("data/articles.parquet", "articles.parquet") if name in files), + None, + ) + return { + "repo": repo, + "revision": getattr(info, "sha", None), + "files": sorted(files), + "has_laws": laws_file is not None, + "has_articles": arts_file is not None, + "laws_bytes": files.get(laws_file) if laws_file else None, + "articles_bytes": files.get(arts_file) if arts_file else None, + } + + +def _inspect_ir(slug: str, cache_dir: Path) -> dict[str, Any] | None: + from huggingface_hub import HfApi, dataset_info, hf_hub_download + from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError + + from .auth import configure_hf, operator_token, public_token + + repo = target_repo(slug) + configure_hf() + token = operator_token() or public_token() + try: + info = dataset_info(repo, token=token) + except RepositoryNotFoundError: + return None + files = _sibling_map(info) + if len(files) < 8: + try: + listed = HfApi(token=token).list_repo_files(repo_id=repo, repo_type="dataset") + for name in listed: + files.setdefault(str(name), None) + except Exception: + pass + manifest: dict[str, Any] = {} + if "manifest.json" in files: + try: + path = hf_hub_download( + repo_id=repo, + filename="manifest.json", + repo_type="dataset", + token=token, + cache_dir=str(cache_dir / "hf"), + ) + payload = json.loads(Path(path).read_text(encoding="utf-8")) + if isinstance(payload, dict): + manifest = payload + except (EntryNotFoundError, OSError, json.JSONDecodeError): + manifest = {} + counts = manifest.get("counts") if isinstance(manifest.get("counts"), dict) else {} + return { + "repo": repo, + "hub_revision": getattr(info, "sha", None), + "files": sorted(files), + "manifest": manifest, + "source_revision": _ir_source_revision(manifest), + "corpus_rows": counts.get("corpus_rows"), + "vector_status": _vector_status(manifest), + } + + +def gap_report( + releases_dir: Path | None = None, + *, + slugs: list[str] | None = None, + workers: int = 8, +) -> dict[str, Any]: + """Live Hub scan: missing, stale, incomplete, and unpublished country IR.""" + from .build import CACHE, RELEASES + + sources = slugs or [ + s + for s in list_hub_slugs(author="endomorphosis", kind="source") + if s not in ALIAS_TO_CANONICAL + ] + hub_ir = set(list_hub_slugs(author="justicedao", kind="ir")) + local_dir = Path(releases_dir) if releases_dir else RELEASES + local_ir = set(local_release_slugs(local_dir)) + cache_dir = CACHE + cache_dir.mkdir(parents=True, exist_ok=True) + + rows: list[dict[str, Any]] = [] + + def _one(slug: str) -> dict[str, Any]: + last_exc: Exception | None = None + for attempt in range(4): + try: + source = _inspect_source(slug) + ir = _inspect_ir(slug, cache_dir) if slug in hub_ir else None + break + except Exception as exc: + last_exc = exc + name = type(exc).__name__ + msg = str(exc) + if "429" in msg or "rate limit" in msg.lower(): + time.sleep(min(45, 3 ** attempt * 2)) + continue + raise + else: + raise last_exc or RuntimeError(f"scan failed for {slug}") + local_manifest = load_local_manifest(local_dir / f"ipfs_{slug}_laws_ir") + local_rev = _ir_source_revision(local_manifest) if local_manifest else None + classified = classify_gap( + excluded=slug in EXCLUDED_SLUGS, + alias=False, + source_has_laws=bool(source.get("has_laws")), + source_laws_bytes=source.get("laws_bytes"), + source_revision=source.get("revision"), + ir_files=None if ir is None else ir.get("files"), + ir_source_revision=(ir or {}).get("source_revision") or local_rev, + ir_corpus_rows=(ir or {}).get("corpus_rows") + if ir is not None + else (local_manifest.get("counts") or {}).get("corpus_rows") + if local_manifest + else None, + vector_status=(ir or {}).get("vector_status") + or _vector_status(local_manifest), + local_only=slug in local_ir and slug not in hub_ir, + local_source_revision=local_rev, + ) + return { + "slug": slug, + "source": source.get("repo"), + "target": target_repo(slug), + "source_revision": source.get("revision"), + "ir_source_revision": (ir or {}).get("source_revision"), + "local_source_revision": local_rev, + "has_hub_ir": ir is not None, + "has_local_ir": slug in local_ir, + "source_has_articles": source.get("has_articles"), + "source_laws_bytes": source.get("laws_bytes"), + "corpus_rows": (ir or {}).get("corpus_rows") + if ir is not None + else (local_manifest.get("counts") or {}).get("corpus_rows") + if local_manifest + else None, + "vector_status": (ir or {}).get("vector_status") + or _vector_status(local_manifest), + **classified, + } + + workers = max(1, min(int(workers), 16)) + with ThreadPoolExecutor(max_workers=workers) as pool: + futs = {pool.submit(_one, slug): slug for slug in sources} + for fut in as_completed(futs): + slug = futs[fut] + try: + rows.append(fut.result()) + except Exception as exc: + rows.append( + { + "slug": slug, + "source": f"endomorphosis/ipfs_{slug}_laws", + "target": target_repo(slug), + "status": "incomplete", + "issues": [f"scan_error:{type(exc).__name__}"], + "rebuild": False, + "publish": False, + "error": str(exc), + } + ) + rows.sort(key=lambda r: str(r.get("slug"))) + by_status: dict[str, list[str]] = {} + for row in rows: + by_status.setdefault(str(row.get("status")), []).append(str(row.get("slug"))) + return { + "n": len(rows), + "by_status": {k: sorted(v) for k, v in sorted(by_status.items())}, + "counts": {k: len(v) for k, v in sorted(by_status.items())}, + "rebuild": [r["slug"] for r in rows if r.get("rebuild")], + "publish": [r["slug"] for r in rows if r.get("publish")], + "countries": rows, + } + + +def coverage_report(releases_dir: Path | None = None) -> dict[str, Any]: + from .build import RELEASES + + sources = list_hub_slugs(author="endomorphosis", kind="source") + hub_ir = list_hub_slugs(author="justicedao", kind="ir") + local_ir = local_release_slugs(Path(releases_dir) if releases_dir else RELEASES) + hub_ir_canon = {canonical_slug(s) for s in hub_ir} + local_ir_canon = {canonical_slug(s) for s in local_ir} + missing_hub: list[dict[str, Any]] = [] + missing_local: list[dict[str, Any]] = [] + excluded: list[str] = [] + aliases: list[str] = [] + for slug in sources: + if slug in ALIAS_TO_CANONICAL: + aliases.append(slug) + continue + if slug in EXCLUDED_SLUGS: + excluded.append(slug) + continue + row = { + "slug": slug, + "source": f"endomorphosis/ipfs_{slug}_laws", + "target": target_repo(slug), + } + if slug not in hub_ir_canon: + missing_hub.append(row) + if slug not in local_ir_canon and slug not in hub_ir_canon: + missing_local.append(row) + return { + "n_sources": len(sources), + "n_hub_ir": len(hub_ir), + "n_local_ir": len(local_ir), + "n_catalog": len(all_countries()), + "excluded": excluded, + "alias_sources": aliases, + "missing_justicedao": missing_hub, + "missing_local_and_hub": missing_local, + "local_only": sorted(local_ir_canon - hub_ir_canon), + } diff --git a/country_laws_ir/duckdb_store.py b/country_laws_ir/duckdb_store.py new file mode 100644 index 0000000000000000000000000000000000000000..743473eea8b69f71eb222568bcadf0549160db49 --- /dev/null +++ b/country_laws_ir/duckdb_store.py @@ -0,0 +1,408 @@ +"""DuckDB views over country-laws sparse GraphRAG parquet shards. + +Published artifacts are ZSTD parquet (SkillCenter / publicus-ir family). +Query and large-corpus neighbor generation read those shards through DuckDB +instead of loading them into pandas or SQLite. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pandas as pd + +K1 = 1.2 +B = 0.75 +TITLE_WEIGHT = 5.0 +BODY_WEIGHT = 1.0 +MAX_QUERY_TERMS = 64 + +VIEWS = ( + ("corpus", "data/corpus/*.parquet"), + ("bm25_documents", "data/bm25/documents/*.parquet"), + ("bm25_postings", "data/bm25/postings/*.parquet"), + ("graph_nodes", "data/graph/nodes/*.parquet"), + ("graph_edges", "data/graph/edges/*.parquet"), + # Shared hf_graphrag layout (US Code / state laws / FR). + ("graph_in", "data/graph/adjacency/in/*.parquet"), + ("graph_out", "data/graph/adjacency/out/*.parquet"), + # Legacy country-laws-ir layout still on some Hub packs. + ("graph_incoming", "data/graph/adjacency/incoming/*.parquet"), + ("graph_outgoing", "data/graph/adjacency/outgoing/*.parquet"), + ("vectors", "data/vectors/*.parquet"), +) + + +class DuckDBStoreError(RuntimeError): + """Raised when a parquet/DuckDB sparse index cannot be opened.""" + + +def _require_duckdb(): + try: + import duckdb # type: ignore + except ImportError as exc: + raise DuckDBStoreError("duckdb is required for parquet sparse GraphRAG query") from exc + return duckdb + + +def parquet_glob(root: Path, pattern: str) -> str: + return str(Path(root) / pattern) + + +def connect_release(root: Path, *, database: str = ":memory:"): + """Open a DuckDB connection with views over parquet shards.""" + duckdb = _require_duckdb() + root = Path(root) + if not (root / "manifest.json").is_file(): + raise DuckDBStoreError(f"release missing manifest.json: {root}") + con = duckdb.connect(database) + for name, pattern in VIEWS: + glob = parquet_glob(root, pattern) + if list(root.glob(pattern)): + escaped = glob.replace("'", "''") + con.execute( + f"CREATE OR REPLACE VIEW {name} AS SELECT * FROM read_parquet('{escaped}')" + ) + return con + + +def load_manifest(root: Path) -> dict[str, Any]: + return json.loads((Path(root) / "manifest.json").read_text(encoding="utf-8")) + + +def tokenize(text: str) -> list[str]: + import re + import unicodedata + + if not text: + return [] + nfkd = unicodedata.normalize("NFKD", text) + folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower() + return re.findall(r"[0-9A-Za-z]+", folded) + + +def bm25_search(root: Path, query: str, top_k: int = 10) -> list[dict[str, Any]]: + """Okapi BM25 over parquet posting shards via DuckDB UNNEST.""" + terms = tokenize(query)[:MAX_QUERY_TERMS] + if not terms: + return [] + manifest = load_manifest(root) + avgdl = float((manifest.get("bm25") or {}).get("average_document_length") or 1.0) or 1.0 + con = connect_release(root) + try: + tables = { + r[0] + for r in con.execute( + "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'" + ).fetchall() + } + if "bm25_postings" not in tables or "bm25_documents" not in tables: + raise DuckDBStoreError("release is missing BM25 parquet shards") + placeholders = ", ".join(["?"] * len(terms)) + sql = f""" + WITH exploded AS ( + SELECT + unnest(document_indices) AS document_index, + unnest(title_frequencies) AS title_tf, + unnest(body_frequencies) AS body_tf, + unnest(document_lengths) AS dl, + idf + FROM bm25_postings + WHERE term IN ({placeholders}) + ), + scored AS ( + SELECT + document_index, + SUM( + idf * ( + ( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf ) + * ({K1} + 1.0) + ) / ( + ( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf ) + + {K1} * (1.0 - {B} + {B} * (dl / {avgdl})) + ) + ) AS score + FROM exploded + GROUP BY document_index + ) + SELECT + s.document_index, + s.score, + d.entry_cid, + d.title, + d.record_type + FROM scored s + JOIN bm25_documents d USING (document_index) + ORDER BY s.score DESC, s.document_index + LIMIT ? + """ + rows = con.execute(sql, [*terms, int(top_k)]).fetchall() + cols = [ + "document_index", + "score", + "entry_cid", + "title", + "record_type", + ] + return [dict(zip(cols, row)) for row in rows] + finally: + con.close() + + +def graph_neighbors( + root: Path, + node_cid: str, + *, + direction: str = "both", + limit: int = 25, +) -> list[dict[str, Any]]: + """Adjacency lookup over parquet shards via DuckDB.""" + aliases = { + "both": ("in", "out", "incoming", "outgoing"), + "in": ("in", "incoming"), + "out": ("out", "outgoing"), + "incoming": ("in", "incoming"), + "outgoing": ("out", "outgoing"), + } + dirs = aliases.get(direction, (direction,)) + con = connect_release(root) + try: + tables = { + r[0] + for r in con.execute( + "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'" + ).fetchall() + } + hits: list[dict[str, Any]] = [] + for d in dirs: + view = { + "in": "graph_in", + "out": "graph_out", + "incoming": "graph_incoming", + "outgoing": "graph_outgoing", + }.get(d, d) + if view not in tables: + continue + rows = con.execute( + f""" + SELECT node_cid, neighbor_cids, edge_types, scores + FROM {view} + WHERE node_cid = ? + """, + [node_cid], + ).fetchall() + for node, neighs, types, scores in rows: + neighs = list(neighs or []) + types = list(types or []) + scores = list(scores or []) + for i, neigh in enumerate(neighs): + hits.append( + { + "direction": d, + "node_cid": node, + "neighbor_cid": neigh, + "edge_type": types[i] if i < len(types) else "", + "score": scores[i] if i < len(scores) else None, + } + ) + hits.sort(key=lambda r: (-(r["score"] or 0), str(r["neighbor_cid"]))) + return hits[: int(limit)] + finally: + con.close() + + +def build_fts_index( + corpus_parquet: Path, + duckdb_path: Path, + expected: int, + *, + log: Any | None = None, +) -> Path: + """Load corpus parquet into DuckDB and create an FTS index (no SQLite).""" + duckdb = _require_duckdb() + duckdb_path = Path(duckdb_path) + duckdb_path.parent.mkdir(parents=True, exist_ok=True) + if duckdb_path.exists(): + duckdb_path.unlink() + escaped = str(Path(corpus_parquet).resolve()).replace("'", "''") + con = duckdb.connect(str(duckdb_path)) + try: + con.execute( + f""" + CREATE TABLE documents AS + SELECT + CAST(document_index AS INTEGER) AS document_index, + CAST(entry_cid AS VARCHAR) AS entry_cid, + CAST(COALESCE(title, '') AS VARCHAR) AS title, + CAST(COALESCE(body, '') AS VARCHAR) AS body + FROM read_parquet('{escaped}') + """ + ) + n = int(con.execute("SELECT COUNT(*) FROM documents").fetchone()[0]) + if n != int(expected): + raise DuckDBStoreError(f"DuckDB corpus rows {n} != expected {expected}") + con.execute("INSTALL fts") + con.execute("LOAD fts") + con.execute( + "PRAGMA create_fts_index('documents', 'document_index', 'title', 'body', " + "stemmer='porter', stopwords='english', ignore='(\\.+)', strip_accents=1, lower=1)" + ) + if log: + log(f"duckdb fts ready n={n} path={duckdb_path}") + finally: + con.close() + return duckdb_path + + +def stream_neighbors_to_parquet( + duckdb_path: Path, + spill: Path, + n_docs: int, + *, + k: int = 8, + shard: int = 5000, + batch: int = 256, + resume: bool = True, + log: Any | None = None, +) -> list[Path]: + """Stream DuckDB FTS neighbors into flattened neighbor_*.parquet shards.""" + duckdb = _require_duckdb() + spill = Path(spill) + spill.mkdir(parents=True, exist_ok=True) + existing = sorted(spill.glob("neighbors_*.parquet")) + buf_start = 0 + shard_paths: list[Path] = [] + if resume and existing: + covered = 0 + for path in existing: + parts = path.stem.split("_") + try: + start_i, end_i = int(parts[1]), int(parts[2]) + except (IndexError, ValueError): + continue + if start_i != covered: + break + shard_paths.append(path) + covered = end_i + buf_start = covered + if buf_start >= n_docs: + if log: + log(f"neighbors resume complete {buf_start}/{n_docs}") + return shard_paths + for path in existing: + if path not in shard_paths: + path.unlink(missing_ok=True) + else: + for path in existing: + path.unlink(missing_ok=True) + + con = duckdb.connect(str(duckdb_path), read_only=True) + con.execute("LOAD fts") + rows_buf: list[dict[str, Any]] = [] + shard_start = buf_start + last_idx = buf_start - 1 + done = buf_start + try: + while True: + batch_rows = con.execute( + "SELECT document_index, title, body FROM documents " + "WHERE document_index > ? ORDER BY document_index LIMIT ?", + [last_idx, batch], + ).fetchall() + if not batch_rows: + break + for di, title, body in batch_rows: + di = int(di) + query = (str(title or "").strip() or str(body or "")[:800]).strip() + hits: list[tuple[int, float]] = [] + if query: + hits = con.execute( + "SELECT document_index, " + "fts_main_documents.match_bm25(document_index, ?) AS score " + "FROM documents " + "WHERE document_index != ? AND score IS NOT NULL " + "ORDER BY score DESC, document_index " + "LIMIT ?", + [query, di, int(k)], + ).fetchall() + for neigh_i, score in hits: + rows_buf.append( + { + "source_index": di, + "neighbor_index": int(neigh_i), + "score": float(score or 0.0), + } + ) + last_idx = di + done += 1 + if (di + 1 - shard_start) >= shard: + end = di + 1 + path = spill / f"neighbors_{shard_start:06d}_{end:06d}.parquet" + pd.DataFrame(rows_buf).to_parquet(path, index=False) + shard_paths.append(path) + rows_buf = [] + shard_start = end + if log: + log(f"neighbors parquet shard {path.name}") + if done % 5_000 == 0 and log: + log(f"duckdb neighbors {done}/{n_docs}") + if shard_start < n_docs: + path = spill / f"neighbors_{shard_start:06d}_{n_docs:06d}.parquet" + pd.DataFrame(rows_buf).to_parquet(path, index=False) + shard_paths.append(path) + if log: + log(f"duckdb neighbors done={done} shards={len(shard_paths)}") + return shard_paths + finally: + con.close() + + +def iter_neighbor_parquet_shards(spill: Path) -> Any: + """Yield (start_index, list-of-neighbor-lists) from parquet shards.""" + import pandas as pd + + paths = sorted(Path(spill).glob("neighbors_*.parquet")) + for path in paths: + parts = path.stem.split("_") + start_i = int(parts[1]) + end_i = int(parts[2]) + frame = pd.read_parquet(path) + part: list[list] = [[] for _ in range(max(0, end_i - start_i))] + if not frame.empty: + for rec in frame.itertuples(index=False): + src = int(rec.source_index) + offset = src - start_i + if 0 <= offset < len(part): + part[offset].append( + (int(rec.neighbor_index), float(rec.score), []) + ) + yield start_i, part + + +def materialize_corpus_duckdb(corpus_parquet: Path, duckdb_path: Path) -> Path: + """Load a corpus parquet file into a persistent DuckDB database.""" + duckdb = _require_duckdb() + duckdb_path = Path(duckdb_path) + duckdb_path.parent.mkdir(parents=True, exist_ok=True) + if duckdb_path.exists(): + duckdb_path.unlink() + con = duckdb.connect(str(duckdb_path)) + try: + con.execute( + """ + CREATE TABLE documents AS + SELECT + CAST(document_index AS INTEGER) AS document_index, + CAST(entry_cid AS VARCHAR) AS entry_cid, + CAST(title AS VARCHAR) AS title, + CAST(body AS VARCHAR) AS body + FROM read_parquet(?) + """, + [str(corpus_parquet)], + ) + con.execute("CREATE INDEX documents_idx ON documents(document_index)") + finally: + con.close() + return duckdb_path diff --git a/country_laws_ir/incremental.py b/country_laws_ir/incremental.py new file mode 100644 index 0000000000000000000000000000000000000000..870039d76530cefabb9284ebd6322289345b1c06 --- /dev/null +++ b/country_laws_ir/incremental.py @@ -0,0 +1,518 @@ +"""CID-keyed incremental GraphRAG rebuild for country-laws IR. + +Follows the US Code / patent persistent-index pattern: + +* ``entry_cid`` is the durable identity (not positional ``document_index``). +* A matching source revision + parquet digest is a no-op. +* Unchanged CIDs reuse embeddings; BM25/graph are rebuilt from the current + corpus because ``document_index`` is a shard pointer, not an identity. +* Delta refresh is never labeled equivalent to a full rebuild. + +Public Hub reads stay anonymous. Publication to ``justicedao/*`` is a separate +gated upload step. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import Enum +import json +from pathlib import Path +from typing import Any, Iterable, Mapping + +import pandas as pd + +from . import SCHEMA_VERSION + +class RebuildKind(str, Enum): + UNCHANGED = "unchanged" + DELTA_REFRESH = "delta_refresh" + FULL_REBUILD = "full_rebuild" + + @classmethod + def coerce(cls, value: Any) -> "RebuildKind": + if isinstance(value, RebuildKind): + return value + text = str(value or "").strip().lower().replace("-", "_") + aliases = { + "skip": cls.UNCHANGED, + "noop": cls.UNCHANGED, + "none": cls.UNCHANGED, + "delta": cls.DELTA_REFRESH, + "incremental": cls.DELTA_REFRESH, + "partial": cls.DELTA_REFRESH, + "full": cls.FULL_REBUILD, + "rebuild": cls.FULL_REBUILD, + "force": cls.FULL_REBUILD, + } + if text in aliases: + return aliases[text] + for kind in cls: + if kind.value == text or kind.name.lower() == text: + return kind + raise ValueError(f"unknown rebuild kind: {value!r}") + + +class BuildMode(str, Enum): + AUTO = "auto" + FULL = "full" + DELTA = "delta" + + @classmethod + def coerce(cls, value: Any) -> "BuildMode": + if isinstance(value, BuildMode): + return value + text = str(value or "").strip().lower().replace("-", "_") + aliases = { + "incremental": cls.DELTA, + "diff": cls.DELTA, + "rebuild": cls.FULL, + "complete": cls.FULL, + } + if text in aliases: + return aliases[text] + for mode in cls: + if mode.value == text or mode.name.lower() == text: + return mode + raise ValueError(f"unknown build mode: {value!r}") + + +@dataclass(frozen=True) +class CorpusDelta: + added_cids: tuple[str, ...] = () + removed_cids: tuple[str, ...] = () + unchanged_cids: tuple[str, ...] = () + prior_count: int = 0 + current_count: int = 0 + changed_ratio: float = 1.0 + equivalent_to_full: bool = False + + @property + def n_added(self) -> int: + return len(self.added_cids) + + @property + def n_removed(self) -> int: + return len(self.removed_cids) + + @property + def n_unchanged(self) -> int: + return len(self.unchanged_cids) + + def to_dict(self, *, include_cids: bool = False, cid_sample: int = 8) -> dict[str, Any]: + payload = { + "n_added": self.n_added, + "n_removed": self.n_removed, + "n_unchanged": self.n_unchanged, + "prior_count": self.prior_count, + "current_count": self.current_count, + "changed_ratio": self.changed_ratio, + "equivalent_to_full": self.equivalent_to_full, + } + if include_cids: + payload["added_cids"] = list(self.added_cids) + payload["removed_cids"] = list(self.removed_cids) + payload["unchanged_cids"] = list(self.unchanged_cids) + else: + payload["added_cids_sample"] = list(self.added_cids[:cid_sample]) + payload["removed_cids_sample"] = list(self.removed_cids[:cid_sample]) + return payload + + +@dataclass(frozen=True) +class RebuildPlan: + kind: RebuildKind + mode: BuildMode + reason: str + source_revision: str + prior_revision: str | None = None + source_fingerprint: str = "" + prior_fingerprint: str | None = None + delta: CorpusDelta | None = None + reuse_embeddings: bool = False + skip_build: bool = False + equivalent_to_full: bool = False + + def to_dict(self) -> dict[str, Any]: + return { + "kind": self.kind.value, + "mode": self.mode.value, + "reason": self.reason, + "source_revision": self.source_revision, + "prior_revision": self.prior_revision, + "source_fingerprint": self.source_fingerprint, + "prior_fingerprint": self.prior_fingerprint, + "delta": None if self.delta is None else self.delta.to_dict(include_cids=False), + "reuse_embeddings": self.reuse_embeddings, + "skip_build": self.skip_build, + "equivalent_to_full": self.equivalent_to_full, + "schema_version": SCHEMA_VERSION, + } + + +@dataclass +class PriorRelease: + directory: Path + manifest: dict[str, Any] = field(default_factory=dict) + corpus: pd.DataFrame | None = None + vectors_by_cid: dict[str, list[float]] | None = None + + @property + def source_revision(self) -> str | None: + return ( + self.manifest.get("dataset_revision") + or (self.manifest.get("source") or {}).get("source_revision") + ) + + @property + def fingerprint(self) -> str: + return source_fingerprint_from_manifest(self.manifest) + + +def source_fingerprint(source_meta: Mapping[str, Any]) -> str: + """Stable skip key: Hub SHA plus parquet digests when present.""" + revision = str(source_meta.get("source_revision") or "") + laws = str(source_meta.get("laws_sha256") or "") + articles = str(source_meta.get("articles_sha256") or "") + return f"{revision}|{laws}|{articles}" + + +def source_fingerprint_from_manifest(manifest: Mapping[str, Any]) -> str: + revision = str( + manifest.get("dataset_revision") + or (manifest.get("source") or {}).get("source_revision") + or "" + ) + sha = manifest.get("input_sha256") or {} + laws = str(sha.get("laws.parquet") or "") + articles = str(sha.get("articles.parquet") or "") + if not laws and not articles: + src = manifest.get("source") or {} + laws = str(src.get("laws_sha256") or "") + articles = str(src.get("articles_sha256") or "") + return f"{revision}|{laws}|{articles}" + + +def _cid_set(frame: pd.DataFrame | None) -> set[str]: + if frame is None or frame.empty or "entry_cid" not in frame.columns: + return set() + return {str(x) for x in frame["entry_cid"].dropna().astype(str) if str(x).strip()} + + +def diff_corpus( + prior: pd.DataFrame | None, + current: pd.DataFrame, +) -> CorpusDelta: + """Diff two CID-keyed corpora. Same ``entry_cid`` implies same body.""" + current_cids = _cid_set(current) + prior_cids = _cid_set(prior) + added = tuple(sorted(current_cids - prior_cids)) + removed = tuple(sorted(prior_cids - current_cids)) + unchanged = tuple(sorted(current_cids & prior_cids)) + current_count = int(len(current_cids)) + prior_count = int(len(prior_cids)) + if current_count == 0: + ratio = 1.0 if prior_count else 0.0 + else: + ratio = 1.0 - (len(unchanged) / float(current_count)) + equivalent = prior_count == 0 or (not unchanged and current_count > 0) + return CorpusDelta( + added_cids=added, + removed_cids=removed, + unchanged_cids=unchanged, + prior_count=prior_count, + current_count=current_count, + changed_ratio=float(ratio), + equivalent_to_full=equivalent, + ) + + +def plan_rebuild( + *, + mode: BuildMode | str, + source_meta: Mapping[str, Any], + prior: PriorRelease | None, + current_corpus: pd.DataFrame | None = None, + force: bool = False, + rebuild_stub_vectors: bool = True, +) -> RebuildPlan: + """Decide skip / delta / full from source fingerprints and CID overlap.""" + mode = BuildMode.coerce(mode) + revision = str(source_meta.get("source_revision") or "") + fingerprint = source_fingerprint(source_meta) + prior_revision = prior.source_revision if prior is not None else None + prior_fp = prior.fingerprint if prior is not None else None + + if force or mode is BuildMode.FULL: + delta = None + if current_corpus is not None and prior is not None: + delta = diff_corpus(prior.corpus, current_corpus) + return RebuildPlan( + kind=RebuildKind.FULL_REBUILD, + mode=mode, + reason="operator forced full rebuild" if force else "build mode is full", + source_revision=revision, + prior_revision=prior_revision, + source_fingerprint=fingerprint, + prior_fingerprint=prior_fp, + delta=delta, + reuse_embeddings=False, + skip_build=False, + equivalent_to_full=True, + ) + + if prior is None: + return RebuildPlan( + kind=RebuildKind.FULL_REBUILD, + mode=mode, + reason="no prior release", + source_revision=revision, + prior_revision=None, + source_fingerprint=fingerprint, + prior_fingerprint=None, + delta=None, + reuse_embeddings=False, + skip_build=False, + equivalent_to_full=True, + ) + + prior_vector_status = str( + ((prior.manifest.get("vector") or {}) if prior.manifest else {}).get("status") + or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status") + or "" + ).strip().lower() + stub_vectors = rebuild_stub_vectors and prior_vector_status in { + "stub", + "stub_missing_encoder", + "incomplete", + "partial", + } + + if prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors: + return RebuildPlan( + kind=RebuildKind.UNCHANGED, + mode=mode, + reason="source revision and parquet digests match prior release", + source_revision=revision, + prior_revision=prior_revision, + source_fingerprint=fingerprint, + prior_fingerprint=prior_fp, + delta=CorpusDelta( + unchanged_cids=tuple(sorted(_cid_set(prior.corpus))), + prior_count=int(len(_cid_set(prior.corpus))), + current_count=int(len(_cid_set(prior.corpus))), + changed_ratio=0.0, + equivalent_to_full=False, + ), + reuse_embeddings=True, + skip_build=True, + equivalent_to_full=False, + ) + + delta = None + if current_corpus is not None: + delta = diff_corpus(prior.corpus, current_corpus) + if delta.equivalent_to_full: + return RebuildPlan( + kind=RebuildKind.FULL_REBUILD, + mode=mode, + reason="CID overlap is empty; delta equals a full rebuild", + source_revision=revision, + prior_revision=prior_revision, + source_fingerprint=fingerprint, + prior_fingerprint=prior_fp, + delta=delta, + reuse_embeddings=False, + skip_build=False, + equivalent_to_full=True, + ) + + reason = ( + "source fingerprint matches but vectors are stub/incomplete; encode missing CIDs" + if stub_vectors and prior_fp == fingerprint + else "source changed; reuse embeddings for unchanged entry_cids" + ) + return RebuildPlan( + kind=RebuildKind.DELTA_REFRESH, + mode=mode, + reason=reason, + source_revision=revision, + prior_revision=prior_revision, + source_fingerprint=fingerprint, + prior_fingerprint=prior_fp, + delta=delta, + reuse_embeddings=True, + skip_build=False, + equivalent_to_full=False, + ) + + +def _read_sharded_parquet(directory: Path) -> pd.DataFrame | None: + if not directory.is_dir(): + return None + parts = sorted(directory.glob("part-*.parquet")) + if not parts: + parts = sorted(p for p in directory.rglob("*.parquet") if p.is_file()) + if not parts: + return None + frames = [pd.read_parquet(p) for p in parts] + return pd.concat(frames, ignore_index=True) if frames else None + + +def load_release_manifest(release_dir: Path) -> dict[str, Any]: + path = Path(release_dir) / "manifest.json" + if not path.is_file(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return {} + return data if isinstance(data, dict) else {} + + +def load_release_corpus(release_dir: Path) -> pd.DataFrame | None: + release_dir = Path(release_dir) + corpus = _read_sharded_parquet(release_dir / "data" / "corpus") + if corpus is not None: + return corpus + checkpoint = release_dir / "corpus.parquet" + if checkpoint.is_file(): + return pd.read_parquet(checkpoint) + return None + + +def embeddings_from_vector_table(frame: pd.DataFrame) -> dict[str, list[float]]: + out: dict[str, list[float]] = {} + if frame is None or frame.empty: + return out + if "entry_cid" not in frame.columns or "embedding" not in frame.columns: + return out + for rec in frame.itertuples(index=False): + cid = str(getattr(rec, "entry_cid", "") or "") + emb = getattr(rec, "embedding", None) + if not cid or emb is None: + continue + if isinstance(emb, float) and pd.isna(emb): + continue + try: + values = [float(x) for x in list(emb)] + except Exception: + continue + if not values: + continue + out[cid] = values + return out + + +def load_release_vectors_by_cid(release_dir: Path) -> dict[str, list[float]]: + frame = _read_sharded_parquet(Path(release_dir) / "data" / "vectors") + if frame is None: + return {} + return embeddings_from_vector_table(frame) + + +def load_prior_release(release_dir: Path | None) -> PriorRelease | None: + if release_dir is None: + return None + directory = Path(release_dir) + if not directory.is_dir(): + return None + manifest = load_release_manifest(directory) + if not manifest and not (directory / "data").is_dir(): + return None + return PriorRelease( + directory=directory, + manifest=manifest, + corpus=load_release_corpus(directory), + vectors_by_cid=None, + ) + + +def load_embedding_cache(path: Path) -> dict[str, list[float]]: + if not path.is_file(): + return {} + try: + frame = pd.read_parquet(path) + except Exception: + return {} + return embeddings_from_vector_table(frame) + + +def save_embedding_cache( + path: Path, + by_cid: Mapping[str, Iterable[float]], + *, + model_name: str, + dimension: int, +) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + rows = [ + { + "entry_cid": cid, + "embedding": list(vec), + "model_name": model_name, + "dimension": int(dimension), + } + for cid, vec in sorted(by_cid.items()) + ] + frame = pd.DataFrame(rows) + tmp = path.with_suffix(path.suffix + ".tmp") + frame.to_parquet(tmp, index=False) + tmp.replace(path) + + +def merge_embedding_maps( + *maps: Mapping[str, list[float]] | None, +) -> dict[str, list[float]]: + merged: dict[str, list[float]] = {} + for mapping in maps: + if not mapping: + continue + merged.update(mapping) + return merged + + +def fetch_hub_prior( + slug: str, + dest: Path | None = None, + *, + cache_root: Path | None = None, +) -> Path | None: + """Download JusticeDAO corpus+vector shards to use as an incremental parent. + + Missing Hub IR is not an error: first-time countries return ``None``. + """ + from huggingface_hub import snapshot_download + from huggingface_hub.errors import RepositoryNotFoundError + + from .auth import operator_token, public_token + from .catalog import target_repo + + root = Path(cache_root) if cache_root is not None else ( + Path.home() / ".ipfs_datasets" / "country-laws-ir" / "cache" / "hub-ir" + ) + dest = Path(dest) if dest is not None else (root / slug) + dest.mkdir(parents=True, exist_ok=True) + repo = target_repo(slug) + try: + snapshot_download( + repo_id=repo, + repo_type="dataset", + local_dir=str(dest), + allow_patterns=[ + "manifest.json", + "data/vectors/**", + "data/corpus/**", + "indexes/vector_chunks.parquet", + ], + token=operator_token() or public_token(), + ) + except RepositoryNotFoundError: + return None + except Exception: + if not (dest / "manifest.json").is_file(): + return None + raise + if not (dest / "manifest.json").is_file(): + return None + return dest diff --git a/country_laws_ir/normalize.py b/country_laws_ir/normalize.py index f976040f7a40a86488e840a2770ec00ab62ecac1..b3c348f675dd13ca6f9184c6ffffce5cdfead2d8 100644 --- a/country_laws_ir/normalize.py +++ b/country_laws_ir/normalize.py @@ -1,8 +1,9 @@ """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus. Prefer article/section as the retrieval unit; fall back to law-level when -articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE -GraphRAG. Never invent legal text or identifiers. +articles are missing or empty. Strip leftover HTML, then detect multilingual +title/chapter/article/section headings (Oregon-style) when present. Never +invent legal text or a hierarchy that is not in the source. Public Hub reads only (token=False). No Hugging Face token is read or stored. """ @@ -11,30 +12,42 @@ from __future__ import annotations import json import os -import re -import unicodedata from collections import Counter from pathlib import Path from typing import Any import pandas as pd from huggingface_hub import dataset_info, hf_hub_download +from huggingface_hub.errors import EntryNotFoundError from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION from .auth import configure_hf, public_token from .cidutil import cid_of_json, sha256_file, sha256_hex from .schema import SchemaError, validate_articles, validate_laws +from .structure import normalize_legal_text, split_structured_units -_WS_RE = re.compile(r"\s+", re.UNICODE) COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py" +EMPTY_ARTICLE_COLUMNS = ( + "law_id", + "id", + "title", + "text", + "source_url", + "document_number", + "article_number", + "record_type", + "metadata_json", +) + + +def _empty_articles() -> pd.DataFrame: + return pd.DataFrame(columns=list(EMPTY_ARTICLE_COLUMNS)) def normalize_text(value: Any) -> str: if value is None or (isinstance(value, float) and pd.isna(value)): return "" - text = unicodedata.normalize("NFKC", str(value)) - text = _WS_RE.sub(" ", text).strip() - return text + return normalize_legal_text(value) def _s(value: Any) -> str: @@ -53,21 +66,34 @@ def _download(repo_id: str, filename: str, cache_dir: Path) -> Path: return Path(path) -def _resolve_local_parquet(root: Path, name: str) -> Path: +def _repo_filenames(info: Any) -> set[str]: + return {str(getattr(s, "rfilename", "") or "") for s in (getattr(info, "siblings", None) or [])} + + +def _pick_repo_file(filenames: set[str], name: str) -> str | None: + for cand in (f"data/{name}.parquet", f"{name}.parquet"): + if cand in filenames: + return cand + return None + + +def _resolve_local_parquet(root: Path, name: str, *, required: bool = True) -> Path | None: """Accept either /data/.parquet or /.parquet.""" for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"): if cand.is_file(): return cand - raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)") + if required: + raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)") + return None def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: """Load a local country-laws pack (filtered preprocess layout).""" local_dir = Path(local_dir).resolve() laws_path = _resolve_local_parquet(local_dir, "laws") - articles_path = _resolve_local_parquet(local_dir, "articles") + articles_path = _resolve_local_parquet(local_dir, "articles", required=False) laws = pd.read_parquet(laws_path) - articles = pd.read_parquet(articles_path) + articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles() validate_laws(laws) validate_articles(articles) pack_meta: dict[str, Any] = {} @@ -91,9 +117,9 @@ def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict "source_dataset": source_dataset, "source_revision": source_revision, "laws_path": str(laws_path), - "articles_path": str(articles_path), + "articles_path": str(articles_path) if articles_path is not None else None, "laws_sha256": sha256_file(laws_path), - "articles_sha256": sha256_file(articles_path), + "articles_sha256": sha256_file(articles_path) if articles_path is not None else None, "n_laws_source": int(len(laws)), "n_articles_source": int(len(articles)), "laws_columns": list(map(str, laws.columns)), @@ -118,19 +144,27 @@ def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFra os.environ.setdefault("HF_HOME", str(cache_dir / "hf")) info = dataset_info(repo_id, token=public_token()) revision = info.sha - laws_path = _download(repo_id, "data/laws.parquet", cache_dir) - articles_path = _download(repo_id, "data/articles.parquet", cache_dir) + filenames = _repo_filenames(info) + laws_file = _pick_repo_file(filenames, "laws") or "data/laws.parquet" + articles_file = _pick_repo_file(filenames, "articles") + laws_path = _download(repo_id, laws_file, cache_dir) + articles_path: Path | None = None + if articles_file is not None: + try: + articles_path = _download(repo_id, articles_file, cache_dir) + except EntryNotFoundError: + articles_path = None laws = pd.read_parquet(laws_path) - articles = pd.read_parquet(articles_path) + articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles() validate_laws(laws) validate_articles(articles) meta = { "source_dataset": repo_id, "source_revision": revision, "laws_path": str(laws_path), - "articles_path": str(articles_path), + "articles_path": str(articles_path) if articles_path is not None else None, "laws_sha256": sha256_file(laws_path), - "articles_sha256": sha256_file(articles_path), + "articles_sha256": sha256_file(articles_path) if articles_path is not None else None, "n_laws_source": int(len(laws)), "n_articles_source": int(len(articles)), "laws_columns": list(map(str, laws.columns)), @@ -248,6 +282,35 @@ def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, return "" +def _hierarchy_fields( + title: str, body: str, article_number: str, *, language: str = "" +) -> dict[str, Any]: + """Best-effort hierarchy from a single already-split article/section body.""" + units = split_structured_units( + f"{title}\n{body}" if title else body, language=language + ) + if not units: + return { + "hierarchy_kind": "article" if article_number else "law", + "hierarchy_path": "", + "title_number": "", + "chapter_number": "", + "part_number": "", + "section_number": "", + "subsections": [], + } + unit = units[0] + return { + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + } + + def _collector(meta: dict[str, Any], source_dataset: str) -> str: nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for blob in (meta, nested): @@ -452,6 +515,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": instrument_id, "article_id": source_id, + **_hierarchy_fields( + article_title, body, article_number, language=parent["language"] + ), }, ) ) @@ -464,6 +530,49 @@ def build_corpus( report["drop_samples"]["empty_body"].append(instrument_id) continue meta = parent["metadata"] + units = split_structured_units(body, language=parent["language"]) + if units: + report["unit"] = "structured" + for unit in units: + entries.append( + _base_record( + record_type=unit.kind if unit.kind in {"article", "section"} else "article", + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number=unit.article_number or unit.number, + article_title=unit.heading, + body=unit.body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage="structured (headings detected in law body)", + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=f"{instrument_id}-{unit.kind}-{unit.number}", + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": instrument_id, + "article_id": "", + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + }, + ) + ) + continue entries.append( _base_record( record_type="law", @@ -494,6 +603,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": "", "article_id": "", + **_hierarchy_fields( + parent["instrument_title"], body, "", language=parent["language"] + ), }, ) ) @@ -570,5 +682,23 @@ def build_corpus( "empty_bodies_dropped": report["drops"]["empty_body"], "duplicate_cids_dropped": report["drops"]["duplicate_cid"], } + from .profiles import majority_language, score_heading_languages + + sample_text = "" + if not df.empty and "body" in df.columns: + sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist()) + if "title" in df.columns: + sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text + heading_langs = score_heading_languages(sample_text) + report["heading_language_counts"] = dict(heading_langs) + report["heading_language_majority"] = majority_language(heading_langs) + report["document_language_majority"] = None + if report.get("language_breakdown"): + report["document_language_majority"] = max( + report["language_breakdown"].items(), key=lambda kv: kv[1] + )[0] + from .verify import verify_normalized_corpus + + report["verification"] = verify_normalized_corpus(df, report) df.attrs["normalization_report"] = report return df, report diff --git a/country_laws_ir/package.py b/country_laws_ir/package.py index c905675628f575e5cab5ac71b8ecaf14276e2ed1..05c6be4495ff4b698be8ac375e66f934a3b779b0 100644 --- a/country_laws_ir/package.py +++ b/country_laws_ir/package.py @@ -34,8 +34,11 @@ def package_release( country: dict[str, Any], code_root: Path, normalization_report: dict[str, Any] | None = None, + extra_manifest: dict[str, Any] | None = None, + wipe: bool = True, + skip_bm25_graph: bool = False, ) -> dict[str, Any]: - if out.exists(): + if wipe and out.exists(): shutil.rmtree(out) out.mkdir(parents=True, exist_ok=True) indexes_dir = out / "indexes" @@ -51,78 +54,95 @@ def package_release( ) write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx)) - bm25_doc_idx = write_sharded( - bm25["documents"], - out / "data" / "bm25" / "documents", - "data/bm25/documents", - kind="bm25_documents", - key_col="entry_cid", - index_col="document_index", - ) - write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx)) - - postings = bm25["postings"] - posting_idx = write_sharded( - postings, - out / "data" / "bm25" / "postings", - "data/bm25/postings", - kind="bm25_postings", - key_col="term", - ) - for row, part_start in zip(posting_idx, range(len(posting_idx))): - shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE] - row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0 - row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0 - row["token_instance_count"] = row["posting_count"] - write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx)) - - node_idx = write_sharded( - graph["nodes"], - out / "data" / "graph" / "nodes", - "data/graph/nodes", - kind="graph_nodes", - key_col="node_cid", - ) - write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx)) - - edge_idx = write_sharded( - graph["edges"], - out / "data" / "graph" / "edges", - "data/graph/edges", - kind="graph_edges", - key_col="edge_cid", - ) - write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx)) - - incoming = graph["incoming"] - outgoing = graph["outgoing"] - in_idx = write_sharded( - incoming if incoming is not None and not incoming.empty else pd.DataFrame( - columns=["node_cid", "page_index", "direction"] - ), - out / "data" / "graph" / "adjacency" / "incoming", - "data/graph/adjacency/incoming", - kind="graph_incoming_adjacency", - key_col="node_cid", - ) - out_idx = write_sharded( - outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame( - columns=["node_cid", "page_index", "direction"] - ), - out / "data" / "graph" / "adjacency" / "outgoing", - "data/graph/adjacency/outgoing", - kind="graph_outgoing_adjacency", - key_col="node_cid", - ) - for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")): - for r in rows: - r["direction"] = direction - r["adjacency_count"] = r.get("row_count", 0) - r["node_count"] = r.get("row_count", 0) - r["first_page_index"] = 0 - r["last_page_index"] = 0 - write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx)) - write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx)) + if skip_bm25_graph: + bm25_doc_idx = [] + posting_idx = [] + postings = pd.DataFrame() + node_idx = [] + edge_idx = [] + in_idx = [] + out_idx = [] + incoming = pd.DataFrame() + outgoing = pd.DataFrame() + bm25 = bm25 or {"documents": pd.DataFrame(), "postings": pd.DataFrame(), "stats": {}} + graph = graph or {"nodes": pd.DataFrame(), "edges": pd.DataFrame(), "stats": {}} + else: + bm25_doc_idx = write_sharded( + bm25["documents"], + out / "data" / "bm25" / "documents", + "data/bm25/documents", + kind="bm25_documents", + key_col="entry_cid", + index_col="document_index", + ) + write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx)) + + postings = bm25["postings"] + posting_idx = write_sharded( + postings, + out / "data" / "bm25" / "postings", + "data/bm25/postings", + kind="bm25_postings", + key_col="term", + ) + for row, part_start in zip(posting_idx, range(len(posting_idx))): + shard_df = postings.iloc[ + part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE + ] + row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0 + row["posting_count"] = ( + int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0 + ) + row["token_instance_count"] = row["posting_count"] + write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx)) + + node_idx = write_sharded( + graph["nodes"], + out / "data" / "graph" / "nodes", + "data/graph/nodes", + kind="graph_nodes", + key_col="node_cid", + ) + write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx)) + + edge_idx = write_sharded( + graph["edges"], + out / "data" / "graph" / "edges", + "data/graph/edges", + kind="graph_edges", + key_col="edge_cid", + ) + write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx)) + + incoming = graph["incoming"] + outgoing = graph["outgoing"] + in_idx = write_sharded( + incoming + if incoming is not None and not incoming.empty + else pd.DataFrame(columns=["node_cid", "page_index", "direction"]), + out / "data" / "graph" / "adjacency" / "incoming", + "data/graph/adjacency/incoming", + kind="graph_incoming_adjacency", + key_col="node_cid", + ) + out_idx = write_sharded( + outgoing + if outgoing is not None and not outgoing.empty + else pd.DataFrame(columns=["node_cid", "page_index", "direction"]), + out / "data" / "graph" / "adjacency" / "outgoing", + "data/graph/adjacency/outgoing", + kind="graph_outgoing_adjacency", + key_col="node_cid", + ) + for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")): + for r in rows: + r["direction"] = direction + r["adjacency_count"] = r.get("row_count", 0) + r["node_count"] = r.get("row_count", 0) + r["first_page_index"] = 0 + r["last_page_index"] = 0 + write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx)) + write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx)) vectors_df = vectors["vectors"] # Drop null embeddings for stub releases so parquet stays typed; keep rows when present. @@ -195,8 +215,8 @@ def package_release( "bm25_documents": int(len(bm25["documents"])), "bm25_keyword_shards": len(posting_idx), "bm25_posting_rows": int(len(postings)), - "bm25_postings": int(bm25["stats"]["n_postings"]), - "bm25_terms": int(bm25["stats"]["n_terms"]), + "bm25_postings": int((bm25.get("stats") or {}).get("n_postings") or 0), + "bm25_terms": int((bm25.get("stats") or {}).get("n_terms") or 0), "corpus_chunks": len(corpus_idx), "corpus_rows": int(len(corpus)), "graph_edge_chunks": len(edge_idx), @@ -214,9 +234,22 @@ def package_release( "n_laws": n_laws, "n_articles": n_articles, } + if skip_bm25_graph and extra_manifest and extra_manifest.get("sparse"): + sparse = extra_manifest["sparse"] + bm25_counts = (sparse.get("bm25") or {}).get("counts") or {} + graph_counts = sparse.get("graph") or {} + counts.update( + {k: int(v) for k, v in bm25_counts.items() if isinstance(v, (int, float))} + ) + if graph_counts.get("node_count") is not None: + counts["graph_nodes"] = int(graph_counts["node_count"]) + if graph_counts.get("edge_count") is not None: + counts["graph_edges"] = int(graph_counts["edge_count"]) def idx_desc(name: str) -> dict[str, Any]: path = indexes_dir / name + if not path.is_file(): + return {"relative_path": f"indexes/{name}", "present": False} return file_descriptor(path, f"indexes/{name}") hub_id = target_repo(country["slug"]) @@ -247,6 +280,7 @@ def package_release( "compression_level": 6, "max_rows_per_file": MAX_ROWS_PER_FILE, "row_group_size": MAX_ROWS_PER_FILE, + "query_engine": "duckdb", }, "graph": { "adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW, @@ -324,12 +358,35 @@ def package_release( }, "source": source_meta, } + if extra_manifest: + manifest.update(extra_manifest) (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") _write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id) _write_gitattributes(out) + _write_dataset_configs(out) return manifest +def _write_dataset_configs(out: Path) -> None: + configs = { + "country-laws-ir-graphrag/v1": { + "data_files": { + "corpus": "data/corpus/*.parquet", + "bm25_documents": "data/bm25/documents/*.parquet", + "bm25_postings": "data/bm25/postings/*.parquet", + "graph_nodes": "data/graph/nodes/*.parquet", + "graph_edges": "data/graph/edges/*.parquet", + "graph_adjacency_out": "data/graph/adjacency/out/*.parquet", + "graph_adjacency_in": "data/graph/adjacency/in/*.parquet", + "vectors": "data/vectors/*.parquet", + } + } + } + (out / "dataset_configs.json").write_text( + json.dumps(configs, indent=2) + "\n", encoding="utf-8" + ) + + def _write_gitattributes(out: Path) -> None: (out / ".gitattributes").write_text( "*.parquet filter=lfs diff=lfs merge=lfs -text\n" @@ -546,6 +603,7 @@ def package_release_sequential( code_root: Path, normalization_report: dict[str, Any] | None = None, expected_rows: int | None = None, + extra_manifest: dict[str, Any] | None = None, ) -> dict[str, Any]: """Write release layout one section at a time (never hold corpus+bm25+graph+vectors). @@ -753,6 +811,8 @@ def package_release_sequential( def idx_desc(name: str) -> dict[str, Any]: path = indexes_dir / name + if not path.is_file(): + return {"relative_path": f"indexes/{name}", "present": False} return file_descriptor(path, f"indexes/{name}") manifest = { @@ -835,11 +895,14 @@ def package_release_sequential( }, "source": source_meta, } + if extra_manifest: + manifest.update(extra_manifest) (out / "manifest.json").write_text( json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) _write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id) _write_gitattributes(out) + _write_dataset_configs(out) checkpoint("package_seq_done") return manifest @@ -853,14 +916,20 @@ def package_from_spill( code_root: Path, normalization_report: dict[str, Any] | None = None, expected_rows: int | None = None, + extra_manifest: dict[str, Any] | None = None, ) -> dict[str, Any]: - """Package from spill dir artifacts: bm25_*.parquet, bm25_stats.pkl, graph.pkl, vectors.pkl.""" + """Package from spill dir artifacts: bm25_*.parquet, bm25_stats.json, graph.pkl, vectors.pkl.""" + import json as _json import pickle as _pickle spill = Path(spill) - stats_path = spill / "bm25_stats.pkl" - with stats_path.open("rb") as f: - bm25_stats = _pickle.load(f) + stats_json = spill / "bm25_stats.json" + stats_pkl = spill / "bm25_stats.pkl" + if stats_json.is_file(): + bm25_stats = _json.loads(stats_json.read_text(encoding="utf-8")) + else: + with stats_pkl.open("rb") as f: + bm25_stats = _pickle.load(f) return package_release_sequential( out, corpus_path=Path(corpus_path), @@ -874,4 +943,5 @@ def package_from_spill( code_root=Path(code_root), normalization_report=normalization_report, expected_rows=expected_rows, + extra_manifest=extra_manifest, ) diff --git a/country_laws_ir/profiles.py b/country_laws_ir/profiles.py new file mode 100644 index 0000000000000000000000000000000000000000..44c3d6a91b3c1bf18ede24a585e0409d7ca37518 --- /dev/null +++ b/country_laws_ir/profiles.py @@ -0,0 +1,124 @@ +"""Per-language legal heading lexicons for country-law structure extraction. + +Oregon (ORS) is English title/chapter/section. Other gazettes use their own +words (Artikel, Titre, Artículo, 条, مادة). This table is how we *score* +whether a split used the right language — not a claim that every country +has a dedicated parser. + +Languages with no lexicon (ar, zh, ja, ko, …) must not be force-split on +Latin TITLE/ARTICLE markers; collectors may already have article rows. +""" + +from __future__ import annotations + +from collections import Counter +import re +from typing import Any + +# keyword -> list of (kind, language); some words are shared (article). +HEADING_LEXICON: dict[str, list[tuple[str, str]]] = {} + +def _add(lang: str, kind: str, *words: str) -> None: + for word in words: + HEADING_LEXICON.setdefault(word.casefold(), []).append((kind, lang)) + + +_add("en", "title", "title") +_add("en", "chapter", "chapter") +_add("en", "part", "part") +_add("en", "article", "article") +_add("en", "section", "section", "sec.") + +_add("fr", "title", "titre") +_add("fr", "chapter", "chapitre") +_add("fr", "part", "partie") +_add("fr", "article", "article") +_add("fr", "section", "section") + +_add("de", "title", "titel") +_add("de", "chapter", "kapitel") +_add("de", "part", "teil") +_add("de", "article", "artikel") +_add("de", "section", "abschnitt", "paragraf") + +_add("nl", "title", "titel") +_add("nl", "chapter", "hoofdstuk") +_add("nl", "part", "deel") +_add("nl", "article", "artikel") +_add("nl", "section", "paragraaf", "afdeling") + +_add("es", "title", "título", "titulo") +_add("es", "chapter", "capítulo", "capitulo") +_add("es", "part", "parte") +_add("es", "article", "artículo", "articulo") +_add("es", "section", "sección", "seccion") + +_add("pt", "title", "título", "titulo") +_add("pt", "chapter", "capítulo", "capitulo") +_add("pt", "part", "parte") +_add("pt", "article", "artigo") +_add("pt", "section", "secção", "secao") + +_add("it", "title", "titolo") +_add("it", "chapter", "capitolo") +_add("it", "part", "parte") +_add("it", "article", "articolo") +_add("it", "section", "sezione") + +_add("el", "article", "άρθρο", "αρθρο") +_add("hu", "article", "szakasz") +_add("cs", "article", "článek") +_add("sk", "article", "článok") +_add("sl", "article", "član") +_add("nb", "article", "artikkel") +_add("sv", "article", "artikel") +_add("pl", "article", "artykuł", "artykul") +_add("ro", "article", "articolul", "articol") +_add("zh", "article", "条") +_add("ar", "article", "مادة", "المادة") +_add("ja", "article", "条") + +# Shared abbreviation; language left unknown. +_add("und", "article", "art.") +_add("und", "section", "§") + +# Scripts we do not Latin-split: +NO_LATIN_SPLIT_LANGS = frozenset({"ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn", "am"}) + +_TOKEN_RE = re.compile(r"[^\W\d_]{2,}|art\.|sec\.|§", re.UNICODE) + + +def classify_heading_token(token: str) -> list[tuple[str, str]]: + return list(HEADING_LEXICON.get(token.casefold()) or ()) + + +def score_heading_languages(text: str) -> Counter[str]: + """Count distinctive lexicon hits. Shared words like 'article' do not vote.""" + counts: Counter[str] = Counter() + if not text: + return counts + for token in _TOKEN_RE.findall(text): + hits = classify_heading_token(token) + langs = {lang for _kind, lang in hits if lang != "und"} + if len(langs) == 1: + counts[next(iter(langs))] += 1 + return counts + + +def majority_language(counts: Counter[str], *, exclude: tuple[str, ...] = ("und",)) -> str | None: + filtered = Counter({k: v for k, v in counts.items() if k not in exclude}) + if not filtered: + return None + lang, _n = filtered.most_common(1)[0] + return lang + + +def iso_lang(value: Any) -> str: + text = str(value or "").strip().lower().replace("_", "-") + if not text: + return "" + return text.split("-")[0] + + +def latin_split_allowed(language: str) -> bool: + return iso_lang(language) not in NO_LATIN_SPLIT_LANGS diff --git a/country_laws_ir/query.py b/country_laws_ir/query.py index 04c965ee12f90902c26200bb37af43d46fc8d91d..9cd3a1da6f2ac29b2287609ec1bc797fd55c4774 100644 --- a/country_laws_ir/query.py +++ b/country_laws_ir/query.py @@ -42,6 +42,12 @@ class Release: return pd.read_parquet(path) def bm25(self, query: str, top_k: int = 10) -> list[dict]: + try: + from .duckdb_store import bm25_search + + return bm25_search(self.root, query, top_k=top_k) + except Exception: + pass q_terms = tokenize(query)[:MAX_QUERY_TERMS] if not q_terms: return [] @@ -124,6 +130,12 @@ class Release: return out def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]: + try: + from .duckdb_store import graph_neighbors + + return graph_neighbors(self.root, node_cid, direction=direction, limit=limit) + except Exception: + pass dirs = ["incoming", "outgoing"] if direction == "both" else [direction] hits = [] for d in dirs: @@ -164,13 +176,17 @@ def main(argv: list[str] | None = None) -> int: p_vec.add_argument("query") p_vec.add_argument("--top-k", type=int, default=10) p_vec.add_argument("--candidate-centroids", type=int, default=4) - p_vec.add_argument("--device", default="cpu") + p_vec.add_argument("--device", default="cuda") p_g = sub.add_parser("graph") g_sub = p_g.add_subparsers(dest="graph_cmd", required=True) p_n = g_sub.add_parser("neighbors") p_n.add_argument("node_cid") - p_n.add_argument("--direction", default="both", choices=["both", "incoming", "outgoing"]) + p_n.add_argument( + "--direction", + default="both", + choices=["both", "in", "out", "incoming", "outgoing"], + ) p_n.add_argument("--limit", type=int, default=25) args = ap.parse_args(argv) diff --git a/country_laws_ir/raw_package.py b/country_laws_ir/raw_package.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8dba3b577e74e0852042e51cc9d6c21fe0dfbe --- /dev/null +++ b/country_laws_ir/raw_package.py @@ -0,0 +1,324 @@ +"""Incrementally package raw collector instruments into laws/articles parquet. + +Collectors write one JSON instrument per official page under +``$LEGAL_CORPORA_ROOT//instruments/*.json``. Those files grow as new +pages are scraped. This module merges them into the ``endomorphosis/ipfs_*_laws`` +parquet schema without rewriting unchanged rows, so the GraphRAG builder can +delta-rebuild from the resulting pack. + +Never invents legal text or identifiers. Empty/short bodies are dropped, not +filled. +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pandas as pd + +from .cidutil import sha256_file +from .schema import LAW_FIELD_MAP, REQUIRED_ARTICLE_COLUMNS, REQUIRED_LAW_COLUMNS + +LAW_COLS = [ + "id", + "title", + "text", + "source_url", + "source_type", + "jurisdiction", + "country", + "language", + "eli", + "date", + "date_issued", + "retrieved_at", + "license", + "law_status", + "identifier", + "official_identifier", + "article_count", + "json_path", + "metadata_json", +] +ART_COLS = [ + "law_id", + "id", + "title", + "text", + "source_url", + "document_number", + "article_number", + "record_type", + "metadata_json", +] + +MIN_BODY_CHARS = 80 +DEFAULT_CORPORA_ROOT = Path( + os.environ.get( + "LEGAL_CORPORA_ROOT", + str(Path.home() / ".ipfs_datasets" / "legal-corpora"), + ) +) + + +def _s(value: Any) -> str: + if value is None: + return "" + return str(value).strip() + + +def _meta_json(value: Any) -> str: + if isinstance(value, str): + return value + try: + return json.dumps(value or {}, ensure_ascii=False) + except Exception: + return "{}" + + +def instruments_to_frames( + instruments_dir: Path, + *, + min_body_chars: int = MIN_BODY_CHARS, +) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: + """Read collector JSON instruments into laws/articles dataframes.""" + laws: list[dict[str, Any]] = [] + arts: list[dict[str, Any]] = [] + skipped_short = 0 + skipped_bad = 0 + root = Path(instruments_dir) + files = sorted(root.glob("*.json")) if root.is_dir() else [] + for path in files: + try: + rec = json.loads(path.read_text(encoding="utf-8")) + except Exception: + skipped_bad += 1 + continue + if not isinstance(rec, dict): + skipped_bad += 1 + continue + text = _s(rec.get("text")) + ident = _s(rec.get("id")) + title = _s(rec.get("title")) + if not ident or not title or len(text) < min_body_chars: + skipped_short += 1 + continue + meta = rec.get("metadata") or {} + laws.append( + { + "id": ident, + "title": title, + "text": text, + "source_url": _s(rec.get("source_url")), + "source_type": _s(rec.get("source_type")), + "jurisdiction": _s(rec.get("jurisdiction")), + "country": _s(rec.get("country")), + "language": _s(rec.get("language")), + "eli": _s(rec.get("eli")) or None, + "date": _s(rec.get("date")) or None, + "date_issued": _s(rec.get("date_issued") or rec.get("date")) or None, + "retrieved_at": _s(rec.get("retrieved_at")) or None, + "license": _s(rec.get("license")), + "law_status": _s(rec.get("law_status")), + "identifier": _s(rec.get("identifier")) or ident, + "official_identifier": _s(rec.get("official_identifier")), + "article_count": rec.get("article_count") or len(rec.get("documents") or []), + "json_path": f"instruments/{path.name}", + "metadata_json": _meta_json(meta), + } + ) + for doc in rec.get("documents") or []: + if not isinstance(doc, dict): + continue + art_id = _s(doc.get("id")) + art_title = _s(doc.get("title")) + art_text = _s(doc.get("text")) + if not art_id or not art_title or not art_text: + continue + arts.append( + { + "law_id": ident, + "id": art_id, + "title": art_title, + "text": art_text, + "source_url": _s(doc.get("source_url")) or _s(rec.get("source_url")), + "document_number": _s(doc.get("document_number")), + "article_number": _s(doc.get("article_number")), + "record_type": _s(doc.get("record_type")) or "article", + "metadata_json": _meta_json(doc.get("metadata") or {}), + } + ) + report = { + "n_instrument_files": len(files), + "n_laws": len(laws), + "n_articles": len(arts), + "skipped_short_or_empty": skipped_short, + "skipped_unreadable": skipped_bad, + "min_body_chars": min_body_chars, + "never_invented_legal_text": True, + "required_law_columns": list(REQUIRED_LAW_COLUMNS), + "required_article_columns": list(REQUIRED_ARTICLE_COLUMNS), + "law_field_map": dict(LAW_FIELD_MAP), + } + return ( + pd.DataFrame(laws, columns=LAW_COLS), + pd.DataFrame(arts, columns=ART_COLS), + report, + ) + + +def _retrieved_key(value: Any) -> str: + return _s(value) + + +def merge_laws(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame: + """Upsert laws by ``id``. Newer ``retrieved_at`` wins; otherwise incoming wins.""" + if prior is None or prior.empty: + return incoming.copy() if incoming is not None else pd.DataFrame(columns=LAW_COLS) + if incoming is None or incoming.empty: + return prior.copy() + by_id: dict[str, dict[str, Any]] = {} + for frame, incoming_flag in ((prior, False), (incoming, True)): + for rec in frame.to_dict(orient="records"): + ident = _s(rec.get("id")) + if not ident: + continue + existing = by_id.get(ident) + if existing is None: + by_id[ident] = rec + continue + if incoming_flag: + new_ts = _retrieved_key(rec.get("retrieved_at")) + old_ts = _retrieved_key(existing.get("retrieved_at")) + if not old_ts or new_ts >= old_ts: + by_id[ident] = rec + rows = [by_id[k] for k in sorted(by_id)] + return pd.DataFrame(rows, columns=LAW_COLS) + + +def merge_articles(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame: + """Upsert articles by ``id``. Incoming replaces the same article id.""" + if prior is None or prior.empty: + return incoming.copy() if incoming is not None else pd.DataFrame(columns=ART_COLS) + if incoming is None or incoming.empty: + return prior.copy() + by_id: dict[str, dict[str, Any]] = {} + for frame in (prior, incoming): + for rec in frame.to_dict(orient="records"): + ident = _s(rec.get("id")) + if not ident: + continue + by_id[ident] = rec + rows = [by_id[k] for k in sorted(by_id)] + return pd.DataFrame(rows, columns=ART_COLS) + + +def load_existing_parquet(pack_dir: Path) -> tuple[pd.DataFrame | None, pd.DataFrame | None]: + pack_dir = Path(pack_dir) + laws_path = None + arts_path = None + for cand in (pack_dir / "data" / "laws.parquet", pack_dir / "laws.parquet"): + if cand.is_file(): + laws_path = cand + break + for cand in (pack_dir / "data" / "articles.parquet", pack_dir / "articles.parquet"): + if cand.is_file(): + arts_path = cand + break + laws = pd.read_parquet(laws_path) if laws_path else None + arts = pd.read_parquet(arts_path) if arts_path else None + return laws, arts + + +def write_pack( + out: Path, + laws: pd.DataFrame, + articles: pd.DataFrame, + *, + slug: str, + source_dataset: str, + name: str | None = None, + extra_meta: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Write a local pack that ``load_source`` / ``get_country`` can consume.""" + out = Path(out) + data_dir = out / "data" + data_dir.mkdir(parents=True, exist_ok=True) + laws_path = data_dir / "laws.parquet" + arts_path = data_dir / "articles.parquet" + laws.to_parquet(laws_path, index=False) + articles.to_parquet(arts_path, index=False) + now = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") + meta = { + "slug": slug, + "repo": source_dataset, + "source_dataset": source_dataset, + "name": name or slug.replace("_", " ").title(), + "indexable": True, + "source_revision": f"local:{now}", + "n_laws": int(len(laws)), + "n_articles": int(len(articles)), + "laws_sha256": sha256_file(laws_path), + "articles_sha256": sha256_file(arts_path), + "generated_at": now, + "incremental": True, + } + if extra_meta: + meta.update(extra_meta) + (out / "pack_meta.json").write_text( + json.dumps(meta, indent=2, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + return meta + + +def package_instruments( + *, + instruments_dir: Path, + out: Path, + slug: str, + source_dataset: str | None = None, + prior_pack: Path | None = None, + name: str | None = None, + min_body_chars: int = MIN_BODY_CHARS, +) -> dict[str, Any]: + """Merge collector JSON (+ optional prior parquet) into a local IR source pack.""" + incoming_laws, incoming_arts, extract_report = instruments_to_frames( + instruments_dir, min_body_chars=min_body_chars + ) + prior_laws = prior_arts = None + prior_dir = Path(prior_pack) if prior_pack else (out if out.exists() else None) + if prior_dir is not None: + prior_laws, prior_arts = load_existing_parquet(prior_dir) + laws = merge_laws(prior_laws, incoming_laws) + articles = merge_articles(prior_arts, incoming_arts) + if laws.empty: + raise RuntimeError( + f"no laws with text>={min_body_chars} under {instruments_dir}" + ) + repo = source_dataset or f"endomorphosis/ipfs_{slug}_laws" + meta = write_pack( + out, + laws, + articles, + slug=slug, + source_dataset=repo, + name=name, + extra_meta={"extract": extract_report}, + ) + meta["extract"] = extract_report + meta["n_laws_prior"] = int(len(prior_laws)) if prior_laws is not None else 0 + meta["n_articles_prior"] = int(len(prior_arts)) if prior_arts is not None else 0 + meta["n_laws_incoming"] = int(len(incoming_laws)) + meta["n_articles_incoming"] = int(len(incoming_arts)) + meta["out"] = str(out) + return meta + + +def default_instruments_dir(iso_or_slug: str, root: Path | None = None) -> Path: + base = Path(root) if root is not None else DEFAULT_CORPORA_ROOT + return base / iso_or_slug / "instruments" diff --git a/country_laws_ir/sparse.py b/country_laws_ir/sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed793543ef74b1c48e313ee29cada56fd2aface --- /dev/null +++ b/country_laws_ir/sparse.py @@ -0,0 +1,137 @@ +"""Country-law sparse GraphRAG export through the shared HF GraphRAG builders. + +This is the same parquet layout used by US Code, state laws, Federal Register, +and SkillCenter: + +* ``ipfs_datasets_py.retrieval.hf_graphrag.bm25.build_bm25_layout`` +* ``ipfs_datasets_py.retrieval.hf_graphrag.graph.write_graph_layout`` + +No SQLite. Indexes are ZSTD parquet shards under ``data/bm25`` and +``data/graph``. DuckDB queries those shards at read time. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pandas as pd + +from . import EDGE_IDENTITY_SCHEMA, SCHEMA_VERSION +from .cidutil import cid_of_json +from .graph import build_graph + + +def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]: + """Project a normalized country-law corpus onto the shared BM25 row schema. + + Rows with no searchable tokens are omitted. The shared + ``build_bm25_layout`` builder fail-closes on empty documents (same + admission rule as US Code / Federal Register). + """ + from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text + + _MAX_TITLE = 8_192 + _MAX_BODY = 200_000 + rows: list[dict[str, Any]] = [] + for rec in corpus.itertuples(index=False): + title = str(getattr(rec, "title", "") or "").replace("\x00", "").strip() + body = str(getattr(rec, "body", "") or "").replace("\x00", "").strip() + if len(title) > _MAX_TITLE: + title = title[:_MAX_TITLE].rstrip() + if len(body) > _MAX_BODY: + body = body[:_MAX_BODY].rstrip() + if not title and not body: + continue + if not tokenize_bm25_text(title) and not tokenize_bm25_text(body): + continue + rows.append( + { + "entry_cid": str(rec.entry_cid), + "title": title, + "body": body, + "record_type": str(getattr(rec, "record_type", "") or "law"), + "document_index": int(rec.document_index), + } + ) + if not rows: + raise RuntimeError("no corpus rows had searchable BM25 tokens") + for i, row in enumerate(rows): + row["document_index"] = i + return rows + + +def _graph_nodes_and_edges(corpus: pd.DataFrame) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Structural graph only (no precomputed BM25 neighbor matrix).""" + built = build_graph(corpus, [[] for _ in range(len(corpus))]) + nodes = [ + { + "node_cid": str(row["node_cid"]), + "node_type": str(row["node_type"]), + "label": row.get("label"), + "entry_cid": row.get("entry_cid") or None, + } + for row in built["nodes"].to_dict("records") + ] + edges = [] + for row in built["edges"].to_dict("records"): + source = str(row.get("source_cid") or row.get("source_node_cid") or "") + target = str(row.get("target_cid") or row.get("target_node_cid") or "") + edge_type = str(row.get("edge_type") or "") + if not source or not target or not edge_type: + continue + edge_cid = str(row.get("edge_cid") or "") or cid_of_json( + { + "edge_type": edge_type, + "schema": EDGE_IDENTITY_SCHEMA, + "source": source, + "target": target, + } + ) + edges.append( + { + "edge_cid": edge_cid, + "edge_type": edge_type, + "source_node_cid": source, + "target_node_cid": target, + "retrieval_method": str(row.get("retrieval_method") or "structural"), + "score": row.get("score"), + } + ) + return nodes, edges + + +def export_sparse_graphrag( + corpus: pd.DataFrame, + output_dir: Path, +) -> dict[str, Any]: + """Write BM25 + graph parquet shards using the shared HF GraphRAG builders.""" + from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import ( + BM25LayoutConfig, + build_bm25_layout, + ) + from ipfs_datasets_py.retrieval.hf_graphrag.graph import write_graph_layout + + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + rows = corpus_to_bm25_rows(corpus) + bm25 = build_bm25_layout( + rows, + output_dir, + config=BM25LayoutConfig(max_documents=max(len(rows), 1)), + ) + nodes, edges = _graph_nodes_and_edges(corpus) + written = write_graph_layout(nodes, edges, output_dir) + layout = written.layout + return { + "engine": "hf_graphrag", + "schema_version": SCHEMA_VERSION, + "bm25": bm25.to_manifest_fragment(), + "graph": { + "node_count": int(layout.node_count), + "edge_count": int(layout.edge_count), + "adjacency": "data/graph/adjacency/{out,in}/*.parquet", + }, + "sqlite": False, + "query_engine": "duckdb", + } diff --git a/country_laws_ir/spill.py b/country_laws_ir/spill.py index 4165b480d20436301555ab206b43f07cbe4cfd08..208b549fe475cc6f34575aa2518289a6c6cdd275 100644 --- a/country_laws_ir/spill.py +++ b/country_laws_ir/spill.py @@ -1,17 +1,15 @@ -"""Disk-spill helpers for large country IR builds (SQLite FTS neighbors + BM25 TF). +"""Disk-spill helpers for large country IR builds (DuckDB + parquet). Design (CoS / DO OOM lesson): - Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged). -- Neighbors for n >= SQLITE_THRESHOLD (40k): SQLite FTS5 title-only MATCH streaming - into neighbor_*.pkl shards under cache/_bm25_spill/ — never hold full - neighbor matrix in RAM during streaming. -- BM25 TF: stream tokenize → SQLite WITHOUT ROWID → posting parquet parts. -- Package: use package.package_release_sequential / package_from_spill so corpus, - bm25, graph, vectors are never all resident together; neighbor edges can be - streamed from shards into graph then spilled as graph.pkl. - -Resume-safe: existing FTS DB / neighbor shards / bm25_*.parquet are reused when -row counts match. +- Neighbors for n >= DUCKDB_THRESHOLD (40k): DuckDB FTS over corpus parquet, + streamed into neighbor_*.parquet shards — never hold the full neighbor + matrix in RAM. +- BM25 TF: stream tokenize → DuckDB → posting parquet parts. +- Package: sequential parquet write so corpus, bm25, graph, vectors are never + all resident together. + +No SQLite. Intermediate and published artifacts are parquet / DuckDB. """ from __future__ import annotations @@ -19,7 +17,6 @@ import gc import json import math import pickle -import sqlite3 from collections import defaultdict from pathlib import Path from typing import Any, Callable, Iterable, Iterator @@ -41,7 +38,8 @@ from .graph import _adjacency, _edge, build_graph from .mem import MemAbort, checkpoint, log_mem from .tokenize import tokenize -SQLITE_THRESHOLD = 40_000 +DUCKDB_THRESHOLD = 40_000 +SQLITE_THRESHOLD = DUCKDB_THRESHOLD # backward-compatible alias; not SQLite BATCH = 256 NEIGHBOR_SHARD = 5_000 NEIGHBOR_K = 8 @@ -68,19 +66,24 @@ def load_pickle(path: Path) -> Any: return pickle.load(f) -def quote_fts_term(term: str) -> str: - return '"' + term.replace('"', '""') + '"' - - def _idf(n_docs: int, df: int) -> float: return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0) -def sqlite_ready(db_path: Path, expected: int) -> bool: +def _require_duckdb(): + try: + import duckdb # type: ignore + except ImportError as exc: + raise RuntimeError("duckdb is required for sparse GraphRAG spill (no sqlite)") from exc + return duckdb + + +def duckdb_ready(db_path: Path, expected: int) -> bool: if not db_path.is_file(): return False + duckdb = _require_duckdb() try: - conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) + conn = duckdb.connect(str(db_path), read_only=True) n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0]) conn.close() return n == expected @@ -88,265 +91,49 @@ def sqlite_ready(db_path: Path, expected: int) -> bool: return False -def build_sqlite_fts( - corpus_path: Path, - db_path: Path, - expected: int, - *, - batch: int = BATCH, - log: Callable[[str], None] | None = None, -) -> int: - """Contentless FTS5 over title+body; documents table holds query_text.""" - if db_path.exists(): - db_path.unlink() - db_path.parent.mkdir(parents=True, exist_ok=True) - conn = sqlite3.connect(str(db_path)) - try: - conn.executescript( - """ - PRAGMA journal_mode = OFF; - PRAGMA synchronous = OFF; - PRAGMA temp_store = MEMORY; - PRAGMA locking_mode = EXCLUSIVE; - PRAGMA page_size = 32768; - CREATE TABLE documents ( - document_index INTEGER PRIMARY KEY, - entry_cid TEXT NOT NULL UNIQUE, - title TEXT NOT NULL, - query_text TEXT NOT NULL - ); - CREATE VIRTUAL TABLE documents_fts USING fts5( - title, - body, - content='', - columnsize=1, - tokenize='unicode61 remove_diacritics 2' - ); - """ - ) - pf = pq.ParquetFile(corpus_path) - n = 0 - meta_batch: list[tuple] = [] - fts_batch: list[tuple] = [] - conn.execute("BEGIN") - for batch_tbl in pf.iter_batches( - batch_size=batch, columns=["document_index", "entry_cid", "title", "body"] - ): - cols = batch_tbl.to_pydict() - for i in range(len(cols["document_index"])): - di = int(cols["document_index"][i]) - title = str(cols["title"][i] or "") - body = str(cols["body"][i] or "") - cid = str(cols["entry_cid"][i]) - qtext = title.strip() if title.strip() else body[:800] - meta_batch.append((di, cid, title, qtext)) - fts_batch.append((di + 1, title, body)) - if len(meta_batch) >= batch: - conn.executemany( - "INSERT INTO documents(document_index, entry_cid, title, query_text) " - "VALUES (?,?,?,?)", - meta_batch, - ) - conn.executemany( - "INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)", - fts_batch, - ) - n += len(meta_batch) - meta_batch.clear() - fts_batch.clear() - if n % 20_000 == 0: - checkpoint(f"fts_insert@{n}", row=n, every_n=20_000, log=log) - gc.collect() - if meta_batch: - conn.executemany( - "INSERT INTO documents(document_index, entry_cid, title, query_text) " - "VALUES (?,?,?,?)", - meta_batch, - ) - conn.executemany( - "INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)", - fts_batch, - ) - n += len(meta_batch) - conn.commit() - conn.execute("INSERT INTO documents_fts(documents_fts) VALUES('optimize')") - conn.commit() - conn.execute( - "CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')" - ) - conn.commit() - got = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0]) - assert got == n == expected, (got, n, expected) - return n - except Exception: - conn.rollback() - raise - finally: - conn.close() - gc.collect() +def build_sqlite_fts(*args, **kwargs): # pragma: no cover - removed + raise RuntimeError("SQLite FTS is removed; use DuckDB parquet neighbors") -def load_df_map(conn: sqlite3.Connection, df_cap: int = DF_CAP) -> dict[str, int]: - df_map: dict[str, int] = {} - for term, doc in conn.execute( - "SELECT term, doc FROM documents_vocab WHERE doc <= ?", (df_cap,) - ): - df_map[str(term)] = int(doc) - return df_map - - -def select_query_terms(query_text: str, df_map: dict[str, int]) -> list[str]: - toks = tokenize(query_text)[:24] - seen: set[str] = set() - cands: list[tuple[int, str]] = [] - for t in toks: - if t in seen or len(t) < 2: - continue - seen.add(t) - if t not in df_map: - continue - cands.append((df_map[t], t)) - cands.sort() - return [t for _, t in cands[:MAX_QTERMS]] - - -def stream_neighbors_to_shards( - db_path: Path, +def neighbors_via_duckdb( + corpus_path: Path, spill: Path, n_docs: int, *, k: int = NEIGHBOR_K, - shard: int = NEIGHBOR_SHARD, - batch: int = BATCH, - df_cap: int = DF_CAP, resume: bool = True, log: Callable[[str], None] | None = None, ) -> list[Path]: - """Stream FTS5 title-only neighbors into neighbor_START_END.pkl shards. + """DuckDB FTS over corpus parquet → neighbor_*.parquet shards. No SQLite.""" + from .duckdb_store import build_fts_index, stream_neighbors_to_parquet - Does not assemble the full neighbor list. Resume skips shards already on disk - whose end index is covered (contiguous from 0). - """ + spill = Path(spill) spill.mkdir(parents=True, exist_ok=True) - existing = sorted(spill.glob("neighbors_*.pkl")) - buf_start = 0 - shard_paths: list[Path] = [] - if resume and existing: - # Contiguous cover from 0 - covered = 0 - for sp in existing: - parts = sp.stem.split("_") - # neighbors_000000_005000 - try: - start_i, end_i = int(parts[1]), int(parts[2]) - except (IndexError, ValueError): - continue - if start_i != covered: - break - shard_paths.append(sp) - covered = end_i - buf_start = covered - if buf_start >= n_docs: - if log: - log(f"neighbors resume complete {buf_start}/{n_docs}") - return shard_paths + db_path = spill / "neighbors.duckdb" + if not duckdb_ready(db_path, n_docs): + if db_path.exists(): + db_path.unlink() if log: - log(f"neighbors resume from {buf_start}/{n_docs} shards={len(shard_paths)}") - # Drop non-contiguous leftover shards beyond covered - for sp in existing: - if sp not in shard_paths: - sp.unlink(missing_ok=True) + log(f"building duckdb fts n={n_docs} -> {db_path}") + build_fts_index(corpus_path, db_path, n_docs, log=log) else: - for sp in existing: - sp.unlink(missing_ok=True) - - conn_rw = sqlite3.connect(str(db_path)) - row = conn_rw.execute( - "SELECT name FROM sqlite_master WHERE name='documents_vocab'" - ).fetchone() - if row is None: - conn_rw.execute( - "CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')" - ) - conn_rw.commit() - df_map = load_df_map(conn_rw, df_cap) - conn_rw.close() - spill_pickle(spill / "df_map_meta.pkl", {"n_rare": len(df_map), "df_cap": df_cap}) - if log: - log(f"vocab rare_terms={len(df_map)} df_cap={df_cap}") - - conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) - conn.row_factory = sqlite3.Row - buf: list = [] - done = buf_start - score_sql = f"-bm25(documents_fts, {TITLE_W}, {BODY_W})" - last_idx = buf_start - 1 - try: - while True: - rows = conn.execute( - "SELECT document_index, entry_cid, query_text FROM documents " - "WHERE document_index > ? ORDER BY document_index LIMIT ?", - (last_idx, batch), - ).fetchall() - if not rows: - break - for row in rows: - di = int(row["document_index"]) - terms = select_query_terms(str(row["query_text"]), df_map) - if not terms: - neigh: list = [] - else: - expr = " OR ".join("title : " + quote_fts_term(t) for t in terms) - sql = ( - "SELECT d.document_index, " + score_sql + " AS score " - "FROM documents_fts " - "JOIN documents AS d ON d.document_index = documents_fts.rowid - 1 " - "WHERE documents_fts MATCH ? AND d.document_index != ? " - "ORDER BY score DESC, d.document_index LIMIT ?" - ) - hits = conn.execute(sql, (expr, di, k)).fetchall() - neigh = [ - (int(h["document_index"]), max(0.0, float(h["score"])), list(terms)[:4]) - for h in hits - ] - while buf_start + len(buf) < di: - buf.append([]) - buf.append(neigh) - last_idx = di - done += 1 - if len(buf) >= shard: - end = buf_start + len(buf) - sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl" - spill_pickle(sp, buf) - shard_paths.append(sp) - checkpoint( - f"neighbors_shard_{buf_start}_{end}", - log=log, - ) - buf_start = end - buf = [] - gc.collect() - if done % 5_000 == 0: - checkpoint(f"neighbors_stream", row=done, every_n=5_000, log=log) - if buf: - end = buf_start + len(buf) - sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl" - spill_pickle(sp, buf) - shard_paths.append(sp) - if log: - log(f"neighbors shard final {buf_start}:{end}/{n_docs}") if log: - log(f"bm25 neighbors streamed done={done} n_docs={n_docs} shards={len(shard_paths)}") - return shard_paths - finally: - conn.close() - del df_map - gc.collect() + log(f"reusing duckdb fts n={n_docs} path={db_path}") + return stream_neighbors_to_parquet( + db_path, spill, n_docs, k=k, resume=resume, log=log + ) def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]: - """Yield (start_index, shard_list) without loading all shards.""" - paths = sorted(spill.glob("neighbors_*.pkl")) + """Yield (start_index, shard_list) from parquet neighbor shards.""" + from .duckdb_store import iter_neighbor_parquet_shards + + parquet = list(Path(spill).glob("neighbors_*.parquet")) + if parquet: + yield from iter_neighbor_parquet_shards(spill) + return + # Legacy pickle shards (pre-DuckDB). Do not create new ones. + paths = sorted(Path(spill).glob("neighbors_*.pkl")) for sp in paths: parts = sp.stem.split("_") start_i = int(parts[1]) @@ -369,30 +156,9 @@ def assemble_neighbors_streaming(spill: Path, n_docs: int) -> list: return neighbors -def neighbors_via_sqlite( - corpus_path: Path, - spill: Path, - n_docs: int, - *, - k: int = NEIGHBOR_K, - resume: bool = True, - log: Callable[[str], None] | None = None, -) -> list[Path]: - """Ensure FTS DB + neighbor shards; return shard paths (not full list).""" - spill.mkdir(parents=True, exist_ok=True) - db_path = spill / "fts.sqlite" - if not sqlite_ready(db_path, n_docs): - if db_path.exists(): - db_path.unlink() - if log: - log(f"building sqlite fts n={n_docs} -> {db_path}") - build_sqlite_fts(corpus_path, db_path, n_docs, log=log) - else: - if log: - log(f"reusing sqlite fts n={n_docs} path={db_path}") - return stream_neighbors_to_shards( - db_path, spill, n_docs, k=k, resume=resume, log=log - ) +def neighbors_via_sqlite(*args, **kwargs): + """Removed. Sparse GraphRAG neighbors are DuckDB/parquet only.""" + return neighbors_via_duckdb(*args, **kwargs) def build_graph_from_neighbor_shards( @@ -492,33 +258,35 @@ def build_bm25_tf_spill( batch: int = 512, log: Callable[[str], None] | None = None, ) -> dict[str, Any]: - """Stream tokenize corpus → SQLite TF → bm25_documents/postings parquet + stats. + """Stream tokenize corpus → DuckDB TF → bm25_documents/postings parquet + stats. - Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.pkl exist + Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.json exist with matching n_docs, reuse. """ spill.mkdir(parents=True, exist_ok=True) docs_path = spill / "bm25_documents.parquet" post_path = spill / "bm25_postings.parquet" + stats_json = spill / "bm25_stats.json" stats_path = spill / "bm25_stats.pkl" - if docs_path.is_file() and post_path.is_file() and stats_path.is_file(): - stats = load_pickle(stats_path) - if int(stats.get("n_docs", -1)) == n_docs: + if docs_path.is_file() and post_path.is_file(): + stats = None + if stats_json.is_file(): + stats = json.loads(stats_json.read_text(encoding="utf-8")) + elif stats_path.is_file(): + stats = load_pickle(stats_path) + if stats is not None and int(stats.get("n_docs", -1)) == n_docs: if log: log(f"reusing bm25 spill n_docs={n_docs}") return {"stats": stats, "documents": docs_path, "postings": post_path} - bm25_sql = spill / "bm25_tf.sqlite" - if bm25_sql.exists(): - bm25_sql.unlink() - conn = sqlite3.connect(str(bm25_sql)) - conn.execute("PRAGMA journal_mode=OFF") - conn.execute("PRAGMA synchronous=OFF") - conn.execute("PRAGMA temp_store=MEMORY") - conn.execute("PRAGMA locking_mode=EXCLUSIVE") + duckdb = _require_duckdb() + bm25_db = spill / "bm25_tf.duckdb" + if bm25_db.exists(): + bm25_db.unlink() + conn = duckdb.connect(str(bm25_db)) conn.execute( - "CREATE TABLE tf (term TEXT NOT NULL, doc INTEGER NOT NULL, " - "ttf INTEGER NOT NULL, btf INTEGER NOT NULL, PRIMARY KEY(term, doc)) WITHOUT ROWID" + "CREATE TABLE tf (term VARCHAR NOT NULL, doc INTEGER NOT NULL, " + "ttf INTEGER NOT NULL, btf INTEGER NOT NULL)" ) title_len = np.zeros(n_docs, dtype=np.int32) body_len = np.zeros(n_docs, dtype=np.int32) @@ -549,7 +317,6 @@ def build_bm25_tf_spill( ] processed = 0 batch_rows: list[tuple] = [] - conn.execute("BEGIN") for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols): d = batch_tbl.to_pydict() m = len(d["document_index"]) @@ -593,9 +360,7 @@ def build_bm25_tf_spill( } ) if len(batch_rows) >= 20_000: - conn.executemany( - "INSERT OR REPLACE INTO tf VALUES (?,?,?,?)", batch_rows - ) + conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows) batch_rows.clear() processed += m if len(meta_buf) >= 20_000: @@ -612,7 +377,7 @@ def build_bm25_tf_spill( checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log) gc.collect() if batch_rows: - conn.executemany("INSERT OR REPLACE INTO tf VALUES (?,?,?,?)", batch_rows) + conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows) batch_rows.clear() if meta_buf: dfm = pd.DataFrame(meta_buf) @@ -623,9 +388,8 @@ def build_bm25_tf_spill( dfm.to_parquet(meta_path, index=False) del dfm meta_buf.clear() - conn.commit() if log: - log("bm25 tf spilled; writing documents") + log("bm25 tf spilled to duckdb; writing documents") doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64) avgdl = float(doc_len.mean()) if n_docs else 0.0 @@ -696,7 +460,7 @@ def build_bm25_tf_spill( for term, doc, ttf, btf in conn.execute( "SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc" - ): + ).fetchall(): term = str(term) if cur_term is None: cur_term = term @@ -749,9 +513,9 @@ def build_bm25_tf_spill( "n_posting_rows": int(out_rows), "n_postings": int(n_postings), } - spill_pickle(stats_path, stats) + stats_json.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8") try: - bm25_sql.unlink() + bm25_db.unlink() except Exception: pass if log: @@ -759,5 +523,10 @@ def build_bm25_tf_spill( return {"stats": stats, "documents": docs_path, "postings": post_path} -def should_use_sqlite(n_docs: int, threshold: int = SQLITE_THRESHOLD) -> bool: +def should_use_spill(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool: return n_docs >= threshold + + +def should_use_sqlite(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool: + """Alias: large-corpus path is DuckDB/parquet, not SQLite.""" + return should_use_spill(n_docs, threshold) diff --git a/country_laws_ir/structure.py b/country_laws_ir/structure.py new file mode 100644 index 0000000000000000000000000000000000000000..468ecfdfff4eb76dc26a92c33c0e0e82d12c3712 --- /dev/null +++ b/country_laws_ir/structure.py @@ -0,0 +1,305 @@ +"""Extract legal hierarchy from country-law text (Oregon-style, multilingual). + +Oregon Revised Statutes are stored as title / chapter / section / subsection +trees. National gazettes are not that uniform: some use Article/Artikel, +some §, some only a single instrument body. + +This module: + +* strips leftover HTML chrome so GraphRAG sees legal text, not tags; +* detects multilingual heading markers (title/chapter/part/article/section); +* splits an instrument into those units when at least two headings exist; +* otherwise keeps the whole instrument (never invents a hierarchy). + +Subsection markers such as ``(a)`` / ``(1)`` are recorded on the parent +unit; they are not forced into their own retrieval rows. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from html.parser import HTMLParser +import html as html_lib +import re +import unicodedata +from typing import Any + +_WS_RE = re.compile(r"\s+", re.UNICODE) +_HAS_TAG_RE = re.compile(r"]*>") + +# Line-anchored headings. Numbers may be arabic, roman, or dotted (1.2). +_HEADING_RE = re.compile( + r"(?im)^[ \t]*(?:" + r"(?PTITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|T[IÍ]TUL)\s+" + r"(?P<title_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" + r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|CAP\.)\s+" + r"(?P<chapter_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" + r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL)\s+" + r"(?P<part_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" + r"|(?P<article>ART(?:ICLE|IKEL|ÍCULO|IGO|ICOLO|IKKEL)?\.?|ART\." + r"|ČLÁNEK|ČLÁNOK|ČLAN|SZAKASZ|ΆΡΘΡΟ|ΑΡΘΡΟ)\s+" + r"(?P<article_n>[0-9IVXLCDMΑ-Ω]+[A-Za-zΑ-Ωa-z0-9.\-]*)" + r"|(?P<section>SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|SEC\.)\s+" + r"(?P<section_n>[0-9A-Za-z.\-]+)" + r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9A-Za-z.\-]+)" + r")" + r"(?P<rest>[^\n]{0,200})?" +) + +_SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)") + +_KIND_RANK = { + "title": 1, + "chapter": 2, + "part": 3, + "article": 4, + "section": 5, + "subsection": 6, +} + +MIN_SPLIT_HEADINGS = 2 +MIN_UNIT_CHARS = 40 + +_ZH_ART_RE = re.compile( + r"(?:(?<=\n)|^)[  ]*" + r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)" +) +_AR_ART_RE = re.compile( + r"(?:(?<=\n)|^)[ \t]*(المادة|مادة)\s*([0-9٠-٩]+)" +) +_JA_ART_RE = re.compile( + r"(?:(?<=\n)|^)[  ]*(第[0-9一二三四五六七八九十百]+条)" +) + + +class _HTMLText(HTMLParser): + SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"} + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.parts: list[str] = [] + self.skip = 0 + + def handle_starttag(self, tag, attrs): + if tag in self.SKIP: + self.skip += 1 + if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0: + self.parts.append("\n") + + def handle_endtag(self, tag): + if tag in self.SKIP and self.skip: + self.skip -= 1 + if tag in {"p", "div", "li", "tr"} and self.skip == 0: + self.parts.append("\n") + + def handle_data(self, data): + if self.skip == 0: + self.parts.append(data) + + +def has_html_tags(text: str) -> bool: + return bool(text and _HAS_TAG_RE.search(text)) + + +def strip_html(raw: str) -> str: + """Turn leftover HTML into visible legal text. No-op if there are no tags.""" + if not raw or not _HAS_TAG_RE.search(raw): + return raw + parser = _HTMLText() + try: + parser.feed(raw) + parser.close() + text = "".join(parser.parts) + except Exception: + text = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw) + text = re.sub(r"(?is)<style.*?>.*?</style>", " ", text) + text = re.sub(r"(?is)<[^>]+>", " ", text) + text = html_lib.unescape(text).replace("\xa0", " ") + text = re.sub(r"[ \t]+", " ", text) + text = re.sub(r"\n[ \t]+", "\n", text) + text = re.sub(r"\n{3,}", "\n\n", text) + return text.strip() + + +def normalize_legal_text(value: Any) -> str: + """NFKC + HTML strip. Keeps newlines so heading detection still works.""" + if value is None: + return "" + text = unicodedata.normalize("NFKC", str(value)) + text = strip_html(text) + text = text.replace("\xa0", " ") + text = re.sub(r"[ \t]+", " ", text) + text = re.sub(r"\n[ \t]+", "\n", text) + text = re.sub(r"\n{3,}", "\n\n", text) + return text.strip() + + +@dataclass +class StructureUnit: + kind: str + number: str + heading: str + body: str + title_number: str = "" + chapter_number: str = "" + part_number: str = "" + article_number: str = "" + section_number: str = "" + subsections: tuple[str, ...] = () + hierarchy_path: str = "" + + def to_dict(self) -> dict[str, Any]: + return { + "kind": self.kind, + "number": self.number, + "heading": self.heading, + "body": self.body, + "title_number": self.title_number, + "chapter_number": self.chapter_number, + "part_number": self.part_number, + "article_number": self.article_number, + "section_number": self.section_number, + "subsections": list(self.subsections), + "hierarchy_path": self.hierarchy_path, + } + + +def _cursor_path(cursor: dict[str, str]) -> str: + parts = [] + for key, label in ( + ("title", "Title"), + ("chapter", "Chapter"), + ("part", "Part"), + ("article", "Article"), + ("section", "Section"), + ): + value = cursor.get(key) or "" + if value: + parts.append(f"{label} {value}") + return " > ".join(parts) + + +def _subsection_tokens(text: str) -> tuple[str, ...]: + seen: list[str] = [] + for match in _SUBSECTION_RE.finditer(text): + token = match.group(1) + if token not in seen: + seen.append(token) + if len(seen) >= 40: + break + return tuple(seen) + + +def _units_from_regex( + text: str, matches: list[re.Match[str]], *, kind: str, lang: str +) -> list[StructureUnit]: + if len(matches) < MIN_SPLIT_HEADINGS: + return [] + units: list[StructureUnit] = [] + for i, match in enumerate(matches): + start = match.start() + end = matches[i + 1].start() if i + 1 < len(matches) else len(text) + chunk = text[start:end].strip() + if len(chunk) < 16: + continue + number = re.sub(r"\s+", "", match.group(0)) + heading = re.sub(r"\s+", " ", chunk.split("\n", 1)[0])[:240] + units.append( + StructureUnit( + kind=kind, + number=number, + heading=heading, + body=chunk, + article_number=number, + hierarchy_path=heading, + ) + ) + return units if len(units) >= MIN_SPLIT_HEADINGS else [] + + +def split_script_units(text: str, language: str) -> list[StructureUnit]: + """Article splits for scripts that must not use Latin TITLE/ARTICLE.""" + from .profiles import iso_lang + + lang = iso_lang(language) + if lang in {"zh", "zh-cn", "zh-tw"}: + prepared = re.sub( + r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)", + r"\n\1", + text, + ) + return _units_from_regex(prepared, list(_ZH_ART_RE.finditer(prepared)), kind="article", lang="zh") + if lang in {"ar", "fa"}: + prepared = re.sub(r"(المادة|مادة)", r"\n\1", text) + return _units_from_regex(prepared, list(_AR_ART_RE.finditer(prepared)), kind="article", lang="ar") + if lang == "ja": + prepared = re.sub(r"(第[0-9一二三四五六七八九十百]+条)", r"\n\1", text) + return _units_from_regex(prepared, list(_JA_ART_RE.finditer(prepared)), kind="article", lang="ja") + return [] + + +def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]: + """Split *text* on legal headings. Empty list means keep the whole instrument. + + Latin TITLE/ARTICLE splits are skipped for languages in + ``profiles.NO_LATIN_SPLIT_LANGS`` so Arabic/Chinese bodies are not + carved up on incidental English words. + """ + from .profiles import latin_split_allowed + + if not text or len(text) < 16: + return [] + if language and not latin_split_allowed(language): + return split_script_units(text, language) + matches = list(_HEADING_RE.finditer(text)) + if len(matches) < MIN_SPLIT_HEADINGS: + return [] + cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""} + units: list[StructureUnit] = [] + for i, match in enumerate(matches): + start = match.start() + end = matches[i + 1].start() if i + 1 < len(matches) else len(text) + chunk = text[start:end].strip() + kind = "" + number = "" + for name in ("title", "chapter", "part", "article", "section"): + if match.group(name): + kind = name + number = (match.group(f"{name}_n") or "").strip() + break + if match.group("section_sym"): + kind = "section" + number = (match.group("section_sym_n") or "").strip() + if not kind or not number: + continue + cursor[kind] = number + for lower, rank in _KIND_RANK.items(): + if rank > _KIND_RANK[kind]: + cursor[lower] = "" + if len(chunk) < MIN_UNIT_CHARS: + continue + rest = (match.group("rest") or "").strip(" .-:") + heading = re.sub(r"\s+", " ", match.group(0)).strip() + if rest and rest not in heading: + heading = f"{heading} {rest}".strip() + units.append( + StructureUnit( + kind=kind, + number=number, + heading=heading[:240], + body=chunk, + title_number=cursor["title"], + chapter_number=cursor["chapter"], + part_number=cursor["part"], + article_number=cursor["article"], + section_number=cursor["section"], + subsections=_subsection_tokens(chunk), + hierarchy_path=_cursor_path(cursor), + ) + ) + retrieval = [u for u in units if u.kind in {"article", "section"}] + if len(retrieval) >= MIN_SPLIT_HEADINGS: + return retrieval + if len(units) >= MIN_SPLIT_HEADINGS: + return units + return [] diff --git a/country_laws_ir/upload.py b/country_laws_ir/upload.py index 7a40ae7f15d2bad04939d6506de83737f3375336..182e81b8d9d799dce63653f45feaabdfa3c61e84 100644 --- a/country_laws_ir/upload.py +++ b/country_laws_ir/upload.py @@ -1,24 +1,132 @@ -"""Hub upload is intentionally not implemented in this local pipeline. +"""Publish a local country-laws-ir release to the JusticeDAO Hugging Face org. -Later publish (operator machine, never from this run): - - export HF_TOKEN=... # never commit / never echo - hf upload-large-folder justicedao/ipfs_malta_laws_ir \\ - /workspace/country-laws-ir/releases/ipfs_malta_laws_ir \\ - --repo-type dataset --no-private --num-workers 8 \\ - --exclude "**/__pycache__/**" --exclude "**/*.pyc" +Reads stay anonymous (see ``auth.py``). Writes require an explicit ``--upload`` +path, a ``justicedao/`` repo id, and ``HF_TOKEN``. Protected LCR repositories +are fail-closed via ``require_unprotected_or_runtime``. """ from __future__ import annotations +import os from pathlib import Path from typing import Any +from . import TARGET_ORG + +_OPERATOR_HINT = ( + "Publish later with: hf upload-large-folder " + "{repo} {local_dir} --repo-type dataset --no-private --num-workers 8 " + '--exclude "**/__pycache__/**" --exclude "**/*.pyc"' +) + + +class UploadError(RuntimeError): + """Raised when a JusticeDAO upload cannot proceed.""" + + +def _token_from_env() -> str: + for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): + value = (os.environ.get(key) or "").strip() + if value: + return value + token_path = Path.home() / ".cache" / "huggingface" / "token" + if token_path.is_file(): + try: + return token_path.read_text(encoding="utf-8").strip() + except OSError: + return "" + return "" + + +def upload_release( + local_dir: Path, + repo_id: str, + *, + token: str | None = None, + commit_message: str | None = None, + create: bool = True, +) -> dict[str, Any]: + local_dir = Path(local_dir) + repo_id = str(repo_id or "").strip() + if not local_dir.is_dir(): + raise UploadError(f"release directory does not exist: {local_dir}") + if not repo_id.startswith(f"{TARGET_ORG}/"): + raise UploadError( + f"country-laws-ir publishes only to {TARGET_ORG}/*; got {repo_id!r}" + ) + if not (local_dir / "manifest.json").is_file(): + raise UploadError(f"release is missing manifest.json: {local_dir}") + + # Fail closed for LCR-protected repos without importing the full package + # (site-packages ipfs_datasets_py can be stale and break this thin packager). + _protected = {"justicedao/ipfs_state_laws", "justicedao/ipfs_federal_register"} + if repo_id in _protected: + raise UploadError( + f"{repo_id} is a protected JusticeDAO repository; " + "mutate it only through legal_corpora_publication_runtime" + ) + try: + from ipfs_datasets_py.huggingface.protected_repo_guard import ( + require_unprotected_or_runtime, + ) + + require_unprotected_or_runtime(repo_id, method="upload_folder") + except UploadError: + raise + except Exception: + pass + + resolved = (token or "").strip() or _token_from_env() + if not resolved: + raise UploadError( + "HF_TOKEN is required for --upload. " + + _OPERATOR_HINT.format(repo=repo_id, local_dir=local_dir) + ) + + from huggingface_hub import HfApi + + api = HfApi(token=resolved) + if create: + api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True, private=False) + ignore = ["**/__pycache__/**", "**/*.pyc", "**/*.tmp", "**/*.tmp.npy"] + n_files = sum(1 for path in local_dir.rglob("*") if path.is_file()) + nbytes = sum(path.stat().st_size for path in local_dir.rglob("*") if path.is_file()) + use_large = n_files >= 80 or nbytes >= 80 * 1024 * 1024 + if use_large and hasattr(api, "upload_large_folder"): + api.upload_large_folder( + folder_path=str(local_dir), + repo_id=repo_id, + repo_type="dataset", + ignore_patterns=ignore, + ) + revision = "" + try: + from huggingface_hub import dataset_info as _dataset_info -def upload_release(local_dir: Path, repo_id: str) -> dict[str, Any]: - raise RuntimeError( - "Hub upload is disabled in the local country-laws-ir pipeline. " - "Publish later with: hf upload-large-folder " - f"{repo_id} {local_dir} --repo-type dataset --no-private --num-workers 8 " - '--exclude "**/__pycache__/**" --exclude "**/*.pyc"' + pinned = _dataset_info(repo_id, token=resolved) + revision = str(getattr(pinned, "sha", "") or "") + except Exception: + revision = "" + return { + "url": f"https://huggingface.co/datasets/{repo_id}", + "repo_id": repo_id, + "revision": revision, + "local_dir": str(local_dir), + "method": "upload_large_folder", + } + info = api.upload_folder( + folder_path=str(local_dir), + repo_id=repo_id, + repo_type="dataset", + commit_message=commit_message + or f"Incremental country-laws-ir GraphRAG release for {repo_id}", + ignore_patterns=ignore, ) + revision = getattr(info, "oid", None) or getattr(info, "commit_id", None) or "" + return { + "url": f"https://huggingface.co/datasets/{repo_id}", + "repo_id": repo_id, + "revision": revision, + "local_dir": str(local_dir), + "method": "upload_folder", + } diff --git a/country_laws_ir/vectors.py b/country_laws_ir/vectors.py index 832330d4cd91244107a3c7080623a23db3eddf55..5651e0f0e052dabffed783715a5b3b4c396a7b5e 100644 --- a/country_laws_ir/vectors.py +++ b/country_laws_ir/vectors.py @@ -14,7 +14,11 @@ import pandas as pd from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION MODEL_NAME = "thenlper/gte-small" +MODEL_REVISION = "17e1f347d17fe144873b1201da91788898c639cd" DIMENSION = 384 +MAX_SEQ_LENGTH = 512 +DEFAULT_DEVICE = "cuda" +SUPPORTED_DEVICES = frozenset({"cpu", "cuda", "cuda:0", "mps", "auto"}) MAX_ROWS_PER_CENTROID = 8192 MAX_SHARDS_PER_CENTROID = 2 @@ -24,41 +28,108 @@ def _l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray: return x / np.maximum(n, eps) -def embeddings_available() -> bool: +def device_is_available(device: str) -> bool: + """Probe accelerator availability without loading a model.""" + name = str(device or "").strip().lower() + if not name or name == "cpu": + return True + try: + import torch + except Exception: + return False + if name.startswith("cuda"): + return bool( + getattr(torch, "cuda", None) + and torch.backends.cuda.is_built() + and torch.cuda.is_available() + ) + if name == "mps": + mps = getattr(getattr(torch, "backends", None), "mps", None) + return bool(mps is not None and mps.is_available()) + return False + + +def select_device(requested: str = DEFAULT_DEVICE) -> tuple[str, bool]: + """Prefer CUDA like US Code / Open US Law; fall back to CPU.""" + req = str(requested or DEFAULT_DEVICE).strip().lower() or DEFAULT_DEVICE + if req == "auto": + req = "cuda" + if req not in SUPPORTED_DEVICES and not req.startswith("cuda:"): + raise ValueError(f"unsupported embedding device: {requested!r}") + if device_is_available(req): + return req, False + return "cpu", True + + +def ensure_embedding_stack() -> bool: + """Lazy-import / lazy-install transformers + sentence-transformers. + + Matches ``ipfs_datasets_py.auto_installer.ensure_module`` used by other + GraphRAG producers. Importing this module must not pip-install; first + encode may. + """ + import os + + os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1") try: - import torch # noqa: F401 - from sentence_transformers import SentenceTransformer # noqa: F401 + import sentence_transformers # noqa: F401 + import transformers # noqa: F401 return True + except Exception: + pass + try: + from ipfs_datasets_py.auto_installer import ensure_module, install_for_component + + install_for_component("graphrag") + ensure_module("torchvision", "torchvision") + ensure_module("transformers", "transformers") + module = ensure_module("sentence_transformers", "sentence-transformers") + return module is not None except Exception: return False +def embeddings_available() -> bool: + return ensure_embedding_stack() + + +def _is_real_vector(vec: object) -> bool: + try: + arr = np.asarray(vec, dtype=np.float32).reshape(-1) + except Exception: + return False + if arr.shape[0] != DIMENSION: + return False + if not np.isfinite(arr).all(): + return False + return float(np.linalg.norm(arr)) > 1e-6 + + def encode_corpus( corpus: pd.DataFrame, batch_size: int = 64, - device: str = "cpu", + device: str = DEFAULT_DEVICE, checkpoint_path: str | None = None, chunk_size: int = 4096, ) -> np.ndarray: - """Encode corpus texts with gte-small in chunks; persist checkpoints when given.""" + """Encode corpus texts with pinned gte-small on CUDA when available.""" import json import os from datetime import datetime, timezone from pathlib import Path as _Path + if not ensure_embedding_stack(): + raise RuntimeError( + "sentence-transformers is required for production GTE embeddings; " + "lazy install failed (python -m ipfs_datasets_py.auto_installer)" + ) from sentence_transformers import SentenceTransformer from .auth import configure_hf configure_hf() - cache_root = _Path("/workspace/country-laws-ir/cache/hf") - os.environ.setdefault("HF_HOME", str(cache_root)) - os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1") - os.environ.setdefault( - "SENTENCE_TRANSFORMERS_HOME", - str(cache_root / "sentence-transformers"), - ) + device, _fallback = select_device(device) texts = [] for rec in corpus.itertuples(index=False): title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or "" @@ -70,12 +141,22 @@ def encode_corpus( done = 0 ckpt = _Path(checkpoint_path) if checkpoint_path else None meta_path = ckpt.with_suffix(".json") if ckpt else None - meta_n = None + cache_root = _Path( + os.environ.get( + "COUNTRY_LAWS_IR_ROOT", + str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"), + ) + ) / "cache" / "hf" + os.environ.setdefault("HF_HOME", str(cache_root)) + os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1") + os.environ.setdefault("SENTENCE_TRANSFORMERS_HOME", str(cache_root / "sentence-transformers")) if meta_path is not None and meta_path.exists(): try: meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n") except Exception: meta_n = None + else: + meta_n = None if ckpt is not None and ckpt.exists(): cached = np.load(ckpt) same_corpus = meta_n is None or int(meta_n) == n @@ -87,56 +168,76 @@ def encode_corpus( ): done = int(cached.shape[0]) out[:done] = cached.astype(np.float32, copy=False) - print(f"embeddings resume {done}/{n} from {ckpt}", flush=True) - else: - print( - f"embeddings checkpoint shape {getattr(cached, 'shape', None)} " - f"meta_n={meta_n} incompatible with {(n, DIMENSION)}; restarting", - flush=True, + if done >= n: + return out + + lock_fh = None + if device.startswith("cuda"): + import fcntl + + lock_path = _Path( + os.environ.get( + "COUNTRY_LAWS_IR_ROOT", + str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"), ) - if done >= n: - return out - model = SentenceTransformer(MODEL_NAME, device=device) - while done < n: - j = min(done + int(chunk_size), n) - chunk = model.encode( - texts[done:j], - batch_size=batch_size, - show_progress_bar=True, - convert_to_numpy=True, - normalize_embeddings=True, + ) / "cuda.encode.lock" + lock_path.parent.mkdir(parents=True, exist_ok=True) + lock_fh = open(lock_path, "a", encoding="utf-8") + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) + try: + model = SentenceTransformer( + MODEL_NAME, + revision=MODEL_REVISION, + device=device, ) - out[done:j] = np.asarray(chunk, dtype=np.float32) - done = j - print(f"embeddings checkpoint {done}/{n}", flush=True) try: - from .mem import checkpoint as _mem_checkpoint - _mem_checkpoint(f"embeddings@{done}", row=done, every_n=max(chunk_size, 4096)) - except Exception as _mem_exc: - # MemAbort should propagate; other import issues are non-fatal - from .mem import MemAbort - if isinstance(_mem_exc, MemAbort): - raise - if ckpt is not None: - ckpt.parent.mkdir(parents=True, exist_ok=True) - tmp = ckpt.with_name(ckpt.name + ".tmp.npy") - np.save(tmp, out[:done]) - tmp.replace(ckpt) - if meta_path is not None: - meta_path.write_text( - json.dumps( - { - "n": n, - "done": done, - "dimension": DIMENSION, - "model_name": MODEL_NAME, - "ts": datetime.now(timezone.utc).isoformat(), - } + model.max_seq_length = MAX_SEQ_LENGTH + except Exception: + pass + while done < n: + j = min(done + int(chunk_size), n) + chunk = model.encode( + texts[done:j], + batch_size=batch_size, + show_progress_bar=True, + convert_to_numpy=True, + normalize_embeddings=True, + ) + out[done:j] = np.asarray(chunk, dtype=np.float32) + done = j + if ckpt is not None: + ckpt.parent.mkdir(parents=True, exist_ok=True) + tmp = ckpt.with_name(ckpt.name + ".tmp.npy") + np.save(tmp, out[:done]) + tmp.replace(ckpt) + if meta_path is not None: + meta_path.write_text( + json.dumps( + { + "n": n, + "done": done, + "dimension": DIMENSION, + "model_name": MODEL_NAME, + "ts": datetime.now(timezone.utc).isoformat(), + } + ) + + "\n", + encoding="utf-8", ) - + "\n", - encoding="utf-8", - ) - return out + return out + finally: + if lock_fh is not None: + import fcntl as _fcntl + + _fcntl.flock(lock_fh.fileno(), _fcntl.LOCK_UN) + lock_fh.close() + try: + import torch as _torch + + if _torch.cuda.is_available(): + _torch.cuda.empty_cache() + except Exception: + pass def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray: @@ -160,25 +261,29 @@ def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]: + """Split vectors into shards of at most *max_size* without unbounded recursion. + + Spherical k-means can fail to split (all points one label). In that case + fall back to an even index split so layout cannot recurse forever. + """ n = len(x) - idx = np.arange(n) - if n <= max_size: - return [idx] - labels = _spherical_kmeans(x, k=2) - clusters = [] - for lab in (0, 1): - members = idx[labels == lab] - if len(members) == 0: + if n == 0: + return [] + pending: list[np.ndarray] = [np.arange(n)] + clusters: list[np.ndarray] = [] + while pending: + idx = pending.pop() + if len(idx) <= max_size: + clusters.append(idx) continue - if len(members) <= max_size: - clusters.append(members) - else: - sub = _recursive_clusters(x[members], max_size=max_size) - clusters.extend([members[s] for s in sub]) - if not clusters: - mid = n // 2 - return [idx[:mid], idx[mid:]] - return clusters + labels = _spherical_kmeans(x[idx], k=2) + parts = [idx[labels == lab] for lab in (0, 1)] + parts = [p for p in parts if len(p)] + if len(parts) < 2 or max(len(p) for p in parts) == len(idx): + mid = len(idx) // 2 + parts = [idx[:mid], idx[mid:]] + pending.extend(parts) + return clusters or [np.arange(n)] def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]: @@ -333,3 +438,85 @@ def layout_stub_vectors(corpus: pd.DataFrame, reason: str) -> dict[str, Any]: ], }, } + + +def assemble_embeddings( + corpus: pd.DataFrame, + prior_by_cid: dict[str, list[float]] | None = None, + *, + encode_missing: bool = True, + batch_size: int = 64, + device: str = DEFAULT_DEVICE, + checkpoint_path: str | None = None, +) -> tuple[np.ndarray, dict[str, Any]]: + """Align a (n, 384) matrix to *corpus* row order. + + Reuse is CID-keyed and only accepts real GTE vectors (finite, 384-d, + non-zero). Stub/zero priors are treated as missing and re-encoded on + CUDA when available — the US Code / Open US Law contract. + """ + n = int(len(corpus)) + out = np.zeros((n, DIMENSION), dtype=np.float32) + prior = prior_by_cid or {} + reused_idx: list[int] = [] + missing_idx: list[int] = [] + cids = corpus["entry_cid"].astype(str).tolist() if n else [] + for i, cid in enumerate(cids): + vec = prior.get(cid) + if not _is_real_vector(vec): + missing_idx.append(i) + continue + out[i] = np.asarray(vec, dtype=np.float32).reshape(-1) + reused_idx.append(i) + + report: dict[str, Any] = { + "n_docs": n, + "n_reused": len(reused_idx), + "n_encoded": 0, + "n_missing": len(missing_idx), + "model_name": MODEL_NAME, + "model_revision": MODEL_REVISION, + "dimension": DIMENSION, + "status": "reused" if not missing_idx else "partial", + } + resolved, fallback = select_device(device) + report["device"] = resolved + report["device_fallback"] = fallback + if not missing_idx: + report["status"] = "reused" + return _l2_normalize(out) if n else out, report + if not encode_missing: + report["status"] = "incomplete" + return out, report + if not ensure_embedding_stack(): + report["status"] = "stub_missing_encoder" + report["reason"] = "sentence-transformers/transformers lazy install failed" + return out, report + + missing = corpus.iloc[missing_idx].reset_index(drop=True) + encoded = encode_corpus( + missing, + batch_size=batch_size, + device=resolved, + checkpoint_path=checkpoint_path, + ) + for local_i, corpus_i in enumerate(missing_idx): + out[corpus_i] = encoded[local_i] + report["n_encoded"] = int(len(missing_idx)) + report["n_missing"] = 0 + report["status"] = "merged" + return _l2_normalize(out), report + + +def embeddings_by_cid(corpus: pd.DataFrame, matrix: np.ndarray) -> dict[str, list[float]]: + """Project a row-aligned embedding matrix back to a CID map.""" + out: dict[str, list[float]] = {} + if corpus is None or corpus.empty: + return out + x = np.asarray(matrix, dtype=np.float32) + cids = corpus["entry_cid"].astype(str).tolist() + for i, cid in enumerate(cids): + if i >= len(x): + break + out[cid] = x[i].astype(np.float32).tolist() + return out diff --git a/country_laws_ir/verify.py b/country_laws_ir/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..1dc7970bebb9471cbe2372dd16dc7e87a63d786f --- /dev/null +++ b/country_laws_ir/verify.py @@ -0,0 +1,280 @@ +"""Admission verifiers for country-law normalization, before GraphRAG. + +Oregon-style structure is preferred but not required for every gazette. +Verifiers fail closed on invented text, residual HTML, empty corpora, and +duplicate CIDs. Missing title/section hierarchy is a warning unless the +corpus already split into articles. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +import re +from typing import Any + +import pandas as pd + +from .structure import has_html_tags + +SCHEMA_VERSION = "country-laws-normalize-verify/v1" + +_HTML_FAIL_FRACTION = 0.02 +_SHORT_BODY_FAIL_FRACTION = 0.50 +_MIN_BODY_CHARS = 40 + + +@dataclass(frozen=True) +class Check: + id: str + severity: str # fail | warn + passed: bool + message: str + evidence: dict[str, Any] + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def _bodies(corpus: pd.DataFrame) -> list[str]: + if corpus is None or corpus.empty or "body" not in corpus.columns: + return [] + return [str(x or "") for x in corpus["body"].tolist()] + + +def check_nonempty(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + n = int(len(corpus)) if corpus is not None else 0 + return Check( + id="nonempty_corpus", + severity="fail", + passed=n > 0, + message="normalized corpus has rows" if n else "normalized corpus is empty", + evidence={"n_out": n, "n_dropped": report.get("n_dropped_total")}, + ) + + +def check_entry_cids(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + if corpus is None or corpus.empty: + return Check( + id="entry_cid_unique", + severity="fail", + passed=False, + message="no entry_cid values to verify", + evidence={}, + ) + missing = int(corpus["entry_cid"].isna().sum()) if "entry_cid" in corpus.columns else int(len(corpus)) + dupes = int(corpus["entry_cid"].duplicated().sum()) if "entry_cid" in corpus.columns else 0 + empty = int((corpus["entry_cid"].astype(str).str.strip() == "").sum()) if "entry_cid" in corpus.columns else 0 + ok = missing == 0 and dupes == 0 and empty == 0 + return Check( + id="entry_cid_unique", + severity="fail", + passed=ok, + message="every row has a unique entry_cid" if ok else "missing or duplicate entry_cid", + evidence={"missing": missing, "empty": empty, "duplicate": dupes}, + ) + + +def check_no_invented_text(report: dict[str, Any]) -> Check: + flag = bool(report.get("never_invented_legal_text", False)) + return Check( + id="never_invented_legal_text", + severity="fail", + passed=flag, + message="normalizer did not invent legal text" if flag else "invented-text flag is false", + evidence={"never_invented_legal_text": flag}, + ) + + +def check_html_residual(corpus: pd.DataFrame) -> Check: + bodies = _bodies(corpus) + tagged = [b for b in bodies if has_html_tags(b)] + n = len(bodies) or 1 + fraction = len(tagged) / float(n) + passed = fraction <= _HTML_FAIL_FRACTION + return Check( + id="html_residual", + severity="fail", + passed=passed, + message=( + "HTML tags stripped from legal bodies" + if passed + else f"{len(tagged)}/{len(bodies)} bodies still contain HTML tags" + ), + evidence={ + "n_bodies": len(bodies), + "n_with_tags": len(tagged), + "fraction": fraction, + "samples": [b[:120] for b in tagged[:5]], + }, + ) + + +def check_short_bodies(corpus: pd.DataFrame) -> Check: + bodies = _bodies(corpus) + if not bodies: + return Check( + id="short_bodies", + severity="fail", + passed=False, + message="no bodies to measure", + evidence={}, + ) + short = sum(1 for b in bodies if len(b) < _MIN_BODY_CHARS) + fraction = short / float(len(bodies)) + passed = fraction <= _SHORT_BODY_FAIL_FRACTION + return Check( + id="short_bodies", + severity="fail" if not passed else "warn", + passed=passed, + message=( + "most legal units have usable body length" + if passed + else f"{short}/{len(bodies)} bodies shorter than {_MIN_BODY_CHARS} characters" + ), + evidence={"n_short": short, "n_bodies": len(bodies), "fraction": fraction}, + ) + + +def check_heading_language(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + """Warn when Latin heading dialect disagrees with the document language.""" + from .profiles import NO_LATIN_SPLIT_LANGS, iso_lang + + doc_lang = iso_lang(report.get("document_language_majority") or "") + head_lang = iso_lang(report.get("heading_language_majority") or "") + counts = report.get("heading_language_counts") or {} + if ( + doc_lang in NO_LATIN_SPLIT_LANGS + and report.get("unit") == "structured" + and head_lang + and head_lang not in NO_LATIN_SPLIT_LANGS + and head_lang != doc_lang + ): + return Check( + id="heading_language", + severity="fail", + passed=False, + message=( + f"document language {doc_lang} was split with Latin headings ({head_lang}); " + "use script-specific article markers or collector article rows" + ), + evidence={"document_language": doc_lang, "heading_counts": counts, "unit": report.get("unit")}, + ) + if doc_lang and head_lang and doc_lang != head_lang and sum(counts.values()) >= 8: + return Check( + id="heading_language", + severity="warn", + passed=True, + message=( + f"heading lexicon majority is {head_lang} but documents are {doc_lang}; " + "review samples before trusting structure" + ), + evidence={ + "document_language": doc_lang, + "heading_language": head_lang, + "heading_counts": counts, + }, + ) + return Check( + id="heading_language", + severity="warn", + passed=True, + message=( + f"heading lexicon {head_lang or 'none'} vs document language {doc_lang or 'unknown'}" + ), + evidence={ + "document_language": doc_lang, + "heading_language": head_lang, + "heading_counts": counts, + }, + ) + + +def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + unit = str(report.get("unit") or "") + n = int(len(corpus)) if corpus is not None else 0 + structured_rows = 0 + if corpus is not None and not corpus.empty: + if "hierarchy_path" in corpus.columns: + structured_rows = int((corpus["hierarchy_path"].fillna("").astype(str).str.len() > 0).sum()) + if "record_type" in corpus.columns: + structured_rows = max( + structured_rows, + int(corpus["record_type"].isin(["article", "section"]).sum()), + ) + coverage = structured_rows / float(n) if n else 0.0 + # Article or structured units are success. Pure law-level is a warning, not a fail: + # many gazettes have no title/section markers. + if unit in {"article", "structured"} or coverage >= 0.5: + return Check( + id="legal_structure", + severity="warn", + passed=True, + message=f"retrieval units are structured ({unit}, coverage={coverage:.2f})", + evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage}, + ) + return Check( + id="legal_structure", + severity="warn", + passed=True, + message=( + "kept whole-instrument units; no title/article/section headings detected " + "(expected for some gazettes)" + ), + evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage}, + ) + + +def verify_normalized_corpus( + corpus: pd.DataFrame, + report: dict[str, Any], + *, + slug: str = "", +) -> dict[str, Any]: + """Run all normalization verifiers. Fail-closed on any failed `fail` check.""" + checks = [ + check_nonempty(corpus, report), + check_entry_cids(corpus, report), + check_no_invented_text(report), + check_html_residual(corpus), + check_short_bodies(corpus), + check_structure(corpus, report), + check_heading_language(corpus, report), + ] + failed = [c for c in checks if c.severity == "fail" and not c.passed] + admitted = not failed + return { + "schema_version": SCHEMA_VERSION, + "slug": slug, + "admitted": admitted, + "n_checks": len(checks), + "n_failed": len(failed), + "failed_ids": [c.id for c in failed], + "checks": [c.to_dict() for c in checks], + "blocks_graphrag": not admitted, + } + + +class NormalizationAdmissionError(RuntimeError): + """Raised when verifiers refuse to send a corpus to GraphRAG.""" + + +def verify_source(source: str) -> dict[str, Any]: + """Load a Hub/local pack, normalize, and run verifiers (no GraphRAG).""" + from .build import CACHE + from .catalog import get_country + from .normalize import build_corpus, load_source + + country = get_country(source) + local = country.get("local_source_dir") + laws, articles, source_meta = load_source(local or country["repo"], CACHE) + corpus, report = build_corpus(laws, articles, source_meta) + verdict = verify_normalized_corpus(corpus, report, slug=country["slug"]) + report["verification"] = verdict + return { + "slug": country["slug"], + "source": country["repo"], + "n_out": report.get("n_out"), + "unit": report.get("unit"), + "verification": verdict, + "drops": report.get("drops"), + } diff --git a/data/bm25/documents/part-000000.parquet b/data/bm25/documents/part-000000.parquet index 529b0862861b94c5518dd2a017ae36f5dfc74a61..6eb21c02a4aa6d243d91541914a690b19879ea60 100644 --- a/data/bm25/documents/part-000000.parquet +++ b/data/bm25/documents/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:860a20675797c95295d0858ae80606b1c41f8085b5518b375e9abe0cc3c71dc1 -size 368561 +oid sha256:c5fd4064d3307d65014eda40a56474c085ee0eac48f6882aafd2eeb9596fe5df +size 505685 diff --git a/data/bm25/documents/part-000001.parquet b/data/bm25/documents/part-000001.parquet index 677227703c4de51af2b2e521490641c4fd2186fd..df34ed2f643f57e94c26de122539bdd4ec3354aa 100644 --- a/data/bm25/documents/part-000001.parquet +++ b/data/bm25/documents/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9aed57473c8c6a419d70f7a88e2f812d42d903624437d261637119ced083bf3c -size 368413 +oid sha256:74795c6ccfa80c09b8bd6bc315c86eb173ec038addbaf3a286731a9836908b2d +size 505256 diff --git a/data/bm25/documents/part-000002.parquet b/data/bm25/documents/part-000002.parquet index bbbfd70029d4f9a86bba2ef262f9eef1ef14a981..43185cc7cda8c7a78c8684f7ca51d65db8ca5b48 100644 --- a/data/bm25/documents/part-000002.parquet +++ b/data/bm25/documents/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2865aebd34ab1550cb1bde375e4b8746f414cdb97092ff30cf33af92dfb8ef99 -size 165483 +oid sha256:f8fcb8e856d47144a383b748ad2c1e75f27399b68f0bfbf61f2f7a82ca5236d0 +size 207945 diff --git a/data/bm25/postings/part-000000.parquet b/data/bm25/postings/part-000000.parquet index dba79db7e5117c0b8a1b949ec590d5b2a6fbb65a..2a611c648f108d8471ce3d7c2a5eaf56baf6df88 100644 --- a/data/bm25/postings/part-000000.parquet +++ b/data/bm25/postings/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:449352808135f06bfca2bf528de4e6f8b0d6cd3a3f34984c87edfd2570c745f1 -size 793240 +oid sha256:74899c071ecc3ab75bd7fcac7ad5a6fa4f38f0b7fffbe8fd973f58f718873c22 +size 209619 diff --git a/data/bm25/postings/part-000001.parquet b/data/bm25/postings/part-000001.parquet index 5d215a7eaf3715c049f7e846172b56ffc7df8318..60b283b5efa46d73d09f73b03d86ff9e59dce768 100644 --- a/data/bm25/postings/part-000001.parquet +++ b/data/bm25/postings/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:033470212ddcd40e12979c4ddd2443fcf4a03786ede837ce4024837ffec7ab04 -size 783392 +oid sha256:8be646723478d95c9e03a8a4e5b12ccd93c6bd6ab645e468bb05e6515fc0c493 +size 594030 diff --git a/data/bm25/postings/part-000002.parquet b/data/bm25/postings/part-000002.parquet index 88162f601ae3915ed81d3491f206564a49193344..c435ee33c76e2df8123db743b28e413aa7352db7 100644 --- a/data/bm25/postings/part-000002.parquet +++ b/data/bm25/postings/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0c17ca6cb1c03079c20f9c96336842b1412e554bd555d4c5024085b863697754 -size 948081 +oid sha256:8497d4b6354f5c3b31181f041bb4e055c2e1d49fb8114803af454071d56415e3 +size 514556 diff --git a/data/bm25/postings/part-000003.parquet b/data/bm25/postings/part-000003.parquet index 6f8100f73a6411d8b5efcecee87b03dfe744ff4c..003f8519d18993edb2ba6af74e068fc12e777bc9 100644 --- a/data/bm25/postings/part-000003.parquet +++ b/data/bm25/postings/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:61e65f19169774f27e5cd71a3e00db3dee7aa3d13c36b87042d838cd71d996ac -size 990527 +oid sha256:35b3910b79ba80d5e12f86b657485f40c98ea7a7a26ff5814d17e6eb63595c20 +size 500924 diff --git a/data/bm25/postings/part-000004.parquet b/data/bm25/postings/part-000004.parquet index 29ed19fd567f354526c4a1763368dfbfbcbb206e..6f2eb532b2a188dac09a5eb50a7726600fd2d673 100644 --- a/data/bm25/postings/part-000004.parquet +++ b/data/bm25/postings/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:22b90eb7821fa024d2fe0fcb23a9828b010058381b364b1eeafac5d9bbe98cd7 -size 272391 +oid sha256:f1e4707df479e2f0087ce851102cb5e8bbc4a2572cc1aa72c34dc795ca2e58c6 +size 566517 diff --git a/data/bm25/postings/part-000005.parquet b/data/bm25/postings/part-000005.parquet new file mode 100644 index 0000000000000000000000000000000000000000..10fd0c23cccb206d4cae6493fed40ff3be627d0e --- /dev/null +++ b/data/bm25/postings/part-000005.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e741b34a0f0c0c5be57b1e4eaed76a1665a5bdf98fda0893a5570458de05906 +size 121832 diff --git a/data/corpus/part-000000.parquet b/data/corpus/part-000000.parquet index 0048746aa9c408aab320c9b1233227871e70f1a6..13bb757ef1c24f9c592bf4ccf592281d9bb0bef8 100644 --- a/data/corpus/part-000000.parquet +++ b/data/corpus/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bd47600c807926c73563bf5c40579653a2b8e937ab6e5a1634605b541ca46c9d -size 1561917 +oid sha256:f19ce33a158a468119e6fc7f7de456d5482dbd1c0a7e20d2ecc47a72fed4d74c +size 1570303 diff --git a/data/corpus/part-000001.parquet b/data/corpus/part-000001.parquet index 7a620ed2358ee4df4b77dadea2e52f0bc03a9aae..4390fe418ceb3436569d99bd778a913e650fac94 100644 --- a/data/corpus/part-000001.parquet +++ b/data/corpus/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:db51d39448f4f36bdd0e70cb7a3413acb3e0bbd72df05f86604365d5625e5cba -size 1453906 +oid sha256:edd08e86c071d1146b68a4662720faedeb109b3b4cd008ae44fab6594a5cfb8d +size 1460927 diff --git a/data/corpus/part-000002.parquet b/data/corpus/part-000002.parquet index d6cfa20ed8c7219b17db7e898e209a0df9cbb738..a7a6edb9ed865f40428cad1f2db99066672d12c6 100644 --- a/data/corpus/part-000002.parquet +++ b/data/corpus/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:93f54c3b249d84fcc259f5022b23e99101d1ae515143995e4605414b0f8baa55 -size 596594 +oid sha256:8f48adf69ee081949795f9aa1a9de3b6ee497ce8b9035fbc5f7c816e019ce256 +size 601572 diff --git a/data/graph/adjacency/in/part-000000.parquet b/data/graph/adjacency/in/part-000000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..fe61b6f2349bcb63902c68c208869f839ddea80f --- /dev/null +++ b/data/graph/adjacency/in/part-000000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab76e07550cf005e6a861d466ce304763a2e05b3f5ef47fb13aa2307d82d4cc1 +size 511238 diff --git a/data/graph/adjacency/in/part-000001.parquet b/data/graph/adjacency/in/part-000001.parquet new file mode 100644 index 0000000000000000000000000000000000000000..9108605037bb094859ef2a3d1d7d18174e644003 --- /dev/null +++ b/data/graph/adjacency/in/part-000001.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec8d8e0c2f49c1bb6b378df401494a06fa0bb7e0c9d7f29f571fe452c6a692c8 +size 519126 diff --git a/data/graph/adjacency/in/part-000002.parquet b/data/graph/adjacency/in/part-000002.parquet new file mode 100644 index 0000000000000000000000000000000000000000..98e6661f6fe69656a0b689eba6aaa2c4d9581a23 --- /dev/null +++ b/data/graph/adjacency/in/part-000002.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9eefba389959082004b444c065b7daa4e17df0f6223e76e28a0c22fe5fba0fe1 +size 467734 diff --git a/data/graph/adjacency/in/part-000003.parquet b/data/graph/adjacency/in/part-000003.parquet new file mode 100644 index 0000000000000000000000000000000000000000..b0b6ca9134c3aad4093c54aceca0394cfa585f6e --- /dev/null +++ b/data/graph/adjacency/in/part-000003.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99060370a128f8418041a0caef44cfb002b5927b0b0101728256125f0d06f02d +size 402067 diff --git a/data/graph/adjacency/in/part-000004.parquet b/data/graph/adjacency/in/part-000004.parquet new file mode 100644 index 0000000000000000000000000000000000000000..506b2ceafceea604bae093e32264be621a6738dd --- /dev/null +++ b/data/graph/adjacency/in/part-000004.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:167b7bb1a404185c28acd8e153453d146a829cca3ecd1a765303b4b6d489b5fa +size 480282 diff --git a/data/graph/adjacency/in/part-000005.parquet b/data/graph/adjacency/in/part-000005.parquet new file mode 100644 index 0000000000000000000000000000000000000000..592c38a8876228c31f26c1397a63acd417009947 --- /dev/null +++ b/data/graph/adjacency/in/part-000005.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d489f01fd72dcf69f9e287a017c2a4dd58dc965fa16c1e8fde451386ca9b2c35 +size 583488 diff --git a/data/graph/adjacency/in/part-000006.parquet b/data/graph/adjacency/in/part-000006.parquet new file mode 100644 index 0000000000000000000000000000000000000000..a325ddc1e206bd96a5faa15247720188b96c4e62 --- /dev/null +++ b/data/graph/adjacency/in/part-000006.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33edd225916b56b0761c442933000867564a048fd57fd551bc69e1505c08a7d6 +size 295841 diff --git a/data/graph/adjacency/in/part-000007.parquet b/data/graph/adjacency/in/part-000007.parquet new file mode 100644 index 0000000000000000000000000000000000000000..e8ec9b5f630b908f179374c44264e8ac72ac7596 --- /dev/null +++ b/data/graph/adjacency/in/part-000007.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:731801565bbeabc1ead1d9e6b86444cf4bb3477911448f7cef263c7eaae25071 +size 583935 diff --git a/data/graph/adjacency/in/part-000008.parquet b/data/graph/adjacency/in/part-000008.parquet new file mode 100644 index 0000000000000000000000000000000000000000..c284b3b194b50c155b2b8dd4ccba2141cd9cc959 --- /dev/null +++ b/data/graph/adjacency/in/part-000008.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d6aa3b3c55765a7467540992ee45c4320828e2ae508ed0137dfa373f75543a1 +size 529049 diff --git a/data/graph/adjacency/in/part-000009.parquet b/data/graph/adjacency/in/part-000009.parquet new file mode 100644 index 0000000000000000000000000000000000000000..0273da05fce2e13e2c80ac58b51ff57caaa854d6 --- /dev/null +++ b/data/graph/adjacency/in/part-000009.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c666a42bc11f134c20f06b476ef7ed43328476d149771c86685025d695f74f1d +size 246648 diff --git a/data/graph/adjacency/out/part-000000.parquet b/data/graph/adjacency/out/part-000000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..80b96ca3e6e9b4dfda488600330290f0d1d317e8 --- /dev/null +++ b/data/graph/adjacency/out/part-000000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aaf58471bdab7ec191adbce1d5b1e20ae901f9307b31295e9bbdfd2667e694dc +size 356063 diff --git a/data/graph/adjacency/out/part-000001.parquet b/data/graph/adjacency/out/part-000001.parquet new file mode 100644 index 0000000000000000000000000000000000000000..12da33298a8695e9916d4e28e94ae48b8ea4d5da --- /dev/null +++ b/data/graph/adjacency/out/part-000001.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd53cd85a58f9e9004d7b3ae69fcbc1f3f818558c5908ec0a5bfe95d4d1fdd9a +size 356439 diff --git a/data/graph/adjacency/out/part-000002.parquet b/data/graph/adjacency/out/part-000002.parquet new file mode 100644 index 0000000000000000000000000000000000000000..f072edff31748ba23629fbee372a59205cc6fc38 --- /dev/null +++ b/data/graph/adjacency/out/part-000002.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76c8ea87ff438794fe03ca9ebb34bc542012beb6a86446daa0e9bd55a1ee86e1 +size 356217 diff --git a/data/graph/adjacency/out/part-000003.parquet b/data/graph/adjacency/out/part-000003.parquet new file mode 100644 index 0000000000000000000000000000000000000000..c2fd9c194e505a3ae7087569b9c013bef52a192d --- /dev/null +++ b/data/graph/adjacency/out/part-000003.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26e3c07920dabebbec3a9cad5c192f609c9ad2c0847ad863ab9443e33e7c97ed +size 356067 diff --git a/data/graph/adjacency/out/part-000004.parquet b/data/graph/adjacency/out/part-000004.parquet new file mode 100644 index 0000000000000000000000000000000000000000..da1214ac99867466aae0270265ebf5c3ea89bcc3 --- /dev/null +++ b/data/graph/adjacency/out/part-000004.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f327391a50760b4dbd84e5effa8b70b50d9f716632800604aef49450d421ae63 +size 356743 diff --git a/data/graph/adjacency/out/part-000005.parquet b/data/graph/adjacency/out/part-000005.parquet new file mode 100644 index 0000000000000000000000000000000000000000..98bbd20c45483f02563409c75fd4c93b0cab7f43 --- /dev/null +++ b/data/graph/adjacency/out/part-000005.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e542407c88fbe94be6d29bb169a775a5e8a4d975c1ed11e96e31380de654ea6f +size 356541 diff --git a/data/graph/adjacency/out/part-000006.parquet b/data/graph/adjacency/out/part-000006.parquet new file mode 100644 index 0000000000000000000000000000000000000000..2a76cf4a711bdd3e3e2d9e9a54d117fb988e2fb9 --- /dev/null +++ b/data/graph/adjacency/out/part-000006.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a7552d3e5276f8860272cbc231546fb17a95c59772914fabcdecf813d60b6ec +size 355992 diff --git a/data/graph/adjacency/out/part-000007.parquet b/data/graph/adjacency/out/part-000007.parquet new file mode 100644 index 0000000000000000000000000000000000000000..f621f2879649819fc9fcf195badcec7f31ea6b26 --- /dev/null +++ b/data/graph/adjacency/out/part-000007.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c41e08633852541bdf93d362ec4c8cd49d715cca8a6ec5f3e4b9c7309224fed +size 356122 diff --git a/data/graph/adjacency/out/part-000008.parquet b/data/graph/adjacency/out/part-000008.parquet new file mode 100644 index 0000000000000000000000000000000000000000..97cca7aa12b5be4410e900b5240806f0a43ceec7 --- /dev/null +++ b/data/graph/adjacency/out/part-000008.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8f4d7d059485769dce27a6160cc2128984774d61f721347fe47113d1061c3a8 +size 143859 diff --git a/data/graph/edges/part-000000.parquet b/data/graph/edges/part-000000.parquet index 72769f0e4e213c5e8c19a06a32dd6e86aec46c42..0a52458f5762ea4aa7b895aca79c729c48c16b88 100644 --- a/data/graph/edges/part-000000.parquet +++ b/data/graph/edges/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:12d2cd81644814c46c384ef62c9fa487dbf7131185477a4bb706fbc85b561f3f -size 180963 +oid sha256:f54bf3abc509a2b012baba157c9fd354dcf276f4efc77010a460e26aac25f551 +size 283892 diff --git a/data/graph/edges/part-000001.parquet b/data/graph/edges/part-000001.parquet index 7ec6c447b3a296d188c423a633206e1e0e3b6a4e..e98244a0aad8c1d751db9fe3528048f5607b0a9e 100644 --- a/data/graph/edges/part-000001.parquet +++ b/data/graph/edges/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:045ad5ff665528bd0acbe66e3490c051ee899393f6f9659cef1b7df2d749db02 -size 182447 +oid sha256:b4f2db54b4b48e21edee5d6fbccaab290bd6b2c689c603c3aad9821d54405cf6 +size 285068 diff --git a/data/graph/edges/part-000002.parquet b/data/graph/edges/part-000002.parquet index cdbeabd3154d918e6681e10f7d467792fe418eb7..b2381ff0294264ad73e24c0e21332e72dd4822d3 100644 --- a/data/graph/edges/part-000002.parquet +++ b/data/graph/edges/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:eba9f74eb1b8d53f8b1a63e8189d71c975b03ee50744b1856333097d4b7f6b9b -size 185516 +oid sha256:5bdf60986491d6640f4bd3ec769d19b17c92f98879f37a6de4e1089a9d348a09 +size 283456 diff --git a/data/graph/edges/part-000003.parquet b/data/graph/edges/part-000003.parquet index b08dc272e1d9d11d2ab1b9df9fdad078abc71c76..589af678478dfe634349723492562d506db742ae 100644 --- a/data/graph/edges/part-000003.parquet +++ b/data/graph/edges/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:777580828b86c48b1c05b5912932208699b44d0f4e8ff76e9f95cf2bbac7f429 -size 184250 +oid sha256:7b0bc238098adcd6528ac40803174c292e01b35e6771965f12008b57145883ec +size 285119 diff --git a/data/graph/edges/part-000004.parquet b/data/graph/edges/part-000004.parquet index fd68748779973d556c0aecfc91bb3718e6eb88de..15797b602af0a33f9fdcb9a31bdacc13777cb6f0 100644 --- a/data/graph/edges/part-000004.parquet +++ b/data/graph/edges/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ef7dd30e37be9a6e24341995b9acc1354127ca9476a300360663b03bb74a2657 -size 183464 +oid sha256:c4832fe1be63465c42f0f8cbbdcacbedaca8997f6b25558adb906c3533bc7729 +size 283318 diff --git a/data/graph/edges/part-000005.parquet b/data/graph/edges/part-000005.parquet index 8d0d20c2c6ceddbeec0edc75caa0f1761b3c1b3b..89636951ad174478ded636cba3f7e74c69d90fe9 100644 --- a/data/graph/edges/part-000005.parquet +++ b/data/graph/edges/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a44f09d0f39cbd5148246f4a98aa57875459fbe8cb218d3d3d42c0aef9e4de7f -size 184925 +oid sha256:1bc35b5e452d9b790c6d53e82adaf849c6520abd965b107534206c618e3379c6 +size 284253 diff --git a/data/graph/edges/part-000006.parquet b/data/graph/edges/part-000006.parquet index 45e3c6c15dcd87ff262a2ed28f3638b6997bf16d..0b86e392ad3a7d85239e639390cab77aec50bd70 100644 --- a/data/graph/edges/part-000006.parquet +++ b/data/graph/edges/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e0c2c0cea207d370a5f45c4f726603ce5e29f19c152f87d6fbf01c8bb1eb39e4 -size 184567 +oid sha256:5dbe8c5188ce32776eb45f436cacb1344a79a2d4e1767b5232766e6445901c21 +size 283875 diff --git a/data/graph/edges/part-000007.parquet b/data/graph/edges/part-000007.parquet index 6fdfeb13aa864e9a9230eb51e5602679771a6790..0435fd183f67710d32c411397043c5dc9fa4d779 100644 --- a/data/graph/edges/part-000007.parquet +++ b/data/graph/edges/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5897829145f0a494cb7163e8e3c258db82f3439957fc6ddf5c83c87a51f373bb -size 186019 +oid sha256:00bbfb365d08dd53e3671bf6db59e8c5409c5697879aba7c2eed06f4a5acce03 +size 283585 diff --git a/data/graph/edges/part-000008.parquet b/data/graph/edges/part-000008.parquet index be54b643b86b0bfb9468ab30add69cdfa7db249e..53aac0c0e5d67eadff844def918e70a8b333d832 100644 --- a/data/graph/edges/part-000008.parquet +++ b/data/graph/edges/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:eda36209ef90d96b76459237c3811ce43d596694be1201739dd26cfed82da8e4 -size 185566 +oid sha256:b8b55757254f94a1e5dda30954bf3e419d69ed740ee578c5f439d10aada70cb6 +size 283804 diff --git a/data/graph/edges/part-000009.parquet b/data/graph/edges/part-000009.parquet index d509faab5ad16d4c22c087f626c6de16991bbd93..56f19f80934c5303e170912d2962ba8d43b330e3 100644 --- a/data/graph/edges/part-000009.parquet +++ b/data/graph/edges/part-000009.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:de8becdaeace79f385e49324fe8fd074051c1f72b282a6444b57d1d96734d00e -size 185843 +oid sha256:2815fa2f9a865398302cb73aec6e1de4fdef81fb801bec9d401dd754f3f0ead5 +size 283504 diff --git a/data/graph/edges/part-000010.parquet b/data/graph/edges/part-000010.parquet index e00863e7618037a20d45ec5d325bedd129c8dfa8..aa407320443fa0eb837d4b5583510f4a35a5a3fd 100644 --- a/data/graph/edges/part-000010.parquet +++ b/data/graph/edges/part-000010.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e1d330a63559063726f83b975420cc4f728a67fe8ecbde306e48d5988dc86641 -size 178930 +oid sha256:2e6f1f0c4899e393f7f654c41a820c8e088f53fcf9898a5783fb0a546ff6fe9b +size 283793 diff --git a/data/graph/edges/part-000011.parquet b/data/graph/edges/part-000011.parquet index c9ca769c7b7664a49a17e4cbd4d72ef0fd6bb941..8326ba0cb5beb2106543522852d8218d75e2aed7 100644 --- a/data/graph/edges/part-000011.parquet +++ b/data/graph/edges/part-000011.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3984a44082566296318be2c1c344fb8a8a773cdaf377c17a5dd598610ee67237 -size 177554 +oid sha256:1e3053e1d7e5b5233b499e2e08d8cc0bca20a344188df79f3ae3be4951945c02 +size 283595 diff --git a/data/graph/edges/part-000012.parquet b/data/graph/edges/part-000012.parquet index b38c4d2bee97e88049257a0be44bab68f32facf4..8b9927941583aad3d5890d6f1b401fea8819eb4f 100644 --- a/data/graph/edges/part-000012.parquet +++ b/data/graph/edges/part-000012.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f2feb0b18c7b34d57b42853a639241d51b5d580a3f3e6873c6b7145dd92cc927 -size 182716 +oid sha256:753a05e464e5c40d6a744f5709a6a6c0af0792fb95371178bc81ec1d13387a4f +size 284585 diff --git a/data/graph/edges/part-000013.parquet b/data/graph/edges/part-000013.parquet index ccbf454b26be05eb05947974c5e20e5274d27dc8..0bf5c793eb0600dcdd7b68c12921b40c90273f11 100644 --- a/data/graph/edges/part-000013.parquet +++ b/data/graph/edges/part-000013.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:db84ba5222bfdf7c730873a0e14e085cbc810b5b21413023e40997afda31cb3e -size 181920 +oid sha256:871f55250df1a2ad150f5067b0993ae3ee824db02b0b5f603b4ffa78023a97a4 +size 284362 diff --git a/data/graph/edges/part-000014.parquet b/data/graph/edges/part-000014.parquet index 90bcb77a4951a0e62529e72acd53b92d752b42bd..df92e04878162ba78cf6f58a766aca13f0599144 100644 --- a/data/graph/edges/part-000014.parquet +++ b/data/graph/edges/part-000014.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:96ce995e476aa38befcce093e29eae9cc394d020f51a70249b7468fb6c3bb637 -size 186546 +oid sha256:5070f4ce348bc64c4b6ce47e5ca2e8730394f47dc58493d7667611a33e0a8370 +size 284613 diff --git a/data/graph/edges/part-000015.parquet b/data/graph/edges/part-000015.parquet index 1ce9402f4cea763d4247441596551407e8a45c5c..e0b36bff5762856394512f013ffce2f47ddde9b7 100644 --- a/data/graph/edges/part-000015.parquet +++ b/data/graph/edges/part-000015.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a81d00f0a7171fe6089cb901c4de505aa0b62127c113755316e71ce343473768 -size 185988 +oid sha256:2e67dc655bd70fbb56d24dd309d22988410a0b1d7847f2d87e575ebc92a1cca0 +size 284058 diff --git a/data/graph/edges/part-000016.parquet b/data/graph/edges/part-000016.parquet index c2a4fef60ea449efca5c2125bc1ea73e76b301d3..4819c2abb66736b7700cacc7bdc9d4a719a07eb4 100644 --- a/data/graph/edges/part-000016.parquet +++ b/data/graph/edges/part-000016.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:287bd08f09c37f80d87f1449dd8f9f59e26ba87e9ae580b41faffe1e00cb845d -size 219813 +oid sha256:ff858af59b09dc2022973e486ad20330dde38c116afd650d48ceac2beb1fab28 +size 220058 diff --git a/data/graph/nodes/part-000000.parquet b/data/graph/nodes/part-000000.parquet index 4a6e416bca581833c2ba2adfa110a94664b04090..1c463cdd446132ee57bbf90701b1d39666212a7f 100644 --- a/data/graph/nodes/part-000000.parquet +++ b/data/graph/nodes/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0ac203694ee4b328a312dcbbbd94c024305938d9e764b3a1c311304c4c183d3c -size 535361 +oid sha256:5ac31e16e31143f161e832ef7461bb3379a39d317a47bd550fc6acaaa26dfd6b +size 343262 diff --git a/data/graph/nodes/part-000001.parquet b/data/graph/nodes/part-000001.parquet index 7052562e8e78aa2cd5f637566393d8d2f8a848f8..854dd1c67bd5b0c1b70992c01c4f12dabdb69ce8 100644 --- a/data/graph/nodes/part-000001.parquet +++ b/data/graph/nodes/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:cc91fd8d676dfcf33d305d90fe7470f810a2e6b8c8994aff57368b920853f589 -size 536880 +oid sha256:0feaa3c194b8d00c2c609a7aa0d80154d38a35583acd8e752a48b39e3c6e0712 +size 341956 diff --git a/data/graph/nodes/part-000002.parquet b/data/graph/nodes/part-000002.parquet index 9b974c835dc0ee9667469ed1149e68d92562edbc..3df85c261c29439ebe500338bb7f713aa338f6b8 100644 --- a/data/graph/nodes/part-000002.parquet +++ b/data/graph/nodes/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8f3bcc1d0102fcbb1009cd407554257f3481539a580a18e7979d0e3167848f0d -size 244264 +oid sha256:04846f23b641f3ecabb6021f9bdaab14454d35360d6a718fd30d5fa3892a085f +size 176765 diff --git a/data/vectors/part-000000.parquet b/data/vectors/part-000000.parquet index fbb49a543e254deb7950942e22fc9c7e19b47794..b43d806c2533d5163ef9d57d124b66d1f3952627 100644 --- a/data/vectors/part-000000.parquet +++ b/data/vectors/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ffe486ffcd48b57240b5e8cf8b454a9d2f19ebe10d27ba99b013e107aa919a4e -size 7341838 +oid sha256:68c3fecfc8583882959a26335c7c3e68f0b8a1d307e630ded0ece49e24304f0c +size 7467239 diff --git a/data/vectors/part-000001.parquet b/data/vectors/part-000001.parquet index beb70dcd9c5f9527addbea09137464516c2e2735..9babd2c55b03179f8ad484619a7689ba000e5072 100644 --- a/data/vectors/part-000001.parquet +++ b/data/vectors/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:18aa6170f81416711837ae296e575fd3ee39059b037c3170b19e424fe5e92bbc -size 7287793 +oid sha256:f45098bc8966ee914bb8c1a582d530c342c2b4923bc3146b3ceee3c26a2ed6c8 +size 7483801 diff --git a/data/vectors/part-000002.parquet b/data/vectors/part-000002.parquet index f6654606c3d4a3b358dacb37d8e8e93e06dcb305..9dc00ebda0357125122d97b7b0e28d796177967c 100644 --- a/data/vectors/part-000002.parquet +++ b/data/vectors/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3704cfaed38755a82728c773ce3223d405a105ee4193df67c025be99feb01b57 -size 3042585 +oid sha256:dfcdde06dc0affb553c33f85396de87755227a5f7012e59222e7870956109f13 +size 2896377 diff --git a/dataset_configs.json b/dataset_configs.json new file mode 100644 index 0000000000000000000000000000000000000000..1a266cfc31887140aaff20a14cb0e99095b3ea45 --- /dev/null +++ b/dataset_configs.json @@ -0,0 +1,14 @@ +{ + "country-laws-ir-graphrag/v1": { + "data_files": { + "corpus": "data/corpus/*.parquet", + "bm25_documents": "data/bm25/documents/*.parquet", + "bm25_postings": "data/bm25/postings/*.parquet", + "graph_nodes": "data/graph/nodes/*.parquet", + "graph_edges": "data/graph/edges/*.parquet", + "graph_adjacency_out": "data/graph/adjacency/out/*.parquet", + "graph_adjacency_in": "data/graph/adjacency/in/*.parquet", + "vectors": "data/vectors/*.parquet" + } + } +} diff --git a/indexes/bm25_document_chunks.parquet b/indexes/bm25_document_chunks.parquet index daf5511ad5421547c426ba2fb7ddd6c617783b29..1781e65b62e48d73db3bfb92abec9bb2cab75a69 100644 --- a/indexes/bm25_document_chunks.parquet +++ b/indexes/bm25_document_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bc30aedeb8347f5581cc102c29ed3b49c00e25ef0e3f6a076b0532f9f4af07ae -size 9202 +oid sha256:5c772fc4170f024be5a7459a100896376caeb3b3c68118fdeb968184bed209d2 +size 4968 diff --git a/indexes/bm25_keyword_shards.parquet b/indexes/bm25_keyword_shards.parquet index f9dd1f7cebb9da20c5b3d0afcfcd13e33957e629..61dab9c343d615bb15379543444ae5a1784b3e1c 100644 --- a/indexes/bm25_keyword_shards.parquet +++ b/indexes/bm25_keyword_shards.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:376f190625278454e0d52ea774d00a459a7b5628e95b56954a7cc53a57ba706c -size 8761 +oid sha256:7e4e3036de06ec61e2ad42bd1596e86ae4defff63e5e32b1e037dc05f690dff5 +size 5476 diff --git a/indexes/corpus_chunks.parquet b/indexes/corpus_chunks.parquet index bd873337d70dfbcde212e96a9ad061fd5ed97ccb..aa64b6fd8ea5b4ceaaf51b45b505e4551affaae2 100644 --- a/indexes/corpus_chunks.parquet +++ b/indexes/corpus_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:dc6c890693111b314a78cca35fe9c8273f50887360046fd1edf0ca65a8763fc2 -size 9126 +oid sha256:d55c32f0682d783746e7e35c27e43232636bc967732429414bab704098541422 +size 8984 diff --git a/indexes/graph_edge_chunks.parquet b/indexes/graph_edge_chunks.parquet index 1517a7baa412a813f1560b2e55c65ad320b77bf4..16ad0a488a68e54470223892642ce2992c8eb446 100644 --- a/indexes/graph_edge_chunks.parquet +++ b/indexes/graph_edge_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:79052d51ee298c6262fced23119f7ba13b2b8082730e672fc0d9e7e9e0033a1b -size 12711 +oid sha256:a8d5ca5f99f9a290a488b616364864715ac113948807415329a2dfe5e7651f5f +size 7791 diff --git a/indexes/graph_in_adjacency.parquet b/indexes/graph_in_adjacency.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6dfe6b6cc4280b6abf97162ec796b4830730e8ac --- /dev/null +++ b/indexes/graph_in_adjacency.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7217533fbf17f9c08adb5d1ec5b63de55bacde1ccbce0f3e93fca0e0363973e3 +size 8176 diff --git a/indexes/graph_node_chunks.parquet b/indexes/graph_node_chunks.parquet index 06aff57e005a6c5b10aa15f40f1c87687481cebe..e407987ea9a556b69cdcdc6e384dc08113dc6349 100644 --- a/indexes/graph_node_chunks.parquet +++ b/indexes/graph_node_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:79c81d52422ec50602f0502ebb00fe0da662a1f937417220c5ace34f7794c6c4 -size 9152 +oid sha256:cc95b32426ce5a40fc27d0fed4669cdd6900af95ca75e0085ffe1e8bbfbfe5da +size 5203 diff --git a/indexes/graph_out_adjacency.parquet b/indexes/graph_out_adjacency.parquet new file mode 100644 index 0000000000000000000000000000000000000000..bfd269c629e1f28f9016b5468154ba1b9a63dd7d --- /dev/null +++ b/indexes/graph_out_adjacency.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:380c474b13c733726994f190fe9288b34fc6a466d4a3ca9a234c35d3f9fead98 +size 7992 diff --git a/indexes/vector_chunks.parquet b/indexes/vector_chunks.parquet index 9675a477babd10d38c16cb251d811790dd038667..73cdcd7c2bee03d3e4ab865f201783063d2c1e7e 100644 --- a/indexes/vector_chunks.parquet +++ b/indexes/vector_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9ebad6447e186bad4ed2cc696a085eeb9339d96a9c0c97a16ef329d477f1f480 -size 26184 +oid sha256:ef81b82935ce21b54b0ab9faa3f2da477a9ffddc0c05c03ff2b0e83f13515a58 +size 27370 diff --git a/manifest.json b/manifest.json index afdb67ee5b50ff26a8271648584ecc7480725f26..30580f0ec7f41b54792fd91f267884907f41492c 100644 --- a/manifest.json +++ b/manifest.json @@ -1,22 +1,359 @@ { "schema_version": "country-laws-ir-graphrag/v1", + "layout_family": "skillcenter-huggingface-release/v3", + "packager_version": "0.5.0", + "primary_key": "entry_cid", + "dataset_id": "endomorphosis/ipfs_kenya_laws", + "dataset_repo_id": "justicedao/ipfs_kenya_laws_ir", "dataset_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", "country": { "slug": "kenya", "repo": "endomorphosis/ipfs_kenya_laws", "name": "Kenya", - "indexable": true, - "skip_reason": null, - "local_source_dir": "/workspace/country-laws-ir/cache/kenya_filtered_27b81c642fec", - "source_revision": "27b81c642fec385c9123c30b9eb885d093b70f61" + "indexable": true + }, + "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.", + "bm25": { + "k1": 1.2, + "b": 0.75, + "title_weight": 5.0, + "body_weight": 1.0, + "average_document_length": 175.1078351356866, + "tokenizer": "hf-graphrag-bm25-tokens/v1", + "max_query_terms": 64, + "posting_rows_per_record": 4096, + "terms_per_shard": 4096 + }, + "counts": { + "bm25_document_chunks": 3, + "bm25_documents": 9802, + "bm25_keyword_shards": 6, + "bm25_posting_rows": 21107, + "bm25_postings": 712415, + "bm25_terms": 21080, + "corpus_chunks": 3, + "corpus_rows": 9802, + "graph_edge_chunks": 0, + "graph_edges": 68614, + "graph_incoming_adjacency_edges": 0, + "graph_incoming_adjacency_rows": 0, + "graph_incoming_adjacency_shards": 0, + "graph_node_chunks": 0, + "graph_nodes": 10223, + "graph_outgoing_adjacency_edges": 0, + "graph_outgoing_adjacency_rows": 0, + "graph_outgoing_adjacency_shards": 0, + "vector_chunks": 3, + "vector_rows": 9802, + "n_laws": 0, + "n_articles": 9802, + "bm25_token_instances": 1716407 + }, + "parquet": { + "compression": "zstd", + "compression_level": 6, + "max_rows_per_file": 4096, + "row_group_size": 4096, + "query_engine": "duckdb" + }, + "graph": { + "adjacency_pointers_per_row": 4096, + "adjacency_pointers_per_shard": 8192, + "directions": [ + "incoming", + "outgoing" + ], + "max_remote_walk_depth": 8, + "ordering": "score_desc_nulls_last", + "edge_types": [ + "HAS_JURISDICTION", + "HAS_LANGUAGE", + "BELONGS_TO_LAW", + "HAS_ARTICLE", + "BM25_NEIGHBOR_OF" + ] + }, + "vector": { + "model_name": "thenlper/gte-small", + "dimension": 384, + "similarity": "cosine", + "assignment": "recursive_spherical_kmeans", + "layout": "semantic_centroid_groups", + "rows_sorted_by": "cosine_similarity_to_shard_centroid_desc", + "max_rows_per_chunk": 4096, + "max_rows_per_centroid": 8192, + "max_shards_per_centroid": 2, + "default_probe_centroids": 4, + "centroid_count": 4, + "shard_count": 4, + "n_vectors": 9802, + "status": "embedded" + }, + "canonical_fields": [ + "entry_cid", + "law_cid", + "record_type", + "jurisdiction", + "language", + "instrument_id", + "instrument_title", + "article_number", + "article_title", + "title", + "body", + "source_url", + "snapshot_date", + "coverage", + "license", + "collector", + "source_dataset", + "source_revision" + ], + "input_sha256": { + "laws.parquet": "75141fbb55a5d2426cbaf3825abf2b3c08c3e09f405df30656737e150baf2439", + "articles.parquet": "cc4af552d319fec593b42ef8ddb57e0d6da23581ae6c558dc7cfe9aaccf6afad" + }, + "model_id": "thenlper/gte-small", + "cid": { + "codec": "raw", + "hash": "sha2-256", + "multibase": "base32", + "payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')" + }, + "normalization": { + "source_dataset": "endomorphosis/ipfs_kenya_laws", + "source_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", + "laws_sha256": "75141fbb55a5d2426cbaf3825abf2b3c08c3e09f405df30656737e150baf2439", + "articles_sha256": "cc4af552d319fec593b42ef8ddb57e0d6da23581ae6c558dc7cfe9aaccf6afad", + "n_laws_in": 261, + "n_articles_in": 9802, + "unit": "article", + "article_law_coverage": 37.55555555555556, + "sparse_article_fallback": false, + "drops": { + "empty_body": 0, + "missing_instrument": 0, + "duplicate_cid": 0, + "duplicate_source_kept_first": 0 + }, + "drop_samples": { + "empty_body": [], + "missing_instrument": [], + "duplicate_cid": [] + }, + "language_breakdown": { + "en": 9802 + }, + "quality_flags": { + "articles_table_empty": false, + "sparse_article_fallback": false, + "article_law_coverage": 37.55555555555556, + "all_source_article_counts_zero": false, + "article_extraction_status_counts": { + "ok": 141, + "missing": 120 + }, + "missing_date": false, + "missing_date_issued": true, + "eli_present": false, + "never_invented_legal_text": true, + "empty_bodies_dropped": 0, + "duplicate_cids_dropped": 0 + }, + "schema_surprises": [ + "laws.article_count dtype=int32", + "laws.date_issued is entirely null", + "laws.eli non-null=0/261", + "laws.language values=['en']" + ], + "n_out": 9802, + "never_invented_legal_text": true, + "n_before_dedupe": 9802, + "n_dropped_total": 0, + "record_type_breakdown": { + "article": 9802 + }, + "jurisdiction_breakdown": { + "KE": 9802 + }, + "snapshot_dates": [ + "2026-09-03" + ], + "heading_language_counts": { + "en": 13 + }, + "heading_language_majority": "en", + "document_language_majority": "en", + "verification": { + "schema_version": "country-laws-normalize-verify/v1", + "slug": "", + "admitted": true, + "n_checks": 7, + "n_failed": 0, + "failed_ids": [], + "checks": [ + { + "id": "nonempty_corpus", + "severity": "fail", + "passed": true, + "message": "normalized corpus has rows", + "evidence": { + "n_out": 9802, + "n_dropped": 0 + } + }, + { + "id": "entry_cid_unique", + "severity": "fail", + "passed": true, + "message": "every row has a unique entry_cid", + "evidence": { + "missing": 0, + "empty": 0, + "duplicate": 0 + } + }, + { + "id": "never_invented_legal_text", + "severity": "fail", + "passed": true, + "message": "normalizer did not invent legal text", + "evidence": { + "never_invented_legal_text": true + } + }, + { + "id": "html_residual", + "severity": "fail", + "passed": true, + "message": "HTML tags stripped from legal bodies", + "evidence": { + "n_bodies": 9802, + "n_with_tags": 0, + "fraction": 0.0, + "samples": [] + } + }, + { + "id": "short_bodies", + "severity": "warn", + "passed": true, + "message": "most legal units have usable body length", + "evidence": { + "n_short": 680, + "n_bodies": 9802, + "fraction": 0.06937359722505611 + } + }, + { + "id": "legal_structure", + "severity": "warn", + "passed": true, + "message": "retrieval units are structured (article, coverage=1.00)", + "evidence": { + "unit": "article", + "structured_rows": 9802, + "coverage": 1.0 + } + }, + { + "id": "heading_language", + "severity": "warn", + "passed": true, + "message": "heading lexicon en vs document language en", + "evidence": { + "document_language": "en", + "heading_language": "en", + "heading_counts": { + "en": 13 + } + } + } + ], + "blocks_graphrag": false + } + }, + "schema_mapping": { + "laws": { + "id": "instrument_id", + "title": "instrument_title", + "text": "body", + "article_count_dtype_source": "int32" + }, + "articles": { + "id": "source_id / article identity", + "law_id": "instrument_id", + "title": "article_title", + "text": "body" + }, + "unit_policy": "prefer articles; fall back to law-level when articles empty", + "required_law_columns": [ + "id", + "title", + "text" + ], + "required_article_columns": [ + "id", + "law_id", + "title", + "text" + ], + "fail_closed": true, + "notes": "Malta and Germany share the same column names. Drift: Malta article_count is int64, Germany article_count is int32; Germany eli is often null. Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family." + }, + "indexes": { + "bm25_document_chunks": { + "cid": "bafkreic4o4x4ifypajf6lj2ftiiarfrxnsxlhm6gqemp324wqgcl5uqj2i", + "sha256": "5c772fc4170f024be5a7459a100896376caeb3b3c68118fdeb968184bed209d2", + "size_bytes": 4968, + "relative_path": "indexes/bm25_document_chunks.parquet" + }, + "bm25_keyword_shards": { + "cid": "bafkreid6jyydnxqg5rq6flkcxukzn2dk4tpp75r6lyzldybx3qc7neg76u", + "sha256": "7e4e3036de06ec61e2ad42bd1596e86ae4defff63e5e32b1e037dc05f690dff5", + "size_bytes": 5476, + "relative_path": "indexes/bm25_keyword_shards.parquet" + }, + "corpus_chunks": { + "cid": "bafkreigvlqzpa2bnpa3unz7dlqt6imrsmnv4sz3tequucs5lobajqvauei", + "sha256": "d55c32f0682d783746e7e35c27e43232636bc967732429414bab704098541422", + "size_bytes": 8984, + "relative_path": "indexes/corpus_chunks.parquet" + }, + "graph_edge_chunks": { + "cid": "bafkreifi2xff7gpzukikjcfwcy3eqzdrllarhfeia5avgknc37s6ozi7l4", + "sha256": "a8d5ca5f99f9a290a488b616364864715ac113948807415329a2dfe5e7651f5f", + "size_bytes": 7791, + "relative_path": "indexes/graph_edge_chunks.parquet" + }, + "graph_incoming_adjacency": { + "relative_path": "indexes/graph_incoming_adjacency.parquet", + "present": false + }, + "graph_node_chunks": { + "cid": "bafkreigmswzsijwoljapyj6q73kgnhg5neak7fokoxqaqx76d2f37p7f3i", + "sha256": "cc95b32426ce5a40fc27d0fed4669cdd6900af95ca75e0085ffe1e8bbfbfe5da", + "size_bytes": 5203, + "relative_path": "indexes/graph_node_chunks.parquet" + }, + "graph_outgoing_adjacency": { + "relative_path": "indexes/graph_outgoing_adjacency.parquet", + "present": false + }, + "vector_chunks": { + "cid": "bafkreihpqg4csnooeg2uwcvz7kr7fwshpkp73xamaxad74vq5a7rguk2la", + "sha256": "ef81b82935ce21b54b0ab9faa3f2da477a9ffddc0c05c03ff2b0e83f13515a58", + "size_bytes": 27370, + "relative_path": "indexes/vector_chunks.parquet" + } }, "source": { "source_dataset": "endomorphosis/ipfs_kenya_laws", "source_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", - "laws_path": "/workspace/country-laws-ir/cache/kenya_filtered_27b81c642fec/data/laws.parquet", - "articles_path": "/workspace/country-laws-ir/cache/kenya_filtered_27b81c642fec/data/articles.parquet", - "laws_sha256": null, - "articles_sha256": null, + "laws_path": "/home/barberb/.ipfs_datasets/country-laws-ir/cache/hf/datasets--endomorphosis--ipfs_kenya_laws/snapshots/27b81c642fec385c9123c30b9eb885d093b70f61/data/laws.parquet", + "articles_path": "/home/barberb/.ipfs_datasets/country-laws-ir/cache/hf/datasets--endomorphosis--ipfs_kenya_laws/snapshots/27b81c642fec385c9123c30b9eb885d093b70f61/data/articles.parquet", + "laws_sha256": "75141fbb55a5d2426cbaf3825abf2b3c08c3e09f405df30656737e150baf2439", + "articles_sha256": "cc4af552d319fec593b42ef8ddb57e0d6da23581ae6c558dc7cfe9aaccf6afad", "n_laws_source": 261, "n_articles_source": 9802, "laws_columns": [ @@ -51,103 +388,121 @@ "record_type", "metadata_json" ], - "local_source_dir": "/workspace/country-laws-ir/cache/kenya_filtered_27b81c642fec", - "pack_meta": { - "slug": "kenya", - "name": "Kenya", - "repo": "endomorphosis/ipfs_kenya_laws", - "source_dataset": "endomorphosis/ipfs_kenya_laws", - "source_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", - "filtered": true, - "filter_reason": "memsafe pass-through (chrome skipped; floor==hub; soft never-thin)", - "indexable": true, - "skip_reason": null, - "n_laws": 261, - "n_articles": 9802 - } + "article_count_dtype": "int32", + "schema_surprises": [ + "laws.article_count dtype=int32", + "laws.date_issued is entirely null", + "laws.eli non-null=0/261", + "laws.language values=['en']" + ] }, - "counts": { - "corpus_rows": 9802, - "laws": 0, - "articles": 9802, - "bm25_documents": 9802, - "bm25_posting_rows": 17559, - "graph_nodes": 10223, - "graph_edges": 145827, - "vector_rows": 9802, - "graph_incoming_adjacency_rows": 0, - "graph_outgoing_adjacency_rows": 0 - }, - "bm25": { - "k1": 1.2, - "b": 0.75, - "title_weight": 5.0, - "body_weight": 1.0, - "average_document_length": 198.4584778616609, - "tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1", - "max_query_terms": 64, - "posting_rows_per_record": 4096, - "terms_per_shard": 4096, - "n_docs": 9802, - "n_terms": 17532, - "n_posting_rows": 17559, - "n_postings": 705453 - }, - "graph": { - "n_nodes": 10223, - "n_edges": 145827, - "n_doc_nodes": 9943, - "n_facet_nodes": 280, - "edge_types": [ - "ARTICLE_OF", - "BM25_NEIGHBOR_OF", - "HAS_INSTRUMENT", - "HAS_JURISDICTION", - "HAS_LANGUAGE", - "HAS_SOURCE", - "HAS_STATUS", - "IDENTIFIED_BY", - "IDENTIFIED_BY_ELI" - ], - "adjacency": "empty_placeholder_oom_avoidance" - }, - "vector": { - "model_name": "thenlper/gte-small", - "dimension": 384, - "similarity": "cosine", - "assignment": "sequential_shards", - "layout": "semantic_centroid_groups", - "rows_sorted_by": "cosine_similarity_to_shard_centroid_desc", - "max_rows_per_chunk": 4096, - "n_vectors": 9802, - "centroid_count": 3, - "shard_count": 3, - "status": "embedded", - "via": "layout_vectors_memsafe_sequential" - }, - "normalization": { - "source_dataset": "endomorphosis/ipfs_kenya_laws", + "incremental": { + "kind": "full_rebuild", + "mode": "auto", + "reason": "operator forced full rebuild", "source_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", - "n_laws_in": 261, - "n_articles_in": 9802, - "unit": "article", - "drops": { - "empty_body": 0, - "missing_instrument": 0, - "duplicate_cid": 0 + "prior_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", + "source_fingerprint": "27b81c642fec385c9123c30b9eb885d093b70f61|75141fbb55a5d2426cbaf3825abf2b3c08c3e09f405df30656737e150baf2439|cc4af552d319fec593b42ef8ddb57e0d6da23581ae6c558dc7cfe9aaccf6afad", + "prior_fingerprint": "27b81c642fec385c9123c30b9eb885d093b70f61||", + "delta": { + "n_added": 8952, + "n_removed": 8952, + "n_unchanged": 850, + "prior_count": 9802, + "current_count": 9802, + "changed_ratio": 0.9132830034686799, + "equivalent_to_full": false, + "added_cids_sample": [ + "bafkreia2262dj2cwaiuwqymgcwy7sjbvjt2xjv6oax2uupig7ezt46anki", + "bafkreia22ddwnkjrlskdlydzwk6bz47mg2n65jrnspr2cflfed3zef62mq", + "bafkreia22x25qkb2dn2vlhc7wl53gub2fbsuxqcp257j2ehyhysd7lwlgy", + "bafkreia23xq6jcho7rd2auqkvb4u7orsyakxvd6eyqpvgpdy7ccilxefru", + "bafkreia23y6kagptqurj6dm44ugphfz5fdj44zz5me3rnej5v6ounpipwy", + "bafkreia24rrast4bhtprigu47d5fdpepibkqzbcqar4ipqz3rnvzh74igq", + "bafkreia25lpqllu7dpbxaxmjfc43es4txh2bm7v3zql7yhoml2o2bb6ide", + "bafkreia25trvlhmusgvvqgrmcli56uvkyiqlqhedhfp67gdt7ytz4shfru" + ], + "removed_cids_sample": [ + "bafkreia22ploqefnksul2rpnrpswzduqx5ucthterccdryfuav25n7pze4", + "bafkreia243jkw3ykucxud73u2hsc7ailzxdvifnjluhmruaslzcfqkqyca", + "bafkreia24i7siiyhytxe63e7bqcwnjo7wndpqw4ik6jpvd3kxw3i2puyei", + "bafkreia26bbe4j44ov4aquz7efb2w7bwgtzb6uszmpqbclru5hztb5zkf4", + "bafkreia27hefyyzxsgcs22qods25mey5nvm4f4g3gswyxa7abac62ejuwy", + "bafkreia27vmvwpxrvaygf5stai2g27cobqpdkfgplkwf4vjrspw6uvhyuu", + "bafkreia27y6b2epwmsulvo5tbc3tflk353teqv2u7j5kjpgr5s2l473e4i", + "bafkreia2bee7ymugwhybfqxvhu4rnuchpuip7nd7dsjvpjubzeqrst62am" + ] }, - "n_out": 9802, - "n_dropped_total": 0, - "via": "kenya_corpus_stream", - "record_type_breakdown": { - "article": 9802 + "reuse_embeddings": false, + "skip_build": false, + "equivalent_to_full": true, + "schema_version": "country-laws-ir-graphrag/v1", + "vectors": { + "n_docs": 9802, + "n_reused": 0, + "n_encoded": 9802, + "n_missing": 0, + "model_name": "thenlper/gte-small", + "model_revision": "17e1f347d17fe144873b1201da91788898c639cd", + "dimension": 384, + "status": "merged", + "device": "cuda", + "device_fallback": false + } + }, + "sparse": { + "engine": "hf_graphrag", + "schema_version": "country-laws-ir-graphrag/v1", + "bm25": { + "bm25": { + "average_document_length": 175.1078351356866, + "b": 0.75, + "body_weight": 1.0, + "k1": 1.2, + "max_query_terms": 64, + "posting_rows_per_record": 4096, + "terms_per_shard": 4096, + "title_weight": 5.0, + "tokenizer": "hf-graphrag-bm25-tokens/v1" + }, + "configs": { + "bm25_documents": "data/bm25/documents/*.parquet", + "bm25_postings": "data/bm25/postings/*.parquet", + "bm25_keyword_index": "indexes/bm25_keyword_shards.parquet" + }, + "counts": { + "bm25_document_chunks": 3, + "bm25_documents": 9802, + "bm25_keyword_shards": 6, + "bm25_posting_rows": 21107, + "bm25_postings": 712415, + "bm25_terms": 21080, + "bm25_token_instances": 1716407 + }, + "indexes": { + "bm25_document_chunks": { + "cid": "bafkreic4o4x4ifypajf6lj2ftiiarfrxnsxlhm6gqemp324wqgcl5uqj2i", + "relative_path": "indexes/bm25_document_chunks.parquet", + "row_count": 3, + "sha256": "5c772fc4170f024be5a7459a100896376caeb3b3c68118fdeb968184bed209d2", + "size_bytes": 4968 + }, + "bm25_keyword_shards": { + "cid": "bafkreid6jyydnxqg5rq6flkcxukzn2dk4tpp75r6lyzldybx3qc7neg76u", + "relative_path": "indexes/bm25_keyword_shards.parquet", + "row_count": 6, + "sha256": "7e4e3036de06ec61e2ad42bd1596e86ae4defff63e5e32b1e037dc05f690dff5", + "size_bytes": 5476 + } + }, + "schema_version": "hf-graphrag-bm25-layout/v1" }, - "language_breakdown": { - "en": 9802 + "graph": { + "node_count": 10223, + "edge_count": 68614, + "adjacency": "data/graph/adjacency/{out,in}/*.parquet" }, - "never_invented_legal_text": true - }, - "neighbor_via": "sqlite_fts", - "built_utc": "2026-09-13T14:29:27.111231+00:00", - "via": "kenya_package_stream_graph" + "sqlite": false, + "query_engine": "duckdb" + } } diff --git a/normalization_report.json b/normalization_report.json index 8e57e10b33676f965cae4ddf3ef02b0d260cb69a..4755f5b7f5c66dd1ec9b4dabeac439e74213405e 100644 --- a/normalization_report.json +++ b/normalization_report.json @@ -1,12 +1,12 @@ { "source_dataset": "endomorphosis/ipfs_kenya_laws", - "source_revision": "c037537a3f170bceb9a08e907321ebe04b5856cd", - "laws_sha256": "3f24988196e4ed4fbf69f56326c2ae4f7827fe24a2a273b01345645d8d2fbc44", - "articles_sha256": "a7abc155ae78385e2b7b2ed6a9a98f26eea7fde184a178e899cdc4c93f780733", + "source_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", + "laws_sha256": "75141fbb55a5d2426cbaf3825abf2b3c08c3e09f405df30656737e150baf2439", + "articles_sha256": "cc4af552d319fec593b42ef8ddb57e0d6da23581ae6c558dc7cfe9aaccf6afad", "n_laws_in": 261, - "n_articles_in": 8858, + "n_articles_in": 9802, "unit": "article", - "article_law_coverage": 33.93869731800766, + "article_law_coverage": 37.55555555555556, "sparse_article_fallback": false, "drops": { "empty_body": 0, @@ -20,16 +20,16 @@ "duplicate_cid": [] }, "language_breakdown": { - "en": 8858 + "en": 9802 }, "quality_flags": { "articles_table_empty": false, "sparse_article_fallback": false, - "article_law_coverage": 33.93869731800766, + "article_law_coverage": 37.55555555555556, "all_source_article_counts_zero": false, "article_extraction_status_counts": { - "ok": 140, - "missing": 121 + "ok": 141, + "missing": 120 }, "missing_date": false, "missing_date_issued": true, @@ -44,17 +44,110 @@ "laws.eli non-null=0/261", "laws.language values=['en']" ], - "n_out": 8858, + "n_out": 9802, "never_invented_legal_text": true, - "n_before_dedupe": 8858, + "n_before_dedupe": 9802, "n_dropped_total": 0, "record_type_breakdown": { - "article": 8858 + "article": 9802 }, "jurisdiction_breakdown": { - "KE": 8858 + "KE": 9802 }, "snapshot_dates": [ "2026-09-03" - ] + ], + "heading_language_counts": { + "en": 13 + }, + "heading_language_majority": "en", + "document_language_majority": "en", + "verification": { + "schema_version": "country-laws-normalize-verify/v1", + "slug": "", + "admitted": true, + "n_checks": 7, + "n_failed": 0, + "failed_ids": [], + "checks": [ + { + "id": "nonempty_corpus", + "severity": "fail", + "passed": true, + "message": "normalized corpus has rows", + "evidence": { + "n_out": 9802, + "n_dropped": 0 + } + }, + { + "id": "entry_cid_unique", + "severity": "fail", + "passed": true, + "message": "every row has a unique entry_cid", + "evidence": { + "missing": 0, + "empty": 0, + "duplicate": 0 + } + }, + { + "id": "never_invented_legal_text", + "severity": "fail", + "passed": true, + "message": "normalizer did not invent legal text", + "evidence": { + "never_invented_legal_text": true + } + }, + { + "id": "html_residual", + "severity": "fail", + "passed": true, + "message": "HTML tags stripped from legal bodies", + "evidence": { + "n_bodies": 9802, + "n_with_tags": 0, + "fraction": 0.0, + "samples": [] + } + }, + { + "id": "short_bodies", + "severity": "warn", + "passed": true, + "message": "most legal units have usable body length", + "evidence": { + "n_short": 680, + "n_bodies": 9802, + "fraction": 0.06937359722505611 + } + }, + { + "id": "legal_structure", + "severity": "warn", + "passed": true, + "message": "retrieval units are structured (article, coverage=1.00)", + "evidence": { + "unit": "article", + "structured_rows": 9802, + "coverage": 1.0 + } + }, + { + "id": "heading_language", + "severity": "warn", + "passed": true, + "message": "heading lexicon en vs document language en", + "evidence": { + "document_language": "en", + "heading_language": "en", + "heading_counts": { + "en": 13 + } + } + } + ], + "blocks_graphrag": false + } } diff --git a/normalize.py b/normalize.py index 0581461c6d8397c50d0ed3db0d5b3f1171eca20d..b3c348f675dd13ca6f9184c6ffffce5cdfead2d8 100644 --- a/normalize.py +++ b/normalize.py @@ -1,8 +1,9 @@ """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus. Prefer article/section as the retrieval unit; fall back to law-level when -articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE -GraphRAG. Never invent legal text or identifiers. +articles are missing or empty. Strip leftover HTML, then detect multilingual +title/chapter/article/section headings (Oregon-style) when present. Never +invent legal text or a hierarchy that is not in the source. Public Hub reads only (token=False). No Hugging Face token is read or stored. """ @@ -11,30 +12,42 @@ from __future__ import annotations import json import os -import re -import unicodedata from collections import Counter from pathlib import Path from typing import Any import pandas as pd from huggingface_hub import dataset_info, hf_hub_download +from huggingface_hub.errors import EntryNotFoundError from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION from .auth import configure_hf, public_token from .cidutil import cid_of_json, sha256_file, sha256_hex from .schema import SchemaError, validate_articles, validate_laws +from .structure import normalize_legal_text, split_structured_units -_WS_RE = re.compile(r"\s+", re.UNICODE) COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py" +EMPTY_ARTICLE_COLUMNS = ( + "law_id", + "id", + "title", + "text", + "source_url", + "document_number", + "article_number", + "record_type", + "metadata_json", +) + + +def _empty_articles() -> pd.DataFrame: + return pd.DataFrame(columns=list(EMPTY_ARTICLE_COLUMNS)) def normalize_text(value: Any) -> str: if value is None or (isinstance(value, float) and pd.isna(value)): return "" - text = unicodedata.normalize("NFKC", str(value)) - text = _WS_RE.sub(" ", text).strip() - return text + return normalize_legal_text(value) def _s(value: Any) -> str: @@ -53,24 +66,105 @@ def _download(repo_id: str, filename: str, cache_dir: Path) -> Path: return Path(path) +def _repo_filenames(info: Any) -> set[str]: + return {str(getattr(s, "rfilename", "") or "") for s in (getattr(info, "siblings", None) or [])} + + +def _pick_repo_file(filenames: set[str], name: str) -> str | None: + for cand in (f"data/{name}.parquet", f"{name}.parquet"): + if cand in filenames: + return cand + return None + + +def _resolve_local_parquet(root: Path, name: str, *, required: bool = True) -> Path | None: + """Accept either <root>/data/<name>.parquet or <root>/<name>.parquet.""" + for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"): + if cand.is_file(): + return cand + if required: + raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)") + return None + + +def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: + """Load a local country-laws pack (filtered preprocess layout).""" + local_dir = Path(local_dir).resolve() + laws_path = _resolve_local_parquet(local_dir, "laws") + articles_path = _resolve_local_parquet(local_dir, "articles", required=False) + laws = pd.read_parquet(laws_path) + articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles() + validate_laws(laws) + validate_articles(articles) + pack_meta: dict[str, Any] = {} + meta_path = local_dir / "pack_meta.json" + if meta_path.is_file(): + try: + pack_meta = json.loads(meta_path.read_text(encoding="utf-8")) + except Exception: + pack_meta = {} + source_dataset = ( + pack_meta.get("source_dataset") + or pack_meta.get("repo") + or f"local/{local_dir.name}" + ) + source_revision = str( + pack_meta.get("source_revision") + or pack_meta.get("revision") + or f"local:{local_dir.name}" + ) + meta = { + "source_dataset": source_dataset, + "source_revision": source_revision, + "laws_path": str(laws_path), + "articles_path": str(articles_path) if articles_path is not None else None, + "laws_sha256": sha256_file(laws_path), + "articles_sha256": sha256_file(articles_path) if articles_path is not None else None, + "n_laws_source": int(len(laws)), + "n_articles_source": int(len(articles)), + "laws_columns": list(map(str, laws.columns)), + "articles_columns": list(map(str, articles.columns)), + "article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None, + "schema_surprises": _schema_surprises(laws, articles), + "local_source_dir": str(local_dir), + "pack_meta": pack_meta, + } + return laws, articles, meta + + def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: + """Load Hub dataset id OR a local directory with laws/articles parquet.""" + local = Path(repo_id) + if local.is_dir() and ( + (local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file() + ): + return load_local_source(local) + configure_hf() os.environ.setdefault("HF_HOME", str(cache_dir / "hf")) info = dataset_info(repo_id, token=public_token()) revision = info.sha - laws_path = _download(repo_id, "data/laws.parquet", cache_dir) - articles_path = _download(repo_id, "data/articles.parquet", cache_dir) + filenames = _repo_filenames(info) + laws_file = _pick_repo_file(filenames, "laws") or "data/laws.parquet" + articles_file = _pick_repo_file(filenames, "articles") + laws_path = _download(repo_id, laws_file, cache_dir) + articles_path: Path | None = None + if articles_file is not None: + try: + articles_path = _download(repo_id, articles_file, cache_dir) + except EntryNotFoundError: + articles_path = None laws = pd.read_parquet(laws_path) - articles = pd.read_parquet(articles_path) + articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles() validate_laws(laws) validate_articles(articles) meta = { "source_dataset": repo_id, "source_revision": revision, "laws_path": str(laws_path), - "articles_path": str(articles_path), + "articles_path": str(articles_path) if articles_path is not None else None, "laws_sha256": sha256_file(laws_path), - "articles_sha256": sha256_file(articles_path), + "articles_sha256": sha256_file(articles_path) if articles_path is not None else None, "n_laws_source": int(len(laws)), "n_articles_source": int(len(articles)), "laws_columns": list(map(str, laws.columns)), @@ -188,6 +282,35 @@ def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, return "" +def _hierarchy_fields( + title: str, body: str, article_number: str, *, language: str = "" +) -> dict[str, Any]: + """Best-effort hierarchy from a single already-split article/section body.""" + units = split_structured_units( + f"{title}\n{body}" if title else body, language=language + ) + if not units: + return { + "hierarchy_kind": "article" if article_number else "law", + "hierarchy_path": "", + "title_number": "", + "chapter_number": "", + "part_number": "", + "section_number": "", + "subsections": [], + } + unit = units[0] + return { + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + } + + def _collector(meta: dict[str, Any], source_dataset: str) -> str: nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for blob in (meta, nested): @@ -392,6 +515,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": instrument_id, "article_id": source_id, + **_hierarchy_fields( + article_title, body, article_number, language=parent["language"] + ), }, ) ) @@ -404,6 +530,49 @@ def build_corpus( report["drop_samples"]["empty_body"].append(instrument_id) continue meta = parent["metadata"] + units = split_structured_units(body, language=parent["language"]) + if units: + report["unit"] = "structured" + for unit in units: + entries.append( + _base_record( + record_type=unit.kind if unit.kind in {"article", "section"} else "article", + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number=unit.article_number or unit.number, + article_title=unit.heading, + body=unit.body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage="structured (headings detected in law body)", + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=f"{instrument_id}-{unit.kind}-{unit.number}", + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": instrument_id, + "article_id": "", + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + }, + ) + ) + continue entries.append( _base_record( record_type="law", @@ -434,6 +603,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": "", "article_id": "", + **_hierarchy_fields( + parent["instrument_title"], body, "", language=parent["language"] + ), }, ) ) @@ -510,5 +682,23 @@ def build_corpus( "empty_bodies_dropped": report["drops"]["empty_body"], "duplicate_cids_dropped": report["drops"]["duplicate_cid"], } + from .profiles import majority_language, score_heading_languages + + sample_text = "" + if not df.empty and "body" in df.columns: + sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist()) + if "title" in df.columns: + sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text + heading_langs = score_heading_languages(sample_text) + report["heading_language_counts"] = dict(heading_langs) + report["heading_language_majority"] = majority_language(heading_langs) + report["document_language_majority"] = None + if report.get("language_breakdown"): + report["document_language_majority"] = max( + report["language_breakdown"].items(), key=lambda kv: kv[1] + )[0] + from .verify import verify_normalized_corpus + + report["verification"] = verify_normalized_corpus(df, report) df.attrs["normalization_report"] = report return df, report diff --git a/query.py b/query.py index 04c965ee12f90902c26200bb37af43d46fc8d91d..9cd3a1da6f2ac29b2287609ec1bc797fd55c4774 100644 --- a/query.py +++ b/query.py @@ -42,6 +42,12 @@ class Release: return pd.read_parquet(path) def bm25(self, query: str, top_k: int = 10) -> list[dict]: + try: + from .duckdb_store import bm25_search + + return bm25_search(self.root, query, top_k=top_k) + except Exception: + pass q_terms = tokenize(query)[:MAX_QUERY_TERMS] if not q_terms: return [] @@ -124,6 +130,12 @@ class Release: return out def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]: + try: + from .duckdb_store import graph_neighbors + + return graph_neighbors(self.root, node_cid, direction=direction, limit=limit) + except Exception: + pass dirs = ["incoming", "outgoing"] if direction == "both" else [direction] hits = [] for d in dirs: @@ -164,13 +176,17 @@ def main(argv: list[str] | None = None) -> int: p_vec.add_argument("query") p_vec.add_argument("--top-k", type=int, default=10) p_vec.add_argument("--candidate-centroids", type=int, default=4) - p_vec.add_argument("--device", default="cpu") + p_vec.add_argument("--device", default="cuda") p_g = sub.add_parser("graph") g_sub = p_g.add_subparsers(dest="graph_cmd", required=True) p_n = g_sub.add_parser("neighbors") p_n.add_argument("node_cid") - p_n.add_argument("--direction", default="both", choices=["both", "incoming", "outgoing"]) + p_n.add_argument( + "--direction", + default="both", + choices=["both", "in", "out", "incoming", "outgoing"], + ) p_n.add_argument("--limit", type=int, default=25) args = ap.parse_args(argv) diff --git a/reports/normalization.json b/reports/normalization.json index 8e57e10b33676f965cae4ddf3ef02b0d260cb69a..4755f5b7f5c66dd1ec9b4dabeac439e74213405e 100644 --- a/reports/normalization.json +++ b/reports/normalization.json @@ -1,12 +1,12 @@ { "source_dataset": "endomorphosis/ipfs_kenya_laws", - "source_revision": "c037537a3f170bceb9a08e907321ebe04b5856cd", - "laws_sha256": "3f24988196e4ed4fbf69f56326c2ae4f7827fe24a2a273b01345645d8d2fbc44", - "articles_sha256": "a7abc155ae78385e2b7b2ed6a9a98f26eea7fde184a178e899cdc4c93f780733", + "source_revision": "27b81c642fec385c9123c30b9eb885d093b70f61", + "laws_sha256": "75141fbb55a5d2426cbaf3825abf2b3c08c3e09f405df30656737e150baf2439", + "articles_sha256": "cc4af552d319fec593b42ef8ddb57e0d6da23581ae6c558dc7cfe9aaccf6afad", "n_laws_in": 261, - "n_articles_in": 8858, + "n_articles_in": 9802, "unit": "article", - "article_law_coverage": 33.93869731800766, + "article_law_coverage": 37.55555555555556, "sparse_article_fallback": false, "drops": { "empty_body": 0, @@ -20,16 +20,16 @@ "duplicate_cid": [] }, "language_breakdown": { - "en": 8858 + "en": 9802 }, "quality_flags": { "articles_table_empty": false, "sparse_article_fallback": false, - "article_law_coverage": 33.93869731800766, + "article_law_coverage": 37.55555555555556, "all_source_article_counts_zero": false, "article_extraction_status_counts": { - "ok": 140, - "missing": 121 + "ok": 141, + "missing": 120 }, "missing_date": false, "missing_date_issued": true, @@ -44,17 +44,110 @@ "laws.eli non-null=0/261", "laws.language values=['en']" ], - "n_out": 8858, + "n_out": 9802, "never_invented_legal_text": true, - "n_before_dedupe": 8858, + "n_before_dedupe": 9802, "n_dropped_total": 0, "record_type_breakdown": { - "article": 8858 + "article": 9802 }, "jurisdiction_breakdown": { - "KE": 8858 + "KE": 9802 }, "snapshot_dates": [ "2026-09-03" - ] + ], + "heading_language_counts": { + "en": 13 + }, + "heading_language_majority": "en", + "document_language_majority": "en", + "verification": { + "schema_version": "country-laws-normalize-verify/v1", + "slug": "", + "admitted": true, + "n_checks": 7, + "n_failed": 0, + "failed_ids": [], + "checks": [ + { + "id": "nonempty_corpus", + "severity": "fail", + "passed": true, + "message": "normalized corpus has rows", + "evidence": { + "n_out": 9802, + "n_dropped": 0 + } + }, + { + "id": "entry_cid_unique", + "severity": "fail", + "passed": true, + "message": "every row has a unique entry_cid", + "evidence": { + "missing": 0, + "empty": 0, + "duplicate": 0 + } + }, + { + "id": "never_invented_legal_text", + "severity": "fail", + "passed": true, + "message": "normalizer did not invent legal text", + "evidence": { + "never_invented_legal_text": true + } + }, + { + "id": "html_residual", + "severity": "fail", + "passed": true, + "message": "HTML tags stripped from legal bodies", + "evidence": { + "n_bodies": 9802, + "n_with_tags": 0, + "fraction": 0.0, + "samples": [] + } + }, + { + "id": "short_bodies", + "severity": "warn", + "passed": true, + "message": "most legal units have usable body length", + "evidence": { + "n_short": 680, + "n_bodies": 9802, + "fraction": 0.06937359722505611 + } + }, + { + "id": "legal_structure", + "severity": "warn", + "passed": true, + "message": "retrieval units are structured (article, coverage=1.00)", + "evidence": { + "unit": "article", + "structured_rows": 9802, + "coverage": 1.0 + } + }, + { + "id": "heading_language", + "severity": "warn", + "passed": true, + "message": "heading lexicon en vs document language en", + "evidence": { + "document_language": "en", + "heading_language": "en", + "heading_counts": { + "en": 13 + } + } + } + ], + "blocks_graphrag": false + } }