diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..416f02acd37983301b8ebeb9146b3dfb0e20b2d4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,60 +1,2 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.avro filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.lz4 filter=lfs diff=lfs merge=lfs -text -*.mds filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text *.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zst filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text -# Audio files - uncompressed -*.pcm filter=lfs diff=lfs merge=lfs -text -*.sam filter=lfs diff=lfs merge=lfs -text -*.raw filter=lfs diff=lfs merge=lfs -text -# Audio files - compressed -*.aac filter=lfs diff=lfs merge=lfs -text -*.flac filter=lfs diff=lfs merge=lfs -text -*.mp3 filter=lfs diff=lfs merge=lfs -text -*.ogg filter=lfs diff=lfs merge=lfs -text -*.wav filter=lfs diff=lfs merge=lfs -text -# Image files - uncompressed -*.bmp filter=lfs diff=lfs merge=lfs -text -*.gif filter=lfs diff=lfs merge=lfs -text -*.png filter=lfs diff=lfs merge=lfs -text -*.tiff filter=lfs diff=lfs merge=lfs -text -# Image files - compressed -*.jpg filter=lfs diff=lfs merge=lfs -text -*.jpeg filter=lfs diff=lfs merge=lfs -text -*.webp filter=lfs diff=lfs merge=lfs -text -# Video files - compressed -*.mp4 filter=lfs diff=lfs merge=lfs -text -*.webm filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 1bcfb6ec6a0d5246021e751c61c8b239acce210c..8cc20a5d944f601bcc924dd711d1dd14befb6194 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,132 @@ -# justicedao/ipfs_nicaragua_laws_ir +--- +license: other +task_categories: +- text-retrieval +tags: +- legal +- law +- graphrag +- bm25 +- research +- not-legal-advice +- nicaragua +pretty_name: Nicaragua 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 +--- -Nicaragua laws IR release. +# Nicaragua legislation IR (CID-keyed sparse GraphRAG) + +Research retrieval release of `endomorphosis/ipfs_nicaragua_laws` (revision `59efc0b35ac8296762d3626ac0ea8fef7c7f19a7`) 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 Nicaragua 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_nicaragua_laws_ir`. + +## Counts + +| Field | Value | +| --- | --- | +| Laws (corpus units) | 0 | +| Articles (corpus units) | 34604 | +| Canonical docs | 34604 | +| BM25 terms | 221138 | +| BM25 postings | 2980657 | +| Graph nodes | 35514 | +| Graph edges | 242228 | +| Vectors | 34604 × 384-d `thenlper/gte-small` (partial) | + +## 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_nicaragua_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_nicaragua_laws`. CIDs identify local content; they do not prove public IPFS pinning. diff --git a/build.py b/build.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6b82f409b0f85a8460b49d5039733040996490 --- /dev/null +++ b/build.py @@ -0,0 +1,447 @@ +"""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 .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 .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 ( + DIMENSION, + MODEL_NAME, + assemble_embeddings, + embeddings_by_cid, + layout_stub_vectors, + layout_vectors, + select_device, +) + +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" +PROGRESS = ROOT / "progress.jsonl" + + +def _log(msg: str) -> None: + ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + print(f"[{ts}] {msg}", flush=True) + + +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") + + +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 = "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" + 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(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 + ) + 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") + (REPORTS / "normalization.json").write_text( + json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + _log( + f"normalized docs={len(corpus)} unit={norm_report['unit']} " + f"dropped={norm_report['n_dropped_total']} report={report_path}" + ) + if corpus.empty: + raise RuntimeError("Normalized corpus is empty; refusing to package") + + import gc + + plan = plan_rebuild( + mode=mode, + source_meta=source_meta, + prior=prior, + current_corpus=corpus, + force=force, + ) + _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, + 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"], + "source": repo, + "source_revision": source_meta["source_revision"], + "out": str(out), + "target_hub_id": target_repo(country["slug"]), + "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 + + hub = upload_release(out, target_repo(country["slug"])) + result["hub"] = hub + _log(f"uploaded {hub['url']} rev={hub['revision']}") + record_progress({"event": "uploaded", **result}) + else: + record_progress({"event": "built_local", **{k: v for k, v in result.items() if k != "normalization"}}) + return result + + +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]]: + """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: + try: + 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( + { + "event": "failed", + "country": slug, + "error": str(exc), + "traceback": traceback.format_exc(), + } + ) + 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", +) -> list[dict[str, Any]]: + """Scan Hub gaps and incrementally rebuild stale/missing country IR. + + Default cap skips huge corpora (Finland, Dominican Republic). Pass + ``max_corpus_rows=None`` to include them. + """ + from .coverage import gap_report + + if slugs is None: + report = gap_report(workers=workers) + rows = [c for c in report["countries"] if c.get("rebuild")] + 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] + _log( + f"reindex targets n={len(slugs)} " + f"(from scan rebuild={len(report.get('rebuild') or [])})" + ) + results: list[dict[str, Any]] = [] + for slug in slugs: + _log(f"reindex start {slug}") + try: + results.append( + build_country( + slug, + upload=upload, + mode=mode, + skip_vectors=skip_vectors, + fetch_hub_prior_ir=True, + ) + ) + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + record_progress( + { + "event": "failed", + "country": slug, + "error": str(exc), + "traceback": traceback.format_exc(), + } + ) + results.append({"country": slug, "skipped": False, "error": str(exc)}) + continue + return results 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..6c290939fff5b2871bb2d70b2198aefee715c946 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,38 @@ 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=4) + p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"]) + + 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 +90,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 +100,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 +118,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 +132,69 @@ 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 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, + ) + 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 == "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..0e6b82f409b0f85a8460b49d5039733040996490 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" @@ -47,13 +64,109 @@ def record_progress(event: dict[str, Any]) -> None: 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 +182,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 +193,35 @@ 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 + ) + 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") @@ -93,6 +237,19 @@ def build_country( import gc + plan = plan_rebuild( + mode=mode, + source_meta=source_meta, + prior=prior, + current_corpus=corpus, + force=force, + ) + _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 +257,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 +326,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 +345,93 @@ 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}") + try: + 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( + { + "event": "failed", + "country": slug, + "error": str(exc), + "traceback": traceback.format_exc(), + } + ) 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", +) -> list[dict[str, Any]]: + """Scan Hub gaps and incrementally rebuild stale/missing country IR. + + Default cap skips huge corpora (Finland, Dominican Republic). Pass + ``max_corpus_rows=None`` to include them. + """ + from .coverage import gap_report + + if slugs is None: + report = gap_report(workers=workers) + rows = [c for c in report["countries"] if c.get("rebuild")] + 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] + _log( + f"reindex targets n={len(slugs)} " + f"(from scan rebuild={len(report.get('rebuild') or [])})" + ) + results: list[dict[str, Any]] = [] + for slug in slugs: + _log(f"reindex start {slug}") try: - results.append(build_country(slug, upload=upload)) + results.append( + build_country( + slug, + upload=upload, + mode=mode, + skip_vectors=skip_vectors, + fetch_hub_prior_ir=True, + ) + ) except Exception as exc: _log(f"FAILED {slug}: {exc}") record_progress( @@ -233,5 +442,6 @@ def batch( "traceback": traceback.format_exc(), } ) + results.append({"country": slug, "skipped": False, "error": str(exc)}) continue return results 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..9d50697c25456b2057cd4d86403277bc86d43bc0 --- /dev/null +++ b/country_laws_ir/incremental.py @@ -0,0 +1,517 @@ +"""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, +) -> 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 = 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..d518f83f1b2fe701b6c1fc5f79335bc6c760a414 100644 --- a/country_laws_ir/normalize.py +++ b/country_laws_ir/normalize.py @@ -19,6 +19,7 @@ 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 @@ -27,6 +28,21 @@ from .schema import SchemaError, validate_articles, validate_laws _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: @@ -53,21 +69,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 +120,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 +147,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)), 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/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..5c691b4a91403e46ca842b2a62f76f16f4231fac --- /dev/null +++ b/country_laws_ir/sparse.py @@ -0,0 +1,129 @@ +"""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 + + rows: list[dict[str, Any]] = [] + for rec in corpus.itertuples(index=False): + title = str(getattr(rec, "title", "") or "") + body = str(getattr(rec, "body", "") or "") + 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/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..31376d982f8d70c0c5e5c2a52192614c84f0cea8 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,35 +28,109 @@ 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") + device, _fallback = select_device(device) + 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( @@ -96,7 +174,15 @@ def encode_corpus( ) if done >= n: return out - model = SentenceTransformer(MODEL_NAME, device=device) + model = SentenceTransformer( + MODEL_NAME, + revision=MODEL_REVISION, + device=device, + ) + try: + model.max_seq_length = MAX_SEQ_LENGTH + except Exception: + pass while done < n: j = min(done + int(chunk_size), n) chunk = model.encode( @@ -160,25 +246,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 +423,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/data/corpus/part-000000.parquet b/data/corpus/part-000000.parquet index 2f177023806ee79bf79d479a32306d42be215744..dae5dfbe9da963b5817489469da7c187714e1f40 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:a4509f8958d76746e126687f70799061233dea9359ea12da5270d3f958ced5e5 -size 1575273 +oid sha256:5541aad8783a9cab3406be923f64dd5b1d0e7ffde3c9103bee5466bca34549c0 +size 917950 diff --git a/data/corpus/part-000001.parquet b/data/corpus/part-000001.parquet index 377e4682ff4090dfaf0ca4edfe91403193d3275b..f93446743ba02bdad57fc1f8f4b38b2f0dbd32f9 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:a656b4898b583f36c303de29e5b7d96819f3c47f897c78ebfcb1ae4f5a13535e -size 2175547 +oid sha256:e68c2e234e0eb4461cecab20659a37e4b0390b86d22728245aaeafede377124f +size 1263719 diff --git a/data/corpus/part-000002.parquet b/data/corpus/part-000002.parquet index cd1babdb98cbe3dd9086bb1a20db0abef65736b6..54c55d91f7115ea94485fab77c96dedc217a7bcf 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:b793972929cd85ec839265c977e9dfb989c0c80c749c3b880a05e22e6bf8c367 -size 2301124 +oid sha256:3cf57f24e91e053b94828c787ad4dd231b3fc2c704e0d21ed38774c77537dba9 +size 1981566 diff --git a/data/corpus/part-000003.parquet b/data/corpus/part-000003.parquet index 7163f74d6b419a7a6b0f71e267bf887815506fd6..59bdd3c20acd830b1032620f0d88a8aa86203dbf 100644 --- a/data/corpus/part-000003.parquet +++ b/data/corpus/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:60a8516e327dee0d15214ca4948705a5d78e8d591e48401f2bc26764e377c207 -size 1190866 +oid sha256:b0134f61f61bd2c10612fb96567f8731190287b2339dcfab013e7642262acbf6 +size 2136779 diff --git a/data/corpus/part-000004.parquet b/data/corpus/part-000004.parquet new file mode 100644 index 0000000000000000000000000000000000000000..c69f57ef9a3340552c66ed9b0f6305db43627bf3 --- /dev/null +++ b/data/corpus/part-000004.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f2faf871605e3574624102596a73d182ab5dbe8efa14bd0e5b33fede0fa0a85 +size 1421748 diff --git a/data/corpus/part-000005.parquet b/data/corpus/part-000005.parquet new file mode 100644 index 0000000000000000000000000000000000000000..7bee9d03b7d240d4d9d3b810a89f7c7d4f2e0987 --- /dev/null +++ b/data/corpus/part-000005.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a69830cb34a5a517bfe1cc88b9d45d3da961b42f8c21e28027f7a5491ad6a75 +size 1228698 diff --git a/data/corpus/part-000006.parquet b/data/corpus/part-000006.parquet new file mode 100644 index 0000000000000000000000000000000000000000..1f6d073900258beee0ba113bb9fbcb0806704519 --- /dev/null +++ b/data/corpus/part-000006.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccff86a19f70ccf047bafaf90b718cbedb219046edb8da78e034d85b51f677fb +size 3356654 diff --git a/data/corpus/part-000007.parquet b/data/corpus/part-000007.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6600ea75904edb1f7697753e53d8d174594c9816 --- /dev/null +++ b/data/corpus/part-000007.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d96b8df8fa236833e266f27676febe4d17ca1f4d8ccf958d22d3753350354fc +size 1048756 diff --git a/data/corpus/part-000008.parquet b/data/corpus/part-000008.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6a15e2d5856715e8aee80b1aac1e35e8ce0bb5a0 --- /dev/null +++ b/data/corpus/part-000008.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84f671b5be85aaa4db3129842e2d53598202198476fea5ead03e9e10b240d534 +size 1378444 diff --git a/data/graph/adjacency/out/part-000000.parquet b/data/graph/adjacency/out/part-000000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..2f9a00550fdef86404b383b1dc488ecb0b2bedb5 --- /dev/null +++ b/data/graph/adjacency/out/part-000000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d15c2e80fc37cf6e3e137f781b06f2110eb3321101d456b0de32d1a6adc2d687 +size 360967 diff --git a/data/graph/adjacency/out/part-000001.parquet b/data/graph/adjacency/out/part-000001.parquet new file mode 100644 index 0000000000000000000000000000000000000000..998b4befa0a7b8a3d3dcbbc035b4ffcce9c34491 --- /dev/null +++ b/data/graph/adjacency/out/part-000001.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e30b603a7c5bde1bced0fcf79ea3f99b1896ac2f5eb59b8995a7e8384600d7a9 +size 360499 diff --git a/data/graph/adjacency/out/part-000002.parquet b/data/graph/adjacency/out/part-000002.parquet new file mode 100644 index 0000000000000000000000000000000000000000..f8fb00520786004bbadeb03b452090e7461b988d --- /dev/null +++ b/data/graph/adjacency/out/part-000002.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6b67373294b8c49fcdfa5ea920464ab06ec1c4f89ea5dbad8599cd25e68c067 +size 360784 diff --git a/data/graph/adjacency/out/part-000004.parquet b/data/graph/adjacency/out/part-000004.parquet new file mode 100644 index 0000000000000000000000000000000000000000..597bd88ec973c76531b66e8cdee5ca17268e8a90 --- /dev/null +++ b/data/graph/adjacency/out/part-000004.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:530adb914eac34f9b6d2dc5d9a20251bcc9f0327389c09634f1423af8d730e0d +size 360140 diff --git a/data/graph/adjacency/out/part-000005.parquet b/data/graph/adjacency/out/part-000005.parquet new file mode 100644 index 0000000000000000000000000000000000000000..9e77a215c2354ac3821398143b1608228b44b800 --- /dev/null +++ b/data/graph/adjacency/out/part-000005.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d09b965756703a7ba54477acb8bb20bb35ec25a1a1ef9e29e15ebbbc1ff9136 +size 361076 diff --git a/data/graph/adjacency/out/part-000006.parquet b/data/graph/adjacency/out/part-000006.parquet new file mode 100644 index 0000000000000000000000000000000000000000..1d734fa826337a9ff01fe277dac039f27ccb2170 --- /dev/null +++ b/data/graph/adjacency/out/part-000006.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ee022e291eb4c1751b1d0e391469cdd3d34bb4fdaac0229548d73573b9d1b7f +size 361201 diff --git a/data/graph/adjacency/out/part-000008.parquet b/data/graph/adjacency/out/part-000008.parquet new file mode 100644 index 0000000000000000000000000000000000000000..05045c518c21d7a2daf496ee51ea8fd4e9e8665f --- /dev/null +++ b/data/graph/adjacency/out/part-000008.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05b6789960dcc67764f100066236da71f69e5ad82141f1dcb6b8cd01bd326d23 +size 361486 diff --git a/data/graph/adjacency/out/part-000009.parquet b/data/graph/adjacency/out/part-000009.parquet new file mode 100644 index 0000000000000000000000000000000000000000..a78339c906b79e4ee5585b59448d3aedfbeae817 --- /dev/null +++ b/data/graph/adjacency/out/part-000009.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49800ad6c3aee4750ae53599992d58e86710a110e3b43fcd00bd41b142cd0ca3 +size 361794 diff --git a/data/graph/adjacency/out/part-000010.parquet b/data/graph/adjacency/out/part-000010.parquet new file mode 100644 index 0000000000000000000000000000000000000000..78aee18de81ff941618dd49123317ca7fc0498ad --- /dev/null +++ b/data/graph/adjacency/out/part-000010.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97dd68683a6a82ab64dcc72f14e50724a035ad9779e9fcb4d0a2baf1487fa625 +size 360316 diff --git a/data/graph/adjacency/out/part-000011.parquet b/data/graph/adjacency/out/part-000011.parquet new file mode 100644 index 0000000000000000000000000000000000000000..8ac0306dd1fd65d7ff8445a6cb24e36ada982514 --- /dev/null +++ b/data/graph/adjacency/out/part-000011.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c0f1adc22e1e3d2b8b2a3f5ec31990c44dcde47a5450fb9da3d8aaea0ba06f7 +size 361311 diff --git a/data/graph/adjacency/out/part-000013.parquet b/data/graph/adjacency/out/part-000013.parquet new file mode 100644 index 0000000000000000000000000000000000000000..1a99a3dda2bd9581c20e3dd7c6f3313c257ff91e --- /dev/null +++ b/data/graph/adjacency/out/part-000013.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cc4e0e946a2f93d10ccb4de792c31480b9ecc2acea14396b83dcb7892a908a7 +size 360274 diff --git a/data/graph/adjacency/out/part-000014.parquet b/data/graph/adjacency/out/part-000014.parquet new file mode 100644 index 0000000000000000000000000000000000000000..a8c9003fb40865417be12d6f1194d27d9754d3fe --- /dev/null +++ b/data/graph/adjacency/out/part-000014.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f197d300daa3156b568441a8485592e88d04fe1a5a0d73061fc509d31f9609d4 +size 361304 diff --git a/data/graph/adjacency/out/part-000015.parquet b/data/graph/adjacency/out/part-000015.parquet new file mode 100644 index 0000000000000000000000000000000000000000..e908d62ef6412c3f05ce3a3660841bdfaf575605 --- /dev/null +++ b/data/graph/adjacency/out/part-000015.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:baac790e69a9f0be6c35e374644a9ee81e9ee1a7d35cc041b279eb559a0b8c25 +size 359536 diff --git a/data/graph/adjacency/out/part-000017.parquet b/data/graph/adjacency/out/part-000017.parquet new file mode 100644 index 0000000000000000000000000000000000000000..04643ab7c43606380f5568ecf12a6fc62c1d1e43 --- /dev/null +++ b/data/graph/adjacency/out/part-000017.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ac399a5a479d5aa852fa8304fadddc8ec98a1f54df6aa1402ba9ba91a11d7ab +size 361407 diff --git a/data/graph/adjacency/out/part-000018.parquet b/data/graph/adjacency/out/part-000018.parquet new file mode 100644 index 0000000000000000000000000000000000000000..b2f0b294fdc72df10164bac02b87f83618b86a59 --- /dev/null +++ b/data/graph/adjacency/out/part-000018.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75a4b922ebd03cf8356d3deb4f1dd25f1f898a98642c95a75f0c619077b0a8d6 +size 360808 diff --git a/data/graph/adjacency/out/part-000019.parquet b/data/graph/adjacency/out/part-000019.parquet new file mode 100644 index 0000000000000000000000000000000000000000..b87b396a64e51ee047c426846d8009f2518e07f7 --- /dev/null +++ b/data/graph/adjacency/out/part-000019.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8bd423520817a0b73a1912638ed300f28f7b24a2549a15964da969dd1705d04 +size 360878 diff --git a/data/graph/adjacency/out/part-000021.parquet b/data/graph/adjacency/out/part-000021.parquet new file mode 100644 index 0000000000000000000000000000000000000000..fe1078cbdb5d7c55e9212f570352b8e6d35493e5 --- /dev/null +++ b/data/graph/adjacency/out/part-000021.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef3fad9df94ff1ed6aaa188c2435864475ccfb4ea9bba2a0aad23cf92a33baa8 +size 362303 diff --git a/data/graph/adjacency/out/part-000022.parquet b/data/graph/adjacency/out/part-000022.parquet new file mode 100644 index 0000000000000000000000000000000000000000..92387b45192ed50691e4487d3b7fd8be17080703 --- /dev/null +++ b/data/graph/adjacency/out/part-000022.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec5a7f54a5a96bab1ab03bf889dd0061bced697298491b05a3dd230f7e66de71 +size 361630 diff --git a/data/graph/adjacency/out/part-000023.parquet b/data/graph/adjacency/out/part-000023.parquet new file mode 100644 index 0000000000000000000000000000000000000000..bcbcf3f7f226540ee70d9acdbdac189a842647b2 --- /dev/null +++ b/data/graph/adjacency/out/part-000023.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4bc324071b8da0f60e03ed99e9abbe5730a98401878abf97bc83d79b3211987 +size 360420 diff --git a/data/graph/adjacency/out/part-000026.parquet b/data/graph/adjacency/out/part-000026.parquet new file mode 100644 index 0000000000000000000000000000000000000000..a34285db7b51cfcd632d2d793da7dc127c71e962 --- /dev/null +++ b/data/graph/adjacency/out/part-000026.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1ef7d5750160ad52cce87dffe9ba60ed8ba78b35df76cb76276accf31484306 +size 362495 diff --git a/data/graph/adjacency/out/part-000027.parquet b/data/graph/adjacency/out/part-000027.parquet new file mode 100644 index 0000000000000000000000000000000000000000..ceea91fd9142d043c3599f4281ff7a5e67195463 --- /dev/null +++ b/data/graph/adjacency/out/part-000027.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ac06929af3bfa17b01e67d679ccbd0f70f9c169c68d877eb6b53a18b1096ad8 +size 361350 diff --git a/data/graph/adjacency/out/part-000029.parquet b/data/graph/adjacency/out/part-000029.parquet new file mode 100644 index 0000000000000000000000000000000000000000..7df652735ccca8d347cef16c48447a1c03363bcd --- /dev/null +++ b/data/graph/adjacency/out/part-000029.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:daaed100d0260aa8c1384c5716352c09e2af749204c3cb533f80a2da753b44c3 +size 215086 diff --git a/data/graph/edges/part-000000.parquet b/data/graph/edges/part-000000.parquet index 6bf071d5844fba33026bfe79f73be9b298e3591c..a500881754cb2d64003cfb69c0d23dbc4ac20aa4 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:53e7f795f2c7d2ed3568f9638ac345d4e4cc8772c555ed857ca3b04d9e61acf6 -size 178746 +oid sha256:a0559d392de49abdb14f24e98804633493caaddd8e6a4e5ca10b6a6f8577f81d +size 301245 diff --git a/data/graph/edges/part-000001.parquet b/data/graph/edges/part-000001.parquet index 6aa932d115ae4f6c1ba35a208e93c6947be7fbe6..3c75de4a01d1535a4eb20f2af51364459de759a3 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:801ef84ed1ba8f2158f4528db691994ebdcc0378252303179c672e22297ff728 -size 180571 +oid sha256:70f1678a6b0efff0c209d84fe4a3cdbe2d2012177f5069ff41488b41b889acdb +size 301412 diff --git a/data/graph/edges/part-000002.parquet b/data/graph/edges/part-000002.parquet index 7f78755da05cb659e7e96e90558cf353197fce1c..ad3a9e82d9ec5eb73821edb5935569f3c3becac1 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:44dfcee505e9196c4a6c250b1612791af2bf89c1195a71d42fae007b5f90e42e -size 179194 +oid sha256:1c3e1faae96e1e61ebba3fbe05a2fe1dd2f1f84641d99ea2102e8ced055bea0e +size 301278 diff --git a/data/graph/edges/part-000003.parquet b/data/graph/edges/part-000003.parquet index a746001a66ee656b90a358e3d3f781780c913787..747e38e8b612fa9f10906568836e0a583232e6f8 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:3722367cb6d036de094207beefb657f38a18652fe7745c56dff6996505e99e37 -size 181104 +oid sha256:326ef41ca9b3129d97b8732ef6a89ef6961a3b63ec04a9e3bd3840dbe5aabc8c +size 301456 diff --git a/data/graph/edges/part-000004.parquet b/data/graph/edges/part-000004.parquet index c7f8faa98627f0f186f00ff9ed75a5d15c3f44e0..8f74afc85b3a4b05738bf586cd6b3952c032b261 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:4712d4c1fbb4026eb11a4cc3ea5346f413b9df6bc8a36b53fb504bf0d19b9fec -size 178242 +oid sha256:5655c32d60239adbd901b6f206560c7e0d4174d94391b33396b4ce29554968df +size 301895 diff --git a/data/graph/edges/part-000005.parquet b/data/graph/edges/part-000005.parquet index d9563174c68746f29072a55fd74585cb3fd2a109..30164d2bc3d3ead5b500679344c1b66cde3b3acd 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:21a7de3710ee525e8967c02f46ca6e02e8377f65b8dbaf25a718c1c6e7a865f4 -size 181306 +oid sha256:ef1f3370ed496e94293d2152bce2e4844277ba56db958eecb87a6fbf7e88a64a +size 300436 diff --git a/data/graph/edges/part-000006.parquet b/data/graph/edges/part-000006.parquet index 39b0ddf04ec4973cd9c273ecc91b2e85a26831e8..c678686b631b5f315a04e0d061f09d028d9973bf 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:0a1e1281c335e9c27811178891948f5fc3d34e36f38d7c87506c5569d7f956ff -size 183501 +oid sha256:117313a27e4b7742771423fa0689d889d5f4d3dac17e4a0efbfeb2fa291f4c8e +size 301623 diff --git a/data/graph/edges/part-000007.parquet b/data/graph/edges/part-000007.parquet index 59bb1d7a1a8e8be9bbab890df30f8551c35a2d5e..d03e59a8d04cab6c42955b914eac79857e46466f 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:34f27c3b492a0483f9655c7349801ee5d97c714e8c1dfd404756aeb3ef23b570 -size 176174 +oid sha256:e92b0bffc67005a71983f005e5e1b14464a6e8c33654b214e428173feefcaaac +size 301327 diff --git a/data/graph/edges/part-000008.parquet b/data/graph/edges/part-000008.parquet index df29646eef21da07b5ed5297c8f301b6815fa951..2b840dc50ddb5ec62ea9b902532b93ebbf030fee 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:a14c6e3a5e2e42043f6c018350d0c81405d98c4e00fb8be669f9ff05896f77e9 -size 180226 +oid sha256:0fb418db6dcb89e8c7d18a4e0a8d71b10d181c7ab6a57798068e7c302e5c2225 +size 302053 diff --git a/data/graph/edges/part-000009.parquet b/data/graph/edges/part-000009.parquet index 27e28d1469c36ffdb09251d149fd01cbc358ea6e..75fb5303537b21c23be0a0e30a2e7e5f8895cf84 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:80a84f32f8fc6737bfbff02c14790886e2941ac2dabb5e3cd6d136b356648cc4 -size 179643 +oid sha256:93ec0ac4c917bf8b054fb41e9119887d875b47649c51223930c0fda43c8c92f0 +size 301824 diff --git a/data/graph/edges/part-000010.parquet b/data/graph/edges/part-000010.parquet index 219699367570c34085f3b2d5cf99d059fbb2c6a6..c52ca04c39c53f29e17feaadcc734d6bc7b1c843 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:9d74df8d9033fedb2669de349fde1d8b35c88c23d347ab196e24ebe8ed941e4c -size 180363 +oid sha256:8cbca67fb4f80f3e4c96d3a654a284867ad02be366d5c272561cdb45790b98ac +size 301174 diff --git a/data/graph/edges/part-000011.parquet b/data/graph/edges/part-000011.parquet index 0f45fd5f306817060500a07572fd1674e1212520..0a0a1a37a5af09f54e5a4493f6cb990d26c220f9 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:471688d43a3d5df9f9437b49a272566d3653d03d60e4a4ed3a207ef2ea1acceb -size 176337 +oid sha256:0d6a7a2e609307affacd8d556f66c32ebd488d042dd076915120680f0a11a21d +size 301632 diff --git a/data/graph/edges/part-000012.parquet b/data/graph/edges/part-000012.parquet index 9251c0ae99da4cbd21460444e1ddd0248f07870c..82789e82a649dfca753b05208615110c8649e8c0 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:9141d9956b18b2bb3c5f2159a21ec02e06bc60bc52e9a070e8e17c4923a5cb0d -size 176740 +oid sha256:633618ec059f68fd79c5b6894214ae5168c775a4e10e0e043cfd598f24402c6e +size 302076 diff --git a/data/graph/edges/part-000013.parquet b/data/graph/edges/part-000013.parquet index 888f280218e69f1a5dd23462bc6797eb8ad8e9d6..ec91862e038ba0e0cbe146efdbe5a884f2a2f08b 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:c589d4ad768448fec19959eb25705315aef73c13085798a63396b81fc05743fb -size 175848 +oid sha256:f76b3242481cd38e246a7b86ad2dc3fc691e11308133c0f929599f25dc66797a +size 302223 diff --git a/data/graph/edges/part-000014.parquet b/data/graph/edges/part-000014.parquet index 1c83a186bc1a0401b63e9d71ef826dd4272e7aba..b80d877caafdea2f4955d9830c35625a47f8f24e 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:48e9c716bfc81d9b65eab71c7e329911b228601881689f2d26a862c2cd359be6 -size 176070 +oid sha256:9eb0dbf3c8cc175845e7cf8be5d72f8ee8383ea507f50e63e604267fb7e4e719 +size 302259 diff --git a/data/graph/edges/part-000015.parquet b/data/graph/edges/part-000015.parquet index eaf1b6dd6e55b7522d24d3ecc3214290e598bdf2..c61cc79ad6bddbe15f07a75fe8dce720274c3d69 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:b356c521a5e8fb1fe1b8f465eb75aba2d3725f935f99cc2f35b111d5e569908f -size 177102 +oid sha256:032d8af6dc6aeb6c8be7aeda71a64657948faedd8d5abcadd0178c8c362d776e +size 302789 diff --git a/data/graph/edges/part-000016.parquet b/data/graph/edges/part-000016.parquet index 82972b4260acdc1799ebc374e92fa7c8f2ddded3..55060f7fa22a78a365434d2a27e69ba22f9e7174 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:76eb3be22304024de042137b19ed752e4b914a87745bc4c73c05e720678a0c47 -size 177303 +oid sha256:c3e2a6a98e2235410f57dfc07dee3052514d9d857ec0443395c5f9e2d4b1e047 +size 301182 diff --git a/data/graph/edges/part-000017.parquet b/data/graph/edges/part-000017.parquet index 8008e2d7e7ea6f6f93f022a03a4f646125c5a4d6..5da287f9e3ad2d1360f7756946b0ae7d86d1d198 100644 --- a/data/graph/edges/part-000017.parquet +++ b/data/graph/edges/part-000017.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3a4b09f8913da28695a887daa308922026eece1643c4f0c726a7f67647dbaffa -size 180339 +oid sha256:06017b1d438c71ac6b873af9102983d9015c9454c564e38344fad5f57544eb44 +size 301443 diff --git a/data/graph/edges/part-000018.parquet b/data/graph/edges/part-000018.parquet index b4959ee1de83636cfce1882ca3e06e5b87bf07df..bf69c4925d0a84e79e78ed4c2ce3d2aa44c291b8 100644 --- a/data/graph/edges/part-000018.parquet +++ b/data/graph/edges/part-000018.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6e756a168d2dce75166f489a9e36bdfc6348443a1a4f902f0ef426c79c83f16c -size 181339 +oid sha256:da1e5773c430dad531aee5868d79175fc4a7a7cf527c4eac4a62fcbcb8493355 +size 300473 diff --git a/data/graph/edges/part-000019.parquet b/data/graph/edges/part-000019.parquet index 07f99369d2dd633b5ff292847ba93012ed3c3d47..1429134eb695eb0cbec5b4321c014ac89026faf2 100644 --- a/data/graph/edges/part-000019.parquet +++ b/data/graph/edges/part-000019.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8794b11eb45b1e628c0d92e5317a4374e404f89de4192df267ae8a9bc8e07245 -size 180688 +oid sha256:2b59416f3748d24fdd08900a37301d59244d0802938f6e98fe9dc8a8d8b90f68 +size 301879 diff --git a/data/graph/edges/part-000020.parquet b/data/graph/edges/part-000020.parquet index 7fa4c38e56cf7609e2deb1287660e863e2a49b8f..36cd5eaee653bef7034ac7f4680104a5f72a3f6a 100644 --- a/data/graph/edges/part-000020.parquet +++ b/data/graph/edges/part-000020.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ea89eef9ecf603f19b2fe2bbeb3190ae39d8be4f6db2a6471013b36392a5d850 -size 177008 +oid sha256:974e744b25cbe85edad566ea13660c1e50e2b50eceb60c1df0b560dd13db79ee +size 300938 diff --git a/data/graph/edges/part-000021.parquet b/data/graph/edges/part-000021.parquet index ddc5c2bfda017807dc4f97955de356e58dfe8e3f..ec04d241a227df644bb80c7bf181be0cd933d9d7 100644 --- a/data/graph/edges/part-000021.parquet +++ b/data/graph/edges/part-000021.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f8de91d112c590478ad87b0cc2d03b59d926e851c5f7dc792b2ee43ba9e913d4 -size 177553 +oid sha256:43f031a05f69cfe6d541c3b9b77a651c9f99ae5f3dd6e7862beebe22f157cb52 +size 300755 diff --git a/data/graph/edges/part-000022.parquet b/data/graph/edges/part-000022.parquet index 81b54f1a71fb2b69c4a533e234a6a76c92982ea8..a95c5dc733ed2b8c5ea688d093be5062d6ffe51c 100644 --- a/data/graph/edges/part-000022.parquet +++ b/data/graph/edges/part-000022.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:89246e37e315a98179614cc11ee045cf7c1a043e1ce40d2146aa8d8c2b72b8a2 -size 177915 +oid sha256:fa7eadb673db068d8924a85e6c9c0df9e81a99d67c4b75c69214092cdb712b75 +size 301735 diff --git a/data/graph/edges/part-000023.parquet b/data/graph/edges/part-000023.parquet index 47b9cb8a7f624a1a2e5722db6452dd94f9228bc3..31592db1fd13d8b6e48e644e03c2f849c8fe1304 100644 --- a/data/graph/edges/part-000023.parquet +++ b/data/graph/edges/part-000023.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:10f836268dcef9152e0b7484dc4f92307a8513049cee5c6e0acab2db6fe3f971 -size 178966 +oid sha256:71a604287575fcbc2df9996b29fa07a3cfa457d79dd9f9c6af60bd840e7ee30e +size 302894 diff --git a/data/graph/edges/part-000024.parquet b/data/graph/edges/part-000024.parquet index c3b58fcf0a4bc47244818e31b33e2d9d3674d03f..5e8d4bd8c016ce909ba251b5417d1fc9707df705 100644 --- a/data/graph/edges/part-000024.parquet +++ b/data/graph/edges/part-000024.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c4f33f54fba91f9cbb4739a79e9b4afc22266c0318053bdfeafcc7f3dfe9b31e -size 188266 +oid sha256:d59870991b23dbb78ca26061b406513d9da53b2fa212dbf557edd7aea333b9df +size 302206 diff --git a/data/graph/edges/part-000025.parquet b/data/graph/edges/part-000025.parquet index e982d097611ff8ef2a7381ca7d91697ac4eab72a..c7e255d2994e3bcef40751b81f0ccec464079256 100644 --- a/data/graph/edges/part-000025.parquet +++ b/data/graph/edges/part-000025.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a4e9bbbc37b0eced6bf614ff5407acefd951bd7b4c2a15818a79e1e6d2f663d9 -size 277060 +oid sha256:ff4355ee4ae53cd55677521bf85f69341cf17c17c9b44f61989c2e1f7be8a079 +size 300940 diff --git a/data/graph/edges/part-000026.parquet b/data/graph/edges/part-000026.parquet index f4ccda357bd29bbe2013271bd1d18819303a1d7f..9599a17049d34d843ba2ae60e469e8bba11539cf 100644 --- a/data/graph/edges/part-000026.parquet +++ b/data/graph/edges/part-000026.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:833752c93c0a3af2a93b7b0b4a31072b6cfa01cdbec3fdc6eb3a6be1a3202444 -size 284608 +oid sha256:fc527278d6fd28a9de9053ba5d340f9b153e1e14942bbd2366d2a99c8c9de583 +size 300973 diff --git a/data/graph/edges/part-000027.parquet b/data/graph/edges/part-000027.parquet index 4065cd5b7394346eb98df6551a99c41e3e58a2fc..6454d0b77df755d417460dc57905b93e9f188cd8 100644 --- a/data/graph/edges/part-000027.parquet +++ b/data/graph/edges/part-000027.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:711f6e1cfc1c7271ff3ebb893f3963961d32f34bb7670f4215ddce8145795a99 -size 247727 +oid sha256:fc0ccc0dc19f4cae6a111a2b23a1a03ade5cab58362123673ae25d06b5cff7c8 +size 302061 diff --git a/data/graph/edges/part-000028.parquet b/data/graph/edges/part-000028.parquet index 210b60d3d3e9bc43d7ad3b9fd88870c3e7f5e977..192506e16804bad1452c9ad34efdd06d019c5556 100644 --- a/data/graph/edges/part-000028.parquet +++ b/data/graph/edges/part-000028.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e119f6a1cbad7f737c02d81a39fb299eb2a57a5fe28f5da788a60575c6127219 -size 275598 +oid sha256:f441e984e53be5042284424d0e7835f148f84998db9ba7dd2ea7fb499ea5823c +size 301204 diff --git a/data/graph/edges/part-000029.parquet b/data/graph/edges/part-000029.parquet index d1b4777b30adadcc76d04e712ad59cf8134040db..e0f84ddb22986a45c2e2b5f9ea5ffcdb28c676f9 100644 --- a/data/graph/edges/part-000029.parquet +++ b/data/graph/edges/part-000029.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f87c13fac3251462dd5fd3e520b4c62df16fbfbd745aa1614a4233370fae5072 -size 302991 +oid sha256:0dd1be870f3a0655af0f6066c1da0176116b70b5f3f6ecc971e430e017933e53 +size 301386 diff --git a/data/graph/edges/part-000030.parquet b/data/graph/edges/part-000030.parquet index 2f3c083cf790b67c088425e19057447207b98da7..1a7df672d96cb98189750b8f8c450a969eb68806 100644 --- a/data/graph/edges/part-000030.parquet +++ b/data/graph/edges/part-000030.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6b2b8112c75b15bb5ce50d766af1beb310c36575aa3c0e92d103a84c25961638 -size 284405 +oid sha256:b1b915fc0bc52e6a39de097b20a91b45deb9ae3c0ee098d4015bcb32f48b9958 +size 301679 diff --git a/data/graph/edges/part-000031.parquet b/data/graph/edges/part-000031.parquet index eea576e18dd0473735b22200c4f93927f47ea5fd..4c7d279567f20a1617c61dc7f4e1dc34b0ecaa1e 100644 --- a/data/graph/edges/part-000031.parquet +++ b/data/graph/edges/part-000031.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7991b66ce3f67a0b5404002c0a6657f4a081a05c93c337c9c81229f49e8c7cb6 -size 278229 +oid sha256:8d65520a2990acf75fc3db116fcfba95046eb4dea845f4c1ff5a855a4982f303 +size 302008 diff --git a/data/graph/edges/part-000032.parquet b/data/graph/edges/part-000032.parquet index 2265281c9d98ff9ea3927db91abb1fcce0cc2fba..cbef5b47f74ed63ab36dabd6101e636731afe68c 100644 --- a/data/graph/edges/part-000032.parquet +++ b/data/graph/edges/part-000032.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1f7dd2fb654edbe5f1856dc6bf72daf7769c20bd6ef91e46a0b30b281bf814e5 -size 301929 +oid sha256:65c623a665cd61b8bc08e4a40e9c92edb177d0eefb31a5b0594096eede17d728 +size 300813 diff --git a/data/graph/edges/part-000033.parquet b/data/graph/edges/part-000033.parquet index 08a6a89a1a07a2eeb6fcdac3e5d2de70badca631..e00c095349a4750660fc1715f5732aa282de8a59 100644 --- a/data/graph/edges/part-000033.parquet +++ b/data/graph/edges/part-000033.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5a2f862aba4d690f3f43bf93061184ba1068f215348fa0355b3f5dcbab3efd80 -size 285088 +oid sha256:aff15feadb4532485227006c9f710c4e208770d35c15b6fffffde5466dd43971 +size 301833 diff --git a/data/graph/edges/part-000034.parquet b/data/graph/edges/part-000034.parquet index 3255acb4b1b307eb3def456cf7ba2d3709d35d19..794043ad9122db7507858b7659cd41a15fbc8434 100644 --- a/data/graph/edges/part-000034.parquet +++ b/data/graph/edges/part-000034.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4bc2c4ec7dfc986c5d1516e03b4b2e4f7b7853dada3089dd61889e175659e185 -size 304119 +oid sha256:346c5b4c29514b62243ebb3639cfc76784ca2aa0d1de1dab1e57899e3b94136b +size 300426 diff --git a/data/graph/edges/part-000035.parquet b/data/graph/edges/part-000035.parquet index fa6bb740d4cc265313fde47118078b00f4ba12d6..524912bcbedca5f1517dbf4b5768d757af8f5b1b 100644 --- a/data/graph/edges/part-000035.parquet +++ b/data/graph/edges/part-000035.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c4f7254f894780a1ef8793123ccb458e62c430b35b4b10282c64a031c90a3f4d -size 269807 +oid sha256:90546f65538ba3ea291aa5d04782808134a4f5601cf003f6406b850f9c611eb2 +size 301549 diff --git a/data/graph/edges/part-000036.parquet b/data/graph/edges/part-000036.parquet index ac42f9afe8930bd20271a69bdd67bfa2e5646ab5..83fcbae8c1f390b785cae77857111915c448747b 100644 --- a/data/graph/edges/part-000036.parquet +++ b/data/graph/edges/part-000036.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:20337659765cdbdc9a09823e21696c3119a3a3afeb50cea419ce3dddf41822e6 -size 297168 +oid sha256:d3aabbba577a5556fafe7f6a26dac5b235e2d01a93eb9df01ba2540eec86dfc5 +size 301517 diff --git a/data/graph/edges/part-000037.parquet b/data/graph/edges/part-000037.parquet index f96425ecb899187d234ffb2867a2aa7f9c5a66d2..c4d43704a717479db2deaa228b5579bd98dc2fad 100644 --- a/data/graph/edges/part-000037.parquet +++ b/data/graph/edges/part-000037.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:73832daa238949b262ca6bdc6cf0dfc83a9ef0888ec17c5ace262658271f1ed2 -size 293108 +oid sha256:726651ed55e713a71a477db4d4cfa9fc8d4bed3e57a013e7f5ce5225e42ea591 +size 302281 diff --git a/data/graph/edges/part-000038.parquet b/data/graph/edges/part-000038.parquet index 9d50aa14f32cc7e6f6d3396113a9dc0bf5ba6227..e37972c2489670fd8ca924da5ca3eb4318e2f76a 100644 --- a/data/graph/edges/part-000038.parquet +++ b/data/graph/edges/part-000038.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:edcd717c26471b79a17d2307527b4da22ab5337c3760b52a09a8d486bb832468 -size 292233 +oid sha256:2b44c7ab31f5907324a4eb4bd758d9e3c6a3b770373ea339edf879ebde112f26 +size 302606 diff --git a/data/graph/edges/part-000039.parquet b/data/graph/edges/part-000039.parquet index 280cf64f3b9e485946eb8e9124f4bf2b3ffefc40..5dbe910dbe54ad9e1b672143ded2f8b2576e3c84 100644 --- a/data/graph/edges/part-000039.parquet +++ b/data/graph/edges/part-000039.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bb7addf71583a45e10cb00446b1b5ae113b179b6ace6a7eefa8b098cb9acc3d4 -size 308857 +oid sha256:9761cedd6ab54f927eede27d31edd5213e2e758bd43308f68befabd8c90a921f +size 301743 diff --git a/data/graph/edges/part-000040.parquet b/data/graph/edges/part-000040.parquet index 1d3f7391248d2b576f6aed74dd5f2d540b9fa76e..3eed6c54ecee498a46cd81f47f2aaada308b11e8 100644 --- a/data/graph/edges/part-000040.parquet +++ b/data/graph/edges/part-000040.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6f15563f2b41b8c86c37d4859a4123bcd7487b0c4f461427ad52788d55d2345a -size 297747 +oid sha256:1f17d69feebb487a868a6ae7d36e2e25956e99ec45f79cab9bf2d7abcd94de9d +size 301790 diff --git a/data/graph/edges/part-000041.parquet b/data/graph/edges/part-000041.parquet index 2d69fad582031818ad9822beb34ee5b8b2deec58..3b8bd2d733ce664e7cfc60d3c4993b6ec037f0cf 100644 --- a/data/graph/edges/part-000041.parquet +++ b/data/graph/edges/part-000041.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6f8051b7ed2adc0324e6298935c59f6e68bafb22d10d6964819ae6b6f10c292f -size 301421 +oid sha256:50f6591e0072aed1e8faadbd3eb8aa1ebcb3ec2ceffc40d15578fd0c81a28148 +size 301019 diff --git a/data/graph/edges/part-000042.parquet b/data/graph/edges/part-000042.parquet index e90b3b8ac557d19dbd5cb7b86f1cc10b96358324..d62a76310fcd3c5c1eea2d9b62ecae1046ae3013 100644 --- a/data/graph/edges/part-000042.parquet +++ b/data/graph/edges/part-000042.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f50a4f62d8d8c0c0c9613595d5f6a421620cb57ea86b5ee8f0561cd3787030ad -size 304555 +oid sha256:6973136b1b3b5c1e3ceb1f84680b272da9cdbc416350e83c1029033545c51b10 +size 301977 diff --git a/data/graph/edges/part-000043.parquet b/data/graph/edges/part-000043.parquet index fd3d649e5a42c123a7f5f9e4ebe8c02fafecb87d..6d60635038a6c6efd5cf3a9c425451ae43936146 100644 --- a/data/graph/edges/part-000043.parquet +++ b/data/graph/edges/part-000043.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1e30cfb976406d2b9a6f174c8312951f1a70b89fedb0b0f99485f5a69af974a8 -size 305269 +oid sha256:d737f71697377e21b84f7f9099969b36c95518333f011708e787cf129b663231 +size 300790 diff --git a/data/graph/edges/part-000044.parquet b/data/graph/edges/part-000044.parquet index 278a131d59e2946919a7069494451b67cd9a11cc..dc72cbaeb16f28c0b3a0ac6270f67beef952a45f 100644 --- a/data/graph/edges/part-000044.parquet +++ b/data/graph/edges/part-000044.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e78e05726e836adc841b92f5e7c2a20b1dbf0b87a3e4c2448ca5416f93f61e64 -size 308688 +oid sha256:7de2f644088a0ded767535f8f89bbd1e8e423f8609b9ae294195f1df3b6ad126 +size 301032 diff --git a/data/graph/edges/part-000045.parquet b/data/graph/edges/part-000045.parquet index 112101094331e0b94041d950fbf232f437ef2114..7ead84fd58c750bc372d0c818d07bd9623fa11c1 100644 --- a/data/graph/edges/part-000045.parquet +++ b/data/graph/edges/part-000045.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2de170d242d48470bd3602efe5a9c60f28a9b8532f8c5318629c1e8b089cf589 -size 313877 +oid sha256:d3f21262c0990e005eba6ebb94c0b76ed0545fd4cf85a3f943249f2c88316d1e +size 302148 diff --git a/data/graph/edges/part-000046.parquet b/data/graph/edges/part-000046.parquet index 9bbfcd7210216464b49470a967700ca51c84f92d..c3a92517d91f80b297d1881dda71087caeea3abc 100644 --- a/data/graph/edges/part-000046.parquet +++ b/data/graph/edges/part-000046.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f857ce954ada73a646180c88808d0838ad6f8383082ed2a900c9911c4c0ebe96 -size 294019 +oid sha256:2075dd05818b952313d8783167d1792db0aa2d0cf17b76ee103a44afac4f9db9 +size 302289 diff --git a/data/graph/edges/part-000047.parquet b/data/graph/edges/part-000047.parquet index 1a9aea7569c7dacc3a70ea5bc054bf7136176512..e6d1707b489ef2b9d9ae20bfef3b9e7d52359016 100644 --- a/data/graph/edges/part-000047.parquet +++ b/data/graph/edges/part-000047.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:05724b09a4f47387e8066332a0dd2645583feb7317ca385d62524adbe1c9bce4 -size 305551 +oid sha256:47c071ddfbd2dd6e0970c3d60f3b83d7392502706b454dd75c1ab6e5a431ed11 +size 300260 diff --git a/data/graph/edges/part-000048.parquet b/data/graph/edges/part-000048.parquet index 63b03faceb2c877a51981013cb86fcdc7fe62578..dc6d172f30f43ef3f8248b61fb84cc2f6ceeb414 100644 --- a/data/graph/edges/part-000048.parquet +++ b/data/graph/edges/part-000048.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:94bcca80f53bc4d9d508df4471a276fb21ce3cf6f04947c84fadbb6c9152d2a6 -size 294630 +oid sha256:eb81212f70a6981116626a866fc194f31c1bfc9cb79fc8c01c0e8ba0441cc85a +size 301238 diff --git a/data/graph/edges/part-000049.parquet b/data/graph/edges/part-000049.parquet index b06f7f8ec8cf5e3e16cac12e2ff931dfe81ffef2..3277b0eb058e66189d0d0e6f550a6c4dc3f112c9 100644 --- a/data/graph/edges/part-000049.parquet +++ b/data/graph/edges/part-000049.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c0b0058e92a358c1a9b3ca5d07e13e08ae41e55fbc62448e4bb2522c35d1f7c4 -size 300246 +oid sha256:e79a491bc96acf97e4f0b00af7aa17bbe99a920143eb767cacff195becf8a5ca +size 301573 diff --git a/data/graph/edges/part-000050.parquet b/data/graph/edges/part-000050.parquet index 1c832f62e6280e4b4439846d1134c48dfb637f7d..9643efac7c54095177b5a94a8628a4538e1d635c 100644 --- a/data/graph/edges/part-000050.parquet +++ b/data/graph/edges/part-000050.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c438b6b7154039f851cb232c8cfcb1736b5d16e622d0fd8813c7a7d103059734 -size 301378 +oid sha256:885d3e2190b82f2c336d7b70803951558f711e14b78b81edb2b742328e9465b3 +size 302489 diff --git a/data/graph/edges/part-000051.parquet b/data/graph/edges/part-000051.parquet index e215da87d73a490fd967e427c1e6a050646090ed..df30ba4e07ec4f78287f41c7b021861c07cf0618 100644 --- a/data/graph/edges/part-000051.parquet +++ b/data/graph/edges/part-000051.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:65209f4d4a3ac8cfb0b7c0dcd8a9b70f32204c0e5b3db81621c3ce09d16e8e52 -size 304322 +oid sha256:72b6448e74408ff8122332b46779f0b82b84bf3b2e57e43e478a152a2751f8bb +size 301306 diff --git a/data/graph/edges/part-000052.parquet b/data/graph/edges/part-000052.parquet index ba55e7ca1bbe3e9cde6e17892b2ec24c2ff8ea30..3e9413b9748368ad88b6a9f1905fb8db7a9d6cf6 100644 --- a/data/graph/edges/part-000052.parquet +++ b/data/graph/edges/part-000052.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f91719993cb6ceb78915570f449b91fae52b4997931d3cf6ba0ed467b982217c -size 288645 +oid sha256:8eded06ccc3de432fa5a299c645ae3130981ad33772ca9a862cfa76d1f8bd6be +size 300447 diff --git a/data/graph/edges/part-000053.parquet b/data/graph/edges/part-000053.parquet index 0714e346e1c9b272ca292eb86d42fa2906a624ba..800a16d33f72f0eef9389eb852b18e7e54ab4a0c 100644 --- a/data/graph/edges/part-000053.parquet +++ b/data/graph/edges/part-000053.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:883ceab6716ebecf9cbdcc948e94f0a6dd392ae5cfb88578aa7ad8db035c1f7f -size 49035 +oid sha256:62f3be4395144204b3a72edba59c16f04a95fa74e4145601b732dff7e2ad00b0 +size 301226 diff --git a/data/graph/edges/part-000054.parquet b/data/graph/edges/part-000054.parquet new file mode 100644 index 0000000000000000000000000000000000000000..01d5a3bc13819e129554b4d1b564c022335b0762 --- /dev/null +++ b/data/graph/edges/part-000054.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39e760ce10a6bf10daf90544f42d0c12d940f4a1351567a35ffd774454df0a21 +size 302535 diff --git a/data/graph/edges/part-000055.parquet b/data/graph/edges/part-000055.parquet new file mode 100644 index 0000000000000000000000000000000000000000..e5fc42c86fc729332b219a52e2e1f8ac26776528 --- /dev/null +++ b/data/graph/edges/part-000055.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:deca52e2ef56a90858e8bfc7dd522657dd478e16d57a9fbe16ff0eb93c60d171 +size 300490 diff --git a/data/graph/edges/part-000056.parquet b/data/graph/edges/part-000056.parquet new file mode 100644 index 0000000000000000000000000000000000000000..fc876821adc8fd1ce5a12c1c1ce9ad053b212654 --- /dev/null +++ b/data/graph/edges/part-000056.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebadeffe5c12271c45f1718553d959363170dd1d83493ef672d6e2c8645e3d70 +size 301184 diff --git a/data/graph/edges/part-000057.parquet b/data/graph/edges/part-000057.parquet new file mode 100644 index 0000000000000000000000000000000000000000..144018f774ffb1034fcbde10fbd013bcd14c64b8 --- /dev/null +++ b/data/graph/edges/part-000057.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4af8e8bf830657f688c85815db04895f800e75a285564a9db3a9fbcaa0835f7 +size 301697 diff --git a/data/graph/edges/part-000058.parquet b/data/graph/edges/part-000058.parquet new file mode 100644 index 0000000000000000000000000000000000000000..150ab8d600aa151da08d89f1705bed63dce62800 --- /dev/null +++ b/data/graph/edges/part-000058.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5898b54e634b350c068666de16f2ea21c4a464cff0fed0074da9efa382bff1cb +size 301117 diff --git a/data/graph/edges/part-000059.parquet b/data/graph/edges/part-000059.parquet new file mode 100644 index 0000000000000000000000000000000000000000..02a65aef875b152e74a3c12311191dbc8608e4f7 --- /dev/null +++ b/data/graph/edges/part-000059.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:394ef7fdcb6726c732e57188f90a3e04efba9725cb22a83021f172d7affea5ad +size 47627 diff --git a/data/graph/nodes/part-000000.parquet b/data/graph/nodes/part-000000.parquet index b0d10190f439a12bc0395f0745aba94795507cc6..4c1e178e896afeaf5274d6f3a68e520061301fc5 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:7f44bd04889dbba5c83630828309517563d95c40c8fb0bb1ac833ba726e8eb4c -size 602387 +oid sha256:61a0d1c5e011a33ce5f2db8681bfb8ff7c23bd31015e7226c5d3062ba27d8c55 +size 378221 diff --git a/data/graph/nodes/part-000001.parquet b/data/graph/nodes/part-000001.parquet index f12cb58992b5a1d53bde4344ba5f17a6acf20c28..096a1c321f14d22a4406008a62c40510134d04d1 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:86713a6583d4bc3a3779ff06d4be955658a26b4b6d03db99206438869ac776be -size 598988 +oid sha256:306bc61e4bd4a394b227adc736ccb52d3990aeeec00c6d5e462a850fb7c819d6 +size 376303 diff --git a/data/graph/nodes/part-000002.parquet b/data/graph/nodes/part-000002.parquet index 5a6c6bad8114bcc3dcd678710e400f5ee8050fa0..99b95720fa44e560c731f3fe10446474f977ab72 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:146ceddf500c7ffadefba5ebd6c7a89bce8cec308e03c14c664cad89a25816ee -size 598560 +oid sha256:405f214f9becb425fe85dd7ccd867d1383461cd38d22a239e4974e7c1488d3a3 +size 377752 diff --git a/data/graph/nodes/part-000003.parquet b/data/graph/nodes/part-000003.parquet index 7d58fcad428ab894a3dba25ab35820ae689a1b6f..4163c6e350410461bad48778b3fcc62640412b9d 100644 --- a/data/graph/nodes/part-000003.parquet +++ b/data/graph/nodes/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5beeaf36b4cae8421b51644de6871c7bf1510b9403af3d1d63e665143c179218 -size 394189 +oid sha256:70f0f923e98a8a97efb6b44c6370d1c561001ff292243ccd5a766496b51d0929 +size 376797 diff --git a/data/graph/nodes/part-000004.parquet b/data/graph/nodes/part-000004.parquet new file mode 100644 index 0000000000000000000000000000000000000000..75c24e8c8c4c34e5deca538c76f232b31f780818 --- /dev/null +++ b/data/graph/nodes/part-000004.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:473df51e118972d856ae1a7dee150a5d73992a4256e2a21282a5cdd29ba90322 +size 375904 diff --git a/data/graph/nodes/part-000005.parquet b/data/graph/nodes/part-000005.parquet new file mode 100644 index 0000000000000000000000000000000000000000..0225e42d3c1e8851a18193efbced5916b2073b26 --- /dev/null +++ b/data/graph/nodes/part-000005.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d0b9da5754c6b7820b8a805cb8fdd92201c047b7bdfcde795ff4f59359532cf +size 376367 diff --git a/data/graph/nodes/part-000006.parquet b/data/graph/nodes/part-000006.parquet new file mode 100644 index 0000000000000000000000000000000000000000..dc1a857003a9cc0283fc7bd5808aaa1dcb3f2c9e --- /dev/null +++ b/data/graph/nodes/part-000006.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7573805f514b8db3a64101c61cdb135ca4159b46f8a328541790ac03c85f8d66 +size 377495 diff --git a/data/graph/nodes/part-000007.parquet b/data/graph/nodes/part-000007.parquet new file mode 100644 index 0000000000000000000000000000000000000000..07cdc41eaa7990849a54d250bc51294586b4ee02 --- /dev/null +++ b/data/graph/nodes/part-000007.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01d3cfd58eabb844b7fac7f5bf8dc27ed392991203e90718472657ac40373cdc +size 377556 diff --git a/data/graph/nodes/part-000008.parquet b/data/graph/nodes/part-000008.parquet new file mode 100644 index 0000000000000000000000000000000000000000..cc39db9fc8a11eb295a9bb35a95606fd8cfa5953 --- /dev/null +++ b/data/graph/nodes/part-000008.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44a4d31069b65cff1417ff44689b8142131deca776842b72f1295d26768579a9 +size 254484 diff --git a/data/vectors/part-000000.parquet b/data/vectors/part-000000.parquet index e49ff10e61152047bbb985e1845923e0993a1582..b85261913a865ffbc645641bc18178b829ca2e53 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:a850fb6c79fe8f69bdbb75a3abb3971d11d9c4aaea83e5f7e5eeee5e71e0534b -size 4612109 +oid sha256:d309d8bc955ac8b3b66dd99824d07a9e375282bb1b6d92c42c62c8abd86827bc +size 5426415 diff --git a/data/vectors/part-000001.parquet b/data/vectors/part-000001.parquet index 334449038bbdd403f52beaaeddbd3f062accb146..616e31b300010117bade5839d792dcfeefffec7a 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:2c00da3b43b6030097e2968ed957e57b6bd864a1f6319d73f0320aabb0c55fce -size 7021425 +oid sha256:6a8835c4ad85143cab162b61c8b76c70ecbc6f0836d155472ea35f1d8f1102f4 +size 647832 diff --git a/data/vectors/part-000002.parquet b/data/vectors/part-000002.parquet index 4a1e48fcb775c12d4c24cf27defc5c7d95908b81..4a6378f5de77cbceac7c17096ce3b118c78f09a3 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:1b19b740b56fb2b3cab6404f148c19c9dadbe5cd2df11c128686605cf3d6e9a1 -size 6725778 +oid sha256:c97758a94e7b0bec9d3e8ad2a28e8dc331d3681bc31d10750f32f89ac68201e9 +size 289119 diff --git a/data/vectors/part-000003.parquet b/data/vectors/part-000003.parquet index 6e3e47640149e4be01db7d68822b5dff4927003c..34e251faffa6f158f6da5dfc057ea5582acec518 100644 --- a/data/vectors/part-000003.parquet +++ b/data/vectors/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c78c54a40a8a1da75c76297621c6fd5a5f4e0091330bdbd3fa04a5e56b0e76db -size 4168891 +oid sha256:cbb2fad529baea8a56c15f8829d4a5625650648e91cffcf3e00cf6723e0247a2 +size 287814 diff --git a/data/vectors/part-000004.parquet b/data/vectors/part-000004.parquet new file mode 100644 index 0000000000000000000000000000000000000000..4ca399f2eff75f5b0dba572da021f2eb1eadfa9a --- /dev/null +++ b/data/vectors/part-000004.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85a0689df13cf4868bde3413267797aa36aee2ef50c8ed56cb6c3ed9a4dc1a5b +size 3736451 diff --git a/data/vectors/part-000005.parquet b/data/vectors/part-000005.parquet new file mode 100644 index 0000000000000000000000000000000000000000..461b32bf398e243a01c946bb11967261f87f0c52 --- /dev/null +++ b/data/vectors/part-000005.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16b8391574c122dae9dfb1fec0eeafba237d5d73919578957b92fd5e0c23b8f3 +size 1726013 diff --git a/data/vectors/part-000006.parquet b/data/vectors/part-000006.parquet new file mode 100644 index 0000000000000000000000000000000000000000..fa848b9c9cc1b1f06f7dcfb7e96f6c047b3855b7 --- /dev/null +++ b/data/vectors/part-000006.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad19d05b78e895453bbc43a522016ac05ade64edcc5c69555cb0658a5a0343ac +size 1201731 diff --git a/data/vectors/part-000007.parquet b/data/vectors/part-000007.parquet new file mode 100644 index 0000000000000000000000000000000000000000..e01e1baf502567732ef3d77b546d33fdd449d6cf --- /dev/null +++ b/data/vectors/part-000007.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1304edb653890b99eec09cf48dcfbfc911668ac0795eed377652c51cc1570258 +size 833030 diff --git a/data/vectors/part-000008.parquet b/data/vectors/part-000008.parquet new file mode 100644 index 0000000000000000000000000000000000000000..01767c4cceb11fbc63474fc60513b2de6fc795b9 --- /dev/null +++ b/data/vectors/part-000008.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:133d120a7d74812b900b1e4aec6f17d765c522765ae12771e32412a802b0dc99 +size 113528 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 093137aa1470ea5f991055097792f913320b2e9a..b65c7b16f4e73ab2be93f42e3d20cfd3de9a61bb 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:23ba0bb9b2299ef7042efd1133edd3d9630982f8da4216c657caba496925f2c8 -size 9359 +oid sha256:dd5a1d1e5965c153f70c97f985d37e9d7660366e1c07c903b139dbb25b149674 +size 5921 diff --git a/indexes/bm25_keyword_shards.parquet b/indexes/bm25_keyword_shards.parquet index 9ab58cd4d049f370aaec9d95ff17e34d8fbdffd0..b36650969453b8a35ca2940285f16c7880014746 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:caefe805a01e279fbff7e476df5dac914983f9da591d82b8a9fef31f91b64ba1 -size 10900 +oid sha256:84f07d52e0d3eca10920b19d96f4a2acc7a93360743c3e9d2488084440a08b9f +size 10190 diff --git a/indexes/corpus_chunks.parquet b/indexes/corpus_chunks.parquet index fbdecd1c2d4f7cd660bfd54401db9bc96f481040..fd03b8e7872e3ea701fbbd079d6083947c53a2ea 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:510901750606c7f9a56ff0dfcda21e17cccb3cbe9358fc5593ec931e7e3beed2 -size 9280 +oid sha256:ad4f89691a06621466f74d6746188205c3e88d7a44d3ada1a76e0d58b868c536 +size 9973 diff --git a/indexes/graph_edge_chunks.parquet b/indexes/graph_edge_chunks.parquet index d5c6ebf40077570a8beba578ea7f3c198d860eba..f417b3387d6b49d2ca59ca8a30781f006bcda297 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:4592ab4bcd44fe273204b7594839a8b09f5ed0d118f789c98d7925ee9b0bf076 -size 15344 +oid sha256:48aed6fac12fafa017d13d93b9d8a7e95b15f9a4f6a75533d272fd8c8e394a6a +size 15534 diff --git a/indexes/graph_in_adjacency.parquet b/indexes/graph_in_adjacency.parquet new file mode 100644 index 0000000000000000000000000000000000000000..3082beec2d125d7fe91970f20d97dbdb6c81e676 --- /dev/null +++ b/indexes/graph_in_adjacency.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d65880423af0c318a58b12e3fd1bdd22922fae1526804817d483e7a594b5d41 +size 11404 diff --git a/indexes/graph_node_chunks.parquet b/indexes/graph_node_chunks.parquet index 3f70e7d01ffaa422648ec9819dec1015c8932228..d80e570a8e5b7e679676b2e227ea34c5b6f81861 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:c4f60670406ede8607142c2d2beb754d583a3f348a9b524d231b446770b0b506 -size 9305 +oid sha256:e266cf0dca96a221a515b6f8a5cd36eb90efb5185219b69fdd897b623f7587ee +size 6366 diff --git a/indexes/graph_out_adjacency.parquet b/indexes/graph_out_adjacency.parquet new file mode 100644 index 0000000000000000000000000000000000000000..89489bb61e587056662b2776ca90c0b5dc9fc567 --- /dev/null +++ b/indexes/graph_out_adjacency.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72216264f3e7c04c6dad19dbd0c6f43f51969ed20b3b82e27325e50c6b9ed0ef +size 11705 diff --git a/indexes/vector_chunks.parquet b/indexes/vector_chunks.parquet index 6d58df98f4132fe6f114c3a1e60e0dbd054d754e..079a1709bce61ed1eef1664a2fe93445144657ca 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:7024a3111552d6d62abd1af5ca4befec3c169dede8e4956d070233e5adb3ea97 -size 30608 +oid sha256:05a11e0d173034b493be39714248ad9dfea89d7b3e68846adcf5ec05affa4a4e +size 42111 diff --git a/manifest.json b/manifest.json index 060a9d4a0c822a362edd6bccb1a7f5f6083fc03d..9ad7effda23466ee1b59d630d8931a8b06d8ef5d 100644 --- a/manifest.json +++ b/manifest.json @@ -1,24 +1,295 @@ { "schema_version": "country-laws-ir-graphrag/v1", - "dataset_revision": "a796be6509ee8207d87b7bd35923640875f5a5e9", + "layout_family": "skillcenter-huggingface-release/v3", + "packager_version": "0.5.0", + "primary_key": "entry_cid", + "dataset_id": "endomorphosis/ipfs_nicaragua_laws", + "dataset_repo_id": "justicedao/ipfs_nicaragua_laws_ir", + "dataset_revision": "59efc0b35ac8296762d3626ac0ea8fef7c7f19a7", "country": { "slug": "nicaragua", "repo": "endomorphosis/ipfs_nicaragua_laws", "name": "Nicaragua", "indexable": true, - "skip_reason": null, - "local_source_dir": "/workspace/country-laws-ir/cache/nicaragua_filtered_a796be6509ee", - "source_revision": "a796be6509ee8207d87b7bd35923640875f5a5e9" + "skip_reason": null + }, + "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": 241.97639001271529, + "tokenizer": "hf-graphrag-bm25-tokens/v1", + "max_query_terms": 64, + "posting_rows_per_record": 4096, + "terms_per_shard": 4096 + }, + "counts": { + "bm25_document_chunks": 9, + "bm25_documents": 34604, + "bm25_keyword_shards": 55, + "bm25_posting_rows": 221279, + "bm25_postings": 2980657, + "bm25_terms": 221138, + "corpus_chunks": 9, + "corpus_rows": 34604, + "graph_edge_chunks": 0, + "graph_edges": 242228, + "graph_incoming_adjacency_edges": 0, + "graph_incoming_adjacency_rows": 0, + "graph_incoming_adjacency_shards": 0, + "graph_node_chunks": 0, + "graph_nodes": 35514, + "graph_outgoing_adjacency_edges": 0, + "graph_outgoing_adjacency_rows": 0, + "graph_outgoing_adjacency_shards": 0, + "vector_chunks": 9, + "vector_rows": 34604, + "n_laws": 0, + "n_articles": 34604, + "bm25_token_instances": 8373351 + }, + "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": 47, + "shard_count": 47, + "n_vectors": 34604, + "status": "partial", + "n_reused": 7942, + "n_missing": 26662 + }, + "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": "d4cc0cdd38018549134920af839de3f9c978f5b7449c46b44eac3a80a7ef8053", + "articles.parquet": "fa5dd8f8e21563ed9ec21494ec0ff130bc5b0d94d850c5fe298636d23325ea3d" + }, + "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_nicaragua_laws", + "source_revision": "59efc0b35ac8296762d3626ac0ea8fef7c7f19a7", + "laws_sha256": "d4cc0cdd38018549134920af839de3f9c978f5b7449c46b44eac3a80a7ef8053", + "articles_sha256": "fa5dd8f8e21563ed9ec21494ec0ff130bc5b0d94d850c5fe298636d23325ea3d", + "n_laws_in": 353, + "n_articles_in": 34727, + "unit": "article", + "article_law_coverage": 98.37677053824362, + "sparse_article_fallback": false, + "drops": { + "empty_body": 0, + "missing_instrument": 0, + "duplicate_cid": 123, + "duplicate_source_kept_first": 123 + }, + "drop_samples": { + "empty_body": [], + "missing_instrument": [], + "duplicate_cid": [ + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-43", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-48", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-50", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-52", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-54", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-55", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-56", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-57", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-43", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-48", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-50", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-52", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-54", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-55", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-56", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-57", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-i", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-i", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-iii", + "ni-dictamen_ley_especial_para_la_atencion_a_los_excomb.-_15-10-2012-capitulo-i" + ] + }, + "language_breakdown": { + "es": 34604 + }, + "quality_flags": { + "articles_table_empty": false, + "sparse_article_fallback": false, + "article_law_coverage": 98.37677053824362, + "all_source_article_counts_zero": false, + "article_extraction_status_counts": { + "missing": 51, + "ok": 302 + }, + "missing_date": true, + "missing_date_issued": true, + "eli_present": false, + "never_invented_legal_text": true, + "empty_bodies_dropped": 0, + "duplicate_cids_dropped": 123 + }, + "schema_surprises": [ + "laws.article_count dtype=int32", + "laws.date is entirely null", + "laws.date_issued is entirely null", + "laws.eli non-null=0/353", + "laws.language values=['es']" + ], + "n_out": 34604, + "never_invented_legal_text": true, + "n_before_dedupe": 34727, + "n_dropped_total": 123, + "record_type_breakdown": { + "article": 34604 + }, + "jurisdiction_breakdown": { + "NI": 34604 + }, + "snapshot_dates": [ + "2026-09-10", + "2026-09-15", + "2026-09-16" + ] + }, + "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": "bafkreig5lior4wlfyfj7odex7gc5g7u5ozqdm3q4a7eqhmjz3ozfwfewoq", + "sha256": "dd5a1d1e5965c153f70c97f985d37e9d7660366e1c07c903b139dbb25b149674", + "size_bytes": 5921, + "relative_path": "indexes/bm25_document_chunks.parquet" + }, + "bm25_keyword_shards": { + "cid": "bafkreiee6b6vfygt5sqqsifrtwlpjivmy6utgyduhq7j2jeibbcebielt4", + "sha256": "84f07d52e0d3eca10920b19d96f4a2acc7a93360743c3e9d2488084440a08b9f", + "size_bytes": 10190, + "relative_path": "indexes/bm25_keyword_shards.parquet" + }, + "corpus_chunks": { + "cid": "bafkreifnj6ewsgqgmikgn52nm5dbraqfypui26se2ow2dj3obvmlq2gfgy", + "sha256": "ad4f89691a06621466f74d6746188205c3e88d7a44d3ada1a76e0d58b868c536", + "size_bytes": 9973, + "relative_path": "indexes/corpus_chunks.parquet" + }, + "graph_edge_chunks": { + "cid": "bafkreiciv3lpvqjpv6qbpuj5so45rj7jlmk7tjhwu5kthuts7wgi4okkni", + "sha256": "48aed6fac12fafa017d13d93b9d8a7e95b15f9a4f6a75533d272fd8c8e394a6a", + "size_bytes": 15534, + "relative_path": "indexes/graph_edge_chunks.parquet" + }, + "graph_incoming_adjacency": { + "relative_path": "indexes/graph_incoming_adjacency.parquet", + "present": false + }, + "graph_node_chunks": { + "cid": "bafkreihcm3hq3suwuiq2kfnw7cs42nxlsdx3kgcsdg3j7xmjpnrd65mh5y", + "sha256": "e266cf0dca96a221a515b6f8a5cd36eb90efb5185219b69fdd897b623f7587ee", + "size_bytes": 6366, + "relative_path": "indexes/graph_node_chunks.parquet" + }, + "graph_outgoing_adjacency": { + "relative_path": "indexes/graph_outgoing_adjacency.parquet", + "present": false + }, + "vector_chunks": { + "cid": "bafkreiafuepa2fzqgs2jhprzofberlm572uj26z6nccgvxhv5qc276skjy", + "sha256": "05a11e0d173034b493be39714248ad9dfea89d7b3e68846adcf5ec05affa4a4e", + "size_bytes": 42111, + "relative_path": "indexes/vector_chunks.parquet" + } }, "source": { "source_dataset": "endomorphosis/ipfs_nicaragua_laws", - "source_revision": "a796be6509ee8207d87b7bd35923640875f5a5e9", - "laws_path": "/workspace/country-laws-ir/cache/nicaragua_filtered_a796be6509ee/data/laws.parquet", - "articles_path": "/workspace/country-laws-ir/cache/nicaragua_filtered_a796be6509ee/data/articles.parquet", - "laws_sha256": null, - "articles_sha256": null, - "n_laws_source": 278, - "n_articles_source": 14597, + "source_revision": "59efc0b35ac8296762d3626ac0ea8fef7c7f19a7", + "laws_path": "/home/barberb/.ipfs_datasets/country-laws-ir/cache/hf/datasets--endomorphosis--ipfs_nicaragua_laws/snapshots/59efc0b35ac8296762d3626ac0ea8fef7c7f19a7/data/laws.parquet", + "articles_path": "/home/barberb/.ipfs_datasets/country-laws-ir/cache/hf/datasets--endomorphosis--ipfs_nicaragua_laws/snapshots/59efc0b35ac8296762d3626ac0ea8fef7c7f19a7/data/articles.parquet", + "laws_sha256": "d4cc0cdd38018549134920af839de3f9c978f5b7449c46b44eac3a80a7ef8053", + "articles_sha256": "fa5dd8f8e21563ed9ec21494ec0ff130bc5b0d94d850c5fe298636d23325ea3d", + "n_laws_source": 353, + "n_articles_source": 34727, "laws_columns": [ "id", "title", @@ -51,103 +322,123 @@ "record_type", "metadata_json" ], - "local_source_dir": "/workspace/country-laws-ir/cache/nicaragua_filtered_a796be6509ee", - "pack_meta": { - "slug": "nicaragua", - "name": "Nicaragua", - "repo": "endomorphosis/ipfs_nicaragua_laws", - "source_dataset": "endomorphosis/ipfs_nicaragua_laws", - "source_revision": "a796be6509ee8207d87b7bd35923640875f5a5e9", - "filtered": true, - "filter_reason": "memsafe pass-through (chrome skipped; floor==hub; soft never-thin)", - "indexable": true, - "skip_reason": null, - "n_laws": 278, - "n_articles": 14597 - } - }, - "counts": { - "corpus_rows": 14597, - "laws": 0, - "articles": 14597, - "bm25_documents": 14597, - "bm25_posting_rows": 112561, - "graph_nodes": 15141, - "graph_edges": 217613, - "vector_rows": 14597, - "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": 319.47105569637597, - "tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1", - "max_query_terms": 64, - "posting_rows_per_record": 4096, - "terms_per_shard": 4096, - "n_docs": 14597, - "n_terms": 112520, - "n_posting_rows": 112561, - "n_postings": 1513726 - }, - "graph": { - "n_nodes": 15141, - "n_edges": 217613, - "n_doc_nodes": 14777, - "n_facet_nodes": 364, - "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" + "article_count_dtype": "int32", + "schema_surprises": [ + "laws.article_count dtype=int32", + "laws.date is entirely null", + "laws.date_issued is entirely null", + "laws.eli non-null=0/353", + "laws.language values=['es']" + ] }, - "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": 14597, - "centroid_count": 4, - "shard_count": 4, - "status": "embedded", - "via": "layout_vectors_memsafe_sequential" - }, - "normalization": { - "source_dataset": "endomorphosis/ipfs_nicaragua_laws", - "source_revision": "a796be6509ee8207d87b7bd35923640875f5a5e9", - "n_laws_in": 278, - "n_articles_in": 14597, - "unit": "article", - "drops": { - "empty_body": 0, - "missing_instrument": 0, - "duplicate_cid": 11 + "incremental": { + "kind": "delta_refresh", + "mode": "auto", + "reason": "source changed; reuse embeddings for unchanged entry_cids", + "source_revision": "59efc0b35ac8296762d3626ac0ea8fef7c7f19a7", + "prior_revision": "a796be6509ee8207d87b7bd35923640875f5a5e9", + "source_fingerprint": "59efc0b35ac8296762d3626ac0ea8fef7c7f19a7|d4cc0cdd38018549134920af839de3f9c978f5b7449c46b44eac3a80a7ef8053|fa5dd8f8e21563ed9ec21494ec0ff130bc5b0d94d850c5fe298636d23325ea3d", + "prior_fingerprint": "a796be6509ee8207d87b7bd35923640875f5a5e9||", + "delta": { + "n_added": 26662, + "n_removed": 6655, + "n_unchanged": 7942, + "prior_count": 14597, + "current_count": 34604, + "changed_ratio": 0.7704889608137788, + "equivalent_to_full": false, + "added_cids_sample": [ + "bafkreia22c5qy7el5a27qmms7lxa3bbtaxns3tn47h4i2oavu5zthdjqzq", + "bafkreia22ypdyqssc35fjsktci4bo7terexnyz6mxfijguhy4emn2vosdy", + "bafkreia236fnsgsjrkuslwo7jklpsrm5e2p7pg3qzs4le6b33q6uye65wi", + "bafkreia242gy7qqfp3zxbyk67gawqr3pkl5m4u44z6my2hccrfckz5ilre", + "bafkreia24aqlra6htd3f2aflhqa5srzgtz4d2l5ov2wug436rrtwdyj3ca", + "bafkreia24ed4xyosbvslcbf76wm53fbflx43ymccmx5ptoc6kuqo2r3fby", + "bafkreia24ezlltpqyikqd3wothjwgq2zuteagi34vsxuehxzcuzrcfjeju", + "bafkreia24g7gzecvty4obsm32uokbm5ft75iidkqdf4wbblmlpp3e2tooq" + ], + "removed_cids_sample": [ + "bafkreia23ermc4bmiqqvghtg2nsctscrfxlwjthpiqi5gudpvxnsqxz3ky", + "bafkreia23esasrwxbnyhtg6jg3qvmloadz4jzs4uqodktjpqq75mpetdce", + "bafkreia242uzwl3q2mm7i3pujeaqy7ajnrmo6vltv2sra72jemf5kesisu", + "bafkreia2bln7av5idgtwuq63yonzjybb3lfqva7aq6ouqkogetwytlcczy", + "bafkreia2bmxtmodorjcynwealwxzmezecxeputa7k5aazonhhympf3xkam", + "bafkreia2btew5yaydmrxpjxpwhrf5jggqoeehxyxcnmt7ndvfu4j5eizfi", + "bafkreia2cinkeofvwkq3diad3claylgqwswk2hdpsckvkcipg6k4skh27u", + "bafkreia2dmuf2ylny6tgl5aebhozgzbccpmspzpd4nec3z6hx342phozcm" + ] }, - "n_out": 14597, - "n_dropped_total": 11, - "via": "nicaragua_corpus_stream", - "record_type_breakdown": { - "article": 14597 + "reuse_embeddings": true, + "skip_build": false, + "equivalent_to_full": false, + "schema_version": "country-laws-ir-graphrag/v1", + "vectors": { + "n_docs": 34604, + "n_reused": 7942, + "n_encoded": 0, + "n_missing": 26662, + "model_name": "thenlper/gte-small", + "model_revision": "17e1f347d17fe144873b1201da91788898c639cd", + "dimension": 384, + "status": "stub_missing_encoder", + "device": "cuda", + "device_fallback": false, + "reason": "sentence-transformers/transformers lazy install failed" + } + }, + "sparse": { + "engine": "hf_graphrag", + "schema_version": "country-laws-ir-graphrag/v1", + "bm25": { + "bm25": { + "average_document_length": 241.97639001271529, + "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": 9, + "bm25_documents": 34604, + "bm25_keyword_shards": 55, + "bm25_posting_rows": 221279, + "bm25_postings": 2980657, + "bm25_terms": 221138, + "bm25_token_instances": 8373351 + }, + "indexes": { + "bm25_document_chunks": { + "cid": "bafkreig5lior4wlfyfj7odex7gc5g7u5ozqdm3q4a7eqhmjz3ozfwfewoq", + "relative_path": "indexes/bm25_document_chunks.parquet", + "row_count": 9, + "sha256": "dd5a1d1e5965c153f70c97f985d37e9d7660366e1c07c903b139dbb25b149674", + "size_bytes": 5921 + }, + "bm25_keyword_shards": { + "cid": "bafkreiee6b6vfygt5sqqsifrtwlpjivmy6utgyduhq7j2jeibbcebielt4", + "relative_path": "indexes/bm25_keyword_shards.parquet", + "row_count": 55, + "sha256": "84f07d52e0d3eca10920b19d96f4a2acc7a93360743c3e9d2488084440a08b9f", + "size_bytes": 10190 + } + }, + "schema_version": "hf-graphrag-bm25-layout/v1" }, - "language_breakdown": { - "es": 14597 + "graph": { + "node_count": 35514, + "edge_count": 242228, + "adjacency": "data/graph/adjacency/{out,in}/*.parquet" }, - "never_invented_legal_text": true - }, - "neighbor_via": "sqlite_fts", - "built_utc": "2026-09-13T23:33:41.365538+00:00", - "via": "nicaragua_package_stream_graph" + "sqlite": false, + "query_engine": "duckdb" + } } diff --git a/normalization_report.json b/normalization_report.json new file mode 100644 index 0000000000000000000000000000000000000000..b902bfade1a69a4ce97bad4c71fc8f44d954a171 --- /dev/null +++ b/normalization_report.json @@ -0,0 +1,84 @@ +{ + "source_dataset": "endomorphosis/ipfs_nicaragua_laws", + "source_revision": "59efc0b35ac8296762d3626ac0ea8fef7c7f19a7", + "laws_sha256": "d4cc0cdd38018549134920af839de3f9c978f5b7449c46b44eac3a80a7ef8053", + "articles_sha256": "fa5dd8f8e21563ed9ec21494ec0ff130bc5b0d94d850c5fe298636d23325ea3d", + "n_laws_in": 353, + "n_articles_in": 34727, + "unit": "article", + "article_law_coverage": 98.37677053824362, + "sparse_article_fallback": false, + "drops": { + "empty_body": 0, + "missing_instrument": 0, + "duplicate_cid": 123, + "duplicate_source_kept_first": 123 + }, + "drop_samples": { + "empty_body": [], + "missing_instrument": [], + "duplicate_cid": [ + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-43", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-48", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-50", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-52", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-54", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-55", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-56", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-57", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-43", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-48", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-50", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-52", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-54", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-55", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-56", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-57", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-i", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-i", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-iii", + "ni-dictamen_ley_especial_para_la_atencion_a_los_excomb.-_15-10-2012-capitulo-i" + ] + }, + "language_breakdown": { + "es": 34604 + }, + "quality_flags": { + "articles_table_empty": false, + "sparse_article_fallback": false, + "article_law_coverage": 98.37677053824362, + "all_source_article_counts_zero": false, + "article_extraction_status_counts": { + "missing": 51, + "ok": 302 + }, + "missing_date": true, + "missing_date_issued": true, + "eli_present": false, + "never_invented_legal_text": true, + "empty_bodies_dropped": 0, + "duplicate_cids_dropped": 123 + }, + "schema_surprises": [ + "laws.article_count dtype=int32", + "laws.date is entirely null", + "laws.date_issued is entirely null", + "laws.eli non-null=0/353", + "laws.language values=['es']" + ], + "n_out": 34604, + "never_invented_legal_text": true, + "n_before_dedupe": 34727, + "n_dropped_total": 123, + "record_type_breakdown": { + "article": 34604 + }, + "jurisdiction_breakdown": { + "NI": 34604 + }, + "snapshot_dates": [ + "2026-09-10", + "2026-09-15", + "2026-09-16" + ] +} diff --git a/normalize.py b/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..d518f83f1b2fe701b6c1fc5f79335bc6c760a414 --- /dev/null +++ b/normalize.py @@ -0,0 +1,611 @@ +"""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. + +Public Hub reads only (token=False). No Hugging Face token is read or stored. +""" + +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 + +_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 + + +def _s(value: Any) -> str: + return normalize_text(value) + + +def _download(repo_id: str, filename: str, cache_dir: Path) -> Path: + configure_hf() + path = hf_hub_download( + repo_id=repo_id, + filename=filename, + repo_type="dataset", + token=public_token(), + cache_dir=str(cache_dir / "hf"), + ) + 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 /data/.parquet or /.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 + 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) 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) 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), + } + return laws, articles, meta + + +def _schema_surprises(laws: pd.DataFrame, articles: pd.DataFrame) -> list[str]: + notes: list[str] = [] + if articles is None or articles.empty: + notes.append("articles.parquet has 0 rows; corpus falls back to law-level units") + if "article_count" in laws.columns: + dtype = str(laws["article_count"].dtype) + notes.append(f"laws.article_count dtype={dtype}") + try: + if int((laws["article_count"].fillna(0) == 0).sum()) == len(laws): + notes.append("every law has article_count=0") + except Exception: + pass + for col in ("date", "date_issued"): + if col in laws.columns and laws[col].isna().all(): + notes.append(f"laws.{col} is entirely null") + if "eli" in laws.columns: + n_eli = int(laws["eli"].notna().sum()) if hasattr(laws["eli"], "notna") else 0 + notes.append(f"laws.eli non-null={n_eli}/{len(laws)}") + if "language" in laws.columns: + langs = sorted({str(x) for x in laws["language"].dropna().unique()}) + notes.append(f"laws.language values={langs}") + return notes + + +def _parse_meta(raw: str) -> dict[str, Any]: + if not raw: + return {} + try: + obj = json.loads(raw) + return obj if isinstance(obj, dict) else {} + except Exception: + return {} + + +def _law_cid(instrument_id: str, instrument_title: str, jurisdiction: str, language: str, source_dataset: str) -> str: + identity = { + "schema": LAW_IDENTITY_SCHEMA, + "source_dataset": source_dataset, + "instrument_id": instrument_id, + "instrument_title": instrument_title, + "jurisdiction": jurisdiction, + "language": language, + } + return cid_of_json(identity) + + +def _entry_cid(record: dict[str, Any]) -> str: + identity = { + "schema": ENTRY_IDENTITY_SCHEMA, + "record_type": record["record_type"], + "source_dataset": record["source_dataset"], + "instrument_id": record["instrument_id"], + "article_number": record.get("article_number") or "", + "article_title": record.get("article_title") or "", + "body_sha256": record["body_sha256"], + "language": record.get("language") or "", + "jurisdiction": record.get("jurisdiction") or "", + "source_url": record.get("source_url") or "", + } + return cid_of_json(identity) + + +def _row_get(row: pd.Series, col: str, default: str = "") -> str: + if col not in row.index: + return default + return _s(row[col]) + + +def _coverage_from( + row: pd.Series, + meta: dict[str, Any], + articles_empty: bool, + sparse_fallback: bool = False, +) -> str: + for key in ("coverage", "coverage_note"): + if key in meta and meta[key]: + return normalize_text(meta[key]) + status = normalize_text(meta.get("article_extraction_status") or "") + if sparse_fallback: + note = "law-level (article coverage below 10% of laws; sparse articles table)" + if status: + return f"{note}; extraction_status={status}" + return note + if articles_empty: + if status: + return f"law-level (articles empty or unavailable in source snapshot); extraction_status={status}" + return "law-level (articles empty or unavailable in source snapshot)" + if status: + return f"article-level; extraction_status={status}" + return "article-level" + + +def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, Any]) -> str: + for col in ("retrieved_at", "date_issued", "date"): + val = _row_get(row, col) + if val: + return val[:10] if len(val) >= 10 and val[4] == "-" else val + for key in ("snapshot_date", "retrieved_at"): + if key in meta and meta[key]: + return normalize_text(str(meta[key]))[:10] + nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} + for key in ("snapshot_date", "retrieved_at"): + if nested.get(key): + return normalize_text(str(nested[key]))[:10] + return "" + + +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): + for key in ("collector", "collector_id", "harvester"): + if blob.get(key): + return normalize_text(blob[key]) + return f"{COLLECTOR_DEFAULT} ({source_dataset})" + + +def laws_index(laws: pd.DataFrame, source_dataset: str) -> dict[str, dict[str, Any]]: + """Map instrument_id -> law facet fields (always computed; not always corpus units).""" + out: dict[str, dict[str, Any]] = {} + for _, row in laws.iterrows(): + instrument_id = _row_get(row, "id") + instrument_title = _row_get(row, "title") + jurisdiction = _row_get(row, "jurisdiction") or _row_get(row, "country") + language = _row_get(row, "language") + law_cid = _law_cid(instrument_id, instrument_title, jurisdiction, language, source_dataset) + meta = _parse_meta(_row_get(row, "metadata_json")) + out[instrument_id] = { + "instrument_id": instrument_id, + "instrument_title": instrument_title, + "law_cid": law_cid, + "jurisdiction": jurisdiction, + "language": language, + "source_url": _row_get(row, "source_url"), + "license": _row_get(row, "license"), + "eli": _row_get(row, "eli"), + "identifier": _row_get(row, "identifier") or instrument_id, + "official_identifier": _row_get(row, "official_identifier"), + "source_type": _row_get(row, "source_type"), + "country": _row_get(row, "country"), + "law_status": _row_get(row, "law_status"), + "body": _row_get(row, "text"), + "metadata": meta, + "row": row, + } + return out + + +def _base_record( + *, + record_type: str, + source_dataset: str, + source_revision: str, + instrument_id: str, + instrument_title: str, + law_cid: str, + article_number: str, + article_title: str, + body: str, + jurisdiction: str, + language: str, + source_url: str, + snapshot_date: str, + coverage: str, + license_expr: str, + collector: str, + source_id: str, + extra: dict[str, Any] | None = None, +) -> dict[str, Any]: + title_for_bm25 = article_title if record_type == "article" and article_title else instrument_title + rec: dict[str, Any] = { + "record_type": record_type, + "source_dataset": source_dataset, + "source_revision": source_revision, + "source_id": source_id, + "instrument_id": instrument_id, + "instrument_title": instrument_title, + "law_id": instrument_id, + "law_cid": law_cid, + "article_number": article_number, + "article_title": article_title, + "title": title_for_bm25, + "body": body, + "body_sha256": sha256_hex(body.encode("utf-8")), + "jurisdiction": jurisdiction, + "language": language, + "source_url": source_url, + "snapshot_date": snapshot_date, + "coverage": coverage, + "license": license_expr, + "collector": collector, + "schema_version": SCHEMA_VERSION, + "entry_identity_schema_version": ENTRY_IDENTITY_SCHEMA, + } + if extra: + rec.update(extra) + rec["entry_cid"] = _entry_cid(rec) + rec["title_length"] = len(title_for_bm25) + rec["body_length"] = len(body) + rec["document_length"] = len(title_for_bm25) + len(body) + return rec + + +def build_corpus( + laws: pd.DataFrame, + articles: pd.DataFrame, + source_meta: dict[str, Any], +) -> tuple[pd.DataFrame, dict[str, Any]]: + source_dataset = source_meta["source_dataset"] + source_revision = source_meta["source_revision"] + law_map = laws_index(laws, source_dataset) + articles_empty = articles is None or articles.empty + n_laws = int(len(laws)) + n_arts = int(len(articles) if articles is not None else 0) + article_law_coverage = (n_arts / n_laws) if n_laws else 0.0 + # Empty articles.parquet already falls back. Also fall back when the table is + # present but covers under ~10% as many rows as laws (Estonia: 2 vs 3484). + sparse_fallback = (not articles_empty) and article_law_coverage < 0.10 + use_articles = (not articles_empty) and not sparse_fallback + + extraction_statuses: Counter[str] = Counter() + for parent in law_map.values(): + st = normalize_text(parent["metadata"].get("article_extraction_status") or "") + if st: + extraction_statuses[st] += 1 + + report: dict[str, Any] = { + "source_dataset": source_dataset, + "source_revision": source_revision, + "laws_sha256": source_meta.get("laws_sha256"), + "articles_sha256": source_meta.get("articles_sha256"), + "n_laws_in": int(len(laws)), + "n_articles_in": int(len(articles) if articles is not None else 0), + "unit": "article" if use_articles else "law", + "article_law_coverage": article_law_coverage, + "sparse_article_fallback": sparse_fallback, + "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": {}, + "quality_flags": {}, + "schema_surprises": list(source_meta.get("schema_surprises") or []), + "n_out": 0, + "never_invented_legal_text": True, + } + + entries: list[dict[str, Any]] = [] + + if sparse_fallback: + report["schema_surprises"].append( + f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units" + ) + + if use_articles: + for _, row in articles.iterrows(): + source_id = _row_get(row, "id") + instrument_id = _row_get(row, "law_id") + body = _row_get(row, "text") + article_title = _row_get(row, "title") + article_number = _row_get(row, "article_number") + if not body: + report["drops"]["empty_body"] += 1 + if len(report["drop_samples"]["empty_body"]) < 20: + report["drop_samples"]["empty_body"].append(source_id) + continue + parent = law_map.get(instrument_id) + if not parent: + report["drops"]["missing_instrument"] += 1 + if len(report["drop_samples"]["missing_instrument"]) < 20: + report["drop_samples"]["missing_instrument"].append( + {"article_id": source_id, "law_id": instrument_id} + ) + continue + meta = parent["metadata"] + art_meta = _parse_meta(_row_get(row, "metadata_json")) + merged_meta = {**meta, **art_meta} + entries.append( + _base_record( + record_type="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=article_number, + article_title=article_title, + body=body, + jurisdiction=parent["jurisdiction"], + language=parent["language"] or _row_get(row, "language"), + source_url=_row_get(row, "source_url") or parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], merged_meta, source_meta), + coverage=_coverage_from(parent["row"], merged_meta, articles_empty=False), + license_expr=parent["license"], + collector=_collector(merged_meta, source_dataset), + source_id=source_id, + 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": source_id, + }, + ) + ) + else: + for instrument_id, parent in law_map.items(): + body = parent["body"] + if not body: + report["drops"]["empty_body"] += 1 + if len(report["drop_samples"]["empty_body"]) < 20: + report["drop_samples"]["empty_body"].append(instrument_id) + continue + meta = parent["metadata"] + entries.append( + _base_record( + record_type="law", + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number="", + article_title="", + body=body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage=_coverage_from( + parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback + ), + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=instrument_id, + 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": "", + "article_id": "", + }, + ) + ) + + entries.sort( + key=lambda r: ( + r["instrument_id"], + r.get("article_number") or "", + r["source_id"], + ) + ) + n_before = len(entries) + seen: set[str] = set() + deduped: list[dict[str, Any]] = [] + for rec in entries: + cid = rec["entry_cid"] + if cid in seen: + report["drops"]["duplicate_cid"] += 1 + report["drops"]["duplicate_source_kept_first"] += 1 + if len(report["drop_samples"]["duplicate_cid"]) < 20: + report["drop_samples"]["duplicate_cid"].append(rec["source_id"]) + continue + seen.add(cid) + deduped.append(rec) + for i, rec in enumerate(deduped): + rec["document_index"] = i + rec["corpus_index"] = i + + df = pd.DataFrame(deduped) + if not df.empty and df["entry_cid"].duplicated().any(): + raise SchemaError("Duplicate entry_cid remained after dedupe") + report["n_before_dedupe"] = n_before + report["n_out"] = int(len(df)) + report["n_dropped_total"] = ( + report["drops"]["empty_body"] + + report["drops"]["missing_instrument"] + + report["drops"]["duplicate_cid"] + ) + if not df.empty: + report["language_breakdown"] = { + str(k): int(v) for k, v in df["language"].fillna("").value_counts().items() + } + report["record_type_breakdown"] = { + str(k): int(v) for k, v in df["record_type"].value_counts().items() + } + report["jurisdiction_breakdown"] = { + str(k): int(v) for k, v in df["jurisdiction"].fillna("").value_counts().items() + } + snapshot_dates = sorted({str(x) for x in df["snapshot_date"].fillna("") if str(x)}) + report["snapshot_dates"] = snapshot_dates + else: + report["language_breakdown"] = {} + report["record_type_breakdown"] = {} + report["jurisdiction_breakdown"] = {} + report["snapshot_dates"] = [] + + all_article_count_zero = False + if "article_count" in laws.columns and len(laws): + try: + all_article_count_zero = int((laws["article_count"].fillna(0) == 0).sum()) == len(laws) + except Exception: + all_article_count_zero = False + + report["quality_flags"] = { + "articles_table_empty": bool(articles_empty), + "sparse_article_fallback": bool(sparse_fallback), + "article_law_coverage": article_law_coverage, + "all_source_article_counts_zero": all_article_count_zero, + "article_extraction_status_counts": dict(extraction_statuses), + "missing_date": bool("date" in laws.columns and laws["date"].isna().all()) if len(laws) else False, + "missing_date_issued": bool("date_issued" in laws.columns and laws["date_issued"].isna().all()) if len(laws) else False, + "eli_present": bool("eli" in laws.columns and laws["eli"].notna().any()) if len(laws) else False, + "never_invented_legal_text": True, + "empty_bodies_dropped": report["drops"]["empty_body"], + "duplicate_cids_dropped": report["drops"]["duplicate_cid"], + } + df.attrs["normalization_report"] = report + return df, report diff --git a/query.py b/query.py new file mode 100644 index 0000000000000000000000000000000000000000..9cd3a1da6f2ac29b2287609ec1bc797fd55c4774 --- /dev/null +++ b/query.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Thin-client query for country-laws IR releases (local dir).""" + +from __future__ import annotations + +import argparse +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np +import pandas as pd + +K1 = 1.2 +B = 0.75 +TITLE_WEIGHT = 5.0 +BODY_WEIGHT = 1.0 +MAX_QUERY_TERMS = 64 + + +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) + + +class Release: + def __init__(self, root: Path): + self.root = Path(root) + self.manifest = json.loads((self.root / "manifest.json").read_text(encoding="utf-8")) + + def _read(self, rel: str) -> pd.DataFrame: + path = self.root / rel + if path.is_dir(): + files = sorted(path.glob("*.parquet")) + return pd.concat([pd.read_parquet(f) for f in files], ignore_index=True) if files else pd.DataFrame() + 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 [] + shards = pd.read_parquet(self.root / "indexes" / "bm25_keyword_shards.parquet") + needed = set() + for term in q_terms: + hit = shards[(shards["first_key"] <= term) & (shards["last_key"] >= term)] + if hit.empty: + hit = shards + for rel in hit["relative_path"].tolist(): + needed.add(rel) + postings = pd.concat( + [pd.read_parquet(self.root / rel) for rel in sorted(needed)], + ignore_index=True, + ) + postings = postings[postings["term"].isin(q_terms)] + docs = self._read("data/bm25/documents") + avgdl = float(self.manifest["bm25"]["average_document_length"]) or 1.0 + scores: dict[int, float] = defaultdict(float) + for rec in postings.itertuples(index=False): + idf = float(rec.idf) + for di, ttf, btf, dl in zip( + rec.document_indices, rec.title_frequencies, rec.body_frequencies, rec.document_lengths + ): + tf = TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf) + denom = tf + K1 * (1.0 - B + B * (int(dl) / avgdl)) + if denom: + scores[int(di)] += idf * (tf * (K1 + 1.0)) / denom + ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:top_k] + by_idx = docs.set_index("document_index") + out = [] + for di, score in ranked: + row = by_idx.loc[di] + out.append( + { + "document_index": int(di), + "entry_cid": row["entry_cid"], + "title": row["title"], + "record_type": row["record_type"], + "instrument_id": row.get("instrument_id", row.get("law_id", "")), + "law_cid": row.get("law_cid", ""), + "score": float(score), + } + ) + return out + + def vector(self, query: str, top_k: int = 10, candidate_centroids: int = 4, device: str = "cpu") -> list[dict]: + status = (self.manifest.get("vector") or {}).get("status") + if status == "stub": + return [{"error": "vectors are stubbed", "reason": self.manifest["vector"].get("stub_reason")}] + from sentence_transformers import SentenceTransformer + + model = SentenceTransformer(self.manifest["vector"]["model_name"], device=device) + q = model.encode([query], normalize_embeddings=True, convert_to_numpy=True)[0].astype(np.float32) + meta = pd.read_parquet(self.root / "indexes" / "vector_chunks.parquet") + cents = np.stack(meta["centroid"].map(lambda c: np.asarray(c, dtype=np.float32)).to_numpy()) + sims = cents @ q + order = np.argsort(-sims)[: max(1, candidate_centroids)] + shards = meta.iloc[order] + frames = [pd.read_parquet(self.root / rel) for rel in shards["relative_path"].tolist()] + vecs = pd.concat(frames, ignore_index=True) + if "embedding" not in vecs.columns or vecs["embedding"].isna().all(): + return [{"error": "vector shard missing embeddings"}] + emb = np.stack(vecs["embedding"].map(lambda e: np.asarray(e, dtype=np.float32)).to_numpy()) + scores = emb @ q + top = np.argsort(-scores)[:top_k] + out = [] + for i in top: + row = vecs.iloc[int(i)] + out.append( + { + "document_index": int(row["document_index"]), + "entry_cid": row["entry_cid"], + "title": row["title"], + "record_type": row["record_type"], + "instrument_id": row.get("instrument_id", row.get("law_id", "")), + "score": float(scores[int(i)]), + } + ) + 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: + path = self.root / "data" / "graph" / "adjacency" / d + files = sorted(path.glob("*.parquet")) + for f in files: + df = pd.read_parquet(f) + sub = df[df["node_cid"] == node_cid] + for rec in sub.itertuples(index=False): + for i, neigh in enumerate(rec.neighbor_cids): + hits.append( + { + "direction": d, + "node_cid": node_cid, + "neighbor_cid": neigh, + "edge_type": rec.edge_types[i] if i < len(rec.edge_types) else "", + "score": rec.scores[i] if rec.scores is not None and i < len(rec.scores) else None, + } + ) + hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"])) + return hits[:limit] + + +def _print(rows: list[dict]) -> None: + print(json.dumps(rows, indent=2, ensure_ascii=False)) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description="Query a country-laws IR release") + ap.add_argument("--local-dir", required=True, help="Path to local release root") + sub = ap.add_subparsers(dest="cmd", required=True) + + p_bm = sub.add_parser("bm25") + p_bm.add_argument("query") + p_bm.add_argument("--top-k", type=int, default=10) + + p_vec = sub.add_parser("vector") + 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="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", "in", "out", "incoming", "outgoing"], + ) + p_n.add_argument("--limit", type=int, default=25) + + args = ap.parse_args(argv) + rel = Release(Path(args.local_dir)) + if args.cmd == "bm25": + _print(rel.bm25(args.query, top_k=args.top_k)) + elif args.cmd == "vector": + _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device)) + elif args.cmd == "graph" and args.graph_cmd == "neighbors": + _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/reports/normalization.json b/reports/normalization.json new file mode 100644 index 0000000000000000000000000000000000000000..b902bfade1a69a4ce97bad4c71fc8f44d954a171 --- /dev/null +++ b/reports/normalization.json @@ -0,0 +1,84 @@ +{ + "source_dataset": "endomorphosis/ipfs_nicaragua_laws", + "source_revision": "59efc0b35ac8296762d3626ac0ea8fef7c7f19a7", + "laws_sha256": "d4cc0cdd38018549134920af839de3f9c978f5b7449c46b44eac3a80a7ef8053", + "articles_sha256": "fa5dd8f8e21563ed9ec21494ec0ff130bc5b0d94d850c5fe298636d23325ea3d", + "n_laws_in": 353, + "n_articles_in": 34727, + "unit": "article", + "article_law_coverage": 98.37677053824362, + "sparse_article_fallback": false, + "drops": { + "empty_body": 0, + "missing_instrument": 0, + "duplicate_cid": 123, + "duplicate_source_kept_first": 123 + }, + "drop_samples": { + "empty_body": [], + "missing_instrument": [], + "duplicate_cid": [ + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-43", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-48", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-50", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-52", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-54", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-55", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-56", + "ni-2011-10-05-_ley__no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-57", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-43", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-48", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-50", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-52", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-54", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-55", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-56", + "ni-2011-10-05-_ley_no._774-_ley_de_medicina_natural-_terapias_complementarias_y_productos_naturales_en_nicaragua-art-57", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-i", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-i", + "ni-dictamen_iniciativa_no._20138081-_ley_de_ref._a_la_ley_n-_181-capitulo-iii", + "ni-dictamen_ley_especial_para_la_atencion_a_los_excomb.-_15-10-2012-capitulo-i" + ] + }, + "language_breakdown": { + "es": 34604 + }, + "quality_flags": { + "articles_table_empty": false, + "sparse_article_fallback": false, + "article_law_coverage": 98.37677053824362, + "all_source_article_counts_zero": false, + "article_extraction_status_counts": { + "missing": 51, + "ok": 302 + }, + "missing_date": true, + "missing_date_issued": true, + "eli_present": false, + "never_invented_legal_text": true, + "empty_bodies_dropped": 0, + "duplicate_cids_dropped": 123 + }, + "schema_surprises": [ + "laws.article_count dtype=int32", + "laws.date is entirely null", + "laws.date_issued is entirely null", + "laws.eli non-null=0/353", + "laws.language values=['es']" + ], + "n_out": 34604, + "never_invented_legal_text": true, + "n_before_dedupe": 34727, + "n_dropped_total": 123, + "record_type_breakdown": { + "article": 34604 + }, + "jurisdiction_breakdown": { + "NI": 34604 + }, + "snapshot_dates": [ + "2026-09-10", + "2026-09-15", + "2026-09-16" + ] +} diff --git a/skill/query-country-laws-hf/SKILL.md b/skill/query-country-laws-hf/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..4e4ac643f22f6358aebed43016ff54a96dc96568 --- /dev/null +++ b/skill/query-country-laws-hf/SKILL.md @@ -0,0 +1,34 @@ +--- +name: query-country-laws-hf +description: Query a local or Hub country-laws-ir GraphRAG release (BM25, vectors, graph neighbors). Research retrieval only — not legal advice. +--- + +# Query country-laws-ir (SkillCenter-style sparse GraphRAG) + +Thin client for `justicedao/ipfs_nicaragua_laws_ir` / local release roots that follow +`country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3`). + +**Not legal advice.** Official gazettes prevail. Retrieved hits are context only. + +## Local + +```bash +python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 5 +python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 5 +python scripts/query_country_laws_hf.py --local-dir . graph neighbors +``` + +Or: + +```bash +python -m country_laws_ir query --local-dir /workspace/country-laws-ir/releases/ipfs_nicaragua_laws_ir -- bm25 "constitution" +``` + +## Method + +- Primary key `entry_cid` (CIDv1 raw sha2-256). `document_index` is a shard pointer. +- BM25 Okapi k1=1.2 b=0.75, title_weight=5, body_weight=1, FTS5-style tokenizer. +- Vectors `thenlper/gte-small` 384-d, mean-pool, L2, centroid-sorted shards. +- Graph: facets + `BM25_NEIGHBOR_OF` (k=8, score + matched terms) + `ARTICLE_OF`. + +Do not treat retrieval as proof. Do not invent citations.