Datasets:
Add files using upload-large-folder tool
Browse files- README.md +3 -0
- country_laws_ir/__init__.py +19 -0
- country_laws_ir/__main__.py +87 -0
- country_laws_ir/auth.py +16 -0
- country_laws_ir/bm25.py +227 -0
- country_laws_ir/build.py +237 -0
- country_laws_ir/catalog.py +183 -0
- country_laws_ir/cidutil.py +81 -0
- country_laws_ir/graph.py +336 -0
- country_laws_ir/mem.py +236 -0
- country_laws_ir/normalize.py +574 -0
- country_laws_ir/package.py +877 -0
- country_laws_ir/parquet_io.py +83 -0
- country_laws_ir/query.py +188 -0
- country_laws_ir/schema.py +128 -0
- country_laws_ir/spill.py +763 -0
- country_laws_ir/tokenize.py +21 -0
- country_laws_ir/upload.py +24 -0
- country_laws_ir/vectors.py +335 -0
- data/graph/edges/part-000001.parquet +3 -0
- data/graph/edges/part-000004.parquet +3 -0
- data/graph/edges/part-000008.parquet +3 -0
- data/graph/edges/part-000010.parquet +3 -0
- data/graph/edges/part-000018.parquet +3 -0
- data/graph/edges/part-000025.parquet +3 -0
- data/graph/edges/part-000053.parquet +3 -0
- data/graph/edges/part-000071.parquet +3 -0
- data/graph/edges/part-000079.parquet +3 -0
- data/graph/edges/part-000082.parquet +3 -0
- data/graph/edges/part-000092.parquet +3 -0
- data/graph/edges/part-000104.parquet +3 -0
- data/graph/edges/part-000115.parquet +3 -0
- data/graph/edges/part-000122.parquet +3 -0
- data/graph/edges/part-000135.parquet +3 -0
- data/graph/edges/part-000150.parquet +3 -0
- data/graph/edges/part-000160.parquet +3 -0
- data/graph/edges/part-000175.parquet +3 -0
- data/graph/edges/part-000179.parquet +3 -0
- data/graph/edges/part-000222.parquet +3 -0
- data/graph/edges/part-000245.parquet +3 -0
- data/graph/edges/part-000247.parquet +3 -0
- data/graph/edges/part-000249.parquet +3 -0
- data/graph/edges/part-000271.parquet +3 -0
- data/graph/edges/part-000272.parquet +3 -0
- manifest.json +153 -0
- scripts/build_country_laws_ir.py +55 -0
- scripts/generate_country_laws_ir.py +15 -0
- scripts/normalize_country_laws.py +44 -0
- scripts/query_country_laws_hf.py +10 -0
- scripts/query_country_laws_ir.py +16 -0
README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# justicedao/ipfs_colombia_laws_ir
|
| 2 |
+
|
| 3 |
+
Colombia laws IR release.
|
country_laws_ir/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.3.0"
|
| 4 |
+
# Layout matches SkillCenter HF release / publicus-ir family; schema string is domain-specific.
|
| 5 |
+
SCHEMA_VERSION = "country-laws-ir-graphrag/v1"
|
| 6 |
+
LAYOUT_FAMILY = "skillcenter-huggingface-release/v3"
|
| 7 |
+
ENTRY_IDENTITY_SCHEMA = "country-laws-entry/v1"
|
| 8 |
+
LAW_IDENTITY_SCHEMA = "country-laws-law/v1"
|
| 9 |
+
FACET_IDENTITY_SCHEMA = "country-laws-facet/v1"
|
| 10 |
+
EDGE_IDENTITY_SCHEMA = "country-laws-edge/v1"
|
| 11 |
+
MAX_ROWS_PER_FILE = 4096
|
| 12 |
+
TARGET_ORG = "justicedao"
|
| 13 |
+
|
| 14 |
+
# CID payload: UTF-8 bytes of json.dumps(obj, sort_keys=True, ensure_ascii=False,
|
| 15 |
+
# separators=(",", ":")) hashed as CIDv1 codec=raw (0x55) hash=sha2-256 (0x12)
|
| 16 |
+
# multibase base32 (`bafkrei...`). Same payload -> same CID.
|
| 17 |
+
CID_CODEC = "raw"
|
| 18 |
+
CID_HASH = "sha2-256"
|
| 19 |
+
CID_MULTIBASE = "base32"
|
country_laws_ir/__main__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""python -m country_laws_ir {build,query,batch,catalog}"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main(argv: list[str] | None = None) -> int:
|
| 12 |
+
ap = argparse.ArgumentParser(prog="country_laws_ir")
|
| 13 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 14 |
+
|
| 15 |
+
p_build = sub.add_parser("build")
|
| 16 |
+
p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
|
| 17 |
+
help="Hub dataset id (endomorphosis/ipfs_<slug>_laws) or country slug")
|
| 18 |
+
p_build.add_argument("--out", default=None)
|
| 19 |
+
p_build.add_argument("--device", default="cpu")
|
| 20 |
+
p_build.add_argument("--neighbor-k", type=int, default=8)
|
| 21 |
+
p_build.add_argument("--skip-vectors", action="store_true")
|
| 22 |
+
p_build.add_argument("--upload", action="store_true")
|
| 23 |
+
|
| 24 |
+
p_batch = sub.add_parser("batch")
|
| 25 |
+
p_batch.add_argument("--slugs", nargs="*", default=None)
|
| 26 |
+
p_batch.add_argument("--upload", action="store_true")
|
| 27 |
+
p_batch.add_argument("--no-skip-done", action="store_true")
|
| 28 |
+
|
| 29 |
+
p_q = sub.add_parser("query")
|
| 30 |
+
p_q.add_argument("--local-dir", required=True)
|
| 31 |
+
p_q.add_argument("rest", nargs=argparse.REMAINDER)
|
| 32 |
+
|
| 33 |
+
p_norm = sub.add_parser("normalize")
|
| 34 |
+
p_norm.add_argument("--source-repo", "--source", dest="source", default="malta")
|
| 35 |
+
p_norm.add_argument("--out", default=None, help="Optional JSON report path")
|
| 36 |
+
|
| 37 |
+
sub.add_parser("catalog")
|
| 38 |
+
|
| 39 |
+
args = ap.parse_args(argv)
|
| 40 |
+
if args.cmd == "build":
|
| 41 |
+
from .build import build_country
|
| 42 |
+
|
| 43 |
+
result = build_country(
|
| 44 |
+
args.source,
|
| 45 |
+
out=Path(args.out) if args.out else None,
|
| 46 |
+
upload=args.upload,
|
| 47 |
+
device=args.device,
|
| 48 |
+
neighbor_k=args.neighbor_k,
|
| 49 |
+
skip_vectors=args.skip_vectors,
|
| 50 |
+
)
|
| 51 |
+
print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str))
|
| 52 |
+
print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str))
|
| 53 |
+
return 0
|
| 54 |
+
if args.cmd == "batch":
|
| 55 |
+
from .build import batch
|
| 56 |
+
|
| 57 |
+
results = batch(slugs=args.slugs, upload=args.upload, skip_done=not args.no_skip_done)
|
| 58 |
+
print(json.dumps([{"country": r["country"], "out": r["out"]} for r in results], indent=2))
|
| 59 |
+
return 0
|
| 60 |
+
if args.cmd == "query":
|
| 61 |
+
from .query import main as qmain
|
| 62 |
+
|
| 63 |
+
argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"]
|
| 64 |
+
return qmain(argv2)
|
| 65 |
+
if args.cmd == "normalize":
|
| 66 |
+
from .build import CACHE, REPORTS, ROOT
|
| 67 |
+
from .catalog import get_country
|
| 68 |
+
from .normalize import build_corpus, load_source
|
| 69 |
+
|
| 70 |
+
country = get_country(args.source)
|
| 71 |
+
laws, articles, source_meta = load_source(country["repo"], CACHE)
|
| 72 |
+
corpus, report = build_corpus(laws, articles, source_meta)
|
| 73 |
+
out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
|
| 74 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 76 |
+
print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2))
|
| 77 |
+
return 0
|
| 78 |
+
if args.cmd == "catalog":
|
| 79 |
+
from .catalog import COUNTRIES, indexable_countries
|
| 80 |
+
|
| 81 |
+
print(json.dumps({"n": len(COUNTRIES), "indexable": len(indexable_countries()), "countries": COUNTRIES}, indent=2))
|
| 82 |
+
return 0
|
| 83 |
+
return 1
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
raise SystemExit(main())
|
country_laws_ir/auth.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public Hugging Face reads only. This pipeline never loads, stores, or uses a token."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def configure_hf() -> None:
|
| 9 |
+
"""Force anonymous public Hub access. Tokens are ignored, never printed, never stored."""
|
| 10 |
+
os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
|
| 11 |
+
# Do not read HF_TOKEN / HUGGING_FACE_HUB_TOKEN. Public datasets need no auth.
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def public_token() -> bool:
|
| 15 |
+
"""huggingface_hub `token=False` means anonymous (do not pick up env tokens)."""
|
| 16 |
+
return False
|
country_laws_ir/bm25.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Okapi BM25 (k1=1.2, b=0.75, title_weight=5, body_weight=1) + posting shards."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from typing import Any, Iterable
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 13 |
+
from .tokenize import tokenize
|
| 14 |
+
|
| 15 |
+
K1 = 1.2
|
| 16 |
+
B = 0.75
|
| 17 |
+
TITLE_WEIGHT = 5.0
|
| 18 |
+
BODY_WEIGHT = 1.0
|
| 19 |
+
POSTING_ROWS_PER_RECORD = 4096
|
| 20 |
+
TERMS_PER_SHARD = 4096
|
| 21 |
+
MAX_QUERY_TERMS = 64
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _idf(n_docs: int, df: int) -> float:
|
| 25 |
+
# rank_bm25 Okapi: ln((N - df + 0.5) / (df + 0.5) + 1)
|
| 26 |
+
return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def build_index(corpus: pd.DataFrame) -> dict[str, Any]:
|
| 30 |
+
n = len(corpus)
|
| 31 |
+
titles = corpus["title"].fillna("").astype(str).tolist()
|
| 32 |
+
bodies = corpus["body"].fillna("").astype(str).tolist()
|
| 33 |
+
title_toks = [tokenize(t) for t in titles]
|
| 34 |
+
body_toks = [tokenize(t) for t in bodies]
|
| 35 |
+
|
| 36 |
+
title_len = np.array([len(t) for t in title_toks], dtype=np.int32)
|
| 37 |
+
body_len = np.array([len(t) for t in body_toks], dtype=np.int32)
|
| 38 |
+
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
|
| 39 |
+
avgdl = float(doc_len.mean()) if n else 0.0
|
| 40 |
+
|
| 41 |
+
# term -> {doc: [title_tf, body_tf]}
|
| 42 |
+
postings: dict[str, dict[int, list[int]]] = defaultdict(dict)
|
| 43 |
+
for i, (tt, bt) in enumerate(zip(title_toks, body_toks)):
|
| 44 |
+
tf_t: dict[str, int] = defaultdict(int)
|
| 45 |
+
tf_b: dict[str, int] = defaultdict(int)
|
| 46 |
+
for tok in tt:
|
| 47 |
+
tf_t[tok] += 1
|
| 48 |
+
for tok in bt:
|
| 49 |
+
tf_b[tok] += 1
|
| 50 |
+
for tok in set(tf_t) | set(tf_b):
|
| 51 |
+
postings[tok][i] = [int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0))]
|
| 52 |
+
|
| 53 |
+
terms = sorted(postings)
|
| 54 |
+
idf = {t: _idf(n, len(postings[t])) for t in terms}
|
| 55 |
+
|
| 56 |
+
doc_rows = []
|
| 57 |
+
for i, row in corpus.iterrows():
|
| 58 |
+
idx = int(row["document_index"])
|
| 59 |
+
doc_rows.append(
|
| 60 |
+
{
|
| 61 |
+
"entry_cid": row["entry_cid"],
|
| 62 |
+
"document_index": idx,
|
| 63 |
+
"law_cid": row.get("law_cid", ""),
|
| 64 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 65 |
+
"law_id": row.get("law_id", row.get("instrument_id", "")),
|
| 66 |
+
"source_id": row["source_id"],
|
| 67 |
+
"title": row["title"],
|
| 68 |
+
"instrument_title": row.get("instrument_title", ""),
|
| 69 |
+
"article_number": row.get("article_number", ""),
|
| 70 |
+
"article_title": row.get("article_title", ""),
|
| 71 |
+
"record_type": row["record_type"],
|
| 72 |
+
"language": row.get("language", ""),
|
| 73 |
+
"jurisdiction": row.get("jurisdiction", ""),
|
| 74 |
+
"title_length": int(title_len[idx]),
|
| 75 |
+
"body_length": int(body_len[idx]),
|
| 76 |
+
"document_length": int(round(doc_len[idx])),
|
| 77 |
+
"schema_version": SCHEMA_VERSION,
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
documents = pd.DataFrame(doc_rows).sort_values("document_index").reset_index(drop=True)
|
| 81 |
+
|
| 82 |
+
posting_rows = []
|
| 83 |
+
for term in terms:
|
| 84 |
+
items = sorted(postings[term].items())
|
| 85 |
+
chunks = [
|
| 86 |
+
items[i : i + POSTING_ROWS_PER_RECORD]
|
| 87 |
+
for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD)
|
| 88 |
+
]
|
| 89 |
+
n_chunks = len(chunks)
|
| 90 |
+
dfreq = len(items)
|
| 91 |
+
cfreq = sum(v[0] + v[1] for _, v in items)
|
| 92 |
+
for cidx, chunk in enumerate(chunks):
|
| 93 |
+
posting_rows.append(
|
| 94 |
+
{
|
| 95 |
+
"term": term,
|
| 96 |
+
"document_indices": [d for d, _ in chunk],
|
| 97 |
+
"title_frequencies": [v[0] for _, v in chunk],
|
| 98 |
+
"body_frequencies": [v[1] for _, v in chunk],
|
| 99 |
+
"tfs": [TITLE_WEIGHT * v[0] + BODY_WEIGHT * v[1] for _, v in chunk],
|
| 100 |
+
"lengths": [int(round(doc_len[d])) for d, _ in chunk],
|
| 101 |
+
"document_lengths": [int(round(doc_len[d])) for d, _ in chunk],
|
| 102 |
+
"document_frequency": int(dfreq),
|
| 103 |
+
"corpus_frequency": int(cfreq),
|
| 104 |
+
"idf": float(idf[term]),
|
| 105 |
+
"posting_chunk_index": int(cidx),
|
| 106 |
+
"posting_chunk_count": int(n_chunks),
|
| 107 |
+
"schema_version": SCHEMA_VERSION,
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
postings_df = pd.DataFrame(posting_rows)
|
| 111 |
+
|
| 112 |
+
stats = {
|
| 113 |
+
"k1": K1,
|
| 114 |
+
"b": B,
|
| 115 |
+
"title_weight": TITLE_WEIGHT,
|
| 116 |
+
"body_weight": BODY_WEIGHT,
|
| 117 |
+
"average_document_length": avgdl,
|
| 118 |
+
"tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1",
|
| 119 |
+
"max_query_terms": MAX_QUERY_TERMS,
|
| 120 |
+
"posting_rows_per_record": POSTING_ROWS_PER_RECORD,
|
| 121 |
+
"terms_per_shard": TERMS_PER_SHARD,
|
| 122 |
+
"n_docs": n,
|
| 123 |
+
"n_terms": len(terms),
|
| 124 |
+
"n_posting_rows": int(len(postings_df)),
|
| 125 |
+
"n_postings": int(sum(len(postings[t]) for t in terms)),
|
| 126 |
+
}
|
| 127 |
+
return {
|
| 128 |
+
"documents": documents,
|
| 129 |
+
"postings": postings_df,
|
| 130 |
+
"postings_map": postings,
|
| 131 |
+
"idf": idf,
|
| 132 |
+
"doc_len": doc_len,
|
| 133 |
+
"avgdl": avgdl,
|
| 134 |
+
"title_toks": title_toks,
|
| 135 |
+
"body_toks": body_toks,
|
| 136 |
+
"stats": stats,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _tf_score(tf: float, dl: float, avgdl: float) -> float:
|
| 141 |
+
denom = tf + K1 * (1.0 - B + B * (dl / avgdl if avgdl else 0.0))
|
| 142 |
+
if denom == 0:
|
| 143 |
+
return 0.0
|
| 144 |
+
return (tf * (K1 + 1.0)) / denom
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def score_query(
|
| 148 |
+
query: str,
|
| 149 |
+
index: dict[str, Any],
|
| 150 |
+
top_k: int = 10,
|
| 151 |
+
) -> list[tuple[int, float]]:
|
| 152 |
+
q_terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 153 |
+
if not q_terms:
|
| 154 |
+
return []
|
| 155 |
+
postings = index["postings_map"]
|
| 156 |
+
idf = index["idf"]
|
| 157 |
+
doc_len = index["doc_len"]
|
| 158 |
+
avgdl = index["avgdl"] or 1.0
|
| 159 |
+
scores: dict[int, float] = defaultdict(float)
|
| 160 |
+
for term in q_terms:
|
| 161 |
+
plist = postings.get(term)
|
| 162 |
+
if not plist:
|
| 163 |
+
continue
|
| 164 |
+
w = idf.get(term, 0.0)
|
| 165 |
+
for doc, (ttf, btf) in plist.items():
|
| 166 |
+
tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf
|
| 167 |
+
scores[doc] += w * _tf_score(tf, float(doc_len[doc]), avgdl)
|
| 168 |
+
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
|
| 169 |
+
return ranked[:top_k]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def bm25_neighbors(index: dict[str, Any], k: int = 8) -> list[list[tuple[int, float, list[str]]]]:
|
| 173 |
+
"""Top-k BM25 neighbors from title tokens (body prefix only if title is empty).
|
| 174 |
+
|
| 175 |
+
Each neighbor is (document_index, score, matched_terms).
|
| 176 |
+
"""
|
| 177 |
+
import heapq
|
| 178 |
+
|
| 179 |
+
n = index["stats"]["n_docs"]
|
| 180 |
+
postings = index["postings_map"]
|
| 181 |
+
idf = index["idf"]
|
| 182 |
+
doc_len = index["doc_len"]
|
| 183 |
+
avgdl = index["avgdl"] or 1.0
|
| 184 |
+
title_toks = index["title_toks"]
|
| 185 |
+
body_toks = index["body_toks"]
|
| 186 |
+
df_cap = max(256, min(1500, n // 40 or 1))
|
| 187 |
+
term_docs: dict[str, np.ndarray] = {}
|
| 188 |
+
term_pay: dict[str, np.ndarray] = {}
|
| 189 |
+
for term, plist in postings.items():
|
| 190 |
+
if len(plist) > df_cap:
|
| 191 |
+
continue
|
| 192 |
+
docs = np.fromiter(plist.keys(), dtype=np.int32, count=len(plist))
|
| 193 |
+
tfs = np.empty(len(plist), dtype=np.float64)
|
| 194 |
+
for j, (doc, (ttf, btf)) in enumerate(plist.items()):
|
| 195 |
+
tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf
|
| 196 |
+
tfs[j] = _tf_score(tf, float(doc_len[doc]), avgdl)
|
| 197 |
+
term_docs[term] = docs
|
| 198 |
+
term_pay[term] = tfs * float(idf.get(term, 0.0))
|
| 199 |
+
|
| 200 |
+
neighbors: list[list[tuple[int, float, list[str]]]] = [[] for _ in range(n)]
|
| 201 |
+
step = 20000 if n >= 40000 else max(n, 1)
|
| 202 |
+
for i in range(n):
|
| 203 |
+
if i and i % step == 0:
|
| 204 |
+
print(f"bm25 neighbors {i}/{n}", flush=True)
|
| 205 |
+
q_terms = title_toks[i][:16] or body_toks[i][:16]
|
| 206 |
+
if not q_terms:
|
| 207 |
+
continue
|
| 208 |
+
tf_q: dict[str, int] = defaultdict(int)
|
| 209 |
+
for tok in q_terms:
|
| 210 |
+
tf_q[tok] += 1
|
| 211 |
+
scores: dict[int, float] = defaultdict(float)
|
| 212 |
+
matched: dict[int, set[str]] = defaultdict(set)
|
| 213 |
+
for term, qtf in tf_q.items():
|
| 214 |
+
docs = term_docs.get(term)
|
| 215 |
+
if docs is None:
|
| 216 |
+
continue
|
| 217 |
+
pay = term_pay[term] * qtf
|
| 218 |
+
for doc, val in zip(docs, pay):
|
| 219 |
+
di = int(doc)
|
| 220 |
+
if di != i:
|
| 221 |
+
scores[di] += float(val)
|
| 222 |
+
matched[di].add(term)
|
| 223 |
+
if scores:
|
| 224 |
+
top = heapq.nlargest(k, scores.items(), key=lambda kv: kv[1])
|
| 225 |
+
neighbors[i] = [(doc, score, sorted(matched[doc])) for doc, score in top]
|
| 226 |
+
print(f"bm25 neighbors {n}/{n}", flush=True)
|
| 227 |
+
return neighbors
|
country_laws_ir/build.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end build: normalize → BM25 → graph → vectors → package (no upload by default)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import traceback
|
| 9 |
+
from datetime import datetime, timezone
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
from .bm25 import bm25_neighbors, build_index
|
| 14 |
+
from .mem import MemAbort, checkpoint, log_mem
|
| 15 |
+
from .spill import (
|
| 16 |
+
SQLITE_THRESHOLD,
|
| 17 |
+
build_bm25_tf_spill,
|
| 18 |
+
build_graph_from_neighbor_shards,
|
| 19 |
+
neighbors_via_sqlite,
|
| 20 |
+
should_use_sqlite,
|
| 21 |
+
spill_dir_for,
|
| 22 |
+
spill_pickle,
|
| 23 |
+
)
|
| 24 |
+
from .package import package_from_spill, package_release
|
| 25 |
+
from .catalog import get_country, indexable_countries, target_repo
|
| 26 |
+
from .graph import build_graph
|
| 27 |
+
from .normalize import build_corpus, load_source
|
| 28 |
+
from .auth import configure_hf
|
| 29 |
+
from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors
|
| 30 |
+
|
| 31 |
+
ROOT = Path("/workspace/country-laws-ir")
|
| 32 |
+
CACHE = ROOT / "cache"
|
| 33 |
+
RELEASES = ROOT / "releases"
|
| 34 |
+
REPORTS = ROOT / "reports"
|
| 35 |
+
PROGRESS = ROOT / "progress.jsonl"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _log(msg: str) -> None:
|
| 39 |
+
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 40 |
+
print(f"[{ts}] {msg}", flush=True)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def record_progress(event: dict[str, Any]) -> None:
|
| 44 |
+
event = dict(event)
|
| 45 |
+
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 46 |
+
with PROGRESS.open("a", encoding="utf-8") as f:
|
| 47 |
+
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def build_country(
|
| 51 |
+
source: str,
|
| 52 |
+
out: Path | None = None,
|
| 53 |
+
upload: bool = False,
|
| 54 |
+
device: str = "cpu",
|
| 55 |
+
neighbor_k: int = 8,
|
| 56 |
+
skip_vectors: bool = False,
|
| 57 |
+
) -> dict[str, Any]:
|
| 58 |
+
country = get_country(source)
|
| 59 |
+
if not country.get("indexable", True):
|
| 60 |
+
raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}")
|
| 61 |
+
repo = country["repo"]
|
| 62 |
+
out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir"
|
| 63 |
+
local_dir = country.get("local_source_dir") or (
|
| 64 |
+
str(Path(source).resolve())
|
| 65 |
+
if Path(source).is_dir()
|
| 66 |
+
and (
|
| 67 |
+
(Path(source) / "data" / "laws.parquet").is_file()
|
| 68 |
+
or (Path(source) / "laws.parquet").is_file()
|
| 69 |
+
)
|
| 70 |
+
else None
|
| 71 |
+
)
|
| 72 |
+
_log(f"build start {repo} -> {out} (upload={upload}) local={local_dir}")
|
| 73 |
+
configure_hf()
|
| 74 |
+
CACHE.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
REPORTS.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
laws, articles, source_meta = load_source(local_dir or repo, CACHE)
|
| 77 |
+
_log(
|
| 78 |
+
f"source loaded laws={source_meta['n_laws_source']} "
|
| 79 |
+
f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
|
| 80 |
+
)
|
| 81 |
+
corpus, norm_report = build_corpus(laws, articles, source_meta)
|
| 82 |
+
report_path = REPORTS / f"{country['slug']}_normalization.json"
|
| 83 |
+
report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 84 |
+
(REPORTS / "normalization.json").write_text(
|
| 85 |
+
json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 86 |
+
)
|
| 87 |
+
_log(
|
| 88 |
+
f"normalized docs={len(corpus)} unit={norm_report['unit']} "
|
| 89 |
+
f"dropped={norm_report['n_dropped_total']} report={report_path}"
|
| 90 |
+
)
|
| 91 |
+
if corpus.empty:
|
| 92 |
+
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
| 93 |
+
|
| 94 |
+
import gc
|
| 95 |
+
|
| 96 |
+
n_docs = len(corpus)
|
| 97 |
+
spill = spill_dir_for(country["slug"], CACHE)
|
| 98 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet"
|
| 100 |
+
corpus.to_parquet(corpus_ckpt, index=False)
|
| 101 |
+
checkpoint("after_normalize", log=_log)
|
| 102 |
+
|
| 103 |
+
vector_blocker = None
|
| 104 |
+
if skip_vectors:
|
| 105 |
+
vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
|
| 106 |
+
vector_blocker = "skip_vectors"
|
| 107 |
+
spill_pickle(spill / "vectors.pkl", vectors)
|
| 108 |
+
del vectors
|
| 109 |
+
gc.collect()
|
| 110 |
+
elif embeddings_available():
|
| 111 |
+
try:
|
| 112 |
+
ckpt = CACHE / "embeddings" / f"{country['slug']}.npy"
|
| 113 |
+
_log(f"vectors encode start n={n_docs} checkpoint={ckpt}")
|
| 114 |
+
embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt))
|
| 115 |
+
vectors = layout_vectors(corpus, embeddings)
|
| 116 |
+
_log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
|
| 117 |
+
spill_pickle(spill / "vectors.pkl", vectors)
|
| 118 |
+
del embeddings, vectors
|
| 119 |
+
gc.collect()
|
| 120 |
+
checkpoint("vectors_spilled", log=_log)
|
| 121 |
+
except Exception as exc:
|
| 122 |
+
vector_blocker = f"embedding_failed: {exc}"
|
| 123 |
+
_log(f"vector embedding failed; writing stub ({exc})")
|
| 124 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 125 |
+
spill_pickle(spill / "vectors.pkl", vectors)
|
| 126 |
+
del vectors
|
| 127 |
+
gc.collect()
|
| 128 |
+
else:
|
| 129 |
+
vector_blocker = "sentence-transformers/torch unavailable"
|
| 130 |
+
_log(f"vectors stub: {vector_blocker}")
|
| 131 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 132 |
+
spill_pickle(spill / "vectors.pkl", vectors)
|
| 133 |
+
del vectors
|
| 134 |
+
gc.collect()
|
| 135 |
+
|
| 136 |
+
use_sqlite = should_use_sqlite(n_docs)
|
| 137 |
+
neighbor_via = "stock"
|
| 138 |
+
if use_sqlite:
|
| 139 |
+
_log(f"sqlite neighbors path n={n_docs} (>= {SQLITE_THRESHOLD}) spill={spill}")
|
| 140 |
+
# Free corpus body for neighbor stream — reload later for graph
|
| 141 |
+
del corpus
|
| 142 |
+
gc.collect()
|
| 143 |
+
neighbors_via_sqlite(corpus_ckpt, spill, n_docs, k=neighbor_k, log=_log)
|
| 144 |
+
neighbor_via = "sqlite_fts"
|
| 145 |
+
bm25_info = build_bm25_tf_spill(corpus_ckpt, spill, n_docs, log=_log)
|
| 146 |
+
corpus = pd.read_parquet(corpus_ckpt)
|
| 147 |
+
graph = build_graph_from_neighbor_shards(corpus, spill, log=_log)
|
| 148 |
+
spill_pickle(spill / "graph.pkl", graph)
|
| 149 |
+
del graph, corpus
|
| 150 |
+
gc.collect()
|
| 151 |
+
checkpoint("graph_spilled", log=_log)
|
| 152 |
+
code_root = Path(__file__).resolve().parent.parent
|
| 153 |
+
manifest = package_from_spill(
|
| 154 |
+
out, spill, corpus_ckpt, source_meta, country, code_root,
|
| 155 |
+
normalization_report=norm_report, expected_rows=n_docs,
|
| 156 |
+
)
|
| 157 |
+
_log(f"packaged sequential via={neighbor_via} {out}")
|
| 158 |
+
else:
|
| 159 |
+
bm25 = build_index(corpus)
|
| 160 |
+
_log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
|
| 161 |
+
_log(f"bm25 neighbors start n={n_docs} k={neighbor_k}")
|
| 162 |
+
neighbors = bm25_neighbors(bm25, k=neighbor_k)
|
| 163 |
+
_log("bm25 neighbors done")
|
| 164 |
+
graph = build_graph(corpus, neighbors)
|
| 165 |
+
del neighbors
|
| 166 |
+
gc.collect()
|
| 167 |
+
_log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
|
| 168 |
+
with open(spill / "vectors.pkl", "rb") as _vf:
|
| 169 |
+
import pickle as _pickle
|
| 170 |
+
vectors = _pickle.load(_vf)
|
| 171 |
+
code_root = Path(__file__).resolve().parent.parent
|
| 172 |
+
manifest = package_release(
|
| 173 |
+
out, corpus, bm25, graph, vectors, source_meta, country, code_root,
|
| 174 |
+
normalization_report=norm_report,
|
| 175 |
+
)
|
| 176 |
+
del corpus, bm25, graph, vectors
|
| 177 |
+
gc.collect()
|
| 178 |
+
_log(f"packaged {out}")
|
| 179 |
+
result = {
|
| 180 |
+
"country": country["slug"],
|
| 181 |
+
"source": repo,
|
| 182 |
+
"source_revision": source_meta["source_revision"],
|
| 183 |
+
"out": str(out),
|
| 184 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 185 |
+
"counts": manifest["counts"],
|
| 186 |
+
"normalization": norm_report,
|
| 187 |
+
"vector_blocker": vector_blocker,
|
| 188 |
+
"neighbor_via": neighbor_via,
|
| 189 |
+
"schema_version": manifest["schema_version"],
|
| 190 |
+
}
|
| 191 |
+
if upload:
|
| 192 |
+
from .upload import upload_release
|
| 193 |
+
|
| 194 |
+
hub = upload_release(out, target_repo(country["slug"]))
|
| 195 |
+
result["hub"] = hub
|
| 196 |
+
_log(f"uploaded {hub['url']} rev={hub['revision']}")
|
| 197 |
+
record_progress({"event": "uploaded", **result})
|
| 198 |
+
else:
|
| 199 |
+
record_progress({"event": "built_local", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 200 |
+
return result
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def batch(
|
| 204 |
+
slugs: list[str] | None = None,
|
| 205 |
+
upload: bool = False,
|
| 206 |
+
skip_done: bool = True,
|
| 207 |
+
) -> list[dict[str, Any]]:
|
| 208 |
+
done = set()
|
| 209 |
+
if skip_done and PROGRESS.exists():
|
| 210 |
+
for line in PROGRESS.read_text(encoding="utf-8").splitlines():
|
| 211 |
+
if not line.strip():
|
| 212 |
+
continue
|
| 213 |
+
rec = json.loads(line)
|
| 214 |
+
if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
|
| 215 |
+
done.add(rec["country"])
|
| 216 |
+
targets = slugs or [c["slug"] for c in indexable_countries()]
|
| 217 |
+
if "malta" in targets:
|
| 218 |
+
targets = ["malta"] + [s for s in targets if s != "malta"]
|
| 219 |
+
results = []
|
| 220 |
+
for slug in targets:
|
| 221 |
+
if skip_done and slug in done:
|
| 222 |
+
_log(f"skip already done {slug}")
|
| 223 |
+
continue
|
| 224 |
+
try:
|
| 225 |
+
results.append(build_country(slug, upload=upload))
|
| 226 |
+
except Exception as exc:
|
| 227 |
+
_log(f"FAILED {slug}: {exc}")
|
| 228 |
+
record_progress(
|
| 229 |
+
{
|
| 230 |
+
"event": "failed",
|
| 231 |
+
"country": slug,
|
| 232 |
+
"error": str(exc),
|
| 233 |
+
"traceback": traceback.format_exc(),
|
| 234 |
+
}
|
| 235 |
+
)
|
| 236 |
+
continue
|
| 237 |
+
return results
|
country_laws_ir/catalog.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Catalog of endomorphosis/ipfs_*_laws corpora.
|
| 2 |
+
|
| 3 |
+
Belgium, Portugal, and Lithuania are incomplete Wayback harvests and are
|
| 4 |
+
excluded from indexing. american_municipal_law is out of scope.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania"}
|
| 12 |
+
EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS}
|
| 13 |
+
|
| 14 |
+
# Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`.
|
| 15 |
+
COUNTRIES: list[dict[str, Any]] = [
|
| 16 |
+
{"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True},
|
| 17 |
+
{"slug": "australia", "repo": "endomorphosis/ipfs_australia_laws", "name": "Australia", "indexable": True},
|
| 18 |
+
{"slug": "austria", "repo": "endomorphosis/ipfs_austria_laws", "name": "Austria", "indexable": True},
|
| 19 |
+
{"slug": "bangladesh", "repo": "endomorphosis/ipfs_bangladesh_laws", "name": "Bangladesh", "indexable": True},
|
| 20 |
+
{"slug": "belgium", "repo": "endomorphosis/ipfs_belgium_laws", "name": "Belgium", "indexable": False,
|
| 21 |
+
"skip_reason": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)"},
|
| 22 |
+
{"slug": "brazil", "repo": "endomorphosis/ipfs_brazil_laws", "name": "Brazil", "indexable": True},
|
| 23 |
+
{"slug": "canada", "repo": "endomorphosis/ipfs_canada_laws", "name": "Canada", "indexable": True},
|
| 24 |
+
{"slug": "chile", "repo": "endomorphosis/ipfs_chile_laws", "name": "Chile", "indexable": True},
|
| 25 |
+
{"slug": "china", "repo": "endomorphosis/ipfs_china_laws", "name": "China", "indexable": True},
|
| 26 |
+
{"slug": "colombia", "repo": "endomorphosis/ipfs_colombia_laws", "name": "Colombia", "indexable": True},
|
| 27 |
+
{"slug": "croatia", "repo": "endomorphosis/ipfs_croatia_laws", "name": "Croatia", "indexable": True},
|
| 28 |
+
{"slug": "czechia", "repo": "endomorphosis/ipfs_czechia_laws", "name": "Czechia", "indexable": True},
|
| 29 |
+
{"slug": "denmark", "repo": "endomorphosis/ipfs_denmark_laws", "name": "Denmark", "indexable": True},
|
| 30 |
+
{"slug": "egypt", "repo": "endomorphosis/ipfs_egypt_laws", "name": "Egypt", "indexable": True},
|
| 31 |
+
{"slug": "estonia", "repo": "endomorphosis/ipfs_estonia_laws", "name": "Estonia", "indexable": True},
|
| 32 |
+
{"slug": "eu", "repo": "endomorphosis/ipfs_eu_laws", "name": "European Union", "indexable": True},
|
| 33 |
+
{"slug": "finland", "repo": "endomorphosis/ipfs_finland_laws", "name": "Finland", "indexable": True},
|
| 34 |
+
{"slug": "france", "repo": "endomorphosis/ipfs_france_laws", "name": "France", "indexable": True},
|
| 35 |
+
{"slug": "ghana", "repo": "endomorphosis/ipfs_ghana_laws", "name": "Ghana", "indexable": False,
|
| 36 |
+
"skip_reason": "thin scrape; Act PDF path blocked by robots"},
|
| 37 |
+
{"slug": "germany", "repo": "endomorphosis/ipfs_germany_laws", "name": "Germany", "indexable": True},
|
| 38 |
+
{"slug": "greece", "repo": "endomorphosis/ipfs_greece_laws", "name": "Greece", "indexable": True},
|
| 39 |
+
{"slug": "hongkong", "repo": "endomorphosis/ipfs_hongkong_laws", "name": "Hong Kong", "indexable": True},
|
| 40 |
+
{"slug": "iceland", "repo": "endomorphosis/ipfs_iceland_laws", "name": "Iceland", "indexable": True},
|
| 41 |
+
{"slug": "hungary", "repo": "endomorphosis/ipfs_hungary_laws", "name": "Hungary", "indexable": True},
|
| 42 |
+
{"slug": "india", "repo": "endomorphosis/ipfs_india_laws", "name": "India", "indexable": True},
|
| 43 |
+
{"slug": "indonesia", "repo": "endomorphosis/ipfs_indonesia_laws", "name": "Indonesia", "indexable": True},
|
| 44 |
+
{"slug": "ireland", "repo": "endomorphosis/ipfs_ireland_laws", "name": "Ireland", "indexable": True},
|
| 45 |
+
{"slug": "israel", "repo": "endomorphosis/ipfs_israel_laws", "name": "Israel", "indexable": True},
|
| 46 |
+
{"slug": "japan", "repo": "endomorphosis/ipfs_japan_laws", "name": "Japan", "indexable": True},
|
| 47 |
+
{"slug": "kenya", "repo": "endomorphosis/ipfs_kenya_laws", "name": "Kenya", "indexable": True},
|
| 48 |
+
{"slug": "korea", "repo": "endomorphosis/ipfs_korea_laws", "name": "Korea (ROK)", "indexable": True},
|
| 49 |
+
{"slug": "kuwait", "repo": "endomorphosis/ipfs_kuwait_laws", "name": "Kuwait", "indexable": True},
|
| 50 |
+
{"slug": "latvia", "repo": "endomorphosis/ipfs_latvia_laws", "name": "Latvia", "indexable": True},
|
| 51 |
+
{"slug": "lithuania", "repo": "endomorphosis/ipfs_lithuania_laws", "name": "Lithuania", "indexable": False,
|
| 52 |
+
"skip_reason": "incomplete Wayback harvest (e-TAR archive shard)"},
|
| 53 |
+
{"slug": "luxembourg", "repo": "endomorphosis/ipfs_luxembourg_laws", "name": "Luxembourg", "indexable": True},
|
| 54 |
+
{"slug": "malaysia", "repo": "endomorphosis/ipfs_malaysia_laws", "name": "Malaysia", "indexable": True},
|
| 55 |
+
{"slug": "malta", "repo": "endomorphosis/ipfs_malta_laws", "name": "Malta", "indexable": True, "pilot": True},
|
| 56 |
+
{"slug": "morocco", "repo": "endomorphosis/ipfs_morocco_laws", "name": "Morocco", "indexable": True},
|
| 57 |
+
{"slug": "mexico", "repo": "endomorphosis/ipfs_mexico_laws", "name": "Mexico", "indexable": True},
|
| 58 |
+
{"slug": "netherlands", "repo": "endomorphosis/ipfs_netherlands_laws", "name": "Netherlands", "indexable": True},
|
| 59 |
+
{"slug": "newzealand", "repo": "endomorphosis/ipfs_newzealand_laws", "name": "New Zealand", "indexable": True},
|
| 60 |
+
{"slug": "nigeria", "repo": "endomorphosis/ipfs_nigeria_laws", "name": "Nigeria", "indexable": True},
|
| 61 |
+
{"slug": "norway", "repo": "endomorphosis/ipfs_norway_laws", "name": "Norway", "indexable": True},
|
| 62 |
+
{"slug": "pakistan", "repo": "endomorphosis/ipfs_pakistan_laws", "name": "Pakistan", "indexable": True},
|
| 63 |
+
{"slug": "philippines", "repo": "endomorphosis/ipfs_philippines_laws", "name": "Philippines", "indexable": True},
|
| 64 |
+
{"slug": "poland", "repo": "endomorphosis/ipfs_poland_laws", "name": "Poland", "indexable": True},
|
| 65 |
+
{"slug": "portugal", "repo": "endomorphosis/ipfs_portugal_laws", "name": "Portugal", "indexable": False,
|
| 66 |
+
"skip_reason": "incomplete Wayback harvest (Diário da República archive shard)"},
|
| 67 |
+
{"slug": "qatar", "repo": "endomorphosis/ipfs_qatar_laws", "name": "Qatar", "indexable": True},
|
| 68 |
+
{"slug": "russia", "repo": "endomorphosis/ipfs_russia_laws", "name": "Russia", "indexable": True},
|
| 69 |
+
{"slug": "saudiarabia", "repo": "endomorphosis/ipfs_saudiarabia_laws", "name": "Saudi Arabia", "indexable": True},
|
| 70 |
+
{"slug": "singapore", "repo": "endomorphosis/ipfs_singapore_laws", "name": "Singapore", "indexable": True},
|
| 71 |
+
{"slug": "slovakia", "repo": "endomorphosis/ipfs_slovakia_laws", "name": "Slovakia", "indexable": True},
|
| 72 |
+
{"slug": "southafrica", "repo": "endomorphosis/ipfs_southafrica_laws", "name": "South Africa", "indexable": True},
|
| 73 |
+
{"slug": "spain", "repo": "endomorphosis/ipfs_spain_laws", "name": "Spain", "indexable": True},
|
| 74 |
+
{"slug": "sweden", "repo": "endomorphosis/ipfs_sweden_laws", "name": "Sweden", "indexable": True},
|
| 75 |
+
{"slug": "switzerland", "repo": "endomorphosis/ipfs_switzerland_laws", "name": "Switzerland", "indexable": True},
|
| 76 |
+
{"slug": "taiwan", "repo": "endomorphosis/ipfs_taiwan_laws", "name": "Taiwan", "indexable": True},
|
| 77 |
+
{"slug": "thailand", "repo": "endomorphosis/ipfs_thailand_laws", "name": "Thailand", "indexable": True},
|
| 78 |
+
{"slug": "turkey", "repo": "endomorphosis/ipfs_turkey_laws", "name": "Turkey", "indexable": True},
|
| 79 |
+
{"slug": "uae", "repo": "endomorphosis/ipfs_uae_laws", "name": "United Arab Emirates", "indexable": True},
|
| 80 |
+
{"slug": "uk", "repo": "endomorphosis/ipfs_uk_laws", "name": "United Kingdom", "indexable": True},
|
| 81 |
+
{"slug": "ukraine", "repo": "endomorphosis/ipfs_ukraine_laws", "name": "Ukraine", "indexable": True},
|
| 82 |
+
{"slug": "vietnam", "repo": "endomorphosis/ipfs_vietnam_laws", "name": "Vietnam", "indexable": True},
|
| 83 |
+
{"slug": "bulgaria", "repo": "endomorphosis/ipfs_bulgaria_laws", "name": "Bulgaria", "indexable": True},
|
| 84 |
+
{"slug": "cyprus", "repo": "endomorphosis/ipfs_cyprus_laws", "name": "Cyprus", "indexable": True},
|
| 85 |
+
{"slug": "italy", "repo": "endomorphosis/ipfs_italy_laws", "name": "Italy", "indexable": True},
|
| 86 |
+
{"slug": "romania", "repo": "endomorphosis/ipfs_romania_laws", "name": "Romania", "indexable": True},
|
| 87 |
+
{"slug": "slovenia", "repo": "endomorphosis/ipfs_slovenia_laws", "name": "Slovenia", "indexable": True},
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def get_country(source: str) -> dict[str, Any]:
|
| 92 |
+
source = source.strip()
|
| 93 |
+
# Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json)
|
| 94 |
+
from pathlib import Path as _Path
|
| 95 |
+
import json as _json
|
| 96 |
+
|
| 97 |
+
local = _Path(source)
|
| 98 |
+
if local.is_dir() and (
|
| 99 |
+
(local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file()
|
| 100 |
+
):
|
| 101 |
+
pack_meta: dict[str, Any] = {}
|
| 102 |
+
meta_path = local / "pack_meta.json"
|
| 103 |
+
if meta_path.is_file():
|
| 104 |
+
try:
|
| 105 |
+
pack_meta = _json.loads(meta_path.read_text(encoding="utf-8"))
|
| 106 |
+
except Exception:
|
| 107 |
+
pack_meta = {}
|
| 108 |
+
slug = str(pack_meta.get("slug") or local.name)
|
| 109 |
+
# strip common cache prefixes like oman_filtered_c72f142a
|
| 110 |
+
if slug.startswith("oman"):
|
| 111 |
+
slug = "oman"
|
| 112 |
+
for prefix in ("ipfs_",):
|
| 113 |
+
if slug.startswith(prefix):
|
| 114 |
+
slug = slug[len(prefix):]
|
| 115 |
+
for suffix in ("_laws", "_filtered", "-ir"):
|
| 116 |
+
if slug.endswith(suffix):
|
| 117 |
+
slug = slug[: -len(suffix)]
|
| 118 |
+
# e.g. oman_filtered_c72f142a -> oman
|
| 119 |
+
if "_filtered" in slug:
|
| 120 |
+
slug = slug.split("_filtered", 1)[0]
|
| 121 |
+
repo = str(pack_meta.get("repo") or pack_meta.get("source_dataset") or f"endomorphosis/ipfs_{slug}_laws")
|
| 122 |
+
return {
|
| 123 |
+
"slug": slug,
|
| 124 |
+
"repo": repo,
|
| 125 |
+
"name": str(pack_meta.get("name") or slug.replace("_", " ").title()),
|
| 126 |
+
"indexable": bool(pack_meta.get("indexable", slug not in EXCLUDED_SLUGS)),
|
| 127 |
+
"skip_reason": pack_meta.get("skip_reason"),
|
| 128 |
+
"local_source_dir": str(local.resolve()),
|
| 129 |
+
"source_revision": pack_meta.get("source_revision"),
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
slug = source
|
| 133 |
+
if "/" in source:
|
| 134 |
+
slug = source.rsplit("/", 1)[-1]
|
| 135 |
+
slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir")
|
| 136 |
+
for row in COUNTRIES:
|
| 137 |
+
if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source):
|
| 138 |
+
return dict(row)
|
| 139 |
+
if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"):
|
| 140 |
+
inferred = source.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 141 |
+
return {
|
| 142 |
+
"slug": inferred,
|
| 143 |
+
"repo": source,
|
| 144 |
+
"name": inferred.replace("_", " ").title(),
|
| 145 |
+
"indexable": inferred not in EXCLUDED_SLUGS,
|
| 146 |
+
"skip_reason": "incomplete Wayback harvest" if inferred in EXCLUDED_SLUGS else None,
|
| 147 |
+
}
|
| 148 |
+
raise KeyError(f"Unknown country-law source: {source}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def indexable_countries() -> list[dict[str, Any]]:
|
| 152 |
+
return [c for c in COUNTRIES if c.get("indexable")]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def target_repo(slug: str) -> str:
|
| 156 |
+
return f"justicedao/ipfs_{slug}_laws_ir"
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def refresh_from_hub() -> list[dict[str, Any]]:
|
| 160 |
+
"""Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets."""
|
| 161 |
+
from huggingface_hub import HfApi
|
| 162 |
+
|
| 163 |
+
from .auth import configure_hf, public_token
|
| 164 |
+
|
| 165 |
+
configure_hf()
|
| 166 |
+
api = HfApi(token=public_token())
|
| 167 |
+
found: list[dict[str, Any]] = []
|
| 168 |
+
for ds in api.list_datasets(author="endomorphosis"):
|
| 169 |
+
ds_id = ds.id
|
| 170 |
+
if not ds_id.startswith("endomorphosis/ipfs_") or not ds_id.endswith("_laws"):
|
| 171 |
+
continue
|
| 172 |
+
slug = ds_id.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 173 |
+
found.append({
|
| 174 |
+
"slug": slug,
|
| 175 |
+
"repo": ds_id,
|
| 176 |
+
"name": slug.replace("_", " ").title(),
|
| 177 |
+
"indexable": slug not in EXCLUDED_SLUGS,
|
| 178 |
+
"skip_reason": (
|
| 179 |
+
"incomplete Wayback harvest" if slug in EXCLUDED_SLUGS else None
|
| 180 |
+
),
|
| 181 |
+
})
|
| 182 |
+
found.sort(key=lambda r: r["slug"])
|
| 183 |
+
return found
|
country_laws_ir/cidutil.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CIDv1 (raw + sha2-256) helpers. Produces bafkrei... identifiers.
|
| 2 |
+
|
| 3 |
+
Payload format (deterministic):
|
| 4 |
+
json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 5 |
+
|
| 6 |
+
Codec: CIDv1 version=0x01, multicodec raw=0x55, multihash sha2-256=0x12, length=0x20,
|
| 7 |
+
then 32-byte digest. Multibase prefix `b` + RFC 4648 base32 (lowercase, no padding).
|
| 8 |
+
Same payload bytes always yield the same CID.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_B32 = "abcdefghijklmnopqrstuvwxyz234567"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def sha256_hex(data: bytes) -> str:
|
| 23 |
+
return hashlib.sha256(data).hexdigest()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def sha256_file(path: Path) -> str:
|
| 27 |
+
h = hashlib.sha256()
|
| 28 |
+
with path.open("rb") as f:
|
| 29 |
+
while True:
|
| 30 |
+
chunk = f.read(1024 * 1024)
|
| 31 |
+
if not chunk:
|
| 32 |
+
break
|
| 33 |
+
h.update(chunk)
|
| 34 |
+
return h.hexdigest()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def canonical_json_bytes(obj: Any) -> bytes:
|
| 38 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _b32encode(data: bytes) -> str:
|
| 42 |
+
bits = 0
|
| 43 |
+
value = 0
|
| 44 |
+
out = []
|
| 45 |
+
for byte in data:
|
| 46 |
+
value = (value << 8) | byte
|
| 47 |
+
bits += 8
|
| 48 |
+
while bits >= 5:
|
| 49 |
+
bits -= 5
|
| 50 |
+
out.append(_B32[(value >> bits) & 31])
|
| 51 |
+
if bits:
|
| 52 |
+
out.append(_B32[(value << (5 - bits)) & 31])
|
| 53 |
+
return "".join(out)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def cid_v1_raw_sha256(data: bytes) -> str:
|
| 57 |
+
digest = hashlib.sha256(data).digest()
|
| 58 |
+
cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest
|
| 59 |
+
return "b" + _b32encode(cid_bytes)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def cid_of_json(obj: Any) -> str:
|
| 63 |
+
return cid_v1_raw_sha256(canonical_json_bytes(obj))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def cid_of_text(*parts: str) -> str:
|
| 67 |
+
blob = "\n".join("" if p is None else str(p) for p in parts).encode("utf-8")
|
| 68 |
+
return cid_v1_raw_sha256(blob)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def file_descriptor(path: Path, relative_path: str, extra: dict | None = None) -> dict:
|
| 72 |
+
data = path.read_bytes()
|
| 73 |
+
desc = {
|
| 74 |
+
"cid": cid_v1_raw_sha256(data),
|
| 75 |
+
"sha256": sha256_hex(data),
|
| 76 |
+
"size_bytes": len(data),
|
| 77 |
+
"relative_path": relative_path,
|
| 78 |
+
}
|
| 79 |
+
if extra:
|
| 80 |
+
desc.update(extra)
|
| 81 |
+
return desc
|
country_laws_ir/graph.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Property graph: entry nodes, facet nodes, BM25_NEIGHBOR_OF k=8, ARTICLE_OF, ELI."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from . import EDGE_IDENTITY_SCHEMA, FACET_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 11 |
+
from .cidutil import cid_of_json
|
| 12 |
+
|
| 13 |
+
# Facet kinds requested by the SkillCenter-style country-laws graph:
|
| 14 |
+
# jurisdiction, language, instrument/law, source, status.
|
| 15 |
+
FACET_FIELDS = (
|
| 16 |
+
("jurisdiction", "HAS_JURISDICTION", "jurisdiction"),
|
| 17 |
+
("language", "HAS_LANGUAGE", "language"),
|
| 18 |
+
("instrument", "HAS_INSTRUMENT", "instrument_id"),
|
| 19 |
+
("source", "HAS_SOURCE", "source_type"),
|
| 20 |
+
("status", "HAS_STATUS", "law_status"),
|
| 21 |
+
)
|
| 22 |
+
ADJ_POINTERS_PER_ROW = 4096
|
| 23 |
+
ADJ_POINTERS_PER_SHARD = 8192
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _facet_cid(kind: str, value: str) -> str:
|
| 27 |
+
"""CIDv1 raw sha2-256 of sorted JSON {kind, schema, value}."""
|
| 28 |
+
return cid_of_json(
|
| 29 |
+
{
|
| 30 |
+
"kind": kind,
|
| 31 |
+
"schema": FACET_IDENTITY_SCHEMA,
|
| 32 |
+
"value": value,
|
| 33 |
+
}
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _edge_cid(source: str, edge_type: str, target: str) -> str:
|
| 38 |
+
return cid_of_json(
|
| 39 |
+
{
|
| 40 |
+
"edge_type": edge_type,
|
| 41 |
+
"schema": EDGE_IDENTITY_SCHEMA,
|
| 42 |
+
"source": source,
|
| 43 |
+
"target": target,
|
| 44 |
+
}
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def build_graph(
|
| 49 |
+
corpus: pd.DataFrame,
|
| 50 |
+
neighbors: list[list[tuple]],
|
| 51 |
+
) -> dict[str, Any]:
|
| 52 |
+
nodes: list[dict[str, Any]] = []
|
| 53 |
+
edges: list[dict[str, Any]] = []
|
| 54 |
+
seen_facets: set[str] = set()
|
| 55 |
+
cid_by_idx = corpus["entry_cid"].tolist()
|
| 56 |
+
|
| 57 |
+
# Law identity nodes (targets of ARTICLE_OF when the parent is not a corpus entry).
|
| 58 |
+
law_nodes: dict[str, dict[str, Any]] = {}
|
| 59 |
+
entry_by_instrument: dict[str, str] = {}
|
| 60 |
+
for rec in corpus.itertuples(index=False):
|
| 61 |
+
law_cid = str(getattr(rec, "law_cid", "") or "")
|
| 62 |
+
instrument_id = str(getattr(rec, "instrument_id", "") or "")
|
| 63 |
+
if getattr(rec, "record_type", "") == "law" and instrument_id and rec.entry_cid:
|
| 64 |
+
entry_by_instrument.setdefault(instrument_id, rec.entry_cid)
|
| 65 |
+
if not law_cid or law_cid in law_nodes:
|
| 66 |
+
continue
|
| 67 |
+
law_nodes[law_cid] = {
|
| 68 |
+
"node_cid": law_cid,
|
| 69 |
+
"node_type": "law",
|
| 70 |
+
"entry_cid": "",
|
| 71 |
+
"label": getattr(rec, "instrument_title", None) or instrument_id,
|
| 72 |
+
"properties_json": _json(
|
| 73 |
+
{
|
| 74 |
+
"instrument_id": instrument_id,
|
| 75 |
+
"instrument_title": str(getattr(rec, "instrument_title", "") or ""),
|
| 76 |
+
"jurisdiction": str(getattr(rec, "jurisdiction", "") or ""),
|
| 77 |
+
"language": str(getattr(rec, "language", "") or ""),
|
| 78 |
+
"law_cid": law_cid,
|
| 79 |
+
}
|
| 80 |
+
),
|
| 81 |
+
"schema_version": SCHEMA_VERSION,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
for law_node in law_nodes.values():
|
| 85 |
+
nodes.append(law_node)
|
| 86 |
+
|
| 87 |
+
for rec in corpus.itertuples(index=False):
|
| 88 |
+
node_type = "law_entry" if rec.record_type == "law" else "article"
|
| 89 |
+
title = getattr(rec, "title", None) or getattr(rec, "instrument_title", None) or rec.source_id
|
| 90 |
+
nodes.append(
|
| 91 |
+
{
|
| 92 |
+
"node_cid": rec.entry_cid,
|
| 93 |
+
"node_type": node_type,
|
| 94 |
+
"entry_cid": rec.entry_cid,
|
| 95 |
+
"label": title,
|
| 96 |
+
"properties_json": _props_tuple(rec),
|
| 97 |
+
"schema_version": SCHEMA_VERSION,
|
| 98 |
+
}
|
| 99 |
+
)
|
| 100 |
+
src = rec.entry_cid
|
| 101 |
+
row_map = rec._asdict() if hasattr(rec, "_asdict") else {}
|
| 102 |
+
|
| 103 |
+
for kind, edge_type, col in FACET_FIELDS:
|
| 104 |
+
value = str(row_map.get(col) or "").strip()
|
| 105 |
+
if not value:
|
| 106 |
+
continue
|
| 107 |
+
fc = _facet_cid(kind, value)
|
| 108 |
+
if fc not in seen_facets:
|
| 109 |
+
seen_facets.add(fc)
|
| 110 |
+
nodes.append(
|
| 111 |
+
{
|
| 112 |
+
"node_cid": fc,
|
| 113 |
+
"node_type": f"facet_{kind}",
|
| 114 |
+
"entry_cid": "",
|
| 115 |
+
"label": f"{kind}:{value}",
|
| 116 |
+
"properties_json": _json({"kind": kind, "value": value}),
|
| 117 |
+
"schema_version": SCHEMA_VERSION,
|
| 118 |
+
}
|
| 119 |
+
)
|
| 120 |
+
edges.append(_edge(src, edge_type, fc, "facet", 1.0, {"facet": kind, "value": value}))
|
| 121 |
+
|
| 122 |
+
# ELI / identifier links — only values present in the source, never invented.
|
| 123 |
+
eli = str(row_map.get("eli") or "").strip()
|
| 124 |
+
if eli:
|
| 125 |
+
fc = _facet_cid("eli", eli)
|
| 126 |
+
if fc not in seen_facets:
|
| 127 |
+
seen_facets.add(fc)
|
| 128 |
+
nodes.append(
|
| 129 |
+
{
|
| 130 |
+
"node_cid": fc,
|
| 131 |
+
"node_type": "facet_eli",
|
| 132 |
+
"entry_cid": "",
|
| 133 |
+
"label": f"eli:{eli}",
|
| 134 |
+
"properties_json": _json({"kind": "eli", "value": eli}),
|
| 135 |
+
"schema_version": SCHEMA_VERSION,
|
| 136 |
+
}
|
| 137 |
+
)
|
| 138 |
+
edges.append(_edge(src, "IDENTIFIED_BY_ELI", fc, "identifier", 1.0, {"eli": eli}))
|
| 139 |
+
ident = str(row_map.get("official_identifier") or row_map.get("identifier") or "").strip()
|
| 140 |
+
if ident and ident != eli:
|
| 141 |
+
fc = _facet_cid("identifier", ident)
|
| 142 |
+
if fc not in seen_facets:
|
| 143 |
+
seen_facets.add(fc)
|
| 144 |
+
nodes.append(
|
| 145 |
+
{
|
| 146 |
+
"node_cid": fc,
|
| 147 |
+
"node_type": "facet_identifier",
|
| 148 |
+
"entry_cid": "",
|
| 149 |
+
"label": f"identifier:{ident}",
|
| 150 |
+
"properties_json": _json({"kind": "identifier", "value": ident}),
|
| 151 |
+
"schema_version": SCHEMA_VERSION,
|
| 152 |
+
}
|
| 153 |
+
)
|
| 154 |
+
edges.append(
|
| 155 |
+
_edge(src, "IDENTIFIED_BY", fc, "identifier", 1.0, {"identifier": ident})
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
law_cid = str(row_map.get("law_cid") or "")
|
| 159 |
+
instrument_id = str(row_map.get("instrument_id") or "")
|
| 160 |
+
if rec.record_type == "article":
|
| 161 |
+
parent = entry_by_instrument.get(instrument_id) or law_cid
|
| 162 |
+
if parent and parent != rec.entry_cid:
|
| 163 |
+
edges.append(
|
| 164 |
+
_edge(
|
| 165 |
+
rec.entry_cid,
|
| 166 |
+
"ARTICLE_OF",
|
| 167 |
+
parent,
|
| 168 |
+
"structural",
|
| 169 |
+
1.0,
|
| 170 |
+
{
|
| 171 |
+
"instrument_id": instrument_id,
|
| 172 |
+
"article_number": row_map.get("article_number"),
|
| 173 |
+
},
|
| 174 |
+
)
|
| 175 |
+
)
|
| 176 |
+
elif law_cid and rec.entry_cid != law_cid:
|
| 177 |
+
# Law-level corpus unit still points at its instrument identity node.
|
| 178 |
+
edges.append(
|
| 179 |
+
_edge(
|
| 180 |
+
rec.entry_cid,
|
| 181 |
+
"HAS_INSTRUMENT",
|
| 182 |
+
law_cid,
|
| 183 |
+
"structural",
|
| 184 |
+
1.0,
|
| 185 |
+
{"instrument_id": instrument_id},
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
for i, neigh in enumerate(neighbors):
|
| 190 |
+
src = cid_by_idx[i]
|
| 191 |
+
for item in neigh:
|
| 192 |
+
if len(item) == 3:
|
| 193 |
+
j, score, terms = item
|
| 194 |
+
else:
|
| 195 |
+
j, score = item[0], item[1]
|
| 196 |
+
terms = []
|
| 197 |
+
tgt = cid_by_idx[int(j)]
|
| 198 |
+
edges.append(
|
| 199 |
+
_edge(
|
| 200 |
+
src,
|
| 201 |
+
"BM25_NEIGHBOR_OF",
|
| 202 |
+
tgt,
|
| 203 |
+
"bm25-okapi",
|
| 204 |
+
float(score),
|
| 205 |
+
{"k": 8, "neighbor_index": int(j)},
|
| 206 |
+
matched_terms=list(terms),
|
| 207 |
+
)
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
nodes_df = pd.DataFrame(nodes).drop_duplicates("node_cid").reset_index(drop=True)
|
| 211 |
+
nodes_df = nodes_df.sort_values(["node_type", "node_cid"]).reset_index(drop=True)
|
| 212 |
+
edges_df = pd.DataFrame(edges)
|
| 213 |
+
if not edges_df.empty:
|
| 214 |
+
edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True)
|
| 215 |
+
edges_df = edges_df.sort_values(["edge_type", "source_cid", "target_cid"]).reset_index(drop=True)
|
| 216 |
+
|
| 217 |
+
node_type = {r["node_cid"]: r["node_type"] for r in nodes_df.to_dict("records")}
|
| 218 |
+
incoming, outgoing = _adjacency(edges_df, node_type)
|
| 219 |
+
return {
|
| 220 |
+
"nodes": nodes_df,
|
| 221 |
+
"edges": edges_df,
|
| 222 |
+
"incoming": incoming,
|
| 223 |
+
"outgoing": outgoing,
|
| 224 |
+
"stats": {
|
| 225 |
+
"n_nodes": int(len(nodes_df)),
|
| 226 |
+
"n_edges": int(len(edges_df)),
|
| 227 |
+
"n_doc_nodes": int(nodes_df["node_type"].isin(["law_entry", "article", "law"]).sum()),
|
| 228 |
+
"n_facet_nodes": int(nodes_df["node_type"].astype(str).str.startswith("facet_").sum()),
|
| 229 |
+
"edge_types": sorted(edges_df["edge_type"].unique().tolist()) if not edges_df.empty else [],
|
| 230 |
+
},
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _json(obj: dict) -> str:
|
| 235 |
+
import json
|
| 236 |
+
|
| 237 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _props_tuple(rec: Any) -> str:
|
| 241 |
+
keys = [
|
| 242 |
+
"record_type",
|
| 243 |
+
"instrument_id",
|
| 244 |
+
"instrument_title",
|
| 245 |
+
"law_cid",
|
| 246 |
+
"article_number",
|
| 247 |
+
"article_title",
|
| 248 |
+
"jurisdiction",
|
| 249 |
+
"language",
|
| 250 |
+
"source_url",
|
| 251 |
+
"snapshot_date",
|
| 252 |
+
"coverage",
|
| 253 |
+
"license",
|
| 254 |
+
"collector",
|
| 255 |
+
"source_id",
|
| 256 |
+
"eli",
|
| 257 |
+
"law_status",
|
| 258 |
+
"source_type",
|
| 259 |
+
]
|
| 260 |
+
d = rec._asdict() if hasattr(rec, "_asdict") else {}
|
| 261 |
+
out = {}
|
| 262 |
+
for k in keys:
|
| 263 |
+
v = d.get(k, "")
|
| 264 |
+
if v is None or (isinstance(v, float) and pd.isna(v)):
|
| 265 |
+
v = ""
|
| 266 |
+
out[k] = str(v)
|
| 267 |
+
return _json(out)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _edge(
|
| 271 |
+
src: str,
|
| 272 |
+
etype: str,
|
| 273 |
+
tgt: str,
|
| 274 |
+
method: str,
|
| 275 |
+
score: float,
|
| 276 |
+
props: dict,
|
| 277 |
+
matched_terms: list[str] | None = None,
|
| 278 |
+
) -> dict[str, Any]:
|
| 279 |
+
import json
|
| 280 |
+
|
| 281 |
+
terms = matched_terms or []
|
| 282 |
+
return {
|
| 283 |
+
"edge_cid": _edge_cid(src, etype, tgt),
|
| 284 |
+
"edge_type": etype,
|
| 285 |
+
"source_cid": src,
|
| 286 |
+
"target_cid": tgt,
|
| 287 |
+
"retrieval_method": method,
|
| 288 |
+
"score": float(score),
|
| 289 |
+
"query_terms_json": json.dumps(terms, ensure_ascii=False, separators=(",", ":")),
|
| 290 |
+
"matched_terms": terms,
|
| 291 |
+
"properties_json": _json({k: v for k, v in props.items() if v is not None}),
|
| 292 |
+
"schema_version": SCHEMA_VERSION,
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _adjacency(edges: pd.DataFrame, node_type: dict[str, str]) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 297 |
+
out_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list)
|
| 298 |
+
in_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list)
|
| 299 |
+
if edges is None or edges.empty:
|
| 300 |
+
return pd.DataFrame(), pd.DataFrame()
|
| 301 |
+
for rec in edges.itertuples(index=False):
|
| 302 |
+
score = float(rec.score) if rec.score == rec.score else float("-inf")
|
| 303 |
+
out_map[rec.source_cid].append((score, rec.target_cid, rec.edge_type, rec.edge_cid))
|
| 304 |
+
in_map[rec.target_cid].append((score, rec.source_cid, rec.edge_type, rec.edge_cid))
|
| 305 |
+
|
| 306 |
+
def pages(mapping: dict[str, list], direction: str) -> pd.DataFrame:
|
| 307 |
+
rows = []
|
| 308 |
+
for node, items in mapping.items():
|
| 309 |
+
items = sorted(items, key=lambda t: (-t[0] if t[0] == t[0] else float("inf"), t[1]))
|
| 310 |
+
total = len(items)
|
| 311 |
+
page_size = ADJ_POINTERS_PER_ROW
|
| 312 |
+
n_pages = max(1, (total + page_size - 1) // page_size)
|
| 313 |
+
for p in range(n_pages):
|
| 314 |
+
chunk = items[p * page_size : (p + 1) * page_size]
|
| 315 |
+
rows.append(
|
| 316 |
+
{
|
| 317 |
+
"direction": direction,
|
| 318 |
+
"node_cid": node,
|
| 319 |
+
"page_index": p,
|
| 320 |
+
"page_count": n_pages,
|
| 321 |
+
"neighbor_count": len(chunk),
|
| 322 |
+
"total_neighbor_count": total,
|
| 323 |
+
"neighbor_cids": [t[1] for t in chunk],
|
| 324 |
+
"neighbor_node_types": [node_type.get(t[1], "") for t in chunk],
|
| 325 |
+
"edge_types": [t[2] for t in chunk],
|
| 326 |
+
"edge_cids": [t[3] for t in chunk],
|
| 327 |
+
"retrieval_methods": ["graph"] * len(chunk),
|
| 328 |
+
"scores": [t[0] if t[0] != float("-inf") else None for t in chunk],
|
| 329 |
+
"schema_version": SCHEMA_VERSION,
|
| 330 |
+
}
|
| 331 |
+
)
|
| 332 |
+
if not rows:
|
| 333 |
+
return pd.DataFrame()
|
| 334 |
+
return pd.DataFrame(rows).sort_values(["node_cid", "page_index"]).reset_index(drop=True)
|
| 335 |
+
|
| 336 |
+
return pages(in_map, "incoming"), pages(out_map, "outgoing")
|
country_laws_ir/mem.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Process / host memory watchdog for large IR builds (DO OOM lesson).
|
| 2 |
+
|
| 3 |
+
Env overrides:
|
| 4 |
+
IR_MEM_WARN_GIB MemAvailable threshold to shed collectors (default 3.5)
|
| 5 |
+
IR_MEM_ABORT_GIB MemAvailable abort floor (default 2.5)
|
| 6 |
+
IR_RSS_ABORT_GIB process RSS hard abort (default 12.0)
|
| 7 |
+
IR_MEM_LOG_EVERY rows between mem logs when callers pass every_n (default 5000)
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import gc
|
| 12 |
+
import os
|
| 13 |
+
import signal
|
| 14 |
+
from datetime import datetime, timezone
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any, Callable
|
| 17 |
+
|
| 18 |
+
DEFAULT_WARN_GIB = 3.5
|
| 19 |
+
DEFAULT_ABORT_AVAIL_GIB = 2.5
|
| 20 |
+
DEFAULT_ABORT_RSS_GIB = 12.0
|
| 21 |
+
DEFAULT_LOG_EVERY = 5000
|
| 22 |
+
|
| 23 |
+
# Prefer shedding zero-article / lean collectors first; protect AT+DK until last.
|
| 24 |
+
DEFAULT_SHED_ORDER: list[tuple[str, tuple[str, ...]]] = [
|
| 25 |
+
("mm", ("collect_mm", "run_collector_cc.sh collect_mm")),
|
| 26 |
+
("th", ("collect_th", "run_collector_cc.sh collect_th")),
|
| 27 |
+
("is-reg", ("collect_is", "is-reg", "run_collector_cc.sh collect_is")),
|
| 28 |
+
("lt", ("collect_lt", "run_collector_cc.sh collect_lt")),
|
| 29 |
+
("kw", ("collect_kw", "run_collector_cc.sh collect_kw")),
|
| 30 |
+
("mt", ("collect_mt", "run_collector_cc.sh collect_mt")),
|
| 31 |
+
("dk", ("collect_dk", "run_collector_cc.sh collect_dk")),
|
| 32 |
+
("at", ("collect_at", "run_collector_cc.sh collect_at", "at_deepen")),
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MemAbort(RuntimeError):
|
| 37 |
+
"""Raised when MemAvailable or RSS crosses hard abort thresholds."""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _env_float(name: str, default: float) -> float:
|
| 41 |
+
raw = os.environ.get(name)
|
| 42 |
+
if raw is None or raw == "":
|
| 43 |
+
return default
|
| 44 |
+
try:
|
| 45 |
+
return float(raw)
|
| 46 |
+
except ValueError:
|
| 47 |
+
return default
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def warn_gib() -> float:
|
| 51 |
+
return _env_float("IR_MEM_WARN_GIB", DEFAULT_WARN_GIB)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def abort_avail_gib() -> float:
|
| 55 |
+
return _env_float("IR_MEM_ABORT_GIB", DEFAULT_ABORT_AVAIL_GIB)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def abort_rss_gib() -> float:
|
| 59 |
+
return _env_float("IR_RSS_ABORT_GIB", DEFAULT_ABORT_RSS_GIB)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def log_every() -> int:
|
| 63 |
+
try:
|
| 64 |
+
return max(1, int(os.environ.get("IR_MEM_LOG_EVERY", DEFAULT_LOG_EVERY)))
|
| 65 |
+
except ValueError:
|
| 66 |
+
return DEFAULT_LOG_EVERY
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def mem_available_gib() -> float:
|
| 70 |
+
try:
|
| 71 |
+
for line in Path("/proc/meminfo").read_text().splitlines():
|
| 72 |
+
if line.startswith("MemAvailable:"):
|
| 73 |
+
return int(line.split()[1]) / 1024 / 1024
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
return -1.0
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def rss_gib(pid: int | None = None) -> float:
|
| 80 |
+
path = Path(f"/proc/{pid or 'self'}/status")
|
| 81 |
+
try:
|
| 82 |
+
for line in path.read_text().splitlines():
|
| 83 |
+
if line.startswith("VmRSS:"):
|
| 84 |
+
return int(line.split()[1]) / 1024 / 1024
|
| 85 |
+
except Exception:
|
| 86 |
+
pass
|
| 87 |
+
return -1.0
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def snapshot(stage: str = "") -> dict[str, Any]:
|
| 91 |
+
return {
|
| 92 |
+
"stage": stage,
|
| 93 |
+
"mem_avail_gib": round(mem_available_gib(), 3),
|
| 94 |
+
"rss_gib": round(rss_gib(), 3),
|
| 95 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def log_mem(stage: str, log: Callable[[str], None] | None = None) -> dict[str, Any]:
|
| 100 |
+
snap = snapshot(stage)
|
| 101 |
+
msg = (
|
| 102 |
+
f"mem stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G "
|
| 103 |
+
f"RSS={snap['rss_gib']:.2f}G"
|
| 104 |
+
)
|
| 105 |
+
if log is not None:
|
| 106 |
+
log(msg)
|
| 107 |
+
else:
|
| 108 |
+
print(f"[{snap['ts']}] {msg}", flush=True)
|
| 109 |
+
return snap
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def discover_pids(*patterns: str) -> list[int]:
|
| 113 |
+
found: list[int] = []
|
| 114 |
+
try:
|
| 115 |
+
for proc in Path("/proc").iterdir():
|
| 116 |
+
if not proc.name.isdigit():
|
| 117 |
+
continue
|
| 118 |
+
try:
|
| 119 |
+
cmd = (proc / "cmdline").read_bytes().replace(b"\x00", b" ").decode(
|
| 120 |
+
"utf-8", "ignore"
|
| 121 |
+
)
|
| 122 |
+
except Exception:
|
| 123 |
+
continue
|
| 124 |
+
if any(p in cmd for p in patterns):
|
| 125 |
+
found.append(int(proc.name))
|
| 126 |
+
except Exception:
|
| 127 |
+
pass
|
| 128 |
+
return found
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def shed_collectors(
|
| 132 |
+
stage: str,
|
| 133 |
+
*,
|
| 134 |
+
warn: float | None = None,
|
| 135 |
+
protect: frozenset[str] | None = None,
|
| 136 |
+
log: Callable[[str], None] | None = None,
|
| 137 |
+
notes: list[dict[str, Any]] | None = None,
|
| 138 |
+
) -> list[dict[str, Any]]:
|
| 139 |
+
"""SIGTERM lean collectors when MemAvailable < warn. Protect AT/DK by default until last."""
|
| 140 |
+
warn = warn_gib() if warn is None else warn
|
| 141 |
+
protect = protect if protect is not None else frozenset({"at", "dk"})
|
| 142 |
+
g = mem_available_gib()
|
| 143 |
+
out: list[dict[str, Any]] = []
|
| 144 |
+
if g < 0 or g >= warn:
|
| 145 |
+
return out
|
| 146 |
+
# First pass: non-protected; second pass: protected if still under warn.
|
| 147 |
+
for pass_protected in (False, True):
|
| 148 |
+
for name, pats in DEFAULT_SHED_ORDER:
|
| 149 |
+
if (name in protect) != pass_protected:
|
| 150 |
+
continue
|
| 151 |
+
pids = discover_pids(*pats)
|
| 152 |
+
for pid in pids:
|
| 153 |
+
try:
|
| 154 |
+
os.kill(pid, 0)
|
| 155 |
+
except ProcessLookupError:
|
| 156 |
+
continue
|
| 157 |
+
except PermissionError:
|
| 158 |
+
continue
|
| 159 |
+
try:
|
| 160 |
+
os.kill(pid, signal.SIGTERM)
|
| 161 |
+
note = {
|
| 162 |
+
"stage": stage,
|
| 163 |
+
"name": name,
|
| 164 |
+
"pid": pid,
|
| 165 |
+
"mem_before": round(g, 2),
|
| 166 |
+
"protected_pass": pass_protected,
|
| 167 |
+
}
|
| 168 |
+
out.append(note)
|
| 169 |
+
if notes is not None:
|
| 170 |
+
notes.append(note)
|
| 171 |
+
msg = f"SIGTERM collector {name} pid={pid} mem={g:.2f}G stage={stage}"
|
| 172 |
+
if log:
|
| 173 |
+
log(msg)
|
| 174 |
+
else:
|
| 175 |
+
print(msg, flush=True)
|
| 176 |
+
except ProcessLookupError:
|
| 177 |
+
pass
|
| 178 |
+
except Exception as exc:
|
| 179 |
+
msg = f"SIGTERM failed {name} pid={pid}: {exc}"
|
| 180 |
+
if log:
|
| 181 |
+
log(msg)
|
| 182 |
+
else:
|
| 183 |
+
print(msg, flush=True)
|
| 184 |
+
g = mem_available_gib()
|
| 185 |
+
if g >= warn:
|
| 186 |
+
return out
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def checkpoint(
|
| 191 |
+
stage: str,
|
| 192 |
+
*,
|
| 193 |
+
row: int | None = None,
|
| 194 |
+
every_n: int | None = None,
|
| 195 |
+
shed: bool = True,
|
| 196 |
+
abort: bool = True,
|
| 197 |
+
log: Callable[[str], None] | None = None,
|
| 198 |
+
notes: list[dict[str, Any]] | None = None,
|
| 199 |
+
) -> dict[str, Any]:
|
| 200 |
+
"""Periodic mem log + optional shed + hard abort.
|
| 201 |
+
|
| 202 |
+
Call every N rows with ``row`` set; always logs when row is None.
|
| 203 |
+
"""
|
| 204 |
+
every = every_n if every_n is not None else log_every()
|
| 205 |
+
if row is not None and row != 0 and row % every != 0:
|
| 206 |
+
# Still enforce hard abort cheaply on every call.
|
| 207 |
+
rss = rss_gib()
|
| 208 |
+
avail = mem_available_gib()
|
| 209 |
+
if abort and rss >= abort_rss_gib():
|
| 210 |
+
raise MemAbort(f"RSS_ABORT stage={stage} rss={rss:.2f}G > {abort_rss_gib()}G")
|
| 211 |
+
if abort and 0 <= avail < abort_avail_gib():
|
| 212 |
+
if shed:
|
| 213 |
+
shed_collectors(stage, log=log, notes=notes)
|
| 214 |
+
avail = mem_available_gib()
|
| 215 |
+
if 0 <= avail < abort_avail_gib():
|
| 216 |
+
raise MemAbort(
|
| 217 |
+
f"MEM_ABORT stage={stage} MemAvailable={avail:.2f}G < {abort_avail_gib()}G"
|
| 218 |
+
)
|
| 219 |
+
return snapshot(stage)
|
| 220 |
+
|
| 221 |
+
snap = log_mem(stage if row is None else f"{stage}@{row}", log=log)
|
| 222 |
+
if shed and 0 <= snap["mem_avail_gib"] < warn_gib():
|
| 223 |
+
shed_collectors(stage, log=log, notes=notes)
|
| 224 |
+
snap = log_mem(f"{stage}_after_shed", log=log)
|
| 225 |
+
gc.collect()
|
| 226 |
+
if abort:
|
| 227 |
+
if snap["rss_gib"] >= abort_rss_gib():
|
| 228 |
+
raise MemAbort(
|
| 229 |
+
f"RSS_ABORT stage={stage} rss={snap['rss_gib']:.2f}G > {abort_rss_gib()}G"
|
| 230 |
+
)
|
| 231 |
+
if 0 <= snap["mem_avail_gib"] < abort_avail_gib():
|
| 232 |
+
raise MemAbort(
|
| 233 |
+
f"MEM_ABORT stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G "
|
| 234 |
+
f"< {abort_avail_gib()}G"
|
| 235 |
+
)
|
| 236 |
+
return snap
|
country_laws_ir/normalize.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
|
| 2 |
+
|
| 3 |
+
Prefer article/section as the retrieval unit; fall back to law-level when
|
| 4 |
+
articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE
|
| 5 |
+
GraphRAG. Never invent legal text or identifiers.
|
| 6 |
+
|
| 7 |
+
Public Hub reads only (token=False). No Hugging Face token is read or stored.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import re
|
| 15 |
+
import unicodedata
|
| 16 |
+
from collections import Counter
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from huggingface_hub import dataset_info, hf_hub_download
|
| 22 |
+
|
| 23 |
+
from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 24 |
+
from .auth import configure_hf, public_token
|
| 25 |
+
from .cidutil import cid_of_json, sha256_file, sha256_hex
|
| 26 |
+
from .schema import SchemaError, validate_articles, validate_laws
|
| 27 |
+
|
| 28 |
+
_WS_RE = re.compile(r"\s+", re.UNICODE)
|
| 29 |
+
COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def normalize_text(value: Any) -> str:
|
| 33 |
+
if value is None or (isinstance(value, float) and pd.isna(value)):
|
| 34 |
+
return ""
|
| 35 |
+
text = unicodedata.normalize("NFKC", str(value))
|
| 36 |
+
text = _WS_RE.sub(" ", text).strip()
|
| 37 |
+
return text
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _s(value: Any) -> str:
|
| 41 |
+
return normalize_text(value)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _download(repo_id: str, filename: str, cache_dir: Path) -> Path:
|
| 45 |
+
configure_hf()
|
| 46 |
+
path = hf_hub_download(
|
| 47 |
+
repo_id=repo_id,
|
| 48 |
+
filename=filename,
|
| 49 |
+
repo_type="dataset",
|
| 50 |
+
token=public_token(),
|
| 51 |
+
cache_dir=str(cache_dir / "hf"),
|
| 52 |
+
)
|
| 53 |
+
return Path(path)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _resolve_local_parquet(root: Path, name: str) -> Path:
|
| 57 |
+
"""Accept either <root>/data/<name>.parquet or <root>/<name>.parquet."""
|
| 58 |
+
for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"):
|
| 59 |
+
if cand.is_file():
|
| 60 |
+
return cand
|
| 61 |
+
raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 65 |
+
"""Load a local country-laws pack (filtered preprocess layout)."""
|
| 66 |
+
local_dir = Path(local_dir).resolve()
|
| 67 |
+
laws_path = _resolve_local_parquet(local_dir, "laws")
|
| 68 |
+
articles_path = _resolve_local_parquet(local_dir, "articles")
|
| 69 |
+
laws = pd.read_parquet(laws_path)
|
| 70 |
+
articles = pd.read_parquet(articles_path)
|
| 71 |
+
validate_laws(laws)
|
| 72 |
+
validate_articles(articles)
|
| 73 |
+
pack_meta: dict[str, Any] = {}
|
| 74 |
+
meta_path = local_dir / "pack_meta.json"
|
| 75 |
+
if meta_path.is_file():
|
| 76 |
+
try:
|
| 77 |
+
pack_meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 78 |
+
except Exception:
|
| 79 |
+
pack_meta = {}
|
| 80 |
+
source_dataset = (
|
| 81 |
+
pack_meta.get("source_dataset")
|
| 82 |
+
or pack_meta.get("repo")
|
| 83 |
+
or f"local/{local_dir.name}"
|
| 84 |
+
)
|
| 85 |
+
source_revision = str(
|
| 86 |
+
pack_meta.get("source_revision")
|
| 87 |
+
or pack_meta.get("revision")
|
| 88 |
+
or f"local:{local_dir.name}"
|
| 89 |
+
)
|
| 90 |
+
meta = {
|
| 91 |
+
"source_dataset": source_dataset,
|
| 92 |
+
"source_revision": source_revision,
|
| 93 |
+
"laws_path": str(laws_path),
|
| 94 |
+
"articles_path": str(articles_path),
|
| 95 |
+
"laws_sha256": sha256_file(laws_path),
|
| 96 |
+
"articles_sha256": sha256_file(articles_path),
|
| 97 |
+
"n_laws_source": int(len(laws)),
|
| 98 |
+
"n_articles_source": int(len(articles)),
|
| 99 |
+
"laws_columns": list(map(str, laws.columns)),
|
| 100 |
+
"articles_columns": list(map(str, articles.columns)),
|
| 101 |
+
"article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None,
|
| 102 |
+
"schema_surprises": _schema_surprises(laws, articles),
|
| 103 |
+
"local_source_dir": str(local_dir),
|
| 104 |
+
"pack_meta": pack_meta,
|
| 105 |
+
}
|
| 106 |
+
return laws, articles, meta
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 110 |
+
"""Load Hub dataset id OR a local directory with laws/articles parquet."""
|
| 111 |
+
local = Path(repo_id)
|
| 112 |
+
if local.is_dir() and (
|
| 113 |
+
(local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file()
|
| 114 |
+
):
|
| 115 |
+
return load_local_source(local)
|
| 116 |
+
|
| 117 |
+
configure_hf()
|
| 118 |
+
os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
|
| 119 |
+
info = dataset_info(repo_id, token=public_token())
|
| 120 |
+
revision = info.sha
|
| 121 |
+
laws_path = _download(repo_id, "data/laws.parquet", cache_dir)
|
| 122 |
+
articles_path = _download(repo_id, "data/articles.parquet", cache_dir)
|
| 123 |
+
laws = pd.read_parquet(laws_path)
|
| 124 |
+
articles = pd.read_parquet(articles_path)
|
| 125 |
+
validate_laws(laws)
|
| 126 |
+
validate_articles(articles)
|
| 127 |
+
meta = {
|
| 128 |
+
"source_dataset": repo_id,
|
| 129 |
+
"source_revision": revision,
|
| 130 |
+
"laws_path": str(laws_path),
|
| 131 |
+
"articles_path": str(articles_path),
|
| 132 |
+
"laws_sha256": sha256_file(laws_path),
|
| 133 |
+
"articles_sha256": sha256_file(articles_path),
|
| 134 |
+
"n_laws_source": int(len(laws)),
|
| 135 |
+
"n_articles_source": int(len(articles)),
|
| 136 |
+
"laws_columns": list(map(str, laws.columns)),
|
| 137 |
+
"articles_columns": list(map(str, articles.columns)),
|
| 138 |
+
"article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None,
|
| 139 |
+
"schema_surprises": _schema_surprises(laws, articles),
|
| 140 |
+
}
|
| 141 |
+
return laws, articles, meta
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _schema_surprises(laws: pd.DataFrame, articles: pd.DataFrame) -> list[str]:
|
| 145 |
+
notes: list[str] = []
|
| 146 |
+
if articles is None or articles.empty:
|
| 147 |
+
notes.append("articles.parquet has 0 rows; corpus falls back to law-level units")
|
| 148 |
+
if "article_count" in laws.columns:
|
| 149 |
+
dtype = str(laws["article_count"].dtype)
|
| 150 |
+
notes.append(f"laws.article_count dtype={dtype}")
|
| 151 |
+
try:
|
| 152 |
+
if int((laws["article_count"].fillna(0) == 0).sum()) == len(laws):
|
| 153 |
+
notes.append("every law has article_count=0")
|
| 154 |
+
except Exception:
|
| 155 |
+
pass
|
| 156 |
+
for col in ("date", "date_issued"):
|
| 157 |
+
if col in laws.columns and laws[col].isna().all():
|
| 158 |
+
notes.append(f"laws.{col} is entirely null")
|
| 159 |
+
if "eli" in laws.columns:
|
| 160 |
+
n_eli = int(laws["eli"].notna().sum()) if hasattr(laws["eli"], "notna") else 0
|
| 161 |
+
notes.append(f"laws.eli non-null={n_eli}/{len(laws)}")
|
| 162 |
+
if "language" in laws.columns:
|
| 163 |
+
langs = sorted({str(x) for x in laws["language"].dropna().unique()})
|
| 164 |
+
notes.append(f"laws.language values={langs}")
|
| 165 |
+
return notes
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _parse_meta(raw: str) -> dict[str, Any]:
|
| 169 |
+
if not raw:
|
| 170 |
+
return {}
|
| 171 |
+
try:
|
| 172 |
+
obj = json.loads(raw)
|
| 173 |
+
return obj if isinstance(obj, dict) else {}
|
| 174 |
+
except Exception:
|
| 175 |
+
return {}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _law_cid(instrument_id: str, instrument_title: str, jurisdiction: str, language: str, source_dataset: str) -> str:
|
| 179 |
+
identity = {
|
| 180 |
+
"schema": LAW_IDENTITY_SCHEMA,
|
| 181 |
+
"source_dataset": source_dataset,
|
| 182 |
+
"instrument_id": instrument_id,
|
| 183 |
+
"instrument_title": instrument_title,
|
| 184 |
+
"jurisdiction": jurisdiction,
|
| 185 |
+
"language": language,
|
| 186 |
+
}
|
| 187 |
+
return cid_of_json(identity)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _entry_cid(record: dict[str, Any]) -> str:
|
| 191 |
+
identity = {
|
| 192 |
+
"schema": ENTRY_IDENTITY_SCHEMA,
|
| 193 |
+
"record_type": record["record_type"],
|
| 194 |
+
"source_dataset": record["source_dataset"],
|
| 195 |
+
"instrument_id": record["instrument_id"],
|
| 196 |
+
"article_number": record.get("article_number") or "",
|
| 197 |
+
"article_title": record.get("article_title") or "",
|
| 198 |
+
"body_sha256": record["body_sha256"],
|
| 199 |
+
"language": record.get("language") or "",
|
| 200 |
+
"jurisdiction": record.get("jurisdiction") or "",
|
| 201 |
+
"source_url": record.get("source_url") or "",
|
| 202 |
+
}
|
| 203 |
+
return cid_of_json(identity)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _row_get(row: pd.Series, col: str, default: str = "") -> str:
|
| 207 |
+
if col not in row.index:
|
| 208 |
+
return default
|
| 209 |
+
return _s(row[col])
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _coverage_from(
|
| 213 |
+
row: pd.Series,
|
| 214 |
+
meta: dict[str, Any],
|
| 215 |
+
articles_empty: bool,
|
| 216 |
+
sparse_fallback: bool = False,
|
| 217 |
+
) -> str:
|
| 218 |
+
for key in ("coverage", "coverage_note"):
|
| 219 |
+
if key in meta and meta[key]:
|
| 220 |
+
return normalize_text(meta[key])
|
| 221 |
+
status = normalize_text(meta.get("article_extraction_status") or "")
|
| 222 |
+
if sparse_fallback:
|
| 223 |
+
note = "law-level (article coverage below 10% of laws; sparse articles table)"
|
| 224 |
+
if status:
|
| 225 |
+
return f"{note}; extraction_status={status}"
|
| 226 |
+
return note
|
| 227 |
+
if articles_empty:
|
| 228 |
+
if status:
|
| 229 |
+
return f"law-level (articles empty or unavailable in source snapshot); extraction_status={status}"
|
| 230 |
+
return "law-level (articles empty or unavailable in source snapshot)"
|
| 231 |
+
if status:
|
| 232 |
+
return f"article-level; extraction_status={status}"
|
| 233 |
+
return "article-level"
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, Any]) -> str:
|
| 237 |
+
for col in ("retrieved_at", "date_issued", "date"):
|
| 238 |
+
val = _row_get(row, col)
|
| 239 |
+
if val:
|
| 240 |
+
return val[:10] if len(val) >= 10 and val[4] == "-" else val
|
| 241 |
+
for key in ("snapshot_date", "retrieved_at"):
|
| 242 |
+
if key in meta and meta[key]:
|
| 243 |
+
return normalize_text(str(meta[key]))[:10]
|
| 244 |
+
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 245 |
+
for key in ("snapshot_date", "retrieved_at"):
|
| 246 |
+
if nested.get(key):
|
| 247 |
+
return normalize_text(str(nested[key]))[:10]
|
| 248 |
+
return ""
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _collector(meta: dict[str, Any], source_dataset: str) -> str:
|
| 252 |
+
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 253 |
+
for blob in (meta, nested):
|
| 254 |
+
for key in ("collector", "collector_id", "harvester"):
|
| 255 |
+
if blob.get(key):
|
| 256 |
+
return normalize_text(blob[key])
|
| 257 |
+
return f"{COLLECTOR_DEFAULT} ({source_dataset})"
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def laws_index(laws: pd.DataFrame, source_dataset: str) -> dict[str, dict[str, Any]]:
|
| 261 |
+
"""Map instrument_id -> law facet fields (always computed; not always corpus units)."""
|
| 262 |
+
out: dict[str, dict[str, Any]] = {}
|
| 263 |
+
for _, row in laws.iterrows():
|
| 264 |
+
instrument_id = _row_get(row, "id")
|
| 265 |
+
instrument_title = _row_get(row, "title")
|
| 266 |
+
jurisdiction = _row_get(row, "jurisdiction") or _row_get(row, "country")
|
| 267 |
+
language = _row_get(row, "language")
|
| 268 |
+
law_cid = _law_cid(instrument_id, instrument_title, jurisdiction, language, source_dataset)
|
| 269 |
+
meta = _parse_meta(_row_get(row, "metadata_json"))
|
| 270 |
+
out[instrument_id] = {
|
| 271 |
+
"instrument_id": instrument_id,
|
| 272 |
+
"instrument_title": instrument_title,
|
| 273 |
+
"law_cid": law_cid,
|
| 274 |
+
"jurisdiction": jurisdiction,
|
| 275 |
+
"language": language,
|
| 276 |
+
"source_url": _row_get(row, "source_url"),
|
| 277 |
+
"license": _row_get(row, "license"),
|
| 278 |
+
"eli": _row_get(row, "eli"),
|
| 279 |
+
"identifier": _row_get(row, "identifier") or instrument_id,
|
| 280 |
+
"official_identifier": _row_get(row, "official_identifier"),
|
| 281 |
+
"source_type": _row_get(row, "source_type"),
|
| 282 |
+
"country": _row_get(row, "country"),
|
| 283 |
+
"law_status": _row_get(row, "law_status"),
|
| 284 |
+
"body": _row_get(row, "text"),
|
| 285 |
+
"metadata": meta,
|
| 286 |
+
"row": row,
|
| 287 |
+
}
|
| 288 |
+
return out
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _base_record(
|
| 292 |
+
*,
|
| 293 |
+
record_type: str,
|
| 294 |
+
source_dataset: str,
|
| 295 |
+
source_revision: str,
|
| 296 |
+
instrument_id: str,
|
| 297 |
+
instrument_title: str,
|
| 298 |
+
law_cid: str,
|
| 299 |
+
article_number: str,
|
| 300 |
+
article_title: str,
|
| 301 |
+
body: str,
|
| 302 |
+
jurisdiction: str,
|
| 303 |
+
language: str,
|
| 304 |
+
source_url: str,
|
| 305 |
+
snapshot_date: str,
|
| 306 |
+
coverage: str,
|
| 307 |
+
license_expr: str,
|
| 308 |
+
collector: str,
|
| 309 |
+
source_id: str,
|
| 310 |
+
extra: dict[str, Any] | None = None,
|
| 311 |
+
) -> dict[str, Any]:
|
| 312 |
+
title_for_bm25 = article_title if record_type == "article" and article_title else instrument_title
|
| 313 |
+
rec: dict[str, Any] = {
|
| 314 |
+
"record_type": record_type,
|
| 315 |
+
"source_dataset": source_dataset,
|
| 316 |
+
"source_revision": source_revision,
|
| 317 |
+
"source_id": source_id,
|
| 318 |
+
"instrument_id": instrument_id,
|
| 319 |
+
"instrument_title": instrument_title,
|
| 320 |
+
"law_id": instrument_id,
|
| 321 |
+
"law_cid": law_cid,
|
| 322 |
+
"article_number": article_number,
|
| 323 |
+
"article_title": article_title,
|
| 324 |
+
"title": title_for_bm25,
|
| 325 |
+
"body": body,
|
| 326 |
+
"body_sha256": sha256_hex(body.encode("utf-8")),
|
| 327 |
+
"jurisdiction": jurisdiction,
|
| 328 |
+
"language": language,
|
| 329 |
+
"source_url": source_url,
|
| 330 |
+
"snapshot_date": snapshot_date,
|
| 331 |
+
"coverage": coverage,
|
| 332 |
+
"license": license_expr,
|
| 333 |
+
"collector": collector,
|
| 334 |
+
"schema_version": SCHEMA_VERSION,
|
| 335 |
+
"entry_identity_schema_version": ENTRY_IDENTITY_SCHEMA,
|
| 336 |
+
}
|
| 337 |
+
if extra:
|
| 338 |
+
rec.update(extra)
|
| 339 |
+
rec["entry_cid"] = _entry_cid(rec)
|
| 340 |
+
rec["title_length"] = len(title_for_bm25)
|
| 341 |
+
rec["body_length"] = len(body)
|
| 342 |
+
rec["document_length"] = len(title_for_bm25) + len(body)
|
| 343 |
+
return rec
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def build_corpus(
|
| 347 |
+
laws: pd.DataFrame,
|
| 348 |
+
articles: pd.DataFrame,
|
| 349 |
+
source_meta: dict[str, Any],
|
| 350 |
+
) -> tuple[pd.DataFrame, dict[str, Any]]:
|
| 351 |
+
source_dataset = source_meta["source_dataset"]
|
| 352 |
+
source_revision = source_meta["source_revision"]
|
| 353 |
+
law_map = laws_index(laws, source_dataset)
|
| 354 |
+
articles_empty = articles is None or articles.empty
|
| 355 |
+
n_laws = int(len(laws))
|
| 356 |
+
n_arts = int(len(articles) if articles is not None else 0)
|
| 357 |
+
article_law_coverage = (n_arts / n_laws) if n_laws else 0.0
|
| 358 |
+
# Empty articles.parquet already falls back. Also fall back when the table is
|
| 359 |
+
# present but covers under ~10% as many rows as laws (Estonia: 2 vs 3484).
|
| 360 |
+
sparse_fallback = (not articles_empty) and article_law_coverage < 0.10
|
| 361 |
+
use_articles = (not articles_empty) and not sparse_fallback
|
| 362 |
+
|
| 363 |
+
extraction_statuses: Counter[str] = Counter()
|
| 364 |
+
for parent in law_map.values():
|
| 365 |
+
st = normalize_text(parent["metadata"].get("article_extraction_status") or "")
|
| 366 |
+
if st:
|
| 367 |
+
extraction_statuses[st] += 1
|
| 368 |
+
|
| 369 |
+
report: dict[str, Any] = {
|
| 370 |
+
"source_dataset": source_dataset,
|
| 371 |
+
"source_revision": source_revision,
|
| 372 |
+
"laws_sha256": source_meta.get("laws_sha256"),
|
| 373 |
+
"articles_sha256": source_meta.get("articles_sha256"),
|
| 374 |
+
"n_laws_in": int(len(laws)),
|
| 375 |
+
"n_articles_in": int(len(articles) if articles is not None else 0),
|
| 376 |
+
"unit": "article" if use_articles else "law",
|
| 377 |
+
"article_law_coverage": article_law_coverage,
|
| 378 |
+
"sparse_article_fallback": sparse_fallback,
|
| 379 |
+
"drops": {
|
| 380 |
+
"empty_body": 0,
|
| 381 |
+
"missing_instrument": 0,
|
| 382 |
+
"duplicate_cid": 0,
|
| 383 |
+
"duplicate_source_kept_first": 0,
|
| 384 |
+
},
|
| 385 |
+
"drop_samples": {
|
| 386 |
+
"empty_body": [],
|
| 387 |
+
"missing_instrument": [],
|
| 388 |
+
"duplicate_cid": [],
|
| 389 |
+
},
|
| 390 |
+
"language_breakdown": {},
|
| 391 |
+
"quality_flags": {},
|
| 392 |
+
"schema_surprises": list(source_meta.get("schema_surprises") or []),
|
| 393 |
+
"n_out": 0,
|
| 394 |
+
"never_invented_legal_text": True,
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
entries: list[dict[str, Any]] = []
|
| 398 |
+
|
| 399 |
+
if sparse_fallback:
|
| 400 |
+
report["schema_surprises"].append(
|
| 401 |
+
f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
if use_articles:
|
| 405 |
+
for _, row in articles.iterrows():
|
| 406 |
+
source_id = _row_get(row, "id")
|
| 407 |
+
instrument_id = _row_get(row, "law_id")
|
| 408 |
+
body = _row_get(row, "text")
|
| 409 |
+
article_title = _row_get(row, "title")
|
| 410 |
+
article_number = _row_get(row, "article_number")
|
| 411 |
+
if not body:
|
| 412 |
+
report["drops"]["empty_body"] += 1
|
| 413 |
+
if len(report["drop_samples"]["empty_body"]) < 20:
|
| 414 |
+
report["drop_samples"]["empty_body"].append(source_id)
|
| 415 |
+
continue
|
| 416 |
+
parent = law_map.get(instrument_id)
|
| 417 |
+
if not parent:
|
| 418 |
+
report["drops"]["missing_instrument"] += 1
|
| 419 |
+
if len(report["drop_samples"]["missing_instrument"]) < 20:
|
| 420 |
+
report["drop_samples"]["missing_instrument"].append(
|
| 421 |
+
{"article_id": source_id, "law_id": instrument_id}
|
| 422 |
+
)
|
| 423 |
+
continue
|
| 424 |
+
meta = parent["metadata"]
|
| 425 |
+
art_meta = _parse_meta(_row_get(row, "metadata_json"))
|
| 426 |
+
merged_meta = {**meta, **art_meta}
|
| 427 |
+
entries.append(
|
| 428 |
+
_base_record(
|
| 429 |
+
record_type="article",
|
| 430 |
+
source_dataset=source_dataset,
|
| 431 |
+
source_revision=source_revision,
|
| 432 |
+
instrument_id=instrument_id,
|
| 433 |
+
instrument_title=parent["instrument_title"],
|
| 434 |
+
law_cid=parent["law_cid"],
|
| 435 |
+
article_number=article_number,
|
| 436 |
+
article_title=article_title,
|
| 437 |
+
body=body,
|
| 438 |
+
jurisdiction=parent["jurisdiction"],
|
| 439 |
+
language=parent["language"] or _row_get(row, "language"),
|
| 440 |
+
source_url=_row_get(row, "source_url") or parent["source_url"],
|
| 441 |
+
snapshot_date=_snapshot_date(parent["row"], merged_meta, source_meta),
|
| 442 |
+
coverage=_coverage_from(parent["row"], merged_meta, articles_empty=False),
|
| 443 |
+
license_expr=parent["license"],
|
| 444 |
+
collector=_collector(merged_meta, source_dataset),
|
| 445 |
+
source_id=source_id,
|
| 446 |
+
extra={
|
| 447 |
+
"eli": parent["eli"],
|
| 448 |
+
"identifier": parent["identifier"],
|
| 449 |
+
"official_identifier": parent["official_identifier"],
|
| 450 |
+
"source_type": parent["source_type"],
|
| 451 |
+
"country": parent["country"],
|
| 452 |
+
"law_status": parent["law_status"],
|
| 453 |
+
"parent_law_id": instrument_id,
|
| 454 |
+
"article_id": source_id,
|
| 455 |
+
},
|
| 456 |
+
)
|
| 457 |
+
)
|
| 458 |
+
else:
|
| 459 |
+
for instrument_id, parent in law_map.items():
|
| 460 |
+
body = parent["body"]
|
| 461 |
+
if not body:
|
| 462 |
+
report["drops"]["empty_body"] += 1
|
| 463 |
+
if len(report["drop_samples"]["empty_body"]) < 20:
|
| 464 |
+
report["drop_samples"]["empty_body"].append(instrument_id)
|
| 465 |
+
continue
|
| 466 |
+
meta = parent["metadata"]
|
| 467 |
+
entries.append(
|
| 468 |
+
_base_record(
|
| 469 |
+
record_type="law",
|
| 470 |
+
source_dataset=source_dataset,
|
| 471 |
+
source_revision=source_revision,
|
| 472 |
+
instrument_id=instrument_id,
|
| 473 |
+
instrument_title=parent["instrument_title"],
|
| 474 |
+
law_cid=parent["law_cid"],
|
| 475 |
+
article_number="",
|
| 476 |
+
article_title="",
|
| 477 |
+
body=body,
|
| 478 |
+
jurisdiction=parent["jurisdiction"],
|
| 479 |
+
language=parent["language"],
|
| 480 |
+
source_url=parent["source_url"],
|
| 481 |
+
snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
|
| 482 |
+
coverage=_coverage_from(
|
| 483 |
+
parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback
|
| 484 |
+
),
|
| 485 |
+
license_expr=parent["license"],
|
| 486 |
+
collector=_collector(meta, source_dataset),
|
| 487 |
+
source_id=instrument_id,
|
| 488 |
+
extra={
|
| 489 |
+
"eli": parent["eli"],
|
| 490 |
+
"identifier": parent["identifier"],
|
| 491 |
+
"official_identifier": parent["official_identifier"],
|
| 492 |
+
"source_type": parent["source_type"],
|
| 493 |
+
"country": parent["country"],
|
| 494 |
+
"law_status": parent["law_status"],
|
| 495 |
+
"parent_law_id": "",
|
| 496 |
+
"article_id": "",
|
| 497 |
+
},
|
| 498 |
+
)
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
entries.sort(
|
| 502 |
+
key=lambda r: (
|
| 503 |
+
r["instrument_id"],
|
| 504 |
+
r.get("article_number") or "",
|
| 505 |
+
r["source_id"],
|
| 506 |
+
)
|
| 507 |
+
)
|
| 508 |
+
n_before = len(entries)
|
| 509 |
+
seen: set[str] = set()
|
| 510 |
+
deduped: list[dict[str, Any]] = []
|
| 511 |
+
for rec in entries:
|
| 512 |
+
cid = rec["entry_cid"]
|
| 513 |
+
if cid in seen:
|
| 514 |
+
report["drops"]["duplicate_cid"] += 1
|
| 515 |
+
report["drops"]["duplicate_source_kept_first"] += 1
|
| 516 |
+
if len(report["drop_samples"]["duplicate_cid"]) < 20:
|
| 517 |
+
report["drop_samples"]["duplicate_cid"].append(rec["source_id"])
|
| 518 |
+
continue
|
| 519 |
+
seen.add(cid)
|
| 520 |
+
deduped.append(rec)
|
| 521 |
+
for i, rec in enumerate(deduped):
|
| 522 |
+
rec["document_index"] = i
|
| 523 |
+
rec["corpus_index"] = i
|
| 524 |
+
|
| 525 |
+
df = pd.DataFrame(deduped)
|
| 526 |
+
if not df.empty and df["entry_cid"].duplicated().any():
|
| 527 |
+
raise SchemaError("Duplicate entry_cid remained after dedupe")
|
| 528 |
+
report["n_before_dedupe"] = n_before
|
| 529 |
+
report["n_out"] = int(len(df))
|
| 530 |
+
report["n_dropped_total"] = (
|
| 531 |
+
report["drops"]["empty_body"]
|
| 532 |
+
+ report["drops"]["missing_instrument"]
|
| 533 |
+
+ report["drops"]["duplicate_cid"]
|
| 534 |
+
)
|
| 535 |
+
if not df.empty:
|
| 536 |
+
report["language_breakdown"] = {
|
| 537 |
+
str(k): int(v) for k, v in df["language"].fillna("").value_counts().items()
|
| 538 |
+
}
|
| 539 |
+
report["record_type_breakdown"] = {
|
| 540 |
+
str(k): int(v) for k, v in df["record_type"].value_counts().items()
|
| 541 |
+
}
|
| 542 |
+
report["jurisdiction_breakdown"] = {
|
| 543 |
+
str(k): int(v) for k, v in df["jurisdiction"].fillna("").value_counts().items()
|
| 544 |
+
}
|
| 545 |
+
snapshot_dates = sorted({str(x) for x in df["snapshot_date"].fillna("") if str(x)})
|
| 546 |
+
report["snapshot_dates"] = snapshot_dates
|
| 547 |
+
else:
|
| 548 |
+
report["language_breakdown"] = {}
|
| 549 |
+
report["record_type_breakdown"] = {}
|
| 550 |
+
report["jurisdiction_breakdown"] = {}
|
| 551 |
+
report["snapshot_dates"] = []
|
| 552 |
+
|
| 553 |
+
all_article_count_zero = False
|
| 554 |
+
if "article_count" in laws.columns and len(laws):
|
| 555 |
+
try:
|
| 556 |
+
all_article_count_zero = int((laws["article_count"].fillna(0) == 0).sum()) == len(laws)
|
| 557 |
+
except Exception:
|
| 558 |
+
all_article_count_zero = False
|
| 559 |
+
|
| 560 |
+
report["quality_flags"] = {
|
| 561 |
+
"articles_table_empty": bool(articles_empty),
|
| 562 |
+
"sparse_article_fallback": bool(sparse_fallback),
|
| 563 |
+
"article_law_coverage": article_law_coverage,
|
| 564 |
+
"all_source_article_counts_zero": all_article_count_zero,
|
| 565 |
+
"article_extraction_status_counts": dict(extraction_statuses),
|
| 566 |
+
"missing_date": bool("date" in laws.columns and laws["date"].isna().all()) if len(laws) else False,
|
| 567 |
+
"missing_date_issued": bool("date_issued" in laws.columns and laws["date_issued"].isna().all()) if len(laws) else False,
|
| 568 |
+
"eli_present": bool("eli" in laws.columns and laws["eli"].notna().any()) if len(laws) else False,
|
| 569 |
+
"never_invented_legal_text": True,
|
| 570 |
+
"empty_bodies_dropped": report["drops"]["empty_body"],
|
| 571 |
+
"duplicate_cids_dropped": report["drops"]["duplicate_cid"],
|
| 572 |
+
}
|
| 573 |
+
df.attrs["normalization_report"] = report
|
| 574 |
+
return df, report
|
country_laws_ir/package.py
ADDED
|
@@ -0,0 +1,877 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write country-laws-ir-graphrag/v1 thin-client layout (SkillCenter / publicus-ir family)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import gc
|
| 6 |
+
import json
|
| 7 |
+
import pickle
|
| 8 |
+
import shutil
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from . import LAYOUT_FAMILY, MAX_ROWS_PER_FILE, SCHEMA_VERSION, __version__
|
| 15 |
+
from .catalog import target_repo
|
| 16 |
+
from .cidutil import file_descriptor
|
| 17 |
+
from .parquet_io import write_parquet, write_sharded
|
| 18 |
+
|
| 19 |
+
ADJ_POINTERS_PER_ROW = 4096
|
| 20 |
+
ADJ_POINTERS_PER_SHARD = 8192
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _index_df(rows: list[dict[str, Any]]) -> pd.DataFrame:
|
| 24 |
+
return pd.DataFrame(rows)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def package_release(
|
| 28 |
+
out: Path,
|
| 29 |
+
corpus: pd.DataFrame,
|
| 30 |
+
bm25: dict[str, Any],
|
| 31 |
+
graph: dict[str, Any],
|
| 32 |
+
vectors: dict[str, Any],
|
| 33 |
+
source_meta: dict[str, Any],
|
| 34 |
+
country: dict[str, Any],
|
| 35 |
+
code_root: Path,
|
| 36 |
+
normalization_report: dict[str, Any] | None = None,
|
| 37 |
+
) -> dict[str, Any]:
|
| 38 |
+
if out.exists():
|
| 39 |
+
shutil.rmtree(out)
|
| 40 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
indexes_dir = out / "indexes"
|
| 42 |
+
indexes_dir.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
|
| 44 |
+
corpus_idx = write_sharded(
|
| 45 |
+
corpus,
|
| 46 |
+
out / "data" / "corpus",
|
| 47 |
+
"data/corpus",
|
| 48 |
+
kind="corpus",
|
| 49 |
+
key_col="entry_cid",
|
| 50 |
+
index_col="document_index",
|
| 51 |
+
)
|
| 52 |
+
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 53 |
+
|
| 54 |
+
bm25_doc_idx = write_sharded(
|
| 55 |
+
bm25["documents"],
|
| 56 |
+
out / "data" / "bm25" / "documents",
|
| 57 |
+
"data/bm25/documents",
|
| 58 |
+
kind="bm25_documents",
|
| 59 |
+
key_col="entry_cid",
|
| 60 |
+
index_col="document_index",
|
| 61 |
+
)
|
| 62 |
+
write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
|
| 63 |
+
|
| 64 |
+
postings = bm25["postings"]
|
| 65 |
+
posting_idx = write_sharded(
|
| 66 |
+
postings,
|
| 67 |
+
out / "data" / "bm25" / "postings",
|
| 68 |
+
"data/bm25/postings",
|
| 69 |
+
kind="bm25_postings",
|
| 70 |
+
key_col="term",
|
| 71 |
+
)
|
| 72 |
+
for row, part_start in zip(posting_idx, range(len(posting_idx))):
|
| 73 |
+
shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE]
|
| 74 |
+
row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
|
| 75 |
+
row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
|
| 76 |
+
row["token_instance_count"] = row["posting_count"]
|
| 77 |
+
write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
|
| 78 |
+
|
| 79 |
+
node_idx = write_sharded(
|
| 80 |
+
graph["nodes"],
|
| 81 |
+
out / "data" / "graph" / "nodes",
|
| 82 |
+
"data/graph/nodes",
|
| 83 |
+
kind="graph_nodes",
|
| 84 |
+
key_col="node_cid",
|
| 85 |
+
)
|
| 86 |
+
write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
|
| 87 |
+
|
| 88 |
+
edge_idx = write_sharded(
|
| 89 |
+
graph["edges"],
|
| 90 |
+
out / "data" / "graph" / "edges",
|
| 91 |
+
"data/graph/edges",
|
| 92 |
+
kind="graph_edges",
|
| 93 |
+
key_col="edge_cid",
|
| 94 |
+
)
|
| 95 |
+
write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
|
| 96 |
+
|
| 97 |
+
incoming = graph["incoming"]
|
| 98 |
+
outgoing = graph["outgoing"]
|
| 99 |
+
in_idx = write_sharded(
|
| 100 |
+
incoming if incoming is not None and not incoming.empty else pd.DataFrame(
|
| 101 |
+
columns=["node_cid", "page_index", "direction"]
|
| 102 |
+
),
|
| 103 |
+
out / "data" / "graph" / "adjacency" / "incoming",
|
| 104 |
+
"data/graph/adjacency/incoming",
|
| 105 |
+
kind="graph_incoming_adjacency",
|
| 106 |
+
key_col="node_cid",
|
| 107 |
+
)
|
| 108 |
+
out_idx = write_sharded(
|
| 109 |
+
outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame(
|
| 110 |
+
columns=["node_cid", "page_index", "direction"]
|
| 111 |
+
),
|
| 112 |
+
out / "data" / "graph" / "adjacency" / "outgoing",
|
| 113 |
+
"data/graph/adjacency/outgoing",
|
| 114 |
+
kind="graph_outgoing_adjacency",
|
| 115 |
+
key_col="node_cid",
|
| 116 |
+
)
|
| 117 |
+
for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
|
| 118 |
+
for r in rows:
|
| 119 |
+
r["direction"] = direction
|
| 120 |
+
r["adjacency_count"] = r.get("row_count", 0)
|
| 121 |
+
r["node_count"] = r.get("row_count", 0)
|
| 122 |
+
r["first_page_index"] = 0
|
| 123 |
+
r["last_page_index"] = 0
|
| 124 |
+
write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
|
| 125 |
+
write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
|
| 126 |
+
|
| 127 |
+
vectors_df = vectors["vectors"]
|
| 128 |
+
# Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
|
| 129 |
+
if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all():
|
| 130 |
+
vectors_write = vectors_df.drop(columns=["embedding"])
|
| 131 |
+
vectors_write["embedding_status"] = "stub_missing"
|
| 132 |
+
else:
|
| 133 |
+
vectors_write = vectors_df
|
| 134 |
+
vec_idx = write_sharded(
|
| 135 |
+
vectors_write,
|
| 136 |
+
out / "data" / "vectors",
|
| 137 |
+
"data/vectors",
|
| 138 |
+
kind="vectors",
|
| 139 |
+
key_col="entry_cid",
|
| 140 |
+
index_col="document_index",
|
| 141 |
+
)
|
| 142 |
+
meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]}
|
| 143 |
+
for r in vec_idx:
|
| 144 |
+
m = meta_by_cluster.get(r["shard_id"], {})
|
| 145 |
+
r["centroid"] = m.get("centroid", [])
|
| 146 |
+
r["shard_centroid"] = m.get("shard_centroid", [])
|
| 147 |
+
r["centroid_min_score"] = m.get("centroid_min_score", 0.0)
|
| 148 |
+
r["centroid_shard_count"] = m.get("centroid_shard_count", 1)
|
| 149 |
+
r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0)
|
| 150 |
+
r["cluster_id"] = m.get("cluster_id", r["shard_id"])
|
| 151 |
+
r["dimension"] = 384
|
| 152 |
+
r["model_name"] = "thenlper/gte-small"
|
| 153 |
+
if m.get("stub"):
|
| 154 |
+
r["stub"] = True
|
| 155 |
+
r["stub_reason"] = m.get("stub_reason", "")
|
| 156 |
+
write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx))
|
| 157 |
+
|
| 158 |
+
# Bundle package + scripts into the release
|
| 159 |
+
pkg_src = Path(__file__).resolve().parent
|
| 160 |
+
dest_pkg = out / "country_laws_ir"
|
| 161 |
+
shutil.copytree(
|
| 162 |
+
pkg_src,
|
| 163 |
+
dest_pkg,
|
| 164 |
+
dirs_exist_ok=True,
|
| 165 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"),
|
| 166 |
+
)
|
| 167 |
+
scripts_dir = out / "scripts"
|
| 168 |
+
scripts_dir.mkdir(exist_ok=True)
|
| 169 |
+
for name in (
|
| 170 |
+
"build_country_laws_ir.py",
|
| 171 |
+
"normalize_country_laws.py",
|
| 172 |
+
"query_country_laws_hf.py",
|
| 173 |
+
"query_country_laws_ir.py",
|
| 174 |
+
"generate_country_laws_ir.py",
|
| 175 |
+
):
|
| 176 |
+
src = code_root / "scripts" / name
|
| 177 |
+
if src.exists():
|
| 178 |
+
shutil.copy2(src, scripts_dir / name)
|
| 179 |
+
shutil.copy2(pkg_src / "normalize.py", out / "normalize.py")
|
| 180 |
+
shutil.copy2(pkg_src / "query.py", out / "query.py")
|
| 181 |
+
shutil.copy2(pkg_src / "build.py", out / "build.py")
|
| 182 |
+
_write_skill(out, country, hub_id=target_repo(country["slug"]))
|
| 183 |
+
|
| 184 |
+
reports_dir = out / "reports"
|
| 185 |
+
reports_dir.mkdir(exist_ok=True)
|
| 186 |
+
if normalization_report is not None:
|
| 187 |
+
payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n"
|
| 188 |
+
(out / "normalization_report.json").write_text(payload, encoding="utf-8")
|
| 189 |
+
(reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
|
| 190 |
+
|
| 191 |
+
n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0
|
| 192 |
+
n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0
|
| 193 |
+
counts = {
|
| 194 |
+
"bm25_document_chunks": len(bm25_doc_idx),
|
| 195 |
+
"bm25_documents": int(len(bm25["documents"])),
|
| 196 |
+
"bm25_keyword_shards": len(posting_idx),
|
| 197 |
+
"bm25_posting_rows": int(len(postings)),
|
| 198 |
+
"bm25_postings": int(bm25["stats"]["n_postings"]),
|
| 199 |
+
"bm25_terms": int(bm25["stats"]["n_terms"]),
|
| 200 |
+
"corpus_chunks": len(corpus_idx),
|
| 201 |
+
"corpus_rows": int(len(corpus)),
|
| 202 |
+
"graph_edge_chunks": len(edge_idx),
|
| 203 |
+
"graph_edges": int(len(graph["edges"])),
|
| 204 |
+
"graph_incoming_adjacency_edges": int(len(graph["edges"])),
|
| 205 |
+
"graph_incoming_adjacency_rows": int(len(incoming)) if incoming is not None else 0,
|
| 206 |
+
"graph_incoming_adjacency_shards": len(in_idx),
|
| 207 |
+
"graph_node_chunks": len(node_idx),
|
| 208 |
+
"graph_nodes": int(len(graph["nodes"])),
|
| 209 |
+
"graph_outgoing_adjacency_edges": int(len(graph["edges"])),
|
| 210 |
+
"graph_outgoing_adjacency_rows": int(len(outgoing)) if outgoing is not None else 0,
|
| 211 |
+
"graph_outgoing_adjacency_shards": len(out_idx),
|
| 212 |
+
"vector_chunks": len(vec_idx),
|
| 213 |
+
"vector_rows": int(len(vectors_df)),
|
| 214 |
+
"n_laws": n_laws,
|
| 215 |
+
"n_articles": n_articles,
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
def idx_desc(name: str) -> dict[str, Any]:
|
| 219 |
+
path = indexes_dir / name
|
| 220 |
+
return file_descriptor(path, f"indexes/{name}")
|
| 221 |
+
|
| 222 |
+
hub_id = target_repo(country["slug"])
|
| 223 |
+
edge_types = graph["stats"].get("edge_types") or [
|
| 224 |
+
"HAS_JURISDICTION",
|
| 225 |
+
"HAS_LANGUAGE",
|
| 226 |
+
"BELONGS_TO_LAW",
|
| 227 |
+
"HAS_ARTICLE",
|
| 228 |
+
"BM25_NEIGHBOR_OF",
|
| 229 |
+
]
|
| 230 |
+
manifest = {
|
| 231 |
+
"schema_version": SCHEMA_VERSION,
|
| 232 |
+
"layout_family": LAYOUT_FAMILY,
|
| 233 |
+
"packager_version": __version__,
|
| 234 |
+
"primary_key": "entry_cid",
|
| 235 |
+
"dataset_id": source_meta["source_dataset"],
|
| 236 |
+
"dataset_repo_id": hub_id,
|
| 237 |
+
"dataset_revision": source_meta["source_revision"],
|
| 238 |
+
"country": country,
|
| 239 |
+
"disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
|
| 240 |
+
"bm25": {k: bm25["stats"][k] for k in (
|
| 241 |
+
"k1", "b", "title_weight", "body_weight", "average_document_length",
|
| 242 |
+
"tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
|
| 243 |
+
)},
|
| 244 |
+
"counts": counts,
|
| 245 |
+
"parquet": {
|
| 246 |
+
"compression": "zstd",
|
| 247 |
+
"compression_level": 6,
|
| 248 |
+
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 249 |
+
"row_group_size": MAX_ROWS_PER_FILE,
|
| 250 |
+
},
|
| 251 |
+
"graph": {
|
| 252 |
+
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
| 253 |
+
"adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD,
|
| 254 |
+
"directions": ["incoming", "outgoing"],
|
| 255 |
+
"max_remote_walk_depth": 8,
|
| 256 |
+
"ordering": "score_desc_nulls_last",
|
| 257 |
+
"edge_types": edge_types,
|
| 258 |
+
},
|
| 259 |
+
"vector": vectors["stats"],
|
| 260 |
+
"canonical_fields": [
|
| 261 |
+
"entry_cid",
|
| 262 |
+
"law_cid",
|
| 263 |
+
"record_type",
|
| 264 |
+
"jurisdiction",
|
| 265 |
+
"language",
|
| 266 |
+
"instrument_id",
|
| 267 |
+
"instrument_title",
|
| 268 |
+
"article_number",
|
| 269 |
+
"article_title",
|
| 270 |
+
"title",
|
| 271 |
+
"body",
|
| 272 |
+
"source_url",
|
| 273 |
+
"snapshot_date",
|
| 274 |
+
"coverage",
|
| 275 |
+
"license",
|
| 276 |
+
"collector",
|
| 277 |
+
"source_dataset",
|
| 278 |
+
"source_revision",
|
| 279 |
+
],
|
| 280 |
+
"input_sha256": {
|
| 281 |
+
"laws.parquet": source_meta.get("laws_sha256"),
|
| 282 |
+
"articles.parquet": source_meta.get("articles_sha256"),
|
| 283 |
+
},
|
| 284 |
+
"model_id": (vectors.get("stats") or {}).get("model_name", "thenlper/gte-small"),
|
| 285 |
+
"cid": {
|
| 286 |
+
"codec": "raw",
|
| 287 |
+
"hash": "sha2-256",
|
| 288 |
+
"multibase": "base32",
|
| 289 |
+
"payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')",
|
| 290 |
+
},
|
| 291 |
+
"normalization": normalization_report or {},
|
| 292 |
+
"schema_mapping": {
|
| 293 |
+
"laws": {
|
| 294 |
+
"id": "instrument_id",
|
| 295 |
+
"title": "instrument_title",
|
| 296 |
+
"text": "body",
|
| 297 |
+
"article_count_dtype_source": source_meta.get("article_count_dtype"),
|
| 298 |
+
},
|
| 299 |
+
"articles": {
|
| 300 |
+
"id": "source_id / article identity",
|
| 301 |
+
"law_id": "instrument_id",
|
| 302 |
+
"title": "article_title",
|
| 303 |
+
"text": "body",
|
| 304 |
+
},
|
| 305 |
+
"unit_policy": "prefer articles; fall back to law-level when articles empty",
|
| 306 |
+
"required_law_columns": ["id", "title", "text"],
|
| 307 |
+
"required_article_columns": ["id", "law_id", "title", "text"],
|
| 308 |
+
"fail_closed": True,
|
| 309 |
+
"notes": (
|
| 310 |
+
"Malta and Germany share the same column names. Drift: Malta article_count "
|
| 311 |
+
"is int64, Germany article_count is int32; Germany eli is often null. "
|
| 312 |
+
"Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family."
|
| 313 |
+
),
|
| 314 |
+
},
|
| 315 |
+
"indexes": {
|
| 316 |
+
"bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"),
|
| 317 |
+
"bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"),
|
| 318 |
+
"corpus_chunks": idx_desc("corpus_chunks.parquet"),
|
| 319 |
+
"graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"),
|
| 320 |
+
"graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"),
|
| 321 |
+
"graph_node_chunks": idx_desc("graph_node_chunks.parquet"),
|
| 322 |
+
"graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"),
|
| 323 |
+
"vector_chunks": idx_desc("vector_chunks.parquet"),
|
| 324 |
+
},
|
| 325 |
+
"source": source_meta,
|
| 326 |
+
}
|
| 327 |
+
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 328 |
+
_write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
|
| 329 |
+
_write_gitattributes(out)
|
| 330 |
+
return manifest
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _write_gitattributes(out: Path) -> None:
|
| 334 |
+
(out / ".gitattributes").write_text(
|
| 335 |
+
"*.parquet filter=lfs diff=lfs merge=lfs -text\n"
|
| 336 |
+
"*.bin filter=lfs diff=lfs merge=lfs -text\n",
|
| 337 |
+
encoding="utf-8",
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _write_readme(
|
| 342 |
+
out: Path,
|
| 343 |
+
country: dict[str, Any],
|
| 344 |
+
source_meta: dict[str, Any],
|
| 345 |
+
counts: dict[str, Any],
|
| 346 |
+
bm25_stats: dict[str, Any],
|
| 347 |
+
graph_stats: dict[str, Any],
|
| 348 |
+
vector_stats: dict[str, Any],
|
| 349 |
+
hub_id: str,
|
| 350 |
+
) -> None:
|
| 351 |
+
slug = country["slug"]
|
| 352 |
+
name = country["name"]
|
| 353 |
+
src = source_meta["source_dataset"]
|
| 354 |
+
rev = source_meta["source_revision"]
|
| 355 |
+
vec_status = vector_stats.get("status", "embedded")
|
| 356 |
+
text = f"""---
|
| 357 |
+
license: other
|
| 358 |
+
task_categories:
|
| 359 |
+
- text-retrieval
|
| 360 |
+
tags:
|
| 361 |
+
- legal
|
| 362 |
+
- law
|
| 363 |
+
- graphrag
|
| 364 |
+
- bm25
|
| 365 |
+
- research
|
| 366 |
+
- not-legal-advice
|
| 367 |
+
- {slug}
|
| 368 |
+
pretty_name: {name} laws IR (CID-keyed GraphRAG)
|
| 369 |
+
configs:
|
| 370 |
+
- config_name: corpus
|
| 371 |
+
data_files:
|
| 372 |
+
- split: train
|
| 373 |
+
path: data/corpus/*.parquet
|
| 374 |
+
- config_name: bm25_documents
|
| 375 |
+
data_files:
|
| 376 |
+
- split: train
|
| 377 |
+
path: data/bm25/documents/*.parquet
|
| 378 |
+
- config_name: bm25_postings
|
| 379 |
+
data_files:
|
| 380 |
+
- split: train
|
| 381 |
+
path: data/bm25/postings/*.parquet
|
| 382 |
+
- config_name: bm25_keyword_index
|
| 383 |
+
data_files:
|
| 384 |
+
- split: train
|
| 385 |
+
path: indexes/bm25_keyword_shards.parquet
|
| 386 |
+
- config_name: vectors
|
| 387 |
+
data_files:
|
| 388 |
+
- split: train
|
| 389 |
+
path: data/vectors/*.parquet
|
| 390 |
+
- config_name: vector_meta_index
|
| 391 |
+
data_files:
|
| 392 |
+
- split: train
|
| 393 |
+
path: indexes/vector_chunks.parquet
|
| 394 |
+
- config_name: graph_nodes
|
| 395 |
+
data_files:
|
| 396 |
+
- split: train
|
| 397 |
+
path: data/graph/nodes/*.parquet
|
| 398 |
+
- config_name: graph_edges
|
| 399 |
+
data_files:
|
| 400 |
+
- split: train
|
| 401 |
+
path: data/graph/edges/*.parquet
|
| 402 |
+
- config_name: graph_outgoing_adjacency
|
| 403 |
+
data_files:
|
| 404 |
+
- split: train
|
| 405 |
+
path: data/graph/adjacency/outgoing/*.parquet
|
| 406 |
+
- config_name: graph_incoming_adjacency
|
| 407 |
+
data_files:
|
| 408 |
+
- split: train
|
| 409 |
+
path: data/graph/adjacency/incoming/*.parquet
|
| 410 |
+
---
|
| 411 |
+
|
| 412 |
+
# {name} legislation IR (CID-keyed sparse GraphRAG)
|
| 413 |
+
|
| 414 |
+
Research retrieval release of `{src}` (revision `{rev}`) packaged as
|
| 415 |
+
`{SCHEMA_VERSION}` (layout family `{LAYOUT_FAMILY}` / publicus-ir).
|
| 416 |
+
|
| 417 |
+
**Not legal advice.** This is a research snapshot. The official gazette /
|
| 418 |
+
authentic source of {name} prevails over this corpus. Retrieved documents
|
| 419 |
+
and graph edges are retrieval evidence only. No legal text was invented.
|
| 420 |
+
|
| 421 |
+
Primary key: `entry_cid` (CIDv1 raw sha2-256 of a canonical identity record).
|
| 422 |
+
Integer `document_index` values are compact shard pointers, not identities.
|
| 423 |
+
|
| 424 |
+
Target Hub id (packaging metadata only): `{hub_id}`.
|
| 425 |
+
|
| 426 |
+
## Counts
|
| 427 |
+
|
| 428 |
+
| Field | Value |
|
| 429 |
+
| --- | --- |
|
| 430 |
+
| Laws (corpus units) | {counts['n_laws']} |
|
| 431 |
+
| Articles (corpus units) | {counts['n_articles']} |
|
| 432 |
+
| Canonical docs | {counts['corpus_rows']} |
|
| 433 |
+
| BM25 terms | {counts['bm25_terms']} |
|
| 434 |
+
| BM25 postings | {counts['bm25_postings']} |
|
| 435 |
+
| Graph nodes | {counts['graph_nodes']} |
|
| 436 |
+
| Graph edges | {counts['graph_edges']} |
|
| 437 |
+
| Vectors | {counts['vector_rows']} × {vector_stats['dimension']}-d `{vector_stats['model_name']}` ({vec_status}) |
|
| 438 |
+
|
| 439 |
+
## Canonical fields
|
| 440 |
+
|
| 441 |
+
`entry_cid`, `law_cid`, `record_type`, `jurisdiction`, `language`,
|
| 442 |
+
`instrument_id`, `instrument_title`, `article_number`, `article_title`,
|
| 443 |
+
`title`, `body`, `source_url`, `snapshot_date`, `coverage`, `license`,
|
| 444 |
+
`collector`, `source_dataset`, `source_revision`.
|
| 445 |
+
|
| 446 |
+
Unit policy: prefer article/section rows; fall back to law-level when
|
| 447 |
+
`articles.parquet` is empty.
|
| 448 |
+
|
| 449 |
+
## Index layout
|
| 450 |
+
|
| 451 |
+
Zstandard parquet shards with at most 4,096 rows.
|
| 452 |
+
|
| 453 |
+
- `indexes/bm25_keyword_shards.parquet` — lexical term ranges → BM25 posting shards
|
| 454 |
+
- `indexes/vector_chunks.parquet` — semantic routing centroids (rows sorted by cosine to shard centroid)
|
| 455 |
+
- `indexes/corpus_chunks.parquet` — document ranges → corpus shards
|
| 456 |
+
- `data/graph/nodes` / `data/graph/edges` — property graph
|
| 457 |
+
- `data/graph/adjacency/{{incoming,outgoing}}` — score-ordered neighbor pages
|
| 458 |
+
|
| 459 |
+
BM25: Okapi k1=1.2, b=0.75, title_weight=5, body_weight=1 (FTS5 unicode61-style tokenizer).
|
| 460 |
+
|
| 461 |
+
Graph: one node per `entry_cid` plus facet nodes (`_facet_cid(kind, value)` for
|
| 462 |
+
jurisdiction, language, instrument, source, status). Neighbor edges
|
| 463 |
+
`BM25_NEIGHBOR_OF` (k=8) carry score and matched terms. Structural edges:
|
| 464 |
+
`ARTICLE_OF` (article → parent law) when articles exist, plus `IDENTIFIED_BY_ELI`
|
| 465 |
+
/ `IDENTIFIED_BY` only when those identifiers are present in the source.
|
| 466 |
+
|
| 467 |
+
## Query
|
| 468 |
+
|
| 469 |
+
```
|
| 470 |
+
python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 10
|
| 471 |
+
python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 10
|
| 472 |
+
python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
|
| 473 |
+
```
|
| 474 |
+
|
| 475 |
+
## Publish later (operator)
|
| 476 |
+
|
| 477 |
+
```
|
| 478 |
+
export HF_TOKEN=... # never commit
|
| 479 |
+
hf upload-large-folder {hub_id} . \\
|
| 480 |
+
--repo-type dataset --no-private --num-workers 8 \\
|
| 481 |
+
--exclude "**/__pycache__/**" --exclude "**/*.pyc"
|
| 482 |
+
```
|
| 483 |
+
|
| 484 |
+
## Provenance
|
| 485 |
+
|
| 486 |
+
Packaged by country-laws-ir. Upstream collector and official license remain those
|
| 487 |
+
of `{src}`. CIDs identify local content; they do not prove public IPFS pinning.
|
| 488 |
+
"""
|
| 489 |
+
(out / "README.md").write_text(text, encoding="utf-8")
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def _write_skill(out: Path, country: dict[str, Any], hub_id: str) -> None:
|
| 493 |
+
skill_dir = out / "skill" / "query-country-laws-hf"
|
| 494 |
+
skill_dir.mkdir(parents=True, exist_ok=True)
|
| 495 |
+
name = country.get("name") or country.get("slug")
|
| 496 |
+
slug = country.get("slug")
|
| 497 |
+
text = f"""---
|
| 498 |
+
name: query-country-laws-hf
|
| 499 |
+
description: Query a local or Hub country-laws-ir GraphRAG release (BM25, vectors, graph neighbors). Research retrieval only — not legal advice.
|
| 500 |
+
---
|
| 501 |
+
|
| 502 |
+
# Query country-laws-ir (SkillCenter-style sparse GraphRAG)
|
| 503 |
+
|
| 504 |
+
Thin client for `{hub_id}` / local release roots that follow
|
| 505 |
+
`country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3`).
|
| 506 |
+
|
| 507 |
+
**Not legal advice.** Official gazettes prevail. Retrieved hits are context only.
|
| 508 |
+
|
| 509 |
+
## Local
|
| 510 |
+
|
| 511 |
+
```bash
|
| 512 |
+
python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 5
|
| 513 |
+
python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 5
|
| 514 |
+
python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
|
| 515 |
+
```
|
| 516 |
+
|
| 517 |
+
Or:
|
| 518 |
+
|
| 519 |
+
```bash
|
| 520 |
+
python -m country_laws_ir query --local-dir /workspace/country-laws-ir/releases/ipfs_{slug}_laws_ir -- bm25 "constitution"
|
| 521 |
+
```
|
| 522 |
+
|
| 523 |
+
## Method
|
| 524 |
+
|
| 525 |
+
- Primary key `entry_cid` (CIDv1 raw sha2-256). `document_index` is a shard pointer.
|
| 526 |
+
- BM25 Okapi k1=1.2 b=0.75, title_weight=5, body_weight=1, FTS5-style tokenizer.
|
| 527 |
+
- Vectors `thenlper/gte-small` 384-d, mean-pool, L2, centroid-sorted shards.
|
| 528 |
+
- Graph: facets + `BM25_NEIGHBOR_OF` (k=8, score + matched terms) + `ARTICLE_OF`.
|
| 529 |
+
|
| 530 |
+
Do not treat retrieval as proof. Do not invent citations.
|
| 531 |
+
"""
|
| 532 |
+
(skill_dir / "SKILL.md").write_text(text, encoding="utf-8")
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def package_release_sequential(
|
| 536 |
+
out: Path,
|
| 537 |
+
*,
|
| 538 |
+
corpus_path: Path,
|
| 539 |
+
bm25_documents_path: Path,
|
| 540 |
+
bm25_postings_path: Path,
|
| 541 |
+
bm25_stats: dict[str, Any],
|
| 542 |
+
graph: dict[str, Any] | Path,
|
| 543 |
+
vectors: dict[str, Any] | Path,
|
| 544 |
+
source_meta: dict[str, Any],
|
| 545 |
+
country: dict[str, Any],
|
| 546 |
+
code_root: Path,
|
| 547 |
+
normalization_report: dict[str, Any] | None = None,
|
| 548 |
+
expected_rows: int | None = None,
|
| 549 |
+
) -> dict[str, Any]:
|
| 550 |
+
"""Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
|
| 551 |
+
|
| 552 |
+
``graph`` / ``vectors`` may be in-memory dicts or pickle Paths.
|
| 553 |
+
Loads and frees each artifact before the next. Prefer this for n>=40k.
|
| 554 |
+
"""
|
| 555 |
+
from .mem import checkpoint, log_mem
|
| 556 |
+
|
| 557 |
+
def _load_obj(obj_or_path):
|
| 558 |
+
if isinstance(obj_or_path, (str, Path)):
|
| 559 |
+
p = Path(obj_or_path)
|
| 560 |
+
with p.open("rb") as f:
|
| 561 |
+
return pickle.load(f)
|
| 562 |
+
return obj_or_path
|
| 563 |
+
|
| 564 |
+
if out.exists():
|
| 565 |
+
shutil.rmtree(out)
|
| 566 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 567 |
+
indexes_dir = out / "indexes"
|
| 568 |
+
indexes_dir.mkdir(parents=True, exist_ok=True)
|
| 569 |
+
log_mem("package_seq_start")
|
| 570 |
+
|
| 571 |
+
# --- corpus ---
|
| 572 |
+
corpus = pd.read_parquet(corpus_path)
|
| 573 |
+
if expected_rows is not None and len(corpus) != expected_rows:
|
| 574 |
+
raise ValueError(f"corpus rows {len(corpus)} != expected {expected_rows}")
|
| 575 |
+
n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0
|
| 576 |
+
n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0
|
| 577 |
+
corpus_rows = int(len(corpus))
|
| 578 |
+
corpus_idx = write_sharded(
|
| 579 |
+
corpus, out / "data" / "corpus", "data/corpus",
|
| 580 |
+
kind="corpus", key_col="entry_cid", index_col="document_index",
|
| 581 |
+
)
|
| 582 |
+
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 583 |
+
del corpus
|
| 584 |
+
gc.collect()
|
| 585 |
+
checkpoint("package_corpus_done")
|
| 586 |
+
|
| 587 |
+
# --- bm25 documents ---
|
| 588 |
+
documents = pd.read_parquet(bm25_documents_path)
|
| 589 |
+
bm25_doc_idx = write_sharded(
|
| 590 |
+
documents, out / "data" / "bm25" / "documents", "data/bm25/documents",
|
| 591 |
+
kind="bm25_documents", key_col="entry_cid", index_col="document_index",
|
| 592 |
+
)
|
| 593 |
+
write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
|
| 594 |
+
n_bm25_docs = int(len(documents))
|
| 595 |
+
del documents
|
| 596 |
+
gc.collect()
|
| 597 |
+
|
| 598 |
+
postings = pd.read_parquet(bm25_postings_path)
|
| 599 |
+
posting_idx = write_sharded(
|
| 600 |
+
postings, out / "data" / "bm25" / "postings", "data/bm25/postings",
|
| 601 |
+
kind="bm25_postings", key_col="term",
|
| 602 |
+
)
|
| 603 |
+
for row, part_start in zip(posting_idx, range(len(posting_idx))):
|
| 604 |
+
shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE]
|
| 605 |
+
row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
|
| 606 |
+
row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
|
| 607 |
+
row["token_instance_count"] = row["posting_count"]
|
| 608 |
+
write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
|
| 609 |
+
n_posting_rows = int(len(postings))
|
| 610 |
+
del postings
|
| 611 |
+
gc.collect()
|
| 612 |
+
checkpoint("package_bm25_done")
|
| 613 |
+
|
| 614 |
+
# --- graph ---
|
| 615 |
+
graph = _load_obj(graph)
|
| 616 |
+
node_idx = write_sharded(
|
| 617 |
+
graph["nodes"], out / "data" / "graph" / "nodes", "data/graph/nodes",
|
| 618 |
+
kind="graph_nodes", key_col="node_cid",
|
| 619 |
+
)
|
| 620 |
+
write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
|
| 621 |
+
edge_idx = write_sharded(
|
| 622 |
+
graph["edges"], out / "data" / "graph" / "edges", "data/graph/edges",
|
| 623 |
+
kind="graph_edges", key_col="edge_cid",
|
| 624 |
+
)
|
| 625 |
+
write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
|
| 626 |
+
incoming = graph["incoming"]
|
| 627 |
+
outgoing = graph["outgoing"]
|
| 628 |
+
in_idx = write_sharded(
|
| 629 |
+
incoming if incoming is not None and not incoming.empty else pd.DataFrame(
|
| 630 |
+
columns=["node_cid", "page_index", "direction"]
|
| 631 |
+
),
|
| 632 |
+
out / "data" / "graph" / "adjacency" / "incoming",
|
| 633 |
+
"data/graph/adjacency/incoming",
|
| 634 |
+
kind="graph_incoming_adjacency",
|
| 635 |
+
key_col="node_cid",
|
| 636 |
+
)
|
| 637 |
+
out_idx = write_sharded(
|
| 638 |
+
outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame(
|
| 639 |
+
columns=["node_cid", "page_index", "direction"]
|
| 640 |
+
),
|
| 641 |
+
out / "data" / "graph" / "adjacency" / "outgoing",
|
| 642 |
+
"data/graph/adjacency/outgoing",
|
| 643 |
+
kind="graph_outgoing_adjacency",
|
| 644 |
+
key_col="node_cid",
|
| 645 |
+
)
|
| 646 |
+
for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
|
| 647 |
+
for r in rows:
|
| 648 |
+
r["direction"] = direction
|
| 649 |
+
r["adjacency_count"] = r.get("row_count", 0)
|
| 650 |
+
r["node_count"] = r.get("row_count", 0)
|
| 651 |
+
r["first_page_index"] = 0
|
| 652 |
+
r["last_page_index"] = 0
|
| 653 |
+
write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
|
| 654 |
+
write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
|
| 655 |
+
gstats = graph["stats"]
|
| 656 |
+
n_graph_nodes = int(len(graph["nodes"]))
|
| 657 |
+
n_graph_edges = int(len(graph["edges"]))
|
| 658 |
+
n_in = int(len(incoming)) if incoming is not None else 0
|
| 659 |
+
n_out = int(len(outgoing)) if outgoing is not None else 0
|
| 660 |
+
edge_types = gstats.get("edge_types") or [
|
| 661 |
+
"HAS_JURISDICTION", "HAS_LANGUAGE", "BELONGS_TO_LAW", "HAS_ARTICLE", "BM25_NEIGHBOR_OF",
|
| 662 |
+
]
|
| 663 |
+
del graph, incoming, outgoing
|
| 664 |
+
gc.collect()
|
| 665 |
+
checkpoint("package_graph_done")
|
| 666 |
+
|
| 667 |
+
# --- vectors ---
|
| 668 |
+
vectors = _load_obj(vectors)
|
| 669 |
+
vectors_df = vectors["vectors"]
|
| 670 |
+
if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all():
|
| 671 |
+
vectors_write = vectors_df.drop(columns=["embedding"])
|
| 672 |
+
vectors_write["embedding_status"] = "stub_missing"
|
| 673 |
+
else:
|
| 674 |
+
vectors_write = vectors_df
|
| 675 |
+
vec_idx = write_sharded(
|
| 676 |
+
vectors_write, out / "data" / "vectors", "data/vectors",
|
| 677 |
+
kind="vectors", key_col="entry_cid", index_col="document_index",
|
| 678 |
+
)
|
| 679 |
+
meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]}
|
| 680 |
+
for r in vec_idx:
|
| 681 |
+
m = meta_by_cluster.get(r["shard_id"], {})
|
| 682 |
+
r["centroid"] = m.get("centroid", [])
|
| 683 |
+
r["shard_centroid"] = m.get("shard_centroid", [])
|
| 684 |
+
r["centroid_min_score"] = m.get("centroid_min_score", 0.0)
|
| 685 |
+
r["centroid_shard_count"] = m.get("centroid_shard_count", 1)
|
| 686 |
+
r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0)
|
| 687 |
+
r["cluster_id"] = m.get("cluster_id", r["shard_id"])
|
| 688 |
+
r["dimension"] = 384
|
| 689 |
+
r["model_name"] = "thenlper/gte-small"
|
| 690 |
+
if m.get("stub"):
|
| 691 |
+
r["stub"] = True
|
| 692 |
+
r["stub_reason"] = m.get("stub_reason", "")
|
| 693 |
+
write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx))
|
| 694 |
+
vstats = vectors["stats"]
|
| 695 |
+
n_vectors = int(len(vectors_df))
|
| 696 |
+
del vectors, vectors_df, vectors_write
|
| 697 |
+
gc.collect()
|
| 698 |
+
checkpoint("package_vectors_done")
|
| 699 |
+
|
| 700 |
+
# --- bundle code ---
|
| 701 |
+
pkg_src = Path(__file__).resolve().parent
|
| 702 |
+
dest_pkg = out / "country_laws_ir"
|
| 703 |
+
shutil.copytree(
|
| 704 |
+
pkg_src, dest_pkg, dirs_exist_ok=True,
|
| 705 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"),
|
| 706 |
+
)
|
| 707 |
+
scripts_dir = out / "scripts"
|
| 708 |
+
scripts_dir.mkdir(exist_ok=True)
|
| 709 |
+
for name in (
|
| 710 |
+
"build_country_laws_ir.py", "normalize_country_laws.py",
|
| 711 |
+
"query_country_laws_hf.py", "query_country_laws_ir.py", "generate_country_laws_ir.py",
|
| 712 |
+
):
|
| 713 |
+
src = code_root / "scripts" / name
|
| 714 |
+
if src.exists():
|
| 715 |
+
shutil.copy2(src, scripts_dir / name)
|
| 716 |
+
shutil.copy2(pkg_src / "normalize.py", out / "normalize.py")
|
| 717 |
+
shutil.copy2(pkg_src / "query.py", out / "query.py")
|
| 718 |
+
shutil.copy2(pkg_src / "build.py", out / "build.py")
|
| 719 |
+
hub_id = target_repo(country["slug"])
|
| 720 |
+
_write_skill(out, country, hub_id=hub_id)
|
| 721 |
+
|
| 722 |
+
reports_dir = out / "reports"
|
| 723 |
+
reports_dir.mkdir(exist_ok=True)
|
| 724 |
+
if normalization_report is not None:
|
| 725 |
+
payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n"
|
| 726 |
+
(out / "normalization_report.json").write_text(payload, encoding="utf-8")
|
| 727 |
+
(reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
|
| 728 |
+
|
| 729 |
+
counts = {
|
| 730 |
+
"bm25_document_chunks": len(bm25_doc_idx),
|
| 731 |
+
"bm25_documents": n_bm25_docs,
|
| 732 |
+
"bm25_keyword_shards": len(posting_idx),
|
| 733 |
+
"bm25_posting_rows": n_posting_rows,
|
| 734 |
+
"bm25_postings": int(bm25_stats["n_postings"]),
|
| 735 |
+
"bm25_terms": int(bm25_stats["n_terms"]),
|
| 736 |
+
"corpus_chunks": len(corpus_idx),
|
| 737 |
+
"corpus_rows": corpus_rows,
|
| 738 |
+
"graph_edge_chunks": len(edge_idx),
|
| 739 |
+
"graph_edges": n_graph_edges,
|
| 740 |
+
"graph_incoming_adjacency_edges": n_graph_edges,
|
| 741 |
+
"graph_incoming_adjacency_rows": n_in,
|
| 742 |
+
"graph_incoming_adjacency_shards": len(in_idx),
|
| 743 |
+
"graph_node_chunks": len(node_idx),
|
| 744 |
+
"graph_nodes": n_graph_nodes,
|
| 745 |
+
"graph_outgoing_adjacency_edges": n_graph_edges,
|
| 746 |
+
"graph_outgoing_adjacency_rows": n_out,
|
| 747 |
+
"graph_outgoing_adjacency_shards": len(out_idx),
|
| 748 |
+
"vector_chunks": len(vec_idx),
|
| 749 |
+
"vector_rows": n_vectors,
|
| 750 |
+
"n_laws": n_laws,
|
| 751 |
+
"n_articles": n_articles,
|
| 752 |
+
}
|
| 753 |
+
|
| 754 |
+
def idx_desc(name: str) -> dict[str, Any]:
|
| 755 |
+
path = indexes_dir / name
|
| 756 |
+
return file_descriptor(path, f"indexes/{name}")
|
| 757 |
+
|
| 758 |
+
manifest = {
|
| 759 |
+
"schema_version": SCHEMA_VERSION,
|
| 760 |
+
"layout_family": LAYOUT_FAMILY,
|
| 761 |
+
"packager_version": __version__,
|
| 762 |
+
"primary_key": "entry_cid",
|
| 763 |
+
"dataset_id": source_meta["source_dataset"],
|
| 764 |
+
"dataset_repo_id": hub_id,
|
| 765 |
+
"dataset_revision": source_meta["source_revision"],
|
| 766 |
+
"country": country,
|
| 767 |
+
"disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
|
| 768 |
+
"bm25": {k: bm25_stats[k] for k in (
|
| 769 |
+
"k1", "b", "title_weight", "body_weight", "average_document_length",
|
| 770 |
+
"tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
|
| 771 |
+
) if k in bm25_stats},
|
| 772 |
+
"counts": counts,
|
| 773 |
+
"parquet": {
|
| 774 |
+
"compression": "zstd",
|
| 775 |
+
"compression_level": 6,
|
| 776 |
+
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 777 |
+
"row_group_size": MAX_ROWS_PER_FILE,
|
| 778 |
+
},
|
| 779 |
+
"graph": {
|
| 780 |
+
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
| 781 |
+
"adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD,
|
| 782 |
+
"directions": ["incoming", "outgoing"],
|
| 783 |
+
"max_remote_walk_depth": 8,
|
| 784 |
+
"ordering": "score_desc_nulls_last",
|
| 785 |
+
"edge_types": edge_types,
|
| 786 |
+
},
|
| 787 |
+
"vector": vstats,
|
| 788 |
+
"canonical_fields": [
|
| 789 |
+
"entry_cid", "law_cid", "record_type", "jurisdiction", "language",
|
| 790 |
+
"instrument_id", "instrument_title", "article_number", "article_title",
|
| 791 |
+
"title", "body", "source_url", "snapshot_date", "coverage", "license",
|
| 792 |
+
"collector", "source_dataset", "source_revision",
|
| 793 |
+
],
|
| 794 |
+
"input_sha256": {
|
| 795 |
+
"laws.parquet": source_meta.get("laws_sha256"),
|
| 796 |
+
"articles.parquet": source_meta.get("articles_sha256"),
|
| 797 |
+
},
|
| 798 |
+
"model_id": (vstats or {}).get("model_name", "thenlper/gte-small"),
|
| 799 |
+
"cid": {
|
| 800 |
+
"codec": "raw",
|
| 801 |
+
"hash": "sha2-256",
|
| 802 |
+
"multibase": "base32",
|
| 803 |
+
"payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')",
|
| 804 |
+
},
|
| 805 |
+
"normalization": normalization_report or {},
|
| 806 |
+
"packaging_mode": "sequential_spill",
|
| 807 |
+
"schema_mapping": {
|
| 808 |
+
"laws": {
|
| 809 |
+
"id": "instrument_id", "title": "instrument_title", "text": "body",
|
| 810 |
+
"article_count_dtype_source": source_meta.get("article_count_dtype"),
|
| 811 |
+
},
|
| 812 |
+
"articles": {
|
| 813 |
+
"id": "source_id / article identity", "law_id": "instrument_id",
|
| 814 |
+
"title": "article_title", "text": "body",
|
| 815 |
+
},
|
| 816 |
+
"unit_policy": "prefer articles; fall back to law-level when articles empty",
|
| 817 |
+
"required_law_columns": ["id", "title", "text"],
|
| 818 |
+
"required_article_columns": ["id", "law_id", "title", "text"],
|
| 819 |
+
"fail_closed": True,
|
| 820 |
+
"notes": (
|
| 821 |
+
"Malta and Germany share the same column names. Drift: Malta article_count "
|
| 822 |
+
"is int64, Germany article_count is int32; Germany eli is often null. "
|
| 823 |
+
"Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family."
|
| 824 |
+
),
|
| 825 |
+
},
|
| 826 |
+
"indexes": {
|
| 827 |
+
"bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"),
|
| 828 |
+
"bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"),
|
| 829 |
+
"corpus_chunks": idx_desc("corpus_chunks.parquet"),
|
| 830 |
+
"graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"),
|
| 831 |
+
"graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"),
|
| 832 |
+
"graph_node_chunks": idx_desc("graph_node_chunks.parquet"),
|
| 833 |
+
"graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"),
|
| 834 |
+
"vector_chunks": idx_desc("vector_chunks.parquet"),
|
| 835 |
+
},
|
| 836 |
+
"source": source_meta,
|
| 837 |
+
}
|
| 838 |
+
(out / "manifest.json").write_text(
|
| 839 |
+
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 840 |
+
)
|
| 841 |
+
_write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id)
|
| 842 |
+
_write_gitattributes(out)
|
| 843 |
+
checkpoint("package_seq_done")
|
| 844 |
+
return manifest
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def package_from_spill(
|
| 848 |
+
out: Path,
|
| 849 |
+
spill: Path,
|
| 850 |
+
corpus_path: Path,
|
| 851 |
+
source_meta: dict[str, Any],
|
| 852 |
+
country: dict[str, Any],
|
| 853 |
+
code_root: Path,
|
| 854 |
+
normalization_report: dict[str, Any] | None = None,
|
| 855 |
+
expected_rows: int | None = None,
|
| 856 |
+
) -> dict[str, Any]:
|
| 857 |
+
"""Package from spill dir artifacts: bm25_*.parquet, bm25_stats.pkl, graph.pkl, vectors.pkl."""
|
| 858 |
+
import pickle as _pickle
|
| 859 |
+
|
| 860 |
+
spill = Path(spill)
|
| 861 |
+
stats_path = spill / "bm25_stats.pkl"
|
| 862 |
+
with stats_path.open("rb") as f:
|
| 863 |
+
bm25_stats = _pickle.load(f)
|
| 864 |
+
return package_release_sequential(
|
| 865 |
+
out,
|
| 866 |
+
corpus_path=Path(corpus_path),
|
| 867 |
+
bm25_documents_path=spill / "bm25_documents.parquet",
|
| 868 |
+
bm25_postings_path=spill / "bm25_postings.parquet",
|
| 869 |
+
bm25_stats=bm25_stats,
|
| 870 |
+
graph=spill / "graph.pkl",
|
| 871 |
+
vectors=spill / "vectors.pkl",
|
| 872 |
+
source_meta=source_meta,
|
| 873 |
+
country=country,
|
| 874 |
+
code_root=Path(code_root),
|
| 875 |
+
normalization_report=normalization_report,
|
| 876 |
+
expected_rows=expected_rows,
|
| 877 |
+
)
|
country_laws_ir/parquet_io.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ZSTD parquet shard writer matching skillcenter-huggingface-release/v3."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Iterable
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import pyarrow as pa
|
| 11 |
+
import pyarrow.parquet as pq
|
| 12 |
+
|
| 13 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 14 |
+
from .cidutil import file_descriptor
|
| 15 |
+
|
| 16 |
+
COMPRESSION = "zstd"
|
| 17 |
+
COMPRESSION_LEVEL = 6
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def write_parquet(path: Path, df: pd.DataFrame) -> None:
|
| 21 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
table = pa.Table.from_pandas(df, preserve_index=False)
|
| 23 |
+
pq.write_table(
|
| 24 |
+
table,
|
| 25 |
+
path,
|
| 26 |
+
compression=COMPRESSION,
|
| 27 |
+
compression_level=COMPRESSION_LEVEL,
|
| 28 |
+
row_group_size=min(MAX_ROWS_PER_FILE, max(len(df), 1)),
|
| 29 |
+
use_dictionary=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def shard_frames(df: pd.DataFrame, max_rows: int = MAX_ROWS_PER_FILE) -> list[pd.DataFrame]:
|
| 34 |
+
if df.empty:
|
| 35 |
+
return [df.copy()]
|
| 36 |
+
n = int(math.ceil(len(df) / max_rows))
|
| 37 |
+
return [df.iloc[i * max_rows : (i + 1) * max_rows].copy() for i in range(n)]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def write_sharded(
|
| 41 |
+
df: pd.DataFrame,
|
| 42 |
+
out_dir: Path,
|
| 43 |
+
relative_dir: str,
|
| 44 |
+
kind: str,
|
| 45 |
+
key_col: str | None = None,
|
| 46 |
+
index_col: str | None = None,
|
| 47 |
+
extra_index: dict | None = None,
|
| 48 |
+
) -> list[dict[str, Any]]:
|
| 49 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
shards = shard_frames(df)
|
| 51 |
+
rows: list[dict[str, Any]] = []
|
| 52 |
+
for i, part in enumerate(shards):
|
| 53 |
+
name = f"part-{i:06d}.parquet"
|
| 54 |
+
path = out_dir / name
|
| 55 |
+
write_parquet(path, part)
|
| 56 |
+
rel = f"{relative_dir}/{name}"
|
| 57 |
+
first_key = last_key = ""
|
| 58 |
+
if key_col and key_col in part.columns and not part.empty:
|
| 59 |
+
keys = part[key_col].astype(str)
|
| 60 |
+
first_key = keys.iloc[0]
|
| 61 |
+
last_key = keys.iloc[-1]
|
| 62 |
+
start_idx = end_idx = 0
|
| 63 |
+
if index_col and index_col in part.columns and not part.empty:
|
| 64 |
+
start_idx = int(part[index_col].iloc[0])
|
| 65 |
+
end_idx = int(part[index_col].iloc[-1])
|
| 66 |
+
desc = file_descriptor(
|
| 67 |
+
path,
|
| 68 |
+
rel,
|
| 69 |
+
extra={
|
| 70 |
+
"shard_id": i,
|
| 71 |
+
"kind": kind,
|
| 72 |
+
"row_count": int(len(part)),
|
| 73 |
+
"first_key": first_key,
|
| 74 |
+
"last_key": last_key,
|
| 75 |
+
"start_document_index": start_idx,
|
| 76 |
+
"end_document_index": end_idx,
|
| 77 |
+
"schema_version": SCHEMA_VERSION,
|
| 78 |
+
},
|
| 79 |
+
)
|
| 80 |
+
if extra_index:
|
| 81 |
+
desc.update(extra_index)
|
| 82 |
+
rows.append(desc)
|
| 83 |
+
return rows
|
country_laws_ir/query.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Thin-client query for country-laws IR releases (local dir)."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
K1 = 1.2
|
| 15 |
+
B = 0.75
|
| 16 |
+
TITLE_WEIGHT = 5.0
|
| 17 |
+
BODY_WEIGHT = 1.0
|
| 18 |
+
MAX_QUERY_TERMS = 64
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def tokenize(text: str) -> list[str]:
|
| 22 |
+
import re
|
| 23 |
+
import unicodedata
|
| 24 |
+
|
| 25 |
+
if not text:
|
| 26 |
+
return []
|
| 27 |
+
nfkd = unicodedata.normalize("NFKD", text)
|
| 28 |
+
folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
|
| 29 |
+
return re.findall(r"[0-9A-Za-z]+", folded)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Release:
|
| 33 |
+
def __init__(self, root: Path):
|
| 34 |
+
self.root = Path(root)
|
| 35 |
+
self.manifest = json.loads((self.root / "manifest.json").read_text(encoding="utf-8"))
|
| 36 |
+
|
| 37 |
+
def _read(self, rel: str) -> pd.DataFrame:
|
| 38 |
+
path = self.root / rel
|
| 39 |
+
if path.is_dir():
|
| 40 |
+
files = sorted(path.glob("*.parquet"))
|
| 41 |
+
return pd.concat([pd.read_parquet(f) for f in files], ignore_index=True) if files else pd.DataFrame()
|
| 42 |
+
return pd.read_parquet(path)
|
| 43 |
+
|
| 44 |
+
def bm25(self, query: str, top_k: int = 10) -> list[dict]:
|
| 45 |
+
q_terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 46 |
+
if not q_terms:
|
| 47 |
+
return []
|
| 48 |
+
shards = pd.read_parquet(self.root / "indexes" / "bm25_keyword_shards.parquet")
|
| 49 |
+
needed = set()
|
| 50 |
+
for term in q_terms:
|
| 51 |
+
hit = shards[(shards["first_key"] <= term) & (shards["last_key"] >= term)]
|
| 52 |
+
if hit.empty:
|
| 53 |
+
hit = shards
|
| 54 |
+
for rel in hit["relative_path"].tolist():
|
| 55 |
+
needed.add(rel)
|
| 56 |
+
postings = pd.concat(
|
| 57 |
+
[pd.read_parquet(self.root / rel) for rel in sorted(needed)],
|
| 58 |
+
ignore_index=True,
|
| 59 |
+
)
|
| 60 |
+
postings = postings[postings["term"].isin(q_terms)]
|
| 61 |
+
docs = self._read("data/bm25/documents")
|
| 62 |
+
avgdl = float(self.manifest["bm25"]["average_document_length"]) or 1.0
|
| 63 |
+
scores: dict[int, float] = defaultdict(float)
|
| 64 |
+
for rec in postings.itertuples(index=False):
|
| 65 |
+
idf = float(rec.idf)
|
| 66 |
+
for di, ttf, btf, dl in zip(
|
| 67 |
+
rec.document_indices, rec.title_frequencies, rec.body_frequencies, rec.document_lengths
|
| 68 |
+
):
|
| 69 |
+
tf = TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf)
|
| 70 |
+
denom = tf + K1 * (1.0 - B + B * (int(dl) / avgdl))
|
| 71 |
+
if denom:
|
| 72 |
+
scores[int(di)] += idf * (tf * (K1 + 1.0)) / denom
|
| 73 |
+
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:top_k]
|
| 74 |
+
by_idx = docs.set_index("document_index")
|
| 75 |
+
out = []
|
| 76 |
+
for di, score in ranked:
|
| 77 |
+
row = by_idx.loc[di]
|
| 78 |
+
out.append(
|
| 79 |
+
{
|
| 80 |
+
"document_index": int(di),
|
| 81 |
+
"entry_cid": row["entry_cid"],
|
| 82 |
+
"title": row["title"],
|
| 83 |
+
"record_type": row["record_type"],
|
| 84 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 85 |
+
"law_cid": row.get("law_cid", ""),
|
| 86 |
+
"score": float(score),
|
| 87 |
+
}
|
| 88 |
+
)
|
| 89 |
+
return out
|
| 90 |
+
|
| 91 |
+
def vector(self, query: str, top_k: int = 10, candidate_centroids: int = 4, device: str = "cpu") -> list[dict]:
|
| 92 |
+
status = (self.manifest.get("vector") or {}).get("status")
|
| 93 |
+
if status == "stub":
|
| 94 |
+
return [{"error": "vectors are stubbed", "reason": self.manifest["vector"].get("stub_reason")}]
|
| 95 |
+
from sentence_transformers import SentenceTransformer
|
| 96 |
+
|
| 97 |
+
model = SentenceTransformer(self.manifest["vector"]["model_name"], device=device)
|
| 98 |
+
q = model.encode([query], normalize_embeddings=True, convert_to_numpy=True)[0].astype(np.float32)
|
| 99 |
+
meta = pd.read_parquet(self.root / "indexes" / "vector_chunks.parquet")
|
| 100 |
+
cents = np.stack(meta["centroid"].map(lambda c: np.asarray(c, dtype=np.float32)).to_numpy())
|
| 101 |
+
sims = cents @ q
|
| 102 |
+
order = np.argsort(-sims)[: max(1, candidate_centroids)]
|
| 103 |
+
shards = meta.iloc[order]
|
| 104 |
+
frames = [pd.read_parquet(self.root / rel) for rel in shards["relative_path"].tolist()]
|
| 105 |
+
vecs = pd.concat(frames, ignore_index=True)
|
| 106 |
+
if "embedding" not in vecs.columns or vecs["embedding"].isna().all():
|
| 107 |
+
return [{"error": "vector shard missing embeddings"}]
|
| 108 |
+
emb = np.stack(vecs["embedding"].map(lambda e: np.asarray(e, dtype=np.float32)).to_numpy())
|
| 109 |
+
scores = emb @ q
|
| 110 |
+
top = np.argsort(-scores)[:top_k]
|
| 111 |
+
out = []
|
| 112 |
+
for i in top:
|
| 113 |
+
row = vecs.iloc[int(i)]
|
| 114 |
+
out.append(
|
| 115 |
+
{
|
| 116 |
+
"document_index": int(row["document_index"]),
|
| 117 |
+
"entry_cid": row["entry_cid"],
|
| 118 |
+
"title": row["title"],
|
| 119 |
+
"record_type": row["record_type"],
|
| 120 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 121 |
+
"score": float(scores[int(i)]),
|
| 122 |
+
}
|
| 123 |
+
)
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]:
|
| 127 |
+
dirs = ["incoming", "outgoing"] if direction == "both" else [direction]
|
| 128 |
+
hits = []
|
| 129 |
+
for d in dirs:
|
| 130 |
+
path = self.root / "data" / "graph" / "adjacency" / d
|
| 131 |
+
files = sorted(path.glob("*.parquet"))
|
| 132 |
+
for f in files:
|
| 133 |
+
df = pd.read_parquet(f)
|
| 134 |
+
sub = df[df["node_cid"] == node_cid]
|
| 135 |
+
for rec in sub.itertuples(index=False):
|
| 136 |
+
for i, neigh in enumerate(rec.neighbor_cids):
|
| 137 |
+
hits.append(
|
| 138 |
+
{
|
| 139 |
+
"direction": d,
|
| 140 |
+
"node_cid": node_cid,
|
| 141 |
+
"neighbor_cid": neigh,
|
| 142 |
+
"edge_type": rec.edge_types[i] if i < len(rec.edge_types) else "",
|
| 143 |
+
"score": rec.scores[i] if rec.scores is not None and i < len(rec.scores) else None,
|
| 144 |
+
}
|
| 145 |
+
)
|
| 146 |
+
hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
|
| 147 |
+
return hits[:limit]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _print(rows: list[dict]) -> None:
|
| 151 |
+
print(json.dumps(rows, indent=2, ensure_ascii=False))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def main(argv: list[str] | None = None) -> int:
|
| 155 |
+
ap = argparse.ArgumentParser(description="Query a country-laws IR release")
|
| 156 |
+
ap.add_argument("--local-dir", required=True, help="Path to local release root")
|
| 157 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 158 |
+
|
| 159 |
+
p_bm = sub.add_parser("bm25")
|
| 160 |
+
p_bm.add_argument("query")
|
| 161 |
+
p_bm.add_argument("--top-k", type=int, default=10)
|
| 162 |
+
|
| 163 |
+
p_vec = sub.add_parser("vector")
|
| 164 |
+
p_vec.add_argument("query")
|
| 165 |
+
p_vec.add_argument("--top-k", type=int, default=10)
|
| 166 |
+
p_vec.add_argument("--candidate-centroids", type=int, default=4)
|
| 167 |
+
p_vec.add_argument("--device", default="cpu")
|
| 168 |
+
|
| 169 |
+
p_g = sub.add_parser("graph")
|
| 170 |
+
g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
|
| 171 |
+
p_n = g_sub.add_parser("neighbors")
|
| 172 |
+
p_n.add_argument("node_cid")
|
| 173 |
+
p_n.add_argument("--direction", default="both", choices=["both", "incoming", "outgoing"])
|
| 174 |
+
p_n.add_argument("--limit", type=int, default=25)
|
| 175 |
+
|
| 176 |
+
args = ap.parse_args(argv)
|
| 177 |
+
rel = Release(Path(args.local_dir))
|
| 178 |
+
if args.cmd == "bm25":
|
| 179 |
+
_print(rel.bm25(args.query, top_k=args.top_k))
|
| 180 |
+
elif args.cmd == "vector":
|
| 181 |
+
_print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
|
| 182 |
+
elif args.cmd == "graph" and args.graph_cmd == "neighbors":
|
| 183 |
+
_print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
|
| 184 |
+
return 0
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if __name__ == "__main__":
|
| 188 |
+
raise SystemExit(main())
|
country_laws_ir/schema.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail-closed schema mapping for endomorphosis/ipfs_*_laws parquet tables.
|
| 2 |
+
|
| 3 |
+
Verified 2026-09-03 against Malta (pilot) and Germany (column-drift check):
|
| 4 |
+
|
| 5 |
+
Laws columns (both countries):
|
| 6 |
+
id, title, text, source_url, source_type, jurisdiction, country, language,
|
| 7 |
+
eli, date, date_issued, retrieved_at, license, law_status, identifier,
|
| 8 |
+
official_identifier, article_count, json_path, metadata_json
|
| 9 |
+
|
| 10 |
+
Drift: Malta article_count is int64; Germany article_count is int32.
|
| 11 |
+
Germany eli is frequently null. Neither is a missing identifier.
|
| 12 |
+
|
| 13 |
+
Articles columns (both countries; Malta snapshot has 0 rows):
|
| 14 |
+
law_id, id, title, text, source_url, document_number, article_number,
|
| 15 |
+
record_type, metadata_json
|
| 16 |
+
|
| 17 |
+
Required identity columns are NOT invented. Missing required identifiers
|
| 18 |
+
fail the build.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
REQUIRED_LAW_COLUMNS = ("id", "title", "text")
|
| 24 |
+
REQUIRED_ARTICLE_COLUMNS = ("id", "law_id", "title", "text")
|
| 25 |
+
|
| 26 |
+
OPTIONAL_LAW_COLUMNS = (
|
| 27 |
+
"source_url",
|
| 28 |
+
"source_type",
|
| 29 |
+
"jurisdiction",
|
| 30 |
+
"country",
|
| 31 |
+
"language",
|
| 32 |
+
"eli",
|
| 33 |
+
"date",
|
| 34 |
+
"date_issued",
|
| 35 |
+
"retrieved_at",
|
| 36 |
+
"license",
|
| 37 |
+
"law_status",
|
| 38 |
+
"identifier",
|
| 39 |
+
"official_identifier",
|
| 40 |
+
"article_count",
|
| 41 |
+
"json_path",
|
| 42 |
+
"metadata_json",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
OPTIONAL_ARTICLE_COLUMNS = (
|
| 46 |
+
"source_url",
|
| 47 |
+
"document_number",
|
| 48 |
+
"article_number",
|
| 49 |
+
"record_type",
|
| 50 |
+
"metadata_json",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Canonical field mapping used in the CID-keyed corpus.
|
| 54 |
+
LAW_FIELD_MAP = {
|
| 55 |
+
"source_id": "id",
|
| 56 |
+
"title": "title",
|
| 57 |
+
"body": "text",
|
| 58 |
+
"source_url": "source_url",
|
| 59 |
+
"source_type": "source_type",
|
| 60 |
+
"jurisdiction": "jurisdiction",
|
| 61 |
+
"country": "country",
|
| 62 |
+
"language": "language",
|
| 63 |
+
"eli": "eli",
|
| 64 |
+
"date": "date",
|
| 65 |
+
"date_issued": "date_issued",
|
| 66 |
+
"retrieved_at": "retrieved_at",
|
| 67 |
+
"license_expression": "license",
|
| 68 |
+
"law_status": "law_status",
|
| 69 |
+
"identifier": "identifier",
|
| 70 |
+
"official_identifier": "official_identifier",
|
| 71 |
+
"article_count": "article_count",
|
| 72 |
+
"metadata_json": "metadata_json",
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
ARTICLE_FIELD_MAP = {
|
| 76 |
+
"source_id": "id",
|
| 77 |
+
"law_id": "law_id",
|
| 78 |
+
"title": "title",
|
| 79 |
+
"body": "text",
|
| 80 |
+
"source_url": "source_url",
|
| 81 |
+
"document_number": "document_number",
|
| 82 |
+
"article_number": "article_number",
|
| 83 |
+
"record_type_src": "record_type",
|
| 84 |
+
"metadata_json": "metadata_json",
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SchemaError(ValueError):
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _cols(df) -> set[str]:
|
| 93 |
+
return set(map(str, df.columns))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def validate_laws(df) -> None:
|
| 97 |
+
missing = [c for c in REQUIRED_LAW_COLUMNS if c not in _cols(df)]
|
| 98 |
+
if missing:
|
| 99 |
+
raise SchemaError(
|
| 100 |
+
f"laws.parquet missing required identifier/content columns {missing}; "
|
| 101 |
+
f"present={sorted(_cols(df))}. Fail closed — will not invent ids."
|
| 102 |
+
)
|
| 103 |
+
null_ids = int(df["id"].isna().sum()) if "id" in df.columns else len(df)
|
| 104 |
+
empty_ids = int((df["id"].astype(str).str.strip() == "").sum()) if "id" in df.columns else 0
|
| 105 |
+
if null_ids or empty_ids:
|
| 106 |
+
raise SchemaError(
|
| 107 |
+
f"laws.parquet has {null_ids} null and {empty_ids} empty id values. Fail closed."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def validate_articles(df) -> None:
|
| 112 |
+
if df is None or df.empty:
|
| 113 |
+
return
|
| 114 |
+
missing = [c for c in REQUIRED_ARTICLE_COLUMNS if c not in _cols(df)]
|
| 115 |
+
if missing:
|
| 116 |
+
raise SchemaError(
|
| 117 |
+
f"articles.parquet missing required identifier/content columns {missing}; "
|
| 118 |
+
f"present={sorted(_cols(df))}. Fail closed — will not invent ids."
|
| 119 |
+
)
|
| 120 |
+
null_ids = int(df["id"].isna().sum())
|
| 121 |
+
null_law = int(df["law_id"].isna().sum())
|
| 122 |
+
empty_ids = int((df["id"].astype(str).str.strip() == "").sum())
|
| 123 |
+
empty_law = int((df["law_id"].astype(str).str.strip() == "").sum())
|
| 124 |
+
if null_ids or empty_ids or null_law or empty_law:
|
| 125 |
+
raise SchemaError(
|
| 126 |
+
f"articles.parquet has null/empty identifiers "
|
| 127 |
+
f"(id null={null_ids} empty={empty_ids}; law_id null={null_law} empty={empty_law}). Fail closed."
|
| 128 |
+
)
|
country_laws_ir/spill.py
ADDED
|
@@ -0,0 +1,763 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Disk-spill helpers for large country IR builds (SQLite FTS neighbors + BM25 TF).
|
| 2 |
+
|
| 3 |
+
Design (CoS / DO OOM lesson):
|
| 4 |
+
- Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).
|
| 5 |
+
- Neighbors for n >= SQLITE_THRESHOLD (40k): SQLite FTS5 title-only MATCH streaming
|
| 6 |
+
into neighbor_*.pkl shards under cache/<slug>_bm25_spill/ — never hold full
|
| 7 |
+
neighbor matrix in RAM during streaming.
|
| 8 |
+
- BM25 TF: stream tokenize → SQLite WITHOUT ROWID → posting parquet parts.
|
| 9 |
+
- Package: use package.package_release_sequential / package_from_spill so corpus,
|
| 10 |
+
bm25, graph, vectors are never all resident together; neighbor edges can be
|
| 11 |
+
streamed from shards into graph then spilled as graph.pkl.
|
| 12 |
+
|
| 13 |
+
Resume-safe: existing FTS DB / neighbor shards / bm25_*.parquet are reused when
|
| 14 |
+
row counts match.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import gc
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
import pickle
|
| 22 |
+
import sqlite3
|
| 23 |
+
from collections import defaultdict
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Any, Callable, Iterable, Iterator
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
import pyarrow.parquet as pq
|
| 30 |
+
|
| 31 |
+
from . import SCHEMA_VERSION
|
| 32 |
+
from .bm25 import (
|
| 33 |
+
B,
|
| 34 |
+
BODY_WEIGHT,
|
| 35 |
+
K1,
|
| 36 |
+
POSTING_ROWS_PER_RECORD,
|
| 37 |
+
TERMS_PER_SHARD,
|
| 38 |
+
TITLE_WEIGHT,
|
| 39 |
+
)
|
| 40 |
+
from .graph import _adjacency, _edge, build_graph
|
| 41 |
+
from .mem import MemAbort, checkpoint, log_mem
|
| 42 |
+
from .tokenize import tokenize
|
| 43 |
+
|
| 44 |
+
SQLITE_THRESHOLD = 40_000
|
| 45 |
+
BATCH = 256
|
| 46 |
+
NEIGHBOR_SHARD = 5_000
|
| 47 |
+
NEIGHBOR_K = 8
|
| 48 |
+
DF_CAP = 1500
|
| 49 |
+
MAX_QTERMS = 8
|
| 50 |
+
TITLE_W = TITLE_WEIGHT
|
| 51 |
+
BODY_W = BODY_WEIGHT
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def spill_dir_for(slug: str, cache: Path) -> Path:
|
| 55 |
+
return Path(cache) / f"{slug}_bm25_spill"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def spill_pickle(path: Path, obj: Any) -> None:
|
| 59 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 60 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 61 |
+
with tmp.open("wb") as f:
|
| 62 |
+
pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 63 |
+
tmp.replace(path)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_pickle(path: Path) -> Any:
|
| 67 |
+
with path.open("rb") as f:
|
| 68 |
+
return pickle.load(f)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def quote_fts_term(term: str) -> str:
|
| 72 |
+
return '"' + term.replace('"', '""') + '"'
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _idf(n_docs: int, df: int) -> float:
|
| 76 |
+
return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def sqlite_ready(db_path: Path, expected: int) -> bool:
|
| 80 |
+
if not db_path.is_file():
|
| 81 |
+
return False
|
| 82 |
+
try:
|
| 83 |
+
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
| 84 |
+
n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 85 |
+
conn.close()
|
| 86 |
+
return n == expected
|
| 87 |
+
except Exception:
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def build_sqlite_fts(
|
| 92 |
+
corpus_path: Path,
|
| 93 |
+
db_path: Path,
|
| 94 |
+
expected: int,
|
| 95 |
+
*,
|
| 96 |
+
batch: int = BATCH,
|
| 97 |
+
log: Callable[[str], None] | None = None,
|
| 98 |
+
) -> int:
|
| 99 |
+
"""Contentless FTS5 over title+body; documents table holds query_text."""
|
| 100 |
+
if db_path.exists():
|
| 101 |
+
db_path.unlink()
|
| 102 |
+
db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 103 |
+
conn = sqlite3.connect(str(db_path))
|
| 104 |
+
try:
|
| 105 |
+
conn.executescript(
|
| 106 |
+
"""
|
| 107 |
+
PRAGMA journal_mode = OFF;
|
| 108 |
+
PRAGMA synchronous = OFF;
|
| 109 |
+
PRAGMA temp_store = MEMORY;
|
| 110 |
+
PRAGMA locking_mode = EXCLUSIVE;
|
| 111 |
+
PRAGMA page_size = 32768;
|
| 112 |
+
CREATE TABLE documents (
|
| 113 |
+
document_index INTEGER PRIMARY KEY,
|
| 114 |
+
entry_cid TEXT NOT NULL UNIQUE,
|
| 115 |
+
title TEXT NOT NULL,
|
| 116 |
+
query_text TEXT NOT NULL
|
| 117 |
+
);
|
| 118 |
+
CREATE VIRTUAL TABLE documents_fts USING fts5(
|
| 119 |
+
title,
|
| 120 |
+
body,
|
| 121 |
+
content='',
|
| 122 |
+
columnsize=1,
|
| 123 |
+
tokenize='unicode61 remove_diacritics 2'
|
| 124 |
+
);
|
| 125 |
+
"""
|
| 126 |
+
)
|
| 127 |
+
pf = pq.ParquetFile(corpus_path)
|
| 128 |
+
n = 0
|
| 129 |
+
meta_batch: list[tuple] = []
|
| 130 |
+
fts_batch: list[tuple] = []
|
| 131 |
+
conn.execute("BEGIN")
|
| 132 |
+
for batch_tbl in pf.iter_batches(
|
| 133 |
+
batch_size=batch, columns=["document_index", "entry_cid", "title", "body"]
|
| 134 |
+
):
|
| 135 |
+
cols = batch_tbl.to_pydict()
|
| 136 |
+
for i in range(len(cols["document_index"])):
|
| 137 |
+
di = int(cols["document_index"][i])
|
| 138 |
+
title = str(cols["title"][i] or "")
|
| 139 |
+
body = str(cols["body"][i] or "")
|
| 140 |
+
cid = str(cols["entry_cid"][i])
|
| 141 |
+
qtext = title.strip() if title.strip() else body[:800]
|
| 142 |
+
meta_batch.append((di, cid, title, qtext))
|
| 143 |
+
fts_batch.append((di + 1, title, body))
|
| 144 |
+
if len(meta_batch) >= batch:
|
| 145 |
+
conn.executemany(
|
| 146 |
+
"INSERT INTO documents(document_index, entry_cid, title, query_text) "
|
| 147 |
+
"VALUES (?,?,?,?)",
|
| 148 |
+
meta_batch,
|
| 149 |
+
)
|
| 150 |
+
conn.executemany(
|
| 151 |
+
"INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)",
|
| 152 |
+
fts_batch,
|
| 153 |
+
)
|
| 154 |
+
n += len(meta_batch)
|
| 155 |
+
meta_batch.clear()
|
| 156 |
+
fts_batch.clear()
|
| 157 |
+
if n % 20_000 == 0:
|
| 158 |
+
checkpoint(f"fts_insert@{n}", row=n, every_n=20_000, log=log)
|
| 159 |
+
gc.collect()
|
| 160 |
+
if meta_batch:
|
| 161 |
+
conn.executemany(
|
| 162 |
+
"INSERT INTO documents(document_index, entry_cid, title, query_text) "
|
| 163 |
+
"VALUES (?,?,?,?)",
|
| 164 |
+
meta_batch,
|
| 165 |
+
)
|
| 166 |
+
conn.executemany(
|
| 167 |
+
"INSERT INTO documents_fts(rowid, title, body) VALUES (?,?,?)",
|
| 168 |
+
fts_batch,
|
| 169 |
+
)
|
| 170 |
+
n += len(meta_batch)
|
| 171 |
+
conn.commit()
|
| 172 |
+
conn.execute("INSERT INTO documents_fts(documents_fts) VALUES('optimize')")
|
| 173 |
+
conn.commit()
|
| 174 |
+
conn.execute(
|
| 175 |
+
"CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')"
|
| 176 |
+
)
|
| 177 |
+
conn.commit()
|
| 178 |
+
got = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 179 |
+
assert got == n == expected, (got, n, expected)
|
| 180 |
+
return n
|
| 181 |
+
except Exception:
|
| 182 |
+
conn.rollback()
|
| 183 |
+
raise
|
| 184 |
+
finally:
|
| 185 |
+
conn.close()
|
| 186 |
+
gc.collect()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def load_df_map(conn: sqlite3.Connection, df_cap: int = DF_CAP) -> dict[str, int]:
|
| 190 |
+
df_map: dict[str, int] = {}
|
| 191 |
+
for term, doc in conn.execute(
|
| 192 |
+
"SELECT term, doc FROM documents_vocab WHERE doc <= ?", (df_cap,)
|
| 193 |
+
):
|
| 194 |
+
df_map[str(term)] = int(doc)
|
| 195 |
+
return df_map
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def select_query_terms(query_text: str, df_map: dict[str, int]) -> list[str]:
|
| 199 |
+
toks = tokenize(query_text)[:24]
|
| 200 |
+
seen: set[str] = set()
|
| 201 |
+
cands: list[tuple[int, str]] = []
|
| 202 |
+
for t in toks:
|
| 203 |
+
if t in seen or len(t) < 2:
|
| 204 |
+
continue
|
| 205 |
+
seen.add(t)
|
| 206 |
+
if t not in df_map:
|
| 207 |
+
continue
|
| 208 |
+
cands.append((df_map[t], t))
|
| 209 |
+
cands.sort()
|
| 210 |
+
return [t for _, t in cands[:MAX_QTERMS]]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def stream_neighbors_to_shards(
|
| 214 |
+
db_path: Path,
|
| 215 |
+
spill: Path,
|
| 216 |
+
n_docs: int,
|
| 217 |
+
*,
|
| 218 |
+
k: int = NEIGHBOR_K,
|
| 219 |
+
shard: int = NEIGHBOR_SHARD,
|
| 220 |
+
batch: int = BATCH,
|
| 221 |
+
df_cap: int = DF_CAP,
|
| 222 |
+
resume: bool = True,
|
| 223 |
+
log: Callable[[str], None] | None = None,
|
| 224 |
+
) -> list[Path]:
|
| 225 |
+
"""Stream FTS5 title-only neighbors into neighbor_START_END.pkl shards.
|
| 226 |
+
|
| 227 |
+
Does not assemble the full neighbor list. Resume skips shards already on disk
|
| 228 |
+
whose end index is covered (contiguous from 0).
|
| 229 |
+
"""
|
| 230 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 231 |
+
existing = sorted(spill.glob("neighbors_*.pkl"))
|
| 232 |
+
buf_start = 0
|
| 233 |
+
shard_paths: list[Path] = []
|
| 234 |
+
if resume and existing:
|
| 235 |
+
# Contiguous cover from 0
|
| 236 |
+
covered = 0
|
| 237 |
+
for sp in existing:
|
| 238 |
+
parts = sp.stem.split("_")
|
| 239 |
+
# neighbors_000000_005000
|
| 240 |
+
try:
|
| 241 |
+
start_i, end_i = int(parts[1]), int(parts[2])
|
| 242 |
+
except (IndexError, ValueError):
|
| 243 |
+
continue
|
| 244 |
+
if start_i != covered:
|
| 245 |
+
break
|
| 246 |
+
shard_paths.append(sp)
|
| 247 |
+
covered = end_i
|
| 248 |
+
buf_start = covered
|
| 249 |
+
if buf_start >= n_docs:
|
| 250 |
+
if log:
|
| 251 |
+
log(f"neighbors resume complete {buf_start}/{n_docs}")
|
| 252 |
+
return shard_paths
|
| 253 |
+
if log:
|
| 254 |
+
log(f"neighbors resume from {buf_start}/{n_docs} shards={len(shard_paths)}")
|
| 255 |
+
# Drop non-contiguous leftover shards beyond covered
|
| 256 |
+
for sp in existing:
|
| 257 |
+
if sp not in shard_paths:
|
| 258 |
+
sp.unlink(missing_ok=True)
|
| 259 |
+
else:
|
| 260 |
+
for sp in existing:
|
| 261 |
+
sp.unlink(missing_ok=True)
|
| 262 |
+
|
| 263 |
+
conn_rw = sqlite3.connect(str(db_path))
|
| 264 |
+
row = conn_rw.execute(
|
| 265 |
+
"SELECT name FROM sqlite_master WHERE name='documents_vocab'"
|
| 266 |
+
).fetchone()
|
| 267 |
+
if row is None:
|
| 268 |
+
conn_rw.execute(
|
| 269 |
+
"CREATE VIRTUAL TABLE documents_vocab USING fts5vocab(documents_fts, 'row')"
|
| 270 |
+
)
|
| 271 |
+
conn_rw.commit()
|
| 272 |
+
df_map = load_df_map(conn_rw, df_cap)
|
| 273 |
+
conn_rw.close()
|
| 274 |
+
spill_pickle(spill / "df_map_meta.pkl", {"n_rare": len(df_map), "df_cap": df_cap})
|
| 275 |
+
if log:
|
| 276 |
+
log(f"vocab rare_terms={len(df_map)} df_cap={df_cap}")
|
| 277 |
+
|
| 278 |
+
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
| 279 |
+
conn.row_factory = sqlite3.Row
|
| 280 |
+
buf: list = []
|
| 281 |
+
done = buf_start
|
| 282 |
+
score_sql = f"-bm25(documents_fts, {TITLE_W}, {BODY_W})"
|
| 283 |
+
last_idx = buf_start - 1
|
| 284 |
+
try:
|
| 285 |
+
while True:
|
| 286 |
+
rows = conn.execute(
|
| 287 |
+
"SELECT document_index, entry_cid, query_text FROM documents "
|
| 288 |
+
"WHERE document_index > ? ORDER BY document_index LIMIT ?",
|
| 289 |
+
(last_idx, batch),
|
| 290 |
+
).fetchall()
|
| 291 |
+
if not rows:
|
| 292 |
+
break
|
| 293 |
+
for row in rows:
|
| 294 |
+
di = int(row["document_index"])
|
| 295 |
+
terms = select_query_terms(str(row["query_text"]), df_map)
|
| 296 |
+
if not terms:
|
| 297 |
+
neigh: list = []
|
| 298 |
+
else:
|
| 299 |
+
expr = " OR ".join("title : " + quote_fts_term(t) for t in terms)
|
| 300 |
+
sql = (
|
| 301 |
+
"SELECT d.document_index, " + score_sql + " AS score "
|
| 302 |
+
"FROM documents_fts "
|
| 303 |
+
"JOIN documents AS d ON d.document_index = documents_fts.rowid - 1 "
|
| 304 |
+
"WHERE documents_fts MATCH ? AND d.document_index != ? "
|
| 305 |
+
"ORDER BY score DESC, d.document_index LIMIT ?"
|
| 306 |
+
)
|
| 307 |
+
hits = conn.execute(sql, (expr, di, k)).fetchall()
|
| 308 |
+
neigh = [
|
| 309 |
+
(int(h["document_index"]), max(0.0, float(h["score"])), list(terms)[:4])
|
| 310 |
+
for h in hits
|
| 311 |
+
]
|
| 312 |
+
while buf_start + len(buf) < di:
|
| 313 |
+
buf.append([])
|
| 314 |
+
buf.append(neigh)
|
| 315 |
+
last_idx = di
|
| 316 |
+
done += 1
|
| 317 |
+
if len(buf) >= shard:
|
| 318 |
+
end = buf_start + len(buf)
|
| 319 |
+
sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl"
|
| 320 |
+
spill_pickle(sp, buf)
|
| 321 |
+
shard_paths.append(sp)
|
| 322 |
+
checkpoint(
|
| 323 |
+
f"neighbors_shard_{buf_start}_{end}",
|
| 324 |
+
log=log,
|
| 325 |
+
)
|
| 326 |
+
buf_start = end
|
| 327 |
+
buf = []
|
| 328 |
+
gc.collect()
|
| 329 |
+
if done % 5_000 == 0:
|
| 330 |
+
checkpoint(f"neighbors_stream", row=done, every_n=5_000, log=log)
|
| 331 |
+
if buf:
|
| 332 |
+
end = buf_start + len(buf)
|
| 333 |
+
sp = spill / f"neighbors_{buf_start:06d}_{end:06d}.pkl"
|
| 334 |
+
spill_pickle(sp, buf)
|
| 335 |
+
shard_paths.append(sp)
|
| 336 |
+
if log:
|
| 337 |
+
log(f"neighbors shard final {buf_start}:{end}/{n_docs}")
|
| 338 |
+
if log:
|
| 339 |
+
log(f"bm25 neighbors streamed done={done} n_docs={n_docs} shards={len(shard_paths)}")
|
| 340 |
+
return shard_paths
|
| 341 |
+
finally:
|
| 342 |
+
conn.close()
|
| 343 |
+
del df_map
|
| 344 |
+
gc.collect()
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]:
|
| 348 |
+
"""Yield (start_index, shard_list) without loading all shards."""
|
| 349 |
+
paths = sorted(spill.glob("neighbors_*.pkl"))
|
| 350 |
+
for sp in paths:
|
| 351 |
+
parts = sp.stem.split("_")
|
| 352 |
+
start_i = int(parts[1])
|
| 353 |
+
yield start_i, load_pickle(sp)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def assemble_neighbors_streaming(spill: Path, n_docs: int) -> list:
|
| 357 |
+
"""Assemble only when unavoidable; prefer build_graph_from_neighbor_shards."""
|
| 358 |
+
neighbors: list = []
|
| 359 |
+
for start_i, part in iter_neighbor_shards(spill):
|
| 360 |
+
while len(neighbors) < start_i:
|
| 361 |
+
neighbors.append([])
|
| 362 |
+
neighbors.extend(part)
|
| 363 |
+
del part
|
| 364 |
+
gc.collect()
|
| 365 |
+
while len(neighbors) < n_docs:
|
| 366 |
+
neighbors.append([])
|
| 367 |
+
if len(neighbors) > n_docs:
|
| 368 |
+
neighbors = neighbors[:n_docs]
|
| 369 |
+
return neighbors
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def neighbors_via_sqlite(
|
| 373 |
+
corpus_path: Path,
|
| 374 |
+
spill: Path,
|
| 375 |
+
n_docs: int,
|
| 376 |
+
*,
|
| 377 |
+
k: int = NEIGHBOR_K,
|
| 378 |
+
resume: bool = True,
|
| 379 |
+
log: Callable[[str], None] | None = None,
|
| 380 |
+
) -> list[Path]:
|
| 381 |
+
"""Ensure FTS DB + neighbor shards; return shard paths (not full list)."""
|
| 382 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 383 |
+
db_path = spill / "fts.sqlite"
|
| 384 |
+
if not sqlite_ready(db_path, n_docs):
|
| 385 |
+
if db_path.exists():
|
| 386 |
+
db_path.unlink()
|
| 387 |
+
if log:
|
| 388 |
+
log(f"building sqlite fts n={n_docs} -> {db_path}")
|
| 389 |
+
build_sqlite_fts(corpus_path, db_path, n_docs, log=log)
|
| 390 |
+
else:
|
| 391 |
+
if log:
|
| 392 |
+
log(f"reusing sqlite fts n={n_docs} path={db_path}")
|
| 393 |
+
return stream_neighbors_to_shards(
|
| 394 |
+
db_path, spill, n_docs, k=k, resume=resume, log=log
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def build_graph_from_neighbor_shards(
|
| 399 |
+
corpus: pd.DataFrame,
|
| 400 |
+
spill: Path,
|
| 401 |
+
*,
|
| 402 |
+
log: Callable[[str], None] | None = None,
|
| 403 |
+
) -> dict[str, Any]:
|
| 404 |
+
"""Build graph without holding the full neighbor list.
|
| 405 |
+
|
| 406 |
+
Structural edges first (neighbors=[]), then stream BM25_NEIGHBOR_OF from shards
|
| 407 |
+
and recompute adjacency once.
|
| 408 |
+
"""
|
| 409 |
+
n = len(corpus)
|
| 410 |
+
# Structural + facets only
|
| 411 |
+
graph = build_graph(corpus, [[] for _ in range(n)])
|
| 412 |
+
cid_by_idx = corpus["entry_cid"].tolist()
|
| 413 |
+
extra_edges: list[dict[str, Any]] = []
|
| 414 |
+
seen = 0
|
| 415 |
+
for start_i, part in iter_neighbor_shards(spill):
|
| 416 |
+
for offset, neigh in enumerate(part):
|
| 417 |
+
i = start_i + offset
|
| 418 |
+
if i >= n:
|
| 419 |
+
break
|
| 420 |
+
src = cid_by_idx[i]
|
| 421 |
+
for item in neigh:
|
| 422 |
+
if len(item) == 3:
|
| 423 |
+
j, score, terms = item
|
| 424 |
+
else:
|
| 425 |
+
j, score = item[0], item[1]
|
| 426 |
+
terms = []
|
| 427 |
+
tgt = cid_by_idx[int(j)]
|
| 428 |
+
extra_edges.append(
|
| 429 |
+
_edge(
|
| 430 |
+
src,
|
| 431 |
+
"BM25_NEIGHBOR_OF",
|
| 432 |
+
tgt,
|
| 433 |
+
"bm25-okapi",
|
| 434 |
+
float(score),
|
| 435 |
+
{"k": 8, "neighbor_index": int(j)},
|
| 436 |
+
matched_terms=list(terms),
|
| 437 |
+
)
|
| 438 |
+
)
|
| 439 |
+
seen += len(part)
|
| 440 |
+
del part
|
| 441 |
+
if len(extra_edges) >= 50_000:
|
| 442 |
+
# Flush into edges df incrementally
|
| 443 |
+
add = pd.DataFrame(extra_edges)
|
| 444 |
+
graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True)
|
| 445 |
+
extra_edges.clear()
|
| 446 |
+
del add
|
| 447 |
+
gc.collect()
|
| 448 |
+
checkpoint(f"graph_neighbor_edges@{seen}", row=seen, every_n=50_000, log=log)
|
| 449 |
+
if extra_edges:
|
| 450 |
+
add = pd.DataFrame(extra_edges)
|
| 451 |
+
graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True)
|
| 452 |
+
del add, extra_edges
|
| 453 |
+
gc.collect()
|
| 454 |
+
|
| 455 |
+
edges_df = graph["edges"]
|
| 456 |
+
if not edges_df.empty:
|
| 457 |
+
edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True)
|
| 458 |
+
edges_df = edges_df.sort_values(
|
| 459 |
+
["edge_type", "source_cid", "target_cid"]
|
| 460 |
+
).reset_index(drop=True)
|
| 461 |
+
graph["edges"] = edges_df
|
| 462 |
+
node_type = {r["node_cid"]: r["node_type"] for r in graph["nodes"].to_dict("records")}
|
| 463 |
+
incoming, outgoing = _adjacency(edges_df, node_type)
|
| 464 |
+
graph["incoming"] = incoming
|
| 465 |
+
graph["outgoing"] = outgoing
|
| 466 |
+
graph["stats"] = {
|
| 467 |
+
"n_nodes": int(len(graph["nodes"])),
|
| 468 |
+
"n_edges": int(len(edges_df)),
|
| 469 |
+
"n_doc_nodes": int(
|
| 470 |
+
graph["nodes"]["node_type"].isin(["law_entry", "article", "law"]).sum()
|
| 471 |
+
),
|
| 472 |
+
"n_facet_nodes": int(
|
| 473 |
+
graph["nodes"]["node_type"].astype(str).str.startswith("facet_").sum()
|
| 474 |
+
),
|
| 475 |
+
"edge_types": sorted(edges_df["edge_type"].unique().tolist())
|
| 476 |
+
if not edges_df.empty
|
| 477 |
+
else [],
|
| 478 |
+
}
|
| 479 |
+
if log:
|
| 480 |
+
log(
|
| 481 |
+
f"graph from shards nodes={graph['stats']['n_nodes']} "
|
| 482 |
+
f"edges={graph['stats']['n_edges']}"
|
| 483 |
+
)
|
| 484 |
+
return graph
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def build_bm25_tf_spill(
|
| 488 |
+
corpus_path: Path,
|
| 489 |
+
spill: Path,
|
| 490 |
+
n_docs: int,
|
| 491 |
+
*,
|
| 492 |
+
batch: int = 512,
|
| 493 |
+
log: Callable[[str], None] | None = None,
|
| 494 |
+
) -> dict[str, Any]:
|
| 495 |
+
"""Stream tokenize corpus → SQLite TF → bm25_documents/postings parquet + stats.
|
| 496 |
+
|
| 497 |
+
Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.pkl exist
|
| 498 |
+
with matching n_docs, reuse.
|
| 499 |
+
"""
|
| 500 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 501 |
+
docs_path = spill / "bm25_documents.parquet"
|
| 502 |
+
post_path = spill / "bm25_postings.parquet"
|
| 503 |
+
stats_path = spill / "bm25_stats.pkl"
|
| 504 |
+
if docs_path.is_file() and post_path.is_file() and stats_path.is_file():
|
| 505 |
+
stats = load_pickle(stats_path)
|
| 506 |
+
if int(stats.get("n_docs", -1)) == n_docs:
|
| 507 |
+
if log:
|
| 508 |
+
log(f"reusing bm25 spill n_docs={n_docs}")
|
| 509 |
+
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 510 |
+
|
| 511 |
+
bm25_sql = spill / "bm25_tf.sqlite"
|
| 512 |
+
if bm25_sql.exists():
|
| 513 |
+
bm25_sql.unlink()
|
| 514 |
+
conn = sqlite3.connect(str(bm25_sql))
|
| 515 |
+
conn.execute("PRAGMA journal_mode=OFF")
|
| 516 |
+
conn.execute("PRAGMA synchronous=OFF")
|
| 517 |
+
conn.execute("PRAGMA temp_store=MEMORY")
|
| 518 |
+
conn.execute("PRAGMA locking_mode=EXCLUSIVE")
|
| 519 |
+
conn.execute(
|
| 520 |
+
"CREATE TABLE tf (term TEXT NOT NULL, doc INTEGER NOT NULL, "
|
| 521 |
+
"ttf INTEGER NOT NULL, btf INTEGER NOT NULL, PRIMARY KEY(term, doc)) WITHOUT ROWID"
|
| 522 |
+
)
|
| 523 |
+
title_len = np.zeros(n_docs, dtype=np.int32)
|
| 524 |
+
body_len = np.zeros(n_docs, dtype=np.int32)
|
| 525 |
+
meta_path = spill / "doc_meta_rows.parquet"
|
| 526 |
+
meta_path.unlink(missing_ok=True)
|
| 527 |
+
meta_buf: list[dict] = []
|
| 528 |
+
pf = pq.ParquetFile(corpus_path)
|
| 529 |
+
schema_names = set(pf.schema_arrow.names)
|
| 530 |
+
cols = [
|
| 531 |
+
c
|
| 532 |
+
for c in [
|
| 533 |
+
"document_index",
|
| 534 |
+
"entry_cid",
|
| 535 |
+
"law_cid",
|
| 536 |
+
"instrument_id",
|
| 537 |
+
"law_id",
|
| 538 |
+
"source_id",
|
| 539 |
+
"title",
|
| 540 |
+
"instrument_title",
|
| 541 |
+
"article_number",
|
| 542 |
+
"article_title",
|
| 543 |
+
"record_type",
|
| 544 |
+
"language",
|
| 545 |
+
"jurisdiction",
|
| 546 |
+
"body",
|
| 547 |
+
]
|
| 548 |
+
if c in schema_names
|
| 549 |
+
]
|
| 550 |
+
processed = 0
|
| 551 |
+
batch_rows: list[tuple] = []
|
| 552 |
+
conn.execute("BEGIN")
|
| 553 |
+
for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols):
|
| 554 |
+
d = batch_tbl.to_pydict()
|
| 555 |
+
m = len(d["document_index"])
|
| 556 |
+
for i in range(m):
|
| 557 |
+
di = int(d["document_index"][i])
|
| 558 |
+
title = str((d.get("title") or [""])[i] or "")
|
| 559 |
+
body = str((d.get("body") or [""])[i] or "")
|
| 560 |
+
tt = tokenize(title)
|
| 561 |
+
bt = tokenize(body)
|
| 562 |
+
title_len[di] = len(tt)
|
| 563 |
+
body_len[di] = len(bt)
|
| 564 |
+
tf_t: dict[str, int] = defaultdict(int)
|
| 565 |
+
tf_b: dict[str, int] = defaultdict(int)
|
| 566 |
+
for tok in tt:
|
| 567 |
+
tf_t[tok] += 1
|
| 568 |
+
for tok in bt:
|
| 569 |
+
tf_b[tok] += 1
|
| 570 |
+
for tok in set(tf_t) | set(tf_b):
|
| 571 |
+
batch_rows.append((tok, di, int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0))))
|
| 572 |
+
law_id = str((d.get("law_id") or d.get("instrument_id") or [""])[i] or "")
|
| 573 |
+
instrument_id = str(
|
| 574 |
+
(d.get("instrument_id") or d.get("law_id") or [""])[i] or ""
|
| 575 |
+
)
|
| 576 |
+
meta_buf.append(
|
| 577 |
+
{
|
| 578 |
+
"entry_cid": str(d["entry_cid"][i]),
|
| 579 |
+
"document_index": di,
|
| 580 |
+
"law_cid": str((d.get("law_cid") or [""])[i] or ""),
|
| 581 |
+
"instrument_id": instrument_id,
|
| 582 |
+
"law_id": law_id,
|
| 583 |
+
"source_id": str(d["source_id"][i]),
|
| 584 |
+
"title": title,
|
| 585 |
+
"instrument_title": str(
|
| 586 |
+
(d.get("instrument_title") or [""])[i] or ""
|
| 587 |
+
),
|
| 588 |
+
"article_number": str((d.get("article_number") or [""])[i] or ""),
|
| 589 |
+
"article_title": str((d.get("article_title") or [""])[i] or ""),
|
| 590 |
+
"record_type": str(d["record_type"][i]),
|
| 591 |
+
"language": str((d.get("language") or [""])[i] or ""),
|
| 592 |
+
"jurisdiction": str((d.get("jurisdiction") or [""])[i] or ""),
|
| 593 |
+
}
|
| 594 |
+
)
|
| 595 |
+
if len(batch_rows) >= 20_000:
|
| 596 |
+
conn.executemany(
|
| 597 |
+
"INSERT OR REPLACE INTO tf VALUES (?,?,?,?)", batch_rows
|
| 598 |
+
)
|
| 599 |
+
batch_rows.clear()
|
| 600 |
+
processed += m
|
| 601 |
+
if len(meta_buf) >= 20_000:
|
| 602 |
+
dfm = pd.DataFrame(meta_buf)
|
| 603 |
+
if meta_path.exists():
|
| 604 |
+
old = pd.read_parquet(meta_path)
|
| 605 |
+
dfm = pd.concat([old, dfm], ignore_index=True)
|
| 606 |
+
del old
|
| 607 |
+
dfm.to_parquet(meta_path, index=False)
|
| 608 |
+
del dfm
|
| 609 |
+
meta_buf.clear()
|
| 610 |
+
gc.collect()
|
| 611 |
+
if processed % 20_000 == 0:
|
| 612 |
+
checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log)
|
| 613 |
+
gc.collect()
|
| 614 |
+
if batch_rows:
|
| 615 |
+
conn.executemany("INSERT OR REPLACE INTO tf VALUES (?,?,?,?)", batch_rows)
|
| 616 |
+
batch_rows.clear()
|
| 617 |
+
if meta_buf:
|
| 618 |
+
dfm = pd.DataFrame(meta_buf)
|
| 619 |
+
if meta_path.exists():
|
| 620 |
+
old = pd.read_parquet(meta_path)
|
| 621 |
+
dfm = pd.concat([old, dfm], ignore_index=True)
|
| 622 |
+
del old
|
| 623 |
+
dfm.to_parquet(meta_path, index=False)
|
| 624 |
+
del dfm
|
| 625 |
+
meta_buf.clear()
|
| 626 |
+
conn.commit()
|
| 627 |
+
if log:
|
| 628 |
+
log("bm25 tf spilled; writing documents")
|
| 629 |
+
|
| 630 |
+
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
|
| 631 |
+
avgdl = float(doc_len.mean()) if n_docs else 0.0
|
| 632 |
+
meta_df = pd.read_parquet(meta_path).sort_values("document_index").reset_index(drop=True)
|
| 633 |
+
assert len(meta_df) == n_docs
|
| 634 |
+
meta_df["title_length"] = title_len[meta_df["document_index"].to_numpy()]
|
| 635 |
+
meta_df["body_length"] = body_len[meta_df["document_index"].to_numpy()]
|
| 636 |
+
meta_df["document_length"] = np.round(
|
| 637 |
+
doc_len[meta_df["document_index"].to_numpy()]
|
| 638 |
+
).astype(int)
|
| 639 |
+
meta_df["schema_version"] = SCHEMA_VERSION
|
| 640 |
+
meta_df.to_parquet(docs_path, index=False)
|
| 641 |
+
del meta_df
|
| 642 |
+
gc.collect()
|
| 643 |
+
meta_path.unlink(missing_ok=True)
|
| 644 |
+
|
| 645 |
+
posting_rows: list[dict] = []
|
| 646 |
+
n_postings = 0
|
| 647 |
+
n_terms = 0
|
| 648 |
+
part_i = 0
|
| 649 |
+
cur_term = None
|
| 650 |
+
cur_items: list = []
|
| 651 |
+
|
| 652 |
+
def flush_term(term: str, items: list) -> None:
|
| 653 |
+
nonlocal n_postings, n_terms, part_i, posting_rows
|
| 654 |
+
if not items:
|
| 655 |
+
return
|
| 656 |
+
n_terms += 1
|
| 657 |
+
dfreq = len(items)
|
| 658 |
+
cfreq = sum(int(ttf) + int(btf) for _, ttf, btf in items)
|
| 659 |
+
idf = _idf(n_docs, dfreq)
|
| 660 |
+
chunks = [
|
| 661 |
+
items[i : i + POSTING_ROWS_PER_RECORD]
|
| 662 |
+
for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD)
|
| 663 |
+
]
|
| 664 |
+
n_chunks = len(chunks)
|
| 665 |
+
for cidx, chunk in enumerate(chunks):
|
| 666 |
+
posting_rows.append(
|
| 667 |
+
{
|
| 668 |
+
"term": term,
|
| 669 |
+
"document_indices": [int(d) for d, _, _ in chunk],
|
| 670 |
+
"title_frequencies": [int(ttf) for _, ttf, _ in chunk],
|
| 671 |
+
"body_frequencies": [int(btf) for _, _, btf in chunk],
|
| 672 |
+
"tfs": [
|
| 673 |
+
TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf)
|
| 674 |
+
for _, ttf, btf in chunk
|
| 675 |
+
],
|
| 676 |
+
"lengths": [int(round(doc_len[int(d)])) for d, _, _ in chunk],
|
| 677 |
+
"document_lengths": [
|
| 678 |
+
int(round(doc_len[int(d)])) for d, _, _ in chunk
|
| 679 |
+
],
|
| 680 |
+
"document_frequency": int(dfreq),
|
| 681 |
+
"corpus_frequency": int(cfreq),
|
| 682 |
+
"idf": float(idf),
|
| 683 |
+
"posting_chunk_index": int(cidx),
|
| 684 |
+
"posting_chunk_count": int(n_chunks),
|
| 685 |
+
"schema_version": SCHEMA_VERSION,
|
| 686 |
+
}
|
| 687 |
+
)
|
| 688 |
+
n_postings += dfreq
|
| 689 |
+
if len(posting_rows) >= 8_000:
|
| 690 |
+
pd.DataFrame(posting_rows).to_parquet(
|
| 691 |
+
spill / f"postings_part_{part_i:08d}.parquet", index=False
|
| 692 |
+
)
|
| 693 |
+
posting_rows.clear()
|
| 694 |
+
part_i += 1
|
| 695 |
+
gc.collect()
|
| 696 |
+
|
| 697 |
+
for term, doc, ttf, btf in conn.execute(
|
| 698 |
+
"SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc"
|
| 699 |
+
):
|
| 700 |
+
term = str(term)
|
| 701 |
+
if cur_term is None:
|
| 702 |
+
cur_term = term
|
| 703 |
+
if term != cur_term:
|
| 704 |
+
flush_term(cur_term, cur_items)
|
| 705 |
+
cur_items = []
|
| 706 |
+
cur_term = term
|
| 707 |
+
if n_terms and n_terms % 50_000 == 0:
|
| 708 |
+
checkpoint(f"bm25_postings_terms", row=n_terms, every_n=50_000, log=log)
|
| 709 |
+
cur_items.append((int(doc), int(ttf), int(btf)))
|
| 710 |
+
if cur_term is not None:
|
| 711 |
+
flush_term(cur_term, cur_items)
|
| 712 |
+
if posting_rows:
|
| 713 |
+
pd.DataFrame(posting_rows).to_parquet(
|
| 714 |
+
spill / f"postings_part_{part_i:08d}.parquet", index=False
|
| 715 |
+
)
|
| 716 |
+
posting_rows.clear()
|
| 717 |
+
conn.close()
|
| 718 |
+
gc.collect()
|
| 719 |
+
|
| 720 |
+
parts = sorted(spill.glob("postings_part_*.parquet"))
|
| 721 |
+
frames: list[pd.DataFrame] = []
|
| 722 |
+
for i, part in enumerate(parts):
|
| 723 |
+
frames.append(pd.read_parquet(part))
|
| 724 |
+
if len(frames) >= 8:
|
| 725 |
+
frames = [pd.concat(frames, ignore_index=True)]
|
| 726 |
+
gc.collect()
|
| 727 |
+
if i and i % 20 == 0:
|
| 728 |
+
checkpoint(f"concat_postings", row=i, every_n=20, log=log)
|
| 729 |
+
postings = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
|
| 730 |
+
del frames
|
| 731 |
+
for part in parts:
|
| 732 |
+
part.unlink()
|
| 733 |
+
postings.to_parquet(post_path, index=False)
|
| 734 |
+
out_rows = len(postings)
|
| 735 |
+
del postings
|
| 736 |
+
gc.collect()
|
| 737 |
+
stats = {
|
| 738 |
+
"k1": K1,
|
| 739 |
+
"b": B,
|
| 740 |
+
"title_weight": TITLE_WEIGHT,
|
| 741 |
+
"body_weight": BODY_WEIGHT,
|
| 742 |
+
"average_document_length": avgdl,
|
| 743 |
+
"tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1",
|
| 744 |
+
"max_query_terms": 64,
|
| 745 |
+
"posting_rows_per_record": POSTING_ROWS_PER_RECORD,
|
| 746 |
+
"terms_per_shard": TERMS_PER_SHARD,
|
| 747 |
+
"n_docs": n_docs,
|
| 748 |
+
"n_terms": int(n_terms),
|
| 749 |
+
"n_posting_rows": int(out_rows),
|
| 750 |
+
"n_postings": int(n_postings),
|
| 751 |
+
}
|
| 752 |
+
spill_pickle(stats_path, stats)
|
| 753 |
+
try:
|
| 754 |
+
bm25_sql.unlink()
|
| 755 |
+
except Exception:
|
| 756 |
+
pass
|
| 757 |
+
if log:
|
| 758 |
+
log(f"bm25 spill done terms={n_terms} posting_rows={out_rows}")
|
| 759 |
+
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def should_use_sqlite(n_docs: int, threshold: int = SQLITE_THRESHOLD) -> bool:
|
| 763 |
+
return n_docs >= threshold
|
country_laws_ir/tokenize.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FTS5 unicode61 remove_diacritics=2-style tokenizer."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
import unicodedata
|
| 7 |
+
|
| 8 |
+
_TOKEN_RE = re.compile(r"[0-9A-Za-z]+", re.UNICODE)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def fold_diacritics(text: str) -> str:
|
| 12 |
+
if not text:
|
| 13 |
+
return ""
|
| 14 |
+
nfkd = unicodedata.normalize("NFKD", text)
|
| 15 |
+
return "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def tokenize(text: str | None) -> list[str]:
|
| 19 |
+
if not text:
|
| 20 |
+
return []
|
| 21 |
+
return _TOKEN_RE.findall(fold_diacritics(str(text)))
|
country_laws_ir/upload.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hub upload is intentionally not implemented in this local pipeline.
|
| 2 |
+
|
| 3 |
+
Later publish (operator machine, never from this run):
|
| 4 |
+
|
| 5 |
+
export HF_TOKEN=... # never commit / never echo
|
| 6 |
+
hf upload-large-folder justicedao/ipfs_malta_laws_ir \\
|
| 7 |
+
/workspace/country-laws-ir/releases/ipfs_malta_laws_ir \\
|
| 8 |
+
--repo-type dataset --no-private --num-workers 8 \\
|
| 9 |
+
--exclude "**/__pycache__/**" --exclude "**/*.pyc"
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def upload_release(local_dir: Path, repo_id: str) -> dict[str, Any]:
|
| 19 |
+
raise RuntimeError(
|
| 20 |
+
"Hub upload is disabled in the local country-laws-ir pipeline. "
|
| 21 |
+
"Publish later with: hf upload-large-folder "
|
| 22 |
+
f"{repo_id} {local_dir} --repo-type dataset --no-private --num-workers 8 "
|
| 23 |
+
'--exclude "**/__pycache__/**" --exclude "**/*.pyc"'
|
| 24 |
+
)
|
country_laws_ir/vectors.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""thenlper/gte-small 384-d embeddings + centroid-sorted shards.
|
| 2 |
+
|
| 3 |
+
If sentence-transformers/torch cannot embed, layout_stub_vectors() documents the
|
| 4 |
+
expected schema so corpus/BM25/graph releases remain complete.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 15 |
+
|
| 16 |
+
MODEL_NAME = "thenlper/gte-small"
|
| 17 |
+
DIMENSION = 384
|
| 18 |
+
MAX_ROWS_PER_CENTROID = 8192
|
| 19 |
+
MAX_SHARDS_PER_CENTROID = 2
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray:
|
| 23 |
+
n = np.linalg.norm(x, axis=-1, keepdims=True)
|
| 24 |
+
return x / np.maximum(n, eps)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def embeddings_available() -> bool:
|
| 28 |
+
try:
|
| 29 |
+
import torch # noqa: F401
|
| 30 |
+
from sentence_transformers import SentenceTransformer # noqa: F401
|
| 31 |
+
|
| 32 |
+
return True
|
| 33 |
+
except Exception:
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def encode_corpus(
|
| 38 |
+
corpus: pd.DataFrame,
|
| 39 |
+
batch_size: int = 64,
|
| 40 |
+
device: str = "cpu",
|
| 41 |
+
checkpoint_path: str | None = None,
|
| 42 |
+
chunk_size: int = 4096,
|
| 43 |
+
) -> np.ndarray:
|
| 44 |
+
"""Encode corpus texts with gte-small in chunks; persist checkpoints when given."""
|
| 45 |
+
import json
|
| 46 |
+
import os
|
| 47 |
+
from datetime import datetime, timezone
|
| 48 |
+
from pathlib import Path as _Path
|
| 49 |
+
|
| 50 |
+
from sentence_transformers import SentenceTransformer
|
| 51 |
+
|
| 52 |
+
from .auth import configure_hf
|
| 53 |
+
|
| 54 |
+
configure_hf()
|
| 55 |
+
cache_root = _Path("/workspace/country-laws-ir/cache/hf")
|
| 56 |
+
os.environ.setdefault("HF_HOME", str(cache_root))
|
| 57 |
+
os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
|
| 58 |
+
os.environ.setdefault(
|
| 59 |
+
"SENTENCE_TRANSFORMERS_HOME",
|
| 60 |
+
str(cache_root / "sentence-transformers"),
|
| 61 |
+
)
|
| 62 |
+
texts = []
|
| 63 |
+
for rec in corpus.itertuples(index=False):
|
| 64 |
+
title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
|
| 65 |
+
body = getattr(rec, "body", "") or ""
|
| 66 |
+
sid = getattr(rec, "source_id", "") or getattr(rec, "instrument_id", "")
|
| 67 |
+
texts.append(f"{title}\n{body[:4000]}".strip() or title or sid)
|
| 68 |
+
n = len(texts)
|
| 69 |
+
out = np.zeros((n, DIMENSION), dtype=np.float32)
|
| 70 |
+
done = 0
|
| 71 |
+
ckpt = _Path(checkpoint_path) if checkpoint_path else None
|
| 72 |
+
meta_path = ckpt.with_suffix(".json") if ckpt else None
|
| 73 |
+
meta_n = None
|
| 74 |
+
if meta_path is not None and meta_path.exists():
|
| 75 |
+
try:
|
| 76 |
+
meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
|
| 77 |
+
except Exception:
|
| 78 |
+
meta_n = None
|
| 79 |
+
if ckpt is not None and ckpt.exists():
|
| 80 |
+
cached = np.load(ckpt)
|
| 81 |
+
same_corpus = meta_n is None or int(meta_n) == n
|
| 82 |
+
if (
|
| 83 |
+
same_corpus
|
| 84 |
+
and cached.ndim == 2
|
| 85 |
+
and cached.shape[1] == DIMENSION
|
| 86 |
+
and 0 < cached.shape[0] <= n
|
| 87 |
+
):
|
| 88 |
+
done = int(cached.shape[0])
|
| 89 |
+
out[:done] = cached.astype(np.float32, copy=False)
|
| 90 |
+
print(f"embeddings resume {done}/{n} from {ckpt}", flush=True)
|
| 91 |
+
else:
|
| 92 |
+
print(
|
| 93 |
+
f"embeddings checkpoint shape {getattr(cached, 'shape', None)} "
|
| 94 |
+
f"meta_n={meta_n} incompatible with {(n, DIMENSION)}; restarting",
|
| 95 |
+
flush=True,
|
| 96 |
+
)
|
| 97 |
+
if done >= n:
|
| 98 |
+
return out
|
| 99 |
+
model = SentenceTransformer(MODEL_NAME, device=device)
|
| 100 |
+
while done < n:
|
| 101 |
+
j = min(done + int(chunk_size), n)
|
| 102 |
+
chunk = model.encode(
|
| 103 |
+
texts[done:j],
|
| 104 |
+
batch_size=batch_size,
|
| 105 |
+
show_progress_bar=True,
|
| 106 |
+
convert_to_numpy=True,
|
| 107 |
+
normalize_embeddings=True,
|
| 108 |
+
)
|
| 109 |
+
out[done:j] = np.asarray(chunk, dtype=np.float32)
|
| 110 |
+
done = j
|
| 111 |
+
print(f"embeddings checkpoint {done}/{n}", flush=True)
|
| 112 |
+
try:
|
| 113 |
+
from .mem import checkpoint as _mem_checkpoint
|
| 114 |
+
_mem_checkpoint(f"embeddings@{done}", row=done, every_n=max(chunk_size, 4096))
|
| 115 |
+
except Exception as _mem_exc:
|
| 116 |
+
# MemAbort should propagate; other import issues are non-fatal
|
| 117 |
+
from .mem import MemAbort
|
| 118 |
+
if isinstance(_mem_exc, MemAbort):
|
| 119 |
+
raise
|
| 120 |
+
if ckpt is not None:
|
| 121 |
+
ckpt.parent.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
|
| 123 |
+
np.save(tmp, out[:done])
|
| 124 |
+
tmp.replace(ckpt)
|
| 125 |
+
if meta_path is not None:
|
| 126 |
+
meta_path.write_text(
|
| 127 |
+
json.dumps(
|
| 128 |
+
{
|
| 129 |
+
"n": n,
|
| 130 |
+
"done": done,
|
| 131 |
+
"dimension": DIMENSION,
|
| 132 |
+
"model_name": MODEL_NAME,
|
| 133 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 134 |
+
}
|
| 135 |
+
)
|
| 136 |
+
+ "\n",
|
| 137 |
+
encoding="utf-8",
|
| 138 |
+
)
|
| 139 |
+
return out
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
|
| 143 |
+
rng = np.random.default_rng(seed)
|
| 144 |
+
n = len(x)
|
| 145 |
+
k = min(k, n)
|
| 146 |
+
centers = x[rng.choice(n, size=k, replace=False)].copy()
|
| 147 |
+
labels = np.zeros(n, dtype=np.int32)
|
| 148 |
+
for _ in range(iters):
|
| 149 |
+
sim = x @ centers.T
|
| 150 |
+
labels = sim.argmax(axis=1).astype(np.int32)
|
| 151 |
+
new = []
|
| 152 |
+
for j in range(k):
|
| 153 |
+
mask = labels == j
|
| 154 |
+
if not mask.any():
|
| 155 |
+
new.append(x[rng.integers(0, n)])
|
| 156 |
+
else:
|
| 157 |
+
new.append(_l2_normalize(x[mask].mean(axis=0)))
|
| 158 |
+
centers = np.stack(new).astype(np.float32)
|
| 159 |
+
return labels
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
|
| 163 |
+
n = len(x)
|
| 164 |
+
idx = np.arange(n)
|
| 165 |
+
if n <= max_size:
|
| 166 |
+
return [idx]
|
| 167 |
+
labels = _spherical_kmeans(x, k=2)
|
| 168 |
+
clusters = []
|
| 169 |
+
for lab in (0, 1):
|
| 170 |
+
members = idx[labels == lab]
|
| 171 |
+
if len(members) == 0:
|
| 172 |
+
continue
|
| 173 |
+
if len(members) <= max_size:
|
| 174 |
+
clusters.append(members)
|
| 175 |
+
else:
|
| 176 |
+
sub = _recursive_clusters(x[members], max_size=max_size)
|
| 177 |
+
clusters.extend([members[s] for s in sub])
|
| 178 |
+
if not clusters:
|
| 179 |
+
mid = n // 2
|
| 180 |
+
return [idx[:mid], idx[mid:]]
|
| 181 |
+
return clusters
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
|
| 185 |
+
x = _l2_normalize(np.asarray(embeddings, dtype=np.float32))
|
| 186 |
+
clusters = _recursive_clusters(x, max_size=MAX_ROWS_PER_FILE)
|
| 187 |
+
vector_rows = []
|
| 188 |
+
chunk_meta = []
|
| 189 |
+
global_centroid = _l2_normalize(x.mean(axis=0))
|
| 190 |
+
for cluster_id, members in enumerate(clusters):
|
| 191 |
+
shard_centroid = _l2_normalize(x[members].mean(axis=0))
|
| 192 |
+
sims = x[members] @ shard_centroid
|
| 193 |
+
order = np.argsort(-sims)
|
| 194 |
+
members = members[order]
|
| 195 |
+
sims = sims[order]
|
| 196 |
+
chunk_id = f"vec-{cluster_id:06d}"
|
| 197 |
+
for local_i, doc_i in enumerate(members):
|
| 198 |
+
row = corpus.iloc[int(doc_i)]
|
| 199 |
+
vector_rows.append(
|
| 200 |
+
{
|
| 201 |
+
"chunk_id": chunk_id,
|
| 202 |
+
"cluster_id": int(cluster_id),
|
| 203 |
+
"entry_cid": row["entry_cid"],
|
| 204 |
+
"faiss_id": int(doc_i),
|
| 205 |
+
"document_index": int(row["document_index"]),
|
| 206 |
+
"corpus_chunk_id": int(row["document_index"] // MAX_ROWS_PER_FILE),
|
| 207 |
+
"corpus_row_offset": int(row["document_index"] % MAX_ROWS_PER_FILE),
|
| 208 |
+
"law_cid": row.get("law_cid", ""),
|
| 209 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 210 |
+
"law_id": row.get("law_id", row.get("instrument_id", "")),
|
| 211 |
+
"title": row.get("title", row.get("instrument_title", "")),
|
| 212 |
+
"record_type": row["record_type"],
|
| 213 |
+
"language": row.get("language", ""),
|
| 214 |
+
"jurisdiction": row.get("jurisdiction", ""),
|
| 215 |
+
"embedding": x[int(doc_i)].tolist(),
|
| 216 |
+
"schema_version": SCHEMA_VERSION,
|
| 217 |
+
}
|
| 218 |
+
)
|
| 219 |
+
chunk_meta.append(
|
| 220 |
+
{
|
| 221 |
+
"cluster_id": int(cluster_id),
|
| 222 |
+
"chunk_id": chunk_id,
|
| 223 |
+
"centroid": shard_centroid.tolist(),
|
| 224 |
+
"shard_centroid": shard_centroid.tolist(),
|
| 225 |
+
"centroid_min_score": float(sims.min()) if len(sims) else 0.0,
|
| 226 |
+
"centroid_shard_count": 1,
|
| 227 |
+
"chunk_in_cluster": 0,
|
| 228 |
+
"dimension": DIMENSION,
|
| 229 |
+
"model_name": MODEL_NAME,
|
| 230 |
+
"row_count": int(len(members)),
|
| 231 |
+
"first_key": corpus.iloc[int(members[0])]["entry_cid"] if len(members) else "",
|
| 232 |
+
"last_key": corpus.iloc[int(members[-1])]["entry_cid"] if len(members) else "",
|
| 233 |
+
}
|
| 234 |
+
)
|
| 235 |
+
vectors_df = pd.DataFrame(vector_rows)
|
| 236 |
+
return {
|
| 237 |
+
"vectors": vectors_df,
|
| 238 |
+
"chunk_meta": chunk_meta,
|
| 239 |
+
"global_centroid": global_centroid.tolist(),
|
| 240 |
+
"stats": {
|
| 241 |
+
"model_name": MODEL_NAME,
|
| 242 |
+
"dimension": DIMENSION,
|
| 243 |
+
"similarity": "cosine",
|
| 244 |
+
"assignment": "recursive_spherical_kmeans",
|
| 245 |
+
"layout": "semantic_centroid_groups",
|
| 246 |
+
"rows_sorted_by": "cosine_similarity_to_shard_centroid_desc",
|
| 247 |
+
"max_rows_per_chunk": MAX_ROWS_PER_FILE,
|
| 248 |
+
"max_rows_per_centroid": MAX_ROWS_PER_CENTROID,
|
| 249 |
+
"max_shards_per_centroid": MAX_SHARDS_PER_CENTROID,
|
| 250 |
+
"default_probe_centroids": min(4, max(1, len(clusters))),
|
| 251 |
+
"centroid_count": len(clusters),
|
| 252 |
+
"shard_count": len(clusters),
|
| 253 |
+
"n_vectors": int(len(vectors_df)),
|
| 254 |
+
"status": "embedded",
|
| 255 |
+
},
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def layout_stub_vectors(corpus: pd.DataFrame, reason: str) -> dict[str, Any]:
|
| 260 |
+
"""Document expected vector schema when embeddings cannot be produced."""
|
| 261 |
+
rows = []
|
| 262 |
+
for _, row in corpus.iterrows():
|
| 263 |
+
rows.append(
|
| 264 |
+
{
|
| 265 |
+
"chunk_id": "vec-stub-000000",
|
| 266 |
+
"cluster_id": 0,
|
| 267 |
+
"entry_cid": row["entry_cid"],
|
| 268 |
+
"faiss_id": int(row["document_index"]),
|
| 269 |
+
"document_index": int(row["document_index"]),
|
| 270 |
+
"corpus_chunk_id": int(row["document_index"] // MAX_ROWS_PER_FILE),
|
| 271 |
+
"corpus_row_offset": int(row["document_index"] % MAX_ROWS_PER_FILE),
|
| 272 |
+
"law_cid": row.get("law_cid", ""),
|
| 273 |
+
"instrument_id": row.get("instrument_id", ""),
|
| 274 |
+
"law_id": row.get("law_id", ""),
|
| 275 |
+
"title": row.get("title", ""),
|
| 276 |
+
"record_type": row["record_type"],
|
| 277 |
+
"language": row.get("language", ""),
|
| 278 |
+
"jurisdiction": row.get("jurisdiction", ""),
|
| 279 |
+
"embedding": None,
|
| 280 |
+
"schema_version": SCHEMA_VERSION,
|
| 281 |
+
}
|
| 282 |
+
)
|
| 283 |
+
vectors_df = pd.DataFrame(rows)
|
| 284 |
+
zero = [0.0] * DIMENSION
|
| 285 |
+
chunk_meta = [
|
| 286 |
+
{
|
| 287 |
+
"cluster_id": 0,
|
| 288 |
+
"chunk_id": "vec-stub-000000",
|
| 289 |
+
"centroid": zero,
|
| 290 |
+
"shard_centroid": zero,
|
| 291 |
+
"centroid_min_score": 0.0,
|
| 292 |
+
"centroid_shard_count": 1,
|
| 293 |
+
"chunk_in_cluster": 0,
|
| 294 |
+
"dimension": DIMENSION,
|
| 295 |
+
"model_name": MODEL_NAME,
|
| 296 |
+
"row_count": int(len(vectors_df)),
|
| 297 |
+
"first_key": vectors_df.iloc[0]["entry_cid"] if len(vectors_df) else "",
|
| 298 |
+
"last_key": vectors_df.iloc[-1]["entry_cid"] if len(vectors_df) else "",
|
| 299 |
+
"stub": True,
|
| 300 |
+
"stub_reason": reason,
|
| 301 |
+
}
|
| 302 |
+
]
|
| 303 |
+
return {
|
| 304 |
+
"vectors": vectors_df,
|
| 305 |
+
"chunk_meta": chunk_meta,
|
| 306 |
+
"global_centroid": zero,
|
| 307 |
+
"stats": {
|
| 308 |
+
"model_name": MODEL_NAME,
|
| 309 |
+
"dimension": DIMENSION,
|
| 310 |
+
"similarity": "cosine",
|
| 311 |
+
"assignment": "stub",
|
| 312 |
+
"layout": "semantic_centroid_groups",
|
| 313 |
+
"rows_sorted_by": "document_index",
|
| 314 |
+
"max_rows_per_chunk": MAX_ROWS_PER_FILE,
|
| 315 |
+
"max_rows_per_centroid": MAX_ROWS_PER_CENTROID,
|
| 316 |
+
"max_shards_per_centroid": MAX_SHARDS_PER_CENTROID,
|
| 317 |
+
"default_probe_centroids": 1,
|
| 318 |
+
"centroid_count": 1 if len(vectors_df) else 0,
|
| 319 |
+
"shard_count": 1 if len(vectors_df) else 0,
|
| 320 |
+
"n_vectors": 0,
|
| 321 |
+
"status": "stub",
|
| 322 |
+
"stub_reason": reason,
|
| 323 |
+
"expected_columns": [
|
| 324 |
+
"entry_cid",
|
| 325 |
+
"document_index",
|
| 326 |
+
"embedding",
|
| 327 |
+
"law_cid",
|
| 328 |
+
"instrument_id",
|
| 329 |
+
"title",
|
| 330 |
+
"record_type",
|
| 331 |
+
"language",
|
| 332 |
+
"jurisdiction",
|
| 333 |
+
],
|
| 334 |
+
},
|
| 335 |
+
}
|
data/graph/edges/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b524d5d52eca7179744fb856eeb35e41478149636d80b297b325d64377d1c3fb
|
| 3 |
+
size 177511
|
data/graph/edges/part-000004.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dac33af49edadad39e21ae7dc0c371e7bf1689ed2cf009dd4406bc45731341ca
|
| 3 |
+
size 177172
|
data/graph/edges/part-000008.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1c82c4024e6c628ac1b67f9a810dc8a0418ee2e2f34264df7de08daf7cfc1ca5
|
| 3 |
+
size 177377
|
data/graph/edges/part-000010.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b40ff40ec00dcb462fb66aa05ff44a632e13992ee8454e58bfb58238b73ad28
|
| 3 |
+
size 178001
|
data/graph/edges/part-000018.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8bc2cc63ba319528f98cceb854999c5f6217c3d56c942735dc0d50646b7b585a
|
| 3 |
+
size 183909
|
data/graph/edges/part-000025.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1cdc31ce4685da957a569ec45eeb8da4490fde71c0021363f19c9bfcbc35afc0
|
| 3 |
+
size 183043
|
data/graph/edges/part-000053.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:541b3f67fac5a7749f490dd49f39eeaeb37863892a60a69165b1a18b1f4d68e7
|
| 3 |
+
size 180338
|
data/graph/edges/part-000071.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1ea55caec6c97e0828f86573b08927303be656309553f9d7d120a235ce3314a6
|
| 3 |
+
size 179939
|
data/graph/edges/part-000079.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc65c2716a406cf3a60ca7da9199f48d6f01ae5546110ffaef83d6236baa31e8
|
| 3 |
+
size 181335
|
data/graph/edges/part-000082.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:88cfbde0a002d9a21b052666a2dd21f05ef8ad1346209bc4be7973397e437f84
|
| 3 |
+
size 179660
|
data/graph/edges/part-000092.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f066e3186c59a8e69ccfd4b5333ab7383e0a7a32c55758aaef983d236f729f56
|
| 3 |
+
size 183524
|
data/graph/edges/part-000104.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:777c9b3e8953a546fd7507011a25ba774bc431770dedfbb05ec090d95dcf06a6
|
| 3 |
+
size 181959
|
data/graph/edges/part-000115.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a082f0165bcf70387698adc48463b44b7ef4d18d9846b2b361bbddd844c27120
|
| 3 |
+
size 182221
|
data/graph/edges/part-000122.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:edf66c6423399719bf405b925e25f924df012c52e47b9791b0956ea4fdefec3a
|
| 3 |
+
size 182164
|
data/graph/edges/part-000135.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:243664d9bdee33d88bf2ea35c0a25841b812428d98b45037f3ad2df2491d8f41
|
| 3 |
+
size 180022
|
data/graph/edges/part-000150.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:14e4f2a4b53ebe75d94f62fc558012489aa103ce2a5bd61c147c2ef33580a059
|
| 3 |
+
size 195851
|
data/graph/edges/part-000160.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b755c5fa528fbe7de7a6d1ce0d37ecdb49d19b92153cf7152efbad8cbb0c01fd
|
| 3 |
+
size 274539
|
data/graph/edges/part-000175.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3ec593793beabb0e4b5f1f90bc263882c9a207eaac96219a34c0fc561bcdee3b
|
| 3 |
+
size 292449
|
data/graph/edges/part-000179.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:596e3c7f9f243dd6222959536f1590ae137216f296e25ca1b5f96a3270217345
|
| 3 |
+
size 325535
|
data/graph/edges/part-000222.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a161567844491a027de8f6b7afd82b0849936a0f7707979ab305cbba6b668a9b
|
| 3 |
+
size 316245
|
data/graph/edges/part-000245.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d553e5daf22374e2277245ffa703d8d503e80d941a1f4904452bb4fbd7097fa0
|
| 3 |
+
size 300213
|
data/graph/edges/part-000247.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6096810559eee5e9ac13ca378042cd8c2cd10846b9c3c38063a442411f50e8c4
|
| 3 |
+
size 298030
|
data/graph/edges/part-000249.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4a10d65985110285e8ca12f0181297f3c70d4cf016855b90d23c28fb8c11076b
|
| 3 |
+
size 323477
|
data/graph/edges/part-000271.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:25527385e6a0db22f18d17faa81c8d15a509aebfd0474cd4179f41414510955c
|
| 3 |
+
size 324407
|
data/graph/edges/part-000272.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a5a0c923a08bb81f616bf953221131a4202a058d2867b0b461714cc44d03c5a4
|
| 3 |
+
size 262225
|
manifest.json
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "country-laws-ir-graphrag/v1",
|
| 3 |
+
"dataset_revision": "bfafc6e2e8d60e113523de3bf0903e1c0349c963",
|
| 4 |
+
"country": {
|
| 5 |
+
"slug": "colombia",
|
| 6 |
+
"repo": "endomorphosis/ipfs_colombia_laws",
|
| 7 |
+
"name": "Colombia",
|
| 8 |
+
"indexable": true,
|
| 9 |
+
"skip_reason": null,
|
| 10 |
+
"local_source_dir": "/workspace/country-laws-ir/cache/colombia_filtered_bfafc6e2e8d6",
|
| 11 |
+
"source_revision": "bfafc6e2e8d60e113523de3bf0903e1c0349c963"
|
| 12 |
+
},
|
| 13 |
+
"source": {
|
| 14 |
+
"source_dataset": "endomorphosis/ipfs_colombia_laws",
|
| 15 |
+
"source_revision": "bfafc6e2e8d60e113523de3bf0903e1c0349c963",
|
| 16 |
+
"laws_path": "/workspace/country-laws-ir/cache/colombia_filtered_bfafc6e2e8d6/data/laws.parquet",
|
| 17 |
+
"articles_path": "/workspace/country-laws-ir/cache/colombia_filtered_bfafc6e2e8d6/data/articles.parquet",
|
| 18 |
+
"laws_sha256": null,
|
| 19 |
+
"articles_sha256": null,
|
| 20 |
+
"n_laws_source": 2708,
|
| 21 |
+
"n_articles_source": 81694,
|
| 22 |
+
"laws_columns": [
|
| 23 |
+
"id",
|
| 24 |
+
"title",
|
| 25 |
+
"text",
|
| 26 |
+
"source_url",
|
| 27 |
+
"source_type",
|
| 28 |
+
"jurisdiction",
|
| 29 |
+
"country",
|
| 30 |
+
"language",
|
| 31 |
+
"eli",
|
| 32 |
+
"date",
|
| 33 |
+
"date_issued",
|
| 34 |
+
"retrieved_at",
|
| 35 |
+
"license",
|
| 36 |
+
"law_status",
|
| 37 |
+
"identifier",
|
| 38 |
+
"official_identifier",
|
| 39 |
+
"article_count",
|
| 40 |
+
"json_path",
|
| 41 |
+
"metadata_json"
|
| 42 |
+
],
|
| 43 |
+
"articles_columns": [
|
| 44 |
+
"law_id",
|
| 45 |
+
"id",
|
| 46 |
+
"title",
|
| 47 |
+
"text",
|
| 48 |
+
"source_url",
|
| 49 |
+
"document_number",
|
| 50 |
+
"article_number",
|
| 51 |
+
"record_type",
|
| 52 |
+
"metadata_json"
|
| 53 |
+
],
|
| 54 |
+
"local_source_dir": "/workspace/country-laws-ir/cache/colombia_filtered_bfafc6e2e8d6",
|
| 55 |
+
"pack_meta": {
|
| 56 |
+
"slug": "colombia",
|
| 57 |
+
"name": "Colombia",
|
| 58 |
+
"repo": "endomorphosis/ipfs_colombia_laws",
|
| 59 |
+
"source_dataset": "endomorphosis/ipfs_colombia_laws",
|
| 60 |
+
"source_revision": "bfafc6e2e8d60e113523de3bf0903e1c0349c963",
|
| 61 |
+
"filtered": true,
|
| 62 |
+
"filter_reason": "memsafe pass-through (chrome skipped; floor==hub; soft never-thin)",
|
| 63 |
+
"indexable": true,
|
| 64 |
+
"skip_reason": null,
|
| 65 |
+
"n_laws": 2708,
|
| 66 |
+
"n_articles": 81694
|
| 67 |
+
}
|
| 68 |
+
},
|
| 69 |
+
"counts": {
|
| 70 |
+
"corpus_rows": 81306,
|
| 71 |
+
"laws": 0,
|
| 72 |
+
"articles": 81306,
|
| 73 |
+
"bm25_documents": 81306,
|
| 74 |
+
"bm25_posting_rows": 78039,
|
| 75 |
+
"graph_nodes": 89425,
|
| 76 |
+
"graph_edges": 1170969,
|
| 77 |
+
"vector_rows": 81306,
|
| 78 |
+
"graph_incoming_adjacency_rows": 0,
|
| 79 |
+
"graph_outgoing_adjacency_rows": 0
|
| 80 |
+
},
|
| 81 |
+
"bm25": {
|
| 82 |
+
"k1": 1.2,
|
| 83 |
+
"b": 0.75,
|
| 84 |
+
"title_weight": 5.0,
|
| 85 |
+
"body_weight": 1.0,
|
| 86 |
+
"average_document_length": 292.7782574471749,
|
| 87 |
+
"tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1",
|
| 88 |
+
"max_query_terms": 64,
|
| 89 |
+
"posting_rows_per_record": 4096,
|
| 90 |
+
"terms_per_shard": 4096,
|
| 91 |
+
"n_docs": 81306,
|
| 92 |
+
"n_terms": 77496,
|
| 93 |
+
"n_posting_rows": 78039,
|
| 94 |
+
"n_postings": 6459851
|
| 95 |
+
},
|
| 96 |
+
"graph": {
|
| 97 |
+
"n_nodes": 89425,
|
| 98 |
+
"n_edges": 1170969,
|
| 99 |
+
"n_doc_nodes": 84011,
|
| 100 |
+
"n_facet_nodes": 5414,
|
| 101 |
+
"edge_types": [
|
| 102 |
+
"ARTICLE_OF",
|
| 103 |
+
"BM25_NEIGHBOR_OF",
|
| 104 |
+
"HAS_INSTRUMENT",
|
| 105 |
+
"HAS_JURISDICTION",
|
| 106 |
+
"HAS_LANGUAGE",
|
| 107 |
+
"HAS_SOURCE",
|
| 108 |
+
"HAS_STATUS",
|
| 109 |
+
"IDENTIFIED_BY",
|
| 110 |
+
"IDENTIFIED_BY_ELI"
|
| 111 |
+
],
|
| 112 |
+
"adjacency": "empty_placeholder_oom_avoidance"
|
| 113 |
+
},
|
| 114 |
+
"vector": {
|
| 115 |
+
"model_name": "thenlper/gte-small",
|
| 116 |
+
"dimension": 384,
|
| 117 |
+
"similarity": "cosine",
|
| 118 |
+
"assignment": "sequential_shards",
|
| 119 |
+
"layout": "semantic_centroid_groups",
|
| 120 |
+
"rows_sorted_by": "cosine_similarity_to_shard_centroid_desc",
|
| 121 |
+
"max_rows_per_chunk": 4096,
|
| 122 |
+
"n_vectors": 81306,
|
| 123 |
+
"centroid_count": 20,
|
| 124 |
+
"shard_count": 20,
|
| 125 |
+
"status": "embedded",
|
| 126 |
+
"via": "layout_vectors_memsafe_sequential"
|
| 127 |
+
},
|
| 128 |
+
"normalization": {
|
| 129 |
+
"source_dataset": "endomorphosis/ipfs_colombia_laws",
|
| 130 |
+
"source_revision": "bfafc6e2e8d60e113523de3bf0903e1c0349c963",
|
| 131 |
+
"n_laws_in": 2708,
|
| 132 |
+
"n_articles_in": 81694,
|
| 133 |
+
"unit": "article",
|
| 134 |
+
"drops": {
|
| 135 |
+
"empty_body": 0,
|
| 136 |
+
"missing_instrument": 0,
|
| 137 |
+
"duplicate_cid": 388
|
| 138 |
+
},
|
| 139 |
+
"n_out": 81306,
|
| 140 |
+
"n_dropped_total": 388,
|
| 141 |
+
"via": "colombia_corpus_stream",
|
| 142 |
+
"record_type_breakdown": {
|
| 143 |
+
"article": 81306
|
| 144 |
+
},
|
| 145 |
+
"language_breakdown": {
|
| 146 |
+
"es": 81306
|
| 147 |
+
},
|
| 148 |
+
"never_invented_legal_text": true
|
| 149 |
+
},
|
| 150 |
+
"neighbor_via": "sqlite_fts",
|
| 151 |
+
"built_utc": "2026-09-10T10:51:02.397946+00:00",
|
| 152 |
+
"via": "colombia_package_stream_graph"
|
| 153 |
+
}
|
scripts/build_country_laws_ir.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CLI: build a country-laws IR release (local; does not upload)."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
sys.path.insert(0, str(ROOT))
|
| 13 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 14 |
+
|
| 15 |
+
from country_laws_ir.build import build_country # noqa: E402
|
| 16 |
+
from country_laws_ir.catalog import target_repo # noqa: E402
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main() -> int:
|
| 20 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 21 |
+
ap.add_argument("--source-repo", "--source", dest="source", default="endomorphosis/ipfs_malta_laws",
|
| 22 |
+
help="Hub dataset id or country slug (default: Malta pilot)")
|
| 23 |
+
ap.add_argument("--out", default=None, help="Release output directory")
|
| 24 |
+
ap.add_argument("--device", default="cpu")
|
| 25 |
+
ap.add_argument("--neighbor-k", type=int, default=8)
|
| 26 |
+
ap.add_argument("--skip-vectors", action="store_true")
|
| 27 |
+
ap.add_argument("--upload", action="store_true", help="Opt-in Hub upload (default: off)")
|
| 28 |
+
args = ap.parse_args()
|
| 29 |
+
result = build_country(
|
| 30 |
+
args.source,
|
| 31 |
+
out=Path(args.out) if args.out else None,
|
| 32 |
+
upload=bool(args.upload),
|
| 33 |
+
device=args.device,
|
| 34 |
+
neighbor_k=args.neighbor_k,
|
| 35 |
+
skip_vectors=args.skip_vectors,
|
| 36 |
+
)
|
| 37 |
+
print(json.dumps({
|
| 38 |
+
"out": result["out"],
|
| 39 |
+
"target_hub_id": result.get("target_hub_id") or target_repo(result["country"]),
|
| 40 |
+
"counts": result["counts"],
|
| 41 |
+
"normalization": {
|
| 42 |
+
"n_laws_in": result["normalization"]["n_laws_in"],
|
| 43 |
+
"n_articles_in": result["normalization"]["n_articles_in"],
|
| 44 |
+
"n_out": result["normalization"]["n_out"],
|
| 45 |
+
"unit": result["normalization"]["unit"],
|
| 46 |
+
"drops": result["normalization"]["drops"],
|
| 47 |
+
},
|
| 48 |
+
"vector_blocker": result.get("vector_blocker"),
|
| 49 |
+
"schema_version": result.get("schema_version"),
|
| 50 |
+
}, indent=2, ensure_ascii=False))
|
| 51 |
+
return 0
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
raise SystemExit(main())
|
scripts/generate_country_laws_ir.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generation entrypoint copied into Hub dataset repos."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
sys.path.insert(0, str(ROOT))
|
| 11 |
+
|
| 12 |
+
from country_laws_ir.__main__ import main
|
| 13 |
+
|
| 14 |
+
if __name__ == "__main__":
|
| 15 |
+
raise SystemExit(main())
|
scripts/normalize_country_laws.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Normalize a country-law source into a CID-keyed corpus report (no GraphRAG, no upload)."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
sys.path.insert(0, str(ROOT))
|
| 13 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 14 |
+
|
| 15 |
+
from country_laws_ir.build import CACHE, REPORTS # noqa: E402
|
| 16 |
+
from country_laws_ir.catalog import get_country # noqa: E402
|
| 17 |
+
from country_laws_ir.normalize import build_corpus, load_source # noqa: E402
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def main() -> int:
|
| 21 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 22 |
+
ap.add_argument("--source-repo", "--source", dest="source", default="endomorphosis/ipfs_malta_laws")
|
| 23 |
+
ap.add_argument("--out", default=None)
|
| 24 |
+
args = ap.parse_args()
|
| 25 |
+
country = get_country(args.source)
|
| 26 |
+
laws, articles, source_meta = load_source(country["repo"], CACHE)
|
| 27 |
+
corpus, report = build_corpus(laws, articles, source_meta)
|
| 28 |
+
out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
|
| 29 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 31 |
+
print(json.dumps({
|
| 32 |
+
"out": str(out),
|
| 33 |
+
"n_out": int(len(corpus)),
|
| 34 |
+
"unit": report["unit"],
|
| 35 |
+
"drops": report["drops"],
|
| 36 |
+
"language_breakdown": report.get("language_breakdown"),
|
| 37 |
+
"quality_flags": report.get("quality_flags"),
|
| 38 |
+
"schema_surprises": report.get("schema_surprises"),
|
| 39 |
+
}, indent=2, ensure_ascii=False))
|
| 40 |
+
return 0
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == "__main__":
|
| 44 |
+
raise SystemExit(main())
|
scripts/query_country_laws_hf.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import sys
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 6 |
+
sys.path.insert(0, str(ROOT))
|
| 7 |
+
from country_laws_ir.query import main
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
raise SystemExit(main())
|
scripts/query_country_laws_ir.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CLI wrapper for country_laws_ir.query."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
sys.path.insert(0, str(ROOT))
|
| 11 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 12 |
+
|
| 13 |
+
from country_laws_ir.query import main # noqa: E402
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
raise SystemExit(main())
|