diff --git a/build.py b/build.py index ebf8d6b94aa80d9f023be3d41df12e52e2a8a31a..768973af97da5ea96deef2b5b7bbbc06909d9ebe 100644 --- a/build.py +++ b/build.py @@ -39,10 +39,10 @@ from .vectors import ( DIMENSION, MODEL_NAME, assemble_embeddings, - embeddings_available, embeddings_by_cid, layout_stub_vectors, layout_vectors, + select_device, ) ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir"))) @@ -60,8 +60,17 @@ def _log(msg: str) -> None: def record_progress(event: dict[str, Any]) -> None: event = dict(event) event.setdefault("ts", datetime.now(timezone.utc).isoformat()) - with PROGRESS.open("a", encoding="utf-8") as f: - f.write(json.dumps(event, ensure_ascii=False) + "\n") + PROGRESS.parent.mkdir(parents=True, exist_ok=True) + lock_path = PROGRESS.with_suffix(".lock") + with lock_path.open("a", encoding="utf-8") as lock_fh: + try: + import fcntl + + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) + except Exception: + pass + with PROGRESS.open("a", encoding="utf-8") as f: + f.write(json.dumps(event, ensure_ascii=False) + "\n") def _prior_dir_for( @@ -113,11 +122,14 @@ def _encode_vectors( _log(f"embedding cache reused_cids={len(prior_by_cid)}") try: positional = CACHE / "embeddings" / f"{country_slug}.npy" + resolved, fallback = select_device(device) + if fallback: + _log(f"embedding device fallback requested={device} using={resolved}") embeddings, vector_report = assemble_embeddings( corpus, prior_by_cid, - encode_missing=embeddings_available(), - device=device, + encode_missing=True, + device=resolved, checkpoint_path=str(positional), ) if ( @@ -157,7 +169,7 @@ def build_country( source: str, out: Path | None = None, upload: bool = False, - device: str = "cpu", + device: str = "cuda", neighbor_k: int = 8, skip_vectors: bool = False, mode: str = "auto", @@ -199,7 +211,11 @@ def build_country( ) ) plan = plan_rebuild( - mode=mode, source_meta=source_meta, prior=prior, force=force + mode=mode, + source_meta=source_meta, + prior=prior, + force=force, + rebuild_stub_vectors=not skip_vectors, ) if plan.skip_build: _log(f"skip unchanged {country['slug']} rev={plan.source_revision}") @@ -231,6 +247,13 @@ def build_country( ) if corpus.empty: raise RuntimeError("Normalized corpus is empty; refusing to package") + verdict = (norm_report or {}).get("verification") or {} + if verdict.get("blocks_graphrag") and not force: + from .verify import NormalizationAdmissionError + + raise NormalizationAdmissionError( + f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}" + ) import gc @@ -240,6 +263,7 @@ def build_country( prior=prior, current_corpus=corpus, force=force, + rebuild_stub_vectors=not skip_vectors, ) _log( f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} " @@ -391,17 +415,29 @@ def reindex_from_gaps( skip_vectors: bool = False, workers: int = 4, mode: str = "auto", + force: bool = False, + all_indexable: bool = False, + device: str = "cuda", ) -> list[dict[str, Any]]: - """Scan Hub gaps and incrementally rebuild stale/missing country IR. + """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country. Default cap skips huge corpora (Finland, Dominican Republic). Pass ``max_corpus_rows=None`` to include them. """ + from .catalog import indexable_countries from .coverage import gap_report if slugs is None: - report = gap_report(workers=workers) - rows = [c for c in report["countries"] if c.get("rebuild")] + if all_indexable: + rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()] + _log(f"reindex all indexable n={len(rows)}") + else: + report = gap_report(workers=workers) + rows = [c for c in report["countries"] if c.get("rebuild")] + _log( + f"reindex targets n={len(rows)} " + f"(from scan rebuild={len(report.get('rebuild') or [])})" + ) rows.sort(key=lambda r: int(r.get("corpus_rows") or 0)) if max_corpus_rows is not None: rows = [ @@ -412,33 +448,54 @@ def reindex_from_gaps( if limit is not None: rows = rows[: int(limit)] slugs = [str(r["slug"]) for r in rows] - _log( - f"reindex targets n={len(slugs)} " - f"(from scan rebuild={len(report.get('rebuild') or [])})" + kwargs = { + "upload": upload, + "mode": mode, + "force": force, + "skip_vectors": skip_vectors, + "fetch_hub_prior_ir": True, + "device": device, + } + n_workers = max(1, int(workers or 1)) + _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda") + import multiprocessing as mp + from concurrent.futures import ProcessPoolExecutor, as_completed + + try: + mp.set_start_method("spawn", force=False) + except RuntimeError: + pass + + results = [None] * len(slugs) + with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool: + futs = { + pool.submit(_reindex_one_country, (slug, kwargs)): i + for i, slug in enumerate(slugs) + } + for fut in as_completed(futs): + idx = futs[fut] + slug = slugs[idx] + try: + results[idx] = fut.result() + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + results[idx] = {"country": slug, "skipped": False, "error": str(exc)} + return [r for r in results if r is not None] + + +def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]: + slug, kwargs = item + _log(f"reindex start {slug}") + try: + return build_country(slug, **kwargs) + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + record_progress( + { + "event": "failed", + "country": slug, + "error": str(exc), + "traceback": traceback.format_exc(), + } ) - results: list[dict[str, Any]] = [] - for slug in slugs: - _log(f"reindex start {slug}") - try: - results.append( - build_country( - slug, - upload=upload, - mode=mode, - skip_vectors=skip_vectors, - fetch_hub_prior_ir=True, - ) - ) - except Exception as exc: - _log(f"FAILED {slug}: {exc}") - record_progress( - { - "event": "failed", - "country": slug, - "error": str(exc), - "traceback": traceback.format_exc(), - } - ) - results.append({"country": slug, "skipped": False, "error": str(exc)}) - continue - return results + return {"country": slug, "skipped": False, "error": str(exc)} diff --git a/country_laws_ir/__main__.py b/country_laws_ir/__main__.py index af9b0919ae746120102bd7b5593ef5215c382dc3..438bb8d0cca0f061a42ee449d414a2ff2c0383cf 100644 --- a/country_laws_ir/__main__.py +++ b/country_laws_ir/__main__.py @@ -16,7 +16,11 @@ def main(argv: list[str] | None = None) -> int: p_build.add_argument("--source-repo", "--source", dest="source", default="malta", help="Hub dataset id (endomorphosis/ipfs__laws), country slug, or local pack dir") p_build.add_argument("--out", default=None) - p_build.add_argument("--device", default="cpu") + p_build.add_argument( + "--device", + default="cuda", + help="Embedding device (cuda by default, like US Code / Open US Law; falls back to cpu)", + ) p_build.add_argument("--neighbor-k", type=int, default=8) p_build.add_argument("--skip-vectors", action="store_true") p_build.add_argument("--upload", action="store_true", @@ -62,8 +66,22 @@ def main(argv: list[str] | None = None) -> int: p_re.add_argument("--max-corpus-rows", type=int, default=20000, help="Skip IR larger than this many rows (0 = no cap)") p_re.add_argument("--skip-vectors", action="store_true") - p_re.add_argument("--workers", type=int, default=4) + p_re.add_argument("--workers", type=int, default=2, + help="Parallel country workers (default 2 to stay under MemAbort; CUDA encodes are file-locked)") + p_re.add_argument("--device", default="cuda") p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"]) + p_re.add_argument("--all", action="store_true", + help="Process every indexable catalog country (not only Hub gaps)") + p_re.add_argument("--force", action="store_true", + help="Rebuild even when the source SHA matches (rerun normalize/verifiers)") + + p_ver = sub.add_parser( + "verify", + help="Normalize a country pack and run admission verifiers (no GraphRAG)", + ) + p_ver.add_argument("--source-repo", "--source", dest="source", default=None) + p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country") + p_ver.add_argument("--limit", type=int, default=None) p_raw = sub.add_parser("package-raw") p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs__laws_ir") @@ -145,7 +163,7 @@ def main(argv: list[str] | None = None) -> int: if args.cmd == "reindex": from .build import reindex_from_gaps - cap = None if int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows) + cap = None if args.all or int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows) results = reindex_from_gaps( upload=args.upload, slugs=args.slugs or None, @@ -154,6 +172,9 @@ def main(argv: list[str] | None = None) -> int: skip_vectors=args.skip_vectors, workers=args.workers, mode=args.mode, + force=args.force, + all_indexable=args.all, + device=args.device, ) print(json.dumps( [ @@ -173,6 +194,65 @@ def main(argv: list[str] | None = None) -> int: default=str, )) return 1 if any(r.get("error") for r in results) else 0 + if args.cmd == "verify": + from .catalog import indexable_countries + from .verify import verify_source + + slugs = [] + if args.all: + slugs = [c["slug"] for c in indexable_countries()] + if args.limit: + slugs = slugs[: int(args.limit)] + elif args.source: + slugs = [args.source] + else: + print(json.dumps({"error": "pass --source or --all"}, indent=2)) + return 2 + rows = [] + failed = 0 + for slug in slugs: + try: + row = verify_source(slug) + except Exception as exc: + row = {"slug": slug, "error": str(exc), "verification": {"admitted": False}} + rows.append(row) + if not (row.get("verification") or {}).get("admitted", False): + failed += 1 + from collections import Counter + + units = Counter(str(r.get("unit") or "") for r in rows) + mismatch = [] + latin_blocked = [] + for r in rows: + for chk in (r.get("verification") or {}).get("checks") or []: + if chk.get("id") != "heading_language": + continue + ev = chk.get("evidence") or {} + if chk.get("severity") == "fail" and not chk.get("passed"): + latin_blocked.append(r.get("slug")) + if "review samples" in str(chk.get("message") or ""): + mismatch.append( + { + "slug": r.get("slug"), + "document_language": ev.get("document_language"), + "heading_language": ev.get("heading_language"), + } + ) + print( + json.dumps( + { + "n": len(rows), + "n_failed": failed, + "by_unit": dict(units), + "heading_mismatch": mismatch, + "latin_split_blocked": latin_blocked, + "countries": rows, + }, + indent=2, + default=str, + ) + ) + return 1 if failed else 0 if args.cmd == "package-raw": from .build import RELEASES from .raw_package import default_instruments_dir, package_instruments diff --git a/country_laws_ir/build.py b/country_laws_ir/build.py index ebf8d6b94aa80d9f023be3d41df12e52e2a8a31a..768973af97da5ea96deef2b5b7bbbc06909d9ebe 100644 --- a/country_laws_ir/build.py +++ b/country_laws_ir/build.py @@ -39,10 +39,10 @@ from .vectors import ( DIMENSION, MODEL_NAME, assemble_embeddings, - embeddings_available, embeddings_by_cid, layout_stub_vectors, layout_vectors, + select_device, ) ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir"))) @@ -60,8 +60,17 @@ def _log(msg: str) -> None: def record_progress(event: dict[str, Any]) -> None: event = dict(event) event.setdefault("ts", datetime.now(timezone.utc).isoformat()) - with PROGRESS.open("a", encoding="utf-8") as f: - f.write(json.dumps(event, ensure_ascii=False) + "\n") + PROGRESS.parent.mkdir(parents=True, exist_ok=True) + lock_path = PROGRESS.with_suffix(".lock") + with lock_path.open("a", encoding="utf-8") as lock_fh: + try: + import fcntl + + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) + except Exception: + pass + with PROGRESS.open("a", encoding="utf-8") as f: + f.write(json.dumps(event, ensure_ascii=False) + "\n") def _prior_dir_for( @@ -113,11 +122,14 @@ def _encode_vectors( _log(f"embedding cache reused_cids={len(prior_by_cid)}") try: positional = CACHE / "embeddings" / f"{country_slug}.npy" + resolved, fallback = select_device(device) + if fallback: + _log(f"embedding device fallback requested={device} using={resolved}") embeddings, vector_report = assemble_embeddings( corpus, prior_by_cid, - encode_missing=embeddings_available(), - device=device, + encode_missing=True, + device=resolved, checkpoint_path=str(positional), ) if ( @@ -157,7 +169,7 @@ def build_country( source: str, out: Path | None = None, upload: bool = False, - device: str = "cpu", + device: str = "cuda", neighbor_k: int = 8, skip_vectors: bool = False, mode: str = "auto", @@ -199,7 +211,11 @@ def build_country( ) ) plan = plan_rebuild( - mode=mode, source_meta=source_meta, prior=prior, force=force + mode=mode, + source_meta=source_meta, + prior=prior, + force=force, + rebuild_stub_vectors=not skip_vectors, ) if plan.skip_build: _log(f"skip unchanged {country['slug']} rev={plan.source_revision}") @@ -231,6 +247,13 @@ def build_country( ) if corpus.empty: raise RuntimeError("Normalized corpus is empty; refusing to package") + verdict = (norm_report or {}).get("verification") or {} + if verdict.get("blocks_graphrag") and not force: + from .verify import NormalizationAdmissionError + + raise NormalizationAdmissionError( + f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}" + ) import gc @@ -240,6 +263,7 @@ def build_country( prior=prior, current_corpus=corpus, force=force, + rebuild_stub_vectors=not skip_vectors, ) _log( f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} " @@ -391,17 +415,29 @@ def reindex_from_gaps( skip_vectors: bool = False, workers: int = 4, mode: str = "auto", + force: bool = False, + all_indexable: bool = False, + device: str = "cuda", ) -> list[dict[str, Any]]: - """Scan Hub gaps and incrementally rebuild stale/missing country IR. + """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country. Default cap skips huge corpora (Finland, Dominican Republic). Pass ``max_corpus_rows=None`` to include them. """ + from .catalog import indexable_countries from .coverage import gap_report if slugs is None: - report = gap_report(workers=workers) - rows = [c for c in report["countries"] if c.get("rebuild")] + if all_indexable: + rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()] + _log(f"reindex all indexable n={len(rows)}") + else: + report = gap_report(workers=workers) + rows = [c for c in report["countries"] if c.get("rebuild")] + _log( + f"reindex targets n={len(rows)} " + f"(from scan rebuild={len(report.get('rebuild') or [])})" + ) rows.sort(key=lambda r: int(r.get("corpus_rows") or 0)) if max_corpus_rows is not None: rows = [ @@ -412,33 +448,54 @@ def reindex_from_gaps( if limit is not None: rows = rows[: int(limit)] slugs = [str(r["slug"]) for r in rows] - _log( - f"reindex targets n={len(slugs)} " - f"(from scan rebuild={len(report.get('rebuild') or [])})" + kwargs = { + "upload": upload, + "mode": mode, + "force": force, + "skip_vectors": skip_vectors, + "fetch_hub_prior_ir": True, + "device": device, + } + n_workers = max(1, int(workers or 1)) + _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda") + import multiprocessing as mp + from concurrent.futures import ProcessPoolExecutor, as_completed + + try: + mp.set_start_method("spawn", force=False) + except RuntimeError: + pass + + results = [None] * len(slugs) + with ProcessPoolExecutor(max_workers=n_workers, max_tasks_per_child=1) as pool: + futs = { + pool.submit(_reindex_one_country, (slug, kwargs)): i + for i, slug in enumerate(slugs) + } + for fut in as_completed(futs): + idx = futs[fut] + slug = slugs[idx] + try: + results[idx] = fut.result() + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + results[idx] = {"country": slug, "skipped": False, "error": str(exc)} + return [r for r in results if r is not None] + + +def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]: + slug, kwargs = item + _log(f"reindex start {slug}") + try: + return build_country(slug, **kwargs) + except Exception as exc: + _log(f"FAILED {slug}: {exc}") + record_progress( + { + "event": "failed", + "country": slug, + "error": str(exc), + "traceback": traceback.format_exc(), + } ) - results: list[dict[str, Any]] = [] - for slug in slugs: - _log(f"reindex start {slug}") - try: - results.append( - build_country( - slug, - upload=upload, - mode=mode, - skip_vectors=skip_vectors, - fetch_hub_prior_ir=True, - ) - ) - except Exception as exc: - _log(f"FAILED {slug}: {exc}") - record_progress( - { - "event": "failed", - "country": slug, - "error": str(exc), - "traceback": traceback.format_exc(), - } - ) - results.append({"country": slug, "skipped": False, "error": str(exc)}) - continue - return results + return {"country": slug, "skipped": False, "error": str(exc)} diff --git a/country_laws_ir/coverage.py b/country_laws_ir/coverage.py index c37eef9751f22272d5cf85e6a7afc465c1227884..380d7fda93c8d35799efb1997f13847eec6ea3aa 100644 --- a/country_laws_ir/coverage.py +++ b/country_laws_ir/coverage.py @@ -159,7 +159,10 @@ def classify_gap( and local_source_revision and str(source_revision) == str(local_source_revision) ) - rebuild = status in {"missing", "unpublished", "stale", "incomplete"} and not local_current + rebuild = ( + status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} + and (not local_current or status == "stub_vectors") + ) publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and ( "source_missing_laws" not in issues ) diff --git a/country_laws_ir/incremental.py b/country_laws_ir/incremental.py index 1ef90ceefcde63417d7b106c0b595840518bbd24..870039d76530cefabb9284ebd6322289345b1c06 100644 --- a/country_laws_ir/incremental.py +++ b/country_laws_ir/incremental.py @@ -234,6 +234,7 @@ def plan_rebuild( prior: PriorRelease | None, current_corpus: pd.DataFrame | None = None, force: bool = False, + rebuild_stub_vectors: bool = True, ) -> RebuildPlan: """Decide skip / delta / full from source fingerprints and CID overlap.""" mode = BuildMode.coerce(mode) @@ -275,7 +276,19 @@ def plan_rebuild( equivalent_to_full=True, ) - if prior_fp == fingerprint and fingerprint.strip("|"): + prior_vector_status = str( + ((prior.manifest.get("vector") or {}) if prior.manifest else {}).get("status") + or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status") + or "" + ).strip().lower() + stub_vectors = rebuild_stub_vectors and prior_vector_status in { + "stub", + "stub_missing_encoder", + "incomplete", + "partial", + } + + if prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors: return RebuildPlan( kind=RebuildKind.UNCHANGED, mode=mode, @@ -314,10 +327,15 @@ def plan_rebuild( equivalent_to_full=True, ) + reason = ( + "source fingerprint matches but vectors are stub/incomplete; encode missing CIDs" + if stub_vectors and prior_fp == fingerprint + else "source changed; reuse embeddings for unchanged entry_cids" + ) return RebuildPlan( kind=RebuildKind.DELTA_REFRESH, mode=mode, - reason="source changed; reuse embeddings for unchanged entry_cids", + reason=reason, source_revision=revision, prior_revision=prior_revision, source_fingerprint=fingerprint, diff --git a/country_laws_ir/normalize.py b/country_laws_ir/normalize.py index d518f83f1b2fe701b6c1fc5f79335bc6c760a414..b3c348f675dd13ca6f9184c6ffffce5cdfead2d8 100644 --- a/country_laws_ir/normalize.py +++ b/country_laws_ir/normalize.py @@ -1,8 +1,9 @@ """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus. Prefer article/section as the retrieval unit; fall back to law-level when -articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE -GraphRAG. Never invent legal text or identifiers. +articles are missing or empty. Strip leftover HTML, then detect multilingual +title/chapter/article/section headings (Oregon-style) when present. Never +invent legal text or a hierarchy that is not in the source. Public Hub reads only (token=False). No Hugging Face token is read or stored. """ @@ -11,8 +12,6 @@ from __future__ import annotations import json import os -import re -import unicodedata from collections import Counter from pathlib import Path from typing import Any @@ -25,8 +24,8 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION from .auth import configure_hf, public_token from .cidutil import cid_of_json, sha256_file, sha256_hex from .schema import SchemaError, validate_articles, validate_laws +from .structure import normalize_legal_text, split_structured_units -_WS_RE = re.compile(r"\s+", re.UNICODE) COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py" EMPTY_ARTICLE_COLUMNS = ( "law_id", @@ -48,9 +47,7 @@ def _empty_articles() -> pd.DataFrame: def normalize_text(value: Any) -> str: if value is None or (isinstance(value, float) and pd.isna(value)): return "" - text = unicodedata.normalize("NFKC", str(value)) - text = _WS_RE.sub(" ", text).strip() - return text + return normalize_legal_text(value) def _s(value: Any) -> str: @@ -285,6 +282,35 @@ def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, return "" +def _hierarchy_fields( + title: str, body: str, article_number: str, *, language: str = "" +) -> dict[str, Any]: + """Best-effort hierarchy from a single already-split article/section body.""" + units = split_structured_units( + f"{title}\n{body}" if title else body, language=language + ) + if not units: + return { + "hierarchy_kind": "article" if article_number else "law", + "hierarchy_path": "", + "title_number": "", + "chapter_number": "", + "part_number": "", + "section_number": "", + "subsections": [], + } + unit = units[0] + return { + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + } + + def _collector(meta: dict[str, Any], source_dataset: str) -> str: nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for blob in (meta, nested): @@ -489,6 +515,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": instrument_id, "article_id": source_id, + **_hierarchy_fields( + article_title, body, article_number, language=parent["language"] + ), }, ) ) @@ -501,6 +530,49 @@ def build_corpus( report["drop_samples"]["empty_body"].append(instrument_id) continue meta = parent["metadata"] + units = split_structured_units(body, language=parent["language"]) + if units: + report["unit"] = "structured" + for unit in units: + entries.append( + _base_record( + record_type=unit.kind if unit.kind in {"article", "section"} else "article", + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number=unit.article_number or unit.number, + article_title=unit.heading, + body=unit.body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage="structured (headings detected in law body)", + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=f"{instrument_id}-{unit.kind}-{unit.number}", + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": instrument_id, + "article_id": "", + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + }, + ) + ) + continue entries.append( _base_record( record_type="law", @@ -531,6 +603,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": "", "article_id": "", + **_hierarchy_fields( + parent["instrument_title"], body, "", language=parent["language"] + ), }, ) ) @@ -607,5 +682,23 @@ def build_corpus( "empty_bodies_dropped": report["drops"]["empty_body"], "duplicate_cids_dropped": report["drops"]["duplicate_cid"], } + from .profiles import majority_language, score_heading_languages + + sample_text = "" + if not df.empty and "body" in df.columns: + sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist()) + if "title" in df.columns: + sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text + heading_langs = score_heading_languages(sample_text) + report["heading_language_counts"] = dict(heading_langs) + report["heading_language_majority"] = majority_language(heading_langs) + report["document_language_majority"] = None + if report.get("language_breakdown"): + report["document_language_majority"] = max( + report["language_breakdown"].items(), key=lambda kv: kv[1] + )[0] + from .verify import verify_normalized_corpus + + report["verification"] = verify_normalized_corpus(df, report) df.attrs["normalization_report"] = report return df, report diff --git a/country_laws_ir/profiles.py b/country_laws_ir/profiles.py new file mode 100644 index 0000000000000000000000000000000000000000..44c3d6a91b3c1bf18ede24a585e0409d7ca37518 --- /dev/null +++ b/country_laws_ir/profiles.py @@ -0,0 +1,124 @@ +"""Per-language legal heading lexicons for country-law structure extraction. + +Oregon (ORS) is English title/chapter/section. Other gazettes use their own +words (Artikel, Titre, Artículo, 条, مادة). This table is how we *score* +whether a split used the right language — not a claim that every country +has a dedicated parser. + +Languages with no lexicon (ar, zh, ja, ko, …) must not be force-split on +Latin TITLE/ARTICLE markers; collectors may already have article rows. +""" + +from __future__ import annotations + +from collections import Counter +import re +from typing import Any + +# keyword -> list of (kind, language); some words are shared (article). +HEADING_LEXICON: dict[str, list[tuple[str, str]]] = {} + +def _add(lang: str, kind: str, *words: str) -> None: + for word in words: + HEADING_LEXICON.setdefault(word.casefold(), []).append((kind, lang)) + + +_add("en", "title", "title") +_add("en", "chapter", "chapter") +_add("en", "part", "part") +_add("en", "article", "article") +_add("en", "section", "section", "sec.") + +_add("fr", "title", "titre") +_add("fr", "chapter", "chapitre") +_add("fr", "part", "partie") +_add("fr", "article", "article") +_add("fr", "section", "section") + +_add("de", "title", "titel") +_add("de", "chapter", "kapitel") +_add("de", "part", "teil") +_add("de", "article", "artikel") +_add("de", "section", "abschnitt", "paragraf") + +_add("nl", "title", "titel") +_add("nl", "chapter", "hoofdstuk") +_add("nl", "part", "deel") +_add("nl", "article", "artikel") +_add("nl", "section", "paragraaf", "afdeling") + +_add("es", "title", "título", "titulo") +_add("es", "chapter", "capítulo", "capitulo") +_add("es", "part", "parte") +_add("es", "article", "artículo", "articulo") +_add("es", "section", "sección", "seccion") + +_add("pt", "title", "título", "titulo") +_add("pt", "chapter", "capítulo", "capitulo") +_add("pt", "part", "parte") +_add("pt", "article", "artigo") +_add("pt", "section", "secção", "secao") + +_add("it", "title", "titolo") +_add("it", "chapter", "capitolo") +_add("it", "part", "parte") +_add("it", "article", "articolo") +_add("it", "section", "sezione") + +_add("el", "article", "άρθρο", "αρθρο") +_add("hu", "article", "szakasz") +_add("cs", "article", "článek") +_add("sk", "article", "článok") +_add("sl", "article", "član") +_add("nb", "article", "artikkel") +_add("sv", "article", "artikel") +_add("pl", "article", "artykuł", "artykul") +_add("ro", "article", "articolul", "articol") +_add("zh", "article", "条") +_add("ar", "article", "مادة", "المادة") +_add("ja", "article", "条") + +# Shared abbreviation; language left unknown. +_add("und", "article", "art.") +_add("und", "section", "§") + +# Scripts we do not Latin-split: +NO_LATIN_SPLIT_LANGS = frozenset({"ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn", "am"}) + +_TOKEN_RE = re.compile(r"[^\W\d_]{2,}|art\.|sec\.|§", re.UNICODE) + + +def classify_heading_token(token: str) -> list[tuple[str, str]]: + return list(HEADING_LEXICON.get(token.casefold()) or ()) + + +def score_heading_languages(text: str) -> Counter[str]: + """Count distinctive lexicon hits. Shared words like 'article' do not vote.""" + counts: Counter[str] = Counter() + if not text: + return counts + for token in _TOKEN_RE.findall(text): + hits = classify_heading_token(token) + langs = {lang for _kind, lang in hits if lang != "und"} + if len(langs) == 1: + counts[next(iter(langs))] += 1 + return counts + + +def majority_language(counts: Counter[str], *, exclude: tuple[str, ...] = ("und",)) -> str | None: + filtered = Counter({k: v for k, v in counts.items() if k not in exclude}) + if not filtered: + return None + lang, _n = filtered.most_common(1)[0] + return lang + + +def iso_lang(value: Any) -> str: + text = str(value or "").strip().lower().replace("_", "-") + if not text: + return "" + return text.split("-")[0] + + +def latin_split_allowed(language: str) -> bool: + return iso_lang(language) not in NO_LATIN_SPLIT_LANGS diff --git a/country_laws_ir/query.py b/country_laws_ir/query.py index 061c17c4439724d2d93b26ffc09f7fc6cb4ea70b..9cd3a1da6f2ac29b2287609ec1bc797fd55c4774 100644 --- a/country_laws_ir/query.py +++ b/country_laws_ir/query.py @@ -176,7 +176,7 @@ def main(argv: list[str] | None = None) -> int: p_vec.add_argument("query") p_vec.add_argument("--top-k", type=int, default=10) p_vec.add_argument("--candidate-centroids", type=int, default=4) - p_vec.add_argument("--device", default="cpu") + p_vec.add_argument("--device", default="cuda") p_g = sub.add_parser("graph") g_sub = p_g.add_subparsers(dest="graph_cmd", required=True) diff --git a/country_laws_ir/sparse.py b/country_laws_ir/sparse.py index 5c691b4a91403e46ca842b2a62f76f16f4231fac..5ed793543ef74b1c48e313ee29cada56fd2aface 100644 --- a/country_laws_ir/sparse.py +++ b/country_laws_ir/sparse.py @@ -31,10 +31,18 @@ def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]: """ from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text + _MAX_TITLE = 8_192 + _MAX_BODY = 200_000 rows: list[dict[str, Any]] = [] for rec in corpus.itertuples(index=False): - title = str(getattr(rec, "title", "") or "") - body = str(getattr(rec, "body", "") or "") + title = str(getattr(rec, "title", "") or "").replace("\x00", "").strip() + body = str(getattr(rec, "body", "") or "").replace("\x00", "").strip() + if len(title) > _MAX_TITLE: + title = title[:_MAX_TITLE].rstrip() + if len(body) > _MAX_BODY: + body = body[:_MAX_BODY].rstrip() + if not title and not body: + continue if not tokenize_bm25_text(title) and not tokenize_bm25_text(body): continue rows.append( diff --git a/country_laws_ir/structure.py b/country_laws_ir/structure.py new file mode 100644 index 0000000000000000000000000000000000000000..468ecfdfff4eb76dc26a92c33c0e0e82d12c3712 --- /dev/null +++ b/country_laws_ir/structure.py @@ -0,0 +1,305 @@ +"""Extract legal hierarchy from country-law text (Oregon-style, multilingual). + +Oregon Revised Statutes are stored as title / chapter / section / subsection +trees. National gazettes are not that uniform: some use Article/Artikel, +some §, some only a single instrument body. + +This module: + +* strips leftover HTML chrome so GraphRAG sees legal text, not tags; +* detects multilingual heading markers (title/chapter/part/article/section); +* splits an instrument into those units when at least two headings exist; +* otherwise keeps the whole instrument (never invents a hierarchy). + +Subsection markers such as ``(a)`` / ``(1)`` are recorded on the parent +unit; they are not forced into their own retrieval rows. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from html.parser import HTMLParser +import html as html_lib +import re +import unicodedata +from typing import Any + +_WS_RE = re.compile(r"\s+", re.UNICODE) +_HAS_TAG_RE = re.compile(r"]*>") + +# Line-anchored headings. Numbers may be arabic, roman, or dotted (1.2). +_HEADING_RE = re.compile( + r"(?im)^[ \t]*(?:" + r"(?PTITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|T[IÍ]TUL)\s+" + r"(?P<title_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" + r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|CAP\.)\s+" + r"(?P<chapter_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" + r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL)\s+" + r"(?P<part_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" + r"|(?P<article>ART(?:ICLE|IKEL|ÍCULO|IGO|ICOLO|IKKEL)?\.?|ART\." + r"|ČLÁNEK|ČLÁNOK|ČLAN|SZAKASZ|ΆΡΘΡΟ|ΑΡΘΡΟ)\s+" + r"(?P<article_n>[0-9IVXLCDMΑ-Ω]+[A-Za-zΑ-Ωa-z0-9.\-]*)" + r"|(?P<section>SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|SEC\.)\s+" + r"(?P<section_n>[0-9A-Za-z.\-]+)" + r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9A-Za-z.\-]+)" + r")" + r"(?P<rest>[^\n]{0,200})?" +) + +_SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)") + +_KIND_RANK = { + "title": 1, + "chapter": 2, + "part": 3, + "article": 4, + "section": 5, + "subsection": 6, +} + +MIN_SPLIT_HEADINGS = 2 +MIN_UNIT_CHARS = 40 + +_ZH_ART_RE = re.compile( + r"(?:(?<=\n)|^)[  ]*" + r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)" +) +_AR_ART_RE = re.compile( + r"(?:(?<=\n)|^)[ \t]*(المادة|مادة)\s*([0-9٠-٩]+)" +) +_JA_ART_RE = re.compile( + r"(?:(?<=\n)|^)[  ]*(第[0-9一二三四五六七八九十百]+条)" +) + + +class _HTMLText(HTMLParser): + SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"} + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.parts: list[str] = [] + self.skip = 0 + + def handle_starttag(self, tag, attrs): + if tag in self.SKIP: + self.skip += 1 + if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0: + self.parts.append("\n") + + def handle_endtag(self, tag): + if tag in self.SKIP and self.skip: + self.skip -= 1 + if tag in {"p", "div", "li", "tr"} and self.skip == 0: + self.parts.append("\n") + + def handle_data(self, data): + if self.skip == 0: + self.parts.append(data) + + +def has_html_tags(text: str) -> bool: + return bool(text and _HAS_TAG_RE.search(text)) + + +def strip_html(raw: str) -> str: + """Turn leftover HTML into visible legal text. No-op if there are no tags.""" + if not raw or not _HAS_TAG_RE.search(raw): + return raw + parser = _HTMLText() + try: + parser.feed(raw) + parser.close() + text = "".join(parser.parts) + except Exception: + text = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw) + text = re.sub(r"(?is)<style.*?>.*?</style>", " ", text) + text = re.sub(r"(?is)<[^>]+>", " ", text) + text = html_lib.unescape(text).replace("\xa0", " ") + text = re.sub(r"[ \t]+", " ", text) + text = re.sub(r"\n[ \t]+", "\n", text) + text = re.sub(r"\n{3,}", "\n\n", text) + return text.strip() + + +def normalize_legal_text(value: Any) -> str: + """NFKC + HTML strip. Keeps newlines so heading detection still works.""" + if value is None: + return "" + text = unicodedata.normalize("NFKC", str(value)) + text = strip_html(text) + text = text.replace("\xa0", " ") + text = re.sub(r"[ \t]+", " ", text) + text = re.sub(r"\n[ \t]+", "\n", text) + text = re.sub(r"\n{3,}", "\n\n", text) + return text.strip() + + +@dataclass +class StructureUnit: + kind: str + number: str + heading: str + body: str + title_number: str = "" + chapter_number: str = "" + part_number: str = "" + article_number: str = "" + section_number: str = "" + subsections: tuple[str, ...] = () + hierarchy_path: str = "" + + def to_dict(self) -> dict[str, Any]: + return { + "kind": self.kind, + "number": self.number, + "heading": self.heading, + "body": self.body, + "title_number": self.title_number, + "chapter_number": self.chapter_number, + "part_number": self.part_number, + "article_number": self.article_number, + "section_number": self.section_number, + "subsections": list(self.subsections), + "hierarchy_path": self.hierarchy_path, + } + + +def _cursor_path(cursor: dict[str, str]) -> str: + parts = [] + for key, label in ( + ("title", "Title"), + ("chapter", "Chapter"), + ("part", "Part"), + ("article", "Article"), + ("section", "Section"), + ): + value = cursor.get(key) or "" + if value: + parts.append(f"{label} {value}") + return " > ".join(parts) + + +def _subsection_tokens(text: str) -> tuple[str, ...]: + seen: list[str] = [] + for match in _SUBSECTION_RE.finditer(text): + token = match.group(1) + if token not in seen: + seen.append(token) + if len(seen) >= 40: + break + return tuple(seen) + + +def _units_from_regex( + text: str, matches: list[re.Match[str]], *, kind: str, lang: str +) -> list[StructureUnit]: + if len(matches) < MIN_SPLIT_HEADINGS: + return [] + units: list[StructureUnit] = [] + for i, match in enumerate(matches): + start = match.start() + end = matches[i + 1].start() if i + 1 < len(matches) else len(text) + chunk = text[start:end].strip() + if len(chunk) < 16: + continue + number = re.sub(r"\s+", "", match.group(0)) + heading = re.sub(r"\s+", " ", chunk.split("\n", 1)[0])[:240] + units.append( + StructureUnit( + kind=kind, + number=number, + heading=heading, + body=chunk, + article_number=number, + hierarchy_path=heading, + ) + ) + return units if len(units) >= MIN_SPLIT_HEADINGS else [] + + +def split_script_units(text: str, language: str) -> list[StructureUnit]: + """Article splits for scripts that must not use Latin TITLE/ARTICLE.""" + from .profiles import iso_lang + + lang = iso_lang(language) + if lang in {"zh", "zh-cn", "zh-tw"}: + prepared = re.sub( + r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)", + r"\n\1", + text, + ) + return _units_from_regex(prepared, list(_ZH_ART_RE.finditer(prepared)), kind="article", lang="zh") + if lang in {"ar", "fa"}: + prepared = re.sub(r"(المادة|مادة)", r"\n\1", text) + return _units_from_regex(prepared, list(_AR_ART_RE.finditer(prepared)), kind="article", lang="ar") + if lang == "ja": + prepared = re.sub(r"(第[0-9一二三四五六七八九十百]+条)", r"\n\1", text) + return _units_from_regex(prepared, list(_JA_ART_RE.finditer(prepared)), kind="article", lang="ja") + return [] + + +def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]: + """Split *text* on legal headings. Empty list means keep the whole instrument. + + Latin TITLE/ARTICLE splits are skipped for languages in + ``profiles.NO_LATIN_SPLIT_LANGS`` so Arabic/Chinese bodies are not + carved up on incidental English words. + """ + from .profiles import latin_split_allowed + + if not text or len(text) < 16: + return [] + if language and not latin_split_allowed(language): + return split_script_units(text, language) + matches = list(_HEADING_RE.finditer(text)) + if len(matches) < MIN_SPLIT_HEADINGS: + return [] + cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""} + units: list[StructureUnit] = [] + for i, match in enumerate(matches): + start = match.start() + end = matches[i + 1].start() if i + 1 < len(matches) else len(text) + chunk = text[start:end].strip() + kind = "" + number = "" + for name in ("title", "chapter", "part", "article", "section"): + if match.group(name): + kind = name + number = (match.group(f"{name}_n") or "").strip() + break + if match.group("section_sym"): + kind = "section" + number = (match.group("section_sym_n") or "").strip() + if not kind or not number: + continue + cursor[kind] = number + for lower, rank in _KIND_RANK.items(): + if rank > _KIND_RANK[kind]: + cursor[lower] = "" + if len(chunk) < MIN_UNIT_CHARS: + continue + rest = (match.group("rest") or "").strip(" .-:") + heading = re.sub(r"\s+", " ", match.group(0)).strip() + if rest and rest not in heading: + heading = f"{heading} {rest}".strip() + units.append( + StructureUnit( + kind=kind, + number=number, + heading=heading[:240], + body=chunk, + title_number=cursor["title"], + chapter_number=cursor["chapter"], + part_number=cursor["part"], + article_number=cursor["article"], + section_number=cursor["section"], + subsections=_subsection_tokens(chunk), + hierarchy_path=_cursor_path(cursor), + ) + ) + retrieval = [u for u in units if u.kind in {"article", "section"}] + if len(retrieval) >= MIN_SPLIT_HEADINGS: + return retrieval + if len(units) >= MIN_SPLIT_HEADINGS: + return units + return [] diff --git a/country_laws_ir/vectors.py b/country_laws_ir/vectors.py index 86964fc732be9eac45cc37036862fa0078bc1948..5651e0f0e052dabffed783715a5b3b4c396a7b5e 100644 --- a/country_laws_ir/vectors.py +++ b/country_laws_ir/vectors.py @@ -14,7 +14,11 @@ import pandas as pd from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION MODEL_NAME = "thenlper/gte-small" +MODEL_REVISION = "17e1f347d17fe144873b1201da91788898c639cd" DIMENSION = 384 +MAX_SEQ_LENGTH = 512 +DEFAULT_DEVICE = "cuda" +SUPPORTED_DEVICES = frozenset({"cpu", "cuda", "cuda:0", "mps", "auto"}) MAX_ROWS_PER_CENTROID = 8192 MAX_SHARDS_PER_CENTROID = 2 @@ -24,41 +28,108 @@ def _l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray: return x / np.maximum(n, eps) -def embeddings_available() -> bool: +def device_is_available(device: str) -> bool: + """Probe accelerator availability without loading a model.""" + name = str(device or "").strip().lower() + if not name or name == "cpu": + return True + try: + import torch + except Exception: + return False + if name.startswith("cuda"): + return bool( + getattr(torch, "cuda", None) + and torch.backends.cuda.is_built() + and torch.cuda.is_available() + ) + if name == "mps": + mps = getattr(getattr(torch, "backends", None), "mps", None) + return bool(mps is not None and mps.is_available()) + return False + + +def select_device(requested: str = DEFAULT_DEVICE) -> tuple[str, bool]: + """Prefer CUDA like US Code / Open US Law; fall back to CPU.""" + req = str(requested or DEFAULT_DEVICE).strip().lower() or DEFAULT_DEVICE + if req == "auto": + req = "cuda" + if req not in SUPPORTED_DEVICES and not req.startswith("cuda:"): + raise ValueError(f"unsupported embedding device: {requested!r}") + if device_is_available(req): + return req, False + return "cpu", True + + +def ensure_embedding_stack() -> bool: + """Lazy-import / lazy-install transformers + sentence-transformers. + + Matches ``ipfs_datasets_py.auto_installer.ensure_module`` used by other + GraphRAG producers. Importing this module must not pip-install; first + encode may. + """ + import os + + os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1") try: - import torch # noqa: F401 - from sentence_transformers import SentenceTransformer # noqa: F401 + import sentence_transformers # noqa: F401 + import transformers # noqa: F401 return True + except Exception: + pass + try: + from ipfs_datasets_py.auto_installer import ensure_module, install_for_component + + install_for_component("graphrag") + ensure_module("torchvision", "torchvision") + ensure_module("transformers", "transformers") + module = ensure_module("sentence_transformers", "sentence-transformers") + return module is not None except Exception: return False +def embeddings_available() -> bool: + return ensure_embedding_stack() + + +def _is_real_vector(vec: object) -> bool: + try: + arr = np.asarray(vec, dtype=np.float32).reshape(-1) + except Exception: + return False + if arr.shape[0] != DIMENSION: + return False + if not np.isfinite(arr).all(): + return False + return float(np.linalg.norm(arr)) > 1e-6 + + def encode_corpus( corpus: pd.DataFrame, batch_size: int = 64, - device: str = "cpu", + device: str = DEFAULT_DEVICE, checkpoint_path: str | None = None, chunk_size: int = 4096, ) -> np.ndarray: - """Encode corpus texts with gte-small in chunks; persist checkpoints when given.""" + """Encode corpus texts with pinned gte-small on CUDA when available.""" import json import os from datetime import datetime, timezone from pathlib import Path as _Path + if not ensure_embedding_stack(): + raise RuntimeError( + "sentence-transformers is required for production GTE embeddings; " + "lazy install failed (python -m ipfs_datasets_py.auto_installer)" + ) from sentence_transformers import SentenceTransformer from .auth import configure_hf configure_hf() - cache_root = _Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"))) / "cache" / "hf" - os.environ.setdefault("HF_HOME", str(cache_root)) - os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1") - os.environ.setdefault( - "SENTENCE_TRANSFORMERS_HOME", - str(cache_root / "sentence-transformers"), - ) + device, _fallback = select_device(device) texts = [] for rec in corpus.itertuples(index=False): title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or "" @@ -70,12 +141,22 @@ def encode_corpus( done = 0 ckpt = _Path(checkpoint_path) if checkpoint_path else None meta_path = ckpt.with_suffix(".json") if ckpt else None - meta_n = None + cache_root = _Path( + os.environ.get( + "COUNTRY_LAWS_IR_ROOT", + str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"), + ) + ) / "cache" / "hf" + os.environ.setdefault("HF_HOME", str(cache_root)) + os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1") + os.environ.setdefault("SENTENCE_TRANSFORMERS_HOME", str(cache_root / "sentence-transformers")) if meta_path is not None and meta_path.exists(): try: meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n") except Exception: meta_n = None + else: + meta_n = None if ckpt is not None and ckpt.exists(): cached = np.load(ckpt) same_corpus = meta_n is None or int(meta_n) == n @@ -87,56 +168,76 @@ def encode_corpus( ): done = int(cached.shape[0]) out[:done] = cached.astype(np.float32, copy=False) - print(f"embeddings resume {done}/{n} from {ckpt}", flush=True) - else: - print( - f"embeddings checkpoint shape {getattr(cached, 'shape', None)} " - f"meta_n={meta_n} incompatible with {(n, DIMENSION)}; restarting", - flush=True, + if done >= n: + return out + + lock_fh = None + if device.startswith("cuda"): + import fcntl + + lock_path = _Path( + os.environ.get( + "COUNTRY_LAWS_IR_ROOT", + str(_Path.home() / ".ipfs_datasets" / "country-laws-ir"), ) - if done >= n: - return out - model = SentenceTransformer(MODEL_NAME, device=device) - while done < n: - j = min(done + int(chunk_size), n) - chunk = model.encode( - texts[done:j], - batch_size=batch_size, - show_progress_bar=True, - convert_to_numpy=True, - normalize_embeddings=True, + ) / "cuda.encode.lock" + lock_path.parent.mkdir(parents=True, exist_ok=True) + lock_fh = open(lock_path, "a", encoding="utf-8") + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) + try: + model = SentenceTransformer( + MODEL_NAME, + revision=MODEL_REVISION, + device=device, ) - out[done:j] = np.asarray(chunk, dtype=np.float32) - done = j - print(f"embeddings checkpoint {done}/{n}", flush=True) try: - from .mem import checkpoint as _mem_checkpoint - _mem_checkpoint(f"embeddings@{done}", row=done, every_n=max(chunk_size, 4096)) - except Exception as _mem_exc: - # MemAbort should propagate; other import issues are non-fatal - from .mem import MemAbort - if isinstance(_mem_exc, MemAbort): - raise - if ckpt is not None: - ckpt.parent.mkdir(parents=True, exist_ok=True) - tmp = ckpt.with_name(ckpt.name + ".tmp.npy") - np.save(tmp, out[:done]) - tmp.replace(ckpt) - if meta_path is not None: - meta_path.write_text( - json.dumps( - { - "n": n, - "done": done, - "dimension": DIMENSION, - "model_name": MODEL_NAME, - "ts": datetime.now(timezone.utc).isoformat(), - } + model.max_seq_length = MAX_SEQ_LENGTH + except Exception: + pass + while done < n: + j = min(done + int(chunk_size), n) + chunk = model.encode( + texts[done:j], + batch_size=batch_size, + show_progress_bar=True, + convert_to_numpy=True, + normalize_embeddings=True, + ) + out[done:j] = np.asarray(chunk, dtype=np.float32) + done = j + if ckpt is not None: + ckpt.parent.mkdir(parents=True, exist_ok=True) + tmp = ckpt.with_name(ckpt.name + ".tmp.npy") + np.save(tmp, out[:done]) + tmp.replace(ckpt) + if meta_path is not None: + meta_path.write_text( + json.dumps( + { + "n": n, + "done": done, + "dimension": DIMENSION, + "model_name": MODEL_NAME, + "ts": datetime.now(timezone.utc).isoformat(), + } + ) + + "\n", + encoding="utf-8", ) - + "\n", - encoding="utf-8", - ) - return out + return out + finally: + if lock_fh is not None: + import fcntl as _fcntl + + _fcntl.flock(lock_fh.fileno(), _fcntl.LOCK_UN) + lock_fh.close() + try: + import torch as _torch + + if _torch.cuda.is_available(): + _torch.cuda.empty_cache() + except Exception: + pass def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray: @@ -345,14 +446,14 @@ def assemble_embeddings( *, encode_missing: bool = True, batch_size: int = 64, - device: str = "cpu", + device: str = DEFAULT_DEVICE, checkpoint_path: str | None = None, ) -> tuple[np.ndarray, dict[str, Any]]: - """Align a (n, 384) matrix to *corpus* row order, reusing unchanged CIDs. + """Align a (n, 384) matrix to *corpus* row order. - Positional checkpoints are unsafe when scrapes append pages. Identity is - ``entry_cid``. Missing CIDs are encoded only when ``encode_missing`` is true - and sentence-transformers is available. + Reuse is CID-keyed and only accepts real GTE vectors (finite, 384-d, + non-zero). Stub/zero priors are treated as missing and re-encoded on + CUDA when available — the US Code / Open US Law contract. """ n = int(len(corpus)) out = np.zeros((n, DIMENSION), dtype=np.float32) @@ -362,18 +463,10 @@ def assemble_embeddings( cids = corpus["entry_cid"].astype(str).tolist() if n else [] for i, cid in enumerate(cids): vec = prior.get(cid) - if vec is None: - missing_idx.append(i) - continue - try: - arr = np.asarray(vec, dtype=np.float32).reshape(-1) - except Exception: - missing_idx.append(i) - continue - if arr.shape[0] != DIMENSION: + if not _is_real_vector(vec): missing_idx.append(i) continue - out[i] = arr + out[i] = np.asarray(vec, dtype=np.float32).reshape(-1) reused_idx.append(i) report: dict[str, Any] = { @@ -382,25 +475,29 @@ def assemble_embeddings( "n_encoded": 0, "n_missing": len(missing_idx), "model_name": MODEL_NAME, + "model_revision": MODEL_REVISION, "dimension": DIMENSION, "status": "reused" if not missing_idx else "partial", } + resolved, fallback = select_device(device) + report["device"] = resolved + report["device_fallback"] = fallback if not missing_idx: report["status"] = "reused" return _l2_normalize(out) if n else out, report if not encode_missing: report["status"] = "incomplete" return out, report - if not embeddings_available(): + if not ensure_embedding_stack(): report["status"] = "stub_missing_encoder" - report["reason"] = "sentence-transformers/torch unavailable" + report["reason"] = "sentence-transformers/transformers lazy install failed" return out, report missing = corpus.iloc[missing_idx].reset_index(drop=True) encoded = encode_corpus( missing, batch_size=batch_size, - device=device, + device=resolved, checkpoint_path=checkpoint_path, ) for local_i, corpus_i in enumerate(missing_idx): diff --git a/country_laws_ir/verify.py b/country_laws_ir/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..1dc7970bebb9471cbe2372dd16dc7e87a63d786f --- /dev/null +++ b/country_laws_ir/verify.py @@ -0,0 +1,280 @@ +"""Admission verifiers for country-law normalization, before GraphRAG. + +Oregon-style structure is preferred but not required for every gazette. +Verifiers fail closed on invented text, residual HTML, empty corpora, and +duplicate CIDs. Missing title/section hierarchy is a warning unless the +corpus already split into articles. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +import re +from typing import Any + +import pandas as pd + +from .structure import has_html_tags + +SCHEMA_VERSION = "country-laws-normalize-verify/v1" + +_HTML_FAIL_FRACTION = 0.02 +_SHORT_BODY_FAIL_FRACTION = 0.50 +_MIN_BODY_CHARS = 40 + + +@dataclass(frozen=True) +class Check: + id: str + severity: str # fail | warn + passed: bool + message: str + evidence: dict[str, Any] + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def _bodies(corpus: pd.DataFrame) -> list[str]: + if corpus is None or corpus.empty or "body" not in corpus.columns: + return [] + return [str(x or "") for x in corpus["body"].tolist()] + + +def check_nonempty(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + n = int(len(corpus)) if corpus is not None else 0 + return Check( + id="nonempty_corpus", + severity="fail", + passed=n > 0, + message="normalized corpus has rows" if n else "normalized corpus is empty", + evidence={"n_out": n, "n_dropped": report.get("n_dropped_total")}, + ) + + +def check_entry_cids(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + if corpus is None or corpus.empty: + return Check( + id="entry_cid_unique", + severity="fail", + passed=False, + message="no entry_cid values to verify", + evidence={}, + ) + missing = int(corpus["entry_cid"].isna().sum()) if "entry_cid" in corpus.columns else int(len(corpus)) + dupes = int(corpus["entry_cid"].duplicated().sum()) if "entry_cid" in corpus.columns else 0 + empty = int((corpus["entry_cid"].astype(str).str.strip() == "").sum()) if "entry_cid" in corpus.columns else 0 + ok = missing == 0 and dupes == 0 and empty == 0 + return Check( + id="entry_cid_unique", + severity="fail", + passed=ok, + message="every row has a unique entry_cid" if ok else "missing or duplicate entry_cid", + evidence={"missing": missing, "empty": empty, "duplicate": dupes}, + ) + + +def check_no_invented_text(report: dict[str, Any]) -> Check: + flag = bool(report.get("never_invented_legal_text", False)) + return Check( + id="never_invented_legal_text", + severity="fail", + passed=flag, + message="normalizer did not invent legal text" if flag else "invented-text flag is false", + evidence={"never_invented_legal_text": flag}, + ) + + +def check_html_residual(corpus: pd.DataFrame) -> Check: + bodies = _bodies(corpus) + tagged = [b for b in bodies if has_html_tags(b)] + n = len(bodies) or 1 + fraction = len(tagged) / float(n) + passed = fraction <= _HTML_FAIL_FRACTION + return Check( + id="html_residual", + severity="fail", + passed=passed, + message=( + "HTML tags stripped from legal bodies" + if passed + else f"{len(tagged)}/{len(bodies)} bodies still contain HTML tags" + ), + evidence={ + "n_bodies": len(bodies), + "n_with_tags": len(tagged), + "fraction": fraction, + "samples": [b[:120] for b in tagged[:5]], + }, + ) + + +def check_short_bodies(corpus: pd.DataFrame) -> Check: + bodies = _bodies(corpus) + if not bodies: + return Check( + id="short_bodies", + severity="fail", + passed=False, + message="no bodies to measure", + evidence={}, + ) + short = sum(1 for b in bodies if len(b) < _MIN_BODY_CHARS) + fraction = short / float(len(bodies)) + passed = fraction <= _SHORT_BODY_FAIL_FRACTION + return Check( + id="short_bodies", + severity="fail" if not passed else "warn", + passed=passed, + message=( + "most legal units have usable body length" + if passed + else f"{short}/{len(bodies)} bodies shorter than {_MIN_BODY_CHARS} characters" + ), + evidence={"n_short": short, "n_bodies": len(bodies), "fraction": fraction}, + ) + + +def check_heading_language(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + """Warn when Latin heading dialect disagrees with the document language.""" + from .profiles import NO_LATIN_SPLIT_LANGS, iso_lang + + doc_lang = iso_lang(report.get("document_language_majority") or "") + head_lang = iso_lang(report.get("heading_language_majority") or "") + counts = report.get("heading_language_counts") or {} + if ( + doc_lang in NO_LATIN_SPLIT_LANGS + and report.get("unit") == "structured" + and head_lang + and head_lang not in NO_LATIN_SPLIT_LANGS + and head_lang != doc_lang + ): + return Check( + id="heading_language", + severity="fail", + passed=False, + message=( + f"document language {doc_lang} was split with Latin headings ({head_lang}); " + "use script-specific article markers or collector article rows" + ), + evidence={"document_language": doc_lang, "heading_counts": counts, "unit": report.get("unit")}, + ) + if doc_lang and head_lang and doc_lang != head_lang and sum(counts.values()) >= 8: + return Check( + id="heading_language", + severity="warn", + passed=True, + message=( + f"heading lexicon majority is {head_lang} but documents are {doc_lang}; " + "review samples before trusting structure" + ), + evidence={ + "document_language": doc_lang, + "heading_language": head_lang, + "heading_counts": counts, + }, + ) + return Check( + id="heading_language", + severity="warn", + passed=True, + message=( + f"heading lexicon {head_lang or 'none'} vs document language {doc_lang or 'unknown'}" + ), + evidence={ + "document_language": doc_lang, + "heading_language": head_lang, + "heading_counts": counts, + }, + ) + + +def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + unit = str(report.get("unit") or "") + n = int(len(corpus)) if corpus is not None else 0 + structured_rows = 0 + if corpus is not None and not corpus.empty: + if "hierarchy_path" in corpus.columns: + structured_rows = int((corpus["hierarchy_path"].fillna("").astype(str).str.len() > 0).sum()) + if "record_type" in corpus.columns: + structured_rows = max( + structured_rows, + int(corpus["record_type"].isin(["article", "section"]).sum()), + ) + coverage = structured_rows / float(n) if n else 0.0 + # Article or structured units are success. Pure law-level is a warning, not a fail: + # many gazettes have no title/section markers. + if unit in {"article", "structured"} or coverage >= 0.5: + return Check( + id="legal_structure", + severity="warn", + passed=True, + message=f"retrieval units are structured ({unit}, coverage={coverage:.2f})", + evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage}, + ) + return Check( + id="legal_structure", + severity="warn", + passed=True, + message=( + "kept whole-instrument units; no title/article/section headings detected " + "(expected for some gazettes)" + ), + evidence={"unit": unit, "structured_rows": structured_rows, "coverage": coverage}, + ) + + +def verify_normalized_corpus( + corpus: pd.DataFrame, + report: dict[str, Any], + *, + slug: str = "", +) -> dict[str, Any]: + """Run all normalization verifiers. Fail-closed on any failed `fail` check.""" + checks = [ + check_nonempty(corpus, report), + check_entry_cids(corpus, report), + check_no_invented_text(report), + check_html_residual(corpus), + check_short_bodies(corpus), + check_structure(corpus, report), + check_heading_language(corpus, report), + ] + failed = [c for c in checks if c.severity == "fail" and not c.passed] + admitted = not failed + return { + "schema_version": SCHEMA_VERSION, + "slug": slug, + "admitted": admitted, + "n_checks": len(checks), + "n_failed": len(failed), + "failed_ids": [c.id for c in failed], + "checks": [c.to_dict() for c in checks], + "blocks_graphrag": not admitted, + } + + +class NormalizationAdmissionError(RuntimeError): + """Raised when verifiers refuse to send a corpus to GraphRAG.""" + + +def verify_source(source: str) -> dict[str, Any]: + """Load a Hub/local pack, normalize, and run verifiers (no GraphRAG).""" + from .build import CACHE + from .catalog import get_country + from .normalize import build_corpus, load_source + + country = get_country(source) + local = country.get("local_source_dir") + laws, articles, source_meta = load_source(local or country["repo"], CACHE) + corpus, report = build_corpus(laws, articles, source_meta) + verdict = verify_normalized_corpus(corpus, report, slug=country["slug"]) + report["verification"] = verdict + return { + "slug": country["slug"], + "source": country["repo"], + "n_out": report.get("n_out"), + "unit": report.get("unit"), + "verification": verdict, + "drops": report.get("drops"), + } diff --git a/data/bm25/documents/part-000000.parquet b/data/bm25/documents/part-000000.parquet index 3bc94144c68e144a73ff49f93d44f8edce01885f..b68a2ec14002c096e6a37b2db4e7d5096801f3ed 100644 --- a/data/bm25/documents/part-000000.parquet +++ b/data/bm25/documents/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0b662bb923de230d8d1485fc742f51bf85e846eefbfd4cef84a78444838c5aec -size 475351 +oid sha256:460b93df18faa027d93d98533a93050663a6e7646390941a7a828b8366c8f363 +size 475277 diff --git a/data/bm25/documents/part-000001.parquet b/data/bm25/documents/part-000001.parquet index 6d36f2d06709cac8326a65b4ff2399e8eb9eafc0..7aeb727dc1e8f0d9149bb5000a1808b946fa2a57 100644 --- a/data/bm25/documents/part-000001.parquet +++ b/data/bm25/documents/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bf014b7d1643d3d45404e5ac2d14a31d207e967a0effb0e93bdd2532ad6771e3 -size 487273 +oid sha256:ef04d08740257b450afa4eaae22e4ff400512fe886c5e6da94cb5b3453a3b04b +size 487237 diff --git a/data/corpus/part-000000.parquet b/data/corpus/part-000000.parquet index 01eddf85c24483600ab32cddcda1621ae90d2263..9bfe4c786f37013d8b6ee6045dc0bc2a2b7cb176 100644 --- a/data/corpus/part-000000.parquet +++ b/data/corpus/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:de8188af94587254a44e6fd655aee3b3424aaf57e01a5001ee3f07ce16ff3348 -size 2307689 +oid sha256:25e7813b8911d95c122e6fa623b2aa2614d622cec9d9f9838644cd56b1864019 +size 2377416 diff --git a/data/corpus/part-000001.parquet b/data/corpus/part-000001.parquet index 6e15ebc3110c5abbbdd5cdaa9329fda4a84629b8..bc6fa96c181a30a5e17c9a4c9317dc42ed9bfa13 100644 --- a/data/corpus/part-000001.parquet +++ b/data/corpus/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7de905c875ec742f78c7efd1976a0f8bf87aef1fac7deb4543c9bc427b4d7524 -size 2495771 +oid sha256:e565339afc1d1f2a09bd5287f9b10cc6cc9b2282c0ffea3aac4ac9f5a3c426b8 +size 2572576 diff --git a/data/graph/adjacency/in/part-000000.parquet b/data/graph/adjacency/in/part-000000.parquet index b2a2bba29a87bf7a54b9199566f54049f6a56892..28e827e89cf19cce0c7bed546bd760464b3b5a03 100644 --- a/data/graph/adjacency/in/part-000000.parquet +++ b/data/graph/adjacency/in/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fca17077428de67ef7ac6fb178f8fc4e6c436ac6a2d0bc1d9b996454e03d61af -size 316554 +oid sha256:e5ea70c1c8d77e93636c8417decda929c3769b55a727097ce7dfb83f7a501598 +size 316588 diff --git a/data/graph/adjacency/in/part-000001.parquet b/data/graph/adjacency/in/part-000001.parquet index 084e152a75782161abfb9dcc12d4f7672bb0ff75..d17728f1684ce91a2bc1fa83e8e310053ae933a6 100644 --- a/data/graph/adjacency/in/part-000001.parquet +++ b/data/graph/adjacency/in/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:25d77bf75d244236af46226f0c9a820396b5becc30b2926968cff8721fcc12ab -size 571936 +oid sha256:0247655b967e82ff89cb43de9d8b1ac6740fb197f2b48ad6d16444a88823cf46 +size 572860 diff --git a/data/graph/adjacency/in/part-000002.parquet b/data/graph/adjacency/in/part-000002.parquet index c4f359427366df7ea67f2e6c1c55d5fb744a57f4..423389bc29e24a6ed10da6424fe0e295da5a2e62 100644 --- a/data/graph/adjacency/in/part-000002.parquet +++ b/data/graph/adjacency/in/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ea84a1a209bb7cea4006cd0bc2bcc0898a11c418291625f00cb6ed9852c66f23 -size 407618 +oid sha256:55e6a1ef03beb467d7cd8ba3ddf32a6008a66c9b2788a1a5b45b67c01394f6e6 +size 408484 diff --git a/data/graph/adjacency/in/part-000003.parquet b/data/graph/adjacency/in/part-000003.parquet index e314c7b4d804e7b7a3f0f3b896c48694253467df..eb7f3dfe9a13ab7b75d8834f6370e8c194185e7a 100644 --- a/data/graph/adjacency/in/part-000003.parquet +++ b/data/graph/adjacency/in/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:42326f24e20306b969b3a59b2076d5d9ddad16a132261ae59e065e368322eb5d -size 510927 +oid sha256:9779ddccbe028c629045fd5e4b79fd3cf69c8a013d683fab49b2819191b0c1fc +size 511388 diff --git a/data/graph/adjacency/in/part-000004.parquet b/data/graph/adjacency/in/part-000004.parquet index 53bf498398e973ed7b0e365ef47996cbf6321b7e..5618ad1320f7a9808ba7030a64dfe756efeb2fd3 100644 --- a/data/graph/adjacency/in/part-000004.parquet +++ b/data/graph/adjacency/in/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:cfc08466007f77bf4109c51f1cb1d8daffd3891ff7cc2006cf12c8bd50bfca58 -size 373027 +oid sha256:5a547efa604a4d94e46e3e3d3b1cec5fb77858ebbeefb5e797ea6414bfcf4a4a +size 372774 diff --git a/data/graph/adjacency/in/part-000005.parquet b/data/graph/adjacency/in/part-000005.parquet index 6e4395bf85686a091a02ae9b54d3f97c34366cd2..0ef9846e2f7f6846c21a6fcaa57736be0aa9cfa1 100644 --- a/data/graph/adjacency/in/part-000005.parquet +++ b/data/graph/adjacency/in/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:32b9aae1a66d9734843277af0cdbddd17c6e7373236168f46222c3518b3460db -size 512847 +oid sha256:c8b31c37fa9f390fa4b95c4f20f0aee3b72852a8f375a95d3e6fda9edf21eac4 +size 512632 diff --git a/data/graph/adjacency/in/part-000006.parquet b/data/graph/adjacency/in/part-000006.parquet index b7b5a2815e66312980f7b15d539239068d125e20..9c06c59bbed7cd789e71f30c8e1178d6952c1881 100644 --- a/data/graph/adjacency/in/part-000006.parquet +++ b/data/graph/adjacency/in/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bfdef8f5544ca8e59220590e0929682b52fa24690724617c435605d4bd9013f7 -size 392399 +oid sha256:ac11a83320ad42abbf093ef5fbc69247a5957439153f411cbb884413057fad25 +size 392139 diff --git a/data/graph/adjacency/in/part-000007.parquet b/data/graph/adjacency/in/part-000007.parquet index 9d143960261ecec2c56496164d33dae985e9b5c6..2af2eabb862b8e495bd48c9e187a37b92d3aafbf 100644 --- a/data/graph/adjacency/in/part-000007.parquet +++ b/data/graph/adjacency/in/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7b6d422f8d17a3e9d6a1bdd1f43ebea0b4ef5ac8fe7401e241eedc5cb8f90990 -size 516302 +oid sha256:cf71ec170b4b0a544bcd2f29dce7afd30da94d10de17490198a1a918dde32cbc +size 517362 diff --git a/data/graph/adjacency/in/part-000008.parquet b/data/graph/adjacency/in/part-000008.parquet index 2d7c8a521e3397582a7bad3a692b763c52acf59e..9918e34f575bc121af703f415fa699f810d63148 100644 --- a/data/graph/adjacency/in/part-000008.parquet +++ b/data/graph/adjacency/in/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:de32220d057c192cbdfac912cfbcdc1bbf024d939a7af4e08ff989f709df1bb3 -size 82763 +oid sha256:e8ab6a3a23ed5ff7ce0d84c81938b3a3b14bd8418293c51a71176b8f58c1c29b +size 82743 diff --git a/data/graph/adjacency/out/part-000000.parquet b/data/graph/adjacency/out/part-000000.parquet index c1587caf7f33d6b1d30cab2d75e63fb8a368044a..9f0a2f04c8847800a7470fef29079f6cb709cec9 100644 --- a/data/graph/adjacency/out/part-000000.parquet +++ b/data/graph/adjacency/out/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:027fd8204a5b7d8fcb14462bc29c0905e773832a7d65ac4bf4fca1d2c80326ad -size 382359 +oid sha256:35a676ad8a9926bcc1acf930b8c548a1c6941f995c22f6da165c1f1ebc5b39a7 +size 383181 diff --git a/data/graph/adjacency/out/part-000001.parquet b/data/graph/adjacency/out/part-000001.parquet index 91a5d196f7ce4b1bd36460aba163a004618975d3..3db8b06d4bd57c0604ee17d052d28791fd33539a 100644 --- a/data/graph/adjacency/out/part-000001.parquet +++ b/data/graph/adjacency/out/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9ae272b0d9d60508d6c2be5e2c48f7ae2246e611449f45edac4951d6379e85d8 -size 382079 +oid sha256:dbd2f86c77a6093201ad019a1eb26ed9c094cb179f2f9e28447e9b79539cea25 +size 383385 diff --git a/data/graph/adjacency/out/part-000002.parquet b/data/graph/adjacency/out/part-000002.parquet index 02129b5654141dee58d8460c8ac628f06308786b..cab5730255e1a2f931a191c85a519dcfb8cf8336 100644 --- a/data/graph/adjacency/out/part-000002.parquet +++ b/data/graph/adjacency/out/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6e431b536084531787705e2abd060c0d083959657f5b09d136e0115fcbf358f5 -size 381672 +oid sha256:edc316004880c2ac916e01b2735b347547731e4b13ad5fb22ec83b9e5cdf51c4 +size 383066 diff --git a/data/graph/adjacency/out/part-000003.parquet b/data/graph/adjacency/out/part-000003.parquet index 04881eff2c5c373d8bcc59d12d3bb333d288b245..2c3a2a3ec29b159e987028b5e9dcee4ef600cf12 100644 --- a/data/graph/adjacency/out/part-000003.parquet +++ b/data/graph/adjacency/out/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:33224f09595aa5bbfbcba2bcaf219bb01035f56ed8c4ee38bf691f0a4b87b13b -size 383307 +oid sha256:bafc9d61142c07f30f2588b17f7673a026c42732f15bbdfa08272ff71997c2f7 +size 383363 diff --git a/data/graph/adjacency/out/part-000004.parquet b/data/graph/adjacency/out/part-000004.parquet index 1a4bdaf4f379fe27873eedfe04f24619764cb92e..67b6a608fd302cdfbbdc8e78046da28817de2664 100644 --- a/data/graph/adjacency/out/part-000004.parquet +++ b/data/graph/adjacency/out/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:432be4853ae5914c61675e84acd1d630529fd8495d12c53b1b3203956fbf9816 -size 383787 +oid sha256:4325529239333361dd44290989e0c96420b34b9233b6e4939462008bacdf92fd +size 381335 diff --git a/data/graph/adjacency/out/part-000005.parquet b/data/graph/adjacency/out/part-000005.parquet index c4ff2f8938675ad0f8ed63c3a3c5050c829b91bd..183f3a5ebab3451d9260ca58a9537556f068e09b 100644 --- a/data/graph/adjacency/out/part-000005.parquet +++ b/data/graph/adjacency/out/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:261093574601918cbe5a69258a45f9b14e1af12f94fa6d44b10b507cfb7a6b1a -size 383559 +oid sha256:88aad192b7a916b5d6bbc757d423a1207091efa34feec4edc72d21cdf5cb3096 +size 382132 diff --git a/data/graph/adjacency/out/part-000006.parquet b/data/graph/adjacency/out/part-000006.parquet index 288acdf2e8d2bb6a7fd80d9e4cef20a1faa8baa6..b184a11f39658b01c24feb5ad088d3051a351a01 100644 --- a/data/graph/adjacency/out/part-000006.parquet +++ b/data/graph/adjacency/out/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f0ab3b4697139c261323409300c3b9463e6db050b3a280c0ea451ae95ff7cf5a -size 296760 +oid sha256:fe8b34e5690664ed820aca49ed4e6200f8a8890f285576e0172a8af9da7e8331 +size 297299 diff --git a/data/graph/edges/part-000000.parquet b/data/graph/edges/part-000000.parquet index 8ebd5dfd36a1c80e8f9735d013012a152f09f544..df42c36279d23547a3de6c56b9c675a943d03f2a 100644 --- a/data/graph/edges/part-000000.parquet +++ b/data/graph/edges/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:21428b00a0321ba37a5bc43288ee34cf94006c4d53747ad91b6fb0c4696b191d -size 294782 +oid sha256:64c8c438f73029872c143ff6696e36dab28a3d2cfbafa1d04ba1370404694f64 +size 292788 diff --git a/data/graph/edges/part-000001.parquet b/data/graph/edges/part-000001.parquet index 3a993049b1ea84c76d416f9f83de8441683952f5..7351275a344fd2054291991d06daf0af3073c8f7 100644 --- a/data/graph/edges/part-000001.parquet +++ b/data/graph/edges/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1b9cea0516f829a789ef0d71164ea785eb9cd22ddbcf051e4b6a65b6a84e2333 -size 294424 +oid sha256:dfc633ef9bf6d9b70f494d507f44af118c4f8ae6ac8101f22876f601b19bd74d +size 295424 diff --git a/data/graph/edges/part-000002.parquet b/data/graph/edges/part-000002.parquet index a9ef823dbe6e7ce7fbd4d5577d7861b534a75774..7354ba456d8672f131d07d1201fc19e80ea73f96 100644 --- a/data/graph/edges/part-000002.parquet +++ b/data/graph/edges/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2d91070d212e0b9d5cd62cc93c629d5323c6ba40a0ac4ac97216ae680150a078 -size 294376 +oid sha256:c2f135a25a433e58682afbf174d76d192a9ec4316b0b240af538ec769aabc863 +size 294426 diff --git a/data/graph/edges/part-000003.parquet b/data/graph/edges/part-000003.parquet index 4b90db29fb9a84cbb44ae488f5e2df1da763371d..3a708b49b6dac0660ecec3a5101224000d2f267b 100644 --- a/data/graph/edges/part-000003.parquet +++ b/data/graph/edges/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:897916ba941761bce30b42c4d18b814e8a569edffabd53714565e2813ca5a185 -size 292957 +oid sha256:c3cf6e1bcf5b138b1dbe33a87bc21e15b51c1f9a21e6b9b450f6c89b91fe33bc +size 294729 diff --git a/data/graph/edges/part-000004.parquet b/data/graph/edges/part-000004.parquet index 362f66caf4e1202729192371fdb728a80b5bf4ef..6e4c637d2f68b19856589de6dbce8d2e8e0e402f 100644 --- a/data/graph/edges/part-000004.parquet +++ b/data/graph/edges/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d2ccd0b6a2b148135351267ccd0d1be7da6478ddba14490f299be580d0ef631c -size 295027 +oid sha256:3e9da5ed631f417ac0d20538a31b9a5a148b7a50b6538c025189babfee7d74ea +size 295419 diff --git a/data/graph/edges/part-000005.parquet b/data/graph/edges/part-000005.parquet index e84358611d20a92e7feb10a3f4b03a01aef22dc1..7df7a5d9ca486564a5fe0f08c0cf08c637c3fab5 100644 --- a/data/graph/edges/part-000005.parquet +++ b/data/graph/edges/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:10f105fc2e3c0aa0ed5eb9f5923a2a973536fcc201c61e17aa7a7c1877b63942 -size 294298 +oid sha256:a3b24f850942ee0a8f5b54aaadfa2c19aa1366dcb693d5ca1d229bb22408467f +size 294953 diff --git a/data/graph/edges/part-000006.parquet b/data/graph/edges/part-000006.parquet index f338109d5acd4ba7807fcb67fe09030c1ac170e1..d17e4ace62b585910517ca934b49fbadacb8249c 100644 --- a/data/graph/edges/part-000006.parquet +++ b/data/graph/edges/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ac89aaaf371a16b8d776b0d2b099517fce328e1dd2b812fbf3487cf417743d07 -size 292629 +oid sha256:099ca3b9c9457db48e5a385e1725968f620576b5079332341312be83c0958c57 +size 294836 diff --git a/data/graph/edges/part-000007.parquet b/data/graph/edges/part-000007.parquet index 75087238a33ac6904bcecefe03105fbd715d7fe3..6994f993d0229eec70c5eecf56ee4f617508a7e8 100644 --- a/data/graph/edges/part-000007.parquet +++ b/data/graph/edges/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:01951eff89a87f5605b33dca71743388ba6b28a799de36c23b6b4a5c94ffaeaa -size 294475 +oid sha256:90eee28c2fe8d3de995f8aeb065905b0b52702d29cd3398e30ad3a121c113b3b +size 292884 diff --git a/data/graph/edges/part-000008.parquet b/data/graph/edges/part-000008.parquet index 1ea18883b7df32d8d1243bd3572981b89b64d29c..4f950f0ecdadff3dae3e2e3485783f7970488f1f 100644 --- a/data/graph/edges/part-000008.parquet +++ b/data/graph/edges/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:eb3a8d18ed3e7aa1757ea48e79af1afbed8866a6f488d473636243f081a06505 -size 294094 +oid sha256:dcf2084a740302b5ea24cc99684da1337f96b820a692d79923d3616663094a84 +size 295885 diff --git a/data/graph/edges/part-000009.parquet b/data/graph/edges/part-000009.parquet index 3673b3792066119116c8907e668c8de4ec782cd1..0c7291a022ae486679651ea52e8f938a4b832bed 100644 --- a/data/graph/edges/part-000009.parquet +++ b/data/graph/edges/part-000009.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7eb63219c2301f5eba230b7fcaa9330774d4111d2c07947c89f6ded757603b2d -size 294031 +oid sha256:32c82a34b4570eff2d4929c7029a2bfe11b97e28147e1ebc45cebe0f02f19143 +size 294911 diff --git a/data/graph/edges/part-000010.parquet b/data/graph/edges/part-000010.parquet index 9d512fab1ac3c4f35a899f06bfc2b3b656b99d5d..ca1238c21ee4d2baf7dce35673078482caecfcef 100644 --- a/data/graph/edges/part-000010.parquet +++ b/data/graph/edges/part-000010.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:832284a909c6399bf61098161c7ea04518ec5c4620b500276f593c54eb950250 -size 292979 +oid sha256:4e73f9b03c038628fd19155baa2cf79d1200dcaedc1069e0b1f96b87fc46f72f +size 293854 diff --git a/data/graph/edges/part-000011.parquet b/data/graph/edges/part-000011.parquet index 15462d55295dc089c67f610a4c923f4e7963c626..317955db992bdd68a1a742ee8aa6c3743a0bdb16 100644 --- a/data/graph/edges/part-000011.parquet +++ b/data/graph/edges/part-000011.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0fa894848b8e32c6a77f178f47f7cdb213fc03995c5757f1bbc549aeb53fa40f -size 295400 +oid sha256:76749c3f60fe6f3c9825a71c35068e356d303b945010aa6e6f93ad331be58f7a +size 294383 diff --git a/data/graph/edges/part-000012.parquet b/data/graph/edges/part-000012.parquet index 527675adb06236e0e2fadc6d78bbd56df66eaa31..cdba2d861dcccb8ffdc3a4f8c8dad58385267c10 100644 --- a/data/graph/edges/part-000012.parquet +++ b/data/graph/edges/part-000012.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3ce3324e52232b46d44496c77e86587f612f52398d3f7d55fa6abc851b1f95ab -size 292949 +oid sha256:9096e81367d7874444a7bed374067cb0beef2267c9eee7454c1fd885fa66ffc5 +size 295537 diff --git a/data/graph/edges/part-000013.parquet b/data/graph/edges/part-000013.parquet index 39ccc5f4d5bd210a9fbcc58037096446e5010f36..e3462674977725a7bda3bf187f22e548d17f4e43 100644 --- a/data/graph/edges/part-000013.parquet +++ b/data/graph/edges/part-000013.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:186a0c1e9121c72a7d58f74c8bacccd8842c821f1a59584f7895cb959c3f31d6 -size 168527 +oid sha256:3d2b8b3e409611f9662ac08b092633a1cb11bf4587009a64ea26e401864ac264 +size 167601 diff --git a/data/graph/nodes/part-000000.parquet b/data/graph/nodes/part-000000.parquet index cafeb0dc07b79226cc4cf73ccdd6a9c73a1a60ce..de0f06225fdbc177f09e4b3c8a0c0fec92960c0a 100644 --- a/data/graph/nodes/part-000000.parquet +++ b/data/graph/nodes/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d9501f3fedba78b0ddc2a5a6a647353806f7b6ce161b52d361f8bcb77d3b9d38 -size 359564 +oid sha256:5c19e2b488467e6e9fcc04b529d36b114d7d2407296867033ca0607df0b26b0c +size 359603 diff --git a/data/graph/nodes/part-000001.parquet b/data/graph/nodes/part-000001.parquet index 5c0fd6924c649fd3c6658dca2ca27e929bf1c65b..47814b243949aa4a7c9e862e4fedf4d840e8d29c 100644 --- a/data/graph/nodes/part-000001.parquet +++ b/data/graph/nodes/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d11b2796c86569b0fbae928a7d2121d8f1e3c577a3ba0c6922006b187460dfb2 -size 360358 +oid sha256:e9396a6f64a70631ce94adb7728e18caf1c2fda9cffae0c52ffafcaf536913f4 +size 360828 diff --git a/data/graph/nodes/part-000002.parquet b/data/graph/nodes/part-000002.parquet index bf26e47865dfc45ab65932cf0b11235e88dd5198..63ba46324c454193ff0829cddd7bda74230a34dd 100644 --- a/data/graph/nodes/part-000002.parquet +++ b/data/graph/nodes/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:dd27b8ce3c419cff070ae196a55e0d7f0db86237e847f9db4897d6d8552e74c0 -size 158740 +oid sha256:5861ae106713a4241035013cb13173347c00e32d220da43e7a0f2213d0e35e0e +size 158860 diff --git a/data/vectors/part-000000.parquet b/data/vectors/part-000000.parquet index b77d04de6e6a2cf06b07b7c36001e00303d70d1a..4fcb4d6221ee5ecd31642a4c5b943a3ba566367e 100644 --- a/data/vectors/part-000000.parquet +++ b/data/vectors/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:67c7bd47e6a211f28110a853e4403d7a0b80e7c194f4d21bf807af2012687c5f -size 6086870 +oid sha256:6c47b38c5ea14b065df28f20242caca067cc548d42c5aa772167d42fac727ea4 +size 6158742 diff --git a/data/vectors/part-000001.parquet b/data/vectors/part-000001.parquet index 8d677804c98c8ed4a6019e022ce97a871e12442d..bc16b64efc022b61f402fd65ba3caaa3d1e4161c 100644 --- a/data/vectors/part-000001.parquet +++ b/data/vectors/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:24d796857b096cfa7fe202f6bc6ee4f2d5d78c754b5388a43de36fadd99a630b -size 5942734 +oid sha256:8efc5e70a34d36b421eefb7c76b98db83ab3a99a4875ab75b07cf09213f386b5 +size 6032660 diff --git a/indexes/bm25_document_chunks.parquet b/indexes/bm25_document_chunks.parquet index 24f8390d10df4a2007a663d7f3ee1ae6d3756d62..596c783980231c417f6ef2761617d33920167f20 100644 --- a/indexes/bm25_document_chunks.parquet +++ b/indexes/bm25_document_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:606d60dfbf5200eb4170e39dcccd78b7d0ba4e8f807524eef86eb36892a9f8ed +oid sha256:bd90a5bd7f2b5c0f736aa36b6a60c93a3250eaf75e11416ab4fc5f8956e7f3a1 size 4801 diff --git a/indexes/corpus_chunks.parquet b/indexes/corpus_chunks.parquet index d0b8dfd3d8a9c6b9e1e4fb890cb29d0cdf5a7db5..ec84bc88e3dec50994ad902e9c2791ac81238177 100644 --- a/indexes/corpus_chunks.parquet +++ b/indexes/corpus_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:245db7bd8ebcd432fbcb9a66d7134419c670692e7a042b4c2df25b144f495913 +oid sha256:bc42677d4e2eeb5906e33aa4f188286cc022a51d10b939361c60f977237a4bad size 8817 diff --git a/indexes/graph_edge_chunks.parquet b/indexes/graph_edge_chunks.parquet index a533d78f423ba47885a477fee874832790b058a5..8f574c47b103ebb58ca7c483d04353fba165e0ea 100644 --- a/indexes/graph_edge_chunks.parquet +++ b/indexes/graph_edge_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0c67d942b6a99a77fcc4533be8933c9174cb7f87180e2bda6580fdc4403bae01 -size 7232 +oid sha256:297a17118ce3380aa237bbf78f9593e402ea948ac9523f76c0d9f051244756af +size 7222 diff --git a/indexes/graph_in_adjacency.parquet b/indexes/graph_in_adjacency.parquet index 231ccfabb89d47ced5e15612f9b1aa0146b7a1cd..d8f0d457c6c50084411c3ebc11e4c5093cdc4336 100644 --- a/indexes/graph_in_adjacency.parquet +++ b/indexes/graph_in_adjacency.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ea15a36a7fa44786b255af9afea55f98fc2818dea3ac30f0c4b0ecfe019a33ee -size 8074 +oid sha256:419e0c69a53788b80489da89fb453f9e488cae93977f5d7d0f859b05e000c1ec +size 8067 diff --git a/indexes/graph_node_chunks.parquet b/indexes/graph_node_chunks.parquet index ec52f2a7d3e376aa4400599ce72d69ec666fc5f1..56fcf0e3c6edcfeae20e0aaffbff180f24d62e64 100644 --- a/indexes/graph_node_chunks.parquet +++ b/indexes/graph_node_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e40128389edf1f9bdb91dcd1dd2f2d5e139b282791709e016e83d06c85a46d8a -size 5199 +oid sha256:3f6401a31822fa6e98aca2593b909267143cf90e95c452262793fd0d655bc065 +size 5202 diff --git a/indexes/graph_out_adjacency.parquet b/indexes/graph_out_adjacency.parquet index 6ab451ecb700b494e790ae980df15530225275bb..94580a2076e0417e8638ddf4ab609e2105644151 100644 --- a/indexes/graph_out_adjacency.parquet +++ b/indexes/graph_out_adjacency.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:aed38cd9698e79c7fc2df2b2e433ee78585d0630baf3e724c5456ce0dca466a9 -size 7580 +oid sha256:5ea9183d1b3318ce166185c0f1643b89f957ba61a7975b5d96bda1f46e991548 +size 7578 diff --git a/indexes/vector_chunks.parquet b/indexes/vector_chunks.parquet index 46375f44c4884e3416ebf22680f79cf18d808dad..dff49794d22e641f4f5f8796cd098a7909140078 100644 --- a/indexes/vector_chunks.parquet +++ b/indexes/vector_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8b0956e1cc5e5adfebae75d53968caa1f8a9b5121a62b494fc58deb6af9c6769 -size 22705 +oid sha256:89c34bb77b0609f29b039fca517bd25f61ddd751f146292f6cca7d8feec6c62d +size 22694 diff --git a/manifest.json b/manifest.json index af56512d97a413490885d614a805e9b831294fa9..68ff8bcd03905e352588ffa0f9458818a301ab21 100644 --- a/manifest.json +++ b/manifest.json @@ -178,7 +178,96 @@ "snapshot_dates": [ "2026-09-04", "2026-09-05" - ] + ], + "heading_language_counts": {}, + "heading_language_majority": null, + "document_language_majority": "he", + "verification": { + "schema_version": "country-laws-normalize-verify/v1", + "slug": "", + "admitted": true, + "n_checks": 7, + "n_failed": 0, + "failed_ids": [], + "checks": [ + { + "id": "nonempty_corpus", + "severity": "fail", + "passed": true, + "message": "normalized corpus has rows", + "evidence": { + "n_out": 7915, + "n_dropped": 0 + } + }, + { + "id": "entry_cid_unique", + "severity": "fail", + "passed": true, + "message": "every row has a unique entry_cid", + "evidence": { + "missing": 0, + "empty": 0, + "duplicate": 0 + } + }, + { + "id": "never_invented_legal_text", + "severity": "fail", + "passed": true, + "message": "normalizer did not invent legal text", + "evidence": { + "never_invented_legal_text": true + } + }, + { + "id": "html_residual", + "severity": "fail", + "passed": true, + "message": "HTML tags stripped from legal bodies", + "evidence": { + "n_bodies": 7915, + "n_with_tags": 0, + "fraction": 0.0, + "samples": [] + } + }, + { + "id": "short_bodies", + "severity": "warn", + "passed": true, + "message": "most legal units have usable body length", + "evidence": { + "n_short": 565, + "n_bodies": 7915, + "fraction": 0.07138344914718889 + } + }, + { + "id": "legal_structure", + "severity": "warn", + "passed": true, + "message": "retrieval units are structured (article, coverage=1.00)", + "evidence": { + "unit": "article", + "structured_rows": 7915, + "coverage": 1.0 + } + }, + { + "id": "heading_language", + "severity": "warn", + "passed": true, + "message": "heading lexicon none vs document language he", + "evidence": { + "document_language": "he", + "heading_language": "", + "heading_counts": {} + } + } + ], + "blocks_graphrag": false + } }, "schema_mapping": { "laws": { @@ -210,8 +299,8 @@ }, "indexes": { "bm25_document_chunks": { - "cid": "bafkreidanvqn7p2sadvuc4hdtxgm26fx2c5e5d4aouso56downujfkpy5u", - "sha256": "606d60dfbf5200eb4170e39dcccd78b7d0ba4e8f807524eef86eb36892a9f8ed", + "cid": "bafkreif5scs327zllqhxg2vdnnvgbsj2gjiov526cfawvnh4l6evnz7tue", + "sha256": "bd90a5bd7f2b5c0f736aa36b6a60c93a3250eaf75e11416ab4fc5f8956e7f3a1", "size_bytes": 4801, "relative_path": "indexes/bm25_document_chunks.parquet" }, @@ -222,15 +311,15 @@ "relative_path": "indexes/bm25_keyword_shards.parquet" }, "corpus_chunks": { - "cid": "bafkreibelw333dv42qzpxs42m3lrgrazyzygslt2aqvuylpslmke6skzcm", - "sha256": "245db7bd8ebcd432fbcb9a66d7134419c670692e7a042b4c2df25b144f495913", + "cid": "bafkreif4ijtx2tro5nmqnyz2utyyqkdmyarkkhiqxe4tmhda7f3sg6slvu", + "sha256": "bc42677d4e2eeb5906e33aa4f188286cc022a51d10b939361c60f977237a4bad", "size_bytes": 8817, "relative_path": "indexes/corpus_chunks.parquet" }, "graph_edge_chunks": { - "cid": "bafkreiamm7mufnvjtj37zrcthpujgperotfx7byybyv5uzma7xceao5oae", - "sha256": "0c67d942b6a99a77fcc4533be8933c9174cb7f87180e2bda6580fdc4403bae01", - "size_bytes": 7232, + "cid": "bafkreibjpilrddhdhafken5366hzle7ealvjjcwjki7xnqgz6bisir2wv4", + "sha256": "297a17118ce3380aa237bbf78f9593e402ea948ac9523f76c0d9f051244756af", + "size_bytes": 7222, "relative_path": "indexes/graph_edge_chunks.parquet" }, "graph_incoming_adjacency": { @@ -238,9 +327,9 @@ "present": false }, "graph_node_chunks": { - "cid": "bafkreiheaeudrhw7d6n5xeo42hos6lk6consqj4rocpac3ud2bwiljdnri", - "sha256": "e40128389edf1f9bdb91dcd1dd2f2d5e139b282791709e016e83d06c85a46d8a", - "size_bytes": 5199, + "cid": "bafkreib7mqa2ggbc7jxjrlfcle5zbethcq6psduvyrjcmj4t7ugwkw6amu", + "sha256": "3f6401a31822fa6e98aca2593b909267143cf90e95c452262793fd0d655bc065", + "size_bytes": 5202, "relative_path": "indexes/graph_node_chunks.parquet" }, "graph_outgoing_adjacency": { @@ -248,9 +337,9 @@ "present": false }, "vector_chunks": { - "cid": "bafkreielbflodtc6llp6xltv2u4wrsvb7cu3keq2mk2jj7cy323k7hdhne", - "sha256": "8b0956e1cc5e5adfebae75d53968caa1f8a9b5121a62b494fc58deb6af9c6769", - "size_bytes": 22705, + "cid": "bafkreiejynf3o6ygbhzjwa47zjixxus7mho5oupriyus63gkpwh65rwgfu", + "sha256": "89c34bb77b0609f29b039fca517bd25f61ddd751f146292f6cca7d8feec6c62d", + "size_bytes": 22694, "relative_path": "indexes/vector_chunks.parquet" } }, @@ -303,36 +392,57 @@ ] }, "incremental": { - "kind": "delta_refresh", + "kind": "full_rebuild", "mode": "auto", - "reason": "source changed; reuse embeddings for unchanged entry_cids", + "reason": "operator forced full rebuild", "source_revision": "86221a671797406ddfd71daf033378292578a86d", - "prior_revision": "5750aaffa89615197f1d200c8fb0375574579c24", + "prior_revision": "86221a671797406ddfd71daf033378292578a86d", "source_fingerprint": "86221a671797406ddfd71daf033378292578a86d|99cf0712661a0cb0043c8be0b593cb16dbbc5553950fcf859c71ab1df838a394|bc246168d4650c6c5630db7e81c7b22d8d8bd86a6f46fc1f3c1eb82bb2cab8e1", - "prior_fingerprint": "5750aaffa89615197f1d200c8fb0375574579c24||", + "prior_fingerprint": "86221a671797406ddfd71daf033378292578a86d|99cf0712661a0cb0043c8be0b593cb16dbbc5553950fcf859c71ab1df838a394|bc246168d4650c6c5630db7e81c7b22d8d8bd86a6f46fc1f3c1eb82bb2cab8e1", "delta": { - "n_added": 0, - "n_removed": 0, - "n_unchanged": 7915, + "n_added": 7169, + "n_removed": 7169, + "n_unchanged": 746, "prior_count": 7915, "current_count": 7915, - "changed_ratio": 0.0, + "changed_ratio": 0.9057485786481364, "equivalent_to_full": false, - "added_cids_sample": [], - "removed_cids_sample": [] + "added_cids_sample": [ + "bafkreia22kgornios6busjb7vewnx4jgnj6ys7aedmkpfg7x4yfhzsteqm", + "bafkreia234ligxeam5ojd26kcpxvo36e3hec7hep6wikf7cl4tg4v5sevy", + "bafkreia24aj5autuuedzsw2t54mwr3mjnglkip5lhl7pd7yzqelcrv7hmi", + "bafkreia24bhv3uwhfvn43xmlq4pzpkmxcwxycq6t6d2nu6xwspf3ianxt4", + "bafkreia26gtaahbqvxtihw4emzsvqgphzazwbx2wpczina2tguverkxcmy", + "bafkreia26w4xasm6miib5cou7mmd4bhhtfteobtplue53jcddntfczpisy", + "bafkreia275epskmmithagfyh6kicrbjett75jj3quowogmrfadnirvphze", + "bafkreia27hfgr5tsulax5nmqfjcnwaisob6rbrg54jyqfu5xmbdlqo6q2q" + ], + "removed_cids_sample": [ + "bafkreia22e73dt5wrewg242hq3tgzsdb22yzloflhrxq3jq4sie34hwsaq", + "bafkreia22rmk3b7hnihkwwvrrxguwszr6b5h7p7ensuyvlhtdwojafvoxm", + "bafkreia23itw26qoa5ooz6va4rxkm5sqjkunsdny7obltnrlarkpqpau2e", + "bafkreia26kl33thaguxvcxkslf5bhoxntfbfyqjmn6v2ov6hmistbt6jsu", + "bafkreia2b6zsejzna5iixqgf2s4ufgexoutj42nmu23aknif4f4vyusmny", + "bafkreia2dqkxxlp52r5kvc3aqpqjq54upu4slewb7uoiqxp4qcioei4mzi", + "bafkreia2duhuyk42lerpbwpeb5isrvqnxd5errpdamljngw5hfsur7w7lq", + "bafkreia2effv74avwtyizd22obcipwop5yk5vomg6ecearzid2m4zniie4" + ] }, - "reuse_embeddings": true, + "reuse_embeddings": false, "skip_build": false, - "equivalent_to_full": false, + "equivalent_to_full": true, "schema_version": "country-laws-ir-graphrag/v1", "vectors": { "n_docs": 7915, - "n_reused": 7915, - "n_encoded": 0, + "n_reused": 0, + "n_encoded": 7915, "n_missing": 0, "model_name": "thenlper/gte-small", + "model_revision": "17e1f347d17fe144873b1201da91788898c639cd", "dimension": 384, - "status": "reused" + "status": "merged", + "device": "cuda", + "device_fallback": false } }, "sparse": { @@ -366,10 +476,10 @@ }, "indexes": { "bm25_document_chunks": { - "cid": "bafkreidanvqn7p2sadvuc4hdtxgm26fx2c5e5d4aouso56downujfkpy5u", + "cid": "bafkreif5scs327zllqhxg2vdnnvgbsj2gjiov526cfawvnh4l6evnz7tue", "relative_path": "indexes/bm25_document_chunks.parquet", "row_count": 2, - "sha256": "606d60dfbf5200eb4170e39dcccd78b7d0ba4e8f807524eef86eb36892a9f8ed", + "sha256": "bd90a5bd7f2b5c0f736aa36b6a60c93a3250eaf75e11416ab4fc5f8956e7f3a1", "size_bytes": 4801 }, "bm25_keyword_shards": { diff --git a/normalization_report.json b/normalization_report.json index 11e4ecc51141cbe86830188c01751ae2563920ca..0b141a08cbc392fc9ef47feccb838e96e94f8ad9 100644 --- a/normalization_report.json +++ b/normalization_report.json @@ -56,5 +56,94 @@ "snapshot_dates": [ "2026-09-04", "2026-09-05" - ] + ], + "heading_language_counts": {}, + "heading_language_majority": null, + "document_language_majority": "he", + "verification": { + "schema_version": "country-laws-normalize-verify/v1", + "slug": "", + "admitted": true, + "n_checks": 7, + "n_failed": 0, + "failed_ids": [], + "checks": [ + { + "id": "nonempty_corpus", + "severity": "fail", + "passed": true, + "message": "normalized corpus has rows", + "evidence": { + "n_out": 7915, + "n_dropped": 0 + } + }, + { + "id": "entry_cid_unique", + "severity": "fail", + "passed": true, + "message": "every row has a unique entry_cid", + "evidence": { + "missing": 0, + "empty": 0, + "duplicate": 0 + } + }, + { + "id": "never_invented_legal_text", + "severity": "fail", + "passed": true, + "message": "normalizer did not invent legal text", + "evidence": { + "never_invented_legal_text": true + } + }, + { + "id": "html_residual", + "severity": "fail", + "passed": true, + "message": "HTML tags stripped from legal bodies", + "evidence": { + "n_bodies": 7915, + "n_with_tags": 0, + "fraction": 0.0, + "samples": [] + } + }, + { + "id": "short_bodies", + "severity": "warn", + "passed": true, + "message": "most legal units have usable body length", + "evidence": { + "n_short": 565, + "n_bodies": 7915, + "fraction": 0.07138344914718889 + } + }, + { + "id": "legal_structure", + "severity": "warn", + "passed": true, + "message": "retrieval units are structured (article, coverage=1.00)", + "evidence": { + "unit": "article", + "structured_rows": 7915, + "coverage": 1.0 + } + }, + { + "id": "heading_language", + "severity": "warn", + "passed": true, + "message": "heading lexicon none vs document language he", + "evidence": { + "document_language": "he", + "heading_language": "", + "heading_counts": {} + } + } + ], + "blocks_graphrag": false + } } diff --git a/normalize.py b/normalize.py index d518f83f1b2fe701b6c1fc5f79335bc6c760a414..b3c348f675dd13ca6f9184c6ffffce5cdfead2d8 100644 --- a/normalize.py +++ b/normalize.py @@ -1,8 +1,9 @@ """Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus. Prefer article/section as the retrieval unit; fall back to law-level when -articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE -GraphRAG. Never invent legal text or identifiers. +articles are missing or empty. Strip leftover HTML, then detect multilingual +title/chapter/article/section headings (Oregon-style) when present. Never +invent legal text or a hierarchy that is not in the source. Public Hub reads only (token=False). No Hugging Face token is read or stored. """ @@ -11,8 +12,6 @@ from __future__ import annotations import json import os -import re -import unicodedata from collections import Counter from pathlib import Path from typing import Any @@ -25,8 +24,8 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION from .auth import configure_hf, public_token from .cidutil import cid_of_json, sha256_file, sha256_hex from .schema import SchemaError, validate_articles, validate_laws +from .structure import normalize_legal_text, split_structured_units -_WS_RE = re.compile(r"\s+", re.UNICODE) COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py" EMPTY_ARTICLE_COLUMNS = ( "law_id", @@ -48,9 +47,7 @@ def _empty_articles() -> pd.DataFrame: def normalize_text(value: Any) -> str: if value is None or (isinstance(value, float) and pd.isna(value)): return "" - text = unicodedata.normalize("NFKC", str(value)) - text = _WS_RE.sub(" ", text).strip() - return text + return normalize_legal_text(value) def _s(value: Any) -> str: @@ -285,6 +282,35 @@ def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, return "" +def _hierarchy_fields( + title: str, body: str, article_number: str, *, language: str = "" +) -> dict[str, Any]: + """Best-effort hierarchy from a single already-split article/section body.""" + units = split_structured_units( + f"{title}\n{body}" if title else body, language=language + ) + if not units: + return { + "hierarchy_kind": "article" if article_number else "law", + "hierarchy_path": "", + "title_number": "", + "chapter_number": "", + "part_number": "", + "section_number": "", + "subsections": [], + } + unit = units[0] + return { + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + } + + def _collector(meta: dict[str, Any], source_dataset: str) -> str: nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for blob in (meta, nested): @@ -489,6 +515,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": instrument_id, "article_id": source_id, + **_hierarchy_fields( + article_title, body, article_number, language=parent["language"] + ), }, ) ) @@ -501,6 +530,49 @@ def build_corpus( report["drop_samples"]["empty_body"].append(instrument_id) continue meta = parent["metadata"] + units = split_structured_units(body, language=parent["language"]) + if units: + report["unit"] = "structured" + for unit in units: + entries.append( + _base_record( + record_type=unit.kind if unit.kind in {"article", "section"} else "article", + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number=unit.article_number or unit.number, + article_title=unit.heading, + body=unit.body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage="structured (headings detected in law body)", + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=f"{instrument_id}-{unit.kind}-{unit.number}", + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": instrument_id, + "article_id": "", + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + }, + ) + ) + continue entries.append( _base_record( record_type="law", @@ -531,6 +603,9 @@ def build_corpus( "law_status": parent["law_status"], "parent_law_id": "", "article_id": "", + **_hierarchy_fields( + parent["instrument_title"], body, "", language=parent["language"] + ), }, ) ) @@ -607,5 +682,23 @@ def build_corpus( "empty_bodies_dropped": report["drops"]["empty_body"], "duplicate_cids_dropped": report["drops"]["duplicate_cid"], } + from .profiles import majority_language, score_heading_languages + + sample_text = "" + if not df.empty and "body" in df.columns: + sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist()) + if "title" in df.columns: + sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text + heading_langs = score_heading_languages(sample_text) + report["heading_language_counts"] = dict(heading_langs) + report["heading_language_majority"] = majority_language(heading_langs) + report["document_language_majority"] = None + if report.get("language_breakdown"): + report["document_language_majority"] = max( + report["language_breakdown"].items(), key=lambda kv: kv[1] + )[0] + from .verify import verify_normalized_corpus + + report["verification"] = verify_normalized_corpus(df, report) df.attrs["normalization_report"] = report return df, report diff --git a/query.py b/query.py index 061c17c4439724d2d93b26ffc09f7fc6cb4ea70b..9cd3a1da6f2ac29b2287609ec1bc797fd55c4774 100644 --- a/query.py +++ b/query.py @@ -176,7 +176,7 @@ def main(argv: list[str] | None = None) -> int: p_vec.add_argument("query") p_vec.add_argument("--top-k", type=int, default=10) p_vec.add_argument("--candidate-centroids", type=int, default=4) - p_vec.add_argument("--device", default="cpu") + p_vec.add_argument("--device", default="cuda") p_g = sub.add_parser("graph") g_sub = p_g.add_subparsers(dest="graph_cmd", required=True) diff --git a/reports/normalization.json b/reports/normalization.json index 11e4ecc51141cbe86830188c01751ae2563920ca..0b141a08cbc392fc9ef47feccb838e96e94f8ad9 100644 --- a/reports/normalization.json +++ b/reports/normalization.json @@ -56,5 +56,94 @@ "snapshot_dates": [ "2026-09-04", "2026-09-05" - ] + ], + "heading_language_counts": {}, + "heading_language_majority": null, + "document_language_majority": "he", + "verification": { + "schema_version": "country-laws-normalize-verify/v1", + "slug": "", + "admitted": true, + "n_checks": 7, + "n_failed": 0, + "failed_ids": [], + "checks": [ + { + "id": "nonempty_corpus", + "severity": "fail", + "passed": true, + "message": "normalized corpus has rows", + "evidence": { + "n_out": 7915, + "n_dropped": 0 + } + }, + { + "id": "entry_cid_unique", + "severity": "fail", + "passed": true, + "message": "every row has a unique entry_cid", + "evidence": { + "missing": 0, + "empty": 0, + "duplicate": 0 + } + }, + { + "id": "never_invented_legal_text", + "severity": "fail", + "passed": true, + "message": "normalizer did not invent legal text", + "evidence": { + "never_invented_legal_text": true + } + }, + { + "id": "html_residual", + "severity": "fail", + "passed": true, + "message": "HTML tags stripped from legal bodies", + "evidence": { + "n_bodies": 7915, + "n_with_tags": 0, + "fraction": 0.0, + "samples": [] + } + }, + { + "id": "short_bodies", + "severity": "warn", + "passed": true, + "message": "most legal units have usable body length", + "evidence": { + "n_short": 565, + "n_bodies": 7915, + "fraction": 0.07138344914718889 + } + }, + { + "id": "legal_structure", + "severity": "warn", + "passed": true, + "message": "retrieval units are structured (article, coverage=1.00)", + "evidence": { + "unit": "article", + "structured_rows": 7915, + "coverage": 1.0 + } + }, + { + "id": "heading_language", + "severity": "warn", + "passed": true, + "message": "heading lexicon none vs document language he", + "evidence": { + "document_language": "he", + "heading_language": "", + "heading_counts": {} + } + } + ], + "blocks_graphrag": false + } }