Datasets:
Initial pakistan country-laws-ir-graphrag/v1 release
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -59
- README.md +132 -0
- build.py +171 -0
- country_laws_ir/__init__.py +19 -0
- country_laws_ir/__main__.py +87 -0
- country_laws_ir/auth.py +16 -0
- country_laws_ir/bm25.py +227 -0
- country_laws_ir/build.py +171 -0
- country_laws_ir/catalog.py +135 -0
- country_laws_ir/cidutil.py +81 -0
- country_laws_ir/graph.py +336 -0
- country_laws_ir/normalize.py +514 -0
- country_laws_ir/package.py +530 -0
- country_laws_ir/parquet_io.py +83 -0
- country_laws_ir/query.py +188 -0
- country_laws_ir/schema.py +128 -0
- country_laws_ir/tokenize.py +21 -0
- country_laws_ir/upload.py +24 -0
- country_laws_ir/vectors.py +327 -0
- data/bm25/documents/part-000000.parquet +3 -0
- data/bm25/documents/part-000001.parquet +3 -0
- data/bm25/postings/part-000000.parquet +3 -0
- data/bm25/postings/part-000001.parquet +3 -0
- data/bm25/postings/part-000002.parquet +3 -0
- data/bm25/postings/part-000003.parquet +3 -0
- data/bm25/postings/part-000004.parquet +3 -0
- data/bm25/postings/part-000005.parquet +3 -0
- data/bm25/postings/part-000006.parquet +3 -0
- data/corpus/part-000000.parquet +3 -0
- data/corpus/part-000001.parquet +3 -0
- data/graph/adjacency/incoming/part-000000.parquet +3 -0
- data/graph/adjacency/outgoing/part-000000.parquet +3 -0
- data/graph/adjacency/outgoing/part-000001.parquet +3 -0
- data/graph/edges/part-000000.parquet +3 -0
- data/graph/edges/part-000001.parquet +3 -0
- data/graph/edges/part-000002.parquet +3 -0
- data/graph/edges/part-000003.parquet +3 -0
- data/graph/edges/part-000004.parquet +3 -0
- data/graph/edges/part-000005.parquet +3 -0
- data/graph/edges/part-000006.parquet +3 -0
- data/graph/edges/part-000007.parquet +3 -0
- data/graph/edges/part-000008.parquet +3 -0
- data/graph/edges/part-000009.parquet +3 -0
- data/graph/nodes/part-000000.parquet +3 -0
- data/graph/nodes/part-000001.parquet +3 -0
- data/vectors/part-000000.parquet +3 -0
- data/vectors/part-000001.parquet +3 -0
- indexes/bm25_document_chunks.parquet +3 -0
- indexes/bm25_keyword_shards.parquet +3 -0
- indexes/corpus_chunks.parquet +3 -0
.gitattributes
CHANGED
|
@@ -1,60 +1,2 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.
|
| 23 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
-
# Audio files - uncompressed
|
| 40 |
-
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
-
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
-
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
-
# Audio files - compressed
|
| 44 |
-
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
-
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
-
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
-
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
-
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
-
# Image files - uncompressed
|
| 50 |
-
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
-
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
-
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
-
# Image files - compressed
|
| 55 |
-
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
-
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
-
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
-
# Video files - compressed
|
| 59 |
-
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
-
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
task_categories:
|
| 4 |
+
- text-retrieval
|
| 5 |
+
tags:
|
| 6 |
+
- legal
|
| 7 |
+
- law
|
| 8 |
+
- graphrag
|
| 9 |
+
- bm25
|
| 10 |
+
- research
|
| 11 |
+
- not-legal-advice
|
| 12 |
+
- pakistan
|
| 13 |
+
pretty_name: Pakistan laws IR (CID-keyed GraphRAG)
|
| 14 |
+
configs:
|
| 15 |
+
- config_name: corpus
|
| 16 |
+
data_files:
|
| 17 |
+
- split: train
|
| 18 |
+
path: data/corpus/*.parquet
|
| 19 |
+
- config_name: bm25_documents
|
| 20 |
+
data_files:
|
| 21 |
+
- split: train
|
| 22 |
+
path: data/bm25/documents/*.parquet
|
| 23 |
+
- config_name: bm25_postings
|
| 24 |
+
data_files:
|
| 25 |
+
- split: train
|
| 26 |
+
path: data/bm25/postings/*.parquet
|
| 27 |
+
- config_name: bm25_keyword_index
|
| 28 |
+
data_files:
|
| 29 |
+
- split: train
|
| 30 |
+
path: indexes/bm25_keyword_shards.parquet
|
| 31 |
+
- config_name: vectors
|
| 32 |
+
data_files:
|
| 33 |
+
- split: train
|
| 34 |
+
path: data/vectors/*.parquet
|
| 35 |
+
- config_name: vector_meta_index
|
| 36 |
+
data_files:
|
| 37 |
+
- split: train
|
| 38 |
+
path: indexes/vector_chunks.parquet
|
| 39 |
+
- config_name: graph_nodes
|
| 40 |
+
data_files:
|
| 41 |
+
- split: train
|
| 42 |
+
path: data/graph/nodes/*.parquet
|
| 43 |
+
- config_name: graph_edges
|
| 44 |
+
data_files:
|
| 45 |
+
- split: train
|
| 46 |
+
path: data/graph/edges/*.parquet
|
| 47 |
+
- config_name: graph_outgoing_adjacency
|
| 48 |
+
data_files:
|
| 49 |
+
- split: train
|
| 50 |
+
path: data/graph/adjacency/outgoing/*.parquet
|
| 51 |
+
- config_name: graph_incoming_adjacency
|
| 52 |
+
data_files:
|
| 53 |
+
- split: train
|
| 54 |
+
path: data/graph/adjacency/incoming/*.parquet
|
| 55 |
+
---
|
| 56 |
+
|
| 57 |
+
# Pakistan legislation IR (CID-keyed sparse GraphRAG)
|
| 58 |
+
|
| 59 |
+
Research retrieval release of `endomorphosis/ipfs_pakistan_laws` (revision `1455aac2978239f7047f06cf5755b217b315b158`) packaged as
|
| 60 |
+
`country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3` / publicus-ir).
|
| 61 |
+
|
| 62 |
+
**Not legal advice.** This is a research snapshot. The official gazette /
|
| 63 |
+
authentic source of Pakistan prevails over this corpus. Retrieved documents
|
| 64 |
+
and graph edges are retrieval evidence only. No legal text was invented.
|
| 65 |
+
|
| 66 |
+
Primary key: `entry_cid` (CIDv1 raw sha2-256 of a canonical identity record).
|
| 67 |
+
Integer `document_index` values are compact shard pointers, not identities.
|
| 68 |
+
|
| 69 |
+
Target Hub id (packaging metadata only): `justicedao/ipfs_pakistan_laws_ir`.
|
| 70 |
+
|
| 71 |
+
## Counts
|
| 72 |
+
|
| 73 |
+
| Field | Value |
|
| 74 |
+
| --- | --- |
|
| 75 |
+
| Laws (corpus units) | 0 |
|
| 76 |
+
| Articles (corpus units) | 4189 |
|
| 77 |
+
| Canonical docs | 4189 |
|
| 78 |
+
| BM25 terms | 28374 |
|
| 79 |
+
| BM25 postings | 897615 |
|
| 80 |
+
| Graph nodes | 5171 |
|
| 81 |
+
| Graph edges | 40442 |
|
| 82 |
+
| Vectors | 4189 × 384-d `thenlper/gte-small` (embedded) |
|
| 83 |
+
|
| 84 |
+
## Canonical fields
|
| 85 |
+
|
| 86 |
+
`entry_cid`, `law_cid`, `record_type`, `jurisdiction`, `language`,
|
| 87 |
+
`instrument_id`, `instrument_title`, `article_number`, `article_title`,
|
| 88 |
+
`title`, `body`, `source_url`, `snapshot_date`, `coverage`, `license`,
|
| 89 |
+
`collector`, `source_dataset`, `source_revision`.
|
| 90 |
+
|
| 91 |
+
Unit policy: prefer article/section rows; fall back to law-level when
|
| 92 |
+
`articles.parquet` is empty.
|
| 93 |
+
|
| 94 |
+
## Index layout
|
| 95 |
+
|
| 96 |
+
Zstandard parquet shards with at most 4,096 rows.
|
| 97 |
+
|
| 98 |
+
- `indexes/bm25_keyword_shards.parquet` — lexical term ranges → BM25 posting shards
|
| 99 |
+
- `indexes/vector_chunks.parquet` — semantic routing centroids (rows sorted by cosine to shard centroid)
|
| 100 |
+
- `indexes/corpus_chunks.parquet` — document ranges → corpus shards
|
| 101 |
+
- `data/graph/nodes` / `data/graph/edges` — property graph
|
| 102 |
+
- `data/graph/adjacency/{incoming,outgoing}` — score-ordered neighbor pages
|
| 103 |
+
|
| 104 |
+
BM25: Okapi k1=1.2, b=0.75, title_weight=5, body_weight=1 (FTS5 unicode61-style tokenizer).
|
| 105 |
+
|
| 106 |
+
Graph: one node per `entry_cid` plus facet nodes (`_facet_cid(kind, value)` for
|
| 107 |
+
jurisdiction, language, instrument, source, status). Neighbor edges
|
| 108 |
+
`BM25_NEIGHBOR_OF` (k=8) carry score and matched terms. Structural edges:
|
| 109 |
+
`ARTICLE_OF` (article → parent law) when articles exist, plus `IDENTIFIED_BY_ELI`
|
| 110 |
+
/ `IDENTIFIED_BY` only when those identifiers are present in the source.
|
| 111 |
+
|
| 112 |
+
## Query
|
| 113 |
+
|
| 114 |
+
```
|
| 115 |
+
python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 10
|
| 116 |
+
python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 10
|
| 117 |
+
python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
## Publish later (operator)
|
| 121 |
+
|
| 122 |
+
```
|
| 123 |
+
export HF_TOKEN=... # never commit
|
| 124 |
+
hf upload-large-folder justicedao/ipfs_pakistan_laws_ir . \
|
| 125 |
+
--repo-type dataset --no-private --num-workers 8 \
|
| 126 |
+
--exclude "**/__pycache__/**" --exclude "**/*.pyc"
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
## Provenance
|
| 130 |
+
|
| 131 |
+
Packaged by country-laws-ir. Upstream collector and official license remain those
|
| 132 |
+
of `endomorphosis/ipfs_pakistan_laws`. CIDs identify local content; they do not prove public IPFS pinning.
|
build.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end build: normalize → BM25 → graph → vectors → package (no upload by default)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import traceback
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from .bm25 import bm25_neighbors, build_index
|
| 12 |
+
from .catalog import get_country, indexable_countries, target_repo
|
| 13 |
+
from .graph import build_graph
|
| 14 |
+
from .normalize import build_corpus, load_source
|
| 15 |
+
from .package import package_release
|
| 16 |
+
from .auth import configure_hf
|
| 17 |
+
from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors
|
| 18 |
+
|
| 19 |
+
ROOT = Path("/workspace/country-laws-ir")
|
| 20 |
+
CACHE = ROOT / "cache"
|
| 21 |
+
RELEASES = ROOT / "releases"
|
| 22 |
+
REPORTS = ROOT / "reports"
|
| 23 |
+
PROGRESS = ROOT / "progress.jsonl"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _log(msg: str) -> None:
|
| 27 |
+
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 28 |
+
print(f"[{ts}] {msg}", flush=True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def record_progress(event: dict[str, Any]) -> None:
|
| 32 |
+
event = dict(event)
|
| 33 |
+
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 34 |
+
with PROGRESS.open("a", encoding="utf-8") as f:
|
| 35 |
+
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_country(
|
| 39 |
+
source: str,
|
| 40 |
+
out: Path | None = None,
|
| 41 |
+
upload: bool = False,
|
| 42 |
+
device: str = "cpu",
|
| 43 |
+
neighbor_k: int = 8,
|
| 44 |
+
skip_vectors: bool = False,
|
| 45 |
+
) -> dict[str, Any]:
|
| 46 |
+
country = get_country(source)
|
| 47 |
+
if not country.get("indexable", True):
|
| 48 |
+
raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}")
|
| 49 |
+
repo = country["repo"]
|
| 50 |
+
out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir"
|
| 51 |
+
_log(f"build start {repo} -> {out} (upload={upload})")
|
| 52 |
+
configure_hf()
|
| 53 |
+
CACHE.mkdir(parents=True, exist_ok=True)
|
| 54 |
+
REPORTS.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
laws, articles, source_meta = load_source(repo, CACHE)
|
| 56 |
+
_log(
|
| 57 |
+
f"source loaded laws={source_meta['n_laws_source']} "
|
| 58 |
+
f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
|
| 59 |
+
)
|
| 60 |
+
corpus, norm_report = build_corpus(laws, articles, source_meta)
|
| 61 |
+
report_path = REPORTS / f"{country['slug']}_normalization.json"
|
| 62 |
+
report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 63 |
+
(REPORTS / "normalization.json").write_text(
|
| 64 |
+
json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 65 |
+
)
|
| 66 |
+
_log(
|
| 67 |
+
f"normalized docs={len(corpus)} unit={norm_report['unit']} "
|
| 68 |
+
f"dropped={norm_report['n_dropped_total']} report={report_path}"
|
| 69 |
+
)
|
| 70 |
+
if corpus.empty:
|
| 71 |
+
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
| 72 |
+
|
| 73 |
+
bm25 = build_index(corpus)
|
| 74 |
+
_log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
|
| 75 |
+
_log(f"bm25 neighbors start n={len(corpus)} k={neighbor_k}")
|
| 76 |
+
neighbors = bm25_neighbors(bm25, k=neighbor_k)
|
| 77 |
+
_log("bm25 neighbors done")
|
| 78 |
+
graph = build_graph(corpus, neighbors)
|
| 79 |
+
_log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
|
| 80 |
+
|
| 81 |
+
vector_blocker = None
|
| 82 |
+
if skip_vectors:
|
| 83 |
+
vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
|
| 84 |
+
vector_blocker = "skip_vectors"
|
| 85 |
+
elif embeddings_available():
|
| 86 |
+
try:
|
| 87 |
+
ckpt = CACHE / "embeddings" / f"{country['slug']}.npy"
|
| 88 |
+
_log(f"vectors encode start n={len(corpus)} checkpoint={ckpt}")
|
| 89 |
+
embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt))
|
| 90 |
+
vectors = layout_vectors(corpus, embeddings)
|
| 91 |
+
_log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
|
| 92 |
+
except Exception as exc:
|
| 93 |
+
vector_blocker = f"embedding_failed: {exc}"
|
| 94 |
+
_log(f"vector embedding failed; writing stub ({exc})")
|
| 95 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 96 |
+
else:
|
| 97 |
+
vector_blocker = "sentence-transformers/torch unavailable"
|
| 98 |
+
_log(f"vectors stub: {vector_blocker}")
|
| 99 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 100 |
+
|
| 101 |
+
code_root = Path(__file__).resolve().parent.parent
|
| 102 |
+
manifest = package_release(
|
| 103 |
+
out,
|
| 104 |
+
corpus,
|
| 105 |
+
bm25,
|
| 106 |
+
graph,
|
| 107 |
+
vectors,
|
| 108 |
+
source_meta,
|
| 109 |
+
country,
|
| 110 |
+
code_root,
|
| 111 |
+
normalization_report=norm_report,
|
| 112 |
+
)
|
| 113 |
+
_log(f"packaged {out}")
|
| 114 |
+
result = {
|
| 115 |
+
"country": country["slug"],
|
| 116 |
+
"source": repo,
|
| 117 |
+
"source_revision": source_meta["source_revision"],
|
| 118 |
+
"out": str(out),
|
| 119 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 120 |
+
"counts": manifest["counts"],
|
| 121 |
+
"normalization": norm_report,
|
| 122 |
+
"vector_blocker": vector_blocker,
|
| 123 |
+
"schema_version": manifest["schema_version"],
|
| 124 |
+
}
|
| 125 |
+
if upload:
|
| 126 |
+
from .upload import upload_release
|
| 127 |
+
|
| 128 |
+
hub = upload_release(out, target_repo(country["slug"]))
|
| 129 |
+
result["hub"] = hub
|
| 130 |
+
_log(f"uploaded {hub['url']} rev={hub['revision']}")
|
| 131 |
+
record_progress({"event": "uploaded", **result})
|
| 132 |
+
else:
|
| 133 |
+
record_progress({"event": "built_local", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 134 |
+
return result
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def batch(
|
| 138 |
+
slugs: list[str] | None = None,
|
| 139 |
+
upload: bool = False,
|
| 140 |
+
skip_done: bool = True,
|
| 141 |
+
) -> list[dict[str, Any]]:
|
| 142 |
+
done = set()
|
| 143 |
+
if skip_done and PROGRESS.exists():
|
| 144 |
+
for line in PROGRESS.read_text(encoding="utf-8").splitlines():
|
| 145 |
+
if not line.strip():
|
| 146 |
+
continue
|
| 147 |
+
rec = json.loads(line)
|
| 148 |
+
if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
|
| 149 |
+
done.add(rec["country"])
|
| 150 |
+
targets = slugs or [c["slug"] for c in indexable_countries()]
|
| 151 |
+
if "malta" in targets:
|
| 152 |
+
targets = ["malta"] + [s for s in targets if s != "malta"]
|
| 153 |
+
results = []
|
| 154 |
+
for slug in targets:
|
| 155 |
+
if skip_done and slug in done:
|
| 156 |
+
_log(f"skip already done {slug}")
|
| 157 |
+
continue
|
| 158 |
+
try:
|
| 159 |
+
results.append(build_country(slug, upload=upload))
|
| 160 |
+
except Exception as exc:
|
| 161 |
+
_log(f"FAILED {slug}: {exc}")
|
| 162 |
+
record_progress(
|
| 163 |
+
{
|
| 164 |
+
"event": "failed",
|
| 165 |
+
"country": slug,
|
| 166 |
+
"error": str(exc),
|
| 167 |
+
"traceback": traceback.format_exc(),
|
| 168 |
+
}
|
| 169 |
+
)
|
| 170 |
+
continue
|
| 171 |
+
return results
|
country_laws_ir/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.3.0"
|
| 4 |
+
# Layout matches SkillCenter HF release / publicus-ir family; schema string is domain-specific.
|
| 5 |
+
SCHEMA_VERSION = "country-laws-ir-graphrag/v1"
|
| 6 |
+
LAYOUT_FAMILY = "skillcenter-huggingface-release/v3"
|
| 7 |
+
ENTRY_IDENTITY_SCHEMA = "country-laws-entry/v1"
|
| 8 |
+
LAW_IDENTITY_SCHEMA = "country-laws-law/v1"
|
| 9 |
+
FACET_IDENTITY_SCHEMA = "country-laws-facet/v1"
|
| 10 |
+
EDGE_IDENTITY_SCHEMA = "country-laws-edge/v1"
|
| 11 |
+
MAX_ROWS_PER_FILE = 4096
|
| 12 |
+
TARGET_ORG = "justicedao"
|
| 13 |
+
|
| 14 |
+
# CID payload: UTF-8 bytes of json.dumps(obj, sort_keys=True, ensure_ascii=False,
|
| 15 |
+
# separators=(",", ":")) hashed as CIDv1 codec=raw (0x55) hash=sha2-256 (0x12)
|
| 16 |
+
# multibase base32 (`bafkrei...`). Same payload -> same CID.
|
| 17 |
+
CID_CODEC = "raw"
|
| 18 |
+
CID_HASH = "sha2-256"
|
| 19 |
+
CID_MULTIBASE = "base32"
|
country_laws_ir/__main__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""python -m country_laws_ir {build,query,batch,catalog}"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main(argv: list[str] | None = None) -> int:
|
| 12 |
+
ap = argparse.ArgumentParser(prog="country_laws_ir")
|
| 13 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 14 |
+
|
| 15 |
+
p_build = sub.add_parser("build")
|
| 16 |
+
p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
|
| 17 |
+
help="Hub dataset id (endomorphosis/ipfs_<slug>_laws) or country slug")
|
| 18 |
+
p_build.add_argument("--out", default=None)
|
| 19 |
+
p_build.add_argument("--device", default="cpu")
|
| 20 |
+
p_build.add_argument("--neighbor-k", type=int, default=8)
|
| 21 |
+
p_build.add_argument("--skip-vectors", action="store_true")
|
| 22 |
+
p_build.add_argument("--upload", action="store_true")
|
| 23 |
+
|
| 24 |
+
p_batch = sub.add_parser("batch")
|
| 25 |
+
p_batch.add_argument("--slugs", nargs="*", default=None)
|
| 26 |
+
p_batch.add_argument("--upload", action="store_true")
|
| 27 |
+
p_batch.add_argument("--no-skip-done", action="store_true")
|
| 28 |
+
|
| 29 |
+
p_q = sub.add_parser("query")
|
| 30 |
+
p_q.add_argument("--local-dir", required=True)
|
| 31 |
+
p_q.add_argument("rest", nargs=argparse.REMAINDER)
|
| 32 |
+
|
| 33 |
+
p_norm = sub.add_parser("normalize")
|
| 34 |
+
p_norm.add_argument("--source-repo", "--source", dest="source", default="malta")
|
| 35 |
+
p_norm.add_argument("--out", default=None, help="Optional JSON report path")
|
| 36 |
+
|
| 37 |
+
sub.add_parser("catalog")
|
| 38 |
+
|
| 39 |
+
args = ap.parse_args(argv)
|
| 40 |
+
if args.cmd == "build":
|
| 41 |
+
from .build import build_country
|
| 42 |
+
|
| 43 |
+
result = build_country(
|
| 44 |
+
args.source,
|
| 45 |
+
out=Path(args.out) if args.out else None,
|
| 46 |
+
upload=args.upload,
|
| 47 |
+
device=args.device,
|
| 48 |
+
neighbor_k=args.neighbor_k,
|
| 49 |
+
skip_vectors=args.skip_vectors,
|
| 50 |
+
)
|
| 51 |
+
print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str))
|
| 52 |
+
print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str))
|
| 53 |
+
return 0
|
| 54 |
+
if args.cmd == "batch":
|
| 55 |
+
from .build import batch
|
| 56 |
+
|
| 57 |
+
results = batch(slugs=args.slugs, upload=args.upload, skip_done=not args.no_skip_done)
|
| 58 |
+
print(json.dumps([{"country": r["country"], "out": r["out"]} for r in results], indent=2))
|
| 59 |
+
return 0
|
| 60 |
+
if args.cmd == "query":
|
| 61 |
+
from .query import main as qmain
|
| 62 |
+
|
| 63 |
+
argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"]
|
| 64 |
+
return qmain(argv2)
|
| 65 |
+
if args.cmd == "normalize":
|
| 66 |
+
from .build import CACHE, REPORTS, ROOT
|
| 67 |
+
from .catalog import get_country
|
| 68 |
+
from .normalize import build_corpus, load_source
|
| 69 |
+
|
| 70 |
+
country = get_country(args.source)
|
| 71 |
+
laws, articles, source_meta = load_source(country["repo"], CACHE)
|
| 72 |
+
corpus, report = build_corpus(laws, articles, source_meta)
|
| 73 |
+
out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
|
| 74 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 76 |
+
print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2))
|
| 77 |
+
return 0
|
| 78 |
+
if args.cmd == "catalog":
|
| 79 |
+
from .catalog import COUNTRIES, indexable_countries
|
| 80 |
+
|
| 81 |
+
print(json.dumps({"n": len(COUNTRIES), "indexable": len(indexable_countries()), "countries": COUNTRIES}, indent=2))
|
| 82 |
+
return 0
|
| 83 |
+
return 1
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
raise SystemExit(main())
|
country_laws_ir/auth.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public Hugging Face reads only. This pipeline never loads, stores, or uses a token."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def configure_hf() -> None:
|
| 9 |
+
"""Force anonymous public Hub access. Tokens are ignored, never printed, never stored."""
|
| 10 |
+
os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
|
| 11 |
+
# Do not read HF_TOKEN / HUGGING_FACE_HUB_TOKEN. Public datasets need no auth.
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def public_token() -> bool:
|
| 15 |
+
"""huggingface_hub `token=False` means anonymous (do not pick up env tokens)."""
|
| 16 |
+
return False
|
country_laws_ir/bm25.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Okapi BM25 (k1=1.2, b=0.75, title_weight=5, body_weight=1) + posting shards."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from typing import Any, Iterable
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 13 |
+
from .tokenize import tokenize
|
| 14 |
+
|
| 15 |
+
K1 = 1.2
|
| 16 |
+
B = 0.75
|
| 17 |
+
TITLE_WEIGHT = 5.0
|
| 18 |
+
BODY_WEIGHT = 1.0
|
| 19 |
+
POSTING_ROWS_PER_RECORD = 4096
|
| 20 |
+
TERMS_PER_SHARD = 4096
|
| 21 |
+
MAX_QUERY_TERMS = 64
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _idf(n_docs: int, df: int) -> float:
|
| 25 |
+
# rank_bm25 Okapi: ln((N - df + 0.5) / (df + 0.5) + 1)
|
| 26 |
+
return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def build_index(corpus: pd.DataFrame) -> dict[str, Any]:
|
| 30 |
+
n = len(corpus)
|
| 31 |
+
titles = corpus["title"].fillna("").astype(str).tolist()
|
| 32 |
+
bodies = corpus["body"].fillna("").astype(str).tolist()
|
| 33 |
+
title_toks = [tokenize(t) for t in titles]
|
| 34 |
+
body_toks = [tokenize(t) for t in bodies]
|
| 35 |
+
|
| 36 |
+
title_len = np.array([len(t) for t in title_toks], dtype=np.int32)
|
| 37 |
+
body_len = np.array([len(t) for t in body_toks], dtype=np.int32)
|
| 38 |
+
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
|
| 39 |
+
avgdl = float(doc_len.mean()) if n else 0.0
|
| 40 |
+
|
| 41 |
+
# term -> {doc: [title_tf, body_tf]}
|
| 42 |
+
postings: dict[str, dict[int, list[int]]] = defaultdict(dict)
|
| 43 |
+
for i, (tt, bt) in enumerate(zip(title_toks, body_toks)):
|
| 44 |
+
tf_t: dict[str, int] = defaultdict(int)
|
| 45 |
+
tf_b: dict[str, int] = defaultdict(int)
|
| 46 |
+
for tok in tt:
|
| 47 |
+
tf_t[tok] += 1
|
| 48 |
+
for tok in bt:
|
| 49 |
+
tf_b[tok] += 1
|
| 50 |
+
for tok in set(tf_t) | set(tf_b):
|
| 51 |
+
postings[tok][i] = [int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0))]
|
| 52 |
+
|
| 53 |
+
terms = sorted(postings)
|
| 54 |
+
idf = {t: _idf(n, len(postings[t])) for t in terms}
|
| 55 |
+
|
| 56 |
+
doc_rows = []
|
| 57 |
+
for i, row in corpus.iterrows():
|
| 58 |
+
idx = int(row["document_index"])
|
| 59 |
+
doc_rows.append(
|
| 60 |
+
{
|
| 61 |
+
"entry_cid": row["entry_cid"],
|
| 62 |
+
"document_index": idx,
|
| 63 |
+
"law_cid": row.get("law_cid", ""),
|
| 64 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 65 |
+
"law_id": row.get("law_id", row.get("instrument_id", "")),
|
| 66 |
+
"source_id": row["source_id"],
|
| 67 |
+
"title": row["title"],
|
| 68 |
+
"instrument_title": row.get("instrument_title", ""),
|
| 69 |
+
"article_number": row.get("article_number", ""),
|
| 70 |
+
"article_title": row.get("article_title", ""),
|
| 71 |
+
"record_type": row["record_type"],
|
| 72 |
+
"language": row.get("language", ""),
|
| 73 |
+
"jurisdiction": row.get("jurisdiction", ""),
|
| 74 |
+
"title_length": int(title_len[idx]),
|
| 75 |
+
"body_length": int(body_len[idx]),
|
| 76 |
+
"document_length": int(round(doc_len[idx])),
|
| 77 |
+
"schema_version": SCHEMA_VERSION,
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
documents = pd.DataFrame(doc_rows).sort_values("document_index").reset_index(drop=True)
|
| 81 |
+
|
| 82 |
+
posting_rows = []
|
| 83 |
+
for term in terms:
|
| 84 |
+
items = sorted(postings[term].items())
|
| 85 |
+
chunks = [
|
| 86 |
+
items[i : i + POSTING_ROWS_PER_RECORD]
|
| 87 |
+
for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD)
|
| 88 |
+
]
|
| 89 |
+
n_chunks = len(chunks)
|
| 90 |
+
dfreq = len(items)
|
| 91 |
+
cfreq = sum(v[0] + v[1] for _, v in items)
|
| 92 |
+
for cidx, chunk in enumerate(chunks):
|
| 93 |
+
posting_rows.append(
|
| 94 |
+
{
|
| 95 |
+
"term": term,
|
| 96 |
+
"document_indices": [d for d, _ in chunk],
|
| 97 |
+
"title_frequencies": [v[0] for _, v in chunk],
|
| 98 |
+
"body_frequencies": [v[1] for _, v in chunk],
|
| 99 |
+
"tfs": [TITLE_WEIGHT * v[0] + BODY_WEIGHT * v[1] for _, v in chunk],
|
| 100 |
+
"lengths": [int(round(doc_len[d])) for d, _ in chunk],
|
| 101 |
+
"document_lengths": [int(round(doc_len[d])) for d, _ in chunk],
|
| 102 |
+
"document_frequency": int(dfreq),
|
| 103 |
+
"corpus_frequency": int(cfreq),
|
| 104 |
+
"idf": float(idf[term]),
|
| 105 |
+
"posting_chunk_index": int(cidx),
|
| 106 |
+
"posting_chunk_count": int(n_chunks),
|
| 107 |
+
"schema_version": SCHEMA_VERSION,
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
postings_df = pd.DataFrame(posting_rows)
|
| 111 |
+
|
| 112 |
+
stats = {
|
| 113 |
+
"k1": K1,
|
| 114 |
+
"b": B,
|
| 115 |
+
"title_weight": TITLE_WEIGHT,
|
| 116 |
+
"body_weight": BODY_WEIGHT,
|
| 117 |
+
"average_document_length": avgdl,
|
| 118 |
+
"tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1",
|
| 119 |
+
"max_query_terms": MAX_QUERY_TERMS,
|
| 120 |
+
"posting_rows_per_record": POSTING_ROWS_PER_RECORD,
|
| 121 |
+
"terms_per_shard": TERMS_PER_SHARD,
|
| 122 |
+
"n_docs": n,
|
| 123 |
+
"n_terms": len(terms),
|
| 124 |
+
"n_posting_rows": int(len(postings_df)),
|
| 125 |
+
"n_postings": int(sum(len(postings[t]) for t in terms)),
|
| 126 |
+
}
|
| 127 |
+
return {
|
| 128 |
+
"documents": documents,
|
| 129 |
+
"postings": postings_df,
|
| 130 |
+
"postings_map": postings,
|
| 131 |
+
"idf": idf,
|
| 132 |
+
"doc_len": doc_len,
|
| 133 |
+
"avgdl": avgdl,
|
| 134 |
+
"title_toks": title_toks,
|
| 135 |
+
"body_toks": body_toks,
|
| 136 |
+
"stats": stats,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _tf_score(tf: float, dl: float, avgdl: float) -> float:
|
| 141 |
+
denom = tf + K1 * (1.0 - B + B * (dl / avgdl if avgdl else 0.0))
|
| 142 |
+
if denom == 0:
|
| 143 |
+
return 0.0
|
| 144 |
+
return (tf * (K1 + 1.0)) / denom
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def score_query(
|
| 148 |
+
query: str,
|
| 149 |
+
index: dict[str, Any],
|
| 150 |
+
top_k: int = 10,
|
| 151 |
+
) -> list[tuple[int, float]]:
|
| 152 |
+
q_terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 153 |
+
if not q_terms:
|
| 154 |
+
return []
|
| 155 |
+
postings = index["postings_map"]
|
| 156 |
+
idf = index["idf"]
|
| 157 |
+
doc_len = index["doc_len"]
|
| 158 |
+
avgdl = index["avgdl"] or 1.0
|
| 159 |
+
scores: dict[int, float] = defaultdict(float)
|
| 160 |
+
for term in q_terms:
|
| 161 |
+
plist = postings.get(term)
|
| 162 |
+
if not plist:
|
| 163 |
+
continue
|
| 164 |
+
w = idf.get(term, 0.0)
|
| 165 |
+
for doc, (ttf, btf) in plist.items():
|
| 166 |
+
tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf
|
| 167 |
+
scores[doc] += w * _tf_score(tf, float(doc_len[doc]), avgdl)
|
| 168 |
+
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
|
| 169 |
+
return ranked[:top_k]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def bm25_neighbors(index: dict[str, Any], k: int = 8) -> list[list[tuple[int, float, list[str]]]]:
|
| 173 |
+
"""Top-k BM25 neighbors from title tokens (body prefix only if title is empty).
|
| 174 |
+
|
| 175 |
+
Each neighbor is (document_index, score, matched_terms).
|
| 176 |
+
"""
|
| 177 |
+
import heapq
|
| 178 |
+
|
| 179 |
+
n = index["stats"]["n_docs"]
|
| 180 |
+
postings = index["postings_map"]
|
| 181 |
+
idf = index["idf"]
|
| 182 |
+
doc_len = index["doc_len"]
|
| 183 |
+
avgdl = index["avgdl"] or 1.0
|
| 184 |
+
title_toks = index["title_toks"]
|
| 185 |
+
body_toks = index["body_toks"]
|
| 186 |
+
df_cap = max(256, min(1500, n // 40 or 1))
|
| 187 |
+
term_docs: dict[str, np.ndarray] = {}
|
| 188 |
+
term_pay: dict[str, np.ndarray] = {}
|
| 189 |
+
for term, plist in postings.items():
|
| 190 |
+
if len(plist) > df_cap:
|
| 191 |
+
continue
|
| 192 |
+
docs = np.fromiter(plist.keys(), dtype=np.int32, count=len(plist))
|
| 193 |
+
tfs = np.empty(len(plist), dtype=np.float64)
|
| 194 |
+
for j, (doc, (ttf, btf)) in enumerate(plist.items()):
|
| 195 |
+
tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf
|
| 196 |
+
tfs[j] = _tf_score(tf, float(doc_len[doc]), avgdl)
|
| 197 |
+
term_docs[term] = docs
|
| 198 |
+
term_pay[term] = tfs * float(idf.get(term, 0.0))
|
| 199 |
+
|
| 200 |
+
neighbors: list[list[tuple[int, float, list[str]]]] = [[] for _ in range(n)]
|
| 201 |
+
step = 20000 if n >= 40000 else max(n, 1)
|
| 202 |
+
for i in range(n):
|
| 203 |
+
if i and i % step == 0:
|
| 204 |
+
print(f"bm25 neighbors {i}/{n}", flush=True)
|
| 205 |
+
q_terms = title_toks[i][:16] or body_toks[i][:16]
|
| 206 |
+
if not q_terms:
|
| 207 |
+
continue
|
| 208 |
+
tf_q: dict[str, int] = defaultdict(int)
|
| 209 |
+
for tok in q_terms:
|
| 210 |
+
tf_q[tok] += 1
|
| 211 |
+
scores: dict[int, float] = defaultdict(float)
|
| 212 |
+
matched: dict[int, set[str]] = defaultdict(set)
|
| 213 |
+
for term, qtf in tf_q.items():
|
| 214 |
+
docs = term_docs.get(term)
|
| 215 |
+
if docs is None:
|
| 216 |
+
continue
|
| 217 |
+
pay = term_pay[term] * qtf
|
| 218 |
+
for doc, val in zip(docs, pay):
|
| 219 |
+
di = int(doc)
|
| 220 |
+
if di != i:
|
| 221 |
+
scores[di] += float(val)
|
| 222 |
+
matched[di].add(term)
|
| 223 |
+
if scores:
|
| 224 |
+
top = heapq.nlargest(k, scores.items(), key=lambda kv: kv[1])
|
| 225 |
+
neighbors[i] = [(doc, score, sorted(matched[doc])) for doc, score in top]
|
| 226 |
+
print(f"bm25 neighbors {n}/{n}", flush=True)
|
| 227 |
+
return neighbors
|
country_laws_ir/build.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end build: normalize → BM25 → graph → vectors → package (no upload by default)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import traceback
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from .bm25 import bm25_neighbors, build_index
|
| 12 |
+
from .catalog import get_country, indexable_countries, target_repo
|
| 13 |
+
from .graph import build_graph
|
| 14 |
+
from .normalize import build_corpus, load_source
|
| 15 |
+
from .package import package_release
|
| 16 |
+
from .auth import configure_hf
|
| 17 |
+
from .vectors import encode_corpus, embeddings_available, layout_stub_vectors, layout_vectors
|
| 18 |
+
|
| 19 |
+
ROOT = Path("/workspace/country-laws-ir")
|
| 20 |
+
CACHE = ROOT / "cache"
|
| 21 |
+
RELEASES = ROOT / "releases"
|
| 22 |
+
REPORTS = ROOT / "reports"
|
| 23 |
+
PROGRESS = ROOT / "progress.jsonl"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _log(msg: str) -> None:
|
| 27 |
+
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 28 |
+
print(f"[{ts}] {msg}", flush=True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def record_progress(event: dict[str, Any]) -> None:
|
| 32 |
+
event = dict(event)
|
| 33 |
+
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 34 |
+
with PROGRESS.open("a", encoding="utf-8") as f:
|
| 35 |
+
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_country(
|
| 39 |
+
source: str,
|
| 40 |
+
out: Path | None = None,
|
| 41 |
+
upload: bool = False,
|
| 42 |
+
device: str = "cpu",
|
| 43 |
+
neighbor_k: int = 8,
|
| 44 |
+
skip_vectors: bool = False,
|
| 45 |
+
) -> dict[str, Any]:
|
| 46 |
+
country = get_country(source)
|
| 47 |
+
if not country.get("indexable", True):
|
| 48 |
+
raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}")
|
| 49 |
+
repo = country["repo"]
|
| 50 |
+
out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir"
|
| 51 |
+
_log(f"build start {repo} -> {out} (upload={upload})")
|
| 52 |
+
configure_hf()
|
| 53 |
+
CACHE.mkdir(parents=True, exist_ok=True)
|
| 54 |
+
REPORTS.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
laws, articles, source_meta = load_source(repo, CACHE)
|
| 56 |
+
_log(
|
| 57 |
+
f"source loaded laws={source_meta['n_laws_source']} "
|
| 58 |
+
f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
|
| 59 |
+
)
|
| 60 |
+
corpus, norm_report = build_corpus(laws, articles, source_meta)
|
| 61 |
+
report_path = REPORTS / f"{country['slug']}_normalization.json"
|
| 62 |
+
report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 63 |
+
(REPORTS / "normalization.json").write_text(
|
| 64 |
+
json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 65 |
+
)
|
| 66 |
+
_log(
|
| 67 |
+
f"normalized docs={len(corpus)} unit={norm_report['unit']} "
|
| 68 |
+
f"dropped={norm_report['n_dropped_total']} report={report_path}"
|
| 69 |
+
)
|
| 70 |
+
if corpus.empty:
|
| 71 |
+
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
| 72 |
+
|
| 73 |
+
bm25 = build_index(corpus)
|
| 74 |
+
_log(f"bm25 terms={bm25['stats']['n_terms']} postings={bm25['stats']['n_postings']}")
|
| 75 |
+
_log(f"bm25 neighbors start n={len(corpus)} k={neighbor_k}")
|
| 76 |
+
neighbors = bm25_neighbors(bm25, k=neighbor_k)
|
| 77 |
+
_log("bm25 neighbors done")
|
| 78 |
+
graph = build_graph(corpus, neighbors)
|
| 79 |
+
_log(f"graph nodes={graph['stats']['n_nodes']} edges={graph['stats']['n_edges']}")
|
| 80 |
+
|
| 81 |
+
vector_blocker = None
|
| 82 |
+
if skip_vectors:
|
| 83 |
+
vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
|
| 84 |
+
vector_blocker = "skip_vectors"
|
| 85 |
+
elif embeddings_available():
|
| 86 |
+
try:
|
| 87 |
+
ckpt = CACHE / "embeddings" / f"{country['slug']}.npy"
|
| 88 |
+
_log(f"vectors encode start n={len(corpus)} checkpoint={ckpt}")
|
| 89 |
+
embeddings = encode_corpus(corpus, device=device, checkpoint_path=str(ckpt))
|
| 90 |
+
vectors = layout_vectors(corpus, embeddings)
|
| 91 |
+
_log(f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']}")
|
| 92 |
+
except Exception as exc:
|
| 93 |
+
vector_blocker = f"embedding_failed: {exc}"
|
| 94 |
+
_log(f"vector embedding failed; writing stub ({exc})")
|
| 95 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 96 |
+
else:
|
| 97 |
+
vector_blocker = "sentence-transformers/torch unavailable"
|
| 98 |
+
_log(f"vectors stub: {vector_blocker}")
|
| 99 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 100 |
+
|
| 101 |
+
code_root = Path(__file__).resolve().parent.parent
|
| 102 |
+
manifest = package_release(
|
| 103 |
+
out,
|
| 104 |
+
corpus,
|
| 105 |
+
bm25,
|
| 106 |
+
graph,
|
| 107 |
+
vectors,
|
| 108 |
+
source_meta,
|
| 109 |
+
country,
|
| 110 |
+
code_root,
|
| 111 |
+
normalization_report=norm_report,
|
| 112 |
+
)
|
| 113 |
+
_log(f"packaged {out}")
|
| 114 |
+
result = {
|
| 115 |
+
"country": country["slug"],
|
| 116 |
+
"source": repo,
|
| 117 |
+
"source_revision": source_meta["source_revision"],
|
| 118 |
+
"out": str(out),
|
| 119 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 120 |
+
"counts": manifest["counts"],
|
| 121 |
+
"normalization": norm_report,
|
| 122 |
+
"vector_blocker": vector_blocker,
|
| 123 |
+
"schema_version": manifest["schema_version"],
|
| 124 |
+
}
|
| 125 |
+
if upload:
|
| 126 |
+
from .upload import upload_release
|
| 127 |
+
|
| 128 |
+
hub = upload_release(out, target_repo(country["slug"]))
|
| 129 |
+
result["hub"] = hub
|
| 130 |
+
_log(f"uploaded {hub['url']} rev={hub['revision']}")
|
| 131 |
+
record_progress({"event": "uploaded", **result})
|
| 132 |
+
else:
|
| 133 |
+
record_progress({"event": "built_local", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 134 |
+
return result
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def batch(
|
| 138 |
+
slugs: list[str] | None = None,
|
| 139 |
+
upload: bool = False,
|
| 140 |
+
skip_done: bool = True,
|
| 141 |
+
) -> list[dict[str, Any]]:
|
| 142 |
+
done = set()
|
| 143 |
+
if skip_done and PROGRESS.exists():
|
| 144 |
+
for line in PROGRESS.read_text(encoding="utf-8").splitlines():
|
| 145 |
+
if not line.strip():
|
| 146 |
+
continue
|
| 147 |
+
rec = json.loads(line)
|
| 148 |
+
if rec.get("event") in {"uploaded", "built_local"} and rec.get("country"):
|
| 149 |
+
done.add(rec["country"])
|
| 150 |
+
targets = slugs or [c["slug"] for c in indexable_countries()]
|
| 151 |
+
if "malta" in targets:
|
| 152 |
+
targets = ["malta"] + [s for s in targets if s != "malta"]
|
| 153 |
+
results = []
|
| 154 |
+
for slug in targets:
|
| 155 |
+
if skip_done and slug in done:
|
| 156 |
+
_log(f"skip already done {slug}")
|
| 157 |
+
continue
|
| 158 |
+
try:
|
| 159 |
+
results.append(build_country(slug, upload=upload))
|
| 160 |
+
except Exception as exc:
|
| 161 |
+
_log(f"FAILED {slug}: {exc}")
|
| 162 |
+
record_progress(
|
| 163 |
+
{
|
| 164 |
+
"event": "failed",
|
| 165 |
+
"country": slug,
|
| 166 |
+
"error": str(exc),
|
| 167 |
+
"traceback": traceback.format_exc(),
|
| 168 |
+
}
|
| 169 |
+
)
|
| 170 |
+
continue
|
| 171 |
+
return results
|
country_laws_ir/catalog.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Catalog of endomorphosis/ipfs_*_laws corpora.
|
| 2 |
+
|
| 3 |
+
Belgium, Portugal, and Lithuania are incomplete Wayback harvests and are
|
| 4 |
+
excluded from indexing. american_municipal_law is out of scope.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania"}
|
| 12 |
+
EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS}
|
| 13 |
+
|
| 14 |
+
# Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`.
|
| 15 |
+
COUNTRIES: list[dict[str, Any]] = [
|
| 16 |
+
{"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True},
|
| 17 |
+
{"slug": "australia", "repo": "endomorphosis/ipfs_australia_laws", "name": "Australia", "indexable": True},
|
| 18 |
+
{"slug": "austria", "repo": "endomorphosis/ipfs_austria_laws", "name": "Austria", "indexable": True},
|
| 19 |
+
{"slug": "bangladesh", "repo": "endomorphosis/ipfs_bangladesh_laws", "name": "Bangladesh", "indexable": True},
|
| 20 |
+
{"slug": "belgium", "repo": "endomorphosis/ipfs_belgium_laws", "name": "Belgium", "indexable": False,
|
| 21 |
+
"skip_reason": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)"},
|
| 22 |
+
{"slug": "brazil", "repo": "endomorphosis/ipfs_brazil_laws", "name": "Brazil", "indexable": True},
|
| 23 |
+
{"slug": "canada", "repo": "endomorphosis/ipfs_canada_laws", "name": "Canada", "indexable": True},
|
| 24 |
+
{"slug": "chile", "repo": "endomorphosis/ipfs_chile_laws", "name": "Chile", "indexable": True},
|
| 25 |
+
{"slug": "china", "repo": "endomorphosis/ipfs_china_laws", "name": "China", "indexable": True},
|
| 26 |
+
{"slug": "colombia", "repo": "endomorphosis/ipfs_colombia_laws", "name": "Colombia", "indexable": True},
|
| 27 |
+
{"slug": "croatia", "repo": "endomorphosis/ipfs_croatia_laws", "name": "Croatia", "indexable": True},
|
| 28 |
+
{"slug": "czechia", "repo": "endomorphosis/ipfs_czechia_laws", "name": "Czechia", "indexable": True},
|
| 29 |
+
{"slug": "denmark", "repo": "endomorphosis/ipfs_denmark_laws", "name": "Denmark", "indexable": True},
|
| 30 |
+
{"slug": "egypt", "repo": "endomorphosis/ipfs_egypt_laws", "name": "Egypt", "indexable": True},
|
| 31 |
+
{"slug": "estonia", "repo": "endomorphosis/ipfs_estonia_laws", "name": "Estonia", "indexable": True},
|
| 32 |
+
{"slug": "eu", "repo": "endomorphosis/ipfs_eu_laws", "name": "European Union", "indexable": True},
|
| 33 |
+
{"slug": "finland", "repo": "endomorphosis/ipfs_finland_laws", "name": "Finland", "indexable": True},
|
| 34 |
+
{"slug": "france", "repo": "endomorphosis/ipfs_france_laws", "name": "France", "indexable": True},
|
| 35 |
+
{"slug": "germany", "repo": "endomorphosis/ipfs_germany_laws", "name": "Germany", "indexable": True},
|
| 36 |
+
{"slug": "greece", "repo": "endomorphosis/ipfs_greece_laws", "name": "Greece", "indexable": True},
|
| 37 |
+
{"slug": "hongkong", "repo": "endomorphosis/ipfs_hongkong_laws", "name": "Hong Kong", "indexable": True},
|
| 38 |
+
{"slug": "hungary", "repo": "endomorphosis/ipfs_hungary_laws", "name": "Hungary", "indexable": True},
|
| 39 |
+
{"slug": "india", "repo": "endomorphosis/ipfs_india_laws", "name": "India", "indexable": True},
|
| 40 |
+
{"slug": "indonesia", "repo": "endomorphosis/ipfs_indonesia_laws", "name": "Indonesia", "indexable": True},
|
| 41 |
+
{"slug": "ireland", "repo": "endomorphosis/ipfs_ireland_laws", "name": "Ireland", "indexable": True},
|
| 42 |
+
{"slug": "israel", "repo": "endomorphosis/ipfs_israel_laws", "name": "Israel", "indexable": True},
|
| 43 |
+
{"slug": "japan", "repo": "endomorphosis/ipfs_japan_laws", "name": "Japan", "indexable": True},
|
| 44 |
+
{"slug": "kenya", "repo": "endomorphosis/ipfs_kenya_laws", "name": "Kenya", "indexable": True},
|
| 45 |
+
{"slug": "korea", "repo": "endomorphosis/ipfs_korea_laws", "name": "Korea (ROK)", "indexable": True},
|
| 46 |
+
{"slug": "kuwait", "repo": "endomorphosis/ipfs_kuwait_laws", "name": "Kuwait", "indexable": True},
|
| 47 |
+
{"slug": "latvia", "repo": "endomorphosis/ipfs_latvia_laws", "name": "Latvia", "indexable": True},
|
| 48 |
+
{"slug": "lithuania", "repo": "endomorphosis/ipfs_lithuania_laws", "name": "Lithuania", "indexable": False,
|
| 49 |
+
"skip_reason": "incomplete Wayback harvest (e-TAR archive shard)"},
|
| 50 |
+
{"slug": "luxembourg", "repo": "endomorphosis/ipfs_luxembourg_laws", "name": "Luxembourg", "indexable": True},
|
| 51 |
+
{"slug": "malaysia", "repo": "endomorphosis/ipfs_malaysia_laws", "name": "Malaysia", "indexable": True},
|
| 52 |
+
{"slug": "malta", "repo": "endomorphosis/ipfs_malta_laws", "name": "Malta", "indexable": True, "pilot": True},
|
| 53 |
+
{"slug": "mexico", "repo": "endomorphosis/ipfs_mexico_laws", "name": "Mexico", "indexable": True},
|
| 54 |
+
{"slug": "netherlands", "repo": "endomorphosis/ipfs_netherlands_laws", "name": "Netherlands", "indexable": True},
|
| 55 |
+
{"slug": "newzealand", "repo": "endomorphosis/ipfs_newzealand_laws", "name": "New Zealand", "indexable": True},
|
| 56 |
+
{"slug": "nigeria", "repo": "endomorphosis/ipfs_nigeria_laws", "name": "Nigeria", "indexable": True},
|
| 57 |
+
{"slug": "norway", "repo": "endomorphosis/ipfs_norway_laws", "name": "Norway", "indexable": True},
|
| 58 |
+
{"slug": "pakistan", "repo": "endomorphosis/ipfs_pakistan_laws", "name": "Pakistan", "indexable": True},
|
| 59 |
+
{"slug": "philippines", "repo": "endomorphosis/ipfs_philippines_laws", "name": "Philippines", "indexable": True},
|
| 60 |
+
{"slug": "poland", "repo": "endomorphosis/ipfs_poland_laws", "name": "Poland", "indexable": True},
|
| 61 |
+
{"slug": "portugal", "repo": "endomorphosis/ipfs_portugal_laws", "name": "Portugal", "indexable": False,
|
| 62 |
+
"skip_reason": "incomplete Wayback harvest (Diário da República archive shard)"},
|
| 63 |
+
{"slug": "qatar", "repo": "endomorphosis/ipfs_qatar_laws", "name": "Qatar", "indexable": True},
|
| 64 |
+
{"slug": "russia", "repo": "endomorphosis/ipfs_russia_laws", "name": "Russia", "indexable": True},
|
| 65 |
+
{"slug": "saudiarabia", "repo": "endomorphosis/ipfs_saudiarabia_laws", "name": "Saudi Arabia", "indexable": True},
|
| 66 |
+
{"slug": "singapore", "repo": "endomorphosis/ipfs_singapore_laws", "name": "Singapore", "indexable": True},
|
| 67 |
+
{"slug": "slovakia", "repo": "endomorphosis/ipfs_slovakia_laws", "name": "Slovakia", "indexable": True},
|
| 68 |
+
{"slug": "southafrica", "repo": "endomorphosis/ipfs_southafrica_laws", "name": "South Africa", "indexable": True},
|
| 69 |
+
{"slug": "spain", "repo": "endomorphosis/ipfs_spain_laws", "name": "Spain", "indexable": True},
|
| 70 |
+
{"slug": "sweden", "repo": "endomorphosis/ipfs_sweden_laws", "name": "Sweden", "indexable": True},
|
| 71 |
+
{"slug": "switzerland", "repo": "endomorphosis/ipfs_switzerland_laws", "name": "Switzerland", "indexable": True},
|
| 72 |
+
{"slug": "taiwan", "repo": "endomorphosis/ipfs_taiwan_laws", "name": "Taiwan", "indexable": True},
|
| 73 |
+
{"slug": "thailand", "repo": "endomorphosis/ipfs_thailand_laws", "name": "Thailand", "indexable": True},
|
| 74 |
+
{"slug": "turkey", "repo": "endomorphosis/ipfs_turkey_laws", "name": "Turkey", "indexable": True},
|
| 75 |
+
{"slug": "uae", "repo": "endomorphosis/ipfs_uae_laws", "name": "United Arab Emirates", "indexable": True},
|
| 76 |
+
{"slug": "uk", "repo": "endomorphosis/ipfs_uk_laws", "name": "United Kingdom", "indexable": True},
|
| 77 |
+
{"slug": "ukraine", "repo": "endomorphosis/ipfs_ukraine_laws", "name": "Ukraine", "indexable": True},
|
| 78 |
+
{"slug": "vietnam", "repo": "endomorphosis/ipfs_vietnam_laws", "name": "Vietnam", "indexable": True},
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_country(source: str) -> dict[str, Any]:
|
| 83 |
+
source = source.strip()
|
| 84 |
+
slug = source
|
| 85 |
+
if "/" in source:
|
| 86 |
+
slug = source.rsplit("/", 1)[-1]
|
| 87 |
+
slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir")
|
| 88 |
+
for row in COUNTRIES:
|
| 89 |
+
if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source):
|
| 90 |
+
return dict(row)
|
| 91 |
+
if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"):
|
| 92 |
+
inferred = source.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 93 |
+
return {
|
| 94 |
+
"slug": inferred,
|
| 95 |
+
"repo": source,
|
| 96 |
+
"name": inferred.replace("_", " ").title(),
|
| 97 |
+
"indexable": inferred not in EXCLUDED_SLUGS,
|
| 98 |
+
"skip_reason": "incomplete Wayback harvest" if inferred in EXCLUDED_SLUGS else None,
|
| 99 |
+
}
|
| 100 |
+
raise KeyError(f"Unknown country-law source: {source}")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def indexable_countries() -> list[dict[str, Any]]:
|
| 104 |
+
return [c for c in COUNTRIES if c.get("indexable")]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def target_repo(slug: str) -> str:
|
| 108 |
+
return f"justicedao/ipfs_{slug}_laws_ir"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def refresh_from_hub() -> list[dict[str, Any]]:
|
| 112 |
+
"""Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets."""
|
| 113 |
+
from huggingface_hub import HfApi
|
| 114 |
+
|
| 115 |
+
from .auth import configure_hf, public_token
|
| 116 |
+
|
| 117 |
+
configure_hf()
|
| 118 |
+
api = HfApi(token=public_token())
|
| 119 |
+
found: list[dict[str, Any]] = []
|
| 120 |
+
for ds in api.list_datasets(author="endomorphosis"):
|
| 121 |
+
ds_id = ds.id
|
| 122 |
+
if not ds_id.startswith("endomorphosis/ipfs_") or not ds_id.endswith("_laws"):
|
| 123 |
+
continue
|
| 124 |
+
slug = ds_id.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 125 |
+
found.append({
|
| 126 |
+
"slug": slug,
|
| 127 |
+
"repo": ds_id,
|
| 128 |
+
"name": slug.replace("_", " ").title(),
|
| 129 |
+
"indexable": slug not in EXCLUDED_SLUGS,
|
| 130 |
+
"skip_reason": (
|
| 131 |
+
"incomplete Wayback harvest" if slug in EXCLUDED_SLUGS else None
|
| 132 |
+
),
|
| 133 |
+
})
|
| 134 |
+
found.sort(key=lambda r: r["slug"])
|
| 135 |
+
return found
|
country_laws_ir/cidutil.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CIDv1 (raw + sha2-256) helpers. Produces bafkrei... identifiers.
|
| 2 |
+
|
| 3 |
+
Payload format (deterministic):
|
| 4 |
+
json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 5 |
+
|
| 6 |
+
Codec: CIDv1 version=0x01, multicodec raw=0x55, multihash sha2-256=0x12, length=0x20,
|
| 7 |
+
then 32-byte digest. Multibase prefix `b` + RFC 4648 base32 (lowercase, no padding).
|
| 8 |
+
Same payload bytes always yield the same CID.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_B32 = "abcdefghijklmnopqrstuvwxyz234567"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def sha256_hex(data: bytes) -> str:
|
| 23 |
+
return hashlib.sha256(data).hexdigest()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def sha256_file(path: Path) -> str:
|
| 27 |
+
h = hashlib.sha256()
|
| 28 |
+
with path.open("rb") as f:
|
| 29 |
+
while True:
|
| 30 |
+
chunk = f.read(1024 * 1024)
|
| 31 |
+
if not chunk:
|
| 32 |
+
break
|
| 33 |
+
h.update(chunk)
|
| 34 |
+
return h.hexdigest()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def canonical_json_bytes(obj: Any) -> bytes:
|
| 38 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _b32encode(data: bytes) -> str:
|
| 42 |
+
bits = 0
|
| 43 |
+
value = 0
|
| 44 |
+
out = []
|
| 45 |
+
for byte in data:
|
| 46 |
+
value = (value << 8) | byte
|
| 47 |
+
bits += 8
|
| 48 |
+
while bits >= 5:
|
| 49 |
+
bits -= 5
|
| 50 |
+
out.append(_B32[(value >> bits) & 31])
|
| 51 |
+
if bits:
|
| 52 |
+
out.append(_B32[(value << (5 - bits)) & 31])
|
| 53 |
+
return "".join(out)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def cid_v1_raw_sha256(data: bytes) -> str:
|
| 57 |
+
digest = hashlib.sha256(data).digest()
|
| 58 |
+
cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest
|
| 59 |
+
return "b" + _b32encode(cid_bytes)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def cid_of_json(obj: Any) -> str:
|
| 63 |
+
return cid_v1_raw_sha256(canonical_json_bytes(obj))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def cid_of_text(*parts: str) -> str:
|
| 67 |
+
blob = "\n".join("" if p is None else str(p) for p in parts).encode("utf-8")
|
| 68 |
+
return cid_v1_raw_sha256(blob)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def file_descriptor(path: Path, relative_path: str, extra: dict | None = None) -> dict:
|
| 72 |
+
data = path.read_bytes()
|
| 73 |
+
desc = {
|
| 74 |
+
"cid": cid_v1_raw_sha256(data),
|
| 75 |
+
"sha256": sha256_hex(data),
|
| 76 |
+
"size_bytes": len(data),
|
| 77 |
+
"relative_path": relative_path,
|
| 78 |
+
}
|
| 79 |
+
if extra:
|
| 80 |
+
desc.update(extra)
|
| 81 |
+
return desc
|
country_laws_ir/graph.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Property graph: entry nodes, facet nodes, BM25_NEIGHBOR_OF k=8, ARTICLE_OF, ELI."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from . import EDGE_IDENTITY_SCHEMA, FACET_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 11 |
+
from .cidutil import cid_of_json
|
| 12 |
+
|
| 13 |
+
# Facet kinds requested by the SkillCenter-style country-laws graph:
|
| 14 |
+
# jurisdiction, language, instrument/law, source, status.
|
| 15 |
+
FACET_FIELDS = (
|
| 16 |
+
("jurisdiction", "HAS_JURISDICTION", "jurisdiction"),
|
| 17 |
+
("language", "HAS_LANGUAGE", "language"),
|
| 18 |
+
("instrument", "HAS_INSTRUMENT", "instrument_id"),
|
| 19 |
+
("source", "HAS_SOURCE", "source_type"),
|
| 20 |
+
("status", "HAS_STATUS", "law_status"),
|
| 21 |
+
)
|
| 22 |
+
ADJ_POINTERS_PER_ROW = 4096
|
| 23 |
+
ADJ_POINTERS_PER_SHARD = 8192
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _facet_cid(kind: str, value: str) -> str:
|
| 27 |
+
"""CIDv1 raw sha2-256 of sorted JSON {kind, schema, value}."""
|
| 28 |
+
return cid_of_json(
|
| 29 |
+
{
|
| 30 |
+
"kind": kind,
|
| 31 |
+
"schema": FACET_IDENTITY_SCHEMA,
|
| 32 |
+
"value": value,
|
| 33 |
+
}
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _edge_cid(source: str, edge_type: str, target: str) -> str:
|
| 38 |
+
return cid_of_json(
|
| 39 |
+
{
|
| 40 |
+
"edge_type": edge_type,
|
| 41 |
+
"schema": EDGE_IDENTITY_SCHEMA,
|
| 42 |
+
"source": source,
|
| 43 |
+
"target": target,
|
| 44 |
+
}
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def build_graph(
|
| 49 |
+
corpus: pd.DataFrame,
|
| 50 |
+
neighbors: list[list[tuple]],
|
| 51 |
+
) -> dict[str, Any]:
|
| 52 |
+
nodes: list[dict[str, Any]] = []
|
| 53 |
+
edges: list[dict[str, Any]] = []
|
| 54 |
+
seen_facets: set[str] = set()
|
| 55 |
+
cid_by_idx = corpus["entry_cid"].tolist()
|
| 56 |
+
|
| 57 |
+
# Law identity nodes (targets of ARTICLE_OF when the parent is not a corpus entry).
|
| 58 |
+
law_nodes: dict[str, dict[str, Any]] = {}
|
| 59 |
+
entry_by_instrument: dict[str, str] = {}
|
| 60 |
+
for rec in corpus.itertuples(index=False):
|
| 61 |
+
law_cid = str(getattr(rec, "law_cid", "") or "")
|
| 62 |
+
instrument_id = str(getattr(rec, "instrument_id", "") or "")
|
| 63 |
+
if getattr(rec, "record_type", "") == "law" and instrument_id and rec.entry_cid:
|
| 64 |
+
entry_by_instrument.setdefault(instrument_id, rec.entry_cid)
|
| 65 |
+
if not law_cid or law_cid in law_nodes:
|
| 66 |
+
continue
|
| 67 |
+
law_nodes[law_cid] = {
|
| 68 |
+
"node_cid": law_cid,
|
| 69 |
+
"node_type": "law",
|
| 70 |
+
"entry_cid": "",
|
| 71 |
+
"label": getattr(rec, "instrument_title", None) or instrument_id,
|
| 72 |
+
"properties_json": _json(
|
| 73 |
+
{
|
| 74 |
+
"instrument_id": instrument_id,
|
| 75 |
+
"instrument_title": str(getattr(rec, "instrument_title", "") or ""),
|
| 76 |
+
"jurisdiction": str(getattr(rec, "jurisdiction", "") or ""),
|
| 77 |
+
"language": str(getattr(rec, "language", "") or ""),
|
| 78 |
+
"law_cid": law_cid,
|
| 79 |
+
}
|
| 80 |
+
),
|
| 81 |
+
"schema_version": SCHEMA_VERSION,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
for law_node in law_nodes.values():
|
| 85 |
+
nodes.append(law_node)
|
| 86 |
+
|
| 87 |
+
for rec in corpus.itertuples(index=False):
|
| 88 |
+
node_type = "law_entry" if rec.record_type == "law" else "article"
|
| 89 |
+
title = getattr(rec, "title", None) or getattr(rec, "instrument_title", None) or rec.source_id
|
| 90 |
+
nodes.append(
|
| 91 |
+
{
|
| 92 |
+
"node_cid": rec.entry_cid,
|
| 93 |
+
"node_type": node_type,
|
| 94 |
+
"entry_cid": rec.entry_cid,
|
| 95 |
+
"label": title,
|
| 96 |
+
"properties_json": _props_tuple(rec),
|
| 97 |
+
"schema_version": SCHEMA_VERSION,
|
| 98 |
+
}
|
| 99 |
+
)
|
| 100 |
+
src = rec.entry_cid
|
| 101 |
+
row_map = rec._asdict() if hasattr(rec, "_asdict") else {}
|
| 102 |
+
|
| 103 |
+
for kind, edge_type, col in FACET_FIELDS:
|
| 104 |
+
value = str(row_map.get(col) or "").strip()
|
| 105 |
+
if not value:
|
| 106 |
+
continue
|
| 107 |
+
fc = _facet_cid(kind, value)
|
| 108 |
+
if fc not in seen_facets:
|
| 109 |
+
seen_facets.add(fc)
|
| 110 |
+
nodes.append(
|
| 111 |
+
{
|
| 112 |
+
"node_cid": fc,
|
| 113 |
+
"node_type": f"facet_{kind}",
|
| 114 |
+
"entry_cid": "",
|
| 115 |
+
"label": f"{kind}:{value}",
|
| 116 |
+
"properties_json": _json({"kind": kind, "value": value}),
|
| 117 |
+
"schema_version": SCHEMA_VERSION,
|
| 118 |
+
}
|
| 119 |
+
)
|
| 120 |
+
edges.append(_edge(src, edge_type, fc, "facet", 1.0, {"facet": kind, "value": value}))
|
| 121 |
+
|
| 122 |
+
# ELI / identifier links — only values present in the source, never invented.
|
| 123 |
+
eli = str(row_map.get("eli") or "").strip()
|
| 124 |
+
if eli:
|
| 125 |
+
fc = _facet_cid("eli", eli)
|
| 126 |
+
if fc not in seen_facets:
|
| 127 |
+
seen_facets.add(fc)
|
| 128 |
+
nodes.append(
|
| 129 |
+
{
|
| 130 |
+
"node_cid": fc,
|
| 131 |
+
"node_type": "facet_eli",
|
| 132 |
+
"entry_cid": "",
|
| 133 |
+
"label": f"eli:{eli}",
|
| 134 |
+
"properties_json": _json({"kind": "eli", "value": eli}),
|
| 135 |
+
"schema_version": SCHEMA_VERSION,
|
| 136 |
+
}
|
| 137 |
+
)
|
| 138 |
+
edges.append(_edge(src, "IDENTIFIED_BY_ELI", fc, "identifier", 1.0, {"eli": eli}))
|
| 139 |
+
ident = str(row_map.get("official_identifier") or row_map.get("identifier") or "").strip()
|
| 140 |
+
if ident and ident != eli:
|
| 141 |
+
fc = _facet_cid("identifier", ident)
|
| 142 |
+
if fc not in seen_facets:
|
| 143 |
+
seen_facets.add(fc)
|
| 144 |
+
nodes.append(
|
| 145 |
+
{
|
| 146 |
+
"node_cid": fc,
|
| 147 |
+
"node_type": "facet_identifier",
|
| 148 |
+
"entry_cid": "",
|
| 149 |
+
"label": f"identifier:{ident}",
|
| 150 |
+
"properties_json": _json({"kind": "identifier", "value": ident}),
|
| 151 |
+
"schema_version": SCHEMA_VERSION,
|
| 152 |
+
}
|
| 153 |
+
)
|
| 154 |
+
edges.append(
|
| 155 |
+
_edge(src, "IDENTIFIED_BY", fc, "identifier", 1.0, {"identifier": ident})
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
law_cid = str(row_map.get("law_cid") or "")
|
| 159 |
+
instrument_id = str(row_map.get("instrument_id") or "")
|
| 160 |
+
if rec.record_type == "article":
|
| 161 |
+
parent = entry_by_instrument.get(instrument_id) or law_cid
|
| 162 |
+
if parent and parent != rec.entry_cid:
|
| 163 |
+
edges.append(
|
| 164 |
+
_edge(
|
| 165 |
+
rec.entry_cid,
|
| 166 |
+
"ARTICLE_OF",
|
| 167 |
+
parent,
|
| 168 |
+
"structural",
|
| 169 |
+
1.0,
|
| 170 |
+
{
|
| 171 |
+
"instrument_id": instrument_id,
|
| 172 |
+
"article_number": row_map.get("article_number"),
|
| 173 |
+
},
|
| 174 |
+
)
|
| 175 |
+
)
|
| 176 |
+
elif law_cid and rec.entry_cid != law_cid:
|
| 177 |
+
# Law-level corpus unit still points at its instrument identity node.
|
| 178 |
+
edges.append(
|
| 179 |
+
_edge(
|
| 180 |
+
rec.entry_cid,
|
| 181 |
+
"HAS_INSTRUMENT",
|
| 182 |
+
law_cid,
|
| 183 |
+
"structural",
|
| 184 |
+
1.0,
|
| 185 |
+
{"instrument_id": instrument_id},
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
for i, neigh in enumerate(neighbors):
|
| 190 |
+
src = cid_by_idx[i]
|
| 191 |
+
for item in neigh:
|
| 192 |
+
if len(item) == 3:
|
| 193 |
+
j, score, terms = item
|
| 194 |
+
else:
|
| 195 |
+
j, score = item[0], item[1]
|
| 196 |
+
terms = []
|
| 197 |
+
tgt = cid_by_idx[int(j)]
|
| 198 |
+
edges.append(
|
| 199 |
+
_edge(
|
| 200 |
+
src,
|
| 201 |
+
"BM25_NEIGHBOR_OF",
|
| 202 |
+
tgt,
|
| 203 |
+
"bm25-okapi",
|
| 204 |
+
float(score),
|
| 205 |
+
{"k": 8, "neighbor_index": int(j)},
|
| 206 |
+
matched_terms=list(terms),
|
| 207 |
+
)
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
nodes_df = pd.DataFrame(nodes).drop_duplicates("node_cid").reset_index(drop=True)
|
| 211 |
+
nodes_df = nodes_df.sort_values(["node_type", "node_cid"]).reset_index(drop=True)
|
| 212 |
+
edges_df = pd.DataFrame(edges)
|
| 213 |
+
if not edges_df.empty:
|
| 214 |
+
edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True)
|
| 215 |
+
edges_df = edges_df.sort_values(["edge_type", "source_cid", "target_cid"]).reset_index(drop=True)
|
| 216 |
+
|
| 217 |
+
node_type = {r["node_cid"]: r["node_type"] for r in nodes_df.to_dict("records")}
|
| 218 |
+
incoming, outgoing = _adjacency(edges_df, node_type)
|
| 219 |
+
return {
|
| 220 |
+
"nodes": nodes_df,
|
| 221 |
+
"edges": edges_df,
|
| 222 |
+
"incoming": incoming,
|
| 223 |
+
"outgoing": outgoing,
|
| 224 |
+
"stats": {
|
| 225 |
+
"n_nodes": int(len(nodes_df)),
|
| 226 |
+
"n_edges": int(len(edges_df)),
|
| 227 |
+
"n_doc_nodes": int(nodes_df["node_type"].isin(["law_entry", "article", "law"]).sum()),
|
| 228 |
+
"n_facet_nodes": int(nodes_df["node_type"].astype(str).str.startswith("facet_").sum()),
|
| 229 |
+
"edge_types": sorted(edges_df["edge_type"].unique().tolist()) if not edges_df.empty else [],
|
| 230 |
+
},
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _json(obj: dict) -> str:
|
| 235 |
+
import json
|
| 236 |
+
|
| 237 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _props_tuple(rec: Any) -> str:
|
| 241 |
+
keys = [
|
| 242 |
+
"record_type",
|
| 243 |
+
"instrument_id",
|
| 244 |
+
"instrument_title",
|
| 245 |
+
"law_cid",
|
| 246 |
+
"article_number",
|
| 247 |
+
"article_title",
|
| 248 |
+
"jurisdiction",
|
| 249 |
+
"language",
|
| 250 |
+
"source_url",
|
| 251 |
+
"snapshot_date",
|
| 252 |
+
"coverage",
|
| 253 |
+
"license",
|
| 254 |
+
"collector",
|
| 255 |
+
"source_id",
|
| 256 |
+
"eli",
|
| 257 |
+
"law_status",
|
| 258 |
+
"source_type",
|
| 259 |
+
]
|
| 260 |
+
d = rec._asdict() if hasattr(rec, "_asdict") else {}
|
| 261 |
+
out = {}
|
| 262 |
+
for k in keys:
|
| 263 |
+
v = d.get(k, "")
|
| 264 |
+
if v is None or (isinstance(v, float) and pd.isna(v)):
|
| 265 |
+
v = ""
|
| 266 |
+
out[k] = str(v)
|
| 267 |
+
return _json(out)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _edge(
|
| 271 |
+
src: str,
|
| 272 |
+
etype: str,
|
| 273 |
+
tgt: str,
|
| 274 |
+
method: str,
|
| 275 |
+
score: float,
|
| 276 |
+
props: dict,
|
| 277 |
+
matched_terms: list[str] | None = None,
|
| 278 |
+
) -> dict[str, Any]:
|
| 279 |
+
import json
|
| 280 |
+
|
| 281 |
+
terms = matched_terms or []
|
| 282 |
+
return {
|
| 283 |
+
"edge_cid": _edge_cid(src, etype, tgt),
|
| 284 |
+
"edge_type": etype,
|
| 285 |
+
"source_cid": src,
|
| 286 |
+
"target_cid": tgt,
|
| 287 |
+
"retrieval_method": method,
|
| 288 |
+
"score": float(score),
|
| 289 |
+
"query_terms_json": json.dumps(terms, ensure_ascii=False, separators=(",", ":")),
|
| 290 |
+
"matched_terms": terms,
|
| 291 |
+
"properties_json": _json({k: v for k, v in props.items() if v is not None}),
|
| 292 |
+
"schema_version": SCHEMA_VERSION,
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _adjacency(edges: pd.DataFrame, node_type: dict[str, str]) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 297 |
+
out_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list)
|
| 298 |
+
in_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list)
|
| 299 |
+
if edges is None or edges.empty:
|
| 300 |
+
return pd.DataFrame(), pd.DataFrame()
|
| 301 |
+
for rec in edges.itertuples(index=False):
|
| 302 |
+
score = float(rec.score) if rec.score == rec.score else float("-inf")
|
| 303 |
+
out_map[rec.source_cid].append((score, rec.target_cid, rec.edge_type, rec.edge_cid))
|
| 304 |
+
in_map[rec.target_cid].append((score, rec.source_cid, rec.edge_type, rec.edge_cid))
|
| 305 |
+
|
| 306 |
+
def pages(mapping: dict[str, list], direction: str) -> pd.DataFrame:
|
| 307 |
+
rows = []
|
| 308 |
+
for node, items in mapping.items():
|
| 309 |
+
items = sorted(items, key=lambda t: (-t[0] if t[0] == t[0] else float("inf"), t[1]))
|
| 310 |
+
total = len(items)
|
| 311 |
+
page_size = ADJ_POINTERS_PER_ROW
|
| 312 |
+
n_pages = max(1, (total + page_size - 1) // page_size)
|
| 313 |
+
for p in range(n_pages):
|
| 314 |
+
chunk = items[p * page_size : (p + 1) * page_size]
|
| 315 |
+
rows.append(
|
| 316 |
+
{
|
| 317 |
+
"direction": direction,
|
| 318 |
+
"node_cid": node,
|
| 319 |
+
"page_index": p,
|
| 320 |
+
"page_count": n_pages,
|
| 321 |
+
"neighbor_count": len(chunk),
|
| 322 |
+
"total_neighbor_count": total,
|
| 323 |
+
"neighbor_cids": [t[1] for t in chunk],
|
| 324 |
+
"neighbor_node_types": [node_type.get(t[1], "") for t in chunk],
|
| 325 |
+
"edge_types": [t[2] for t in chunk],
|
| 326 |
+
"edge_cids": [t[3] for t in chunk],
|
| 327 |
+
"retrieval_methods": ["graph"] * len(chunk),
|
| 328 |
+
"scores": [t[0] if t[0] != float("-inf") else None for t in chunk],
|
| 329 |
+
"schema_version": SCHEMA_VERSION,
|
| 330 |
+
}
|
| 331 |
+
)
|
| 332 |
+
if not rows:
|
| 333 |
+
return pd.DataFrame()
|
| 334 |
+
return pd.DataFrame(rows).sort_values(["node_cid", "page_index"]).reset_index(drop=True)
|
| 335 |
+
|
| 336 |
+
return pages(in_map, "incoming"), pages(out_map, "outgoing")
|
country_laws_ir/normalize.py
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
|
| 2 |
+
|
| 3 |
+
Prefer article/section as the retrieval unit; fall back to law-level when
|
| 4 |
+
articles are missing or empty. Normalize (NFKC + whitespace collapse) BEFORE
|
| 5 |
+
GraphRAG. Never invent legal text or identifiers.
|
| 6 |
+
|
| 7 |
+
Public Hub reads only (token=False). No Hugging Face token is read or stored.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import re
|
| 15 |
+
import unicodedata
|
| 16 |
+
from collections import Counter
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from huggingface_hub import dataset_info, hf_hub_download
|
| 22 |
+
|
| 23 |
+
from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 24 |
+
from .auth import configure_hf, public_token
|
| 25 |
+
from .cidutil import cid_of_json, sha256_file, sha256_hex
|
| 26 |
+
from .schema import SchemaError, validate_articles, validate_laws
|
| 27 |
+
|
| 28 |
+
_WS_RE = re.compile(r"\s+", re.UNICODE)
|
| 29 |
+
COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def normalize_text(value: Any) -> str:
|
| 33 |
+
if value is None or (isinstance(value, float) and pd.isna(value)):
|
| 34 |
+
return ""
|
| 35 |
+
text = unicodedata.normalize("NFKC", str(value))
|
| 36 |
+
text = _WS_RE.sub(" ", text).strip()
|
| 37 |
+
return text
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _s(value: Any) -> str:
|
| 41 |
+
return normalize_text(value)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _download(repo_id: str, filename: str, cache_dir: Path) -> Path:
|
| 45 |
+
configure_hf()
|
| 46 |
+
path = hf_hub_download(
|
| 47 |
+
repo_id=repo_id,
|
| 48 |
+
filename=filename,
|
| 49 |
+
repo_type="dataset",
|
| 50 |
+
token=public_token(),
|
| 51 |
+
cache_dir=str(cache_dir / "hf"),
|
| 52 |
+
)
|
| 53 |
+
return Path(path)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 57 |
+
configure_hf()
|
| 58 |
+
os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
|
| 59 |
+
info = dataset_info(repo_id, token=public_token())
|
| 60 |
+
revision = info.sha
|
| 61 |
+
laws_path = _download(repo_id, "data/laws.parquet", cache_dir)
|
| 62 |
+
articles_path = _download(repo_id, "data/articles.parquet", cache_dir)
|
| 63 |
+
laws = pd.read_parquet(laws_path)
|
| 64 |
+
articles = pd.read_parquet(articles_path)
|
| 65 |
+
validate_laws(laws)
|
| 66 |
+
validate_articles(articles)
|
| 67 |
+
meta = {
|
| 68 |
+
"source_dataset": repo_id,
|
| 69 |
+
"source_revision": revision,
|
| 70 |
+
"laws_path": str(laws_path),
|
| 71 |
+
"articles_path": str(articles_path),
|
| 72 |
+
"laws_sha256": sha256_file(laws_path),
|
| 73 |
+
"articles_sha256": sha256_file(articles_path),
|
| 74 |
+
"n_laws_source": int(len(laws)),
|
| 75 |
+
"n_articles_source": int(len(articles)),
|
| 76 |
+
"laws_columns": list(map(str, laws.columns)),
|
| 77 |
+
"articles_columns": list(map(str, articles.columns)),
|
| 78 |
+
"article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None,
|
| 79 |
+
"schema_surprises": _schema_surprises(laws, articles),
|
| 80 |
+
}
|
| 81 |
+
return laws, articles, meta
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _schema_surprises(laws: pd.DataFrame, articles: pd.DataFrame) -> list[str]:
|
| 85 |
+
notes: list[str] = []
|
| 86 |
+
if articles is None or articles.empty:
|
| 87 |
+
notes.append("articles.parquet has 0 rows; corpus falls back to law-level units")
|
| 88 |
+
if "article_count" in laws.columns:
|
| 89 |
+
dtype = str(laws["article_count"].dtype)
|
| 90 |
+
notes.append(f"laws.article_count dtype={dtype}")
|
| 91 |
+
try:
|
| 92 |
+
if int((laws["article_count"].fillna(0) == 0).sum()) == len(laws):
|
| 93 |
+
notes.append("every law has article_count=0")
|
| 94 |
+
except Exception:
|
| 95 |
+
pass
|
| 96 |
+
for col in ("date", "date_issued"):
|
| 97 |
+
if col in laws.columns and laws[col].isna().all():
|
| 98 |
+
notes.append(f"laws.{col} is entirely null")
|
| 99 |
+
if "eli" in laws.columns:
|
| 100 |
+
n_eli = int(laws["eli"].notna().sum()) if hasattr(laws["eli"], "notna") else 0
|
| 101 |
+
notes.append(f"laws.eli non-null={n_eli}/{len(laws)}")
|
| 102 |
+
if "language" in laws.columns:
|
| 103 |
+
langs = sorted({str(x) for x in laws["language"].dropna().unique()})
|
| 104 |
+
notes.append(f"laws.language values={langs}")
|
| 105 |
+
return notes
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _parse_meta(raw: str) -> dict[str, Any]:
|
| 109 |
+
if not raw:
|
| 110 |
+
return {}
|
| 111 |
+
try:
|
| 112 |
+
obj = json.loads(raw)
|
| 113 |
+
return obj if isinstance(obj, dict) else {}
|
| 114 |
+
except Exception:
|
| 115 |
+
return {}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _law_cid(instrument_id: str, instrument_title: str, jurisdiction: str, language: str, source_dataset: str) -> str:
|
| 119 |
+
identity = {
|
| 120 |
+
"schema": LAW_IDENTITY_SCHEMA,
|
| 121 |
+
"source_dataset": source_dataset,
|
| 122 |
+
"instrument_id": instrument_id,
|
| 123 |
+
"instrument_title": instrument_title,
|
| 124 |
+
"jurisdiction": jurisdiction,
|
| 125 |
+
"language": language,
|
| 126 |
+
}
|
| 127 |
+
return cid_of_json(identity)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _entry_cid(record: dict[str, Any]) -> str:
|
| 131 |
+
identity = {
|
| 132 |
+
"schema": ENTRY_IDENTITY_SCHEMA,
|
| 133 |
+
"record_type": record["record_type"],
|
| 134 |
+
"source_dataset": record["source_dataset"],
|
| 135 |
+
"instrument_id": record["instrument_id"],
|
| 136 |
+
"article_number": record.get("article_number") or "",
|
| 137 |
+
"article_title": record.get("article_title") or "",
|
| 138 |
+
"body_sha256": record["body_sha256"],
|
| 139 |
+
"language": record.get("language") or "",
|
| 140 |
+
"jurisdiction": record.get("jurisdiction") or "",
|
| 141 |
+
"source_url": record.get("source_url") or "",
|
| 142 |
+
}
|
| 143 |
+
return cid_of_json(identity)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _row_get(row: pd.Series, col: str, default: str = "") -> str:
|
| 147 |
+
if col not in row.index:
|
| 148 |
+
return default
|
| 149 |
+
return _s(row[col])
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _coverage_from(
|
| 153 |
+
row: pd.Series,
|
| 154 |
+
meta: dict[str, Any],
|
| 155 |
+
articles_empty: bool,
|
| 156 |
+
sparse_fallback: bool = False,
|
| 157 |
+
) -> str:
|
| 158 |
+
for key in ("coverage", "coverage_note"):
|
| 159 |
+
if key in meta and meta[key]:
|
| 160 |
+
return normalize_text(meta[key])
|
| 161 |
+
status = normalize_text(meta.get("article_extraction_status") or "")
|
| 162 |
+
if sparse_fallback:
|
| 163 |
+
note = "law-level (article coverage below 10% of laws; sparse articles table)"
|
| 164 |
+
if status:
|
| 165 |
+
return f"{note}; extraction_status={status}"
|
| 166 |
+
return note
|
| 167 |
+
if articles_empty:
|
| 168 |
+
if status:
|
| 169 |
+
return f"law-level (articles empty or unavailable in source snapshot); extraction_status={status}"
|
| 170 |
+
return "law-level (articles empty or unavailable in source snapshot)"
|
| 171 |
+
if status:
|
| 172 |
+
return f"article-level; extraction_status={status}"
|
| 173 |
+
return "article-level"
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, Any]) -> str:
|
| 177 |
+
for col in ("retrieved_at", "date_issued", "date"):
|
| 178 |
+
val = _row_get(row, col)
|
| 179 |
+
if val:
|
| 180 |
+
return val[:10] if len(val) >= 10 and val[4] == "-" else val
|
| 181 |
+
for key in ("snapshot_date", "retrieved_at"):
|
| 182 |
+
if key in meta and meta[key]:
|
| 183 |
+
return normalize_text(str(meta[key]))[:10]
|
| 184 |
+
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 185 |
+
for key in ("snapshot_date", "retrieved_at"):
|
| 186 |
+
if nested.get(key):
|
| 187 |
+
return normalize_text(str(nested[key]))[:10]
|
| 188 |
+
return ""
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _collector(meta: dict[str, Any], source_dataset: str) -> str:
|
| 192 |
+
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 193 |
+
for blob in (meta, nested):
|
| 194 |
+
for key in ("collector", "collector_id", "harvester"):
|
| 195 |
+
if blob.get(key):
|
| 196 |
+
return normalize_text(blob[key])
|
| 197 |
+
return f"{COLLECTOR_DEFAULT} ({source_dataset})"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def laws_index(laws: pd.DataFrame, source_dataset: str) -> dict[str, dict[str, Any]]:
|
| 201 |
+
"""Map instrument_id -> law facet fields (always computed; not always corpus units)."""
|
| 202 |
+
out: dict[str, dict[str, Any]] = {}
|
| 203 |
+
for _, row in laws.iterrows():
|
| 204 |
+
instrument_id = _row_get(row, "id")
|
| 205 |
+
instrument_title = _row_get(row, "title")
|
| 206 |
+
jurisdiction = _row_get(row, "jurisdiction") or _row_get(row, "country")
|
| 207 |
+
language = _row_get(row, "language")
|
| 208 |
+
law_cid = _law_cid(instrument_id, instrument_title, jurisdiction, language, source_dataset)
|
| 209 |
+
meta = _parse_meta(_row_get(row, "metadata_json"))
|
| 210 |
+
out[instrument_id] = {
|
| 211 |
+
"instrument_id": instrument_id,
|
| 212 |
+
"instrument_title": instrument_title,
|
| 213 |
+
"law_cid": law_cid,
|
| 214 |
+
"jurisdiction": jurisdiction,
|
| 215 |
+
"language": language,
|
| 216 |
+
"source_url": _row_get(row, "source_url"),
|
| 217 |
+
"license": _row_get(row, "license"),
|
| 218 |
+
"eli": _row_get(row, "eli"),
|
| 219 |
+
"identifier": _row_get(row, "identifier") or instrument_id,
|
| 220 |
+
"official_identifier": _row_get(row, "official_identifier"),
|
| 221 |
+
"source_type": _row_get(row, "source_type"),
|
| 222 |
+
"country": _row_get(row, "country"),
|
| 223 |
+
"law_status": _row_get(row, "law_status"),
|
| 224 |
+
"body": _row_get(row, "text"),
|
| 225 |
+
"metadata": meta,
|
| 226 |
+
"row": row,
|
| 227 |
+
}
|
| 228 |
+
return out
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _base_record(
|
| 232 |
+
*,
|
| 233 |
+
record_type: str,
|
| 234 |
+
source_dataset: str,
|
| 235 |
+
source_revision: str,
|
| 236 |
+
instrument_id: str,
|
| 237 |
+
instrument_title: str,
|
| 238 |
+
law_cid: str,
|
| 239 |
+
article_number: str,
|
| 240 |
+
article_title: str,
|
| 241 |
+
body: str,
|
| 242 |
+
jurisdiction: str,
|
| 243 |
+
language: str,
|
| 244 |
+
source_url: str,
|
| 245 |
+
snapshot_date: str,
|
| 246 |
+
coverage: str,
|
| 247 |
+
license_expr: str,
|
| 248 |
+
collector: str,
|
| 249 |
+
source_id: str,
|
| 250 |
+
extra: dict[str, Any] | None = None,
|
| 251 |
+
) -> dict[str, Any]:
|
| 252 |
+
title_for_bm25 = article_title if record_type == "article" and article_title else instrument_title
|
| 253 |
+
rec: dict[str, Any] = {
|
| 254 |
+
"record_type": record_type,
|
| 255 |
+
"source_dataset": source_dataset,
|
| 256 |
+
"source_revision": source_revision,
|
| 257 |
+
"source_id": source_id,
|
| 258 |
+
"instrument_id": instrument_id,
|
| 259 |
+
"instrument_title": instrument_title,
|
| 260 |
+
"law_id": instrument_id,
|
| 261 |
+
"law_cid": law_cid,
|
| 262 |
+
"article_number": article_number,
|
| 263 |
+
"article_title": article_title,
|
| 264 |
+
"title": title_for_bm25,
|
| 265 |
+
"body": body,
|
| 266 |
+
"body_sha256": sha256_hex(body.encode("utf-8")),
|
| 267 |
+
"jurisdiction": jurisdiction,
|
| 268 |
+
"language": language,
|
| 269 |
+
"source_url": source_url,
|
| 270 |
+
"snapshot_date": snapshot_date,
|
| 271 |
+
"coverage": coverage,
|
| 272 |
+
"license": license_expr,
|
| 273 |
+
"collector": collector,
|
| 274 |
+
"schema_version": SCHEMA_VERSION,
|
| 275 |
+
"entry_identity_schema_version": ENTRY_IDENTITY_SCHEMA,
|
| 276 |
+
}
|
| 277 |
+
if extra:
|
| 278 |
+
rec.update(extra)
|
| 279 |
+
rec["entry_cid"] = _entry_cid(rec)
|
| 280 |
+
rec["title_length"] = len(title_for_bm25)
|
| 281 |
+
rec["body_length"] = len(body)
|
| 282 |
+
rec["document_length"] = len(title_for_bm25) + len(body)
|
| 283 |
+
return rec
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def build_corpus(
|
| 287 |
+
laws: pd.DataFrame,
|
| 288 |
+
articles: pd.DataFrame,
|
| 289 |
+
source_meta: dict[str, Any],
|
| 290 |
+
) -> tuple[pd.DataFrame, dict[str, Any]]:
|
| 291 |
+
source_dataset = source_meta["source_dataset"]
|
| 292 |
+
source_revision = source_meta["source_revision"]
|
| 293 |
+
law_map = laws_index(laws, source_dataset)
|
| 294 |
+
articles_empty = articles is None or articles.empty
|
| 295 |
+
n_laws = int(len(laws))
|
| 296 |
+
n_arts = int(len(articles) if articles is not None else 0)
|
| 297 |
+
article_law_coverage = (n_arts / n_laws) if n_laws else 0.0
|
| 298 |
+
# Empty articles.parquet already falls back. Also fall back when the table is
|
| 299 |
+
# present but covers under ~10% as many rows as laws (Estonia: 2 vs 3484).
|
| 300 |
+
sparse_fallback = (not articles_empty) and article_law_coverage < 0.10
|
| 301 |
+
use_articles = (not articles_empty) and not sparse_fallback
|
| 302 |
+
|
| 303 |
+
extraction_statuses: Counter[str] = Counter()
|
| 304 |
+
for parent in law_map.values():
|
| 305 |
+
st = normalize_text(parent["metadata"].get("article_extraction_status") or "")
|
| 306 |
+
if st:
|
| 307 |
+
extraction_statuses[st] += 1
|
| 308 |
+
|
| 309 |
+
report: dict[str, Any] = {
|
| 310 |
+
"source_dataset": source_dataset,
|
| 311 |
+
"source_revision": source_revision,
|
| 312 |
+
"laws_sha256": source_meta.get("laws_sha256"),
|
| 313 |
+
"articles_sha256": source_meta.get("articles_sha256"),
|
| 314 |
+
"n_laws_in": int(len(laws)),
|
| 315 |
+
"n_articles_in": int(len(articles) if articles is not None else 0),
|
| 316 |
+
"unit": "article" if use_articles else "law",
|
| 317 |
+
"article_law_coverage": article_law_coverage,
|
| 318 |
+
"sparse_article_fallback": sparse_fallback,
|
| 319 |
+
"drops": {
|
| 320 |
+
"empty_body": 0,
|
| 321 |
+
"missing_instrument": 0,
|
| 322 |
+
"duplicate_cid": 0,
|
| 323 |
+
"duplicate_source_kept_first": 0,
|
| 324 |
+
},
|
| 325 |
+
"drop_samples": {
|
| 326 |
+
"empty_body": [],
|
| 327 |
+
"missing_instrument": [],
|
| 328 |
+
"duplicate_cid": [],
|
| 329 |
+
},
|
| 330 |
+
"language_breakdown": {},
|
| 331 |
+
"quality_flags": {},
|
| 332 |
+
"schema_surprises": list(source_meta.get("schema_surprises") or []),
|
| 333 |
+
"n_out": 0,
|
| 334 |
+
"never_invented_legal_text": True,
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
entries: list[dict[str, Any]] = []
|
| 338 |
+
|
| 339 |
+
if sparse_fallback:
|
| 340 |
+
report["schema_surprises"].append(
|
| 341 |
+
f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
if use_articles:
|
| 345 |
+
for _, row in articles.iterrows():
|
| 346 |
+
source_id = _row_get(row, "id")
|
| 347 |
+
instrument_id = _row_get(row, "law_id")
|
| 348 |
+
body = _row_get(row, "text")
|
| 349 |
+
article_title = _row_get(row, "title")
|
| 350 |
+
article_number = _row_get(row, "article_number")
|
| 351 |
+
if not body:
|
| 352 |
+
report["drops"]["empty_body"] += 1
|
| 353 |
+
if len(report["drop_samples"]["empty_body"]) < 20:
|
| 354 |
+
report["drop_samples"]["empty_body"].append(source_id)
|
| 355 |
+
continue
|
| 356 |
+
parent = law_map.get(instrument_id)
|
| 357 |
+
if not parent:
|
| 358 |
+
report["drops"]["missing_instrument"] += 1
|
| 359 |
+
if len(report["drop_samples"]["missing_instrument"]) < 20:
|
| 360 |
+
report["drop_samples"]["missing_instrument"].append(
|
| 361 |
+
{"article_id": source_id, "law_id": instrument_id}
|
| 362 |
+
)
|
| 363 |
+
continue
|
| 364 |
+
meta = parent["metadata"]
|
| 365 |
+
art_meta = _parse_meta(_row_get(row, "metadata_json"))
|
| 366 |
+
merged_meta = {**meta, **art_meta}
|
| 367 |
+
entries.append(
|
| 368 |
+
_base_record(
|
| 369 |
+
record_type="article",
|
| 370 |
+
source_dataset=source_dataset,
|
| 371 |
+
source_revision=source_revision,
|
| 372 |
+
instrument_id=instrument_id,
|
| 373 |
+
instrument_title=parent["instrument_title"],
|
| 374 |
+
law_cid=parent["law_cid"],
|
| 375 |
+
article_number=article_number,
|
| 376 |
+
article_title=article_title,
|
| 377 |
+
body=body,
|
| 378 |
+
jurisdiction=parent["jurisdiction"],
|
| 379 |
+
language=parent["language"] or _row_get(row, "language"),
|
| 380 |
+
source_url=_row_get(row, "source_url") or parent["source_url"],
|
| 381 |
+
snapshot_date=_snapshot_date(parent["row"], merged_meta, source_meta),
|
| 382 |
+
coverage=_coverage_from(parent["row"], merged_meta, articles_empty=False),
|
| 383 |
+
license_expr=parent["license"],
|
| 384 |
+
collector=_collector(merged_meta, source_dataset),
|
| 385 |
+
source_id=source_id,
|
| 386 |
+
extra={
|
| 387 |
+
"eli": parent["eli"],
|
| 388 |
+
"identifier": parent["identifier"],
|
| 389 |
+
"official_identifier": parent["official_identifier"],
|
| 390 |
+
"source_type": parent["source_type"],
|
| 391 |
+
"country": parent["country"],
|
| 392 |
+
"law_status": parent["law_status"],
|
| 393 |
+
"parent_law_id": instrument_id,
|
| 394 |
+
"article_id": source_id,
|
| 395 |
+
},
|
| 396 |
+
)
|
| 397 |
+
)
|
| 398 |
+
else:
|
| 399 |
+
for instrument_id, parent in law_map.items():
|
| 400 |
+
body = parent["body"]
|
| 401 |
+
if not body:
|
| 402 |
+
report["drops"]["empty_body"] += 1
|
| 403 |
+
if len(report["drop_samples"]["empty_body"]) < 20:
|
| 404 |
+
report["drop_samples"]["empty_body"].append(instrument_id)
|
| 405 |
+
continue
|
| 406 |
+
meta = parent["metadata"]
|
| 407 |
+
entries.append(
|
| 408 |
+
_base_record(
|
| 409 |
+
record_type="law",
|
| 410 |
+
source_dataset=source_dataset,
|
| 411 |
+
source_revision=source_revision,
|
| 412 |
+
instrument_id=instrument_id,
|
| 413 |
+
instrument_title=parent["instrument_title"],
|
| 414 |
+
law_cid=parent["law_cid"],
|
| 415 |
+
article_number="",
|
| 416 |
+
article_title="",
|
| 417 |
+
body=body,
|
| 418 |
+
jurisdiction=parent["jurisdiction"],
|
| 419 |
+
language=parent["language"],
|
| 420 |
+
source_url=parent["source_url"],
|
| 421 |
+
snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
|
| 422 |
+
coverage=_coverage_from(
|
| 423 |
+
parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback
|
| 424 |
+
),
|
| 425 |
+
license_expr=parent["license"],
|
| 426 |
+
collector=_collector(meta, source_dataset),
|
| 427 |
+
source_id=instrument_id,
|
| 428 |
+
extra={
|
| 429 |
+
"eli": parent["eli"],
|
| 430 |
+
"identifier": parent["identifier"],
|
| 431 |
+
"official_identifier": parent["official_identifier"],
|
| 432 |
+
"source_type": parent["source_type"],
|
| 433 |
+
"country": parent["country"],
|
| 434 |
+
"law_status": parent["law_status"],
|
| 435 |
+
"parent_law_id": "",
|
| 436 |
+
"article_id": "",
|
| 437 |
+
},
|
| 438 |
+
)
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
entries.sort(
|
| 442 |
+
key=lambda r: (
|
| 443 |
+
r["instrument_id"],
|
| 444 |
+
r.get("article_number") or "",
|
| 445 |
+
r["source_id"],
|
| 446 |
+
)
|
| 447 |
+
)
|
| 448 |
+
n_before = len(entries)
|
| 449 |
+
seen: set[str] = set()
|
| 450 |
+
deduped: list[dict[str, Any]] = []
|
| 451 |
+
for rec in entries:
|
| 452 |
+
cid = rec["entry_cid"]
|
| 453 |
+
if cid in seen:
|
| 454 |
+
report["drops"]["duplicate_cid"] += 1
|
| 455 |
+
report["drops"]["duplicate_source_kept_first"] += 1
|
| 456 |
+
if len(report["drop_samples"]["duplicate_cid"]) < 20:
|
| 457 |
+
report["drop_samples"]["duplicate_cid"].append(rec["source_id"])
|
| 458 |
+
continue
|
| 459 |
+
seen.add(cid)
|
| 460 |
+
deduped.append(rec)
|
| 461 |
+
for i, rec in enumerate(deduped):
|
| 462 |
+
rec["document_index"] = i
|
| 463 |
+
rec["corpus_index"] = i
|
| 464 |
+
|
| 465 |
+
df = pd.DataFrame(deduped)
|
| 466 |
+
if not df.empty and df["entry_cid"].duplicated().any():
|
| 467 |
+
raise SchemaError("Duplicate entry_cid remained after dedupe")
|
| 468 |
+
report["n_before_dedupe"] = n_before
|
| 469 |
+
report["n_out"] = int(len(df))
|
| 470 |
+
report["n_dropped_total"] = (
|
| 471 |
+
report["drops"]["empty_body"]
|
| 472 |
+
+ report["drops"]["missing_instrument"]
|
| 473 |
+
+ report["drops"]["duplicate_cid"]
|
| 474 |
+
)
|
| 475 |
+
if not df.empty:
|
| 476 |
+
report["language_breakdown"] = {
|
| 477 |
+
str(k): int(v) for k, v in df["language"].fillna("").value_counts().items()
|
| 478 |
+
}
|
| 479 |
+
report["record_type_breakdown"] = {
|
| 480 |
+
str(k): int(v) for k, v in df["record_type"].value_counts().items()
|
| 481 |
+
}
|
| 482 |
+
report["jurisdiction_breakdown"] = {
|
| 483 |
+
str(k): int(v) for k, v in df["jurisdiction"].fillna("").value_counts().items()
|
| 484 |
+
}
|
| 485 |
+
snapshot_dates = sorted({str(x) for x in df["snapshot_date"].fillna("") if str(x)})
|
| 486 |
+
report["snapshot_dates"] = snapshot_dates
|
| 487 |
+
else:
|
| 488 |
+
report["language_breakdown"] = {}
|
| 489 |
+
report["record_type_breakdown"] = {}
|
| 490 |
+
report["jurisdiction_breakdown"] = {}
|
| 491 |
+
report["snapshot_dates"] = []
|
| 492 |
+
|
| 493 |
+
all_article_count_zero = False
|
| 494 |
+
if "article_count" in laws.columns and len(laws):
|
| 495 |
+
try:
|
| 496 |
+
all_article_count_zero = int((laws["article_count"].fillna(0) == 0).sum()) == len(laws)
|
| 497 |
+
except Exception:
|
| 498 |
+
all_article_count_zero = False
|
| 499 |
+
|
| 500 |
+
report["quality_flags"] = {
|
| 501 |
+
"articles_table_empty": bool(articles_empty),
|
| 502 |
+
"sparse_article_fallback": bool(sparse_fallback),
|
| 503 |
+
"article_law_coverage": article_law_coverage,
|
| 504 |
+
"all_source_article_counts_zero": all_article_count_zero,
|
| 505 |
+
"article_extraction_status_counts": dict(extraction_statuses),
|
| 506 |
+
"missing_date": bool("date" in laws.columns and laws["date"].isna().all()) if len(laws) else False,
|
| 507 |
+
"missing_date_issued": bool("date_issued" in laws.columns and laws["date_issued"].isna().all()) if len(laws) else False,
|
| 508 |
+
"eli_present": bool("eli" in laws.columns and laws["eli"].notna().any()) if len(laws) else False,
|
| 509 |
+
"never_invented_legal_text": True,
|
| 510 |
+
"empty_bodies_dropped": report["drops"]["empty_body"],
|
| 511 |
+
"duplicate_cids_dropped": report["drops"]["duplicate_cid"],
|
| 512 |
+
}
|
| 513 |
+
df.attrs["normalization_report"] = report
|
| 514 |
+
return df, report
|
country_laws_ir/package.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write country-laws-ir-graphrag/v1 thin-client layout (SkillCenter / publicus-ir family)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import shutil
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from . import LAYOUT_FAMILY, MAX_ROWS_PER_FILE, SCHEMA_VERSION, __version__
|
| 13 |
+
from .catalog import target_repo
|
| 14 |
+
from .cidutil import file_descriptor
|
| 15 |
+
from .parquet_io import write_parquet, write_sharded
|
| 16 |
+
|
| 17 |
+
ADJ_POINTERS_PER_ROW = 4096
|
| 18 |
+
ADJ_POINTERS_PER_SHARD = 8192
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _index_df(rows: list[dict[str, Any]]) -> pd.DataFrame:
|
| 22 |
+
return pd.DataFrame(rows)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def package_release(
|
| 26 |
+
out: Path,
|
| 27 |
+
corpus: pd.DataFrame,
|
| 28 |
+
bm25: dict[str, Any],
|
| 29 |
+
graph: dict[str, Any],
|
| 30 |
+
vectors: dict[str, Any],
|
| 31 |
+
source_meta: dict[str, Any],
|
| 32 |
+
country: dict[str, Any],
|
| 33 |
+
code_root: Path,
|
| 34 |
+
normalization_report: dict[str, Any] | None = None,
|
| 35 |
+
) -> dict[str, Any]:
|
| 36 |
+
if out.exists():
|
| 37 |
+
shutil.rmtree(out)
|
| 38 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 39 |
+
indexes_dir = out / "indexes"
|
| 40 |
+
indexes_dir.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
|
| 42 |
+
corpus_idx = write_sharded(
|
| 43 |
+
corpus,
|
| 44 |
+
out / "data" / "corpus",
|
| 45 |
+
"data/corpus",
|
| 46 |
+
kind="corpus",
|
| 47 |
+
key_col="entry_cid",
|
| 48 |
+
index_col="document_index",
|
| 49 |
+
)
|
| 50 |
+
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 51 |
+
|
| 52 |
+
bm25_doc_idx = write_sharded(
|
| 53 |
+
bm25["documents"],
|
| 54 |
+
out / "data" / "bm25" / "documents",
|
| 55 |
+
"data/bm25/documents",
|
| 56 |
+
kind="bm25_documents",
|
| 57 |
+
key_col="entry_cid",
|
| 58 |
+
index_col="document_index",
|
| 59 |
+
)
|
| 60 |
+
write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
|
| 61 |
+
|
| 62 |
+
postings = bm25["postings"]
|
| 63 |
+
posting_idx = write_sharded(
|
| 64 |
+
postings,
|
| 65 |
+
out / "data" / "bm25" / "postings",
|
| 66 |
+
"data/bm25/postings",
|
| 67 |
+
kind="bm25_postings",
|
| 68 |
+
key_col="term",
|
| 69 |
+
)
|
| 70 |
+
for row, part_start in zip(posting_idx, range(len(posting_idx))):
|
| 71 |
+
shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE]
|
| 72 |
+
row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
|
| 73 |
+
row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
|
| 74 |
+
row["token_instance_count"] = row["posting_count"]
|
| 75 |
+
write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
|
| 76 |
+
|
| 77 |
+
node_idx = write_sharded(
|
| 78 |
+
graph["nodes"],
|
| 79 |
+
out / "data" / "graph" / "nodes",
|
| 80 |
+
"data/graph/nodes",
|
| 81 |
+
kind="graph_nodes",
|
| 82 |
+
key_col="node_cid",
|
| 83 |
+
)
|
| 84 |
+
write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
|
| 85 |
+
|
| 86 |
+
edge_idx = write_sharded(
|
| 87 |
+
graph["edges"],
|
| 88 |
+
out / "data" / "graph" / "edges",
|
| 89 |
+
"data/graph/edges",
|
| 90 |
+
kind="graph_edges",
|
| 91 |
+
key_col="edge_cid",
|
| 92 |
+
)
|
| 93 |
+
write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
|
| 94 |
+
|
| 95 |
+
incoming = graph["incoming"]
|
| 96 |
+
outgoing = graph["outgoing"]
|
| 97 |
+
in_idx = write_sharded(
|
| 98 |
+
incoming if incoming is not None and not incoming.empty else pd.DataFrame(
|
| 99 |
+
columns=["node_cid", "page_index", "direction"]
|
| 100 |
+
),
|
| 101 |
+
out / "data" / "graph" / "adjacency" / "incoming",
|
| 102 |
+
"data/graph/adjacency/incoming",
|
| 103 |
+
kind="graph_incoming_adjacency",
|
| 104 |
+
key_col="node_cid",
|
| 105 |
+
)
|
| 106 |
+
out_idx = write_sharded(
|
| 107 |
+
outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame(
|
| 108 |
+
columns=["node_cid", "page_index", "direction"]
|
| 109 |
+
),
|
| 110 |
+
out / "data" / "graph" / "adjacency" / "outgoing",
|
| 111 |
+
"data/graph/adjacency/outgoing",
|
| 112 |
+
kind="graph_outgoing_adjacency",
|
| 113 |
+
key_col="node_cid",
|
| 114 |
+
)
|
| 115 |
+
for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
|
| 116 |
+
for r in rows:
|
| 117 |
+
r["direction"] = direction
|
| 118 |
+
r["adjacency_count"] = r.get("row_count", 0)
|
| 119 |
+
r["node_count"] = r.get("row_count", 0)
|
| 120 |
+
r["first_page_index"] = 0
|
| 121 |
+
r["last_page_index"] = 0
|
| 122 |
+
write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
|
| 123 |
+
write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
|
| 124 |
+
|
| 125 |
+
vectors_df = vectors["vectors"]
|
| 126 |
+
# Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
|
| 127 |
+
if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all():
|
| 128 |
+
vectors_write = vectors_df.drop(columns=["embedding"])
|
| 129 |
+
vectors_write["embedding_status"] = "stub_missing"
|
| 130 |
+
else:
|
| 131 |
+
vectors_write = vectors_df
|
| 132 |
+
vec_idx = write_sharded(
|
| 133 |
+
vectors_write,
|
| 134 |
+
out / "data" / "vectors",
|
| 135 |
+
"data/vectors",
|
| 136 |
+
kind="vectors",
|
| 137 |
+
key_col="entry_cid",
|
| 138 |
+
index_col="document_index",
|
| 139 |
+
)
|
| 140 |
+
meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]}
|
| 141 |
+
for r in vec_idx:
|
| 142 |
+
m = meta_by_cluster.get(r["shard_id"], {})
|
| 143 |
+
r["centroid"] = m.get("centroid", [])
|
| 144 |
+
r["shard_centroid"] = m.get("shard_centroid", [])
|
| 145 |
+
r["centroid_min_score"] = m.get("centroid_min_score", 0.0)
|
| 146 |
+
r["centroid_shard_count"] = m.get("centroid_shard_count", 1)
|
| 147 |
+
r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0)
|
| 148 |
+
r["cluster_id"] = m.get("cluster_id", r["shard_id"])
|
| 149 |
+
r["dimension"] = 384
|
| 150 |
+
r["model_name"] = "thenlper/gte-small"
|
| 151 |
+
if m.get("stub"):
|
| 152 |
+
r["stub"] = True
|
| 153 |
+
r["stub_reason"] = m.get("stub_reason", "")
|
| 154 |
+
write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx))
|
| 155 |
+
|
| 156 |
+
# Bundle package + scripts into the release
|
| 157 |
+
pkg_src = Path(__file__).resolve().parent
|
| 158 |
+
dest_pkg = out / "country_laws_ir"
|
| 159 |
+
shutil.copytree(
|
| 160 |
+
pkg_src,
|
| 161 |
+
dest_pkg,
|
| 162 |
+
dirs_exist_ok=True,
|
| 163 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"),
|
| 164 |
+
)
|
| 165 |
+
scripts_dir = out / "scripts"
|
| 166 |
+
scripts_dir.mkdir(exist_ok=True)
|
| 167 |
+
for name in (
|
| 168 |
+
"build_country_laws_ir.py",
|
| 169 |
+
"normalize_country_laws.py",
|
| 170 |
+
"query_country_laws_hf.py",
|
| 171 |
+
"query_country_laws_ir.py",
|
| 172 |
+
"generate_country_laws_ir.py",
|
| 173 |
+
):
|
| 174 |
+
src = code_root / "scripts" / name
|
| 175 |
+
if src.exists():
|
| 176 |
+
shutil.copy2(src, scripts_dir / name)
|
| 177 |
+
shutil.copy2(pkg_src / "normalize.py", out / "normalize.py")
|
| 178 |
+
shutil.copy2(pkg_src / "query.py", out / "query.py")
|
| 179 |
+
shutil.copy2(pkg_src / "build.py", out / "build.py")
|
| 180 |
+
_write_skill(out, country, hub_id=target_repo(country["slug"]))
|
| 181 |
+
|
| 182 |
+
reports_dir = out / "reports"
|
| 183 |
+
reports_dir.mkdir(exist_ok=True)
|
| 184 |
+
if normalization_report is not None:
|
| 185 |
+
payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n"
|
| 186 |
+
(out / "normalization_report.json").write_text(payload, encoding="utf-8")
|
| 187 |
+
(reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
|
| 188 |
+
|
| 189 |
+
n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0
|
| 190 |
+
n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0
|
| 191 |
+
counts = {
|
| 192 |
+
"bm25_document_chunks": len(bm25_doc_idx),
|
| 193 |
+
"bm25_documents": int(len(bm25["documents"])),
|
| 194 |
+
"bm25_keyword_shards": len(posting_idx),
|
| 195 |
+
"bm25_posting_rows": int(len(postings)),
|
| 196 |
+
"bm25_postings": int(bm25["stats"]["n_postings"]),
|
| 197 |
+
"bm25_terms": int(bm25["stats"]["n_terms"]),
|
| 198 |
+
"corpus_chunks": len(corpus_idx),
|
| 199 |
+
"corpus_rows": int(len(corpus)),
|
| 200 |
+
"graph_edge_chunks": len(edge_idx),
|
| 201 |
+
"graph_edges": int(len(graph["edges"])),
|
| 202 |
+
"graph_incoming_adjacency_edges": int(len(graph["edges"])),
|
| 203 |
+
"graph_incoming_adjacency_rows": int(len(incoming)) if incoming is not None else 0,
|
| 204 |
+
"graph_incoming_adjacency_shards": len(in_idx),
|
| 205 |
+
"graph_node_chunks": len(node_idx),
|
| 206 |
+
"graph_nodes": int(len(graph["nodes"])),
|
| 207 |
+
"graph_outgoing_adjacency_edges": int(len(graph["edges"])),
|
| 208 |
+
"graph_outgoing_adjacency_rows": int(len(outgoing)) if outgoing is not None else 0,
|
| 209 |
+
"graph_outgoing_adjacency_shards": len(out_idx),
|
| 210 |
+
"vector_chunks": len(vec_idx),
|
| 211 |
+
"vector_rows": int(len(vectors_df)),
|
| 212 |
+
"n_laws": n_laws,
|
| 213 |
+
"n_articles": n_articles,
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
def idx_desc(name: str) -> dict[str, Any]:
|
| 217 |
+
path = indexes_dir / name
|
| 218 |
+
return file_descriptor(path, f"indexes/{name}")
|
| 219 |
+
|
| 220 |
+
hub_id = target_repo(country["slug"])
|
| 221 |
+
edge_types = graph["stats"].get("edge_types") or [
|
| 222 |
+
"HAS_JURISDICTION",
|
| 223 |
+
"HAS_LANGUAGE",
|
| 224 |
+
"BELONGS_TO_LAW",
|
| 225 |
+
"HAS_ARTICLE",
|
| 226 |
+
"BM25_NEIGHBOR_OF",
|
| 227 |
+
]
|
| 228 |
+
manifest = {
|
| 229 |
+
"schema_version": SCHEMA_VERSION,
|
| 230 |
+
"layout_family": LAYOUT_FAMILY,
|
| 231 |
+
"packager_version": __version__,
|
| 232 |
+
"primary_key": "entry_cid",
|
| 233 |
+
"dataset_id": source_meta["source_dataset"],
|
| 234 |
+
"dataset_repo_id": hub_id,
|
| 235 |
+
"dataset_revision": source_meta["source_revision"],
|
| 236 |
+
"country": country,
|
| 237 |
+
"disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
|
| 238 |
+
"bm25": {k: bm25["stats"][k] for k in (
|
| 239 |
+
"k1", "b", "title_weight", "body_weight", "average_document_length",
|
| 240 |
+
"tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
|
| 241 |
+
)},
|
| 242 |
+
"counts": counts,
|
| 243 |
+
"parquet": {
|
| 244 |
+
"compression": "zstd",
|
| 245 |
+
"compression_level": 6,
|
| 246 |
+
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 247 |
+
"row_group_size": MAX_ROWS_PER_FILE,
|
| 248 |
+
},
|
| 249 |
+
"graph": {
|
| 250 |
+
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
| 251 |
+
"adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD,
|
| 252 |
+
"directions": ["incoming", "outgoing"],
|
| 253 |
+
"max_remote_walk_depth": 8,
|
| 254 |
+
"ordering": "score_desc_nulls_last",
|
| 255 |
+
"edge_types": edge_types,
|
| 256 |
+
},
|
| 257 |
+
"vector": vectors["stats"],
|
| 258 |
+
"canonical_fields": [
|
| 259 |
+
"entry_cid",
|
| 260 |
+
"law_cid",
|
| 261 |
+
"record_type",
|
| 262 |
+
"jurisdiction",
|
| 263 |
+
"language",
|
| 264 |
+
"instrument_id",
|
| 265 |
+
"instrument_title",
|
| 266 |
+
"article_number",
|
| 267 |
+
"article_title",
|
| 268 |
+
"title",
|
| 269 |
+
"body",
|
| 270 |
+
"source_url",
|
| 271 |
+
"snapshot_date",
|
| 272 |
+
"coverage",
|
| 273 |
+
"license",
|
| 274 |
+
"collector",
|
| 275 |
+
"source_dataset",
|
| 276 |
+
"source_revision",
|
| 277 |
+
],
|
| 278 |
+
"input_sha256": {
|
| 279 |
+
"laws.parquet": source_meta.get("laws_sha256"),
|
| 280 |
+
"articles.parquet": source_meta.get("articles_sha256"),
|
| 281 |
+
},
|
| 282 |
+
"model_id": (vectors.get("stats") or {}).get("model_name", "thenlper/gte-small"),
|
| 283 |
+
"cid": {
|
| 284 |
+
"codec": "raw",
|
| 285 |
+
"hash": "sha2-256",
|
| 286 |
+
"multibase": "base32",
|
| 287 |
+
"payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')",
|
| 288 |
+
},
|
| 289 |
+
"normalization": normalization_report or {},
|
| 290 |
+
"schema_mapping": {
|
| 291 |
+
"laws": {
|
| 292 |
+
"id": "instrument_id",
|
| 293 |
+
"title": "instrument_title",
|
| 294 |
+
"text": "body",
|
| 295 |
+
"article_count_dtype_source": source_meta.get("article_count_dtype"),
|
| 296 |
+
},
|
| 297 |
+
"articles": {
|
| 298 |
+
"id": "source_id / article identity",
|
| 299 |
+
"law_id": "instrument_id",
|
| 300 |
+
"title": "article_title",
|
| 301 |
+
"text": "body",
|
| 302 |
+
},
|
| 303 |
+
"unit_policy": "prefer articles; fall back to law-level when articles empty",
|
| 304 |
+
"required_law_columns": ["id", "title", "text"],
|
| 305 |
+
"required_article_columns": ["id", "law_id", "title", "text"],
|
| 306 |
+
"fail_closed": True,
|
| 307 |
+
"notes": (
|
| 308 |
+
"Malta and Germany share the same column names. Drift: Malta article_count "
|
| 309 |
+
"is int64, Germany article_count is int32; Germany eli is often null. "
|
| 310 |
+
"Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family."
|
| 311 |
+
),
|
| 312 |
+
},
|
| 313 |
+
"indexes": {
|
| 314 |
+
"bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"),
|
| 315 |
+
"bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"),
|
| 316 |
+
"corpus_chunks": idx_desc("corpus_chunks.parquet"),
|
| 317 |
+
"graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"),
|
| 318 |
+
"graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"),
|
| 319 |
+
"graph_node_chunks": idx_desc("graph_node_chunks.parquet"),
|
| 320 |
+
"graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"),
|
| 321 |
+
"vector_chunks": idx_desc("vector_chunks.parquet"),
|
| 322 |
+
},
|
| 323 |
+
"source": source_meta,
|
| 324 |
+
}
|
| 325 |
+
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 326 |
+
_write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id)
|
| 327 |
+
_write_gitattributes(out)
|
| 328 |
+
return manifest
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _write_gitattributes(out: Path) -> None:
|
| 332 |
+
(out / ".gitattributes").write_text(
|
| 333 |
+
"*.parquet filter=lfs diff=lfs merge=lfs -text\n"
|
| 334 |
+
"*.bin filter=lfs diff=lfs merge=lfs -text\n",
|
| 335 |
+
encoding="utf-8",
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def _write_readme(
|
| 340 |
+
out: Path,
|
| 341 |
+
country: dict[str, Any],
|
| 342 |
+
source_meta: dict[str, Any],
|
| 343 |
+
counts: dict[str, Any],
|
| 344 |
+
bm25_stats: dict[str, Any],
|
| 345 |
+
graph_stats: dict[str, Any],
|
| 346 |
+
vector_stats: dict[str, Any],
|
| 347 |
+
hub_id: str,
|
| 348 |
+
) -> None:
|
| 349 |
+
slug = country["slug"]
|
| 350 |
+
name = country["name"]
|
| 351 |
+
src = source_meta["source_dataset"]
|
| 352 |
+
rev = source_meta["source_revision"]
|
| 353 |
+
vec_status = vector_stats.get("status", "embedded")
|
| 354 |
+
text = f"""---
|
| 355 |
+
license: other
|
| 356 |
+
task_categories:
|
| 357 |
+
- text-retrieval
|
| 358 |
+
tags:
|
| 359 |
+
- legal
|
| 360 |
+
- law
|
| 361 |
+
- graphrag
|
| 362 |
+
- bm25
|
| 363 |
+
- research
|
| 364 |
+
- not-legal-advice
|
| 365 |
+
- {slug}
|
| 366 |
+
pretty_name: {name} laws IR (CID-keyed GraphRAG)
|
| 367 |
+
configs:
|
| 368 |
+
- config_name: corpus
|
| 369 |
+
data_files:
|
| 370 |
+
- split: train
|
| 371 |
+
path: data/corpus/*.parquet
|
| 372 |
+
- config_name: bm25_documents
|
| 373 |
+
data_files:
|
| 374 |
+
- split: train
|
| 375 |
+
path: data/bm25/documents/*.parquet
|
| 376 |
+
- config_name: bm25_postings
|
| 377 |
+
data_files:
|
| 378 |
+
- split: train
|
| 379 |
+
path: data/bm25/postings/*.parquet
|
| 380 |
+
- config_name: bm25_keyword_index
|
| 381 |
+
data_files:
|
| 382 |
+
- split: train
|
| 383 |
+
path: indexes/bm25_keyword_shards.parquet
|
| 384 |
+
- config_name: vectors
|
| 385 |
+
data_files:
|
| 386 |
+
- split: train
|
| 387 |
+
path: data/vectors/*.parquet
|
| 388 |
+
- config_name: vector_meta_index
|
| 389 |
+
data_files:
|
| 390 |
+
- split: train
|
| 391 |
+
path: indexes/vector_chunks.parquet
|
| 392 |
+
- config_name: graph_nodes
|
| 393 |
+
data_files:
|
| 394 |
+
- split: train
|
| 395 |
+
path: data/graph/nodes/*.parquet
|
| 396 |
+
- config_name: graph_edges
|
| 397 |
+
data_files:
|
| 398 |
+
- split: train
|
| 399 |
+
path: data/graph/edges/*.parquet
|
| 400 |
+
- config_name: graph_outgoing_adjacency
|
| 401 |
+
data_files:
|
| 402 |
+
- split: train
|
| 403 |
+
path: data/graph/adjacency/outgoing/*.parquet
|
| 404 |
+
- config_name: graph_incoming_adjacency
|
| 405 |
+
data_files:
|
| 406 |
+
- split: train
|
| 407 |
+
path: data/graph/adjacency/incoming/*.parquet
|
| 408 |
+
---
|
| 409 |
+
|
| 410 |
+
# {name} legislation IR (CID-keyed sparse GraphRAG)
|
| 411 |
+
|
| 412 |
+
Research retrieval release of `{src}` (revision `{rev}`) packaged as
|
| 413 |
+
`{SCHEMA_VERSION}` (layout family `{LAYOUT_FAMILY}` / publicus-ir).
|
| 414 |
+
|
| 415 |
+
**Not legal advice.** This is a research snapshot. The official gazette /
|
| 416 |
+
authentic source of {name} prevails over this corpus. Retrieved documents
|
| 417 |
+
and graph edges are retrieval evidence only. No legal text was invented.
|
| 418 |
+
|
| 419 |
+
Primary key: `entry_cid` (CIDv1 raw sha2-256 of a canonical identity record).
|
| 420 |
+
Integer `document_index` values are compact shard pointers, not identities.
|
| 421 |
+
|
| 422 |
+
Target Hub id (packaging metadata only): `{hub_id}`.
|
| 423 |
+
|
| 424 |
+
## Counts
|
| 425 |
+
|
| 426 |
+
| Field | Value |
|
| 427 |
+
| --- | --- |
|
| 428 |
+
| Laws (corpus units) | {counts['n_laws']} |
|
| 429 |
+
| Articles (corpus units) | {counts['n_articles']} |
|
| 430 |
+
| Canonical docs | {counts['corpus_rows']} |
|
| 431 |
+
| BM25 terms | {counts['bm25_terms']} |
|
| 432 |
+
| BM25 postings | {counts['bm25_postings']} |
|
| 433 |
+
| Graph nodes | {counts['graph_nodes']} |
|
| 434 |
+
| Graph edges | {counts['graph_edges']} |
|
| 435 |
+
| Vectors | {counts['vector_rows']} × {vector_stats['dimension']}-d `{vector_stats['model_name']}` ({vec_status}) |
|
| 436 |
+
|
| 437 |
+
## Canonical fields
|
| 438 |
+
|
| 439 |
+
`entry_cid`, `law_cid`, `record_type`, `jurisdiction`, `language`,
|
| 440 |
+
`instrument_id`, `instrument_title`, `article_number`, `article_title`,
|
| 441 |
+
`title`, `body`, `source_url`, `snapshot_date`, `coverage`, `license`,
|
| 442 |
+
`collector`, `source_dataset`, `source_revision`.
|
| 443 |
+
|
| 444 |
+
Unit policy: prefer article/section rows; fall back to law-level when
|
| 445 |
+
`articles.parquet` is empty.
|
| 446 |
+
|
| 447 |
+
## Index layout
|
| 448 |
+
|
| 449 |
+
Zstandard parquet shards with at most 4,096 rows.
|
| 450 |
+
|
| 451 |
+
- `indexes/bm25_keyword_shards.parquet` — lexical term ranges → BM25 posting shards
|
| 452 |
+
- `indexes/vector_chunks.parquet` — semantic routing centroids (rows sorted by cosine to shard centroid)
|
| 453 |
+
- `indexes/corpus_chunks.parquet` — document ranges → corpus shards
|
| 454 |
+
- `data/graph/nodes` / `data/graph/edges` — property graph
|
| 455 |
+
- `data/graph/adjacency/{{incoming,outgoing}}` — score-ordered neighbor pages
|
| 456 |
+
|
| 457 |
+
BM25: Okapi k1=1.2, b=0.75, title_weight=5, body_weight=1 (FTS5 unicode61-style tokenizer).
|
| 458 |
+
|
| 459 |
+
Graph: one node per `entry_cid` plus facet nodes (`_facet_cid(kind, value)` for
|
| 460 |
+
jurisdiction, language, instrument, source, status). Neighbor edges
|
| 461 |
+
`BM25_NEIGHBOR_OF` (k=8) carry score and matched terms. Structural edges:
|
| 462 |
+
`ARTICLE_OF` (article → parent law) when articles exist, plus `IDENTIFIED_BY_ELI`
|
| 463 |
+
/ `IDENTIFIED_BY` only when those identifiers are present in the source.
|
| 464 |
+
|
| 465 |
+
## Query
|
| 466 |
+
|
| 467 |
+
```
|
| 468 |
+
python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 10
|
| 469 |
+
python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 10
|
| 470 |
+
python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
|
| 471 |
+
```
|
| 472 |
+
|
| 473 |
+
## Publish later (operator)
|
| 474 |
+
|
| 475 |
+
```
|
| 476 |
+
export HF_TOKEN=... # never commit
|
| 477 |
+
hf upload-large-folder {hub_id} . \\
|
| 478 |
+
--repo-type dataset --no-private --num-workers 8 \\
|
| 479 |
+
--exclude "**/__pycache__/**" --exclude "**/*.pyc"
|
| 480 |
+
```
|
| 481 |
+
|
| 482 |
+
## Provenance
|
| 483 |
+
|
| 484 |
+
Packaged by country-laws-ir. Upstream collector and official license remain those
|
| 485 |
+
of `{src}`. CIDs identify local content; they do not prove public IPFS pinning.
|
| 486 |
+
"""
|
| 487 |
+
(out / "README.md").write_text(text, encoding="utf-8")
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def _write_skill(out: Path, country: dict[str, Any], hub_id: str) -> None:
|
| 491 |
+
skill_dir = out / "skill" / "query-country-laws-hf"
|
| 492 |
+
skill_dir.mkdir(parents=True, exist_ok=True)
|
| 493 |
+
name = country.get("name") or country.get("slug")
|
| 494 |
+
slug = country.get("slug")
|
| 495 |
+
text = f"""---
|
| 496 |
+
name: query-country-laws-hf
|
| 497 |
+
description: Query a local or Hub country-laws-ir GraphRAG release (BM25, vectors, graph neighbors). Research retrieval only — not legal advice.
|
| 498 |
+
---
|
| 499 |
+
|
| 500 |
+
# Query country-laws-ir (SkillCenter-style sparse GraphRAG)
|
| 501 |
+
|
| 502 |
+
Thin client for `{hub_id}` / local release roots that follow
|
| 503 |
+
`country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3`).
|
| 504 |
+
|
| 505 |
+
**Not legal advice.** Official gazettes prevail. Retrieved hits are context only.
|
| 506 |
+
|
| 507 |
+
## Local
|
| 508 |
+
|
| 509 |
+
```bash
|
| 510 |
+
python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 5
|
| 511 |
+
python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 5
|
| 512 |
+
python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
|
| 513 |
+
```
|
| 514 |
+
|
| 515 |
+
Or:
|
| 516 |
+
|
| 517 |
+
```bash
|
| 518 |
+
python -m country_laws_ir query --local-dir /workspace/country-laws-ir/releases/ipfs_{slug}_laws_ir -- bm25 "constitution"
|
| 519 |
+
```
|
| 520 |
+
|
| 521 |
+
## Method
|
| 522 |
+
|
| 523 |
+
- Primary key `entry_cid` (CIDv1 raw sha2-256). `document_index` is a shard pointer.
|
| 524 |
+
- BM25 Okapi k1=1.2 b=0.75, title_weight=5, body_weight=1, FTS5-style tokenizer.
|
| 525 |
+
- Vectors `thenlper/gte-small` 384-d, mean-pool, L2, centroid-sorted shards.
|
| 526 |
+
- Graph: facets + `BM25_NEIGHBOR_OF` (k=8, score + matched terms) + `ARTICLE_OF`.
|
| 527 |
+
|
| 528 |
+
Do not treat retrieval as proof. Do not invent citations.
|
| 529 |
+
"""
|
| 530 |
+
(skill_dir / "SKILL.md").write_text(text, encoding="utf-8")
|
country_laws_ir/parquet_io.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ZSTD parquet shard writer matching skillcenter-huggingface-release/v3."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Iterable
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import pyarrow as pa
|
| 11 |
+
import pyarrow.parquet as pq
|
| 12 |
+
|
| 13 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 14 |
+
from .cidutil import file_descriptor
|
| 15 |
+
|
| 16 |
+
COMPRESSION = "zstd"
|
| 17 |
+
COMPRESSION_LEVEL = 6
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def write_parquet(path: Path, df: pd.DataFrame) -> None:
|
| 21 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
table = pa.Table.from_pandas(df, preserve_index=False)
|
| 23 |
+
pq.write_table(
|
| 24 |
+
table,
|
| 25 |
+
path,
|
| 26 |
+
compression=COMPRESSION,
|
| 27 |
+
compression_level=COMPRESSION_LEVEL,
|
| 28 |
+
row_group_size=min(MAX_ROWS_PER_FILE, max(len(df), 1)),
|
| 29 |
+
use_dictionary=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def shard_frames(df: pd.DataFrame, max_rows: int = MAX_ROWS_PER_FILE) -> list[pd.DataFrame]:
|
| 34 |
+
if df.empty:
|
| 35 |
+
return [df.copy()]
|
| 36 |
+
n = int(math.ceil(len(df) / max_rows))
|
| 37 |
+
return [df.iloc[i * max_rows : (i + 1) * max_rows].copy() for i in range(n)]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def write_sharded(
|
| 41 |
+
df: pd.DataFrame,
|
| 42 |
+
out_dir: Path,
|
| 43 |
+
relative_dir: str,
|
| 44 |
+
kind: str,
|
| 45 |
+
key_col: str | None = None,
|
| 46 |
+
index_col: str | None = None,
|
| 47 |
+
extra_index: dict | None = None,
|
| 48 |
+
) -> list[dict[str, Any]]:
|
| 49 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
shards = shard_frames(df)
|
| 51 |
+
rows: list[dict[str, Any]] = []
|
| 52 |
+
for i, part in enumerate(shards):
|
| 53 |
+
name = f"part-{i:06d}.parquet"
|
| 54 |
+
path = out_dir / name
|
| 55 |
+
write_parquet(path, part)
|
| 56 |
+
rel = f"{relative_dir}/{name}"
|
| 57 |
+
first_key = last_key = ""
|
| 58 |
+
if key_col and key_col in part.columns and not part.empty:
|
| 59 |
+
keys = part[key_col].astype(str)
|
| 60 |
+
first_key = keys.iloc[0]
|
| 61 |
+
last_key = keys.iloc[-1]
|
| 62 |
+
start_idx = end_idx = 0
|
| 63 |
+
if index_col and index_col in part.columns and not part.empty:
|
| 64 |
+
start_idx = int(part[index_col].iloc[0])
|
| 65 |
+
end_idx = int(part[index_col].iloc[-1])
|
| 66 |
+
desc = file_descriptor(
|
| 67 |
+
path,
|
| 68 |
+
rel,
|
| 69 |
+
extra={
|
| 70 |
+
"shard_id": i,
|
| 71 |
+
"kind": kind,
|
| 72 |
+
"row_count": int(len(part)),
|
| 73 |
+
"first_key": first_key,
|
| 74 |
+
"last_key": last_key,
|
| 75 |
+
"start_document_index": start_idx,
|
| 76 |
+
"end_document_index": end_idx,
|
| 77 |
+
"schema_version": SCHEMA_VERSION,
|
| 78 |
+
},
|
| 79 |
+
)
|
| 80 |
+
if extra_index:
|
| 81 |
+
desc.update(extra_index)
|
| 82 |
+
rows.append(desc)
|
| 83 |
+
return rows
|
country_laws_ir/query.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Thin-client query for country-laws IR releases (local dir)."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
K1 = 1.2
|
| 15 |
+
B = 0.75
|
| 16 |
+
TITLE_WEIGHT = 5.0
|
| 17 |
+
BODY_WEIGHT = 1.0
|
| 18 |
+
MAX_QUERY_TERMS = 64
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def tokenize(text: str) -> list[str]:
|
| 22 |
+
import re
|
| 23 |
+
import unicodedata
|
| 24 |
+
|
| 25 |
+
if not text:
|
| 26 |
+
return []
|
| 27 |
+
nfkd = unicodedata.normalize("NFKD", text)
|
| 28 |
+
folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
|
| 29 |
+
return re.findall(r"[0-9A-Za-z]+", folded)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Release:
|
| 33 |
+
def __init__(self, root: Path):
|
| 34 |
+
self.root = Path(root)
|
| 35 |
+
self.manifest = json.loads((self.root / "manifest.json").read_text(encoding="utf-8"))
|
| 36 |
+
|
| 37 |
+
def _read(self, rel: str) -> pd.DataFrame:
|
| 38 |
+
path = self.root / rel
|
| 39 |
+
if path.is_dir():
|
| 40 |
+
files = sorted(path.glob("*.parquet"))
|
| 41 |
+
return pd.concat([pd.read_parquet(f) for f in files], ignore_index=True) if files else pd.DataFrame()
|
| 42 |
+
return pd.read_parquet(path)
|
| 43 |
+
|
| 44 |
+
def bm25(self, query: str, top_k: int = 10) -> list[dict]:
|
| 45 |
+
q_terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 46 |
+
if not q_terms:
|
| 47 |
+
return []
|
| 48 |
+
shards = pd.read_parquet(self.root / "indexes" / "bm25_keyword_shards.parquet")
|
| 49 |
+
needed = set()
|
| 50 |
+
for term in q_terms:
|
| 51 |
+
hit = shards[(shards["first_key"] <= term) & (shards["last_key"] >= term)]
|
| 52 |
+
if hit.empty:
|
| 53 |
+
hit = shards
|
| 54 |
+
for rel in hit["relative_path"].tolist():
|
| 55 |
+
needed.add(rel)
|
| 56 |
+
postings = pd.concat(
|
| 57 |
+
[pd.read_parquet(self.root / rel) for rel in sorted(needed)],
|
| 58 |
+
ignore_index=True,
|
| 59 |
+
)
|
| 60 |
+
postings = postings[postings["term"].isin(q_terms)]
|
| 61 |
+
docs = self._read("data/bm25/documents")
|
| 62 |
+
avgdl = float(self.manifest["bm25"]["average_document_length"]) or 1.0
|
| 63 |
+
scores: dict[int, float] = defaultdict(float)
|
| 64 |
+
for rec in postings.itertuples(index=False):
|
| 65 |
+
idf = float(rec.idf)
|
| 66 |
+
for di, ttf, btf, dl in zip(
|
| 67 |
+
rec.document_indices, rec.title_frequencies, rec.body_frequencies, rec.document_lengths
|
| 68 |
+
):
|
| 69 |
+
tf = TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf)
|
| 70 |
+
denom = tf + K1 * (1.0 - B + B * (int(dl) / avgdl))
|
| 71 |
+
if denom:
|
| 72 |
+
scores[int(di)] += idf * (tf * (K1 + 1.0)) / denom
|
| 73 |
+
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:top_k]
|
| 74 |
+
by_idx = docs.set_index("document_index")
|
| 75 |
+
out = []
|
| 76 |
+
for di, score in ranked:
|
| 77 |
+
row = by_idx.loc[di]
|
| 78 |
+
out.append(
|
| 79 |
+
{
|
| 80 |
+
"document_index": int(di),
|
| 81 |
+
"entry_cid": row["entry_cid"],
|
| 82 |
+
"title": row["title"],
|
| 83 |
+
"record_type": row["record_type"],
|
| 84 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 85 |
+
"law_cid": row.get("law_cid", ""),
|
| 86 |
+
"score": float(score),
|
| 87 |
+
}
|
| 88 |
+
)
|
| 89 |
+
return out
|
| 90 |
+
|
| 91 |
+
def vector(self, query: str, top_k: int = 10, candidate_centroids: int = 4, device: str = "cpu") -> list[dict]:
|
| 92 |
+
status = (self.manifest.get("vector") or {}).get("status")
|
| 93 |
+
if status == "stub":
|
| 94 |
+
return [{"error": "vectors are stubbed", "reason": self.manifest["vector"].get("stub_reason")}]
|
| 95 |
+
from sentence_transformers import SentenceTransformer
|
| 96 |
+
|
| 97 |
+
model = SentenceTransformer(self.manifest["vector"]["model_name"], device=device)
|
| 98 |
+
q = model.encode([query], normalize_embeddings=True, convert_to_numpy=True)[0].astype(np.float32)
|
| 99 |
+
meta = pd.read_parquet(self.root / "indexes" / "vector_chunks.parquet")
|
| 100 |
+
cents = np.stack(meta["centroid"].map(lambda c: np.asarray(c, dtype=np.float32)).to_numpy())
|
| 101 |
+
sims = cents @ q
|
| 102 |
+
order = np.argsort(-sims)[: max(1, candidate_centroids)]
|
| 103 |
+
shards = meta.iloc[order]
|
| 104 |
+
frames = [pd.read_parquet(self.root / rel) for rel in shards["relative_path"].tolist()]
|
| 105 |
+
vecs = pd.concat(frames, ignore_index=True)
|
| 106 |
+
if "embedding" not in vecs.columns or vecs["embedding"].isna().all():
|
| 107 |
+
return [{"error": "vector shard missing embeddings"}]
|
| 108 |
+
emb = np.stack(vecs["embedding"].map(lambda e: np.asarray(e, dtype=np.float32)).to_numpy())
|
| 109 |
+
scores = emb @ q
|
| 110 |
+
top = np.argsort(-scores)[:top_k]
|
| 111 |
+
out = []
|
| 112 |
+
for i in top:
|
| 113 |
+
row = vecs.iloc[int(i)]
|
| 114 |
+
out.append(
|
| 115 |
+
{
|
| 116 |
+
"document_index": int(row["document_index"]),
|
| 117 |
+
"entry_cid": row["entry_cid"],
|
| 118 |
+
"title": row["title"],
|
| 119 |
+
"record_type": row["record_type"],
|
| 120 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 121 |
+
"score": float(scores[int(i)]),
|
| 122 |
+
}
|
| 123 |
+
)
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]:
|
| 127 |
+
dirs = ["incoming", "outgoing"] if direction == "both" else [direction]
|
| 128 |
+
hits = []
|
| 129 |
+
for d in dirs:
|
| 130 |
+
path = self.root / "data" / "graph" / "adjacency" / d
|
| 131 |
+
files = sorted(path.glob("*.parquet"))
|
| 132 |
+
for f in files:
|
| 133 |
+
df = pd.read_parquet(f)
|
| 134 |
+
sub = df[df["node_cid"] == node_cid]
|
| 135 |
+
for rec in sub.itertuples(index=False):
|
| 136 |
+
for i, neigh in enumerate(rec.neighbor_cids):
|
| 137 |
+
hits.append(
|
| 138 |
+
{
|
| 139 |
+
"direction": d,
|
| 140 |
+
"node_cid": node_cid,
|
| 141 |
+
"neighbor_cid": neigh,
|
| 142 |
+
"edge_type": rec.edge_types[i] if i < len(rec.edge_types) else "",
|
| 143 |
+
"score": rec.scores[i] if rec.scores is not None and i < len(rec.scores) else None,
|
| 144 |
+
}
|
| 145 |
+
)
|
| 146 |
+
hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
|
| 147 |
+
return hits[:limit]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _print(rows: list[dict]) -> None:
|
| 151 |
+
print(json.dumps(rows, indent=2, ensure_ascii=False))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def main(argv: list[str] | None = None) -> int:
|
| 155 |
+
ap = argparse.ArgumentParser(description="Query a country-laws IR release")
|
| 156 |
+
ap.add_argument("--local-dir", required=True, help="Path to local release root")
|
| 157 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 158 |
+
|
| 159 |
+
p_bm = sub.add_parser("bm25")
|
| 160 |
+
p_bm.add_argument("query")
|
| 161 |
+
p_bm.add_argument("--top-k", type=int, default=10)
|
| 162 |
+
|
| 163 |
+
p_vec = sub.add_parser("vector")
|
| 164 |
+
p_vec.add_argument("query")
|
| 165 |
+
p_vec.add_argument("--top-k", type=int, default=10)
|
| 166 |
+
p_vec.add_argument("--candidate-centroids", type=int, default=4)
|
| 167 |
+
p_vec.add_argument("--device", default="cpu")
|
| 168 |
+
|
| 169 |
+
p_g = sub.add_parser("graph")
|
| 170 |
+
g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
|
| 171 |
+
p_n = g_sub.add_parser("neighbors")
|
| 172 |
+
p_n.add_argument("node_cid")
|
| 173 |
+
p_n.add_argument("--direction", default="both", choices=["both", "incoming", "outgoing"])
|
| 174 |
+
p_n.add_argument("--limit", type=int, default=25)
|
| 175 |
+
|
| 176 |
+
args = ap.parse_args(argv)
|
| 177 |
+
rel = Release(Path(args.local_dir))
|
| 178 |
+
if args.cmd == "bm25":
|
| 179 |
+
_print(rel.bm25(args.query, top_k=args.top_k))
|
| 180 |
+
elif args.cmd == "vector":
|
| 181 |
+
_print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
|
| 182 |
+
elif args.cmd == "graph" and args.graph_cmd == "neighbors":
|
| 183 |
+
_print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
|
| 184 |
+
return 0
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if __name__ == "__main__":
|
| 188 |
+
raise SystemExit(main())
|
country_laws_ir/schema.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail-closed schema mapping for endomorphosis/ipfs_*_laws parquet tables.
|
| 2 |
+
|
| 3 |
+
Verified 2026-09-03 against Malta (pilot) and Germany (column-drift check):
|
| 4 |
+
|
| 5 |
+
Laws columns (both countries):
|
| 6 |
+
id, title, text, source_url, source_type, jurisdiction, country, language,
|
| 7 |
+
eli, date, date_issued, retrieved_at, license, law_status, identifier,
|
| 8 |
+
official_identifier, article_count, json_path, metadata_json
|
| 9 |
+
|
| 10 |
+
Drift: Malta article_count is int64; Germany article_count is int32.
|
| 11 |
+
Germany eli is frequently null. Neither is a missing identifier.
|
| 12 |
+
|
| 13 |
+
Articles columns (both countries; Malta snapshot has 0 rows):
|
| 14 |
+
law_id, id, title, text, source_url, document_number, article_number,
|
| 15 |
+
record_type, metadata_json
|
| 16 |
+
|
| 17 |
+
Required identity columns are NOT invented. Missing required identifiers
|
| 18 |
+
fail the build.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
REQUIRED_LAW_COLUMNS = ("id", "title", "text")
|
| 24 |
+
REQUIRED_ARTICLE_COLUMNS = ("id", "law_id", "title", "text")
|
| 25 |
+
|
| 26 |
+
OPTIONAL_LAW_COLUMNS = (
|
| 27 |
+
"source_url",
|
| 28 |
+
"source_type",
|
| 29 |
+
"jurisdiction",
|
| 30 |
+
"country",
|
| 31 |
+
"language",
|
| 32 |
+
"eli",
|
| 33 |
+
"date",
|
| 34 |
+
"date_issued",
|
| 35 |
+
"retrieved_at",
|
| 36 |
+
"license",
|
| 37 |
+
"law_status",
|
| 38 |
+
"identifier",
|
| 39 |
+
"official_identifier",
|
| 40 |
+
"article_count",
|
| 41 |
+
"json_path",
|
| 42 |
+
"metadata_json",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
OPTIONAL_ARTICLE_COLUMNS = (
|
| 46 |
+
"source_url",
|
| 47 |
+
"document_number",
|
| 48 |
+
"article_number",
|
| 49 |
+
"record_type",
|
| 50 |
+
"metadata_json",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Canonical field mapping used in the CID-keyed corpus.
|
| 54 |
+
LAW_FIELD_MAP = {
|
| 55 |
+
"source_id": "id",
|
| 56 |
+
"title": "title",
|
| 57 |
+
"body": "text",
|
| 58 |
+
"source_url": "source_url",
|
| 59 |
+
"source_type": "source_type",
|
| 60 |
+
"jurisdiction": "jurisdiction",
|
| 61 |
+
"country": "country",
|
| 62 |
+
"language": "language",
|
| 63 |
+
"eli": "eli",
|
| 64 |
+
"date": "date",
|
| 65 |
+
"date_issued": "date_issued",
|
| 66 |
+
"retrieved_at": "retrieved_at",
|
| 67 |
+
"license_expression": "license",
|
| 68 |
+
"law_status": "law_status",
|
| 69 |
+
"identifier": "identifier",
|
| 70 |
+
"official_identifier": "official_identifier",
|
| 71 |
+
"article_count": "article_count",
|
| 72 |
+
"metadata_json": "metadata_json",
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
ARTICLE_FIELD_MAP = {
|
| 76 |
+
"source_id": "id",
|
| 77 |
+
"law_id": "law_id",
|
| 78 |
+
"title": "title",
|
| 79 |
+
"body": "text",
|
| 80 |
+
"source_url": "source_url",
|
| 81 |
+
"document_number": "document_number",
|
| 82 |
+
"article_number": "article_number",
|
| 83 |
+
"record_type_src": "record_type",
|
| 84 |
+
"metadata_json": "metadata_json",
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SchemaError(ValueError):
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _cols(df) -> set[str]:
|
| 93 |
+
return set(map(str, df.columns))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def validate_laws(df) -> None:
|
| 97 |
+
missing = [c for c in REQUIRED_LAW_COLUMNS if c not in _cols(df)]
|
| 98 |
+
if missing:
|
| 99 |
+
raise SchemaError(
|
| 100 |
+
f"laws.parquet missing required identifier/content columns {missing}; "
|
| 101 |
+
f"present={sorted(_cols(df))}. Fail closed — will not invent ids."
|
| 102 |
+
)
|
| 103 |
+
null_ids = int(df["id"].isna().sum()) if "id" in df.columns else len(df)
|
| 104 |
+
empty_ids = int((df["id"].astype(str).str.strip() == "").sum()) if "id" in df.columns else 0
|
| 105 |
+
if null_ids or empty_ids:
|
| 106 |
+
raise SchemaError(
|
| 107 |
+
f"laws.parquet has {null_ids} null and {empty_ids} empty id values. Fail closed."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def validate_articles(df) -> None:
|
| 112 |
+
if df is None or df.empty:
|
| 113 |
+
return
|
| 114 |
+
missing = [c for c in REQUIRED_ARTICLE_COLUMNS if c not in _cols(df)]
|
| 115 |
+
if missing:
|
| 116 |
+
raise SchemaError(
|
| 117 |
+
f"articles.parquet missing required identifier/content columns {missing}; "
|
| 118 |
+
f"present={sorted(_cols(df))}. Fail closed — will not invent ids."
|
| 119 |
+
)
|
| 120 |
+
null_ids = int(df["id"].isna().sum())
|
| 121 |
+
null_law = int(df["law_id"].isna().sum())
|
| 122 |
+
empty_ids = int((df["id"].astype(str).str.strip() == "").sum())
|
| 123 |
+
empty_law = int((df["law_id"].astype(str).str.strip() == "").sum())
|
| 124 |
+
if null_ids or empty_ids or null_law or empty_law:
|
| 125 |
+
raise SchemaError(
|
| 126 |
+
f"articles.parquet has null/empty identifiers "
|
| 127 |
+
f"(id null={null_ids} empty={empty_ids}; law_id null={null_law} empty={empty_law}). Fail closed."
|
| 128 |
+
)
|
country_laws_ir/tokenize.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FTS5 unicode61 remove_diacritics=2-style tokenizer."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
import unicodedata
|
| 7 |
+
|
| 8 |
+
_TOKEN_RE = re.compile(r"[0-9A-Za-z]+", re.UNICODE)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def fold_diacritics(text: str) -> str:
|
| 12 |
+
if not text:
|
| 13 |
+
return ""
|
| 14 |
+
nfkd = unicodedata.normalize("NFKD", text)
|
| 15 |
+
return "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def tokenize(text: str | None) -> list[str]:
|
| 19 |
+
if not text:
|
| 20 |
+
return []
|
| 21 |
+
return _TOKEN_RE.findall(fold_diacritics(str(text)))
|
country_laws_ir/upload.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hub upload is intentionally not implemented in this local pipeline.
|
| 2 |
+
|
| 3 |
+
Later publish (operator machine, never from this run):
|
| 4 |
+
|
| 5 |
+
export HF_TOKEN=... # never commit / never echo
|
| 6 |
+
hf upload-large-folder justicedao/ipfs_malta_laws_ir \\
|
| 7 |
+
/workspace/country-laws-ir/releases/ipfs_malta_laws_ir \\
|
| 8 |
+
--repo-type dataset --no-private --num-workers 8 \\
|
| 9 |
+
--exclude "**/__pycache__/**" --exclude "**/*.pyc"
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def upload_release(local_dir: Path, repo_id: str) -> dict[str, Any]:
|
| 19 |
+
raise RuntimeError(
|
| 20 |
+
"Hub upload is disabled in the local country-laws-ir pipeline. "
|
| 21 |
+
"Publish later with: hf upload-large-folder "
|
| 22 |
+
f"{repo_id} {local_dir} --repo-type dataset --no-private --num-workers 8 "
|
| 23 |
+
'--exclude "**/__pycache__/**" --exclude "**/*.pyc"'
|
| 24 |
+
)
|
country_laws_ir/vectors.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""thenlper/gte-small 384-d embeddings + centroid-sorted shards.
|
| 2 |
+
|
| 3 |
+
If sentence-transformers/torch cannot embed, layout_stub_vectors() documents the
|
| 4 |
+
expected schema so corpus/BM25/graph releases remain complete.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 15 |
+
|
| 16 |
+
MODEL_NAME = "thenlper/gte-small"
|
| 17 |
+
DIMENSION = 384
|
| 18 |
+
MAX_ROWS_PER_CENTROID = 8192
|
| 19 |
+
MAX_SHARDS_PER_CENTROID = 2
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray:
|
| 23 |
+
n = np.linalg.norm(x, axis=-1, keepdims=True)
|
| 24 |
+
return x / np.maximum(n, eps)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def embeddings_available() -> bool:
|
| 28 |
+
try:
|
| 29 |
+
import torch # noqa: F401
|
| 30 |
+
from sentence_transformers import SentenceTransformer # noqa: F401
|
| 31 |
+
|
| 32 |
+
return True
|
| 33 |
+
except Exception:
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def encode_corpus(
|
| 38 |
+
corpus: pd.DataFrame,
|
| 39 |
+
batch_size: int = 64,
|
| 40 |
+
device: str = "cpu",
|
| 41 |
+
checkpoint_path: str | None = None,
|
| 42 |
+
chunk_size: int = 4096,
|
| 43 |
+
) -> np.ndarray:
|
| 44 |
+
"""Encode corpus texts with gte-small in chunks; persist checkpoints when given."""
|
| 45 |
+
import json
|
| 46 |
+
import os
|
| 47 |
+
from datetime import datetime, timezone
|
| 48 |
+
from pathlib import Path as _Path
|
| 49 |
+
|
| 50 |
+
from sentence_transformers import SentenceTransformer
|
| 51 |
+
|
| 52 |
+
from .auth import configure_hf
|
| 53 |
+
|
| 54 |
+
configure_hf()
|
| 55 |
+
cache_root = _Path("/workspace/country-laws-ir/cache/hf")
|
| 56 |
+
os.environ.setdefault("HF_HOME", str(cache_root))
|
| 57 |
+
os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
|
| 58 |
+
os.environ.setdefault(
|
| 59 |
+
"SENTENCE_TRANSFORMERS_HOME",
|
| 60 |
+
str(cache_root / "sentence-transformers"),
|
| 61 |
+
)
|
| 62 |
+
texts = []
|
| 63 |
+
for rec in corpus.itertuples(index=False):
|
| 64 |
+
title = getattr(rec, "title", None) or getattr(rec, "instrument_title", "") or ""
|
| 65 |
+
body = getattr(rec, "body", "") or ""
|
| 66 |
+
sid = getattr(rec, "source_id", "") or getattr(rec, "instrument_id", "")
|
| 67 |
+
texts.append(f"{title}\n{body[:4000]}".strip() or title or sid)
|
| 68 |
+
n = len(texts)
|
| 69 |
+
out = np.zeros((n, DIMENSION), dtype=np.float32)
|
| 70 |
+
done = 0
|
| 71 |
+
ckpt = _Path(checkpoint_path) if checkpoint_path else None
|
| 72 |
+
meta_path = ckpt.with_suffix(".json") if ckpt else None
|
| 73 |
+
meta_n = None
|
| 74 |
+
if meta_path is not None and meta_path.exists():
|
| 75 |
+
try:
|
| 76 |
+
meta_n = json.loads(meta_path.read_text(encoding="utf-8")).get("n")
|
| 77 |
+
except Exception:
|
| 78 |
+
meta_n = None
|
| 79 |
+
if ckpt is not None and ckpt.exists():
|
| 80 |
+
cached = np.load(ckpt)
|
| 81 |
+
same_corpus = meta_n is None or int(meta_n) == n
|
| 82 |
+
if (
|
| 83 |
+
same_corpus
|
| 84 |
+
and cached.ndim == 2
|
| 85 |
+
and cached.shape[1] == DIMENSION
|
| 86 |
+
and 0 < cached.shape[0] <= n
|
| 87 |
+
):
|
| 88 |
+
done = int(cached.shape[0])
|
| 89 |
+
out[:done] = cached.astype(np.float32, copy=False)
|
| 90 |
+
print(f"embeddings resume {done}/{n} from {ckpt}", flush=True)
|
| 91 |
+
else:
|
| 92 |
+
print(
|
| 93 |
+
f"embeddings checkpoint shape {getattr(cached, 'shape', None)} "
|
| 94 |
+
f"meta_n={meta_n} incompatible with {(n, DIMENSION)}; restarting",
|
| 95 |
+
flush=True,
|
| 96 |
+
)
|
| 97 |
+
if done >= n:
|
| 98 |
+
return out
|
| 99 |
+
model = SentenceTransformer(MODEL_NAME, device=device)
|
| 100 |
+
while done < n:
|
| 101 |
+
j = min(done + int(chunk_size), n)
|
| 102 |
+
chunk = model.encode(
|
| 103 |
+
texts[done:j],
|
| 104 |
+
batch_size=batch_size,
|
| 105 |
+
show_progress_bar=True,
|
| 106 |
+
convert_to_numpy=True,
|
| 107 |
+
normalize_embeddings=True,
|
| 108 |
+
)
|
| 109 |
+
out[done:j] = np.asarray(chunk, dtype=np.float32)
|
| 110 |
+
done = j
|
| 111 |
+
print(f"embeddings checkpoint {done}/{n}", flush=True)
|
| 112 |
+
if ckpt is not None:
|
| 113 |
+
ckpt.parent.mkdir(parents=True, exist_ok=True)
|
| 114 |
+
tmp = ckpt.with_name(ckpt.name + ".tmp.npy")
|
| 115 |
+
np.save(tmp, out[:done])
|
| 116 |
+
tmp.replace(ckpt)
|
| 117 |
+
if meta_path is not None:
|
| 118 |
+
meta_path.write_text(
|
| 119 |
+
json.dumps(
|
| 120 |
+
{
|
| 121 |
+
"n": n,
|
| 122 |
+
"done": done,
|
| 123 |
+
"dimension": DIMENSION,
|
| 124 |
+
"model_name": MODEL_NAME,
|
| 125 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 126 |
+
}
|
| 127 |
+
)
|
| 128 |
+
+ "\n",
|
| 129 |
+
encoding="utf-8",
|
| 130 |
+
)
|
| 131 |
+
return out
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _spherical_kmeans(x: np.ndarray, k: int, iters: int = 12, seed: int = 0) -> np.ndarray:
|
| 135 |
+
rng = np.random.default_rng(seed)
|
| 136 |
+
n = len(x)
|
| 137 |
+
k = min(k, n)
|
| 138 |
+
centers = x[rng.choice(n, size=k, replace=False)].copy()
|
| 139 |
+
labels = np.zeros(n, dtype=np.int32)
|
| 140 |
+
for _ in range(iters):
|
| 141 |
+
sim = x @ centers.T
|
| 142 |
+
labels = sim.argmax(axis=1).astype(np.int32)
|
| 143 |
+
new = []
|
| 144 |
+
for j in range(k):
|
| 145 |
+
mask = labels == j
|
| 146 |
+
if not mask.any():
|
| 147 |
+
new.append(x[rng.integers(0, n)])
|
| 148 |
+
else:
|
| 149 |
+
new.append(_l2_normalize(x[mask].mean(axis=0)))
|
| 150 |
+
centers = np.stack(new).astype(np.float32)
|
| 151 |
+
return labels
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _recursive_clusters(x: np.ndarray, max_size: int = MAX_ROWS_PER_FILE) -> list[np.ndarray]:
|
| 155 |
+
n = len(x)
|
| 156 |
+
idx = np.arange(n)
|
| 157 |
+
if n <= max_size:
|
| 158 |
+
return [idx]
|
| 159 |
+
labels = _spherical_kmeans(x, k=2)
|
| 160 |
+
clusters = []
|
| 161 |
+
for lab in (0, 1):
|
| 162 |
+
members = idx[labels == lab]
|
| 163 |
+
if len(members) == 0:
|
| 164 |
+
continue
|
| 165 |
+
if len(members) <= max_size:
|
| 166 |
+
clusters.append(members)
|
| 167 |
+
else:
|
| 168 |
+
sub = _recursive_clusters(x[members], max_size=max_size)
|
| 169 |
+
clusters.extend([members[s] for s in sub])
|
| 170 |
+
if not clusters:
|
| 171 |
+
mid = n // 2
|
| 172 |
+
return [idx[:mid], idx[mid:]]
|
| 173 |
+
return clusters
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def layout_vectors(corpus: pd.DataFrame, embeddings: np.ndarray) -> dict[str, Any]:
|
| 177 |
+
x = _l2_normalize(np.asarray(embeddings, dtype=np.float32))
|
| 178 |
+
clusters = _recursive_clusters(x, max_size=MAX_ROWS_PER_FILE)
|
| 179 |
+
vector_rows = []
|
| 180 |
+
chunk_meta = []
|
| 181 |
+
global_centroid = _l2_normalize(x.mean(axis=0))
|
| 182 |
+
for cluster_id, members in enumerate(clusters):
|
| 183 |
+
shard_centroid = _l2_normalize(x[members].mean(axis=0))
|
| 184 |
+
sims = x[members] @ shard_centroid
|
| 185 |
+
order = np.argsort(-sims)
|
| 186 |
+
members = members[order]
|
| 187 |
+
sims = sims[order]
|
| 188 |
+
chunk_id = f"vec-{cluster_id:06d}"
|
| 189 |
+
for local_i, doc_i in enumerate(members):
|
| 190 |
+
row = corpus.iloc[int(doc_i)]
|
| 191 |
+
vector_rows.append(
|
| 192 |
+
{
|
| 193 |
+
"chunk_id": chunk_id,
|
| 194 |
+
"cluster_id": int(cluster_id),
|
| 195 |
+
"entry_cid": row["entry_cid"],
|
| 196 |
+
"faiss_id": int(doc_i),
|
| 197 |
+
"document_index": int(row["document_index"]),
|
| 198 |
+
"corpus_chunk_id": int(row["document_index"] // MAX_ROWS_PER_FILE),
|
| 199 |
+
"corpus_row_offset": int(row["document_index"] % MAX_ROWS_PER_FILE),
|
| 200 |
+
"law_cid": row.get("law_cid", ""),
|
| 201 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 202 |
+
"law_id": row.get("law_id", row.get("instrument_id", "")),
|
| 203 |
+
"title": row.get("title", row.get("instrument_title", "")),
|
| 204 |
+
"record_type": row["record_type"],
|
| 205 |
+
"language": row.get("language", ""),
|
| 206 |
+
"jurisdiction": row.get("jurisdiction", ""),
|
| 207 |
+
"embedding": x[int(doc_i)].tolist(),
|
| 208 |
+
"schema_version": SCHEMA_VERSION,
|
| 209 |
+
}
|
| 210 |
+
)
|
| 211 |
+
chunk_meta.append(
|
| 212 |
+
{
|
| 213 |
+
"cluster_id": int(cluster_id),
|
| 214 |
+
"chunk_id": chunk_id,
|
| 215 |
+
"centroid": shard_centroid.tolist(),
|
| 216 |
+
"shard_centroid": shard_centroid.tolist(),
|
| 217 |
+
"centroid_min_score": float(sims.min()) if len(sims) else 0.0,
|
| 218 |
+
"centroid_shard_count": 1,
|
| 219 |
+
"chunk_in_cluster": 0,
|
| 220 |
+
"dimension": DIMENSION,
|
| 221 |
+
"model_name": MODEL_NAME,
|
| 222 |
+
"row_count": int(len(members)),
|
| 223 |
+
"first_key": corpus.iloc[int(members[0])]["entry_cid"] if len(members) else "",
|
| 224 |
+
"last_key": corpus.iloc[int(members[-1])]["entry_cid"] if len(members) else "",
|
| 225 |
+
}
|
| 226 |
+
)
|
| 227 |
+
vectors_df = pd.DataFrame(vector_rows)
|
| 228 |
+
return {
|
| 229 |
+
"vectors": vectors_df,
|
| 230 |
+
"chunk_meta": chunk_meta,
|
| 231 |
+
"global_centroid": global_centroid.tolist(),
|
| 232 |
+
"stats": {
|
| 233 |
+
"model_name": MODEL_NAME,
|
| 234 |
+
"dimension": DIMENSION,
|
| 235 |
+
"similarity": "cosine",
|
| 236 |
+
"assignment": "recursive_spherical_kmeans",
|
| 237 |
+
"layout": "semantic_centroid_groups",
|
| 238 |
+
"rows_sorted_by": "cosine_similarity_to_shard_centroid_desc",
|
| 239 |
+
"max_rows_per_chunk": MAX_ROWS_PER_FILE,
|
| 240 |
+
"max_rows_per_centroid": MAX_ROWS_PER_CENTROID,
|
| 241 |
+
"max_shards_per_centroid": MAX_SHARDS_PER_CENTROID,
|
| 242 |
+
"default_probe_centroids": min(4, max(1, len(clusters))),
|
| 243 |
+
"centroid_count": len(clusters),
|
| 244 |
+
"shard_count": len(clusters),
|
| 245 |
+
"n_vectors": int(len(vectors_df)),
|
| 246 |
+
"status": "embedded",
|
| 247 |
+
},
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def layout_stub_vectors(corpus: pd.DataFrame, reason: str) -> dict[str, Any]:
|
| 252 |
+
"""Document expected vector schema when embeddings cannot be produced."""
|
| 253 |
+
rows = []
|
| 254 |
+
for _, row in corpus.iterrows():
|
| 255 |
+
rows.append(
|
| 256 |
+
{
|
| 257 |
+
"chunk_id": "vec-stub-000000",
|
| 258 |
+
"cluster_id": 0,
|
| 259 |
+
"entry_cid": row["entry_cid"],
|
| 260 |
+
"faiss_id": int(row["document_index"]),
|
| 261 |
+
"document_index": int(row["document_index"]),
|
| 262 |
+
"corpus_chunk_id": int(row["document_index"] // MAX_ROWS_PER_FILE),
|
| 263 |
+
"corpus_row_offset": int(row["document_index"] % MAX_ROWS_PER_FILE),
|
| 264 |
+
"law_cid": row.get("law_cid", ""),
|
| 265 |
+
"instrument_id": row.get("instrument_id", ""),
|
| 266 |
+
"law_id": row.get("law_id", ""),
|
| 267 |
+
"title": row.get("title", ""),
|
| 268 |
+
"record_type": row["record_type"],
|
| 269 |
+
"language": row.get("language", ""),
|
| 270 |
+
"jurisdiction": row.get("jurisdiction", ""),
|
| 271 |
+
"embedding": None,
|
| 272 |
+
"schema_version": SCHEMA_VERSION,
|
| 273 |
+
}
|
| 274 |
+
)
|
| 275 |
+
vectors_df = pd.DataFrame(rows)
|
| 276 |
+
zero = [0.0] * DIMENSION
|
| 277 |
+
chunk_meta = [
|
| 278 |
+
{
|
| 279 |
+
"cluster_id": 0,
|
| 280 |
+
"chunk_id": "vec-stub-000000",
|
| 281 |
+
"centroid": zero,
|
| 282 |
+
"shard_centroid": zero,
|
| 283 |
+
"centroid_min_score": 0.0,
|
| 284 |
+
"centroid_shard_count": 1,
|
| 285 |
+
"chunk_in_cluster": 0,
|
| 286 |
+
"dimension": DIMENSION,
|
| 287 |
+
"model_name": MODEL_NAME,
|
| 288 |
+
"row_count": int(len(vectors_df)),
|
| 289 |
+
"first_key": vectors_df.iloc[0]["entry_cid"] if len(vectors_df) else "",
|
| 290 |
+
"last_key": vectors_df.iloc[-1]["entry_cid"] if len(vectors_df) else "",
|
| 291 |
+
"stub": True,
|
| 292 |
+
"stub_reason": reason,
|
| 293 |
+
}
|
| 294 |
+
]
|
| 295 |
+
return {
|
| 296 |
+
"vectors": vectors_df,
|
| 297 |
+
"chunk_meta": chunk_meta,
|
| 298 |
+
"global_centroid": zero,
|
| 299 |
+
"stats": {
|
| 300 |
+
"model_name": MODEL_NAME,
|
| 301 |
+
"dimension": DIMENSION,
|
| 302 |
+
"similarity": "cosine",
|
| 303 |
+
"assignment": "stub",
|
| 304 |
+
"layout": "semantic_centroid_groups",
|
| 305 |
+
"rows_sorted_by": "document_index",
|
| 306 |
+
"max_rows_per_chunk": MAX_ROWS_PER_FILE,
|
| 307 |
+
"max_rows_per_centroid": MAX_ROWS_PER_CENTROID,
|
| 308 |
+
"max_shards_per_centroid": MAX_SHARDS_PER_CENTROID,
|
| 309 |
+
"default_probe_centroids": 1,
|
| 310 |
+
"centroid_count": 1 if len(vectors_df) else 0,
|
| 311 |
+
"shard_count": 1 if len(vectors_df) else 0,
|
| 312 |
+
"n_vectors": 0,
|
| 313 |
+
"status": "stub",
|
| 314 |
+
"stub_reason": reason,
|
| 315 |
+
"expected_columns": [
|
| 316 |
+
"entry_cid",
|
| 317 |
+
"document_index",
|
| 318 |
+
"embedding",
|
| 319 |
+
"law_cid",
|
| 320 |
+
"instrument_id",
|
| 321 |
+
"title",
|
| 322 |
+
"record_type",
|
| 323 |
+
"language",
|
| 324 |
+
"jurisdiction",
|
| 325 |
+
],
|
| 326 |
+
},
|
| 327 |
+
}
|
data/bm25/documents/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:53530a3dc381f267cc068dd9dabbf3a0aa0f6c65afca9d89310560672d0778f5
|
| 3 |
+
size 298706
|
data/bm25/documents/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c9f93c0e641d4d77e6ef7e4fbd217f5f36f03a1b3312a1b077f61b24632e2457
|
| 3 |
+
size 18747
|
data/bm25/postings/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6a0e148fd34a01670a2ffc8466eb11a81ceb10d5409c78753ec4a1b40a07848f
|
| 3 |
+
size 485972
|
data/bm25/postings/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:486fbecbfd39b16efb17e7251cd9a2c0501a029644875b502588ec66c3f5bccc
|
| 3 |
+
size 843314
|
data/bm25/postings/part-000002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b8d5eda96baff6faf8e6828ad4200b2eb262688b2b93e883df7febce7d2d004e
|
| 3 |
+
size 671293
|
data/bm25/postings/part-000003.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b1d345dfd55da4370c33eb6632ddb1065d368909375d61950e22dcd8b14f25b
|
| 3 |
+
size 688725
|
data/bm25/postings/part-000004.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ac5f6d64790848078bf66df62a57eb8495d734df0486216530ed1322236f0dc
|
| 3 |
+
size 737329
|
data/bm25/postings/part-000005.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ff699b701317961c3722c7dca66a5fbf4c2b68a456cfc4fe3396d824c92d4db9
|
| 3 |
+
size 732666
|
data/bm25/postings/part-000006.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb4edcf5ba4ac1c36c4d1a8a98d233ad619b0c5ae038cbf6c4604834ab6f0468
|
| 3 |
+
size 727515
|
data/corpus/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bf1cc36fc56bc14e004937b75a9597c8726eefd4bcb2d0eb004f63e2727a3f67
|
| 3 |
+
size 5736646
|
data/corpus/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8aceda051fea5bc3f50ccef256680f29f503fa4edafd19728119eedaa68842de
|
| 3 |
+
size 103224
|
data/graph/adjacency/incoming/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fc893b31f6a4d00c7f805a9d91b8047f356975ab3a176f7fd46db071f66360b8
|
| 3 |
+
size 1858719
|
data/graph/adjacency/outgoing/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:be98c9874ad7a6d11981b5df6ae829ce96743a7c01905f81fd9ba329a1a32d28
|
| 3 |
+
size 1793099
|
data/graph/adjacency/outgoing/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:97e6aecb16abd3100ab12eea085b9ef151f6deef13fe8a9dbef611a249c6c1bf
|
| 3 |
+
size 67190
|
data/graph/edges/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a21f736479f8743a8a9f897bbfa1f2b4234c07281faf3fe5ccecb421d44c713b
|
| 3 |
+
size 336199
|
data/graph/edges/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aee31e39ad8ff70e8702ff89971ac8131321ddc767aa8c5c7e6b824672360d3c
|
| 3 |
+
size 305358
|
data/graph/edges/part-000002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1f2b7ddf71f88b8165b2caa258669f904a23ae948784b0c9084cd111081759da
|
| 3 |
+
size 307124
|
data/graph/edges/part-000003.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:37c91a234ca857645b423bb218bdc7e91e44f3ff3f002d31389e14dc73609152
|
| 3 |
+
size 327554
|
data/graph/edges/part-000004.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f13da1a6c3437f5a51ac63dda98c4ea9d870655125c3ec0f83b56fe2804268b1
|
| 3 |
+
size 314293
|
data/graph/edges/part-000005.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9134f0f106a1fae6a3d1d4f348360b95e1cc227ba8e445bd2f239e21dcdc9916
|
| 3 |
+
size 294815
|
data/graph/edges/part-000006.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2e3816f25e515c79d05e3200ff17d2af42efbd5a1d3a569e5764c60c1e908da5
|
| 3 |
+
size 294810
|
data/graph/edges/part-000007.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c6d2b486b1746d5c84a021e5ef3681f0799f85f28e9c61d4d6d4eae454a4d045
|
| 3 |
+
size 294836
|
data/graph/edges/part-000008.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fb2dd32325e147157edd4063833d3a0a7dafc6fa93c41e8f38fdf84d57742a56
|
| 3 |
+
size 307783
|
data/graph/edges/part-000009.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:238e541195c01d2b8ebfc8d0f0a39ac7baa923de63334df3ad28e0782493f37e
|
| 3 |
+
size 283453
|
data/graph/nodes/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d1fcab16d070ac15caac8585b137eaee394b12b8fcc36581480c1895743922ab
|
| 3 |
+
size 483116
|
data/graph/nodes/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:314b8a7e8db017c6ed67c1a79e9054a44dd9637a6d236f9f62ccc24f2b6d16ee
|
| 3 |
+
size 91354
|
data/vectors/part-000000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:21e00f61bbc2b37c642169c0af7e4220a6d5b9f1b6b1936afe92ea51f4cf933d
|
| 3 |
+
size 7302876
|
data/vectors/part-000001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:53310ae2c2b94add4cb989c0bdbe182d3142305c15c3b212a49bcea0cd44761e
|
| 3 |
+
size 241613
|
indexes/bm25_document_chunks.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:36239d081eae8b10a1dd3d9382eec64cfddf1e71af50f9ca3c73141066ebad50
|
| 3 |
+
size 9041
|
indexes/bm25_keyword_shards.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a3c0a8ab2c258f606a66b81e04d275721917eebf2af35b70283cb92bc70e64f2
|
| 3 |
+
size 10862
|
indexes/corpus_chunks.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd27ff387252a8b7f96dc131cf8bf4e06a4abf894de61bf3bd6cbee393d142c5
|
| 3 |
+
size 8959
|